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