pch.c revision 328147
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 328147 2018-01-18 21:46:42Z 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	}
182246074Sgabor	if (verbose)
183246074Sgabor		say("Hmm...");
184246074Sgabor	diff_type = intuit_diff_type();
185246074Sgabor	if (!diff_type) {
186275553Spfg		if (p_base != 0) {
187246074Sgabor			if (verbose)
188246074Sgabor				say("  Ignoring the trailing garbage.\ndone\n");
189246074Sgabor		} else
190246074Sgabor			say("  I can't seem to find a patch in there anywhere.\n");
191246074Sgabor		return false;
192246074Sgabor	}
193246074Sgabor	if (verbose)
194246074Sgabor		say("  %sooks like %s to me...\n",
195275553Spfg		    (p_base == 0 ? "L" : "The next patch l"),
196246074Sgabor		    diff_type == UNI_DIFF ? "a unified diff" :
197246074Sgabor		    diff_type == CONTEXT_DIFF ? "a context diff" :
198246074Sgabor		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
199246074Sgabor		    diff_type == NORMAL_DIFF ? "a normal diff" :
200246074Sgabor		    "an ed script");
201246074Sgabor	if (p_indent && verbose)
202246074Sgabor		say("(Patch is indented %d space%s.)\n", p_indent,
203246074Sgabor		    p_indent == 1 ? "" : "s");
204246074Sgabor	skip_to(p_start, p_sline);
205246074Sgabor	while (filearg[0] == NULL) {
206246074Sgabor		if (force || batch) {
207246074Sgabor			say("No file to patch.  Skipping...\n");
208276218Spfg			filearg[0] = xstrdup(bestguess);
209246074Sgabor			skip_rest_of_patch = true;
210246074Sgabor			return true;
211246074Sgabor		}
212246074Sgabor		ask("File to patch: ");
213246074Sgabor		if (*buf != '\n') {
214246074Sgabor			free(bestguess);
215276218Spfg			bestguess = xstrdup(buf);
216246074Sgabor			filearg[0] = fetchname(buf, &exists, 0);
217246074Sgabor		}
218246074Sgabor		if (!exists) {
219320084Spfg			int def_skip = *bestguess == '\0';
220320084Spfg			ask("No file found--skip this patch? [%c] ",
221320084Spfg			    def_skip  ? 'y' : 'n');
222320084Spfg			if (*buf == 'n' || (!def_skip && *buf != 'y'))
223246074Sgabor				continue;
224246074Sgabor			if (verbose)
225246074Sgabor				say("Skipping patch...\n");
226246074Sgabor			free(filearg[0]);
227246074Sgabor			filearg[0] = fetchname(bestguess, &exists, 0);
228246074Sgabor			skip_rest_of_patch = true;
229246074Sgabor			return true;
230246074Sgabor		}
231246074Sgabor	}
232246074Sgabor	return true;
233246074Sgabor}
234246074Sgabor
235246074Sgaborstatic void
236246074Sgaborp4_fetchname(struct file_name *name, char *str)
237246074Sgabor{
238246074Sgabor	char *t, *h;
239246074Sgabor
240246074Sgabor	/* Skip leading whitespace. */
241246074Sgabor	while (isspace((unsigned char)*str))
242246074Sgabor		str++;
243246074Sgabor
244246074Sgabor	/* Remove the file revision number. */
245246074Sgabor	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
246246074Sgabor		if (*t == '#')
247246074Sgabor			h = t;
248246074Sgabor	if (h != NULL)
249246074Sgabor		*h = '\0';
250246074Sgabor
251246074Sgabor	name->path = fetchname(str, &name->exists, strippath);
252246074Sgabor}
253246074Sgabor
254246074Sgabor/* Determine what kind of diff is in the remaining part of the patch file. */
255246074Sgabor
256246074Sgaborstatic int
257246074Sgaborintuit_diff_type(void)
258246074Sgabor{
259275553Spfg	off_t	this_line = 0, previous_line;
260275553Spfg	off_t	first_command_line = -1;
261246074Sgabor	LINENUM	fcl_line = -1;
262246074Sgabor	bool	last_line_was_command = false, this_is_a_command = false;
263246074Sgabor	bool	stars_last_line = false, stars_this_line = false;
264246074Sgabor	char	*s, *t;
265246074Sgabor	int	indent, retval;
266246074Sgabor	struct file_name names[MAX_FILE];
267246074Sgabor
268246074Sgabor	memset(names, 0, sizeof(names));
269246074Sgabor	ok_to_create_file = false;
270275553Spfg	fseeko(pfp, p_base, SEEK_SET);
271246074Sgabor	p_input_line = p_bline - 1;
272246074Sgabor	for (;;) {
273246074Sgabor		previous_line = this_line;
274246074Sgabor		last_line_was_command = this_is_a_command;
275246074Sgabor		stars_last_line = stars_this_line;
276275553Spfg		this_line = ftello(pfp);
277246074Sgabor		indent = 0;
278246074Sgabor		p_input_line++;
279246074Sgabor		if (pgets(false) == 0) {
280275553Spfg			if (first_command_line >= 0) {
281246074Sgabor				/* nothing but deletes!? */
282246074Sgabor				p_start = first_command_line;
283246074Sgabor				p_sline = fcl_line;
284246074Sgabor				retval = ED_DIFF;
285246074Sgabor				goto scan_exit;
286246074Sgabor			} else {
287246074Sgabor				p_start = this_line;
288246074Sgabor				p_sline = p_input_line;
289246074Sgabor				retval = 0;
290246074Sgabor				goto scan_exit;
291246074Sgabor			}
292246074Sgabor		}
293246074Sgabor		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
294246074Sgabor			if (*s == '\t')
295246074Sgabor				indent += 8 - (indent % 8);
296246074Sgabor			else
297246074Sgabor				indent++;
298246074Sgabor		}
299246074Sgabor		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
300246074Sgabor			;
301246074Sgabor		this_is_a_command = (isdigit((unsigned char)*s) &&
302246074Sgabor		    (*t == 'd' || *t == 'c' || *t == 'a'));
303275553Spfg		if (first_command_line < 0 && this_is_a_command) {
304246074Sgabor			first_command_line = this_line;
305246074Sgabor			fcl_line = p_input_line;
306246074Sgabor			p_indent = indent;	/* assume this for now */
307246074Sgabor		}
308246074Sgabor		if (!stars_last_line && strnEQ(s, "*** ", 4))
309246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
310246074Sgabor			    &names[OLD_FILE].exists, strippath);
311246074Sgabor		else if (strnEQ(s, "--- ", 4))
312246074Sgabor			names[NEW_FILE].path = fetchname(s + 4,
313246074Sgabor			    &names[NEW_FILE].exists, strippath);
314246074Sgabor		else if (strnEQ(s, "+++ ", 4))
315246074Sgabor			/* pretend it is the old name */
316246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
317246074Sgabor			    &names[OLD_FILE].exists, strippath);
318246074Sgabor		else if (strnEQ(s, "Index:", 6))
319246074Sgabor			names[INDEX_FILE].path = fetchname(s + 6,
320246074Sgabor			    &names[INDEX_FILE].exists, strippath);
321246074Sgabor		else if (strnEQ(s, "Prereq:", 7)) {
322246074Sgabor			for (t = s + 7; isspace((unsigned char)*t); t++)
323246074Sgabor				;
324276218Spfg			revision = xstrdup(t);
325275582Spfg			for (t = revision;
326275582Spfg			     *t && !isspace((unsigned char)*t); t++)
327246074Sgabor				;
328246074Sgabor			*t = '\0';
329246074Sgabor			if (*revision == '\0') {
330246074Sgabor				free(revision);
331246074Sgabor				revision = NULL;
332246074Sgabor			}
333246074Sgabor		} else if (strnEQ(s, "==== ", 5)) {
334246074Sgabor			/* Perforce-style diffs. */
335246074Sgabor			if ((t = strstr(s + 5, " - ")) != NULL)
336246074Sgabor				p4_fetchname(&names[NEW_FILE], t + 3);
337246074Sgabor			p4_fetchname(&names[OLD_FILE], s + 5);
338246074Sgabor		}
339246074Sgabor		if ((!diff_type || diff_type == ED_DIFF) &&
340275553Spfg		    first_command_line >= 0 &&
341246074Sgabor		    strEQ(s, ".\n")) {
342246074Sgabor			p_indent = indent;
343246074Sgabor			p_start = first_command_line;
344246074Sgabor			p_sline = fcl_line;
345246074Sgabor			retval = ED_DIFF;
346246074Sgabor			goto scan_exit;
347246074Sgabor		}
348246074Sgabor		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
349246074Sgabor			if (strnEQ(s + 4, "0,0", 3))
350246074Sgabor				ok_to_create_file = true;
351246074Sgabor			p_indent = indent;
352246074Sgabor			p_start = this_line;
353246074Sgabor			p_sline = p_input_line;
354246074Sgabor			retval = UNI_DIFF;
355246074Sgabor			goto scan_exit;
356246074Sgabor		}
357246074Sgabor		stars_this_line = strnEQ(s, "********", 8);
358246074Sgabor		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
359246074Sgabor		    strnEQ(s, "*** ", 4)) {
360275612Spfg			if (strtolinenum(s + 4, &s) == 0)
361246074Sgabor				ok_to_create_file = true;
362246074Sgabor			/*
363246074Sgabor			 * If this is a new context diff the character just
364275553Spfg			 * at the end of the line is a '*'.
365246074Sgabor			 */
366275553Spfg			while (*s && *s != '\n')
367246074Sgabor				s++;
368246074Sgabor			p_indent = indent;
369246074Sgabor			p_start = previous_line;
370246074Sgabor			p_sline = p_input_line - 1;
371246074Sgabor			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
372246074Sgabor			goto scan_exit;
373246074Sgabor		}
374246074Sgabor		if ((!diff_type || diff_type == NORMAL_DIFF) &&
375246074Sgabor		    last_line_was_command &&
376246074Sgabor		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
377246074Sgabor			p_start = previous_line;
378246074Sgabor			p_sline = p_input_line - 1;
379246074Sgabor			p_indent = indent;
380246074Sgabor			retval = NORMAL_DIFF;
381246074Sgabor			goto scan_exit;
382246074Sgabor		}
383246074Sgabor	}
384246074Sgaborscan_exit:
385246074Sgabor	if (retval == UNI_DIFF) {
386246074Sgabor		/* unswap old and new */
387246074Sgabor		struct file_name tmp = names[OLD_FILE];
388246074Sgabor		names[OLD_FILE] = names[NEW_FILE];
389246074Sgabor		names[NEW_FILE] = tmp;
390246074Sgabor	}
391246074Sgabor	if (filearg[0] == NULL) {
392246074Sgabor		if (posix)
393246074Sgabor			filearg[0] = posix_name(names, ok_to_create_file);
394246074Sgabor		else {
395246074Sgabor			/* Ignore the Index: name for context diffs, like GNU */
396246074Sgabor			if (names[OLD_FILE].path != NULL ||
397246074Sgabor			    names[NEW_FILE].path != NULL) {
398246074Sgabor				free(names[INDEX_FILE].path);
399246074Sgabor				names[INDEX_FILE].path = NULL;
400246074Sgabor			}
401246074Sgabor			filearg[0] = best_name(names, ok_to_create_file);
402246074Sgabor		}
403246074Sgabor	}
404246074Sgabor
405246074Sgabor	free(bestguess);
406246074Sgabor	bestguess = NULL;
407246074Sgabor	if (filearg[0] != NULL)
408276218Spfg		bestguess = xstrdup(filearg[0]);
409246074Sgabor	else if (!ok_to_create_file) {
410246074Sgabor		/*
411246074Sgabor		 * We don't want to create a new file but we need a
412246074Sgabor		 * filename to set bestguess.  Avoid setting filearg[0]
413246074Sgabor		 * so the file is not created automatically.
414246074Sgabor		 */
415246074Sgabor		if (posix)
416246074Sgabor			bestguess = posix_name(names, true);
417246074Sgabor		else
418246074Sgabor			bestguess = best_name(names, true);
419246074Sgabor	}
420246074Sgabor	free(names[OLD_FILE].path);
421246074Sgabor	free(names[NEW_FILE].path);
422246074Sgabor	free(names[INDEX_FILE].path);
423246074Sgabor	return retval;
424246074Sgabor}
425246074Sgabor
426246074Sgabor/*
427246074Sgabor * Remember where this patch ends so we know where to start up again.
428246074Sgabor */
429246074Sgaborstatic void
430275553Spfgnext_intuit_at(off_t file_pos, LINENUM file_line)
431246074Sgabor{
432246074Sgabor	p_base = file_pos;
433246074Sgabor	p_bline = file_line;
434246074Sgabor}
435246074Sgabor
436246074Sgabor/*
437275553Spfg * Basically a verbose fseeko() to the actual diff listing.
438246074Sgabor */
439246074Sgaborstatic void
440275553Spfgskip_to(off_t file_pos, LINENUM file_line)
441246074Sgabor{
442246074Sgabor	size_t	len;
443246074Sgabor
444246074Sgabor	if (p_base > file_pos)
445275553Spfg		fatal("Internal error: seek %lld>%lld\n",
446275553Spfg		   (long long)p_base, (long long)file_pos);
447246074Sgabor	if (verbose && p_base < file_pos) {
448275553Spfg		fseeko(pfp, p_base, SEEK_SET);
449246074Sgabor		say("The text leading up to this was:\n--------------------------\n");
450275553Spfg		while (ftello(pfp) < file_pos) {
451246074Sgabor			len = pgets(false);
452246074Sgabor			if (len == 0)
453246074Sgabor				fatal("Unexpected end of file\n");
454246074Sgabor			say("|%s", buf);
455246074Sgabor		}
456246074Sgabor		say("--------------------------\n");
457246074Sgabor	} else
458275553Spfg		fseeko(pfp, file_pos, SEEK_SET);
459246074Sgabor	p_input_line = file_line - 1;
460246074Sgabor}
461246074Sgabor
462246074Sgabor/* Make this a function for better debugging.  */
463246074Sgaborstatic void
464246074Sgabormalformed(void)
465246074Sgabor{
466246074Sgabor	fatal("malformed patch at line %ld: %s", p_input_line, buf);
467246074Sgabor	/* about as informative as "Syntax error" in C */
468246074Sgabor}
469246074Sgabor
470246074Sgabor/*
471246074Sgabor * True if the line has been discarded (i.e. it is a line saying
472246074Sgabor *  "\ No newline at end of file".)
473246074Sgabor */
474246074Sgaborstatic bool
475246074Sgaborremove_special_line(void)
476246074Sgabor{
477246074Sgabor	int	c;
478246074Sgabor
479246074Sgabor	c = fgetc(pfp);
480246074Sgabor	if (c == '\\') {
481246074Sgabor		do {
482246074Sgabor			c = fgetc(pfp);
483246074Sgabor		} while (c != EOF && c != '\n');
484246074Sgabor
485246074Sgabor		return true;
486246074Sgabor	}
487246074Sgabor	if (c != EOF)
488275553Spfg		fseeko(pfp, -1, SEEK_CUR);
489246074Sgabor
490246074Sgabor	return false;
491246074Sgabor}
492246074Sgabor
493246074Sgabor/*
494246074Sgabor * True if there is more of the current diff listing to process.
495246074Sgabor */
496246074Sgaborbool
497246074Sgaboranother_hunk(void)
498246074Sgabor{
499275553Spfg	off_t	line_beginning;			/* file pos of the current line */
500246074Sgabor	LINENUM	repl_beginning;			/* index of --- line */
501246074Sgabor	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
502246074Sgabor	LINENUM	fillsrc;			/* index of first line to copy */
503246074Sgabor	LINENUM	filldst;			/* index of first missing line */
504289677Seadler	bool	ptrn_spaces_eaten;		/* ptrn was slightly malformed */
505246074Sgabor	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
506246074Sgabor	bool	repl_missing;			/* we are now backtracking */
507275553Spfg	off_t	repl_backtrack_position;	/* file pos of first repl line */
508246074Sgabor	LINENUM	repl_patch_line;		/* input line number for same */
509246074Sgabor	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
510246074Sgabor	char	*s;
511246074Sgabor	size_t	len;
512246074Sgabor	int	context = 0;
513246074Sgabor
514246074Sgabor	while (p_end >= 0) {
515246074Sgabor		if (p_end == p_efake)
516246074Sgabor			p_end = p_bfake;	/* don't free twice */
517246074Sgabor		else
518246074Sgabor			free(p_line[p_end]);
519246074Sgabor		p_end--;
520246074Sgabor	}
521246074Sgabor	p_efake = -1;
522246074Sgabor
523246074Sgabor	p_max = hunkmax;	/* gets reduced when --- found */
524246074Sgabor	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
525275553Spfg		line_beginning = ftello(pfp);
526246074Sgabor		repl_beginning = 0;
527246074Sgabor		fillcnt = 0;
528246074Sgabor		fillsrc = 0;
529246074Sgabor		filldst = 0;
530246074Sgabor		ptrn_spaces_eaten = false;
531246074Sgabor		repl_could_be_missing = true;
532246074Sgabor		repl_missing = false;
533246074Sgabor		repl_backtrack_position = 0;
534246074Sgabor		repl_patch_line = 0;
535246074Sgabor		ptrn_copiable = 0;
536246074Sgabor
537246074Sgabor		len = pgets(true);
538246074Sgabor		p_input_line++;
539246074Sgabor		if (len == 0 || strnNE(buf, "********", 8)) {
540246074Sgabor			next_intuit_at(line_beginning, p_input_line);
541246074Sgabor			return false;
542246074Sgabor		}
543246074Sgabor		p_context = 100;
544246074Sgabor		p_hunk_beg = p_input_line + 1;
545246074Sgabor		while (p_end < p_max) {
546275553Spfg			line_beginning = ftello(pfp);
547246074Sgabor			len = pgets(true);
548246074Sgabor			p_input_line++;
549246074Sgabor			if (len == 0) {
550246074Sgabor				if (p_max - p_end < 4) {
551246074Sgabor					/* assume blank lines got chopped */
552246074Sgabor					strlcpy(buf, "  \n", buf_size);
553246074Sgabor				} else {
554246074Sgabor					if (repl_beginning && repl_could_be_missing) {
555246074Sgabor						repl_missing = true;
556246074Sgabor						goto hunk_done;
557246074Sgabor					}
558246074Sgabor					fatal("unexpected end of file in patch\n");
559246074Sgabor				}
560246074Sgabor			}
561246074Sgabor			p_end++;
562246074Sgabor			if (p_end >= hunkmax)
563246074Sgabor				fatal("Internal error: hunk larger than hunk "
564246074Sgabor				    "buffer size");
565246074Sgabor			p_char[p_end] = *buf;
566246074Sgabor			p_line[p_end] = NULL;
567246074Sgabor			switch (*buf) {
568246074Sgabor			case '*':
569246074Sgabor				if (strnEQ(buf, "********", 8)) {
570246074Sgabor					if (repl_beginning && repl_could_be_missing) {
571246074Sgabor						repl_missing = true;
572246074Sgabor						goto hunk_done;
573246074Sgabor					} else
574246074Sgabor						fatal("unexpected end of hunk "
575246074Sgabor						    "at line %ld\n",
576246074Sgabor						    p_input_line);
577246074Sgabor				}
578246074Sgabor				if (p_end != 0) {
579246074Sgabor					if (repl_beginning && repl_could_be_missing) {
580246074Sgabor						repl_missing = true;
581246074Sgabor						goto hunk_done;
582246074Sgabor					}
583246074Sgabor					fatal("unexpected *** at line %ld: %s",
584246074Sgabor					    p_input_line, buf);
585246074Sgabor				}
586246074Sgabor				context = 0;
587246074Sgabor				p_line[p_end] = savestr(buf);
588246074Sgabor				if (out_of_mem) {
589246074Sgabor					p_end--;
590246074Sgabor					return false;
591246074Sgabor				}
592275582Spfg				for (s = buf;
593275582Spfg				     *s && !isdigit((unsigned char)*s); s++)
594246074Sgabor					;
595246074Sgabor				if (!*s)
596246074Sgabor					malformed();
597246074Sgabor				if (strnEQ(s, "0,0", 3))
598246074Sgabor					memmove(s, s + 2, strlen(s + 2) + 1);
599275612Spfg				p_first = strtolinenum(s, &s);
600246074Sgabor				if (*s == ',') {
601275582Spfg					for (;
602275582Spfg					     *s && !isdigit((unsigned char)*s); s++)
603246074Sgabor						;
604246074Sgabor					if (!*s)
605246074Sgabor						malformed();
606275612Spfg					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
607275612Spfg					if (p_ptrn_lines < 0)
608275612Spfg						malformed();
609246074Sgabor				} else if (p_first)
610246074Sgabor					p_ptrn_lines = 1;
611246074Sgabor				else {
612246074Sgabor					p_ptrn_lines = 0;
613246074Sgabor					p_first = 1;
614246074Sgabor				}
615275612Spfg				if (p_first >= LINENUM_MAX - p_ptrn_lines ||
616275612Spfg				    p_ptrn_lines >= LINENUM_MAX - 6)
617275612Spfg					malformed();
618246074Sgabor
619246074Sgabor				/* we need this much at least */
620246074Sgabor				p_max = p_ptrn_lines + 6;
621246074Sgabor				while (p_max >= hunkmax)
622246074Sgabor					grow_hunkmax();
623246074Sgabor				p_max = hunkmax;
624246074Sgabor				break;
625246074Sgabor			case '-':
626246074Sgabor				if (buf[1] == '-') {
627246074Sgabor					if (repl_beginning ||
628246074Sgabor					    (p_end != p_ptrn_lines + 1 +
629246074Sgabor					    (p_char[p_end - 1] == '\n'))) {
630246074Sgabor						if (p_end == 1) {
631246074Sgabor							/*
632246074Sgabor							 * `old' lines were omitted;
633246074Sgabor							 * set up to fill them in
634246074Sgabor							 * from 'new' context lines.
635246074Sgabor							 */
636246074Sgabor							p_end = p_ptrn_lines + 1;
637246074Sgabor							fillsrc = p_end + 1;
638246074Sgabor							filldst = 1;
639246074Sgabor							fillcnt = p_ptrn_lines;
640246074Sgabor						} else {
641246074Sgabor							if (repl_beginning) {
642246074Sgabor								if (repl_could_be_missing) {
643246074Sgabor									repl_missing = true;
644246074Sgabor									goto hunk_done;
645246074Sgabor								}
646246074Sgabor								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
647246074Sgabor								    p_input_line, p_hunk_beg + repl_beginning);
648246074Sgabor							} else {
649246074Sgabor								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
650246074Sgabor								    (p_end <= p_ptrn_lines
651246074Sgabor								    ? "Premature"
652246074Sgabor								    : "Overdue"),
653246074Sgabor								    p_input_line, p_hunk_beg);
654246074Sgabor							}
655246074Sgabor						}
656246074Sgabor					}
657246074Sgabor					repl_beginning = p_end;
658275553Spfg					repl_backtrack_position = ftello(pfp);
659246074Sgabor					repl_patch_line = p_input_line;
660246074Sgabor					p_line[p_end] = savestr(buf);
661246074Sgabor					if (out_of_mem) {
662246074Sgabor						p_end--;
663246074Sgabor						return false;
664246074Sgabor					}
665246074Sgabor					p_char[p_end] = '=';
666246074Sgabor					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
667246074Sgabor						;
668246074Sgabor					if (!*s)
669246074Sgabor						malformed();
670275612Spfg					p_newfirst = strtolinenum(s, &s);
671246074Sgabor					if (*s == ',') {
672246074Sgabor						for (; *s && !isdigit((unsigned char)*s); s++)
673246074Sgabor							;
674246074Sgabor						if (!*s)
675246074Sgabor							malformed();
676275612Spfg						p_repl_lines = strtolinenum(s, &s) -
677246074Sgabor						    p_newfirst + 1;
678275612Spfg						if (p_repl_lines < 0)
679275612Spfg							malformed();
680246074Sgabor					} else if (p_newfirst)
681246074Sgabor						p_repl_lines = 1;
682246074Sgabor					else {
683246074Sgabor						p_repl_lines = 0;
684246074Sgabor						p_newfirst = 1;
685246074Sgabor					}
686275612Spfg					if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
687275612Spfg					    p_repl_lines >= LINENUM_MAX - p_end)
688275612Spfg						malformed();
689246074Sgabor					p_max = p_repl_lines + p_end;
690246074Sgabor					if (p_max > MAXHUNKSIZE)
691246074Sgabor						fatal("hunk too large (%ld lines) at line %ld: %s",
692246074Sgabor						    p_max, p_input_line, buf);
693246074Sgabor					while (p_max >= hunkmax)
694246074Sgabor						grow_hunkmax();
695246074Sgabor					if (p_repl_lines != ptrn_copiable &&
696246074Sgabor					    (p_context != 0 || p_repl_lines != 1))
697246074Sgabor						repl_could_be_missing = false;
698246074Sgabor					break;
699246074Sgabor				}
700246074Sgabor				goto change_line;
701246074Sgabor			case '+':
702246074Sgabor			case '!':
703246074Sgabor				repl_could_be_missing = false;
704246074Sgabor		change_line:
705246074Sgabor				if (buf[1] == '\n' && canonicalize)
706246074Sgabor					strlcpy(buf + 1, " \n", buf_size - 1);
707275582Spfg				if (!isspace((unsigned char)buf[1]) &&
708275582Spfg				    buf[1] != '>' && buf[1] != '<' &&
709246074Sgabor				    repl_beginning && repl_could_be_missing) {
710246074Sgabor					repl_missing = true;
711246074Sgabor					goto hunk_done;
712246074Sgabor				}
713246074Sgabor				if (context >= 0) {
714246074Sgabor					if (context < p_context)
715246074Sgabor						p_context = context;
716246074Sgabor					context = -1000;
717246074Sgabor				}
718246074Sgabor				p_line[p_end] = savestr(buf + 2);
719246074Sgabor				if (out_of_mem) {
720246074Sgabor					p_end--;
721246074Sgabor					return false;
722246074Sgabor				}
723246074Sgabor				if (p_end == p_ptrn_lines) {
724246074Sgabor					if (remove_special_line()) {
725246074Sgabor						int	l;
726246074Sgabor
727246074Sgabor						l = strlen(p_line[p_end]) - 1;
728246074Sgabor						(p_line[p_end])[l] = 0;
729246074Sgabor					}
730246074Sgabor				}
731246074Sgabor				break;
732246074Sgabor			case '\t':
733246074Sgabor			case '\n':	/* assume the 2 spaces got eaten */
734246074Sgabor				if (repl_beginning && repl_could_be_missing &&
735246074Sgabor				    (!ptrn_spaces_eaten ||
736246074Sgabor				    diff_type == NEW_CONTEXT_DIFF)) {
737246074Sgabor					repl_missing = true;
738246074Sgabor					goto hunk_done;
739246074Sgabor				}
740246074Sgabor				p_line[p_end] = savestr(buf);
741246074Sgabor				if (out_of_mem) {
742246074Sgabor					p_end--;
743246074Sgabor					return false;
744246074Sgabor				}
745246074Sgabor				if (p_end != p_ptrn_lines + 1) {
746246074Sgabor					ptrn_spaces_eaten |= (repl_beginning != 0);
747246074Sgabor					context++;
748246074Sgabor					if (!repl_beginning)
749246074Sgabor						ptrn_copiable++;
750246074Sgabor					p_char[p_end] = ' ';
751246074Sgabor				}
752246074Sgabor				break;
753246074Sgabor			case ' ':
754246074Sgabor				if (!isspace((unsigned char)buf[1]) &&
755246074Sgabor				    repl_beginning && repl_could_be_missing) {
756246074Sgabor					repl_missing = true;
757246074Sgabor					goto hunk_done;
758246074Sgabor				}
759246074Sgabor				context++;
760246074Sgabor				if (!repl_beginning)
761246074Sgabor					ptrn_copiable++;
762246074Sgabor				p_line[p_end] = savestr(buf + 2);
763246074Sgabor				if (out_of_mem) {
764246074Sgabor					p_end--;
765246074Sgabor					return false;
766246074Sgabor				}
767246074Sgabor				break;
768246074Sgabor			default:
769246074Sgabor				if (repl_beginning && repl_could_be_missing) {
770246074Sgabor					repl_missing = true;
771246074Sgabor					goto hunk_done;
772246074Sgabor				}
773246074Sgabor				malformed();
774246074Sgabor			}
775246074Sgabor			/* set up p_len for strncmp() so we don't have to */
776246074Sgabor			/* assume null termination */
777246074Sgabor			if (p_line[p_end])
778246074Sgabor				p_len[p_end] = strlen(p_line[p_end]);
779246074Sgabor			else
780246074Sgabor				p_len[p_end] = 0;
781246074Sgabor		}
782246074Sgabor
783246074Sgaborhunk_done:
784246074Sgabor		if (p_end >= 0 && !repl_beginning)
785246074Sgabor			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
786246074Sgabor
787246074Sgabor		if (repl_missing) {
788246074Sgabor
789246074Sgabor			/* reset state back to just after --- */
790246074Sgabor			p_input_line = repl_patch_line;
791246074Sgabor			for (p_end--; p_end > repl_beginning; p_end--)
792246074Sgabor				free(p_line[p_end]);
793275553Spfg			fseeko(pfp, repl_backtrack_position, SEEK_SET);
794246074Sgabor
795246074Sgabor			/* redundant 'new' context lines were omitted - set */
796246074Sgabor			/* up to fill them in from the old file context */
797246074Sgabor			if (!p_context && p_repl_lines == 1) {
798246074Sgabor				p_repl_lines = 0;
799246074Sgabor				p_max--;
800246074Sgabor			}
801246074Sgabor			fillsrc = 1;
802246074Sgabor			filldst = repl_beginning + 1;
803246074Sgabor			fillcnt = p_repl_lines;
804246074Sgabor			p_end = p_max;
805246074Sgabor		} else if (!p_context && fillcnt == 1) {
806246074Sgabor			/* the first hunk was a null hunk with no context */
807246074Sgabor			/* and we were expecting one line -- fix it up. */
808246074Sgabor			while (filldst < p_end) {
809246074Sgabor				p_line[filldst] = p_line[filldst + 1];
810246074Sgabor				p_char[filldst] = p_char[filldst + 1];
811246074Sgabor				p_len[filldst] = p_len[filldst + 1];
812246074Sgabor				filldst++;
813246074Sgabor			}
814246074Sgabor#if 0
815246074Sgabor			repl_beginning--;	/* this doesn't need to be fixed */
816246074Sgabor#endif
817246074Sgabor			p_end--;
818246074Sgabor			p_first++;	/* do append rather than insert */
819246074Sgabor			fillcnt = 0;
820246074Sgabor			p_ptrn_lines = 0;
821246074Sgabor		}
822246074Sgabor		if (diff_type == CONTEXT_DIFF &&
823246074Sgabor		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
824246074Sgabor			if (verbose)
825246074Sgabor				say("%s\n%s\n%s\n",
826246074Sgabor				    "(Fascinating--this is really a new-style context diff but without",
827246074Sgabor				    "the telltale extra asterisks on the *** line that usually indicate",
828246074Sgabor				    "the new style...)");
829246074Sgabor			diff_type = NEW_CONTEXT_DIFF;
830246074Sgabor		}
831246074Sgabor		/* if there were omitted context lines, fill them in now */
832246074Sgabor		if (fillcnt) {
833246074Sgabor			p_bfake = filldst;	/* remember where not to free() */
834246074Sgabor			p_efake = filldst + fillcnt - 1;
835246074Sgabor			while (fillcnt-- > 0) {
836246074Sgabor				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
837246074Sgabor					fillsrc++;
838246074Sgabor				if (fillsrc > p_end)
839246074Sgabor					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
840246074Sgabor					    p_hunk_beg);
841246074Sgabor				p_line[filldst] = p_line[fillsrc];
842246074Sgabor				p_char[filldst] = p_char[fillsrc];
843246074Sgabor				p_len[filldst] = p_len[fillsrc];
844246074Sgabor				fillsrc++;
845246074Sgabor				filldst++;
846246074Sgabor			}
847246074Sgabor			while (fillsrc <= p_end && fillsrc != repl_beginning &&
848246074Sgabor			    p_char[fillsrc] != ' ')
849246074Sgabor				fillsrc++;
850246074Sgabor#ifdef DEBUGGING
851246074Sgabor			if (debug & 64)
852246074Sgabor				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
853246074Sgabor				fillsrc, filldst, repl_beginning, p_end + 1);
854246074Sgabor#endif
855246074Sgabor			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
856246074Sgabor				malformed();
857246074Sgabor			if (filldst != p_end + 1 && filldst != repl_beginning)
858246074Sgabor				malformed();
859246074Sgabor		}
860246074Sgabor		if (p_line[p_end] != NULL) {
861246074Sgabor			if (remove_special_line()) {
862246074Sgabor				p_len[p_end] -= 1;
863246074Sgabor				(p_line[p_end])[p_len[p_end]] = 0;
864246074Sgabor			}
865246074Sgabor		}
866246074Sgabor	} else if (diff_type == UNI_DIFF) {
867246074Sgabor		LINENUM	fillold;	/* index of old lines */
868246074Sgabor		LINENUM	fillnew;	/* index of new lines */
869246074Sgabor		char	ch;
870246074Sgabor
871275553Spfg		line_beginning = ftello(pfp); /* file pos of the current line */
872246074Sgabor		len = pgets(true);
873246074Sgabor		p_input_line++;
874246074Sgabor		if (len == 0 || strnNE(buf, "@@ -", 4)) {
875246074Sgabor			next_intuit_at(line_beginning, p_input_line);
876246074Sgabor			return false;
877246074Sgabor		}
878246074Sgabor		s = buf + 4;
879246074Sgabor		if (!*s)
880246074Sgabor			malformed();
881275612Spfg		p_first = strtolinenum(s, &s);
882246074Sgabor		if (*s == ',') {
883275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s);
884246074Sgabor		} else
885246074Sgabor			p_ptrn_lines = 1;
886246074Sgabor		if (*s == ' ')
887246074Sgabor			s++;
888246074Sgabor		if (*s != '+' || !*++s)
889246074Sgabor			malformed();
890275612Spfg		p_newfirst = strtolinenum(s, &s);
891246074Sgabor		if (*s == ',') {
892275612Spfg			p_repl_lines = strtolinenum(s + 1, &s);
893246074Sgabor		} else
894246074Sgabor			p_repl_lines = 1;
895246074Sgabor		if (*s == ' ')
896246074Sgabor			s++;
897246074Sgabor		if (*s != '@')
898246074Sgabor			malformed();
899275612Spfg		if (p_first >= LINENUM_MAX - p_ptrn_lines ||
900275612Spfg		    p_newfirst > LINENUM_MAX - p_repl_lines ||
901275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
902275612Spfg			malformed();
903246074Sgabor		if (!p_ptrn_lines)
904246074Sgabor			p_first++;	/* do append rather than insert */
905246074Sgabor		p_max = p_ptrn_lines + p_repl_lines + 1;
906246074Sgabor		while (p_max >= hunkmax)
907246074Sgabor			grow_hunkmax();
908246074Sgabor		fillold = 1;
909246074Sgabor		fillnew = fillold + p_ptrn_lines;
910246074Sgabor		p_end = fillnew + p_repl_lines;
911246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
912246074Sgabor		    p_first + p_ptrn_lines - 1);
913246074Sgabor		p_line[0] = savestr(buf);
914246074Sgabor		if (out_of_mem) {
915246074Sgabor			p_end = -1;
916246074Sgabor			return false;
917246074Sgabor		}
918246074Sgabor		p_char[0] = '*';
919246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
920246074Sgabor		    p_newfirst + p_repl_lines - 1);
921246074Sgabor		p_line[fillnew] = savestr(buf);
922246074Sgabor		if (out_of_mem) {
923246074Sgabor			p_end = 0;
924246074Sgabor			return false;
925246074Sgabor		}
926246074Sgabor		p_char[fillnew++] = '=';
927246074Sgabor		p_context = 100;
928246074Sgabor		context = 0;
929246074Sgabor		p_hunk_beg = p_input_line + 1;
930246074Sgabor		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
931275553Spfg			line_beginning = ftello(pfp);
932246074Sgabor			len = pgets(true);
933246074Sgabor			p_input_line++;
934246074Sgabor			if (len == 0) {
935246074Sgabor				if (p_max - fillnew < 3) {
936246074Sgabor					/* assume blank lines got chopped */
937246074Sgabor					strlcpy(buf, " \n", buf_size);
938246074Sgabor				} else {
939246074Sgabor					fatal("unexpected end of file in patch\n");
940246074Sgabor				}
941246074Sgabor			}
942246074Sgabor			if (*buf == '\t' || *buf == '\n') {
943246074Sgabor				ch = ' ';	/* assume the space got eaten */
944246074Sgabor				s = savestr(buf);
945246074Sgabor			} else {
946246074Sgabor				ch = *buf;
947246074Sgabor				s = savestr(buf + 1);
948246074Sgabor			}
949246074Sgabor			if (out_of_mem) {
950246074Sgabor				while (--fillnew > p_ptrn_lines)
951246074Sgabor					free(p_line[fillnew]);
952246074Sgabor				p_end = fillold - 1;
953246074Sgabor				return false;
954246074Sgabor			}
955246074Sgabor			switch (ch) {
956246074Sgabor			case '-':
957246074Sgabor				if (fillold > p_ptrn_lines) {
958246074Sgabor					free(s);
959246074Sgabor					p_end = fillnew - 1;
960246074Sgabor					malformed();
961246074Sgabor				}
962246074Sgabor				p_char[fillold] = ch;
963246074Sgabor				p_line[fillold] = s;
964246074Sgabor				p_len[fillold++] = strlen(s);
965246074Sgabor				if (fillold > p_ptrn_lines) {
966246074Sgabor					if (remove_special_line()) {
967246074Sgabor						p_len[fillold - 1] -= 1;
968246074Sgabor						s[p_len[fillold - 1]] = 0;
969246074Sgabor					}
970246074Sgabor				}
971246074Sgabor				break;
972246074Sgabor			case '=':
973246074Sgabor				ch = ' ';
974246074Sgabor				/* FALL THROUGH */
975246074Sgabor			case ' ':
976246074Sgabor				if (fillold > p_ptrn_lines) {
977246074Sgabor					free(s);
978246074Sgabor					while (--fillnew > p_ptrn_lines)
979246074Sgabor						free(p_line[fillnew]);
980246074Sgabor					p_end = fillold - 1;
981246074Sgabor					malformed();
982246074Sgabor				}
983246074Sgabor				context++;
984246074Sgabor				p_char[fillold] = ch;
985246074Sgabor				p_line[fillold] = s;
986246074Sgabor				p_len[fillold++] = strlen(s);
987246074Sgabor				s = savestr(s);
988246074Sgabor				if (out_of_mem) {
989246074Sgabor					while (--fillnew > p_ptrn_lines)
990246074Sgabor						free(p_line[fillnew]);
991246074Sgabor					p_end = fillold - 1;
992246074Sgabor					return false;
993246074Sgabor				}
994246074Sgabor				if (fillold > p_ptrn_lines) {
995246074Sgabor					if (remove_special_line()) {
996246074Sgabor						p_len[fillold - 1] -= 1;
997246074Sgabor						s[p_len[fillold - 1]] = 0;
998246074Sgabor					}
999246074Sgabor				}
1000246074Sgabor				/* FALL THROUGH */
1001246074Sgabor			case '+':
1002246074Sgabor				if (fillnew > p_end) {
1003246074Sgabor					free(s);
1004246074Sgabor					while (--fillnew > p_ptrn_lines)
1005246074Sgabor						free(p_line[fillnew]);
1006246074Sgabor					p_end = fillold - 1;
1007246074Sgabor					malformed();
1008246074Sgabor				}
1009246074Sgabor				p_char[fillnew] = ch;
1010246074Sgabor				p_line[fillnew] = s;
1011246074Sgabor				p_len[fillnew++] = strlen(s);
1012246074Sgabor				if (fillold > p_ptrn_lines) {
1013246074Sgabor					if (remove_special_line()) {
1014246074Sgabor						p_len[fillnew - 1] -= 1;
1015246074Sgabor						s[p_len[fillnew - 1]] = 0;
1016246074Sgabor					}
1017246074Sgabor				}
1018246074Sgabor				break;
1019246074Sgabor			default:
1020246074Sgabor				p_end = fillnew;
1021246074Sgabor				malformed();
1022246074Sgabor			}
1023246074Sgabor			if (ch != ' ' && context > 0) {
1024246074Sgabor				if (context < p_context)
1025246074Sgabor					p_context = context;
1026246074Sgabor				context = -1000;
1027246074Sgabor			}
1028246074Sgabor		}		/* while */
1029246074Sgabor	} else {		/* normal diff--fake it up */
1030246074Sgabor		char	hunk_type;
1031246074Sgabor		int	i;
1032246074Sgabor		LINENUM	min, max;
1033246074Sgabor
1034275553Spfg		line_beginning = ftello(pfp);
1035246074Sgabor		p_context = 0;
1036246074Sgabor		len = pgets(true);
1037246074Sgabor		p_input_line++;
1038246074Sgabor		if (len == 0 || !isdigit((unsigned char)*buf)) {
1039246074Sgabor			next_intuit_at(line_beginning, p_input_line);
1040246074Sgabor			return false;
1041246074Sgabor		}
1042275612Spfg		p_first = strtolinenum(buf, &s);
1043246074Sgabor		if (*s == ',') {
1044275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1045275612Spfg			if (p_ptrn_lines < 0)
1046275612Spfg				malformed();
1047246074Sgabor		} else
1048246074Sgabor			p_ptrn_lines = (*s != 'a');
1049246074Sgabor		hunk_type = *s;
1050246074Sgabor		if (hunk_type == 'a')
1051246074Sgabor			p_first++;	/* do append rather than insert */
1052275612Spfg		min = strtolinenum(s + 1, &s);
1053246074Sgabor		if (*s == ',')
1054275612Spfg			max = strtolinenum(s + 1, &s);
1055246074Sgabor		else
1056246074Sgabor			max = min;
1057275612Spfg		if (min < 0 || min > max || max - min == LINENUM_MAX)
1058275612Spfg			malformed();
1059246074Sgabor		if (hunk_type == 'd')
1060246074Sgabor			min++;
1061275612Spfg		p_newfirst = min;
1062275612Spfg		p_repl_lines = max - min + 1;
1063275612Spfg		if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1064275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1065275612Spfg			malformed();
1066275612Spfg		p_end = p_ptrn_lines + p_repl_lines + 1;
1067246074Sgabor		if (p_end > MAXHUNKSIZE)
1068246074Sgabor			fatal("hunk too large (%ld lines) at line %ld: %s",
1069246074Sgabor			    p_end, p_input_line, buf);
1070246074Sgabor		while (p_end >= hunkmax)
1071246074Sgabor			grow_hunkmax();
1072246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1073246074Sgabor		    p_first + p_ptrn_lines - 1);
1074246074Sgabor		p_line[0] = savestr(buf);
1075246074Sgabor		if (out_of_mem) {
1076246074Sgabor			p_end = -1;
1077246074Sgabor			return false;
1078246074Sgabor		}
1079246074Sgabor		p_char[0] = '*';
1080246074Sgabor		for (i = 1; i <= p_ptrn_lines; i++) {
1081246074Sgabor			len = pgets(true);
1082246074Sgabor			p_input_line++;
1083246074Sgabor			if (len == 0)
1084246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1085246074Sgabor				    p_input_line);
1086246074Sgabor			if (*buf != '<')
1087246074Sgabor				fatal("< expected at line %ld of patch\n",
1088246074Sgabor				    p_input_line);
1089246074Sgabor			p_line[i] = savestr(buf + 2);
1090246074Sgabor			if (out_of_mem) {
1091246074Sgabor				p_end = i - 1;
1092246074Sgabor				return false;
1093246074Sgabor			}
1094246074Sgabor			p_len[i] = strlen(p_line[i]);
1095246074Sgabor			p_char[i] = '-';
1096246074Sgabor		}
1097246074Sgabor
1098246074Sgabor		if (remove_special_line()) {
1099246074Sgabor			p_len[i - 1] -= 1;
1100246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1101246074Sgabor		}
1102246074Sgabor		if (hunk_type == 'c') {
1103246074Sgabor			len = pgets(true);
1104246074Sgabor			p_input_line++;
1105246074Sgabor			if (len == 0)
1106246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1107246074Sgabor				    p_input_line);
1108246074Sgabor			if (*buf != '-')
1109246074Sgabor				fatal("--- expected at line %ld of patch\n",
1110246074Sgabor				    p_input_line);
1111246074Sgabor		}
1112246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1113246074Sgabor		p_line[i] = savestr(buf);
1114246074Sgabor		if (out_of_mem) {
1115246074Sgabor			p_end = i - 1;
1116246074Sgabor			return false;
1117246074Sgabor		}
1118246074Sgabor		p_char[i] = '=';
1119246074Sgabor		for (i++; i <= p_end; i++) {
1120246074Sgabor			len = pgets(true);
1121246074Sgabor			p_input_line++;
1122246074Sgabor			if (len == 0)
1123246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1124246074Sgabor				    p_input_line);
1125246074Sgabor			if (*buf != '>')
1126246074Sgabor				fatal("> expected at line %ld of patch\n",
1127246074Sgabor				    p_input_line);
1128328147Skevans			/* Don't overrun if we don't have enough line */
1129328147Skevans			if (len > 2)
1130328147Skevans				p_line[i] = savestr(buf + 2);
1131328147Skevans			else
1132328147Skevans				p_line[i] = savestr("");
1133328147Skevans
1134246074Sgabor			if (out_of_mem) {
1135246074Sgabor				p_end = i - 1;
1136246074Sgabor				return false;
1137246074Sgabor			}
1138246074Sgabor			p_len[i] = strlen(p_line[i]);
1139246074Sgabor			p_char[i] = '+';
1140246074Sgabor		}
1141246074Sgabor
1142246074Sgabor		if (remove_special_line()) {
1143246074Sgabor			p_len[i - 1] -= 1;
1144246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1145246074Sgabor		}
1146246074Sgabor	}
1147246074Sgabor	if (reverse)		/* backwards patch? */
1148246074Sgabor		if (!pch_swap())
1149246074Sgabor			say("Not enough memory to swap next hunk!\n");
1150246074Sgabor#ifdef DEBUGGING
1151246074Sgabor	if (debug & 2) {
1152298530Spfg		LINENUM	i;
1153246074Sgabor		char	special;
1154246074Sgabor
1155246074Sgabor		for (i = 0; i <= p_end; i++) {
1156246074Sgabor			if (i == p_ptrn_lines)
1157246074Sgabor				special = '^';
1158246074Sgabor			else
1159246074Sgabor				special = ' ';
1160298530Spfg			fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1161246074Sgabor			    special, p_line[i]);
1162246074Sgabor			fflush(stderr);
1163246074Sgabor		}
1164246074Sgabor	}
1165246074Sgabor#endif
1166246074Sgabor	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1167246074Sgabor		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1168246074Sgabor	return true;
1169246074Sgabor}
1170246074Sgabor
1171246074Sgabor/*
1172246074Sgabor * Input a line from the patch file.
1173246074Sgabor * Worry about indentation if do_indent is true.
1174246074Sgabor * The line is read directly into the buf global variable which
1175246074Sgabor * is resized if necessary in order to hold the complete line.
1176246074Sgabor * Returns the number of characters read including the terminating
1177246074Sgabor * '\n', if any.
1178246074Sgabor */
1179246074Sgaborsize_t
1180246074Sgaborpgets(bool do_indent)
1181246074Sgabor{
1182246074Sgabor	char *line;
1183246074Sgabor	size_t len;
1184246074Sgabor	int indent = 0, skipped = 0;
1185246074Sgabor
1186246074Sgabor	line = fgetln(pfp, &len);
1187246074Sgabor	if (line != NULL) {
1188246074Sgabor		if (len + 1 > buf_size) {
1189246074Sgabor			while (len + 1 > buf_size)
1190246074Sgabor				buf_size *= 2;
1191246074Sgabor			free(buf);
1192246074Sgabor			buf = malloc(buf_size);
1193246074Sgabor			if (buf == NULL)
1194246074Sgabor				fatal("out of memory\n");
1195246074Sgabor		}
1196246074Sgabor		if (do_indent == 1 && p_indent) {
1197246074Sgabor			for (;
1198246074Sgabor			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1199246074Sgabor			    line++, skipped++) {
1200246074Sgabor				if (*line == '\t')
1201246074Sgabor					indent += 8 - (indent %7);
1202246074Sgabor				else
1203246074Sgabor					indent++;
1204246074Sgabor			}
1205246074Sgabor		}
1206252637Sobrien		memcpy(buf, line, len - skipped);
1207246074Sgabor		buf[len - skipped] = '\0';
1208246074Sgabor	}
1209246074Sgabor	return len;
1210246074Sgabor}
1211246074Sgabor
1212246074Sgabor
1213246074Sgabor/*
1214246074Sgabor * Reverse the old and new portions of the current hunk.
1215246074Sgabor */
1216246074Sgaborbool
1217246074Sgaborpch_swap(void)
1218246074Sgabor{
1219246074Sgabor	char	**tp_line;	/* the text of the hunk */
1220267490Spfg	unsigned short	*tp_len;/* length of each line */
1221246074Sgabor	char	*tp_char;	/* +, -, and ! */
1222246074Sgabor	LINENUM	i;
1223246074Sgabor	LINENUM	n;
1224246074Sgabor	bool	blankline = false;
1225246074Sgabor	char	*s;
1226246074Sgabor
1227246074Sgabor	i = p_first;
1228246074Sgabor	p_first = p_newfirst;
1229246074Sgabor	p_newfirst = i;
1230246074Sgabor
1231246074Sgabor	/* make a scratch copy */
1232246074Sgabor
1233246074Sgabor	tp_line = p_line;
1234246074Sgabor	tp_len = p_len;
1235246074Sgabor	tp_char = p_char;
1236246074Sgabor	p_line = NULL;	/* force set_hunkmax to allocate again */
1237246074Sgabor	p_len = NULL;
1238246074Sgabor	p_char = NULL;
1239246074Sgabor	set_hunkmax();
1240246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1241246074Sgabor
1242246074Sgabor		free(p_line);
1243246074Sgabor		p_line = tp_line;
1244246074Sgabor		free(p_len);
1245246074Sgabor		p_len = tp_len;
1246246074Sgabor		free(p_char);
1247246074Sgabor		p_char = tp_char;
1248246074Sgabor		return false;	/* not enough memory to swap hunk! */
1249246074Sgabor	}
1250246074Sgabor	/* now turn the new into the old */
1251246074Sgabor
1252246074Sgabor	i = p_ptrn_lines + 1;
1253246074Sgabor	if (tp_char[i] == '\n') {	/* account for possible blank line */
1254246074Sgabor		blankline = true;
1255246074Sgabor		i++;
1256246074Sgabor	}
1257246074Sgabor	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1258246074Sgabor		if (p_efake <= i)
1259246074Sgabor			n = p_end - i + 1;
1260246074Sgabor		else
1261246074Sgabor			n = -i;
1262246074Sgabor		p_efake += n;
1263246074Sgabor		p_bfake += n;
1264246074Sgabor	}
1265246074Sgabor	for (n = 0; i <= p_end; i++, n++) {
1266246074Sgabor		p_line[n] = tp_line[i];
1267246074Sgabor		p_char[n] = tp_char[i];
1268246074Sgabor		if (p_char[n] == '+')
1269246074Sgabor			p_char[n] = '-';
1270246074Sgabor		p_len[n] = tp_len[i];
1271246074Sgabor	}
1272246074Sgabor	if (blankline) {
1273246074Sgabor		i = p_ptrn_lines + 1;
1274246074Sgabor		p_line[n] = tp_line[i];
1275246074Sgabor		p_char[n] = tp_char[i];
1276246074Sgabor		p_len[n] = tp_len[i];
1277246074Sgabor		n++;
1278246074Sgabor	}
1279246074Sgabor	if (p_char[0] != '=')
1280246074Sgabor		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1281246074Sgabor		    p_input_line, p_char[0]);
1282246074Sgabor	p_char[0] = '*';
1283246074Sgabor	for (s = p_line[0]; *s; s++)
1284246074Sgabor		if (*s == '-')
1285246074Sgabor			*s = '*';
1286246074Sgabor
1287246074Sgabor	/* now turn the old into the new */
1288246074Sgabor
1289246074Sgabor	if (p_char[0] != '*')
1290246074Sgabor		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1291246074Sgabor		    p_input_line, p_char[0]);
1292246074Sgabor	tp_char[0] = '=';
1293246074Sgabor	for (s = tp_line[0]; *s; s++)
1294246074Sgabor		if (*s == '*')
1295246074Sgabor			*s = '-';
1296246074Sgabor	for (i = 0; n <= p_end; i++, n++) {
1297246074Sgabor		p_line[n] = tp_line[i];
1298246074Sgabor		p_char[n] = tp_char[i];
1299246074Sgabor		if (p_char[n] == '-')
1300246074Sgabor			p_char[n] = '+';
1301246074Sgabor		p_len[n] = tp_len[i];
1302246074Sgabor	}
1303246074Sgabor
1304246074Sgabor	if (i != p_ptrn_lines + 1)
1305246074Sgabor		fatal("Malformed patch at line %ld: expected %ld lines, "
1306246074Sgabor		    "got %ld\n",
1307246074Sgabor		    p_input_line, p_ptrn_lines + 1, i);
1308246074Sgabor
1309246074Sgabor	i = p_ptrn_lines;
1310246074Sgabor	p_ptrn_lines = p_repl_lines;
1311246074Sgabor	p_repl_lines = i;
1312246074Sgabor
1313246074Sgabor	free(tp_line);
1314246074Sgabor	free(tp_len);
1315246074Sgabor	free(tp_char);
1316246074Sgabor
1317246074Sgabor	return true;
1318246074Sgabor}
1319246074Sgabor
1320246074Sgabor/*
1321246074Sgabor * Return the specified line position in the old file of the old context.
1322246074Sgabor */
1323246074SgaborLINENUM
1324246074Sgaborpch_first(void)
1325246074Sgabor{
1326246074Sgabor	return p_first;
1327246074Sgabor}
1328246074Sgabor
1329246074Sgabor/*
1330246074Sgabor * Return the number of lines of old context.
1331246074Sgabor */
1332246074SgaborLINENUM
1333246074Sgaborpch_ptrn_lines(void)
1334246074Sgabor{
1335246074Sgabor	return p_ptrn_lines;
1336246074Sgabor}
1337246074Sgabor
1338246074Sgabor/*
1339246074Sgabor * Return the probable line position in the new file of the first line.
1340246074Sgabor */
1341246074SgaborLINENUM
1342246074Sgaborpch_newfirst(void)
1343246074Sgabor{
1344246074Sgabor	return p_newfirst;
1345246074Sgabor}
1346246074Sgabor
1347246074Sgabor/*
1348246074Sgabor * Return the number of lines in the replacement text including context.
1349246074Sgabor */
1350246074SgaborLINENUM
1351246074Sgaborpch_repl_lines(void)
1352246074Sgabor{
1353246074Sgabor	return p_repl_lines;
1354246074Sgabor}
1355246074Sgabor
1356246074Sgabor/*
1357246074Sgabor * Return the number of lines in the whole hunk.
1358246074Sgabor */
1359246074SgaborLINENUM
1360246074Sgaborpch_end(void)
1361246074Sgabor{
1362246074Sgabor	return p_end;
1363246074Sgabor}
1364246074Sgabor
1365246074Sgabor/*
1366246074Sgabor * Return the number of context lines before the first changed line.
1367246074Sgabor */
1368246074SgaborLINENUM
1369246074Sgaborpch_context(void)
1370246074Sgabor{
1371246074Sgabor	return p_context;
1372246074Sgabor}
1373246074Sgabor
1374246074Sgabor/*
1375246074Sgabor * Return the length of a particular patch line.
1376246074Sgabor */
1377267490Spfgunsigned short
1378246074Sgaborpch_line_len(LINENUM line)
1379246074Sgabor{
1380246074Sgabor	return p_len[line];
1381246074Sgabor}
1382246074Sgabor
1383246074Sgabor/*
1384246074Sgabor * Return the control character (+, -, *, !, etc) for a patch line.
1385246074Sgabor */
1386246074Sgaborchar
1387246074Sgaborpch_char(LINENUM line)
1388246074Sgabor{
1389246074Sgabor	return p_char[line];
1390246074Sgabor}
1391246074Sgabor
1392246074Sgabor/*
1393246074Sgabor * Return a pointer to a particular patch line.
1394246074Sgabor */
1395246074Sgaborchar *
1396246074Sgaborpfetch(LINENUM line)
1397246074Sgabor{
1398246074Sgabor	return p_line[line];
1399246074Sgabor}
1400246074Sgabor
1401246074Sgabor/*
1402246074Sgabor * Return where in the patch file this hunk began, for error messages.
1403246074Sgabor */
1404246074SgaborLINENUM
1405246074Sgaborpch_hunk_beg(void)
1406246074Sgabor{
1407246074Sgabor	return p_hunk_beg;
1408246074Sgabor}
1409246074Sgabor
1410246074Sgabor/*
1411246074Sgabor * Apply an ed script by feeding ed itself.
1412246074Sgabor */
1413246074Sgaborvoid
1414246074Sgabordo_ed_script(void)
1415246074Sgabor{
1416246074Sgabor	char	*t;
1417275553Spfg	off_t	beginning_of_this_line;
1418246074Sgabor	FILE	*pipefp = NULL;
1419286346Sdelphij	int	continuation;
1420246074Sgabor
1421246074Sgabor	if (!skip_rest_of_patch) {
1422246074Sgabor		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1423246074Sgabor			unlink(TMPOUTNAME);
1424246074Sgabor			fatal("can't create temp file %s", TMPOUTNAME);
1425246074Sgabor		}
1426286346Sdelphij		snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1427246074Sgabor		    verbose ? " " : " -s ", TMPOUTNAME);
1428246074Sgabor		pipefp = popen(buf, "w");
1429246074Sgabor	}
1430246074Sgabor	for (;;) {
1431275553Spfg		beginning_of_this_line = ftello(pfp);
1432246074Sgabor		if (pgets(true) == 0) {
1433246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1434246074Sgabor			break;
1435246074Sgabor		}
1436246074Sgabor		p_input_line++;
1437246074Sgabor		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1438246074Sgabor			;
1439246074Sgabor		/* POSIX defines allowed commands as {a,c,d,i,s} */
1440275582Spfg		if (isdigit((unsigned char)*buf) &&
1441275582Spfg		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1442246074Sgabor			if (pipefp != NULL)
1443246074Sgabor				fputs(buf, pipefp);
1444286346Sdelphij			if (*t == 's') {
1445286346Sdelphij				for (;;) {
1446286346Sdelphij					continuation = 0;
1447286346Sdelphij					t = strchr(buf, '\0') - 1;
1448286346Sdelphij					while (--t >= buf && *t == '\\')
1449286346Sdelphij						continuation = !continuation;
1450286346Sdelphij					if (!continuation ||
1451286346Sdelphij					    pgets(true) == 0)
1452286346Sdelphij						break;
1453286346Sdelphij					if (pipefp != NULL)
1454286346Sdelphij						fputs(buf, pipefp);
1455286346Sdelphij				}
1456286346Sdelphij			} else if (*t != 'd') {
1457246074Sgabor				while (pgets(true)) {
1458246074Sgabor					p_input_line++;
1459246074Sgabor					if (pipefp != NULL)
1460246074Sgabor						fputs(buf, pipefp);
1461246074Sgabor					if (strEQ(buf, ".\n"))
1462246074Sgabor						break;
1463246074Sgabor				}
1464246074Sgabor			}
1465246074Sgabor		} else {
1466246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1467246074Sgabor			break;
1468246074Sgabor		}
1469246074Sgabor	}
1470246074Sgabor	if (pipefp == NULL)
1471246074Sgabor		return;
1472246074Sgabor	fprintf(pipefp, "w\n");
1473246074Sgabor	fprintf(pipefp, "q\n");
1474246074Sgabor	fflush(pipefp);
1475246074Sgabor	pclose(pipefp);
1476246074Sgabor	ignore_signals();
1477246074Sgabor	if (!check_only) {
1478246074Sgabor		if (move_file(TMPOUTNAME, outname) < 0) {
1479246074Sgabor			toutkeep = true;
1480246074Sgabor			chmod(TMPOUTNAME, filemode);
1481246074Sgabor		} else
1482246074Sgabor			chmod(outname, filemode);
1483246074Sgabor	}
1484246074Sgabor	set_signals(1);
1485246074Sgabor}
1486246074Sgabor
1487246074Sgabor/*
1488246074Sgabor * Choose the name of the file to be patched based on POSIX rules.
1489246074Sgabor * NOTE: the POSIX rules are amazingly stupid and we only follow them
1490246074Sgabor *       if the user specified --posix or set POSIXLY_CORRECT.
1491246074Sgabor */
1492246074Sgaborstatic char *
1493246074Sgaborposix_name(const struct file_name *names, bool assume_exists)
1494246074Sgabor{
1495246074Sgabor	char *path = NULL;
1496246074Sgabor	int i;
1497246074Sgabor
1498246074Sgabor	/*
1499246074Sgabor	 * POSIX states that the filename will be chosen from one
1500246074Sgabor	 * of the old, new and index names (in that order) if
1501246074Sgabor	 * the file exists relative to CWD after -p stripping.
1502246074Sgabor	 */
1503246074Sgabor	for (i = 0; i < MAX_FILE; i++) {
1504246074Sgabor		if (names[i].path != NULL && names[i].exists) {
1505246074Sgabor			path = names[i].path;
1506246074Sgabor			break;
1507246074Sgabor		}
1508246074Sgabor	}
1509246074Sgabor	if (path == NULL && !assume_exists) {
1510246074Sgabor		/*
1511286795Sdelphij		 * No files found, check to see if the diff could be
1512286795Sdelphij		 * creating a new file.
1513246074Sgabor		 */
1514246074Sgabor		if (path == NULL && ok_to_create_file &&
1515246074Sgabor		    names[NEW_FILE].path != NULL)
1516246074Sgabor			path = names[NEW_FILE].path;
1517246074Sgabor	}
1518246074Sgabor
1519276218Spfg	return path ? xstrdup(path) : NULL;
1520246074Sgabor}
1521246074Sgabor
1522246074Sgaborstatic char *
1523286795Sdelphijcompare_names(const struct file_name *names, bool assume_exists)
1524246074Sgabor{
1525246074Sgabor	size_t min_components, min_baselen, min_len, tmp;
1526246074Sgabor	char *best = NULL;
1527255232Sse	char *path;
1528246074Sgabor	int i;
1529246074Sgabor
1530246074Sgabor	/*
1531246074Sgabor	 * The "best" name is the one with the fewest number of path
1532246074Sgabor	 * components, the shortest basename length, and the shortest
1533246074Sgabor	 * overall length (in that order).  We only use the Index: file
1534246074Sgabor	 * if neither of the old or new files could be intuited from
1535246074Sgabor	 * the diff header.
1536246074Sgabor	 */
1537246074Sgabor	min_components = min_baselen = min_len = SIZE_MAX;
1538246074Sgabor	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1539255232Sse		path = names[i].path;
1540286795Sdelphij		if (path == NULL || (!names[i].exists && !assume_exists))
1541246074Sgabor			continue;
1542255232Sse		if ((tmp = num_components(path)) > min_components)
1543246074Sgabor			continue;
1544250943Sse		if (tmp < min_components) {
1545250943Sse			min_components = tmp;
1546255232Sse			best = path;
1547250943Sse		}
1548255232Sse		if ((tmp = strlen(basename(path))) > min_baselen)
1549246074Sgabor			continue;
1550250943Sse		if (tmp < min_baselen) {
1551250943Sse			min_baselen = tmp;
1552255232Sse			best = path;
1553250943Sse		}
1554255232Sse		if ((tmp = strlen(path)) > min_len)
1555246074Sgabor			continue;
1556246074Sgabor		min_len = tmp;
1557255232Sse		best = path;
1558246074Sgabor	}
1559255232Sse	return best;
1560255232Sse}
1561255232Sse
1562255232Sse/*
1563255232Sse * Choose the name of the file to be patched based the "best" one
1564255232Sse * available.
1565255232Sse */
1566255232Ssestatic char *
1567255232Ssebest_name(const struct file_name *names, bool assume_exists)
1568255232Sse{
1569255232Sse	char *best;
1570255232Sse
1571286795Sdelphij	best = compare_names(names, assume_exists);
1572246074Sgabor
1573286795Sdelphij	/* No match?  Check to see if the diff could be creating a new file. */
1574286795Sdelphij	if (best == NULL && ok_to_create_file)
1575286795Sdelphij		best = names[NEW_FILE].path;
1576286795Sdelphij
1577276218Spfg	return best ? xstrdup(best) : NULL;
1578246074Sgabor}
1579246074Sgabor
1580246074Sgaborstatic size_t
1581246074Sgabornum_components(const char *path)
1582246074Sgabor{
1583246074Sgabor	size_t n;
1584246074Sgabor	const char *cp;
1585246074Sgabor
1586246074Sgabor	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1587246074Sgabor		while (*cp == '/')
1588246074Sgabor			cp++;		/* skip consecutive slashes */
1589246074Sgabor	}
1590246074Sgabor	return n;
1591246074Sgabor}
1592275612Spfg
1593275612Spfg/*
1594275612Spfg * Convert number at NPTR into LINENUM and save address of first
1595275612Spfg * character that is not a digit in ENDPTR.  If conversion is not
1596275612Spfg * possible, call fatal.
1597275612Spfg */
1598275612Spfgstatic LINENUM
1599275612Spfgstrtolinenum(char *nptr, char **endptr)
1600275612Spfg{
1601275612Spfg	LINENUM rv;
1602275612Spfg	char c;
1603275612Spfg	char *p;
1604275612Spfg	const char *errstr;
1605275612Spfg
1606275612Spfg	for (p = nptr; isdigit((unsigned char)*p); p++)
1607275612Spfg		;
1608275612Spfg
1609275612Spfg	if (p == nptr)
1610275612Spfg		malformed();
1611275612Spfg
1612275612Spfg	c = *p;
1613275612Spfg	*p = '\0';
1614275612Spfg
1615275612Spfg	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1616275612Spfg	if (errstr != NULL)
1617275612Spfg		fatal("invalid line number at line %ld: `%s' is %s\n",
1618275612Spfg		    p_input_line, nptr, errstr);
1619276218Spfg
1620275612Spfg	*p = c;
1621275612Spfg	*endptr = p;
1622275612Spfg
1623275612Spfg	return rv;
1624275612Spfg}
1625