pch.c revision 275840
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.43 2014/11/18 17:03:35 tobias Exp $
28 * $FreeBSD: stable/10/usr.bin/patch/pch.c 275840 2014-12-16 21:05:28Z 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;
322			     *t && !isspace((unsigned char)*t); t++)
323				;
324			*t = '\0';
325			if (*revision == '\0') {
326				free(revision);
327				revision = NULL;
328			}
329		} else if (strnEQ(s, "==== ", 5)) {
330			/* Perforce-style diffs. */
331			if ((t = strstr(s + 5, " - ")) != NULL)
332				p4_fetchname(&names[NEW_FILE], t + 3);
333			p4_fetchname(&names[OLD_FILE], s + 5);
334		}
335		if ((!diff_type || diff_type == ED_DIFF) &&
336		    first_command_line >= 0L &&
337		    strEQ(s, ".\n")) {
338			p_indent = indent;
339			p_start = first_command_line;
340			p_sline = fcl_line;
341			retval = ED_DIFF;
342			goto scan_exit;
343		}
344		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
345			if (strnEQ(s + 4, "0,0", 3))
346				ok_to_create_file = true;
347			p_indent = indent;
348			p_start = this_line;
349			p_sline = p_input_line;
350			retval = UNI_DIFF;
351			goto scan_exit;
352		}
353		stars_this_line = strnEQ(s, "********", 8);
354		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
355		    strnEQ(s, "*** ", 4)) {
356			if (atol(s + 4) == 0)
357				ok_to_create_file = true;
358			/*
359			 * If this is a new context diff the character just
360			 * before the newline is a '*'.
361			 */
362			while (*s != '\n')
363				s++;
364			p_indent = indent;
365			p_start = previous_line;
366			p_sline = p_input_line - 1;
367			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
368			goto scan_exit;
369		}
370		if ((!diff_type || diff_type == NORMAL_DIFF) &&
371		    last_line_was_command &&
372		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
373			p_start = previous_line;
374			p_sline = p_input_line - 1;
375			p_indent = indent;
376			retval = NORMAL_DIFF;
377			goto scan_exit;
378		}
379	}
380scan_exit:
381	if (retval == UNI_DIFF) {
382		/* unswap old and new */
383		struct file_name tmp = names[OLD_FILE];
384		names[OLD_FILE] = names[NEW_FILE];
385		names[NEW_FILE] = tmp;
386	}
387	if (filearg[0] == NULL) {
388		if (posix)
389			filearg[0] = posix_name(names, ok_to_create_file);
390		else {
391			/* Ignore the Index: name for context diffs, like GNU */
392			if (names[OLD_FILE].path != NULL ||
393			    names[NEW_FILE].path != NULL) {
394				free(names[INDEX_FILE].path);
395				names[INDEX_FILE].path = NULL;
396			}
397			filearg[0] = best_name(names, ok_to_create_file);
398		}
399	}
400
401	free(bestguess);
402	bestguess = NULL;
403	if (filearg[0] != NULL)
404		bestguess = savestr(filearg[0]);
405	else if (!ok_to_create_file) {
406		/*
407		 * We don't want to create a new file but we need a
408		 * filename to set bestguess.  Avoid setting filearg[0]
409		 * so the file is not created automatically.
410		 */
411		if (posix)
412			bestguess = posix_name(names, true);
413		else
414			bestguess = best_name(names, true);
415	}
416	free(names[OLD_FILE].path);
417	free(names[NEW_FILE].path);
418	free(names[INDEX_FILE].path);
419	return retval;
420}
421
422/*
423 * Remember where this patch ends so we know where to start up again.
424 */
425static void
426next_intuit_at(LINENUM file_pos, LINENUM file_line)
427{
428	p_base = file_pos;
429	p_bline = file_line;
430}
431
432/*
433 * Basically a verbose fseek() to the actual diff listing.
434 */
435static void
436skip_to(LINENUM file_pos, LINENUM file_line)
437{
438	size_t	len;
439
440	if (p_base > file_pos)
441		fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
442	if (verbose && p_base < file_pos) {
443		fseek(pfp, p_base, SEEK_SET);
444		say("The text leading up to this was:\n--------------------------\n");
445		while (ftell(pfp) < file_pos) {
446			len = pgets(false);
447			if (len == 0)
448				fatal("Unexpected end of file\n");
449			say("|%s", buf);
450		}
451		say("--------------------------\n");
452	} else
453		fseek(pfp, file_pos, SEEK_SET);
454	p_input_line = file_line - 1;
455}
456
457/* Make this a function for better debugging.  */
458static void
459malformed(void)
460{
461	fatal("malformed patch at line %ld: %s", p_input_line, buf);
462	/* about as informative as "Syntax error" in C */
463}
464
465/*
466 * True if the line has been discarded (i.e. it is a line saying
467 *  "\ No newline at end of file".)
468 */
469static bool
470remove_special_line(void)
471{
472	int	c;
473
474	c = fgetc(pfp);
475	if (c == '\\') {
476		do {
477			c = fgetc(pfp);
478		} while (c != EOF && c != '\n');
479
480		return true;
481	}
482	if (c != EOF)
483		fseek(pfp, -1L, SEEK_CUR);
484
485	return false;
486}
487
488/*
489 * True if there is more of the current diff listing to process.
490 */
491bool
492another_hunk(void)
493{
494	long	line_beginning;			/* file pos of the current line */
495	LINENUM	repl_beginning;			/* index of --- line */
496	LINENUM	fillcnt;			/* #lines of missing ptrn or repl */
497	LINENUM	fillsrc;			/* index of first line to copy */
498	LINENUM	filldst;			/* index of first missing line */
499	bool	ptrn_spaces_eaten;		/* ptrn was slightly misformed */
500	bool	repl_could_be_missing;		/* no + or ! lines in this hunk */
501	bool	repl_missing;			/* we are now backtracking */
502	long	repl_backtrack_position;	/* file pos of first repl line */
503	LINENUM	repl_patch_line;		/* input line number for same */
504	LINENUM	ptrn_copiable;			/* # of copiable lines in ptrn */
505	char	*s;
506	size_t	len;
507	int	context = 0;
508
509	while (p_end >= 0) {
510		if (p_end == p_efake)
511			p_end = p_bfake;	/* don't free twice */
512		else
513			free(p_line[p_end]);
514		p_end--;
515	}
516	p_efake = -1;
517
518	p_max = hunkmax;	/* gets reduced when --- found */
519	if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
520		line_beginning = ftell(pfp);
521		repl_beginning = 0;
522		fillcnt = 0;
523		fillsrc = 0;
524		filldst = 0;
525		ptrn_spaces_eaten = false;
526		repl_could_be_missing = true;
527		repl_missing = false;
528		repl_backtrack_position = 0;
529		repl_patch_line = 0;
530		ptrn_copiable = 0;
531
532		len = pgets(true);
533		p_input_line++;
534		if (len == 0 || strnNE(buf, "********", 8)) {
535			next_intuit_at(line_beginning, p_input_line);
536			return false;
537		}
538		p_context = 100;
539		p_hunk_beg = p_input_line + 1;
540		while (p_end < p_max) {
541			line_beginning = ftell(pfp);
542			len = pgets(true);
543			p_input_line++;
544			if (len == 0) {
545				if (p_max - p_end < 4) {
546					/* assume blank lines got chopped */
547					strlcpy(buf, "  \n", buf_size);
548				} else {
549					if (repl_beginning && repl_could_be_missing) {
550						repl_missing = true;
551						goto hunk_done;
552					}
553					fatal("unexpected end of file in patch\n");
554				}
555			}
556			p_end++;
557			if (p_end >= hunkmax)
558				fatal("Internal error: hunk larger than hunk "
559				    "buffer size");
560			p_char[p_end] = *buf;
561			p_line[p_end] = NULL;
562			switch (*buf) {
563			case '*':
564				if (strnEQ(buf, "********", 8)) {
565					if (repl_beginning && repl_could_be_missing) {
566						repl_missing = true;
567						goto hunk_done;
568					} else
569						fatal("unexpected end of hunk "
570						    "at line %ld\n",
571						    p_input_line);
572				}
573				if (p_end != 0) {
574					if (repl_beginning && repl_could_be_missing) {
575						repl_missing = true;
576						goto hunk_done;
577					}
578					fatal("unexpected *** at line %ld: %s",
579					    p_input_line, buf);
580				}
581				context = 0;
582				p_line[p_end] = savestr(buf);
583				if (out_of_mem) {
584					p_end--;
585					return false;
586				}
587				for (s = buf;
588				     *s && !isdigit((unsigned char)*s); s++)
589					;
590				if (!*s)
591					malformed();
592				if (strnEQ(s, "0,0", 3))
593					memmove(s, s + 2, strlen(s + 2) + 1);
594				p_first = (LINENUM) atol(s);
595				while (isdigit((unsigned char)*s))
596					s++;
597				if (*s == ',') {
598					for (;
599					     *s && !isdigit((unsigned char)*s); s++)
600						;
601					if (!*s)
602						malformed();
603					p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
604				} else if (p_first)
605					p_ptrn_lines = 1;
606				else {
607					p_ptrn_lines = 0;
608					p_first = 1;
609				}
610
611				/* we need this much at least */
612				p_max = p_ptrn_lines + 6;
613				while (p_max >= hunkmax)
614					grow_hunkmax();
615				p_max = hunkmax;
616				break;
617			case '-':
618				if (buf[1] == '-') {
619					if (repl_beginning ||
620					    (p_end != p_ptrn_lines + 1 +
621					    (p_char[p_end - 1] == '\n'))) {
622						if (p_end == 1) {
623							/*
624							 * `old' lines were omitted;
625							 * set up to fill them in
626							 * from 'new' context lines.
627							 */
628							p_end = p_ptrn_lines + 1;
629							fillsrc = p_end + 1;
630							filldst = 1;
631							fillcnt = p_ptrn_lines;
632						} else {
633							if (repl_beginning) {
634								if (repl_could_be_missing) {
635									repl_missing = true;
636									goto hunk_done;
637								}
638								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
639								    p_input_line, p_hunk_beg + repl_beginning);
640							} else {
641								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
642								    (p_end <= p_ptrn_lines
643								    ? "Premature"
644								    : "Overdue"),
645								    p_input_line, p_hunk_beg);
646							}
647						}
648					}
649					repl_beginning = p_end;
650					repl_backtrack_position = ftell(pfp);
651					repl_patch_line = p_input_line;
652					p_line[p_end] = savestr(buf);
653					if (out_of_mem) {
654						p_end--;
655						return false;
656					}
657					p_char[p_end] = '=';
658					for (s = buf; *s && !isdigit((unsigned char)*s); s++)
659						;
660					if (!*s)
661						malformed();
662					p_newfirst = (LINENUM) atol(s);
663					while (isdigit((unsigned char)*s))
664						s++;
665					if (*s == ',') {
666						for (; *s && !isdigit((unsigned char)*s); s++)
667							;
668						if (!*s)
669							malformed();
670						p_repl_lines = ((LINENUM) atol(s)) -
671						    p_newfirst + 1;
672					} else if (p_newfirst)
673						p_repl_lines = 1;
674					else {
675						p_repl_lines = 0;
676						p_newfirst = 1;
677					}
678					p_max = p_repl_lines + p_end;
679					if (p_max > MAXHUNKSIZE)
680						fatal("hunk too large (%ld lines) at line %ld: %s",
681						    p_max, p_input_line, buf);
682					while (p_max >= hunkmax)
683						grow_hunkmax();
684					if (p_repl_lines != ptrn_copiable &&
685					    (p_context != 0 || p_repl_lines != 1))
686						repl_could_be_missing = false;
687					break;
688				}
689				goto change_line;
690			case '+':
691			case '!':
692				repl_could_be_missing = false;
693		change_line:
694				if (buf[1] == '\n' && canonicalize)
695					strlcpy(buf + 1, " \n", buf_size - 1);
696				if (!isspace((unsigned char)buf[1]) &&
697				    buf[1] != '>' && buf[1] != '<' &&
698				    repl_beginning && repl_could_be_missing) {
699					repl_missing = true;
700					goto hunk_done;
701				}
702				if (context >= 0) {
703					if (context < p_context)
704						p_context = context;
705					context = -1000;
706				}
707				p_line[p_end] = savestr(buf + 2);
708				if (out_of_mem) {
709					p_end--;
710					return false;
711				}
712				if (p_end == p_ptrn_lines) {
713					if (remove_special_line()) {
714						int	l;
715
716						l = strlen(p_line[p_end]) - 1;
717						(p_line[p_end])[l] = 0;
718					}
719				}
720				break;
721			case '\t':
722			case '\n':	/* assume the 2 spaces got eaten */
723				if (repl_beginning && repl_could_be_missing &&
724				    (!ptrn_spaces_eaten ||
725				    diff_type == NEW_CONTEXT_DIFF)) {
726					repl_missing = true;
727					goto hunk_done;
728				}
729				p_line[p_end] = savestr(buf);
730				if (out_of_mem) {
731					p_end--;
732					return false;
733				}
734				if (p_end != p_ptrn_lines + 1) {
735					ptrn_spaces_eaten |= (repl_beginning != 0);
736					context++;
737					if (!repl_beginning)
738						ptrn_copiable++;
739					p_char[p_end] = ' ';
740				}
741				break;
742			case ' ':
743				if (!isspace((unsigned char)buf[1]) &&
744				    repl_beginning && repl_could_be_missing) {
745					repl_missing = true;
746					goto hunk_done;
747				}
748				context++;
749				if (!repl_beginning)
750					ptrn_copiable++;
751				p_line[p_end] = savestr(buf + 2);
752				if (out_of_mem) {
753					p_end--;
754					return false;
755				}
756				break;
757			default:
758				if (repl_beginning && repl_could_be_missing) {
759					repl_missing = true;
760					goto hunk_done;
761				}
762				malformed();
763			}
764			/* set up p_len for strncmp() so we don't have to */
765			/* assume null termination */
766			if (p_line[p_end])
767				p_len[p_end] = strlen(p_line[p_end]);
768			else
769				p_len[p_end] = 0;
770		}
771
772hunk_done:
773		if (p_end >= 0 && !repl_beginning)
774			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
775
776		if (repl_missing) {
777
778			/* reset state back to just after --- */
779			p_input_line = repl_patch_line;
780			for (p_end--; p_end > repl_beginning; p_end--)
781				free(p_line[p_end]);
782			fseek(pfp, repl_backtrack_position, SEEK_SET);
783
784			/* redundant 'new' context lines were omitted - set */
785			/* up to fill them in from the old file context */
786			if (!p_context && p_repl_lines == 1) {
787				p_repl_lines = 0;
788				p_max--;
789			}
790			fillsrc = 1;
791			filldst = repl_beginning + 1;
792			fillcnt = p_repl_lines;
793			p_end = p_max;
794		} else if (!p_context && fillcnt == 1) {
795			/* the first hunk was a null hunk with no context */
796			/* and we were expecting one line -- fix it up. */
797			while (filldst < p_end) {
798				p_line[filldst] = p_line[filldst + 1];
799				p_char[filldst] = p_char[filldst + 1];
800				p_len[filldst] = p_len[filldst + 1];
801				filldst++;
802			}
803#if 0
804			repl_beginning--;	/* this doesn't need to be fixed */
805#endif
806			p_end--;
807			p_first++;	/* do append rather than insert */
808			fillcnt = 0;
809			p_ptrn_lines = 0;
810		}
811		if (diff_type == CONTEXT_DIFF &&
812		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
813			if (verbose)
814				say("%s\n%s\n%s\n",
815				    "(Fascinating--this is really a new-style context diff but without",
816				    "the telltale extra asterisks on the *** line that usually indicate",
817				    "the new style...)");
818			diff_type = NEW_CONTEXT_DIFF;
819		}
820		/* if there were omitted context lines, fill them in now */
821		if (fillcnt) {
822			p_bfake = filldst;	/* remember where not to free() */
823			p_efake = filldst + fillcnt - 1;
824			while (fillcnt-- > 0) {
825				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
826					fillsrc++;
827				if (fillsrc > p_end)
828					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
829					    p_hunk_beg);
830				p_line[filldst] = p_line[fillsrc];
831				p_char[filldst] = p_char[fillsrc];
832				p_len[filldst] = p_len[fillsrc];
833				fillsrc++;
834				filldst++;
835			}
836			while (fillsrc <= p_end && fillsrc != repl_beginning &&
837			    p_char[fillsrc] != ' ')
838				fillsrc++;
839#ifdef DEBUGGING
840			if (debug & 64)
841				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
842				fillsrc, filldst, repl_beginning, p_end + 1);
843#endif
844			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
845				malformed();
846			if (filldst != p_end + 1 && filldst != repl_beginning)
847				malformed();
848		}
849		if (p_line[p_end] != NULL) {
850			if (remove_special_line()) {
851				p_len[p_end] -= 1;
852				(p_line[p_end])[p_len[p_end]] = 0;
853			}
854		}
855	} else if (diff_type == UNI_DIFF) {
856		LINENUM	fillold;	/* index of old lines */
857		LINENUM	fillnew;	/* index of new lines */
858		char	ch;
859
860		line_beginning = ftell(pfp); /* file pos of the current line */
861		len = pgets(true);
862		p_input_line++;
863		if (len == 0 || strnNE(buf, "@@ -", 4)) {
864			next_intuit_at(line_beginning, p_input_line);
865			return false;
866		}
867		s = buf + 4;
868		if (!*s)
869			malformed();
870		p_first = (LINENUM) atol(s);
871		while (isdigit((unsigned char)*s))
872			s++;
873		if (*s == ',') {
874			p_ptrn_lines = (LINENUM) atol(++s);
875			while (isdigit((unsigned char)*s))
876				s++;
877		} else
878			p_ptrn_lines = 1;
879		if (*s == ' ')
880			s++;
881		if (*s != '+' || !*++s)
882			malformed();
883		p_newfirst = (LINENUM) atol(s);
884		while (isdigit((unsigned char)*s))
885			s++;
886		if (*s == ',') {
887			p_repl_lines = (LINENUM) atol(++s);
888			while (isdigit((unsigned char)*s))
889				s++;
890		} else
891			p_repl_lines = 1;
892		if (*s == ' ')
893			s++;
894		if (*s != '@')
895			malformed();
896		if (!p_ptrn_lines)
897			p_first++;	/* do append rather than insert */
898		p_max = p_ptrn_lines + p_repl_lines + 1;
899		while (p_max >= hunkmax)
900			grow_hunkmax();
901		fillold = 1;
902		fillnew = fillold + p_ptrn_lines;
903		p_end = fillnew + p_repl_lines;
904		snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
905		    p_first + p_ptrn_lines - 1);
906		p_line[0] = savestr(buf);
907		if (out_of_mem) {
908			p_end = -1;
909			return false;
910		}
911		p_char[0] = '*';
912		snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
913		    p_newfirst + p_repl_lines - 1);
914		p_line[fillnew] = savestr(buf);
915		if (out_of_mem) {
916			p_end = 0;
917			return false;
918		}
919		p_char[fillnew++] = '=';
920		p_context = 100;
921		context = 0;
922		p_hunk_beg = p_input_line + 1;
923		while (fillold <= p_ptrn_lines || fillnew <= p_end) {
924			line_beginning = ftell(pfp);
925			len = pgets(true);
926			p_input_line++;
927			if (len == 0) {
928				if (p_max - fillnew < 3) {
929					/* assume blank lines got chopped */
930					strlcpy(buf, " \n", buf_size);
931				} else {
932					fatal("unexpected end of file in patch\n");
933				}
934			}
935			if (*buf == '\t' || *buf == '\n') {
936				ch = ' ';	/* assume the space got eaten */
937				s = savestr(buf);
938			} else {
939				ch = *buf;
940				s = savestr(buf + 1);
941			}
942			if (out_of_mem) {
943				while (--fillnew > p_ptrn_lines)
944					free(p_line[fillnew]);
945				p_end = fillold - 1;
946				return false;
947			}
948			switch (ch) {
949			case '-':
950				if (fillold > p_ptrn_lines) {
951					free(s);
952					p_end = fillnew - 1;
953					malformed();
954				}
955				p_char[fillold] = ch;
956				p_line[fillold] = s;
957				p_len[fillold++] = strlen(s);
958				if (fillold > p_ptrn_lines) {
959					if (remove_special_line()) {
960						p_len[fillold - 1] -= 1;
961						s[p_len[fillold - 1]] = 0;
962					}
963				}
964				break;
965			case '=':
966				ch = ' ';
967				/* FALL THROUGH */
968			case ' ':
969				if (fillold > p_ptrn_lines) {
970					free(s);
971					while (--fillnew > p_ptrn_lines)
972						free(p_line[fillnew]);
973					p_end = fillold - 1;
974					malformed();
975				}
976				context++;
977				p_char[fillold] = ch;
978				p_line[fillold] = s;
979				p_len[fillold++] = strlen(s);
980				s = savestr(s);
981				if (out_of_mem) {
982					while (--fillnew > p_ptrn_lines)
983						free(p_line[fillnew]);
984					p_end = fillold - 1;
985					return false;
986				}
987				if (fillold > p_ptrn_lines) {
988					if (remove_special_line()) {
989						p_len[fillold - 1] -= 1;
990						s[p_len[fillold - 1]] = 0;
991					}
992				}
993				/* FALL THROUGH */
994			case '+':
995				if (fillnew > p_end) {
996					free(s);
997					while (--fillnew > p_ptrn_lines)
998						free(p_line[fillnew]);
999					p_end = fillold - 1;
1000					malformed();
1001				}
1002				p_char[fillnew] = ch;
1003				p_line[fillnew] = s;
1004				p_len[fillnew++] = strlen(s);
1005				if (fillold > p_ptrn_lines) {
1006					if (remove_special_line()) {
1007						p_len[fillnew - 1] -= 1;
1008						s[p_len[fillnew - 1]] = 0;
1009					}
1010				}
1011				break;
1012			default:
1013				p_end = fillnew;
1014				malformed();
1015			}
1016			if (ch != ' ' && context > 0) {
1017				if (context < p_context)
1018					p_context = context;
1019				context = -1000;
1020			}
1021		}		/* while */
1022	} else {		/* normal diff--fake it up */
1023		char	hunk_type;
1024		int	i;
1025		LINENUM	min, max;
1026
1027		line_beginning = ftell(pfp);
1028		p_context = 0;
1029		len = pgets(true);
1030		p_input_line++;
1031		if (len == 0 || !isdigit((unsigned char)*buf)) {
1032			next_intuit_at(line_beginning, p_input_line);
1033			return false;
1034		}
1035		p_first = (LINENUM) atol(buf);
1036		for (s = buf; isdigit((unsigned char)*s); s++)
1037			;
1038		if (*s == ',') {
1039			p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1040			while (isdigit((unsigned char)*s))
1041				s++;
1042		} else
1043			p_ptrn_lines = (*s != 'a');
1044		hunk_type = *s;
1045		if (hunk_type == 'a')
1046			p_first++;	/* do append rather than insert */
1047		min = (LINENUM) atol(++s);
1048		for (; isdigit((unsigned char)*s); s++)
1049			;
1050		if (*s == ',')
1051			max = (LINENUM) atol(++s);
1052		else
1053			max = min;
1054		if (hunk_type == 'd')
1055			min++;
1056		p_end = p_ptrn_lines + 1 + max - min + 1;
1057		if (p_end > MAXHUNKSIZE)
1058			fatal("hunk too large (%ld lines) at line %ld: %s",
1059			    p_end, p_input_line, buf);
1060		while (p_end >= hunkmax)
1061			grow_hunkmax();
1062		p_newfirst = min;
1063		p_repl_lines = max - min + 1;
1064		snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1065		    p_first + p_ptrn_lines - 1);
1066		p_line[0] = savestr(buf);
1067		if (out_of_mem) {
1068			p_end = -1;
1069			return false;
1070		}
1071		p_char[0] = '*';
1072		for (i = 1; i <= p_ptrn_lines; i++) {
1073			len = pgets(true);
1074			p_input_line++;
1075			if (len == 0)
1076				fatal("unexpected end of file in patch at line %ld\n",
1077				    p_input_line);
1078			if (*buf != '<')
1079				fatal("< expected at line %ld of patch\n",
1080				    p_input_line);
1081			p_line[i] = savestr(buf + 2);
1082			if (out_of_mem) {
1083				p_end = i - 1;
1084				return false;
1085			}
1086			p_len[i] = strlen(p_line[i]);
1087			p_char[i] = '-';
1088		}
1089
1090		if (remove_special_line()) {
1091			p_len[i - 1] -= 1;
1092			(p_line[i - 1])[p_len[i - 1]] = 0;
1093		}
1094		if (hunk_type == 'c') {
1095			len = pgets(true);
1096			p_input_line++;
1097			if (len == 0)
1098				fatal("unexpected end of file in patch at line %ld\n",
1099				    p_input_line);
1100			if (*buf != '-')
1101				fatal("--- expected at line %ld of patch\n",
1102				    p_input_line);
1103		}
1104		snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1105		p_line[i] = savestr(buf);
1106		if (out_of_mem) {
1107			p_end = i - 1;
1108			return false;
1109		}
1110		p_char[i] = '=';
1111		for (i++; i <= p_end; i++) {
1112			len = pgets(true);
1113			p_input_line++;
1114			if (len == 0)
1115				fatal("unexpected end of file in patch at line %ld\n",
1116				    p_input_line);
1117			if (*buf != '>')
1118				fatal("> expected at line %ld of patch\n",
1119				    p_input_line);
1120			p_line[i] = savestr(buf + 2);
1121			if (out_of_mem) {
1122				p_end = i - 1;
1123				return false;
1124			}
1125			p_len[i] = strlen(p_line[i]);
1126			p_char[i] = '+';
1127		}
1128
1129		if (remove_special_line()) {
1130			p_len[i - 1] -= 1;
1131			(p_line[i - 1])[p_len[i - 1]] = 0;
1132		}
1133	}
1134	if (reverse)		/* backwards patch? */
1135		if (!pch_swap())
1136			say("Not enough memory to swap next hunk!\n");
1137#ifdef DEBUGGING
1138	if (debug & 2) {
1139		int	i;
1140		char	special;
1141
1142		for (i = 0; i <= p_end; i++) {
1143			if (i == p_ptrn_lines)
1144				special = '^';
1145			else
1146				special = ' ';
1147			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1148			    special, p_line[i]);
1149			fflush(stderr);
1150		}
1151	}
1152#endif
1153	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1154		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1155	return true;
1156}
1157
1158/*
1159 * Input a line from the patch file.
1160 * Worry about indentation if do_indent is true.
1161 * The line is read directly into the buf global variable which
1162 * is resized if necessary in order to hold the complete line.
1163 * Returns the number of characters read including the terminating
1164 * '\n', if any.
1165 */
1166size_t
1167pgets(bool do_indent)
1168{
1169	char *line;
1170	size_t len;
1171	int indent = 0, skipped = 0;
1172
1173	line = fgetln(pfp, &len);
1174	if (line != NULL) {
1175		if (len + 1 > buf_size) {
1176			while (len + 1 > buf_size)
1177				buf_size *= 2;
1178			free(buf);
1179			buf = malloc(buf_size);
1180			if (buf == NULL)
1181				fatal("out of memory\n");
1182		}
1183		if (do_indent == 1 && p_indent) {
1184			for (;
1185			    indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1186			    line++, skipped++) {
1187				if (*line == '\t')
1188					indent += 8 - (indent %7);
1189				else
1190					indent++;
1191			}
1192		}
1193		memcpy(buf, line, len - skipped);
1194		buf[len - skipped] = '\0';
1195	}
1196	return len;
1197}
1198
1199
1200/*
1201 * Reverse the old and new portions of the current hunk.
1202 */
1203bool
1204pch_swap(void)
1205{
1206	char	**tp_line;	/* the text of the hunk */
1207	unsigned short	*tp_len;/* length of each line */
1208	char	*tp_char;	/* +, -, and ! */
1209	LINENUM	i;
1210	LINENUM	n;
1211	bool	blankline = false;
1212	char	*s;
1213
1214	i = p_first;
1215	p_first = p_newfirst;
1216	p_newfirst = i;
1217
1218	/* make a scratch copy */
1219
1220	tp_line = p_line;
1221	tp_len = p_len;
1222	tp_char = p_char;
1223	p_line = NULL;	/* force set_hunkmax to allocate again */
1224	p_len = NULL;
1225	p_char = NULL;
1226	set_hunkmax();
1227	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1228
1229		free(p_line);
1230		p_line = tp_line;
1231		free(p_len);
1232		p_len = tp_len;
1233		free(p_char);
1234		p_char = tp_char;
1235		return false;	/* not enough memory to swap hunk! */
1236	}
1237	/* now turn the new into the old */
1238
1239	i = p_ptrn_lines + 1;
1240	if (tp_char[i] == '\n') {	/* account for possible blank line */
1241		blankline = true;
1242		i++;
1243	}
1244	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1245		if (p_efake <= i)
1246			n = p_end - i + 1;
1247		else
1248			n = -i;
1249		p_efake += n;
1250		p_bfake += n;
1251	}
1252	for (n = 0; i <= p_end; i++, n++) {
1253		p_line[n] = tp_line[i];
1254		p_char[n] = tp_char[i];
1255		if (p_char[n] == '+')
1256			p_char[n] = '-';
1257		p_len[n] = tp_len[i];
1258	}
1259	if (blankline) {
1260		i = p_ptrn_lines + 1;
1261		p_line[n] = tp_line[i];
1262		p_char[n] = tp_char[i];
1263		p_len[n] = tp_len[i];
1264		n++;
1265	}
1266	if (p_char[0] != '=')
1267		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1268		    p_input_line, p_char[0]);
1269	p_char[0] = '*';
1270	for (s = p_line[0]; *s; s++)
1271		if (*s == '-')
1272			*s = '*';
1273
1274	/* now turn the old into the new */
1275
1276	if (p_char[0] != '*')
1277		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1278		    p_input_line, p_char[0]);
1279	tp_char[0] = '=';
1280	for (s = tp_line[0]; *s; s++)
1281		if (*s == '*')
1282			*s = '-';
1283	for (i = 0; n <= p_end; i++, n++) {
1284		p_line[n] = tp_line[i];
1285		p_char[n] = tp_char[i];
1286		if (p_char[n] == '-')
1287			p_char[n] = '+';
1288		p_len[n] = tp_len[i];
1289	}
1290
1291	if (i != p_ptrn_lines + 1)
1292		fatal("Malformed patch at line %ld: expected %ld lines, "
1293		    "got %ld\n",
1294		    p_input_line, p_ptrn_lines + 1, i);
1295
1296	i = p_ptrn_lines;
1297	p_ptrn_lines = p_repl_lines;
1298	p_repl_lines = i;
1299
1300	free(tp_line);
1301	free(tp_len);
1302	free(tp_char);
1303
1304	return true;
1305}
1306
1307/*
1308 * Return the specified line position in the old file of the old context.
1309 */
1310LINENUM
1311pch_first(void)
1312{
1313	return p_first;
1314}
1315
1316/*
1317 * Return the number of lines of old context.
1318 */
1319LINENUM
1320pch_ptrn_lines(void)
1321{
1322	return p_ptrn_lines;
1323}
1324
1325/*
1326 * Return the probable line position in the new file of the first line.
1327 */
1328LINENUM
1329pch_newfirst(void)
1330{
1331	return p_newfirst;
1332}
1333
1334/*
1335 * Return the number of lines in the replacement text including context.
1336 */
1337LINENUM
1338pch_repl_lines(void)
1339{
1340	return p_repl_lines;
1341}
1342
1343/*
1344 * Return the number of lines in the whole hunk.
1345 */
1346LINENUM
1347pch_end(void)
1348{
1349	return p_end;
1350}
1351
1352/*
1353 * Return the number of context lines before the first changed line.
1354 */
1355LINENUM
1356pch_context(void)
1357{
1358	return p_context;
1359}
1360
1361/*
1362 * Return the length of a particular patch line.
1363 */
1364unsigned short
1365pch_line_len(LINENUM line)
1366{
1367	return p_len[line];
1368}
1369
1370/*
1371 * Return the control character (+, -, *, !, etc) for a patch line.
1372 */
1373char
1374pch_char(LINENUM line)
1375{
1376	return p_char[line];
1377}
1378
1379/*
1380 * Return a pointer to a particular patch line.
1381 */
1382char *
1383pfetch(LINENUM line)
1384{
1385	return p_line[line];
1386}
1387
1388/*
1389 * Return where in the patch file this hunk began, for error messages.
1390 */
1391LINENUM
1392pch_hunk_beg(void)
1393{
1394	return p_hunk_beg;
1395}
1396
1397/*
1398 * Apply an ed script by feeding ed itself.
1399 */
1400void
1401do_ed_script(void)
1402{
1403	char	*t;
1404	long	beginning_of_this_line;
1405	FILE	*pipefp = NULL;
1406
1407	if (!skip_rest_of_patch) {
1408		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1409			unlink(TMPOUTNAME);
1410			fatal("can't create temp file %s", TMPOUTNAME);
1411		}
1412		snprintf(buf, buf_size, "%s%s%s", _PATH_ED,
1413		    verbose ? " " : " -s ", TMPOUTNAME);
1414		pipefp = popen(buf, "w");
1415	}
1416	for (;;) {
1417		beginning_of_this_line = ftell(pfp);
1418		if (pgets(true) == 0) {
1419			next_intuit_at(beginning_of_this_line, p_input_line);
1420			break;
1421		}
1422		p_input_line++;
1423		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1424			;
1425		/* POSIX defines allowed commands as {a,c,d,i,s} */
1426		if (isdigit((unsigned char)*buf) &&
1427		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1428			if (pipefp != NULL)
1429				fputs(buf, pipefp);
1430			if (*t != 'd') {
1431				while (pgets(true)) {
1432					p_input_line++;
1433					if (pipefp != NULL)
1434						fputs(buf, pipefp);
1435					if (strEQ(buf, ".\n"))
1436						break;
1437				}
1438			}
1439		} else {
1440			next_intuit_at(beginning_of_this_line, p_input_line);
1441			break;
1442		}
1443	}
1444	if (pipefp == NULL)
1445		return;
1446	fprintf(pipefp, "w\n");
1447	fprintf(pipefp, "q\n");
1448	fflush(pipefp);
1449	pclose(pipefp);
1450	ignore_signals();
1451	if (!check_only) {
1452		if (move_file(TMPOUTNAME, outname) < 0) {
1453			toutkeep = true;
1454			chmod(TMPOUTNAME, filemode);
1455		} else
1456			chmod(outname, filemode);
1457	}
1458	set_signals(1);
1459}
1460
1461/*
1462 * Choose the name of the file to be patched based on POSIX rules.
1463 * NOTE: the POSIX rules are amazingly stupid and we only follow them
1464 *       if the user specified --posix or set POSIXLY_CORRECT.
1465 */
1466static char *
1467posix_name(const struct file_name *names, bool assume_exists)
1468{
1469	char *path = NULL;
1470	int i;
1471
1472	/*
1473	 * POSIX states that the filename will be chosen from one
1474	 * of the old, new and index names (in that order) if
1475	 * the file exists relative to CWD after -p stripping.
1476	 */
1477	for (i = 0; i < MAX_FILE; i++) {
1478		if (names[i].path != NULL && names[i].exists) {
1479			path = names[i].path;
1480			break;
1481		}
1482	}
1483	if (path == NULL && !assume_exists) {
1484		/*
1485		 * No files found, look for something we can checkout from
1486		 * RCS/SCCS dirs.  Same order as above.
1487		 */
1488		for (i = 0; i < MAX_FILE; i++) {
1489			if (names[i].path != NULL &&
1490			    (path = checked_in(names[i].path)) != NULL)
1491				break;
1492		}
1493		/*
1494		 * Still no match?  Check to see if the diff could be creating
1495		 * a new file.
1496		 */
1497		if (path == NULL && ok_to_create_file &&
1498		    names[NEW_FILE].path != NULL)
1499			path = names[NEW_FILE].path;
1500	}
1501
1502	return path ? savestr(path) : NULL;
1503}
1504
1505static char *
1506compare_names(const struct file_name *names, bool assume_exists, int phase)
1507{
1508	size_t min_components, min_baselen, min_len, tmp;
1509	char *best = NULL;
1510	char *path;
1511	int i;
1512
1513	/*
1514	 * The "best" name is the one with the fewest number of path
1515	 * components, the shortest basename length, and the shortest
1516	 * overall length (in that order).  We only use the Index: file
1517	 * if neither of the old or new files could be intuited from
1518	 * the diff header.
1519	 */
1520	min_components = min_baselen = min_len = SIZE_MAX;
1521	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1522		path = names[i].path;
1523		if (path == NULL ||
1524		    (phase == 1 && !names[i].exists && !assume_exists) ||
1525		    (phase == 2 && checked_in(path) == NULL))
1526			continue;
1527		if ((tmp = num_components(path)) > min_components)
1528			continue;
1529		if (tmp < min_components) {
1530			min_components = tmp;
1531			best = path;
1532		}
1533		if ((tmp = strlen(basename(path))) > min_baselen)
1534			continue;
1535		if (tmp < min_baselen) {
1536			min_baselen = tmp;
1537			best = path;
1538		}
1539		if ((tmp = strlen(path)) > min_len)
1540			continue;
1541		min_len = tmp;
1542		best = path;
1543	}
1544	return best;
1545}
1546
1547/*
1548 * Choose the name of the file to be patched based the "best" one
1549 * available.
1550 */
1551static char *
1552best_name(const struct file_name *names, bool assume_exists)
1553{
1554	char *best;
1555
1556	best = compare_names(names, assume_exists, 1);
1557	if (best == NULL) {
1558		best = compare_names(names, assume_exists, 2);
1559		/*
1560		 * Still no match?  Check to see if the diff could be creating
1561		 * a new file.
1562		 */
1563		if (best == NULL && ok_to_create_file &&
1564		    names[NEW_FILE].path != NULL)
1565			best = names[NEW_FILE].path;
1566	}
1567
1568	return best ? savestr(best) : NULL;
1569}
1570
1571static size_t
1572num_components(const char *path)
1573{
1574	size_t n;
1575	const char *cp;
1576
1577	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1578		while (*cp == '/')
1579			cp++;		/* skip consecutive slashes */
1580	}
1581	return n;
1582}
1583