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