pch.c revision 298763
1227825Stheraven/*-
2227825Stheraven * Copyright 1986, Larry Wall
3227825Stheraven *
4353358Sdim * Redistribution and use in source and binary forms, with or without
5353358Sdim * modification, are permitted provided that the following condition is met:
6353358Sdim * 1. Redistributions of source code must retain the above copyright notice,
7227825Stheraven * this condition and the following disclaimer.
8227825Stheraven *
9227825Stheraven * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10227825Stheraven * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11227825Stheraven * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12227825Stheraven * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13227825Stheraven * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14227825Stheraven * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15227825Stheraven * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16227825Stheraven * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17227825Stheraven * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18227825Stheraven * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
19227825Stheraven * SUCH DAMAGE.
20227825Stheraven *
21227825Stheraven * patch - a program to apply diffs to original files
22227825Stheraven *
23227825Stheraven * -C option added in 1998, original code by Marc Espie, based on FreeBSD
24227825Stheraven * behaviour
25227825Stheraven *
26227825Stheraven * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
27227825Stheraven * $FreeBSD: stable/10/usr.bin/patch/pch.c 298763 2016-04-29 02:56:03Z pfg $
28227825Stheraven */
29227825Stheraven
30227825Stheraven#include <sys/types.h>
31227825Stheraven#include <sys/stat.h>
32227825Stheraven
33227825Stheraven#include <ctype.h>
34227825Stheraven#include <libgen.h>
35227825Stheraven#include <limits.h>
36227825Stheraven#include <stdint.h>
37227825Stheraven#include <stdio.h>
38227825Stheraven#include <stdlib.h>
39227825Stheraven#include <string.h>
40227825Stheraven#include <unistd.h>
41227825Stheraven
42227825Stheraven#include "common.h"
43227825Stheraven#include "util.h"
44227825Stheraven#include "pch.h"
45341825Sdim#include "pathnames.h"
46341825Sdim
47341825Sdim/* Patch (diff listing) abstract type. */
48227825Stheraven
49227825Stheravenstatic off_t	p_filesize;	/* size of the patch file */
50227825Stheravenstatic LINENUM	p_first;	/* 1st line number */
51227825Stheravenstatic LINENUM	p_newfirst;	/* 1st line number of replacement */
52227825Stheravenstatic LINENUM	p_ptrn_lines;	/* # lines in pattern */
53227825Stheravenstatic LINENUM	p_repl_lines;	/* # lines in replacement text */
54227825Stheravenstatic LINENUM	p_end = -1;	/* last line in hunk */
55227825Stheravenstatic LINENUM	p_max;		/* max allowed value of p_end */
56227825Stheravenstatic LINENUM	p_context = 3;	/* # of context lines */
57227825Stheravenstatic LINENUM	p_input_line = 0;	/* current line # from patch file */
58227825Stheravenstatic char	**p_line = NULL;/* the text of the hunk */
59227825Stheravenstatic unsigned short	*p_len = NULL; /* length of each line */
60227825Stheravenstatic char	*p_char = NULL;	/* +, -, and ! */
61227825Stheravenstatic int	hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
62227825Stheravenstatic int	p_indent;	/* indent to patch */
63227825Stheravenstatic off_t	p_base;		/* where to intuit this time */
64227825Stheravenstatic LINENUM	p_bline;	/* line # of p_base */
65227825Stheravenstatic off_t	p_start;	/* where intuit found a patch */
66227825Stheravenstatic LINENUM	p_sline;	/* and the line number for it */
67227825Stheravenstatic LINENUM	p_hunk_beg;	/* line number of current hunk */
68227825Stheravenstatic LINENUM	p_efake = -1;	/* end of faked up lines--don't free */
69227825Stheravenstatic LINENUM	p_bfake = -1;	/* beg of faked up lines */
70227825Stheravenstatic FILE	*pfp = NULL;	/* patch file pointer */
71227825Stheravenstatic char	*bestguess = NULL;	/* guess at correct filename */
72227825Stheraven
73261272Sdimstatic void	grow_hunkmax(void);
74261272Sdimstatic int	intuit_diff_type(void);
75261272Sdimstatic void	next_intuit_at(off_t, LINENUM);
76261272Sdimstatic void	skip_to(off_t, LINENUM);
77261272Sdimstatic size_t	pgets(bool _do_indent);
78353358Sdimstatic char	*best_name(const struct file_name *, bool);
79261272Sdimstatic char	*posix_name(const struct file_name *, bool);
80261272Sdimstatic size_t	num_components(const char *);
81261272Sdimstatic LINENUM	strtolinenum(char *, char **);
82261272Sdim
83227825Stheraven/*
84227825Stheraven * Prepare to look for the next patch in the patch file.
85227825Stheraven */
86227825Stheravenvoid
87227825Stheravenre_patch(void)
88227825Stheraven{
89227825Stheraven	p_first = 0;
90227825Stheraven	p_newfirst = 0;
91227825Stheraven	p_ptrn_lines = 0;
92227825Stheraven	p_repl_lines = 0;
93227825Stheraven	p_end = (LINENUM) - 1;
94227825Stheraven	p_max = 0;
95227825Stheraven	p_indent = 0;
96227825Stheraven}
97227825Stheraven
98227825Stheraven/*
99227825Stheraven * Open the patch file at the beginning of time.
100227825Stheraven */
101227825Stheravenvoid
102227825Stheravenopen_patch_file(const char *filename)
103227825Stheraven{
104227825Stheraven	struct stat filestat;
105227825Stheraven	int nr, nw;
106227825Stheraven
107227825Stheraven	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
108227825Stheraven		pfp = fopen(TMPPATNAME, "w");
109227825Stheraven		if (pfp == NULL)
110227825Stheraven			pfatal("can't create %s", TMPPATNAME);
111227825Stheraven		while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
112227825Stheraven			nw = fwrite(buf, 1, nr, pfp);
113227825Stheraven			if (nr != nw)
114227825Stheraven				pfatal("write error to %s", TMPPATNAME);
115227825Stheraven		}
116227825Stheraven		if (ferror(pfp) || fclose(pfp))
117227825Stheraven			pfatal("can't write %s", TMPPATNAME);
118341825Sdim		filename = TMPPATNAME;
119341825Sdim	}
120341825Sdim	pfp = fopen(filename, "r");
121341825Sdim	if (pfp == NULL)
122341825Sdim		pfatal("patch file %s not found", filename);
123227825Stheraven	if (fstat(fileno(pfp), &filestat))
124288943Sdim		pfatal("can't stat %s", filename);
125227825Stheraven	p_filesize = filestat.st_size;
126227825Stheraven	next_intuit_at(0, 1L);	/* start at the beginning */
127227825Stheraven	set_hunkmax();
128227825Stheraven}
129344779Sdim
130344779Sdim/*
131344779Sdim * Make sure our dynamically realloced tables are malloced to begin with.
132344779Sdim */
133344779Sdimvoid
134344779Sdimset_hunkmax(void)
135344779Sdim{
136344779Sdim	if (p_line == NULL)
137344779Sdim		p_line = malloc(hunkmax * sizeof(char *));
138227825Stheraven	if (p_len == NULL)
139288943Sdim		p_len = malloc(hunkmax * sizeof(unsigned short));
140288943Sdim	if (p_char == NULL)
141288943Sdim		p_char = malloc(hunkmax * sizeof(char));
142227825Stheraven}
143227825Stheraven
144227825Stheraven/*
145227825Stheraven * Enlarge the arrays containing the current hunk of patch.
146227825Stheraven */
147227825Stheravenstatic void
148227825Stheravengrow_hunkmax(void)
149353358Sdim{
150227825Stheraven	int new_hunkmax = hunkmax * 2;
151227825Stheraven
152227825Stheraven	if (p_line == NULL || p_len == NULL || p_char == NULL)
153227825Stheraven		fatal("Internal memory allocation error\n");
154227825Stheraven
155227825Stheraven	p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
156227825Stheraven	p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
157227825Stheraven	p_char = reallocf(p_char, new_hunkmax * sizeof(char));
158227825Stheraven
159227825Stheraven	if (p_line != NULL && p_len != NULL && p_char != NULL) {
160227825Stheraven		hunkmax = new_hunkmax;
161227825Stheraven		return;
162227825Stheraven	}
163227825Stheraven
164227825Stheraven	if (!using_plan_a)
165227825Stheraven		fatal("out of memory\n");
166227825Stheraven	out_of_mem = true;	/* whatever is null will be allocated again */
167227825Stheraven				/* from within plan_a(), of all places */
168227825Stheraven}
169227825Stheraven
170227825Stheraven/* True if the remainder of the patch file contains a diff of some sort. */
171227825Stheraven
172227825Stheravenbool
173227825Stheraventhere_is_another_patch(void)
174227825Stheraven{
175227825Stheraven	bool exists = false;
176227825Stheraven
177227825Stheraven	if (p_base != 0 && p_base >= p_filesize) {
178227825Stheraven		if (verbose)
179227825Stheraven			say("done\n");
180227825Stheraven		return false;
181227825Stheraven	}
182227825Stheraven	if (verbose)
183227825Stheraven		say("Hmm...");
184227825Stheraven	diff_type = intuit_diff_type();
185227825Stheraven	if (!diff_type) {
186227825Stheraven		if (p_base != 0) {
187227825Stheraven			if (verbose)
188227825Stheraven				say("  Ignoring the trailing garbage.\ndone\n");
189227825Stheraven		} else
190227825Stheraven			say("  I can't seem to find a patch in there anywhere.\n");
191227825Stheraven		return false;
192227825Stheraven	}
193227825Stheraven	if (verbose)
194227825Stheraven		say("  %sooks like %s to me...\n",
195227825Stheraven		    (p_base == 0 ? "L" : "The next patch l"),
196227825Stheraven		    diff_type == UNI_DIFF ? "a unified diff" :
197227825Stheraven		    diff_type == CONTEXT_DIFF ? "a context diff" :
198227825Stheraven		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
199227825Stheraven		    diff_type == NORMAL_DIFF ? "a normal diff" :
200227825Stheraven		    "an ed script");
201227825Stheraven	if (p_indent && verbose)
202227825Stheraven		say("(Patch is indented %d space%s.)\n", p_indent,
203227825Stheraven		    p_indent == 1 ? "" : "s");
204227825Stheraven	skip_to(p_start, p_sline);
205227825Stheraven	while (filearg[0] == NULL) {
206227825Stheraven		if (force || batch) {
207227825Stheraven			say("No file to patch.  Skipping...\n");
208227825Stheraven			filearg[0] = xstrdup(bestguess);
209227825Stheraven			skip_rest_of_patch = true;
210227825Stheraven			return true;
211341825Sdim		}
212341825Sdim		ask("File to patch: ");
213227825Stheraven		if (*buf != '\n') {
214227825Stheraven			free(bestguess);
215227825Stheraven			bestguess = xstrdup(buf);
216227825Stheraven			filearg[0] = fetchname(buf, &exists, 0);
217227825Stheraven		}
218227825Stheraven		if (!exists) {
219227825Stheraven			ask("No file found--skip this patch? [n] ");
220227825Stheraven			if (*buf != 'y')
221227825Stheraven				continue;
222227825Stheraven			if (verbose)
223227825Stheraven				say("Skipping patch...\n");
224227825Stheraven			free(filearg[0]);
225227825Stheraven			filearg[0] = fetchname(bestguess, &exists, 0);
226227825Stheraven			skip_rest_of_patch = true;
227227825Stheraven			return true;
228227825Stheraven		}
229227825Stheraven	}
230227825Stheraven	return true;
231227825Stheraven}
232227825Stheraven
233227825Stheravenstatic void
234227825Stheravenp4_fetchname(struct file_name *name, char *str)
235227825Stheraven{
236227825Stheraven	char *t, *h;
237227825Stheraven
238261272Sdim	/* Skip leading whitespace. */
239261272Sdim	while (isspace((unsigned char)*str))
240261272Sdim		str++;
241261272Sdim
242261272Sdim	/* Remove the file revision number. */
243261272Sdim	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
244261272Sdim		if (*t == '#')
245261272Sdim			h = t;
246353358Sdim	if (h != NULL)
247261272Sdim		*h = '\0';
248227825Stheraven
249227825Stheraven	name->path = fetchname(str, &name->exists, strippath);
250227825Stheraven}
251227825Stheraven
252227825Stheraven/* Determine what kind of diff is in the remaining part of the patch file. */
253227825Stheraven
254227825Stheravenstatic int
255227825Stheravenintuit_diff_type(void)
256227825Stheraven{
257227825Stheraven	off_t	this_line = 0, previous_line;
258227825Stheraven	off_t	first_command_line = -1;
259227825Stheraven	LINENUM	fcl_line = -1;
260227825Stheraven	bool	last_line_was_command = false, this_is_a_command = false;
261227825Stheraven	bool	stars_last_line = false, stars_this_line = false;
262227825Stheraven	char	*s, *t;
263227825Stheraven	int	indent, retval;
264227825Stheraven	struct file_name names[MAX_FILE];
265227825Stheraven
266227825Stheraven	memset(names, 0, sizeof(names));
267227825Stheraven	ok_to_create_file = false;
268227825Stheraven	fseeko(pfp, p_base, SEEK_SET);
269227825Stheraven	p_input_line = p_bline - 1;
270227825Stheraven	for (;;) {
271227825Stheraven		previous_line = this_line;
272227825Stheraven		last_line_was_command = this_is_a_command;
273227825Stheraven		stars_last_line = stars_this_line;
274227825Stheraven		this_line = ftello(pfp);
275227825Stheraven		indent = 0;
276227825Stheraven		p_input_line++;
277227825Stheraven		if (pgets(false) == 0) {
278227825Stheraven			if (first_command_line >= 0) {
279227825Stheraven				/* nothing but deletes!? */
280227825Stheraven				p_start = first_command_line;
281227825Stheraven				p_sline = fcl_line;
282227825Stheraven				retval = ED_DIFF;
283341825Sdim				goto scan_exit;
284341825Sdim			} else {
285341825Sdim				p_start = this_line;
286341825Sdim				p_sline = p_input_line;
287341825Sdim				retval = 0;
288227825Stheraven				goto scan_exit;
289288943Sdim			}
290227825Stheraven		}
291227825Stheraven		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
292227825Stheraven			if (*s == '\t')
293227825Stheraven				indent += 8 - (indent % 8);
294344779Sdim			else
295344779Sdim				indent++;
296344779Sdim		}
297344779Sdim		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
298344779Sdim			;
299344779Sdim		this_is_a_command = (isdigit((unsigned char)*s) &&
300344779Sdim		    (*t == 'd' || *t == 'c' || *t == 'a'));
301344779Sdim		if (first_command_line < 0 && this_is_a_command) {
302344779Sdim			first_command_line = this_line;
303227825Stheraven			fcl_line = p_input_line;
304288943Sdim			p_indent = indent;	/* assume this for now */
305288943Sdim		}
306288943Sdim		if (!stars_last_line && strnEQ(s, "*** ", 4))
307227825Stheraven			names[OLD_FILE].path = fetchname(s + 4,
308227825Stheraven			    &names[OLD_FILE].exists, strippath);
309227825Stheraven		else if (strnEQ(s, "--- ", 4))
310227825Stheraven			names[NEW_FILE].path = fetchname(s + 4,
311227825Stheraven			    &names[NEW_FILE].exists, strippath);
312227825Stheraven		else if (strnEQ(s, "+++ ", 4))
313227825Stheraven			/* pretend it is the old name */
314353358Sdim			names[OLD_FILE].path = fetchname(s + 4,
315227825Stheraven			    &names[OLD_FILE].exists, strippath);
316227825Stheraven		else if (strnEQ(s, "Index:", 6))
317227825Stheraven			names[INDEX_FILE].path = fetchname(s + 6,
318227825Stheraven			    &names[INDEX_FILE].exists, strippath);
319227825Stheraven		else if (strnEQ(s, "Prereq:", 7)) {
320227825Stheraven			for (t = s + 7; isspace((unsigned char)*t); t++)
321227825Stheraven				;
322227825Stheraven			revision = xstrdup(t);
323227825Stheraven			for (t = revision;
324227825Stheraven			     *t && !isspace((unsigned char)*t); t++)
325227825Stheraven				;
326227825Stheraven			*t = '\0';
327227825Stheraven			if (*revision == '\0') {
328227825Stheraven				free(revision);
329227825Stheraven				revision = NULL;
330227825Stheraven			}
331227825Stheraven		} else if (strnEQ(s, "==== ", 5)) {
332227825Stheraven			/* Perforce-style diffs. */
333227825Stheraven			if ((t = strstr(s + 5, " - ")) != NULL)
334227825Stheraven				p4_fetchname(&names[NEW_FILE], t + 3);
335227825Stheraven			p4_fetchname(&names[OLD_FILE], s + 5);
336227825Stheraven		}
337227825Stheraven		if ((!diff_type || diff_type == ED_DIFF) &&
338227825Stheraven		    first_command_line >= 0 &&
339227825Stheraven		    strEQ(s, ".\n")) {
340227825Stheraven			p_indent = indent;
341227825Stheraven			p_start = first_command_line;
342227825Stheraven			p_sline = fcl_line;
343344779Sdim			retval = ED_DIFF;
344344779Sdim			goto scan_exit;
345344779Sdim		}
346344779Sdim		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
347344779Sdim			if (strnEQ(s + 4, "0,0", 3))
348344779Sdim				ok_to_create_file = true;
349344779Sdim			p_indent = indent;
350227825Stheraven			p_start = this_line;
351227825Stheraven			p_sline = p_input_line;
352227825Stheraven			retval = UNI_DIFF;
353227825Stheraven			goto scan_exit;
354227825Stheraven		}
355227825Stheraven		stars_this_line = strnEQ(s, "********", 8);
356227825Stheraven		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
357227825Stheraven		    strnEQ(s, "*** ", 4)) {
358227825Stheraven			if (strtolinenum(s + 4, &s) == 0)
359227825Stheraven				ok_to_create_file = true;
360227825Stheraven			/*
361227825Stheraven			 * If this is a new context diff the character just
362227825Stheraven			 * at the end of the line is a '*'.
363227825Stheraven			 */
364227825Stheraven			while (*s && *s != '\n')
365341825Sdim				s++;
366227825Stheraven			p_indent = indent;
367344779Sdim			p_start = previous_line;
368227825Stheraven			p_sline = p_input_line - 1;
369276792Sdim			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
370276792Sdim			goto scan_exit;
371227825Stheraven		}
372227825Stheraven		if ((!diff_type || diff_type == NORMAL_DIFF) &&
373227825Stheraven		    last_line_was_command &&
374227825Stheraven		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
375227825Stheraven			p_start = previous_line;
376227825Stheraven			p_sline = p_input_line - 1;
377344779Sdim			p_indent = indent;
378344779Sdim			retval = NORMAL_DIFF;
379344779Sdim			goto scan_exit;
380227825Stheraven		}
381227825Stheraven	}
382314564Sdimscan_exit:
383227825Stheraven	if (retval == UNI_DIFF) {
384227825Stheraven		/* unswap old and new */
385227825Stheraven		struct file_name tmp = names[OLD_FILE];
386227825Stheraven		names[OLD_FILE] = names[NEW_FILE];
387227825Stheraven		names[NEW_FILE] = tmp;
388353358Sdim	}
389353358Sdim	if (filearg[0] == NULL) {
390353358Sdim		if (posix)
391227825Stheraven			filearg[0] = posix_name(names, ok_to_create_file);
392227825Stheraven		else {
393261272Sdim			/* Ignore the Index: name for context diffs, like GNU */
394261272Sdim			if (names[OLD_FILE].path != NULL ||
395227825Stheraven			    names[NEW_FILE].path != NULL) {
396227825Stheraven				free(names[INDEX_FILE].path);
397227825Stheraven				names[INDEX_FILE].path = NULL;
398227825Stheraven			}
399227825Stheraven			filearg[0] = best_name(names, ok_to_create_file);
400227825Stheraven		}
401227825Stheraven	}
402227825Stheraven
403227825Stheraven	free(bestguess);
404227825Stheraven	bestguess = NULL;
405227825Stheraven	if (filearg[0] != NULL)
406227825Stheraven		bestguess = xstrdup(filearg[0]);
407227825Stheraven	else if (!ok_to_create_file) {
408227825Stheraven		/*
409227825Stheraven		 * We don't want to create a new file but we need a
410227825Stheraven		 * filename to set bestguess.  Avoid setting filearg[0]
411227825Stheraven		 * so the file is not created automatically.
412341825Sdim		 */
413341825Sdim		if (posix)
414341825Sdim			bestguess = posix_name(names, true);
415341825Sdim		else
416341825Sdim			bestguess = best_name(names, true);
417344779Sdim	}
418344779Sdim	free(names[OLD_FILE].path);
419344779Sdim	free(names[NEW_FILE].path);
420344779Sdim	free(names[INDEX_FILE].path);
421344779Sdim	return retval;
422227825Stheraven}
423227825Stheraven
424227825Stheraven/*
425261272Sdim * Remember where this patch ends so we know where to start up again.
426261272Sdim */
427261272Sdimstatic void
428261272Sdimnext_intuit_at(off_t file_pos, LINENUM file_line)
429261272Sdim{
430227825Stheraven	p_base = file_pos;
431227825Stheraven	p_bline = file_line;
432261272Sdim}
433261272Sdim
434261272Sdim/*
435261272Sdim * Basically a verbose fseeko() to the actual diff listing.
436261272Sdim */
437261272Sdimstatic void
438261272Sdimskip_to(off_t file_pos, LINENUM file_line)
439261272Sdim{
440227825Stheraven	size_t	len;
441227825Stheraven
442227825Stheraven	if (p_base > file_pos)
443227825Stheraven		fatal("Internal error: seek %lld>%lld\n",
444227825Stheraven		   (long long)p_base, (long long)file_pos);
445227825Stheraven	if (verbose && p_base < file_pos) {
446227825Stheraven		fseeko(pfp, p_base, SEEK_SET);
447227825Stheraven		say("The text leading up to this was:\n--------------------------\n");
448227825Stheraven		while (ftello(pfp) < file_pos) {
449227825Stheraven			len = pgets(false);
450227825Stheraven			if (len == 0)
451227825Stheraven				fatal("Unexpected end of file\n");
452261272Sdim			say("|%s", buf);
453261272Sdim		}
454261272Sdim		say("--------------------------\n");
455353358Sdim	} else
456261272Sdim		fseeko(pfp, file_pos, SEEK_SET);
457261272Sdim	p_input_line = file_line - 1;
458261272Sdim}
459353358Sdim
460261272Sdim/* Make this a function for better debugging.  */
461261272Sdimstatic void
462261272Sdimmalformed(void)
463309124Sdim{
464227825Stheraven	fatal("malformed patch at line %ld: %s", p_input_line, buf);
465227825Stheraven	/* about as informative as "Syntax error" in C */
466227825Stheraven}
467321369Sdim
468309124Sdim/*
469227825Stheraven * True if the line has been discarded (i.e. it is a line saying
470227825Stheraven *  "\ No newline at end of file".)
471227825Stheraven */
472227825Stheravenstatic bool
473227825Stheravenremove_special_line(void)
474227825Stheraven{
475227825Stheraven	int	c;
476227825Stheraven
477227825Stheraven	c = fgetc(pfp);
478227825Stheraven	if (c == '\\') {
479261272Sdim		do {
480261272Sdim			c = fgetc(pfp);
481261272Sdim		} while (c != EOF && c != '\n');
482261272Sdim
483261272Sdim		return true;
484261272Sdim	}
485353358Sdim	if (c != EOF)
486261272Sdim		fseeko(pfp, -1, SEEK_CUR);
487261272Sdim
488261272Sdim	return false;
489321369Sdim}
490227825Stheraven
491353358Sdim/*
492353358Sdim * True if there is more of the current diff listing to process.
493353358Sdim */
494353358Sdimbool
495353358Sdimanother_hunk(void)
496227825Stheraven{
497227825Stheraven	off_t	line_beginning;			/* file pos of the current line */
498227825Stheraven	LINENUM	repl_beginning;			/* index of --- line */
499227825Stheraven	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
500227825Stheraven	LINENUM	fillsrc;			/* index of first line to copy */
501321369Sdim	LINENUM	filldst;			/* index of first missing line */
502309124Sdim	bool	ptrn_spaces_eaten;		/* ptrn was slightly malformed */
503227825Stheraven	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
504227825Stheraven	bool	repl_missing;			/* we are now backtracking */
505309124Sdim	off_t	repl_backtrack_position;	/* file pos of first repl line */
506227825Stheraven	LINENUM	repl_patch_line;		/* input line number for same */
507321369Sdim	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
508227825Stheraven	char	*s;
509227825Stheraven	size_t	len;
510227825Stheraven	int	context = 0;
511227825Stheraven
512227825Stheraven	while (p_end >= 0) {
513327952Sdim		if (p_end == p_efake)
514227825Stheraven			p_end = p_bfake;	/* don't free twice */
515227825Stheraven		else
516227825Stheraven			free(p_line[p_end]);
517227825Stheraven		p_end--;
518227825Stheraven	}
519227825Stheraven	p_efake = -1;
520227825Stheraven
521227825Stheraven	p_max = hunkmax;	/* gets reduced when --- found */
522227825Stheraven	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
523227825Stheraven		line_beginning = ftello(pfp);
524227825Stheraven		repl_beginning = 0;
525227825Stheraven		fillcnt = 0;
526227825Stheraven		fillsrc = 0;
527227825Stheraven		filldst = 0;
528227825Stheraven		ptrn_spaces_eaten = false;
529227825Stheraven		repl_could_be_missing = true;
530227825Stheraven		repl_missing = false;
531227825Stheraven		repl_backtrack_position = 0;
532227825Stheraven		repl_patch_line = 0;
533321369Sdim		ptrn_copiable = 0;
534227825Stheraven
535227825Stheraven		len = pgets(true);
536227825Stheraven		p_input_line++;
537227825Stheraven		if (len == 0 || strnNE(buf, "********", 8)) {
538227825Stheraven			next_intuit_at(line_beginning, p_input_line);
539227825Stheraven			return false;
540261272Sdim		}
541261272Sdim		p_context = 100;
542261272Sdim		p_hunk_beg = p_input_line + 1;
543261272Sdim		while (p_end < p_max) {
544261272Sdim			line_beginning = ftello(pfp);
545261272Sdim			len = pgets(true);
546261272Sdim			p_input_line++;
547261272Sdim			if (len == 0) {
548261272Sdim				if (p_max - p_end < 4) {
549227825Stheraven					/* assume blank lines got chopped */
550227825Stheraven					strlcpy(buf, "  \n", buf_size);
551261272Sdim				} else {
552321369Sdim					if (repl_beginning && repl_could_be_missing) {
553227825Stheraven						repl_missing = true;
554227825Stheraven						goto hunk_done;
555227825Stheraven					}
556227825Stheraven					fatal("unexpected end of file in patch\n");
557261272Sdim				}
558321369Sdim			}
559261272Sdim			p_end++;
560261272Sdim			if (p_end >= hunkmax)
561321369Sdim				fatal("Internal error: hunk larger than hunk "
562261272Sdim				    "buffer size");
563321369Sdim			p_char[p_end] = *buf;
564261272Sdim			p_line[p_end] = NULL;
565261272Sdim			switch (*buf) {
566321369Sdim			case '*':
567321369Sdim				if (strnEQ(buf, "********", 8)) {
568261272Sdim					if (repl_beginning && repl_could_be_missing) {
569227825Stheraven						repl_missing = true;
570321369Sdim						goto hunk_done;
571321369Sdim					} else
572321369Sdim						fatal("unexpected end of hunk "
573321369Sdim						    "at line %ld\n",
574321369Sdim						    p_input_line);
575321369Sdim				}
576321369Sdim				if (p_end != 0) {
577321369Sdim					if (repl_beginning && repl_could_be_missing) {
578261272Sdim						repl_missing = true;
579321369Sdim						goto hunk_done;
580261272Sdim					}
581261272Sdim					fatal("unexpected *** at line %ld: %s",
582321369Sdim					    p_input_line, buf);
583261272Sdim				}
584321369Sdim				context = 0;
585261272Sdim				p_line[p_end] = savestr(buf);
586261272Sdim				if (out_of_mem) {
587321369Sdim					p_end--;
588321369Sdim					return false;
589261272Sdim				}
590227825Stheraven				for (s = buf;
591309124Sdim				     *s && !isdigit((unsigned char)*s); s++)
592227825Stheraven					;
593227825Stheraven				if (!*s)
594227825Stheraven					malformed();
595227825Stheraven				if (strnEQ(s, "0,0", 3))
596227825Stheraven					memmove(s, s + 2, strlen(s + 2) + 1);
597227825Stheraven				p_first = strtolinenum(s, &s);
598227825Stheraven				if (*s == ',') {
599227825Stheraven					for (;
600227825Stheraven					     *s && !isdigit((unsigned char)*s); s++)
601227825Stheraven						;
602227825Stheraven					if (!*s)
603227825Stheraven						malformed();
604341825Sdim					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
605227825Stheraven					if (p_ptrn_lines < 0)
606341825Sdim						malformed();
607341825Sdim				} else if (p_first)
608341825Sdim					p_ptrn_lines = 1;
609341825Sdim				else {
610341825Sdim					p_ptrn_lines = 0;
611341825Sdim					p_first = 1;
612341825Sdim				}
613341825Sdim				if (p_first >= LINENUM_MAX - p_ptrn_lines ||
614341825Sdim				    p_ptrn_lines >= LINENUM_MAX - 6)
615341825Sdim					malformed();
616341825Sdim
617341825Sdim				/* we need this much at least */
618341825Sdim				p_max = p_ptrn_lines + 6;
619341825Sdim				while (p_max >= hunkmax)
620341825Sdim					grow_hunkmax();
621341825Sdim				p_max = hunkmax;
622341825Sdim				break;
623341825Sdim			case '-':
624341825Sdim				if (buf[1] == '-') {
625341825Sdim					if (repl_beginning ||
626341825Sdim					    (p_end != p_ptrn_lines + 1 +
627341825Sdim					    (p_char[p_end - 1] == '\n'))) {
628341825Sdim						if (p_end == 1) {
629341825Sdim							/*
630341825Sdim							 * `old' lines were omitted;
631344779Sdim							 * set up to fill them in
632344779Sdim							 * from 'new' context lines.
633344779Sdim							 */
634344779Sdim							p_end = p_ptrn_lines + 1;
635344779Sdim							fillsrc = p_end + 1;
636344779Sdim							filldst = 1;
637344779Sdim							fillcnt = p_ptrn_lines;
638344779Sdim						} else {
639344779Sdim							if (repl_beginning) {
640344779Sdim								if (repl_could_be_missing) {
641344779Sdim									repl_missing = true;
642344779Sdim									goto hunk_done;
643344779Sdim								}
644344779Sdim								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
645344779Sdim								    p_input_line, p_hunk_beg + repl_beginning);
646344779Sdim							} else {
647344779Sdim								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
648344779Sdim								    (p_end <= p_ptrn_lines
649344779Sdim								    ? "Premature"
650344779Sdim								    : "Overdue"),
651344779Sdim								    p_input_line, p_hunk_beg);
652344779Sdim							}
653344779Sdim						}
654344779Sdim					}
655344779Sdim					repl_beginning = p_end;
656344779Sdim					repl_backtrack_position = ftello(pfp);
657344779Sdim					repl_patch_line = p_input_line;
658344779Sdim					p_line[p_end] = savestr(buf);
659344779Sdim					if (out_of_mem) {
660344779Sdim						p_end--;
661344779Sdim						return false;
662344779Sdim					}
663344779Sdim					p_char[p_end] = '=';
664341825Sdim					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
665341825Sdim						;
666341825Sdim					if (!*s)
667227825Stheraven						malformed();
668227825Stheraven					p_newfirst = strtolinenum(s, &s);
669227825Stheraven					if (*s == ',') {
670227825Stheraven						for (; *s && !isdigit((unsigned char)*s); s++)
671227825Stheraven							;
672227825Stheraven						if (!*s)
673227825Stheraven							malformed();
674227825Stheraven						p_repl_lines = strtolinenum(s, &s) -
675227825Stheraven						    p_newfirst + 1;
676227825Stheraven						if (p_repl_lines < 0)
677227825Stheraven							malformed();
678227825Stheraven					} else if (p_newfirst)
679227825Stheraven						p_repl_lines = 1;
680227825Stheraven					else {
681227825Stheraven						p_repl_lines = 0;
682353358Sdim						p_newfirst = 1;
683353358Sdim					}
684353358Sdim					if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
685353358Sdim					    p_repl_lines >= LINENUM_MAX - p_end)
686227825Stheraven						malformed();
687227825Stheraven					p_max = p_repl_lines + p_end;
688227825Stheraven					if (p_max > MAXHUNKSIZE)
689227825Stheraven						fatal("hunk too large (%ld lines) at line %ld: %s",
690227825Stheraven						    p_max, p_input_line, buf);
691227825Stheraven					while (p_max >= hunkmax)
692227825Stheraven						grow_hunkmax();
693227825Stheraven					if (p_repl_lines != ptrn_copiable &&
694227825Stheraven					    (p_context != 0 || p_repl_lines != 1))
695227825Stheraven						repl_could_be_missing = false;
696227825Stheraven					break;
697227825Stheraven				}
698227825Stheraven				goto change_line;
699227825Stheraven			case '+':
700227825Stheraven			case '!':
701227825Stheraven				repl_could_be_missing = false;
702227825Stheraven		change_line:
703227825Stheraven				if (buf[1] == '\n' && canonicalize)
704227825Stheraven					strlcpy(buf + 1, " \n", buf_size - 1);
705227825Stheraven				if (!isspace((unsigned char)buf[1]) &&
706227825Stheraven				    buf[1] != '>' && buf[1] != '<' &&
707227825Stheraven				    repl_beginning && repl_could_be_missing) {
708227825Stheraven					repl_missing = true;
709227825Stheraven					goto hunk_done;
710227825Stheraven				}
711227825Stheraven				if (context >= 0) {
712227825Stheraven					if (context < p_context)
713227825Stheraven						p_context = context;
714227825Stheraven					context = -1000;
715227825Stheraven				}
716227825Stheraven				p_line[p_end] = savestr(buf + 2);
717227825Stheraven				if (out_of_mem) {
718227825Stheraven					p_end--;
719227825Stheraven					return false;
720227825Stheraven				}
721227825Stheraven				if (p_end == p_ptrn_lines) {
722227825Stheraven					if (remove_special_line()) {
723227825Stheraven						int	l;
724227825Stheraven
725227825Stheraven						l = strlen(p_line[p_end]) - 1;
726261272Sdim						(p_line[p_end])[l] = 0;
727261272Sdim					}
728261272Sdim				}
729261272Sdim				break;
730261272Sdim			case '\t':
731261272Sdim			case '\n':	/* assume the 2 spaces got eaten */
732261272Sdim				if (repl_beginning && repl_could_be_missing &&
733261272Sdim				    (!ptrn_spaces_eaten ||
734261272Sdim				    diff_type == NEW_CONTEXT_DIFF)) {
735261272Sdim					repl_missing = true;
736261272Sdim					goto hunk_done;
737261272Sdim				}
738261272Sdim				p_line[p_end] = savestr(buf);
739261272Sdim				if (out_of_mem) {
740227825Stheraven					p_end--;
741227825Stheraven					return false;
742353358Sdim				}
743353358Sdim				if (p_end != p_ptrn_lines + 1) {
744353358Sdim					ptrn_spaces_eaten |= (repl_beginning != 0);
745353358Sdim					context++;
746353358Sdim					if (!repl_beginning)
747353358Sdim						ptrn_copiable++;
748353358Sdim					p_char[p_end] = ' ';
749353358Sdim				}
750353358Sdim				break;
751353358Sdim			case ' ':
752353358Sdim				if (!isspace((unsigned char)buf[1]) &&
753353358Sdim				    repl_beginning && repl_could_be_missing) {
754353358Sdim					repl_missing = true;
755353358Sdim					goto hunk_done;
756353358Sdim				}
757353358Sdim				context++;
758353358Sdim				if (!repl_beginning)
759353358Sdim					ptrn_copiable++;
760353358Sdim				p_line[p_end] = savestr(buf + 2);
761353358Sdim				if (out_of_mem) {
762353358Sdim					p_end--;
763353358Sdim					return false;
764353358Sdim				}
765353358Sdim				break;
766353358Sdim			default:
767353358Sdim				if (repl_beginning && repl_could_be_missing) {
768353358Sdim					repl_missing = true;
769353358Sdim					goto hunk_done;
770353358Sdim				}
771353358Sdim				malformed();
772353358Sdim			}
773353358Sdim			/* set up p_len for strncmp() so we don't have to */
774353358Sdim			/* assume null termination */
775353358Sdim			if (p_line[p_end])
776353358Sdim				p_len[p_end] = strlen(p_line[p_end]);
777353358Sdim			else
778353358Sdim				p_len[p_end] = 0;
779353358Sdim		}
780353358Sdim
781353358Sdimhunk_done:
782353358Sdim		if (p_end >= 0 && !repl_beginning)
783353358Sdim			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
784353358Sdim
785353358Sdim		if (repl_missing) {
786353358Sdim
787353358Sdim			/* reset state back to just after --- */
788353358Sdim			p_input_line = repl_patch_line;
789353358Sdim			for (p_end--; p_end > repl_beginning; p_end--)
790353358Sdim				free(p_line[p_end]);
791353358Sdim			fseeko(pfp, repl_backtrack_position, SEEK_SET);
792353358Sdim
793353358Sdim			/* redundant 'new' context lines were omitted - set */
794353358Sdim			/* up to fill them in from the old file context */
795353358Sdim			if (!p_context && p_repl_lines == 1) {
796353358Sdim				p_repl_lines = 0;
797353358Sdim				p_max--;
798227825Stheraven			}
799227825Stheraven			fillsrc = 1;
800227825Stheraven			filldst = repl_beginning + 1;
801227825Stheraven			fillcnt = p_repl_lines;
802227825Stheraven			p_end = p_max;
803261272Sdim		} else if (!p_context && fillcnt == 1) {
804261272Sdim			/* the first hunk was a null hunk with no context */
805261272Sdim			/* and we were expecting one line -- fix it up. */
806227825Stheraven			while (filldst < p_end) {
807227825Stheraven				p_line[filldst] = p_line[filldst + 1];
808227825Stheraven				p_char[filldst] = p_char[filldst + 1];
809227825Stheraven				p_len[filldst] = p_len[filldst + 1];
810227825Stheraven				filldst++;
811227825Stheraven			}
812227825Stheraven#if 0
813227825Stheraven			repl_beginning--;	/* this doesn't need to be fixed */
814261272Sdim#endif
815261272Sdim			p_end--;
816261272Sdim			p_first++;	/* do append rather than insert */
817227825Stheraven			fillcnt = 0;
818227825Stheraven			p_ptrn_lines = 0;
819227825Stheraven		}
820227825Stheraven		if (diff_type == CONTEXT_DIFF &&
821227825Stheraven		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
822227825Stheraven			if (verbose)
823227825Stheraven				say("%s\n%s\n%s\n",
824227825Stheraven				    "(Fascinating--this is really a new-style context diff but without",
825261272Sdim				    "the telltale extra asterisks on the *** line that usually indicate",
826261272Sdim				    "the new style...)");
827261272Sdim			diff_type = NEW_CONTEXT_DIFF;
828227825Stheraven		}
829227825Stheraven		/* if there were omitted context lines, fill them in now */
830227825Stheraven		if (fillcnt) {
831227825Stheraven			p_bfake = filldst;	/* remember where not to free() */
832227825Stheraven			p_efake = filldst + fillcnt - 1;
833227825Stheraven			while (fillcnt-- > 0) {
834227825Stheraven				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
835227825Stheraven					fillsrc++;
836227825Stheraven				if (fillsrc > p_end)
837227825Stheraven					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
838261272Sdim					    p_hunk_beg);
839261272Sdim				p_line[filldst] = p_line[fillsrc];
840261272Sdim				p_char[filldst] = p_char[fillsrc];
841227825Stheraven				p_len[filldst] = p_len[fillsrc];
842227825Stheraven				fillsrc++;
843227825Stheraven				filldst++;
844227825Stheraven			}
845227825Stheraven			while (fillsrc <= p_end && fillsrc != repl_beginning &&
846227825Stheraven			    p_char[fillsrc] != ' ')
847227825Stheraven				fillsrc++;
848227825Stheraven#ifdef DEBUGGING
849227825Stheraven			if (debug & 64)
850227825Stheraven				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
851227825Stheraven				fillsrc, filldst, repl_beginning, p_end + 1);
852261272Sdim#endif
853261272Sdim			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
854261272Sdim				malformed();
855227825Stheraven			if (filldst != p_end + 1 && filldst != repl_beginning)
856227825Stheraven				malformed();
857227825Stheraven		}
858227825Stheraven		if (p_line[p_end] != NULL) {
859227825Stheraven			if (remove_special_line()) {
860309124Sdim				p_len[p_end] -= 1;
861227825Stheraven				(p_line[p_end])[p_len[p_end]] = 0;
862227825Stheraven			}
863227825Stheraven		}
864227825Stheraven	} else if (diff_type == UNI_DIFF) {
865261272Sdim		LINENUM	fillold;	/* index of old lines */
866261272Sdim		LINENUM	fillnew;	/* index of new lines */
867261272Sdim		char	ch;
868227825Stheraven
869227825Stheraven		line_beginning = ftello(pfp); /* file pos of the current line */
870227825Stheraven		len = pgets(true);
871227825Stheraven		p_input_line++;
872227825Stheraven		if (len == 0 || strnNE(buf, "@@ -", 4)) {
873227825Stheraven			next_intuit_at(line_beginning, p_input_line);
874227825Stheraven			return false;
875261272Sdim		}
876261272Sdim		s = buf + 4;
877261272Sdim		if (!*s)
878227825Stheraven			malformed();
879227825Stheraven		p_first = strtolinenum(s, &s);
880227825Stheraven		if (*s == ',') {
881227825Stheraven			p_ptrn_lines = strtolinenum(s + 1, &s);
882227825Stheraven		} else
883227825Stheraven			p_ptrn_lines = 1;
884227825Stheraven		if (*s == ' ')
885227825Stheraven			s++;
886227825Stheraven		if (*s != '+' || !*++s)
887261272Sdim			malformed();
888261272Sdim		p_newfirst = strtolinenum(s, &s);
889261272Sdim		if (*s == ',') {
890227825Stheraven			p_repl_lines = strtolinenum(s + 1, &s);
891227825Stheraven		} else
892227825Stheraven			p_repl_lines = 1;
893227825Stheraven		if (*s == ' ')
894321369Sdim			s++;
895227825Stheraven		if (*s != '@')
896227825Stheraven			malformed();
897309124Sdim		if (p_first >= LINENUM_MAX - p_ptrn_lines ||
898227825Stheraven		    p_newfirst > LINENUM_MAX - p_repl_lines ||
899227825Stheraven		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
900227825Stheraven			malformed();
901227825Stheraven		if (!p_ptrn_lines)
902227825Stheraven			p_first++;	/* do append rather than insert */
903261272Sdim		p_max = p_ptrn_lines + p_repl_lines + 1;
904261272Sdim		while (p_max >= hunkmax)
905261272Sdim			grow_hunkmax();
906261272Sdim		fillold = 1;
907227825Stheraven		fillnew = fillold + p_ptrn_lines;
908227825Stheraven		p_end = fillnew + p_repl_lines;
909227825Stheraven		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
910227825Stheraven		    p_first + p_ptrn_lines - 1);
911227825Stheraven		p_line[0] = savestr(buf);
912227825Stheraven		if (out_of_mem) {
913227825Stheraven			p_end = -1;
914261272Sdim			return false;
915261272Sdim		}
916261272Sdim		p_char[0] = '*';
917227825Stheraven		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
918227825Stheraven		    p_newfirst + p_repl_lines - 1);
919227825Stheraven		p_line[fillnew] = savestr(buf);
920227825Stheraven		if (out_of_mem) {
921227825Stheraven			p_end = 0;
922227825Stheraven			return false;
923261272Sdim		}
924261272Sdim		p_char[fillnew++] = '=';
925261272Sdim		p_context = 100;
926261272Sdim		context = 0;
927227825Stheraven		p_hunk_beg = p_input_line + 1;
928227825Stheraven		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
929227825Stheraven			line_beginning = ftello(pfp);
930227825Stheraven			len = pgets(true);
931227825Stheraven			p_input_line++;
932227825Stheraven			if (len == 0) {
933261272Sdim				if (p_max - fillnew < 3) {
934261272Sdim					/* assume blank lines got chopped */
935261272Sdim					strlcpy(buf, " \n", buf_size);
936227825Stheraven				} else {
937227825Stheraven					fatal("unexpected end of file in patch\n");
938227825Stheraven				}
939227825Stheraven			}
940227825Stheraven			if (*buf == '\t' || *buf == '\n') {
941227825Stheraven				ch = ' ';	/* assume the space got eaten */
942227825Stheraven				s = savestr(buf);
943227825Stheraven			} else {
944227825Stheraven				ch = *buf;
945261272Sdim				s = savestr(buf + 1);
946261272Sdim			}
947261272Sdim			if (out_of_mem) {
948227825Stheraven				while (--fillnew > p_ptrn_lines)
949227825Stheraven					free(p_line[fillnew]);
950227825Stheraven				p_end = fillold - 1;
951227825Stheraven				return false;
952227825Stheraven			}
953227825Stheraven			switch (ch) {
954227825Stheraven			case '-':
955227825Stheraven				if (fillold > p_ptrn_lines) {
956227825Stheraven					free(s);
957227825Stheraven					p_end = fillnew - 1;
958261272Sdim					malformed();
959261272Sdim				}
960261272Sdim				p_char[fillold] = ch;
961227825Stheraven				p_line[fillold] = s;
962227825Stheraven				p_len[fillold++] = strlen(s);
963227825Stheraven				if (fillold > p_ptrn_lines) {
964227825Stheraven					if (remove_special_line()) {
965227825Stheraven						p_len[fillold - 1] -= 1;
966309124Sdim						s[p_len[fillold - 1]] = 0;
967227825Stheraven					}
968227825Stheraven				}
969227825Stheraven				break;
970227825Stheraven			case '=':
971227825Stheraven				ch = ' ';
972227825Stheraven				/* FALL THROUGH */
973227825Stheraven			case ' ':
974227825Stheraven				if (fillold > p_ptrn_lines) {
975227825Stheraven					free(s);
976309124Sdim					while (--fillnew > p_ptrn_lines)
977227825Stheraven						free(p_line[fillnew]);
978227825Stheraven					p_end = fillold - 1;
979227825Stheraven					malformed();
980227825Stheraven				}
981227825Stheraven				context++;
982227825Stheraven				p_char[fillold] = ch;
983227825Stheraven				p_line[fillold] = s;
984227825Stheraven				p_len[fillold++] = strlen(s);
985321369Sdim				s = savestr(s);
986227825Stheraven				if (out_of_mem) {
987227825Stheraven					while (--fillnew > p_ptrn_lines)
988227825Stheraven						free(p_line[fillnew]);
989309124Sdim					p_end = fillold - 1;
990227825Stheraven					return false;
991227825Stheraven				}
992227825Stheraven				if (fillold > p_ptrn_lines) {
993227825Stheraven					if (remove_special_line()) {
994227825Stheraven						p_len[fillold - 1] -= 1;
995227825Stheraven						s[p_len[fillold - 1]] = 0;
996227825Stheraven					}
997227825Stheraven				}
998227825Stheraven				/* FALL THROUGH */
999227825Stheraven			case '+':
1000227825Stheraven				if (fillnew > p_end) {
1001227825Stheraven					free(s);
1002227825Stheraven					while (--fillnew > p_ptrn_lines)
1003227825Stheraven						free(p_line[fillnew]);
1004227825Stheraven					p_end = fillold - 1;
1005227825Stheraven					malformed();
1006227825Stheraven				}
1007227825Stheraven				p_char[fillnew] = ch;
1008344779Sdim				p_line[fillnew] = s;
1009344779Sdim				p_len[fillnew++] = strlen(s);
1010344779Sdim				if (fillold > p_ptrn_lines) {
1011344779Sdim					if (remove_special_line()) {
1012344779Sdim						p_len[fillnew - 1] -= 1;
1013344779Sdim						s[p_len[fillnew - 1]] = 0;
1014344779Sdim					}
1015227825Stheraven				}
1016227825Stheraven				break;
1017227825Stheraven			default:
1018227825Stheraven				p_end = fillnew;
1019227825Stheraven				malformed();
1020227825Stheraven			}
1021227825Stheraven			if (ch != ' ' && context > 0) {
1022227825Stheraven				if (context < p_context)
1023227825Stheraven					p_context = context;
1024227825Stheraven				context = -1000;
1025227825Stheraven			}
1026227825Stheraven		}		/* while */
1027227825Stheraven	} else {		/* normal diff--fake it up */
1028227825Stheraven		char	hunk_type;
1029227825Stheraven		int	i;
1030227825Stheraven		LINENUM	min, max;
1031227825Stheraven
1032227825Stheraven		line_beginning = ftello(pfp);
1033227825Stheraven		p_context = 0;
1034227825Stheraven		len = pgets(true);
1035227825Stheraven		p_input_line++;
1036227825Stheraven		if (len == 0 || !isdigit((unsigned char)*buf)) {
1037227825Stheraven			next_intuit_at(line_beginning, p_input_line);
1038227825Stheraven			return false;
1039227825Stheraven		}
1040227825Stheraven		p_first = strtolinenum(buf, &s);
1041227825Stheraven		if (*s == ',') {
1042227825Stheraven			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1043227825Stheraven			if (p_ptrn_lines < 0)
1044227825Stheraven				malformed();
1045314564Sdim		} else
1046227825Stheraven			p_ptrn_lines = (*s != 'a');
1047227825Stheraven		hunk_type = *s;
1048227825Stheraven		if (hunk_type == 'a')
1049227825Stheraven			p_first++;	/* do append rather than insert */
1050227825Stheraven		min = strtolinenum(s + 1, &s);
1051353358Sdim		if (*s == ',')
1052353358Sdim			max = strtolinenum(s + 1, &s);
1053353358Sdim		else
1054227825Stheraven			max = min;
1055227825Stheraven		if (min < 0 || min > max || max - min == LINENUM_MAX)
1056261272Sdim			malformed();
1057261272Sdim		if (hunk_type == 'd')
1058227825Stheraven			min++;
1059227825Stheraven		p_newfirst = min;
1060227825Stheraven		p_repl_lines = max - min + 1;
1061227825Stheraven		if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1062227825Stheraven		    p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1063227825Stheraven			malformed();
1064227825Stheraven		p_end = p_ptrn_lines + p_repl_lines + 1;
1065227825Stheraven		if (p_end > MAXHUNKSIZE)
1066227825Stheraven			fatal("hunk too large (%ld lines) at line %ld: %s",
1067227825Stheraven			    p_end, p_input_line, buf);
1068227825Stheraven		while (p_end >= hunkmax)
1069227825Stheraven			grow_hunkmax();
1070227825Stheraven		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1071227825Stheraven		    p_first + p_ptrn_lines - 1);
1072227825Stheraven		p_line[0] = savestr(buf);
1073227825Stheraven		if (out_of_mem) {
1074227825Stheraven			p_end = -1;
1075341825Sdim			return false;
1076341825Sdim		}
1077341825Sdim		p_char[0] = '*';
1078341825Sdim		for (i = 1; i <= p_ptrn_lines; i++) {
1079344779Sdim			len = pgets(true);
1080344779Sdim			p_input_line++;
1081344779Sdim			if (len == 0)
1082344779Sdim				fatal("unexpected end of file in patch at line %ld\n",
1083344779Sdim				    p_input_line);
1084227825Stheraven			if (*buf != '<')
1085227825Stheraven				fatal("< expected at line %ld of patch\n",
1086227825Stheraven				    p_input_line);
1087261272Sdim			p_line[i] = savestr(buf + 2);
1088261272Sdim			if (out_of_mem) {
1089261272Sdim				p_end = i - 1;
1090261272Sdim				return false;
1091261272Sdim			}
1092227825Stheraven			p_len[i] = strlen(p_line[i]);
1093227825Stheraven			p_char[i] = '-';
1094227825Stheraven		}
1095227825Stheraven
1096261272Sdim		if (remove_special_line()) {
1097261272Sdim			p_len[i - 1] -= 1;
1098261272Sdim			(p_line[i - 1])[p_len[i - 1]] = 0;
1099261272Sdim		}
1100261272Sdim		if (hunk_type == 'c') {
1101261272Sdim			len = pgets(true);
1102261272Sdim			p_input_line++;
1103261272Sdim			if (len == 0)
1104227825Stheraven				fatal("unexpected end of file in patch at line %ld\n",
1105227825Stheraven				    p_input_line);
1106227825Stheraven			if (*buf != '-')
1107227825Stheraven				fatal("--- expected at line %ld of patch\n",
1108227825Stheraven				    p_input_line);
1109227825Stheraven		}
1110227825Stheraven		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1111227825Stheraven		p_line[i] = savestr(buf);
1112227825Stheraven		if (out_of_mem) {
1113227825Stheraven			p_end = i - 1;
1114261272Sdim			return false;
1115261272Sdim		}
1116261272Sdim		p_char[i] = '=';
1117353358Sdim		for (i++; i <= p_end; i++) {
1118261272Sdim			len = pgets(true);
1119261272Sdim			p_input_line++;
1120261272Sdim			if (len == 0)
1121261272Sdim				fatal("unexpected end of file in patch at line %ld\n",
1122261272Sdim				    p_input_line);
1123261272Sdim			if (*buf != '>')
1124261272Sdim				fatal("> expected at line %ld of patch\n",
1125261272Sdim				    p_input_line);
1126309124Sdim			p_line[i] = savestr(buf + 2);
1127227825Stheraven			if (out_of_mem) {
1128227825Stheraven				p_end = i - 1;
1129227825Stheraven				return false;
1130321369Sdim			}
1131309124Sdim			p_len[i] = strlen(p_line[i]);
1132227825Stheraven			p_char[i] = '+';
1133227825Stheraven		}
1134227825Stheraven
1135227825Stheraven		if (remove_special_line()) {
1136227825Stheraven			p_len[i - 1] -= 1;
1137227825Stheraven			(p_line[i - 1])[p_len[i - 1]] = 0;
1138227825Stheraven		}
1139227825Stheraven	}
1140227825Stheraven	if (reverse)		/* backwards patch? */
1141227825Stheraven		if (!pch_swap())
1142261272Sdim			say("Not enough memory to swap next hunk!\n");
1143261272Sdim#ifdef DEBUGGING
1144261272Sdim	if (debug & 2) {
1145261272Sdim		LINENUM	i;
1146261272Sdim		char	special;
1147261272Sdim
1148261272Sdim		for (i = 0; i <= p_end; i++) {
1149261272Sdim			if (i == p_ptrn_lines)
1150321369Sdim				special = '^';
1151227825Stheraven			else
1152353358Sdim				special = ' ';
1153353358Sdim			fprintf(stderr, "%3ld %c %c %s", i, p_char[i],
1154353358Sdim			    special, p_line[i]);
1155353358Sdim			fflush(stderr);
1156353358Sdim		}
1157227825Stheraven	}
1158227825Stheraven#endif
1159227825Stheraven	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1160227825Stheraven		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1161227825Stheraven	return true;
1162321369Sdim}
1163309124Sdim
1164227825Stheraven/*
1165227825Stheraven * Input a line from the patch file.
1166227825Stheraven * Worry about indentation if do_indent is true.
1167321369Sdim * The line is read directly into the buf global variable which
1168227825Stheraven * is resized if necessary in order to hold the complete line.
1169227825Stheraven * Returns the number of characters read including the terminating
1170227825Stheraven * '\n', if any.
1171227825Stheraven */
1172227825Stheravensize_t
1173327952Sdimpgets(bool do_indent)
1174227825Stheraven{
1175227825Stheraven	char *line;
1176227825Stheraven	size_t len;
1177227825Stheraven	int indent = 0, skipped = 0;
1178227825Stheraven
1179227825Stheraven	line = fgetln(pfp, &len);
1180227825Stheraven	if (line != NULL) {
1181227825Stheraven		if (len + 1 > buf_size) {
1182227825Stheraven			while (len + 1 > buf_size)
1183227825Stheraven				buf_size *= 2;
1184227825Stheraven			free(buf);
1185227825Stheraven			buf = malloc(buf_size);
1186227825Stheraven			if (buf == NULL)
1187227825Stheraven				fatal("out of memory\n");
1188227825Stheraven		}
1189227825Stheraven		if (do_indent == 1 && p_indent) {
1190227825Stheraven			for (;
1191227825Stheraven			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1192227825Stheraven			    line++, skipped++) {
1193321369Sdim				if (*line == '\t')
1194227825Stheraven					indent += 8 - (indent %7);
1195227825Stheraven				else
1196227825Stheraven					indent++;
1197227825Stheraven			}
1198227825Stheraven		}
1199227825Stheraven		memcpy(buf, line, len - skipped);
1200227825Stheraven		buf[len - skipped] = '\0';
1201227825Stheraven	}
1202321369Sdim	return len;
1203227825Stheraven}
1204227825Stheraven
1205227825Stheraven
1206227825Stheraven/*
1207227825Stheraven * Reverse the old and new portions of the current hunk.
1208227825Stheraven */
1209227825Stheravenbool
1210227825Stheravenpch_swap(void)
1211321369Sdim{
1212227825Stheraven	char	**tp_line;	/* the text of the hunk */
1213227825Stheraven	unsigned short	*tp_len;/* length of each line */
1214321369Sdim	char	*tp_char;	/* +, -, and ! */
1215321369Sdim	LINENUM	i;
1216321369Sdim	LINENUM	n;
1217321369Sdim	bool	blankline = false;
1218321369Sdim	char	*s;
1219321369Sdim
1220321369Sdim	i = p_first;
1221321369Sdim	p_first = p_newfirst;
1222321369Sdim	p_newfirst = i;
1223321369Sdim
1224341825Sdim	/* make a scratch copy */
1225321369Sdim
1226341825Sdim	tp_line = p_line;
1227341825Sdim	tp_len = p_len;
1228341825Sdim	tp_char = p_char;
1229341825Sdim	p_line = NULL;	/* force set_hunkmax to allocate again */
1230341825Sdim	p_len = NULL;
1231341825Sdim	p_char = NULL;
1232341825Sdim	set_hunkmax();
1233341825Sdim	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1234341825Sdim
1235341825Sdim		free(p_line);
1236341825Sdim		p_line = tp_line;
1237341825Sdim		free(p_len);
1238341825Sdim		p_len = tp_len;
1239341825Sdim		free(p_char);
1240341825Sdim		p_char = tp_char;
1241341825Sdim		return false;	/* not enough memory to swap hunk! */
1242341825Sdim	}
1243341825Sdim	/* now turn the new into the old */
1244341825Sdim
1245341825Sdim	i = p_ptrn_lines + 1;
1246341825Sdim	if (tp_char[i] == '\n') {	/* account for possible blank line */
1247341825Sdim		blankline = true;
1248341825Sdim		i++;
1249341825Sdim	}
1250341825Sdim	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1251341825Sdim		if (p_efake <= i)
1252344779Sdim			n = p_end - i + 1;
1253344779Sdim		else
1254344779Sdim			n = -i;
1255344779Sdim		p_efake += n;
1256344779Sdim		p_bfake += n;
1257344779Sdim	}
1258344779Sdim	for (n = 0; i <= p_end; i++, n++) {
1259344779Sdim		p_line[n] = tp_line[i];
1260344779Sdim		p_char[n] = tp_char[i];
1261344779Sdim		if (p_char[n] == '+')
1262344779Sdim			p_char[n] = '-';
1263344779Sdim		p_len[n] = tp_len[i];
1264344779Sdim	}
1265344779Sdim	if (blankline) {
1266344779Sdim		i = p_ptrn_lines + 1;
1267344779Sdim		p_line[n] = tp_line[i];
1268344779Sdim		p_char[n] = tp_char[i];
1269344779Sdim		p_len[n] = tp_len[i];
1270344779Sdim		n++;
1271344779Sdim	}
1272344779Sdim	if (p_char[0] != '=')
1273344779Sdim		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1274344779Sdim		    p_input_line, p_char[0]);
1275344779Sdim	p_char[0] = '*';
1276344779Sdim	for (s = p_line[0]; *s; s++)
1277344779Sdim		if (*s == '-')
1278344779Sdim			*s = '*';
1279344779Sdim
1280344779Sdim	/* now turn the old into the new */
1281344779Sdim
1282344779Sdim	if (p_char[0] != '*')
1283344779Sdim		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1284344779Sdim		    p_input_line, p_char[0]);
1285341825Sdim	tp_char[0] = '=';
1286341825Sdim	for (s = tp_line[0]; *s; s++)
1287341825Sdim		if (*s == '*')
1288227825Stheraven			*s = '-';
1289227825Stheraven	for (i = 0; n <= p_end; i++, n++) {
1290227825Stheraven		p_line[n] = tp_line[i];
1291227825Stheraven		p_char[n] = tp_char[i];
1292227825Stheraven		if (p_char[n] == '-')
1293227825Stheraven			p_char[n] = '+';
1294227825Stheraven		p_len[n] = tp_len[i];
1295227825Stheraven	}
1296227825Stheraven
1297227825Stheraven	if (i != p_ptrn_lines + 1)
1298227825Stheraven		fatal("Malformed patch at line %ld: expected %ld lines, "
1299227825Stheraven		    "got %ld\n",
1300227825Stheraven		    p_input_line, p_ptrn_lines + 1, i);
1301227825Stheraven
1302227825Stheraven	i = p_ptrn_lines;
1303227825Stheraven	p_ptrn_lines = p_repl_lines;
1304227825Stheraven	p_repl_lines = i;
1305227825Stheraven
1306227825Stheraven	free(tp_line);
1307227825Stheraven	free(tp_len);
1308227825Stheraven	free(tp_char);
1309227825Stheraven
1310227825Stheraven	return true;
1311227825Stheraven}
1312227825Stheraven
1313353358Sdim/*
1314353358Sdim * Return the specified line position in the old file of the old context.
1315353358Sdim */
1316353358SdimLINENUM
1317227825Stheravenpch_first(void)
1318227825Stheraven{
1319227825Stheraven	return p_first;
1320227825Stheraven}
1321227825Stheraven
1322227825Stheraven/*
1323227825Stheraven * Return the number of lines of old context.
1324227825Stheraven */
1325227825StheravenLINENUM
1326227825Stheravenpch_ptrn_lines(void)
1327227825Stheraven{
1328227825Stheraven	return p_ptrn_lines;
1329227825Stheraven}
1330227825Stheraven
1331227825Stheraven/*
1332227825Stheraven * Return the probable line position in the new file of the first line.
1333227825Stheraven */
1334227825StheravenLINENUM
1335227825Stheravenpch_newfirst(void)
1336227825Stheraven{
1337227825Stheraven	return p_newfirst;
1338227825Stheraven}
1339227825Stheraven
1340227825Stheraven/*
1341227825Stheraven * Return the number of lines in the replacement text including context.
1342227825Stheraven */
1343227825StheravenLINENUM
1344227825Stheravenpch_repl_lines(void)
1345227825Stheraven{
1346227825Stheraven	return p_repl_lines;
1347227825Stheraven}
1348227825Stheraven
1349227825Stheraven/*
1350227825Stheraven * Return the number of lines in the whole hunk.
1351227825Stheraven */
1352227825StheravenLINENUM
1353227825Stheravenpch_end(void)
1354227825Stheraven{
1355227825Stheraven	return p_end;
1356227825Stheraven}
1357261272Sdim
1358261272Sdim/*
1359261272Sdim * Return the number of context lines before the first changed line.
1360261272Sdim */
1361261272SdimLINENUM
1362261272Sdimpch_context(void)
1363261272Sdim{
1364261272Sdim	return p_context;
1365261272Sdim}
1366261272Sdim
1367261272Sdim/*
1368261272Sdim * Return the length of a particular patch line.
1369261272Sdim */
1370261272Sdimunsigned short
1371227825Stheravenpch_line_len(LINENUM line)
1372227825Stheraven{
1373353358Sdim	return p_len[line];
1374353358Sdim}
1375353358Sdim
1376353358Sdim/*
1377353358Sdim * Return the control character (+, -, *, !, etc) for a patch line.
1378353358Sdim */
1379353358Sdimchar
1380353358Sdimpch_char(LINENUM line)
1381353358Sdim{
1382353358Sdim	return p_char[line];
1383353358Sdim}
1384353358Sdim
1385353358Sdim/*
1386353358Sdim * Return a pointer to a particular patch line.
1387353358Sdim */
1388353358Sdimchar *
1389353358Sdimpfetch(LINENUM line)
1390353358Sdim{
1391353358Sdim	return p_line[line];
1392353358Sdim}
1393353358Sdim
1394353358Sdim/*
1395353358Sdim * Return where in the patch file this hunk began, for error messages.
1396353358Sdim */
1397353358SdimLINENUM
1398353358Sdimpch_hunk_beg(void)
1399353358Sdim{
1400353358Sdim	return p_hunk_beg;
1401353358Sdim}
1402353358Sdim
1403353358Sdim/*
1404353358Sdim * Apply an ed script by feeding ed itself.
1405353358Sdim */
1406353358Sdimvoid
1407353358Sdimdo_ed_script(void)
1408353358Sdim{
1409353358Sdim	char	*t;
1410353358Sdim	off_t	beginning_of_this_line;
1411353358Sdim	FILE	*pipefp = NULL;
1412353358Sdim	int	continuation;
1413353358Sdim
1414353358Sdim	if (!skip_rest_of_patch) {
1415353358Sdim		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1416353358Sdim			unlink(TMPOUTNAME);
1417353358Sdim			fatal("can't create temp file %s", TMPOUTNAME);
1418353358Sdim		}
1419353358Sdim		snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1420353358Sdim		    verbose ? " " : " -s ", TMPOUTNAME);
1421353358Sdim		pipefp = popen(buf, "w");
1422353358Sdim	}
1423353358Sdim	for (;;) {
1424353358Sdim		beginning_of_this_line = ftello(pfp);
1425353358Sdim		if (pgets(true) == 0) {
1426353358Sdim			next_intuit_at(beginning_of_this_line, p_input_line);
1427227825Stheraven			break;
1428227825Stheraven		}
1429227825Stheraven		p_input_line++;
1430227825Stheraven		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1431227825Stheraven			;
1432261272Sdim		/* POSIX defines allowed commands as {a,c,d,i,s} */
1433261272Sdim		if (isdigit((unsigned char)*buf) &&
1434261272Sdim		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1435227825Stheraven			if (pipefp != NULL)
1436227825Stheraven				fputs(buf, pipefp);
1437227825Stheraven			if (*t == 's') {
1438227825Stheraven				for (;;) {
1439227825Stheraven					continuation = 0;
1440227825Stheraven					t = strchr(buf, '\0') - 1;
1441227825Stheraven					while (--t >= buf && *t == '\\')
1442227825Stheraven						continuation = !continuation;
1443227825Stheraven					if (!continuation ||
1444261272Sdim					    pgets(true) == 0)
1445261272Sdim						break;
1446261272Sdim					if (pipefp != NULL)
1447227825Stheraven						fputs(buf, pipefp);
1448227825Stheraven				}
1449227825Stheraven			} else if (*t != 'd') {
1450227825Stheraven				while (pgets(true)) {
1451227825Stheraven					p_input_line++;
1452227825Stheraven					if (pipefp != NULL)
1453227825Stheraven						fputs(buf, pipefp);
1454227825Stheraven					if (strEQ(buf, ".\n"))
1455261272Sdim						break;
1456261272Sdim				}
1457261272Sdim			}
1458227825Stheraven		} else {
1459227825Stheraven			next_intuit_at(beginning_of_this_line, p_input_line);
1460227825Stheraven			break;
1461227825Stheraven		}
1462227825Stheraven	}
1463227825Stheraven	if (pipefp == NULL)
1464227825Stheraven		return;
1465227825Stheraven	fprintf(pipefp, "w\n");
1466227825Stheraven	fprintf(pipefp, "q\n");
1467227825Stheraven	fflush(pipefp);
1468261272Sdim	pclose(pipefp);
1469261272Sdim	ignore_signals();
1470261272Sdim	if (!check_only) {
1471227825Stheraven		if (move_file(TMPOUTNAME, outname) < 0) {
1472227825Stheraven			toutkeep = true;
1473227825Stheraven			chmod(TMPOUTNAME, filemode);
1474227825Stheraven		} else
1475227825Stheraven			chmod(outname, filemode);
1476227825Stheraven	}
1477227825Stheraven	set_signals(1);
1478227825Stheraven}
1479227825Stheraven
1480227825Stheraven/*
1481227825Stheraven * Choose the name of the file to be patched based on POSIX rules.
1482261272Sdim * NOTE: the POSIX rules are amazingly stupid and we only follow them
1483261272Sdim *       if the user specified --posix or set POSIXLY_CORRECT.
1484261272Sdim */
1485227825Stheravenstatic char *
1486227825Stheravenposix_name(const struct file_name *names, bool assume_exists)
1487227825Stheraven{
1488227825Stheraven	char *path = NULL;
1489227825Stheraven	int i;
1490309124Sdim
1491227825Stheraven	/*
1492227825Stheraven	 * POSIX states that the filename will be chosen from one
1493227825Stheraven	 * of the old, new and index names (in that order) if
1494227825Stheraven	 * the file exists relative to CWD after -p stripping.
1495261272Sdim	 */
1496261272Sdim	for (i = 0; i < MAX_FILE; i++) {
1497261272Sdim		if (names[i].path != NULL && names[i].exists) {
1498227825Stheraven			path = names[i].path;
1499227825Stheraven			break;
1500227825Stheraven		}
1501227825Stheraven	}
1502227825Stheraven	if (path == NULL && !assume_exists) {
1503227825Stheraven		/*
1504227825Stheraven		 * No files found, look for something we can checkout from
1505261272Sdim		 * RCS/SCCS dirs.  Same order as above.
1506261272Sdim		 */
1507261272Sdim		for (i = 0; i < MAX_FILE; i++) {
1508227825Stheraven			if (names[i].path != NULL &&
1509227825Stheraven			    (path = checked_in(names[i].path)) != NULL)
1510227825Stheraven				break;
1511227825Stheraven		}
1512227825Stheraven		/*
1513227825Stheraven		 * Still no match?  Check to see if the diff could be creating
1514227825Stheraven		 * a new file.
1515227825Stheraven		 */
1516227825Stheraven		if (path == NULL && ok_to_create_file &&
1517261272Sdim		    names[NEW_FILE].path != NULL)
1518261272Sdim			path = names[NEW_FILE].path;
1519261272Sdim	}
1520227825Stheraven
1521227825Stheraven	return path ? xstrdup(path) : NULL;
1522227825Stheraven}
1523227825Stheraven
1524321369Sdimstatic char *
1525227825Stheravencompare_names(const struct file_name *names, bool assume_exists, int phase)
1526227825Stheraven{
1527309124Sdim	size_t min_components, min_baselen, min_len, tmp;
1528227825Stheraven	char *best = NULL;
1529227825Stheraven	char *path;
1530227825Stheraven	int i;
1531227825Stheraven
1532227825Stheraven	/*
1533261272Sdim	 * The "best" name is the one with the fewest number of path
1534261272Sdim	 * components, the shortest basename length, and the shortest
1535261272Sdim	 * overall length (in that order).  We only use the Index: file
1536261272Sdim	 * if neither of the old or new files could be intuited from
1537227825Stheraven	 * the diff header.
1538227825Stheraven	 */
1539227825Stheraven	min_components = min_baselen = min_len = SIZE_MAX;
1540227825Stheraven	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1541227825Stheraven		path = names[i].path;
1542227825Stheraven		if (path == NULL ||
1543227825Stheraven		    (phase == 1 && !names[i].exists && !assume_exists) ||
1544261272Sdim		    (phase == 2 && checked_in(path) == NULL))
1545261272Sdim			continue;
1546261272Sdim		if ((tmp = num_components(path)) > min_components)
1547227825Stheraven			continue;
1548227825Stheraven		if (tmp < min_components) {
1549227825Stheraven			min_components = tmp;
1550227825Stheraven			best = path;
1551227825Stheraven		}
1552227825Stheraven		if ((tmp = strlen(basename(path))) > min_baselen)
1553261272Sdim			continue;
1554261272Sdim		if (tmp < min_baselen) {
1555261272Sdim			min_baselen = tmp;
1556261272Sdim			best = path;
1557227825Stheraven		}
1558227825Stheraven		if ((tmp = strlen(path)) > min_len)
1559227825Stheraven			continue;
1560227825Stheraven		min_len = tmp;
1561227825Stheraven		best = path;
1562227825Stheraven	}
1563261272Sdim	return best;
1564261272Sdim}
1565261272Sdim
1566227825Stheraven/*
1567227825Stheraven * Choose the name of the file to be patched based the "best" one
1568227825Stheraven * available.
1569227825Stheraven */
1570227825Stheravenstatic char *
1571227825Stheravenbest_name(const struct file_name *names, bool assume_exists)
1572227825Stheraven{
1573227825Stheraven	char *best;
1574227825Stheraven
1575261272Sdim	best = compare_names(names, assume_exists, 1);
1576261272Sdim	if (best == NULL) {
1577261272Sdim		best = compare_names(names, assume_exists, 2);
1578227825Stheraven		/*
1579227825Stheraven		 * Still no match?  Check to see if the diff could be creating
1580227825Stheraven		 * a new file.
1581227825Stheraven		 */
1582227825Stheraven		if (best == NULL && ok_to_create_file &&
1583227825Stheraven		    names[NEW_FILE].path != NULL)
1584227825Stheraven			best = names[NEW_FILE].path;
1585227825Stheraven	}
1586227825Stheraven
1587227825Stheraven	return best ? xstrdup(best) : NULL;
1588261272Sdim}
1589261272Sdim
1590261272Sdimstatic size_t
1591227825Stheravennum_components(const char *path)
1592227825Stheraven{
1593227825Stheraven	size_t n;
1594227825Stheraven	const char *cp;
1595227825Stheraven
1596309124Sdim	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1597227825Stheraven		while (*cp == '/')
1598227825Stheraven			cp++;		/* skip consecutive slashes */
1599227825Stheraven	}
1600227825Stheraven	return n;
1601227825Stheraven}
1602227825Stheraven
1603227825Stheraven/*
1604227825Stheraven * Convert number at NPTR into LINENUM and save address of first
1605227825Stheraven * character that is not a digit in ENDPTR.  If conversion is not
1606227825Stheraven * possible, call fatal.
1607227825Stheraven */
1608227825Stheravenstatic LINENUM
1609227825Stheravenstrtolinenum(char *nptr, char **endptr)
1610227825Stheraven{
1611227825Stheraven	LINENUM rv;
1612227825Stheraven	char c;
1613227825Stheraven	char *p;
1614227825Stheraven	const char *errstr;
1615227825Stheraven
1616321369Sdim	for (p = nptr; isdigit((unsigned char)*p); p++)
1617227825Stheraven		;
1618227825Stheraven
1619227825Stheraven	if (p == nptr)
1620309124Sdim		malformed();
1621227825Stheraven
1622227825Stheraven	c = *p;
1623227825Stheraven	*p = '\0';
1624227825Stheraven
1625227825Stheraven	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1626227825Stheraven	if (errstr != NULL)
1627227825Stheraven		fatal("invalid line number at line %ld: `%s' is %s\n",
1628227825Stheraven		    p_input_line, nptr, errstr);
1629227825Stheraven
1630227825Stheraven	*p = c;
1631227825Stheraven	*endptr = p;
1632227825Stheraven
1633227825Stheraven	return rv;
1634227825Stheraven}
1635227825Stheraven