xref: /dragonfly/usr.bin/patch/patch.c (revision 0dace59e)
1 /*
2  * $OpenBSD: patch.c,v 1.45 2007/04/18 21:52:24 sobrado Exp $
3  */
4 
5 /*
6  * patch - a program to apply diffs to original files
7  *
8  * Copyright 1986, Larry Wall
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following condition is met:
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this condition and the following disclaimer.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
28  * behaviour
29  */
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 
34 #include <ctype.h>
35 #include <getopt.h>
36 #include <limits.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 
42 #include "common.h"
43 #include "util.h"
44 #include "pch.h"
45 #include "inp.h"
46 #include "backupfile.h"
47 #include "pathnames.h"
48 
49 mode_t		filemode = 0644;
50 
51 char		buf[MAXLINELEN];	/* general purpose buffer */
52 size_t		buf_len = sizeof(buf);
53 
54 bool		using_plan_a = true;	/* try to keep everything in memory */
55 bool		out_of_mem = false;	/* ran out of memory in plan a */
56 
57 #define MAXFILEC 2
58 
59 char		*filearg[MAXFILEC];
60 bool		ok_to_create_file = false;
61 char		*outname = NULL;
62 char		*origprae = NULL;
63 char		*TMPOUTNAME;
64 char		*TMPINNAME;
65 char		*TMPREJNAME;
66 char		*TMPPATNAME;
67 bool		toutkeep = false;
68 bool		trejkeep = false;
69 bool		warn_on_invalid_line;
70 bool		last_line_missing_eol;
71 
72 #ifdef DEBUGGING
73 int		debug = 0;
74 #endif
75 
76 bool		force = false;
77 bool		batch = false;
78 bool		verbose = true;
79 bool		reverse = false;
80 bool		noreverse = false;
81 bool		skip_rest_of_patch = false;
82 int		strippath = 957;
83 bool		canonicalize = false;
84 bool		check_only = false;
85 int		diff_type = 0;
86 char		*revision = NULL;	/* prerequisite revision, if any */
87 LINENUM		input_lines = 0;	/* how long is input file in lines */
88 int		posix = 0;		/* strict POSIX mode? */
89 
90 static void	reinitialize_almost_everything(void);
91 static void	get_some_switches(void);
92 static LINENUM	locate_hunk(LINENUM);
93 static void	abort_context_hunk(void);
94 static void	rej_line(int, LINENUM);
95 static void	abort_hunk(void);
96 static void	apply_hunk(LINENUM);
97 static void	init_output(const char *);
98 static void	init_reject(const char *);
99 static void	copy_till(LINENUM, bool);
100 static bool	spew_output(void);
101 static void	dump_line(LINENUM, bool);
102 static bool	patch_match(LINENUM, LINENUM, LINENUM);
103 static bool	similar(const char *, const char *, int);
104 static void	usage(void);
105 
106 /* true if -E was specified on command line.  */
107 static bool	remove_empty_files = false;
108 
109 /* true if -R was specified on command line.  */
110 static bool	reverse_flag_specified = false;
111 
112 /* buffer holding the name of the rejected patch file. */
113 static char	rejname[NAME_MAX + 1];
114 
115 /* buffer for stderr */
116 static char	serrbuf[BUFSIZ];
117 
118 /* how many input lines have been irretractibly output */
119 static LINENUM	last_frozen_line = 0;
120 
121 static int	Argc;		/* guess */
122 static char	**Argv;
123 static int	Argc_last;	/* for restarting plan_b */
124 static char	**Argv_last;
125 
126 static FILE	*ofp = NULL;	/* output file pointer */
127 static FILE	*rejfp = NULL;	/* reject file pointer */
128 
129 static int	filec = 0;	/* how many file arguments? */
130 static LINENUM	last_offset = 0;
131 static LINENUM	maxfuzz = 2;
132 
133 /* patch using ifdef, ifndef, etc. */
134 static bool		do_defines = false;
135 /* #ifdef xyzzy */
136 static char		if_defined[128];
137 /* #ifndef xyzzy */
138 static char		not_defined[128];
139 /* #else */
140 static const char	else_defined[] = "#else\n";
141 /* #endif xyzzy */
142 static char		end_defined[128];
143 
144 
145 /* Apply a set of diffs as appropriate. */
146 
147 int
148 main(int argc, char *argv[])
149 {
150 	int	error = 0, hunk, failed, i, fd;
151 	LINENUM	where = 0, newwhere, fuzz, mymaxfuzz;
152 	const	char *tmpdir;
153 	char	*v;
154 
155 	setbuf(stderr, serrbuf);
156 	for (i = 0; i < MAXFILEC; i++)
157 		filearg[i] = NULL;
158 
159 	/* Cons up the names of the temporary files.  */
160 	if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
161 		tmpdir = _PATH_TMP;
162 	for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
163 		;
164 	i++;
165 	if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
166 		fatal("cannot allocate memory");
167 	if ((fd = mkstemp(TMPOUTNAME)) < 0)
168 		pfatal("can't create %s", TMPOUTNAME);
169 	close(fd);
170 
171 	if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
172 		fatal("cannot allocate memory");
173 	if ((fd = mkstemp(TMPINNAME)) < 0)
174 		pfatal("can't create %s", TMPINNAME);
175 	close(fd);
176 
177 	if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
178 		fatal("cannot allocate memory");
179 	if ((fd = mkstemp(TMPREJNAME)) < 0)
180 		pfatal("can't create %s", TMPREJNAME);
181 	close(fd);
182 
183 	if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
184 		fatal("cannot allocate memory");
185 	if ((fd = mkstemp(TMPPATNAME)) < 0)
186 		pfatal("can't create %s", TMPPATNAME);
187 	close(fd);
188 
189 	v = getenv("SIMPLE_BACKUP_SUFFIX");
190 	if (v)
191 		simple_backup_suffix = v;
192 	else
193 		simple_backup_suffix = ORIGEXT;
194 
195 	/* parse switches */
196 	Argc = argc;
197 	Argv = argv;
198 	get_some_switches();
199 
200 	if (backup_type == none) {
201 		if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
202 			v = getenv("VERSION_CONTROL");
203 		if (v != NULL || !posix)
204 			backup_type = get_version(v);	/* OK to pass NULL. */
205 	}
206 
207 	/* make sure we clean up /tmp in case of disaster */
208 	set_signals(0);
209 
210 	for (open_patch_file(filearg[1]); there_is_another_patch();
211 	    reinitialize_almost_everything()) {
212 		/* for each patch in patch file */
213 
214 		warn_on_invalid_line = true;
215 
216 		if (outname == NULL)
217 			outname = savestr(filearg[0]);
218 
219 		/* for ed script just up and do it and exit */
220 		if (diff_type == ED_DIFF) {
221 			do_ed_script();
222 			continue;
223 		}
224 		/* initialize the patched file */
225 		if (!skip_rest_of_patch)
226 			init_output(TMPOUTNAME);
227 
228 		/* initialize reject file */
229 		init_reject(TMPREJNAME);
230 
231 		/* find out where all the lines are */
232 		if (!skip_rest_of_patch)
233 			scan_input(filearg[0]);
234 
235 		/* from here on, open no standard i/o files, because malloc */
236 		/* might misfire and we can't catch it easily */
237 
238 		/* apply each hunk of patch */
239 		hunk = 0;
240 		failed = 0;
241 		out_of_mem = false;
242 		while (another_hunk()) {
243 			hunk++;
244 			fuzz = 0;
245 			mymaxfuzz = pch_context();
246 			if (maxfuzz < mymaxfuzz)
247 				mymaxfuzz = maxfuzz;
248 			if (!skip_rest_of_patch) {
249 				do {
250 					where = locate_hunk(fuzz);
251 					if (hunk == 1 && where == 0 && !force) {
252 						/* dwim for reversed patch? */
253 						if (!pch_swap()) {
254 							if (fuzz == 0)
255 								say("Not enough memory to try swapped hunk!  Assuming unswapped.\n");
256 							continue;
257 						}
258 						reverse = !reverse;
259 						/* try again */
260 						where = locate_hunk(fuzz);
261 						if (where == 0) {
262 							/* didn't find it swapped */
263 							if (!pch_swap())
264 								/* put it back to normal */
265 								fatal("lost hunk on alloc error!\n");
266 							reverse = !reverse;
267 						} else if (noreverse) {
268 							if (!pch_swap())
269 								/* put it back to normal */
270 								fatal("lost hunk on alloc error!\n");
271 							reverse = !reverse;
272 							say("Ignoring previously applied (or reversed) patch.\n");
273 							skip_rest_of_patch = true;
274 						} else if (batch) {
275 							if (verbose)
276 								say("%seversed (or previously applied) patch detected!  %s -R.",
277 								    reverse ? "R" : "Unr",
278 								    reverse ? "Assuming" : "Ignoring");
279 						} else {
280 							ask("%seversed (or previously applied) patch detected!  %s -R? [y] ",
281 							    reverse ? "R" : "Unr",
282 							    reverse ? "Assume" : "Ignore");
283 							if (*buf == 'n') {
284 								ask("Apply anyway? [n] ");
285 								if (*buf != 'y')
286 									skip_rest_of_patch = true;
287 								where = 0;
288 								reverse = !reverse;
289 								if (!pch_swap())
290 									/* put it back to normal */
291 									fatal("lost hunk on alloc error!\n");
292 							}
293 						}
294 					}
295 				} while (!skip_rest_of_patch && where == 0 &&
296 				    ++fuzz <= mymaxfuzz);
297 
298 				if (skip_rest_of_patch) {	/* just got decided */
299 					if (ferror(ofp) || fclose(ofp)) {
300 						say("Error writing %s\n",
301 						    TMPOUTNAME);
302 						error = 1;
303 					}
304 					ofp = NULL;
305 				}
306 			}
307 			newwhere = pch_newfirst() + last_offset;
308 			if (skip_rest_of_patch) {
309 				abort_hunk();
310 				failed++;
311 				if (verbose)
312 					say("Hunk #%d ignored at %ld.\n",
313 					    hunk, newwhere);
314 			} else if (where == 0) {
315 				abort_hunk();
316 				failed++;
317 				if (verbose)
318 					say("Hunk #%d failed at %ld.\n",
319 					    hunk, newwhere);
320 			} else {
321 				apply_hunk(where);
322 				if (verbose) {
323 					say("Hunk #%d succeeded at %ld",
324 					    hunk, newwhere);
325 					if (fuzz != 0)
326 						say(" with fuzz %ld", fuzz);
327 					if (last_offset)
328 						say(" (offset %ld line%s)",
329 						    last_offset,
330 						    last_offset == 1L ? "" : "s");
331 					say(".\n");
332 				}
333 			}
334 		}
335 
336 		if (out_of_mem && using_plan_a) {
337 			Argc = Argc_last;
338 			Argv = Argv_last;
339 			say("\n\nRan out of memory using Plan A--trying again...\n\n");
340 			if (ofp)
341 				fclose(ofp);
342 			ofp = NULL;
343 			if (rejfp)
344 				fclose(rejfp);
345 			rejfp = NULL;
346 			continue;
347 		}
348 		if (hunk == 0)
349 			fatal("Internal error: hunk should not be 0\n");
350 
351 		/* finish spewing out the new file */
352 		if (!skip_rest_of_patch && !spew_output()) {
353 			say("Can't write %s\n", TMPOUTNAME);
354 			error = 1;
355 		}
356 
357 		/* and put the output where desired */
358 		ignore_signals();
359 		if (!skip_rest_of_patch) {
360 			struct stat	statbuf;
361 			char	*realout = outname;
362 
363 			if (!check_only) {
364 				if (move_file(TMPOUTNAME, outname) < 0) {
365 					toutkeep = true;
366 					realout = TMPOUTNAME;
367 					chmod(TMPOUTNAME, filemode);
368 				} else
369 					chmod(outname, filemode);
370 
371 				if (remove_empty_files &&
372 				    stat(realout, &statbuf) == 0 &&
373 				    statbuf.st_size == 0) {
374 					if (verbose)
375 						say("Removing %s (empty after patching).\n",
376 						    realout);
377 					unlink(realout);
378 				}
379 			}
380 		}
381 		if (ferror(rejfp) || fclose(rejfp)) {
382 			say("Error writing %s\n", rejname);
383 			error = 1;
384 		}
385 		rejfp = NULL;
386 		if (failed) {
387 			error = 1;
388 			if (*rejname == '\0') {
389 				if (strlcpy(rejname, outname,
390 				    sizeof(rejname)) >= sizeof(rejname))
391 					fatal("filename %s is too long\n", outname);
392 				if (strlcat(rejname, REJEXT,
393 				    sizeof(rejname)) >= sizeof(rejname))
394 					fatal("filename %s is too long\n", outname);
395 			}
396 			if (!check_only) {
397 				say("%d out of %d hunks %s--saving rejects to %s\n",
398 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
399 			} else {
400 				say("%d out of %d hunks %s\n",
401 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
402 			}
403 			if (!check_only && move_file(TMPREJNAME, rejname) < 0)
404 				trejkeep = true;
405 		}
406 		set_signals(1);
407 	}
408 	my_exit(error);
409 	/* NOTREACHED */
410 }
411 
412 /* Prepare to find the next patch to do in the patch file. */
413 
414 static void
415 reinitialize_almost_everything(void)
416 {
417 	re_patch();
418 	re_input();
419 
420 	input_lines = 0;
421 	last_frozen_line = 0;
422 
423 	filec = 0;
424 	if (!out_of_mem) {
425 		free(filearg[0]);
426 		filearg[0] = NULL;
427 	}
428 
429 	free(outname);
430 	outname = NULL;
431 
432 	last_offset = 0;
433 	diff_type = 0;
434 
435 	free(revision);
436 	revision = NULL;
437 
438 	reverse = reverse_flag_specified;
439 	skip_rest_of_patch = false;
440 
441 	get_some_switches();
442 }
443 
444 /* Process switches and filenames. */
445 
446 static void
447 get_some_switches(void)
448 {
449 	const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
450 	static struct option longopts[] = {
451 		{"backup",		no_argument,		0,	'b'},
452 		{"batch",		no_argument,		0,	't'},
453 		{"check",		no_argument,		0,	'C'},
454 		{"context",		no_argument,		0,	'c'},
455 		{"debug",		required_argument,	0,	'x'},
456 		{"directory",		required_argument,	0,	'd'},
457 		{"ed",			no_argument,		0,	'e'},
458 		{"force",		no_argument,		0,	'f'},
459 		{"forward",		no_argument,		0,	'N'},
460 		{"fuzz",		required_argument,	0,	'F'},
461 		{"ifdef",		required_argument,	0,	'D'},
462 		{"input",		required_argument,	0,	'i'},
463 		{"ignore-whitespace",	no_argument,		0,	'l'},
464 		{"normal",		no_argument,		0,	'n'},
465 		{"output",		required_argument,	0,	'o'},
466 		{"prefix",		required_argument,	0,	'B'},
467 		{"quiet",		no_argument,		0,	's'},
468 		{"reject-file",		required_argument,	0,	'r'},
469 		{"remove-empty-files",	no_argument,		0,	'E'},
470 		{"reverse",		no_argument,		0,	'R'},
471 		{"silent",		no_argument,		0,	's'},
472 		{"strip",		required_argument,	0,	'p'},
473 		{"suffix",		required_argument,	0,	'z'},
474 		{"unified",		no_argument,		0,	'u'},
475 		{"version",		no_argument,		0,	'v'},
476 		{"version-control",	required_argument,	0,	'V'},
477 		{"posix",		no_argument,		&posix,	1},
478 		{NULL,			0,			0,	0}
479 	};
480 	int ch;
481 
482 	rejname[0] = '\0';
483 	Argc_last = Argc;
484 	Argv_last = Argv;
485 	if (!Argc)
486 		return;
487 	optreset = optind = 1;
488 	while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
489 		switch (ch) {
490 		case 'b':
491 			if (backup_type == none)
492 				backup_type = numbered_existing;
493 			if (optarg == NULL)
494 				break;
495 			if (verbose)
496 				say("Warning, the ``-b suffix'' option has been"
497 				    " obsoleted by the -z option.\n");
498 			/* FALLTHROUGH */
499 		case 'z':
500 			/* must directly follow 'b' case for backwards compat */
501 			simple_backup_suffix = savestr(optarg);
502 			break;
503 		case 'B':
504 			origprae = savestr(optarg);
505 			break;
506 		case 'c':
507 			diff_type = CONTEXT_DIFF;
508 			break;
509 		case 'C':
510 			check_only = true;
511 			break;
512 		case 'd':
513 			if (chdir(optarg) < 0)
514 				pfatal("can't cd to %s", optarg);
515 			break;
516 		case 'D':
517 			do_defines = true;
518 			if (!isalpha((unsigned char)*optarg) && *optarg != '_')
519 				fatal("argument to -D is not an identifier\n");
520 			snprintf(if_defined, sizeof if_defined,
521 			    "#ifdef %s\n", optarg);
522 			snprintf(not_defined, sizeof not_defined,
523 			    "#ifndef %s\n", optarg);
524 			snprintf(end_defined, sizeof end_defined,
525 			    "#endif /* %s */\n", optarg);
526 			break;
527 		case 'e':
528 			diff_type = ED_DIFF;
529 			break;
530 		case 'E':
531 			remove_empty_files = true;
532 			break;
533 		case 'f':
534 			force = true;
535 			break;
536 		case 'F':
537 			maxfuzz = atoi(optarg);
538 			break;
539 		case 'i':
540 			if (++filec == MAXFILEC)
541 				fatal("too many file arguments\n");
542 			filearg[filec] = savestr(optarg);
543 			break;
544 		case 'l':
545 			canonicalize = true;
546 			break;
547 		case 'n':
548 			diff_type = NORMAL_DIFF;
549 			break;
550 		case 'N':
551 			noreverse = true;
552 			break;
553 		case 'o':
554 			outname = savestr(optarg);
555 			break;
556 		case 'p':
557 			strippath = atoi(optarg);
558 			break;
559 		case 'r':
560 			if (strlcpy(rejname, optarg,
561 			    sizeof(rejname)) >= sizeof(rejname))
562 				fatal("argument for -r is too long\n");
563 			break;
564 		case 'R':
565 			reverse = true;
566 			reverse_flag_specified = true;
567 			break;
568 		case 's':
569 			verbose = false;
570 			break;
571 		case 't':
572 			batch = true;
573 			break;
574 		case 'u':
575 			diff_type = UNI_DIFF;
576 			break;
577 		case 'v':
578 			version();
579 			break;
580 		case 'V':
581 			backup_type = get_version(optarg);
582 			break;
583 #ifdef DEBUGGING
584 		case 'x':
585 			debug = atoi(optarg);
586 			break;
587 #endif
588 		default:
589 			if (ch != '\0')
590 				usage();
591 			break;
592 		}
593 	}
594 	Argc -= optind;
595 	Argv += optind;
596 
597 	if (Argc > 0) {
598 		filearg[0] = savestr(*Argv++);
599 		Argc--;
600 		while (Argc > 0) {
601 			if (++filec == MAXFILEC)
602 				fatal("too many file arguments\n");
603 			filearg[filec] = savestr(*Argv++);
604 			Argc--;
605 		}
606 	}
607 
608 	if (getenv("POSIXLY_CORRECT") != NULL)
609 		posix = 1;
610 }
611 
612 static void
613 usage(void)
614 {
615 	fprintf(stderr,
616 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
617 "             [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
618 "             [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
619 "             [--posix] [origfile [patchfile]]\n"
620 "       patch <patchfile\n");
621 	my_exit(EXIT_SUCCESS);
622 }
623 
624 /*
625  * Attempt to find the right place to apply this hunk of patch.
626  */
627 static LINENUM
628 locate_hunk(LINENUM fuzz)
629 {
630 	LINENUM	first_guess = pch_first() + last_offset;
631 	LINENUM	offset;
632 	LINENUM	pat_lines = pch_ptrn_lines();
633 	LINENUM	max_pos_offset = input_lines - first_guess - pat_lines + 1;
634 	LINENUM	max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
635 
636 	if (pat_lines == 0) {		/* null range matches always */
637 		if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
638 		    || diff_type == NEW_CONTEXT_DIFF
639 		    || diff_type == UNI_DIFF)) {
640 			say("Empty context always matches.\n");
641 		}
642 		return (first_guess);
643 	}
644 	if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
645 		max_neg_offset = first_guess - 1;
646 	if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
647 		return first_guess;
648 	for (offset = 1; ; offset++) {
649 		bool	check_after = (offset <= max_pos_offset);
650 		bool	check_before = (offset <= max_neg_offset);
651 
652 		if (check_after && patch_match(first_guess, offset, fuzz)) {
653 #ifdef DEBUGGING
654 			if (debug & 1)
655 				say("Offset changing from %ld to %ld\n",
656 				    last_offset, offset);
657 #endif
658 			last_offset = offset;
659 			return first_guess + offset;
660 		} else if (check_before && patch_match(first_guess, -offset, fuzz)) {
661 #ifdef DEBUGGING
662 			if (debug & 1)
663 				say("Offset changing from %ld to %ld\n",
664 				    last_offset, -offset);
665 #endif
666 			last_offset = -offset;
667 			return first_guess - offset;
668 		} else if (!check_before && !check_after)
669 			return 0;
670 	}
671 }
672 
673 /* We did not find the pattern, dump out the hunk so they can handle it. */
674 
675 static void
676 abort_context_hunk(void)
677 {
678 	LINENUM	i;
679 	const LINENUM	pat_end = pch_end();
680 	/*
681 	 * add in last_offset to guess the same as the previous successful
682 	 * hunk
683 	 */
684 	const LINENUM	oldfirst = pch_first() + last_offset;
685 	const LINENUM	newfirst = pch_newfirst() + last_offset;
686 	const LINENUM	oldlast = oldfirst + pch_ptrn_lines() - 1;
687 	const LINENUM	newlast = newfirst + pch_repl_lines() - 1;
688 	const char	*stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
689 	const char	*minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
690 
691 	fprintf(rejfp, "***************\n");
692 	for (i = 0; i <= pat_end; i++) {
693 		switch (pch_char(i)) {
694 		case '*':
695 			if (oldlast < oldfirst)
696 				fprintf(rejfp, "*** 0%s\n", stars);
697 			else if (oldlast == oldfirst)
698 				fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
699 			else
700 				fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
701 				    oldlast, stars);
702 			break;
703 		case '=':
704 			if (newlast < newfirst)
705 				fprintf(rejfp, "--- 0%s\n", minuses);
706 			else if (newlast == newfirst)
707 				fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
708 			else
709 				fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
710 				    newlast, minuses);
711 			break;
712 		case '\n':
713 			fprintf(rejfp, "%s", pfetch(i));
714 			break;
715 		case ' ':
716 		case '-':
717 		case '+':
718 		case '!':
719 			fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
720 			break;
721 		default:
722 			fatal("fatal internal error in abort_context_hunk\n");
723 		}
724 	}
725 }
726 
727 static void
728 rej_line(int ch, LINENUM i)
729 {
730 	size_t len;
731 	const char *line = pfetch(i);
732 
733 	len = strlen(line);
734 
735 	fprintf(rejfp, "%c%s", ch, line);
736 	if (len == 0 || line[len-1] != '\n')
737 		fprintf(rejfp, "\n\\ No newline at end of file\n");
738 }
739 
740 static void
741 abort_hunk(void)
742 {
743 	LINENUM		i, j, split;
744 	int		ch1, ch2;
745 	const LINENUM	pat_end = pch_end();
746 	const LINENUM	oldfirst = pch_first() + last_offset;
747 	const LINENUM	newfirst = pch_newfirst() + last_offset;
748 
749 	if (diff_type != UNI_DIFF) {
750 		abort_context_hunk();
751 		return;
752 	}
753 	split = -1;
754 	for (i = 0; i <= pat_end; i++) {
755 		if (pch_char(i) == '=') {
756 			split = i;
757 			break;
758 		}
759 	}
760 	if (split == -1) {
761 		fprintf(rejfp, "malformed hunk: no split found\n");
762 		return;
763 	}
764 	i = 0;
765 	j = split + 1;
766 	fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
767 	    pch_ptrn_lines() ? oldfirst : 0,
768 	    pch_ptrn_lines(), newfirst, pch_repl_lines());
769 	while (i < split || j <= pat_end) {
770 		ch1 = i < split ? pch_char(i) : -1;
771 		ch2 = j <= pat_end ? pch_char(j) : -1;
772 		if (ch1 == '-') {
773 			rej_line('-', i);
774 			i++;
775 		} else if (ch1 == ' ' && ch2 == ' ') {
776 			rej_line(' ', i);
777 			i++;
778 			j++;
779 		} else if (ch1 == '!' && ch2 == '!') {
780 			while (i < split && ch1 == '!') {
781 				rej_line('-', i);
782 				i++;
783 				ch1 = i < split ? pch_char(i) : -1;
784 			}
785 			while (j <= pat_end && ch2 == '!') {
786 				rej_line('+', j);
787 				j++;
788 				ch2 = j <= pat_end ? pch_char(j) : -1;
789 			}
790 		} else if (ch1 == '*') {
791 			i++;
792 		} else if (ch2 == '+' || ch2 == ' ') {
793 			rej_line(ch2, j);
794 			j++;
795 		} else {
796 			fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
797 			    i, split, j);
798 			rej_line(ch1, i);
799 			rej_line(ch2, j);
800 			return;
801 		}
802 	}
803 }
804 
805 /* We found where to apply it (we hope), so do it. */
806 
807 static void
808 apply_hunk(LINENUM where)
809 {
810 	LINENUM		old = 1;
811 	const LINENUM	lastline = pch_ptrn_lines();
812 	LINENUM		new = lastline + 1;
813 #define OUTSIDE 0
814 #define IN_IFNDEF 1
815 #define IN_IFDEF 2
816 #define IN_ELSE 3
817 	int		def_state = OUTSIDE;
818 	const LINENUM	pat_end = pch_end();
819 
820 	where--;
821 	while (pch_char(new) == '=' || pch_char(new) == '\n')
822 		new++;
823 
824 	while (old <= lastline) {
825 		if (pch_char(old) == '-') {
826 			copy_till(where + old - 1, false);
827 			if (do_defines) {
828 				if (def_state == OUTSIDE) {
829 					fputs(not_defined, ofp);
830 					def_state = IN_IFNDEF;
831 				} else if (def_state == IN_IFDEF) {
832 					fputs(else_defined, ofp);
833 					def_state = IN_ELSE;
834 				}
835 				fputs(pfetch(old), ofp);
836 			}
837 			last_frozen_line++;
838 			old++;
839 		} else if (new > pat_end) {
840 			break;
841 		} else if (pch_char(new) == '+') {
842 			copy_till(where + old - 1, false);
843 			if (do_defines) {
844 				if (def_state == IN_IFNDEF) {
845 					fputs(else_defined, ofp);
846 					def_state = IN_ELSE;
847 				} else if (def_state == OUTSIDE) {
848 					fputs(if_defined, ofp);
849 					def_state = IN_IFDEF;
850 				}
851 			}
852 			fputs(pfetch(new), ofp);
853 			new++;
854 		} else if (pch_char(new) != pch_char(old)) {
855 			say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
856 			    pch_hunk_beg() + old,
857 			    pch_hunk_beg() + new);
858 #ifdef DEBUGGING
859 			say("oldchar = '%c', newchar = '%c'\n",
860 			    pch_char(old), pch_char(new));
861 #endif
862 			my_exit(2);
863 		} else if (pch_char(new) == '!') {
864 			copy_till(where + old - 1, false);
865 			if (do_defines) {
866 				fputs(not_defined, ofp);
867 				def_state = IN_IFNDEF;
868 			}
869 			while (pch_char(old) == '!') {
870 				if (do_defines) {
871 					fputs(pfetch(old), ofp);
872 				}
873 				last_frozen_line++;
874 				old++;
875 			}
876 			if (do_defines) {
877 				fputs(else_defined, ofp);
878 				def_state = IN_ELSE;
879 			}
880 			while (pch_char(new) == '!') {
881 				fputs(pfetch(new), ofp);
882 				new++;
883 			}
884 		} else {
885 			if (pch_char(new) != ' ')
886 				fatal("Internal error: expected ' '\n");
887 			old++;
888 			new++;
889 			if (do_defines && def_state != OUTSIDE) {
890 				fputs(end_defined, ofp);
891 				def_state = OUTSIDE;
892 			}
893 		}
894 	}
895 	if (new <= pat_end && pch_char(new) == '+') {
896 		copy_till(where + old - 1, false);
897 		if (do_defines) {
898 			if (def_state == OUTSIDE) {
899 				fputs(if_defined, ofp);
900 				def_state = IN_IFDEF;
901 			} else if (def_state == IN_IFNDEF) {
902 				fputs(else_defined, ofp);
903 				def_state = IN_ELSE;
904 			}
905 		}
906 		while (new <= pat_end && pch_char(new) == '+') {
907 			fputs(pfetch(new), ofp);
908 			new++;
909 		}
910 	}
911 	if (do_defines && def_state != OUTSIDE) {
912 		fputs(end_defined, ofp);
913 	}
914 }
915 
916 /*
917  * Open the new file.
918  */
919 static void
920 init_output(const char *name)
921 {
922 	ofp = fopen(name, "w");
923 	if (ofp == NULL)
924 		pfatal("can't create %s", name);
925 }
926 
927 /*
928  * Open a file to put hunks we can't locate.
929  */
930 static void
931 init_reject(const char *name)
932 {
933 	rejfp = fopen(name, "w");
934 	if (rejfp == NULL)
935 		pfatal("can't create %s", name);
936 }
937 
938 /*
939  * Copy input file to output, up to wherever hunk is to be applied.
940  * If endoffile is true, treat the last line specially since it may
941  * lack a newline.
942  */
943 static void
944 copy_till(LINENUM lastline, bool endoffile)
945 {
946 	if (last_frozen_line > lastline)
947 		fatal("misordered hunks! output would be garbled\n");
948 	while (last_frozen_line < lastline) {
949 		if (++last_frozen_line == lastline && endoffile)
950 			dump_line(last_frozen_line, !last_line_missing_eol);
951 		else
952 			dump_line(last_frozen_line, true);
953 	}
954 }
955 
956 /*
957  * Finish copying the input file to the output file.
958  */
959 static bool
960 spew_output(void)
961 {
962 	int rv;
963 
964 #ifdef DEBUGGING
965 	if (debug & 256)
966 		say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
967 #endif
968 	if (input_lines)
969 		copy_till(input_lines, true);	/* dump remainder of file */
970 	rv = ferror(ofp) == 0 && fclose(ofp) == 0;
971 	ofp = NULL;
972 	return rv;
973 }
974 
975 /*
976  * Copy one line from input to output.
977  */
978 static void
979 dump_line(LINENUM line, bool write_newline)
980 {
981 	char	*s;
982 
983 	s = ifetch(line, 0);
984 	if (s == NULL)
985 		return;
986 	/* Note: string is not NUL terminated. */
987 	for (; *s != '\n'; s++)
988 		putc(*s, ofp);
989 	if (write_newline)
990 		putc('\n', ofp);
991 }
992 
993 /*
994  * Does the patch pattern match at line base+offset?
995  */
996 static bool
997 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
998 {
999 	LINENUM		pline = 1 + fuzz;
1000 	LINENUM		iline;
1001 	LINENUM		pat_lines = pch_ptrn_lines() - fuzz;
1002 	const char	*ilineptr;
1003 	const char	*plineptr;
1004 	short		plinelen;
1005 
1006 	for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1007 		ilineptr = ifetch(iline, offset >= 0);
1008 		if (ilineptr == NULL)
1009 			return false;
1010 		plineptr = pfetch(pline);
1011 		plinelen = pch_line_len(pline);
1012 		if (canonicalize) {
1013 			if (!similar(ilineptr, plineptr, plinelen))
1014 				return false;
1015 		} else if (strnNE(ilineptr, plineptr, plinelen))
1016 			return false;
1017 		if (iline == input_lines) {
1018 			/*
1019 			 * We are looking at the last line of the file.
1020 			 * If the file has no eol, the patch line should
1021 			 * not have one either and vice-versa. Note that
1022 			 * plinelen > 0.
1023 			 */
1024 			if (last_line_missing_eol) {
1025 				if (plineptr[plinelen - 1] == '\n')
1026 					return false;
1027 			} else {
1028 				if (plineptr[plinelen - 1] != '\n')
1029 					return false;
1030 			}
1031 		}
1032 	}
1033 	return true;
1034 }
1035 
1036 /*
1037  * Do two lines match with canonicalized white space?
1038  */
1039 static bool
1040 similar(const char *a, const char *b, int len)
1041 {
1042 	while (len) {
1043 		if (isspace((unsigned char)*b)) {	/* whitespace (or \n) to match? */
1044 			if (!isspace((unsigned char)*a))	/* no corresponding whitespace? */
1045 				return false;
1046 			while (len && isspace((unsigned char)*b) && *b != '\n')
1047 				b++, len--;	/* skip pattern whitespace */
1048 			while (isspace((unsigned char)*a) && *a != '\n')
1049 				a++;	/* skip target whitespace */
1050 			if (*a == '\n' || *b == '\n')
1051 				return (*a == *b);	/* should end in sync */
1052 		} else if (*a++ != *b++)	/* match non-whitespace chars */
1053 			return false;
1054 		else
1055 			len--;	/* probably not necessary */
1056 	}
1057 	return true;		/* actually, this is not reached */
1058 	/* since there is always a \n */
1059 }
1060