aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

patch.c (82489B)


      1 /* see LICENSE file for copyright and license details */
      2 #if FEATURE_PATCH_EXT
      3 #ifndef _GNU_SOURCE
      4 #define _GNU_SOURCE
      5 #endif
      6 #endif
      7 #include "paths.h"
      8 #include "util.h"
      9 #include "wexec.h"
     10 
     11 #include <sys/file.h>
     12 #include <sys/mman.h>
     13 #include <sys/param.h>
     14 #include <sys/stat.h>
     15 #include <sys/wait.h>
     16 
     17 #include <ctype.h>
     18 #include <dirent.h>
     19 #include <errno.h>
     20 #include <fcntl.h>
     21 #include <getopt.h>
     22 #include <libgen.h>
     23 #include <limits.h>
     24 #include <stdarg.h>
     25 #include <stddef.h>
     26 #include <stdint.h>
     27 #include <stdio.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #include <unistd.h>
     31 
     32 #define DEBUGGING
     33 
     34 #define MAXHUNKSIZE 100000
     35 #define INITHUNKMAX 125
     36 #define INITLINELEN 8192
     37 #define BUFFERSIZE  1024
     38 #define LINENUM_MAX LONG_MAX
     39 
     40 #define SCCSPREFIX "s."
     41 #define GET        "get -e %s"
     42 #define SCCSDIFF   "get -p %s | diff - %s >/dev/null"
     43 
     44 #define RCSSUFFIX ",v"
     45 #define CHECKOUT  "co"
     46 #define RCSDIFF   "rcsdiff"
     47 
     48 #define ORIGEXT ".orig"
     49 #define REJEXT  ".rej"
     50 
     51 #define strNE(s1, s2)     (strcmp(s1, s2))
     52 #define strEQ(s1, s2)     (!strcmp(s1, s2))
     53 #define strnNE(s1, s2, l) (strncmp(s1, s2, l))
     54 #define strnEQ(s1, s2, l) (!strncmp(s1, s2, l))
     55 
     56 #define OLD_FILE   0
     57 #define NEW_FILE   1
     58 #define INDEX_FILE 2
     59 #define MAX_FILE   3
     60 
     61 #define CONTEXT_DIFF     1
     62 #define NORMAL_DIFF      2
     63 #define ED_DIFF          3
     64 #define NEW_CONTEXT_DIFF 4
     65 #define UNI_DIFF         5
     66 
     67 #define _PATH_ED "ed"
     68 
     69 #define ISDIGIT(c) (isascii((unsigned char)c) && isdigit((unsigned char)c))
     70 
     71 #ifndef __UNCONST
     72 #define __UNCONST(a) ((void *)(unsigned long)(const void *)(a))
     73 #endif
     74 
     75 #ifndef __dead
     76 #define __dead __attribute__((__noreturn__))
     77 #endif
     78 
     79 typedef long LINENUM;
     80 
     81 enum BackupType {
     82   BACKUP_UNDEFINED,
     83   BACKUP_NONE,
     84   BACKUP_SIMPLE,
     85   BACKUP_NUMBERED_EXISTING,
     86   BACKUP_NUMBERED
     87 };
     88 
     89 struct FileName {
     90   char *path;
     91   int   exists;
     92 };
     93 
     94 mode_t filemode = 0644;
     95 char  *buf;
     96 size_t bufsz;
     97 int    using_plan_a = 1;
     98 int    out_of_mem   = 0;
     99 
    100 #define MAXFILEC 2
    101 char *filearg[MAXFILEC];
    102 int   ok_to_create_file = 0;
    103 char *outname           = NULL;
    104 char *origprae          = NULL;
    105 char *TMPOUTNAME;
    106 char *TMPINNAME;
    107 char *TMPREJNAME;
    108 char *TMPPATNAME;
    109 int   toutkeep = 0;
    110 int   trejkeep = 0;
    111 int   warn_on_invalid_line;
    112 int   last_line_missing_eol;
    113 
    114 #ifdef DEBUGGING
    115 int debug = 0;
    116 #endif
    117 
    118 int     force              = 0;
    119 int     batch              = 0;
    120 int     verbose            = 1;
    121 int     reverse            = 0;
    122 int     noreverse          = 0;
    123 int     skip_rest_of_patch = 0;
    124 int     strippath          = 957;
    125 int     canonicalize       = 0;
    126 int     check_only         = 0;
    127 int     diff_type          = 0;
    128 char   *revision           = NULL;
    129 LINENUM input_lines        = 0;
    130 int     posix              = 0;
    131 int     backup_if_mismatch = -1;
    132 
    133 enum BackupType backup_type          = BACKUP_UNDEFINED;
    134 const char     *simple_backup_suffix = "~";
    135 
    136 static int     remove_empty_files     = 0;
    137 static int     reverse_flag_specified = 0;
    138 static char    rejname[PATH_MAX];
    139 static char    serrbuf[BUFSIZ];
    140 static LINENUM last_frozen_line = 0;
    141 static int     Argc;
    142 static char  **Argv;
    143 static int     Argc_last;
    144 static char  **Argv_last;
    145 static FILE   *ofp         = NULL;
    146 static FILE   *rejfp       = NULL;
    147 static int     filec       = 0;
    148 static LINENUM last_offset = 0;
    149 static LINENUM maxfuzz     = 2;
    150 
    151 static int        do_defines = 0;
    152 static char       if_defined[128];
    153 static char       not_defined[128];
    154 static const char else_defined[] = "#else\n";
    155 static char       end_defined[128];
    156 
    157 /* function declarations */
    158 static void    reinitialize_almost_everything(void);
    159 static void    get_some_switches(void);
    160 static LINENUM locate_hunk(LINENUM);
    161 static void    rej_line(int, LINENUM);
    162 static void    abort_hunk(void);
    163 static void    apply_hunk(LINENUM);
    164 static void    init_output(const char *);
    165 static void    init_reject(const char *);
    166 static void    copy_till(LINENUM, int);
    167 static int     spew_output(void);
    168 static void    dump_input_line(LINENUM, int);
    169 static int     patch_match(LINENUM, LINENUM, LINENUM);
    170 static int     similar(const char *, const char *, ssize_t);
    171 static void    usage(void);
    172 
    173 void    re_patch(void);
    174 void    open_patch_file(const char *);
    175 void    set_hunkmax(void);
    176 int     there_is_another_patch(void);
    177 int     another_hunk(void);
    178 int     pch_swap(void);
    179 char   *pfetch(LINENUM);
    180 ssize_t pch_line_len(LINENUM);
    181 LINENUM pch_first(void);
    182 LINENUM pch_ptrn_lines(void);
    183 LINENUM pch_newfirst(void);
    184 LINENUM pch_repl_lines(void);
    185 LINENUM pch_end(void);
    186 LINENUM pch_context(void);
    187 LINENUM pch_hunk_beg(void);
    188 char    pch_char(LINENUM);
    189 void    do_ed_script(void);
    190 
    191 void  re_input(void);
    192 void  scan_input(const char *);
    193 char *ifetch(LINENUM, int);
    194 
    195 char           *fetchname(const char *, int *, int);
    196 char           *checked_in(char *);
    197 LINENUM         strtolinenum(char *, char **);
    198 int             backup_file(const char *);
    199 int             move_file(const char *, const char *);
    200 int             copy_file(const char *, const char *);
    201 void            say(const char *, ...);
    202 __dead void     fatal(const char *, ...);
    203 __dead void     pfatal(const char *, ...);
    204 void            ask(const char *, ...);
    205 char           *savestr(const char *);
    206 void            set_signals(int);
    207 void            ignore_signals(void);
    208 void            makedirs(const char *, int);
    209 __dead void     version(void);
    210 __dead void     my_exit(int);
    211 static void    *pch_realloc(void *, size_t, size_t);
    212 int             mkpath(char *);
    213 char           *find_backup_file_name(const char *);
    214 enum BackupType get_version(const char *);
    215 
    216 static off_t  i_size;
    217 static char  *i_womp;
    218 static char **i_ptr;
    219 static char   empty_line[] = {'\0'};
    220 
    221 static int     tifd = -1;
    222 static char   *tibuf[2];
    223 static LINENUM tiline[2] = {-1, -1};
    224 static LINENUM lines_per_buf;
    225 static int     tireclen;
    226 
    227 static int  rev_in_string(const char *);
    228 static int  reallocate_lines(size_t *);
    229 static int  plan_a(const char *);
    230 static void plan_b(const char *);
    231 
    232 static long     p_filesize;
    233 static LINENUM  p_first;
    234 static LINENUM  p_newfirst;
    235 static LINENUM  p_ptrn_lines;
    236 static LINENUM  p_repl_lines;
    237 static LINENUM  p_end = -1;
    238 static LINENUM  p_max;
    239 static LINENUM  p_context    = 3;
    240 static LINENUM  p_input_line = 0;
    241 static char   **p_line       = NULL;
    242 static ssize_t *p_len        = NULL;
    243 static char    *p_char       = NULL;
    244 static int      hunkmax      = INITHUNKMAX;
    245 static int      p_indent;
    246 static LINENUM  p_base;
    247 static LINENUM  p_bline;
    248 static LINENUM  p_start;
    249 static LINENUM  p_sline;
    250 static LINENUM  p_hunk_beg;
    251 static LINENUM  p_efake   = -1;
    252 static LINENUM  p_bfake   = -1;
    253 static FILE    *pfp       = NULL;
    254 static char    *bestguess = NULL;
    255 
    256 static void   grow_hunkmax(void);
    257 static int    intuit_diff_type(void);
    258 static void   next_intuit_at(LINENUM, LINENUM);
    259 static void   skip_to(LINENUM, LINENUM);
    260 static int    pgetline(char **, size_t *, FILE *);
    261 static char  *best_name(const struct FileName *, int);
    262 static char  *posix_name(const struct FileName *, int);
    263 static size_t num_components(const char *);
    264 
    265 static char *patch_concat(const char *, const char *);
    266 static char *make_version_name(const char *, int);
    267 static int   max_backup_version(const char *, const char *);
    268 static int   version_number(const char *, const char *, size_t);
    269 static int   argmatch(const char *, const char **);
    270 static void  invalid_arg(const char *, const char *, int);
    271 
    272 static const char *backup_args[] = {
    273     "none", "never", "simple", "nil", "existing", "t", "numbered", 0
    274 };
    275 static enum BackupType backup_types[] = {
    276     BACKUP_NONE,
    277     BACKUP_SIMPLE,
    278     BACKUP_SIMPLE,
    279     BACKUP_NUMBERED_EXISTING,
    280     BACKUP_NUMBERED_EXISTING,
    281     BACKUP_NUMBERED,
    282     BACKUP_NUMBERED
    283 };
    284 
    285 /* implementation */
    286 
    287 // ?man patch: apply a diff file to an original
    288 int
    289 main(int argc, char *argv[])
    290 {
    291   int         error, hunk, failed, i, fd;
    292   LINENUM     where, newwhere, fuzz, mymaxfuzz;
    293   const char *tmpdir;
    294   char       *v;
    295 
    296   error = 0;
    297   where = 0;
    298   bufsz = INITLINELEN;
    299   if ((buf = malloc(bufsz)) == NULL)
    300     pfatal("allocating input buffer");
    301   buf[0] = '\0';
    302 
    303   setbuf(stderr, serrbuf);
    304   for (i = 0; i < MAXFILEC; i++)
    305     filearg[i] = NULL;
    306 
    307   if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
    308     tmpdir = ARUU_PATH_TMP;
    309   for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
    310     ;
    311   i++;
    312   if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
    313     fatal("cannot allocate memory");
    314   if ((fd = mkstemp(TMPOUTNAME)) < 0)
    315     pfatal("cant create %s", TMPOUTNAME);
    316   close(fd);
    317 
    318   if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
    319     fatal("cannot allocate memory");
    320   if ((fd = mkstemp(TMPINNAME)) < 0)
    321     pfatal("cant create %s", TMPINNAME);
    322   close(fd);
    323 
    324   if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
    325     fatal("cannot allocate memory");
    326   if ((fd = mkstemp(TMPREJNAME)) < 0)
    327     pfatal("cant create %s", TMPREJNAME);
    328   close(fd);
    329 
    330   if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
    331     fatal("cannot allocate memory");
    332   if ((fd = mkstemp(TMPPATNAME)) < 0)
    333     pfatal("cant create %s", TMPPATNAME);
    334   close(fd);
    335 
    336   v = getenv("SIMPLE_BACKUP_SUFFIX");
    337   if (v)
    338     simple_backup_suffix = v;
    339   else
    340     simple_backup_suffix = ORIGEXT;
    341 
    342   if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
    343     v = getenv("VERSION_CONTROL");
    344   if (v != NULL)
    345     backup_type = get_version(v);
    346 
    347   Argc = argc;
    348   Argv = argv;
    349   get_some_switches();
    350 
    351   if (backup_type == BACKUP_UNDEFINED)
    352     backup_type = posix ? BACKUP_NONE : BACKUP_NUMBERED_EXISTING;
    353 
    354   set_signals(0);
    355 
    356   for (open_patch_file(filearg[1]); there_is_another_patch(); reinitialize_almost_everything()) {
    357     warn_on_invalid_line = 1;
    358     if (outname == NULL)
    359       outname = savestr(filearg[0]);
    360 
    361     if (diff_type == ED_DIFF) {
    362       do_ed_script();
    363       continue;
    364     }
    365     if (!skip_rest_of_patch)
    366       init_output(TMPOUTNAME);
    367 
    368     init_reject(TMPREJNAME);
    369 
    370     if (!skip_rest_of_patch)
    371       scan_input(filearg[0]);
    372 
    373     hunk       = 0;
    374     failed     = 0;
    375     out_of_mem = 0;
    376     while (another_hunk()) {
    377       hunk++;
    378       fuzz      = 0;
    379       mymaxfuzz = pch_context();
    380       if (maxfuzz < mymaxfuzz)
    381         mymaxfuzz = maxfuzz;
    382       if (!skip_rest_of_patch) {
    383         do {
    384           where = locate_hunk(fuzz);
    385           if (hunk == 1 && where == 0 && !force) {
    386             if (!pch_swap()) {
    387               if (fuzz == 0)
    388                 say("Not "
    389                     "enough "
    390                     "memory to "
    391                     "try "
    392                     "swapped "
    393                     "hunk! "
    394                     "Assuming "
    395                     "unswapped."
    396                     "\n");
    397               continue;
    398             }
    399             reverse = !reverse;
    400             where   = locate_hunk(fuzz);
    401             if (where == 0) {
    402               if (!pch_swap())
    403                 fatal(
    404                     "lost "
    405                     "hunk on "
    406                     "alloc "
    407                     "error!"
    408                     "\n"
    409                 );
    410               reverse = !reverse;
    411             } else if (noreverse) {
    412               if (!pch_swap())
    413                 fatal(
    414                     "lost "
    415                     "hunk on "
    416                     "alloc "
    417                     "error!"
    418                     "\n"
    419                 );
    420               reverse = !reverse;
    421               say("Ignoring "
    422                   "previously "
    423                   "applied (or "
    424                   "reversed) "
    425                   "patch.\n");
    426               skip_rest_of_patch = 1;
    427             } else if (batch) {
    428               if (verbose)
    429                 say("%seversed "
    430                     "(or "
    431                     "%sprevious"
    432                     "ly "
    433                     "applied) "
    434                     "patch "
    435                     "detected! "
    436                     "%s -R.",
    437                     reverse ? "R" : "Unr",
    438                     reverse ? "" : "not ",
    439                     reverse ? "Assuming" : "Ignoring");
    440             } else {
    441               ask("%seversed (or "
    442                   "%spreviously "
    443                   "applied) patch "
    444                   "detected! %s -R? "
    445                   "[y] ",
    446                   reverse ? "R" : "Unr",
    447                   reverse ? "" : "not ",
    448                   reverse ? "Assume" : "Ignore");
    449               if (*buf == 'n') {
    450                 ask("Apply "
    451                     "anyway? "
    452                     "[n] ");
    453                 if (*buf != 'y')
    454                   skip_rest_of_patch = 1;
    455                 where   = 0;
    456                 reverse = !reverse;
    457                 if (!pch_swap())
    458                   fatal("lost hunk on alloc error!\n");
    459               }
    460             }
    461           }
    462         } while (!skip_rest_of_patch && where == 0 && ++fuzz <= mymaxfuzz);
    463 
    464         if (skip_rest_of_patch) {
    465           if (ferror(ofp) || fclose(ofp)) {
    466             say("Error writing %s\n", TMPOUTNAME);
    467             error = 1;
    468           }
    469           ofp = NULL;
    470         }
    471       }
    472       newwhere = pch_newfirst() + last_offset;
    473       if (skip_rest_of_patch) {
    474         abort_hunk();
    475         failed++;
    476         if (verbose)
    477           say("Hunk #%d ignored at %ld.\n", hunk, newwhere);
    478       } else if (where == 0) {
    479         abort_hunk();
    480         failed++;
    481         if (verbose)
    482           say("Hunk #%d failed at %ld.\n", hunk, newwhere);
    483       } else {
    484         apply_hunk(where);
    485         if (verbose) {
    486           say("Hunk #%d succeeded at %ld", hunk, newwhere);
    487           if (fuzz != 0)
    488             say(" with fuzz %ld", fuzz);
    489           if (last_offset)
    490             say(" (offset %ld line%s)", last_offset, last_offset == 1L ? "" : "s");
    491           say(".\n");
    492         }
    493       }
    494     }
    495 
    496     if (out_of_mem && using_plan_a) {
    497       Argc = Argc_last;
    498       Argv = Argv_last;
    499       say("\n\nRan out of memory using Plan A--trying "
    500           "again...\n\n");
    501       if (ofp)
    502         fclose(ofp);
    503       ofp = NULL;
    504       if (rejfp)
    505         fclose(rejfp);
    506       rejfp = NULL;
    507       continue;
    508     }
    509     if (hunk == 0)
    510       fatal("internal error: hunk should not be 0\n");
    511 
    512     if (!skip_rest_of_patch && !spew_output()) {
    513       say("cant write %s\n", TMPOUTNAME);
    514       error = 1;
    515     }
    516 
    517     ignore_signals();
    518     if (!skip_rest_of_patch) {
    519       struct stat statbuf;
    520       char       *realout = outname;
    521 
    522       if (!check_only) {
    523         enum BackupType saved = backup_type;
    524         if (failed > 0 && backup_if_mismatch > 0 && backup_type == BACKUP_NONE)
    525           backup_type = BACKUP_SIMPLE;
    526         if (move_file(TMPOUTNAME, outname) < 0) {
    527           toutkeep = 1;
    528           realout  = TMPOUTNAME;
    529           chmod(TMPOUTNAME, filemode);
    530         } else
    531           chmod(outname, filemode);
    532         backup_type = saved;
    533 
    534         if (remove_empty_files && stat(realout, &statbuf) == 0 && statbuf.st_size == 0) {
    535           if (verbose)
    536             say("Removing %s (empty after "
    537                 "patching).\n",
    538                 realout);
    539           unlink(realout);
    540         }
    541       }
    542     }
    543     if (ferror(rejfp) || fclose(rejfp)) {
    544       say("Error writing %s\n", rejname);
    545       error = 1;
    546     }
    547     rejfp = NULL;
    548     if (failed) {
    549       error = 1;
    550       if (*rejname == '\0') {
    551         if (strlcpy(rejname, outname, sizeof(rejname)) >= sizeof(rejname))
    552           fatal("filename %s is too long\n", outname);
    553         if (strlcat(rejname, REJEXT, sizeof(rejname)) >= sizeof(rejname))
    554           fatal("filename %s is too long\n", outname);
    555       }
    556       if (skip_rest_of_patch) {
    557         say("%d out of %d hunks ignored--saving "
    558             "rejects to %s\n",
    559             failed,
    560             hunk,
    561             rejname);
    562       } else {
    563         say("%d out of %d hunks FAILED -- saving "
    564             "rejects to %s\n",
    565             failed,
    566             hunk,
    567             rejname);
    568       }
    569       if (!check_only && move_file(TMPREJNAME, rejname) < 0)
    570         trejkeep = 1;
    571     }
    572     set_signals(1);
    573   }
    574   my_exit(error);
    575 }
    576 
    577 static void
    578 reinitialize_almost_everything(void)
    579 {
    580   re_patch();
    581   re_input();
    582 
    583   input_lines      = 0;
    584   last_frozen_line = 0;
    585   filec            = 0;
    586   if (!out_of_mem) {
    587     free(filearg[0]);
    588     filearg[0] = NULL;
    589   }
    590   free(outname);
    591   outname     = NULL;
    592   last_offset = 0;
    593   diff_type   = 0;
    594   free(revision);
    595   revision           = NULL;
    596   reverse            = reverse_flag_specified;
    597   skip_rest_of_patch = 0;
    598   get_some_switches();
    599 }
    600 
    601 static void
    602 get_some_switches(void)
    603 {
    604   const char          *options    = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
    605   static struct option longopts[] = {
    606       {"backup", no_argument, 0, 'b'},
    607       {"backup-if-mismatch", no_argument, &backup_if_mismatch, 1},
    608       {"batch", no_argument, 0, 't'},
    609       {"check", no_argument, 0, 'C'},
    610       {"context", no_argument, 0, 'c'},
    611       {"debug", required_argument, 0, 'x'},
    612       {"directory", required_argument, 0, 'd'},
    613       {"ed", no_argument, 0, 'e'},
    614       {"force", no_argument, 0, 'f'},
    615       {"forward", no_argument, 0, 'N'},
    616       {"fuzz", required_argument, 0, 'F'},
    617       {"ifdef", required_argument, 0, 'D'},
    618       {"input", required_argument, 0, 'i'},
    619       {"ignore-whitespace", no_argument, 0, 'l'},
    620       {"no-backup-if-mismatch", no_argument, &backup_if_mismatch, 0},
    621       {"normal", no_argument, 0, 'n'},
    622       {"output", required_argument, 0, 'o'},
    623       {"prefix", required_argument, 0, 'B'},
    624       {"quiet", no_argument, 0, 's'},
    625       {"reject-file", required_argument, 0, 'r'},
    626       {"remove-empty-files", no_argument, 0, 'E'},
    627       {"reverse", no_argument, 0, 'R'},
    628       {"silent", no_argument, 0, 's'},
    629       {"strip", required_argument, 0, 'p'},
    630       {"suffix", required_argument, 0, 'z'},
    631       {"unified", no_argument, 0, 'u'},
    632       {"version", no_argument, 0, 'v'},
    633       {"version-control", required_argument, 0, 'V'},
    634       {"posix", no_argument, &posix, 1},
    635       {NULL, 0, 0, 0}
    636   };
    637   int ch;
    638 
    639   rejname[0] = '\0';
    640   Argc_last  = Argc;
    641   Argv_last  = Argv;
    642   if (!Argc)
    643     return;
    644   getopt_reset();
    645   while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
    646     switch (ch) {
    647       case 'b':
    648         if (backup_type == BACKUP_UNDEFINED)
    649           backup_type = BACKUP_NUMBERED_EXISTING;
    650         if (optarg == NULL)
    651           break;
    652         if (verbose)
    653           say("Warning, the -b suffix option has been "
    654               "obsoleted by the -z option\n");
    655         /* FALLTHROUGH */
    656       case 'z':
    657         simple_backup_suffix = savestr(optarg);
    658         break;
    659       case 'B':
    660         origprae = savestr(optarg);
    661         break;
    662       case 'c':
    663         diff_type = CONTEXT_DIFF;
    664         break;
    665       case 'C':
    666         check_only = 1;
    667         break;
    668       case 'd':
    669         if (chdir(optarg) < 0)
    670           pfatal("cant cd to %s", optarg);
    671         break;
    672       case 'D':
    673         do_defines = 1;
    674         if (!isalpha((unsigned char)*optarg) && *optarg != '_')
    675           fatal("argument to -D is not an identifier\n");
    676         snprintf(if_defined, sizeof if_defined, "#ifdef %s\n", optarg);
    677         snprintf(not_defined, sizeof not_defined, "#ifndef %s\n", optarg);
    678         snprintf(end_defined, sizeof end_defined, "#endif /* %s */\n", optarg);
    679         break;
    680       case 'e':
    681         diff_type = ED_DIFF;
    682         break;
    683       case 'E':
    684         remove_empty_files = 1;
    685         break;
    686       case 'f':
    687         force = 1;
    688         break;
    689       case 'F':
    690         maxfuzz = strtolinenum(optarg, NULL);
    691         break;
    692       case 'i':
    693         free(filearg[1]);
    694         filearg[1] = fetchname(optarg, &warn_on_invalid_line, 0);
    695         break;
    696       case 'l':
    697         canonicalize = 1;
    698         break;
    699       case 'n':
    700         diff_type = NORMAL_DIFF;
    701         break;
    702       case 'N':
    703         noreverse = 1;
    704         break;
    705       case 'o':
    706         outname = savestr(optarg);
    707         break;
    708       case 'p':
    709         strippath = (int)strtolinenum(optarg, NULL);
    710         break;
    711       case 'r':
    712         if (strlcpy(rejname, optarg, sizeof(rejname)) >= sizeof(rejname))
    713           fatal("reject filename %s too long\n", optarg);
    714         break;
    715       case 'R':
    716         reverse                = 1;
    717         reverse_flag_specified = 1;
    718         break;
    719       case 's':
    720         verbose = 0;
    721         break;
    722       case 't':
    723         batch = 1;
    724         break;
    725       case 'u':
    726         diff_type = UNI_DIFF;
    727         break;
    728       case 'v':
    729         version();
    730         break;
    731       case 'V':
    732         backup_type = get_version(optarg);
    733         break;
    734       case 'x':
    735 #ifdef DEBUGGING
    736         debug = (int)strtolinenum(optarg, NULL);
    737 #endif
    738         break;
    739       default:
    740         if (ch == 0)
    741           break;
    742         usage();
    743     }
    744   }
    745   Argc -= optind;
    746   Argv += optind;
    747 
    748   for (ch = 0; ch < Argc; ch++) {
    749     if (filec >= MAXFILEC)
    750       usage();
    751     filearg[filec++] = savestr(Argv[ch]);
    752   }
    753 }
    754 
    755 static void
    756 usage(void)
    757 {
    758   fprintf(
    759       stderr,
    760       "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] "
    761       "[-d directory] [-F max-fuzz] [-i patchfile] [-o out-file] "
    762       "[-p strip-count] [-r rej-name] [-V method] [-x number] "
    763       "[-z backup-ext] [origfile [patchfile]]\n"
    764   );
    765   my_exit(2);
    766 }
    767 
    768 static LINENUM
    769 locate_hunk(LINENUM fuzz)
    770 {
    771   LINENUM first_hunk_line = pch_first();
    772   LINENUM count           = pch_ptrn_lines();
    773   LINENUM max_line        = input_lines - count + 1;
    774   LINENUM line;
    775   LINENUM offset;
    776 
    777   if (!count)
    778     return first_hunk_line + last_offset;
    779 
    780   if (first_hunk_line + last_offset <= 0)
    781     offset = 1 - first_hunk_line;
    782   else if (first_hunk_line + last_offset > max_line)
    783     offset = max_line - first_hunk_line;
    784   else
    785     offset = last_offset;
    786 
    787   for (line = first_hunk_line + offset; line <= max_line; line++) {
    788     if (patch_match(line, count, fuzz)) {
    789       last_offset = line - first_hunk_line;
    790       return line;
    791     }
    792   }
    793   for (line = first_hunk_line + offset - 1; line >= 1; line--) {
    794     if (patch_match(line, count, fuzz)) {
    795       last_offset = line - first_hunk_line;
    796       return line;
    797     }
    798   }
    799   return 0;
    800 }
    801 
    802 static int
    803 patch_match(LINENUM line, LINENUM count, LINENUM fuzz)
    804 {
    805   LINENUM i;
    806   LINENUM pat_line;
    807   char   *str;
    808   char   *pat;
    809   ssize_t len;
    810 
    811   for (i = 1; i <= count; i++) {
    812     pat_line = i;
    813     if (i <= fuzz)
    814       continue;
    815     if (i > count - fuzz)
    816       continue;
    817     str = ifetch(line + i - 1 - fuzz, 0);
    818     if (str == NULL)
    819       return 0;
    820     pat = pfetch(pat_line);
    821     len = pch_line_len(pat_line);
    822     if (canonicalize) {
    823       if (!similar(str, pat, len))
    824         return 0;
    825     } else if (strncmp(str, pat, len) != 0)
    826       return 0;
    827   }
    828   return 1;
    829 }
    830 
    831 static int
    832 similar(const char *a, const char *b, ssize_t len)
    833 {
    834   while (len > 0) {
    835     if (isspace((unsigned char)*b)) {
    836       if (!isspace((unsigned char)*a))
    837         return 0;
    838       while (len > 0 && isspace((unsigned char)*b)) {
    839         b++;
    840         len--;
    841       }
    842       while (isspace((unsigned char)*a) && *a != '\n')
    843         a++;
    844     } else {
    845       if (*a != *b)
    846         return 0;
    847       a++;
    848       b++;
    849       len--;
    850     }
    851   }
    852   if (*a == '\n' || *a == '\r') {
    853     while (*a == '\n' || *a == '\r')
    854       a++;
    855     return *a == '\0';
    856   }
    857   return *a == '\0' || isspace((unsigned char)*a);
    858 }
    859 
    860 static void
    861 abort_hunk(void)
    862 {
    863   LINENUM i;
    864 
    865   for (i = 1; i <= pch_end(); i++)
    866     rej_line(i, i);
    867 }
    868 
    869 static void
    870 rej_line(int pat_line, LINENUM i)
    871 {
    872   char *str = pfetch(pat_line);
    873   char  ch  = pch_char(pat_line);
    874   (void)i;
    875   if (rejfp != NULL) {
    876     if (ch == ' ')
    877       fprintf(rejfp, " %s", str);
    878     else
    879       fprintf(rejfp, "%c%s", ch, str);
    880   }
    881 }
    882 
    883 static void
    884 apply_hunk(LINENUM where)
    885 {
    886   LINENUM       old      = 1;
    887   const LINENUM lastline = pch_ptrn_lines();
    888   LINENUM new            = lastline + 1;
    889 #define OUTSIDE   0
    890 #define IN_IFNDEF 1
    891 #define IN_IFDEF  2
    892 #define IN_ELSE   3
    893   int           def_state = OUTSIDE;
    894   const LINENUM pat_end   = pch_end();
    895 
    896   where--;
    897   while (pch_char(new) == '=' || pch_char(new) == '\n')
    898     new ++;
    899 
    900   while (old <= lastline) {
    901     if (pch_char(old) == '-') {
    902       copy_till(where + old - 1, 0);
    903       if (do_defines) {
    904         if (def_state == OUTSIDE) {
    905           fputs(not_defined, ofp);
    906           def_state = IN_IFNDEF;
    907         } else if (def_state == IN_IFDEF) {
    908           fputs(else_defined, ofp);
    909           def_state = IN_ELSE;
    910         }
    911         fputs(pfetch(old), ofp);
    912       }
    913       last_frozen_line++;
    914       old++;
    915     } else if (new > pat_end) {
    916       break;
    917     } else if (pch_char(new) == '+') {
    918       copy_till(where + old - 1, 0);
    919       if (do_defines) {
    920         if (def_state == IN_IFNDEF) {
    921           fputs(else_defined, ofp);
    922           def_state = IN_ELSE;
    923         } else if (def_state == OUTSIDE) {
    924           fputs(if_defined, ofp);
    925           def_state = IN_IFDEF;
    926         }
    927       }
    928       fputs(pfetch(new), ofp);
    929       new ++;
    930     } else if (pch_char(new) != pch_char(old)) {
    931       say("Out-of-sync patch, lines %ld,%ld--mangled text or "
    932           "line numbers, maybe?\n",
    933           pch_hunk_beg() + old,
    934           pch_hunk_beg() + new);
    935       my_exit(2);
    936     } else if (pch_char(new) == '!') {
    937       copy_till(where + old - 1, 0);
    938       if (do_defines) {
    939         fputs(not_defined, ofp);
    940         def_state = IN_IFNDEF;
    941       }
    942       while (pch_char(old) == '!') {
    943         if (do_defines) {
    944           fputs(pfetch(old), ofp);
    945         }
    946         last_frozen_line++;
    947         old++;
    948       }
    949       if (do_defines) {
    950         fputs(else_defined, ofp);
    951         def_state = IN_ELSE;
    952       }
    953       while (pch_char(new) == '!') {
    954         fputs(pfetch(new), ofp);
    955         new ++;
    956       }
    957     } else {
    958       if (pch_char(new) != ' ')
    959         fatal("Internal error: expected ' '\n");
    960       old++;
    961       new ++;
    962       if (do_defines && def_state != OUTSIDE) {
    963         fputs(end_defined, ofp);
    964         def_state = OUTSIDE;
    965       }
    966     }
    967   }
    968   if (new <= pat_end &&pch_char(new) == '+') {
    969     copy_till(where + old - 1, 0);
    970     if (do_defines) {
    971       if (def_state == OUTSIDE) {
    972         fputs(if_defined, ofp);
    973         def_state = IN_IFDEF;
    974       } else if (def_state == IN_IFNDEF) {
    975         fputs(else_defined, ofp);
    976         def_state = IN_ELSE;
    977       }
    978     }
    979     while (new <= pat_end &&pch_char(new) == '+') {
    980       fputs(pfetch(new), ofp);
    981       new ++;
    982     }
    983   }
    984   if (do_defines && def_state != OUTSIDE) {
    985     fputs(end_defined, ofp);
    986   }
    987 #undef OUTSIDE
    988 #undef IN_IFNDEF
    989 #undef IN_IFDEF
    990 #undef IN_ELSE
    991 }
    992 
    993 static void
    994 dump_input_line(LINENUM line, int write_newline)
    995 {
    996   char *s = ifetch(line, 0);
    997   if (s == NULL)
    998     return;
    999   for (; *s != '\n' && *s != '\0'; s++)
   1000     putc(*s, ofp);
   1001   if (write_newline)
   1002     putc('\n', ofp);
   1003 }
   1004 
   1005 static void
   1006 copy_till(LINENUM line, int end)
   1007 {
   1008   if (last_frozen_line > line)
   1009     fatal("misordered hunks! output would be garbled\n");
   1010   while (last_frozen_line < line) {
   1011     if (++last_frozen_line == line && end)
   1012       dump_input_line(last_frozen_line, !last_line_missing_eol);
   1013     else
   1014       dump_input_line(last_frozen_line, 1);
   1015   }
   1016 }
   1017 
   1018 static int
   1019 spew_output(void)
   1020 {
   1021   if (input_lines)
   1022     copy_till(input_lines, 1);
   1023   if (ferror(ofp) || fclose(ofp))
   1024     return 0;
   1025   ofp = NULL;
   1026   return 1;
   1027 }
   1028 
   1029 static void
   1030 init_output(const char *name)
   1031 {
   1032   ofp = fopen(name, "w");
   1033   if (ofp == NULL)
   1034     pfatal("cant create %s", name);
   1035 }
   1036 
   1037 static void
   1038 init_reject(const char *name)
   1039 {
   1040   rejfp = fopen(name, "w");
   1041   if (rejfp == NULL)
   1042     pfatal("cant create %s", name);
   1043 }
   1044 
   1045 void
   1046 re_input(void)
   1047 {
   1048   if (using_plan_a) {
   1049     i_size = 0;
   1050     free(i_ptr);
   1051     i_ptr = NULL;
   1052     if (i_womp != NULL) {
   1053       munmap(i_womp, i_size);
   1054       i_womp = NULL;
   1055     }
   1056   } else {
   1057     using_plan_a = 1;
   1058     close(tifd);
   1059     tifd = -1;
   1060     free(tibuf[0]);
   1061     free(tibuf[1]);
   1062     tibuf[0] = tibuf[1] = NULL;
   1063     tiline[0] = tiline[1] = -1;
   1064     tireclen              = 0;
   1065   }
   1066 }
   1067 
   1068 void
   1069 scan_input(const char *filename)
   1070 {
   1071   if (!plan_a(filename))
   1072     plan_b(filename);
   1073   if (verbose) {
   1074     say("Patching file %s using Plan %s...\n", filename, (using_plan_a ? "A" : "B"));
   1075   }
   1076 }
   1077 
   1078 static int
   1079 reallocate_lines(size_t *lines_allocated)
   1080 {
   1081   char **p;
   1082   size_t new_size;
   1083 
   1084   new_size = *lines_allocated * 3 / 2;
   1085   p        = pch_realloc(i_ptr, new_size + 2, sizeof(char *));
   1086   if (p == NULL) {
   1087     munmap(i_womp, i_size);
   1088     i_womp = NULL;
   1089     free(i_ptr);
   1090     i_ptr            = NULL;
   1091     *lines_allocated = 0;
   1092     return 0;
   1093   }
   1094   *lines_allocated = new_size;
   1095   i_ptr            = p;
   1096   return 1;
   1097 }
   1098 
   1099 static int
   1100 plan_a(const char *filename)
   1101 {
   1102   int         ifd, statfailed;
   1103   char       *p, *s, *lbuf;
   1104   struct stat filestat;
   1105   off_t       i;
   1106   ptrdiff_t   sz;
   1107   size_t      iline, lines_allocated, lbufsz;
   1108 
   1109 #ifdef DEBUGGING
   1110   if (debug & 8)
   1111     return 0;
   1112 #endif
   1113 
   1114   if (filename == NULL || *filename == '\0')
   1115     return 0;
   1116 
   1117   statfailed = stat(filename, &filestat);
   1118   if (statfailed && ok_to_create_file) {
   1119     if (verbose)
   1120       say("(Creating file %s...)\n", filename);
   1121     if (check_only)
   1122       return 1;
   1123     makedirs(filename, 1);
   1124     close(creat(filename, 0666));
   1125     statfailed = stat(filename, &filestat);
   1126   }
   1127   if (statfailed && check_only)
   1128     fatal("%s not found, -C mode, cant probe further\n", filename);
   1129 
   1130   if (statfailed || (filestat.st_mode & 0222) == 0
   1131       || ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
   1132     char       *filebase, *filedir;
   1133     struct stat cstat;
   1134     char       *tmp_filename1, *tmp_filename2;
   1135 
   1136     tmp_filename1 = strdup(filename);
   1137     tmp_filename2 = strdup(filename);
   1138     if (tmp_filename1 == NULL || tmp_filename2 == NULL)
   1139       fatal("strdupping filename");
   1140     filebase = basename(tmp_filename1);
   1141     filedir  = dirname(tmp_filename2);
   1142 
   1143     lbufsz = INITLINELEN;
   1144     if ((lbuf = malloc(bufsz)) == NULL)
   1145       pfatal("allocating line buffer");
   1146     lbuf[0] = '\0';
   1147 
   1148 #define try(f, a1, a2, a3) (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &cstat) == 0)
   1149 
   1150     if (try ("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX)
   1151         || try ("%s/RCS/%s%s", filedir, filebase, "")
   1152         || try ("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
   1153       if (!statfailed) {
   1154         if ((filestat.st_mode & 0222) != 0)
   1155           fatal(
   1156               "file %s seems to be locked by "
   1157               "somebody else under RCS\n",
   1158               filename
   1159           );
   1160         if (verbose)
   1161           say("Comparing file %s to default RCS "
   1162               "version...\n",
   1163               filename);
   1164         {
   1165           char *rcsdiff_argv[3];
   1166           rcsdiff_argv[0] = __UNCONST(RCSDIFF);
   1167           rcsdiff_argv[1] = __UNCONST(filename);
   1168           rcsdiff_argv[2] = NULL;
   1169           if (wexecvp(RCSDIFF, rcsdiff_argv) != 0)
   1170             fatal(
   1171                 "cant check out file %s: "
   1172                 "differs from default "
   1173                 "RCS version\n",
   1174                 filename
   1175             );
   1176         }
   1177       }
   1178       if (verbose)
   1179         say("Checking out file %s from RCS...\n", filename);
   1180       {
   1181         char *co_argv[4];
   1182         co_argv[0] = __UNCONST(CHECKOUT);
   1183         co_argv[1] = __UNCONST("-l");
   1184         co_argv[2] = __UNCONST(filename);
   1185         co_argv[3] = NULL;
   1186         if (wexecvp(CHECKOUT, co_argv) != 0 || stat(filename, &filestat))
   1187           fatal(
   1188               "cant check out file %s from "
   1189               "RCS\n",
   1190               filename
   1191           );
   1192       }
   1193     } else if (statfailed) {
   1194       fatal("cant find %s\n", filename);
   1195     }
   1196 #undef try
   1197     free(lbuf);
   1198     free(tmp_filename1);
   1199     free(tmp_filename2);
   1200   }
   1201 
   1202   filemode = filestat.st_mode;
   1203   if (!S_ISREG(filemode))
   1204     fatal("%s is not a normal file--cant patch\n", filename);
   1205   i_size = filestat.st_size;
   1206   if (out_of_mem) {
   1207     set_hunkmax();
   1208     out_of_mem = 0;
   1209     return 0;
   1210   }
   1211   if ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) {
   1212     say("block too large to mmap\n");
   1213     return 0;
   1214   }
   1215   if ((ifd = open(filename, O_RDONLY)) < 0)
   1216     pfatal("cant open file %s", filename);
   1217 
   1218   if (i_size) {
   1219     i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
   1220     if (i_womp == MAP_FAILED) {
   1221       perror("mmap failed");
   1222       i_womp = NULL;
   1223       close(ifd);
   1224       return 0;
   1225     }
   1226   } else
   1227     i_womp = NULL;
   1228 
   1229   close(ifd);
   1230   if (i_size)
   1231     madvise(i_womp, i_size, MADV_SEQUENTIAL);
   1232 
   1233   lines_allocated = i_size / 25;
   1234   if (lines_allocated < 100)
   1235     lines_allocated = 100;
   1236 
   1237   if (!reallocate_lines(&lines_allocated))
   1238     return 0;
   1239 
   1240   iline        = 1;
   1241   i_ptr[iline] = i_womp;
   1242   for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
   1243     if (*s == '\n') {
   1244       if (iline == lines_allocated) {
   1245         if (!reallocate_lines(&lines_allocated))
   1246           return 0;
   1247       }
   1248       i_ptr[++iline] = s + 1;
   1249     }
   1250   }
   1251   if (i_size > 0 && i_womp[i_size - 1] != '\n') {
   1252     last_line_missing_eol = 1;
   1253     sz                    = s - i_ptr[iline];
   1254     p                     = malloc(sz + 1);
   1255     if (p == NULL) {
   1256       free(i_ptr);
   1257       i_ptr = NULL;
   1258       munmap(i_womp, i_size);
   1259       i_womp = NULL;
   1260       return 0;
   1261     }
   1262     memcpy(p, i_ptr[iline], sz);
   1263     p[sz]          = '\n';
   1264     i_ptr[iline]   = p;
   1265     i_ptr[++iline] = empty_line;
   1266   } else
   1267     last_line_missing_eol = 0;
   1268 
   1269   input_lines = iline - 1;
   1270 
   1271   if (revision != NULL) {
   1272     if (!rev_in_string(i_womp)) {
   1273       if (force) {
   1274         if (verbose)
   1275           say("Warning: this file doesnt appear "
   1276               "to be the %s version--patching "
   1277               "anyway\n",
   1278               revision);
   1279       } else if (batch) {
   1280         fatal(
   1281             "this file doesnt appear to be the %s "
   1282             "version--aborting\n",
   1283             revision
   1284         );
   1285       } else {
   1286         ask("This file doesnt appear to be the %s "
   1287             "version--patch anyway? [n] ",
   1288             revision);
   1289         if (*buf != 'y')
   1290           fatal("aborted\n");
   1291       }
   1292     } else if (verbose)
   1293       say("Good. This file appears to be the %s version.\n", revision);
   1294   }
   1295   return 1;
   1296 }
   1297 
   1298 static void
   1299 plan_b(const char *filename)
   1300 {
   1301   FILE  *ifp;
   1302   size_t i = 0, j, maxlen = 1;
   1303   char  *p;
   1304   int    found_revision = (revision == NULL);
   1305 
   1306   using_plan_a = 0;
   1307   if ((ifp = fopen(filename, "r")) == NULL)
   1308     pfatal("cant open file %s", filename);
   1309   unlink(TMPINNAME);
   1310   if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
   1311     pfatal("cant open file %s", TMPINNAME);
   1312   while (getline(&buf, &bufsz, ifp) != -1) {
   1313     if (revision != NULL && !found_revision && rev_in_string(buf))
   1314       found_revision = 1;
   1315     if ((i = strlen(buf)) > maxlen)
   1316       maxlen = i;
   1317   }
   1318   last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
   1319   if (last_line_missing_eol && maxlen == i)
   1320     maxlen++;
   1321 
   1322   if (revision != NULL) {
   1323     if (!found_revision) {
   1324       if (force) {
   1325         if (verbose)
   1326           say("Warning: this file doesnt appear "
   1327               "to be the %s version--patching "
   1328               "anyway\n",
   1329               revision);
   1330       } else if (batch) {
   1331         fatal(
   1332             "this file doesnt appear to be the %s "
   1333             "version--aborting\n",
   1334             revision
   1335         );
   1336       } else {
   1337         ask("This file doesnt appear to be the %s "
   1338             "version--patch anyway? [n] ",
   1339             revision);
   1340         if (*buf != 'y')
   1341           fatal("aborted\n");
   1342       }
   1343     } else if (verbose)
   1344       say("Good. This file appears to be the %s version.\n", revision);
   1345   }
   1346   fseek(ifp, 0L, SEEK_SET);
   1347   lines_per_buf = BUFFERSIZE / maxlen;
   1348   tireclen      = maxlen;
   1349   tibuf[0]      = malloc(BUFFERSIZE + 1);
   1350   if (tibuf[0] == NULL)
   1351     fatal("out of memory\n");
   1352   tibuf[1] = malloc(BUFFERSIZE + 1);
   1353   if (tibuf[1] == NULL)
   1354     fatal("out of memory\n");
   1355   for (i = 1;; i++) {
   1356     p = tibuf[0] + maxlen * (i % lines_per_buf);
   1357     if (i % lines_per_buf == 0) {
   1358       if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
   1359         pfatal("cant write temp file");
   1360     }
   1361     if (fgets(p, maxlen + 1, ifp) == NULL) {
   1362       input_lines = i - 1;
   1363       if (i % lines_per_buf != 0) {
   1364         if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
   1365           pfatal("cant write temp file");
   1366       }
   1367       break;
   1368     }
   1369     j = strlen(p);
   1370     if (j == 0 || p[j - 1] != '\n')
   1371       p[j] = '\n';
   1372   }
   1373   fclose(ifp);
   1374   close(tifd);
   1375   if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
   1376     pfatal("cant reopen file %s", TMPINNAME);
   1377 }
   1378 
   1379 char *
   1380 ifetch(LINENUM line, int whichbuf)
   1381 {
   1382   if (line < 1 || line > input_lines) {
   1383     if (warn_on_invalid_line) {
   1384       say("No such line %ld in input file, ignoring\n", line);
   1385       warn_on_invalid_line = 0;
   1386     }
   1387     return NULL;
   1388   }
   1389   if (using_plan_a)
   1390     return i_ptr[line];
   1391   else {
   1392     LINENUM offline  = line % lines_per_buf;
   1393     LINENUM baseline = line - offline;
   1394 
   1395     if (tiline[0] == baseline)
   1396       whichbuf = 0;
   1397     else if (tiline[1] == baseline)
   1398       whichbuf = 1;
   1399     else {
   1400       tiline[whichbuf] = baseline;
   1401       if (lseek(tifd, (off_t)(baseline / lines_per_buf * BUFFERSIZE), SEEK_SET) < 0)
   1402         pfatal(
   1403             "cannot seek in the temporary input "
   1404             "file"
   1405         );
   1406       if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
   1407         pfatal("error reading tmp file %s", TMPINNAME);
   1408     }
   1409     return tibuf[whichbuf] + (tireclen * offline);
   1410   }
   1411 }
   1412 
   1413 static int
   1414 rev_in_string(const char *string)
   1415 {
   1416   const char *s;
   1417   size_t      patlen;
   1418 
   1419   if (revision == NULL)
   1420     return 1;
   1421   patlen = strlen(revision);
   1422   if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
   1423     return 1;
   1424   for (s = string; *s; s++) {
   1425     if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen)
   1426         && isspace((unsigned char)s[patlen + 1]))
   1427       return 1;
   1428   }
   1429   return 0;
   1430 }
   1431 
   1432 void
   1433 re_patch(void)
   1434 {
   1435   p_first      = 0;
   1436   p_newfirst   = 0;
   1437   p_ptrn_lines = 0;
   1438   p_repl_lines = 0;
   1439   p_end        = (LINENUM)-1;
   1440   p_max        = 0;
   1441   p_indent     = 0;
   1442 }
   1443 
   1444 void
   1445 open_patch_file(const char *filename)
   1446 {
   1447   struct stat filestat;
   1448 
   1449   if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
   1450     pfp = fopen(TMPPATNAME, "w");
   1451     if (pfp == NULL)
   1452       pfatal("cant create %s", TMPPATNAME);
   1453     while (getline(&buf, &bufsz, stdin) != -1)
   1454       fprintf(pfp, "%s", buf);
   1455     if (ferror(pfp) || fclose(pfp))
   1456       pfatal("cant write %s", TMPPATNAME);
   1457     filename = TMPPATNAME;
   1458   }
   1459   pfp = fopen(filename, "r");
   1460   if (pfp == NULL)
   1461     pfatal("patch file %s not found", filename);
   1462   fstat(fileno(pfp), &filestat);
   1463   p_filesize = filestat.st_size;
   1464   next_intuit_at(0L, 1L);
   1465   set_hunkmax();
   1466 }
   1467 
   1468 void
   1469 set_hunkmax(void)
   1470 {
   1471   if (p_line == NULL)
   1472     p_line = calloc((size_t)hunkmax, sizeof(char *));
   1473   if (p_len == NULL)
   1474     p_len = calloc((size_t)hunkmax, sizeof(ssize_t));
   1475   if (p_char == NULL)
   1476     p_char = calloc((size_t)hunkmax, sizeof(char));
   1477 }
   1478 
   1479 static void
   1480 grow_hunkmax(void)
   1481 {
   1482   int      new_hunkmax;
   1483   char   **new_p_line;
   1484   ssize_t *new_p_len;
   1485   char    *new_p_char;
   1486 
   1487   new_hunkmax = hunkmax * 2;
   1488   if (p_line == NULL || p_len == NULL || p_char == NULL)
   1489     fatal("Internal memory allocation error\n");
   1490 
   1491   new_p_line = pch_realloc(p_line, new_hunkmax, sizeof(char *));
   1492   if (new_p_line == NULL)
   1493     free(p_line);
   1494   new_p_len = pch_realloc(p_len, new_hunkmax, sizeof(ssize_t));
   1495   if (new_p_len == NULL)
   1496     free(p_len);
   1497   new_p_char = pch_realloc(p_char, new_hunkmax, sizeof(char));
   1498   if (new_p_char == NULL)
   1499     free(p_char);
   1500 
   1501   p_char = new_p_char;
   1502   p_len  = new_p_len;
   1503   p_line = new_p_line;
   1504 
   1505   if (p_line != NULL && p_len != NULL && p_char != NULL) {
   1506     hunkmax = new_hunkmax;
   1507     return;
   1508   }
   1509 
   1510   if (!using_plan_a)
   1511     fatal("out of memory\n");
   1512   out_of_mem = 1;
   1513 }
   1514 
   1515 int
   1516 there_is_another_patch(void)
   1517 {
   1518   int exists = 0;
   1519 
   1520   if (p_base != 0L && p_base >= p_filesize) {
   1521     if (verbose)
   1522       say("done\n");
   1523     return 0;
   1524   }
   1525   if (verbose)
   1526     say("Hmm...");
   1527   diff_type = intuit_diff_type();
   1528   if (!diff_type) {
   1529     if (p_base != 0L) {
   1530       if (verbose)
   1531         say(" Ignoring the trailing garbage.\ndone\n");
   1532     } else
   1533       say(" I cant seem to find a patch in there anywhere\n");
   1534     return 0;
   1535   }
   1536   if (verbose) {
   1537     say(" %sooks like %s to me...\n",
   1538         (p_base == 0L ? "L" : "The next patch l"),
   1539         diff_type == UNI_DIFF           ? "a unified diff"
   1540         : diff_type == CONTEXT_DIFF     ? "a context diff"
   1541         : diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff"
   1542         : diff_type == NORMAL_DIFF      ? "a normal diff"
   1543                                         : "an ed script");
   1544   }
   1545   if (p_indent && verbose)
   1546     say("(Patch is indented %d space%s.)\n", p_indent, p_indent == 1 ? "" : "s");
   1547   skip_to(p_start, p_sline);
   1548   while (filearg[0] == NULL) {
   1549     if (force || batch) {
   1550       say("No file to patch. Skipping...\n");
   1551       filearg[0]         = savestr(bestguess);
   1552       skip_rest_of_patch = 1;
   1553       return 1;
   1554     }
   1555     ask("File to patch: ");
   1556     if (*buf != '\n') {
   1557       free(bestguess);
   1558       bestguess  = savestr(buf);
   1559       filearg[0] = fetchname(buf, &exists, 0);
   1560     }
   1561     if (!exists) {
   1562       ask("No file found--skip this patch? [n] ");
   1563       if (*buf != 'y')
   1564         continue;
   1565       if (verbose)
   1566         say("Skipping patch...\n");
   1567       free(filearg[0]);
   1568       filearg[0]         = fetchname(bestguess, &exists, 0);
   1569       skip_rest_of_patch = 1;
   1570       return 1;
   1571     }
   1572   }
   1573   return 1;
   1574 }
   1575 
   1576 static int
   1577 intuit_diff_type(void)
   1578 {
   1579   long            this_line             = 0, previous_line;
   1580   long            first_command_line    = -1;
   1581   LINENUM         fcl_line              = -1;
   1582   int             last_line_was_command = 0, this_is_a_command = 0;
   1583   int             stars_last_line = 0, stars_this_line = 0;
   1584   char           *s, *t;
   1585   int             indent, retval;
   1586   struct FileName names[MAX_FILE];
   1587 
   1588   memset(names, 0, sizeof(names));
   1589   ok_to_create_file = 0;
   1590   fseek(pfp, p_base, SEEK_SET);
   1591   p_input_line = p_bline - 1;
   1592   for (;;) {
   1593     previous_line         = this_line;
   1594     last_line_was_command = this_is_a_command;
   1595     stars_last_line       = stars_this_line;
   1596     this_line             = ftell(pfp);
   1597     indent                = 0;
   1598     p_input_line++;
   1599     if (getline(&buf, &bufsz, pfp) == -1) {
   1600       if (first_command_line >= 0L) {
   1601         p_start = first_command_line;
   1602         p_sline = fcl_line;
   1603         retval  = ED_DIFF;
   1604         goto scan_exit;
   1605       } else {
   1606         p_start = this_line;
   1607         p_sline = p_input_line;
   1608         retval  = 0;
   1609         goto scan_exit;
   1610       }
   1611     }
   1612     for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
   1613       if (*s == '\t')
   1614         indent += 8 - (indent % 8);
   1615       else
   1616         indent++;
   1617     }
   1618     for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
   1619       ;
   1620     this_is_a_command = (isdigit((unsigned char)*s) && (*t == 'd' || *t == 'c' || *t == 'a'));
   1621     if (first_command_line < 0L && this_is_a_command) {
   1622       first_command_line = this_line;
   1623       fcl_line           = p_input_line;
   1624       p_indent           = indent;
   1625     }
   1626     if (!stars_last_line && strnEQ(s, "*** ", 4)) {
   1627       names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath);
   1628     } else if (strnEQ(s, "--- ", 4)) {
   1629       names[NEW_FILE].path = fetchname(s + 4, &names[NEW_FILE].exists, strippath);
   1630     } else if (strnEQ(s, "+++ ", 4)) {
   1631       names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath);
   1632     } else if (strnEQ(s, "Index:", 6)) {
   1633       names[INDEX_FILE].path = fetchname(s + 6, &names[INDEX_FILE].exists, strippath);
   1634     } else if (strnEQ(s, "Prereq:", 7)) {
   1635       for (t = s + 7; isspace((unsigned char)*t); t++)
   1636         ;
   1637       revision = savestr(t);
   1638       for (t = revision; *t && !isspace((unsigned char)*t); t++)
   1639         ;
   1640       *t = '\0';
   1641       if (*revision == '\0') {
   1642         free(revision);
   1643         revision = NULL;
   1644       }
   1645     }
   1646     if ((!diff_type || diff_type == ED_DIFF) && first_command_line >= 0L && strEQ(s, ".\n")) {
   1647       p_indent = indent;
   1648       p_start  = first_command_line;
   1649       p_sline  = fcl_line;
   1650       retval   = ED_DIFF;
   1651       goto scan_exit;
   1652     }
   1653     if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
   1654       if (strnEQ(s + 4, "0,0", 3))
   1655         ok_to_create_file = 1;
   1656       p_indent = indent;
   1657       p_start  = this_line;
   1658       p_sline  = p_input_line;
   1659       retval   = UNI_DIFF;
   1660       goto scan_exit;
   1661     }
   1662     stars_this_line = strnEQ(s, "********", 8);
   1663     if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line && strnEQ(s, "*** ", 4)) {
   1664       if (atol(s + 4) == 0)
   1665         ok_to_create_file = 1;
   1666       while (*s != '\n')
   1667         s++;
   1668       p_indent = indent;
   1669       p_start  = previous_line;
   1670       p_sline  = p_input_line - 1;
   1671       retval   = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
   1672       goto scan_exit;
   1673     }
   1674     if ((!diff_type || diff_type == NORMAL_DIFF) && last_line_was_command
   1675         && (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
   1676       p_start  = previous_line;
   1677       p_sline  = p_input_line - 1;
   1678       p_indent = indent;
   1679       retval   = NORMAL_DIFF;
   1680       goto scan_exit;
   1681     }
   1682   }
   1683 scan_exit:
   1684   if (retval == UNI_DIFF) {
   1685     struct FileName tmp = names[OLD_FILE];
   1686     names[OLD_FILE]     = names[NEW_FILE];
   1687     names[NEW_FILE]     = tmp;
   1688   }
   1689   if (filearg[0] == NULL) {
   1690     if (posix)
   1691       filearg[0] = posix_name(names, ok_to_create_file);
   1692     else {
   1693       if (names[OLD_FILE].path != NULL || names[NEW_FILE].path != NULL) {
   1694         free(names[INDEX_FILE].path);
   1695         names[INDEX_FILE].path = NULL;
   1696       }
   1697       filearg[0] = best_name(names, ok_to_create_file);
   1698     }
   1699   }
   1700   free(bestguess);
   1701   bestguess = NULL;
   1702   if (filearg[0] != NULL)
   1703     bestguess = savestr(filearg[0]);
   1704   else if (!ok_to_create_file) {
   1705     if (posix)
   1706       bestguess = posix_name(names, 1);
   1707     else
   1708       bestguess = best_name(names, 1);
   1709   }
   1710   free(names[OLD_FILE].path);
   1711   free(names[NEW_FILE].path);
   1712   free(names[INDEX_FILE].path);
   1713   return retval;
   1714 }
   1715 
   1716 static void
   1717 next_intuit_at(LINENUM file_pos, LINENUM file_line)
   1718 {
   1719   p_base  = file_pos;
   1720   p_bline = file_line;
   1721 }
   1722 
   1723 static void
   1724 skip_to(LINENUM file_pos, LINENUM file_line)
   1725 {
   1726   int ret;
   1727 
   1728   if (p_base > file_pos)
   1729     fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
   1730   if (verbose && p_base < file_pos) {
   1731     fseek(pfp, p_base, SEEK_SET);
   1732     say("The text leading up to this "
   1733         "was:\n--------------------------\n");
   1734     while (ftell(pfp) < file_pos) {
   1735       ret = getline(&buf, &bufsz, pfp);
   1736       if (ret == -1)
   1737         fatal("Unexpected end of file\n");
   1738       say("|%s", buf);
   1739     }
   1740     say("--------------------------\n");
   1741   } else
   1742     fseek(pfp, file_pos, SEEK_SET);
   1743   p_input_line = file_line - 1;
   1744 }
   1745 
   1746 __dead static void
   1747 malformed(void)
   1748 {
   1749   fatal("malformed patch at line %ld: %s", p_input_line, buf);
   1750 }
   1751 
   1752 static LINENUM
   1753 getlinenum(const char *s)
   1754 {
   1755   LINENUM l = (LINENUM)atol(s);
   1756   if (l < 0) {
   1757     l = 0;
   1758     malformed();
   1759   }
   1760   return l;
   1761 }
   1762 
   1763 static LINENUM
   1764 getskiplinenum(char **p)
   1765 {
   1766   char   *s = *p;
   1767   LINENUM l = getlinenum(s);
   1768   while (isdigit((unsigned char)*s))
   1769     s++;
   1770   *p = s;
   1771   return l;
   1772 }
   1773 
   1774 static int
   1775 remove_special_line(void)
   1776 {
   1777   int c;
   1778 
   1779   c = fgetc(pfp);
   1780   if (c == '\\') {
   1781     do {
   1782       c = fgetc(pfp);
   1783     } while (c != EOF && c != '\n');
   1784     return 1;
   1785   }
   1786   if (c != EOF)
   1787     fseek(pfp, -1L, SEEK_CUR);
   1788   return 0;
   1789 }
   1790 
   1791 int
   1792 another_hunk(void)
   1793 {
   1794   long    line_beginning;
   1795   LINENUM repl_beginning;
   1796   LINENUM fillcnt;
   1797   LINENUM fillsrc;
   1798   LINENUM filldst;
   1799   int     ptrn_spaces_eaten;
   1800   int     repl_could_be_missing;
   1801   int     repl_missing;
   1802   long    repl_backtrack_position;
   1803   LINENUM repl_patch_line;
   1804   LINENUM ptrn_copiable;
   1805   char   *s;
   1806   int     context = 0;
   1807   int     ret;
   1808 
   1809   while (p_end >= 0) {
   1810     if (p_end == p_efake)
   1811       p_end = p_bfake;
   1812     else
   1813       free(p_line[p_end]);
   1814     p_end--;
   1815   }
   1816   p_efake = -1;
   1817   p_max   = hunkmax;
   1818 
   1819   if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
   1820     line_beginning          = ftell(pfp);
   1821     repl_beginning          = 0;
   1822     fillcnt                 = 0;
   1823     fillsrc                 = 0;
   1824     filldst                 = 0;
   1825     ptrn_spaces_eaten       = 0;
   1826     repl_could_be_missing   = 1;
   1827     repl_missing            = 0;
   1828     repl_backtrack_position = 0;
   1829     repl_patch_line         = 0;
   1830     ptrn_copiable           = 0;
   1831 
   1832     ret = pgetline(&buf, &bufsz, pfp);
   1833     p_input_line++;
   1834     if (ret == -1 || strnNE(buf, "********", 8)) {
   1835       next_intuit_at(line_beginning, p_input_line);
   1836       return 0;
   1837     }
   1838     p_context  = 100;
   1839     p_hunk_beg = p_input_line + 1;
   1840     while (p_end < p_max) {
   1841       ret = pgetline(&buf, &bufsz, pfp);
   1842       p_input_line++;
   1843       if (ret == -1) {
   1844         if (repl_beginning && repl_could_be_missing) {
   1845           repl_missing = 1;
   1846           goto hunk_done;
   1847         }
   1848         fatal("unexpected end of file in patch\n");
   1849       }
   1850       p_end++;
   1851       if (p_end >= hunkmax)
   1852         fatal(
   1853             "Internal error: hunk larger than hunk "
   1854             "buffer size"
   1855         );
   1856       p_char[p_end] = *buf;
   1857       p_line[p_end] = NULL;
   1858       switch (*buf) {
   1859         case '*':
   1860           if (strnEQ(buf, "********", 8)) {
   1861             if (repl_beginning && repl_could_be_missing) {
   1862               repl_missing = 1;
   1863               goto hunk_done;
   1864             } else
   1865               fatal(
   1866                   "unexpected end of hunk "
   1867                   "at line %ld\n",
   1868                   p_input_line
   1869               );
   1870           }
   1871           if (p_end != 0) {
   1872             if (repl_beginning && repl_could_be_missing) {
   1873               repl_missing = 1;
   1874               goto hunk_done;
   1875             }
   1876             fatal("unexpected *** at line %ld: %s", p_input_line, buf);
   1877           }
   1878           context       = 0;
   1879           p_line[p_end] = savestr(buf);
   1880           if (out_of_mem) {
   1881             p_end--;
   1882             return 0;
   1883           }
   1884           for (s = buf; *s && !isdigit((unsigned char)*s); s++)
   1885             ;
   1886           if (!*s)
   1887             malformed();
   1888           if (strnEQ(s, "0,0", 3))
   1889             memmove(s, s + 2, strlen(s + 2) + 1);
   1890           p_first = getskiplinenum(&s);
   1891           if (*s == ',') {
   1892             for (; *s && !isdigit((unsigned char)*s); s++)
   1893               ;
   1894             if (!*s)
   1895               malformed();
   1896             p_ptrn_lines = (getlinenum(s)) - p_first + 1;
   1897             if (p_ptrn_lines < 0)
   1898               malformed();
   1899           } else if (p_first)
   1900             p_ptrn_lines = 1;
   1901           else {
   1902             p_ptrn_lines = 0;
   1903             p_first      = 1;
   1904           }
   1905           if (p_first >= LINENUM_MAX - p_ptrn_lines || p_ptrn_lines >= LINENUM_MAX - 6)
   1906             malformed();
   1907           p_max = p_ptrn_lines + 6;
   1908           while (p_max >= hunkmax)
   1909             grow_hunkmax();
   1910           p_max = hunkmax;
   1911           break;
   1912         case '-':
   1913           if (buf[1] == '-') {
   1914             if (repl_beginning || (p_end != p_ptrn_lines + 1 + (p_char[p_end - 1] == '\n'))) {
   1915               if (p_end == 1) {
   1916                 p_end   = p_ptrn_lines + 1;
   1917                 fillsrc = p_end + 1;
   1918                 filldst = 1;
   1919                 fillcnt = p_ptrn_lines;
   1920               } else {
   1921                 if (repl_beginning) {
   1922                   if (repl_could_be_missing) {
   1923                     repl_missing = 1;
   1924                     goto hunk_done;
   1925                   }
   1926                   fatal(
   1927                       "duplicat"
   1928                       "e "
   1929                       "\"---\" "
   1930                       "at line "
   1931                       "%ld\n",
   1932                       p_input_line
   1933                   );
   1934                 } else {
   1935                   fatal(
   1936                       "prematur"
   1937                       "e/"
   1938                       "overdue "
   1939                       "\"---\" "
   1940                       "at line "
   1941                       "%ld\n",
   1942                       p_input_line
   1943                   );
   1944                 }
   1945               }
   1946             }
   1947             repl_beginning          = p_end;
   1948             repl_backtrack_position = ftell(pfp);
   1949             repl_patch_line         = p_input_line;
   1950             p_line[p_end]           = savestr(buf);
   1951             if (out_of_mem) {
   1952               p_end--;
   1953               return 0;
   1954             }
   1955             p_char[p_end] = '=';
   1956             for (s = buf; *s && !isdigit((unsigned char)*s); s++)
   1957               ;
   1958             if (!*s)
   1959               malformed();
   1960             p_newfirst = getskiplinenum(&s);
   1961             if (*s == ',') {
   1962               for (; *s && !isdigit((unsigned char)*s); s++)
   1963                 ;
   1964               if (!*s)
   1965                 malformed();
   1966               p_repl_lines = (getlinenum(s)) - p_newfirst + 1;
   1967               if (p_repl_lines < 0)
   1968                 malformed();
   1969             } else if (p_newfirst)
   1970               p_repl_lines = 1;
   1971             else {
   1972               p_repl_lines = 0;
   1973               p_newfirst   = 1;
   1974             }
   1975             if (p_newfirst >= LINENUM_MAX - p_repl_lines || p_repl_lines >= LINENUM_MAX - p_end)
   1976               malformed();
   1977             p_max = p_repl_lines + p_end;
   1978             if (p_max > MAXHUNKSIZE)
   1979               fatal(
   1980                   "hunk too large at line "
   1981                   "%ld\n",
   1982                   p_input_line
   1983               );
   1984             while (p_max >= hunkmax)
   1985               grow_hunkmax();
   1986             if (p_repl_lines != ptrn_copiable && (p_context != 0 || p_repl_lines != 1))
   1987               repl_could_be_missing = 0;
   1988             break;
   1989           }
   1990           goto change_line;
   1991         case '+':
   1992         case '!':
   1993           repl_could_be_missing = 0;
   1994         change_line:
   1995           if (buf[1] == '\n' && canonicalize)
   1996             strlcpy(buf + 1, " \n", bufsz - 1);
   1997           if (!isspace((unsigned char)buf[1]) && buf[1] != '>' && buf[1] != '<' && repl_beginning
   1998               && repl_could_be_missing) {
   1999             repl_missing = 1;
   2000             goto hunk_done;
   2001           }
   2002           if (context >= 0) {
   2003             if (context < p_context)
   2004               p_context = context;
   2005             context = -1000;
   2006           }
   2007           p_line[p_end] = savestr(buf + 2);
   2008           if (out_of_mem) {
   2009             p_end--;
   2010             return 0;
   2011           }
   2012           if (p_end == p_ptrn_lines) {
   2013             if (remove_special_line()) {
   2014               int length              = strlen(p_line[p_end]) - 1;
   2015               (p_line[p_end])[length] = 0;
   2016             }
   2017           }
   2018           break;
   2019         case '\t':
   2020         case '\n':
   2021           if (repl_beginning && repl_could_be_missing
   2022               && (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF)) {
   2023             repl_missing = 1;
   2024             goto hunk_done;
   2025           }
   2026           p_line[p_end] = savestr(buf);
   2027           if (out_of_mem) {
   2028             p_end--;
   2029             return 0;
   2030           }
   2031           if (p_end != p_ptrn_lines + 1) {
   2032             ptrn_spaces_eaten |= (repl_beginning != 0);
   2033             context++;
   2034             if (!repl_beginning)
   2035               ptrn_copiable++;
   2036             p_char[p_end] = ' ';
   2037           }
   2038           break;
   2039         case ' ':
   2040           if (!isspace((unsigned char)buf[1]) && repl_beginning && repl_could_be_missing) {
   2041             repl_missing = 1;
   2042             goto hunk_done;
   2043           }
   2044           context++;
   2045           if (!repl_beginning)
   2046             ptrn_copiable++;
   2047           p_line[p_end] = savestr(buf + 2);
   2048           if (out_of_mem) {
   2049             p_end--;
   2050             return 0;
   2051           }
   2052           break;
   2053         default:
   2054           if (repl_beginning && repl_could_be_missing) {
   2055             repl_missing = 1;
   2056             goto hunk_done;
   2057           }
   2058           malformed();
   2059       }
   2060       if (p_line[p_end])
   2061         p_len[p_end] = strlen(p_line[p_end]);
   2062       else
   2063         p_len[p_end] = 0;
   2064     }
   2065 
   2066   hunk_done:
   2067     if (p_end >= 0 && !repl_beginning)
   2068       fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
   2069 
   2070     if (repl_missing) {
   2071       p_input_line = repl_patch_line;
   2072       for (p_end--; p_end > repl_beginning; p_end--)
   2073         free(p_line[p_end]);
   2074       fseek(pfp, repl_backtrack_position, SEEK_SET);
   2075 
   2076       if (!p_context && p_repl_lines == 1) {
   2077         p_repl_lines = 0;
   2078         p_max--;
   2079       }
   2080       fillsrc = 1;
   2081       filldst = repl_beginning + 1;
   2082       fillcnt = p_repl_lines;
   2083       p_end   = p_max;
   2084     } else if (!p_context && fillcnt == 1) {
   2085       while (filldst < p_end) {
   2086         p_line[filldst] = p_line[filldst + 1];
   2087         p_char[filldst] = p_char[filldst + 1];
   2088         p_len[filldst]  = p_len[filldst + 1];
   2089         filldst++;
   2090       }
   2091       p_end--;
   2092       p_first++;
   2093       fillcnt      = 0;
   2094       p_ptrn_lines = 0;
   2095     }
   2096     if (diff_type == CONTEXT_DIFF && (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
   2097       diff_type = NEW_CONTEXT_DIFF;
   2098     }
   2099     if (fillcnt) {
   2100       p_bfake = filldst;
   2101       p_efake = filldst + fillcnt - 1;
   2102       while (fillcnt-- > 0) {
   2103         while (fillsrc <= p_end && p_char[fillsrc] != ' ')
   2104           fillsrc++;
   2105         if (fillsrc > p_end)
   2106           fatal(
   2107               "replacement text mangled in "
   2108               "hunk at line %ld\n",
   2109               p_hunk_beg
   2110           );
   2111         p_line[filldst] = p_line[fillsrc];
   2112         p_char[filldst] = p_char[fillsrc];
   2113         p_len[filldst]  = p_len[fillsrc];
   2114         fillsrc++;
   2115         filldst++;
   2116       }
   2117       while (fillsrc <= p_end && fillsrc != repl_beginning && p_char[fillsrc] != ' ')
   2118         fillsrc++;
   2119       if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
   2120         malformed();
   2121       if (filldst != p_end + 1 && filldst != repl_beginning)
   2122         malformed();
   2123     }
   2124     if (p_line[p_end] != NULL) {
   2125       if (remove_special_line()) {
   2126         p_len[p_end] -= 1;
   2127         (p_line[p_end])[p_len[p_end]] = 0;
   2128       }
   2129     }
   2130   } else if (diff_type == UNI_DIFF) {
   2131     LINENUM fillold;
   2132     LINENUM fillnew;
   2133     char    ch;
   2134 
   2135     line_beginning = ftell(pfp);
   2136     ret            = pgetline(&buf, &bufsz, pfp);
   2137     p_input_line++;
   2138     if (ret == -1 || strnNE(buf, "@@ -", 4)) {
   2139       next_intuit_at(line_beginning, p_input_line);
   2140       return 0;
   2141     }
   2142     s = buf + 4;
   2143     if (!*s)
   2144       malformed();
   2145     p_first = getskiplinenum(&s);
   2146     if (*s == ',') {
   2147       s++;
   2148       p_ptrn_lines = getskiplinenum(&s);
   2149     } else
   2150       p_ptrn_lines = 1;
   2151     if (p_first >= LINENUM_MAX - p_ptrn_lines)
   2152       malformed();
   2153     if (*s == ' ')
   2154       s++;
   2155     if (*s != '+' || !*++s)
   2156       malformed();
   2157     p_newfirst = getskiplinenum(&s);
   2158     if (*s == ',') {
   2159       s++;
   2160       p_repl_lines = getskiplinenum(&s);
   2161     } else
   2162       p_repl_lines = 1;
   2163     if (*s == ' ')
   2164       s++;
   2165     if (*s != '@')
   2166       malformed();
   2167     if (p_first >= LINENUM_MAX - p_ptrn_lines || p_newfirst > LINENUM_MAX - p_repl_lines
   2168         || p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
   2169       malformed();
   2170     if (!p_ptrn_lines)
   2171       p_first++;
   2172     p_max = p_ptrn_lines + p_repl_lines + 1;
   2173     while (p_max >= hunkmax)
   2174       grow_hunkmax();
   2175     fillold = 1;
   2176     fillnew = fillold + p_ptrn_lines;
   2177     p_end   = fillnew + p_repl_lines;
   2178     snprintf(buf, bufsz, "*** %ld,%ld ****\n", p_first, p_first + p_ptrn_lines - 1);
   2179     p_line[0] = savestr(buf);
   2180     if (out_of_mem) {
   2181       p_end = -1;
   2182       return 0;
   2183     }
   2184     p_char[0] = '*';
   2185     snprintf(buf, bufsz, "--- %ld,%ld ----\n", p_newfirst, p_newfirst + p_repl_lines - 1);
   2186     p_line[fillnew] = savestr(buf);
   2187     if (out_of_mem) {
   2188       p_end = 0;
   2189       return 0;
   2190     }
   2191     p_char[fillnew++] = '=';
   2192     p_context         = 100;
   2193     context           = 0;
   2194     p_hunk_beg        = p_input_line + 1;
   2195     while (fillold <= p_ptrn_lines || fillnew <= p_end) {
   2196       ret = pgetline(&buf, &bufsz, pfp);
   2197       p_input_line++;
   2198       if (ret == -1) {
   2199         if (p_max - fillnew < 3)
   2200           strlcpy(buf, " \n", bufsz);
   2201         else
   2202           fatal(
   2203               "unexpected end of file in "
   2204               "patch\n"
   2205           );
   2206       }
   2207       if (*buf == '\t' || *buf == '\n') {
   2208         ch = ' ';
   2209         s  = savestr(buf);
   2210       } else {
   2211         ch = *buf;
   2212         s  = savestr(buf + 1);
   2213       }
   2214       if (out_of_mem) {
   2215         while (--fillnew > p_ptrn_lines)
   2216           free(p_line[fillnew]);
   2217         p_end = fillold - 1;
   2218         return 0;
   2219       }
   2220       switch (ch) {
   2221         case '-':
   2222           if (fillold > p_ptrn_lines) {
   2223             free(s);
   2224             p_end = fillnew - 1;
   2225             malformed();
   2226           }
   2227           p_char[fillold]  = ch;
   2228           p_line[fillold]  = s;
   2229           p_len[fillold++] = strlen(s);
   2230           if (fillold > p_ptrn_lines) {
   2231             if (remove_special_line()) {
   2232               p_len[fillold - 1] -= 1;
   2233               s[p_len[fillold - 1]] = 0;
   2234             }
   2235           }
   2236           break;
   2237         case '=':
   2238           ch = ' ';
   2239           /* FALL THROUGH */
   2240         case ' ':
   2241           if (fillold > p_ptrn_lines) {
   2242             free(s);
   2243             while (--fillnew > p_ptrn_lines)
   2244               free(p_line[fillnew]);
   2245             p_end = fillold - 1;
   2246             malformed();
   2247           }
   2248           context++;
   2249           p_char[fillold]  = ch;
   2250           p_line[fillold]  = s;
   2251           p_len[fillold++] = strlen(s);
   2252           s                = savestr(s);
   2253           if (out_of_mem) {
   2254             while (--fillnew > p_ptrn_lines)
   2255               free(p_line[fillnew]);
   2256             p_end = fillold - 1;
   2257             return 0;
   2258           }
   2259           if (fillold > p_ptrn_lines) {
   2260             if (remove_special_line()) {
   2261               p_len[fillold - 1] -= 1;
   2262               s[p_len[fillold - 1]] = 0;
   2263             }
   2264           }
   2265           /* FALL THROUGH */
   2266         case '+':
   2267           if (fillnew > p_end) {
   2268             free(s);
   2269             while (--fillnew > p_ptrn_lines)
   2270               free(p_line[fillnew]);
   2271             p_end = fillold - 1;
   2272             malformed();
   2273           }
   2274           p_char[fillnew]  = ch;
   2275           p_line[fillnew]  = s;
   2276           p_len[fillnew++] = strlen(s);
   2277           if (fillold > p_ptrn_lines) {
   2278             if (remove_special_line()) {
   2279               p_len[fillnew - 1] -= 1;
   2280               s[p_len[fillnew - 1]] = 0;
   2281             }
   2282           }
   2283           break;
   2284         default:
   2285           p_end = fillnew;
   2286           malformed();
   2287       }
   2288       if (ch != ' ' && context > 0) {
   2289         if (context < p_context)
   2290           p_context = context;
   2291         context = -1000;
   2292       }
   2293     }
   2294   } else {
   2295     char    hunk_type;
   2296     int     i;
   2297     LINENUM min, max;
   2298 
   2299     line_beginning = ftell(pfp);
   2300     p_context      = 0;
   2301     ret            = pgetline(&buf, &bufsz, pfp);
   2302     p_input_line++;
   2303     if (ret == -1 || !isdigit((unsigned char)*buf)) {
   2304       next_intuit_at(line_beginning, p_input_line);
   2305       return 0;
   2306     }
   2307     s       = buf;
   2308     p_first = getskiplinenum(&s);
   2309     if (*s == ',') {
   2310       s++;
   2311       p_ptrn_lines = getskiplinenum(&s) - p_first + 1;
   2312     } else
   2313       p_ptrn_lines = (*s != 'a');
   2314     if (p_first >= LINENUM_MAX - p_ptrn_lines)
   2315       malformed();
   2316     hunk_type = *s++;
   2317     if (hunk_type == 'a')
   2318       p_first++;
   2319     min = getskiplinenum(&s);
   2320     if (*s == ',')
   2321       max = getlinenum(++s);
   2322     else
   2323       max = min;
   2324     if (min < 0 || min > max || max - min == LINENUM_MAX)
   2325       malformed();
   2326     if (hunk_type == 'd')
   2327       min++;
   2328     p_end        = p_ptrn_lines + p_repl_lines + 1;
   2329     p_newfirst   = min;
   2330     p_repl_lines = max - min + 1;
   2331     if (p_newfirst > LINENUM_MAX - p_repl_lines || p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
   2332       malformed();
   2333     p_end = p_ptrn_lines + p_repl_lines + 1;
   2334     if (p_end > MAXHUNKSIZE)
   2335       fatal("hunk too large at line %ld\n", p_input_line);
   2336     while (p_end >= hunkmax)
   2337       grow_hunkmax();
   2338     snprintf(buf, bufsz, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1);
   2339     p_line[0] = savestr(buf);
   2340     if (out_of_mem) {
   2341       p_end = -1;
   2342       return 0;
   2343     }
   2344     p_char[0] = '*';
   2345     for (i = 1; i <= p_ptrn_lines; i++) {
   2346       ret = pgetline(&buf, &bufsz, pfp);
   2347       p_input_line++;
   2348       if (ret == -1)
   2349         fatal(
   2350             "unexpected end of file in patch at line "
   2351             "%ld\n",
   2352             p_input_line
   2353         );
   2354       if (*buf != '<')
   2355         fatal("< expected at line %ld of patch\n", p_input_line);
   2356       p_line[i] = savestr(buf + 2);
   2357       if (out_of_mem) {
   2358         p_end = i - 1;
   2359         return 0;
   2360       }
   2361       p_len[i]  = strlen(p_line[i]);
   2362       p_char[i] = '-';
   2363     }
   2364     if (remove_special_line()) {
   2365       p_len[i - 1] -= 1;
   2366       (p_line[i - 1])[p_len[i - 1]] = 0;
   2367     }
   2368     if (hunk_type == 'c') {
   2369       ret = pgetline(&buf, &bufsz, pfp);
   2370       p_input_line++;
   2371       if (ret == -1)
   2372         fatal(
   2373             "unexpected end of file in patch at line "
   2374             "%ld\n",
   2375             p_input_line
   2376         );
   2377       if (*buf != '-')
   2378         fatal("--- expected at line %ld of patch\n", p_input_line);
   2379     }
   2380     snprintf(buf, bufsz, "--- %ld,%ld\n", min, max);
   2381     p_line[i] = savestr(buf);
   2382     if (out_of_mem) {
   2383       p_end = i - 1;
   2384       return 0;
   2385     }
   2386     p_char[i] = '=';
   2387     for (i++; i <= p_end; i++) {
   2388       ret = pgetline(&buf, &bufsz, pfp);
   2389       p_input_line++;
   2390       if (ret == -1)
   2391         fatal(
   2392             "unexpected end of file in patch at line "
   2393             "%ld\n",
   2394             p_input_line
   2395         );
   2396       if (*buf != '>')
   2397         fatal("> expected at line %ld of patch\n", p_input_line);
   2398       p_line[i] = savestr(buf + 2);
   2399       if (out_of_mem) {
   2400         p_end = i - 1;
   2401         return 0;
   2402       }
   2403       p_len[i]  = strlen(p_line[i]);
   2404       p_char[i] = '+';
   2405     }
   2406     if (remove_special_line()) {
   2407       p_len[i - 1] -= 1;
   2408       (p_line[i - 1])[p_len[i - 1]] = 0;
   2409     }
   2410   }
   2411   if (reverse) {
   2412     if (!pch_swap())
   2413       say("Not enough memory to swap next hunk!\n");
   2414   }
   2415   if (p_end + 1 < hunkmax)
   2416     p_char[p_end + 1] = '^';
   2417   return 1;
   2418 }
   2419 
   2420 int
   2421 pgetline(char **bf, size_t *sz, FILE *fp)
   2422 {
   2423   char *s;
   2424   int   indent = 0;
   2425   int   ret;
   2426 
   2427   ret = getline(bf, sz, fp);
   2428   if (p_indent && ret != -1) {
   2429     for (s = buf; indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X'); s++) {
   2430       if (*s == '\t')
   2431         indent += 8 - (indent % 7);
   2432       else
   2433         indent++;
   2434     }
   2435     if (buf != s && strlcpy(buf, s, bufsz) >= bufsz)
   2436       fatal("buffer too small in pgetline()\n");
   2437   }
   2438   return ret;
   2439 }
   2440 
   2441 int
   2442 pch_swap(void)
   2443 {
   2444   char   **tp_line;
   2445   ssize_t *tp_len;
   2446   char    *tp_char;
   2447   LINENUM  i;
   2448   LINENUM  n;
   2449   int      blankline = 0;
   2450   char    *s;
   2451 
   2452   i          = p_first;
   2453   p_first    = p_newfirst;
   2454   p_newfirst = i;
   2455 
   2456   tp_line = p_line;
   2457   tp_len  = p_len;
   2458   tp_char = p_char;
   2459   p_line  = NULL;
   2460   p_len   = NULL;
   2461   p_char  = NULL;
   2462   set_hunkmax();
   2463   if (p_line == NULL || p_len == NULL || p_char == NULL) {
   2464     free(p_line);
   2465     p_line = tp_line;
   2466     free(p_len);
   2467     p_len = tp_len;
   2468     free(p_char);
   2469     p_char = tp_char;
   2470     return 0;
   2471   }
   2472 
   2473   i = p_ptrn_lines + 1;
   2474   if (tp_char[i] == '\n') {
   2475     blankline = 1;
   2476     i++;
   2477   }
   2478   if (p_efake >= 0) {
   2479     if (p_efake <= i)
   2480       n = p_end - i + 1;
   2481     else
   2482       n = -i;
   2483     p_efake += n;
   2484     p_bfake += n;
   2485   }
   2486   for (n = 0; i <= p_end; i++, n++) {
   2487     p_line[n] = tp_line[i];
   2488     p_char[n] = tp_char[i];
   2489     if (p_char[n] == '+')
   2490       p_char[n] = '-';
   2491     p_len[n] = tp_len[i];
   2492   }
   2493   if (blankline) {
   2494     i         = p_ptrn_lines + 1;
   2495     p_line[n] = tp_line[i];
   2496     p_char[n] = tp_char[i];
   2497     p_len[n]  = tp_len[i];
   2498     n++;
   2499   }
   2500   if (p_char[0] != '=')
   2501     fatal("expected '=' found '%c'\n", p_char[0]);
   2502   p_char[0] = '*';
   2503   for (s = p_line[0]; *s; s++)
   2504     if (*s == '-')
   2505       *s = '*';
   2506 
   2507   if (p_char[0] != '*')
   2508     fatal("expected '*' found '%c'\n", p_char[0]);
   2509   tp_char[0] = '=';
   2510   for (s = tp_line[0]; *s; s++)
   2511     if (*s == '*')
   2512       *s = '-';
   2513   for (i = 0; n <= p_end; i++, n++) {
   2514     p_line[n] = tp_line[i];
   2515     p_char[n] = tp_char[i];
   2516     if (p_char[n] == '-')
   2517       p_char[n] = '+';
   2518     p_len[n] = tp_len[i];
   2519   }
   2520   if (i != p_ptrn_lines + 1)
   2521     fatal("expected %ld lines, got %ld\n", p_ptrn_lines + 1, i);
   2522 
   2523   i            = p_ptrn_lines;
   2524   p_ptrn_lines = p_repl_lines;
   2525   p_repl_lines = i;
   2526 
   2527   free(tp_line);
   2528   free(tp_len);
   2529   free(tp_char);
   2530   return 1;
   2531 }
   2532 
   2533 LINENUM
   2534 pch_first(void)
   2535 {
   2536   return p_first;
   2537 }
   2538 
   2539 LINENUM
   2540 pch_ptrn_lines(void)
   2541 {
   2542   return p_ptrn_lines;
   2543 }
   2544 
   2545 LINENUM
   2546 pch_newfirst(void)
   2547 {
   2548   return p_newfirst;
   2549 }
   2550 
   2551 LINENUM
   2552 pch_repl_lines(void)
   2553 {
   2554   return p_repl_lines;
   2555 }
   2556 
   2557 LINENUM
   2558 pch_end(void)
   2559 {
   2560   return p_end;
   2561 }
   2562 
   2563 LINENUM
   2564 pch_context(void)
   2565 {
   2566   return p_context;
   2567 }
   2568 
   2569 ssize_t
   2570 pch_line_len(LINENUM line)
   2571 {
   2572   return p_len[line];
   2573 }
   2574 
   2575 char
   2576 pch_char(LINENUM line)
   2577 {
   2578   return p_char[line];
   2579 }
   2580 
   2581 char *
   2582 pfetch(LINENUM line)
   2583 {
   2584   return p_line[line];
   2585 }
   2586 
   2587 LINENUM
   2588 pch_hunk_beg(void)
   2589 {
   2590   return p_hunk_beg;
   2591 }
   2592 
   2593 void
   2594 do_ed_script(void)
   2595 {
   2596   char *t;
   2597   long  beginning_of_this_line;
   2598   FILE *pipefp = NULL;
   2599   int   continuation;
   2600 
   2601   if (!skip_rest_of_patch) {
   2602     if (copy_file(filearg[0], TMPOUTNAME) < 0) {
   2603       unlink(TMPOUTNAME);
   2604       fatal("cant create temp file %s", TMPOUTNAME);
   2605     }
   2606     snprintf(buf, bufsz, "%s -S%s %s", _PATH_ED, verbose ? "" : "s", TMPOUTNAME);
   2607     pipefp = wpopen(buf, NULL, "w");
   2608   }
   2609   for (;;) {
   2610     beginning_of_this_line = ftell(pfp);
   2611     if (pgetline(&buf, &bufsz, pfp) == -1) {
   2612       next_intuit_at(beginning_of_this_line, p_input_line);
   2613       break;
   2614     }
   2615     p_input_line++;
   2616     for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
   2617       ;
   2618     if (isdigit((unsigned char)*buf)
   2619         && (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
   2620       if (pipefp != NULL)
   2621         fprintf(pipefp, "%s", buf);
   2622       if (*t == 's') {
   2623         for (;;) {
   2624           continuation = 0;
   2625           t            = strchr(buf, '\0') - 1;
   2626           while (--t >= buf && *t == '\\')
   2627             continuation = !continuation;
   2628           if (!continuation || pgetline(&buf, &bufsz, pfp) == -1)
   2629             break;
   2630           if (pipefp != NULL)
   2631             fprintf(pipefp, "%s", buf);
   2632         }
   2633       } else if (*t != 'd') {
   2634         while (pgetline(&buf, &bufsz, pfp) != -1) {
   2635           p_input_line++;
   2636           if (pipefp != NULL)
   2637             fprintf(pipefp, "%s", buf);
   2638           if (strEQ(buf, ".\n"))
   2639             break;
   2640         }
   2641       }
   2642     } else {
   2643       next_intuit_at(beginning_of_this_line, p_input_line);
   2644       break;
   2645     }
   2646   }
   2647   if (pipefp == NULL)
   2648     return;
   2649   fprintf(pipefp, "w\n");
   2650   fprintf(pipefp, "q\n");
   2651   fflush(pipefp);
   2652   wpclose(pipefp);
   2653   ignore_signals();
   2654   if (!check_only) {
   2655     if (move_file(TMPOUTNAME, outname) < 0) {
   2656       toutkeep = 1;
   2657       chmod(TMPOUTNAME, filemode);
   2658     } else
   2659       chmod(outname, filemode);
   2660   }
   2661   set_signals(1);
   2662 }
   2663 
   2664 static char *
   2665 posix_name(const struct FileName *names, int assume_exists)
   2666 {
   2667   char *path = NULL;
   2668   int   i;
   2669 
   2670   for (i = 0; i < MAX_FILE; i++) {
   2671     if (names[i].path != NULL && names[i].exists) {
   2672       path = names[i].path;
   2673       break;
   2674     }
   2675   }
   2676   if (path == NULL && !assume_exists) {
   2677     for (i = 0; i < MAX_FILE; i++) {
   2678       if (names[i].path != NULL && (path = checked_in(names[i].path)) != NULL)
   2679         break;
   2680     }
   2681     if (path == NULL && ok_to_create_file && names[NEW_FILE].path != NULL)
   2682       path = names[NEW_FILE].path;
   2683   }
   2684   return path ? savestr(path) : NULL;
   2685 }
   2686 
   2687 static char *
   2688 best_name(const struct FileName *names, int assume_exists)
   2689 {
   2690   size_t min_components, min_baselen, min_len, tmp;
   2691   char  *best = NULL;
   2692   int    i;
   2693 
   2694   min_components = min_baselen = min_len = SIZE_MAX;
   2695   for (i = INDEX_FILE; i >= OLD_FILE; i--) {
   2696     if (names[i].path == NULL || (!names[i].exists && !assume_exists))
   2697       continue;
   2698     if ((tmp = num_components(names[i].path)) > min_components)
   2699       continue;
   2700     min_components = tmp;
   2701     if ((tmp = strlen(basename(names[i].path))) > min_baselen)
   2702       continue;
   2703     min_baselen = tmp;
   2704     if ((tmp = strlen(names[i].path)) > min_len)
   2705       continue;
   2706     min_len = tmp;
   2707     best    = names[i].path;
   2708   }
   2709   if (best == NULL) {
   2710     min_components = min_baselen = min_len = SIZE_MAX;
   2711     for (i = INDEX_FILE; i >= OLD_FILE; i--) {
   2712       if (names[i].path == NULL || checked_in(names[i].path) == NULL)
   2713         continue;
   2714       if ((tmp = num_components(names[i].path)) > min_components)
   2715         continue;
   2716       min_components = tmp;
   2717       if ((tmp = strlen(basename(names[i].path))) > min_baselen)
   2718         continue;
   2719       min_baselen = tmp;
   2720       if ((tmp = strlen(names[i].path)) > min_len)
   2721         continue;
   2722       min_len = tmp;
   2723       best    = names[i].path;
   2724     }
   2725     if (best == NULL && ok_to_create_file && names[NEW_FILE].path != NULL)
   2726       best = names[NEW_FILE].path;
   2727   }
   2728   return best ? savestr(best) : NULL;
   2729 }
   2730 
   2731 static size_t
   2732 num_components(const char *path)
   2733 {
   2734   size_t      n;
   2735   const char *cp;
   2736 
   2737   for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
   2738     while (*cp == '/')
   2739       cp++;
   2740   }
   2741   return n;
   2742 }
   2743 
   2744 LINENUM
   2745 strtolinenum(char *nptr, char **endptr)
   2746 {
   2747   LINENUM     rv;
   2748   char        c;
   2749   char       *p;
   2750   const char *errstr;
   2751 
   2752   for (p = nptr; isdigit((unsigned char)*p); p++)
   2753     ;
   2754 
   2755   if (p == nptr)
   2756     malformed();
   2757 
   2758   c  = *p;
   2759   *p = '\0';
   2760 
   2761   rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
   2762   if (errstr != NULL)
   2763     fatal("invalid line number at line %ld: `%s' is %s\n", p_input_line, nptr, errstr);
   2764 
   2765   *p = c;
   2766   if (endptr)
   2767     *endptr = p;
   2768 
   2769   return rv;
   2770 }
   2771 
   2772 int
   2773 move_file(const char *from, const char *to)
   2774 {
   2775   int     fromfd;
   2776   ssize_t i;
   2777 
   2778   if (strEQ(to, "-")) {
   2779     fromfd = open(from, O_RDONLY);
   2780     if (fromfd < 0)
   2781       pfatal("internal error, cant reopen %s", from);
   2782     while ((i = read(fromfd, buf, bufsz)) > 0) {
   2783       if (write(STDOUT_FILENO, buf, i) != i)
   2784         pfatal("write failed");
   2785     }
   2786     close(fromfd);
   2787     return 0;
   2788   }
   2789   if (backup_file(to) < 0) {
   2790     say("Cant backup %s, output is in %s: %s\n", to, from, strerror(errno));
   2791     return -1;
   2792   }
   2793   if (rename(from, to) < 0) {
   2794     if (errno != EXDEV || copy_file(from, to) < 0) {
   2795       say("Cant create %s, output is in %s: %s\n", to, from, strerror(errno));
   2796       return -1;
   2797     }
   2798   }
   2799   return 0;
   2800 }
   2801 
   2802 int
   2803 backup_file(const char *orig)
   2804 {
   2805   struct stat filestat;
   2806   char        bakname[PATH_MAX], *s, *simplename;
   2807   dev_t       orig_device;
   2808   ino_t       orig_inode;
   2809 
   2810   if (backup_type == BACKUP_NONE || stat(orig, &filestat) != 0)
   2811     return 0;
   2812   if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) {
   2813     unlink(orig);
   2814     return 0;
   2815   }
   2816   orig_device = filestat.st_dev;
   2817   orig_inode  = filestat.st_ino;
   2818 
   2819   if (origprae) {
   2820     if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname)
   2821         || strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname))
   2822       fatal("filename too long\n");
   2823   } else {
   2824     if ((s = find_backup_file_name(orig)) == NULL)
   2825       fatal("out of memory\n");
   2826     if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname))
   2827       fatal("filename too long\n");
   2828     free(s);
   2829   }
   2830 
   2831   if ((simplename = strrchr(bakname, '/')) != NULL)
   2832     simplename = simplename + 1;
   2833   else
   2834     simplename = bakname;
   2835 
   2836   while (stat(bakname, &filestat) == 0 && orig_device == filestat.st_dev
   2837          && orig_inode == filestat.st_ino) {
   2838     for (s = simplename; *s && !islower((unsigned char)*s); s++)
   2839       ;
   2840     if (*s)
   2841       *s = toupper((unsigned char)*s);
   2842     else
   2843       memmove(simplename, simplename + 1, strlen(simplename + 1) + 1);
   2844   }
   2845   if (rename(orig, bakname) < 0) {
   2846     if (errno != EXDEV || copy_file(orig, bakname) < 0)
   2847       return -1;
   2848   }
   2849   return 0;
   2850 }
   2851 
   2852 int
   2853 copy_file(const char *from, const char *to)
   2854 {
   2855   int     tofd, fromfd;
   2856   ssize_t i;
   2857 
   2858   tofd = open(to, O_CREAT | O_TRUNC | O_WRONLY, 0666);
   2859   if (tofd < 0)
   2860     return -1;
   2861   fromfd = open(from, O_RDONLY, 0);
   2862   if (fromfd < 0)
   2863     pfatal("internal error, cant reopen %s", from);
   2864   while ((i = read(fromfd, buf, bufsz)) > 0) {
   2865     if (write(tofd, buf, i) != i)
   2866       pfatal("write to %s failed", to);
   2867   }
   2868   close(fromfd);
   2869   close(tofd);
   2870   return 0;
   2871 }
   2872 
   2873 char *
   2874 savestr(const char *s)
   2875 {
   2876   char *rv;
   2877 
   2878   if (!s)
   2879     s = "Oops";
   2880   rv = strdup(s);
   2881   if (rv == NULL) {
   2882     if (using_plan_a)
   2883       out_of_mem = 1;
   2884     else
   2885       fatal("out of memory\n");
   2886   }
   2887   return rv;
   2888 }
   2889 
   2890 void
   2891 say(const char *fmt, ...)
   2892 {
   2893   va_list ap;
   2894 
   2895   va_start(ap, fmt);
   2896   vfprintf(stderr, fmt, ap);
   2897   va_end(ap);
   2898   fflush(stderr);
   2899 }
   2900 
   2901 __dead void
   2902 fatal(const char *fmt, ...)
   2903 {
   2904   va_list ap;
   2905 
   2906   va_start(ap, fmt);
   2907   fprintf(stderr, "patch: **** ");
   2908   vfprintf(stderr, fmt, ap);
   2909   va_end(ap);
   2910   my_exit(2);
   2911 }
   2912 
   2913 __dead void
   2914 pfatal(const char *fmt, ...)
   2915 {
   2916   va_list ap;
   2917   int     errnum = errno;
   2918 
   2919   fprintf(stderr, "patch: **** ");
   2920   va_start(ap, fmt);
   2921   vfprintf(stderr, fmt, ap);
   2922   va_end(ap);
   2923   fprintf(stderr, ": %s\n", strerror(errnum));
   2924   my_exit(2);
   2925 }
   2926 
   2927 void
   2928 ask(const char *fmt, ...)
   2929 {
   2930   va_list    ap;
   2931   ssize_t    nr    = 0;
   2932   static int ttyfd = -1;
   2933 
   2934   va_start(ap, fmt);
   2935   vfprintf(stdout, fmt, ap);
   2936   va_end(ap);
   2937   fflush(stdout);
   2938   if (ttyfd < 0)
   2939     ttyfd = open(ARUU_PATH_DEVTTY, O_RDONLY);
   2940   if (ttyfd >= 0) {
   2941     if ((nr = read(ttyfd, buf, bufsz)) > 0 && buf[nr - 1] == '\n')
   2942       buf[nr - 1] = '\0';
   2943   }
   2944   if (ttyfd < 0 || nr <= 0) {
   2945     putchar('\n');
   2946     buf[0] = '\0';
   2947   }
   2948 }
   2949 
   2950 void
   2951 set_signals(int reset)
   2952 {
   2953   static sig_t hupval, intval;
   2954 
   2955   if (!reset) {
   2956     hupval = signal(SIGHUP, SIG_IGN);
   2957     if (hupval != SIG_IGN)
   2958       hupval = (sig_t)my_exit;
   2959     intval = signal(SIGINT, SIG_IGN);
   2960     if (intval != SIG_IGN)
   2961       intval = (sig_t)my_exit;
   2962   }
   2963   signal(SIGHUP, hupval);
   2964   signal(SIGINT, intval);
   2965 }
   2966 
   2967 void
   2968 ignore_signals(void)
   2969 {
   2970   signal(SIGHUP, SIG_IGN);
   2971   signal(SIGINT, SIG_IGN);
   2972 }
   2973 
   2974 void
   2975 makedirs(const char *filename, int striplast)
   2976 {
   2977   char *tmpbuf;
   2978 
   2979   if ((tmpbuf = strdup(filename)) == NULL)
   2980     fatal("out of memory\n");
   2981 
   2982   if (striplast) {
   2983     char *s = strrchr(tmpbuf, '/');
   2984     if (s == NULL) {
   2985       free(tmpbuf);
   2986       return;
   2987     }
   2988     *s = '\0';
   2989   }
   2990   if (mkpath(tmpbuf) != 0)
   2991     pfatal("creation of %s failed", tmpbuf);
   2992   free(tmpbuf);
   2993 }
   2994 
   2995 char *
   2996 fetchname(const char *at, int *exists, int strip_leading)
   2997 {
   2998   char       *fullname, *name, *t;
   2999   int         sleading, tab;
   3000   struct stat filestat;
   3001 
   3002   if (at == NULL || *at == '\0')
   3003     return NULL;
   3004   while (isspace((unsigned char)*at))
   3005     at++;
   3006   if (strnEQ(at, ARUU_PATH_DEVNULL, sizeof(ARUU_PATH_DEVNULL) - 1))
   3007     return NULL;
   3008   name = fullname = t = savestr(at);
   3009   tab                 = strchr(t, '\t') != NULL;
   3010   for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') || !isspace((unsigned char)*t));
   3011        t++) {
   3012     if (t[0] == '/' && t[1] != '/' && t[1] != '\0') {
   3013       if (--sleading >= 0)
   3014         name = t + 1;
   3015     }
   3016   }
   3017   *t = '\0';
   3018 
   3019   if (strip_leading == 957 && name != fullname && *fullname != '/') {
   3020     name[-1] = '\0';
   3021     if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
   3022       name[-1] = '/';
   3023       name     = fullname;
   3024     }
   3025   }
   3026   name = savestr(name);
   3027   free(fullname);
   3028 
   3029   *exists = stat(name, &filestat) == 0;
   3030   return name;
   3031 }
   3032 
   3033 char *
   3034 checked_in(char *file)
   3035 {
   3036   char       *filebase, *filedir, tmpbuf[PATH_MAX];
   3037   struct stat filestat;
   3038 
   3039   filebase = basename(file);
   3040   filedir  = dirname(file);
   3041 
   3042 #define try(f, a1, a2, a3)                                                                         \
   3043   (snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0)
   3044 
   3045   if (try ("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX)
   3046       || try ("%s/RCS/%s%s", filedir, filebase, "") || try ("%s/%s%s", filedir, filebase, RCSSUFFIX)
   3047       || try ("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase)
   3048       || try ("%s/%s%s", filedir, SCCSPREFIX, filebase))
   3049     return file;
   3050 
   3051   return NULL;
   3052 }
   3053 
   3054 __dead void
   3055 version(void)
   3056 {
   3057   printf("Patch version 2.0-12u9-NetBSD\n");
   3058   my_exit(EXIT_SUCCESS);
   3059 }
   3060 
   3061 __dead void
   3062 my_exit(int status)
   3063 {
   3064   unlink(TMPINNAME);
   3065   if (!toutkeep)
   3066     unlink(TMPOUTNAME);
   3067   if (!trejkeep)
   3068     unlink(TMPREJNAME);
   3069   unlink(TMPPATNAME);
   3070   exit(status);
   3071 }
   3072 
   3073 static void *
   3074 pch_realloc(void *ptr, size_t number, size_t size)
   3075 {
   3076   if (number > SIZE_MAX / size) {
   3077     errno = EOVERFLOW;
   3078     return NULL;
   3079   }
   3080   return realloc(ptr, number * size);
   3081 }
   3082 
   3083 int
   3084 mkpath(char *path)
   3085 {
   3086   struct stat sb;
   3087   char       *slash;
   3088   int         done = 0;
   3089 
   3090   slash = path;
   3091   while (!done) {
   3092     slash += strspn(slash, "/");
   3093     slash += strcspn(slash, "/");
   3094     done   = (*slash == '\0');
   3095     *slash = '\0';
   3096     if (stat(path, &sb)) {
   3097       if (errno != ENOENT || (mkdir(path, 0777) && errno != EEXIST)) {
   3098         weprintf("%s", path);
   3099         return -1;
   3100       }
   3101     } else if (!S_ISDIR(sb.st_mode)) {
   3102       weprintf("%s: %s", path, strerror(ENOTDIR));
   3103       return -1;
   3104     }
   3105     *slash = '/';
   3106   }
   3107   return 0;
   3108 }
   3109 
   3110 char *
   3111 find_backup_file_name(const char *file)
   3112 {
   3113   char *dir, *base_versions, *tmp_file;
   3114   int   highest_backup;
   3115 
   3116   if (backup_type == BACKUP_SIMPLE)
   3117     return patch_concat(file, simple_backup_suffix);
   3118   tmp_file = strdup(file);
   3119   if (tmp_file == NULL)
   3120     return NULL;
   3121   base_versions = patch_concat(basename(tmp_file), ".~");
   3122   free(tmp_file);
   3123   if (base_versions == NULL)
   3124     return NULL;
   3125   tmp_file = strdup(file);
   3126   if (tmp_file == NULL) {
   3127     free(base_versions);
   3128     return NULL;
   3129   }
   3130   dir = dirname(tmp_file);
   3131   if (dir == NULL) {
   3132     free(base_versions);
   3133     free(tmp_file);
   3134     return NULL;
   3135   }
   3136   highest_backup = max_backup_version(base_versions, dir);
   3137   free(base_versions);
   3138   free(tmp_file);
   3139   if (backup_type == BACKUP_NUMBERED_EXISTING && highest_backup == 0)
   3140     return patch_concat(file, simple_backup_suffix);
   3141   return make_version_name(file, highest_backup + 1);
   3142 }
   3143 
   3144 static int
   3145 max_backup_version(const char *file, const char *dir)
   3146 {
   3147   DIR           *dirp;
   3148   struct dirent *dp;
   3149   int            highest_version, this_version;
   3150   size_t         file_name_length;
   3151 
   3152   dirp = opendir(dir);
   3153   if (dirp == NULL)
   3154     return 0;
   3155 
   3156   highest_version  = 0;
   3157   file_name_length = strlen(file);
   3158   while ((dp = readdir(dirp)) != NULL) {
   3159     if (strlen(dp->d_name) <= file_name_length)
   3160       continue;
   3161     this_version = version_number(file, dp->d_name, file_name_length);
   3162     if (this_version > highest_version)
   3163       highest_version = this_version;
   3164   }
   3165   closedir(dirp);
   3166   return highest_version;
   3167 }
   3168 
   3169 static char *
   3170 make_version_name(const char *file, int version_num)
   3171 {
   3172   char *backup_name;
   3173 
   3174   if (asprintf(&backup_name, "%s.~%d~", file, version_num) == -1)
   3175     return NULL;
   3176   return backup_name;
   3177 }
   3178 
   3179 static int
   3180 version_number(const char *base, const char *backup, size_t base_length)
   3181 {
   3182   int         version_num;
   3183   const char *p;
   3184 
   3185   version_num = 0;
   3186   if (!strncmp(base, backup, base_length) && ISDIGIT(backup[base_length])) {
   3187     for (p = &backup[base_length]; ISDIGIT(*p); ++p)
   3188       version_num = version_num * 10 + *p - '0';
   3189     if (p[0] != '~' || p[1])
   3190       version_num = 0;
   3191   }
   3192   return version_num;
   3193 }
   3194 
   3195 static char *
   3196 patch_concat(const char *str1, const char *str2)
   3197 {
   3198   char *newstr;
   3199 
   3200   if (asprintf(&newstr, "%s%s", str1, str2) == -1)
   3201     return NULL;
   3202   return newstr;
   3203 }
   3204 
   3205 static int
   3206 argmatch(const char *arg, const char **optlist)
   3207 {
   3208   int    i;
   3209   size_t arglen;
   3210   int    matchind  = -1;
   3211   int    ambiguous = 0;
   3212 
   3213   arglen = strlen(arg);
   3214   for (i = 0; optlist[i]; i++) {
   3215     if (!strncmp(optlist[i], arg, arglen)) {
   3216       if (strlen(optlist[i]) == arglen)
   3217         return i;
   3218       else if (matchind == -1)
   3219         matchind = i;
   3220       else
   3221         ambiguous = 1;
   3222     }
   3223   }
   3224   if (ambiguous)
   3225     return -2;
   3226   else
   3227     return matchind;
   3228 }
   3229 
   3230 static void
   3231 invalid_arg(const char *kind, const char *value, int problem)
   3232 {
   3233   fprintf(stderr, "patch: ");
   3234   if (problem == -1)
   3235     fprintf(stderr, "invalid");
   3236   else
   3237     fprintf(stderr, "ambiguous");
   3238   fprintf(stderr, " %s `%s'\n", kind, value);
   3239 }
   3240 
   3241 enum BackupType
   3242 get_version(const char *version_str)
   3243 {
   3244   int i;
   3245 
   3246   if (version_str == NULL || *version_str == '\0')
   3247     return BACKUP_NUMBERED_EXISTING;
   3248   i = argmatch(version_str, backup_args);
   3249   if (i >= 0)
   3250     return backup_types[i];
   3251   invalid_arg("version control type", version_str, i);
   3252   exit(2);
   3253 }