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