2 * $OpenBSD: patch.c,v 1.41 2004/07/09 19:13:46 otto Exp $
3 * $DragonFly: src/usr.bin/patch/patch.c,v 1.2 2004/10/02 05:52:06 dillon Exp $
7 * patch - a program to apply diffs to original files
9 * Copyright 1986, Larry Wall
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following condition is met:
13 * 1. Redistributions of source code must retain the above copyright notice,
14 * this condition and the following disclaimer.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
32 #include <sys/types.h>
47 #include "backupfile.h"
48 #include "pathnames.h"
52 char buf[MAXLINELEN]; /* general purpose buffer */
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 */
59 char *filearg[MAXFILEC];
60 bool ok_to_create_file = false;
62 char *origprae = NULL;
67 bool toutkeep = false;
68 bool trejkeep = false;
69 bool warn_on_invalid_line;
70 bool last_line_missing_eol;
80 bool noreverse = false;
81 bool skip_rest_of_patch = false;
83 bool canonicalize = false;
84 bool check_only = false;
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? */
90 static void reinitialize_almost_everything(void);
91 static void get_some_switches(void);
92 static LINENUM locate_hunk(LINENUM);
93 static void abort_hunk(void);
94 static void apply_hunk(LINENUM);
95 static void init_output(const char *);
96 static void init_reject(const char *);
97 static void copy_till(LINENUM, bool);
98 static void spew_output(void);
99 static void dump_line(LINENUM, bool);
100 static bool patch_match(LINENUM, LINENUM, LINENUM);
101 static bool similar(const char *, const char *, int);
102 static void usage(void);
104 /* true if -E was specified on command line. */
105 static bool remove_empty_files = false;
107 /* true if -R was specified on command line. */
108 static bool reverse_flag_specified = false;
110 /* buffer holding the name of the rejected patch file. */
111 static char rejname[NAME_MAX + 1];
113 /* buffer for stderr */
114 static char serrbuf[BUFSIZ];
116 /* how many input lines have been irretractibly output */
117 static LINENUM last_frozen_line = 0;
119 static int Argc; /* guess */
121 static int Argc_last; /* for restarting plan_b */
122 static char **Argv_last;
124 static FILE *ofp = NULL; /* output file pointer */
125 static FILE *rejfp = NULL; /* reject file pointer */
127 static int filec = 0; /* how many file arguments? */
128 static LINENUM last_offset = 0;
129 static LINENUM maxfuzz = 2;
131 /* patch using ifdef, ifndef, etc. */
132 static bool do_defines = false;
134 static char if_defined[128];
136 static char not_defined[128];
138 static const char else_defined[] = "#else\n";
140 static char end_defined[128];
143 /* Apply a set of diffs as appropriate. */
146 main(int argc, char *argv[])
148 int error = 0, hunk, failed, patch_seen = 0, i, fd;
149 LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
153 setbuf(stderr, serrbuf);
154 for (i = 0; i < MAXFILEC; i++)
157 /* Cons up the names of the temporary files. */
158 if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
160 for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
163 if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
164 fatal("cannot allocate memory");
165 if ((fd = mkstemp(TMPOUTNAME)) < 0)
166 pfatal("can't create %s", TMPOUTNAME);
169 if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
170 fatal("cannot allocate memory");
171 if ((fd = mkstemp(TMPINNAME)) < 0)
172 pfatal("can't create %s", TMPINNAME);
175 if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
176 fatal("cannot allocate memory");
177 if ((fd = mkstemp(TMPREJNAME)) < 0)
178 pfatal("can't create %s", TMPREJNAME);
181 if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
182 fatal("cannot allocate memory");
183 if ((fd = mkstemp(TMPPATNAME)) < 0)
184 pfatal("can't create %s", TMPPATNAME);
187 v = getenv("SIMPLE_BACKUP_SUFFIX");
189 simple_backup_suffix = v;
191 simple_backup_suffix = ORIGEXT;
198 if (backup_type == none) {
199 if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
200 v = getenv("VERSION_CONTROL");
201 if (v != NULL || !posix)
202 backup_type = get_version(v); /* OK to pass NULL. */
205 /* make sure we clean up /tmp in case of disaster */
208 for (open_patch_file(filearg[1]); there_is_another_patch();
209 reinitialize_almost_everything()) {
210 /* for each patch in patch file */
213 warn_on_invalid_line = true;
216 outname = savestr(filearg[0]);
218 /* for ed script just up and do it and exit */
219 if (diff_type == ED_DIFF) {
223 /* initialize the patched file */
224 if (!skip_rest_of_patch)
225 init_output(TMPOUTNAME);
227 /* initialize reject file */
228 init_reject(TMPREJNAME);
230 /* find out where all the lines are */
231 if (!skip_rest_of_patch)
232 scan_input(filearg[0]);
234 /* from here on, open no standard i/o files, because malloc */
235 /* might misfire and we can't catch it easily */
237 /* apply each hunk of patch */
241 while (another_hunk()) {
244 mymaxfuzz = pch_context();
245 if (maxfuzz < mymaxfuzz)
247 if (!skip_rest_of_patch) {
249 where = locate_hunk(fuzz);
250 if (hunk == 1 && where == 0 && !force) {
251 /* dwim for reversed patch? */
254 say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
259 where = locate_hunk(fuzz);
261 /* didn't find it swapped */
263 /* put it back to normal */
264 fatal("lost hunk on alloc error!\n");
266 } else if (noreverse) {
268 /* put it back to normal */
269 fatal("lost hunk on alloc error!\n");
271 say("Ignoring previously applied (or reversed) patch.\n");
272 skip_rest_of_patch = true;
275 say("%seversed (or previously applied) patch detected! %s -R.",
276 reverse ? "R" : "Unr",
277 reverse ? "Assuming" : "Ignoring");
279 ask("%seversed (or previously applied) patch detected! %s -R? [y] ",
280 reverse ? "R" : "Unr",
281 reverse ? "Assume" : "Ignore");
283 ask("Apply anyway? [n] ");
285 skip_rest_of_patch = true;
289 /* put it back to normal */
290 fatal("lost hunk on alloc error!\n");
294 } while (!skip_rest_of_patch && where == 0 &&
295 ++fuzz <= mymaxfuzz);
297 if (skip_rest_of_patch) { /* just got decided */
302 newwhere = pch_newfirst() + last_offset;
303 if (skip_rest_of_patch) {
307 say("Hunk #%d ignored at %ld.\n",
309 } else if (where == 0) {
313 say("Hunk #%d failed at %ld.\n",
318 say("Hunk #%d succeeded at %ld",
321 say(" with fuzz %ld", fuzz);
323 say(" (offset %ld line%s)",
325 last_offset == 1L ? "" : "s");
331 if (out_of_mem && using_plan_a) {
334 say("\n\nRan out of memory using Plan A--trying again...\n\n");
344 fatal("Internal error: hunk should not be 0\n");
346 /* finish spewing out the new file */
347 if (!skip_rest_of_patch)
350 /* and put the output where desired */
352 if (!skip_rest_of_patch) {
354 char *realout = outname;
357 if (move_file(TMPOUTNAME, outname) < 0) {
359 realout = TMPOUTNAME;
360 chmod(TMPOUTNAME, filemode);
362 chmod(outname, filemode);
364 if (remove_empty_files &&
365 stat(realout, &statbuf) == 0 &&
366 statbuf.st_size == 0) {
368 say("Removing %s (empty after patching).\n",
378 if (*rejname == '\0') {
379 if (strlcpy(rejname, outname,
380 sizeof(rejname)) >= sizeof(rejname))
381 fatal("filename %s is too long\n", outname);
382 if (strlcat(rejname, REJEXT,
383 sizeof(rejname)) >= sizeof(rejname))
384 fatal("filename %s is too long\n", outname);
386 if (skip_rest_of_patch) {
387 say("%d out of %d hunks ignored--saving rejects to %s\n",
388 failed, hunk, rejname);
390 say("%d out of %d hunks failed--saving rejects to %s\n",
391 failed, hunk, rejname);
393 if (!check_only && move_file(TMPREJNAME, rejname) < 0)
402 /* Prepare to find the next patch to do in the patch file. */
405 reinitialize_almost_everything(void)
411 last_frozen_line = 0;
428 reverse = reverse_flag_specified;
429 skip_rest_of_patch = false;
434 /* Process switches and filenames. */
437 get_some_switches(void)
439 const char *options = "b:B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
440 static struct option longopts[] = {
441 {"backup", no_argument, 0, 'b'},
442 {"batch", no_argument, 0, 't'},
443 {"check", no_argument, 0, 'C'},
444 {"context", no_argument, 0, 'c'},
445 {"debug", required_argument, 0, 'x'},
446 {"directory", required_argument, 0, 'd'},
447 {"ed", no_argument, 0, 'e'},
448 {"force", no_argument, 0, 'f'},
449 {"forward", no_argument, 0, 'N'},
450 {"fuzz", required_argument, 0, 'F'},
451 {"ifdef", required_argument, 0, 'D'},
452 {"input", required_argument, 0, 'i'},
453 {"ignore-whitespace", no_argument, 0, 'l'},
454 {"normal", no_argument, 0, 'n'},
455 {"output", required_argument, 0, 'o'},
456 {"prefix", required_argument, 0, 'B'},
457 {"quiet", no_argument, 0, 's'},
458 {"reject-file", required_argument, 0, 'r'},
459 {"remove-empty-files", no_argument, 0, 'E'},
460 {"reverse", no_argument, 0, 'R'},
461 {"silent", no_argument, 0, 's'},
462 {"strip", required_argument, 0, 'p'},
463 {"suffix", required_argument, 0, 'z'},
464 {"unified", no_argument, 0, 'u'},
465 {"version", no_argument, 0, 'v'},
466 {"version-control", required_argument, 0, 'V'},
467 {"posix", no_argument, &posix, 1},
477 optreset = optind = 1;
478 while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
481 if (backup_type == none)
482 backup_type = numbered_existing;
486 say("Warning, the ``-b suffix'' option has been"
487 " obsoleted by the -z option.\n");
490 /* must directly follow 'b' case for backwards compat */
491 simple_backup_suffix = savestr(optarg);
494 origprae = savestr(optarg);
497 diff_type = CONTEXT_DIFF;
503 if (chdir(optarg) < 0)
504 pfatal("can't cd to %s", optarg);
508 if (!isalpha(*optarg) && *optarg != '_')
509 fatal("argument to -D is not an identifier\n");
510 snprintf(if_defined, sizeof if_defined,
511 "#ifdef %s\n", optarg);
512 snprintf(not_defined, sizeof not_defined,
513 "#ifndef %s\n", optarg);
514 snprintf(end_defined, sizeof end_defined,
515 "#endif /* %s */\n", optarg);
521 remove_empty_files = true;
527 maxfuzz = atoi(optarg);
530 if (++filec == MAXFILEC)
531 fatal("too many file arguments\n");
532 filearg[filec] = savestr(optarg);
538 diff_type = NORMAL_DIFF;
544 outname = savestr(optarg);
547 strippath = atoi(optarg);
550 if (strlcpy(rejname, optarg,
551 sizeof(rejname)) >= sizeof(rejname))
552 fatal("argument for -r is too long\n");
556 reverse_flag_specified = true;
565 diff_type = UNI_DIFF;
571 backup_type = get_version(optarg);
575 debug = atoi(optarg);
588 filearg[0] = savestr(*Argv++);
591 if (++filec == MAXFILEC)
592 fatal("too many file arguments\n");
593 filearg[filec] = savestr(*Argv++);
598 if (getenv("POSIXLY_CORRECT") != NULL)
606 "usage: patch [-bcCeEflnNRstuv] [-B backup-prefix] [-d directory] [-D symbol]\n"
607 " [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
608 " [-r rej-name] [-V {numbered,existing,simple}] [-z backup-ext]\n"
609 " [origfile [patchfile]]\n");
610 my_exit(EXIT_SUCCESS);
614 * Attempt to find the right place to apply this hunk of patch.
617 locate_hunk(LINENUM fuzz)
619 LINENUM first_guess = pch_first() + last_offset;
621 LINENUM pat_lines = pch_ptrn_lines();
622 LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
623 LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
625 if (pat_lines == 0) { /* null range matches always */
626 if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
627 || diff_type == NEW_CONTEXT_DIFF
628 || diff_type == UNI_DIFF)) {
629 say("Empty context always matches.\n");
631 if (diff_type == CONTEXT_DIFF
632 || diff_type == NEW_CONTEXT_DIFF
633 || diff_type == UNI_DIFF) {
635 return (input_lines == 0 ? first_guess : 0);
637 return (first_guess);
639 if (max_neg_offset >= first_guess) /* do not try lines < 0 */
640 max_neg_offset = first_guess - 1;
641 if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
643 for (offset = 1; ; offset++) {
644 bool check_after = (offset <= max_pos_offset);
645 bool check_before = (offset <= max_neg_offset);
647 if (check_after && patch_match(first_guess, offset, fuzz)) {
650 say("Offset changing from %ld to %ld\n",
651 last_offset, offset);
653 last_offset = offset;
654 return first_guess + offset;
655 } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
658 say("Offset changing from %ld to %ld\n",
659 last_offset, -offset);
661 last_offset = -offset;
662 return first_guess - offset;
663 } else if (!check_before && !check_after)
668 /* We did not find the pattern, dump out the hunk so they can handle it. */
674 const LINENUM pat_end = pch_end();
676 * add in last_offset to guess the same as the previous successful
679 const LINENUM oldfirst = pch_first() + last_offset;
680 const LINENUM newfirst = pch_newfirst() + last_offset;
681 const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
682 const LINENUM newlast = newfirst + pch_repl_lines() - 1;
683 const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
684 const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
686 fprintf(rejfp, "***************\n");
687 for (i = 0; i <= pat_end; i++) {
688 switch (pch_char(i)) {
690 if (oldlast < oldfirst)
691 fprintf(rejfp, "*** 0%s\n", stars);
692 else if (oldlast == oldfirst)
693 fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
695 fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
699 if (newlast < newfirst)
700 fprintf(rejfp, "--- 0%s\n", minuses);
701 else if (newlast == newfirst)
702 fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
704 fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
708 fprintf(rejfp, "%s", pfetch(i));
714 fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
717 fatal("fatal internal error in abort_hunk\n");
722 /* We found where to apply it (we hope), so do it. */
725 apply_hunk(LINENUM where)
728 const LINENUM lastline = pch_ptrn_lines();
729 LINENUM new = lastline + 1;
734 int def_state = OUTSIDE;
735 const LINENUM pat_end = pch_end();
738 while (pch_char(new) == '=' || pch_char(new) == '\n')
741 while (old <= lastline) {
742 if (pch_char(old) == '-') {
743 copy_till(where + old - 1, false);
745 if (def_state == OUTSIDE) {
746 fputs(not_defined, ofp);
747 def_state = IN_IFNDEF;
748 } else if (def_state == IN_IFDEF) {
749 fputs(else_defined, ofp);
752 fputs(pfetch(old), ofp);
756 } else if (new > pat_end) {
758 } else if (pch_char(new) == '+') {
759 copy_till(where + old - 1, false);
761 if (def_state == IN_IFNDEF) {
762 fputs(else_defined, ofp);
764 } else if (def_state == OUTSIDE) {
765 fputs(if_defined, ofp);
766 def_state = IN_IFDEF;
769 fputs(pfetch(new), ofp);
771 } else if (pch_char(new) != pch_char(old)) {
772 say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
773 pch_hunk_beg() + old,
774 pch_hunk_beg() + new);
776 say("oldchar = '%c', newchar = '%c'\n",
777 pch_char(old), pch_char(new));
780 } else if (pch_char(new) == '!') {
781 copy_till(where + old - 1, false);
783 fputs(not_defined, ofp);
784 def_state = IN_IFNDEF;
786 while (pch_char(old) == '!') {
788 fputs(pfetch(old), ofp);
794 fputs(else_defined, ofp);
797 while (pch_char(new) == '!') {
798 fputs(pfetch(new), ofp);
802 if (pch_char(new) != ' ')
803 fatal("Internal error: expected ' '\n");
806 if (do_defines && def_state != OUTSIDE) {
807 fputs(end_defined, ofp);
812 if (new <= pat_end && pch_char(new) == '+') {
813 copy_till(where + old - 1, false);
815 if (def_state == OUTSIDE) {
816 fputs(if_defined, ofp);
817 def_state = IN_IFDEF;
818 } else if (def_state == IN_IFNDEF) {
819 fputs(else_defined, ofp);
823 while (new <= pat_end && pch_char(new) == '+') {
824 fputs(pfetch(new), ofp);
828 if (do_defines && def_state != OUTSIDE) {
829 fputs(end_defined, ofp);
837 init_output(const char *name)
839 ofp = fopen(name, "w");
841 pfatal("can't create %s", name);
845 * Open a file to put hunks we can't locate.
848 init_reject(const char *name)
850 rejfp = fopen(name, "w");
852 pfatal("can't create %s", name);
856 * Copy input file to output, up to wherever hunk is to be applied.
857 * If endoffile is true, treat the last line specially since it may
861 copy_till(LINENUM lastline, bool endoffile)
863 if (last_frozen_line > lastline)
864 fatal("misordered hunks! output would be garbled\n");
865 while (last_frozen_line < lastline) {
866 if (++last_frozen_line == lastline && endoffile)
867 dump_line(last_frozen_line, !last_line_missing_eol);
869 dump_line(last_frozen_line, true);
874 * Finish copying the input file to the output file.
881 say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
884 copy_till(input_lines, true); /* dump remainder of file */
890 * Copy one line from input to output.
893 dump_line(LINENUM line, bool write_newline)
900 /* Note: string is not NUL terminated. */
901 for (; *s != '\n'; s++)
908 * Does the patch pattern match at line base+offset?
911 patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
913 LINENUM pline = 1 + fuzz;
915 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
916 const char *ilineptr;
917 const char *plineptr;
920 for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
921 ilineptr = ifetch(iline, offset >= 0);
922 if (ilineptr == NULL)
924 plineptr = pfetch(pline);
925 plinelen = pch_line_len(pline);
927 if (!similar(ilineptr, plineptr, plinelen))
929 } else if (strnNE(ilineptr, plineptr, plinelen))
931 if (iline == input_lines) {
933 * We are looking at the last line of the file.
934 * If the file has no eol, the patch line should
935 * not have one either and vice-versa. Note that
938 if (last_line_missing_eol) {
939 if (plineptr[plinelen - 1] == '\n')
942 if (plineptr[plinelen - 1] != '\n')
951 * Do two lines match with canonicalized white space?
954 similar(const char *a, const char *b, int len)
957 if (isspace(*b)) { /* whitespace (or \n) to match? */
958 if (!isspace(*a)) /* no corresponding whitespace? */
960 while (len && isspace(*b) && *b != '\n')
961 b++, len--; /* skip pattern whitespace */
962 while (isspace(*a) && *a != '\n')
963 a++; /* skip target whitespace */
964 if (*a == '\n' || *b == '\n')
965 return (*a == *b); /* should end in sync */
966 } else if (*a++ != *b++) /* match non-whitespace chars */
969 len--; /* probably not necessary */
971 return true; /* actually, this is not reached */
972 /* since there is always a \n */