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