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