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