xref: /openbsd-src/usr.bin/patch/patch.c (revision 5c389b79544373bccfce668b646e62e7ba9802a3)
1 /*	$OpenBSD: patch.c,v 1.71 2022/08/03 07:30:37 op 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 *, int);
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", 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 
208 	if (backup_type == none) {
209 		if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
210 			v = getenv("VERSION_CONTROL");
211 		if (v != NULL || !posix)
212 			backup_type = get_version(v);	/* OK to pass NULL. */
213 	}
214 
215 	/* make sure we clean up /tmp in case of disaster */
216 	set_signals(0);
217 
218 	patch_seen = false;
219 	for (open_patch_file(filearg[1]); there_is_another_patch();
220 	    reinitialize_almost_everything()) {
221 		/* for each patch in patch file */
222 
223 		patch_seen = true;
224 
225 		warn_on_invalid_line = true;
226 
227 		if (outname == NULL)
228 			outname = xstrdup(filearg[0]);
229 
230 		/* initialize the patched file */
231 		if (!skip_rest_of_patch)
232 			init_output(TMPOUTNAME);
233 
234 		/* initialize reject file */
235 		init_reject(TMPREJNAME);
236 
237 		/* find out where all the lines are */
238 		if (!skip_rest_of_patch)
239 			scan_input(filearg[0]);
240 
241 		/* for ed script just up and do it and exit */
242 		if (diff_type == ED_DIFF) {
243 			do_ed_script();
244 			continue;
245 		}
246 
247 		/* from here on, open no standard i/o files, because malloc */
248 		/* might misfire and we can't catch it easily */
249 
250 		/* apply each hunk of patch */
251 		hunk = 0;
252 		failed = 0;
253 		out_of_mem = false;
254 		while (another_hunk()) {
255 			hunk++;
256 			fuzz = 0;
257 			mymaxfuzz = pch_context();
258 			if (maxfuzz < mymaxfuzz)
259 				mymaxfuzz = maxfuzz;
260 			if (!skip_rest_of_patch) {
261 				do {
262 					where = locate_hunk(fuzz);
263 					if ((hunk == 1 && where == 0 && !force) ||
264 					    (where == 1 && pch_ptrn_lines() == 0 && !force)) {
265 						/* dwim for reversed patch? */
266 						if (!pch_swap()) {
267 							if (fuzz == 0)
268 								say("Not enough memory to try swapped hunk!  Assuming unswapped.\n");
269 							continue;
270 						}
271 						reverse = !reverse;
272 						/* try again */
273 						where = locate_hunk(fuzz);
274 						if (where == 0) {
275 							/* didn't find it swapped */
276 							if (!pch_swap())
277 								/* put it back to normal */
278 								fatal("lost hunk on alloc error!\n");
279 							reverse = !reverse;
280 
281 							/* restore position if this patch creates a file */
282 							if (pch_ptrn_lines() == 0)
283 								where = 1;
284 						} else if (noreverse) {
285 							if (!pch_swap())
286 								/* put it back to normal */
287 								fatal("lost hunk on alloc error!\n");
288 							reverse = !reverse;
289 							say("Ignoring previously applied (or reversed) patch.\n");
290 							skip_rest_of_patch = true;
291 						} else if (batch) {
292 							if (verbose)
293 								say("%seversed (or previously applied) patch detected!  %s -R.",
294 								    reverse ? "R" : "Unr",
295 								    reverse ? "Assuming" : "Ignoring");
296 						} else {
297 							ask("%seversed (or previously applied) patch detected!  %s -R? [y] ",
298 							    reverse ? "R" : "Unr",
299 							    reverse ? "Assume" : "Ignore");
300 							if (*buf == 'n') {
301 								ask("Apply anyway? [n] ");
302 								if (*buf != 'y')
303 									skip_rest_of_patch = true;
304 								where = 0;
305 								reverse = !reverse;
306 								if (!pch_swap())
307 									/* put it back to normal */
308 									fatal("lost hunk on alloc error!\n");
309 							}
310 						}
311 					}
312 				} while (!skip_rest_of_patch && where == 0 &&
313 				    ++fuzz <= mymaxfuzz);
314 
315 				if (skip_rest_of_patch) {	/* just got decided */
316 					fclose(ofp);
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)
366 			spew_output();
367 
368 		/* and put the output where desired */
369 		ignore_signals();
370 		if (!skip_rest_of_patch) {
371 			struct stat	statbuf;
372 			char	*realout = outname;
373 
374 			if (!check_only) {
375 				if (move_file(TMPOUTNAME, outname) < 0) {
376 					toutkeep = true;
377 					realout = TMPOUTNAME;
378 					chmod(TMPOUTNAME, filemode);
379 				} else
380 					chmod(outname, filemode);
381 
382 				if (remove_empty_files &&
383 				    stat(realout, &statbuf) == 0 &&
384 				    statbuf.st_size == 0) {
385 					if (verbose)
386 						say("Removing %s (empty after patching).\n",
387 						    realout);
388 					unlink(realout);
389 				}
390 			}
391 		}
392 		fclose(rejfp);
393 		rejfp = NULL;
394 		if (failed) {
395 			error = 1;
396 			if (*rejname == '\0') {
397 				if (strlcpy(rejname, outname,
398 				    sizeof(rejname)) >= sizeof(rejname))
399 					fatal("filename %s is too long\n", outname);
400 				if (strlcat(rejname, REJEXT,
401 				    sizeof(rejname)) >= sizeof(rejname))
402 					fatal("filename %s is too long\n", outname);
403 			}
404 			if (!check_only)
405 				say("%d out of %d hunks %s--saving rejects to %s\n",
406 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
407 			else
408 				say("%d out of %d hunks %s\n",
409 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
410 			if (!check_only && move_file(TMPREJNAME, rejname) < 0)
411 				trejkeep = true;
412 		}
413 		set_signals(1);
414 	}
415 
416 	if (!patch_seen)
417 		error = 2;
418 
419 	my_exit(error);
420 	/* NOTREACHED */
421 }
422 
423 /* Prepare to find the next patch to do in the patch file. */
424 
425 static void
426 reinitialize_almost_everything(void)
427 {
428 	re_patch();
429 	re_input();
430 
431 	input_lines = 0;
432 	last_frozen_line = 0;
433 
434 	filec = 0;
435 	if (!out_of_mem) {
436 		free(filearg[0]);
437 		filearg[0] = NULL;
438 	}
439 
440 	free(outname);
441 	outname = NULL;
442 
443 	last_offset = 0;
444 	diff_type = 0;
445 
446 	free(revision);
447 	revision = NULL;
448 
449 	reverse = reverse_flag_specified;
450 	skip_rest_of_patch = false;
451 
452 	get_some_switches();
453 }
454 
455 /* Process switches and filenames. */
456 
457 static void
458 get_some_switches(void)
459 {
460 	const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
461 	static struct option longopts[] = {
462 		{"backup",		no_argument,		0,	'b'},
463 		{"batch",		no_argument,		0,	't'},
464 		{"check",		no_argument,		0,	'C'},
465 		{"context",		no_argument,		0,	'c'},
466 		{"debug",		required_argument,	0,	'x'},
467 		{"directory",		required_argument,	0,	'd'},
468 		{"dry-run",		no_argument,		0,	'C'},
469 		{"ed",			no_argument,		0,	'e'},
470 		{"force",		no_argument,		0,	'f'},
471 		{"forward",		no_argument,		0,	'N'},
472 		{"fuzz",		required_argument,	0,	'F'},
473 		{"ifdef",		required_argument,	0,	'D'},
474 		{"input",		required_argument,	0,	'i'},
475 		{"ignore-whitespace",	no_argument,		0,	'l'},
476 		{"normal",		no_argument,		0,	'n'},
477 		{"output",		required_argument,	0,	'o'},
478 		{"prefix",		required_argument,	0,	'B'},
479 		{"quiet",		no_argument,		0,	's'},
480 		{"reject-file",		required_argument,	0,	'r'},
481 		{"remove-empty-files",	no_argument,		0,	'E'},
482 		{"reverse",		no_argument,		0,	'R'},
483 		{"silent",		no_argument,		0,	's'},
484 		{"strip",		required_argument,	0,	'p'},
485 		{"suffix",		required_argument,	0,	'z'},
486 		{"unified",		no_argument,		0,	'u'},
487 		{"version",		no_argument,		0,	'v'},
488 		{"version-control",	required_argument,	0,	'V'},
489 		{"posix",		no_argument,		&posix,	1},
490 		{NULL,			0,			0,	0}
491 	};
492 	int ch;
493 
494 	rejname[0] = '\0';
495 	Argc_last = Argc;
496 	Argv_last = Argv;
497 	if (!Argc)
498 		return;
499 	optreset = optind = 1;
500 	while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
501 		switch (ch) {
502 		case 'b':
503 			if (backup_type == none)
504 				backup_type = numbered_existing;
505 			if (optarg == NULL)
506 				break;
507 			if (verbose)
508 				say("Warning, the ``-b suffix'' option has been"
509 				    " obsoleted by the -z option.\n");
510 			/* FALLTHROUGH */
511 		case 'z':
512 			/* must directly follow 'b' case for backwards compat */
513 			simple_backup_suffix = xstrdup(optarg);
514 			break;
515 		case 'B':
516 			origprae = xstrdup(optarg);
517 			break;
518 		case 'c':
519 			diff_type = CONTEXT_DIFF;
520 			break;
521 		case 'C':
522 			check_only = true;
523 			break;
524 		case 'd':
525 			if (chdir(optarg) == -1)
526 				pfatal("can't cd to %s", optarg);
527 			break;
528 		case 'D':
529 			do_defines = true;
530 			if (!isalpha((unsigned char)*optarg) && *optarg != '_')
531 				fatal("argument to -D is not an identifier\n");
532 			snprintf(if_defined, sizeof if_defined,
533 			    "#ifdef %s\n", optarg);
534 			snprintf(not_defined, sizeof not_defined,
535 			    "#ifndef %s\n", optarg);
536 			snprintf(end_defined, sizeof end_defined,
537 			    "#endif /* %s */\n", optarg);
538 			break;
539 		case 'e':
540 			diff_type = ED_DIFF;
541 			break;
542 		case 'E':
543 			remove_empty_files = true;
544 			break;
545 		case 'f':
546 			force = true;
547 			break;
548 		case 'F':
549 			maxfuzz = atoi(optarg);
550 			break;
551 		case 'i':
552 			if (++filec == MAXFILEC)
553 				fatal("too many file arguments\n");
554 			filearg[filec] = xstrdup(optarg);
555 			break;
556 		case 'l':
557 			canonicalize = true;
558 			break;
559 		case 'n':
560 			diff_type = NORMAL_DIFF;
561 			break;
562 		case 'N':
563 			noreverse = true;
564 			break;
565 		case 'o':
566 			outname = xstrdup(optarg);
567 			break;
568 		case 'p':
569 			strippath = atoi(optarg);
570 			break;
571 		case 'r':
572 			if (strlcpy(rejname, optarg,
573 			    sizeof(rejname)) >= sizeof(rejname))
574 				fatal("argument for -r is too long\n");
575 			break;
576 		case 'R':
577 			reverse = true;
578 			reverse_flag_specified = true;
579 			break;
580 		case 's':
581 			verbose = false;
582 			break;
583 		case 't':
584 			batch = true;
585 			break;
586 		case 'u':
587 			diff_type = UNI_DIFF;
588 			break;
589 		case 'v':
590 			version();
591 			break;
592 		case 'V':
593 			backup_type = get_version(optarg);
594 			break;
595 #ifdef DEBUGGING
596 		case 'x':
597 			debug = atoi(optarg);
598 			break;
599 #endif
600 		default:
601 			if (ch != '\0')
602 				usage();
603 			break;
604 		}
605 	}
606 	Argc -= optind;
607 	Argv += optind;
608 
609 	if (Argc > 0) {
610 		filearg[0] = xstrdup(*Argv++);
611 		Argc--;
612 		while (Argc > 0) {
613 			if (++filec == MAXFILEC)
614 				fatal("too many file arguments\n");
615 			filearg[filec] = xstrdup(*Argv++);
616 			Argc--;
617 		}
618 	}
619 
620 	if (getenv("POSIXLY_CORRECT") != NULL)
621 		posix = 1;
622 }
623 
624 static __dead void
625 usage(void)
626 {
627 	fprintf(stderr,
628 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
629 "             [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
630 "             [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
631 "             [--posix] [origfile [patchfile]]\n"
632 "       patch <patchfile\n");
633 	my_exit(2);
634 }
635 
636 /*
637  * Attempt to find the right place to apply this hunk of patch.
638  */
639 static LINENUM
640 locate_hunk(LINENUM fuzz)
641 {
642 	LINENUM	first_guess = pch_first() + last_offset;
643 	LINENUM	offset;
644 	LINENUM	pat_lines = pch_ptrn_lines();
645 	LINENUM	max_pos_offset = input_lines - first_guess - pat_lines + 1;
646 	LINENUM	max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
647 
648 	if (pat_lines == 0) {		/* null range matches always */
649 		if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
650 		    || diff_type == NEW_CONTEXT_DIFF
651 		    || diff_type == UNI_DIFF)) {
652 			say("Empty context always matches.\n");
653 		}
654 		if (first_guess == 0)
655 			return 1;
656 		return (first_guess);
657 	}
658 	if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
659 		max_neg_offset = first_guess - 1;
660 	if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
661 		return first_guess;
662 	for (offset = 1; ; offset++) {
663 		bool	check_after = (offset <= max_pos_offset);
664 		bool	check_before = (offset <= max_neg_offset);
665 
666 		if (check_after && patch_match(first_guess, offset, fuzz)) {
667 #ifdef DEBUGGING
668 			if (debug & 1)
669 				say("Offset changing from %ld to %ld\n",
670 				    last_offset, offset);
671 #endif
672 			last_offset = offset;
673 			return first_guess + offset;
674 		} else if (check_before && patch_match(first_guess, -offset, fuzz)) {
675 #ifdef DEBUGGING
676 			if (debug & 1)
677 				say("Offset changing from %ld to %ld\n",
678 				    last_offset, -offset);
679 #endif
680 			last_offset = -offset;
681 			return first_guess - offset;
682 		} else if (!check_before && !check_after)
683 			return 0;
684 	}
685 }
686 
687 /* We did not find the pattern, dump out the hunk so they can handle it. */
688 
689 static void
690 abort_context_hunk(void)
691 {
692 	LINENUM	i;
693 	const LINENUM	pat_end = pch_end();
694 	/*
695 	 * add in last_offset to guess the same as the previous successful
696 	 * hunk
697 	 */
698 	const LINENUM	oldfirst = pch_first() + last_offset;
699 	const LINENUM	newfirst = pch_newfirst() + last_offset;
700 	const LINENUM	oldlast = oldfirst + pch_ptrn_lines() - 1;
701 	const LINENUM	newlast = newfirst + pch_repl_lines() - 1;
702 	const char	*stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
703 	const char	*minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
704 
705 	fprintf(rejfp, "***************\n");
706 	for (i = 0; i <= pat_end; i++) {
707 		switch (pch_char(i)) {
708 		case '*':
709 			if (oldlast < oldfirst)
710 				fprintf(rejfp, "*** 0%s\n", stars);
711 			else if (oldlast == oldfirst)
712 				fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
713 			else
714 				fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
715 				    oldlast, stars);
716 			break;
717 		case '=':
718 			if (newlast < newfirst)
719 				fprintf(rejfp, "--- 0%s\n", minuses);
720 			else if (newlast == newfirst)
721 				fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
722 			else
723 				fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
724 				    newlast, minuses);
725 			break;
726 		case '\n':
727 			fprintf(rejfp, "%s", pfetch(i));
728 			break;
729 		case ' ':
730 		case '-':
731 		case '+':
732 		case '!':
733 			fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
734 			break;
735 		default:
736 			fatal("fatal internal error in abort_context_hunk\n");
737 		}
738 	}
739 }
740 
741 static void
742 rej_line(int ch, LINENUM i)
743 {
744 	size_t len;
745 	const char *line = pfetch(i);
746 
747 	len = strlen(line);
748 
749 	fprintf(rejfp, "%c%s", ch, line);
750 	if (len == 0 || line[len-1] != '\n')
751 		fprintf(rejfp, "\n\\ No newline at end of file\n");
752 }
753 
754 static void
755 abort_hunk(void)
756 {
757 	LINENUM		i, j, split;
758 	int		ch1, ch2;
759 	const LINENUM	pat_end = pch_end();
760 	const LINENUM	oldfirst = pch_first() + last_offset;
761 	const LINENUM	newfirst = pch_newfirst() + last_offset;
762 
763 	if (diff_type != UNI_DIFF) {
764 		abort_context_hunk();
765 		return;
766 	}
767 	split = -1;
768 	for (i = 0; i <= pat_end; i++) {
769 		if (pch_char(i) == '=') {
770 			split = i;
771 			break;
772 		}
773 	}
774 	if (split == -1) {
775 		fprintf(rejfp, "malformed hunk: no split found\n");
776 		return;
777 	}
778 	i = 0;
779 	j = split + 1;
780 	fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
781 	    pch_ptrn_lines() ? oldfirst : 0,
782 	    pch_ptrn_lines(), newfirst, pch_repl_lines());
783 	while (i < split || j <= pat_end) {
784 		ch1 = i < split ? pch_char(i) : -1;
785 		ch2 = j <= pat_end ? pch_char(j) : -1;
786 		if (ch1 == '-') {
787 			rej_line('-', i);
788 			i++;
789 		} else if (ch1 == ' ' && ch2 == ' ') {
790 			rej_line(' ', i);
791 			i++;
792 			j++;
793 		} else if (ch1 == '!' && ch2 == '!') {
794 			while (i < split && ch1 == '!') {
795 				rej_line('-', i);
796 				i++;
797 				ch1 = i < split ? pch_char(i) : -1;
798 			}
799 			while (j <= pat_end && ch2 == '!') {
800 				rej_line('+', j);
801 				j++;
802 				ch2 = j <= pat_end ? pch_char(j) : -1;
803 			}
804 		} else if (ch1 == '*') {
805 			i++;
806 		} else if (ch2 == '+' || ch2 == ' ') {
807 			rej_line(ch2, j);
808 			j++;
809 		} else {
810 			fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
811 			    i, split, j);
812 			rej_line(ch1, i);
813 			rej_line(ch2, j);
814 			return;
815 		}
816 	}
817 }
818 
819 /* We found where to apply it (we hope), so do it. */
820 
821 static void
822 apply_hunk(LINENUM where)
823 {
824 	LINENUM		old = 1;
825 	const LINENUM	lastline = pch_ptrn_lines();
826 	LINENUM		new = lastline + 1;
827 #define OUTSIDE 0
828 #define IN_IFNDEF 1
829 #define IN_IFDEF 2
830 #define IN_ELSE 3
831 	int		def_state = OUTSIDE;
832 	const LINENUM	pat_end = pch_end();
833 
834 	where--;
835 	while (pch_char(new) == '=' || pch_char(new) == '\n')
836 		new++;
837 
838 	while (old <= lastline) {
839 		if (pch_char(old) == '-') {
840 			copy_till(where + old - 1, false);
841 			if (do_defines) {
842 				if (def_state == OUTSIDE) {
843 					fputs(not_defined, ofp);
844 					def_state = IN_IFNDEF;
845 				} else if (def_state == IN_IFDEF) {
846 					fputs(else_defined, ofp);
847 					def_state = IN_ELSE;
848 				}
849 				fputs(pfetch(old), ofp);
850 			}
851 			last_frozen_line++;
852 			old++;
853 		} else if (new > pat_end) {
854 			break;
855 		} else if (pch_char(new) == '+') {
856 			copy_till(where + old - 1, false);
857 			if (do_defines) {
858 				if (def_state == IN_IFNDEF) {
859 					fputs(else_defined, ofp);
860 					def_state = IN_ELSE;
861 				} else if (def_state == OUTSIDE) {
862 					fputs(if_defined, ofp);
863 					def_state = IN_IFDEF;
864 				}
865 			}
866 			fputs(pfetch(new), ofp);
867 			new++;
868 		} else if (pch_char(new) != pch_char(old)) {
869 			say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
870 			    pch_hunk_beg() + old,
871 			    pch_hunk_beg() + new);
872 #ifdef DEBUGGING
873 			say("oldchar = '%c', newchar = '%c'\n",
874 			    pch_char(old), pch_char(new));
875 #endif
876 			my_exit(2);
877 		} else if (pch_char(new) == '!') {
878 			copy_till(where + old - 1, false);
879 			if (do_defines) {
880 				fputs(not_defined, ofp);
881 				def_state = IN_IFNDEF;
882 			}
883 			while (pch_char(old) == '!') {
884 				if (do_defines) {
885 					fputs(pfetch(old), ofp);
886 				}
887 				last_frozen_line++;
888 				old++;
889 			}
890 			if (do_defines) {
891 				fputs(else_defined, ofp);
892 				def_state = IN_ELSE;
893 			}
894 			while (pch_char(new) == '!') {
895 				fputs(pfetch(new), ofp);
896 				new++;
897 			}
898 		} else {
899 			if (pch_char(new) != ' ')
900 				fatal("Internal error: expected ' '\n");
901 			old++;
902 			new++;
903 			if (do_defines && def_state != OUTSIDE) {
904 				fputs(end_defined, ofp);
905 				def_state = OUTSIDE;
906 			}
907 		}
908 	}
909 	if (new <= pat_end && pch_char(new) == '+') {
910 		copy_till(where + old - 1, false);
911 		if (do_defines) {
912 			if (def_state == OUTSIDE) {
913 				fputs(if_defined, ofp);
914 				def_state = IN_IFDEF;
915 			} else if (def_state == IN_IFNDEF) {
916 				fputs(else_defined, ofp);
917 				def_state = IN_ELSE;
918 			}
919 		}
920 		while (new <= pat_end && pch_char(new) == '+') {
921 			fputs(pfetch(new), ofp);
922 			new++;
923 		}
924 	}
925 	if (do_defines && def_state != OUTSIDE) {
926 		fputs(end_defined, ofp);
927 	}
928 }
929 
930 /*
931  * Open the new file.
932  */
933 static void
934 init_output(const char *name)
935 {
936 	ofp = fopen(name, "w");
937 	if (ofp == NULL)
938 		pfatal("can't create %s", name);
939 }
940 
941 /*
942  * Open a file to put hunks we can't locate.
943  */
944 static void
945 init_reject(const char *name)
946 {
947 	rejfp = fopen(name, "w");
948 	if (rejfp == NULL)
949 		pfatal("can't create %s", name);
950 }
951 
952 /*
953  * Copy input file to output, up to wherever hunk is to be applied.
954  * If endoffile is true, treat the last line specially since it may
955  * lack a newline.
956  */
957 static void
958 copy_till(LINENUM lastline, bool endoffile)
959 {
960 	if (last_frozen_line > lastline)
961 		fatal("misordered hunks! output would be garbled\n");
962 	while (last_frozen_line < lastline) {
963 		if (++last_frozen_line == lastline && endoffile)
964 			dump_line(last_frozen_line, !last_line_missing_eol);
965 		else
966 			dump_line(last_frozen_line, true);
967 	}
968 }
969 
970 /*
971  * Finish copying the input file to the output file.
972  */
973 static void
974 spew_output(void)
975 {
976 #ifdef DEBUGGING
977 	if (debug & 256)
978 		say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
979 #endif
980 	if (input_lines)
981 		copy_till(input_lines, true);	/* dump remainder of file */
982 	fclose(ofp);
983 	ofp = NULL;
984 }
985 
986 /*
987  * Copy one line from input to output.
988  */
989 static void
990 dump_line(LINENUM line, bool write_newline)
991 {
992 	char	*s;
993 
994 	s = ifetch(line, 0);
995 	if (s == NULL)
996 		return;
997 	/* Note: string is not NUL terminated. */
998 	for (; *s != '\n'; s++)
999 		putc(*s, ofp);
1000 	if (write_newline)
1001 		putc('\n', ofp);
1002 }
1003 
1004 /*
1005  * Does the patch pattern match at line base+offset?
1006  */
1007 static bool
1008 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1009 {
1010 	LINENUM		pline = 1 + fuzz;
1011 	LINENUM		iline;
1012 	LINENUM		pat_lines = pch_ptrn_lines() - fuzz;
1013 	const char	*ilineptr;
1014 	const char	*plineptr;
1015 	short		plinelen;
1016 
1017 	for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1018 		ilineptr = ifetch(iline, offset >= 0);
1019 		if (ilineptr == NULL)
1020 			return false;
1021 		plineptr = pfetch(pline);
1022 		plinelen = pch_line_len(pline);
1023 		if (canonicalize) {
1024 			if (!similar(ilineptr, plineptr, plinelen))
1025 				return false;
1026 		} else if (strnNE(ilineptr, plineptr, plinelen))
1027 			return false;
1028 		if (iline == input_lines) {
1029 			/*
1030 			 * We are looking at the last line of the file.
1031 			 * If the file has no eol, the patch line should
1032 			 * not have one either and vice-versa. Note that
1033 			 * plinelen > 0.
1034 			 */
1035 			if (last_line_missing_eol) {
1036 				if (plineptr[plinelen - 1] == '\n')
1037 					return false;
1038 			} else {
1039 				if (plineptr[plinelen - 1] != '\n')
1040 					return false;
1041 			}
1042 		}
1043 	}
1044 	return true;
1045 }
1046 
1047 /*
1048  * Do two lines match with canonicalized white space?
1049  */
1050 static bool
1051 similar(const char *a, const char *b, int len)
1052 {
1053 	while (len) {
1054 		if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1055 			if (!isspace((unsigned char)*a))
1056 				return false;	/* no corresponding whitespace */
1057 			while (len && isspace((unsigned char)*b) && *b != '\n')
1058 				b++, len--;	/* skip pattern whitespace */
1059 			while (isspace((unsigned char)*a) && *a != '\n')
1060 				a++;	/* skip target whitespace */
1061 			if (*a == '\n' || *b == '\n')
1062 				return (*a == *b);	/* should end in sync */
1063 		} else if (*a++ != *b++)	/* match non-whitespace chars */
1064 			return false;
1065 		else
1066 			len--;	/* probably not necessary */
1067 	}
1068 	return true;		/* actually, this is not reached */
1069 	/* since there is always a \n */
1070 }
1071