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