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