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