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