[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.26

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