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