xref: /openbsd/usr.bin/patch/pch.c (revision a6445c1d)
1 /*	$OpenBSD: pch.c,v 1.45 2014/11/25 10:26:07 tobias 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 off_t	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 off_t	p_base;		/* where to intuit this time */
62 static LINENUM	p_bline;	/* line # of p_base */
63 static off_t	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(off_t, LINENUM);
74 static void	skip_to(off_t, 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 static LINENUM	strtolinenum(char *, char **);
80 
81 /*
82  * Prepare to look for the next patch in the patch file.
83  */
84 void
85 re_patch(void)
86 {
87 	p_first = 0;
88 	p_newfirst = 0;
89 	p_ptrn_lines = 0;
90 	p_repl_lines = 0;
91 	p_end = (LINENUM) - 1;
92 	p_max = 0;
93 	p_indent = 0;
94 }
95 
96 /*
97  * Open the patch file at the beginning of time.
98  */
99 void
100 open_patch_file(const char *filename)
101 {
102 	struct stat filestat;
103 
104 	if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
105 		pfp = fopen(TMPPATNAME, "w");
106 		if (pfp == NULL)
107 			pfatal("can't create %s", TMPPATNAME);
108 		while (fgets(buf, sizeof buf, stdin) != NULL)
109 			fputs(buf, pfp);
110 		fclose(pfp);
111 		filename = TMPPATNAME;
112 	}
113 	pfp = fopen(filename, "r");
114 	if (pfp == NULL)
115 		pfatal("patch file %s not found", filename);
116 	if (fstat(fileno(pfp), &filestat))
117 		pfatal("can't stat %s", filename);
118 	p_filesize = filestat.st_size;
119 	next_intuit_at(0, 1L);	/* start at the beginning */
120 	set_hunkmax();
121 }
122 
123 /*
124  * Make sure our dynamically realloced tables are malloced to begin with.
125  */
126 void
127 set_hunkmax(void)
128 {
129 	if (p_line == NULL)
130 		p_line = calloc((size_t) hunkmax, sizeof(char *));
131 	if (p_len == NULL)
132 		p_len = calloc((size_t) hunkmax, sizeof(short));
133 	if (p_char == NULL)
134 		p_char = calloc((size_t) hunkmax, sizeof(char));
135 }
136 
137 /*
138  * Enlarge the arrays containing the current hunk of patch.
139  */
140 static void
141 grow_hunkmax(void)
142 {
143 	int		new_hunkmax;
144 	char		**new_p_line;
145 	short		*new_p_len;
146 	char		*new_p_char;
147 
148 	new_hunkmax = hunkmax * 2;
149 
150 	if (p_line == NULL || p_len == NULL || p_char == NULL)
151 		fatal("Internal memory allocation error\n");
152 
153 	new_p_line = realloc(p_line, new_hunkmax * sizeof(char *));
154 	if (new_p_line == NULL)
155 		free(p_line);
156 
157 	new_p_len = realloc(p_len, new_hunkmax * sizeof(short));
158 	if (new_p_len == NULL)
159 		free(p_len);
160 
161 	new_p_char = realloc(p_char, new_hunkmax * sizeof(char));
162 	if (new_p_char == NULL)
163 		free(p_char);
164 
165 	p_char = new_p_char;
166 	p_len = new_p_len;
167 	p_line = new_p_line;
168 
169 	if (p_line != NULL && p_len != NULL && p_char != NULL) {
170 		hunkmax = new_hunkmax;
171 		return;
172 	}
173 
174 	if (!using_plan_a)
175 		fatal("out of memory\n");
176 	out_of_mem = true;	/* whatever is null will be allocated again */
177 				/* from within plan_a(), of all places */
178 }
179 
180 /* True if the remainder of the patch file contains a diff of some sort. */
181 
182 bool
183 there_is_another_patch(void)
184 {
185 	bool exists = false;
186 
187 	if (p_base != 0 && p_base >= p_filesize) {
188 		if (verbose)
189 			say("done\n");
190 		return false;
191 	}
192 	if (verbose)
193 		say("Hmm...");
194 	diff_type = intuit_diff_type();
195 	if (!diff_type) {
196 		if (p_base != 0) {
197 			if (verbose)
198 				say("  Ignoring the trailing garbage.\ndone\n");
199 		} else
200 			say("  I can't seem to find a patch in there anywhere.\n");
201 		return false;
202 	}
203 	if (verbose)
204 		say("  %sooks like %s to me...\n",
205 		    (p_base == 0 ? "L" : "The next patch l"),
206 		    diff_type == UNI_DIFF ? "a unified diff" :
207 		    diff_type == CONTEXT_DIFF ? "a context diff" :
208 		diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
209 		    diff_type == NORMAL_DIFF ? "a normal diff" :
210 		    "an ed script");
211 	if (p_indent && verbose)
212 		say("(Patch is indented %d space%s.)\n", p_indent,
213 		    p_indent == 1 ? "" : "s");
214 	skip_to(p_start, p_sline);
215 	while (filearg[0] == NULL) {
216 		if (force || batch) {
217 			say("No file to patch.  Skipping...\n");
218 			filearg[0] = savestr(bestguess);
219 			skip_rest_of_patch = true;
220 			return true;
221 		}
222 		ask("File to patch: ");
223 		if (*buf != '\n') {
224 			free(bestguess);
225 			bestguess = savestr(buf);
226 			filearg[0] = fetchname(buf, &exists, 0);
227 		}
228 		if (!exists) {
229 			ask("No file found--skip this patch? [n] ");
230 			if (*buf != 'y')
231 				continue;
232 			if (verbose)
233 				say("Skipping patch...\n");
234 			free(filearg[0]);
235 			filearg[0] = fetchname(bestguess, &exists, 0);
236 			skip_rest_of_patch = true;
237 			return true;
238 		}
239 	}
240 	return true;
241 }
242 
243 /* Determine what kind of diff is in the remaining part of the patch file. */
244 
245 static int
246 intuit_diff_type(void)
247 {
248 	off_t	this_line = 0, previous_line;
249 	off_t	first_command_line = -1;
250 	LINENUM	fcl_line = -1;
251 	bool	last_line_was_command = false, this_is_a_command = false;
252 	bool	stars_last_line = false, stars_this_line = false;
253 	char	*s, *t;
254 	int	indent, retval;
255 	struct file_name names[MAX_FILE];
256 
257 	memset(names, 0, sizeof(names));
258 	ok_to_create_file = false;
259 	fseeko(pfp, p_base, SEEK_SET);
260 	p_input_line = p_bline - 1;
261 	for (;;) {
262 		previous_line = this_line;
263 		last_line_was_command = this_is_a_command;
264 		stars_last_line = stars_this_line;
265 		this_line = ftello(pfp);
266 		indent = 0;
267 		p_input_line++;
268 		if (fgets(buf, sizeof buf, pfp) == NULL) {
269 			if (first_command_line >= 0) {
270 				/* nothing but deletes!? */
271 				p_start = first_command_line;
272 				p_sline = fcl_line;
273 				retval = ED_DIFF;
274 				goto scan_exit;
275 			} else {
276 				p_start = this_line;
277 				p_sline = p_input_line;
278 				retval = 0;
279 				goto scan_exit;
280 			}
281 		}
282 		for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
283 			if (*s == '\t')
284 				indent += 8 - (indent % 8);
285 			else
286 				indent++;
287 		}
288 		for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
289 			;
290 		this_is_a_command = (isdigit((unsigned char)*s) &&
291 		    (*t == 'd' || *t == 'c' || *t == 'a'));
292 		if (first_command_line < 0 && this_is_a_command) {
293 			first_command_line = this_line;
294 			fcl_line = p_input_line;
295 			p_indent = indent;	/* assume this for now */
296 		}
297 		if (!stars_last_line && strnEQ(s, "*** ", 4))
298 			names[OLD_FILE].path = fetchname(s + 4,
299 			    &names[OLD_FILE].exists, strippath);
300 		else if (strnEQ(s, "--- ", 4))
301 			names[NEW_FILE].path = fetchname(s + 4,
302 			    &names[NEW_FILE].exists, strippath);
303 		else if (strnEQ(s, "+++ ", 4))
304 			/* pretend it is the old name */
305 			names[OLD_FILE].path = fetchname(s + 4,
306 			    &names[OLD_FILE].exists, strippath);
307 		else if (strnEQ(s, "Index:", 6))
308 			names[INDEX_FILE].path = fetchname(s + 6,
309 			    &names[INDEX_FILE].exists, strippath);
310 		else if (strnEQ(s, "Prereq:", 7)) {
311 			for (t = s + 7; isspace((unsigned char)*t); t++)
312 				;
313 			revision = savestr(t);
314 			for (t = revision;
315 			    *t && !isspace((unsigned char)*t); t++)
316 				;
317 			*t = '\0';
318 			if (*revision == '\0') {
319 				free(revision);
320 				revision = NULL;
321 			}
322 		}
323 		if ((!diff_type || diff_type == ED_DIFF) &&
324 		    first_command_line >= 0 &&
325 		    strEQ(s, ".\n")) {
326 			p_indent = indent;
327 			p_start = first_command_line;
328 			p_sline = fcl_line;
329 			retval = ED_DIFF;
330 			goto scan_exit;
331 		}
332 		if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
333 			if (strnEQ(s + 4, "0,0", 3))
334 				ok_to_create_file = true;
335 			p_indent = indent;
336 			p_start = this_line;
337 			p_sline = p_input_line;
338 			retval = UNI_DIFF;
339 			goto scan_exit;
340 		}
341 		stars_this_line = strnEQ(s, "********", 8);
342 		if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
343 		    strnEQ(s, "*** ", 4)) {
344 			if (strtolinenum(s + 4, &s) == 0)
345 				ok_to_create_file = true;
346 			/*
347 			 * If this is a new context diff the character just
348 			 * at the end of the line is a '*'.
349 			 */
350 			while (*s && *s != '\n')
351 				s++;
352 			p_indent = indent;
353 			p_start = previous_line;
354 			p_sline = p_input_line - 1;
355 			retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
356 			goto scan_exit;
357 		}
358 		if ((!diff_type || diff_type == NORMAL_DIFF) &&
359 		    last_line_was_command &&
360 		    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
361 			p_start = previous_line;
362 			p_sline = p_input_line - 1;
363 			p_indent = indent;
364 			retval = NORMAL_DIFF;
365 			goto scan_exit;
366 		}
367 	}
368 scan_exit:
369 	if (retval == UNI_DIFF) {
370 		/* unswap old and new */
371 		struct file_name tmp = names[OLD_FILE];
372 		names[OLD_FILE] = names[NEW_FILE];
373 		names[NEW_FILE] = tmp;
374 	}
375 	if (filearg[0] == NULL) {
376 		if (posix)
377 			filearg[0] = posix_name(names, ok_to_create_file);
378 		else {
379 			/* Ignore the Index: name for context diffs, like GNU */
380 			if (names[OLD_FILE].path != NULL ||
381 			    names[NEW_FILE].path != NULL) {
382 				free(names[INDEX_FILE].path);
383 				names[INDEX_FILE].path = NULL;
384 			}
385 			filearg[0] = best_name(names, ok_to_create_file);
386 		}
387 	}
388 
389 	free(bestguess);
390 	bestguess = NULL;
391 	if (filearg[0] != NULL)
392 		bestguess = savestr(filearg[0]);
393 	else if (!ok_to_create_file) {
394 		/*
395 		 * We don't want to create a new file but we need a
396 		 * filename to set bestguess.  Avoid setting filearg[0]
397 		 * so the file is not created automatically.
398 		 */
399 		if (posix)
400 			bestguess = posix_name(names, true);
401 		else
402 			bestguess = best_name(names, true);
403 	}
404 	free(names[OLD_FILE].path);
405 	free(names[NEW_FILE].path);
406 	free(names[INDEX_FILE].path);
407 	return retval;
408 }
409 
410 /*
411  * Remember where this patch ends so we know where to start up again.
412  */
413 static void
414 next_intuit_at(off_t file_pos, LINENUM file_line)
415 {
416 	p_base = file_pos;
417 	p_bline = file_line;
418 }
419 
420 /*
421  * Basically a verbose fseeko() to the actual diff listing.
422  */
423 static void
424 skip_to(off_t file_pos, LINENUM file_line)
425 {
426 	char	*ret;
427 
428 	if (p_base > file_pos)
429 		fatal("Internal error: seek %lld>%lld\n",
430 		    (long long)p_base, (long long)file_pos);
431 	if (verbose && p_base < file_pos) {
432 		fseeko(pfp, p_base, SEEK_SET);
433 		say("The text leading up to this was:\n--------------------------\n");
434 		while (ftello(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 		fseeko(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 		fseeko(pfp, -1, 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 	off_t	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 	off_t	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 = ftello(pfp);
509 		repl_beginning = 0;
510 		fillcnt = 0;
511 		fillsrc = 0;
512 		ptrn_spaces_eaten = false;
513 		repl_could_be_missing = true;
514 		repl_missing = false;
515 		repl_backtrack_position = 0;
516 		repl_patch_line = 0;
517 		ptrn_copiable = 0;
518 
519 		ret = pgets(buf, sizeof buf, pfp);
520 		p_input_line++;
521 		if (ret == NULL || strnNE(buf, "********", 8)) {
522 			next_intuit_at(line_beginning, p_input_line);
523 			return false;
524 		}
525 		p_context = 100;
526 		p_hunk_beg = p_input_line + 1;
527 		while (p_end < p_max) {
528 			line_beginning = ftello(pfp);
529 			ret = pgets(buf, sizeof buf, pfp);
530 			p_input_line++;
531 			if (ret == NULL) {
532 				if (p_max - p_end < 4) {
533 					/* assume blank lines got chopped */
534 					strlcpy(buf, "  \n", sizeof buf);
535 				} else {
536 					if (repl_beginning && repl_could_be_missing) {
537 						repl_missing = true;
538 						goto hunk_done;
539 					}
540 					fatal("unexpected end of file in patch\n");
541 				}
542 			}
543 			p_end++;
544 			if (p_end >= hunkmax)
545 				fatal("Internal error: hunk larger than hunk "
546 				    "buffer size");
547 			p_char[p_end] = *buf;
548 			p_line[p_end] = NULL;
549 			switch (*buf) {
550 			case '*':
551 				if (strnEQ(buf, "********", 8)) {
552 					if (repl_beginning && repl_could_be_missing) {
553 						repl_missing = true;
554 						goto hunk_done;
555 					} else
556 						fatal("unexpected end of hunk "
557 						    "at line %ld\n",
558 						    p_input_line);
559 				}
560 				if (p_end != 0) {
561 					if (repl_beginning && repl_could_be_missing) {
562 						repl_missing = true;
563 						goto hunk_done;
564 					}
565 					fatal("unexpected *** at line %ld: %s",
566 					    p_input_line, buf);
567 				}
568 				context = 0;
569 				p_line[p_end] = savestr(buf);
570 				if (out_of_mem) {
571 					p_end--;
572 					return false;
573 				}
574 				for (s = buf;
575 				    *s && !isdigit((unsigned char)*s); s++)
576 					;
577 				if (!*s)
578 					malformed();
579 				if (strnEQ(s, "0,0", 3))
580 					memmove(s, s + 2, strlen(s + 2) + 1);
581 				p_first = strtolinenum(s, &s);
582 				if (*s == ',') {
583 					for (; *s && !isdigit((unsigned char)*s); s++)
584 						;
585 					if (!*s)
586 						malformed();
587 					p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
588 				} else if (p_first)
589 					p_ptrn_lines = 1;
590 				else {
591 					p_ptrn_lines = 0;
592 					p_first = 1;
593 				}
594 
595 				/* we need this much at least */
596 				p_max = p_ptrn_lines + 6;
597 				while (p_max >= hunkmax)
598 					grow_hunkmax();
599 				p_max = hunkmax;
600 				break;
601 			case '-':
602 				if (buf[1] == '-') {
603 					if (repl_beginning ||
604 					    (p_end != p_ptrn_lines + 1 +
605 					    (p_char[p_end - 1] == '\n'))) {
606 						if (p_end == 1) {
607 							/*
608 							 * `old' lines were omitted;
609 							 * set up to fill them in
610 							 * from 'new' context lines.
611 							 */
612 							p_end = p_ptrn_lines + 1;
613 							fillsrc = p_end + 1;
614 							filldst = 1;
615 							fillcnt = p_ptrn_lines;
616 						} else {
617 							if (repl_beginning) {
618 								if (repl_could_be_missing) {
619 									repl_missing = true;
620 									goto hunk_done;
621 								}
622 								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
623 								    p_input_line, p_hunk_beg + repl_beginning);
624 							} else {
625 								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
626 								    (p_end <= p_ptrn_lines
627 								    ? "Premature"
628 								    : "Overdue"),
629 								    p_input_line, p_hunk_beg);
630 							}
631 						}
632 					}
633 					repl_beginning = p_end;
634 					repl_backtrack_position = ftello(pfp);
635 					repl_patch_line = p_input_line;
636 					p_line[p_end] = savestr(buf);
637 					if (out_of_mem) {
638 						p_end--;
639 						return false;
640 					}
641 					p_char[p_end] = '=';
642 					for (s = buf;
643 					    *s && !isdigit((unsigned char)*s); s++)
644 						;
645 					if (!*s)
646 						malformed();
647 					p_newfirst = strtolinenum(s, &s);
648 					if (*s == ',') {
649 						for (; *s && !isdigit((unsigned char)*s); s++)
650 							;
651 						if (!*s)
652 							malformed();
653 						p_repl_lines = strtolinenum(s, &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((unsigned char)buf[1]) &&
680 				    buf[1] != '>' && 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((unsigned char)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 			fseeko(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 		off_t	line_beginning = ftello(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 = strtolinenum(s, &s);
854 		if (*s == ',') {
855 			p_ptrn_lines = strtolinenum(s + 1, &s);
856 		} else
857 			p_ptrn_lines = 1;
858 		if (*s == ' ')
859 			s++;
860 		if (*s != '+' || !*++s)
861 			malformed();
862 		p_newfirst = strtolinenum(s, &s);
863 		if (*s == ',') {
864 			p_repl_lines = strtolinenum(s + 1, &s);
865 		} else
866 			p_repl_lines = 1;
867 		if (*s == ' ')
868 			s++;
869 		if (*s != '@')
870 			malformed();
871 		if (!p_ptrn_lines)
872 			p_first++;	/* do append rather than insert */
873 		p_max = p_ptrn_lines + p_repl_lines + 1;
874 		while (p_max >= hunkmax)
875 			grow_hunkmax();
876 		fillsrc = 1;
877 		filldst = fillsrc + p_ptrn_lines;
878 		p_end = filldst + p_repl_lines;
879 		snprintf(buf, sizeof buf, "*** %ld,%ld ****\n", p_first,
880 		    p_first + p_ptrn_lines - 1);
881 		p_line[0] = savestr(buf);
882 		if (out_of_mem) {
883 			p_end = -1;
884 			return false;
885 		}
886 		p_char[0] = '*';
887 		snprintf(buf, sizeof buf, "--- %ld,%ld ----\n", p_newfirst,
888 		    p_newfirst + p_repl_lines - 1);
889 		p_line[filldst] = savestr(buf);
890 		if (out_of_mem) {
891 			p_end = 0;
892 			return false;
893 		}
894 		p_char[filldst++] = '=';
895 		p_context = 100;
896 		context = 0;
897 		p_hunk_beg = p_input_line + 1;
898 		while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
899 			line_beginning = ftello(pfp);
900 			ret = pgets(buf, sizeof buf, pfp);
901 			p_input_line++;
902 			if (ret == NULL) {
903 				if (p_max - filldst < 3) {
904 					/* assume blank lines got chopped */
905 					strlcpy(buf, " \n", sizeof buf);
906 				} else {
907 					fatal("unexpected end of file in patch\n");
908 				}
909 			}
910 			if (*buf == '\t' || *buf == '\n') {
911 				ch = ' ';	/* assume the space got eaten */
912 				s = savestr(buf);
913 			} else {
914 				ch = *buf;
915 				s = savestr(buf + 1);
916 			}
917 			if (out_of_mem) {
918 				while (--filldst > p_ptrn_lines)
919 					free(p_line[filldst]);
920 				p_end = fillsrc - 1;
921 				return false;
922 			}
923 			switch (ch) {
924 			case '-':
925 				if (fillsrc > p_ptrn_lines) {
926 					free(s);
927 					p_end = filldst - 1;
928 					malformed();
929 				}
930 				p_char[fillsrc] = ch;
931 				p_line[fillsrc] = s;
932 				p_len[fillsrc++] = strlen(s);
933 				if (fillsrc > p_ptrn_lines) {
934 					if (remove_special_line()) {
935 						p_len[fillsrc - 1] -= 1;
936 						s[p_len[fillsrc - 1]] = 0;
937 					}
938 				}
939 				break;
940 			case '=':
941 				ch = ' ';
942 				/* FALL THROUGH */
943 			case ' ':
944 				if (fillsrc > p_ptrn_lines) {
945 					free(s);
946 					while (--filldst > p_ptrn_lines)
947 						free(p_line[filldst]);
948 					p_end = fillsrc - 1;
949 					malformed();
950 				}
951 				context++;
952 				p_char[fillsrc] = ch;
953 				p_line[fillsrc] = s;
954 				p_len[fillsrc++] = strlen(s);
955 				s = savestr(s);
956 				if (out_of_mem) {
957 					while (--filldst > p_ptrn_lines)
958 						free(p_line[filldst]);
959 					p_end = fillsrc - 1;
960 					return false;
961 				}
962 				if (fillsrc > p_ptrn_lines) {
963 					if (remove_special_line()) {
964 						p_len[fillsrc - 1] -= 1;
965 						s[p_len[fillsrc - 1]] = 0;
966 					}
967 				}
968 				/* FALL THROUGH */
969 			case '+':
970 				if (filldst > p_end) {
971 					free(s);
972 					while (--filldst > p_ptrn_lines)
973 						free(p_line[filldst]);
974 					p_end = fillsrc - 1;
975 					malformed();
976 				}
977 				p_char[filldst] = ch;
978 				p_line[filldst] = s;
979 				p_len[filldst++] = strlen(s);
980 				if (fillsrc > p_ptrn_lines) {
981 					if (remove_special_line()) {
982 						p_len[filldst - 1] -= 1;
983 						s[p_len[filldst - 1]] = 0;
984 					}
985 				}
986 				break;
987 			default:
988 				p_end = filldst;
989 				malformed();
990 			}
991 			if (ch != ' ' && context > 0) {
992 				if (context < p_context)
993 					p_context = context;
994 				context = -1000;
995 			}
996 		}		/* while */
997 	} else {		/* normal diff--fake it up */
998 		char	hunk_type;
999 		int	i;
1000 		LINENUM	min, max;
1001 		off_t	line_beginning = ftello(pfp);
1002 
1003 		p_context = 0;
1004 		ret = pgets(buf, sizeof buf, pfp);
1005 		p_input_line++;
1006 		if (ret == NULL || !isdigit((unsigned char)*buf)) {
1007 			next_intuit_at(line_beginning, p_input_line);
1008 			return false;
1009 		}
1010 		p_first = strtolinenum(buf, &s);
1011 		if (*s == ',') {
1012 			p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1013 		} else
1014 			p_ptrn_lines = (*s != 'a');
1015 		hunk_type = *s;
1016 		if (hunk_type == 'a')
1017 			p_first++;	/* do append rather than insert */
1018 		min = strtolinenum(s + 1, &s);
1019 		if (*s == ',')
1020 			max = strtolinenum(s + 1, &s);
1021 		else
1022 			max = min;
1023 		if (hunk_type == 'd')
1024 			min++;
1025 		p_end = p_ptrn_lines + 1 + max - min + 1;
1026 		if (p_end > MAXHUNKSIZE)
1027 			fatal("hunk too large (%ld lines) at line %ld: %s",
1028 			    p_end, p_input_line, buf);
1029 		while (p_end >= hunkmax)
1030 			grow_hunkmax();
1031 		p_newfirst = min;
1032 		p_repl_lines = max - min + 1;
1033 		snprintf(buf, sizeof buf, "*** %ld,%ld\n", p_first,
1034 		    p_first + p_ptrn_lines - 1);
1035 		p_line[0] = savestr(buf);
1036 		if (out_of_mem) {
1037 			p_end = -1;
1038 			return false;
1039 		}
1040 		p_char[0] = '*';
1041 		for (i = 1; i <= p_ptrn_lines; i++) {
1042 			ret = pgets(buf, sizeof buf, pfp);
1043 			p_input_line++;
1044 			if (ret == NULL)
1045 				fatal("unexpected end of file in patch at line %ld\n",
1046 				    p_input_line);
1047 			if (*buf != '<')
1048 				fatal("< expected at line %ld of patch\n",
1049 				    p_input_line);
1050 			p_line[i] = savestr(buf + 2);
1051 			if (out_of_mem) {
1052 				p_end = i - 1;
1053 				return false;
1054 			}
1055 			p_len[i] = strlen(p_line[i]);
1056 			p_char[i] = '-';
1057 		}
1058 
1059 		if (remove_special_line()) {
1060 			p_len[i - 1] -= 1;
1061 			(p_line[i - 1])[p_len[i - 1]] = 0;
1062 		}
1063 		if (hunk_type == 'c') {
1064 			ret = pgets(buf, sizeof buf, pfp);
1065 			p_input_line++;
1066 			if (ret == NULL)
1067 				fatal("unexpected end of file in patch at line %ld\n",
1068 				    p_input_line);
1069 			if (*buf != '-')
1070 				fatal("--- expected at line %ld of patch\n",
1071 				    p_input_line);
1072 		}
1073 		snprintf(buf, sizeof(buf), "--- %ld,%ld\n", min, max);
1074 		p_line[i] = savestr(buf);
1075 		if (out_of_mem) {
1076 			p_end = i - 1;
1077 			return false;
1078 		}
1079 		p_char[i] = '=';
1080 		for (i++; i <= p_end; i++) {
1081 			ret = pgets(buf, sizeof buf, pfp);
1082 			p_input_line++;
1083 			if (ret == NULL)
1084 				fatal("unexpected end of file in patch at line %ld\n",
1085 				    p_input_line);
1086 			if (*buf != '>')
1087 				fatal("> expected at line %ld of patch\n",
1088 				    p_input_line);
1089 			p_line[i] = savestr(buf + 2);
1090 			if (out_of_mem) {
1091 				p_end = i - 1;
1092 				return false;
1093 			}
1094 			p_len[i] = strlen(p_line[i]);
1095 			p_char[i] = '+';
1096 		}
1097 
1098 		if (remove_special_line()) {
1099 			p_len[i - 1] -= 1;
1100 			(p_line[i - 1])[p_len[i - 1]] = 0;
1101 		}
1102 	}
1103 	if (reverse)		/* backwards patch? */
1104 		if (!pch_swap())
1105 			say("Not enough memory to swap next hunk!\n");
1106 #ifdef DEBUGGING
1107 	if (debug & 2) {
1108 		int	i;
1109 		char	special;
1110 
1111 		for (i = 0; i <= p_end; i++) {
1112 			if (i == p_ptrn_lines)
1113 				special = '^';
1114 			else
1115 				special = ' ';
1116 			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1117 			    special, p_line[i]);
1118 			fflush(stderr);
1119 		}
1120 	}
1121 #endif
1122 	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1123 		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1124 	return true;
1125 }
1126 
1127 /*
1128  * Input a line from the patch file, worrying about indentation.
1129  */
1130 static char *
1131 pgets(char *bf, int sz, FILE *fp)
1132 {
1133 	char	*s, *ret = fgets(bf, sz, fp);
1134 	int	indent = 0;
1135 
1136 	if (p_indent && ret != NULL) {
1137 		for (s = buf;
1138 		    indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
1139 		    s++) {
1140 			if (*s == '\t')
1141 				indent += 8 - (indent % 7);
1142 			else
1143 				indent++;
1144 		}
1145 		if (buf != s && strlcpy(buf, s, sizeof(buf)) >= sizeof(buf))
1146 			fatal("buffer too small in pgets()\n");
1147 	}
1148 	return ret;
1149 }
1150 
1151 /*
1152  * Reverse the old and new portions of the current hunk.
1153  */
1154 bool
1155 pch_swap(void)
1156 {
1157 	char	**tp_line;	/* the text of the hunk */
1158 	short	*tp_len;	/* length of each line */
1159 	char	*tp_char;	/* +, -, and ! */
1160 	LINENUM	i;
1161 	LINENUM	n;
1162 	bool	blankline = false;
1163 	char	*s;
1164 
1165 	i = p_first;
1166 	p_first = p_newfirst;
1167 	p_newfirst = i;
1168 
1169 	/* make a scratch copy */
1170 
1171 	tp_line = p_line;
1172 	tp_len = p_len;
1173 	tp_char = p_char;
1174 	p_line = NULL;	/* force set_hunkmax to allocate again */
1175 	p_len = NULL;
1176 	p_char = NULL;
1177 	set_hunkmax();
1178 	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1179 
1180 		free(p_line);
1181 		p_line = tp_line;
1182 		free(p_len);
1183 		p_len = tp_len;
1184 		free(p_char);
1185 		p_char = tp_char;
1186 		return false;	/* not enough memory to swap hunk! */
1187 	}
1188 	/* now turn the new into the old */
1189 
1190 	i = p_ptrn_lines + 1;
1191 	if (tp_char[i] == '\n') {	/* account for possible blank line */
1192 		blankline = true;
1193 		i++;
1194 	}
1195 	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1196 		if (p_efake <= i)
1197 			n = p_end - i + 1;
1198 		else
1199 			n = -i;
1200 		p_efake += n;
1201 		p_bfake += n;
1202 	}
1203 	for (n = 0; i <= p_end; i++, n++) {
1204 		p_line[n] = tp_line[i];
1205 		p_char[n] = tp_char[i];
1206 		if (p_char[n] == '+')
1207 			p_char[n] = '-';
1208 		p_len[n] = tp_len[i];
1209 	}
1210 	if (blankline) {
1211 		i = p_ptrn_lines + 1;
1212 		p_line[n] = tp_line[i];
1213 		p_char[n] = tp_char[i];
1214 		p_len[n] = tp_len[i];
1215 		n++;
1216 	}
1217 	if (p_char[0] != '=')
1218 		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1219 		    p_input_line, p_char[0]);
1220 	p_char[0] = '*';
1221 	for (s = p_line[0]; *s; s++)
1222 		if (*s == '-')
1223 			*s = '*';
1224 
1225 	/* now turn the old into the new */
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 	tp_char[0] = '=';
1231 	for (s = tp_line[0]; *s; s++)
1232 		if (*s == '*')
1233 			*s = '-';
1234 	for (i = 0; n <= p_end; i++, n++) {
1235 		p_line[n] = tp_line[i];
1236 		p_char[n] = tp_char[i];
1237 		if (p_char[n] == '-')
1238 			p_char[n] = '+';
1239 		p_len[n] = tp_len[i];
1240 	}
1241 
1242 	if (i != p_ptrn_lines + 1)
1243 		fatal("Malformed patch at line %ld: expected %ld lines, "
1244 		    "got %ld\n",
1245 		    p_input_line, p_ptrn_lines + 1, i);
1246 
1247 	i = p_ptrn_lines;
1248 	p_ptrn_lines = p_repl_lines;
1249 	p_repl_lines = i;
1250 
1251 	free(tp_line);
1252 	free(tp_len);
1253 	free(tp_char);
1254 
1255 	return true;
1256 }
1257 
1258 /*
1259  * Return the specified line position in the old file of the old context.
1260  */
1261 LINENUM
1262 pch_first(void)
1263 {
1264 	return p_first;
1265 }
1266 
1267 /*
1268  * Return the number of lines of old context.
1269  */
1270 LINENUM
1271 pch_ptrn_lines(void)
1272 {
1273 	return p_ptrn_lines;
1274 }
1275 
1276 /*
1277  * Return the probable line position in the new file of the first line.
1278  */
1279 LINENUM
1280 pch_newfirst(void)
1281 {
1282 	return p_newfirst;
1283 }
1284 
1285 /*
1286  * Return the number of lines in the replacement text including context.
1287  */
1288 LINENUM
1289 pch_repl_lines(void)
1290 {
1291 	return p_repl_lines;
1292 }
1293 
1294 /*
1295  * Return the number of lines in the whole hunk.
1296  */
1297 LINENUM
1298 pch_end(void)
1299 {
1300 	return p_end;
1301 }
1302 
1303 /*
1304  * Return the number of context lines before the first changed line.
1305  */
1306 LINENUM
1307 pch_context(void)
1308 {
1309 	return p_context;
1310 }
1311 
1312 /*
1313  * Return the length of a particular patch line.
1314  */
1315 short
1316 pch_line_len(LINENUM line)
1317 {
1318 	return p_len[line];
1319 }
1320 
1321 /*
1322  * Return the control character (+, -, *, !, etc) for a patch line.
1323  */
1324 char
1325 pch_char(LINENUM line)
1326 {
1327 	return p_char[line];
1328 }
1329 
1330 /*
1331  * Return a pointer to a particular patch line.
1332  */
1333 char *
1334 pfetch(LINENUM line)
1335 {
1336 	return p_line[line];
1337 }
1338 
1339 /*
1340  * Return where in the patch file this hunk began, for error messages.
1341  */
1342 LINENUM
1343 pch_hunk_beg(void)
1344 {
1345 	return p_hunk_beg;
1346 }
1347 
1348 /*
1349  * Apply an ed script by feeding ed itself.
1350  */
1351 void
1352 do_ed_script(void)
1353 {
1354 	char	*t;
1355 	off_t	beginning_of_this_line;
1356 	FILE	*pipefp = NULL;
1357 
1358 	if (!skip_rest_of_patch) {
1359 		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1360 			unlink(TMPOUTNAME);
1361 			fatal("can't create temp file %s", TMPOUTNAME);
1362 		}
1363 		snprintf(buf, sizeof buf, "%s%s%s", _PATH_ED,
1364 		    verbose ? " " : " -s ", TMPOUTNAME);
1365 		pipefp = popen(buf, "w");
1366 	}
1367 	for (;;) {
1368 		beginning_of_this_line = ftello(pfp);
1369 		if (pgets(buf, sizeof buf, pfp) == NULL) {
1370 			next_intuit_at(beginning_of_this_line, p_input_line);
1371 			break;
1372 		}
1373 		p_input_line++;
1374 		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1375 			;
1376 		/* POSIX defines allowed commands as {a,c,d,i,s} */
1377 		if (isdigit((unsigned char)*buf) &&
1378 		    (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1379 			if (pipefp != NULL)
1380 				fputs(buf, pipefp);
1381 			if (*t != 'd') {
1382 				while (pgets(buf, sizeof buf, pfp) != NULL) {
1383 					p_input_line++;
1384 					if (pipefp != NULL)
1385 						fputs(buf, pipefp);
1386 					if (strEQ(buf, ".\n"))
1387 						break;
1388 				}
1389 			}
1390 		} else {
1391 			next_intuit_at(beginning_of_this_line, p_input_line);
1392 			break;
1393 		}
1394 	}
1395 	if (pipefp == NULL)
1396 		return;
1397 	fprintf(pipefp, "w\n");
1398 	fprintf(pipefp, "q\n");
1399 	fflush(pipefp);
1400 	pclose(pipefp);
1401 	ignore_signals();
1402 	if (!check_only) {
1403 		if (move_file(TMPOUTNAME, outname) < 0) {
1404 			toutkeep = true;
1405 			chmod(TMPOUTNAME, filemode);
1406 		} else
1407 			chmod(outname, filemode);
1408 	}
1409 	set_signals(1);
1410 }
1411 
1412 /*
1413  * Choose the name of the file to be patched based on POSIX rules.
1414  * NOTE: the POSIX rules are amazingly stupid and we only follow them
1415  *       if the user specified --posix or set POSIXLY_CORRECT.
1416  */
1417 static char *
1418 posix_name(const struct file_name *names, bool assume_exists)
1419 {
1420 	char *path = NULL;
1421 	int i;
1422 
1423 	/*
1424 	 * POSIX states that the filename will be chosen from one
1425 	 * of the old, new and index names (in that order) if
1426 	 * the file exists relative to CWD after -p stripping.
1427 	 */
1428 	for (i = 0; i < MAX_FILE; i++) {
1429 		if (names[i].path != NULL && names[i].exists) {
1430 			path = names[i].path;
1431 			break;
1432 		}
1433 	}
1434 	if (path == NULL && !assume_exists) {
1435 		/*
1436 		 * No files found, look for something we can checkout from
1437 		 * RCS dirs.  Same order as above.
1438 		 */
1439 		for (i = 0; i < MAX_FILE; i++) {
1440 			if (names[i].path != NULL &&
1441 			    (path = checked_in(names[i].path)) != NULL)
1442 				break;
1443 		}
1444 		/*
1445 		 * Still no match?  Check to see if the diff could be creating
1446 		 * a new file.
1447 		 */
1448 		if (path == NULL && ok_to_create_file &&
1449 		    names[NEW_FILE].path != NULL)
1450 			path = names[NEW_FILE].path;
1451 	}
1452 
1453 	return path ? savestr(path) : NULL;
1454 }
1455 
1456 static char *
1457 compare_names(const struct file_name *names, bool assume_exists, int phase)
1458 {
1459 	size_t min_components, min_baselen, min_len, tmp;
1460 	char *best = NULL;
1461 	char *path;
1462 	int i;
1463 
1464 	/*
1465 	 * The "best" name is the one with the fewest number of path
1466 	 * components, the shortest basename length, and the shortest
1467 	 * overall length (in that order).  We only use the Index: file
1468 	 * if neither of the old or new files could be intuited from
1469 	 * the diff header.
1470 	 */
1471 	min_components = min_baselen = min_len = SIZE_MAX;
1472 	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1473 		path = names[i].path;
1474 		if (path == NULL ||
1475 		    (phase == 1 && !names[i].exists && !assume_exists) ||
1476 		    (phase == 2 && checked_in(path) == NULL))
1477 			continue;
1478 		if ((tmp = num_components(path)) > min_components)
1479 			continue;
1480 		if (tmp < min_components) {
1481 			min_components = tmp;
1482 			best = path;
1483 		}
1484 		if ((tmp = strlen(basename(path))) > min_baselen)
1485 			continue;
1486 		if (tmp < min_baselen) {
1487 			min_baselen = tmp;
1488 			best = path;
1489 		}
1490 		if ((tmp = strlen(path)) > min_len)
1491 			continue;
1492 		min_len = tmp;
1493 		best = path;
1494 	}
1495 	return best;
1496 }
1497 
1498 /*
1499  * Choose the name of the file to be patched based the "best" one
1500  * available.
1501  */
1502 static char *
1503 best_name(const struct file_name *names, bool assume_exists)
1504 {
1505 	char *best;
1506 
1507 	best = compare_names(names, assume_exists, 1);
1508 	if (best == NULL) {
1509 		best = compare_names(names, assume_exists, 2);
1510 		/*
1511 		 * Still no match?  Check to see if the diff could be creating
1512 		 * a new file.
1513 		 */
1514 		if (best == NULL && ok_to_create_file &&
1515 		    names[NEW_FILE].path != NULL)
1516 			best = names[NEW_FILE].path;
1517 	}
1518 	return best ? savestr(best) : NULL;
1519 }
1520 
1521 static size_t
1522 num_components(const char *path)
1523 {
1524 	size_t n;
1525 	const char *cp;
1526 
1527 	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1528 		while (*cp == '/')
1529 			cp++;		/* skip consecutive slashes */
1530 	}
1531 	return n;
1532 }
1533 
1534 /*
1535  * Convert number at NPTR into LINENUM and save address of first
1536  * character that is not a digit in ENDPTR.  If conversion is not
1537  * possible, call fatal.
1538  */
1539 static LINENUM
1540 strtolinenum(char *nptr, char **endptr)
1541 {
1542 	LINENUM rv;
1543 	char c;
1544 	char *p;
1545 	const char *errstr;
1546 
1547 	for (p = nptr; isdigit((unsigned char)*p); p++)
1548 		;
1549 
1550 	if (p == nptr)
1551 		malformed();
1552 
1553 	c = *p;
1554 	*p = '\0';
1555 
1556 	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1557 	if (errstr != NULL)
1558 		fatal("invalid line number at line %ld: `%s' is %s\n",
1559 		    p_input_line, nptr, errstr);
1560 
1561 	*p = c;
1562 	*endptr = p;
1563 
1564 	return rv;
1565 }
1566