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