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