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