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