]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - gnu/usr.bin/patch/patch.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / gnu / usr.bin / patch / patch.c
1 char rcsid[] =
2   "$FreeBSD$";
3
4 /* patch - a program to apply diffs to original files
5  *
6  * Copyright 1986, Larry Wall
7  *
8  * This program may be copied as long as you don't try to make any
9  * money off of it, or pretend that you wrote it.
10  *
11  * $Log: patch.c,v $
12  * Revision 2.0.2.0  90/05/01  22:17:50  davison
13  * patch12u: unidiff support added
14  *
15  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
16  * patch12: rindex() wasn't declared
17  *
18  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
19  * patch10: exit code improved.
20  * patch10: better support for non-flexfilenames.
21  *
22  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
23  * Short replacement caused spurious "Out of sync" message.
24  *
25  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
26  * Improved diagnostic on sync error.
27  * Moved do_ed_script() to pch.c.
28  *
29  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
30  * Fuzz factor caused offset of installed lines.
31  *
32  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
33  * Backwards search could terminate prematurely.
34  *
35  * Revision 2.0  86/09/17  15:37:32  lwall
36  * Baseline for netwide release.
37  *
38  * Revision 1.5  86/08/01  20:53:24  lwall
39  * Changed some %d's to %ld's.
40  * Linted.
41  *
42  * Revision 1.4  86/08/01  19:17:29  lwall
43  * Fixes for machines that can't vararg.
44  * Added fuzz factor.
45  * Generalized -p.
46  * General cleanup.
47  *
48  * 85/08/15 van%ucbmonet@berkeley
49  * Changes for 4.3bsd diff -c.
50  *
51  * Revision 1.3  85/03/26  15:07:43  lwall
52  * Frozen.
53  *
54  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
55  * Changed pfp->_file to fileno(pfp).
56  *
57  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
58  * Check i_ptr and i_womp to make sure they aren't null before freeing.
59  * Also allow ed output to be suppressed.
60  *
61  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
62  * Added -p option from jromine@uci-750a.
63  *
64  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
65  * Now checks for normalness of file to patch.
66  *
67  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
68  * Added -D (#ifdef) option from joe@fluke.
69  *
70  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
71  * Made smarter about SCCS subdirectories.
72  *
73  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
74  * Added -l switch to do loose string comparison.
75  *
76  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
77  * Failed hunk count not reset on multiple patch file.
78  *
79  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
80  * Branch for sdcrdcf changes.
81  *
82  * Revision 1.2  84/11/29  13:29:51  lwall
83  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
84  * multiple calls to mktemp().  Will now work on machines that can only
85  * read 32767 chars.  Added -R option for diffs with new and old swapped.
86  * Various cosmetic changes.
87  *
88  * Revision 1.1  84/11/09  17:03:58  lwall
89  * Initial revision
90  *
91  */
92
93 #include <paths.h>
94 #include "INTERN.h"
95 #include "common.h"
96 #include "EXTERN.h"
97 #include "version.h"
98 #include "util.h"
99 #include "pch.h"
100 #include "inp.h"
101 #include "backupfile.h"
102 #include "getopt.h"
103
104 /* procedures */
105
106 void    reinitialize_almost_everything(void);
107 void    get_some_switches(void);
108 LINENUM locate_hunk(LINENUM _fuzz);
109 void    abort_hunk(void);
110 void    apply_hunk(LINENUM _where);
111 void    init_output(char *_name);
112 void    init_reject(char *_name);
113 void    copy_till(LINENUM _lastline);
114 void    spew_output(void);
115 void    dump_line(LINENUM _line);
116 bool    patch_match(LINENUM _base, LINENUM _offset, LINENUM _fuzz);
117 bool    similar(char *_a, char *_b, int _len);
118 void    my_exit(int _status);
119
120
121 /* TRUE if -E was specified on command line.  */
122 static int remove_empty_files = FALSE;
123
124 /* TRUE if -R was specified on command line.  */
125 static int reverse_flag_specified = FALSE;
126
127 /* TRUE if -C was specified on command line.  */
128 int check_patch = FALSE;
129
130 /* TRUE if -I was specified on command line  */
131 /* or PATCH_INDEX_FIRST env. variable is set */
132 int index_first;
133
134 /* TRUE if -S was specified on command line. */
135 int skip_flag_specified = FALSE;
136
137 /* Apply a set of diffs as appropriate. */
138
139 int
140 main(argc,argv)
141 int argc;
142 char **argv;
143 {
144     LINENUM where;
145     LINENUM newwhere;
146     LINENUM fuzz;
147     LINENUM mymaxfuzz;
148     int hunk = 0;
149     int failed = 0;
150     int failtotal = 0;
151     bool rev_okayed = 0;
152     int i;
153
154     setbuf(stderr, serrbuf);
155     for (i = 0; i<MAXFILEC; i++)
156         filearg[i] = Nullch;
157
158     buf_size = INITLINELEN;
159     buf = malloc((MEM)(buf_size));
160     if (buf == Nullch)
161         fatal1("out of memory\n");
162
163     myuid = getuid();
164
165     index_first = getenv ("PATCH_INDEX_FIRST") != 0;
166
167     /* Cons up the names of the temporary files.  */
168     {
169       /* Directory for temporary files.  */
170       char *tmpdir;
171       int tmpname_len;
172
173       tmpdir = getenv ("TMPDIR");
174       if (tmpdir == NULL) {
175         tmpdir = _PATH_TMP;
176       }
177       tmpname_len = strlen (tmpdir) + 20;
178
179       TMPOUTNAME = (char *) malloc (tmpname_len);
180       strcpy (TMPOUTNAME, tmpdir);
181       strcat (TMPOUTNAME, "/patchoXXXXXX");
182       Mktemp(TMPOUTNAME);
183
184       TMPINNAME = (char *) malloc (tmpname_len);
185       strcpy (TMPINNAME, tmpdir);
186       strcat (TMPINNAME, "/patchiXXXXXX");
187       Mktemp(TMPINNAME);
188
189       TMPREJNAME = (char *) malloc (tmpname_len);
190       strcpy (TMPREJNAME, tmpdir);
191       strcat (TMPREJNAME, "/patchrXXXXXX");
192       Mktemp(TMPREJNAME);
193
194       TMPPATNAME = (char *) malloc (tmpname_len);
195       strcpy (TMPPATNAME, tmpdir);
196       strcat (TMPPATNAME, "/patchpXXXXXX");
197       Mktemp(TMPPATNAME);
198     }
199
200     {
201       char *v;
202
203       v = getenv ("SIMPLE_BACKUP_SUFFIX");
204       if (v)
205         simple_backup_suffix = v;
206       else
207         simple_backup_suffix = ".orig";
208 #ifndef NODIR
209       v = getenv ("VERSION_CONTROL");
210       backup_type = get_version (v); /* OK to pass NULL. */
211 #endif
212     }
213
214     /* parse switches */
215     Argc = argc;
216     Argv = argv;
217     get_some_switches();
218
219     /* make sure we clean up /tmp in case of disaster */
220     set_signals(0);
221
222     for (
223         open_patch_file(filearg[1]);
224         there_is_another_patch();
225         reinitialize_almost_everything()
226     ) {                                 /* for each patch in patch file */
227
228         if (outname == Nullch)
229             outname = savestr(filearg[0]);
230
231         /* for ed script just up and do it and exit */
232         if (diff_type == ED_DIFF) {
233             do_ed_script();
234             continue;
235         }
236
237         /* initialize the patched file */
238         if (!skip_rest_of_patch)
239             init_output(TMPOUTNAME);
240
241         /* initialize reject file */
242         init_reject(TMPREJNAME);
243
244         /* find out where all the lines are */
245         if (!skip_rest_of_patch)
246             scan_input(filearg[0]);
247
248         /* from here on, open no standard i/o files, because malloc */
249         /* might misfire and we can't catch it easily */
250
251         /* apply each hunk of patch */
252         hunk = 0;
253         failed = 0;
254         rev_okayed = FALSE;
255         out_of_mem = FALSE;
256         while (another_hunk()) {
257             hunk++;
258             fuzz = Nulline;
259             mymaxfuzz = pch_context();
260             if (maxfuzz < mymaxfuzz)
261                 mymaxfuzz = maxfuzz;
262             if (!skip_rest_of_patch) {
263                 do {
264                     where = locate_hunk(fuzz);
265                     if (hunk == 1 && where == Nulline && !(force|rev_okayed)) {
266                                                 /* dwim for reversed patch? */
267                         if (!pch_swap()) {
268                             if (fuzz == Nulline)
269                                 say1(
270 "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
271                             continue;
272                         }
273                         reverse = !reverse;
274                         where = locate_hunk(fuzz);  /* try again */
275                         if (where == Nulline) {     /* didn't find it swapped */
276                             if (!pch_swap())         /* put it back to normal */
277                                 fatal1("lost hunk on alloc error!\n");
278                             reverse = !reverse;
279                         }
280                         else if (noreverse) {
281                             if (!pch_swap())         /* put it back to normal */
282                                 fatal1("lost hunk on alloc error!\n");
283                             reverse = !reverse;
284                             say1(
285 "Ignoring previously applied (or reversed) patch.\n");
286                             skip_rest_of_patch = TRUE;
287                         }
288                         else if (batch) {
289                             if (verbose)
290                                 say3(
291 "%seversed (or previously applied) patch detected!  %s -R.",
292                                 reverse ? "R" : "Unr",
293                                 reverse ? "Assuming" : "Ignoring");
294                         }
295                         else {
296                             (void) ask3(
297 "%seversed (or previously applied) patch detected!  %s -R? [y] ",
298                                 reverse ? "R" : "Unr",
299                                 reverse ? "Assume" : "Ignore");
300                             if (*buf == 'n') {
301                                 (void) ask1("Apply anyway? [n] ");
302                                 if (*buf == 'y')
303                                     rev_okayed = TRUE;
304                                 else
305                                     skip_rest_of_patch = TRUE;
306                                 where = Nulline;
307                                 reverse = !reverse;
308                                 if (!pch_swap())  /* put it back to normal */
309                                     fatal1("lost hunk on alloc error!\n");
310                             }
311                         }
312                     }
313                 } while (!skip_rest_of_patch && where == Nulline &&
314                     ++fuzz <= mymaxfuzz);
315
316                 if (skip_rest_of_patch) {               /* just got decided */
317                     Fclose(ofp);
318                     ofp = Nullfp;
319                 }
320             }
321
322             newwhere = pch_newfirst() + last_offset;
323             if (skip_rest_of_patch) {
324                 abort_hunk();
325                 if (! skip_flag_specified)
326                     failed++;
327                 if (verbose)
328                     say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
329             }
330             else if (where == Nulline) {
331                 abort_hunk();
332                 failed++;
333                 if (verbose)
334                     say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
335             }
336             else {
337                 apply_hunk(where);
338                 if (verbose) {
339                     say3("Hunk #%d succeeded at %ld", hunk, newwhere);
340                     if (fuzz)
341                         say2(" with fuzz %ld", fuzz);
342                     if (last_offset)
343                         say3(" (offset %ld line%s)",
344                             last_offset, last_offset==1L?"":"s");
345                     say1(".\n");
346                 }
347             }
348         }
349
350         if (out_of_mem && using_plan_a) {
351             optind = optind_last;
352             say1("\n\nRan out of memory using Plan A--trying again...\n\n");
353             if (ofp)
354                 Fclose(ofp);
355             ofp = Nullfp;
356             if (rejfp)
357                 Fclose(rejfp);
358             rejfp = Nullfp;
359             continue;
360         }
361
362         assert(hunk);
363
364         /* finish spewing out the new file */
365         if (!skip_rest_of_patch)
366             spew_output();
367
368         /* and put the output where desired */
369         ignore_signals();
370         if (!skip_rest_of_patch) {
371             struct stat statbuf;
372             char *realout = outname;
373
374             if (check_patch) {
375                 ;
376             } else if (move_file(TMPOUTNAME, outname) < 0) {
377                 toutkeep = TRUE;
378                 realout = TMPOUTNAME;
379                 chmod(TMPOUTNAME, filemode);
380             }
381             else
382                 chmod(outname, filemode);
383
384             if (remove_empty_files && stat(realout, &statbuf) == 0
385                 && statbuf.st_size == 0) {
386                 if (verbose)
387                     say2("Removing %s (empty after patching).\n", realout);
388                 while (unlink(realout) >= 0) ; /* while is for Eunice.  */
389             }
390         }
391         Fclose(rejfp);
392         rejfp = Nullfp;
393         if (failed) {
394             failtotal += failed;
395             if (!*rejname) {
396                 Strlcpy(rejname, outname, sizeof(rejname));
397                 addext(rejname, ".rej", '#');
398             }
399             if (skip_rest_of_patch) {
400                 say4("%d out of %d hunks ignored--saving rejects to %s\n",
401                     failed, hunk, rejname);
402             }
403             else {
404                 say4("%d out of %d hunks failed--saving rejects to %s\n",
405                     failed, hunk, rejname);
406             }
407             if (check_patch) {
408                 ;
409             } else if (move_file(TMPREJNAME, rejname) < 0)
410                 trejkeep = TRUE;
411         }
412         set_signals(1);
413     }
414     my_exit(failtotal);
415     return (failtotal);
416 }
417
418 /* Prepare to find the next patch to do in the patch file. */
419
420 void
421 reinitialize_almost_everything(void)
422 {
423     re_patch();
424     re_input();
425
426     input_lines = 0;
427     last_frozen_line = 0;
428
429     filec = 0;
430     if (filearg[0] != Nullch && !out_of_mem) {
431         free(filearg[0]);
432         filearg[0] = Nullch;
433     }
434
435     if (outname != Nullch) {
436         free(outname);
437         outname = Nullch;
438     }
439
440     last_offset = 0;
441
442     diff_type = 0;
443
444     if (revision != Nullch) {
445         free(revision);
446         revision = Nullch;
447     }
448
449     reverse = reverse_flag_specified;
450     skip_rest_of_patch = FALSE;
451     skip_flag_specified = FALSE;
452
453     get_some_switches();
454
455     if (filec >= 2)
456         fatal1("you may not change to a different patch file\n");
457 }
458
459 static char *shortopts = "-b:B:cCd:D:eEfF:i:IlnNo:p::r:RsStuvV:x:";
460 static struct option longopts[] =
461 {
462   {"suffix", 1, NULL, 'b'},
463   {"prefix", 1, NULL, 'B'},
464   {"check", 0, NULL, 'C'},
465   {"context", 0, NULL, 'c'},
466   {"directory", 1, NULL, 'd'},
467   {"ifdef", 1, NULL, 'D'},
468   {"ed", 0, NULL, 'e'},
469   {"remove-empty-files", 0, NULL, 'E'},
470   {"force", 0, NULL, 'f'},
471   {"fuzz", 1, NULL, 'F'},
472   {"index-first", 0, NULL, 'I'},
473   {"ignore-whitespace", 0, NULL, 'l'},
474   {"normal", 0, NULL, 'n'},
475   {"forward", 0, NULL, 'N'},
476   {"output", 1, NULL, 'o'},
477   {"strip", 2, NULL, 'p'},
478   {"reject-file", 1, NULL, 'r'},
479   {"reverse", 0, NULL, 'R'},
480   {"quiet", 0, NULL, 's'},
481   {"silent", 0, NULL, 's'},
482   {"skip", 0, NULL, 'S'},
483   {"batch", 0, NULL, 't'},
484   {"unified", 0, NULL, 'u'},
485   {"version", 0, NULL, 'v'},
486   {"version-control", 1, NULL, 'V'},
487   {"debug", 1, NULL, 'x'},
488   {0, 0, 0, 0}
489 };
490
491 /* Process switches and filenames up to next '+' or end of list. */
492
493 void
494 get_some_switches(void)
495 {
496     Reg1 int optc;
497
498     rejname[0] = '\0';
499     optind_last = optind;
500     if (optind == Argc)
501         return;
502     while ((optc = getopt_long (Argc, Argv, shortopts, longopts, (int *) 0))
503            != -1) {
504         if (optc == 1) {
505             if (strEQ(optarg, "+"))
506                 return;
507             if (filec == MAXFILEC)
508                 fatal1("too many file arguments\n");
509             filearg[filec++] = savestr(optarg);
510         }
511         else {
512             switch (optc) {
513             case 'b':
514                 simple_backup_suffix = savestr(optarg);
515                 break;
516             case 'B':
517                 origprae = savestr(optarg);
518                 break;
519             case 'c':
520                 diff_type = CONTEXT_DIFF;
521                 break;
522             case 'C':
523                 check_patch = TRUE;
524                 break;
525             case 'd':
526                 if (chdir(optarg) < 0)
527                     pfatal2("can't cd to %s", optarg);
528                 break;
529             case 'D':
530                 do_defines = TRUE;
531                 if (!isalpha((unsigned char)*optarg) && '_' != *optarg)
532                     fatal1("argument to -D is not an identifier\n");
533                 Snprintf(if_defined, sizeof(if_defined), "#ifdef %s\n", optarg);
534                 Snprintf(not_defined, sizeof(not_defined), "#ifndef %s\n", optarg);
535                 Snprintf(end_defined, sizeof(end_defined), "#endif /* %s */\n", optarg);
536                 break;
537             case 'e':
538                 diff_type = ED_DIFF;
539                 break;
540             case 'E':
541                 remove_empty_files = TRUE;
542                 break;
543             case 'f':
544                 force = TRUE;
545                 break;
546             case 'F':
547                 maxfuzz = atoi(optarg);
548                 break;
549             case 'i':
550                 filearg[1] = savestr(optarg);
551                 break;
552             case 'I':
553                 index_first = TRUE;
554                 break;
555             case 'l':
556                 canonicalize = TRUE;
557                 break;
558             case 'n':
559                 diff_type = NORMAL_DIFF;
560                 break;
561             case 'N':
562                 noreverse = TRUE;
563                 break;
564             case 'o':
565                 outname = savestr(optarg);
566                 break;
567             case 'p':
568                 if (optarg)
569                     strippath = atoi(optarg);
570                 else
571                     strippath = 0;
572                 break;
573             case 'r':
574                 Strlcpy(rejname, optarg, sizeof(rejname));
575                 break;
576             case 'R':
577                 reverse = TRUE;
578                 reverse_flag_specified = TRUE;
579                 break;
580             case 's':
581                 verbose = FALSE;
582                 break;
583             case 'S':
584                 skip_rest_of_patch = TRUE;
585                 skip_flag_specified = TRUE;
586                 break;
587             case 't':
588                 batch = TRUE;
589                 break;
590             case 'u':
591                 diff_type = UNI_DIFF;
592                 break;
593             case 'v':
594                 version();
595                 break;
596             case 'V':
597 #ifndef NODIR
598                 backup_type = get_version (optarg);
599 #endif
600                 break;
601 #ifdef DEBUGGING
602             case 'x':
603                 debug = atoi(optarg);
604                 break;
605 #endif
606             default:
607                 fprintf(stderr, "\
608 Usage: %s [options] [origfile [patchfile]] [+ [options] [origfile]]...\n",
609                         Argv[0]);
610                 fprintf(stderr, "\
611 Options:\n\
612        [-cCeEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
613        [-D symbol] [-F max-fuzz] [-i patchfile] [-o out-file] [-p[strip-count]]\n\
614        [-r rej-name] [-V {numbered,existing,simple}] [--check] [--context]\n\
615        [--prefix=backup-prefix] [--suffix=backup-ext] [--ifdef=symbol]\n\
616        [--directory=directory] [--ed] [--fuzz=max-fuzz] [--force] [--batch]\n\
617        [--ignore-whitespace] [--forward] [--reverse] [--output=out-file]\n");
618                 fprintf(stderr, "\
619        [--strip[=strip-count]] [--normal] [--reject-file=rej-name] [--skip]\n\
620        [--remove-empty-files] [--quiet] [--silent] [--unified] [--version]\n\
621        [--version-control={numbered,existing,simple}] [--index-first]\n");
622                 my_exit(1);
623             }
624         }
625     }
626
627     /* Process any filename args given after "--".  */
628     for (; optind < Argc; ++optind) {
629         if (filec == MAXFILEC)
630             fatal1("too many file arguments\n");
631         filearg[filec++] = savestr(Argv[optind]);
632     }
633 }
634
635 /*
636  * Attempt to find the right place to apply this hunk of patch.
637  */
638 LINENUM
639 locate_hunk(LINENUM fuzz)
640 {
641     Reg1 LINENUM first_guess = pch_first() + last_offset;
642     Reg2 LINENUM offset;
643     LINENUM pat_lines = pch_ptrn_lines();
644     Reg3 LINENUM max_pos_offset = input_lines - first_guess
645                                 - pat_lines + 1;
646     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
647                                 + pch_context();
648
649     if (!pat_lines)                     /* null range matches always */
650         return first_guess;
651     if (max_neg_offset >= first_guess)  /* do not try lines < 0 */
652         max_neg_offset = first_guess - 1;
653     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
654         return first_guess;
655     for (offset = 1; ; offset++) {
656         Reg5 bool check_after = (offset <= max_pos_offset);
657         Reg6 bool check_before = (offset <= max_neg_offset);
658
659         if (check_after && patch_match(first_guess, offset, fuzz)) {
660 #ifdef DEBUGGING
661             if (debug & 1)
662                 say3("Offset changing from %ld to %ld\n", last_offset, offset);
663 #endif
664             last_offset = offset;
665             return first_guess+offset;
666         }
667         else if (check_before && patch_match(first_guess, -offset, fuzz)) {
668 #ifdef DEBUGGING
669             if (debug & 1)
670                 say3("Offset changing from %ld to %ld\n", last_offset, -offset);
671 #endif
672             last_offset = -offset;
673             return first_guess-offset;
674         }
675         else if (!check_before && !check_after)
676             return Nulline;
677     }
678 }
679
680 /* We did not find the pattern, dump out the hunk so they can handle it. */
681
682 void
683 abort_hunk(void)
684 {
685     Reg1 LINENUM i;
686     Reg2 LINENUM pat_end = pch_end();
687     /* add in last_offset to guess the same as the previous successful hunk */
688     LINENUM oldfirst = pch_first() + last_offset;
689     LINENUM newfirst = pch_newfirst() + last_offset;
690     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
691     LINENUM newlast = newfirst + pch_repl_lines() - 1;
692     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
693     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
694
695     fprintf(rejfp, "***************\n");
696     for (i=0; i<=pat_end; i++) {
697         switch (pch_char(i)) {
698         case '*':
699             if (oldlast < oldfirst)
700                 fprintf(rejfp, "*** 0%s\n", stars);
701             else if (oldlast == oldfirst)
702                 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
703             else
704                 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
705             break;
706         case '=':
707             if (newlast < newfirst)
708                 fprintf(rejfp, "--- 0%s\n", minuses);
709             else if (newlast == newfirst)
710                 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
711             else
712                 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
713             break;
714         case '\n':
715             fprintf(rejfp, "%s", pfetch(i));
716             break;
717         case ' ': case '-': case '+': case '!':
718             fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
719             break;
720         default:
721             fatal1("fatal internal error in abort_hunk\n");
722         }
723     }
724 }
725
726 /*
727  * We found where to apply it (we hope), so do it.
728  */
729 void
730 apply_hunk(LINENUM where)
731 {
732     Reg1 LINENUM old = 1;
733     Reg2 LINENUM lastline = pch_ptrn_lines();
734     Reg3 LINENUM new = lastline+1;
735 #define OUTSIDE 0
736 #define IN_IFNDEF 1
737 #define IN_IFDEF 2
738 #define IN_ELSE 3
739     Reg4 int def_state = OUTSIDE;
740     Reg5 bool R_do_defines = do_defines;
741     Reg6 LINENUM pat_end = pch_end();
742
743     where--;
744     while (pch_char(new) == '=' || pch_char(new) == '\n')
745         new++;
746
747     while (old <= lastline) {
748         if (pch_char(old) == '-') {
749             copy_till(where + old - 1);
750             if (R_do_defines) {
751                 if (def_state == OUTSIDE) {
752                     fputs(not_defined, ofp);
753                     def_state = IN_IFNDEF;
754                 }
755                 else if (def_state == IN_IFDEF) {
756                     fputs(else_defined, ofp);
757                     def_state = IN_ELSE;
758                 }
759                 fputs(pfetch(old), ofp);
760             }
761             last_frozen_line++;
762             old++;
763         }
764         else if (new > pat_end) {
765             break;
766         }
767         else if (pch_char(new) == '+') {
768             copy_till(where + old - 1);
769             if (R_do_defines) {
770                 if (def_state == IN_IFNDEF) {
771                     fputs(else_defined, ofp);
772                     def_state = IN_ELSE;
773                 }
774                 else if (def_state == OUTSIDE) {
775                     fputs(if_defined, ofp);
776                     def_state = IN_IFDEF;
777                 }
778             }
779             fputs(pfetch(new), ofp);
780             new++;
781         }
782         else if (pch_char(new) != pch_char(old)) {
783             say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
784                 pch_hunk_beg() + old,
785                 pch_hunk_beg() + new);
786 #ifdef DEBUGGING
787             say3("oldchar = '%c', newchar = '%c'\n",
788                 pch_char(old), pch_char(new));
789 #endif
790             my_exit(1);
791         }
792         else if (pch_char(new) == '!') {
793             copy_till(where + old - 1);
794             if (R_do_defines) {
795                fputs(not_defined, ofp);
796                def_state = IN_IFNDEF;
797             }
798             while (pch_char(old) == '!') {
799                 if (R_do_defines) {
800                     fputs(pfetch(old), ofp);
801                 }
802                 last_frozen_line++;
803                 old++;
804             }
805             if (R_do_defines) {
806                 fputs(else_defined, ofp);
807                 def_state = IN_ELSE;
808             }
809             while (pch_char(new) == '!') {
810                 fputs(pfetch(new), ofp);
811                 new++;
812             }
813         }
814         else {
815             assert(pch_char(new) == ' ');
816             old++;
817             new++;
818             if (R_do_defines && def_state != OUTSIDE) {
819                 fputs(end_defined, ofp);
820                 def_state = OUTSIDE;
821             }
822         }
823     }
824     if (new <= pat_end && pch_char(new) == '+') {
825         copy_till(where + old - 1);
826         if (R_do_defines) {
827             if (def_state == OUTSIDE) {
828                 fputs(if_defined, ofp);
829                 def_state = IN_IFDEF;
830             }
831             else if (def_state == IN_IFNDEF) {
832                 fputs(else_defined, ofp);
833                 def_state = IN_ELSE;
834             }
835         }
836         while (new <= pat_end && pch_char(new) == '+') {
837             fputs(pfetch(new), ofp);
838             new++;
839         }
840     }
841     if (R_do_defines && def_state != OUTSIDE) {
842         fputs(end_defined, ofp);
843     }
844 }
845
846 /* Open the new file. */
847
848 void
849 init_output(char *name)
850 {
851     ofp = fopen(name, "w");
852     if (ofp == Nullfp)
853         pfatal2("can't create %s", name);
854 }
855
856 /* Open a file to put hunks we can't locate. */
857
858 void
859 init_reject(char *name)
860 {
861     rejfp = fopen(name, "w");
862     if (rejfp == Nullfp)
863         pfatal2("can't create %s", name);
864 }
865
866 /* Copy input file to output, up to wherever hunk is to be applied. */
867
868 void
869 copy_till(LINENUM lastline)
870 {
871     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
872
873     if (R_last_frozen_line > lastline)
874         fatal1("misordered hunks! output would be garbled\n");
875     while (R_last_frozen_line < lastline) {
876         dump_line(++R_last_frozen_line);
877     }
878     last_frozen_line = R_last_frozen_line;
879 }
880
881 /* Finish copying the input file to the output file. */
882
883 void
884 spew_output(void)
885 {
886 #ifdef DEBUGGING
887     if (debug & 256)
888         say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
889 #endif
890     if (input_lines)
891         copy_till(input_lines);         /* dump remainder of file */
892     Fclose(ofp);
893     ofp = Nullfp;
894 }
895
896 /* Copy one line from input to output. */
897
898 void
899 dump_line(LINENUM line)
900 {
901     Reg1 char *s;
902     Reg2 char R_newline = '\n';
903
904     /* Note: string is not null terminated. */
905     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
906 }
907
908 /* Does the patch pattern match at line base+offset? */
909
910 bool
911 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
912 {
913     Reg1 LINENUM pline = 1 + fuzz;
914     Reg2 LINENUM iline;
915     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
916
917     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
918         if (canonicalize) {
919             if (!similar(ifetch(iline, (offset >= 0)),
920                          pfetch(pline),
921                          pch_line_len(pline) ))
922                 return FALSE;
923         }
924         else if (strnNE(ifetch(iline, (offset >= 0)),
925                    pfetch(pline),
926                    pch_line_len(pline) ))
927             return FALSE;
928     }
929     return TRUE;
930 }
931
932 /* Do two lines match with canonicalized white space? */
933
934 bool
935 similar(char *a, char *b, int len)
936 {
937     while (len) {
938         if (isspace((unsigned char)*b)) {              /* whitespace (or \n) to match? */
939             if (!isspace((unsigned char)*a))           /* no corresponding whitespace? */
940                 return FALSE;
941             while (len && isspace((unsigned char)*b) && *b != '\n')
942                 b++,len--;              /* skip pattern whitespace */
943             while (isspace((unsigned char)*a) && *a != '\n')
944                 a++;                    /* skip target whitespace */
945             if (*a == '\n' || *b == '\n')
946                 return (*a == *b);      /* should end in sync */
947         }
948         else if (*a++ != *b++)          /* match non-whitespace chars */
949             return FALSE;
950         else
951             len--;                      /* probably not necessary */
952     }
953     return TRUE;                        /* actually, this is not reached */
954                                         /* since there is always a \n */
955 }
956
957 /* Exit with cleanup. */
958
959 void
960 my_exit(int status)
961 {
962     Unlink(TMPINNAME);
963     if (!toutkeep) {
964         Unlink(TMPOUTNAME);
965     }
966     if (!trejkeep) {
967         Unlink(TMPREJNAME);
968     }
969     Unlink(TMPPATNAME);
970     exit(status);
971 }