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