1 /* $OpenBSD: patch.c,v 1.77 2024/08/30 07:11:02 op Exp $ */
2
3 /*
4 * patch - a program to apply diffs to original files
5 *
6 * Copyright 1986, Larry Wall
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following condition is met:
10 * 1. Redistributions of source code must retain the above copyright notice,
11 * this condition and the following disclaimer.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
17 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20 * 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 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * behaviour
27 */
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32
33 #include <ctype.h>
34 #include <getopt.h>
35 #include <libgen.h>
36 #include <limits.h>
37 #include <paths.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <stdlib.h>
41
42 #include "common.h"
43 #include "util.h"
44 #include "pch.h"
45 #include "inp.h"
46 #include "backupfile.h"
47 #include "ed.h"
48
49 mode_t filemode = 0644;
50
51 char *buf; /* general purpose buffer */
52 size_t bufsz; /* general purpose buffer size */
53
54 bool using_plan_a = true; /* try to keep everything in memory */
55 bool out_of_mem = false; /* ran out of memory in plan a */
56
57 #define MAXFILEC 2
58
59 char *filearg[MAXFILEC];
60 bool ok_to_create_file = false;
61 char *outname = NULL;
62 char *origprae = NULL;
63 char *TMPOUTNAME;
64 char *TMPINNAME;
65 char *TMPREJNAME;
66 char *TMPPATNAME;
67 bool toutkeep = false;
68 bool trejkeep = false;
69 bool warn_on_invalid_line;
70 bool last_line_missing_eol;
71
72 #ifdef DEBUGGING
73 int debug = 0;
74 #endif
75
76 bool force = false;
77 bool batch = false;
78 bool verbose = true;
79 bool reverse = false;
80 bool noreverse = false;
81 bool skip_rest_of_patch = false;
82 int strippath = 957;
83 bool canonicalize = false;
84 bool check_only = false;
85 int diff_type = 0;
86 char *revision = NULL; /* prerequisite revision, if any */
87 LINENUM input_lines = 0; /* how long is input file in lines */
88 int posix = 0; /* strict POSIX mode? */
89
90 static void reinitialize_almost_everything(void);
91 static void get_some_switches(void);
92 static LINENUM locate_hunk(LINENUM);
93 static void abort_context_hunk(void);
94 static void rej_line(int, LINENUM);
95 static void abort_hunk(void);
96 static void apply_hunk(LINENUM);
97 static void init_output(const char *);
98 static void init_reject(const char *);
99 static void copy_till(LINENUM, bool);
100 static void spew_output(void);
101 static void dump_line(LINENUM, bool);
102 static bool patch_match(LINENUM, LINENUM, LINENUM);
103 static bool similar(const char *, const char *, ssize_t);
104 static __dead void usage(void);
105
106 /* true if -E was specified on command line. */
107 static bool remove_empty_files = false;
108
109 /* true if -R was specified on command line. */
110 static bool reverse_flag_specified = false;
111
112 static bool Vflag = false;
113
114 /* buffer holding the name of the rejected patch file. */
115 static char rejname[PATH_MAX];
116
117 /* how many input lines have been irretractibly output */
118 static LINENUM last_frozen_line = 0;
119
120 static int Argc; /* guess */
121 static char **Argv;
122 static int Argc_last; /* for restarting plan_b */
123 static char **Argv_last;
124
125 static FILE *ofp = NULL; /* output file pointer */
126 static FILE *rejfp = NULL; /* reject file pointer */
127
128 static int filec = 0; /* how many file arguments? */
129 static LINENUM last_offset = 0;
130 static LINENUM maxfuzz = 2;
131
132 /* patch using ifdef, ifndef, etc. */
133 static bool do_defines = false;
134 /* #ifdef xyzzy */
135 static char if_defined[128];
136 /* #ifndef xyzzy */
137 static char not_defined[128];
138 /* #else */
139 static const char else_defined[] = "#else\n";
140 /* #endif xyzzy */
141 static char end_defined[128];
142
143
144 /* Apply a set of diffs as appropriate. */
145
146 int
main(int argc,char * argv[])147 main(int argc, char *argv[])
148 {
149 int error = 0, hunk, failed, i, fd;
150 bool patch_seen;
151 LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
152 const char *tmpdir;
153 char *v;
154
155 if (pledge("stdio rpath wpath cpath tmppath fattr unveil", NULL) == -1) {
156 perror("pledge");
157 my_exit(2);
158 }
159
160 bufsz = INITLINELEN;
161 if ((buf = malloc(bufsz)) == NULL)
162 pfatal("allocating input buffer");
163 buf[0] = '\0';
164
165 setvbuf(stdout, NULL, _IOLBF, 0);
166 setvbuf(stderr, NULL, _IOLBF, 0);
167 for (i = 0; i < MAXFILEC; i++)
168 filearg[i] = NULL;
169
170 /* Cons up the names of the temporary files. */
171 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
172 tmpdir = _PATH_TMP;
173 for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
174 ;
175 i++;
176 if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
177 fatal("cannot allocate memory");
178 if ((fd = mkstemp(TMPOUTNAME)) == -1)
179 pfatal("can't create %s", TMPOUTNAME);
180 close(fd);
181
182 if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
183 fatal("cannot allocate memory");
184 if ((fd = mkstemp(TMPINNAME)) == -1)
185 pfatal("can't create %s", TMPINNAME);
186 close(fd);
187
188 if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
189 fatal("cannot allocate memory");
190 if ((fd = mkstemp(TMPREJNAME)) == -1)
191 pfatal("can't create %s", TMPREJNAME);
192 close(fd);
193
194 if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
195 fatal("cannot allocate memory");
196 if ((fd = mkstemp(TMPPATNAME)) == -1)
197 pfatal("can't create %s", TMPPATNAME);
198 close(fd);
199
200 v = getenv("SIMPLE_BACKUP_SUFFIX");
201 if (v)
202 simple_backup_suffix = v;
203 else
204 simple_backup_suffix = ORIGEXT;
205
206 /* parse switches */
207 Argc = argc;
208 Argv = argv;
209 get_some_switches();
210 if (unveil(tmpdir, "rwc") == -1) {
211 perror("unveil");
212 my_exit(2);
213 }
214 if (outname != NULL)
215 if (unveil(outname, "rwc") == -1) {
216 perror("unveil");
217 my_exit(2);
218 }
219 if (filearg[0] != NULL) {
220 char *origdir;
221
222 if (unveil(filearg[0], "rwc") == -1) {
223 perror("unveil");
224 my_exit(2);
225 }
226 if ((origdir = dirname(filearg[0])) == NULL) {
227 perror("dirname");
228 my_exit(2);
229 }
230 if (unveil(origdir, "rwc") == -1) {
231 perror("unveil");
232 my_exit(2);
233 }
234 } else {
235 if (unveil(".", "rwc") == -1) {
236 perror("unveil");
237 my_exit(2);
238 }
239 }
240 if (filearg[1] != NULL)
241 if (unveil(filearg[1], "r") == -1) {
242 perror("unveil");
243 my_exit(2);
244 }
245 if (!force && !batch)
246 if (unveil(_PATH_TTY, "r") == -1) {
247 perror("unveil");
248 my_exit(2);
249 }
250 if (*rejname != '\0')
251 if (unveil(rejname, "rwc") == -1) {
252 perror("unveil");
253 my_exit(2);
254 }
255 if (pledge("stdio rpath wpath cpath tmppath fattr", NULL) == -1) {
256 perror("pledge");
257 my_exit(2);
258 }
259
260 if (!Vflag) {
261 if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
262 v = getenv("VERSION_CONTROL");
263 if (v != NULL || !posix)
264 backup_type = get_version(v); /* OK to pass NULL. */
265 }
266
267 /* make sure we clean up /tmp in case of disaster */
268 set_signals(0);
269
270 patch_seen = false;
271 for (open_patch_file(filearg[1]); there_is_another_patch();
272 reinitialize_almost_everything()) {
273 /* for each patch in patch file */
274
275 patch_seen = true;
276
277 warn_on_invalid_line = true;
278
279 if (outname == NULL)
280 outname = xstrdup(filearg[0]);
281
282 /* initialize the patched file */
283 if (!skip_rest_of_patch)
284 init_output(TMPOUTNAME);
285
286 /* initialize reject file */
287 init_reject(TMPREJNAME);
288
289 /* find out where all the lines are */
290 if (!skip_rest_of_patch)
291 scan_input(filearg[0]);
292
293 /* for ed script just up and do it and exit */
294 if (diff_type == ED_DIFF) {
295 do_ed_script();
296 continue;
297 }
298
299 /* from here on, open no standard i/o files, because malloc */
300 /* might misfire and we can't catch it easily */
301
302 /* apply each hunk of patch */
303 hunk = 0;
304 failed = 0;
305 out_of_mem = false;
306 while (another_hunk()) {
307 hunk++;
308 fuzz = 0;
309 mymaxfuzz = pch_context();
310 if (maxfuzz < mymaxfuzz)
311 mymaxfuzz = maxfuzz;
312 if (!skip_rest_of_patch) {
313 do {
314 where = locate_hunk(fuzz);
315 if ((hunk == 1 && where == 0 && !force) ||
316 (where == 1 && pch_ptrn_lines() == 0 && !force)) {
317 /* dwim for reversed patch? */
318 if (!pch_swap()) {
319 if (fuzz == 0)
320 say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
321 continue;
322 }
323 reverse = !reverse;
324 /* try again */
325 where = locate_hunk(fuzz);
326 if (where == 0) {
327 /* didn't find it swapped */
328 if (!pch_swap())
329 /* put it back to normal */
330 fatal("lost hunk on alloc error!\n");
331 reverse = !reverse;
332
333 /* restore position if this patch creates a file */
334 if (pch_ptrn_lines() == 0)
335 where = 1;
336 } else if (noreverse) {
337 if (!pch_swap())
338 /* put it back to normal */
339 fatal("lost hunk on alloc error!\n");
340 reverse = !reverse;
341 say("Ignoring previously applied (or reversed) patch.\n");
342 skip_rest_of_patch = true;
343 } else if (batch) {
344 if (verbose)
345 say("%seversed (or previously applied) patch detected! %s -R.",
346 reverse ? "R" : "Unr",
347 reverse ? "Assuming" : "Ignoring");
348 } else {
349 ask("%seversed (or previously applied) patch detected! %s -R? [y] ",
350 reverse ? "R" : "Unr",
351 reverse ? "Assume" : "Ignore");
352 if (*buf == 'n') {
353 ask("Apply anyway? [n] ");
354 if (*buf != 'y')
355 skip_rest_of_patch = true;
356 where = 0;
357 reverse = !reverse;
358 if (!pch_swap())
359 /* put it back to normal */
360 fatal("lost hunk on alloc error!\n");
361 }
362 }
363 }
364 } while (!skip_rest_of_patch && where == 0 &&
365 ++fuzz <= mymaxfuzz);
366
367 if (skip_rest_of_patch) { /* just got decided */
368 fclose(ofp);
369 ofp = NULL;
370 }
371 }
372 newwhere = pch_newfirst() + last_offset;
373 if (skip_rest_of_patch) {
374 abort_hunk();
375 failed++;
376 if (verbose)
377 say("Hunk #%d ignored at %ld.\n",
378 hunk, newwhere);
379 } else if (where == 0) {
380 abort_hunk();
381 failed++;
382 if (verbose)
383 say("Hunk #%d failed at %ld.\n",
384 hunk, newwhere);
385 } else {
386 apply_hunk(where);
387 if (verbose) {
388 say("Hunk #%d succeeded at %ld",
389 hunk, newwhere);
390 if (fuzz != 0)
391 say(" with fuzz %ld", fuzz);
392 if (last_offset)
393 say(" (offset %ld line%s)",
394 last_offset,
395 last_offset == 1L ? "" : "s");
396 say(".\n");
397 }
398 }
399 }
400
401 if (out_of_mem && using_plan_a) {
402 Argc = Argc_last;
403 Argv = Argv_last;
404 say("\n\nRan out of memory using Plan A--trying again...\n\n");
405 if (ofp)
406 fclose(ofp);
407 ofp = NULL;
408 if (rejfp)
409 fclose(rejfp);
410 rejfp = NULL;
411 continue;
412 }
413 if (hunk == 0)
414 fatal("Internal error: hunk should not be 0\n");
415
416 /* finish spewing out the new file */
417 if (!skip_rest_of_patch)
418 spew_output();
419
420 /* and put the output where desired */
421 ignore_signals();
422 if (!skip_rest_of_patch) {
423 struct stat statbuf;
424 char *realout = outname;
425
426 if (!check_only) {
427 if (move_file(TMPOUTNAME, outname) < 0) {
428 toutkeep = true;
429 realout = TMPOUTNAME;
430 chmod(TMPOUTNAME, filemode);
431 } else
432 chmod(outname, filemode);
433
434 if (remove_empty_files &&
435 stat(realout, &statbuf) == 0 &&
436 statbuf.st_size == 0) {
437 if (verbose)
438 say("Removing %s (empty after patching).\n",
439 realout);
440 unlink(realout);
441 }
442 }
443 }
444 fclose(rejfp);
445 rejfp = NULL;
446 if (failed) {
447 error = 1;
448 if (*rejname == '\0') {
449 if (strlcpy(rejname, outname,
450 sizeof(rejname)) >= sizeof(rejname))
451 fatal("filename %s is too long\n", outname);
452 if (strlcat(rejname, REJEXT,
453 sizeof(rejname)) >= sizeof(rejname))
454 fatal("filename %s is too long\n", outname);
455 }
456 if (!check_only)
457 say("%d out of %d hunks %s--saving rejects to %s\n",
458 failed, hunk, skip_rest_of_patch ? "ignored" : "failed", rejname);
459 else
460 say("%d out of %d hunks %s\n",
461 failed, hunk, skip_rest_of_patch ? "ignored" : "failed");
462 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
463 trejkeep = true;
464 }
465 set_signals(1);
466 }
467
468 if (!patch_seen)
469 error = 2;
470
471 my_exit(error);
472 /* NOTREACHED */
473 }
474
475 /* Prepare to find the next patch to do in the patch file. */
476
477 static void
reinitialize_almost_everything(void)478 reinitialize_almost_everything(void)
479 {
480 re_patch();
481 re_input();
482
483 input_lines = 0;
484 last_frozen_line = 0;
485
486 filec = 0;
487 if (!out_of_mem) {
488 free(filearg[0]);
489 filearg[0] = NULL;
490 }
491
492 free(outname);
493 outname = NULL;
494
495 last_offset = 0;
496 diff_type = 0;
497
498 free(revision);
499 revision = NULL;
500
501 reverse = reverse_flag_specified;
502 skip_rest_of_patch = false;
503
504 get_some_switches();
505 }
506
507 /* Process switches and filenames. */
508
509 static void
get_some_switches(void)510 get_some_switches(void)
511 {
512 const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
513 static struct option longopts[] = {
514 {"backup", no_argument, 0, 'b'},
515 {"batch", no_argument, 0, 't'},
516 {"check", no_argument, 0, 'C'},
517 {"context", no_argument, 0, 'c'},
518 {"debug", required_argument, 0, 'x'},
519 {"directory", required_argument, 0, 'd'},
520 {"dry-run", no_argument, 0, 'C'},
521 {"ed", no_argument, 0, 'e'},
522 {"force", no_argument, 0, 'f'},
523 {"forward", no_argument, 0, 'N'},
524 {"fuzz", required_argument, 0, 'F'},
525 {"ifdef", required_argument, 0, 'D'},
526 {"input", required_argument, 0, 'i'},
527 {"ignore-whitespace", no_argument, 0, 'l'},
528 {"normal", no_argument, 0, 'n'},
529 {"output", required_argument, 0, 'o'},
530 {"prefix", required_argument, 0, 'B'},
531 {"quiet", no_argument, 0, 's'},
532 {"reject-file", required_argument, 0, 'r'},
533 {"remove-empty-files", no_argument, 0, 'E'},
534 {"reverse", no_argument, 0, 'R'},
535 {"silent", no_argument, 0, 's'},
536 {"strip", required_argument, 0, 'p'},
537 {"suffix", required_argument, 0, 'z'},
538 {"unified", no_argument, 0, 'u'},
539 {"version", no_argument, 0, 'v'},
540 {"version-control", required_argument, 0, 'V'},
541 {"posix", no_argument, &posix, 1},
542 {NULL, 0, 0, 0}
543 };
544 int ch;
545 const char *errstr;
546
547 rejname[0] = '\0';
548 Argc_last = Argc;
549 Argv_last = Argv;
550 if (!Argc)
551 return;
552 optreset = optind = 1;
553 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
554 switch (ch) {
555 case 'b':
556 if (backup_type == none)
557 backup_type = numbered_existing;
558 if (optarg == NULL)
559 break;
560 if (verbose)
561 say("Warning, the ``-b suffix'' option has been"
562 " obsoleted by the -z option.\n");
563 /* FALLTHROUGH */
564 case 'z':
565 /* must directly follow 'b' case for backwards compat */
566 simple_backup_suffix = xstrdup(optarg);
567 break;
568 case 'B':
569 origprae = xstrdup(optarg);
570 break;
571 case 'c':
572 diff_type = CONTEXT_DIFF;
573 break;
574 case 'C':
575 check_only = true;
576 break;
577 case 'd':
578 if (chdir(optarg) == -1)
579 pfatal("can't cd to %s", optarg);
580 break;
581 case 'D':
582 do_defines = true;
583 if (!isalpha((unsigned char)*optarg) && *optarg != '_')
584 fatal("argument to -D is not an identifier\n");
585 snprintf(if_defined, sizeof if_defined,
586 "#ifdef %s\n", optarg);
587 snprintf(not_defined, sizeof not_defined,
588 "#ifndef %s\n", optarg);
589 snprintf(end_defined, sizeof end_defined,
590 "#endif /* %s */\n", optarg);
591 break;
592 case 'e':
593 diff_type = ED_DIFF;
594 break;
595 case 'E':
596 remove_empty_files = true;
597 break;
598 case 'f':
599 force = true;
600 break;
601 case 'F':
602 maxfuzz = strtonum(optarg, 0, INT_MAX, &errstr);
603 if (errstr != NULL)
604 fatal("maximum fuzz is %s: %s\n",
605 errstr, optarg);
606 break;
607 case 'i':
608 if (++filec == MAXFILEC)
609 fatal("too many file arguments\n");
610 filearg[filec] = xstrdup(optarg);
611 break;
612 case 'l':
613 canonicalize = true;
614 break;
615 case 'n':
616 diff_type = NORMAL_DIFF;
617 break;
618 case 'N':
619 noreverse = true;
620 break;
621 case 'o':
622 outname = xstrdup(optarg);
623 break;
624 case 'p':
625 strippath = strtonum(optarg, 0, INT_MAX, &errstr);
626 if (errstr != NULL)
627 fatal("strip count is %s: %s\n",
628 errstr, optarg);
629 break;
630 case 'r':
631 if (strlcpy(rejname, optarg,
632 sizeof(rejname)) >= sizeof(rejname))
633 fatal("argument for -r is too long\n");
634 break;
635 case 'R':
636 reverse = true;
637 reverse_flag_specified = true;
638 break;
639 case 's':
640 verbose = false;
641 break;
642 case 't':
643 batch = true;
644 break;
645 case 'u':
646 diff_type = UNI_DIFF;
647 break;
648 case 'v':
649 version();
650 break;
651 case 'V':
652 backup_type = get_version(optarg);
653 Vflag = true;
654 break;
655 #ifdef DEBUGGING
656 case 'x':
657 debug = strtonum(optarg, 0, INT_MAX, &errstr);
658 if (errstr != NULL)
659 fatal("debug number is %s: %s\n",
660 errstr, optarg);
661 break;
662 #endif
663 default:
664 if (ch != '\0')
665 usage();
666 break;
667 }
668 }
669 Argc -= optind;
670 Argv += optind;
671
672 if (Argc > 0) {
673 filearg[0] = xstrdup(*Argv++);
674 Argc--;
675 while (Argc > 0) {
676 if (++filec == MAXFILEC)
677 fatal("too many file arguments\n");
678 filearg[filec] = xstrdup(*Argv++);
679 Argc--;
680 }
681 }
682
683 if (getenv("POSIXLY_CORRECT") != NULL)
684 posix = 1;
685 }
686
687 static __dead void
usage(void)688 usage(void)
689 {
690 fprintf(stderr,
691 "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
692 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
693 " [-r rej-name] [-V t | nil | never | none] [-x number]\n"
694 " [-z backup-ext] [--posix] [origfile [patchfile]]\n"
695 " patch <patchfile\n");
696 my_exit(2);
697 }
698
699 /*
700 * Attempt to find the right place to apply this hunk of patch.
701 */
702 static LINENUM
locate_hunk(LINENUM fuzz)703 locate_hunk(LINENUM fuzz)
704 {
705 LINENUM first_guess = pch_first() + last_offset;
706 LINENUM offset;
707 LINENUM pat_lines = pch_ptrn_lines();
708 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
709 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
710
711 if (pat_lines == 0) { /* null range matches always */
712 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
713 || diff_type == NEW_CONTEXT_DIFF
714 || diff_type == UNI_DIFF)) {
715 say("Empty context always matches.\n");
716 }
717 if (first_guess == 0)
718 return 1;
719 return (first_guess);
720 }
721 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
722 max_neg_offset = first_guess - 1;
723 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
724 return first_guess;
725 for (offset = 1; ; offset++) {
726 bool check_after = (offset <= max_pos_offset);
727 bool check_before = (offset <= max_neg_offset);
728
729 if (check_after && patch_match(first_guess, offset, fuzz)) {
730 #ifdef DEBUGGING
731 if (debug & 1)
732 say("Offset changing from %ld to %ld\n",
733 last_offset, offset);
734 #endif
735 last_offset = offset;
736 return first_guess + offset;
737 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
738 #ifdef DEBUGGING
739 if (debug & 1)
740 say("Offset changing from %ld to %ld\n",
741 last_offset, -offset);
742 #endif
743 last_offset = -offset;
744 return first_guess - offset;
745 } else if (!check_before && !check_after)
746 return 0;
747 }
748 }
749
750 /* We did not find the pattern, dump out the hunk so they can handle it. */
751
752 static void
abort_context_hunk(void)753 abort_context_hunk(void)
754 {
755 LINENUM i;
756 const LINENUM pat_end = pch_end();
757 /*
758 * add in last_offset to guess the same as the previous successful
759 * hunk
760 */
761 const LINENUM oldfirst = pch_first() + last_offset;
762 const LINENUM newfirst = pch_newfirst() + last_offset;
763 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
764 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
765 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
766 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
767
768 fprintf(rejfp, "***************\n");
769 for (i = 0; i <= pat_end; i++) {
770 switch (pch_char(i)) {
771 case '*':
772 if (oldlast < oldfirst)
773 fprintf(rejfp, "*** 0%s\n", stars);
774 else if (oldlast == oldfirst)
775 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
776 else
777 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
778 oldlast, stars);
779 break;
780 case '=':
781 if (newlast < newfirst)
782 fprintf(rejfp, "--- 0%s\n", minuses);
783 else if (newlast == newfirst)
784 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
785 else
786 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
787 newlast, minuses);
788 break;
789 case '\n':
790 fprintf(rejfp, "%s", pfetch(i));
791 break;
792 case ' ':
793 case '-':
794 case '+':
795 case '!':
796 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
797 break;
798 default:
799 fatal("fatal internal error in abort_context_hunk\n");
800 }
801 }
802 }
803
804 static void
rej_line(int ch,LINENUM i)805 rej_line(int ch, LINENUM i)
806 {
807 size_t len;
808 const char *line = pfetch(i);
809
810 len = strlen(line);
811
812 fprintf(rejfp, "%c%s", ch, line);
813 if (len == 0 || line[len-1] != '\n')
814 fprintf(rejfp, "\n\\ No newline at end of file\n");
815 }
816
817 static void
abort_hunk(void)818 abort_hunk(void)
819 {
820 LINENUM i, j, split;
821 int ch1, ch2;
822 const LINENUM pat_end = pch_end();
823 const LINENUM oldfirst = pch_first() + last_offset;
824 const LINENUM newfirst = pch_newfirst() + last_offset;
825
826 if (diff_type != UNI_DIFF) {
827 abort_context_hunk();
828 return;
829 }
830 split = -1;
831 for (i = 0; i <= pat_end; i++) {
832 if (pch_char(i) == '=') {
833 split = i;
834 break;
835 }
836 }
837 if (split == -1) {
838 fprintf(rejfp, "malformed hunk: no split found\n");
839 return;
840 }
841 i = 0;
842 j = split + 1;
843 fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
844 pch_ptrn_lines() ? oldfirst : 0,
845 pch_ptrn_lines(), newfirst, pch_repl_lines());
846 while (i < split || j <= pat_end) {
847 ch1 = i < split ? pch_char(i) : -1;
848 ch2 = j <= pat_end ? pch_char(j) : -1;
849 if (ch1 == '-') {
850 rej_line('-', i);
851 i++;
852 } else if (ch1 == ' ' && ch2 == ' ') {
853 rej_line(' ', i);
854 i++;
855 j++;
856 } else if (ch1 == '!' && ch2 == '!') {
857 while (i < split && ch1 == '!') {
858 rej_line('-', i);
859 i++;
860 ch1 = i < split ? pch_char(i) : -1;
861 }
862 while (j <= pat_end && ch2 == '!') {
863 rej_line('+', j);
864 j++;
865 ch2 = j <= pat_end ? pch_char(j) : -1;
866 }
867 } else if (ch1 == '*') {
868 i++;
869 } else if (ch2 == '+' || ch2 == ' ') {
870 rej_line(ch2, j);
871 j++;
872 } else {
873 fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
874 i, split, j);
875 rej_line(ch1, i);
876 rej_line(ch2, j);
877 return;
878 }
879 }
880 }
881
882 /* We found where to apply it (we hope), so do it. */
883
884 static void
apply_hunk(LINENUM where)885 apply_hunk(LINENUM where)
886 {
887 LINENUM old = 1;
888 const LINENUM lastline = pch_ptrn_lines();
889 LINENUM new = lastline + 1;
890 #define OUTSIDE 0
891 #define IN_IFNDEF 1
892 #define IN_IFDEF 2
893 #define IN_ELSE 3
894 int def_state = OUTSIDE;
895 const LINENUM pat_end = pch_end();
896
897 where--;
898 while (pch_char(new) == '=' || pch_char(new) == '\n')
899 new++;
900
901 while (old <= lastline) {
902 if (pch_char(old) == '-') {
903 copy_till(where + old - 1, false);
904 if (do_defines) {
905 if (def_state == OUTSIDE) {
906 fputs(not_defined, ofp);
907 def_state = IN_IFNDEF;
908 } else if (def_state == IN_IFDEF) {
909 fputs(else_defined, ofp);
910 def_state = IN_ELSE;
911 }
912 fputs(pfetch(old), ofp);
913 }
914 last_frozen_line++;
915 old++;
916 } else if (new > pat_end) {
917 break;
918 } else if (pch_char(new) == '+') {
919 copy_till(where + old - 1, false);
920 if (do_defines) {
921 if (def_state == IN_IFNDEF) {
922 fputs(else_defined, ofp);
923 def_state = IN_ELSE;
924 } else if (def_state == OUTSIDE) {
925 fputs(if_defined, ofp);
926 def_state = IN_IFDEF;
927 }
928 }
929 fputs(pfetch(new), ofp);
930 new++;
931 } else if (pch_char(new) != pch_char(old)) {
932 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
933 pch_hunk_beg() + old,
934 pch_hunk_beg() + new);
935 #ifdef DEBUGGING
936 say("oldchar = '%c', newchar = '%c'\n",
937 pch_char(old), pch_char(new));
938 #endif
939 my_exit(2);
940 } else if (pch_char(new) == '!') {
941 copy_till(where + old - 1, false);
942 if (do_defines) {
943 fputs(not_defined, ofp);
944 def_state = IN_IFNDEF;
945 }
946 while (pch_char(old) == '!') {
947 if (do_defines) {
948 fputs(pfetch(old), ofp);
949 }
950 last_frozen_line++;
951 old++;
952 }
953 if (do_defines) {
954 fputs(else_defined, ofp);
955 def_state = IN_ELSE;
956 }
957 while (pch_char(new) == '!') {
958 fputs(pfetch(new), ofp);
959 new++;
960 }
961 } else {
962 if (pch_char(new) != ' ')
963 fatal("Internal error: expected ' '\n");
964 old++;
965 new++;
966 if (do_defines && def_state != OUTSIDE) {
967 fputs(end_defined, ofp);
968 def_state = OUTSIDE;
969 }
970 }
971 }
972 if (new <= pat_end && pch_char(new) == '+') {
973 copy_till(where + old - 1, false);
974 if (do_defines) {
975 if (def_state == OUTSIDE) {
976 fputs(if_defined, ofp);
977 def_state = IN_IFDEF;
978 } else if (def_state == IN_IFNDEF) {
979 fputs(else_defined, ofp);
980 def_state = IN_ELSE;
981 }
982 }
983 while (new <= pat_end && pch_char(new) == '+') {
984 fputs(pfetch(new), ofp);
985 new++;
986 }
987 }
988 if (do_defines && def_state != OUTSIDE) {
989 fputs(end_defined, ofp);
990 }
991 }
992
993 /*
994 * Open the new file.
995 */
996 static void
init_output(const char * name)997 init_output(const char *name)
998 {
999 ofp = fopen(name, "w");
1000 if (ofp == NULL)
1001 pfatal("can't create %s", name);
1002 }
1003
1004 /*
1005 * Open a file to put hunks we can't locate.
1006 */
1007 static void
init_reject(const char * name)1008 init_reject(const char *name)
1009 {
1010 rejfp = fopen(name, "w");
1011 if (rejfp == NULL)
1012 pfatal("can't create %s", name);
1013 }
1014
1015 /*
1016 * Copy input file to output, up to wherever hunk is to be applied.
1017 * If endoffile is true, treat the last line specially since it may
1018 * lack a newline.
1019 */
1020 static void
copy_till(LINENUM lastline,bool endoffile)1021 copy_till(LINENUM lastline, bool endoffile)
1022 {
1023 if (last_frozen_line > lastline)
1024 fatal("misordered hunks! output would be garbled\n");
1025 while (last_frozen_line < lastline) {
1026 if (++last_frozen_line == lastline && endoffile)
1027 dump_line(last_frozen_line, !last_line_missing_eol);
1028 else
1029 dump_line(last_frozen_line, true);
1030 }
1031 }
1032
1033 /*
1034 * Finish copying the input file to the output file.
1035 */
1036 static void
spew_output(void)1037 spew_output(void)
1038 {
1039 #ifdef DEBUGGING
1040 if (debug & 256)
1041 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
1042 #endif
1043 if (input_lines)
1044 copy_till(input_lines, true); /* dump remainder of file */
1045 fclose(ofp);
1046 ofp = NULL;
1047 }
1048
1049 /*
1050 * Copy one line from input to output.
1051 */
1052 static void
dump_line(LINENUM line,bool write_newline)1053 dump_line(LINENUM line, bool write_newline)
1054 {
1055 char *s;
1056
1057 s = ifetch(line, 0);
1058 if (s == NULL)
1059 return;
1060 /* Note: string is not NUL terminated. */
1061 for (; *s != '\n'; s++)
1062 putc(*s, ofp);
1063 if (write_newline)
1064 putc('\n', ofp);
1065 }
1066
1067 /*
1068 * Does the patch pattern match at line base+offset?
1069 */
1070 static bool
patch_match(LINENUM base,LINENUM offset,LINENUM fuzz)1071 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
1072 {
1073 LINENUM pline = 1 + fuzz;
1074 LINENUM iline;
1075 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
1076 const char *ilineptr;
1077 const char *plineptr;
1078 ssize_t plinelen;
1079
1080 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
1081 ilineptr = ifetch(iline, offset >= 0);
1082 if (ilineptr == NULL)
1083 return false;
1084 plineptr = pfetch(pline);
1085 plinelen = pch_line_len(pline);
1086 if (canonicalize) {
1087 if (!similar(ilineptr, plineptr, plinelen))
1088 return false;
1089 } else if (strnNE(ilineptr, plineptr, plinelen))
1090 return false;
1091 if (iline == input_lines) {
1092 /*
1093 * We are looking at the last line of the file.
1094 * If the file has no eol, the patch line should
1095 * not have one either and vice-versa. Note that
1096 * plinelen > 0.
1097 */
1098 if (last_line_missing_eol) {
1099 if (plineptr[plinelen - 1] == '\n')
1100 return false;
1101 } else {
1102 if (plineptr[plinelen - 1] != '\n')
1103 return false;
1104 }
1105 }
1106 }
1107 return true;
1108 }
1109
1110 /*
1111 * Do two lines match with canonicalized white space?
1112 */
1113 static bool
similar(const char * a,const char * b,ssize_t len)1114 similar(const char *a, const char *b, ssize_t len)
1115 {
1116 while (len) {
1117 if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
1118 if (!isspace((unsigned char)*a))
1119 return false; /* no corresponding whitespace */
1120 while (len && isspace((unsigned char)*b) && *b != '\n')
1121 b++, len--; /* skip pattern whitespace */
1122 while (isspace((unsigned char)*a) && *a != '\n')
1123 a++; /* skip target whitespace */
1124 if (*a == '\n' || *b == '\n')
1125 return (*a == *b); /* should end in sync */
1126 } else if (*a++ != *b++) /* match non-whitespace chars */
1127 return false;
1128 else
1129 len--; /* probably not necessary */
1130 }
1131 return true; /* actually, this is not reached */
1132 /* since there is always a \n */
1133 }
1134