xref: /netbsd/usr.bin/patch/patch.c (revision 7e5434fe)
1 /*	$NetBSD: patch.c,v 1.16 2003/05/30 22:33:58 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.16 2003/05/30 22:33:58 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 	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 			    Strcpy(rejname, outname);
306 			    Strcat(rejname, REJEXT);
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 }
325 
326 /* Prepare to find the next patch to do in the patch file. */
327 
328 static void
329 reinitialize_almost_everything(void)
330 {
331     re_patch();
332     re_input();
333 
334     input_lines = 0;
335     last_frozen_line = 0;
336 
337     filec = 0;
338     if (filearg[0] != NULL) {
339 	free(filearg[0]);
340 	filearg[0] = NULL;
341     }
342 
343     if (outname != NULL) {
344 	free(outname);
345 	outname = NULL;
346     }
347 
348     last_offset = 0;
349 
350     diff_type = 0;
351 
352     if (revision != NULL) {
353 	free(revision);
354 	revision = NULL;
355     }
356 
357     reverse = reverse_flag_specified;
358     skip_rest_of_patch = FALSE;
359 
360     get_some_switches();
361 
362     if (filec >= 2)
363 	fatal("you may not change to a different patch file\n");
364 }
365 
366 static char *
367 nextarg(void)
368 {
369     if (!--Argc)
370 	fatal("missing argument after `%s'\n", *Argv);
371     return *++Argv;
372 }
373 
374 /* Module for handling of long options. */
375 
376 struct option {
377     char *long_opt;
378     char short_opt;
379 };
380 
381 static int
382 optcmp(const void *va, const void *vb)
383 {
384     const struct option *a = va, *b = vb;
385     return strcmp (a->long_opt, b->long_opt);
386 }
387 
388 /* Decode Long options beginning with "--" to their short equivalents. */
389 
390 static char
391 decode_long_option(char *opt)
392 {
393     /*
394      * This table must be sorted on the first field.  We also decode
395      * unimplemented options as those will probably be dealt with
396      * later, anyhow.
397      */
398     static struct option options[] = {
399       { "batch",		't' },
400       { "check",		'C' },
401       { "context",		'c' },
402       { "debug",		'x' },
403       { "directory",		'd' },
404       { "ed",			'e' },
405       { "force",		'f' },
406       { "forward",		'N' },
407       { "fuzz",			'F' },
408       { "ifdef",		'D' },
409       { "ignore-whitespace",	'l' },
410       { "normal",		'n' },
411       { "output",		'o' },
412       { "patchfile",		'i' },
413       { "prefix",		'B' },
414       { "quiet",		's' },
415       { "reject-file",		'r' },
416       { "remove-empty-files",	'E' },
417       { "reverse",		'R' },
418       { "silent",		's' },
419       { "skip",			'S' },
420       { "strip",		'p' },
421       { "suffix",		'b' },
422       { "unified",		'u' },
423       { "version",		'v' },
424       { "version-control",	'V' },
425     };
426     struct option key, *found;
427 
428     key.long_opt = opt;
429     found = bsearch(&key, options,
430 	sizeof(options) / sizeof(options[0]), sizeof(options[0]), optcmp);
431 
432     return found ? found->short_opt : '\0';
433 }
434 
435 /* Process switches and filenames up to next '+' or end of list. */
436 
437 static void
438 get_some_switches(void)
439 {
440     char *s;
441 
442     rejname[0] = '\0';
443     if (!Argc)
444 	return;
445     for (Argc--,Argv++; Argc; Argc--,Argv++) {
446 	s = Argv[0];
447 	if (strEQ(s, "+")) {
448 	    return;			/* + will be skipped by for loop */
449 	}
450 	if (*s != '-' || !s[1]) {
451 	    if (filec == MAXFILEC)
452 		fatal("too many file arguments\n");
453 	    if (filec == 1 && filearg[filec] != NULL)
454 		fatal("-i option and patchfile argument are mutually\
455 exclusive\n");
456 	    filearg[filec++] = xstrdup(s);
457 	}
458 	else {
459 	    char opt;
460 
461 	    if (*(s + 1) == '-') {
462 		opt = decode_long_option(s + 2);
463 		s += strlen(s) - 1;
464 	    }
465 	    else
466 		opt = *++s;
467 
468 	    switch (opt) {
469 	    case 'b':
470 		simple_backup_suffix = xstrdup(nextarg());
471 		break;
472 	    case 'B':
473 		origprae = xstrdup(nextarg());
474 		break;
475 	    case 'c':
476 		diff_type = CONTEXT_DIFF;
477 		break;
478 	    case 'd':
479 		if (!*++s)
480 		    s = nextarg();
481 		if (chdir(s) < 0)
482 		    pfatal("can't cd to %s", s);
483 		break;
484 	    case 'D':
485 	    	do_defines = TRUE;
486 		if (!*++s)
487 		    s = nextarg();
488 		if (!isalpha((unsigned char)*s) && '_' != *s)
489 		    fatal("argument to -D is not an identifier\n");
490 		Sprintf(if_defined, "#ifdef %s\n", s);
491 		Sprintf(not_defined, "#ifndef %s\n", s);
492 		Sprintf(end_defined, "#endif /* %s */\n", s);
493 		break;
494 	    case 'e':
495 		diff_type = ED_DIFF;
496 		break;
497 	    case 'E':
498 		remove_empty_files = TRUE;
499 		break;
500 	    case 'f':
501 		force = TRUE;
502 		break;
503 	    case 'F':
504 		if (*++s == '=')
505 		    s++;
506 		maxfuzz = atoi(s);
507 		break;
508 	    case 'i':
509 		if (filearg[1] != NULL)
510 		    free(filearg[1]);
511 		filearg[1] = xstrdup(nextarg());
512 		break;
513 	    case 'l':
514 		canonicalize = TRUE;
515 		break;
516 	    case 'n':
517 		diff_type = NORMAL_DIFF;
518 		break;
519 	    case 'N':
520 		noreverse = TRUE;
521 		break;
522 	    case 'o':
523 		outname = xstrdup(nextarg());
524 		break;
525 	    case 'p':
526 		if (*++s == '=')
527 		    s++;
528 		strippath = atoi(s);
529 		break;
530 	    case 'r':
531 		Strcpy(rejname, nextarg());
532 		break;
533 	    case 'R':
534 		reverse = TRUE;
535 		reverse_flag_specified = TRUE;
536 		break;
537 	    case 's':
538 		verbose = FALSE;
539 		break;
540 	    case 'S':
541 		skip_rest_of_patch = TRUE;
542 		break;
543 	    case 't':
544 		batch = TRUE;
545 		break;
546 	    case 'u':
547 		diff_type = UNI_DIFF;
548 		break;
549 	    case 'v':
550 		version();
551 		break;
552 	    case 'V':
553 #ifndef NODIR
554 		backup_type = get_version (nextarg ());
555 #endif
556 		break;
557 #ifdef DEBUGGING
558 	    case 'x':
559 		debug = atoi(s+1);
560 		break;
561 #endif
562 	    default:
563 		fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
564 		fprintf(stderr, "\
565 Usage: patch [options] [origfile [patchfile]] [+ [options] [origfile]]...\n\
566 Options:\n\
567        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
568        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
569        [-r rej-name] [-V {numbered,existing,simple}]\n");
570 		my_exit(1);
571 	    }
572 	}
573     }
574 }
575 
576 /* Attempt to find the right place to apply this hunk of patch. */
577 
578 static LINENUM
579 locate_hunk(LINENUM fuzz)
580 {
581     LINENUM first_guess = pch_first() + last_offset;
582     LINENUM offset;
583     LINENUM pat_lines = pch_ptrn_lines();
584     LINENUM max_pos_offset = input_lines - first_guess
585 				- pat_lines + 1;
586     LINENUM max_neg_offset = first_guess - last_frozen_line - 1
587 				+ pch_context();
588 
589     if (!pat_lines)			/* null range matches always */
590 	return first_guess;
591     if (max_neg_offset >= first_guess)	/* do not try lines < 0 */
592 	max_neg_offset = first_guess - 1;
593     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
594 	return first_guess;
595     for (offset = 1; ; offset++) {
596 	bool check_after = (offset <= max_pos_offset);
597 	bool check_before = (offset <= max_neg_offset);
598 
599 	if (check_after && patch_match(first_guess, offset, fuzz)) {
600 #ifdef DEBUGGING
601 	    if (debug & 1)
602 		say("Offset changing from %d to %d\n", last_offset, offset);
603 #endif
604 	    last_offset = offset;
605 	    return first_guess+offset;
606 	}
607 	else if (check_before && patch_match(first_guess, -offset, fuzz)) {
608 #ifdef DEBUGGING
609 	    if (debug & 1)
610 		say("Offset changing from %d to %d\n", last_offset, -offset);
611 #endif
612 	    last_offset = -offset;
613 	    return first_guess-offset;
614 	}
615 	else if (!check_before && !check_after)
616 	    return Nulline;
617     }
618 }
619 
620 /* We did not find the pattern, dump out the hunk so they can handle it. */
621 
622 static void
623 abort_hunk(void)
624 {
625     LINENUM i;
626     LINENUM pat_end = pch_end();
627     /* add in last_offset to guess the same as the previous successful hunk */
628     LINENUM oldfirst = pch_first() + last_offset;
629     LINENUM newfirst = pch_newfirst() + last_offset;
630     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
631     LINENUM newlast = newfirst + pch_repl_lines() - 1;
632     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
633     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
634 
635     fprintf(rejfp, "***************\n");
636     for (i=0; i<=pat_end; i++) {
637 	switch (pch_char(i)) {
638 	case '*':
639 	    if (oldlast < oldfirst)
640 		fprintf(rejfp, "*** 0%s\n", stars);
641 	    else if (oldlast == oldfirst)
642 		fprintf(rejfp, "*** %d%s\n", oldfirst, stars);
643 	    else
644 		fprintf(rejfp, "*** %d,%d%s\n", oldfirst, oldlast, stars);
645 	    break;
646 	case '=':
647 	    if (newlast < newfirst)
648 		fprintf(rejfp, "--- 0%s\n", minuses);
649 	    else if (newlast == newfirst)
650 		fprintf(rejfp, "--- %d%s\n", newfirst, minuses);
651 	    else
652 		fprintf(rejfp, "--- %d,%d%s\n", newfirst, newlast, minuses);
653 	    break;
654 	case '\n':
655 	    fprintf(rejfp, "%s", pfetch(i));
656 	    break;
657 	case ' ': case '-': case '+': case '!':
658 	    fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
659 	    break;
660 	default:
661 	    fatal("fatal internal error in abort_hunk\n");
662 	}
663     }
664 }
665 
666 /* We found where to apply it (we hope), so do it. */
667 
668 static void
669 apply_hunk(LINENUM where)
670 {
671     LINENUM old = 1;
672     LINENUM lastline = pch_ptrn_lines();
673     LINENUM new = lastline+1;
674 #define OUTSIDE 0
675 #define IN_IFNDEF 1
676 #define IN_IFDEF 2
677 #define IN_ELSE 3
678     int def_state = OUTSIDE;
679     bool R_do_defines = do_defines;
680     LINENUM pat_end = pch_end();
681 
682     where--;
683     while (pch_char(new) == '=' || pch_char(new) == '\n')
684 	new++;
685 
686     while (old <= lastline) {
687 	if (pch_char(old) == '-') {
688 	    copy_till(where + old - 1);
689 	    if (R_do_defines) {
690 		if (def_state == OUTSIDE) {
691 		    fputs(not_defined, ofp);
692 		    def_state = IN_IFNDEF;
693 		}
694 		else if (def_state == IN_IFDEF) {
695 		    fputs(else_defined, ofp);
696 		    def_state = IN_ELSE;
697 		}
698 		fputs(pfetch(old), ofp);
699 	    }
700 	    last_frozen_line++;
701 	    old++;
702 	}
703 	else if (new > pat_end) {
704 	    break;
705 	}
706 	else if (pch_char(new) == '+') {
707 	    copy_till(where + old - 1);
708 	    if (R_do_defines) {
709 		if (def_state == IN_IFNDEF) {
710 		    fputs(else_defined, ofp);
711 		    def_state = IN_ELSE;
712 		}
713 		else if (def_state == OUTSIDE) {
714 		    fputs(if_defined, ofp);
715 		    def_state = IN_IFDEF;
716 		}
717 	    }
718 	    fputs(pfetch(new), ofp);
719 	    new++;
720 	}
721 	else if (pch_char(new) != pch_char(old)) {
722 	    say("Out-of-sync patch, lines %d,%d--mangled text or line numbers, maybe?\n",
723 		pch_hunk_beg() + old,
724 		pch_hunk_beg() + new);
725 #ifdef DEBUGGING
726 	    say("oldchar = '%c', newchar = '%c'\n",
727 		pch_char(old), pch_char(new));
728 #endif
729 	    my_exit(1);
730 	}
731 	else if (pch_char(new) == '!') {
732 	    copy_till(where + old - 1);
733 	    if (R_do_defines) {
734 	       fputs(not_defined, ofp);
735 	       def_state = IN_IFNDEF;
736 	    }
737 	    while (pch_char(old) == '!') {
738 		if (R_do_defines) {
739 		    fputs(pfetch(old), ofp);
740 		}
741 		last_frozen_line++;
742 		old++;
743 	    }
744 	    if (R_do_defines) {
745 		fputs(else_defined, ofp);
746 		def_state = IN_ELSE;
747 	    }
748 	    while (pch_char(new) == '!') {
749 		fputs(pfetch(new), ofp);
750 		new++;
751 	    }
752 	}
753 	else {
754 	    assert(pch_char(new) == ' ');
755 	    old++;
756 	    new++;
757 	    if (R_do_defines && def_state != OUTSIDE) {
758 		fputs(end_defined, ofp);
759 		def_state = OUTSIDE;
760 	    }
761 	}
762     }
763     if (new <= pat_end && pch_char(new) == '+') {
764 	copy_till(where + old - 1);
765 	if (R_do_defines) {
766 	    if (def_state == OUTSIDE) {
767 	    	fputs(if_defined, ofp);
768 		def_state = IN_IFDEF;
769 	    }
770 	    else if (def_state == IN_IFNDEF) {
771 		fputs(else_defined, ofp);
772 		def_state = IN_ELSE;
773 	    }
774 	}
775 	while (new <= pat_end && pch_char(new) == '+') {
776 	    fputs(pfetch(new), ofp);
777 	    new++;
778 	}
779     }
780     if (R_do_defines && def_state != OUTSIDE) {
781 	fputs(end_defined, ofp);
782     }
783 }
784 
785 /* Open the new file. */
786 
787 static void
788 init_output(char *name)
789 {
790     ofp = fopen(name, "w");
791     if (ofp == NULL)
792 	pfatal("can't create %s", name);
793 }
794 
795 /* Open a file to put hunks we can't locate. */
796 
797 static void
798 init_reject(char *name)
799 {
800     rejfp = fopen(name, "w");
801     if (rejfp == NULL)
802 	pfatal("can't create %s", name);
803 }
804 
805 /* Copy input file to output, up to wherever hunk is to be applied. */
806 
807 static void
808 copy_till(LINENUM lastline)
809 {
810     LINENUM R_last_frozen_line = last_frozen_line;
811 
812     if (R_last_frozen_line > lastline)
813 	fatal("misordered hunks! output would be garbled\n");
814     while (R_last_frozen_line < lastline) {
815 	dump_line(++R_last_frozen_line);
816     }
817     last_frozen_line = R_last_frozen_line;
818 }
819 
820 /* Finish copying the input file to the output file. */
821 
822 static void
823 spew_output(void)
824 {
825 #ifdef DEBUGGING
826     if (debug & 256)
827 	say("il=%d lfl=%d\n",input_lines,last_frozen_line);
828 #endif
829     if (input_lines)
830 	copy_till(input_lines);		/* dump remainder of file */
831     Fclose(ofp);
832     ofp = NULL;
833 }
834 
835 /* Copy one line from input to output. */
836 
837 static void
838 dump_line(LINENUM line)
839 {
840     char *s;
841     char R_newline = '\n';
842 
843     /* Note: string is not null terminated. */
844     for (s=ifetch(line); putc(*s, ofp) != R_newline; s++) ;
845 }
846 
847 /* Does the patch pattern match at line base+offset? */
848 
849 static bool
850 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
851 {
852     LINENUM pline = 1 + fuzz;
853     LINENUM iline;
854     LINENUM pat_lines = pch_ptrn_lines() - fuzz;
855 
856     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
857 	if (canonicalize) {
858 	    if (!similar(ifetch(iline),
859 			 pfetch(pline),
860 			 pch_line_len(pline) ))
861 		return FALSE;
862 	}
863 	else if (strnNE(ifetch(iline),
864 		   pfetch(pline),
865 		   pch_line_len(pline) ))
866 	    return FALSE;
867     }
868     return TRUE;
869 }
870 
871 /* Do two lines match with canonicalized white space? */
872 
873 static bool
874 similar(char *a, char *b, int len)
875 {
876     while (len) {
877 	if (isspace((unsigned char)*b)) {/* whitespace (or \n) to match? */
878 	    if (!isspace((unsigned char)*a))/* no corresponding whitespace? */
879 		return FALSE;
880 	    while (len && isspace((unsigned char)*b) && *b != '\n')
881 		b++,len--;		/* skip pattern whitespace */
882 	    while (isspace((unsigned char)*a) && *a != '\n')
883 		a++;			/* skip target whitespace */
884 	    if (*a == '\n' || *b == '\n')
885 		return (*a == *b);	/* should end in sync */
886 	}
887 	else if (*a++ != *b++)		/* match non-whitespace chars */
888 	    return FALSE;
889 	else
890 	    len--;			/* probably not necessary */
891     }
892     return TRUE;			/* actually, this is not reached */
893 					/* since there is always a \n */
894 }
895 
896 /* Exit with cleanup. */
897 
898 void
899 my_exit(int status)
900 {
901     Unlink(TMPINNAME);
902     if (!toutkeep) {
903 	Unlink(TMPOUTNAME);
904     }
905     if (!trejkeep) {
906 	Unlink(TMPREJNAME);
907     }
908     Unlink(TMPPATNAME);
909     exit(status);
910 }
911