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