xref: /openbsd-src/usr.bin/patch/pch.c (revision ac9b4aacc1da35008afea06a5d23c2f2dea9b93e)
1 /*	$OpenBSD: pch.c,v 1.39 2012/04/11 08:07:13 ajacoutot 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 		fillsrc = 0;
508 		ptrn_spaces_eaten = false;
509 		repl_could_be_missing = true;
510 		repl_missing = false;
511 		repl_backtrack_position = 0;
512 		repl_patch_line = 0;
513 		ptrn_copiable = 0;
514 
515 		ret = pgets(buf, sizeof buf, pfp);
516 		p_input_line++;
517 		if (ret == NULL || strnNE(buf, "********", 8)) {
518 			next_intuit_at(line_beginning, p_input_line);
519 			return false;
520 		}
521 		p_context = 100;
522 		p_hunk_beg = p_input_line + 1;
523 		while (p_end < p_max) {
524 			line_beginning = ftell(pfp);
525 			ret = pgets(buf, sizeof buf, pfp);
526 			p_input_line++;
527 			if (ret == NULL) {
528 				if (p_max - p_end < 4) {
529 					/* assume blank lines got chopped */
530 					strlcpy(buf, "  \n", sizeof buf);
531 				} else {
532 					if (repl_beginning && repl_could_be_missing) {
533 						repl_missing = true;
534 						goto hunk_done;
535 					}
536 					fatal("unexpected end of file in patch\n");
537 				}
538 			}
539 			p_end++;
540 			if (p_end >= hunkmax)
541 				fatal("Internal error: hunk larger than hunk "
542 				    "buffer size");
543 			p_char[p_end] = *buf;
544 			p_line[p_end] = NULL;
545 			switch (*buf) {
546 			case '*':
547 				if (strnEQ(buf, "********", 8)) {
548 					if (repl_beginning && repl_could_be_missing) {
549 						repl_missing = true;
550 						goto hunk_done;
551 					} else
552 						fatal("unexpected end of hunk "
553 						    "at line %ld\n",
554 						    p_input_line);
555 				}
556 				if (p_end != 0) {
557 					if (repl_beginning && repl_could_be_missing) {
558 						repl_missing = true;
559 						goto hunk_done;
560 					}
561 					fatal("unexpected *** at line %ld: %s",
562 					    p_input_line, buf);
563 				}
564 				context = 0;
565 				p_line[p_end] = savestr(buf);
566 				if (out_of_mem) {
567 					p_end--;
568 					return false;
569 				}
570 				for (s = buf; *s && !isdigit(*s); s++)
571 					;
572 				if (!*s)
573 					malformed();
574 				if (strnEQ(s, "0,0", 3))
575 					memmove(s, s + 2, strlen(s + 2) + 1);
576 				p_first = (LINENUM) atol(s);
577 				while (isdigit(*s))
578 					s++;
579 				if (*s == ',') {
580 					for (; *s && !isdigit(*s); s++)
581 						;
582 					if (!*s)
583 						malformed();
584 					p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
585 				} else if (p_first)
586 					p_ptrn_lines = 1;
587 				else {
588 					p_ptrn_lines = 0;
589 					p_first = 1;
590 				}
591 
592 				/* we need this much at least */
593 				p_max = p_ptrn_lines + 6;
594 				while (p_max >= hunkmax)
595 					grow_hunkmax();
596 				p_max = hunkmax;
597 				break;
598 			case '-':
599 				if (buf[1] == '-') {
600 					if (repl_beginning ||
601 					    (p_end != p_ptrn_lines + 1 +
602 					    (p_char[p_end - 1] == '\n'))) {
603 						if (p_end == 1) {
604 							/*
605 							 * `old' lines were omitted;
606 							 * set up to fill them in
607 							 * from 'new' context lines.
608 							 */
609 							p_end = p_ptrn_lines + 1;
610 							fillsrc = p_end + 1;
611 							filldst = 1;
612 							fillcnt = p_ptrn_lines;
613 						} else {
614 							if (repl_beginning) {
615 								if (repl_could_be_missing) {
616 									repl_missing = true;
617 									goto hunk_done;
618 								}
619 								fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
620 								    p_input_line, p_hunk_beg + repl_beginning);
621 							} else {
622 								fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
623 								    (p_end <= p_ptrn_lines
624 								    ? "Premature"
625 								    : "Overdue"),
626 								    p_input_line, p_hunk_beg);
627 							}
628 						}
629 					}
630 					repl_beginning = p_end;
631 					repl_backtrack_position = ftell(pfp);
632 					repl_patch_line = p_input_line;
633 					p_line[p_end] = savestr(buf);
634 					if (out_of_mem) {
635 						p_end--;
636 						return false;
637 					}
638 					p_char[p_end] = '=';
639 					for (s = buf; *s && !isdigit(*s); s++)
640 						;
641 					if (!*s)
642 						malformed();
643 					p_newfirst = (LINENUM) atol(s);
644 					while (isdigit(*s))
645 						s++;
646 					if (*s == ',') {
647 						for (; *s && !isdigit(*s); s++)
648 							;
649 						if (!*s)
650 							malformed();
651 						p_repl_lines = ((LINENUM) atol(s)) -
652 						    p_newfirst + 1;
653 					} else if (p_newfirst)
654 						p_repl_lines = 1;
655 					else {
656 						p_repl_lines = 0;
657 						p_newfirst = 1;
658 					}
659 					p_max = p_repl_lines + p_end;
660 					if (p_max > MAXHUNKSIZE)
661 						fatal("hunk too large (%ld lines) at line %ld: %s",
662 						    p_max, p_input_line, buf);
663 					while (p_max >= hunkmax)
664 						grow_hunkmax();
665 					if (p_repl_lines != ptrn_copiable &&
666 					    (p_context != 0 || p_repl_lines != 1))
667 						repl_could_be_missing = false;
668 					break;
669 				}
670 				goto change_line;
671 			case '+':
672 			case '!':
673 				repl_could_be_missing = false;
674 		change_line:
675 				if (buf[1] == '\n' && canonicalize)
676 					strlcpy(buf + 1, " \n", sizeof buf - 1);
677 				if (!isspace(buf[1]) && buf[1] != '>' &&
678 				    buf[1] != '<' &&
679 				    repl_beginning && repl_could_be_missing) {
680 					repl_missing = true;
681 					goto hunk_done;
682 				}
683 				if (context >= 0) {
684 					if (context < p_context)
685 						p_context = context;
686 					context = -1000;
687 				}
688 				p_line[p_end] = savestr(buf + 2);
689 				if (out_of_mem) {
690 					p_end--;
691 					return false;
692 				}
693 				if (p_end == p_ptrn_lines) {
694 					if (remove_special_line()) {
695 						int	len;
696 
697 						len = strlen(p_line[p_end]) - 1;
698 						(p_line[p_end])[len] = 0;
699 					}
700 				}
701 				break;
702 			case '\t':
703 			case '\n':	/* assume the 2 spaces got eaten */
704 				if (repl_beginning && repl_could_be_missing &&
705 				    (!ptrn_spaces_eaten ||
706 				    diff_type == NEW_CONTEXT_DIFF)) {
707 					repl_missing = true;
708 					goto hunk_done;
709 				}
710 				p_line[p_end] = savestr(buf);
711 				if (out_of_mem) {
712 					p_end--;
713 					return false;
714 				}
715 				if (p_end != p_ptrn_lines + 1) {
716 					ptrn_spaces_eaten |= (repl_beginning != 0);
717 					context++;
718 					if (!repl_beginning)
719 						ptrn_copiable++;
720 					p_char[p_end] = ' ';
721 				}
722 				break;
723 			case ' ':
724 				if (!isspace(buf[1]) &&
725 				    repl_beginning && repl_could_be_missing) {
726 					repl_missing = true;
727 					goto hunk_done;
728 				}
729 				context++;
730 				if (!repl_beginning)
731 					ptrn_copiable++;
732 				p_line[p_end] = savestr(buf + 2);
733 				if (out_of_mem) {
734 					p_end--;
735 					return false;
736 				}
737 				break;
738 			default:
739 				if (repl_beginning && repl_could_be_missing) {
740 					repl_missing = true;
741 					goto hunk_done;
742 				}
743 				malformed();
744 			}
745 			/* set up p_len for strncmp() so we don't have to */
746 			/* assume null termination */
747 			if (p_line[p_end])
748 				p_len[p_end] = strlen(p_line[p_end]);
749 			else
750 				p_len[p_end] = 0;
751 		}
752 
753 hunk_done:
754 		if (p_end >= 0 && !repl_beginning)
755 			fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
756 
757 		if (repl_missing) {
758 
759 			/* reset state back to just after --- */
760 			p_input_line = repl_patch_line;
761 			for (p_end--; p_end > repl_beginning; p_end--)
762 				free(p_line[p_end]);
763 			fseek(pfp, repl_backtrack_position, SEEK_SET);
764 
765 			/* redundant 'new' context lines were omitted - set */
766 			/* up to fill them in from the old file context */
767 			if (!p_context && p_repl_lines == 1) {
768 				p_repl_lines = 0;
769 				p_max--;
770 			}
771 			fillsrc = 1;
772 			filldst = repl_beginning + 1;
773 			fillcnt = p_repl_lines;
774 			p_end = p_max;
775 		} else if (!p_context && fillcnt == 1) {
776 			/* the first hunk was a null hunk with no context */
777 			/* and we were expecting one line -- fix it up. */
778 			while (filldst < p_end) {
779 				p_line[filldst] = p_line[filldst + 1];
780 				p_char[filldst] = p_char[filldst + 1];
781 				p_len[filldst] = p_len[filldst + 1];
782 				filldst++;
783 			}
784 #if 0
785 			repl_beginning--;	/* this doesn't need to be fixed */
786 #endif
787 			p_end--;
788 			p_first++;	/* do append rather than insert */
789 			fillcnt = 0;
790 			p_ptrn_lines = 0;
791 		}
792 		if (diff_type == CONTEXT_DIFF &&
793 		    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
794 			if (verbose)
795 				say("%s\n%s\n%s\n",
796 				    "(Fascinating--this is really a new-style context diff but without",
797 				    "the telltale extra asterisks on the *** line that usually indicate",
798 				    "the new style...)");
799 			diff_type = NEW_CONTEXT_DIFF;
800 		}
801 		/* if there were omitted context lines, fill them in now */
802 		if (fillcnt) {
803 			p_bfake = filldst;	/* remember where not to free() */
804 			p_efake = filldst + fillcnt - 1;
805 			while (fillcnt-- > 0) {
806 				while (fillsrc <= p_end && p_char[fillsrc] != ' ')
807 					fillsrc++;
808 				if (fillsrc > p_end)
809 					fatal("replacement text or line numbers mangled in hunk at line %ld\n",
810 					    p_hunk_beg);
811 				p_line[filldst] = p_line[fillsrc];
812 				p_char[filldst] = p_char[fillsrc];
813 				p_len[filldst] = p_len[fillsrc];
814 				fillsrc++;
815 				filldst++;
816 			}
817 			while (fillsrc <= p_end && fillsrc != repl_beginning &&
818 			    p_char[fillsrc] != ' ')
819 				fillsrc++;
820 #ifdef DEBUGGING
821 			if (debug & 64)
822 				printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
823 				fillsrc, filldst, repl_beginning, p_end + 1);
824 #endif
825 			if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
826 				malformed();
827 			if (filldst != p_end + 1 && filldst != repl_beginning)
828 				malformed();
829 		}
830 		if (p_line[p_end] != NULL) {
831 			if (remove_special_line()) {
832 				p_len[p_end] -= 1;
833 				(p_line[p_end])[p_len[p_end]] = 0;
834 			}
835 		}
836 	} else if (diff_type == UNI_DIFF) {
837 		long	line_beginning = ftell(pfp); /* file pos of the current line */
838 		LINENUM	fillsrc;	/* index of old lines */
839 		LINENUM	filldst;	/* index of new lines */
840 		char	ch;
841 
842 		ret = pgets(buf, sizeof buf, pfp);
843 		p_input_line++;
844 		if (ret == NULL || strnNE(buf, "@@ -", 4)) {
845 			next_intuit_at(line_beginning, p_input_line);
846 			return false;
847 		}
848 		s = buf + 4;
849 		if (!*s)
850 			malformed();
851 		p_first = (LINENUM) atol(s);
852 		while (isdigit(*s))
853 			s++;
854 		if (*s == ',') {
855 			p_ptrn_lines = (LINENUM) atol(++s);
856 			while (isdigit(*s))
857 				s++;
858 		} else
859 			p_ptrn_lines = 1;
860 		if (*s == ' ')
861 			s++;
862 		if (*s != '+' || !*++s)
863 			malformed();
864 		p_newfirst = (LINENUM) atol(s);
865 		while (isdigit(*s))
866 			s++;
867 		if (*s == ',') {
868 			p_repl_lines = (LINENUM) atol(++s);
869 			while (isdigit(*s))
870 				s++;
871 		} else
872 			p_repl_lines = 1;
873 		if (*s == ' ')
874 			s++;
875 		if (*s != '@')
876 			malformed();
877 		if (!p_ptrn_lines)
878 			p_first++;	/* do append rather than insert */
879 		p_max = p_ptrn_lines + p_repl_lines + 1;
880 		while (p_max >= hunkmax)
881 			grow_hunkmax();
882 		fillsrc = 1;
883 		filldst = fillsrc + p_ptrn_lines;
884 		p_end = filldst + p_repl_lines;
885 		snprintf(buf, sizeof buf, "*** %ld,%ld ****\n", p_first,
886 		    p_first + p_ptrn_lines - 1);
887 		p_line[0] = savestr(buf);
888 		if (out_of_mem) {
889 			p_end = -1;
890 			return false;
891 		}
892 		p_char[0] = '*';
893 		snprintf(buf, sizeof buf, "--- %ld,%ld ----\n", p_newfirst,
894 		    p_newfirst + p_repl_lines - 1);
895 		p_line[filldst] = savestr(buf);
896 		if (out_of_mem) {
897 			p_end = 0;
898 			return false;
899 		}
900 		p_char[filldst++] = '=';
901 		p_context = 100;
902 		context = 0;
903 		p_hunk_beg = p_input_line + 1;
904 		while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
905 			line_beginning = ftell(pfp);
906 			ret = pgets(buf, sizeof buf, pfp);
907 			p_input_line++;
908 			if (ret == NULL) {
909 				if (p_max - filldst < 3) {
910 					/* assume blank lines got chopped */
911 					strlcpy(buf, " \n", sizeof buf);
912 				} else {
913 					fatal("unexpected end of file in patch\n");
914 				}
915 			}
916 			if (*buf == '\t' || *buf == '\n') {
917 				ch = ' ';	/* assume the space got eaten */
918 				s = savestr(buf);
919 			} else {
920 				ch = *buf;
921 				s = savestr(buf + 1);
922 			}
923 			if (out_of_mem) {
924 				while (--filldst > p_ptrn_lines)
925 					free(p_line[filldst]);
926 				p_end = fillsrc - 1;
927 				return false;
928 			}
929 			switch (ch) {
930 			case '-':
931 				if (fillsrc > p_ptrn_lines) {
932 					free(s);
933 					p_end = filldst - 1;
934 					malformed();
935 				}
936 				p_char[fillsrc] = ch;
937 				p_line[fillsrc] = s;
938 				p_len[fillsrc++] = strlen(s);
939 				if (fillsrc > p_ptrn_lines) {
940 					if (remove_special_line()) {
941 						p_len[fillsrc - 1] -= 1;
942 						s[p_len[fillsrc - 1]] = 0;
943 					}
944 				}
945 				break;
946 			case '=':
947 				ch = ' ';
948 				/* FALL THROUGH */
949 			case ' ':
950 				if (fillsrc > p_ptrn_lines) {
951 					free(s);
952 					while (--filldst > p_ptrn_lines)
953 						free(p_line[filldst]);
954 					p_end = fillsrc - 1;
955 					malformed();
956 				}
957 				context++;
958 				p_char[fillsrc] = ch;
959 				p_line[fillsrc] = s;
960 				p_len[fillsrc++] = strlen(s);
961 				s = savestr(s);
962 				if (out_of_mem) {
963 					while (--filldst > p_ptrn_lines)
964 						free(p_line[filldst]);
965 					p_end = fillsrc - 1;
966 					return false;
967 				}
968 				if (fillsrc > p_ptrn_lines) {
969 					if (remove_special_line()) {
970 						p_len[fillsrc - 1] -= 1;
971 						s[p_len[fillsrc - 1]] = 0;
972 					}
973 				}
974 				/* FALL THROUGH */
975 			case '+':
976 				if (filldst > p_end) {
977 					free(s);
978 					while (--filldst > p_ptrn_lines)
979 						free(p_line[filldst]);
980 					p_end = fillsrc - 1;
981 					malformed();
982 				}
983 				p_char[filldst] = ch;
984 				p_line[filldst] = s;
985 				p_len[filldst++] = strlen(s);
986 				if (fillsrc > p_ptrn_lines) {
987 					if (remove_special_line()) {
988 						p_len[filldst - 1] -= 1;
989 						s[p_len[filldst - 1]] = 0;
990 					}
991 				}
992 				break;
993 			default:
994 				p_end = filldst;
995 				malformed();
996 			}
997 			if (ch != ' ' && context > 0) {
998 				if (context < p_context)
999 					p_context = context;
1000 				context = -1000;
1001 			}
1002 		}		/* while */
1003 	} else {		/* normal diff--fake it up */
1004 		char	hunk_type;
1005 		int	i;
1006 		LINENUM	min, max;
1007 		long	line_beginning = ftell(pfp);
1008 
1009 		p_context = 0;
1010 		ret = pgets(buf, sizeof buf, pfp);
1011 		p_input_line++;
1012 		if (ret == NULL || !isdigit(*buf)) {
1013 			next_intuit_at(line_beginning, p_input_line);
1014 			return false;
1015 		}
1016 		p_first = (LINENUM) atol(buf);
1017 		for (s = buf; isdigit(*s); s++)
1018 			;
1019 		if (*s == ',') {
1020 			p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
1021 			while (isdigit(*s))
1022 				s++;
1023 		} else
1024 			p_ptrn_lines = (*s != 'a');
1025 		hunk_type = *s;
1026 		if (hunk_type == 'a')
1027 			p_first++;	/* do append rather than insert */
1028 		min = (LINENUM) atol(++s);
1029 		for (; isdigit(*s); s++)
1030 			;
1031 		if (*s == ',')
1032 			max = (LINENUM) atol(++s);
1033 		else
1034 			max = min;
1035 		if (hunk_type == 'd')
1036 			min++;
1037 		p_end = p_ptrn_lines + 1 + max - min + 1;
1038 		if (p_end > MAXHUNKSIZE)
1039 			fatal("hunk too large (%ld lines) at line %ld: %s",
1040 			    p_end, p_input_line, buf);
1041 		while (p_end >= hunkmax)
1042 			grow_hunkmax();
1043 		p_newfirst = min;
1044 		p_repl_lines = max - min + 1;
1045 		snprintf(buf, sizeof buf, "*** %ld,%ld\n", p_first,
1046 		    p_first + p_ptrn_lines - 1);
1047 		p_line[0] = savestr(buf);
1048 		if (out_of_mem) {
1049 			p_end = -1;
1050 			return false;
1051 		}
1052 		p_char[0] = '*';
1053 		for (i = 1; i <= p_ptrn_lines; i++) {
1054 			ret = pgets(buf, sizeof buf, pfp);
1055 			p_input_line++;
1056 			if (ret == NULL)
1057 				fatal("unexpected end of file in patch at line %ld\n",
1058 				    p_input_line);
1059 			if (*buf != '<')
1060 				fatal("< expected at line %ld of patch\n",
1061 				    p_input_line);
1062 			p_line[i] = savestr(buf + 2);
1063 			if (out_of_mem) {
1064 				p_end = i - 1;
1065 				return false;
1066 			}
1067 			p_len[i] = strlen(p_line[i]);
1068 			p_char[i] = '-';
1069 		}
1070 
1071 		if (remove_special_line()) {
1072 			p_len[i - 1] -= 1;
1073 			(p_line[i - 1])[p_len[i - 1]] = 0;
1074 		}
1075 		if (hunk_type == 'c') {
1076 			ret = pgets(buf, sizeof buf, pfp);
1077 			p_input_line++;
1078 			if (ret == NULL)
1079 				fatal("unexpected end of file in patch at line %ld\n",
1080 				    p_input_line);
1081 			if (*buf != '-')
1082 				fatal("--- expected at line %ld of patch\n",
1083 				    p_input_line);
1084 		}
1085 		snprintf(buf, sizeof(buf), "--- %ld,%ld\n", min, max);
1086 		p_line[i] = savestr(buf);
1087 		if (out_of_mem) {
1088 			p_end = i - 1;
1089 			return false;
1090 		}
1091 		p_char[i] = '=';
1092 		for (i++; i <= p_end; i++) {
1093 			ret = pgets(buf, sizeof buf, pfp);
1094 			p_input_line++;
1095 			if (ret == NULL)
1096 				fatal("unexpected end of file in patch at line %ld\n",
1097 				    p_input_line);
1098 			if (*buf != '>')
1099 				fatal("> expected at line %ld of patch\n",
1100 				    p_input_line);
1101 			p_line[i] = savestr(buf + 2);
1102 			if (out_of_mem) {
1103 				p_end = i - 1;
1104 				return false;
1105 			}
1106 			p_len[i] = strlen(p_line[i]);
1107 			p_char[i] = '+';
1108 		}
1109 
1110 		if (remove_special_line()) {
1111 			p_len[i - 1] -= 1;
1112 			(p_line[i - 1])[p_len[i - 1]] = 0;
1113 		}
1114 	}
1115 	if (reverse)		/* backwards patch? */
1116 		if (!pch_swap())
1117 			say("Not enough memory to swap next hunk!\n");
1118 #ifdef DEBUGGING
1119 	if (debug & 2) {
1120 		int	i;
1121 		char	special;
1122 
1123 		for (i = 0; i <= p_end; i++) {
1124 			if (i == p_ptrn_lines)
1125 				special = '^';
1126 			else
1127 				special = ' ';
1128 			fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1129 			    special, p_line[i]);
1130 			fflush(stderr);
1131 		}
1132 	}
1133 #endif
1134 	if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1135 		p_char[p_end + 1] = '^';	/* add a stopper for apply_hunk */
1136 	return true;
1137 }
1138 
1139 /*
1140  * Input a line from the patch file, worrying about indentation.
1141  */
1142 static char *
1143 pgets(char *bf, int sz, FILE *fp)
1144 {
1145 	char	*s, *ret = fgets(bf, sz, fp);
1146 	int	indent = 0;
1147 
1148 	if (p_indent && ret != NULL) {
1149 		for (s = buf;
1150 		    indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
1151 		    s++) {
1152 			if (*s == '\t')
1153 				indent += 8 - (indent % 7);
1154 			else
1155 				indent++;
1156 		}
1157 		if (buf != s && strlcpy(buf, s, sizeof(buf)) >= sizeof(buf))
1158 			fatal("buffer too small in pgets()\n");
1159 	}
1160 	return ret;
1161 }
1162 
1163 /*
1164  * Reverse the old and new portions of the current hunk.
1165  */
1166 bool
1167 pch_swap(void)
1168 {
1169 	char	**tp_line;	/* the text of the hunk */
1170 	short	*tp_len;	/* length of each line */
1171 	char	*tp_char;	/* +, -, and ! */
1172 	LINENUM	i;
1173 	LINENUM	n;
1174 	bool	blankline = false;
1175 	char	*s;
1176 
1177 	i = p_first;
1178 	p_first = p_newfirst;
1179 	p_newfirst = i;
1180 
1181 	/* make a scratch copy */
1182 
1183 	tp_line = p_line;
1184 	tp_len = p_len;
1185 	tp_char = p_char;
1186 	p_line = NULL;	/* force set_hunkmax to allocate again */
1187 	p_len = NULL;
1188 	p_char = NULL;
1189 	set_hunkmax();
1190 	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1191 
1192 		free(p_line);
1193 		p_line = tp_line;
1194 		free(p_len);
1195 		p_len = tp_len;
1196 		free(p_char);
1197 		p_char = tp_char;
1198 		return false;	/* not enough memory to swap hunk! */
1199 	}
1200 	/* now turn the new into the old */
1201 
1202 	i = p_ptrn_lines + 1;
1203 	if (tp_char[i] == '\n') {	/* account for possible blank line */
1204 		blankline = true;
1205 		i++;
1206 	}
1207 	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1208 		if (p_efake <= i)
1209 			n = p_end - i + 1;
1210 		else
1211 			n = -i;
1212 		p_efake += n;
1213 		p_bfake += n;
1214 	}
1215 	for (n = 0; i <= p_end; i++, n++) {
1216 		p_line[n] = tp_line[i];
1217 		p_char[n] = tp_char[i];
1218 		if (p_char[n] == '+')
1219 			p_char[n] = '-';
1220 		p_len[n] = tp_len[i];
1221 	}
1222 	if (blankline) {
1223 		i = p_ptrn_lines + 1;
1224 		p_line[n] = tp_line[i];
1225 		p_char[n] = tp_char[i];
1226 		p_len[n] = tp_len[i];
1227 		n++;
1228 	}
1229 	if (p_char[0] != '=')
1230 		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1231 		    p_input_line, p_char[0]);
1232 	p_char[0] = '*';
1233 	for (s = p_line[0]; *s; s++)
1234 		if (*s == '-')
1235 			*s = '*';
1236 
1237 	/* now turn the old into the new */
1238 
1239 	if (p_char[0] != '*')
1240 		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1241 		    p_input_line, p_char[0]);
1242 	tp_char[0] = '=';
1243 	for (s = tp_line[0]; *s; s++)
1244 		if (*s == '*')
1245 			*s = '-';
1246 	for (i = 0; n <= p_end; i++, n++) {
1247 		p_line[n] = tp_line[i];
1248 		p_char[n] = tp_char[i];
1249 		if (p_char[n] == '-')
1250 			p_char[n] = '+';
1251 		p_len[n] = tp_len[i];
1252 	}
1253 
1254 	if (i != p_ptrn_lines + 1)
1255 		fatal("Malformed patch at line %ld: expected %ld lines, "
1256 		    "got %ld\n",
1257 		    p_input_line, p_ptrn_lines + 1, i);
1258 
1259 	i = p_ptrn_lines;
1260 	p_ptrn_lines = p_repl_lines;
1261 	p_repl_lines = i;
1262 
1263 	free(tp_line);
1264 	free(tp_len);
1265 	free(tp_char);
1266 
1267 	return true;
1268 }
1269 
1270 /*
1271  * Return the specified line position in the old file of the old context.
1272  */
1273 LINENUM
1274 pch_first(void)
1275 {
1276 	return p_first;
1277 }
1278 
1279 /*
1280  * Return the number of lines of old context.
1281  */
1282 LINENUM
1283 pch_ptrn_lines(void)
1284 {
1285 	return p_ptrn_lines;
1286 }
1287 
1288 /*
1289  * Return the probable line position in the new file of the first line.
1290  */
1291 LINENUM
1292 pch_newfirst(void)
1293 {
1294 	return p_newfirst;
1295 }
1296 
1297 /*
1298  * Return the number of lines in the replacement text including context.
1299  */
1300 LINENUM
1301 pch_repl_lines(void)
1302 {
1303 	return p_repl_lines;
1304 }
1305 
1306 /*
1307  * Return the number of lines in the whole hunk.
1308  */
1309 LINENUM
1310 pch_end(void)
1311 {
1312 	return p_end;
1313 }
1314 
1315 /*
1316  * Return the number of context lines before the first changed line.
1317  */
1318 LINENUM
1319 pch_context(void)
1320 {
1321 	return p_context;
1322 }
1323 
1324 /*
1325  * Return the length of a particular patch line.
1326  */
1327 short
1328 pch_line_len(LINENUM line)
1329 {
1330 	return p_len[line];
1331 }
1332 
1333 /*
1334  * Return the control character (+, -, *, !, etc) for a patch line.
1335  */
1336 char
1337 pch_char(LINENUM line)
1338 {
1339 	return p_char[line];
1340 }
1341 
1342 /*
1343  * Return a pointer to a particular patch line.
1344  */
1345 char *
1346 pfetch(LINENUM line)
1347 {
1348 	return p_line[line];
1349 }
1350 
1351 /*
1352  * Return where in the patch file this hunk began, for error messages.
1353  */
1354 LINENUM
1355 pch_hunk_beg(void)
1356 {
1357 	return p_hunk_beg;
1358 }
1359 
1360 /*
1361  * Apply an ed script by feeding ed itself.
1362  */
1363 void
1364 do_ed_script(void)
1365 {
1366 	char	*t;
1367 	long	beginning_of_this_line;
1368 	FILE	*pipefp = NULL;
1369 
1370 	if (!skip_rest_of_patch) {
1371 		if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1372 			unlink(TMPOUTNAME);
1373 			fatal("can't create temp file %s", TMPOUTNAME);
1374 		}
1375 		snprintf(buf, sizeof buf, "%s%s%s", _PATH_ED,
1376 		    verbose ? " " : " -s ", TMPOUTNAME);
1377 		pipefp = popen(buf, "w");
1378 	}
1379 	for (;;) {
1380 		beginning_of_this_line = ftell(pfp);
1381 		if (pgets(buf, sizeof buf, pfp) == NULL) {
1382 			next_intuit_at(beginning_of_this_line, p_input_line);
1383 			break;
1384 		}
1385 		p_input_line++;
1386 		for (t = buf; isdigit(*t) || *t == ','; t++)
1387 			;
1388 		/* POSIX defines allowed commands as {a,c,d,i,s} */
1389 		if (isdigit(*buf) && (*t == 'a' || *t == 'c' || *t == 'd' ||
1390 		    *t == 'i' || *t == 's')) {
1391 			if (pipefp != NULL)
1392 				fputs(buf, pipefp);
1393 			if (*t != 'd') {
1394 				while (pgets(buf, sizeof buf, pfp) != NULL) {
1395 					p_input_line++;
1396 					if (pipefp != NULL)
1397 						fputs(buf, pipefp);
1398 					if (strEQ(buf, ".\n"))
1399 						break;
1400 				}
1401 			}
1402 		} else {
1403 			next_intuit_at(beginning_of_this_line, p_input_line);
1404 			break;
1405 		}
1406 	}
1407 	if (pipefp == NULL)
1408 		return;
1409 	fprintf(pipefp, "w\n");
1410 	fprintf(pipefp, "q\n");
1411 	fflush(pipefp);
1412 	pclose(pipefp);
1413 	ignore_signals();
1414 	if (!check_only) {
1415 		if (move_file(TMPOUTNAME, outname) < 0) {
1416 			toutkeep = true;
1417 			chmod(TMPOUTNAME, filemode);
1418 		} else
1419 			chmod(outname, filemode);
1420 	}
1421 	set_signals(1);
1422 }
1423 
1424 /*
1425  * Choose the name of the file to be patched based on POSIX rules.
1426  * NOTE: the POSIX rules are amazingly stupid and we only follow them
1427  *       if the user specified --posix or set POSIXLY_CORRECT.
1428  */
1429 static char *
1430 posix_name(const struct file_name *names, bool assume_exists)
1431 {
1432 	char *path = NULL;
1433 	int i;
1434 
1435 	/*
1436 	 * POSIX states that the filename will be chosen from one
1437 	 * of the old, new and index names (in that order) if
1438 	 * the file exists relative to CWD after -p stripping.
1439 	 */
1440 	for (i = 0; i < MAX_FILE; i++) {
1441 		if (names[i].path != NULL && names[i].exists) {
1442 			path = names[i].path;
1443 			break;
1444 		}
1445 	}
1446 	if (path == NULL && !assume_exists) {
1447 		/*
1448 		 * No files found, look for something we can checkout from
1449 		 * RCS/SCCS dirs.  Same order as above.
1450 		 */
1451 		for (i = 0; i < MAX_FILE; i++) {
1452 			if (names[i].path != NULL &&
1453 			    (path = checked_in(names[i].path)) != NULL)
1454 				break;
1455 		}
1456 		/*
1457 		 * Still no match?  Check to see if the diff could be creating
1458 		 * a new file.
1459 		 */
1460 		if (path == NULL && ok_to_create_file &&
1461 		    names[NEW_FILE].path != NULL)
1462 			path = names[NEW_FILE].path;
1463 	}
1464 
1465 	return path ? savestr(path) : NULL;
1466 }
1467 
1468 /*
1469  * Choose the name of the file to be patched based the "best" one
1470  * available.
1471  */
1472 static char *
1473 best_name(const struct file_name *names, bool assume_exists)
1474 {
1475 	size_t min_components, min_baselen, min_len, tmp;
1476 	char *best = NULL;
1477 	int i;
1478 
1479 	/*
1480 	 * The "best" name is the one with the fewest number of path
1481 	 * components, the shortest basename length, and the shortest
1482 	 * overall length (in that order).  We only use the Index: file
1483 	 * if neither of the old or new files could be intuited from
1484 	 * the diff header.
1485 	 */
1486 	min_components = min_baselen = min_len = SIZE_MAX;
1487 	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1488 		if (names[i].path == NULL ||
1489 		    (!names[i].exists && !assume_exists))
1490 			continue;
1491 		if ((tmp = num_components(names[i].path)) > min_components)
1492 			continue;
1493 		min_components = tmp;
1494 		if ((tmp = strlen(basename(names[i].path))) > min_baselen)
1495 			continue;
1496 		min_baselen = tmp;
1497 		if ((tmp = strlen(names[i].path)) > min_len)
1498 			continue;
1499 		min_len = tmp;
1500 		best = names[i].path;
1501 	}
1502 	if (best == NULL) {
1503 		/*
1504 		 * No files found, look for something we can checkout from
1505 		 * RCS/SCCS dirs.  Logic is identical to that above...
1506 		 */
1507 		min_components = min_baselen = min_len = SIZE_MAX;
1508 		for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1509 			if (names[i].path == NULL ||
1510 			    checked_in(names[i].path) == NULL)
1511 				continue;
1512 			if ((tmp = num_components(names[i].path)) > min_components)
1513 				continue;
1514 			min_components = tmp;
1515 			if ((tmp = strlen(basename(names[i].path))) > min_baselen)
1516 				continue;
1517 			min_baselen = tmp;
1518 			if ((tmp = strlen(names[i].path)) > min_len)
1519 				continue;
1520 			min_len = tmp;
1521 			best = names[i].path;
1522 		}
1523 		/*
1524 		 * Still no match?  Check to see if the diff could be creating
1525 		 * a new file.
1526 		 */
1527 		if (best == NULL && ok_to_create_file &&
1528 		    names[NEW_FILE].path != NULL)
1529 			best = names[NEW_FILE].path;
1530 	}
1531 
1532 	return best ? savestr(best) : NULL;
1533 }
1534 
1535 static size_t
1536 num_components(const char *path)
1537 {
1538 	size_t n;
1539 	const char *cp;
1540 
1541 	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1542 		while (*cp == '/')
1543 			cp++;		/* skip consecutive slashes */
1544 	}
1545 	return n;
1546 }
1547