xref: /netbsd/usr.bin/patch/patch.c (revision 33131ab9)
1 /*	$NetBSD: patch.c,v 1.22 2004/12/09 18:06:10 mycroft 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.22 2004/12/09 18:06:10 mycroft 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(const char *, const char *, size_t);
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       const 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       strlcpy(TMPOUTNAME, tmpdir, tmpname_len);
100       strlcat(TMPOUTNAME, "/patchoXXXXXX", tmpname_len);
101       if ((i = mkstemp(TMPOUTNAME)) < 0)
102         pfatal("can't create %s", TMPOUTNAME);
103       Close(i);
104 
105       TMPINNAME = xmalloc(tmpname_len);
106       strlcpy(TMPINNAME, tmpdir, tmpname_len);
107       strlcat(TMPINNAME, "/patchiXXXXXX", tmpname_len);
108       if ((i = mkstemp(TMPINNAME)) < 0)
109         pfatal("can't create %s", TMPINNAME);
110       Close(i);
111 
112       TMPREJNAME = xmalloc(tmpname_len);
113       strlcpy(TMPREJNAME, tmpdir, tmpname_len);
114       strlcat(TMPREJNAME, "/patchrXXXXXX", tmpname_len);
115       if ((i = mkstemp(TMPREJNAME)) < 0)
116         pfatal("can't create %s", TMPREJNAME);
117       Close(i);
118 
119       TMPPATNAME = xmalloc(tmpname_len);
120       strlcpy(TMPPATNAME, tmpdir, tmpname_len);
121       strlcat(TMPPATNAME, "/patchpXXXXXX", tmpname_len);
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 	while (another_hunk()) {
182 	    hunk++;
183 	    fuzz = Nulline;
184 	    mymaxfuzz = pch_context();
185 	    if (maxfuzz < mymaxfuzz)
186 		mymaxfuzz = maxfuzz;
187 	    if (!skip_rest_of_patch) {
188 		do {
189 		    where = locate_hunk(fuzz);
190 		    if (hunk == 1 && where == Nulline && !force) {
191 						/* dwim for reversed patch? */
192 			if (!pch_swap()) {
193 			    if (fuzz == Nulline)
194 				say(
195 "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
196 			    continue;
197 			}
198 			reverse = !reverse;
199 			where = locate_hunk(fuzz);  /* try again */
200 			if (where == Nulline) {	    /* didn't find it swapped */
201 			    if (!pch_swap())         /* put it back to normal */
202 				fatal("lost hunk on alloc error!\n");
203 			    reverse = !reverse;
204 			}
205 			else if (noreverse) {
206 			    if (!pch_swap())         /* put it back to normal */
207 				fatal("lost hunk on alloc error!\n");
208 			    reverse = !reverse;
209 			    say(
210 "Ignoring previously applied (or reversed) patch.\n");
211 			    skip_rest_of_patch = TRUE;
212 			}
213 			else if (batch) {
214 			    if (verbose)
215 				say(
216 "%seversed (or previously applied) patch detected!  %s -R.",
217 				reverse ? "R" : "Unr",
218 				reverse ? "Assuming" : "Ignoring");
219 			}
220 			else {
221 			    ask(
222 "%seversed (or previously applied) patch detected!  %s -R? [y] ",
223 				reverse ? "R" : "Unr",
224 				reverse ? "Assume" : "Ignore");
225 			    if (*buf == 'n') {
226 				ask("Apply anyway? [n] ");
227 				if (*buf != 'y')
228 				    skip_rest_of_patch = TRUE;
229 				where = Nulline;
230 				reverse = !reverse;
231 				if (!pch_swap())  /* put it back to normal */
232 				    fatal("lost hunk on alloc error!\n");
233 			    }
234 			}
235 		    }
236 		} while (!skip_rest_of_patch && where == Nulline &&
237 		    ++fuzz <= mymaxfuzz);
238 
239 		if (skip_rest_of_patch) {		/* just got decided */
240 		    Fclose(ofp);
241 		    ofp = NULL;
242 		}
243 	    }
244 
245 	    newwhere = pch_newfirst() + last_offset;
246 	    if (skip_rest_of_patch) {
247 		abort_hunk();
248 		failed++;
249 		if (verbose)
250 		    say("Hunk #%d ignored at %d.\n", hunk, newwhere);
251 	    }
252 	    else if (where == Nulline) {
253 		abort_hunk();
254 		failed++;
255 		if (verbose)
256 		    say("Hunk #%d failed at %d.\n", hunk, newwhere);
257 	    }
258 	    else {
259 		apply_hunk(where);
260 		if (verbose) {
261 		    say("Hunk #%d succeeded at %d", hunk, newwhere);
262 		    if (fuzz)
263 			say(" with fuzz %d", fuzz);
264 		    if (last_offset)
265 			say(" (offset %d line%s)",
266 			    last_offset, last_offset==1?"":"s");
267 		    say(".\n");
268 		}
269 	    }
270 	}
271 
272 	assert(hunk);
273 
274 	/* finish spewing out the new file */
275 	if (!skip_rest_of_patch)
276 	    spew_output();
277 
278 	/* and put the output where desired */
279 	ignore_signals();
280 	if (!skip_rest_of_patch) {
281 	    struct stat statbuf;
282 	    char *realout = outname;
283 
284 	    if (move_file(TMPOUTNAME, outname) < 0) {
285 		toutkeep = TRUE;
286 		realout = TMPOUTNAME;
287 		chmod(TMPOUTNAME, filemode);
288 	    }
289 	    else
290 		chmod(outname, filemode);
291 
292 	    if (remove_empty_files && stat(realout, &statbuf) == 0
293 		&& statbuf.st_size == 0) {
294 		if (verbose)
295 		    say("Removing %s (empty after patching).\n", realout);
296 	        while (unlink(realout) >= 0) ; /* while is for Eunice.  */
297 	    }
298 	}
299 	Fclose(rejfp);
300 	rejfp = NULL;
301 	if (failed) {
302 	    failtotal += failed;
303 	    if (outname != NULL) {
304 		    if (!*rejname) {
305 			    strlcpy(rejname, outname, sizeof(rejname));
306 			    strlcat(rejname, REJEXT, sizeof(rejname));
307 		    }
308 		    if (skip_rest_of_patch)
309 			    say("%d out of %d hunks ignored"
310 				"--saving rejects to %s\n",
311 				failed, hunk, rejname);
312 		    else
313 			    say("%d out of %d hunks failed"
314 				"--saving rejects to %s\n",
315 				failed, hunk, rejname);
316 		    if (move_file(TMPREJNAME, rejname) < 0)
317 			    trejkeep = TRUE;
318 	    } else
319 		    say("%d out of %d hunks ignored\n", failed, hunk);
320 	}
321 	set_signals(1);
322     }
323     my_exit(failtotal);
324     /* NOTREACHED */
325 }
326 
327 /* Prepare to find the next patch to do in the patch file. */
328 
329 static void
330 reinitialize_almost_everything(void)
331 {
332     re_patch();
333     re_input();
334 
335     input_lines = 0;
336     last_frozen_line = 0;
337 
338     filec = 0;
339     if (filearg[0] != NULL) {
340 	free(filearg[0]);
341 	filearg[0] = NULL;
342     }
343 
344     if (outname != NULL) {
345 	free(outname);
346 	outname = NULL;
347     }
348 
349     last_offset = 0;
350 
351     diff_type = 0;
352 
353     if (revision != NULL) {
354 	free(revision);
355 	revision = NULL;
356     }
357 
358     reverse = reverse_flag_specified;
359     skip_rest_of_patch = FALSE;
360 
361     get_some_switches();
362 
363     if (filec >= 2)
364 	fatal("you may not change to a different patch file\n");
365 }
366 
367 static char *
368 nextarg(void)
369 {
370     if (!--Argc)
371 	fatal("missing argument after `%s'\n", *Argv);
372     return *++Argv;
373 }
374 
375 /* Module for handling of long options. */
376 
377 struct option {
378     const char *long_opt;
379     char short_opt;
380 };
381 
382 static int
383 optcmp(const void *va, const void *vb)
384 {
385     const struct option *a = va, *b = vb;
386     return strcmp (a->long_opt, b->long_opt);
387 }
388 
389 /* Decode Long options beginning with "--" to their short equivalents. */
390 
391 static char
392 decode_long_option(char *opt)
393 {
394     /*
395      * This table must be sorted on the first field.  We also decode
396      * unimplemented options as those will probably be dealt with
397      * later, anyhow.
398      */
399     static struct option options[] = {
400       { "batch",		't' },
401       { "check",		'C' },
402       { "context",		'c' },
403       { "debug",		'x' },
404       { "directory",		'd' },
405       { "ed",			'e' },
406       { "force",		'f' },
407       { "forward",		'N' },
408       { "fuzz",			'F' },
409       { "ifdef",		'D' },
410       { "ignore-whitespace",	'l' },
411       { "normal",		'n' },
412       { "output",		'o' },
413       { "patchfile",		'i' },
414       { "prefix",		'B' },
415       { "quiet",		's' },
416       { "reject-file",		'r' },
417       { "remove-empty-files",	'E' },
418       { "reverse",		'R' },
419       { "silent",		's' },
420       { "skip",			'S' },
421       { "strip",		'p' },
422       { "suffix",		'b' },
423       { "unified",		'u' },
424       { "version",		'v' },
425       { "version-control",	'V' },
426     };
427     struct option key, *found;
428 
429     key.long_opt = opt;
430     found = bsearch(&key, options,
431 	sizeof(options) / sizeof(options[0]), sizeof(options[0]), optcmp);
432 
433     return found ? found->short_opt : '\0';
434 }
435 
436 /* Process switches and filenames up to next '+' or end of list. */
437 
438 static void
439 get_some_switches(void)
440 {
441     char *s;
442 
443     rejname[0] = '\0';
444     if (!Argc)
445 	return;
446     for (Argc--,Argv++; Argc; Argc--,Argv++) {
447 	s = Argv[0];
448 	if (strEQ(s, "+")) {
449 	    return;			/* + will be skipped by for loop */
450 	}
451 	if (*s != '-' || !s[1]) {
452 	    if (filec == MAXFILEC)
453 		fatal("too many file arguments\n");
454 	    if (filec == 1 && filearg[filec] != NULL)
455 		fatal("-i option and patchfile argument are mutually\
456 exclusive\n");
457 	    filearg[filec++] = xstrdup(s);
458 	}
459 	else {
460 	    char opt;
461 
462 	    if (*(s + 1) == '-') {
463 		opt = decode_long_option(s + 2);
464 		s = "";
465 	    }
466 	    else
467 		opt = *++s;
468 
469 	    do {
470 		switch (opt) {
471 		case 'b':
472 		    simple_backup_suffix = xstrdup(nextarg());
473 		    break;
474 		case 'B':
475 		    origprae = xstrdup(nextarg());
476 		    break;
477 		case 'c':
478 		    diff_type = CONTEXT_DIFF;
479 		    break;
480 		case 'd':
481 		    if (!*++s)
482 			s = nextarg();
483 		    if (chdir(s) < 0)
484 			pfatal("can't cd to %s", s);
485 		    s = "";
486 		    break;
487 		case 'D':
488 	    	    do_defines = TRUE;
489 		    if (!*++s)
490 			s = nextarg();
491 		    if (!isalpha((unsigned char)*s) && '_' != *s)
492 			fatal("argument to -D is not an identifier\n");
493 		    snprintf(if_defined, sizeof(if_defined), "#ifdef %s\n", s);
494 		    snprintf(not_defined, sizeof(not_defined), "#ifndef %s\n", s);
495 		    snprintf(end_defined, sizeof(end_defined),
496 			"#endif /* %s */\n", s);
497 		    s = "";
498 		    break;
499 		case 'e':
500 		    diff_type = ED_DIFF;
501 		    break;
502 		case 'E':
503 		    remove_empty_files = TRUE;
504 		    break;
505 		case 'f':
506 		    force = TRUE;
507 		    break;
508 		case 'F':
509 		    if (*++s == '=')
510 			s++;
511 		    maxfuzz = atoi(s);
512 		    s = "";
513 		    break;
514 		case 'i':
515 		    if (filearg[1] != NULL)
516 			free(filearg[1]);
517 		    filearg[1] = xstrdup(nextarg());
518 		    break;
519 		case 'l':
520 		    canonicalize = TRUE;
521 		    break;
522 		case 'n':
523 		    diff_type = NORMAL_DIFF;
524 		    break;
525 		case 'N':
526 		    noreverse = TRUE;
527 		    break;
528 		case 'o':
529 		    outname = xstrdup(nextarg());
530 		    break;
531 		case 'p':
532 		    if (*++s == '=')
533 			s++;
534 		    strippath = atoi(s);
535 		    s = "";
536 		    break;
537 		case 'r':
538 		    strlcpy(rejname, nextarg(), sizeof(rejname));
539 		    break;
540 		case 'R':
541 		    reverse = TRUE;
542 		    reverse_flag_specified = TRUE;
543 		    break;
544 		case 's':
545 		    verbose = FALSE;
546 		    break;
547 		case 'S':
548 		    skip_rest_of_patch = TRUE;
549 		    break;
550 		case 't':
551 		    batch = TRUE;
552 		    break;
553 		case 'u':
554 		    diff_type = UNI_DIFF;
555 		    break;
556 		case 'v':
557 		    version();
558 		    break;
559 		case 'V':
560 #ifndef NODIR
561 		    backup_type = get_version (nextarg ());
562 #endif
563 		    break;
564 #ifdef DEBUGGING
565 		case 'x':
566 		    debug = atoi(s+1);
567 		    s = "";
568 		    break;
569 #endif
570 		default:
571 		    fprintf(stderr, "patch: unrecognized option `%s'\n",
572 			Argv[0]);
573 		    fprintf(stderr, "\
574 Usage: patch [options] [origfile [patchfile]] [+ [options] [origfile]]...\n\
575 Options:\n\
576        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
577        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
578        [-r rej-name] [-V {numbered,existing,simple}]\n");
579 		    my_exit(1);
580 		}
581 		opt = *s ? *++s : '\0';
582 	    } while (opt != '\0');
583 	}
584     }
585 }
586 
587 /* Attempt to find the right place to apply this hunk of patch. */
588 
589 static LINENUM
590 locate_hunk(LINENUM fuzz)
591 {
592     LINENUM first_guess = pch_first() + last_offset;
593     LINENUM offset;
594     LINENUM pat_lines = pch_ptrn_lines();
595     LINENUM max_pos_offset = input_lines - first_guess
596 				- pat_lines + 1;
597     LINENUM max_neg_offset = first_guess - last_frozen_line - 1
598 				+ pch_context();
599 
600     if (!pat_lines)			/* null range matches always */
601 	return first_guess;
602     if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
603 	max_neg_offset = first_guess - 1;
604     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
605 	return first_guess;
606     for (offset = 1; ; offset++) {
607 	bool check_after = (offset <= max_pos_offset);
608 	bool check_before = (offset <= max_neg_offset);
609 
610 	if (check_after && patch_match(first_guess, offset, fuzz)) {
611 #ifdef DEBUGGING
612 	    if (debug & 1)
613 		say("Offset changing from %d to %d\n", last_offset, offset);
614 #endif
615 	    last_offset = offset;
616 	    return first_guess+offset;
617 	}
618 	else if (check_before && patch_match(first_guess, -offset, fuzz)) {
619 #ifdef DEBUGGING
620 	    if (debug & 1)
621 		say("Offset changing from %d to %d\n", last_offset, -offset);
622 #endif
623 	    last_offset = -offset;
624 	    return first_guess-offset;
625 	}
626 	else if (!check_before && !check_after)
627 	    return Nulline;
628     }
629 }
630 
631 /* We did not find the pattern, dump out the hunk so they can handle it. */
632 
633 static void
634 abort_hunk(void)
635 {
636     LINENUM i;
637     LINENUM pat_end = pch_end();
638     /* add in last_offset to guess the same as the previous successful hunk */
639     LINENUM oldfirst = pch_first() + last_offset;
640     LINENUM newfirst = pch_newfirst() + last_offset;
641     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
642     LINENUM newlast = newfirst + pch_repl_lines() - 1;
643     const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
644     const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
645 
646     fprintf(rejfp, "***************\n");
647     for (i=0; i<=pat_end; i++) {
648 	switch (pch_char(i)) {
649 	case '*':
650 	    if (oldlast < oldfirst)
651 		fprintf(rejfp, "*** 0%s\n", stars);
652 	    else if (oldlast == oldfirst)
653 		fprintf(rejfp, "*** %d%s\n", oldfirst, stars);
654 	    else
655 		fprintf(rejfp, "*** %d,%d%s\n", oldfirst, oldlast, stars);
656 	    break;
657 	case '=':
658 	    if (newlast < newfirst)
659 		fprintf(rejfp, "--- 0%s\n", minuses);
660 	    else if (newlast == newfirst)
661 		fprintf(rejfp, "--- %d%s\n", newfirst, minuses);
662 	    else
663 		fprintf(rejfp, "--- %d,%d%s\n", newfirst, newlast, minuses);
664 	    break;
665 	case '\n':
666 	    fprintf(rejfp, "%s", pfetch(i));
667 	    break;
668 	case ' ': case '-': case '+': case '!':
669 	    fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
670 	    break;
671 	default:
672 	    fatal("fatal internal error in abort_hunk\n");
673 	}
674     }
675 }
676 
677 /* We found where to apply it (we hope), so do it. */
678 
679 static void
680 apply_hunk(LINENUM where)
681 {
682     LINENUM old = 1;
683     LINENUM lastline = pch_ptrn_lines();
684     LINENUM new = lastline+1;
685 #define OUTSIDE 0
686 #define IN_IFNDEF 1
687 #define IN_IFDEF 2
688 #define IN_ELSE 3
689     int def_state = OUTSIDE;
690     bool R_do_defines = do_defines;
691     LINENUM pat_end = pch_end();
692 
693     where--;
694     while (pch_char(new) == '=' || pch_char(new) == '\n')
695 	new++;
696 
697     while (old <= lastline) {
698 	if (pch_char(old) == '-') {
699 	    copy_till(where + old - 1);
700 	    if (R_do_defines) {
701 		if (def_state == OUTSIDE) {
702 		    fputs(not_defined, ofp);
703 		    def_state = IN_IFNDEF;
704 		}
705 		else if (def_state == IN_IFDEF) {
706 		    fputs(else_defined, ofp);
707 		    def_state = IN_ELSE;
708 		}
709 		fputs(pfetch(old), ofp);
710 	    }
711 	    last_frozen_line++;
712 	    old++;
713 	}
714 	else if (new > pat_end) {
715 	    break;
716 	}
717 	else if (pch_char(new) == '+') {
718 	    copy_till(where + old - 1);
719 	    if (R_do_defines) {
720 		if (def_state == IN_IFNDEF) {
721 		    fputs(else_defined, ofp);
722 		    def_state = IN_ELSE;
723 		}
724 		else if (def_state == OUTSIDE) {
725 		    fputs(if_defined, ofp);
726 		    def_state = IN_IFDEF;
727 		}
728 	    }
729 	    fputs(pfetch(new), ofp);
730 	    new++;
731 	}
732 	else if (pch_char(new) != pch_char(old)) {
733 	    say("Out-of-sync patch, lines %d,%d--mangled text or line numbers, maybe?\n",
734 		pch_hunk_beg() + old,
735 		pch_hunk_beg() + new);
736 #ifdef DEBUGGING
737 	    say("oldchar = '%c', newchar = '%c'\n",
738 		pch_char(old), pch_char(new));
739 #endif
740 	    my_exit(1);
741 	}
742 	else if (pch_char(new) == '!') {
743 	    copy_till(where + old - 1);
744 	    if (R_do_defines) {
745 	       fputs(not_defined, ofp);
746 	       def_state = IN_IFNDEF;
747 	    }
748 	    while (pch_char(old) == '!') {
749 		if (R_do_defines) {
750 		    fputs(pfetch(old), ofp);
751 		}
752 		last_frozen_line++;
753 		old++;
754 	    }
755 	    if (R_do_defines) {
756 		fputs(else_defined, ofp);
757 		def_state = IN_ELSE;
758 	    }
759 	    while (pch_char(new) == '!') {
760 		fputs(pfetch(new), ofp);
761 		new++;
762 	    }
763 	}
764 	else {
765 	    assert(pch_char(new) == ' ');
766 	    old++;
767 	    new++;
768 	    if (R_do_defines && def_state != OUTSIDE) {
769 		fputs(end_defined, ofp);
770 		def_state = OUTSIDE;
771 	    }
772 	}
773     }
774     if (new <= pat_end && pch_char(new) == '+') {
775 	copy_till(where + old - 1);
776 	if (R_do_defines) {
777 	    if (def_state == OUTSIDE) {
778 	    	fputs(if_defined, ofp);
779 		def_state = IN_IFDEF;
780 	    }
781 	    else if (def_state == IN_IFNDEF) {
782 		fputs(else_defined, ofp);
783 		def_state = IN_ELSE;
784 	    }
785 	}
786 	while (new <= pat_end && pch_char(new) == '+') {
787 	    fputs(pfetch(new), ofp);
788 	    new++;
789 	}
790     }
791     if (R_do_defines && def_state != OUTSIDE) {
792 	fputs(end_defined, ofp);
793     }
794 }
795 
796 /* Open the new file. */
797 
798 static void
799 init_output(char *name)
800 {
801     ofp = fopen(name, "w");
802     if (ofp == NULL)
803 	pfatal("can't create %s", name);
804 }
805 
806 /* Open a file to put hunks we can't locate. */
807 
808 static void
809 init_reject(char *name)
810 {
811     rejfp = fopen(name, "w");
812     if (rejfp == NULL)
813 	pfatal("can't create %s", name);
814 }
815 
816 /* Copy input file to output, up to wherever hunk is to be applied. */
817 
818 static void
819 copy_till(LINENUM lastline)
820 {
821     LINENUM R_last_frozen_line = last_frozen_line;
822 
823     if (R_last_frozen_line > lastline)
824 	fatal("misordered hunks! output would be garbled\n");
825     while (R_last_frozen_line < lastline) {
826 	dump_line(++R_last_frozen_line);
827     }
828     last_frozen_line = R_last_frozen_line;
829 }
830 
831 /* Finish copying the input file to the output file. */
832 
833 static void
834 spew_output(void)
835 {
836 #ifdef DEBUGGING
837     if (debug & 256)
838 	say("il=%d lfl=%d\n",input_lines,last_frozen_line);
839 #endif
840     if (input_lines)
841 	copy_till(input_lines);		/* dump remainder of file */
842     Fclose(ofp);
843     ofp = NULL;
844 }
845 
846 /* Copy one line from input to output. */
847 
848 static void
849 dump_line(LINENUM line)
850 {
851     const char *s;
852     char R_newline = '\n';
853 
854     /* Note: string is not null terminated. */
855     for (s=ifetch(line); putc(*s, ofp) != R_newline; s++) ;
856 }
857 
858 /* Does the patch pattern match at line base+offset? */
859 
860 static bool
861 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
862 {
863     LINENUM pline = 1 + fuzz;
864     LINENUM iline;
865     LINENUM pat_lines = pch_ptrn_lines() - fuzz;
866 
867     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
868 	if (canonicalize) {
869 	    if (!similar(ifetch(iline),
870 			 pfetch(pline),
871 			 pch_line_len(pline) ))
872 		return FALSE;
873 	}
874 	else if (strnNE(ifetch(iline),
875 		   pfetch(pline),
876 		   pch_line_len(pline) ))
877 	    return FALSE;
878     }
879     return TRUE;
880 }
881 
882 /* Do two lines match with canonicalized white space? */
883 
884 static bool
885 similar(const char *a, const char *b, size_t len)
886 {
887     while (len) {
888 	if (isspace((unsigned char)*b)) {/* whitespace (or \n) to match? */
889 	    if (!isspace((unsigned char)*a))/* no corresponding whitespace? */
890 		return FALSE;
891 	    while (len && isspace((unsigned char)*b) && *b != '\n')
892 		b++,len--;		/* skip pattern whitespace */
893 	    while (isspace((unsigned char)*a) && *a != '\n')
894 		a++;			/* skip target whitespace */
895 	    if (*a == '\n' || *b == '\n')
896 		return (*a == *b);	/* should end in sync */
897 	}
898 	else if (*a++ != *b++)		/* match non-whitespace chars */
899 	    return FALSE;
900 	else
901 	    len--;			/* probably not necessary */
902     }
903     return TRUE;			/* actually, this is not reached */
904 					/* since there is always a \n */
905 }
906 
907 /* Exit with cleanup. */
908 
909 void
910 my_exit(int status)
911 {
912     Unlink(TMPINNAME);
913     if (!toutkeep) {
914 	Unlink(TMPOUTNAME);
915     }
916     if (!trejkeep) {
917 	Unlink(TMPREJNAME);
918     }
919     Unlink(TMPPATNAME);
920     exit(status);
921 }
922