xref: /netbsd-src/usr.bin/patch/pch.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: pch.c,v 1.19 2003/07/30 08:51:04 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.19 2003/07/30 08:51:04 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 		    /* assume blank lines got chopped */
526 		    strlcpy(buf, "  \n", sizeof(buf));
527 		} else {
528 		    if (repl_beginning && repl_could_be_missing) {
529 			repl_missing = TRUE;
530 			goto hunk_done;
531 		    }
532 		    fatal("unexpected end of file in patch\n");
533 		}
534 	    }
535 	    p_end++;
536 	    if (p_end >= hunkmax)
537 		fatal("hunk larger than current buffer size\n");
538 	    p_char[p_end] = *buf;
539 	    p_line[p_end] = NULL;
540 	    switch (*buf) {
541 	    case '*':
542 		if (strnEQ(buf, "********", 8)) {
543 		    if (repl_beginning && repl_could_be_missing) {
544 			repl_missing = TRUE;
545 			goto hunk_done;
546 		    }
547 		    else
548 			fatal("unexpected end of hunk at line %d\n",
549 			    p_input_line);
550 		}
551 		if (p_end != 0) {
552 		    if (repl_beginning && repl_could_be_missing) {
553 			repl_missing = TRUE;
554 			goto hunk_done;
555 		    }
556 		    fatal("unexpected *** at line %d: %s", p_input_line, buf);
557 		}
558 		context = 0;
559 		p_line[p_end] = xstrdup(buf);
560 		for (s = buf; *s && !isdigit((unsigned char)*s); s++)
561 			;
562 		if (!*s)
563 		    malformed();
564 		if (strnEQ(s, "0,0", 3))
565 		    strlcpy(s, s + 2, sizeof(buf) - (s - buf));
566 		p_first = atoi(s);
567 		while (isdigit((unsigned char)*s))
568 			s++;
569 		if (*s == ',') {
570 		    for (; *s && !isdigit((unsigned char)*s); s++)
571 			    ;
572 		    if (!*s)
573 			malformed();
574 		    p_ptrn_lines = atoi(s) - p_first + 1;
575 		} else if (p_first)
576 		    p_ptrn_lines = 1;
577 		else {
578 		    p_ptrn_lines = 0;
579 		    p_first = 1;
580 		}
581 		p_max = p_ptrn_lines + 6;  /* we need this much at least */
582 		while (p_max >= hunkmax)
583 		    grow_hunkmax();
584 		p_max = hunkmax;
585 		break;
586 	    case '-':
587 		if (buf[1] == '-') {
588 		    if (repl_beginning ||
589 			(p_end !=
590 			     p_ptrn_lines + 1 + (p_char[p_end - 1] == '\n'))) {
591 			if (p_end == 1) {
592 			    /* `old' lines were omitted - set up to fill */
593 			    /* them in from 'new' context lines. */
594 			    p_end = p_ptrn_lines + 1;
595 			    fillsrc = p_end + 1;
596 			    filldst = 1;
597 			    fillcnt = p_ptrn_lines;
598 			} else {
599 			    if (repl_beginning) {
600 				if (repl_could_be_missing) {
601 				    repl_missing = TRUE;
602 				    goto hunk_done;
603 				}
604 				fatal("duplicate \"---\" at line %d"
605 				      "--check line numbers at line %d\n",
606 				      p_input_line,
607 				      p_hunk_beg + repl_beginning);
608 			    } else {
609 				fatal("%s \"---\" at line %d"
610 				      "--check line numbers at line %d\n",
611 				      (p_end <= p_ptrn_lines
612 				       ? "Premature"
613 				       : "Overdue" ),
614 				      p_input_line, p_hunk_beg);
615 			    }
616 			}
617 		    }
618 		    repl_beginning = p_end;
619 		    repl_backtrack_position = ftell(pfp);
620 		    repl_patch_line = p_input_line;
621 		    p_line[p_end] = xstrdup(buf);
622 		    p_char[p_end] = '=';
623 		    for (s = buf; *s && !isdigit((unsigned char)*s); s++)
624 			    ;
625 		    if (!*s)
626 			malformed();
627 		    p_newfirst = atoi(s);
628 		    while (isdigit((unsigned char)*s))
629 			    s++;
630 		    if (*s == ',') {
631 			for (; *s && !isdigit((unsigned char)*s); s++)
632 				;
633 			if (!*s)
634 			    malformed();
635 			p_repl_lines = atoi(s) - p_newfirst + 1;
636 		    } else if (p_newfirst)
637 			p_repl_lines = 1;
638 		    else {
639 			p_repl_lines = 0;
640 			p_newfirst = 1;
641 		    }
642 		    p_max = p_repl_lines + p_end;
643 		    if (p_max > MAXHUNKSIZE)
644 			fatal("hunk too large (%d lines) at line %d: %s",
645 			      p_max, p_input_line, buf);
646 		    while (p_max >= hunkmax)
647 			grow_hunkmax();
648 		    if (p_repl_lines != ptrn_copiable
649 			&& (p_context != 0 || p_repl_lines != 1))
650 			repl_could_be_missing = FALSE;
651 		    break;
652 		}
653 		goto change_line;
654 	    case '+':  case '!':
655 		repl_could_be_missing = FALSE;
656 	    change_line:
657 		if (buf[1] == '\n' && canonicalize)
658 		    strlcpy(buf + 1," \n", sizeof(buf) - 1);
659 		if (!isspace((unsigned char)buf[1]) &&
660 		    buf[1] != '>' && buf[1] != '<' &&
661 		    repl_beginning && repl_could_be_missing) {
662 		    repl_missing = TRUE;
663 		    goto hunk_done;
664 		}
665 		if (context >= 0) {
666 		    if (context < p_context)
667 			p_context = context;
668 		    context = -1000;
669 		}
670 		p_line[p_end] = xstrdup(buf + 2);
671 		if (p_end == p_ptrn_lines)
672 		{
673 			if (remove_special_line()) {
674 				int len;
675 
676 				len = strlen(p_line[p_end]) - 1;
677 				(p_line[p_end])[len] = 0;
678 			}
679 		}
680 		break;
681 	    case '\t': case '\n':	/* assume the 2 spaces got eaten */
682 		if (repl_beginning && repl_could_be_missing &&
683 		    (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF)) {
684 		    repl_missing = TRUE;
685 		    goto hunk_done;
686 		}
687 		p_line[p_end] = xstrdup(buf);
688 		if (p_end != p_ptrn_lines + 1) {
689 		    ptrn_spaces_eaten |= (repl_beginning != 0);
690 		    context++;
691 		    if (!repl_beginning)
692 			ptrn_copiable++;
693 		    p_char[p_end] = ' ';
694 		}
695 		break;
696 	    case ' ':
697 		if (!isspace((unsigned char)buf[1]) &&
698 		    repl_beginning && repl_could_be_missing) {
699 		    repl_missing = TRUE;
700 		    goto hunk_done;
701 		}
702 		context++;
703 		if (!repl_beginning)
704 		    ptrn_copiable++;
705 		p_line[p_end] = xstrdup(buf + 2);
706 		break;
707 	    default:
708 		if (repl_beginning && repl_could_be_missing) {
709 		    repl_missing = TRUE;
710 		    goto hunk_done;
711 		}
712 		malformed();
713 	    }
714 	    /* set up p_len for strncmp() so we don't have to */
715 	    /* assume null termination */
716 	    if (p_line[p_end])
717 		p_len[p_end] = strlen(p_line[p_end]);
718 	    else
719 		p_len[p_end] = 0;
720 	}
721 
722     hunk_done:
723 	if (p_end >= 0 && !repl_beginning)
724 	    fatal("no --- found in patch at line %d\n", pch_hunk_beg());
725 
726 	if (repl_missing) {
727 	    /* reset state back to just after --- */
728 	    p_input_line = repl_patch_line;
729 	    for (p_end--; p_end > repl_beginning; p_end--)
730 		free(p_line[p_end]);
731 	    Fseek(pfp, repl_backtrack_position, 0);
732 
733 	    /* redundant 'new' context lines were omitted - set */
734 	    /* up to fill them in from the old file context */
735 	    if (!p_context && p_repl_lines == 1) {
736 		p_repl_lines = 0;
737 		p_max--;
738 	    }
739 	    fillsrc = 1;
740 	    filldst = repl_beginning + 1;
741 	    fillcnt = p_repl_lines;
742 	    p_end = p_max;
743 	} else if (!p_context && fillcnt == 1) {
744 	    /* the first hunk was a null hunk with no context */
745 	    /* and we were expecting one line -- fix it up. */
746 	    while (filldst < p_end) {
747 		p_line[filldst] = p_line[filldst + 1];
748 		p_char[filldst] = p_char[filldst + 1];
749 		p_len[filldst] = p_len[filldst + 1];
750 		filldst++;
751 	    }
752 #if 0
753 	    repl_beginning--;		/* this doesn't need to be fixed */
754 #endif
755 	    p_end--;
756 	    p_first++;			/* do append rather than insert */
757 	    fillcnt = 0;
758 	    p_ptrn_lines = 0;
759 	}
760 
761 	if (diff_type == CONTEXT_DIFF &&
762 	    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
763 	    if (verbose)
764 		say("%s\n",
765 		    "(Fascinating--this is really a new-style context diff"
766 		    "but without\nthe telltale extra asterisks on the *** "
767 		    "line that usually indicate\nthe new style...)");
768 	    diff_type = NEW_CONTEXT_DIFF;
769 	}
770 
771 	/* if there were omitted context lines, fill them in now */
772 	if (fillcnt) {
773 	    p_bfake = filldst;		/* remember where not to free() */
774 	    p_efake = filldst + fillcnt - 1;
775 	    while (fillcnt-- > 0) {
776 		while (fillsrc <= p_end && p_char[fillsrc] != ' ')
777 		    fillsrc++;
778 		if (fillsrc > p_end)
779 		    fatal("replacement text or line numbers mangled in"
780 			  " hunk at line %d\n",
781 			  p_hunk_beg);
782 		p_line[filldst] = p_line[fillsrc];
783 		p_char[filldst] = p_char[fillsrc];
784 		p_len[filldst] = p_len[fillsrc];
785 		fillsrc++; filldst++;
786 	    }
787 	    while (fillsrc <= p_end && fillsrc != repl_beginning &&
788 		   p_char[fillsrc] != ' ')
789 		fillsrc++;
790 #ifdef DEBUGGING
791 	    if (debug & 64)
792 		printf("fillsrc %d, filldst %d, rb %d, e %d\n",
793 		    fillsrc, filldst, repl_beginning, p_end);
794 #endif
795 	    if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
796 		malformed();
797 	    if (filldst != p_end + 1 && filldst != repl_beginning)
798 		malformed();
799 	}
800 
801 	if (p_line[p_end] != NULL)
802 	{
803 		if (remove_special_line()) {
804 			p_len[p_end] -= 1;
805 			(p_line[p_end])[p_len[p_end]] = 0;
806 		}
807 	}
808     } else if (diff_type == UNI_DIFF) {
809 	long line_beginning = ftell(pfp);
810 					/* file pos of the current line */
811 	LINENUM fillsrc;		/* index of old lines */
812 	LINENUM filldst;		/* index of new lines */
813 	char ch;
814 
815 	ret = pgets(buf, sizeof buf, pfp);
816 	p_input_line++;
817 	if (ret == NULL || strnNE(buf, "@@ -", 4)) {
818 	    next_intuit_at(line_beginning,p_input_line);
819 	    return FALSE;
820 	}
821 	s = buf + 4;
822 	if (!*s)
823 	    malformed();
824 	p_first = atoi(s);
825 	while (isdigit((unsigned char)*s))
826 		s++;
827 	if (*s == ',') {
828 	    p_ptrn_lines = atoi(++s);
829 	    while (isdigit((unsigned char)*s))
830 		    s++;
831 	} else
832 	    p_ptrn_lines = 1;
833 	if (*s == ' ')
834 		s++;
835 	if (*s != '+' || !*++s)
836 	    malformed();
837 	p_newfirst = atoi(s);
838 	while (isdigit((unsigned char)*s))
839 		s++;
840 	if (*s == ',') {
841 	    p_repl_lines = atoi(++s);
842 	    while (isdigit((unsigned char)*s))
843 		    s++;
844 	} else
845 	    p_repl_lines = 1;
846 	if (*s == ' ')
847 		s++;
848 	if (*s != '@')
849 	    malformed();
850 	if (!p_ptrn_lines)
851 	    p_first++;			/* do append rather than insert */
852 	p_max = p_ptrn_lines + p_repl_lines + 1;
853 	while (p_max >= hunkmax)
854 	    grow_hunkmax();
855 	fillsrc = 1;
856 	filldst = fillsrc + p_ptrn_lines;
857 	p_end = filldst + p_repl_lines;
858 	snprintf(buf, sizeof(buf), "*** %d,%d ****\n", p_first,
859 	    p_first + p_ptrn_lines - 1);
860 	p_line[0] = xstrdup(buf);
861 	p_char[0] = '*';
862         snprintf(buf, sizeof(buf), "--- %d,%d ----\n", p_newfirst,
863 		p_newfirst + p_repl_lines - 1);
864 	p_line[filldst] = xstrdup(buf);
865 	p_char[filldst++] = '=';
866 	p_context = 100;
867 	context = 0;
868 	p_hunk_beg = p_input_line + 1;
869 	while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
870 	    line_beginning = ftell(pfp);
871 	    ret = pgets(buf, sizeof buf, pfp);
872 	    p_input_line++;
873 	    if (ret == NULL) {
874 		if (p_max - filldst < 3) {
875 		    /* assume blank lines got chopped */
876 		    strlcpy(buf, " \n", sizeof(buf));
877 		} else {
878 		    fatal("unexpected end of file in patch\n");
879 		}
880 	    }
881 	    if (*buf == '\t' || *buf == '\n') {
882 		ch = ' ';		/* assume the space got eaten */
883 		s = xstrdup(buf);
884 	    } else {
885 		ch = *buf;
886 		s = xstrdup(buf + 1);
887 	    }
888 	    switch (ch) {
889 	    case '-':
890 		if (fillsrc > p_ptrn_lines) {
891 		    free(s);
892 		    p_end = filldst - 1;
893 		    malformed();
894 		}
895 		p_char[fillsrc] = ch;
896 		p_line[fillsrc] = s;
897 		p_len[fillsrc++] = strlen(s);
898 		if (fillsrc > p_ptrn_lines) {
899 			if (remove_special_line()) {
900 				p_len[fillsrc - 1] -= 1;
901 				s[p_len[fillsrc - 1]] = 0;
902 			}
903 		}
904 		break;
905 	    case '=':
906 		ch = ' ';
907 		/* FALLTHROUGH */
908 	    case ' ':
909 		if (fillsrc > p_ptrn_lines) {
910 		    free(s);
911 		    while (--filldst > p_ptrn_lines)
912 			free(p_line[filldst]);
913 		    p_end = fillsrc - 1;
914 		    malformed();
915 		}
916 		context++;
917 		p_char[fillsrc] = ch;
918 		p_line[fillsrc] = s;
919 		p_len[fillsrc++] = strlen(s);
920 		s = xstrdup(s);
921 		/* FALLTHROUGH */
922 	    case '+':
923 		if (filldst > p_end) {
924 		    free(s);
925 		    while (--filldst > p_ptrn_lines)
926 			free(p_line[filldst]);
927 		    p_end = fillsrc - 1;
928 		    malformed();
929 		}
930 		p_char[filldst] = ch;
931 		p_line[filldst] = s;
932 		p_len[filldst++] = strlen(s);
933 		if (fillsrc > p_ptrn_lines) {
934 			if (remove_special_line()) {
935 				p_len[filldst - 1] -= 1;
936 				s[p_len[filldst - 1]] = 0;
937 			}
938 		}
939 		break;
940 	    default:
941 		p_end = filldst;
942 		malformed();
943 	    }
944 	    if (ch != ' ' && context > 0) {
945 		if (context < p_context)
946 		    p_context = context;
947 		context = -1000;
948 	    }
949 	}/* while */
950     } else {				/* normal diff--fake it up */
951 	char hunk_type;
952 	int i;
953 	LINENUM min, max;
954 	long line_beginning = ftell(pfp);
955 
956 	p_context = 0;
957 	ret = pgets(buf, sizeof buf, pfp);
958 	p_input_line++;
959 	if (ret == NULL || !isdigit((unsigned char)*buf)) {
960 	    next_intuit_at(line_beginning, p_input_line);
961 	    return FALSE;
962 	}
963 	p_first = atoi(buf);
964 	for (s = buf; isdigit((unsigned char)*s); s++)
965 		;
966 	if (*s == ',') {
967 	    p_ptrn_lines = atoi(++s) - p_first + 1;
968 	    while (isdigit((unsigned char)*s))
969 		    s++;
970 	} else
971 	    p_ptrn_lines = (*s != 'a');
972 	hunk_type = *s;
973 	if (hunk_type == 'a')
974 	    p_first++;			/* do append rather than insert */
975 	min = atoi(++s);
976 	for (; isdigit((unsigned char)*s); s++)
977 		;
978 	if (*s == ',')
979 	    max = atoi(++s);
980 	else
981 	    max = min;
982 	if (hunk_type == 'd')
983 	    min++;
984 	p_end = p_ptrn_lines + 1 + max - min + 1;
985 	if (p_end > MAXHUNKSIZE)
986 	    fatal("hunk too large (%d lines) at line %d: %s",
987 		  p_end, p_input_line, buf);
988 	while (p_end >= hunkmax)
989 	    grow_hunkmax();
990 	p_newfirst = min;
991 	p_repl_lines = max - min + 1;
992 	snprintf(buf, sizeof(buf), "*** %d,%d\n", p_first,
993 	    p_first + p_ptrn_lines - 1);
994 	p_line[0] = xstrdup(buf);
995 	p_char[0] = '*';
996 	for (i = 1; i <= p_ptrn_lines; i++) {
997 	    ret = pgets(buf, sizeof buf, pfp);
998 	    p_input_line++;
999 	    if (ret == NULL)
1000 		fatal("unexpected end of file in patch at line %d\n",
1001 		      p_input_line);
1002 	    if (*buf != '<')
1003 		fatal("< expected at line %d of patch\n", p_input_line);
1004 	    p_line[i] = xstrdup(buf + 2);
1005 	    p_len[i] = strlen(p_line[i]);
1006 	    p_char[i] = '-';
1007 	}
1008 
1009 	if (remove_special_line()) {
1010 		p_len[i - 1] -= 1;
1011 		(p_line[i - 1])[p_len[i - 1]] = 0;
1012 	}
1013 
1014 	if (hunk_type == 'c') {
1015 	    ret = pgets(buf, sizeof buf, pfp);
1016 	    p_input_line++;
1017 	    if (ret == NULL)
1018 		fatal("unexpected end of file in patch at line %d\n",
1019 		    p_input_line);
1020 	    if (*buf != '-')
1021 		fatal("--- expected at line %d of patch\n", p_input_line);
1022 	}
1023 	snprintf(buf, sizeof(buf), "--- %d,%d\n", min, max);
1024 	p_line[i] = xstrdup(buf);
1025 	p_char[i] = '=';
1026 	for (i++; i <= p_end; i++) {
1027 	    ret = pgets(buf, sizeof buf, pfp);
1028 	    p_input_line++;
1029 	    if (ret == NULL)
1030 		fatal("unexpected end of file in patch at line %d\n",
1031 		    p_input_line);
1032 	    if (*buf != '>')
1033 		fatal("> expected at line %d of patch\n", p_input_line);
1034 	    p_line[i] = xstrdup(buf + 2);
1035 	    p_len[i] = strlen(p_line[i]);
1036 	    p_char[i] = '+';
1037 	}
1038 
1039 	if (remove_special_line()) {
1040 		p_len[i - 1] -= 1;
1041 		(p_line[i - 1])[p_len[i - 1]] = 0;
1042 	}
1043     }
1044     if (reverse)			/* backwards patch? */
1045 	if (!pch_swap())
1046 	    say("Not enough memory to swap next hunk!\n");
1047 #ifdef DEBUGGING
1048     if (debug & 2) {
1049 	int i;
1050 	char special;
1051 
1052 	for (i = 0; i <= p_end; i++) {
1053 	    if (i == p_ptrn_lines)
1054 		special = '^';
1055 	    else
1056 		special = ' ';
1057 	    fprintf(stderr, "%3d %c %c %s", i, p_char[i], special, p_line[i]);
1058 	    Fflush(stderr);
1059 	}
1060     }
1061 #endif
1062     if (p_end + 1 < hunkmax)	/* paranoia reigns supreme... */
1063 	p_char[p_end + 1] = '^';  /* add a stopper for apply_hunk */
1064     return TRUE;
1065 }
1066 
1067 /*
1068  * Input a line from the patch file, worrying about indentation.
1069  */
1070 char *
1071 pgets(char *bf, int sz, FILE *fp)
1072 {
1073 	char *ret = fgets(bf, sz, fp);
1074 	char *s;
1075 	int indent = 0;
1076 
1077 	if (p_indent && ret != NULL) {
1078 		for (s = buf;
1079 		     indent < p_indent &&
1080 			     (*s == ' ' || *s == '\t' || *s == 'X');
1081 		     s++) {
1082 			if (*s == '\t')
1083 				indent += 8 - (indent % 7);
1084 			else
1085 				indent++;
1086 		}
1087 		if (buf != s)
1088 			strlcpy(buf, s, sizeof(buf));
1089 	}
1090 	return ret;
1091 }
1092 
1093 /*
1094  * Reverse the old and new portions of the current hunk.
1095  */
1096 bool
1097 pch_swap(void)
1098 {
1099 	char **tp_line;		/* the text of the hunk */
1100 	size_t *tp_len;		/* length of each line */
1101 	char *tp_char;		/* +, -, and ! */
1102 	LINENUM i;
1103 	LINENUM n;
1104 	bool blankline = FALSE;
1105 	char *s;
1106 
1107 	i = p_first;
1108 	p_first = p_newfirst;
1109 	p_newfirst = i;
1110 
1111 	/* make a scratch copy */
1112 
1113 	tp_line = p_line;
1114 	tp_len = p_len;
1115 	tp_char = p_char;
1116 	p_line = NULL;		/* force set_hunkmax to allocate again */
1117 	p_len = NULL;
1118 	p_char = NULL;
1119 	set_hunkmax();
1120 	if (p_line == NULL || p_len == NULL || p_char == NULL) {
1121 		if (p_line == NULL)
1122 			free(p_line);
1123 		p_line = tp_line;
1124 		if (p_len == NULL)
1125 			free(p_len);
1126 		p_len = tp_len;
1127 		if (p_char == NULL)
1128 			free(p_char);
1129 		p_char = tp_char;
1130 		return FALSE;		/* not enough memory to swap hunk! */
1131 	}
1132 
1133 	/* now turn the new into the old */
1134 
1135 	i = p_ptrn_lines + 1;
1136 	if (tp_char[i] == '\n') {	/* account for possible blank line */
1137 		blankline = TRUE;
1138 		i++;
1139 	}
1140 	if (p_efake >= 0) {		/* fix non-freeable ptr range */
1141 		if (p_efake <= i)
1142 			n = p_end - i + 1;
1143 		else
1144 			n = -i;
1145 		p_efake += n;
1146 		p_bfake += n;
1147 	}
1148 	for (n = 0; i <= p_end; i++, n++) {
1149 		p_line[n] = tp_line[i];
1150 		p_char[n] = tp_char[i];
1151 		if (p_char[n] == '+')
1152 			p_char[n] = '-';
1153 		p_len[n] = tp_len[i];
1154 	}
1155 	if (blankline) {
1156 		i = p_ptrn_lines + 1;
1157 		p_line[n] = tp_line[i];
1158 		p_char[n] = tp_char[i];
1159 		p_len[n] = tp_len[i];
1160 		n++;
1161 	}
1162 	if (p_char[0] != '=')
1163 		fatal("malformed patch at line %d: expected `=' found `%c'\n",
1164 		    p_input_line, p_char[0]);
1165 	p_char[0] = '*';
1166 	for (s = p_line[0]; *s; s++)
1167 		if (*s == '-')
1168 			*s = '*';
1169 
1170 	/* now turn the old into the new */
1171 
1172 	if (tp_char[0] != '*')
1173 		fatal("malformed patch at line %d: expected `*' found `%c'\n",
1174 		    p_input_line, tp_char[0]);
1175 	tp_char[0] = '=';
1176 	for (s = tp_line[0]; *s; s++)
1177 		if (*s == '*')
1178 			*s = '-';
1179 	for (i = 0; n <= p_end; i++, n++) {
1180 		p_line[n] = tp_line[i];
1181 		p_char[n] = tp_char[i];
1182 		if (p_char[n] == '-')
1183 			p_char[n] = '+';
1184 		p_len[n] = tp_len[i];
1185 	}
1186 	if (i != p_ptrn_lines + 1)
1187 		fatal("malformed patch at line %d: need %d lines, got %d\n",
1188 		    p_input_line, p_ptrn_lines + 1, i);
1189 	i = p_ptrn_lines;
1190 	p_ptrn_lines = p_repl_lines;
1191 	p_repl_lines = i;
1192 	if (tp_line == NULL)
1193 		free(tp_line);
1194 	if (tp_len == NULL)
1195 		free(tp_len);
1196 	if (tp_char == NULL)
1197 		free(tp_char);
1198 	return TRUE;
1199 }
1200 
1201 /*
1202  * Return the specified line position in the old file of the old context.
1203  */
1204 LINENUM
1205 pch_first(void)
1206 {
1207 	return p_first;
1208 }
1209 
1210 /*
1211  * Return the number of lines of old context.
1212  */
1213 LINENUM
1214 pch_ptrn_lines(void)
1215 {
1216 	return p_ptrn_lines;
1217 }
1218 
1219 /*
1220  * Return the probable line position in the new file of the first line.
1221  */
1222 LINENUM
1223 pch_newfirst(void)
1224 {
1225 	return p_newfirst;
1226 }
1227 
1228 /*
1229  * Return the number of lines in the replacement text including context.
1230  */
1231 LINENUM
1232 pch_repl_lines(void)
1233 {
1234 	return p_repl_lines;
1235 }
1236 
1237 /*
1238  * Return the number of lines in the whole hunk.
1239  */
1240 LINENUM
1241 pch_end(void)
1242 {
1243 	return p_end;
1244 }
1245 
1246 /*
1247  * Return the number of context lines before the first changed line.
1248  */
1249 LINENUM
1250 pch_context(void)
1251 {
1252 	return p_context;
1253 }
1254 
1255 /*
1256  * Return the length of a particular patch line.
1257  */
1258 size_t
1259 pch_line_len(LINENUM line)
1260 {
1261 	return p_len[line];
1262 }
1263 
1264 /*
1265  * Return the control character (+, -, *, !, etc) for a patch line.
1266  */
1267 char
1268 pch_char(LINENUM line)
1269 {
1270 	return p_char[line];
1271 }
1272 
1273 /*
1274  * Return a pointer to a particular patch line.
1275  */
1276 char *
1277 pfetch(LINENUM line)
1278 {
1279 	return p_line[line];
1280 }
1281 
1282 /*
1283  * Return where in the patch file this hunk began, for error messages.
1284  */
1285 LINENUM
1286 pch_hunk_beg(void)
1287 {
1288 	return p_hunk_beg;
1289 }
1290 
1291 /*
1292  * Apply an ed script by feeding ed itself.
1293  */
1294 void
1295 do_ed_script(void)
1296 {
1297 	char *t;
1298 	long beginning_of_this_line;
1299 	bool this_line_is_command = FALSE;
1300 	FILE *pipefp = NULL;
1301 
1302 	if (!skip_rest_of_patch) {
1303 		Unlink(TMPOUTNAME);
1304 		copy_file(filearg[0], TMPOUTNAME);
1305 		if (verbose)
1306 			snprintf(buf, sizeof(buf), "/bin/ed %s", TMPOUTNAME);
1307 		else
1308 			snprintf(buf, sizeof(buf), "/bin/ed - %s", TMPOUTNAME);
1309 		pipefp = popen(buf, "w");
1310 	}
1311 	for (;;) {
1312 		beginning_of_this_line = ftell(pfp);
1313 		if (pgets(buf, sizeof buf, pfp) == NULL) {
1314 			next_intuit_at(beginning_of_this_line, p_input_line);
1315 			break;
1316 		}
1317 		p_input_line++;
1318 		for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1319 			;
1320 		this_line_is_command = (isdigit((unsigned char)*buf) &&
1321 					(*t == 'd' || *t == 'c' || *t == 'a'));
1322 		if (this_line_is_command) {
1323 			if (!skip_rest_of_patch)
1324 				fputs(buf, pipefp);
1325 			if (*t != 'd') {
1326 				while (pgets(buf, sizeof buf, pfp) != NULL) {
1327 					p_input_line++;
1328 					if (!skip_rest_of_patch)
1329 						fputs(buf, pipefp);
1330 					if (strEQ(buf, ".\n"))
1331 						break;
1332 				}
1333 			}
1334 		} else {
1335 			next_intuit_at(beginning_of_this_line,p_input_line);
1336 			break;
1337 		}
1338 	}
1339 	if (skip_rest_of_patch)
1340 		return;
1341 	fprintf(pipefp, "w\n");
1342 	fprintf(pipefp, "q\n");
1343 	Fflush(pipefp);
1344 	Pclose(pipefp);
1345 	ignore_signals();
1346 	if (move_file(TMPOUTNAME, outname) < 0) {
1347 		toutkeep = TRUE;
1348 		chmod(TMPOUTNAME, filemode);
1349 	} else
1350 		chmod(outname, filemode);
1351 	set_signals(1);
1352 }
1353