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