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