patch.c revision 267490
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 267490 2014-06-15 03:54:23Z 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, reverse_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		reverse_seen = false;
251		out_of_mem = false;
252		while (another_hunk()) {
253			hunk++;
254			fuzz = 0;
255			mymaxfuzz = pch_context();
256			if (maxfuzz < mymaxfuzz)
257				mymaxfuzz = maxfuzz;
258			if (!skip_rest_of_patch) {
259				do {
260					where = locate_hunk(fuzz);
261					if (hunk == 1 && where == 0 && !force && !reverse_seen) {
262						/* dwim for reversed patch? */
263						if (!pch_swap()) {
264							if (fuzz == 0)
265								say("Not enough memory to try swapped hunk!  Assuming unswapped.\n");
266							continue;
267						}
268						reverse = !reverse;
269						/* try again */
270						where = locate_hunk(fuzz);
271						if (where == 0) {
272							/* didn't find it swapped */
273							if (!pch_swap())
274								/* put it back to normal */
275								fatal("lost hunk on alloc error!\n");
276							reverse = !reverse;
277						} else if (noreverse) {
278							if (!pch_swap())
279								/* put it back to normal */
280								fatal("lost hunk on alloc error!\n");
281							reverse = !reverse;
282							say("Ignoring previously applied (or reversed) patch.\n");
283							skip_rest_of_patch = true;
284						} else if (batch) {
285							if (verbose)
286								say("%seversed (or previously applied) patch detected!  %s -R.",
287								    reverse ? "R" : "Unr",
288								    reverse ? "Assuming" : "Ignoring");
289						} else {
290							ask("%seversed (or previously applied) patch detected!  %s -R? [y] ",
291							    reverse ? "R" : "Unr",
292							    reverse ? "Assume" : "Ignore");
293							if (*buf == 'n') {
294								ask("Apply anyway? [n] ");
295								if (*buf != 'y')
296									skip_rest_of_patch = true;
297								else
298									reverse_seen = true;
299								where = 0;
300								reverse = !reverse;
301								if (!pch_swap())
302									/* put it back to normal */
303									fatal("lost hunk on alloc error!\n");
304							}
305						}
306					}
307				} while (!skip_rest_of_patch && where == 0 &&
308				    ++fuzz <= mymaxfuzz);
309
310				if (skip_rest_of_patch) {	/* just got decided */
311					if (ferror(ofp) || fclose(ofp)) {
312						say("Error writing %s\n",
313						    TMPOUTNAME);
314						error = 1;
315					}
316					ofp = NULL;
317				}
318			}
319			newwhere = pch_newfirst() + last_offset;
320			if (skip_rest_of_patch) {
321				abort_hunk();
322				failed++;
323				if (verbose)
324					say("Hunk #%d ignored at %ld.\n",
325					    hunk, newwhere);
326			} else if (where == 0) {
327				abort_hunk();
328				failed++;
329				if (verbose)
330					say("Hunk #%d failed at %ld.\n",
331					    hunk, newwhere);
332			} else {
333				apply_hunk(where);
334				if (verbose) {
335					say("Hunk #%d succeeded at %ld",
336					    hunk, newwhere);
337					if (fuzz != 0)
338						say(" with fuzz %ld", fuzz);
339					if (last_offset)
340						say(" (offset %ld line%s)",
341						    last_offset,
342						    last_offset == 1L ? "" : "s");
343					say(".\n");
344				}
345			}
346		}
347
348		if (out_of_mem && using_plan_a) {
349			Argc = Argc_last;
350			Argv = Argv_last;
351			say("\n\nRan out of memory using Plan A--trying again...\n\n");
352			if (ofp)
353				fclose(ofp);
354			ofp = NULL;
355			if (rejfp)
356				fclose(rejfp);
357			rejfp = NULL;
358			continue;
359		}
360		if (hunk == 0)
361			fatal("Internal error: hunk should not be 0\n");
362
363		/* finish spewing out the new file */
364		if (!skip_rest_of_patch && !spew_output()) {
365			say("Can't write %s\n", TMPOUTNAME);
366			error = 1;
367		}
368
369		/* and put the output where desired */
370		ignore_signals();
371		if (!skip_rest_of_patch) {
372			struct stat	statbuf;
373			char	*realout = outname;
374
375			if (!check_only) {
376				if (move_file(TMPOUTNAME, outname) < 0) {
377					toutkeep = true;
378					realout = TMPOUTNAME;
379					chmod(TMPOUTNAME, filemode);
380				} else
381					chmod(outname, filemode);
382
383				if (remove_empty_files &&
384				    stat(realout, &statbuf) == 0 &&
385				    statbuf.st_size == 0) {
386					if (verbose)
387						say("Removing %s (empty after patching).\n",
388						    realout);
389					unlink(realout);
390				}
391			}
392		}
393		if (ferror(rejfp) || fclose(rejfp)) {
394			say("Error writing %s\n", rejname);
395			error = 1;
396		}
397		rejfp = NULL;
398		if (failed) {
399			error = 1;
400			if (*rejname == '\0') {
401				if (strlcpy(rejname, outname,
402				    sizeof(rejname)) >= sizeof(rejname))
403					fatal("filename %s is too long\n", outname);
404				if (strlcat(rejname, REJEXT,
405				    sizeof(rejname)) >= sizeof(rejname))
406					fatal("filename %s is too long\n", outname);
407			}
408			if (!check_only)
409				say("%d out of %d hunks %s--saving rejects to %s\n",
410				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
411			else
412				say("%d out of %d hunks %s while patching %s\n",
413				    failed, hunk, skip_rest_of_patch ? "ignored" : "failed", filearg[0]);
414			if (!check_only && move_file(TMPREJNAME, rejname) < 0)
415				trejkeep = true;
416		}
417		set_signals(1);
418	}
419
420	if (!patch_seen)
421		error = 2;
422
423	my_exit(error);
424	/* NOTREACHED */
425}
426
427/* Prepare to find the next patch to do in the patch file. */
428
429static void
430reinitialize_almost_everything(void)
431{
432	re_patch();
433	re_input();
434
435	input_lines = 0;
436	last_frozen_line = 0;
437
438	filec = 0;
439	if (!out_of_mem) {
440		free(filearg[0]);
441		filearg[0] = NULL;
442	}
443
444	free(outname);
445	outname = NULL;
446
447	last_offset = 0;
448	diff_type = 0;
449
450	free(revision);
451	revision = NULL;
452
453	reverse = reverse_flag_specified;
454	skip_rest_of_patch = false;
455
456	get_some_switches();
457}
458
459/* Process switches and filenames. */
460
461static void
462get_some_switches(void)
463{
464	const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
465	static struct option longopts[] = {
466		{"backup",		no_argument,		0,	'b'},
467		{"batch",		no_argument,		0,	't'},
468		{"check",		no_argument,		0,	'C'},
469		{"context",		no_argument,		0,	'c'},
470		{"debug",		required_argument,	0,	'x'},
471		{"directory",		required_argument,	0,	'd'},
472		{"ed",			no_argument,		0,	'e'},
473		{"force",		no_argument,		0,	'f'},
474		{"forward",		no_argument,		0,	'N'},
475		{"fuzz",		required_argument,	0,	'F'},
476		{"ifdef",		required_argument,	0,	'D'},
477		{"input",		required_argument,	0,	'i'},
478		{"ignore-whitespace",	no_argument,		0,	'l'},
479		{"normal",		no_argument,		0,	'n'},
480		{"output",		required_argument,	0,	'o'},
481		{"prefix",		required_argument,	0,	'B'},
482		{"quiet",		no_argument,		0,	's'},
483		{"reject-file",		required_argument,	0,	'r'},
484		{"remove-empty-files",	no_argument,		0,	'E'},
485		{"reverse",		no_argument,		0,	'R'},
486		{"silent",		no_argument,		0,	's'},
487		{"strip",		required_argument,	0,	'p'},
488		{"suffix",		required_argument,	0,	'z'},
489		{"unified",		no_argument,		0,	'u'},
490		{"version",		no_argument,		0,	'v'},
491		{"version-control",	required_argument,	0,	'V'},
492		{"posix",		no_argument,		&posix,	1},
493		{NULL,			0,			0,	0}
494	};
495	int ch;
496
497	rejname[0] = '\0';
498	Argc_last = Argc;
499	Argv_last = Argv;
500	if (!Argc)
501		return;
502	optreset = optind = 1;
503	while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
504		switch (ch) {
505		case 'b':
506			if (backup_type == none)
507				backup_type = numbered_existing;
508			if (optarg == NULL)
509				break;
510			if (verbose)
511				say("Warning, the ``-b suffix'' option has been"
512				    " obsoleted by the -z option.\n");
513			/* FALLTHROUGH */
514		case 'z':
515			/* must directly follow 'b' case for backwards compat */
516			simple_backup_suffix = savestr(optarg);
517			break;
518		case 'B':
519			origprae = savestr(optarg);
520			break;
521		case 'c':
522			diff_type = CONTEXT_DIFF;
523			break;
524		case 'C':
525			check_only = true;
526			break;
527		case 'd':
528			if (chdir(optarg) < 0)
529				pfatal("can't cd to %s", optarg);
530			break;
531		case 'D':
532			do_defines = true;
533			if (!isalpha((unsigned char)*optarg) && *optarg != '_')
534				fatal("argument to -D is not an identifier\n");
535			snprintf(if_defined, sizeof if_defined,
536			    "#ifdef %s\n", optarg);
537			snprintf(not_defined, sizeof not_defined,
538			    "#ifndef %s\n", optarg);
539			snprintf(end_defined, sizeof end_defined,
540			    "#endif /* %s */\n", optarg);
541			break;
542		case 'e':
543			diff_type = ED_DIFF;
544			break;
545		case 'E':
546			remove_empty_files = true;
547			break;
548		case 'f':
549			force = true;
550			break;
551		case 'F':
552			maxfuzz = atoi(optarg);
553			break;
554		case 'i':
555			if (++filec == MAXFILEC)
556				fatal("too many file arguments\n");
557			filearg[filec] = savestr(optarg);
558			break;
559		case 'l':
560			canonicalize = true;
561			break;
562		case 'n':
563			diff_type = NORMAL_DIFF;
564			break;
565		case 'N':
566			noreverse = true;
567			break;
568		case 'o':
569			outname = savestr(optarg);
570			break;
571		case 'p':
572			strippath = atoi(optarg);
573			break;
574		case 'r':
575			if (strlcpy(rejname, optarg,
576			    sizeof(rejname)) >= sizeof(rejname))
577				fatal("argument for -r is too long\n");
578			break;
579		case 'R':
580			reverse = true;
581			reverse_flag_specified = true;
582			break;
583		case 's':
584			verbose = false;
585			break;
586		case 't':
587			batch = true;
588			break;
589		case 'u':
590			diff_type = UNI_DIFF;
591			break;
592		case 'v':
593			version();
594			break;
595		case 'V':
596			backup_type = get_version(optarg);
597			break;
598#ifdef DEBUGGING
599		case 'x':
600			debug = atoi(optarg);
601			break;
602#endif
603		default:
604			if (ch != '\0')
605				usage();
606			break;
607		}
608	}
609	Argc -= optind;
610	Argv += optind;
611
612	if (Argc > 0) {
613		filearg[0] = savestr(*Argv++);
614		Argc--;
615		while (Argc > 0) {
616			if (++filec == MAXFILEC)
617				fatal("too many file arguments\n");
618			filearg[filec] = savestr(*Argv++);
619			Argc--;
620		}
621	}
622
623	if (getenv("POSIXLY_CORRECT") != NULL)
624		posix = 1;
625}
626
627static void
628usage(void)
629{
630	fprintf(stderr,
631"usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
632"             [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
633"             [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
634"             [--posix] [origfile [patchfile]]\n"
635"       patch <patchfile\n");
636	my_exit(EXIT_SUCCESS);
637}
638
639/*
640 * Attempt to find the right place to apply this hunk of patch.
641 */
642static LINENUM
643locate_hunk(LINENUM fuzz)
644{
645	LINENUM	first_guess = pch_first() + last_offset;
646	LINENUM	offset;
647	LINENUM	pat_lines = pch_ptrn_lines();
648	LINENUM	max_pos_offset = input_lines - first_guess - pat_lines + 1;
649	LINENUM	max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
650
651	if (pat_lines == 0) {		/* null range matches always */
652		if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
653		    || diff_type == NEW_CONTEXT_DIFF
654		    || diff_type == UNI_DIFF)) {
655			say("Empty context always matches.\n");
656		}
657		return (first_guess);
658	}
659	if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
660		max_neg_offset = first_guess - 1;
661	if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
662		return first_guess;
663	for (offset = 1; ; offset++) {
664		bool	check_after = (offset <= max_pos_offset);
665		bool	check_before = (offset <= max_neg_offset);
666
667		if (check_after && patch_match(first_guess, offset, fuzz)) {
668#ifdef DEBUGGING
669			if (debug & 1)
670				say("Offset changing from %ld to %ld\n",
671				    last_offset, offset);
672#endif
673			last_offset = offset;
674			return first_guess + offset;
675		} else if (check_before && patch_match(first_guess, -offset, fuzz)) {
676#ifdef DEBUGGING
677			if (debug & 1)
678				say("Offset changing from %ld to %ld\n",
679				    last_offset, -offset);
680#endif
681			last_offset = -offset;
682			return first_guess - offset;
683		} else if (!check_before && !check_after)
684			return 0;
685	}
686}
687
688/* We did not find the pattern, dump out the hunk so they can handle it. */
689
690static void
691abort_context_hunk(void)
692{
693	LINENUM	i;
694	const LINENUM	pat_end = pch_end();
695	/*
696	 * add in last_offset to guess the same as the previous successful
697	 * hunk
698	 */
699	const LINENUM	oldfirst = pch_first() + last_offset;
700	const LINENUM	newfirst = pch_newfirst() + last_offset;
701	const LINENUM	oldlast = oldfirst + pch_ptrn_lines() - 1;
702	const LINENUM	newlast = newfirst + pch_repl_lines() - 1;
703	const char	*stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
704	const char	*minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
705
706	fprintf(rejfp, "***************\n");
707	for (i = 0; i <= pat_end; i++) {
708		switch (pch_char(i)) {
709		case '*':
710			if (oldlast < oldfirst)
711				fprintf(rejfp, "*** 0%s\n", stars);
712			else if (oldlast == oldfirst)
713				fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
714			else
715				fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
716				    oldlast, stars);
717			break;
718		case '=':
719			if (newlast < newfirst)
720				fprintf(rejfp, "--- 0%s\n", minuses);
721			else if (newlast == newfirst)
722				fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
723			else
724				fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
725				    newlast, minuses);
726			break;
727		case '\n':
728			fprintf(rejfp, "%s", pfetch(i));
729			break;
730		case ' ':
731		case '-':
732		case '+':
733		case '!':
734			fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
735			break;
736		default:
737			fatal("fatal internal error in abort_context_hunk\n");
738		}
739	}
740}
741
742static void
743rej_line(int ch, LINENUM i)
744{
745	unsigned short len;
746	const char *line = pfetch(i);
747
748	len = strnlen(line, USHRT_MAX);
749
750	fprintf(rejfp, "%c%s", ch, line);
751	if (len == 0 || line[len-1] != '\n') {
752		if (len >= USHRT_MAX)
753			fprintf(rejfp, "\n\\ Line too long\n");
754		else
755			fprintf(rejfp, "\n\\ No newline at end of line\n");
756	}
757}
758
759static void
760abort_hunk(void)
761{
762	LINENUM		i, j, split;
763	int		ch1, ch2;
764	const LINENUM	pat_end = pch_end();
765	const LINENUM	oldfirst = pch_first() + last_offset;
766	const LINENUM	newfirst = pch_newfirst() + last_offset;
767
768	if (diff_type != UNI_DIFF) {
769		abort_context_hunk();
770		return;
771	}
772	split = -1;
773	for (i = 0; i <= pat_end; i++) {
774		if (pch_char(i) == '=') {
775			split = i;
776			break;
777		}
778	}
779	if (split == -1) {
780		fprintf(rejfp, "malformed hunk: no split found\n");
781		return;
782	}
783	i = 0;
784	j = split + 1;
785	fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
786	    pch_ptrn_lines() ? oldfirst : 0,
787	    pch_ptrn_lines(), newfirst, pch_repl_lines());
788	while (i < split || j <= pat_end) {
789		ch1 = i < split ? pch_char(i) : -1;
790		ch2 = j <= pat_end ? pch_char(j) : -1;
791		if (ch1 == '-') {
792			rej_line('-', i);
793			i++;
794		} else if (ch1 == ' ' && ch2 == ' ') {
795			rej_line(' ', i);
796			i++;
797			j++;
798		} else if (ch1 == '!' && ch2 == '!') {
799			while (i < split && ch1 == '!') {
800				rej_line('-', i);
801				i++;
802				ch1 = i < split ? pch_char(i) : -1;
803			}
804			while (j <= pat_end && ch2 == '!') {
805				rej_line('+', j);
806				j++;
807				ch2 = j <= pat_end ? pch_char(j) : -1;
808			}
809		} else if (ch1 == '*') {
810			i++;
811		} else if (ch2 == '+' || ch2 == ' ') {
812			rej_line(ch2, j);
813			j++;
814		} else {
815			fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
816			    i, split, j);
817			rej_line(ch1, i);
818			rej_line(ch2, j);
819			return;
820		}
821	}
822}
823
824/* We found where to apply it (we hope), so do it. */
825
826static void
827apply_hunk(LINENUM where)
828{
829	LINENUM		old = 1;
830	const LINENUM	lastline = pch_ptrn_lines();
831	LINENUM		new = lastline + 1;
832#define OUTSIDE 0
833#define IN_IFNDEF 1
834#define IN_IFDEF 2
835#define IN_ELSE 3
836	int		def_state = OUTSIDE;
837	const LINENUM	pat_end = pch_end();
838
839	where--;
840	while (pch_char(new) == '=' || pch_char(new) == '\n')
841		new++;
842
843	while (old <= lastline) {
844		if (pch_char(old) == '-') {
845			copy_till(where + old - 1, false);
846			if (do_defines) {
847				if (def_state == OUTSIDE) {
848					fputs(not_defined, ofp);
849					def_state = IN_IFNDEF;
850				} else if (def_state == IN_IFDEF) {
851					fputs(else_defined, ofp);
852					def_state = IN_ELSE;
853				}
854				fputs(pfetch(old), ofp);
855			}
856			last_frozen_line++;
857			old++;
858		} else if (new > pat_end) {
859			break;
860		} else if (pch_char(new) == '+') {
861			copy_till(where + old - 1, false);
862			if (do_defines) {
863				if (def_state == IN_IFNDEF) {
864					fputs(else_defined, ofp);
865					def_state = IN_ELSE;
866				} else if (def_state == OUTSIDE) {
867					fputs(if_defined, ofp);
868					def_state = IN_IFDEF;
869				}
870			}
871			fputs(pfetch(new), ofp);
872			new++;
873		} else if (pch_char(new) != pch_char(old)) {
874			say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
875			    pch_hunk_beg() + old,
876			    pch_hunk_beg() + new);
877#ifdef DEBUGGING
878			say("oldchar = '%c', newchar = '%c'\n",
879			    pch_char(old), pch_char(new));
880#endif
881			my_exit(2);
882		} else if (pch_char(new) == '!') {
883			copy_till(where + old - 1, false);
884			if (do_defines) {
885				fputs(not_defined, ofp);
886				def_state = IN_IFNDEF;
887			}
888			while (pch_char(old) == '!') {
889				if (do_defines) {
890					fputs(pfetch(old), ofp);
891				}
892				last_frozen_line++;
893				old++;
894			}
895			if (do_defines) {
896				fputs(else_defined, ofp);
897				def_state = IN_ELSE;
898			}
899			while (pch_char(new) == '!') {
900				fputs(pfetch(new), ofp);
901				new++;
902			}
903		} else {
904			if (pch_char(new) != ' ')
905				fatal("Internal error: expected ' '\n");
906			old++;
907			new++;
908			if (do_defines && def_state != OUTSIDE) {
909				fputs(end_defined, ofp);
910				def_state = OUTSIDE;
911			}
912		}
913	}
914	if (new <= pat_end && pch_char(new) == '+') {
915		copy_till(where + old - 1, false);
916		if (do_defines) {
917			if (def_state == OUTSIDE) {
918				fputs(if_defined, ofp);
919				def_state = IN_IFDEF;
920			} else if (def_state == IN_IFNDEF) {
921				fputs(else_defined, ofp);
922				def_state = IN_ELSE;
923			}
924		}
925		while (new <= pat_end && pch_char(new) == '+') {
926			fputs(pfetch(new), ofp);
927			new++;
928		}
929	}
930	if (do_defines && def_state != OUTSIDE) {
931		fputs(end_defined, ofp);
932	}
933}
934
935/*
936 * Open the new file.
937 */
938static void
939init_output(const char *name)
940{
941	ofp = fopen(name, "w");
942	if (ofp == NULL)
943		pfatal("can't create %s", name);
944}
945
946/*
947 * Open a file to put hunks we can't locate.
948 */
949static void
950init_reject(const char *name)
951{
952	rejfp = fopen(name, "w");
953	if (rejfp == NULL)
954		pfatal("can't create %s", name);
955}
956
957/*
958 * Copy input file to output, up to wherever hunk is to be applied.
959 * If endoffile is true, treat the last line specially since it may
960 * lack a newline.
961 */
962static void
963copy_till(LINENUM lastline, bool endoffile)
964{
965	if (last_frozen_line > lastline)
966		fatal("misordered hunks! output would be garbled\n");
967	while (last_frozen_line < lastline) {
968		if (++last_frozen_line == lastline && endoffile)
969			dump_line(last_frozen_line, !last_line_missing_eol);
970		else
971			dump_line(last_frozen_line, true);
972	}
973}
974
975/*
976 * Finish copying the input file to the output file.
977 */
978static bool
979spew_output(void)
980{
981	int rv;
982
983#ifdef DEBUGGING
984	if (debug & 256)
985		say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
986#endif
987	if (input_lines)
988		copy_till(input_lines, true);	/* dump remainder of file */
989	rv = ferror(ofp) == 0 && fclose(ofp) == 0;
990	ofp = NULL;
991	return rv;
992}
993
994/*
995 * Copy one line from input to output.
996 */
997static void
998dump_line(LINENUM line, bool write_newline)
999{
1000	char	*s;
1001
1002	s = ifetch(line, 0);
1003	if (s == NULL)
1004		return;
1005	/* Note: string is not NUL terminated. */
1006	for (; *s != '\n'; s++)
1007		putc(*s, ofp);
1008	if (write_newline)
1009		putc('\n', ofp);
1010}
1011
1012/*
1013 * Does the patch pattern match at line base+offset?
1014 */
1015static bool
1016patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1017{
1018	LINENUM		pline = 1 + fuzz;
1019	LINENUM		iline;
1020	LINENUM		pat_lines = pch_ptrn_lines() - fuzz;
1021	const char	*ilineptr;
1022	const char	*plineptr;
1023	unsigned short	plinelen;
1024
1025	for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1026		ilineptr = ifetch(iline, offset >= 0);
1027		if (ilineptr == NULL)
1028			return false;
1029		plineptr = pfetch(pline);
1030		plinelen = pch_line_len(pline);
1031		if (canonicalize) {
1032			if (!similar(ilineptr, plineptr, plinelen))
1033				return false;
1034		} else if (strnNE(ilineptr, plineptr, plinelen))
1035			return false;
1036		if (iline == input_lines) {
1037			/*
1038			 * We are looking at the last line of the file.
1039			 * If the file has no eol, the patch line should
1040			 * not have one either and vice-versa. Note that
1041			 * plinelen > 0.
1042			 */
1043			if (last_line_missing_eol) {
1044				if (plineptr[plinelen - 1] == '\n')
1045					return false;
1046			} else {
1047				if (plineptr[plinelen - 1] != '\n')
1048					return false;
1049			}
1050		}
1051	}
1052	return true;
1053}
1054
1055/*
1056 * Do two lines match with canonicalized white space?
1057 */
1058static bool
1059similar(const char *a, const char *b, int len)
1060{
1061	while (len) {
1062		if (isspace((unsigned char)*b)) {	/* whitespace (or \n) to match? */
1063			if (!isspace((unsigned char)*a))	/* no corresponding whitespace? */
1064				return false;
1065			while (len && isspace((unsigned char)*b) && *b != '\n')
1066				b++, len--;	/* skip pattern whitespace */
1067			while (isspace((unsigned char)*a) && *a != '\n')
1068				a++;	/* skip target whitespace */
1069			if (*a == '\n' || *b == '\n')
1070				return (*a == *b);	/* should end in sync */
1071		} else if (*a++ != *b++)	/* match non-whitespace chars */
1072			return false;
1073		else
1074			len--;	/* probably not necessary */
1075	}
1076	return true;		/* actually, this is not reached */
1077	/* since there is always a \n */
1078}
1079