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