xref: /freebsd/usr.bin/patch/patch.c (revision 911f0260390e18cf85f3dbf2c719b593efdc1e3c)
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 if (filearg[0] != NULL)
467 				say("%d out of %d hunks %s while patching %s\n",
468 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed", filearg[0]);
469 			else
470 				/* File prompt ignored, just note # hunks. */
471 				say("%d out of %d hunks %s\n",
472 				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
473 			if (!check_only && move_file(TMPREJNAME, rejname) < 0)
474 				trejkeep = true;
475 		}
476 		set_signals(1);
477 	}
478 
479 	if (!patch_seen && nonempty_patchf_seen)
480 		error = 2;
481 
482 	my_exit(error);
483 	/* NOTREACHED */
484 }
485 
486 /* Prepare to find the next patch to do in the patch file. */
487 
488 static void
489 reinitialize_almost_everything(void)
490 {
491 	re_patch();
492 	re_input();
493 
494 	input_lines = 0;
495 	last_frozen_line = 0;
496 
497 	filec = 0;
498 	if (!out_of_mem) {
499 		free(filearg[0]);
500 		filearg[0] = NULL;
501 	}
502 
503 	free(source_file);
504 	source_file = NULL;
505 
506 	free(outname);
507 	outname = NULL;
508 
509 	last_offset = 0;
510 	diff_type = 0;
511 
512 	free(revision);
513 	revision = NULL;
514 
515 	reverse = reverse_flag_specified;
516 	skip_rest_of_patch = false;
517 
518 	get_some_switches();
519 }
520 
521 /* Process switches and filenames. */
522 
523 static void
524 get_some_switches(void)
525 {
526 	const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
527 	static struct option longopts[] = {
528 		{"backup",		no_argument,		0,	'b'},
529 		{"batch",		no_argument,		0,	't'},
530 		{"check",		no_argument,		0,	'C'},
531 		{"context",		no_argument,		0,	'c'},
532 		{"debug",		required_argument,	0,	'x'},
533 		{"directory",		required_argument,	0,	'd'},
534 		{"dry-run",		no_argument,		0,	'C'},
535 		{"ed",			no_argument,		0,	'e'},
536 		{"force",		no_argument,		0,	'f'},
537 		{"forward",		no_argument,		0,	'N'},
538 		{"fuzz",		required_argument,	0,	'F'},
539 		{"ifdef",		required_argument,	0,	'D'},
540 		{"input",		required_argument,	0,	'i'},
541 		{"ignore-whitespace",	no_argument,		0,	'l'},
542 		{"normal",		no_argument,		0,	'n'},
543 		{"output",		required_argument,	0,	'o'},
544 		{"prefix",		required_argument,	0,	'B'},
545 		{"quiet",		no_argument,		0,	's'},
546 		{"reject-file",		required_argument,	0,	'r'},
547 		{"remove-empty-files",	no_argument,		0,	'E'},
548 		{"reverse",		no_argument,		0,	'R'},
549 		{"silent",		no_argument,		0,	's'},
550 		{"strip",		required_argument,	0,	'p'},
551 		{"suffix",		required_argument,	0,	'z'},
552 		{"unified",		no_argument,		0,	'u'},
553 		{"version",		no_argument,		0,	'v'},
554 		{"version-control",	required_argument,	0,	'V'},
555 		{"posix",		no_argument,		&posix,	1},
556 		{NULL,			0,			0,	0}
557 	};
558 	int ch;
559 
560 	rejname[0] = '\0';
561 	Argc_last = Argc;
562 	Argv_last = Argv;
563 	if (!Argc)
564 		return;
565 	optreset = optind = 1;
566 	while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
567 		switch (ch) {
568 		case 'b':
569 			if (backup_type == none)
570 				backup_type = numbered_existing;
571 			if (optarg == NULL)
572 				break;
573 			if (verbose)
574 				say("Warning, the ``-b suffix'' option has been"
575 				    " obsoleted by the -z option.\n");
576 			/* FALLTHROUGH */
577 		case 'z':
578 			/* must directly follow 'b' case for backwards compat */
579 			simple_backup_suffix = xstrdup(optarg);
580 			break;
581 		case 'B':
582 			origprae = xstrdup(optarg);
583 			break;
584 		case 'c':
585 			diff_type = CONTEXT_DIFF;
586 			break;
587 		case 'C':
588 			check_only = true;
589 			break;
590 		case 'd':
591 			if (chdir(optarg) < 0)
592 				pfatal("can't cd to %s", optarg);
593 			break;
594 		case 'D':
595 			do_defines = true;
596 			if (!isalpha((unsigned char)*optarg) && *optarg != '_')
597 				fatal("argument to -D is not an identifier\n");
598 			snprintf(if_defined, sizeof if_defined,
599 			    "#ifdef %s\n", optarg);
600 			snprintf(not_defined, sizeof not_defined,
601 			    "#ifndef %s\n", optarg);
602 			snprintf(end_defined, sizeof end_defined,
603 			    "#endif /* %s */\n", optarg);
604 			break;
605 		case 'e':
606 			diff_type = ED_DIFF;
607 			break;
608 		case 'E':
609 			remove_empty_files = true;
610 			break;
611 		case 'f':
612 			force = true;
613 			break;
614 		case 'F':
615 			maxfuzz = atoi(optarg);
616 			break;
617 		case 'i':
618 			if (++filec == MAXFILEC)
619 				fatal("too many file arguments\n");
620 			filearg[filec] = xstrdup(optarg);
621 			break;
622 		case 'l':
623 			canonicalize = true;
624 			break;
625 		case 'n':
626 			diff_type = NORMAL_DIFF;
627 			break;
628 		case 'N':
629 			noreverse = true;
630 			break;
631 		case 'o':
632 			outname = xstrdup(optarg);
633 			break;
634 		case 'p':
635 			strippath = atoi(optarg);
636 			break;
637 		case 'r':
638 			if (strlcpy(rejname, optarg,
639 			    sizeof(rejname)) >= sizeof(rejname))
640 				fatal("argument for -r is too long\n");
641 			break;
642 		case 'R':
643 			reverse = true;
644 			reverse_flag_specified = true;
645 			break;
646 		case 's':
647 			verbose = false;
648 			break;
649 		case 't':
650 			batch = true;
651 			break;
652 		case 'u':
653 			diff_type = UNI_DIFF;
654 			break;
655 		case 'v':
656 			version();
657 			break;
658 		case 'V':
659 			backup_type = get_version(optarg);
660 			Vflag = true;
661 			break;
662 #ifdef DEBUGGING
663 		case 'x':
664 			debug = atoi(optarg);
665 			break;
666 #endif
667 		default:
668 			if (ch != '\0')
669 				usage();
670 			break;
671 		}
672 	}
673 	Argc -= optind;
674 	Argv += optind;
675 
676 	if (Argc > 0) {
677 		filearg[0] = xstrdup(*Argv++);
678 		Argc--;
679 		while (Argc > 0) {
680 			if (++filec == MAXFILEC)
681 				fatal("too many file arguments\n");
682 			filearg[filec] = xstrdup(*Argv++);
683 			Argc--;
684 		}
685 	}
686 
687 	if (getenv("POSIXLY_CORRECT") != NULL)
688 		posix = 1;
689 }
690 
691 static void
692 usage(void)
693 {
694 	fprintf(stderr,
695 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
696 "             [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
697 "             [-r rej-name] [-V t | nil | never | none] [-x number]\n"
698 "             [-z backup-ext] [--posix] [origfile [patchfile]]\n"
699 "       patch <patchfile\n");
700 	my_exit(EXIT_FAILURE);
701 }
702 
703 /*
704  * Attempt to find the right place to apply this hunk of patch.
705  */
706 static LINENUM
707 locate_hunk(LINENUM fuzz)
708 {
709 	LINENUM	first_guess = pch_first() + last_offset;
710 	LINENUM	offset;
711 	LINENUM	pat_lines = pch_ptrn_lines();
712 	LINENUM	max_pos_offset = input_lines - first_guess - pat_lines + 1;
713 	LINENUM	max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
714 
715 	if (pat_lines == 0) {		/* null range matches always */
716 		if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
717 		    || diff_type == NEW_CONTEXT_DIFF
718 		    || diff_type == UNI_DIFF)) {
719 			say("Empty context always matches.\n");
720 		}
721 		return (first_guess);
722 	}
723 	if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
724 		max_neg_offset = first_guess - 1;
725 	if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
726 		return first_guess;
727 	for (offset = 1; ; offset++) {
728 		bool	check_after = (offset <= max_pos_offset);
729 		bool	check_before = (offset <= max_neg_offset);
730 
731 		if (check_after && patch_match(first_guess, offset, fuzz)) {
732 #ifdef DEBUGGING
733 			if (debug & 1)
734 				say("Offset changing from %ld to %ld\n",
735 				    last_offset, offset);
736 #endif
737 			last_offset = offset;
738 			return first_guess + offset;
739 		} else if (check_before && patch_match(first_guess, -offset, fuzz)) {
740 #ifdef DEBUGGING
741 			if (debug & 1)
742 				say("Offset changing from %ld to %ld\n",
743 				    last_offset, -offset);
744 #endif
745 			last_offset = -offset;
746 			return first_guess - offset;
747 		} else if (!check_before && !check_after)
748 			return 0;
749 	}
750 }
751 
752 /* We did not find the pattern, dump out the hunk so they can handle it. */
753 
754 static void
755 abort_context_hunk(void)
756 {
757 	LINENUM	i;
758 	const LINENUM	pat_end = pch_end();
759 	/*
760 	 * add in last_offset to guess the same as the previous successful
761 	 * hunk
762 	 */
763 	const LINENUM	oldfirst = pch_first() + last_offset;
764 	const LINENUM	newfirst = pch_newfirst() + last_offset;
765 	const LINENUM	oldlast = oldfirst + pch_ptrn_lines() - 1;
766 	const LINENUM	newlast = newfirst + pch_repl_lines() - 1;
767 	const char	*stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
768 	const char	*minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
769 
770 	fprintf(rejfp, "***************\n");
771 	for (i = 0; i <= pat_end; i++) {
772 		switch (pch_char(i)) {
773 		case '*':
774 			if (oldlast < oldfirst)
775 				fprintf(rejfp, "*** 0%s\n", stars);
776 			else if (oldlast == oldfirst)
777 				fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
778 			else
779 				fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
780 				    oldlast, stars);
781 			break;
782 		case '=':
783 			if (newlast < newfirst)
784 				fprintf(rejfp, "--- 0%s\n", minuses);
785 			else if (newlast == newfirst)
786 				fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
787 			else
788 				fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
789 				    newlast, minuses);
790 			break;
791 		case '\n':
792 			fprintf(rejfp, "%s", pfetch(i));
793 			break;
794 		case ' ':
795 		case '-':
796 		case '+':
797 		case '!':
798 			fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
799 			break;
800 		default:
801 			fatal("fatal internal error in abort_context_hunk\n");
802 		}
803 	}
804 }
805 
806 static void
807 rej_line(int ch, LINENUM i)
808 {
809 	size_t len;
810 	const char *line = pfetch(i);
811 
812 	len = strlen(line);
813 
814 	fprintf(rejfp, "%c%s", ch, line);
815 	if (len == 0 || line[len - 1] != '\n') {
816 		if (len >= USHRT_MAX)
817 			fprintf(rejfp, "\n\\ Line too long\n");
818 		else
819 			fprintf(rejfp, "\n\\ No newline at end of line\n");
820 	}
821 }
822 
823 static void
824 abort_hunk(void)
825 {
826 	LINENUM		i, j, split;
827 	int		ch1, ch2;
828 	const LINENUM	pat_end = pch_end();
829 	const LINENUM	oldfirst = pch_first() + last_offset;
830 	const LINENUM	newfirst = pch_newfirst() + last_offset;
831 
832 	if (diff_type != UNI_DIFF) {
833 		abort_context_hunk();
834 		return;
835 	}
836 	split = -1;
837 	for (i = 0; i <= pat_end; i++) {
838 		if (pch_char(i) == '=') {
839 			split = i;
840 			break;
841 		}
842 	}
843 	if (split == -1) {
844 		fprintf(rejfp, "malformed hunk: no split found\n");
845 		return;
846 	}
847 	i = 0;
848 	j = split + 1;
849 	fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
850 	    pch_ptrn_lines() ? oldfirst : 0,
851 	    pch_ptrn_lines(), newfirst, pch_repl_lines());
852 	while (i < split || j <= pat_end) {
853 		ch1 = i < split ? pch_char(i) : -1;
854 		ch2 = j <= pat_end ? pch_char(j) : -1;
855 		if (ch1 == '-') {
856 			rej_line('-', i);
857 			i++;
858 		} else if (ch1 == ' ' && ch2 == ' ') {
859 			rej_line(' ', i);
860 			i++;
861 			j++;
862 		} else if (ch1 == '!' && ch2 == '!') {
863 			while (i < split && ch1 == '!') {
864 				rej_line('-', i);
865 				i++;
866 				ch1 = i < split ? pch_char(i) : -1;
867 			}
868 			while (j <= pat_end && ch2 == '!') {
869 				rej_line('+', j);
870 				j++;
871 				ch2 = j <= pat_end ? pch_char(j) : -1;
872 			}
873 		} else if (ch1 == '*') {
874 			i++;
875 		} else if (ch2 == '+' || ch2 == ' ') {
876 			rej_line(ch2, j);
877 			j++;
878 		} else {
879 			fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
880 			    i, split, j);
881 			rej_line(ch1, i);
882 			rej_line(ch2, j);
883 			return;
884 		}
885 	}
886 }
887 
888 /* We found where to apply it (we hope), so do it. */
889 
890 static void
891 apply_hunk(LINENUM where)
892 {
893 	LINENUM		old = 1;
894 	const LINENUM	lastline = pch_ptrn_lines();
895 	LINENUM		new = lastline + 1;
896 #define OUTSIDE 0
897 #define IN_IFNDEF 1
898 #define IN_IFDEF 2
899 #define IN_ELSE 3
900 	int		def_state = OUTSIDE;
901 	const LINENUM	pat_end = pch_end();
902 
903 	where--;
904 	while (pch_char(new) == '=' || pch_char(new) == '\n')
905 		new++;
906 
907 	while (old <= lastline) {
908 		if (pch_char(old) == '-') {
909 			copy_till(where + old - 1, false);
910 			if (do_defines) {
911 				if (def_state == OUTSIDE) {
912 					fputs(not_defined, ofp);
913 					def_state = IN_IFNDEF;
914 				} else if (def_state == IN_IFDEF) {
915 					fputs(else_defined, ofp);
916 					def_state = IN_ELSE;
917 				}
918 				fputs(pfetch(old), ofp);
919 			}
920 			last_frozen_line++;
921 			old++;
922 		} else if (new > pat_end) {
923 			break;
924 		} else if (pch_char(new) == '+') {
925 			copy_till(where + old - 1, false);
926 			if (do_defines) {
927 				if (def_state == IN_IFNDEF) {
928 					fputs(else_defined, ofp);
929 					def_state = IN_ELSE;
930 				} else if (def_state == OUTSIDE) {
931 					fputs(if_defined, ofp);
932 					def_state = IN_IFDEF;
933 				}
934 			}
935 			fputs(pfetch(new), ofp);
936 			new++;
937 		} else if (pch_char(new) != pch_char(old)) {
938 			say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
939 			    pch_hunk_beg() + old,
940 			    pch_hunk_beg() + new);
941 #ifdef DEBUGGING
942 			say("oldchar = '%c', newchar = '%c'\n",
943 			    pch_char(old), pch_char(new));
944 #endif
945 			my_exit(2);
946 		} else if (pch_char(new) == '!') {
947 			copy_till(where + old - 1, false);
948 			if (do_defines) {
949 				fputs(not_defined, ofp);
950 				def_state = IN_IFNDEF;
951 			}
952 			while (pch_char(old) == '!') {
953 				if (do_defines) {
954 					fputs(pfetch(old), ofp);
955 				}
956 				last_frozen_line++;
957 				old++;
958 			}
959 			if (do_defines) {
960 				fputs(else_defined, ofp);
961 				def_state = IN_ELSE;
962 			}
963 			while (pch_char(new) == '!') {
964 				fputs(pfetch(new), ofp);
965 				new++;
966 			}
967 		} else {
968 			if (pch_char(new) != ' ')
969 				fatal("Internal error: expected ' '\n");
970 			old++;
971 			new++;
972 			if (do_defines && def_state != OUTSIDE) {
973 				fputs(end_defined, ofp);
974 				def_state = OUTSIDE;
975 			}
976 		}
977 	}
978 	if (new <= pat_end && pch_char(new) == '+') {
979 		copy_till(where + old - 1, false);
980 		if (do_defines) {
981 			if (def_state == OUTSIDE) {
982 				fputs(if_defined, ofp);
983 				def_state = IN_IFDEF;
984 			} else if (def_state == IN_IFNDEF) {
985 				fputs(else_defined, ofp);
986 				def_state = IN_ELSE;
987 			}
988 		}
989 		while (new <= pat_end && pch_char(new) == '+') {
990 			fputs(pfetch(new), ofp);
991 			new++;
992 		}
993 	}
994 	if (do_defines && def_state != OUTSIDE) {
995 		fputs(end_defined, ofp);
996 	}
997 }
998 
999 /*
1000  * Open the new file.
1001  */
1002 static void
1003 init_output(const char *name)
1004 {
1005 	ofp = fopen(name, "w");
1006 	if (ofp == NULL)
1007 		pfatal("can't create %s", name);
1008 }
1009 
1010 /*
1011  * Open a file to put hunks we can't locate.
1012  */
1013 static void
1014 init_reject(const char *name)
1015 {
1016 	rejfp = fopen(name, "w");
1017 	if (rejfp == NULL)
1018 		pfatal("can't create %s", name);
1019 }
1020 
1021 /*
1022  * Copy input file to output, up to wherever hunk is to be applied.
1023  * If endoffile is true, treat the last line specially since it may
1024  * lack a newline.
1025  */
1026 static void
1027 copy_till(LINENUM lastline, bool endoffile)
1028 {
1029 	if (last_frozen_line > lastline)
1030 		fatal("misordered hunks! output would be garbled\n");
1031 	while (last_frozen_line < lastline) {
1032 		if (++last_frozen_line == lastline && endoffile)
1033 			dump_line(last_frozen_line, !last_line_missing_eol);
1034 		else
1035 			dump_line(last_frozen_line, true);
1036 	}
1037 }
1038 
1039 /*
1040  * Finish copying the input file to the output file.
1041  */
1042 static bool
1043 spew_output(void)
1044 {
1045 	int rv;
1046 
1047 #ifdef DEBUGGING
1048 	if (debug & 256)
1049 		say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
1050 #endif
1051 	if (input_lines)
1052 		copy_till(input_lines, true);	/* dump remainder of file */
1053 	rv = ferror(ofp) == 0 && fclose(ofp) == 0;
1054 	ofp = NULL;
1055 	return rv;
1056 }
1057 
1058 /*
1059  * Copy one line from input to output.
1060  */
1061 static void
1062 dump_line(LINENUM line, bool write_newline)
1063 {
1064 	char	*s;
1065 
1066 	s = ifetch(line, 0);
1067 	if (s == NULL)
1068 		return;
1069 	/* Note: string is not NUL terminated. */
1070 	for (; *s != '\n'; s++)
1071 		putc(*s, ofp);
1072 	if (write_newline)
1073 		putc('\n', ofp);
1074 }
1075 
1076 /*
1077  * Does the patch pattern match at line base+offset?
1078  */
1079 static bool
1080 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1081 {
1082 	LINENUM		pline = 1 + fuzz;
1083 	LINENUM		iline;
1084 	LINENUM		pat_lines = pch_ptrn_lines() - fuzz;
1085 	const char	*ilineptr;
1086 	const char	*plineptr;
1087 	unsigned short	plinelen;
1088 
1089 	/* Patch does not match if we don't have any more context to use */
1090 	if (pline > pat_lines)
1091 		return false;
1092 	for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1093 		ilineptr = ifetch(iline, offset >= 0);
1094 		if (ilineptr == NULL)
1095 			return false;
1096 		plineptr = pfetch(pline);
1097 		plinelen = pch_line_len(pline);
1098 		if (canonicalize) {
1099 			if (!similar(ilineptr, plineptr, plinelen))
1100 				return false;
1101 		} else if (strnNE(ilineptr, plineptr, plinelen))
1102 			return false;
1103 		if (iline == input_lines) {
1104 			/*
1105 			 * We are looking at the last line of the file.
1106 			 * If the file has no eol, the patch line should
1107 			 * not have one either and vice-versa. Note that
1108 			 * plinelen > 0.
1109 			 */
1110 			if (last_line_missing_eol) {
1111 				if (plineptr[plinelen - 1] == '\n')
1112 					return false;
1113 			} else {
1114 				if (plineptr[plinelen - 1] != '\n')
1115 					return false;
1116 			}
1117 		}
1118 	}
1119 	return true;
1120 }
1121 
1122 /*
1123  * Do two lines match with canonicalized white space?
1124  */
1125 static bool
1126 similar(const char *a, const char *b, int len)
1127 {
1128 	while (len) {
1129 		if (isspace((unsigned char)*b)) {	/* whitespace (or \n) to match? */
1130 			if (!isspace((unsigned char)*a))	/* no corresponding whitespace? */
1131 				return false;
1132 			while (len && isspace((unsigned char)*b) && *b != '\n')
1133 				b++, len--;	/* skip pattern whitespace */
1134 			while (isspace((unsigned char)*a) && *a != '\n')
1135 				a++;	/* skip target whitespace */
1136 			if (*a == '\n' || *b == '\n')
1137 				return (*a == *b);	/* should end in sync */
1138 		} else if (*a++ != *b++)	/* match non-whitespace chars */
1139 			return false;
1140 		else
1141 			len--;	/* probably not necessary */
1142 	}
1143 	return true;		/* actually, this is not reached */
1144 	/* since there is always a \n */
1145 }
1146 
1147 static bool
1148 handle_creation(bool out_existed, bool *remove)
1149 {
1150 	bool reverse_seen;
1151 
1152 	reverse_seen = false;
1153 	if (reverse && out_existed) {
1154 		/*
1155 		 * If the patch creates the file and we're reversing the patch,
1156 		 * then we need to indicate to the patch processor that it's OK
1157 		 * to remove this file.
1158 		 */
1159 		*remove = true;
1160 	} else if (!reverse && out_existed) {
1161 		/*
1162 		 * Otherwise, we need to blow the horn because the patch appears
1163 		 * to be reversed/already applied.  For non-batch jobs, we'll
1164 		 * prompt to figure out what we should be trying to do to raise
1165 		 * awareness of the issue.  batch (-t) processing suppresses the
1166 		 * questions and just assumes that we're reversed if it looks
1167 		 * like we are, which is always the case if we've reached this
1168 		 * branch.
1169 		 */
1170 		if (force) {
1171 			skip_rest_of_patch = true;
1172 			return (false);
1173 		}
1174 		if (noreverse) {
1175 			/* If -N is supplied, however, we bail out/ignore. */
1176 			say("Ignoring previously applied (or reversed) patch.\n");
1177 			skip_rest_of_patch = true;
1178 			return (false);
1179 		}
1180 
1181 		/* Unreversed... suspicious if the file existed. */
1182 		if (!pch_swap())
1183 			fatal("lost hunk on alloc error!\n");
1184 
1185 		reverse = !reverse;
1186 
1187 		if (batch) {
1188 			if (verbose)
1189 				say("Patch creates file that already exists, %s %seversed",
1190 				    reverse ? "Assuming" : "Ignoring",
1191 				    reverse ? "R" : "Unr");
1192 		} else {
1193 			ask("Patch creates file that already exists!  %s -R? [y] ",
1194 			    reverse ? "Assume" : "Ignore");
1195 
1196 			if (*buf == 'n') {
1197 				ask("Apply anyway? [n]");
1198 				if (*buf != 'y')
1199 					/* Don't apply; error out. */
1200 					skip_rest_of_patch = true;
1201 				else
1202 					/* Attempt to apply. */
1203 					reverse_seen = true;
1204 				reverse = !reverse;
1205 				if (!pch_swap())
1206 					fatal("lost hunk on alloc error!\n");
1207 			} else {
1208 				/*
1209 				 * They've opted to assume -R; effectively the
1210 				 * same as the first branch in this function,
1211 				 * but the decision is here rather than in a
1212 				 * prior patch/hunk as in that branch.
1213 				 */
1214 				*remove = true;
1215 			}
1216 		}
1217 	}
1218 
1219 	/*
1220 	 * The return value indicates if we offered a chance to reverse but the
1221 	 * user declined.  This keeps the main patch processor in the loop since
1222 	 * we've taken this out of the normal flow of hunk processing to
1223 	 * simplify logic a little bit.
1224 	 */
1225 	return (reverse_seen);
1226 }
1227