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