pch.c revision 267746
1
2/*-
3 * Copyright 1986, Larry Wall
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following condition is met:
7 * 1. Redistributions of source code must retain the above copyright notice,
8 * this condition and the following disclaimer.
9 *
10 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
11 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
14 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
15 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
16 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
17 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
19 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
20 * SUCH DAMAGE.
21 *
22 * patch - a program to apply diffs to original files
23 *
24 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
25 * behaviour
26 *
27 * $OpenBSD: pch.c,v 1.39 2012/04/11 08:07:13 ajacoutot Exp $
28 * $FreeBSD: stable/10/usr.bin/patch/pch.c 267746 2014-06-22 20:24:17Z pfg $
29 */
30
31#include <sys/types.h>
32#include <sys/stat.h>
33
34#include <ctype.h>
35#include <libgen.h>
36#include <limits.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <unistd.h>
41
42#include "common.h"
43#include "util.h"
44#include "pch.h"
45#include "pathnames.h"
46
47/* Patch (diff listing) abstract type. */
48
49static long	p_filesize;	/* size of the patch file */
50static LINENUM	p_first;	/* 1st line number */
51static LINENUM	p_newfirst;	/* 1st line number of replacement */
52static LINENUM	p_ptrn_lines;	/* # lines in pattern */
53static LINENUM	p_repl_lines;	/* # lines in replacement text */
54static LINENUM	p_end = -1;	/* last line in hunk */
55static LINENUM	p_max;		/* max allowed value of p_end */
56static LINENUM	p_context = 3;	/* # of context lines */
57static LINENUM	p_input_line = 0;	/* current line # from patch file */
58static char	**p_line = NULL;/* the text of the hunk */
59static unsigned short	*p_len = NULL; /* length of each line */
60static char	*p_char = NULL;	/* +, -, and ! */
61static int	hunkmax = INITHUNKMAX;	/* size of above arrays to begin with */
62static int	p_indent;	/* indent to patch */
63static LINENUM	p_base;		/* where to intuit this time */
64static LINENUM	p_bline;	/* line # of p_base */
65static LINENUM	p_start;	/* where intuit found a patch */
66static LINENUM	p_sline;	/* and the line number for it */
67static LINENUM	p_hunk_beg;	/* line number of current hunk */
68static LINENUM	p_efake = -1;	/* end of faked up lines--don't free */
69static LINENUM	p_bfake = -1;	/* beg of faked up lines */
70static FILE	*pfp = NULL;	/* patch file pointer */
71static char	*bestguess = NULL;	/* guess at correct filename */
72
73static void	grow_hunkmax(void);
74static int	intuit_diff_type(void);
75static void	next_intuit_at(LINENUM, LINENUM);
76static void	skip_to(LINENUM, LINENUM);
77static size_t	pgets(bool _do_indent);
78static char	*best_name(const struct file_name *, bool);
79static char	*posix_name(const struct file_name *, bool);
80static size_t	num_components(const char *);
81
82/*
83 * Prepare to look for the next patch in the patch file.
84 */
85void
86re_patch(void)
87{
88	p_first = 0;
89	p_newfirst = 0;
90	p_ptrn_lines = 0;
91	p_repl_lines = 0;
92	p_end = (LINENUM) - 1;
93	p_max = 0;
94	p_indent = 0;
95}
96
97/*
98 * Open the patch file at the beginning of time.
99 */
100void
101open_patch_file(const char *filename)
102{
103	struct stat filestat;
104	int nr, nw;
105
106	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
107		pfp = fopen(TMPPATNAME, "w");
108		if (pfp == NULL)
109			pfatal("can't create %s", TMPPATNAME);
110		while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
111			nw = fwrite(buf, 1, nr, pfp);
112			if (nr != nw)
113				pfatal("write error to %s", TMPPATNAME);
114		}
115		if (ferror(pfp) || fclose(pfp))
116			pfatal("can't write %s", TMPPATNAME);
117		filename = TMPPATNAME;
118	}
119	pfp = fopen(filename, "r");
120	if (pfp == NULL)
121		pfatal("patch file %s not found", filename);
122	fstat(fileno(pfp), &filestat);
123	p_filesize = filestat.st_size;
124	next_intuit_at(0L, 1L);	/* start at the beginning */
125	set_hunkmax();
126}
127
128/*
129 * Make sure our dynamically realloced tables are malloced to begin with.
130 */
131void
132set_hunkmax(void)
133{
134	if (p_line == NULL)
135		p_line = malloc(hunkmax * sizeof(char *));
136	if (p_len == NULL)
137		p_len = malloc(hunkmax * sizeof(unsigned short));
138	if (p_char == NULL)
139		p_char = malloc(hunkmax * sizeof(char));
140}
141
142/*
143 * Enlarge the arrays containing the current hunk of patch.
144 */
145static void
146grow_hunkmax(void)
147{
148	int new_hunkmax = hunkmax * 2;
149
150	if (p_line == NULL || p_len == NULL || p_char == NULL)
151		fatal("Internal memory allocation error\n");
152
153	p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
154	p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
155	p_char = reallocf(p_char, new_hunkmax * sizeof(char));
156
157	if (p_line != NULL && p_len != NULL && p_char != NULL) {
158		hunkmax = new_hunkmax;
159		return;
160	}
161
162	if (!using_plan_a)
163		fatal("out of memory\n");
164	out_of_mem = true;	/* whatever is null will be allocated again */
165				/* from within plan_a(), of all places */
166}
167
168/* True if the remainder of the patch file contains a diff of some sort. */
169
170bool
171there_is_another_patch(void)
172{
173	bool exists = false;
174
175	if (p_base != 0L && p_base >= p_filesize) {
176		if (verbose)
177			say("done\n");
178		return false;
179	}
180	if (verbose)
181		say("Hmm...");
182	diff_type = intuit_diff_type();
183	if (!diff_type) {
184		if (p_base != 0L) {
185			if (verbose)
186				say("  Ignoring the trailing garbage.\ndone\n");
187		} else
188			say("  I can't seem to find a patch in there anywhere.\n");
189		return false;
190	}
191	if (verbose)
192		say("  %sooks like %s to me...\n",
193		    (p_base == 0L ? "L" : "The next patch l"),
194		    diff_type == UNI_DIFF ? "a unified diff" :
195		    diff_type == CONTEXT_DIFF ? "a context diff" :
196		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
197		    diff_type == NORMAL_DIFF ? "a normal diff" :
198		    "an ed script");
199	if (p_indent && verbose)
200		say("(Patch is indented %d space%s.)\n", p_indent,
201		    p_indent == 1 ? "" : "s");
202	skip_to(p_start, p_sline);
203	while (filearg[0] == NULL) {
204		if (force || batch) {
205			say("No file to patch.  Skipping...\n");
206			filearg[0] = savestr(bestguess);
207			skip_rest_of_patch = true;
208			return true;
209		}
210		ask("File to patch: ");
211		if (*buf != '\n') {
212			free(bestguess);
213			bestguess = savestr(buf);
214			filearg[0] = fetchname(buf, &exists, 0);
215		}
216		if (!exists) {
217			ask("No file found--skip this patch? [n] ");
218			if (*buf != 'y')
219				continue;
220			if (verbose)
221				say("Skipping patch...\n");
222			free(filearg[0]);
223			filearg[0] = fetchname(bestguess, &exists, 0);
224			skip_rest_of_patch = true;
225			return true;
226		}
227	}
228	return true;
229}
230
231static void
232p4_fetchname(struct file_name *name, char *str)
233{
234	char *t, *h;
235
236	/* Skip leading whitespace. */
237	while (isspace((unsigned char)*str))
238		str++;
239
240	/* Remove the file revision number. */
241	for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
242		if (*t == '#')
243			h = t;
244	if (h != NULL)
245		*h = '\0';
246
247	name->path = fetchname(str, &name->exists, strippath);
248}
249
250/* Determine what kind of diff is in the remaining part of the patch file. */
251
252static int
253intuit_diff_type(void)
254{
255	long	this_line = 0, previous_line;
256	long	first_command_line = -1;
257	LINENUM	fcl_line = -1;
258	bool	last_line_was_command = false, this_is_a_command = false;
259	bool	stars_last_line = false, stars_this_line = false;
260	char	*s, *t;
261	int	indent, retval;
262	struct file_name names[MAX_FILE];
263
264	memset(names, 0, sizeof(names));
265	ok_to_create_file = false;
266	fseek(pfp, p_base, SEEK_SET);
267	p_input_line = p_bline - 1;
268	for (;;) {
269		previous_line = this_line;
270		last_line_was_command = this_is_a_command;
271		stars_last_line = stars_this_line;
272		this_line = ftell(pfp);
273		indent = 0;
274		p_input_line++;
275		if (pgets(false) == 0) {
276			if (first_command_line >= 0L) {
277				/* nothing but deletes!? */
278				p_start = first_command_line;
279				p_sline = fcl_line;
280				retval = ED_DIFF;
281				goto scan_exit;
282			} else {
283				p_start = this_line;
284				p_sline = p_input_line;
285				retval = 0;
286				goto scan_exit;
287			}
288		}
289		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
290			if (*s == '\t')
291				indent += 8 - (indent % 8);
292			else
293				indent++;
294		}
295		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
296			;
297		this_is_a_command = (isdigit((unsigned char)*s) &&
298		    (*t == 'd' || *t == 'c' || *t == 'a'));
299		if (first_command_line < 0L && this_is_a_command) {
300			first_command_line = this_line;
301			fcl_line = p_input_line;
302			p_indent = indent;	/* assume this for now */
303		}
304		if (!stars_last_line && strnEQ(s, "*** ", 4))
305			names[OLD_FILE].path = fetchname(s + 4,
306			    &names[OLD_FILE].exists, strippath);
307		else if (strnEQ(s, "--- ", 4))
308			names[NEW_FILE].path = fetchname(s + 4,
309			    &names[NEW_FILE].exists, strippath);
310		else if (strnEQ(s, "+++ ", 4))
311			/* pretend it is the old name */
312			names[OLD_FILE].path = fetchname(s + 4,
313			    &names[OLD_FILE].exists, strippath);
314		else if (strnEQ(s, "Index:", 6))
315			names[INDEX_FILE].path = fetchname(s + 6,
316			    &names[INDEX_FILE].exists, strippath);
317		else if (strnEQ(s, "Prereq:", 7)) {
318			for (t = s + 7; isspace((unsigned char)*t); t++)
319				;
320			revision = savestr(t);
321			for (t = revision; *t && !isspace((unsigned char)*t); t++)
322				;
323			*t = '\0';
324			if (*revision == '\0') {
325				free(revision);
326				revision = NULL;
327			}
328		} else if (strnEQ(s, "==== ", 5)) {
329			/* Perforce-style diffs. */
330			if ((t = strstr(s + 5, " - ")) != NULL)
331				p4_fetchname(&names[NEW_FILE], t + 3);
332			p4_fetchname(&names[OLD_FILE], s + 5);
333		}
334		if ((!diff_type || diff_type == ED_DIFF) &&
335		    first_command_line >= 0L &&
336		    strEQ(s, ".\n")) {
337			p_indent = indent;
338			p_start = first_command_line;
339			p_sline = fcl_line;
340			retval = ED_DIFF;
341			goto scan_exit;
342		}
343		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
344			if (strnEQ(s + 4, "0,0", 3))
345				ok_to_create_file = true;
346			p_indent = indent;
347			p_start = this_line;
348			p_sline = p_input_line;
349			retval = UNI_DIFF;
350			goto scan_exit;
351		}
352		stars_this_line = strnEQ(s, "********", 8);
353		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
354		    strnEQ(s, "*** ", 4)) {
355			if (atol(s + 4) == 0)
356				ok_to_create_file = true;
357			/*
358			 * If this is a new context diff the character just
359			 * before the newline is a '*'.
360			 */
361			while (*s != '\n')
362				s++;
363			p_indent = indent;
364			p_start = previous_line;
365			p_sline = p_input_line - 1;
366			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
367			goto scan_exit;
368		}
369		if ((!diff_type || diff_type == NORMAL_DIFF) &&
370		    last_line_was_command &&
371		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
372			p_start = previous_line;
373			p_sline = p_input_line - 1;
374			p_indent = indent;
375			retval = NORMAL_DIFF;
376			goto scan_exit;
377		}
378	}
379scan_exit:
380	if (retval == UNI_DIFF) {
381		/* unswap old and new */
382		struct file_name tmp = names[OLD_FILE];
383		names[OLD_FILE] = names[NEW_FILE];
384		names[NEW_FILE] = tmp;
385	}
386	if (filearg[0] == NULL) {
387		if (posix)
388			filearg[0] = posix_name(names, ok_to_create_file);
389		else {
390			/* Ignore the Index: name for context diffs, like GNU */
391			if (names[OLD_FILE].path != NULL ||
392			    names[NEW_FILE].path != NULL) {
393				free(names[INDEX_FILE].path);
394				names[INDEX_FILE].path = NULL;
395			}
396			filearg[0] = best_name(names, ok_to_create_file);
397		}
398	}
399
400	free(bestguess);
401	bestguess = NULL;
402	if (filearg[0] != NULL)
403		bestguess = savestr(filearg[0]);
404	else if (!ok_to_create_file) {
405		/*
406		 * We don't want to create a new file but we need a
407		 * filename to set bestguess.  Avoid setting filearg[0]
408		 * so the file is not created automatically.
409		 */
410		if (posix)
411			bestguess = posix_name(names, true);
412		else
413			bestguess = best_name(names, true);
414	}
415	free(names[OLD_FILE].path);
416	free(names[NEW_FILE].path);
417	free(names[INDEX_FILE].path);
418	return retval;
419}
420
421/*
422 * Remember where this patch ends so we know where to start up again.
423 */
424static void
425next_intuit_at(LINENUM file_pos, LINENUM file_line)
426{
427	p_base = file_pos;
428	p_bline = file_line;
429}
430
431/*
432 * Basically a verbose fseek() to the actual diff listing.
433 */
434static void
435skip_to(LINENUM file_pos, LINENUM file_line)
436{
437	size_t	len;
438
439	if (p_base > file_pos)
440		fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
441	if (verbose && p_base < file_pos) {
442		fseek(pfp, p_base, SEEK_SET);
443		say("The text leading up to this was:\n--------------------------\n");
444		while (ftell(pfp) < file_pos) {
445			len = pgets(false);
446			if (len == 0)
447				fatal("Unexpected end of file\n");
448			say("|%s", buf);
449		}
450		say("--------------------------\n");
451	} else
452		fseek(pfp, file_pos, SEEK_SET);
453	p_input_line = file_line - 1;
454}
455
456/* Make this a function for better debugging.  */
457static void
458malformed(void)
459{
460	fatal("malformed patch at line %ld: %s", p_input_line, buf);
461	/* about as informative as "Syntax error" in C */
462}
463
464/*
465 * True if the line has been discarded (i.e. it is a line saying
466 *  "\ No newline at end of file".)
467 */
468static bool
469remove_special_line(void)
470{
471	int	c;
472
473	c = fgetc(pfp);
474	if (c == '\\') {
475		do {
476			c = fgetc(pfp);
477		} while (c != EOF && c != '\n');
478
479		return true;
480	}
481	if (c != EOF)
482		fseek(pfp, -1L, SEEK_CUR);
483
484	return false;
485}
486
487/*
488 * True if there is more of the current diff listing to process.
489 */
490bool
491another_hunk(void)
492{
493	long	line_beginning;			/* file pos of the current line */
494	LINENUM	repl_beginning;			/* index of --- line */
495	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
496	LINENUM	fillsrc;			/* index of first line to copy */
497	LINENUM	filldst;			/* index of first missing line */
498	bool	ptrn_spaces_eaten;		/* ptrn was slightly misformed */
499	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
500	bool	repl_missing;			/* we are now backtracking */
501	long	repl_backtrack_position;	/* file pos of first repl line */
502	LINENUM	repl_patch_line;		/* input line number for same */
503	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
504	char	*s;
505	size_t	len;
506	int	context = 0;
507
508	while (p_end >= 0) {
509		if (p_end == p_efake)
510			p_end = p_bfake;	/* don't free twice */
511		else
512			free(p_line[p_end]);
513		p_end--;
514	}
515	p_efake = -1;
516
517	p_max = hunkmax;	/* gets reduced when --- found */
518	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
519		line_beginning = ftell(pfp);
520		repl_beginning = 0;
521		fillcnt = 0;
522		fillsrc = 0;
523		filldst = 0;
524		ptrn_spaces_eaten = false;
525		repl_could_be_missing = true;
526		repl_missing = false;
527		repl_backtrack_position = 0;
528		repl_patch_line = 0;
529		ptrn_copiable = 0;
530
531		len = pgets(true);
532		p_input_line++;
533		if (len == 0 || strnNE(buf, "********", 8)) {
534			next_intuit_at(line_beginning, p_input_line);
535			return false;
536		}
537		p_context = 100;
538		p_hunk_beg = p_input_line + 1;
539		while (p_end < p_max) {
540			line_beginning = ftell(pfp);
541			len = pgets(true);
542			p_input_line++;
543			if (len == 0) {
544				if (p_max - p_end < 4) {
545					/* assume blank lines got chopped */
546					strlcpy(buf, "  \n", buf_size);
547				} else {
548					if (repl_beginning && repl_could_be_missing) {
549						repl_missing = true;
550						goto hunk_done;
551					}
552					fatal("unexpected end of file in patch\n");
553				}
554			}
555			p_end++;
556			if (p_end >= hunkmax)
557				fatal("Internal error: hunk larger than hunk "
558				    "buffer size");
559			p_char[p_end] = *buf;
560			p_line[p_end] = NULL;
561			switch (*buf) {
562			case '*':
563				if (strnEQ(buf, "********", 8)) {
564					if (repl_beginning && repl_could_be_missing) {
565						repl_missing = true;
566						goto hunk_done;
567					} else
568						fatal("unexpected end of hunk "
569						    "at line %ld\n",
570						    p_input_line);
571				}
572				if (p_end != 0) {
573					if (repl_beginning && repl_could_be_missing) {
574						repl_missing = true;
575						goto hunk_done;
576					}
577					fatal("unexpected *** at line %ld: %s",
578					    p_input_line, buf);
579				}
580				context = 0;
581				p_line[p_end] = savestr(buf);
582				if (out_of_mem) {
583					p_end--;
584					return false;
585				}
586				for (s = buf; *s && !isdigit((unsigned char)*s); s++)
587					;
588				if (!*s)
589					malformed();
590				if (strnEQ(s, "0,0", 3))
591					memmove(s, s + 2, strlen(s + 2) + 1);
592				p_first = (LINENUM) atol(s);
593				while (isdigit((unsigned char)*s))
594					s++;
595				if (*s == ',') {
596					for (; *s && !isdigit((unsigned char)*s); s++)
597						;
598					if (!*s)
599						malformed();
600					p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
601				} else if (p_first)
602					p_ptrn_lines = 1;
603				else {
604					p_ptrn_lines = 0;
605					p_first = 1;
606				}
607
608				/* we need this much at least */
609				p_max = p_ptrn_lines + 6;
610				while (p_max >= hunkmax)
611					grow_hunkmax();
612				p_max = hunkmax;
613				break;
614			case '-':
615				if (buf[1] == '-') {
616					if (repl_beginning ||
617					    (p_end != p_ptrn_lines + 1 +
618					    (p_char[p_end - 1] == '\n'))) {
619						if (p_end == 1) {
620							/*
621							 * `old' lines were omitted;
622							 * set up to fill them in
623							 * from 'new' context lines.
624							 */
625							p_end = p_ptrn_lines + 1;
626							fillsrc = p_end + 1;
627							filldst = 1;
628							fillcnt = p_ptrn_lines;
629						} else {
630							if (repl_beginning) {
631								if (repl_could_be_missing) {
632									repl_missing = true;
633									goto hunk_done;
634								}
635								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
636								    p_input_line, p_hunk_beg + repl_beginning);
637							} else {
638								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
639								    (p_end <= p_ptrn_lines
640								    ? "Premature"
641								    : "Overdue"),
642								    p_input_line, p_hunk_beg);
643							}
644						}
645					}
646					repl_beginning = p_end;
647					repl_backtrack_position = ftell(pfp);
648					repl_patch_line = p_input_line;
649					p_line[p_end] = savestr(buf);
650					if (out_of_mem) {
651						p_end--;
652						return false;
653					}
654					p_char[p_end] = '=';
655					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
656						;
657					if (!*s)
658						malformed();
659					p_newfirst = (LINENUM) atol(s);
660					while (isdigit((unsigned char)*s))
661						s++;
662					if (*s == ',') {
663						for (; *s && !isdigit((unsigned char)*s); s++)
664							;
665						if (!*s)
666							malformed();
667						p_repl_lines = ((LINENUM) atol(s)) -
668						    p_newfirst + 1;
669					} else if (p_newfirst)
670						p_repl_lines = 1;
671					else {
672						p_repl_lines = 0;
673						p_newfirst = 1;
674					}
675					p_max = p_repl_lines + p_end;
676					if (p_max > MAXHUNKSIZE)
677						fatal("hunk too large (%ld lines) at line %ld: %s",
678						    p_max, p_input_line, buf);
679					while (p_max >= hunkmax)
680						grow_hunkmax();
681					if (p_repl_lines != ptrn_copiable &&
682					    (p_context != 0 || p_repl_lines != 1))
683						repl_could_be_missing = false;
684					break;
685				}
686				goto change_line;
687			case '+':
688			case '!':
689				repl_could_be_missing = false;
690		change_line:
691				if (buf[1] == '\n' && canonicalize)
692					strlcpy(buf + 1, " \n", buf_size - 1);
693				if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
694				    buf[1] != '<' &&
695				    repl_beginning && repl_could_be_missing) {
696					repl_missing = true;
697					goto hunk_done;
698				}
699				if (context >= 0) {
700					if (context < p_context)
701						p_context = context;
702					context = -1000;
703				}
704				p_line[p_end] = savestr(buf + 2);
705				if (out_of_mem) {
706					p_end--;
707					return false;
708				}
709				if (p_end == p_ptrn_lines) {
710					if (remove_special_line()) {
711						int	l;
712
713						l = strlen(p_line[p_end]) - 1;
714						(p_line[p_end])[l] = 0;
715					}
716				}
717				break;
718			case '\t':
719			case '\n':	/* assume the 2 spaces got eaten */
720				if (repl_beginning && repl_could_be_missing &&
721				    (!ptrn_spaces_eaten ||
722				    diff_type == NEW_CONTEXT_DIFF)) {
723					repl_missing = true;
724					goto hunk_done;
725				}
726				p_line[p_end] = savestr(buf);
727				if (out_of_mem) {
728					p_end--;
729					return false;
730				}
731				if (p_end != p_ptrn_lines + 1) {
732					ptrn_spaces_eaten |= (repl_beginning != 0);
733					context++;
734					if (!repl_beginning)
735						ptrn_copiable++;
736					p_char[p_end] = ' ';
737				}
738				break;
739			case ' ':
740				if (!isspace((unsigned char)buf[1]) &&
741				    repl_beginning && repl_could_be_missing) {
742					repl_missing = true;
743					goto hunk_done;
744				}
745				context++;
746				if (!repl_beginning)
747					ptrn_copiable++;
748				p_line[p_end] = savestr(buf + 2);
749				if (out_of_mem) {
750					p_end--;
751					return false;
752				}
753				break;
754			default:
755				if (repl_beginning && repl_could_be_missing) {
756					repl_missing = true;
757					goto hunk_done;
758				}
759				malformed();
760			}
761			/* set up p_len for strncmp() so we don't have to */
762			/* assume null termination */
763			if (p_line[p_end])
764				p_len[p_end] = strlen(p_line[p_end]);
765			else
766				p_len[p_end] = 0;
767		}
768
769hunk_done:
770		if (p_end >= 0 && !repl_beginning)
771			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
772
773		if (repl_missing) {
774
775			/* reset state back to just after --- */
776			p_input_line = repl_patch_line;
777			for (p_end--; p_end > repl_beginning; p_end--)
778				free(p_line[p_end]);
779			fseek(pfp, repl_backtrack_position, SEEK_SET);
780
781			/* redundant 'new' context lines were omitted - set */
782			/* up to fill them in from the old file context */
783			if (!p_context && p_repl_lines == 1) {
784				p_repl_lines = 0;
785				p_max--;
786			}
787			fillsrc = 1;
788			filldst = repl_beginning + 1;
789			fillcnt = p_repl_lines;
790			p_end = p_max;
791		} else if (!p_context && fillcnt == 1) {
792			/* the first hunk was a null hunk with no context */
793			/* and we were expecting one line -- fix it up. */
794			while (filldst < p_end) {
795				p_line[filldst] = p_line[filldst + 1];
796				p_char[filldst] = p_char[filldst + 1];
797				p_len[filldst] = p_len[filldst + 1];
798				filldst++;
799			}
800#if 0
801			repl_beginning--;	/* this doesn't need to be fixed */
802#endif
803			p_end--;
804			p_first++;	/* do append rather than insert */
805			fillcnt = 0;
806			p_ptrn_lines = 0;
807		}
808		if (diff_type == CONTEXT_DIFF &&
809		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
810			if (verbose)
811				say("%s\n%s\n%s\n",
812				    "(Fascinating--this is really a new-style context diff but without",
813				    "the telltale extra asterisks on the *** line that usually indicate",
814				    "the new style...)");
815			diff_type = NEW_CONTEXT_DIFF;
816		}
817		/* if there were omitted context lines, fill them in now */
818		if (fillcnt) {
819			p_bfake = filldst;	/* remember where not to free() */
820			p_efake = filldst + fillcnt - 1;
821			while (fillcnt-- > 0) {
822				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
823					fillsrc++;
824				if (fillsrc > p_end)
825					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
826					    p_hunk_beg);
827				p_line[filldst] = p_line[fillsrc];
828				p_char[filldst] = p_char[fillsrc];
829				p_len[filldst] = p_len[fillsrc];
830				fillsrc++;
831				filldst++;
832			}
833			while (fillsrc <= p_end && fillsrc != repl_beginning &&
834			    p_char[fillsrc] != ' ')
835				fillsrc++;
836#ifdef DEBUGGING
837			if (debug & 64)
838				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
839				fillsrc, filldst, repl_beginning, p_end + 1);
840#endif
841			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
842				malformed();
843			if (filldst != p_end + 1 && filldst != repl_beginning)
844				malformed();
845		}
846		if (p_line[p_end] != NULL) {
847			if (remove_special_line()) {
848				p_len[p_end] -= 1;
849				(p_line[p_end])[p_len[p_end]] = 0;
850			}
851		}
852	} else if (diff_type == UNI_DIFF) {
853		LINENUM	fillold;	/* index of old lines */
854		LINENUM	fillnew;	/* index of new lines */
855		char	ch;
856
857		line_beginning = ftell(pfp); /* file pos of the current line */
858		len = pgets(true);
859		p_input_line++;
860		if (len == 0 || strnNE(buf, "@@ -", 4)) {
861			next_intuit_at(line_beginning, p_input_line);
862			return false;
863		}
864		s = buf + 4;
865		if (!*s)
866			malformed();
867		p_first = (LINENUM) atol(s);
868		while (isdigit((unsigned char)*s))
869			s++;
870		if (*s == ',') {
871			p_ptrn_lines = (LINENUM) atol(++s);
872			while (isdigit((unsigned char)*s))
873				s++;
874		} else
875			p_ptrn_lines = 1;
876		if (*s == ' ')
877			s++;
878		if (*s != '+' || !*++s)
879			malformed();
880		p_newfirst = (LINENUM) atol(s);
881		while (isdigit((unsigned char)*s))
882			s++;
883		if (*s == ',') {
884			p_repl_lines = (LINENUM) atol(++s);
885			while (isdigit((unsigned char)*s))
886				s++;
887		} else
888			p_repl_lines = 1;
889		if (*s == ' ')
890			s++;
891		if (*s != '@')
892			malformed();
893		if (!p_ptrn_lines)
894			p_first++;	/* do append rather than insert */
895		p_max = p_ptrn_lines + p_repl_lines + 1;
896		while (p_max >= hunkmax)
897			grow_hunkmax();
898		fillold = 1;
899		fillnew = fillold + p_ptrn_lines;
900		p_end = fillnew + p_repl_lines;
901		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
902		    p_first + p_ptrn_lines - 1);
903		p_line[0] = savestr(buf);
904		if (out_of_mem) {
905			p_end = -1;
906			return false;
907		}
908		p_char[0] = '*';
909		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
910		    p_newfirst + p_repl_lines - 1);
911		p_line[fillnew] = savestr(buf);
912		if (out_of_mem) {
913			p_end = 0;
914			return false;
915		}
916		p_char[fillnew++] = '=';
917		p_context = 100;
918		context = 0;
919		p_hunk_beg = p_input_line + 1;
920		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
921			line_beginning = ftell(pfp);
922			len = pgets(true);
923			p_input_line++;
924			if (len == 0) {
925				if (p_max - fillnew < 3) {
926					/* assume blank lines got chopped */
927					strlcpy(buf, " \n", buf_size);
928				} else {
929					fatal("unexpected end of file in patch\n");
930				}
931			}
932			if (*buf == '\t' || *buf == '\n') {
933				ch = ' ';	/* assume the space got eaten */
934				s = savestr(buf);
935			} else {
936				ch = *buf;
937				s = savestr(buf + 1);
938			}
939			if (out_of_mem) {
940				while (--fillnew > p_ptrn_lines)
941					free(p_line[fillnew]);
942				p_end = fillold - 1;
943				return false;
944			}
945			switch (ch) {
946			case '-':
947				if (fillold > p_ptrn_lines) {
948					free(s);
949					p_end = fillnew - 1;
950					malformed();
951				}
952				p_char[fillold] = ch;
953				p_line[fillold] = s;
954				p_len[fillold++] = strlen(s);
955				if (fillold > p_ptrn_lines) {
956					if (remove_special_line()) {
957						p_len[fillold - 1] -= 1;
958						s[p_len[fillold - 1]] = 0;
959					}
960				}
961				break;
962			case '=':
963				ch = ' ';
964				/* FALL THROUGH */
965			case ' ':
966				if (fillold > p_ptrn_lines) {
967					free(s);
968					while (--fillnew > p_ptrn_lines)
969						free(p_line[fillnew]);
970					p_end = fillold - 1;
971					malformed();
972				}
973				context++;
974				p_char[fillold] = ch;
975				p_line[fillold] = s;
976				p_len[fillold++] = strlen(s);
977				s = savestr(s);
978				if (out_of_mem) {
979					while (--fillnew > p_ptrn_lines)
980						free(p_line[fillnew]);
981					p_end = fillold - 1;
982					return false;
983				}
984				if (fillold > p_ptrn_lines) {
985					if (remove_special_line()) {
986						p_len[fillold - 1] -= 1;
987						s[p_len[fillold - 1]] = 0;
988					}
989				}
990				/* FALL THROUGH */
991			case '+':
992				if (fillnew > p_end) {
993					free(s);
994					while (--fillnew > p_ptrn_lines)
995						free(p_line[fillnew]);
996					p_end = fillold - 1;
997					malformed();
998				}
999				p_char[fillnew] = ch;
1000				p_line[fillnew] = s;
1001				p_len[fillnew++] = strlen(s);
1002				if (fillold > p_ptrn_lines) {
1003					if (remove_special_line()) {
1004						p_len[fillnew - 1] -= 1;
1005						s[p_len[fillnew - 1]] = 0;
1006					}
1007				}
1008				break;
1009			default:
1010				p_end = fillnew;
1011				malformed();
1012			}
1013			if (ch != ' ' && context > 0) {
1014				if (context < p_context)
1015					p_context = context;
1016				context = -1000;
1017			}
1018		}		/* while */
1019	} else {		/* normal diff--fake it up */
1020		char	hunk_type;
1021		int	i;
1022		LINENUM	min, max;
1023
1024		line_beginning = ftell(pfp);
1025		p_context = 0;
1026		len = pgets(true);
1027		p_input_line++;
1028		if (len == 0 || !isdigit((unsigned char)*buf)) {
1029			next_intuit_at(line_beginning, p_input_line);
1030			return false;
1031		}
1032		p_first = (LINENUM) atol(buf);
1033		for (s = buf; isdigit((unsigned char)*s); s++)
1034			;
1035		if (*s == ',') {
1036			p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1037			while (isdigit((unsigned char)*s))
1038				s++;
1039		} else
1040			p_ptrn_lines = (*s != 'a');
1041		hunk_type = *s;
1042		if (hunk_type == 'a')
1043			p_first++;	/* do append rather than insert */
1044		min = (LINENUM) atol(++s);
1045		for (; isdigit((unsigned char)*s); s++)
1046			;
1047		if (*s == ',')
1048			max = (LINENUM) atol(++s);
1049		else
1050			max = min;
1051		if (hunk_type == 'd')
1052			min++;
1053		p_end = p_ptrn_lines + 1 + max - min + 1;
1054		if (p_end > MAXHUNKSIZE)
1055			fatal("hunk too large (%ld lines) at line %ld: %s",
1056			    p_end, p_input_line, buf);
1057		while (p_end >= hunkmax)
1058			grow_hunkmax();
1059		p_newfirst = min;
1060		p_repl_lines = max - min + 1;
1061		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1062		    p_first + p_ptrn_lines - 1);
1063		p_line[0] = savestr(buf);
1064		if (out_of_mem) {
1065			p_end = -1;
1066			return false;
1067		}
1068		p_char[0] = '*';
1069		for (i = 1; i <= p_ptrn_lines; i++) {
1070			len = pgets(true);
1071			p_input_line++;
1072			if (len == 0)
1073				fatal("unexpected end of file in patch at line %ld\n",
1074				    p_input_line);
1075			if (*buf != '<')
1076				fatal("< expected at line %ld of patch\n",
1077				    p_input_line);
1078			p_line[i] = savestr(buf + 2);
1079			if (out_of_mem) {
1080				p_end = i - 1;
1081				return false;
1082			}
1083			p_len[i] = strlen(p_line[i]);
1084			p_char[i] = '-';
1085		}
1086
1087		if (remove_special_line()) {
1088			p_len[i - 1] -= 1;
1089			(p_line[i - 1])[p_len[i - 1]] = 0;
1090		}
1091		if (hunk_type == 'c') {
1092			len = pgets(true);
1093			p_input_line++;
1094			if (len == 0)
1095				fatal("unexpected end of file in patch at line %ld\n",
1096				    p_input_line);
1097			if (*buf != '-')
1098				fatal("--- expected at line %ld of patch\n",
1099				    p_input_line);
1100		}
1101		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1102		p_line[i] = savestr(buf);
1103		if (out_of_mem) {
1104			p_end = i - 1;
1105			return false;
1106		}
1107		p_char[i] = '=';
1108		for (i++; i <= p_end; i++) {
1109			len = pgets(true);
1110			p_input_line++;
1111			if (len == 0)
1112				fatal("unexpected end of file in patch at line %ld\n",
1113				    p_input_line);
1114			if (*buf != '>')
1115				fatal("> expected at line %ld of patch\n",
1116				    p_input_line);
1117			p_line[i] = savestr(buf + 2);
1118			if (out_of_mem) {
1119				p_end = i - 1;
1120				return false;
1121			}
1122			p_len[i] = strlen(p_line[i]);
1123			p_char[i] = '+';
1124		}
1125
1126		if (remove_special_line()) {
1127			p_len[i - 1] -= 1;
1128			(p_line[i - 1])[p_len[i - 1]] = 0;
1129		}
1130	}
1131	if (reverse)		/* backwards patch? */
1132		if (!pch_swap())
1133			say("Not enough memory to swap next hunk!\n");
1134#ifdef DEBUGGING
1135	if (debug & 2) {
1136		int	i;
1137		char	special;
1138
1139		for (i = 0; i <= p_end; i++) {
1140			if (i == p_ptrn_lines)
1141				special = '^';
1142			else
1143				special = ' ';
1144			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1145			    special, p_line[i]);
1146			fflush(stderr);
1147		}
1148	}
1149#endif
1150	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1151		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1152	return true;
1153}
1154
1155/*
1156 * Input a line from the patch file.
1157 * Worry about indentation if do_indent is true.
1158 * The line is read directly into the buf global variable which
1159 * is resized if necessary in order to hold the complete line.
1160 * Returns the number of characters read including the terminating
1161 * '\n', if any.
1162 */
1163size_t
1164pgets(bool do_indent)
1165{
1166	char *line;
1167	size_t len;
1168	int indent = 0, skipped = 0;
1169
1170	line = fgetln(pfp, &len);
1171	if (line != NULL) {
1172		if (len + 1 > buf_size) {
1173			while (len + 1 > buf_size)
1174				buf_size *= 2;
1175			free(buf);
1176			buf = malloc(buf_size);
1177			if (buf == NULL)
1178				fatal("out of memory\n");
1179		}
1180		if (do_indent == 1 && p_indent) {
1181			for (;
1182			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1183			    line++, skipped++) {
1184				if (*line == '\t')
1185					indent += 8 - (indent %7);
1186				else
1187					indent++;
1188			}
1189		}
1190		memcpy(buf, line, len - skipped);
1191		buf[len - skipped] = '\0';
1192	}
1193	return len;
1194}
1195
1196
1197/*
1198 * Reverse the old and new portions of the current hunk.
1199 */
1200bool
1201pch_swap(void)
1202{
1203	char	**tp_line;	/* the text of the hunk */
1204	unsigned short	*tp_len;/* length of each line */
1205	char	*tp_char;	/* +, -, and ! */
1206	LINENUM	i;
1207	LINENUM	n;
1208	bool	blankline = false;
1209	char	*s;
1210
1211	i = p_first;
1212	p_first = p_newfirst;
1213	p_newfirst = i;
1214
1215	/* make a scratch copy */
1216
1217	tp_line = p_line;
1218	tp_len = p_len;
1219	tp_char = p_char;
1220	p_line = NULL;	/* force set_hunkmax to allocate again */
1221	p_len = NULL;
1222	p_char = NULL;
1223	set_hunkmax();
1224	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1225
1226		free(p_line);
1227		p_line = tp_line;
1228		free(p_len);
1229		p_len = tp_len;
1230		free(p_char);
1231		p_char = tp_char;
1232		return false;	/* not enough memory to swap hunk! */
1233	}
1234	/* now turn the new into the old */
1235
1236	i = p_ptrn_lines + 1;
1237	if (tp_char[i] == '\n') {	/* account for possible blank line */
1238		blankline = true;
1239		i++;
1240	}
1241	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1242		if (p_efake <= i)
1243			n = p_end - i + 1;
1244		else
1245			n = -i;
1246		p_efake += n;
1247		p_bfake += n;
1248	}
1249	for (n = 0; i <= p_end; i++, n++) {
1250		p_line[n] = tp_line[i];
1251		p_char[n] = tp_char[i];
1252		if (p_char[n] == '+')
1253			p_char[n] = '-';
1254		p_len[n] = tp_len[i];
1255	}
1256	if (blankline) {
1257		i = p_ptrn_lines + 1;
1258		p_line[n] = tp_line[i];
1259		p_char[n] = tp_char[i];
1260		p_len[n] = tp_len[i];
1261		n++;
1262	}
1263	if (p_char[0] != '=')
1264		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1265		    p_input_line, p_char[0]);
1266	p_char[0] = '*';
1267	for (s = p_line[0]; *s; s++)
1268		if (*s == '-')
1269			*s = '*';
1270
1271	/* now turn the old into the new */
1272
1273	if (p_char[0] != '*')
1274		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1275		    p_input_line, p_char[0]);
1276	tp_char[0] = '=';
1277	for (s = tp_line[0]; *s; s++)
1278		if (*s == '*')
1279			*s = '-';
1280	for (i = 0; n <= p_end; i++, n++) {
1281		p_line[n] = tp_line[i];
1282		p_char[n] = tp_char[i];
1283		if (p_char[n] == '-')
1284			p_char[n] = '+';
1285		p_len[n] = tp_len[i];
1286	}
1287
1288	if (i != p_ptrn_lines + 1)
1289		fatal("Malformed patch at line %ld: expected %ld lines, "
1290		    "got %ld\n",
1291		    p_input_line, p_ptrn_lines + 1, i);
1292
1293	i = p_ptrn_lines;
1294	p_ptrn_lines = p_repl_lines;
1295	p_repl_lines = i;
1296
1297	free(tp_line);
1298	free(tp_len);
1299	free(tp_char);
1300
1301	return true;
1302}
1303
1304/*
1305 * Return the specified line position in the old file of the old context.
1306 */
1307LINENUM
1308pch_first(void)
1309{
1310	return p_first;
1311}
1312
1313/*
1314 * Return the number of lines of old context.
1315 */
1316LINENUM
1317pch_ptrn_lines(void)
1318{
1319	return p_ptrn_lines;
1320}
1321
1322/*
1323 * Return the probable line position in the new file of the first line.
1324 */
1325LINENUM
1326pch_newfirst(void)
1327{
1328	return p_newfirst;
1329}
1330
1331/*
1332 * Return the number of lines in the replacement text including context.
1333 */
1334LINENUM
1335pch_repl_lines(void)
1336{
1337	return p_repl_lines;
1338}
1339
1340/*
1341 * Return the number of lines in the whole hunk.
1342 */
1343LINENUM
1344pch_end(void)
1345{
1346	return p_end;
1347}
1348
1349/*
1350 * Return the number of context lines before the first changed line.
1351 */
1352LINENUM
1353pch_context(void)
1354{
1355	return p_context;
1356}
1357
1358/*
1359 * Return the length of a particular patch line.
1360 */
1361unsigned short
1362pch_line_len(LINENUM line)
1363{
1364	return p_len[line];
1365}
1366
1367/*
1368 * Return the control character (+, -, *, !, etc) for a patch line.
1369 */
1370char
1371pch_char(LINENUM line)
1372{
1373	return p_char[line];
1374}
1375
1376/*
1377 * Return a pointer to a particular patch line.
1378 */
1379char *
1380pfetch(LINENUM line)
1381{
1382	return p_line[line];
1383}
1384
1385/*
1386 * Return where in the patch file this hunk began, for error messages.
1387 */
1388LINENUM
1389pch_hunk_beg(void)
1390{
1391	return p_hunk_beg;
1392}
1393
1394/*
1395 * Apply an ed script by feeding ed itself.
1396 */
1397void
1398do_ed_script(void)
1399{
1400	char	*t;
1401	long	beginning_of_this_line;
1402	FILE	*pipefp = NULL;
1403
1404	if (!skip_rest_of_patch) {
1405		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1406			unlink(TMPOUTNAME);
1407			fatal("can't create temp file %s", TMPOUTNAME);
1408		}
1409		snprintf(buf, buf_size, "%s%s%s", _PATH_ED,
1410		    verbose ? " " : " -s ", TMPOUTNAME);
1411		pipefp = popen(buf, "w");
1412	}
1413	for (;;) {
1414		beginning_of_this_line = ftell(pfp);
1415		if (pgets(true) == 0) {
1416			next_intuit_at(beginning_of_this_line, p_input_line);
1417			break;
1418		}
1419		p_input_line++;
1420		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1421			;
1422		/* POSIX defines allowed commands as {a,c,d,i,s} */
1423		if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
1424		    *t == 'd' || *t == 'i' || *t == 's')) {
1425			if (pipefp != NULL)
1426				fputs(buf, pipefp);
1427			if (*t != 'd') {
1428				while (pgets(true)) {
1429					p_input_line++;
1430					if (pipefp != NULL)
1431						fputs(buf, pipefp);
1432					if (strEQ(buf, ".\n"))
1433						break;
1434				}
1435			}
1436		} else {
1437			next_intuit_at(beginning_of_this_line, p_input_line);
1438			break;
1439		}
1440	}
1441	if (pipefp == NULL)
1442		return;
1443	fprintf(pipefp, "w\n");
1444	fprintf(pipefp, "q\n");
1445	fflush(pipefp);
1446	pclose(pipefp);
1447	ignore_signals();
1448	if (!check_only) {
1449		if (move_file(TMPOUTNAME, outname) < 0) {
1450			toutkeep = true;
1451			chmod(TMPOUTNAME, filemode);
1452		} else
1453			chmod(outname, filemode);
1454	}
1455	set_signals(1);
1456}
1457
1458/*
1459 * Choose the name of the file to be patched based on POSIX rules.
1460 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1461 *       if the user specified --posix or set POSIXLY_CORRECT.
1462 */
1463static char *
1464posix_name(const struct file_name *names, bool assume_exists)
1465{
1466	char *path = NULL;
1467	int i;
1468
1469	/*
1470	 * POSIX states that the filename will be chosen from one
1471	 * of the old, new and index names (in that order) if
1472	 * the file exists relative to CWD after -p stripping.
1473	 */
1474	for (i = 0; i < MAX_FILE; i++) {
1475		if (names[i].path != NULL && names[i].exists) {
1476			path = names[i].path;
1477			break;
1478		}
1479	}
1480	if (path == NULL && !assume_exists) {
1481		/*
1482		 * No files found, look for something we can checkout from
1483		 * RCS/SCCS dirs.  Same order as above.
1484		 */
1485		for (i = 0; i < MAX_FILE; i++) {
1486			if (names[i].path != NULL &&
1487			    (path = checked_in(names[i].path)) != NULL)
1488				break;
1489		}
1490		/*
1491		 * Still no match?  Check to see if the diff could be creating
1492		 * a new file.
1493		 */
1494		if (path == NULL && ok_to_create_file &&
1495		    names[NEW_FILE].path != NULL)
1496			path = names[NEW_FILE].path;
1497	}
1498
1499	return path ? savestr(path) : NULL;
1500}
1501
1502static char *
1503compare_names(const struct file_name *names, bool assume_exists, int phase)
1504{
1505	size_t min_components, min_baselen, min_len, tmp;
1506	char *best = NULL;
1507	char *path;
1508	int i;
1509
1510	/*
1511	 * The "best" name is the one with the fewest number of path
1512	 * components, the shortest basename length, and the shortest
1513	 * overall length (in that order).  We only use the Index: file
1514	 * if neither of the old or new files could be intuited from
1515	 * the diff header.
1516	 */
1517	min_components = min_baselen = min_len = SIZE_MAX;
1518	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1519		path = names[i].path;
1520		if (path == NULL ||
1521		    (phase == 1 && !names[i].exists && !assume_exists) ||
1522		    (phase == 2 && checked_in(path) == NULL))
1523			continue;
1524		if ((tmp = num_components(path)) > min_components)
1525			continue;
1526		if (tmp < min_components) {
1527			min_components = tmp;
1528			best = path;
1529		}
1530		if ((tmp = strlen(basename(path))) > min_baselen)
1531			continue;
1532		if (tmp < min_baselen) {
1533			min_baselen = tmp;
1534			best = path;
1535		}
1536		if ((tmp = strlen(path)) > min_len)
1537			continue;
1538		min_len = tmp;
1539		best = path;
1540	}
1541	return best;
1542}
1543
1544/*
1545 * Choose the name of the file to be patched based the "best" one
1546 * available.
1547 */
1548static char *
1549best_name(const struct file_name *names, bool assume_exists)
1550{
1551	char *best;
1552
1553	best = compare_names(names, assume_exists, 1);
1554	if (best == NULL) {
1555		best = compare_names(names, assume_exists, 2);
1556		/*
1557		 * Still no match?  Check to see if the diff could be creating
1558		 * a new file.
1559		 */
1560		if (best == NULL && ok_to_create_file &&
1561		    names[NEW_FILE].path != NULL)
1562			best = names[NEW_FILE].path;
1563	}
1564
1565	return best ? savestr(best) : NULL;
1566}
1567
1568static size_t
1569num_components(const char *path)
1570{
1571	size_t n;
1572	const char *cp;
1573
1574	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1575		while (*cp == '/')
1576			cp++;		/* skip consecutive slashes */
1577	}
1578	return n;
1579}
1580