[BACK]Return to patch.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / patch

Annotation of src/usr.bin/patch/patch.c, Revision 1.32

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