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