xref: /openbsd/usr.bin/patch/pch.c (revision f344f57b)
1 /*	$OpenBSD: pch.c,v 1.66 2023/07/12 15:45:34 florian 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 ssize_t	*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
re_patch(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
open_patch_file(const char * filename)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 (getline(&buf, &bufsz, stdin) != -1)
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
set_hunkmax(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(ssize_t));
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
grow_hunkmax(void)139 grow_hunkmax(void)
140 {
141 	int		new_hunkmax;
142 	char		**new_p_line;
143 	ssize_t		*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(ssize_t));
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
there_is_another_patch(void)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
intuit_diff_type(void)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 (getline(&buf, &bufsz, pfp) == -1) {
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
next_intuit_at(off_t file_pos,LINENUM file_line)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
skip_to(off_t file_pos,LINENUM file_line)434 skip_to(off_t file_pos, LINENUM file_line)
435 {
436 	int	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 = getline(&buf, &bufsz, pfp);
446 			if (ret == -1)
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
malformed(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
remove_special_line(void)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
another_hunk(void)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 malformed */
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;
505 	int	context = 0;
506 	int	ret;
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 = pgetline(&buf, &bufsz, pfp);
531 		p_input_line++;
532 		if (ret == -1 || 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 = pgetline(&buf, &bufsz, pfp);
541 			p_input_line++;
542 			if (ret == -1) {
543 				if (p_max - p_end < 4) {
544 					/* assume blank lines got chopped */
545 					strlcpy(buf, "  \n", bufsz);
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", bufsz - 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 = pgetline(&buf, &bufsz, pfp);
866 		p_input_line++;
867 		if (ret == -1 || 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, bufsz, "*** %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, bufsz, "--- %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 = pgetline(&buf, &bufsz, pfp);
926 			p_input_line++;
927 			if (ret == -1) {
928 				if (p_max - filldst < 3) {
929 					/* assume blank lines got chopped */
930 					strlcpy(buf, " \n", bufsz);
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 = pgetline(&buf, &bufsz, pfp);
1030 		p_input_line++;
1031 		if (ret == -1 || !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, bufsz, "*** %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 = pgetline(&buf, &bufsz, pfp);
1077 			p_input_line++;
1078 			if (ret == -1)
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 = pgetline(&buf, &bufsz, pfp);
1099 			p_input_line++;
1100 			if (ret == -1)
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, bufsz, "--- %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 = pgetline(&buf, &bufsz, pfp);
1116 			p_input_line++;
1117 			if (ret == -1)
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 int
pgetline(char ** bf,size_t * sz,FILE * fp)1165 pgetline(char **bf, size_t *sz, FILE *fp)
1166 {
1167 	char	*s;
1168 	int	indent = 0;
1169 	int	ret;
1170 
1171 	ret = getline(bf, sz, fp);
1172 
1173 	if (p_indent && ret != -1) {
1174 		for (s = buf;
1175 		    indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
1176 		    s++) {
1177 			if (*s == '\t')
1178 				indent += 8 - (indent % 7);
1179 			else
1180 				indent++;
1181 		}
1182 		if (buf != s && strlcpy(buf, s, bufsz) >= bufsz)
1183 			fatal("buffer too small in pgetline()\n");
1184 	}
1185 	return ret;
1186 }
1187 
1188 /*
1189  * Reverse the old and new portions of the current hunk.
1190  */
1191 bool
pch_swap(void)1192 pch_swap(void)
1193 {
1194 	char	**tp_line;	/* the text of the hunk */
1195 	ssize_t	*tp_len;	/* length of each line */
1196 	char	*tp_char;	/* +, -, and ! */
1197 	LINENUM	i;
1198 	LINENUM	n;
1199 	bool	blankline = false;
1200 	char	*s;
1201 
1202 	i = p_first;
1203 	p_first = p_newfirst;
1204 	p_newfirst = i;
1205 
1206 	/* make a scratch copy */
1207 
1208 	tp_line = p_line;
1209 	tp_len = p_len;
1210 	tp_char = p_char;
1211 	p_line = NULL;	/* force set_hunkmax to allocate again */
1212 	p_len = NULL;
1213 	p_char = NULL;
1214 	set_hunkmax();
1215 	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1216 
1217 		free(p_line);
1218 		p_line = tp_line;
1219 		free(p_len);
1220 		p_len = tp_len;
1221 		free(p_char);
1222 		p_char = tp_char;
1223 		return false;	/* not enough memory to swap hunk! */
1224 	}
1225 	/* now turn the new into the old */
1226 
1227 	i = p_ptrn_lines + 1;
1228 	if (tp_char[i] == '\n') {	/* account for possible blank line */
1229 		blankline = true;
1230 		i++;
1231 	}
1232 	if (p_efake >= 0) {	/* fix non-freeable ptr range */
1233 		if (p_efake <= i)
1234 			n = p_end - i + 1;
1235 		else
1236 			n = -i;
1237 		p_efake += n;
1238 		p_bfake += n;
1239 	}
1240 	for (n = 0; i <= p_end; i++, n++) {
1241 		p_line[n] = tp_line[i];
1242 		p_char[n] = tp_char[i];
1243 		if (p_char[n] == '+')
1244 			p_char[n] = '-';
1245 		p_len[n] = tp_len[i];
1246 	}
1247 	if (blankline) {
1248 		i = p_ptrn_lines + 1;
1249 		p_line[n] = tp_line[i];
1250 		p_char[n] = tp_char[i];
1251 		p_len[n] = tp_len[i];
1252 		n++;
1253 	}
1254 	if (p_char[0] != '=')
1255 		fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1256 		    p_input_line, p_char[0]);
1257 	p_char[0] = '*';
1258 	for (s = p_line[0]; *s; s++)
1259 		if (*s == '-')
1260 			*s = '*';
1261 
1262 	/* now turn the old into the new */
1263 
1264 	if (p_char[0] != '*')
1265 		fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1266 		    p_input_line, p_char[0]);
1267 	tp_char[0] = '=';
1268 	for (s = tp_line[0]; *s; s++)
1269 		if (*s == '*')
1270 			*s = '-';
1271 	for (i = 0; n <= p_end; i++, n++) {
1272 		p_line[n] = tp_line[i];
1273 		p_char[n] = tp_char[i];
1274 		if (p_char[n] == '-')
1275 			p_char[n] = '+';
1276 		p_len[n] = tp_len[i];
1277 	}
1278 
1279 	if (i != p_ptrn_lines + 1)
1280 		fatal("Malformed patch at line %ld: expected %ld lines, "
1281 		    "got %ld\n",
1282 		    p_input_line, p_ptrn_lines + 1, i);
1283 
1284 	i = p_ptrn_lines;
1285 	p_ptrn_lines = p_repl_lines;
1286 	p_repl_lines = i;
1287 
1288 	free(tp_line);
1289 	free(tp_len);
1290 	free(tp_char);
1291 
1292 	return true;
1293 }
1294 
1295 /*
1296  * Return the specified line position in the old file of the old context.
1297  */
1298 LINENUM
pch_first(void)1299 pch_first(void)
1300 {
1301 	return p_first;
1302 }
1303 
1304 /*
1305  * Return the number of lines of old context.
1306  */
1307 LINENUM
pch_ptrn_lines(void)1308 pch_ptrn_lines(void)
1309 {
1310 	return p_ptrn_lines;
1311 }
1312 
1313 /*
1314  * Return the probable line position in the new file of the first line.
1315  */
1316 LINENUM
pch_newfirst(void)1317 pch_newfirst(void)
1318 {
1319 	return p_newfirst;
1320 }
1321 
1322 /*
1323  * Return the number of lines in the replacement text including context.
1324  */
1325 LINENUM
pch_repl_lines(void)1326 pch_repl_lines(void)
1327 {
1328 	return p_repl_lines;
1329 }
1330 
1331 /*
1332  * Return the number of lines in the whole hunk.
1333  */
1334 LINENUM
pch_end(void)1335 pch_end(void)
1336 {
1337 	return p_end;
1338 }
1339 
1340 /*
1341  * Return the number of context lines before the first changed line.
1342  */
1343 LINENUM
pch_context(void)1344 pch_context(void)
1345 {
1346 	return p_context;
1347 }
1348 
1349 /*
1350  * Return the length of a particular patch line.
1351  */
1352 ssize_t
pch_line_len(LINENUM line)1353 pch_line_len(LINENUM line)
1354 {
1355 	return p_len[line];
1356 }
1357 
1358 /*
1359  * Return the control character (+, -, *, !, etc) for a patch line.
1360  */
1361 char
pch_char(LINENUM line)1362 pch_char(LINENUM line)
1363 {
1364 	return p_char[line];
1365 }
1366 
1367 /*
1368  * Return a pointer to a particular patch line.
1369  */
1370 char *
pfetch(LINENUM line)1371 pfetch(LINENUM line)
1372 {
1373 	return p_line[line];
1374 }
1375 
1376 /*
1377  * Return where in the patch file this hunk began, for error messages.
1378  */
1379 LINENUM
pch_hunk_beg(void)1380 pch_hunk_beg(void)
1381 {
1382 	return p_hunk_beg;
1383 }
1384 
1385 /*
1386  * Choose the name of the file to be patched based on POSIX rules.
1387  * NOTE: the POSIX rules are amazingly stupid and we only follow them
1388  *       if the user specified --posix or set POSIXLY_CORRECT.
1389  */
1390 static char *
posix_name(const struct file_name * names,bool assume_exists)1391 posix_name(const struct file_name *names, bool assume_exists)
1392 {
1393 	char *path = NULL;
1394 	int i;
1395 
1396 	/*
1397 	 * POSIX states that the filename will be chosen from one
1398 	 * of the old, new and index names (in that order) if
1399 	 * the file exists relative to CWD after -p stripping.
1400 	 */
1401 	for (i = 0; i < MAX_FILE; i++) {
1402 		if (names[i].path != NULL && names[i].exists) {
1403 			path = names[i].path;
1404 			break;
1405 		}
1406 	}
1407 	if (path == NULL && !assume_exists) {
1408 		/*
1409 		 * No files found, check to see if the diff could be
1410 		 * creating a new file.
1411 		 */
1412 		if (path == NULL && ok_to_create_file &&
1413 		    names[NEW_FILE].path != NULL)
1414 			path = names[NEW_FILE].path;
1415 	}
1416 
1417 	return path ? xstrdup(path) : NULL;
1418 }
1419 
1420 static char *
compare_names(const struct file_name * names,bool assume_exists)1421 compare_names(const struct file_name *names, bool assume_exists)
1422 {
1423 	size_t min_components, min_baselen, min_len, tmp;
1424 	char *best = NULL;
1425 	char *path, *bn;
1426 	int i;
1427 
1428 	/*
1429 	 * The "best" name is the one with the fewest number of path
1430 	 * components, the shortest basename length, and the shortest
1431 	 * overall length (in that order).  We only use the Index: file
1432 	 * if neither of the old or new files could be intuited from
1433 	 * the diff header.
1434 	 */
1435 	min_components = min_baselen = min_len = SIZE_MAX;
1436 	for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1437 		path = names[i].path;
1438 		if (path == NULL || (!names[i].exists && !assume_exists))
1439 			continue;
1440 		if ((tmp = num_components(path)) > min_components)
1441 			continue;
1442 		if (tmp < min_components) {
1443 			min_components = tmp;
1444 			best = path;
1445 		}
1446 		bn = basename(path);
1447 		if (bn == NULL)
1448 			continue;
1449 		if ((tmp = strlen(bn)) > min_baselen)
1450 			continue;
1451 		if (tmp < min_baselen) {
1452 			min_baselen = tmp;
1453 			best = path;
1454 		}
1455 		if ((tmp = strlen(path)) > min_len)
1456 			continue;
1457 		min_len = tmp;
1458 		best = path;
1459 	}
1460 	return best;
1461 }
1462 
1463 /*
1464  * Choose the name of the file to be patched based the "best" one
1465  * available.
1466  */
1467 static char *
best_name(const struct file_name * names,bool assume_exists)1468 best_name(const struct file_name *names, bool assume_exists)
1469 {
1470 	char *best;
1471 
1472 	best = compare_names(names, assume_exists);
1473 
1474 	/* No match?  Check to see if the diff could be creating a new file. */
1475 	if (best == NULL && ok_to_create_file)
1476 		best = names[NEW_FILE].path;
1477 
1478 	return best ? xstrdup(best) : NULL;
1479 }
1480 
1481 static size_t
num_components(const char * path)1482 num_components(const char *path)
1483 {
1484 	size_t n;
1485 	const char *cp;
1486 
1487 	for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++) {
1488 		cp++;
1489 		while (*cp == '/')
1490 			cp++;		/* skip consecutive slashes */
1491 	}
1492 	return n;
1493 }
1494 
1495 /*
1496  * Convert number at NPTR into LINENUM and save address of first
1497  * character that is not a digit in ENDPTR.  If conversion is not
1498  * possible, call fatal.
1499  */
1500 LINENUM
strtolinenum(char * nptr,char ** endptr)1501 strtolinenum(char *nptr, char **endptr)
1502 {
1503 	LINENUM rv;
1504 	char c;
1505 	char *p;
1506 	const char *errstr;
1507 
1508 	for (p = nptr; isdigit((unsigned char)*p); p++)
1509 		;
1510 
1511 	if (p == nptr)
1512 		malformed();
1513 
1514 	c = *p;
1515 	*p = '\0';
1516 
1517 	rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1518 	if (errstr != NULL)
1519 		fatal("invalid line number at line %ld: `%s' is %s\n",
1520 		    p_input_line, nptr, errstr);
1521 
1522 	*p = c;
1523 	*endptr = p;
1524 
1525 	return rv;
1526 }
1527