home *** CD-ROM | disk | FTP | other *** search
/ C!T ROM 2 / ctrom_ii_b.zip / ctrom_ii_b / PROGRAM / C / PATCHSRC / PATCH.C < prev    next >
C/C++ Source or Header  |  1991-01-20  |  21KB  |  869 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.2.0 90/05/01 22:17:50 davison Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  13.  * patch12u: unidiff support added
  14.  * 
  15.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  16.  * patch12: rindex() wasn't declared
  17.  * 
  18.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  19.  * patch10: exit code improved.
  20.  * patch10: better support for non-flexfilenames.
  21.  * 
  22.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  23.  * Short replacement caused spurious "Out of sync" message.
  24.  * 
  25.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  26.  * Improved diagnostic on sync error.
  27.  * Moved do_ed_script() to pch.c.
  28.  * 
  29.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  30.  * Fuzz factor caused offset of installed lines.
  31.  * 
  32.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  33.  * Backwards search could terminate prematurely.
  34.  * 
  35.  * Revision 2.0  86/09/17  15:37:32  lwall
  36.  * Baseline for netwide release.
  37.  * 
  38.  * Revision 1.5  86/08/01  20:53:24  lwall
  39.  * Changed some %d's to %ld's.
  40.  * Linted.
  41.  * 
  42.  * Revision 1.4  86/08/01  19:17:29  lwall
  43.  * Fixes for machines that can't vararg.
  44.  * Added fuzz factor.
  45.  * Generalized -p.
  46.  * General cleanup.
  47.  * 
  48.  * 85/08/15 van%ucbmonet@berkeley
  49.  * Changes for 4.3bsd diff -c.
  50.  *
  51.  * Revision 1.3  85/03/26  15:07:43  lwall
  52.  * Frozen.
  53.  * 
  54.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  55.  * Changed pfp->_file to fileno(pfp).
  56.  * 
  57.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  58.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  59.  * Also allow ed output to be suppressed.
  60.  * 
  61.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  62.  * Added -p option from jromine@uci-750a.
  63.  * 
  64.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  65.  * Now checks for normalness of file to patch.
  66.  * 
  67.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  68.  * Added -D (#ifdef) option from joe@fluke.
  69.  * 
  70.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  71.  * Made smarter about SCCS subdirectories.
  72.  * 
  73.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  74.  * Added -l switch to do loose string comparison.
  75.  * 
  76.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  77.  * Failed hunk count not reset on multiple patch file.
  78.  * 
  79.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  80.  * Branch for sdcrdcf changes.
  81.  * 
  82.  * Revision 1.2  84/11/29  13:29:51  lwall
  83.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  84.  * multiple calls to mktemp().  Will now work on machines that can only
  85.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  86.  * Various cosmetic changes.
  87.  * 
  88.  * Revision 1.1  84/11/09  17:03:58  lwall
  89.  * Initial revision
  90.  * 
  91.  */
  92.  
  93. #include "INTERN.h"
  94. #include "common.h"
  95. #include "EXTERN.h"
  96. #include "version.h"
  97. #include "util.h"
  98. #include "pch.h"
  99. #include "inp.h"
  100.  
  101. /* procedures */
  102.  
  103. void reinitialize_almost_everything();
  104. void get_some_switches();
  105. LINENUM locate_hunk();
  106. void abort_hunk();
  107. void apply_hunk();
  108. void init_output();
  109. void init_reject();
  110. void copy_till();
  111. void spew_output();
  112. void dump_line();
  113. bool patch_match();
  114. bool similar();
  115. void re_input();
  116. void my_exit();
  117.  
  118. /* Nonzero if -R was specified on command line.  */
  119. static int reverse_flag_specified = FALSE;
  120.  
  121. /* Apply a set of diffs as appropriate. */
  122.  
  123. main(argc,argv)
  124. int argc;
  125. char **argv;
  126. {
  127.     LINENUM where;
  128.     LINENUM newwhere;
  129.     LINENUM fuzz;
  130.     LINENUM mymaxfuzz;
  131.     int hunk = 0;
  132.     int failed = 0;
  133.     int failtotal = 0;
  134.     int i;
  135.  
  136.     setbuf(stderr, serrbuf);
  137.     for (i = 0; i<MAXFILEC; i++)
  138.     filearg[i] = Nullch;
  139.  
  140.     /* Cons up the names of the temporary files.  */
  141.     {
  142.       /* Directory for temporary files.  */
  143.       char *tmpdir;
  144.       int tmpname_len;
  145.  
  146.       tmpdir = getenv ("TMPDIR");
  147.       if (tmpdir == NULL) {
  148.     tmpdir = "/tmp";
  149.       }
  150.       tmpname_len = strlen (tmpdir) + 20;
  151.  
  152.       TMPOUTNAME = (char *) malloc (tmpname_len);
  153.       strcpy (TMPOUTNAME, tmpdir);
  154.       strcat (TMPOUTNAME, "/patchoXXXXXX");
  155.       Mktemp(TMPOUTNAME);
  156.  
  157.       TMPINNAME = (char *) malloc (tmpname_len);
  158.       strcpy (TMPINNAME, tmpdir);
  159.       strcat (TMPINNAME, "/patchiXXXXXX");
  160.       Mktemp(TMPINNAME);
  161.  
  162.       TMPREJNAME = (char *) malloc (tmpname_len);
  163.       strcpy (TMPREJNAME, tmpdir);
  164.       strcat (TMPREJNAME, "/patchrXXXXXX");
  165.       Mktemp(TMPREJNAME);
  166.  
  167.       TMPPATNAME = (char *) malloc (tmpname_len);
  168.       strcpy (TMPPATNAME, tmpdir);
  169.       strcat (TMPPATNAME, "/patchpXXXXXX");
  170.       Mktemp(TMPPATNAME);
  171.     }
  172.  
  173.     /* parse switches */
  174.     Argc = argc;
  175.     Argv = argv;
  176.     get_some_switches();
  177.     
  178.     /* make sure we clean up /tmp in case of disaster */
  179.     set_signals(0);
  180.  
  181.     for (
  182.     open_patch_file(filearg[1]);
  183.     there_is_another_patch();
  184.     reinitialize_almost_everything()
  185.     ) {                    /* for each patch in patch file */
  186.  
  187.     if (outname == Nullch)
  188.         outname = savestr(filearg[0]);
  189.     
  190.     /* initialize the patched file */
  191.     if (!skip_rest_of_patch)
  192.         init_output(TMPOUTNAME);
  193.     
  194.     /* for ed script just up and do it and exit */
  195.     if (diff_type == ED_DIFF) {
  196.         do_ed_script();
  197.         continue;
  198.     }
  199.     
  200.     /* initialize reject file */
  201.     init_reject(TMPREJNAME);
  202.     
  203.     /* find out where all the lines are */
  204.     if (!skip_rest_of_patch)
  205.         scan_input(filearg[0]);
  206.     
  207.     /* from here on, open no standard i/o files, because malloc */
  208.     /* might misfire and we can't catch it easily */
  209.     
  210.     /* apply each hunk of patch */
  211.     hunk = 0;
  212.     failed = 0;
  213.     out_of_mem = FALSE;
  214.     while (another_hunk()) {
  215.         hunk++;
  216.         fuzz = Nulline;
  217.         mymaxfuzz = pch_context();
  218.         if (maxfuzz < mymaxfuzz)
  219.         mymaxfuzz = maxfuzz;
  220.         if (!skip_rest_of_patch) {
  221.         do {
  222.             where = locate_hunk(fuzz);
  223.             if (hunk == 1 && where == Nulline && !force) {
  224.                         /* dwim for reversed patch? */
  225.             if (!pch_swap()) {
  226.                 if (fuzz == Nulline)
  227.                 say1(
  228. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  229.                 continue;
  230.             }
  231.             reverse = !reverse;
  232.             where = locate_hunk(fuzz);  /* try again */
  233.             if (where == Nulline) {        /* didn't find it swapped */
  234.                 if (!pch_swap())         /* put it back to normal */
  235.                 fatal1("Lost hunk on alloc error!\n");
  236.                 reverse = !reverse;
  237.             }
  238.             else if (noreverse) {
  239.                 if (!pch_swap())         /* put it back to normal */
  240.                 fatal1("Lost hunk on alloc error!\n");
  241.                 reverse = !reverse;
  242.                 say1(
  243. "Ignoring previously applied (or reversed) patch.\n");
  244.                 skip_rest_of_patch = TRUE;
  245.             }
  246.             else {
  247.                 ask3(
  248. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  249.                 reverse ? "R" : "Unr",
  250.                 reverse ? "Assume" : "Ignore");
  251.                 if (*buf == 'n') {
  252.                 ask1("Apply anyway? [n] ");
  253.                 if (*buf != 'y')
  254.                     skip_rest_of_patch = TRUE;
  255.                 where = Nulline;
  256.                 reverse = !reverse;
  257.                 if (!pch_swap())  /* put it back to normal */
  258.                     fatal1("Lost hunk on alloc error!\n");
  259.                 }
  260.             }
  261.             }
  262.         } while (!skip_rest_of_patch && where == Nulline &&
  263.             ++fuzz <= mymaxfuzz);
  264.  
  265.         if (skip_rest_of_patch) {        /* just got decided */
  266.             Fclose(ofp);
  267.             ofp = Nullfp;
  268.         }
  269.         }
  270.  
  271.         newwhere = pch_newfirst() + last_offset;
  272.         if (skip_rest_of_patch) {
  273.         abort_hunk();
  274.         failed++;
  275.         if (verbose)
  276.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  277.         }
  278.         else if (where == Nulline) {
  279.         abort_hunk();
  280.         failed++;
  281.         if (verbose)
  282.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  283.         }
  284.         else {
  285.         apply_hunk(where);
  286.         if (verbose) {
  287.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  288.             if (fuzz)
  289.             say2(" with fuzz %ld", fuzz);
  290.             if (last_offset)
  291.             say3(" (offset %ld line%s)",
  292.                 last_offset, last_offset==1L?"":"s");
  293.             say1(".\n");
  294.         }
  295.         }
  296.     }
  297.  
  298.     if (out_of_mem && using_plan_a) {
  299.         Argc = Argc_last;
  300.         Argv = Argv_last;
  301.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  302.         continue;
  303.     }
  304.     
  305.     assert(hunk);
  306.     
  307.     /* finish spewing out the new file */
  308.     if (!skip_rest_of_patch)
  309.         spew_output();
  310.     
  311.     /* and put the output where desired */
  312.     ignore_signals();
  313.     if (!skip_rest_of_patch) {
  314.         if (move_file(TMPOUTNAME, outname) < 0) {
  315.         toutkeep = TRUE;
  316.         chmod(TMPOUTNAME, filemode);
  317.         }
  318.         else
  319.         chmod(outname, filemode);
  320.     }
  321.     Fclose(rejfp);
  322.     rejfp = Nullfp;
  323.     if (failed) {
  324.         failtotal += failed;
  325.         if (!*rejname) {
  326.         Strcpy(rejname, outname);
  327. #ifndef FLEXFILENAMES
  328.         {
  329.             char *rindex();
  330.             char *s = rindex(rejname,'/');
  331.  
  332.             if (!s)
  333.             s = rejname;
  334.             if (strlen(s) > 13)
  335.             if (s[12] == '.')    /* try to preserve difference */
  336.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  337.             s[13] = '\0';
  338.         }
  339. #endif
  340.         Strcat(rejname, REJEXT);
  341.         }
  342.         if (skip_rest_of_patch) {
  343.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  344.             failed, hunk, rejname);
  345.         }
  346.         else {
  347.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  348.             failed, hunk, rejname);
  349.         }
  350.         if (move_file(TMPREJNAME, rejname) < 0)
  351.         trejkeep = TRUE;
  352.     }
  353.     set_signals(1);
  354.     }
  355.     my_exit(failtotal);
  356. }
  357.  
  358. /* Prepare to find the next patch to do in the patch file. */
  359.  
  360. void
  361. reinitialize_almost_everything()
  362. {
  363.     re_patch();
  364.     re_input();
  365.  
  366.     input_lines = 0;
  367.     last_frozen_line = 0;
  368.  
  369.     filec = 0;
  370.     if (filearg[0] != Nullch && !out_of_mem) {
  371.     free(filearg[0]);
  372.     filearg[0] = Nullch;
  373.     }
  374.  
  375.     if (outname != Nullch) {
  376.     free(outname);
  377.     outname = Nullch;
  378.     }
  379.  
  380.     last_offset = 0;
  381.  
  382.     diff_type = 0;
  383.  
  384.     if (revision != Nullch) {
  385.     free(revision);
  386.     revision = Nullch;
  387.     }
  388.  
  389.     reverse = reverse_flag_specified;
  390.     skip_rest_of_patch = FALSE;
  391.  
  392.     get_some_switches();
  393.  
  394.     if (filec >= 2)
  395.     fatal1("You may not change to a different patch file.\n");
  396. }
  397.  
  398. static char *
  399. nextarg()
  400. {
  401.     if (!--Argc)
  402.     fatal2("patch: missing argument after `%s'\n", *Argv);
  403.     return *++Argv;
  404. }
  405.  
  406. /* Process switches and filenames up to next '+' or end of list. */
  407.  
  408. void
  409. get_some_switches()
  410. {
  411.     Reg1 char *s;
  412.  
  413.     rejname[0] = '\0';
  414.     Argc_last = Argc;
  415.     Argv_last = Argv;
  416.     if (!Argc)
  417.     return;
  418.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  419.     s = Argv[0];
  420.     if (strEQ(s, "+")) {
  421.         return;            /* + will be skipped by for loop */
  422.     }
  423.     if (*s != '-' || !s[1]) {
  424.         if (filec == MAXFILEC)
  425.         fatal1("patch: Too many file arguments.\n");
  426.         filearg[filec++] = savestr(s);
  427.     }
  428.     else {
  429.         switch (*++s) {
  430.         case 'b':
  431.         origext = savestr(nextarg());
  432.         break;
  433.         case 'B':
  434.         origprae = savestr(nextarg());
  435.         break;
  436.         case 'c':
  437.         diff_type = CONTEXT_DIFF;
  438.         break;
  439.         case 'd':
  440.         if (!*++s)
  441.             s = nextarg();
  442.         if (chdir(s) < 0)
  443.             fatal2("Can't cd to %s.\n", s);
  444.         break;
  445.         case 'D':
  446.             do_defines = TRUE;
  447.         if (!*++s)
  448.             s = nextarg();
  449.         if (!isalpha(*s) && '_' != *s)
  450.             fatal1("Argument to -D not an identifier.\n");
  451.         Sprintf(if_defined, "#ifdef %s\n", s);
  452.         Sprintf(not_defined, "#ifndef %s\n", s);
  453.         Sprintf(end_defined, "#endif /* %s */\n", s);
  454.         break;
  455.         case 'e':
  456.         diff_type = ED_DIFF;
  457.         break;
  458.         case 'f':
  459.         force = TRUE;
  460.         break;
  461.         case 'F':
  462.         if (*++s == '=')
  463.             s++;
  464.         maxfuzz = atoi(s);
  465.         break;
  466.         case 'l':
  467.         canonicalize = TRUE;
  468.         break;
  469.         case 'n':
  470.         diff_type = NORMAL_DIFF;
  471.         break;
  472.         case 'N':
  473.         noreverse = TRUE;
  474.         break;
  475.         case 'o':
  476.         outname = savestr(nextarg());
  477.         break;
  478.         case 'p':
  479.         if (*++s == '=')
  480.             s++;
  481.         strippath = atoi(s);
  482.         break;
  483.         case 'r':
  484.         Strcpy(rejname, nextarg());
  485.         break;
  486.         case 'R':
  487.         reverse = TRUE;
  488.         reverse_flag_specified = TRUE;
  489.         break;
  490.         case 's':
  491.         verbose = FALSE;
  492.         break;
  493.         case 'S':
  494.         skip_rest_of_patch = TRUE;
  495.         break;
  496.         case 'u':
  497.         diff_type = UNI_DIFF;
  498.         break;
  499.         case 'v':
  500.         version();
  501.         break;
  502. #ifdef DEBUGGING
  503.         case 'x':
  504.         debug = atoi(s+1);
  505.         break;
  506. #endif
  507.         default:
  508.         fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
  509.         fprintf(stderr, "\
  510. Usage: patch [-ceflnNRsSuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  511.        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
  512.        [-r rej-name] [origfile] [patchfile] [[+] [options] [origfile]...]\n\
  513. ");
  514.         my_exit(1);
  515.         }
  516.     }
  517.     }
  518. }
  519.  
  520. /* Attempt to find the right place to apply this hunk of patch. */
  521.  
  522. LINENUM
  523. locate_hunk(fuzz)
  524. LINENUM fuzz;
  525. {
  526.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  527.     Reg2 LINENUM offset;
  528.     LINENUM pat_lines = pch_ptrn_lines();
  529.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  530.                 - pat_lines + 1; 
  531.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  532.                 + pch_context();
  533.  
  534.     if (!pat_lines)            /* null range matches always */
  535.     return first_guess;
  536.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  537.     max_neg_offset = first_guess - 1;
  538.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  539.     return first_guess;
  540.     for (offset = 1; ; offset++) {
  541.     Reg5 bool check_after = (offset <= max_pos_offset);
  542.     Reg6 bool check_before = (offset <= max_neg_offset);
  543.  
  544.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  545. #ifdef DEBUGGING
  546.         if (debug & 1)
  547.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  548. #endif
  549.         last_offset = offset;
  550.         return first_guess+offset;
  551.     }
  552.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  553. #ifdef DEBUGGING
  554.         if (debug & 1)
  555.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  556. #endif
  557.         last_offset = -offset;
  558.         return first_guess-offset;
  559.     }
  560.     else if (!check_before && !check_after)
  561.         return Nulline;
  562.     }
  563. }
  564.  
  565. /* We did not find the pattern, dump out the hunk so they can handle it. */
  566.  
  567. void
  568. abort_hunk()
  569. {
  570.     Reg1 LINENUM i;
  571.     Reg2 LINENUM pat_end = pch_end();
  572.     /* add in last_offset to guess the same as the previous successful hunk */
  573.     LINENUM oldfirst = pch_first() + last_offset;
  574.     LINENUM newfirst = pch_newfirst() + last_offset;
  575.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  576.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  577.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  578.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  579.  
  580.     fprintf(rejfp, "***************\n");
  581.     for (i=0; i<=pat_end; i++) {
  582.     switch (pch_char(i)) {
  583.     case '*':
  584.         if (oldlast < oldfirst)
  585.         fprintf(rejfp, "*** 0%s\n", stars);
  586.         else if (oldlast == oldfirst)
  587.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  588.         else
  589.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  590.         break;
  591.     case '=':
  592.         if (newlast < newfirst)
  593.         fprintf(rejfp, "--- 0%s\n", minuses);
  594.         else if (newlast == newfirst)
  595.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  596.         else
  597.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  598.         break;
  599.     case '\n':
  600.         fprintf(rejfp, "%s", pfetch(i));
  601.         break;
  602.     case ' ': case '-': case '+': case '!':
  603.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  604.         break;
  605.     default:
  606.         say1("Fatal internal error in abort_hunk().\n"); 
  607.         abort();
  608.     }
  609.     }
  610. }
  611.  
  612. /* We found where to apply it (we hope), so do it. */
  613.  
  614. void
  615. apply_hunk(where)
  616. LINENUM where;
  617. {
  618.     Reg1 LINENUM old = 1;
  619.     Reg2 LINENUM lastline = pch_ptrn_lines();
  620.     Reg3 LINENUM new = lastline+1;
  621. #define OUTSIDE 0
  622. #define IN_IFNDEF 1
  623. #define IN_IFDEF 2
  624. #define IN_ELSE 3
  625.     Reg4 int def_state = OUTSIDE;
  626.     Reg5 bool R_do_defines = do_defines;
  627.     Reg6 LINENUM pat_end = pch_end();
  628.  
  629.     where--;
  630.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  631.     new++;
  632.     
  633.     while (old <= lastline) {
  634.     if (pch_char(old) == '-') {
  635.         copy_till(where + old - 1);
  636.         if (R_do_defines) {
  637.         if (def_state == OUTSIDE) {
  638.             fputs(not_defined, ofp);
  639.             def_state = IN_IFNDEF;
  640.         }
  641.         else if (def_state == IN_IFDEF) {
  642.             fputs(else_defined, ofp);
  643.             def_state = IN_ELSE;
  644.         }
  645.         fputs(pfetch(old), ofp);
  646.         }
  647.         last_frozen_line++;
  648.         old++;
  649.     }
  650.     else if (new > pat_end) {
  651.         break;
  652.     }
  653.     else if (pch_char(new) == '+') {
  654.         copy_till(where + old - 1);
  655.         if (R_do_defines) {
  656.         if (def_state == IN_IFNDEF) {
  657.             fputs(else_defined, ofp);
  658.             def_state = IN_ELSE;
  659.         }
  660.         else if (def_state == OUTSIDE) {
  661.             fputs(if_defined, ofp);
  662.             def_state = IN_IFDEF;
  663.         }
  664.         }
  665.         fputs(pfetch(new), ofp);
  666.         new++;
  667.     }
  668.     else if (pch_char(new) != pch_char(old)) {
  669.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  670.         pch_hunk_beg() + old,
  671.         pch_hunk_beg() + new);
  672. #ifdef DEBUGGING
  673.         say3("oldchar = '%c', newchar = '%c'\n",
  674.         pch_char(old), pch_char(new));
  675. #endif
  676.         my_exit(1);
  677.     }
  678.     else if (pch_char(new) == '!') {
  679.         copy_till(where + old - 1);
  680.         if (R_do_defines) {
  681.            fputs(not_defined, ofp);
  682.            def_state = IN_IFNDEF;
  683.         }
  684.         while (pch_char(old) == '!') {
  685.         if (R_do_defines) {
  686.             fputs(pfetch(old), ofp);
  687.         }
  688.         last_frozen_line++;
  689.         old++;
  690.         }
  691.         if (R_do_defines) {
  692.         fputs(else_defined, ofp);
  693.         def_state = IN_ELSE;
  694.         }
  695.         while (pch_char(new) == '!') {
  696.         fputs(pfetch(new), ofp);
  697.         new++;
  698.         }
  699.     }
  700.     else {
  701.         assert(pch_char(new) == ' ');
  702.         old++;
  703.         new++;
  704.         if (R_do_defines && def_state != OUTSIDE) {
  705.         fputs(end_defined, ofp);
  706.         def_state = OUTSIDE;
  707.         }
  708.     }
  709.     }
  710.     if (new <= pat_end && pch_char(new) == '+') {
  711.     copy_till(where + old - 1);
  712.     if (R_do_defines) {
  713.         if (def_state == OUTSIDE) {
  714.             fputs(if_defined, ofp);
  715.         def_state = IN_IFDEF;
  716.         }
  717.         else if (def_state == IN_IFNDEF) {
  718.         fputs(else_defined, ofp);
  719.         def_state = IN_ELSE;
  720.         }
  721.     }
  722.     while (new <= pat_end && pch_char(new) == '+') {
  723.         fputs(pfetch(new), ofp);
  724.         new++;
  725.     }
  726.     }
  727.     if (R_do_defines && def_state != OUTSIDE) {
  728.     fputs(end_defined, ofp);
  729.     }
  730. }
  731.  
  732. /* Open the new file. */
  733.  
  734. void
  735. init_output(name)
  736. char *name;
  737. {
  738.     ofp = fopen(name, "w");
  739.     if (ofp == Nullfp)
  740.     fatal2("patch: can't create %s.\n", name);
  741. }
  742.  
  743. /* Open a file to put hunks we can't locate. */
  744.  
  745. void
  746. init_reject(name)
  747. char *name;
  748. {
  749.     rejfp = fopen(name, "w");
  750.     if (rejfp == Nullfp)
  751.     fatal2("patch: can't create %s.\n", name);
  752. }
  753.  
  754. /* Copy input file to output, up to wherever hunk is to be applied. */
  755.  
  756. void
  757. copy_till(lastline)
  758. Reg1 LINENUM lastline;
  759. {
  760.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  761.  
  762.     if (R_last_frozen_line > lastline)
  763.     say1("patch: misordered hunks! output will be garbled.\n");
  764.     while (R_last_frozen_line < lastline) {
  765.     dump_line(++R_last_frozen_line);
  766.     }
  767.     last_frozen_line = R_last_frozen_line;
  768. }
  769.  
  770. /* Finish copying the input file to the output file. */
  771.  
  772. void
  773. spew_output()
  774. {
  775. #ifdef DEBUGGING
  776.     if (debug & 256)
  777.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  778. #endif
  779.     if (input_lines)
  780.     copy_till(input_lines);        /* dump remainder of file */
  781.     Fclose(ofp);
  782.     ofp = Nullfp;
  783. }
  784.  
  785. /* Copy one line from input to output. */
  786.  
  787. void
  788. dump_line(line)
  789. LINENUM line;
  790. {
  791.     Reg1 char *s;
  792.     Reg2 char R_newline = '\n';
  793.  
  794.     /* Note: string is not null terminated. */
  795.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  796. }
  797.  
  798. /* Does the patch pattern match at line base+offset? */
  799.  
  800. bool
  801. patch_match(base, offset, fuzz)
  802. LINENUM base;
  803. LINENUM offset;
  804. LINENUM fuzz;
  805. {
  806.     Reg1 LINENUM pline = 1 + fuzz;
  807.     Reg2 LINENUM iline;
  808.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  809.  
  810.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  811.     if (canonicalize) {
  812.         if (!similar(ifetch(iline, (offset >= 0)),
  813.              pfetch(pline),
  814.              pch_line_len(pline) ))
  815.         return FALSE;
  816.     }
  817.     else if (strnNE(ifetch(iline, (offset >= 0)),
  818.            pfetch(pline),
  819.            pch_line_len(pline) ))
  820.         return FALSE;
  821.     }
  822.     return TRUE;
  823. }
  824.  
  825. /* Do two lines match with canonicalized white space? */
  826.  
  827. bool
  828. similar(a,b,len)
  829. Reg1 char *a;
  830. Reg2 char *b;
  831. Reg3 int len;
  832. {
  833.     while (len) {
  834.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  835.         if (!isspace(*a))        /* no corresponding whitespace? */
  836.         return FALSE;
  837.         while (len && isspace(*b) && *b != '\n')
  838.         b++,len--;        /* skip pattern whitespace */
  839.         while (isspace(*a) && *a != '\n')
  840.         a++;            /* skip target whitespace */
  841.         if (*a == '\n' || *b == '\n')
  842.         return (*a == *b);    /* should end in sync */
  843.     }
  844.     else if (*a++ != *b++)        /* match non-whitespace chars */
  845.         return FALSE;
  846.     else
  847.         len--;            /* probably not necessary */
  848.     }
  849.     return TRUE;            /* actually, this is not reached */
  850.                     /* since there is always a \n */
  851. }
  852.  
  853. /* Exit with cleanup. */
  854.  
  855. void
  856. my_exit(status)
  857. int status;
  858. {
  859.     Unlink(TMPINNAME);
  860.     if (!toutkeep) {
  861.     Unlink(TMPOUTNAME);
  862.     }
  863.     if (!trejkeep) {
  864.     Unlink(TMPREJNAME);
  865.     }
  866.     Unlink(TMPPATNAME);
  867.     exit(status);
  868. }
  869.