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