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