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