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