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