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