pch.c revision 345878
1246074Sgabor/*-
2246074Sgabor * Copyright 1986, Larry Wall
3246074Sgabor *
4246074Sgabor * Redistribution and use in source and binary forms, with or without
5246074Sgabor * modification, are permitted provided that the following condition is met:
6246074Sgabor * 1. Redistributions of source code must retain the above copyright notice,
7246074Sgabor * this condition and the following disclaimer.
8246074Sgabor *
9246074Sgabor * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10246074Sgabor * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11246074Sgabor * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12246074Sgabor * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13246074Sgabor * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14246074Sgabor * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15246074Sgabor * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16246074Sgabor * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17246074Sgabor * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18246074Sgabor * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
19246074Sgabor * SUCH DAMAGE.
20246074Sgabor *
21246074Sgabor * patch - a program to apply diffs to original files
22246074Sgabor *
23246074Sgabor * -C option added in 1998, original code by Marc Espie, based on FreeBSD
24246074Sgabor * behaviour
25246074Sgabor *
26275582Spfg * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
27246091Sdelphij * $FreeBSD: stable/11/usr.bin/patch/pch.c 345878 2019-04-04 17:21:30Z kevans $
28246074Sgabor */
29246074Sgabor
30246074Sgabor#include <sys/types.h>
31246074Sgabor#include <sys/stat.h>
32246074Sgabor
33246074Sgabor#include <ctype.h>
34246074Sgabor#include <libgen.h>
35246074Sgabor#include <limits.h>
36281800Spfg#include <stdint.h>
37246074Sgabor#include <stdio.h>
38246074Sgabor#include <stdlib.h>
39246074Sgabor#include <string.h>
40246074Sgabor#include <unistd.h>
41246074Sgabor
42246074Sgabor#include "common.h"
43246074Sgabor#include "util.h"
44246074Sgabor#include "pch.h"
45246074Sgabor#include "pathnames.h"
46246074Sgabor
47246074Sgabor/* Patch (diff listing) abstract type. */
48246074Sgabor
49275553Spfgstatic off_t	p_filesize;	/* size of the patch file */
50246074Sgaborstatic LINENUM	p_first;	/* 1st line number */
51246074Sgaborstatic LINENUM	p_newfirst;	/* 1st line number of replacement */
52246074Sgaborstatic LINENUM	p_ptrn_lines;	/* # lines in pattern */
53246074Sgaborstatic LINENUM	p_repl_lines;	/* # lines in replacement text */
54246074Sgaborstatic LINENUM	p_end = -1;	/* last line in hunk */
55246074Sgaborstatic LINENUM	p_max;		/* max allowed value of p_end */
56246074Sgaborstatic LINENUM	p_context = 3;	/* # of context lines */
57246074Sgaborstatic LINENUM	p_input_line = 0;	/* current line # from patch file */
58246074Sgaborstatic char	**p_line = NULL;/* the text of the hunk */
59267490Spfgstatic unsigned short	*p_len = NULL; /* length of each line */
60246074Sgaborstatic char	*p_char = NULL;	/* +, -, and ! */
61246074Sgaborstatic int	hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
62246074Sgaborstatic int	p_indent;	/* indent to patch */
63275553Spfgstatic off_t	p_base;		/* where to intuit this time */
64246074Sgaborstatic LINENUM	p_bline;	/* line # of p_base */
65275553Spfgstatic off_t	p_start;	/* where intuit found a patch */
66246074Sgaborstatic LINENUM	p_sline;	/* and the line number for it */
67246074Sgaborstatic LINENUM	p_hunk_beg;	/* line number of current hunk */
68246074Sgaborstatic LINENUM	p_efake = -1;	/* end of faked up lines--don't free */
69246074Sgaborstatic LINENUM	p_bfake = -1;	/* beg of faked up lines */
70246074Sgaborstatic FILE	*pfp = NULL;	/* patch file pointer */
71246074Sgaborstatic char	*bestguess = NULL;	/* guess at correct filename */
72246074Sgabor
73246074Sgaborstatic void	grow_hunkmax(void);
74246074Sgaborstatic int	intuit_diff_type(void);
75275553Spfgstatic void	next_intuit_at(off_t, LINENUM);
76275553Spfgstatic void	skip_to(off_t, LINENUM);
77246074Sgaborstatic size_t	pgets(bool _do_indent);
78246074Sgaborstatic char	*best_name(const struct file_name *, bool);
79246074Sgaborstatic char	*posix_name(const struct file_name *, bool);
80246074Sgaborstatic size_t	num_components(const char *);
81275612Spfgstatic LINENUM	strtolinenum(char *, char **);
82246074Sgabor
83246074Sgabor/*
84246074Sgabor * Prepare to look for the next patch in the patch file.
85246074Sgabor */
86246074Sgaborvoid
87246074Sgaborre_patch(void)
88246074Sgabor{
89246074Sgabor	p_first = 0;
90246074Sgabor	p_newfirst = 0;
91246074Sgabor	p_ptrn_lines = 0;
92246074Sgabor	p_repl_lines = 0;
93246074Sgabor	p_end = (LINENUM) - 1;
94246074Sgabor	p_max = 0;
95246074Sgabor	p_indent = 0;
96246074Sgabor}
97246074Sgabor
98246074Sgabor/*
99246074Sgabor * Open the patch file at the beginning of time.
100246074Sgabor */
101246074Sgaborvoid
102246074Sgaboropen_patch_file(const char *filename)
103246074Sgabor{
104246074Sgabor	struct stat filestat;
105252636Sobrien	int nr, nw;
106246074Sgabor
107246074Sgabor	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
108246074Sgabor		pfp = fopen(TMPPATNAME, "w");
109246074Sgabor		if (pfp == NULL)
110246074Sgabor			pfatal("can't create %s", TMPPATNAME);
111252636Sobrien		while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
112252636Sobrien			nw = fwrite(buf, 1, nr, pfp);
113252636Sobrien			if (nr != nw)
114252636Sobrien				pfatal("write error to %s", TMPPATNAME);
115252636Sobrien		}
116246074Sgabor		if (ferror(pfp) || fclose(pfp))
117246074Sgabor			pfatal("can't write %s", TMPPATNAME);
118246074Sgabor		filename = TMPPATNAME;
119246074Sgabor	}
120246074Sgabor	pfp = fopen(filename, "r");
121246074Sgabor	if (pfp == NULL)
122246074Sgabor		pfatal("patch file %s not found", filename);
123275553Spfg	if (fstat(fileno(pfp), &filestat))
124275553Spfg		pfatal("can't stat %s", filename);
125246074Sgabor	p_filesize = filestat.st_size;
126275553Spfg	next_intuit_at(0, 1L);	/* start at the beginning */
127246074Sgabor	set_hunkmax();
128246074Sgabor}
129246074Sgabor
130246074Sgabor/*
131246074Sgabor * Make sure our dynamically realloced tables are malloced to begin with.
132246074Sgabor */
133246074Sgaborvoid
134246074Sgaborset_hunkmax(void)
135246074Sgabor{
136246074Sgabor	if (p_line == NULL)
137267464Spfg		p_line = malloc(hunkmax * sizeof(char *));
138246074Sgabor	if (p_len == NULL)
139267490Spfg		p_len = malloc(hunkmax * sizeof(unsigned short));
140246074Sgabor	if (p_char == NULL)
141267464Spfg		p_char = malloc(hunkmax * sizeof(char));
142246074Sgabor}
143246074Sgabor
144246074Sgabor/*
145246074Sgabor * Enlarge the arrays containing the current hunk of patch.
146246074Sgabor */
147246074Sgaborstatic void
148246074Sgaborgrow_hunkmax(void)
149246074Sgabor{
150267464Spfg	int new_hunkmax = hunkmax * 2;
151246074Sgabor
152246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL)
153246074Sgabor		fatal("Internal memory allocation error\n");
154246074Sgabor
155267464Spfg	p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
156267490Spfg	p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
157267464Spfg	p_char = reallocf(p_char, new_hunkmax * sizeof(char));
158246074Sgabor
159246074Sgabor	if (p_line != NULL && p_len != NULL && p_char != NULL) {
160246074Sgabor		hunkmax = new_hunkmax;
161246074Sgabor		return;
162246074Sgabor	}
163246074Sgabor
164246074Sgabor	if (!using_plan_a)
165246074Sgabor		fatal("out of memory\n");
166246074Sgabor	out_of_mem = true;	/* whatever is null will be allocated again */
167246074Sgabor				/* from within plan_a(), of all places */
168246074Sgabor}
169246074Sgabor
170246074Sgabor/* True if the remainder of the patch file contains a diff of some sort. */
171246074Sgabor
172246074Sgaborbool
173246074Sgaborthere_is_another_patch(void)
174246074Sgabor{
175246074Sgabor	bool exists = false;
176246074Sgabor
177275553Spfg	if (p_base != 0 && p_base >= p_filesize) {
178246074Sgabor		if (verbose)
179246074Sgabor			say("done\n");
180246074Sgabor		return false;
181246074Sgabor	}
182345878Skevans	if (p_filesize == 0)
183345878Skevans		return false;
184345878Skevans	nonempty_patchf_seen = true;
185246074Sgabor	if (verbose)
186246074Sgabor		say("Hmm...");
187246074Sgabor	diff_type = intuit_diff_type();
188246074Sgabor	if (!diff_type) {
189275553Spfg		if (p_base != 0) {
190246074Sgabor			if (verbose)
191246074Sgabor				say("  Ignoring the trailing garbage.\ndone\n");
192246074Sgabor		} else
193246074Sgabor			say("  I can't seem to find a patch in there anywhere.\n");
194246074Sgabor		return false;
195246074Sgabor	}
196246074Sgabor	if (verbose)
197246074Sgabor		say("  %sooks like %s to me...\n",
198275553Spfg		    (p_base == 0 ? "L" : "The next patch l"),
199246074Sgabor		    diff_type == UNI_DIFF ? "a unified diff" :
200246074Sgabor		    diff_type == CONTEXT_DIFF ? "a context diff" :
201246074Sgabor		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
202246074Sgabor		    diff_type == NORMAL_DIFF ? "a normal diff" :
203246074Sgabor		    "an ed script");
204246074Sgabor	if (p_indent && verbose)
205246074Sgabor		say("(Patch is indented %d space%s.)\n", p_indent,
206246074Sgabor		    p_indent == 1 ? "" : "s");
207246074Sgabor	skip_to(p_start, p_sline);
208246074Sgabor	while (filearg[0] == NULL) {
209246074Sgabor		if (force || batch) {
210246074Sgabor			say("No file to patch.  Skipping...\n");
211276218Spfg			filearg[0] = xstrdup(bestguess);
212246074Sgabor			skip_rest_of_patch = true;
213246074Sgabor			return true;
214246074Sgabor		}
215246074Sgabor		ask("File to patch: ");
216246074Sgabor		if (*buf != '\n') {
217246074Sgabor			free(bestguess);
218276218Spfg			bestguess = xstrdup(buf);
219246074Sgabor			filearg[0] = fetchname(buf, &exists, 0);
220246074Sgabor		}
221246074Sgabor		if (!exists) {
222320084Spfg			int def_skip = *bestguess == '\0';
223320084Spfg			ask("No file found--skip this patch? [%c] ",
224320084Spfg			    def_skip  ? 'y' : 'n');
225320084Spfg			if (*buf == 'n' || (!def_skip && *buf != 'y'))
226246074Sgabor				continue;
227246074Sgabor			if (verbose)
228246074Sgabor				say("Skipping patch...\n");
229246074Sgabor			free(filearg[0]);
230246074Sgabor			filearg[0] = fetchname(bestguess, &exists, 0);
231246074Sgabor			skip_rest_of_patch = true;
232246074Sgabor			return true;
233246074Sgabor		}
234246074Sgabor	}
235246074Sgabor	return true;
236246074Sgabor}
237246074Sgabor
238246074Sgaborstatic void
239246074Sgaborp4_fetchname(struct file_name *name, char *str)
240246074Sgabor{
241246074Sgabor	char *t, *h;
242246074Sgabor
243246074Sgabor	/* Skip leading whitespace. */
244246074Sgabor	while (isspace((unsigned char)*str))
245246074Sgabor		str++;
246246074Sgabor
247246074Sgabor	/* Remove the file revision number. */
248246074Sgabor	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
249246074Sgabor		if (*t == '#')
250246074Sgabor			h = t;
251246074Sgabor	if (h != NULL)
252246074Sgabor		*h = '\0';
253246074Sgabor
254246074Sgabor	name->path = fetchname(str, &name->exists, strippath);
255246074Sgabor}
256246074Sgabor
257246074Sgabor/* Determine what kind of diff is in the remaining part of the patch file. */
258246074Sgabor
259246074Sgaborstatic int
260246074Sgaborintuit_diff_type(void)
261246074Sgabor{
262275553Spfg	off_t	this_line = 0, previous_line;
263275553Spfg	off_t	first_command_line = -1;
264246074Sgabor	LINENUM	fcl_line = -1;
265246074Sgabor	bool	last_line_was_command = false, this_is_a_command = false;
266246074Sgabor	bool	stars_last_line = false, stars_this_line = false;
267246074Sgabor	char	*s, *t;
268246074Sgabor	int	indent, retval;
269246074Sgabor	struct file_name names[MAX_FILE];
270331047Seadler	int	piece_of_git = 0;
271246074Sgabor
272246074Sgabor	memset(names, 0, sizeof(names));
273246074Sgabor	ok_to_create_file = false;
274275553Spfg	fseeko(pfp, p_base, SEEK_SET);
275246074Sgabor	p_input_line = p_bline - 1;
276246074Sgabor	for (;;) {
277246074Sgabor		previous_line = this_line;
278246074Sgabor		last_line_was_command = this_is_a_command;
279246074Sgabor		stars_last_line = stars_this_line;
280275553Spfg		this_line = ftello(pfp);
281246074Sgabor		indent = 0;
282246074Sgabor		p_input_line++;
283246074Sgabor		if (pgets(false) == 0) {
284275553Spfg			if (first_command_line >= 0) {
285246074Sgabor				/* nothing but deletes!? */
286246074Sgabor				p_start = first_command_line;
287246074Sgabor				p_sline = fcl_line;
288246074Sgabor				retval = ED_DIFF;
289246074Sgabor				goto scan_exit;
290246074Sgabor			} else {
291246074Sgabor				p_start = this_line;
292246074Sgabor				p_sline = p_input_line;
293246074Sgabor				retval = 0;
294246074Sgabor				goto scan_exit;
295246074Sgabor			}
296246074Sgabor		}
297246074Sgabor		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
298246074Sgabor			if (*s == '\t')
299246074Sgabor				indent += 8 - (indent % 8);
300246074Sgabor			else
301246074Sgabor				indent++;
302246074Sgabor		}
303246074Sgabor		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
304246074Sgabor			;
305246074Sgabor		this_is_a_command = (isdigit((unsigned char)*s) &&
306246074Sgabor		    (*t == 'd' || *t == 'c' || *t == 'a'));
307275553Spfg		if (first_command_line < 0 && this_is_a_command) {
308246074Sgabor			first_command_line = this_line;
309246074Sgabor			fcl_line = p_input_line;
310246074Sgabor			p_indent = indent;	/* assume this for now */
311246074Sgabor		}
312246074Sgabor		if (!stars_last_line && strnEQ(s, "*** ", 4))
313246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
314246074Sgabor			    &names[OLD_FILE].exists, strippath);
315331047Seadler		else if (strnEQ(s, "--- ", 4)) {
316331047Seadler			size_t off = 4;
317331047Seadler			if (piece_of_git && strippath == 957 &&
318331047Seadler			    strnEQ(s, "--- a/", 6))
319331047Seadler				off = 6;
320331047Seadler			names[NEW_FILE].path = fetchname(s + off,
321246074Sgabor			    &names[NEW_FILE].exists, strippath);
322331047Seadler		} else if (strnEQ(s, "+++ ", 4)) {
323246074Sgabor			/* pretend it is the old name */
324331047Seadler			size_t off = 4;
325331047Seadler			if (piece_of_git && strippath == 957 &&
326331047Seadler			    strnEQ(s, "+++ b/", 6))
327331047Seadler				off = 6;
328331047Seadler			names[OLD_FILE].path = fetchname(s + off,
329246074Sgabor			    &names[OLD_FILE].exists, strippath);
330331047Seadler		} else if (strnEQ(s, "Index:", 6))
331246074Sgabor			names[INDEX_FILE].path = fetchname(s + 6,
332246074Sgabor			    &names[INDEX_FILE].exists, strippath);
333246074Sgabor		else if (strnEQ(s, "Prereq:", 7)) {
334246074Sgabor			for (t = s + 7; isspace((unsigned char)*t); t++)
335246074Sgabor				;
336276218Spfg			revision = xstrdup(t);
337275582Spfg			for (t = revision;
338275582Spfg			     *t && !isspace((unsigned char)*t); t++)
339246074Sgabor				;
340246074Sgabor			*t = '\0';
341246074Sgabor			if (*revision == '\0') {
342246074Sgabor				free(revision);
343246074Sgabor				revision = NULL;
344246074Sgabor			}
345331047Seadler		} else if (strnEQ(s, "diff --git a/", 13)) {
346331047Seadler			/* Git-style diffs. */
347331047Seadler			piece_of_git = 1;
348246074Sgabor		} else if (strnEQ(s, "==== ", 5)) {
349246074Sgabor			/* Perforce-style diffs. */
350246074Sgabor			if ((t = strstr(s + 5, " - ")) != NULL)
351246074Sgabor				p4_fetchname(&names[NEW_FILE], t + 3);
352246074Sgabor			p4_fetchname(&names[OLD_FILE], s + 5);
353246074Sgabor		}
354246074Sgabor		if ((!diff_type || diff_type == ED_DIFF) &&
355275553Spfg		    first_command_line >= 0 &&
356246074Sgabor		    strEQ(s, ".\n")) {
357246074Sgabor			p_indent = indent;
358246074Sgabor			p_start = first_command_line;
359246074Sgabor			p_sline = fcl_line;
360246074Sgabor			retval = ED_DIFF;
361246074Sgabor			goto scan_exit;
362246074Sgabor		}
363246074Sgabor		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
364246074Sgabor			if (strnEQ(s + 4, "0,0", 3))
365246074Sgabor				ok_to_create_file = true;
366246074Sgabor			p_indent = indent;
367246074Sgabor			p_start = this_line;
368246074Sgabor			p_sline = p_input_line;
369246074Sgabor			retval = UNI_DIFF;
370246074Sgabor			goto scan_exit;
371246074Sgabor		}
372246074Sgabor		stars_this_line = strnEQ(s, "********", 8);
373246074Sgabor		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
374246074Sgabor		    strnEQ(s, "*** ", 4)) {
375275612Spfg			if (strtolinenum(s + 4, &s) == 0)
376246074Sgabor				ok_to_create_file = true;
377246074Sgabor			/*
378246074Sgabor			 * If this is a new context diff the character just
379275553Spfg			 * at the end of the line is a '*'.
380246074Sgabor			 */
381275553Spfg			while (*s && *s != '\n')
382246074Sgabor				s++;
383246074Sgabor			p_indent = indent;
384246074Sgabor			p_start = previous_line;
385246074Sgabor			p_sline = p_input_line - 1;
386246074Sgabor			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
387246074Sgabor			goto scan_exit;
388246074Sgabor		}
389246074Sgabor		if ((!diff_type || diff_type == NORMAL_DIFF) &&
390246074Sgabor		    last_line_was_command &&
391246074Sgabor		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
392246074Sgabor			p_start = previous_line;
393246074Sgabor			p_sline = p_input_line - 1;
394246074Sgabor			p_indent = indent;
395246074Sgabor			retval = NORMAL_DIFF;
396246074Sgabor			goto scan_exit;
397246074Sgabor		}
398246074Sgabor	}
399246074Sgaborscan_exit:
400246074Sgabor	if (retval == UNI_DIFF) {
401246074Sgabor		/* unswap old and new */
402246074Sgabor		struct file_name tmp = names[OLD_FILE];
403246074Sgabor		names[OLD_FILE] = names[NEW_FILE];
404246074Sgabor		names[NEW_FILE] = tmp;
405246074Sgabor	}
406246074Sgabor	if (filearg[0] == NULL) {
407246074Sgabor		if (posix)
408246074Sgabor			filearg[0] = posix_name(names, ok_to_create_file);
409246074Sgabor		else {
410246074Sgabor			/* Ignore the Index: name for context diffs, like GNU */
411246074Sgabor			if (names[OLD_FILE].path != NULL ||
412246074Sgabor			    names[NEW_FILE].path != NULL) {
413246074Sgabor				free(names[INDEX_FILE].path);
414246074Sgabor				names[INDEX_FILE].path = NULL;
415246074Sgabor			}
416246074Sgabor			filearg[0] = best_name(names, ok_to_create_file);
417246074Sgabor		}
418246074Sgabor	}
419246074Sgabor
420246074Sgabor	free(bestguess);
421246074Sgabor	bestguess = NULL;
422246074Sgabor	if (filearg[0] != NULL)
423276218Spfg		bestguess = xstrdup(filearg[0]);
424246074Sgabor	else if (!ok_to_create_file) {
425246074Sgabor		/*
426246074Sgabor		 * We don't want to create a new file but we need a
427246074Sgabor		 * filename to set bestguess.  Avoid setting filearg[0]
428246074Sgabor		 * so the file is not created automatically.
429246074Sgabor		 */
430246074Sgabor		if (posix)
431246074Sgabor			bestguess = posix_name(names, true);
432246074Sgabor		else
433246074Sgabor			bestguess = best_name(names, true);
434246074Sgabor	}
435246074Sgabor	free(names[OLD_FILE].path);
436246074Sgabor	free(names[NEW_FILE].path);
437246074Sgabor	free(names[INDEX_FILE].path);
438246074Sgabor	return retval;
439246074Sgabor}
440246074Sgabor
441246074Sgabor/*
442246074Sgabor * Remember where this patch ends so we know where to start up again.
443246074Sgabor */
444246074Sgaborstatic void
445275553Spfgnext_intuit_at(off_t file_pos, LINENUM file_line)
446246074Sgabor{
447246074Sgabor	p_base = file_pos;
448246074Sgabor	p_bline = file_line;
449246074Sgabor}
450246074Sgabor
451246074Sgabor/*
452275553Spfg * Basically a verbose fseeko() to the actual diff listing.
453246074Sgabor */
454246074Sgaborstatic void
455275553Spfgskip_to(off_t file_pos, LINENUM file_line)
456246074Sgabor{
457246074Sgabor	size_t	len;
458246074Sgabor
459246074Sgabor	if (p_base > file_pos)
460275553Spfg		fatal("Internal error: seek %lld>%lld\n",
461275553Spfg		   (long long)p_base, (long long)file_pos);
462246074Sgabor	if (verbose && p_base < file_pos) {
463275553Spfg		fseeko(pfp, p_base, SEEK_SET);
464246074Sgabor		say("The text leading up to this was:\n--------------------------\n");
465275553Spfg		while (ftello(pfp) < file_pos) {
466246074Sgabor			len = pgets(false);
467246074Sgabor			if (len == 0)
468246074Sgabor				fatal("Unexpected end of file\n");
469246074Sgabor			say("|%s", buf);
470246074Sgabor		}
471246074Sgabor		say("--------------------------\n");
472246074Sgabor	} else
473275553Spfg		fseeko(pfp, file_pos, SEEK_SET);
474246074Sgabor	p_input_line = file_line - 1;
475246074Sgabor}
476246074Sgabor
477246074Sgabor/* Make this a function for better debugging.  */
478246074Sgaborstatic void
479246074Sgabormalformed(void)
480246074Sgabor{
481246074Sgabor	fatal("malformed patch at line %ld: %s", p_input_line, buf);
482246074Sgabor	/* about as informative as "Syntax error" in C */
483246074Sgabor}
484246074Sgabor
485246074Sgabor/*
486246074Sgabor * True if the line has been discarded (i.e. it is a line saying
487246074Sgabor *  "\ No newline at end of file".)
488246074Sgabor */
489246074Sgaborstatic bool
490246074Sgaborremove_special_line(void)
491246074Sgabor{
492246074Sgabor	int	c;
493246074Sgabor
494246074Sgabor	c = fgetc(pfp);
495246074Sgabor	if (c == '\\') {
496246074Sgabor		do {
497246074Sgabor			c = fgetc(pfp);
498246074Sgabor		} while (c != EOF && c != '\n');
499246074Sgabor
500246074Sgabor		return true;
501246074Sgabor	}
502246074Sgabor	if (c != EOF)
503275553Spfg		fseeko(pfp, -1, SEEK_CUR);
504246074Sgabor
505246074Sgabor	return false;
506246074Sgabor}
507246074Sgabor
508246074Sgabor/*
509246074Sgabor * True if there is more of the current diff listing to process.
510246074Sgabor */
511246074Sgaborbool
512246074Sgaboranother_hunk(void)
513246074Sgabor{
514275553Spfg	off_t	line_beginning;			/* file pos of the current line */
515246074Sgabor	LINENUM	repl_beginning;			/* index of --- line */
516246074Sgabor	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
517246074Sgabor	LINENUM	fillsrc;			/* index of first line to copy */
518246074Sgabor	LINENUM	filldst;			/* index of first missing line */
519289677Seadler	bool	ptrn_spaces_eaten;		/* ptrn was slightly malformed */
520246074Sgabor	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
521246074Sgabor	bool	repl_missing;			/* we are now backtracking */
522275553Spfg	off_t	repl_backtrack_position;	/* file pos of first repl line */
523246074Sgabor	LINENUM	repl_patch_line;		/* input line number for same */
524246074Sgabor	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
525246074Sgabor	char	*s;
526246074Sgabor	size_t	len;
527246074Sgabor	int	context = 0;
528246074Sgabor
529246074Sgabor	while (p_end >= 0) {
530246074Sgabor		if (p_end == p_efake)
531246074Sgabor			p_end = p_bfake;	/* don't free twice */
532246074Sgabor		else
533246074Sgabor			free(p_line[p_end]);
534246074Sgabor		p_end--;
535246074Sgabor	}
536246074Sgabor	p_efake = -1;
537246074Sgabor
538246074Sgabor	p_max = hunkmax;	/* gets reduced when --- found */
539246074Sgabor	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
540275553Spfg		line_beginning = ftello(pfp);
541246074Sgabor		repl_beginning = 0;
542246074Sgabor		fillcnt = 0;
543246074Sgabor		fillsrc = 0;
544246074Sgabor		filldst = 0;
545246074Sgabor		ptrn_spaces_eaten = false;
546246074Sgabor		repl_could_be_missing = true;
547246074Sgabor		repl_missing = false;
548246074Sgabor		repl_backtrack_position = 0;
549246074Sgabor		repl_patch_line = 0;
550246074Sgabor		ptrn_copiable = 0;
551246074Sgabor
552246074Sgabor		len = pgets(true);
553246074Sgabor		p_input_line++;
554246074Sgabor		if (len == 0 || strnNE(buf, "********", 8)) {
555246074Sgabor			next_intuit_at(line_beginning, p_input_line);
556246074Sgabor			return false;
557246074Sgabor		}
558246074Sgabor		p_context = 100;
559246074Sgabor		p_hunk_beg = p_input_line + 1;
560246074Sgabor		while (p_end < p_max) {
561275553Spfg			line_beginning = ftello(pfp);
562246074Sgabor			len = pgets(true);
563246074Sgabor			p_input_line++;
564246074Sgabor			if (len == 0) {
565246074Sgabor				if (p_max - p_end < 4) {
566246074Sgabor					/* assume blank lines got chopped */
567246074Sgabor					strlcpy(buf, "  \n", buf_size);
568246074Sgabor				} else {
569246074Sgabor					if (repl_beginning && repl_could_be_missing) {
570246074Sgabor						repl_missing = true;
571246074Sgabor						goto hunk_done;
572246074Sgabor					}
573246074Sgabor					fatal("unexpected end of file in patch\n");
574246074Sgabor				}
575246074Sgabor			}
576246074Sgabor			p_end++;
577246074Sgabor			if (p_end >= hunkmax)
578246074Sgabor				fatal("Internal error: hunk larger than hunk "
579246074Sgabor				    "buffer size");
580246074Sgabor			p_char[p_end] = *buf;
581246074Sgabor			p_line[p_end] = NULL;
582246074Sgabor			switch (*buf) {
583246074Sgabor			case '*':
584246074Sgabor				if (strnEQ(buf, "********", 8)) {
585246074Sgabor					if (repl_beginning && repl_could_be_missing) {
586246074Sgabor						repl_missing = true;
587246074Sgabor						goto hunk_done;
588246074Sgabor					} else
589246074Sgabor						fatal("unexpected end of hunk "
590246074Sgabor						    "at line %ld\n",
591246074Sgabor						    p_input_line);
592246074Sgabor				}
593246074Sgabor				if (p_end != 0) {
594246074Sgabor					if (repl_beginning && repl_could_be_missing) {
595246074Sgabor						repl_missing = true;
596246074Sgabor						goto hunk_done;
597246074Sgabor					}
598246074Sgabor					fatal("unexpected *** at line %ld: %s",
599246074Sgabor					    p_input_line, buf);
600246074Sgabor				}
601246074Sgabor				context = 0;
602246074Sgabor				p_line[p_end] = savestr(buf);
603246074Sgabor				if (out_of_mem) {
604246074Sgabor					p_end--;
605246074Sgabor					return false;
606246074Sgabor				}
607275582Spfg				for (s = buf;
608275582Spfg				     *s && !isdigit((unsigned char)*s); s++)
609246074Sgabor					;
610246074Sgabor				if (!*s)
611246074Sgabor					malformed();
612246074Sgabor				if (strnEQ(s, "0,0", 3))
613246074Sgabor					memmove(s, s + 2, strlen(s + 2) + 1);
614275612Spfg				p_first = strtolinenum(s, &s);
615246074Sgabor				if (*s == ',') {
616275582Spfg					for (;
617275582Spfg					     *s && !isdigit((unsigned char)*s); s++)
618246074Sgabor						;
619246074Sgabor					if (!*s)
620246074Sgabor						malformed();
621275612Spfg					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
622275612Spfg					if (p_ptrn_lines < 0)
623275612Spfg						malformed();
624246074Sgabor				} else if (p_first)
625246074Sgabor					p_ptrn_lines = 1;
626246074Sgabor				else {
627246074Sgabor					p_ptrn_lines = 0;
628246074Sgabor					p_first = 1;
629246074Sgabor				}
630275612Spfg				if (p_first >= LINENUM_MAX - p_ptrn_lines ||
631275612Spfg				    p_ptrn_lines >= LINENUM_MAX - 6)
632275612Spfg					malformed();
633246074Sgabor
634246074Sgabor				/* we need this much at least */
635246074Sgabor				p_max = p_ptrn_lines + 6;
636246074Sgabor				while (p_max >= hunkmax)
637246074Sgabor					grow_hunkmax();
638246074Sgabor				p_max = hunkmax;
639246074Sgabor				break;
640246074Sgabor			case '-':
641246074Sgabor				if (buf[1] == '-') {
642246074Sgabor					if (repl_beginning ||
643246074Sgabor					    (p_end != p_ptrn_lines + 1 +
644246074Sgabor					    (p_char[p_end - 1] == '\n'))) {
645246074Sgabor						if (p_end == 1) {
646246074Sgabor							/*
647246074Sgabor							 * `old' lines were omitted;
648246074Sgabor							 * set up to fill them in
649246074Sgabor							 * from 'new' context lines.
650246074Sgabor							 */
651246074Sgabor							p_end = p_ptrn_lines + 1;
652246074Sgabor							fillsrc = p_end + 1;
653246074Sgabor							filldst = 1;
654246074Sgabor							fillcnt = p_ptrn_lines;
655246074Sgabor						} else {
656246074Sgabor							if (repl_beginning) {
657246074Sgabor								if (repl_could_be_missing) {
658246074Sgabor									repl_missing = true;
659246074Sgabor									goto hunk_done;
660246074Sgabor								}
661246074Sgabor								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
662246074Sgabor								    p_input_line, p_hunk_beg + repl_beginning);
663246074Sgabor							} else {
664246074Sgabor								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
665246074Sgabor								    (p_end <= p_ptrn_lines
666246074Sgabor								    ? "Premature"
667246074Sgabor								    : "Overdue"),
668246074Sgabor								    p_input_line, p_hunk_beg);
669246074Sgabor							}
670246074Sgabor						}
671246074Sgabor					}
672246074Sgabor					repl_beginning = p_end;
673275553Spfg					repl_backtrack_position = ftello(pfp);
674246074Sgabor					repl_patch_line = p_input_line;
675246074Sgabor					p_line[p_end] = savestr(buf);
676246074Sgabor					if (out_of_mem) {
677246074Sgabor						p_end--;
678246074Sgabor						return false;
679246074Sgabor					}
680246074Sgabor					p_char[p_end] = '=';
681246074Sgabor					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
682246074Sgabor						;
683246074Sgabor					if (!*s)
684246074Sgabor						malformed();
685275612Spfg					p_newfirst = strtolinenum(s, &s);
686246074Sgabor					if (*s == ',') {
687246074Sgabor						for (; *s && !isdigit((unsigned char)*s); s++)
688246074Sgabor							;
689246074Sgabor						if (!*s)
690246074Sgabor							malformed();
691275612Spfg						p_repl_lines = strtolinenum(s, &s) -
692246074Sgabor						    p_newfirst + 1;
693275612Spfg						if (p_repl_lines < 0)
694275612Spfg							malformed();
695246074Sgabor					} else if (p_newfirst)
696246074Sgabor						p_repl_lines = 1;
697246074Sgabor					else {
698246074Sgabor						p_repl_lines = 0;
699246074Sgabor						p_newfirst = 1;
700246074Sgabor					}
701275612Spfg					if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
702275612Spfg					    p_repl_lines >= LINENUM_MAX - p_end)
703275612Spfg						malformed();
704246074Sgabor					p_max = p_repl_lines + p_end;
705246074Sgabor					if (p_max > MAXHUNKSIZE)
706246074Sgabor						fatal("hunk too large (%ld lines) at line %ld: %s",
707246074Sgabor						    p_max, p_input_line, buf);
708246074Sgabor					while (p_max >= hunkmax)
709246074Sgabor						grow_hunkmax();
710246074Sgabor					if (p_repl_lines != ptrn_copiable &&
711246074Sgabor					    (p_context != 0 || p_repl_lines != 1))
712246074Sgabor						repl_could_be_missing = false;
713246074Sgabor					break;
714246074Sgabor				}
715246074Sgabor				goto change_line;
716246074Sgabor			case '+':
717246074Sgabor			case '!':
718246074Sgabor				repl_could_be_missing = false;
719246074Sgabor		change_line:
720246074Sgabor				if (buf[1] == '\n' && canonicalize)
721246074Sgabor					strlcpy(buf + 1, " \n", buf_size - 1);
722275582Spfg				if (!isspace((unsigned char)buf[1]) &&
723275582Spfg				    buf[1] != '>' && buf[1] != '<' &&
724246074Sgabor				    repl_beginning && repl_could_be_missing) {
725246074Sgabor					repl_missing = true;
726246074Sgabor					goto hunk_done;
727246074Sgabor				}
728246074Sgabor				if (context >= 0) {
729246074Sgabor					if (context < p_context)
730246074Sgabor						p_context = context;
731246074Sgabor					context = -1000;
732246074Sgabor				}
733246074Sgabor				p_line[p_end] = savestr(buf + 2);
734246074Sgabor				if (out_of_mem) {
735246074Sgabor					p_end--;
736246074Sgabor					return false;
737246074Sgabor				}
738246074Sgabor				if (p_end == p_ptrn_lines) {
739246074Sgabor					if (remove_special_line()) {
740246074Sgabor						int	l;
741246074Sgabor
742246074Sgabor						l = strlen(p_line[p_end]) - 1;
743246074Sgabor						(p_line[p_end])[l] = 0;
744246074Sgabor					}
745246074Sgabor				}
746246074Sgabor				break;
747246074Sgabor			case '\t':
748246074Sgabor			case '\n':	/* assume the 2 spaces got eaten */
749246074Sgabor				if (repl_beginning && repl_could_be_missing &&
750246074Sgabor				    (!ptrn_spaces_eaten ||
751246074Sgabor				    diff_type == NEW_CONTEXT_DIFF)) {
752246074Sgabor					repl_missing = true;
753246074Sgabor					goto hunk_done;
754246074Sgabor				}
755246074Sgabor				p_line[p_end] = savestr(buf);
756246074Sgabor				if (out_of_mem) {
757246074Sgabor					p_end--;
758246074Sgabor					return false;
759246074Sgabor				}
760246074Sgabor				if (p_end != p_ptrn_lines + 1) {
761246074Sgabor					ptrn_spaces_eaten |= (repl_beginning != 0);
762246074Sgabor					context++;
763246074Sgabor					if (!repl_beginning)
764246074Sgabor						ptrn_copiable++;
765246074Sgabor					p_char[p_end] = ' ';
766246074Sgabor				}
767246074Sgabor				break;
768246074Sgabor			case ' ':
769246074Sgabor				if (!isspace((unsigned char)buf[1]) &&
770246074Sgabor				    repl_beginning && repl_could_be_missing) {
771246074Sgabor					repl_missing = true;
772246074Sgabor					goto hunk_done;
773246074Sgabor				}
774246074Sgabor				context++;
775246074Sgabor				if (!repl_beginning)
776246074Sgabor					ptrn_copiable++;
777246074Sgabor				p_line[p_end] = savestr(buf + 2);
778246074Sgabor				if (out_of_mem) {
779246074Sgabor					p_end--;
780246074Sgabor					return false;
781246074Sgabor				}
782246074Sgabor				break;
783246074Sgabor			default:
784246074Sgabor				if (repl_beginning && repl_could_be_missing) {
785246074Sgabor					repl_missing = true;
786246074Sgabor					goto hunk_done;
787246074Sgabor				}
788246074Sgabor				malformed();
789246074Sgabor			}
790246074Sgabor			/* set up p_len for strncmp() so we don't have to */
791246074Sgabor			/* assume null termination */
792246074Sgabor			if (p_line[p_end])
793246074Sgabor				p_len[p_end] = strlen(p_line[p_end]);
794246074Sgabor			else
795246074Sgabor				p_len[p_end] = 0;
796246074Sgabor		}
797246074Sgabor
798246074Sgaborhunk_done:
799246074Sgabor		if (p_end >= 0 && !repl_beginning)
800246074Sgabor			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
801246074Sgabor
802246074Sgabor		if (repl_missing) {
803246074Sgabor
804246074Sgabor			/* reset state back to just after --- */
805246074Sgabor			p_input_line = repl_patch_line;
806246074Sgabor			for (p_end--; p_end > repl_beginning; p_end--)
807246074Sgabor				free(p_line[p_end]);
808275553Spfg			fseeko(pfp, repl_backtrack_position, SEEK_SET);
809246074Sgabor
810246074Sgabor			/* redundant 'new' context lines were omitted - set */
811246074Sgabor			/* up to fill them in from the old file context */
812246074Sgabor			if (!p_context && p_repl_lines == 1) {
813246074Sgabor				p_repl_lines = 0;
814246074Sgabor				p_max--;
815246074Sgabor			}
816246074Sgabor			fillsrc = 1;
817246074Sgabor			filldst = repl_beginning + 1;
818246074Sgabor			fillcnt = p_repl_lines;
819246074Sgabor			p_end = p_max;
820246074Sgabor		} else if (!p_context && fillcnt == 1) {
821246074Sgabor			/* the first hunk was a null hunk with no context */
822246074Sgabor			/* and we were expecting one line -- fix it up. */
823246074Sgabor			while (filldst < p_end) {
824246074Sgabor				p_line[filldst] = p_line[filldst + 1];
825246074Sgabor				p_char[filldst] = p_char[filldst + 1];
826246074Sgabor				p_len[filldst] = p_len[filldst + 1];
827246074Sgabor				filldst++;
828246074Sgabor			}
829246074Sgabor#if 0
830246074Sgabor			repl_beginning--;	/* this doesn't need to be fixed */
831246074Sgabor#endif
832246074Sgabor			p_end--;
833246074Sgabor			p_first++;	/* do append rather than insert */
834246074Sgabor			fillcnt = 0;
835246074Sgabor			p_ptrn_lines = 0;
836246074Sgabor		}
837246074Sgabor		if (diff_type == CONTEXT_DIFF &&
838246074Sgabor		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
839246074Sgabor			if (verbose)
840246074Sgabor				say("%s\n%s\n%s\n",
841246074Sgabor				    "(Fascinating--this is really a new-style context diff but without",
842246074Sgabor				    "the telltale extra asterisks on the *** line that usually indicate",
843246074Sgabor				    "the new style...)");
844246074Sgabor			diff_type = NEW_CONTEXT_DIFF;
845246074Sgabor		}
846246074Sgabor		/* if there were omitted context lines, fill them in now */
847246074Sgabor		if (fillcnt) {
848246074Sgabor			p_bfake = filldst;	/* remember where not to free() */
849246074Sgabor			p_efake = filldst + fillcnt - 1;
850246074Sgabor			while (fillcnt-- > 0) {
851246074Sgabor				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
852246074Sgabor					fillsrc++;
853246074Sgabor				if (fillsrc > p_end)
854246074Sgabor					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
855246074Sgabor					    p_hunk_beg);
856246074Sgabor				p_line[filldst] = p_line[fillsrc];
857246074Sgabor				p_char[filldst] = p_char[fillsrc];
858246074Sgabor				p_len[filldst] = p_len[fillsrc];
859246074Sgabor				fillsrc++;
860246074Sgabor				filldst++;
861246074Sgabor			}
862246074Sgabor			while (fillsrc <= p_end && fillsrc != repl_beginning &&
863246074Sgabor			    p_char[fillsrc] != ' ')
864246074Sgabor				fillsrc++;
865246074Sgabor#ifdef DEBUGGING
866246074Sgabor			if (debug & 64)
867246074Sgabor				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
868246074Sgabor				fillsrc, filldst, repl_beginning, p_end + 1);
869246074Sgabor#endif
870246074Sgabor			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
871246074Sgabor				malformed();
872246074Sgabor			if (filldst != p_end + 1 && filldst != repl_beginning)
873246074Sgabor				malformed();
874246074Sgabor		}
875246074Sgabor		if (p_line[p_end] != NULL) {
876246074Sgabor			if (remove_special_line()) {
877246074Sgabor				p_len[p_end] -= 1;
878246074Sgabor				(p_line[p_end])[p_len[p_end]] = 0;
879246074Sgabor			}
880246074Sgabor		}
881246074Sgabor	} else if (diff_type == UNI_DIFF) {
882246074Sgabor		LINENUM	fillold;	/* index of old lines */
883246074Sgabor		LINENUM	fillnew;	/* index of new lines */
884246074Sgabor		char	ch;
885246074Sgabor
886275553Spfg		line_beginning = ftello(pfp); /* file pos of the current line */
887246074Sgabor		len = pgets(true);
888246074Sgabor		p_input_line++;
889246074Sgabor		if (len == 0 || strnNE(buf, "@@ -", 4)) {
890246074Sgabor			next_intuit_at(line_beginning, p_input_line);
891246074Sgabor			return false;
892246074Sgabor		}
893246074Sgabor		s = buf + 4;
894246074Sgabor		if (!*s)
895246074Sgabor			malformed();
896275612Spfg		p_first = strtolinenum(s, &s);
897246074Sgabor		if (*s == ',') {
898275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s);
899246074Sgabor		} else
900246074Sgabor			p_ptrn_lines = 1;
901246074Sgabor		if (*s == ' ')
902246074Sgabor			s++;
903246074Sgabor		if (*s != '+' || !*++s)
904246074Sgabor			malformed();
905275612Spfg		p_newfirst = strtolinenum(s, &s);
906246074Sgabor		if (*s == ',') {
907275612Spfg			p_repl_lines = strtolinenum(s + 1, &s);
908246074Sgabor		} else
909246074Sgabor			p_repl_lines = 1;
910246074Sgabor		if (*s == ' ')
911246074Sgabor			s++;
912246074Sgabor		if (*s != '@')
913246074Sgabor			malformed();
914275612Spfg		if (p_first >= LINENUM_MAX - p_ptrn_lines ||
915275612Spfg		    p_newfirst > LINENUM_MAX - p_repl_lines ||
916275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
917275612Spfg			malformed();
918246074Sgabor		if (!p_ptrn_lines)
919246074Sgabor			p_first++;	/* do append rather than insert */
920246074Sgabor		p_max = p_ptrn_lines + p_repl_lines + 1;
921246074Sgabor		while (p_max >= hunkmax)
922246074Sgabor			grow_hunkmax();
923246074Sgabor		fillold = 1;
924246074Sgabor		fillnew = fillold + p_ptrn_lines;
925246074Sgabor		p_end = fillnew + p_repl_lines;
926246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
927246074Sgabor		    p_first + p_ptrn_lines - 1);
928246074Sgabor		p_line[0] = savestr(buf);
929246074Sgabor		if (out_of_mem) {
930246074Sgabor			p_end = -1;
931246074Sgabor			return false;
932246074Sgabor		}
933246074Sgabor		p_char[0] = '*';
934246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
935246074Sgabor		    p_newfirst + p_repl_lines - 1);
936246074Sgabor		p_line[fillnew] = savestr(buf);
937246074Sgabor		if (out_of_mem) {
938246074Sgabor			p_end = 0;
939246074Sgabor			return false;
940246074Sgabor		}
941246074Sgabor		p_char[fillnew++] = '=';
942246074Sgabor		p_context = 100;
943246074Sgabor		context = 0;
944246074Sgabor		p_hunk_beg = p_input_line + 1;
945246074Sgabor		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
946275553Spfg			line_beginning = ftello(pfp);
947246074Sgabor			len = pgets(true);
948246074Sgabor			p_input_line++;
949246074Sgabor			if (len == 0) {
950246074Sgabor				if (p_max - fillnew < 3) {
951246074Sgabor					/* assume blank lines got chopped */
952246074Sgabor					strlcpy(buf, " \n", buf_size);
953246074Sgabor				} else {
954246074Sgabor					fatal("unexpected end of file in patch\n");
955246074Sgabor				}
956246074Sgabor			}
957246074Sgabor			if (*buf == '\t' || *buf == '\n') {
958246074Sgabor				ch = ' ';	/* assume the space got eaten */
959246074Sgabor				s = savestr(buf);
960246074Sgabor			} else {
961246074Sgabor				ch = *buf;
962246074Sgabor				s = savestr(buf + 1);
963246074Sgabor			}
964246074Sgabor			if (out_of_mem) {
965246074Sgabor				while (--fillnew > p_ptrn_lines)
966246074Sgabor					free(p_line[fillnew]);
967246074Sgabor				p_end = fillold - 1;
968246074Sgabor				return false;
969246074Sgabor			}
970246074Sgabor			switch (ch) {
971246074Sgabor			case '-':
972246074Sgabor				if (fillold > p_ptrn_lines) {
973246074Sgabor					free(s);
974246074Sgabor					p_end = fillnew - 1;
975246074Sgabor					malformed();
976246074Sgabor				}
977246074Sgabor				p_char[fillold] = ch;
978246074Sgabor				p_line[fillold] = s;
979246074Sgabor				p_len[fillold++] = strlen(s);
980246074Sgabor				if (fillold > p_ptrn_lines) {
981246074Sgabor					if (remove_special_line()) {
982246074Sgabor						p_len[fillold - 1] -= 1;
983246074Sgabor						s[p_len[fillold - 1]] = 0;
984246074Sgabor					}
985246074Sgabor				}
986246074Sgabor				break;
987246074Sgabor			case '=':
988246074Sgabor				ch = ' ';
989246074Sgabor				/* FALL THROUGH */
990246074Sgabor			case ' ':
991246074Sgabor				if (fillold > p_ptrn_lines) {
992246074Sgabor					free(s);
993246074Sgabor					while (--fillnew > p_ptrn_lines)
994246074Sgabor						free(p_line[fillnew]);
995246074Sgabor					p_end = fillold - 1;
996246074Sgabor					malformed();
997246074Sgabor				}
998246074Sgabor				context++;
999246074Sgabor				p_char[fillold] = ch;
1000246074Sgabor				p_line[fillold] = s;
1001246074Sgabor				p_len[fillold++] = strlen(s);
1002246074Sgabor				s = savestr(s);
1003246074Sgabor				if (out_of_mem) {
1004246074Sgabor					while (--fillnew > p_ptrn_lines)
1005246074Sgabor						free(p_line[fillnew]);
1006246074Sgabor					p_end = fillold - 1;
1007246074Sgabor					return false;
1008246074Sgabor				}
1009246074Sgabor				if (fillold > p_ptrn_lines) {
1010246074Sgabor					if (remove_special_line()) {
1011246074Sgabor						p_len[fillold - 1] -= 1;
1012246074Sgabor						s[p_len[fillold - 1]] = 0;
1013246074Sgabor					}
1014246074Sgabor				}
1015246074Sgabor				/* FALL THROUGH */
1016246074Sgabor			case '+':
1017246074Sgabor				if (fillnew > p_end) {
1018246074Sgabor					free(s);
1019246074Sgabor					while (--fillnew > p_ptrn_lines)
1020246074Sgabor						free(p_line[fillnew]);
1021246074Sgabor					p_end = fillold - 1;
1022246074Sgabor					malformed();
1023246074Sgabor				}
1024246074Sgabor				p_char[fillnew] = ch;
1025246074Sgabor				p_line[fillnew] = s;
1026246074Sgabor				p_len[fillnew++] = strlen(s);
1027246074Sgabor				if (fillold > p_ptrn_lines) {
1028246074Sgabor					if (remove_special_line()) {
1029246074Sgabor						p_len[fillnew - 1] -= 1;
1030246074Sgabor						s[p_len[fillnew - 1]] = 0;
1031246074Sgabor					}
1032246074Sgabor				}
1033246074Sgabor				break;
1034246074Sgabor			default:
1035246074Sgabor				p_end = fillnew;
1036246074Sgabor				malformed();
1037246074Sgabor			}
1038246074Sgabor			if (ch != ' ' && context > 0) {
1039246074Sgabor				if (context < p_context)
1040246074Sgabor					p_context = context;
1041246074Sgabor				context = -1000;
1042246074Sgabor			}
1043246074Sgabor		}		/* while */
1044246074Sgabor	} else {		/* normal diff--fake it up */
1045246074Sgabor		char	hunk_type;
1046246074Sgabor		int	i;
1047246074Sgabor		LINENUM	min, max;
1048246074Sgabor
1049275553Spfg		line_beginning = ftello(pfp);
1050246074Sgabor		p_context = 0;
1051246074Sgabor		len = pgets(true);
1052246074Sgabor		p_input_line++;
1053246074Sgabor		if (len == 0 || !isdigit((unsigned char)*buf)) {
1054246074Sgabor			next_intuit_at(line_beginning, p_input_line);
1055246074Sgabor			return false;
1056246074Sgabor		}
1057275612Spfg		p_first = strtolinenum(buf, &s);
1058246074Sgabor		if (*s == ',') {
1059275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1060275612Spfg			if (p_ptrn_lines < 0)
1061275612Spfg				malformed();
1062246074Sgabor		} else
1063246074Sgabor			p_ptrn_lines = (*s != 'a');
1064246074Sgabor		hunk_type = *s;
1065246074Sgabor		if (hunk_type == 'a')
1066246074Sgabor			p_first++;	/* do append rather than insert */
1067275612Spfg		min = strtolinenum(s + 1, &s);
1068246074Sgabor		if (*s == ',')
1069275612Spfg			max = strtolinenum(s + 1, &s);
1070246074Sgabor		else
1071246074Sgabor			max = min;
1072275612Spfg		if (min < 0 || min > max || max - min == LINENUM_MAX)
1073275612Spfg			malformed();
1074246074Sgabor		if (hunk_type == 'd')
1075246074Sgabor			min++;
1076275612Spfg		p_newfirst = min;
1077275612Spfg		p_repl_lines = max - min + 1;
1078275612Spfg		if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1079275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1080275612Spfg			malformed();
1081275612Spfg		p_end = p_ptrn_lines + p_repl_lines + 1;
1082246074Sgabor		if (p_end > MAXHUNKSIZE)
1083246074Sgabor			fatal("hunk too large (%ld lines) at line %ld: %s",
1084246074Sgabor			    p_end, p_input_line, buf);
1085246074Sgabor		while (p_end >= hunkmax)
1086246074Sgabor			grow_hunkmax();
1087246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1088246074Sgabor		    p_first + p_ptrn_lines - 1);
1089246074Sgabor		p_line[0] = savestr(buf);
1090246074Sgabor		if (out_of_mem) {
1091246074Sgabor			p_end = -1;
1092246074Sgabor			return false;
1093246074Sgabor		}
1094246074Sgabor		p_char[0] = '*';
1095246074Sgabor		for (i = 1; i <= p_ptrn_lines; i++) {
1096246074Sgabor			len = pgets(true);
1097246074Sgabor			p_input_line++;
1098246074Sgabor			if (len == 0)
1099246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1100246074Sgabor				    p_input_line);
1101246074Sgabor			if (*buf != '<')
1102246074Sgabor				fatal("< expected at line %ld of patch\n",
1103246074Sgabor				    p_input_line);
1104246074Sgabor			p_line[i] = savestr(buf + 2);
1105246074Sgabor			if (out_of_mem) {
1106246074Sgabor				p_end = i - 1;
1107246074Sgabor				return false;
1108246074Sgabor			}
1109246074Sgabor			p_len[i] = strlen(p_line[i]);
1110246074Sgabor			p_char[i] = '-';
1111246074Sgabor		}
1112246074Sgabor
1113246074Sgabor		if (remove_special_line()) {
1114246074Sgabor			p_len[i - 1] -= 1;
1115246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1116246074Sgabor		}
1117246074Sgabor		if (hunk_type == 'c') {
1118246074Sgabor			len = pgets(true);
1119246074Sgabor			p_input_line++;
1120246074Sgabor			if (len == 0)
1121246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1122246074Sgabor				    p_input_line);
1123246074Sgabor			if (*buf != '-')
1124246074Sgabor				fatal("--- expected at line %ld of patch\n",
1125246074Sgabor				    p_input_line);
1126246074Sgabor		}
1127246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1128246074Sgabor		p_line[i] = savestr(buf);
1129246074Sgabor		if (out_of_mem) {
1130246074Sgabor			p_end = i - 1;
1131246074Sgabor			return false;
1132246074Sgabor		}
1133246074Sgabor		p_char[i] = '=';
1134246074Sgabor		for (i++; i <= p_end; i++) {
1135246074Sgabor			len = pgets(true);
1136246074Sgabor			p_input_line++;
1137246074Sgabor			if (len == 0)
1138246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1139246074Sgabor				    p_input_line);
1140246074Sgabor			if (*buf != '>')
1141246074Sgabor				fatal("> expected at line %ld of patch\n",
1142246074Sgabor				    p_input_line);
1143328147Skevans			/* Don't overrun if we don't have enough line */
1144328147Skevans			if (len > 2)
1145328147Skevans				p_line[i] = savestr(buf + 2);
1146328147Skevans			else
1147328147Skevans				p_line[i] = savestr("");
1148328147Skevans
1149246074Sgabor			if (out_of_mem) {
1150246074Sgabor				p_end = i - 1;
1151246074Sgabor				return false;
1152246074Sgabor			}
1153246074Sgabor			p_len[i] = strlen(p_line[i]);
1154246074Sgabor			p_char[i] = '+';
1155246074Sgabor		}
1156246074Sgabor
1157246074Sgabor		if (remove_special_line()) {
1158246074Sgabor			p_len[i - 1] -= 1;
1159246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1160246074Sgabor		}
1161246074Sgabor	}
1162246074Sgabor	if (reverse)		/* backwards patch? */
1163246074Sgabor		if (!pch_swap())
1164246074Sgabor			say("Not enough memory to swap next hunk!\n");
1165246074Sgabor#ifdef DEBUGGING
1166246074Sgabor	if (debug & 2) {
1167298530Spfg		LINENUM	i;
1168246074Sgabor		char	special;
1169246074Sgabor
1170246074Sgabor		for (i = 0; i <= p_end; i++) {
1171246074Sgabor			if (i == p_ptrn_lines)
1172246074Sgabor				special = '^';
1173246074Sgabor			else
1174246074Sgabor				special = ' ';
1175298530Spfg			fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1176246074Sgabor			    special, p_line[i]);
1177246074Sgabor			fflush(stderr);
1178246074Sgabor		}
1179246074Sgabor	}
1180246074Sgabor#endif
1181246074Sgabor	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1182246074Sgabor		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1183246074Sgabor	return true;
1184246074Sgabor}
1185246074Sgabor
1186246074Sgabor/*
1187246074Sgabor * Input a line from the patch file.
1188246074Sgabor * Worry about indentation if do_indent is true.
1189246074Sgabor * The line is read directly into the buf global variable which
1190246074Sgabor * is resized if necessary in order to hold the complete line.
1191246074Sgabor * Returns the number of characters read including the terminating
1192246074Sgabor * '\n', if any.
1193246074Sgabor */
1194246074Sgaborsize_t
1195246074Sgaborpgets(bool do_indent)
1196246074Sgabor{
1197246074Sgabor	char *line;
1198246074Sgabor	size_t len;
1199246074Sgabor	int indent = 0, skipped = 0;
1200246074Sgabor
1201246074Sgabor	line = fgetln(pfp, &len);
1202246074Sgabor	if (line != NULL) {
1203246074Sgabor		if (len + 1 > buf_size) {
1204246074Sgabor			while (len + 1 > buf_size)
1205246074Sgabor				buf_size *= 2;
1206246074Sgabor			free(buf);
1207246074Sgabor			buf = malloc(buf_size);
1208246074Sgabor			if (buf == NULL)
1209246074Sgabor				fatal("out of memory\n");
1210246074Sgabor		}
1211246074Sgabor		if (do_indent == 1 && p_indent) {
1212246074Sgabor			for (;
1213246074Sgabor			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1214246074Sgabor			    line++, skipped++) {
1215246074Sgabor				if (*line == '\t')
1216246074Sgabor					indent += 8 - (indent %7);
1217246074Sgabor				else
1218246074Sgabor					indent++;
1219246074Sgabor			}
1220246074Sgabor		}
1221252637Sobrien		memcpy(buf, line, len - skipped);
1222246074Sgabor		buf[len - skipped] = '\0';
1223246074Sgabor	}
1224246074Sgabor	return len;
1225246074Sgabor}
1226246074Sgabor
1227246074Sgabor
1228246074Sgabor/*
1229246074Sgabor * Reverse the old and new portions of the current hunk.
1230246074Sgabor */
1231246074Sgaborbool
1232246074Sgaborpch_swap(void)
1233246074Sgabor{
1234246074Sgabor	char	**tp_line;	/* the text of the hunk */
1235267490Spfg	unsigned short	*tp_len;/* length of each line */
1236246074Sgabor	char	*tp_char;	/* +, -, and ! */
1237246074Sgabor	LINENUM	i;
1238246074Sgabor	LINENUM	n;
1239246074Sgabor	bool	blankline = false;
1240246074Sgabor	char	*s;
1241246074Sgabor
1242246074Sgabor	i = p_first;
1243246074Sgabor	p_first = p_newfirst;
1244246074Sgabor	p_newfirst = i;
1245246074Sgabor
1246246074Sgabor	/* make a scratch copy */
1247246074Sgabor
1248246074Sgabor	tp_line = p_line;
1249246074Sgabor	tp_len = p_len;
1250246074Sgabor	tp_char = p_char;
1251246074Sgabor	p_line = NULL;	/* force set_hunkmax to allocate again */
1252246074Sgabor	p_len = NULL;
1253246074Sgabor	p_char = NULL;
1254246074Sgabor	set_hunkmax();
1255246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1256246074Sgabor
1257246074Sgabor		free(p_line);
1258246074Sgabor		p_line = tp_line;
1259246074Sgabor		free(p_len);
1260246074Sgabor		p_len = tp_len;
1261246074Sgabor		free(p_char);
1262246074Sgabor		p_char = tp_char;
1263246074Sgabor		return false;	/* not enough memory to swap hunk! */
1264246074Sgabor	}
1265246074Sgabor	/* now turn the new into the old */
1266246074Sgabor
1267246074Sgabor	i = p_ptrn_lines + 1;
1268246074Sgabor	if (tp_char[i] == '\n') {	/* account for possible blank line */
1269246074Sgabor		blankline = true;
1270246074Sgabor		i++;
1271246074Sgabor	}
1272246074Sgabor	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1273246074Sgabor		if (p_efake <= i)
1274246074Sgabor			n = p_end - i + 1;
1275246074Sgabor		else
1276246074Sgabor			n = -i;
1277246074Sgabor		p_efake += n;
1278246074Sgabor		p_bfake += n;
1279246074Sgabor	}
1280246074Sgabor	for (n = 0; i <= p_end; i++, n++) {
1281246074Sgabor		p_line[n] = tp_line[i];
1282246074Sgabor		p_char[n] = tp_char[i];
1283246074Sgabor		if (p_char[n] == '+')
1284246074Sgabor			p_char[n] = '-';
1285246074Sgabor		p_len[n] = tp_len[i];
1286246074Sgabor	}
1287246074Sgabor	if (blankline) {
1288246074Sgabor		i = p_ptrn_lines + 1;
1289246074Sgabor		p_line[n] = tp_line[i];
1290246074Sgabor		p_char[n] = tp_char[i];
1291246074Sgabor		p_len[n] = tp_len[i];
1292246074Sgabor		n++;
1293246074Sgabor	}
1294246074Sgabor	if (p_char[0] != '=')
1295246074Sgabor		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1296246074Sgabor		    p_input_line, p_char[0]);
1297246074Sgabor	p_char[0] = '*';
1298246074Sgabor	for (s = p_line[0]; *s; s++)
1299246074Sgabor		if (*s == '-')
1300246074Sgabor			*s = '*';
1301246074Sgabor
1302246074Sgabor	/* now turn the old into the new */
1303246074Sgabor
1304246074Sgabor	if (p_char[0] != '*')
1305246074Sgabor		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1306246074Sgabor		    p_input_line, p_char[0]);
1307246074Sgabor	tp_char[0] = '=';
1308246074Sgabor	for (s = tp_line[0]; *s; s++)
1309246074Sgabor		if (*s == '*')
1310246074Sgabor			*s = '-';
1311246074Sgabor	for (i = 0; n <= p_end; i++, n++) {
1312246074Sgabor		p_line[n] = tp_line[i];
1313246074Sgabor		p_char[n] = tp_char[i];
1314246074Sgabor		if (p_char[n] == '-')
1315246074Sgabor			p_char[n] = '+';
1316246074Sgabor		p_len[n] = tp_len[i];
1317246074Sgabor	}
1318246074Sgabor
1319246074Sgabor	if (i != p_ptrn_lines + 1)
1320246074Sgabor		fatal("Malformed patch at line %ld: expected %ld lines, "
1321246074Sgabor		    "got %ld\n",
1322246074Sgabor		    p_input_line, p_ptrn_lines + 1, i);
1323246074Sgabor
1324246074Sgabor	i = p_ptrn_lines;
1325246074Sgabor	p_ptrn_lines = p_repl_lines;
1326246074Sgabor	p_repl_lines = i;
1327246074Sgabor
1328246074Sgabor	free(tp_line);
1329246074Sgabor	free(tp_len);
1330246074Sgabor	free(tp_char);
1331246074Sgabor
1332246074Sgabor	return true;
1333246074Sgabor}
1334246074Sgabor
1335246074Sgabor/*
1336246074Sgabor * Return the specified line position in the old file of the old context.
1337246074Sgabor */
1338246074SgaborLINENUM
1339246074Sgaborpch_first(void)
1340246074Sgabor{
1341246074Sgabor	return p_first;
1342246074Sgabor}
1343246074Sgabor
1344246074Sgabor/*
1345246074Sgabor * Return the number of lines of old context.
1346246074Sgabor */
1347246074SgaborLINENUM
1348246074Sgaborpch_ptrn_lines(void)
1349246074Sgabor{
1350246074Sgabor	return p_ptrn_lines;
1351246074Sgabor}
1352246074Sgabor
1353246074Sgabor/*
1354246074Sgabor * Return the probable line position in the new file of the first line.
1355246074Sgabor */
1356246074SgaborLINENUM
1357246074Sgaborpch_newfirst(void)
1358246074Sgabor{
1359246074Sgabor	return p_newfirst;
1360246074Sgabor}
1361246074Sgabor
1362246074Sgabor/*
1363246074Sgabor * Return the number of lines in the replacement text including context.
1364246074Sgabor */
1365246074SgaborLINENUM
1366246074Sgaborpch_repl_lines(void)
1367246074Sgabor{
1368246074Sgabor	return p_repl_lines;
1369246074Sgabor}
1370246074Sgabor
1371246074Sgabor/*
1372246074Sgabor * Return the number of lines in the whole hunk.
1373246074Sgabor */
1374246074SgaborLINENUM
1375246074Sgaborpch_end(void)
1376246074Sgabor{
1377246074Sgabor	return p_end;
1378246074Sgabor}
1379246074Sgabor
1380246074Sgabor/*
1381246074Sgabor * Return the number of context lines before the first changed line.
1382246074Sgabor */
1383246074SgaborLINENUM
1384246074Sgaborpch_context(void)
1385246074Sgabor{
1386246074Sgabor	return p_context;
1387246074Sgabor}
1388246074Sgabor
1389246074Sgabor/*
1390246074Sgabor * Return the length of a particular patch line.
1391246074Sgabor */
1392267490Spfgunsigned short
1393246074Sgaborpch_line_len(LINENUM line)
1394246074Sgabor{
1395246074Sgabor	return p_len[line];
1396246074Sgabor}
1397246074Sgabor
1398246074Sgabor/*
1399246074Sgabor * Return the control character (+, -, *, !, etc) for a patch line.
1400246074Sgabor */
1401246074Sgaborchar
1402246074Sgaborpch_char(LINENUM line)
1403246074Sgabor{
1404246074Sgabor	return p_char[line];
1405246074Sgabor}
1406246074Sgabor
1407246074Sgabor/*
1408246074Sgabor * Return a pointer to a particular patch line.
1409246074Sgabor */
1410246074Sgaborchar *
1411246074Sgaborpfetch(LINENUM line)
1412246074Sgabor{
1413246074Sgabor	return p_line[line];
1414246074Sgabor}
1415246074Sgabor
1416246074Sgabor/*
1417246074Sgabor * Return where in the patch file this hunk began, for error messages.
1418246074Sgabor */
1419246074SgaborLINENUM
1420246074Sgaborpch_hunk_beg(void)
1421246074Sgabor{
1422246074Sgabor	return p_hunk_beg;
1423246074Sgabor}
1424246074Sgabor
1425246074Sgabor/*
1426246074Sgabor * Apply an ed script by feeding ed itself.
1427246074Sgabor */
1428246074Sgaborvoid
1429246074Sgabordo_ed_script(void)
1430246074Sgabor{
1431246074Sgabor	char	*t;
1432275553Spfg	off_t	beginning_of_this_line;
1433246074Sgabor	FILE	*pipefp = NULL;
1434286346Sdelphij	int	continuation;
1435246074Sgabor
1436246074Sgabor	if (!skip_rest_of_patch) {
1437246074Sgabor		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1438246074Sgabor			unlink(TMPOUTNAME);
1439246074Sgabor			fatal("can't create temp file %s", TMPOUTNAME);
1440246074Sgabor		}
1441286346Sdelphij		snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1442246074Sgabor		    verbose ? " " : " -s ", TMPOUTNAME);
1443246074Sgabor		pipefp = popen(buf, "w");
1444246074Sgabor	}
1445246074Sgabor	for (;;) {
1446275553Spfg		beginning_of_this_line = ftello(pfp);
1447246074Sgabor		if (pgets(true) == 0) {
1448246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1449246074Sgabor			break;
1450246074Sgabor		}
1451246074Sgabor		p_input_line++;
1452246074Sgabor		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1453246074Sgabor			;
1454246074Sgabor		/* POSIX defines allowed commands as {a,c,d,i,s} */
1455275582Spfg		if (isdigit((unsigned char)*buf) &&
1456275582Spfg		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1457246074Sgabor			if (pipefp != NULL)
1458246074Sgabor				fputs(buf, pipefp);
1459286346Sdelphij			if (*t == 's') {
1460286346Sdelphij				for (;;) {
1461286346Sdelphij					continuation = 0;
1462286346Sdelphij					t = strchr(buf, '\0') - 1;
1463286346Sdelphij					while (--t >= buf && *t == '\\')
1464286346Sdelphij						continuation = !continuation;
1465286346Sdelphij					if (!continuation ||
1466286346Sdelphij					    pgets(true) == 0)
1467286346Sdelphij						break;
1468286346Sdelphij					if (pipefp != NULL)
1469286346Sdelphij						fputs(buf, pipefp);
1470286346Sdelphij				}
1471286346Sdelphij			} else if (*t != 'd') {
1472246074Sgabor				while (pgets(true)) {
1473246074Sgabor					p_input_line++;
1474246074Sgabor					if (pipefp != NULL)
1475246074Sgabor						fputs(buf, pipefp);
1476246074Sgabor					if (strEQ(buf, ".\n"))
1477246074Sgabor						break;
1478246074Sgabor				}
1479246074Sgabor			}
1480246074Sgabor		} else {
1481246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1482246074Sgabor			break;
1483246074Sgabor		}
1484246074Sgabor	}
1485246074Sgabor	if (pipefp == NULL)
1486246074Sgabor		return;
1487246074Sgabor	fprintf(pipefp, "w\n");
1488246074Sgabor	fprintf(pipefp, "q\n");
1489246074Sgabor	fflush(pipefp);
1490246074Sgabor	pclose(pipefp);
1491246074Sgabor	ignore_signals();
1492246074Sgabor	if (!check_only) {
1493246074Sgabor		if (move_file(TMPOUTNAME, outname) < 0) {
1494246074Sgabor			toutkeep = true;
1495246074Sgabor			chmod(TMPOUTNAME, filemode);
1496246074Sgabor		} else
1497246074Sgabor			chmod(outname, filemode);
1498246074Sgabor	}
1499246074Sgabor	set_signals(1);
1500246074Sgabor}
1501246074Sgabor
1502246074Sgabor/*
1503246074Sgabor * Choose the name of the file to be patched based on POSIX rules.
1504246074Sgabor * NOTE: the POSIX rules are amazingly stupid and we only follow them
1505246074Sgabor *       if the user specified --posix or set POSIXLY_CORRECT.
1506246074Sgabor */
1507246074Sgaborstatic char *
1508246074Sgaborposix_name(const struct file_name *names, bool assume_exists)
1509246074Sgabor{
1510246074Sgabor	char *path = NULL;
1511246074Sgabor	int i;
1512246074Sgabor
1513246074Sgabor	/*
1514246074Sgabor	 * POSIX states that the filename will be chosen from one
1515246074Sgabor	 * of the old, new and index names (in that order) if
1516246074Sgabor	 * the file exists relative to CWD after -p stripping.
1517246074Sgabor	 */
1518246074Sgabor	for (i = 0; i < MAX_FILE; i++) {
1519246074Sgabor		if (names[i].path != NULL && names[i].exists) {
1520246074Sgabor			path = names[i].path;
1521246074Sgabor			break;
1522246074Sgabor		}
1523246074Sgabor	}
1524246074Sgabor	if (path == NULL && !assume_exists) {
1525246074Sgabor		/*
1526286795Sdelphij		 * No files found, check to see if the diff could be
1527286795Sdelphij		 * creating a new file.
1528246074Sgabor		 */
1529246074Sgabor		if (path == NULL && ok_to_create_file &&
1530246074Sgabor		    names[NEW_FILE].path != NULL)
1531246074Sgabor			path = names[NEW_FILE].path;
1532246074Sgabor	}
1533246074Sgabor
1534276218Spfg	return path ? xstrdup(path) : NULL;
1535246074Sgabor}
1536246074Sgabor
1537246074Sgaborstatic char *
1538286795Sdelphijcompare_names(const struct file_name *names, bool assume_exists)
1539246074Sgabor{
1540246074Sgabor	size_t min_components, min_baselen, min_len, tmp;
1541246074Sgabor	char *best = NULL;
1542255232Sse	char *path;
1543246074Sgabor	int i;
1544246074Sgabor
1545246074Sgabor	/*
1546246074Sgabor	 * The "best" name is the one with the fewest number of path
1547246074Sgabor	 * components, the shortest basename length, and the shortest
1548246074Sgabor	 * overall length (in that order).  We only use the Index: file
1549246074Sgabor	 * if neither of the old or new files could be intuited from
1550246074Sgabor	 * the diff header.
1551246074Sgabor	 */
1552246074Sgabor	min_components = min_baselen = min_len = SIZE_MAX;
1553246074Sgabor	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1554255232Sse		path = names[i].path;
1555286795Sdelphij		if (path == NULL || (!names[i].exists && !assume_exists))
1556246074Sgabor			continue;
1557255232Sse		if ((tmp = num_components(path)) > min_components)
1558246074Sgabor			continue;
1559250943Sse		if (tmp < min_components) {
1560250943Sse			min_components = tmp;
1561255232Sse			best = path;
1562250943Sse		}
1563255232Sse		if ((tmp = strlen(basename(path))) > min_baselen)
1564246074Sgabor			continue;
1565250943Sse		if (tmp < min_baselen) {
1566250943Sse			min_baselen = tmp;
1567255232Sse			best = path;
1568250943Sse		}
1569255232Sse		if ((tmp = strlen(path)) > min_len)
1570246074Sgabor			continue;
1571246074Sgabor		min_len = tmp;
1572255232Sse		best = path;
1573246074Sgabor	}
1574255232Sse	return best;
1575255232Sse}
1576255232Sse
1577255232Sse/*
1578255232Sse * Choose the name of the file to be patched based the "best" one
1579255232Sse * available.
1580255232Sse */
1581255232Ssestatic char *
1582255232Ssebest_name(const struct file_name *names, bool assume_exists)
1583255232Sse{
1584255232Sse	char *best;
1585255232Sse
1586286795Sdelphij	best = compare_names(names, assume_exists);
1587246074Sgabor
1588286795Sdelphij	/* No match?  Check to see if the diff could be creating a new file. */
1589286795Sdelphij	if (best == NULL && ok_to_create_file)
1590286795Sdelphij		best = names[NEW_FILE].path;
1591286795Sdelphij
1592276218Spfg	return best ? xstrdup(best) : NULL;
1593246074Sgabor}
1594246074Sgabor
1595246074Sgaborstatic size_t
1596246074Sgabornum_components(const char *path)
1597246074Sgabor{
1598246074Sgabor	size_t n;
1599246074Sgabor	const char *cp;
1600246074Sgabor
1601246074Sgabor	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1602246074Sgabor		while (*cp == '/')
1603246074Sgabor			cp++;		/* skip consecutive slashes */
1604246074Sgabor	}
1605246074Sgabor	return n;
1606246074Sgabor}
1607275612Spfg
1608275612Spfg/*
1609275612Spfg * Convert number at NPTR into LINENUM and save address of first
1610275612Spfg * character that is not a digit in ENDPTR.  If conversion is not
1611275612Spfg * possible, call fatal.
1612275612Spfg */
1613275612Spfgstatic LINENUM
1614275612Spfgstrtolinenum(char *nptr, char **endptr)
1615275612Spfg{
1616275612Spfg	LINENUM rv;
1617275612Spfg	char c;
1618275612Spfg	char *p;
1619275612Spfg	const char *errstr;
1620275612Spfg
1621275612Spfg	for (p = nptr; isdigit((unsigned char)*p); p++)
1622275612Spfg		;
1623275612Spfg
1624275612Spfg	if (p == nptr)
1625275612Spfg		malformed();
1626275612Spfg
1627275612Spfg	c = *p;
1628275612Spfg	*p = '\0';
1629275612Spfg
1630275612Spfg	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1631275612Spfg	if (errstr != NULL)
1632275612Spfg		fatal("invalid line number at line %ld: `%s' is %s\n",
1633275612Spfg		    p_input_line, nptr, errstr);
1634276218Spfg
1635275612Spfg	*p = c;
1636275612Spfg	*endptr = p;
1637275612Spfg
1638275612Spfg	return rv;
1639275612Spfg}
1640