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