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