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