xref: /netbsd-src/usr.bin/patch/patch.c (revision 1ffa7b76c40339c17a0fb2a09fac93f287cfc046)
1 /*	$NetBSD: patch.c,v 1.13 2003/01/19 00:50:28 kristerw Exp $	*/
2 
3 /* patch - a program to apply diffs to original files
4  *
5  * Copyright 1986, Larry Wall
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following condition
9  * is met:
10  *  1. Redistributions of source code must retain the above copyright
11  *     notice, this condition and the following disclaimer.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 #include <sys/cdefs.h>
27 #ifndef lint
28 __RCSID("$NetBSD: patch.c,v 1.13 2003/01/19 00:50:28 kristerw Exp $");
29 #endif /* not lint */
30 
31 #include "INTERN.h"
32 #include "common.h"
33 #include "EXTERN.h"
34 #include "version.h"
35 #include "util.h"
36 #include "pch.h"
37 #include "inp.h"
38 #include "backupfile.h"
39 
40 #include <stdlib.h>
41 #include <unistd.h>
42 
43 /* procedures */
44 static void reinitialize_almost_everything(void);
45 static char *nextarg(void);
46 static int optcmp(const void *, const void *);
47 static char decode_long_option(char *);
48 static void get_some_switches(void);
49 static LINENUM locate_hunk(LINENUM);
50 static void abort_hunk(void);
51 static void apply_hunk(LINENUM);
52 static void init_output(char *);
53 static void init_reject(char *);
54 static void copy_till(LINENUM);
55 static void spew_output(void);
56 static void dump_line(LINENUM);
57 static bool patch_match(LINENUM, LINENUM, LINENUM);
58 static bool similar(char *, char *, int);
59 int main(int, char *[]);
60 
61 /* TRUE if -E was specified on command line.  */
62 static int remove_empty_files = FALSE;
63 
64 /* TRUE if -R was specified on command line.  */
65 static int reverse_flag_specified = FALSE;
66 
67 /* Apply a set of diffs as appropriate. */
68 
69 int
70 main(int argc, char *argv[])
71 {
72     LINENUM where = 0;
73     LINENUM newwhere;
74     LINENUM fuzz;
75     LINENUM mymaxfuzz;
76     int hunk = 0;
77     int failed = 0;
78     int failtotal = 0;
79     int i;
80 
81     for (i = 0; i<MAXFILEC; i++)
82 	filearg[i] = NULL;
83 
84     myuid = getuid();
85 
86     /* Cons up the names of the temporary files.  */
87     {
88       /* Directory for temporary files.  */
89       char *tmpdir;
90       size_t tmpname_len;
91 
92       tmpdir = getenv ("TMPDIR");
93       if (tmpdir == NULL) {
94 	tmpdir = "/tmp";
95       }
96       tmpname_len = strlen (tmpdir) + 20;
97 
98       TMPOUTNAME = xmalloc(tmpname_len);
99       strcpy (TMPOUTNAME, tmpdir);
100       strcat (TMPOUTNAME, "/patchoXXXXXX");
101       if ((i = mkstemp(TMPOUTNAME)) < 0)
102         pfatal("can't create %s", TMPOUTNAME);
103       Close(i);
104 
105       TMPINNAME = xmalloc(tmpname_len);
106       strcpy (TMPINNAME, tmpdir);
107       strcat (TMPINNAME, "/patchiXXXXXX");
108       if ((i = mkstemp(TMPINNAME)) < 0)
109         pfatal("can't create %s", TMPINNAME);
110       Close(i);
111 
112       TMPREJNAME = xmalloc(tmpname_len);
113       strcpy (TMPREJNAME, tmpdir);
114       strcat (TMPREJNAME, "/patchrXXXXXX");
115       if ((i = mkstemp(TMPREJNAME)) < 0)
116         pfatal("can't create %s", TMPREJNAME);
117       Close(i);
118 
119       TMPPATNAME = xmalloc(tmpname_len);
120       strcpy (TMPPATNAME, tmpdir);
121       strcat (TMPPATNAME, "/patchpXXXXXX");
122       if ((i = mkstemp(TMPPATNAME)) < 0)
123         pfatal("can't create %s", TMPPATNAME);
124       Close(i);
125     }
126 
127     {
128       char *v;
129 
130       v = getenv ("SIMPLE_BACKUP_SUFFIX");
131       if (v)
132 	simple_backup_suffix = v;
133       else
134 	simple_backup_suffix = ORIGEXT;
135 #ifndef NODIR
136       v = getenv ("VERSION_CONTROL");
137       backup_type = get_version (v); /* OK to pass NULL. */
138 #endif
139     }
140 
141     /* parse switches */
142     Argc = argc;
143     Argv = argv;
144     get_some_switches();
145 
146     /* make sure we clean up /tmp in case of disaster */
147     set_signals(0);
148 
149     for (
150 	open_patch_file(filearg[1]);
151 	there_is_another_patch();
152 	reinitialize_almost_everything()
153     ) {					/* for each patch in patch file */
154 
155 	if (!skip_rest_of_patch && outname == NULL)
156 	    outname = xstrdup(filearg[0]);
157 
158 	/* for ed script just up and do it and exit */
159 	if (diff_type == ED_DIFF) {
160 	    do_ed_script();
161 	    continue;
162 	}
163 
164 	/* initialize the patched file */
165 	if (!skip_rest_of_patch)
166 	    init_output(TMPOUTNAME);
167 
168 	/* initialize reject file */
169 	init_reject(TMPREJNAME);
170 
171 	/* find out where all the lines are */
172 	if (!skip_rest_of_patch)
173 	    scan_input(filearg[0]);
174 
175 	/* from here on, open no standard i/o files, because malloc */
176 	/* might misfire and we can't catch it easily */
177 
178 	/* apply each hunk of patch */
179 	hunk = 0;
180 	failed = 0;
181 	out_of_mem = FALSE;
182 	while (another_hunk()) {
183 	    hunk++;
184 	    fuzz = Nulline;
185 	    mymaxfuzz = pch_context();
186 	    if (maxfuzz < mymaxfuzz)
187 		mymaxfuzz = maxfuzz;
188 	    if (!skip_rest_of_patch) {
189 		do {
190 		    where = locate_hunk(fuzz);
191 		    if (hunk == 1 && where == Nulline && !force) {
192 						/* dwim for reversed patch? */
193 			if (!pch_swap()) {
194 			    if (fuzz == Nulline)
195 				say(
196 "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
197 			    continue;
198 			}
199 			reverse = !reverse;
200 			where = locate_hunk(fuzz);  /* try again */
201 			if (where == Nulline) {	    /* didn't find it swapped */
202 			    if (!pch_swap())         /* put it back to normal */
203 				fatal("lost hunk on alloc error!\n");
204 			    reverse = !reverse;
205 			}
206 			else if (noreverse) {
207 			    if (!pch_swap())         /* put it back to normal */
208 				fatal("lost hunk on alloc error!\n");
209 			    reverse = !reverse;
210 			    say(
211 "Ignoring previously applied (or reversed) patch.\n");
212 			    skip_rest_of_patch = TRUE;
213 			}
214 			else if (batch) {
215 			    if (verbose)
216 				say(
217 "%seversed (or previously applied) patch detected!  %s -R.",
218 				reverse ? "R" : "Unr",
219 				reverse ? "Assuming" : "Ignoring");
220 			}
221 			else {
222 			    ask(
223 "%seversed (or previously applied) patch detected!  %s -R? [y] ",
224 				reverse ? "R" : "Unr",
225 				reverse ? "Assume" : "Ignore");
226 			    if (*buf == 'n') {
227 				ask("Apply anyway? [n] ");
228 				if (*buf != 'y')
229 				    skip_rest_of_patch = TRUE;
230 				where = Nulline;
231 				reverse = !reverse;
232 				if (!pch_swap())  /* put it back to normal */
233 				    fatal("lost hunk on alloc error!\n");
234 			    }
235 			}
236 		    }
237 		} while (!skip_rest_of_patch && where == Nulline &&
238 		    ++fuzz <= mymaxfuzz);
239 
240 		if (skip_rest_of_patch) {		/* just got decided */
241 		    Fclose(ofp);
242 		    ofp = NULL;
243 		}
244 	    }
245 
246 	    newwhere = pch_newfirst() + last_offset;
247 	    if (skip_rest_of_patch) {
248 		abort_hunk();
249 		failed++;
250 		if (verbose)
251 		    say("Hunk #%d ignored at %ld.\n", hunk, newwhere);
252 	    }
253 	    else if (where == Nulline) {
254 		abort_hunk();
255 		failed++;
256 		if (verbose)
257 		    say("Hunk #%d failed at %ld.\n", hunk, newwhere);
258 	    }
259 	    else {
260 		apply_hunk(where);
261 		if (verbose) {
262 		    say("Hunk #%d succeeded at %ld", hunk, newwhere);
263 		    if (fuzz)
264 			say(" with fuzz %ld", fuzz);
265 		    if (last_offset)
266 			say(" (offset %ld line%s)",
267 			    last_offset, last_offset==1L?"":"s");
268 		    say(".\n");
269 		}
270 	    }
271 	}
272 
273 	if (out_of_mem && using_plan_a) {
274 	    Argc = Argc_last;
275 	    Argv = Argv_last;
276 	    say("\n\nRan out of memory using Plan A--trying again...\n\n");
277 	    if (ofp)
278 	        Fclose(ofp);
279 	    ofp = NULL;
280 	    if (rejfp)
281 	        Fclose(rejfp);
282 	    rejfp = NULL;
283 	    continue;
284 	}
285 
286 	assert(hunk);
287 
288 	/* finish spewing out the new file */
289 	if (!skip_rest_of_patch)
290 	    spew_output();
291 
292 	/* and put the output where desired */
293 	ignore_signals();
294 	if (!skip_rest_of_patch) {
295 	    struct stat statbuf;
296 	    char *realout = outname;
297 
298 	    if (move_file(TMPOUTNAME, outname) < 0) {
299 		toutkeep = TRUE;
300 		realout = TMPOUTNAME;
301 		chmod(TMPOUTNAME, filemode);
302 	    }
303 	    else
304 		chmod(outname, filemode);
305 
306 	    if (remove_empty_files && stat(realout, &statbuf) == 0
307 		&& statbuf.st_size == 0) {
308 		if (verbose)
309 		    say("Removing %s (empty after patching).\n", realout);
310 	        while (unlink(realout) >= 0) ; /* while is for Eunice.  */
311 	    }
312 	}
313 	Fclose(rejfp);
314 	rejfp = NULL;
315 	if (failed) {
316 	    failtotal += failed;
317 	    if (outname != NULL) {
318 		    if (!*rejname) {
319 			    Strcpy(rejname, outname);
320 			    Strcat(rejname, REJEXT);
321 		    }
322 		    if (skip_rest_of_patch)
323 			    say("%d out of %d hunks ignored"
324 				"--saving rejects to %s\n",
325 				failed, hunk, rejname);
326 		    else
327 			    say("%d out of %d hunks failed"
328 				"--saving rejects to %s\n",
329 				failed, hunk, rejname);
330 		    if (move_file(TMPREJNAME, rejname) < 0)
331 			    trejkeep = TRUE;
332 	    } else
333 		    say("%d out of %d hunks ignored\n", failed, hunk);
334 	}
335 	set_signals(1);
336     }
337     my_exit(failtotal);
338 }
339 
340 /* Prepare to find the next patch to do in the patch file. */
341 
342 static void
343 reinitialize_almost_everything(void)
344 {
345     re_patch();
346     re_input();
347 
348     input_lines = 0;
349     last_frozen_line = 0;
350 
351     filec = 0;
352     if (filearg[0] != NULL && !out_of_mem) {
353 	free(filearg[0]);
354 	filearg[0] = NULL;
355     }
356 
357     if (outname != NULL) {
358 	free(outname);
359 	outname = NULL;
360     }
361 
362     last_offset = 0;
363 
364     diff_type = 0;
365 
366     if (revision != NULL) {
367 	free(revision);
368 	revision = NULL;
369     }
370 
371     reverse = reverse_flag_specified;
372     skip_rest_of_patch = FALSE;
373 
374     get_some_switches();
375 
376     if (filec >= 2)
377 	fatal("you may not change to a different patch file\n");
378 }
379 
380 static char *
381 nextarg(void)
382 {
383     if (!--Argc)
384 	fatal("missing argument after `%s'\n", *Argv);
385     return *++Argv;
386 }
387 
388 /* Module for handling of long options. */
389 
390 struct option {
391     char *long_opt;
392     char short_opt;
393 };
394 
395 static int
396 optcmp(const void *va, const void *vb)
397 {
398     const struct option *a = va, *b = vb;
399     return strcmp (a->long_opt, b->long_opt);
400 }
401 
402 /* Decode Long options beginning with "--" to their short equivalents. */
403 
404 static char
405 decode_long_option(char *opt)
406 {
407     /*
408      * This table must be sorted on the first field.  We also decode
409      * unimplemented options as those will probably be dealt with
410      * later, anyhow.
411      */
412     static struct option options[] = {
413       { "batch",		't' },
414       { "check",		'C' },
415       { "context",		'c' },
416       { "debug",		'x' },
417       { "directory",		'd' },
418       { "ed",			'e' },
419       { "force",		'f' },
420       { "forward",		'N' },
421       { "fuzz",			'F' },
422       { "ifdef",		'D' },
423       { "ignore-whitespace",	'l' },
424       { "normal",		'n' },
425       { "output",		'o' },
426       { "patchfile",		'i' },
427       { "prefix",		'B' },
428       { "quiet",		's' },
429       { "reject-file",		'r' },
430       { "remove-empty-files",	'E' },
431       { "reverse",		'R' },
432       { "silent",		's' },
433       { "skip",			'S' },
434       { "strip",		'p' },
435       { "suffix",		'b' },
436       { "unified",		'u' },
437       { "version",		'v' },
438       { "version-control",	'V' },
439     };
440     struct option key, *found;
441 
442     key.long_opt = opt;
443     found = bsearch(&key, options,
444 	sizeof(options) / sizeof(options[0]), sizeof(options[0]), optcmp);
445 
446     return found ? found->short_opt : '\0';
447 }
448 
449 /* Process switches and filenames up to next '+' or end of list. */
450 
451 static void
452 get_some_switches(void)
453 {
454     char *s;
455 
456     rejname[0] = '\0';
457     Argc_last = Argc;
458     Argv_last = Argv;
459     if (!Argc)
460 	return;
461     for (Argc--,Argv++; Argc; Argc--,Argv++) {
462 	s = Argv[0];
463 	if (strEQ(s, "+")) {
464 	    return;			/* + will be skipped by for loop */
465 	}
466 	if (*s != '-' || !s[1]) {
467 	    if (filec == MAXFILEC)
468 		fatal("too many file arguments\n");
469 	    if (filec == 1 && filearg[filec] != NULL)
470 		fatal("-i option and patchfile argument are mutually\
471 exclusive\n");
472 	    filearg[filec++] = xstrdup(s);
473 	}
474 	else {
475 	    char opt;
476 
477 	    if (*(s + 1) == '-') {
478 		opt = decode_long_option(s + 2);
479 		s += strlen(s) - 1;
480 	    }
481 	    else
482 		opt = *++s;
483 
484 	    switch (opt) {
485 	    case 'b':
486 		simple_backup_suffix = xstrdup(nextarg());
487 		break;
488 	    case 'B':
489 		origprae = xstrdup(nextarg());
490 		break;
491 	    case 'c':
492 		diff_type = CONTEXT_DIFF;
493 		break;
494 	    case 'd':
495 		if (!*++s)
496 		    s = nextarg();
497 		if (chdir(s) < 0)
498 		    pfatal("can't cd to %s", s);
499 		break;
500 	    case 'D':
501 	    	do_defines = TRUE;
502 		if (!*++s)
503 		    s = nextarg();
504 		if (!isalpha((unsigned char)*s) && '_' != *s)
505 		    fatal("argument to -D is not an identifier\n");
506 		Sprintf(if_defined, "#ifdef %s\n", s);
507 		Sprintf(not_defined, "#ifndef %s\n", s);
508 		Sprintf(end_defined, "#endif /* %s */\n", s);
509 		break;
510 	    case 'e':
511 		diff_type = ED_DIFF;
512 		break;
513 	    case 'E':
514 		remove_empty_files = TRUE;
515 		break;
516 	    case 'f':
517 		force = TRUE;
518 		break;
519 	    case 'F':
520 		if (*++s == '=')
521 		    s++;
522 		maxfuzz = atoi(s);
523 		break;
524 	    case 'i':
525 		if (filearg[1] != NULL)
526 		    free(filearg[1]);
527 		filearg[1] = xstrdup(nextarg());
528 		break;
529 	    case 'l':
530 		canonicalize = TRUE;
531 		break;
532 	    case 'n':
533 		diff_type = NORMAL_DIFF;
534 		break;
535 	    case 'N':
536 		noreverse = TRUE;
537 		break;
538 	    case 'o':
539 		outname = xstrdup(nextarg());
540 		break;
541 	    case 'p':
542 		if (*++s == '=')
543 		    s++;
544 		strippath = atoi(s);
545 		break;
546 	    case 'r':
547 		Strcpy(rejname, nextarg());
548 		break;
549 	    case 'R':
550 		reverse = TRUE;
551 		reverse_flag_specified = TRUE;
552 		break;
553 	    case 's':
554 		verbose = FALSE;
555 		break;
556 	    case 'S':
557 		skip_rest_of_patch = TRUE;
558 		break;
559 	    case 't':
560 		batch = TRUE;
561 		break;
562 	    case 'u':
563 		diff_type = UNI_DIFF;
564 		break;
565 	    case 'v':
566 		version();
567 		break;
568 	    case 'V':
569 #ifndef NODIR
570 		backup_type = get_version (nextarg ());
571 #endif
572 		break;
573 #ifdef DEBUGGING
574 	    case 'x':
575 		debug = atoi(s+1);
576 		break;
577 #endif
578 	    default:
579 		fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
580 		fprintf(stderr, "\
581 Usage: patch [options] [origfile [patchfile]] [+ [options] [origfile]]...\n\
582 Options:\n\
583        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
584        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
585        [-r rej-name] [-V {numbered,existing,simple}]\n");
586 		my_exit(1);
587 	    }
588 	}
589     }
590 }
591 
592 /* Attempt to find the right place to apply this hunk of patch. */
593 
594 static LINENUM
595 locate_hunk(LINENUM fuzz)
596 {
597     LINENUM first_guess = pch_first() + last_offset;
598     LINENUM offset;
599     LINENUM pat_lines = pch_ptrn_lines();
600     LINENUM max_pos_offset = input_lines - first_guess
601 				- pat_lines + 1;
602     LINENUM max_neg_offset = first_guess - last_frozen_line - 1
603 				+ pch_context();
604 
605     if (!pat_lines)			/* null range matches always */
606 	return first_guess;
607     if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
608 	max_neg_offset = first_guess - 1;
609     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
610 	return first_guess;
611     for (offset = 1; ; offset++) {
612 	bool check_after = (offset <= max_pos_offset);
613 	bool check_before = (offset <= max_neg_offset);
614 
615 	if (check_after && patch_match(first_guess, offset, fuzz)) {
616 #ifdef DEBUGGING
617 	    if (debug & 1)
618 		say("Offset changing from %ld to %ld\n", last_offset, offset);
619 #endif
620 	    last_offset = offset;
621 	    return first_guess+offset;
622 	}
623 	else if (check_before && patch_match(first_guess, -offset, fuzz)) {
624 #ifdef DEBUGGING
625 	    if (debug & 1)
626 		say("Offset changing from %ld to %ld\n", last_offset, -offset);
627 #endif
628 	    last_offset = -offset;
629 	    return first_guess-offset;
630 	}
631 	else if (!check_before && !check_after)
632 	    return Nulline;
633     }
634 }
635 
636 /* We did not find the pattern, dump out the hunk so they can handle it. */
637 
638 static void
639 abort_hunk(void)
640 {
641     LINENUM i;
642     LINENUM pat_end = pch_end();
643     /* add in last_offset to guess the same as the previous successful hunk */
644     LINENUM oldfirst = pch_first() + last_offset;
645     LINENUM newfirst = pch_newfirst() + last_offset;
646     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
647     LINENUM newlast = newfirst + pch_repl_lines() - 1;
648     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
649     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
650 
651     fprintf(rejfp, "***************\n");
652     for (i=0; i<=pat_end; i++) {
653 	switch (pch_char(i)) {
654 	case '*':
655 	    if (oldlast < oldfirst)
656 		fprintf(rejfp, "*** 0%s\n", stars);
657 	    else if (oldlast == oldfirst)
658 		fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
659 	    else
660 		fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
661 	    break;
662 	case '=':
663 	    if (newlast < newfirst)
664 		fprintf(rejfp, "--- 0%s\n", minuses);
665 	    else if (newlast == newfirst)
666 		fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
667 	    else
668 		fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
669 	    break;
670 	case '\n':
671 	    fprintf(rejfp, "%s", pfetch(i));
672 	    break;
673 	case ' ': case '-': case '+': case '!':
674 	    fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
675 	    break;
676 	default:
677 	    fatal("fatal internal error in abort_hunk\n");
678 	}
679     }
680 }
681 
682 /* We found where to apply it (we hope), so do it. */
683 
684 static void
685 apply_hunk(LINENUM where)
686 {
687     LINENUM old = 1;
688     LINENUM lastline = pch_ptrn_lines();
689     LINENUM new = lastline+1;
690 #define OUTSIDE 0
691 #define IN_IFNDEF 1
692 #define IN_IFDEF 2
693 #define IN_ELSE 3
694     int def_state = OUTSIDE;
695     bool R_do_defines = do_defines;
696     LINENUM pat_end = pch_end();
697 
698     where--;
699     while (pch_char(new) == '=' || pch_char(new) == '\n')
700 	new++;
701 
702     while (old <= lastline) {
703 	if (pch_char(old) == '-') {
704 	    copy_till(where + old - 1);
705 	    if (R_do_defines) {
706 		if (def_state == OUTSIDE) {
707 		    fputs(not_defined, ofp);
708 		    def_state = IN_IFNDEF;
709 		}
710 		else if (def_state == IN_IFDEF) {
711 		    fputs(else_defined, ofp);
712 		    def_state = IN_ELSE;
713 		}
714 		fputs(pfetch(old), ofp);
715 	    }
716 	    last_frozen_line++;
717 	    old++;
718 	}
719 	else if (new > pat_end) {
720 	    break;
721 	}
722 	else if (pch_char(new) == '+') {
723 	    copy_till(where + old - 1);
724 	    if (R_do_defines) {
725 		if (def_state == IN_IFNDEF) {
726 		    fputs(else_defined, ofp);
727 		    def_state = IN_ELSE;
728 		}
729 		else if (def_state == OUTSIDE) {
730 		    fputs(if_defined, ofp);
731 		    def_state = IN_IFDEF;
732 		}
733 	    }
734 	    fputs(pfetch(new), ofp);
735 	    new++;
736 	}
737 	else if (pch_char(new) != pch_char(old)) {
738 	    say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
739 		pch_hunk_beg() + old,
740 		pch_hunk_beg() + new);
741 #ifdef DEBUGGING
742 	    say("oldchar = '%c', newchar = '%c'\n",
743 		pch_char(old), pch_char(new));
744 #endif
745 	    my_exit(1);
746 	}
747 	else if (pch_char(new) == '!') {
748 	    copy_till(where + old - 1);
749 	    if (R_do_defines) {
750 	       fputs(not_defined, ofp);
751 	       def_state = IN_IFNDEF;
752 	    }
753 	    while (pch_char(old) == '!') {
754 		if (R_do_defines) {
755 		    fputs(pfetch(old), ofp);
756 		}
757 		last_frozen_line++;
758 		old++;
759 	    }
760 	    if (R_do_defines) {
761 		fputs(else_defined, ofp);
762 		def_state = IN_ELSE;
763 	    }
764 	    while (pch_char(new) == '!') {
765 		fputs(pfetch(new), ofp);
766 		new++;
767 	    }
768 	}
769 	else {
770 	    assert(pch_char(new) == ' ');
771 	    old++;
772 	    new++;
773 	    if (R_do_defines && def_state != OUTSIDE) {
774 		fputs(end_defined, ofp);
775 		def_state = OUTSIDE;
776 	    }
777 	}
778     }
779     if (new <= pat_end && pch_char(new) == '+') {
780 	copy_till(where + old - 1);
781 	if (R_do_defines) {
782 	    if (def_state == OUTSIDE) {
783 	    	fputs(if_defined, ofp);
784 		def_state = IN_IFDEF;
785 	    }
786 	    else if (def_state == IN_IFNDEF) {
787 		fputs(else_defined, ofp);
788 		def_state = IN_ELSE;
789 	    }
790 	}
791 	while (new <= pat_end && pch_char(new) == '+') {
792 	    fputs(pfetch(new), ofp);
793 	    new++;
794 	}
795     }
796     if (R_do_defines && def_state != OUTSIDE) {
797 	fputs(end_defined, ofp);
798     }
799 }
800 
801 /* Open the new file. */
802 
803 static void
804 init_output(char *name)
805 {
806     ofp = fopen(name, "w");
807     if (ofp == NULL)
808 	pfatal("can't create %s", name);
809 }
810 
811 /* Open a file to put hunks we can't locate. */
812 
813 static void
814 init_reject(char *name)
815 {
816     rejfp = fopen(name, "w");
817     if (rejfp == NULL)
818 	pfatal("can't create %s", name);
819 }
820 
821 /* Copy input file to output, up to wherever hunk is to be applied. */
822 
823 static void
824 copy_till(LINENUM lastline)
825 {
826     LINENUM R_last_frozen_line = last_frozen_line;
827 
828     if (R_last_frozen_line > lastline)
829 	fatal("misordered hunks! output would be garbled\n");
830     while (R_last_frozen_line < lastline) {
831 	dump_line(++R_last_frozen_line);
832     }
833     last_frozen_line = R_last_frozen_line;
834 }
835 
836 /* Finish copying the input file to the output file. */
837 
838 static void
839 spew_output(void)
840 {
841 #ifdef DEBUGGING
842     if (debug & 256)
843 	say("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
844 #endif
845     if (input_lines)
846 	copy_till(input_lines);		/* dump remainder of file */
847     Fclose(ofp);
848     ofp = NULL;
849 }
850 
851 /* Copy one line from input to output. */
852 
853 static void
854 dump_line(LINENUM line)
855 {
856     char *s;
857     char R_newline = '\n';
858 
859     /* Note: string is not null terminated. */
860     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
861 }
862 
863 /* Does the patch pattern match at line base+offset? */
864 
865 static bool
866 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
867 {
868     LINENUM pline = 1 + fuzz;
869     LINENUM iline;
870     LINENUM pat_lines = pch_ptrn_lines() - fuzz;
871 
872     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
873 	if (canonicalize) {
874 	    if (!similar(ifetch(iline, (offset >= 0)),
875 			 pfetch(pline),
876 			 pch_line_len(pline) ))
877 		return FALSE;
878 	}
879 	else if (strnNE(ifetch(iline, (offset >= 0)),
880 		   pfetch(pline),
881 		   pch_line_len(pline) ))
882 	    return FALSE;
883     }
884     return TRUE;
885 }
886 
887 /* Do two lines match with canonicalized white space? */
888 
889 static bool
890 similar(char *a, char *b, int len)
891 {
892     while (len) {
893 	if (isspace((unsigned char)*b)) {/* whitespace (or \n) to match? */
894 	    if (!isspace((unsigned char)*a))/* no corresponding whitespace? */
895 		return FALSE;
896 	    while (len && isspace((unsigned char)*b) && *b != '\n')
897 		b++,len--;		/* skip pattern whitespace */
898 	    while (isspace((unsigned char)*a) && *a != '\n')
899 		a++;			/* skip target whitespace */
900 	    if (*a == '\n' || *b == '\n')
901 		return (*a == *b);	/* should end in sync */
902 	}
903 	else if (*a++ != *b++)		/* match non-whitespace chars */
904 	    return FALSE;
905 	else
906 	    len--;			/* probably not necessary */
907     }
908     return TRUE;			/* actually, this is not reached */
909 					/* since there is always a \n */
910 }
911 
912 /* Exit with cleanup. */
913 
914 void
915 my_exit(int status)
916 {
917     Unlink(TMPINNAME);
918     if (!toutkeep) {
919 	Unlink(TMPOUTNAME);
920     }
921     if (!trejkeep) {
922 	Unlink(TMPREJNAME);
923     }
924     Unlink(TMPPATNAME);
925     exit(status);
926 }
927