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