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