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