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