pch.c revision 289677
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: head/usr.bin/patch/pch.c 289677 2015-10-21 05:37:09Z eadler $
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) {
219246074Sgabor			ask("No file found--skip this patch? [n] ");
220246074Sgabor			if (*buf != 'y')
221246074Sgabor				continue;
222246074Sgabor			if (verbose)
223246074Sgabor				say("Skipping patch...\n");
224246074Sgabor			free(filearg[0]);
225246074Sgabor			filearg[0] = fetchname(bestguess, &exists, 0);
226246074Sgabor			skip_rest_of_patch = true;
227246074Sgabor			return true;
228246074Sgabor		}
229246074Sgabor	}
230246074Sgabor	return true;
231246074Sgabor}
232246074Sgabor
233246074Sgaborstatic void
234246074Sgaborp4_fetchname(struct file_name *name, char *str)
235246074Sgabor{
236246074Sgabor	char *t, *h;
237246074Sgabor
238246074Sgabor	/* Skip leading whitespace. */
239246074Sgabor	while (isspace((unsigned char)*str))
240246074Sgabor		str++;
241246074Sgabor
242246074Sgabor	/* Remove the file revision number. */
243246074Sgabor	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
244246074Sgabor		if (*t == '#')
245246074Sgabor			h = t;
246246074Sgabor	if (h != NULL)
247246074Sgabor		*h = '\0';
248246074Sgabor
249246074Sgabor	name->path = fetchname(str, &name->exists, strippath);
250246074Sgabor}
251246074Sgabor
252246074Sgabor/* Determine what kind of diff is in the remaining part of the patch file. */
253246074Sgabor
254246074Sgaborstatic int
255246074Sgaborintuit_diff_type(void)
256246074Sgabor{
257275553Spfg	off_t	this_line = 0, previous_line;
258275553Spfg	off_t	first_command_line = -1;
259246074Sgabor	LINENUM	fcl_line = -1;
260246074Sgabor	bool	last_line_was_command = false, this_is_a_command = false;
261246074Sgabor	bool	stars_last_line = false, stars_this_line = false;
262246074Sgabor	char	*s, *t;
263246074Sgabor	int	indent, retval;
264246074Sgabor	struct file_name names[MAX_FILE];
265246074Sgabor
266246074Sgabor	memset(names, 0, sizeof(names));
267246074Sgabor	ok_to_create_file = false;
268275553Spfg	fseeko(pfp, p_base, SEEK_SET);
269246074Sgabor	p_input_line = p_bline - 1;
270246074Sgabor	for (;;) {
271246074Sgabor		previous_line = this_line;
272246074Sgabor		last_line_was_command = this_is_a_command;
273246074Sgabor		stars_last_line = stars_this_line;
274275553Spfg		this_line = ftello(pfp);
275246074Sgabor		indent = 0;
276246074Sgabor		p_input_line++;
277246074Sgabor		if (pgets(false) == 0) {
278275553Spfg			if (first_command_line >= 0) {
279246074Sgabor				/* nothing but deletes!? */
280246074Sgabor				p_start = first_command_line;
281246074Sgabor				p_sline = fcl_line;
282246074Sgabor				retval = ED_DIFF;
283246074Sgabor				goto scan_exit;
284246074Sgabor			} else {
285246074Sgabor				p_start = this_line;
286246074Sgabor				p_sline = p_input_line;
287246074Sgabor				retval = 0;
288246074Sgabor				goto scan_exit;
289246074Sgabor			}
290246074Sgabor		}
291246074Sgabor		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
292246074Sgabor			if (*s == '\t')
293246074Sgabor				indent += 8 - (indent % 8);
294246074Sgabor			else
295246074Sgabor				indent++;
296246074Sgabor		}
297246074Sgabor		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
298246074Sgabor			;
299246074Sgabor		this_is_a_command = (isdigit((unsigned char)*s) &&
300246074Sgabor		    (*t == 'd' || *t == 'c' || *t == 'a'));
301275553Spfg		if (first_command_line < 0 && this_is_a_command) {
302246074Sgabor			first_command_line = this_line;
303246074Sgabor			fcl_line = p_input_line;
304246074Sgabor			p_indent = indent;	/* assume this for now */
305246074Sgabor		}
306246074Sgabor		if (!stars_last_line && strnEQ(s, "*** ", 4))
307246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
308246074Sgabor			    &names[OLD_FILE].exists, strippath);
309246074Sgabor		else if (strnEQ(s, "--- ", 4))
310246074Sgabor			names[NEW_FILE].path = fetchname(s + 4,
311246074Sgabor			    &names[NEW_FILE].exists, strippath);
312246074Sgabor		else if (strnEQ(s, "+++ ", 4))
313246074Sgabor			/* pretend it is the old name */
314246074Sgabor			names[OLD_FILE].path = fetchname(s + 4,
315246074Sgabor			    &names[OLD_FILE].exists, strippath);
316246074Sgabor		else if (strnEQ(s, "Index:", 6))
317246074Sgabor			names[INDEX_FILE].path = fetchname(s + 6,
318246074Sgabor			    &names[INDEX_FILE].exists, strippath);
319246074Sgabor		else if (strnEQ(s, "Prereq:", 7)) {
320246074Sgabor			for (t = s + 7; isspace((unsigned char)*t); t++)
321246074Sgabor				;
322276218Spfg			revision = xstrdup(t);
323275582Spfg			for (t = revision;
324275582Spfg			     *t && !isspace((unsigned char)*t); t++)
325246074Sgabor				;
326246074Sgabor			*t = '\0';
327246074Sgabor			if (*revision == '\0') {
328246074Sgabor				free(revision);
329246074Sgabor				revision = NULL;
330246074Sgabor			}
331246074Sgabor		} else if (strnEQ(s, "==== ", 5)) {
332246074Sgabor			/* Perforce-style diffs. */
333246074Sgabor			if ((t = strstr(s + 5, " - ")) != NULL)
334246074Sgabor				p4_fetchname(&names[NEW_FILE], t + 3);
335246074Sgabor			p4_fetchname(&names[OLD_FILE], s + 5);
336246074Sgabor		}
337246074Sgabor		if ((!diff_type || diff_type == ED_DIFF) &&
338275553Spfg		    first_command_line >= 0 &&
339246074Sgabor		    strEQ(s, ".\n")) {
340246074Sgabor			p_indent = indent;
341246074Sgabor			p_start = first_command_line;
342246074Sgabor			p_sline = fcl_line;
343246074Sgabor			retval = ED_DIFF;
344246074Sgabor			goto scan_exit;
345246074Sgabor		}
346246074Sgabor		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
347246074Sgabor			if (strnEQ(s + 4, "0,0", 3))
348246074Sgabor				ok_to_create_file = true;
349246074Sgabor			p_indent = indent;
350246074Sgabor			p_start = this_line;
351246074Sgabor			p_sline = p_input_line;
352246074Sgabor			retval = UNI_DIFF;
353246074Sgabor			goto scan_exit;
354246074Sgabor		}
355246074Sgabor		stars_this_line = strnEQ(s, "********", 8);
356246074Sgabor		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
357246074Sgabor		    strnEQ(s, "*** ", 4)) {
358275612Spfg			if (strtolinenum(s + 4, &s) == 0)
359246074Sgabor				ok_to_create_file = true;
360246074Sgabor			/*
361246074Sgabor			 * If this is a new context diff the character just
362275553Spfg			 * at the end of the line is a '*'.
363246074Sgabor			 */
364275553Spfg			while (*s && *s != '\n')
365246074Sgabor				s++;
366246074Sgabor			p_indent = indent;
367246074Sgabor			p_start = previous_line;
368246074Sgabor			p_sline = p_input_line - 1;
369246074Sgabor			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
370246074Sgabor			goto scan_exit;
371246074Sgabor		}
372246074Sgabor		if ((!diff_type || diff_type == NORMAL_DIFF) &&
373246074Sgabor		    last_line_was_command &&
374246074Sgabor		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
375246074Sgabor			p_start = previous_line;
376246074Sgabor			p_sline = p_input_line - 1;
377246074Sgabor			p_indent = indent;
378246074Sgabor			retval = NORMAL_DIFF;
379246074Sgabor			goto scan_exit;
380246074Sgabor		}
381246074Sgabor	}
382246074Sgaborscan_exit:
383246074Sgabor	if (retval == UNI_DIFF) {
384246074Sgabor		/* unswap old and new */
385246074Sgabor		struct file_name tmp = names[OLD_FILE];
386246074Sgabor		names[OLD_FILE] = names[NEW_FILE];
387246074Sgabor		names[NEW_FILE] = tmp;
388246074Sgabor	}
389246074Sgabor	if (filearg[0] == NULL) {
390246074Sgabor		if (posix)
391246074Sgabor			filearg[0] = posix_name(names, ok_to_create_file);
392246074Sgabor		else {
393246074Sgabor			/* Ignore the Index: name for context diffs, like GNU */
394246074Sgabor			if (names[OLD_FILE].path != NULL ||
395246074Sgabor			    names[NEW_FILE].path != NULL) {
396246074Sgabor				free(names[INDEX_FILE].path);
397246074Sgabor				names[INDEX_FILE].path = NULL;
398246074Sgabor			}
399246074Sgabor			filearg[0] = best_name(names, ok_to_create_file);
400246074Sgabor		}
401246074Sgabor	}
402246074Sgabor
403246074Sgabor	free(bestguess);
404246074Sgabor	bestguess = NULL;
405246074Sgabor	if (filearg[0] != NULL)
406276218Spfg		bestguess = xstrdup(filearg[0]);
407246074Sgabor	else if (!ok_to_create_file) {
408246074Sgabor		/*
409246074Sgabor		 * We don't want to create a new file but we need a
410246074Sgabor		 * filename to set bestguess.  Avoid setting filearg[0]
411246074Sgabor		 * so the file is not created automatically.
412246074Sgabor		 */
413246074Sgabor		if (posix)
414246074Sgabor			bestguess = posix_name(names, true);
415246074Sgabor		else
416246074Sgabor			bestguess = best_name(names, true);
417246074Sgabor	}
418246074Sgabor	free(names[OLD_FILE].path);
419246074Sgabor	free(names[NEW_FILE].path);
420246074Sgabor	free(names[INDEX_FILE].path);
421246074Sgabor	return retval;
422246074Sgabor}
423246074Sgabor
424246074Sgabor/*
425246074Sgabor * Remember where this patch ends so we know where to start up again.
426246074Sgabor */
427246074Sgaborstatic void
428275553Spfgnext_intuit_at(off_t file_pos, LINENUM file_line)
429246074Sgabor{
430246074Sgabor	p_base = file_pos;
431246074Sgabor	p_bline = file_line;
432246074Sgabor}
433246074Sgabor
434246074Sgabor/*
435275553Spfg * Basically a verbose fseeko() to the actual diff listing.
436246074Sgabor */
437246074Sgaborstatic void
438275553Spfgskip_to(off_t file_pos, LINENUM file_line)
439246074Sgabor{
440246074Sgabor	size_t	len;
441246074Sgabor
442246074Sgabor	if (p_base > file_pos)
443275553Spfg		fatal("Internal error: seek %lld>%lld\n",
444275553Spfg		   (long long)p_base, (long long)file_pos);
445246074Sgabor	if (verbose && p_base < file_pos) {
446275553Spfg		fseeko(pfp, p_base, SEEK_SET);
447246074Sgabor		say("The text leading up to this was:\n--------------------------\n");
448275553Spfg		while (ftello(pfp) < file_pos) {
449246074Sgabor			len = pgets(false);
450246074Sgabor			if (len == 0)
451246074Sgabor				fatal("Unexpected end of file\n");
452246074Sgabor			say("|%s", buf);
453246074Sgabor		}
454246074Sgabor		say("--------------------------\n");
455246074Sgabor	} else
456275553Spfg		fseeko(pfp, file_pos, SEEK_SET);
457246074Sgabor	p_input_line = file_line - 1;
458246074Sgabor}
459246074Sgabor
460246074Sgabor/* Make this a function for better debugging.  */
461246074Sgaborstatic void
462246074Sgabormalformed(void)
463246074Sgabor{
464246074Sgabor	fatal("malformed patch at line %ld: %s", p_input_line, buf);
465246074Sgabor	/* about as informative as "Syntax error" in C */
466246074Sgabor}
467246074Sgabor
468246074Sgabor/*
469246074Sgabor * True if the line has been discarded (i.e. it is a line saying
470246074Sgabor *  "\ No newline at end of file".)
471246074Sgabor */
472246074Sgaborstatic bool
473246074Sgaborremove_special_line(void)
474246074Sgabor{
475246074Sgabor	int	c;
476246074Sgabor
477246074Sgabor	c = fgetc(pfp);
478246074Sgabor	if (c == '\\') {
479246074Sgabor		do {
480246074Sgabor			c = fgetc(pfp);
481246074Sgabor		} while (c != EOF && c != '\n');
482246074Sgabor
483246074Sgabor		return true;
484246074Sgabor	}
485246074Sgabor	if (c != EOF)
486275553Spfg		fseeko(pfp, -1, SEEK_CUR);
487246074Sgabor
488246074Sgabor	return false;
489246074Sgabor}
490246074Sgabor
491246074Sgabor/*
492246074Sgabor * True if there is more of the current diff listing to process.
493246074Sgabor */
494246074Sgaborbool
495246074Sgaboranother_hunk(void)
496246074Sgabor{
497275553Spfg	off_t	line_beginning;			/* file pos of the current line */
498246074Sgabor	LINENUM	repl_beginning;			/* index of --- line */
499246074Sgabor	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
500246074Sgabor	LINENUM	fillsrc;			/* index of first line to copy */
501246074Sgabor	LINENUM	filldst;			/* index of first missing line */
502289677Seadler	bool	ptrn_spaces_eaten;		/* ptrn was slightly malformed */
503246074Sgabor	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
504246074Sgabor	bool	repl_missing;			/* we are now backtracking */
505275553Spfg	off_t	repl_backtrack_position;	/* file pos of first repl line */
506246074Sgabor	LINENUM	repl_patch_line;		/* input line number for same */
507246074Sgabor	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
508246074Sgabor	char	*s;
509246074Sgabor	size_t	len;
510246074Sgabor	int	context = 0;
511246074Sgabor
512246074Sgabor	while (p_end >= 0) {
513246074Sgabor		if (p_end == p_efake)
514246074Sgabor			p_end = p_bfake;	/* don't free twice */
515246074Sgabor		else
516246074Sgabor			free(p_line[p_end]);
517246074Sgabor		p_end--;
518246074Sgabor	}
519246074Sgabor	p_efake = -1;
520246074Sgabor
521246074Sgabor	p_max = hunkmax;	/* gets reduced when --- found */
522246074Sgabor	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
523275553Spfg		line_beginning = ftello(pfp);
524246074Sgabor		repl_beginning = 0;
525246074Sgabor		fillcnt = 0;
526246074Sgabor		fillsrc = 0;
527246074Sgabor		filldst = 0;
528246074Sgabor		ptrn_spaces_eaten = false;
529246074Sgabor		repl_could_be_missing = true;
530246074Sgabor		repl_missing = false;
531246074Sgabor		repl_backtrack_position = 0;
532246074Sgabor		repl_patch_line = 0;
533246074Sgabor		ptrn_copiable = 0;
534246074Sgabor
535246074Sgabor		len = pgets(true);
536246074Sgabor		p_input_line++;
537246074Sgabor		if (len == 0 || strnNE(buf, "********", 8)) {
538246074Sgabor			next_intuit_at(line_beginning, p_input_line);
539246074Sgabor			return false;
540246074Sgabor		}
541246074Sgabor		p_context = 100;
542246074Sgabor		p_hunk_beg = p_input_line + 1;
543246074Sgabor		while (p_end < p_max) {
544275553Spfg			line_beginning = ftello(pfp);
545246074Sgabor			len = pgets(true);
546246074Sgabor			p_input_line++;
547246074Sgabor			if (len == 0) {
548246074Sgabor				if (p_max - p_end < 4) {
549246074Sgabor					/* assume blank lines got chopped */
550246074Sgabor					strlcpy(buf, "  \n", buf_size);
551246074Sgabor				} else {
552246074Sgabor					if (repl_beginning && repl_could_be_missing) {
553246074Sgabor						repl_missing = true;
554246074Sgabor						goto hunk_done;
555246074Sgabor					}
556246074Sgabor					fatal("unexpected end of file in patch\n");
557246074Sgabor				}
558246074Sgabor			}
559246074Sgabor			p_end++;
560246074Sgabor			if (p_end >= hunkmax)
561246074Sgabor				fatal("Internal error: hunk larger than hunk "
562246074Sgabor				    "buffer size");
563246074Sgabor			p_char[p_end] = *buf;
564246074Sgabor			p_line[p_end] = NULL;
565246074Sgabor			switch (*buf) {
566246074Sgabor			case '*':
567246074Sgabor				if (strnEQ(buf, "********", 8)) {
568246074Sgabor					if (repl_beginning && repl_could_be_missing) {
569246074Sgabor						repl_missing = true;
570246074Sgabor						goto hunk_done;
571246074Sgabor					} else
572246074Sgabor						fatal("unexpected end of hunk "
573246074Sgabor						    "at line %ld\n",
574246074Sgabor						    p_input_line);
575246074Sgabor				}
576246074Sgabor				if (p_end != 0) {
577246074Sgabor					if (repl_beginning && repl_could_be_missing) {
578246074Sgabor						repl_missing = true;
579246074Sgabor						goto hunk_done;
580246074Sgabor					}
581246074Sgabor					fatal("unexpected *** at line %ld: %s",
582246074Sgabor					    p_input_line, buf);
583246074Sgabor				}
584246074Sgabor				context = 0;
585246074Sgabor				p_line[p_end] = savestr(buf);
586246074Sgabor				if (out_of_mem) {
587246074Sgabor					p_end--;
588246074Sgabor					return false;
589246074Sgabor				}
590275582Spfg				for (s = buf;
591275582Spfg				     *s && !isdigit((unsigned char)*s); s++)
592246074Sgabor					;
593246074Sgabor				if (!*s)
594246074Sgabor					malformed();
595246074Sgabor				if (strnEQ(s, "0,0", 3))
596246074Sgabor					memmove(s, s + 2, strlen(s + 2) + 1);
597275612Spfg				p_first = strtolinenum(s, &s);
598246074Sgabor				if (*s == ',') {
599275582Spfg					for (;
600275582Spfg					     *s && !isdigit((unsigned char)*s); s++)
601246074Sgabor						;
602246074Sgabor					if (!*s)
603246074Sgabor						malformed();
604275612Spfg					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
605275612Spfg					if (p_ptrn_lines < 0)
606275612Spfg						malformed();
607246074Sgabor				} else if (p_first)
608246074Sgabor					p_ptrn_lines = 1;
609246074Sgabor				else {
610246074Sgabor					p_ptrn_lines = 0;
611246074Sgabor					p_first = 1;
612246074Sgabor				}
613275612Spfg				if (p_first >= LINENUM_MAX - p_ptrn_lines ||
614275612Spfg				    p_ptrn_lines >= LINENUM_MAX - 6)
615275612Spfg					malformed();
616246074Sgabor
617246074Sgabor				/* we need this much at least */
618246074Sgabor				p_max = p_ptrn_lines + 6;
619246074Sgabor				while (p_max >= hunkmax)
620246074Sgabor					grow_hunkmax();
621246074Sgabor				p_max = hunkmax;
622246074Sgabor				break;
623246074Sgabor			case '-':
624246074Sgabor				if (buf[1] == '-') {
625246074Sgabor					if (repl_beginning ||
626246074Sgabor					    (p_end != p_ptrn_lines + 1 +
627246074Sgabor					    (p_char[p_end - 1] == '\n'))) {
628246074Sgabor						if (p_end == 1) {
629246074Sgabor							/*
630246074Sgabor							 * `old' lines were omitted;
631246074Sgabor							 * set up to fill them in
632246074Sgabor							 * from 'new' context lines.
633246074Sgabor							 */
634246074Sgabor							p_end = p_ptrn_lines + 1;
635246074Sgabor							fillsrc = p_end + 1;
636246074Sgabor							filldst = 1;
637246074Sgabor							fillcnt = p_ptrn_lines;
638246074Sgabor						} else {
639246074Sgabor							if (repl_beginning) {
640246074Sgabor								if (repl_could_be_missing) {
641246074Sgabor									repl_missing = true;
642246074Sgabor									goto hunk_done;
643246074Sgabor								}
644246074Sgabor								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
645246074Sgabor								    p_input_line, p_hunk_beg + repl_beginning);
646246074Sgabor							} else {
647246074Sgabor								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
648246074Sgabor								    (p_end <= p_ptrn_lines
649246074Sgabor								    ? "Premature"
650246074Sgabor								    : "Overdue"),
651246074Sgabor								    p_input_line, p_hunk_beg);
652246074Sgabor							}
653246074Sgabor						}
654246074Sgabor					}
655246074Sgabor					repl_beginning = p_end;
656275553Spfg					repl_backtrack_position = ftello(pfp);
657246074Sgabor					repl_patch_line = p_input_line;
658246074Sgabor					p_line[p_end] = savestr(buf);
659246074Sgabor					if (out_of_mem) {
660246074Sgabor						p_end--;
661246074Sgabor						return false;
662246074Sgabor					}
663246074Sgabor					p_char[p_end] = '=';
664246074Sgabor					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
665246074Sgabor						;
666246074Sgabor					if (!*s)
667246074Sgabor						malformed();
668275612Spfg					p_newfirst = strtolinenum(s, &s);
669246074Sgabor					if (*s == ',') {
670246074Sgabor						for (; *s && !isdigit((unsigned char)*s); s++)
671246074Sgabor							;
672246074Sgabor						if (!*s)
673246074Sgabor							malformed();
674275612Spfg						p_repl_lines = strtolinenum(s, &s) -
675246074Sgabor						    p_newfirst + 1;
676275612Spfg						if (p_repl_lines < 0)
677275612Spfg							malformed();
678246074Sgabor					} else if (p_newfirst)
679246074Sgabor						p_repl_lines = 1;
680246074Sgabor					else {
681246074Sgabor						p_repl_lines = 0;
682246074Sgabor						p_newfirst = 1;
683246074Sgabor					}
684275612Spfg					if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
685275612Spfg					    p_repl_lines >= LINENUM_MAX - p_end)
686275612Spfg						malformed();
687246074Sgabor					p_max = p_repl_lines + p_end;
688246074Sgabor					if (p_max > MAXHUNKSIZE)
689246074Sgabor						fatal("hunk too large (%ld lines) at line %ld: %s",
690246074Sgabor						    p_max, p_input_line, buf);
691246074Sgabor					while (p_max >= hunkmax)
692246074Sgabor						grow_hunkmax();
693246074Sgabor					if (p_repl_lines != ptrn_copiable &&
694246074Sgabor					    (p_context != 0 || p_repl_lines != 1))
695246074Sgabor						repl_could_be_missing = false;
696246074Sgabor					break;
697246074Sgabor				}
698246074Sgabor				goto change_line;
699246074Sgabor			case '+':
700246074Sgabor			case '!':
701246074Sgabor				repl_could_be_missing = false;
702246074Sgabor		change_line:
703246074Sgabor				if (buf[1] == '\n' && canonicalize)
704246074Sgabor					strlcpy(buf + 1, " \n", buf_size - 1);
705275582Spfg				if (!isspace((unsigned char)buf[1]) &&
706275582Spfg				    buf[1] != '>' && buf[1] != '<' &&
707246074Sgabor				    repl_beginning && repl_could_be_missing) {
708246074Sgabor					repl_missing = true;
709246074Sgabor					goto hunk_done;
710246074Sgabor				}
711246074Sgabor				if (context >= 0) {
712246074Sgabor					if (context < p_context)
713246074Sgabor						p_context = context;
714246074Sgabor					context = -1000;
715246074Sgabor				}
716246074Sgabor				p_line[p_end] = savestr(buf + 2);
717246074Sgabor				if (out_of_mem) {
718246074Sgabor					p_end--;
719246074Sgabor					return false;
720246074Sgabor				}
721246074Sgabor				if (p_end == p_ptrn_lines) {
722246074Sgabor					if (remove_special_line()) {
723246074Sgabor						int	l;
724246074Sgabor
725246074Sgabor						l = strlen(p_line[p_end]) - 1;
726246074Sgabor						(p_line[p_end])[l] = 0;
727246074Sgabor					}
728246074Sgabor				}
729246074Sgabor				break;
730246074Sgabor			case '\t':
731246074Sgabor			case '\n':	/* assume the 2 spaces got eaten */
732246074Sgabor				if (repl_beginning && repl_could_be_missing &&
733246074Sgabor				    (!ptrn_spaces_eaten ||
734246074Sgabor				    diff_type == NEW_CONTEXT_DIFF)) {
735246074Sgabor					repl_missing = true;
736246074Sgabor					goto hunk_done;
737246074Sgabor				}
738246074Sgabor				p_line[p_end] = savestr(buf);
739246074Sgabor				if (out_of_mem) {
740246074Sgabor					p_end--;
741246074Sgabor					return false;
742246074Sgabor				}
743246074Sgabor				if (p_end != p_ptrn_lines + 1) {
744246074Sgabor					ptrn_spaces_eaten |= (repl_beginning != 0);
745246074Sgabor					context++;
746246074Sgabor					if (!repl_beginning)
747246074Sgabor						ptrn_copiable++;
748246074Sgabor					p_char[p_end] = ' ';
749246074Sgabor				}
750246074Sgabor				break;
751246074Sgabor			case ' ':
752246074Sgabor				if (!isspace((unsigned char)buf[1]) &&
753246074Sgabor				    repl_beginning && repl_could_be_missing) {
754246074Sgabor					repl_missing = true;
755246074Sgabor					goto hunk_done;
756246074Sgabor				}
757246074Sgabor				context++;
758246074Sgabor				if (!repl_beginning)
759246074Sgabor					ptrn_copiable++;
760246074Sgabor				p_line[p_end] = savestr(buf + 2);
761246074Sgabor				if (out_of_mem) {
762246074Sgabor					p_end--;
763246074Sgabor					return false;
764246074Sgabor				}
765246074Sgabor				break;
766246074Sgabor			default:
767246074Sgabor				if (repl_beginning && repl_could_be_missing) {
768246074Sgabor					repl_missing = true;
769246074Sgabor					goto hunk_done;
770246074Sgabor				}
771246074Sgabor				malformed();
772246074Sgabor			}
773246074Sgabor			/* set up p_len for strncmp() so we don't have to */
774246074Sgabor			/* assume null termination */
775246074Sgabor			if (p_line[p_end])
776246074Sgabor				p_len[p_end] = strlen(p_line[p_end]);
777246074Sgabor			else
778246074Sgabor				p_len[p_end] = 0;
779246074Sgabor		}
780246074Sgabor
781246074Sgaborhunk_done:
782246074Sgabor		if (p_end >= 0 && !repl_beginning)
783246074Sgabor			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
784246074Sgabor
785246074Sgabor		if (repl_missing) {
786246074Sgabor
787246074Sgabor			/* reset state back to just after --- */
788246074Sgabor			p_input_line = repl_patch_line;
789246074Sgabor			for (p_end--; p_end > repl_beginning; p_end--)
790246074Sgabor				free(p_line[p_end]);
791275553Spfg			fseeko(pfp, repl_backtrack_position, SEEK_SET);
792246074Sgabor
793246074Sgabor			/* redundant 'new' context lines were omitted - set */
794246074Sgabor			/* up to fill them in from the old file context */
795246074Sgabor			if (!p_context && p_repl_lines == 1) {
796246074Sgabor				p_repl_lines = 0;
797246074Sgabor				p_max--;
798246074Sgabor			}
799246074Sgabor			fillsrc = 1;
800246074Sgabor			filldst = repl_beginning + 1;
801246074Sgabor			fillcnt = p_repl_lines;
802246074Sgabor			p_end = p_max;
803246074Sgabor		} else if (!p_context && fillcnt == 1) {
804246074Sgabor			/* the first hunk was a null hunk with no context */
805246074Sgabor			/* and we were expecting one line -- fix it up. */
806246074Sgabor			while (filldst < p_end) {
807246074Sgabor				p_line[filldst] = p_line[filldst + 1];
808246074Sgabor				p_char[filldst] = p_char[filldst + 1];
809246074Sgabor				p_len[filldst] = p_len[filldst + 1];
810246074Sgabor				filldst++;
811246074Sgabor			}
812246074Sgabor#if 0
813246074Sgabor			repl_beginning--;	/* this doesn't need to be fixed */
814246074Sgabor#endif
815246074Sgabor			p_end--;
816246074Sgabor			p_first++;	/* do append rather than insert */
817246074Sgabor			fillcnt = 0;
818246074Sgabor			p_ptrn_lines = 0;
819246074Sgabor		}
820246074Sgabor		if (diff_type == CONTEXT_DIFF &&
821246074Sgabor		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
822246074Sgabor			if (verbose)
823246074Sgabor				say("%s\n%s\n%s\n",
824246074Sgabor				    "(Fascinating--this is really a new-style context diff but without",
825246074Sgabor				    "the telltale extra asterisks on the *** line that usually indicate",
826246074Sgabor				    "the new style...)");
827246074Sgabor			diff_type = NEW_CONTEXT_DIFF;
828246074Sgabor		}
829246074Sgabor		/* if there were omitted context lines, fill them in now */
830246074Sgabor		if (fillcnt) {
831246074Sgabor			p_bfake = filldst;	/* remember where not to free() */
832246074Sgabor			p_efake = filldst + fillcnt - 1;
833246074Sgabor			while (fillcnt-- > 0) {
834246074Sgabor				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
835246074Sgabor					fillsrc++;
836246074Sgabor				if (fillsrc > p_end)
837246074Sgabor					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
838246074Sgabor					    p_hunk_beg);
839246074Sgabor				p_line[filldst] = p_line[fillsrc];
840246074Sgabor				p_char[filldst] = p_char[fillsrc];
841246074Sgabor				p_len[filldst] = p_len[fillsrc];
842246074Sgabor				fillsrc++;
843246074Sgabor				filldst++;
844246074Sgabor			}
845246074Sgabor			while (fillsrc <= p_end && fillsrc != repl_beginning &&
846246074Sgabor			    p_char[fillsrc] != ' ')
847246074Sgabor				fillsrc++;
848246074Sgabor#ifdef DEBUGGING
849246074Sgabor			if (debug & 64)
850246074Sgabor				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
851246074Sgabor				fillsrc, filldst, repl_beginning, p_end + 1);
852246074Sgabor#endif
853246074Sgabor			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
854246074Sgabor				malformed();
855246074Sgabor			if (filldst != p_end + 1 && filldst != repl_beginning)
856246074Sgabor				malformed();
857246074Sgabor		}
858246074Sgabor		if (p_line[p_end] != NULL) {
859246074Sgabor			if (remove_special_line()) {
860246074Sgabor				p_len[p_end] -= 1;
861246074Sgabor				(p_line[p_end])[p_len[p_end]] = 0;
862246074Sgabor			}
863246074Sgabor		}
864246074Sgabor	} else if (diff_type == UNI_DIFF) {
865246074Sgabor		LINENUM	fillold;	/* index of old lines */
866246074Sgabor		LINENUM	fillnew;	/* index of new lines */
867246074Sgabor		char	ch;
868246074Sgabor
869275553Spfg		line_beginning = ftello(pfp); /* file pos of the current line */
870246074Sgabor		len = pgets(true);
871246074Sgabor		p_input_line++;
872246074Sgabor		if (len == 0 || strnNE(buf, "@@ -", 4)) {
873246074Sgabor			next_intuit_at(line_beginning, p_input_line);
874246074Sgabor			return false;
875246074Sgabor		}
876246074Sgabor		s = buf + 4;
877246074Sgabor		if (!*s)
878246074Sgabor			malformed();
879275612Spfg		p_first = strtolinenum(s, &s);
880246074Sgabor		if (*s == ',') {
881275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s);
882246074Sgabor		} else
883246074Sgabor			p_ptrn_lines = 1;
884246074Sgabor		if (*s == ' ')
885246074Sgabor			s++;
886246074Sgabor		if (*s != '+' || !*++s)
887246074Sgabor			malformed();
888275612Spfg		p_newfirst = strtolinenum(s, &s);
889246074Sgabor		if (*s == ',') {
890275612Spfg			p_repl_lines = strtolinenum(s + 1, &s);
891246074Sgabor		} else
892246074Sgabor			p_repl_lines = 1;
893246074Sgabor		if (*s == ' ')
894246074Sgabor			s++;
895246074Sgabor		if (*s != '@')
896246074Sgabor			malformed();
897275612Spfg		if (p_first >= LINENUM_MAX - p_ptrn_lines ||
898275612Spfg		    p_newfirst > LINENUM_MAX - p_repl_lines ||
899275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
900275612Spfg			malformed();
901246074Sgabor		if (!p_ptrn_lines)
902246074Sgabor			p_first++;	/* do append rather than insert */
903246074Sgabor		p_max = p_ptrn_lines + p_repl_lines + 1;
904246074Sgabor		while (p_max >= hunkmax)
905246074Sgabor			grow_hunkmax();
906246074Sgabor		fillold = 1;
907246074Sgabor		fillnew = fillold + p_ptrn_lines;
908246074Sgabor		p_end = fillnew + p_repl_lines;
909246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
910246074Sgabor		    p_first + p_ptrn_lines - 1);
911246074Sgabor		p_line[0] = savestr(buf);
912246074Sgabor		if (out_of_mem) {
913246074Sgabor			p_end = -1;
914246074Sgabor			return false;
915246074Sgabor		}
916246074Sgabor		p_char[0] = '*';
917246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
918246074Sgabor		    p_newfirst + p_repl_lines - 1);
919246074Sgabor		p_line[fillnew] = savestr(buf);
920246074Sgabor		if (out_of_mem) {
921246074Sgabor			p_end = 0;
922246074Sgabor			return false;
923246074Sgabor		}
924246074Sgabor		p_char[fillnew++] = '=';
925246074Sgabor		p_context = 100;
926246074Sgabor		context = 0;
927246074Sgabor		p_hunk_beg = p_input_line + 1;
928246074Sgabor		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
929275553Spfg			line_beginning = ftello(pfp);
930246074Sgabor			len = pgets(true);
931246074Sgabor			p_input_line++;
932246074Sgabor			if (len == 0) {
933246074Sgabor				if (p_max - fillnew < 3) {
934246074Sgabor					/* assume blank lines got chopped */
935246074Sgabor					strlcpy(buf, " \n", buf_size);
936246074Sgabor				} else {
937246074Sgabor					fatal("unexpected end of file in patch\n");
938246074Sgabor				}
939246074Sgabor			}
940246074Sgabor			if (*buf == '\t' || *buf == '\n') {
941246074Sgabor				ch = ' ';	/* assume the space got eaten */
942246074Sgabor				s = savestr(buf);
943246074Sgabor			} else {
944246074Sgabor				ch = *buf;
945246074Sgabor				s = savestr(buf + 1);
946246074Sgabor			}
947246074Sgabor			if (out_of_mem) {
948246074Sgabor				while (--fillnew > p_ptrn_lines)
949246074Sgabor					free(p_line[fillnew]);
950246074Sgabor				p_end = fillold - 1;
951246074Sgabor				return false;
952246074Sgabor			}
953246074Sgabor			switch (ch) {
954246074Sgabor			case '-':
955246074Sgabor				if (fillold > p_ptrn_lines) {
956246074Sgabor					free(s);
957246074Sgabor					p_end = fillnew - 1;
958246074Sgabor					malformed();
959246074Sgabor				}
960246074Sgabor				p_char[fillold] = ch;
961246074Sgabor				p_line[fillold] = s;
962246074Sgabor				p_len[fillold++] = strlen(s);
963246074Sgabor				if (fillold > p_ptrn_lines) {
964246074Sgabor					if (remove_special_line()) {
965246074Sgabor						p_len[fillold - 1] -= 1;
966246074Sgabor						s[p_len[fillold - 1]] = 0;
967246074Sgabor					}
968246074Sgabor				}
969246074Sgabor				break;
970246074Sgabor			case '=':
971246074Sgabor				ch = ' ';
972246074Sgabor				/* FALL THROUGH */
973246074Sgabor			case ' ':
974246074Sgabor				if (fillold > p_ptrn_lines) {
975246074Sgabor					free(s);
976246074Sgabor					while (--fillnew > p_ptrn_lines)
977246074Sgabor						free(p_line[fillnew]);
978246074Sgabor					p_end = fillold - 1;
979246074Sgabor					malformed();
980246074Sgabor				}
981246074Sgabor				context++;
982246074Sgabor				p_char[fillold] = ch;
983246074Sgabor				p_line[fillold] = s;
984246074Sgabor				p_len[fillold++] = strlen(s);
985246074Sgabor				s = savestr(s);
986246074Sgabor				if (out_of_mem) {
987246074Sgabor					while (--fillnew > p_ptrn_lines)
988246074Sgabor						free(p_line[fillnew]);
989246074Sgabor					p_end = fillold - 1;
990246074Sgabor					return false;
991246074Sgabor				}
992246074Sgabor				if (fillold > p_ptrn_lines) {
993246074Sgabor					if (remove_special_line()) {
994246074Sgabor						p_len[fillold - 1] -= 1;
995246074Sgabor						s[p_len[fillold - 1]] = 0;
996246074Sgabor					}
997246074Sgabor				}
998246074Sgabor				/* FALL THROUGH */
999246074Sgabor			case '+':
1000246074Sgabor				if (fillnew > p_end) {
1001246074Sgabor					free(s);
1002246074Sgabor					while (--fillnew > p_ptrn_lines)
1003246074Sgabor						free(p_line[fillnew]);
1004246074Sgabor					p_end = fillold - 1;
1005246074Sgabor					malformed();
1006246074Sgabor				}
1007246074Sgabor				p_char[fillnew] = ch;
1008246074Sgabor				p_line[fillnew] = s;
1009246074Sgabor				p_len[fillnew++] = strlen(s);
1010246074Sgabor				if (fillold > p_ptrn_lines) {
1011246074Sgabor					if (remove_special_line()) {
1012246074Sgabor						p_len[fillnew - 1] -= 1;
1013246074Sgabor						s[p_len[fillnew - 1]] = 0;
1014246074Sgabor					}
1015246074Sgabor				}
1016246074Sgabor				break;
1017246074Sgabor			default:
1018246074Sgabor				p_end = fillnew;
1019246074Sgabor				malformed();
1020246074Sgabor			}
1021246074Sgabor			if (ch != ' ' && context > 0) {
1022246074Sgabor				if (context < p_context)
1023246074Sgabor					p_context = context;
1024246074Sgabor				context = -1000;
1025246074Sgabor			}
1026246074Sgabor		}		/* while */
1027246074Sgabor	} else {		/* normal diff--fake it up */
1028246074Sgabor		char	hunk_type;
1029246074Sgabor		int	i;
1030246074Sgabor		LINENUM	min, max;
1031246074Sgabor
1032275553Spfg		line_beginning = ftello(pfp);
1033246074Sgabor		p_context = 0;
1034246074Sgabor		len = pgets(true);
1035246074Sgabor		p_input_line++;
1036246074Sgabor		if (len == 0 || !isdigit((unsigned char)*buf)) {
1037246074Sgabor			next_intuit_at(line_beginning, p_input_line);
1038246074Sgabor			return false;
1039246074Sgabor		}
1040275612Spfg		p_first = strtolinenum(buf, &s);
1041246074Sgabor		if (*s == ',') {
1042275612Spfg			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1043275612Spfg			if (p_ptrn_lines < 0)
1044275612Spfg				malformed();
1045246074Sgabor		} else
1046246074Sgabor			p_ptrn_lines = (*s != 'a');
1047246074Sgabor		hunk_type = *s;
1048246074Sgabor		if (hunk_type == 'a')
1049246074Sgabor			p_first++;	/* do append rather than insert */
1050275612Spfg		min = strtolinenum(s + 1, &s);
1051246074Sgabor		if (*s == ',')
1052275612Spfg			max = strtolinenum(s + 1, &s);
1053246074Sgabor		else
1054246074Sgabor			max = min;
1055275612Spfg		if (min < 0 || min > max || max - min == LINENUM_MAX)
1056275612Spfg			malformed();
1057246074Sgabor		if (hunk_type == 'd')
1058246074Sgabor			min++;
1059275612Spfg		p_newfirst = min;
1060275612Spfg		p_repl_lines = max - min + 1;
1061275612Spfg		if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1062275612Spfg		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1063275612Spfg			malformed();
1064275612Spfg		p_end = p_ptrn_lines + p_repl_lines + 1;
1065246074Sgabor		if (p_end > MAXHUNKSIZE)
1066246074Sgabor			fatal("hunk too large (%ld lines) at line %ld: %s",
1067246074Sgabor			    p_end, p_input_line, buf);
1068246074Sgabor		while (p_end >= hunkmax)
1069246074Sgabor			grow_hunkmax();
1070246074Sgabor		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1071246074Sgabor		    p_first + p_ptrn_lines - 1);
1072246074Sgabor		p_line[0] = savestr(buf);
1073246074Sgabor		if (out_of_mem) {
1074246074Sgabor			p_end = -1;
1075246074Sgabor			return false;
1076246074Sgabor		}
1077246074Sgabor		p_char[0] = '*';
1078246074Sgabor		for (i = 1; i <= p_ptrn_lines; i++) {
1079246074Sgabor			len = pgets(true);
1080246074Sgabor			p_input_line++;
1081246074Sgabor			if (len == 0)
1082246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1083246074Sgabor				    p_input_line);
1084246074Sgabor			if (*buf != '<')
1085246074Sgabor				fatal("< expected at line %ld of patch\n",
1086246074Sgabor				    p_input_line);
1087246074Sgabor			p_line[i] = savestr(buf + 2);
1088246074Sgabor			if (out_of_mem) {
1089246074Sgabor				p_end = i - 1;
1090246074Sgabor				return false;
1091246074Sgabor			}
1092246074Sgabor			p_len[i] = strlen(p_line[i]);
1093246074Sgabor			p_char[i] = '-';
1094246074Sgabor		}
1095246074Sgabor
1096246074Sgabor		if (remove_special_line()) {
1097246074Sgabor			p_len[i - 1] -= 1;
1098246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1099246074Sgabor		}
1100246074Sgabor		if (hunk_type == 'c') {
1101246074Sgabor			len = pgets(true);
1102246074Sgabor			p_input_line++;
1103246074Sgabor			if (len == 0)
1104246074Sgabor				fatal("unexpected end of file in patch at line %ld\n",
1105246074Sgabor				    p_input_line);
1106246074Sgabor			if (*buf != '-')
1107246074Sgabor				fatal("--- expected at line %ld of patch\n",
1108246074Sgabor				    p_input_line);
1109246074Sgabor		}
1110246074Sgabor		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1111246074Sgabor		p_line[i] = savestr(buf);
1112246074Sgabor		if (out_of_mem) {
1113246074Sgabor			p_end = i - 1;
1114246074Sgabor			return false;
1115246074Sgabor		}
1116246074Sgabor		p_char[i] = '=';
1117246074Sgabor		for (i++; i <= p_end; i++) {
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			p_line[i] = savestr(buf + 2);
1127246074Sgabor			if (out_of_mem) {
1128246074Sgabor				p_end = i - 1;
1129246074Sgabor				return false;
1130246074Sgabor			}
1131246074Sgabor			p_len[i] = strlen(p_line[i]);
1132246074Sgabor			p_char[i] = '+';
1133246074Sgabor		}
1134246074Sgabor
1135246074Sgabor		if (remove_special_line()) {
1136246074Sgabor			p_len[i - 1] -= 1;
1137246074Sgabor			(p_line[i - 1])[p_len[i - 1]] = 0;
1138246074Sgabor		}
1139246074Sgabor	}
1140246074Sgabor	if (reverse)		/* backwards patch? */
1141246074Sgabor		if (!pch_swap())
1142246074Sgabor			say("Not enough memory to swap next hunk!\n");
1143246074Sgabor#ifdef DEBUGGING
1144246074Sgabor	if (debug & 2) {
1145246074Sgabor		int	i;
1146246074Sgabor		char	special;
1147246074Sgabor
1148246074Sgabor		for (i = 0; i <= p_end; i++) {
1149246074Sgabor			if (i == p_ptrn_lines)
1150246074Sgabor				special = '^';
1151246074Sgabor			else
1152246074Sgabor				special = ' ';
1153246074Sgabor			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1154246074Sgabor			    special, p_line[i]);
1155246074Sgabor			fflush(stderr);
1156246074Sgabor		}
1157246074Sgabor	}
1158246074Sgabor#endif
1159246074Sgabor	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1160246074Sgabor		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1161246074Sgabor	return true;
1162246074Sgabor}
1163246074Sgabor
1164246074Sgabor/*
1165246074Sgabor * Input a line from the patch file.
1166246074Sgabor * Worry about indentation if do_indent is true.
1167246074Sgabor * The line is read directly into the buf global variable which
1168246074Sgabor * is resized if necessary in order to hold the complete line.
1169246074Sgabor * Returns the number of characters read including the terminating
1170246074Sgabor * '\n', if any.
1171246074Sgabor */
1172246074Sgaborsize_t
1173246074Sgaborpgets(bool do_indent)
1174246074Sgabor{
1175246074Sgabor	char *line;
1176246074Sgabor	size_t len;
1177246074Sgabor	int indent = 0, skipped = 0;
1178246074Sgabor
1179246074Sgabor	line = fgetln(pfp, &len);
1180246074Sgabor	if (line != NULL) {
1181246074Sgabor		if (len + 1 > buf_size) {
1182246074Sgabor			while (len + 1 > buf_size)
1183246074Sgabor				buf_size *= 2;
1184246074Sgabor			free(buf);
1185246074Sgabor			buf = malloc(buf_size);
1186246074Sgabor			if (buf == NULL)
1187246074Sgabor				fatal("out of memory\n");
1188246074Sgabor		}
1189246074Sgabor		if (do_indent == 1 && p_indent) {
1190246074Sgabor			for (;
1191246074Sgabor			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1192246074Sgabor			    line++, skipped++) {
1193246074Sgabor				if (*line == '\t')
1194246074Sgabor					indent += 8 - (indent %7);
1195246074Sgabor				else
1196246074Sgabor					indent++;
1197246074Sgabor			}
1198246074Sgabor		}
1199252637Sobrien		memcpy(buf, line, len - skipped);
1200246074Sgabor		buf[len - skipped] = '\0';
1201246074Sgabor	}
1202246074Sgabor	return len;
1203246074Sgabor}
1204246074Sgabor
1205246074Sgabor
1206246074Sgabor/*
1207246074Sgabor * Reverse the old and new portions of the current hunk.
1208246074Sgabor */
1209246074Sgaborbool
1210246074Sgaborpch_swap(void)
1211246074Sgabor{
1212246074Sgabor	char	**tp_line;	/* the text of the hunk */
1213267490Spfg	unsigned short	*tp_len;/* length of each line */
1214246074Sgabor	char	*tp_char;	/* +, -, and ! */
1215246074Sgabor	LINENUM	i;
1216246074Sgabor	LINENUM	n;
1217246074Sgabor	bool	blankline = false;
1218246074Sgabor	char	*s;
1219246074Sgabor
1220246074Sgabor	i = p_first;
1221246074Sgabor	p_first = p_newfirst;
1222246074Sgabor	p_newfirst = i;
1223246074Sgabor
1224246074Sgabor	/* make a scratch copy */
1225246074Sgabor
1226246074Sgabor	tp_line = p_line;
1227246074Sgabor	tp_len = p_len;
1228246074Sgabor	tp_char = p_char;
1229246074Sgabor	p_line = NULL;	/* force set_hunkmax to allocate again */
1230246074Sgabor	p_len = NULL;
1231246074Sgabor	p_char = NULL;
1232246074Sgabor	set_hunkmax();
1233246074Sgabor	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1234246074Sgabor
1235246074Sgabor		free(p_line);
1236246074Sgabor		p_line = tp_line;
1237246074Sgabor		free(p_len);
1238246074Sgabor		p_len = tp_len;
1239246074Sgabor		free(p_char);
1240246074Sgabor		p_char = tp_char;
1241246074Sgabor		return false;	/* not enough memory to swap hunk! */
1242246074Sgabor	}
1243246074Sgabor	/* now turn the new into the old */
1244246074Sgabor
1245246074Sgabor	i = p_ptrn_lines + 1;
1246246074Sgabor	if (tp_char[i] == '\n') {	/* account for possible blank line */
1247246074Sgabor		blankline = true;
1248246074Sgabor		i++;
1249246074Sgabor	}
1250246074Sgabor	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1251246074Sgabor		if (p_efake <= i)
1252246074Sgabor			n = p_end - i + 1;
1253246074Sgabor		else
1254246074Sgabor			n = -i;
1255246074Sgabor		p_efake += n;
1256246074Sgabor		p_bfake += n;
1257246074Sgabor	}
1258246074Sgabor	for (n = 0; i <= p_end; i++, n++) {
1259246074Sgabor		p_line[n] = tp_line[i];
1260246074Sgabor		p_char[n] = tp_char[i];
1261246074Sgabor		if (p_char[n] == '+')
1262246074Sgabor			p_char[n] = '-';
1263246074Sgabor		p_len[n] = tp_len[i];
1264246074Sgabor	}
1265246074Sgabor	if (blankline) {
1266246074Sgabor		i = p_ptrn_lines + 1;
1267246074Sgabor		p_line[n] = tp_line[i];
1268246074Sgabor		p_char[n] = tp_char[i];
1269246074Sgabor		p_len[n] = tp_len[i];
1270246074Sgabor		n++;
1271246074Sgabor	}
1272246074Sgabor	if (p_char[0] != '=')
1273246074Sgabor		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1274246074Sgabor		    p_input_line, p_char[0]);
1275246074Sgabor	p_char[0] = '*';
1276246074Sgabor	for (s = p_line[0]; *s; s++)
1277246074Sgabor		if (*s == '-')
1278246074Sgabor			*s = '*';
1279246074Sgabor
1280246074Sgabor	/* now turn the old into the new */
1281246074Sgabor
1282246074Sgabor	if (p_char[0] != '*')
1283246074Sgabor		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1284246074Sgabor		    p_input_line, p_char[0]);
1285246074Sgabor	tp_char[0] = '=';
1286246074Sgabor	for (s = tp_line[0]; *s; s++)
1287246074Sgabor		if (*s == '*')
1288246074Sgabor			*s = '-';
1289246074Sgabor	for (i = 0; n <= p_end; i++, n++) {
1290246074Sgabor		p_line[n] = tp_line[i];
1291246074Sgabor		p_char[n] = tp_char[i];
1292246074Sgabor		if (p_char[n] == '-')
1293246074Sgabor			p_char[n] = '+';
1294246074Sgabor		p_len[n] = tp_len[i];
1295246074Sgabor	}
1296246074Sgabor
1297246074Sgabor	if (i != p_ptrn_lines + 1)
1298246074Sgabor		fatal("Malformed patch at line %ld: expected %ld lines, "
1299246074Sgabor		    "got %ld\n",
1300246074Sgabor		    p_input_line, p_ptrn_lines + 1, i);
1301246074Sgabor
1302246074Sgabor	i = p_ptrn_lines;
1303246074Sgabor	p_ptrn_lines = p_repl_lines;
1304246074Sgabor	p_repl_lines = i;
1305246074Sgabor
1306246074Sgabor	free(tp_line);
1307246074Sgabor	free(tp_len);
1308246074Sgabor	free(tp_char);
1309246074Sgabor
1310246074Sgabor	return true;
1311246074Sgabor}
1312246074Sgabor
1313246074Sgabor/*
1314246074Sgabor * Return the specified line position in the old file of the old context.
1315246074Sgabor */
1316246074SgaborLINENUM
1317246074Sgaborpch_first(void)
1318246074Sgabor{
1319246074Sgabor	return p_first;
1320246074Sgabor}
1321246074Sgabor
1322246074Sgabor/*
1323246074Sgabor * Return the number of lines of old context.
1324246074Sgabor */
1325246074SgaborLINENUM
1326246074Sgaborpch_ptrn_lines(void)
1327246074Sgabor{
1328246074Sgabor	return p_ptrn_lines;
1329246074Sgabor}
1330246074Sgabor
1331246074Sgabor/*
1332246074Sgabor * Return the probable line position in the new file of the first line.
1333246074Sgabor */
1334246074SgaborLINENUM
1335246074Sgaborpch_newfirst(void)
1336246074Sgabor{
1337246074Sgabor	return p_newfirst;
1338246074Sgabor}
1339246074Sgabor
1340246074Sgabor/*
1341246074Sgabor * Return the number of lines in the replacement text including context.
1342246074Sgabor */
1343246074SgaborLINENUM
1344246074Sgaborpch_repl_lines(void)
1345246074Sgabor{
1346246074Sgabor	return p_repl_lines;
1347246074Sgabor}
1348246074Sgabor
1349246074Sgabor/*
1350246074Sgabor * Return the number of lines in the whole hunk.
1351246074Sgabor */
1352246074SgaborLINENUM
1353246074Sgaborpch_end(void)
1354246074Sgabor{
1355246074Sgabor	return p_end;
1356246074Sgabor}
1357246074Sgabor
1358246074Sgabor/*
1359246074Sgabor * Return the number of context lines before the first changed line.
1360246074Sgabor */
1361246074SgaborLINENUM
1362246074Sgaborpch_context(void)
1363246074Sgabor{
1364246074Sgabor	return p_context;
1365246074Sgabor}
1366246074Sgabor
1367246074Sgabor/*
1368246074Sgabor * Return the length of a particular patch line.
1369246074Sgabor */
1370267490Spfgunsigned short
1371246074Sgaborpch_line_len(LINENUM line)
1372246074Sgabor{
1373246074Sgabor	return p_len[line];
1374246074Sgabor}
1375246074Sgabor
1376246074Sgabor/*
1377246074Sgabor * Return the control character (+, -, *, !, etc) for a patch line.
1378246074Sgabor */
1379246074Sgaborchar
1380246074Sgaborpch_char(LINENUM line)
1381246074Sgabor{
1382246074Sgabor	return p_char[line];
1383246074Sgabor}
1384246074Sgabor
1385246074Sgabor/*
1386246074Sgabor * Return a pointer to a particular patch line.
1387246074Sgabor */
1388246074Sgaborchar *
1389246074Sgaborpfetch(LINENUM line)
1390246074Sgabor{
1391246074Sgabor	return p_line[line];
1392246074Sgabor}
1393246074Sgabor
1394246074Sgabor/*
1395246074Sgabor * Return where in the patch file this hunk began, for error messages.
1396246074Sgabor */
1397246074SgaborLINENUM
1398246074Sgaborpch_hunk_beg(void)
1399246074Sgabor{
1400246074Sgabor	return p_hunk_beg;
1401246074Sgabor}
1402246074Sgabor
1403246074Sgabor/*
1404246074Sgabor * Apply an ed script by feeding ed itself.
1405246074Sgabor */
1406246074Sgaborvoid
1407246074Sgabordo_ed_script(void)
1408246074Sgabor{
1409246074Sgabor	char	*t;
1410275553Spfg	off_t	beginning_of_this_line;
1411246074Sgabor	FILE	*pipefp = NULL;
1412286346Sdelphij	int	continuation;
1413246074Sgabor
1414246074Sgabor	if (!skip_rest_of_patch) {
1415246074Sgabor		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1416246074Sgabor			unlink(TMPOUTNAME);
1417246074Sgabor			fatal("can't create temp file %s", TMPOUTNAME);
1418246074Sgabor		}
1419286346Sdelphij		snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1420246074Sgabor		    verbose ? " " : " -s ", TMPOUTNAME);
1421246074Sgabor		pipefp = popen(buf, "w");
1422246074Sgabor	}
1423246074Sgabor	for (;;) {
1424275553Spfg		beginning_of_this_line = ftello(pfp);
1425246074Sgabor		if (pgets(true) == 0) {
1426246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1427246074Sgabor			break;
1428246074Sgabor		}
1429246074Sgabor		p_input_line++;
1430246074Sgabor		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1431246074Sgabor			;
1432246074Sgabor		/* POSIX defines allowed commands as {a,c,d,i,s} */
1433275582Spfg		if (isdigit((unsigned char)*buf) &&
1434275582Spfg		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1435246074Sgabor			if (pipefp != NULL)
1436246074Sgabor				fputs(buf, pipefp);
1437286346Sdelphij			if (*t == 's') {
1438286346Sdelphij				for (;;) {
1439286346Sdelphij					continuation = 0;
1440286346Sdelphij					t = strchr(buf, '\0') - 1;
1441286346Sdelphij					while (--t >= buf && *t == '\\')
1442286346Sdelphij						continuation = !continuation;
1443286346Sdelphij					if (!continuation ||
1444286346Sdelphij					    pgets(true) == 0)
1445286346Sdelphij						break;
1446286346Sdelphij					if (pipefp != NULL)
1447286346Sdelphij						fputs(buf, pipefp);
1448286346Sdelphij				}
1449286346Sdelphij			} else if (*t != 'd') {
1450246074Sgabor				while (pgets(true)) {
1451246074Sgabor					p_input_line++;
1452246074Sgabor					if (pipefp != NULL)
1453246074Sgabor						fputs(buf, pipefp);
1454246074Sgabor					if (strEQ(buf, ".\n"))
1455246074Sgabor						break;
1456246074Sgabor				}
1457246074Sgabor			}
1458246074Sgabor		} else {
1459246074Sgabor			next_intuit_at(beginning_of_this_line, p_input_line);
1460246074Sgabor			break;
1461246074Sgabor		}
1462246074Sgabor	}
1463246074Sgabor	if (pipefp == NULL)
1464246074Sgabor		return;
1465246074Sgabor	fprintf(pipefp, "w\n");
1466246074Sgabor	fprintf(pipefp, "q\n");
1467246074Sgabor	fflush(pipefp);
1468246074Sgabor	pclose(pipefp);
1469246074Sgabor	ignore_signals();
1470246074Sgabor	if (!check_only) {
1471246074Sgabor		if (move_file(TMPOUTNAME, outname) < 0) {
1472246074Sgabor			toutkeep = true;
1473246074Sgabor			chmod(TMPOUTNAME, filemode);
1474246074Sgabor		} else
1475246074Sgabor			chmod(outname, filemode);
1476246074Sgabor	}
1477246074Sgabor	set_signals(1);
1478246074Sgabor}
1479246074Sgabor
1480246074Sgabor/*
1481246074Sgabor * Choose the name of the file to be patched based on POSIX rules.
1482246074Sgabor * NOTE: the POSIX rules are amazingly stupid and we only follow them
1483246074Sgabor *       if the user specified --posix or set POSIXLY_CORRECT.
1484246074Sgabor */
1485246074Sgaborstatic char *
1486246074Sgaborposix_name(const struct file_name *names, bool assume_exists)
1487246074Sgabor{
1488246074Sgabor	char *path = NULL;
1489246074Sgabor	int i;
1490246074Sgabor
1491246074Sgabor	/*
1492246074Sgabor	 * POSIX states that the filename will be chosen from one
1493246074Sgabor	 * of the old, new and index names (in that order) if
1494246074Sgabor	 * the file exists relative to CWD after -p stripping.
1495246074Sgabor	 */
1496246074Sgabor	for (i = 0; i < MAX_FILE; i++) {
1497246074Sgabor		if (names[i].path != NULL && names[i].exists) {
1498246074Sgabor			path = names[i].path;
1499246074Sgabor			break;
1500246074Sgabor		}
1501246074Sgabor	}
1502246074Sgabor	if (path == NULL && !assume_exists) {
1503246074Sgabor		/*
1504286795Sdelphij		 * No files found, check to see if the diff could be
1505286795Sdelphij		 * creating a new file.
1506246074Sgabor		 */
1507246074Sgabor		if (path == NULL && ok_to_create_file &&
1508246074Sgabor		    names[NEW_FILE].path != NULL)
1509246074Sgabor			path = names[NEW_FILE].path;
1510246074Sgabor	}
1511246074Sgabor
1512276218Spfg	return path ? xstrdup(path) : NULL;
1513246074Sgabor}
1514246074Sgabor
1515246074Sgaborstatic char *
1516286795Sdelphijcompare_names(const struct file_name *names, bool assume_exists)
1517246074Sgabor{
1518246074Sgabor	size_t min_components, min_baselen, min_len, tmp;
1519246074Sgabor	char *best = NULL;
1520255232Sse	char *path;
1521246074Sgabor	int i;
1522246074Sgabor
1523246074Sgabor	/*
1524246074Sgabor	 * The "best" name is the one with the fewest number of path
1525246074Sgabor	 * components, the shortest basename length, and the shortest
1526246074Sgabor	 * overall length (in that order).  We only use the Index: file
1527246074Sgabor	 * if neither of the old or new files could be intuited from
1528246074Sgabor	 * the diff header.
1529246074Sgabor	 */
1530246074Sgabor	min_components = min_baselen = min_len = SIZE_MAX;
1531246074Sgabor	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1532255232Sse		path = names[i].path;
1533286795Sdelphij		if (path == NULL || (!names[i].exists && !assume_exists))
1534246074Sgabor			continue;
1535255232Sse		if ((tmp = num_components(path)) > min_components)
1536246074Sgabor			continue;
1537250943Sse		if (tmp < min_components) {
1538250943Sse			min_components = tmp;
1539255232Sse			best = path;
1540250943Sse		}
1541255232Sse		if ((tmp = strlen(basename(path))) > min_baselen)
1542246074Sgabor			continue;
1543250943Sse		if (tmp < min_baselen) {
1544250943Sse			min_baselen = tmp;
1545255232Sse			best = path;
1546250943Sse		}
1547255232Sse		if ((tmp = strlen(path)) > min_len)
1548246074Sgabor			continue;
1549246074Sgabor		min_len = tmp;
1550255232Sse		best = path;
1551246074Sgabor	}
1552255232Sse	return best;
1553255232Sse}
1554255232Sse
1555255232Sse/*
1556255232Sse * Choose the name of the file to be patched based the "best" one
1557255232Sse * available.
1558255232Sse */
1559255232Ssestatic char *
1560255232Ssebest_name(const struct file_name *names, bool assume_exists)
1561255232Sse{
1562255232Sse	char *best;
1563255232Sse
1564286795Sdelphij	best = compare_names(names, assume_exists);
1565246074Sgabor
1566286795Sdelphij	/* No match?  Check to see if the diff could be creating a new file. */
1567286795Sdelphij	if (best == NULL && ok_to_create_file)
1568286795Sdelphij		best = names[NEW_FILE].path;
1569286795Sdelphij
1570276218Spfg	return best ? xstrdup(best) : NULL;
1571246074Sgabor}
1572246074Sgabor
1573246074Sgaborstatic size_t
1574246074Sgabornum_components(const char *path)
1575246074Sgabor{
1576246074Sgabor	size_t n;
1577246074Sgabor	const char *cp;
1578246074Sgabor
1579246074Sgabor	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1580246074Sgabor		while (*cp == '/')
1581246074Sgabor			cp++;		/* skip consecutive slashes */
1582246074Sgabor	}
1583246074Sgabor	return n;
1584246074Sgabor}
1585275612Spfg
1586275612Spfg/*
1587275612Spfg * Convert number at NPTR into LINENUM and save address of first
1588275612Spfg * character that is not a digit in ENDPTR.  If conversion is not
1589275612Spfg * possible, call fatal.
1590275612Spfg */
1591275612Spfgstatic LINENUM
1592275612Spfgstrtolinenum(char *nptr, char **endptr)
1593275612Spfg{
1594275612Spfg	LINENUM rv;
1595275612Spfg	char c;
1596275612Spfg	char *p;
1597275612Spfg	const char *errstr;
1598275612Spfg
1599275612Spfg	for (p = nptr; isdigit((unsigned char)*p); p++)
1600275612Spfg		;
1601275612Spfg
1602275612Spfg	if (p == nptr)
1603275612Spfg		malformed();
1604275612Spfg
1605275612Spfg	c = *p;
1606275612Spfg	*p = '\0';
1607275612Spfg
1608275612Spfg	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1609275612Spfg	if (errstr != NULL)
1610275612Spfg		fatal("invalid line number at line %ld: `%s' is %s\n",
1611275612Spfg		    p_input_line, nptr, errstr);
1612276218Spfg
1613275612Spfg	*p = c;
1614275612Spfg	*endptr = p;
1615275612Spfg
1616275612Spfg	return rv;
1617275612Spfg}
1618