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