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

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

1.32    ! millert     1: /*     $OpenBSD: pch.c,v 1.31 2003/09/28 07:55:19 otto Exp $   */
1.30      otto        2:
                      3: /*
                      4:  * patch - a program to apply diffs to original files
                      5:  *
                      6:  * Copyright 1986, Larry Wall
                      7:  *
                      8:  * Redistribution and use in source and binary forms, with or without
                      9:  * modification, are permitted provided that the following condition is met:
                     10:  * 1. Redistributions of source code must retain the above copyright notice,
                     11:  * this condition and the following disclaimer.
                     12:  *
                     13:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
                     14:  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
                     15:  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
                     16:  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
                     17:  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     18:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
                     19:  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
                     20:  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     21:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     22:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     23:  * SUCH DAMAGE.
                     24:  *
                     25:  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
                     26:  * behaviour
                     27:  */
1.2       niklas     28:
1.1       deraadt    29: #ifndef lint
1.32    ! millert    30: static const char rcsid[] = "$OpenBSD: pch.c,v 1.31 2003/09/28 07:55:19 otto Exp $";
1.1       deraadt    31: #endif /* not lint */
                     32:
1.21      otto       33: #include <sys/types.h>
                     34: #include <sys/stat.h>
                     35:
                     36: #include <ctype.h>
1.32    ! millert    37: #include <libgen.h>
        !            38: #include <limits.h>
1.25      otto       39: #include <stdio.h>
1.21      otto       40: #include <stdlib.h>
                     41: #include <string.h>
                     42: #include <unistd.h>
                     43:
1.1       deraadt    44: #include "common.h"
                     45: #include "util.h"
                     46: #include "pch.h"
1.27      millert    47: #include "pathnames.h"
1.1       deraadt    48:
                     49: /* Patch (diff listing) abstract type. */
                     50:
1.17      deraadt    51: static long    p_filesize;     /* size of the patch file */
                     52: static LINENUM p_first;        /* 1st line number */
                     53: static LINENUM p_newfirst;     /* 1st line number of replacement */
                     54: static LINENUM p_ptrn_lines;   /* # lines in pattern */
                     55: static LINENUM p_repl_lines;   /* # lines in replacement text */
                     56: static LINENUM p_end = -1;     /* last line in hunk */
                     57: static LINENUM p_max;          /* max allowed value of p_end */
                     58: static LINENUM p_context = 3;  /* # of context lines */
                     59: static LINENUM p_input_line = 0;       /* current line # from patch file */
1.25      otto       60: static char    **p_line = NULL;/* the text of the hunk */
1.21      otto       61: static short   *p_len = NULL;  /* length of each line */
1.25      otto       62: static char    *p_char = NULL; /* +, -, and ! */
1.17      deraadt    63: static int     hunkmax = INITHUNKMAX;  /* size of above arrays to begin with */
                     64: static int     p_indent;       /* indent to patch */
                     65: static LINENUM p_base;         /* where to intuit this time */
                     66: static LINENUM p_bline;        /* line # of p_base */
                     67: static LINENUM p_start;        /* where intuit found a patch */
                     68: static LINENUM p_sline;        /* and the line number for it */
                     69: static LINENUM p_hunk_beg;     /* line number of current hunk */
                     70: static LINENUM p_efake = -1;   /* end of faked up lines--don't free */
                     71: static LINENUM p_bfake = -1;   /* beg of faked up lines */
1.25      otto       72: static FILE    *pfp = NULL;    /* patch file pointer */
                     73: static char    *bestguess = NULL;      /* guess at correct filename */
1.1       deraadt    74:
1.21      otto       75: static void    grow_hunkmax(void);
                     76: static int     intuit_diff_type(void);
1.25      otto       77: static void    next_intuit_at(LINENUM, LINENUM);
                     78: static void    skip_to(LINENUM, LINENUM);
1.23      deraadt    79: static char    *pgets(char *, int, FILE *);
1.32    ! millert    80: static char    *best_name(const struct file_name *, bool);
        !            81: static char    *posix_name(const struct file_name *, bool);
        !            82: static size_t  num_components(const char *);
1.25      otto       83:
1.17      deraadt    84: /*
                     85:  * Prepare to look for the next patch in the patch file.
                     86:  */
1.1       deraadt    87: void
1.17      deraadt    88: re_patch(void)
1.1       deraadt    89: {
1.25      otto       90:        p_first = 0;
                     91:        p_newfirst = 0;
                     92:        p_ptrn_lines = 0;
                     93:        p_repl_lines = 0;
1.17      deraadt    94:        p_end = (LINENUM) - 1;
1.25      otto       95:        p_max = 0;
1.17      deraadt    96:        p_indent = 0;
1.1       deraadt    97: }
                     98:
1.17      deraadt    99: /*
                    100:  * Open the patch file at the beginning of time.
                    101:  */
1.1       deraadt   102: void
1.25      otto      103: open_patch_file(const char *filename)
1.1       deraadt   104: {
1.25      otto      105:        struct stat filestat;
                    106:
                    107:        if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
1.17      deraadt   108:                pfp = fopen(TMPPATNAME, "w");
1.21      otto      109:                if (pfp == NULL)
1.17      deraadt   110:                        pfatal("can't create %s", TMPPATNAME);
1.21      otto      111:                while (fgets(buf, sizeof buf, stdin) != NULL)
1.17      deraadt   112:                        fputs(buf, pfp);
                    113:                fclose(pfp);
                    114:                filename = TMPPATNAME;
                    115:        }
                    116:        pfp = fopen(filename, "r");
1.21      otto      117:        if (pfp == NULL)
1.17      deraadt   118:                pfatal("patch file %s not found", filename);
                    119:        fstat(fileno(pfp), &filestat);
                    120:        p_filesize = filestat.st_size;
                    121:        next_intuit_at(0L, 1L); /* start at the beginning */
                    122:        set_hunkmax();
1.1       deraadt   123: }
                    124:
1.17      deraadt   125: /*
                    126:  * Make sure our dynamically realloced tables are malloced to begin with.
                    127:  */
1.1       deraadt   128: void
1.17      deraadt   129: set_hunkmax(void)
1.1       deraadt   130: {
1.21      otto      131:        if (p_line == NULL)
                    132:                p_line = malloc((size_t) hunkmax * sizeof(char *));
                    133:        if (p_len == NULL)
                    134:                p_len = malloc((size_t) hunkmax * sizeof(short));
                    135:        if (p_char == NULL)
                    136:                p_char = malloc((size_t) hunkmax * sizeof(char));
1.1       deraadt   137: }
                    138:
1.17      deraadt   139: /*
                    140:  * Enlarge the arrays containing the current hunk of patch.
                    141:  */
1.21      otto      142: static void
1.17      deraadt   143: grow_hunkmax(void)
1.1       deraadt   144: {
1.31      otto      145:        int             new_hunkmax;
                    146:        char            **new_p_line;
                    147:        short           *new_p_len;
                    148:        char            *new_p_char;
                    149:
                    150:        new_hunkmax = hunkmax * 2;
1.17      deraadt   151:
1.28      otto      152:        if (p_line == NULL || p_len == NULL || p_char == NULL)
                    153:                fatal("Internal memory allocation error\n");
1.21      otto      154:
1.31      otto      155:        new_p_line = realloc(p_line, new_hunkmax * sizeof(char *));
                    156:        if (new_p_line == NULL)
                    157:                free(p_line);
                    158:
                    159:        new_p_len = realloc(p_len, new_hunkmax * sizeof(short));
                    160:        if (new_p_len == NULL)
                    161:                free(p_len);
                    162:
                    163:        new_p_char = realloc(p_char, new_hunkmax * sizeof(char));
                    164:        if (new_p_char == NULL)
                    165:                free(p_char);
                    166:
                    167:        p_char = new_p_char;
                    168:        p_len = new_p_len;
                    169:        p_line = new_p_line;
1.21      otto      170:
1.31      otto      171:        if (p_line != NULL && p_len != NULL && p_char != NULL) {
                    172:                hunkmax = new_hunkmax;
1.17      deraadt   173:                return;
1.31      otto      174:        }
                    175:
1.17      deraadt   176:        if (!using_plan_a)
                    177:                fatal("out of memory\n");
1.28      otto      178:        out_of_mem = true;      /* whatever is null will be allocated again */
                    179:                                /* from within plan_a(), of all places */
1.1       deraadt   180: }
                    181:
                    182: /* True if the remainder of the patch file contains a diff of some sort. */
                    183:
                    184: bool
1.17      deraadt   185: there_is_another_patch(void)
1.1       deraadt   186: {
1.32    ! millert   187:        bool exists = false;
        !           188:
1.17      deraadt   189:        if (p_base != 0L && p_base >= p_filesize) {
                    190:                if (verbose)
                    191:                        say("done\n");
1.28      otto      192:                return false;
1.17      deraadt   193:        }
1.1       deraadt   194:        if (verbose)
1.17      deraadt   195:                say("Hmm...");
                    196:        diff_type = intuit_diff_type();
                    197:        if (!diff_type) {
                    198:                if (p_base != 0L) {
                    199:                        if (verbose)
                    200:                                say("  Ignoring the trailing garbage.\ndone\n");
                    201:                } else
                    202:                        say("  I can't seem to find a patch in there anywhere.\n");
1.28      otto      203:                return false;
1.1       deraadt   204:        }
1.17      deraadt   205:        if (verbose)
                    206:                say("  %sooks like %s to me...\n",
                    207:                    (p_base == 0L ? "L" : "The next patch l"),
                    208:                    diff_type == UNI_DIFF ? "a unified diff" :
                    209:                    diff_type == CONTEXT_DIFF ? "a context diff" :
                    210:                diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
                    211:                    diff_type == NORMAL_DIFF ? "a normal diff" :
                    212:                    "an ed script");
                    213:        if (p_indent && verbose)
                    214:                say("(Patch is indented %d space%s.)\n", p_indent,
                    215:                    p_indent == 1 ? "" : "s");
                    216:        skip_to(p_start, p_sline);
1.21      otto      217:        while (filearg[0] == NULL) {
1.17      deraadt   218:                if (force || batch) {
                    219:                        say("No file to patch.  Skipping...\n");
                    220:                        filearg[0] = savestr(bestguess);
1.28      otto      221:                        skip_rest_of_patch = true;
                    222:                        return true;
1.17      deraadt   223:                }
                    224:                ask("File to patch: ");
                    225:                if (*buf != '\n') {
1.25      otto      226:                        free(bestguess);
1.17      deraadt   227:                        bestguess = savestr(buf);
1.32    ! millert   228:                        filearg[0] = fetchname(buf, &exists, 0);
1.17      deraadt   229:                }
1.32    ! millert   230:                if (!exists) {
        !           231:                        free(filearg[0]);
1.17      deraadt   232:                        ask("No file found--skip this patch? [n] ");
                    233:                        if (*buf != 'y')
                    234:                                continue;
                    235:                        if (verbose)
                    236:                                say("Skipping patch...\n");
1.32    ! millert   237:                        filearg[0] = fetchname(bestguess, &exists, 0);
1.28      otto      238:                        skip_rest_of_patch = true;
                    239:                        return true;
1.17      deraadt   240:                }
1.1       deraadt   241:        }
1.28      otto      242:        return true;
1.1       deraadt   243: }
                    244:
                    245: /* Determine what kind of diff is in the remaining part of the patch file. */
                    246:
1.21      otto      247: static int
1.17      deraadt   248: intuit_diff_type(void)
1.1       deraadt   249: {
1.17      deraadt   250:        long    this_line = 0, previous_line;
1.28      otto      251:        long    first_command_line = -1;
                    252:        LINENUM fcl_line = -1;
                    253:        bool    last_line_was_command = false, this_is_a_command = false;
                    254:        bool    stars_last_line = false, stars_this_line = false;
1.17      deraadt   255:        char    *s, *t;
                    256:        int     indent, retval;
1.32    ! millert   257:        struct file_name names[MAX_FILE];
1.17      deraadt   258:
1.32    ! millert   259:        memset(names, 0, sizeof(names));
1.28      otto      260:        ok_to_create_file = false;
1.21      otto      261:        fseek(pfp, p_base, SEEK_SET);
1.17      deraadt   262:        p_input_line = p_bline - 1;
                    263:        for (;;) {
                    264:                previous_line = this_line;
                    265:                last_line_was_command = this_is_a_command;
                    266:                stars_last_line = stars_this_line;
                    267:                this_line = ftell(pfp);
                    268:                indent = 0;
                    269:                p_input_line++;
1.21      otto      270:                if (fgets(buf, sizeof buf, pfp) == NULL) {
1.17      deraadt   271:                        if (first_command_line >= 0L) {
                    272:                                /* nothing but deletes!? */
                    273:                                p_start = first_command_line;
                    274:                                p_sline = fcl_line;
                    275:                                retval = ED_DIFF;
                    276:                                goto scan_exit;
                    277:                        } else {
                    278:                                p_start = this_line;
                    279:                                p_sline = p_input_line;
                    280:                                retval = 0;
                    281:                                goto scan_exit;
                    282:                        }
                    283:                }
                    284:                for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
                    285:                        if (*s == '\t')
                    286:                                indent += 8 - (indent % 8);
                    287:                        else
                    288:                                indent++;
                    289:                }
                    290:                for (t = s; isdigit(*t) || *t == ','; t++)
                    291:                        ;
                    292:                this_is_a_command = (isdigit(*s) &&
                    293:                    (*t == 'd' || *t == 'c' || *t == 'a'));
                    294:                if (first_command_line < 0L && this_is_a_command) {
                    295:                        first_command_line = this_line;
                    296:                        fcl_line = p_input_line;
                    297:                        p_indent = indent;      /* assume this for now */
                    298:                }
                    299:                if (!stars_last_line && strnEQ(s, "*** ", 4))
1.32    ! millert   300:                        names[OLD_FILE].path = fetchname(s + 4,
        !           301:                            &names[OLD_FILE].exists, strippath);
1.17      deraadt   302:                else if (strnEQ(s, "--- ", 4))
1.32    ! millert   303:                        names[NEW_FILE].path = fetchname(s + 4,
        !           304:                            &names[NEW_FILE].exists, strippath);
1.17      deraadt   305:                else if (strnEQ(s, "+++ ", 4))
1.32    ! millert   306:                        /* pretend it is the old name */
        !           307:                        names[OLD_FILE].path = fetchname(s + 4,
        !           308:                            &names[OLD_FILE].exists, strippath);
1.17      deraadt   309:                else if (strnEQ(s, "Index:", 6))
1.32    ! millert   310:                        names[INDEX_FILE].path = fetchname(s + 6,
        !           311:                            &names[INDEX_FILE].exists, strippath);
1.17      deraadt   312:                else if (strnEQ(s, "Prereq:", 7)) {
1.18      deraadt   313:                        for (t = s + 7; isspace(*t); t++)
                    314:                                ;
1.17      deraadt   315:                        revision = savestr(t);
1.18      deraadt   316:                        for (t = revision; *t && !isspace(*t); t++)
                    317:                                ;
1.17      deraadt   318:                        *t = '\0';
1.25      otto      319:                        if (*revision == '\0') {
1.17      deraadt   320:                                free(revision);
1.21      otto      321:                                revision = NULL;
1.17      deraadt   322:                        }
                    323:                }
                    324:                if ((!diff_type || diff_type == ED_DIFF) &&
                    325:                    first_command_line >= 0L &&
                    326:                    strEQ(s, ".\n")) {
                    327:                        p_indent = indent;
                    328:                        p_start = first_command_line;
                    329:                        p_sline = fcl_line;
                    330:                        retval = ED_DIFF;
                    331:                        goto scan_exit;
                    332:                }
                    333:                if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
1.32    ! millert   334:                        if (strnEQ(s + 4, "0,0", 3))
1.28      otto      335:                                ok_to_create_file = true;
1.17      deraadt   336:                        p_indent = indent;
                    337:                        p_start = this_line;
                    338:                        p_sline = p_input_line;
                    339:                        retval = UNI_DIFF;
                    340:                        goto scan_exit;
                    341:                }
                    342:                stars_this_line = strnEQ(s, "********", 8);
                    343:                if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
                    344:                    strnEQ(s, "*** ", 4)) {
1.32    ! millert   345:                        if (atol(s + 4) == 0)
1.28      otto      346:                                ok_to_create_file = true;
1.17      deraadt   347:                        /*
1.32    ! millert   348:                         * If this is a new context diff the character just
        !           349:                         * before the newline is a '*'.
1.17      deraadt   350:                         */
                    351:                        while (*s != '\n')
                    352:                                s++;
                    353:                        p_indent = indent;
                    354:                        p_start = previous_line;
                    355:                        p_sline = p_input_line - 1;
                    356:                        retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
                    357:                        goto scan_exit;
                    358:                }
                    359:                if ((!diff_type || diff_type == NORMAL_DIFF) &&
                    360:                    last_line_was_command &&
                    361:                    (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
                    362:                        p_start = previous_line;
                    363:                        p_sline = p_input_line - 1;
                    364:                        p_indent = indent;
                    365:                        retval = NORMAL_DIFF;
                    366:                        goto scan_exit;
                    367:                }
                    368:        }
                    369: scan_exit:
1.32    ! millert   370:        if (retval == UNI_DIFF) {
        !           371:                /* unswap old and new */
        !           372:                struct file_name tmp = names[OLD_FILE];
        !           373:                names[OLD_FILE] = names[NEW_FILE];
        !           374:                names[NEW_FILE] = tmp;
        !           375:        }
        !           376:        if (filearg[0] == NULL) {
        !           377:                if (posix)
        !           378:                        filearg[0] = posix_name(names, ok_to_create_file);
        !           379:                else {
        !           380:                        /* Ignore the Index: name for context diffs, like GNU */
        !           381:                        if (names[OLD_FILE].path != NULL ||
        !           382:                            names[NEW_FILE].path != NULL) {
        !           383:                                free(names[INDEX_FILE].path);
        !           384:                                names[INDEX_FILE].path = NULL;
        !           385:                        }
        !           386:                        filearg[0] = best_name(names, ok_to_create_file);
        !           387:                }
1.17      deraadt   388:        }
1.25      otto      389:
                    390:        free(bestguess);
                    391:        bestguess = NULL;
1.21      otto      392:        if (filearg[0] != NULL)
1.17      deraadt   393:                bestguess = savestr(filearg[0]);
1.32    ! millert   394:        else if (!ok_to_create_file) {
        !           395:                /*
        !           396:                 * We don't want to create a new file but we need a
        !           397:                 * filename to set bestguess.  Avoid setting filearg[0]
        !           398:                 * so the file is not created automatically.
        !           399:                 */
        !           400:                if (posix)
        !           401:                        bestguess = posix_name(names, true);
        !           402:                else
        !           403:                        bestguess = best_name(names, true);
        !           404:        }
        !           405:        free(names[OLD_FILE].path);
        !           406:        free(names[NEW_FILE].path);
        !           407:        free(names[INDEX_FILE].path);
1.17      deraadt   408:        return retval;
1.1       deraadt   409: }
                    410:
1.17      deraadt   411: /*
                    412:  * Remember where this patch ends so we know where to start up again.
                    413:  */
1.21      otto      414: static void
1.25      otto      415: next_intuit_at(LINENUM file_pos, LINENUM file_line)
1.1       deraadt   416: {
1.17      deraadt   417:        p_base = file_pos;
                    418:        p_bline = file_line;
1.1       deraadt   419: }
                    420:
1.17      deraadt   421: /*
                    422:  * Basically a verbose fseek() to the actual diff listing.
                    423:  */
1.21      otto      424: static void
1.25      otto      425: skip_to(LINENUM file_pos, LINENUM file_line)
1.1       deraadt   426: {
1.17      deraadt   427:        char    *ret;
1.1       deraadt   428:
1.28      otto      429:        if (p_base > file_pos)
                    430:                fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
1.17      deraadt   431:        if (verbose && p_base < file_pos) {
1.21      otto      432:                fseek(pfp, p_base, SEEK_SET);
1.17      deraadt   433:                say("The text leading up to this was:\n--------------------------\n");
                    434:                while (ftell(pfp) < file_pos) {
                    435:                        ret = fgets(buf, sizeof buf, pfp);
1.28      otto      436:                        if (ret == NULL)
                    437:                                fatal("Unexpected end of file\n");
1.17      deraadt   438:                        say("|%s", buf);
                    439:                }
                    440:                say("--------------------------\n");
                    441:        } else
1.21      otto      442:                fseek(pfp, file_pos, SEEK_SET);
1.17      deraadt   443:        p_input_line = file_line - 1;
1.1       deraadt   444: }
                    445:
                    446: /* Make this a function for better debugging.  */
                    447: static void
1.16      deraadt   448: malformed(void)
1.1       deraadt   449: {
1.17      deraadt   450:        fatal("malformed patch at line %ld: %s", p_input_line, buf);
                    451:        /* about as informative as "Syntax error" in C */
1.1       deraadt   452: }
                    453:
1.14      otto      454: /*
                    455:  * True if the line has been discarded (i.e. it is a line saying
                    456:  *  "\ No newline at end of file".)
                    457:  */
                    458: static bool
                    459: remove_special_line(void)
                    460: {
1.17      deraadt   461:        int     c;
1.14      otto      462:
                    463:        c = fgetc(pfp);
                    464:        if (c == '\\') {
                    465:                do {
                    466:                        c = fgetc(pfp);
                    467:                } while (c != EOF && c != '\n');
                    468:
1.28      otto      469:                return true;
1.14      otto      470:        }
                    471:        if (c != EOF)
                    472:                fseek(pfp, -1L, SEEK_CUR);
                    473:
1.28      otto      474:        return false;
1.14      otto      475: }
                    476:
1.17      deraadt   477: /*
                    478:  * True if there is more of the current diff listing to process.
                    479:  */
1.1       deraadt   480: bool
1.17      deraadt   481: another_hunk(void)
1.1       deraadt   482: {
1.17      deraadt   483:        long    line_beginning;                 /* file pos of the current line */
                    484:        LINENUM repl_beginning;                 /* index of --- line */
                    485:        LINENUM fillcnt;                        /* #lines of missing ptrn or repl */
                    486:        LINENUM fillsrc;                        /* index of first line to copy */
                    487:        LINENUM filldst;                        /* index of first missing line */
                    488:        bool    ptrn_spaces_eaten;              /* ptrn was slightly misformed */
                    489:        bool    repl_could_be_missing;          /* no + or ! lines in this hunk */
                    490:        bool    repl_missing;                   /* we are now backtracking */
                    491:        long    repl_backtrack_position;        /* file pos of first repl line */
                    492:        LINENUM repl_patch_line;                /* input line number for same */
                    493:        LINENUM ptrn_copiable;                  /* # of copiable lines in ptrn */
                    494:        char    *s, *ret;
                    495:        int     context = 0;
                    496:
                    497:        while (p_end >= 0) {
                    498:                if (p_end == p_efake)
                    499:                        p_end = p_bfake;        /* don't free twice */
                    500:                else
                    501:                        free(p_line[p_end]);
                    502:                p_end--;
                    503:        }
                    504:        p_efake = -1;
                    505:
                    506:        p_max = hunkmax;        /* gets reduced when --- found */
                    507:        if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
                    508:                line_beginning = ftell(pfp);
                    509:                repl_beginning = 0;
                    510:                fillcnt = 0;
1.28      otto      511:                ptrn_spaces_eaten = false;
                    512:                repl_could_be_missing = true;
                    513:                repl_missing = false;
1.17      deraadt   514:                repl_backtrack_position = 0;
                    515:                ptrn_copiable = 0;
                    516:
                    517:                ret = pgets(buf, sizeof buf, pfp);
                    518:                p_input_line++;
1.21      otto      519:                if (ret == NULL || strnNE(buf, "********", 8)) {
1.17      deraadt   520:                        next_intuit_at(line_beginning, p_input_line);
1.28      otto      521:                        return false;
1.17      deraadt   522:                }
                    523:                p_context = 100;
                    524:                p_hunk_beg = p_input_line + 1;
                    525:                while (p_end < p_max) {
                    526:                        line_beginning = ftell(pfp);
                    527:                        ret = pgets(buf, sizeof buf, pfp);
                    528:                        p_input_line++;
1.21      otto      529:                        if (ret == NULL) {
1.17      deraadt   530:                                if (p_max - p_end < 4) {
                    531:                                        /* assume blank lines got chopped */
                    532:                                        strlcpy(buf, "  \n", sizeof buf);
                    533:                                } else {
                    534:                                        if (repl_beginning && repl_could_be_missing) {
1.28      otto      535:                                                repl_missing = true;
1.17      deraadt   536:                                                goto hunk_done;
                    537:                                        }
                    538:                                        fatal("unexpected end of file in patch\n");
                    539:                                }
                    540:                        }
                    541:                        p_end++;
1.28      otto      542:                        if (p_end >= hunkmax)
                    543:                                fatal("Internal error: hunk larger than hunk "
1.29      deraadt   544:                                    "buffer size");
1.17      deraadt   545:                        p_char[p_end] = *buf;
1.21      otto      546:                        p_line[p_end] = NULL;
1.17      deraadt   547:                        switch (*buf) {
                    548:                        case '*':
                    549:                                if (strnEQ(buf, "********", 8)) {
                    550:                                        if (repl_beginning && repl_could_be_missing) {
1.28      otto      551:                                                repl_missing = true;
1.17      deraadt   552:                                                goto hunk_done;
                    553:                                        } else
                    554:                                                fatal("unexpected end of hunk "
                    555:                                                    "at line %ld\n",
                    556:                                                    p_input_line);
                    557:                                }
                    558:                                if (p_end != 0) {
                    559:                                        if (repl_beginning && repl_could_be_missing) {
1.28      otto      560:                                                repl_missing = true;
1.17      deraadt   561:                                                goto hunk_done;
                    562:                                        }
                    563:                                        fatal("unexpected *** at line %ld: %s",
                    564:                                            p_input_line, buf);
                    565:                                }
                    566:                                context = 0;
                    567:                                p_line[p_end] = savestr(buf);
                    568:                                if (out_of_mem) {
                    569:                                        p_end--;
1.28      otto      570:                                        return false;
1.17      deraadt   571:                                }
                    572:                                for (s = buf; *s && !isdigit(*s); s++)
                    573:                                        ;
                    574:                                if (!*s)
                    575:                                        malformed();
                    576:                                if (strnEQ(s, "0,0", 3))
                    577:                                        memmove(s, s + 2, strlen(s + 2) + 1);
                    578:                                p_first = (LINENUM) atol(s);
                    579:                                while (isdigit(*s))
                    580:                                        s++;
                    581:                                if (*s == ',') {
1.18      deraadt   582:                                        for (; *s && !isdigit(*s); s++)
                    583:                                                ;
1.17      deraadt   584:                                        if (!*s)
                    585:                                                malformed();
                    586:                                        p_ptrn_lines = ((LINENUM) atol(s)) - p_first + 1;
                    587:                                } else if (p_first)
                    588:                                        p_ptrn_lines = 1;
                    589:                                else {
                    590:                                        p_ptrn_lines = 0;
                    591:                                        p_first = 1;
                    592:                                }
1.26      deraadt   593:
                    594:                                /* we need this much at least */
                    595:                                p_max = p_ptrn_lines + 6;
1.17      deraadt   596:                                while (p_max >= hunkmax)
                    597:                                        grow_hunkmax();
                    598:                                p_max = hunkmax;
                    599:                                break;
                    600:                        case '-':
                    601:                                if (buf[1] == '-') {
                    602:                                        if (repl_beginning ||
                    603:                                            (p_end != p_ptrn_lines + 1 +
                    604:                                            (p_char[p_end - 1] == '\n'))) {
                    605:                                                if (p_end == 1) {
                    606:                                                        /*
                    607:                                                         * `old' lines were omitted;
                    608:                                                         * set up to fill them in
                    609:                                                         * from 'new' context lines.
                    610:                                                         */
                    611:                                                        p_end = p_ptrn_lines + 1;
                    612:                                                        fillsrc = p_end + 1;
                    613:                                                        filldst = 1;
                    614:                                                        fillcnt = p_ptrn_lines;
                    615:                                                } else {
                    616:                                                        if (repl_beginning) {
                    617:                                                                if (repl_could_be_missing) {
1.28      otto      618:                                                                        repl_missing = true;
1.17      deraadt   619:                                                                        goto hunk_done;
                    620:                                                                }
                    621:                                                                fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
                    622:                                                                    p_input_line, p_hunk_beg + repl_beginning);
                    623:                                                        } else {
                    624:                                                                fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
                    625:                                                                    (p_end <= p_ptrn_lines
                    626:                                                                    ? "Premature"
                    627:                                                                    : "Overdue"),
                    628:                                                                    p_input_line, p_hunk_beg);
                    629:                                                        }
                    630:                                                }
                    631:                                        }
                    632:                                        repl_beginning = p_end;
                    633:                                        repl_backtrack_position = ftell(pfp);
                    634:                                        repl_patch_line = p_input_line;
                    635:                                        p_line[p_end] = savestr(buf);
                    636:                                        if (out_of_mem) {
                    637:                                                p_end--;
1.28      otto      638:                                                return false;
1.17      deraadt   639:                                        }
                    640:                                        p_char[p_end] = '=';
                    641:                                        for (s = buf; *s && !isdigit(*s); s++)
                    642:                                                ;
                    643:                                        if (!*s)
                    644:                                                malformed();
                    645:                                        p_newfirst = (LINENUM) atol(s);
                    646:                                        while (isdigit(*s))
                    647:                                                s++;
                    648:                                        if (*s == ',') {
                    649:                                                for (; *s && !isdigit(*s); s++)
                    650:                                                        ;
                    651:                                                if (!*s)
                    652:                                                        malformed();
                    653:                                                p_repl_lines = ((LINENUM) atol(s)) -
                    654:                                                    p_newfirst + 1;
                    655:                                        } else if (p_newfirst)
                    656:                                                p_repl_lines = 1;
                    657:                                        else {
                    658:                                                p_repl_lines = 0;
                    659:                                                p_newfirst = 1;
                    660:                                        }
                    661:                                        p_max = p_repl_lines + p_end;
                    662:                                        if (p_max > MAXHUNKSIZE)
                    663:                                                fatal("hunk too large (%ld lines) at line %ld: %s",
                    664:                                                    p_max, p_input_line, buf);
                    665:                                        while (p_max >= hunkmax)
                    666:                                                grow_hunkmax();
                    667:                                        if (p_repl_lines != ptrn_copiable &&
                    668:                                            (p_context != 0 || p_repl_lines != 1))
1.28      otto      669:                                                repl_could_be_missing = false;
1.17      deraadt   670:                                        break;
                    671:                                }
                    672:                                goto change_line;
                    673:                        case '+':
                    674:                        case '!':
1.28      otto      675:                                repl_could_be_missing = false;
1.17      deraadt   676:                change_line:
                    677:                                if (buf[1] == '\n' && canonicalize)
                    678:                                        strlcpy(buf + 1, " \n", sizeof buf - 1);
                    679:                                if (!isspace(buf[1]) && buf[1] != '>' &&
                    680:                                    buf[1] != '<' &&
                    681:                                    repl_beginning && repl_could_be_missing) {
1.28      otto      682:                                        repl_missing = true;
1.17      deraadt   683:                                        goto hunk_done;
                    684:                                }
                    685:                                if (context >= 0) {
                    686:                                        if (context < p_context)
                    687:                                                p_context = context;
                    688:                                        context = -1000;
                    689:                                }
                    690:                                p_line[p_end] = savestr(buf + 2);
                    691:                                if (out_of_mem) {
                    692:                                        p_end--;
1.28      otto      693:                                        return false;
1.17      deraadt   694:                                }
                    695:                                if (p_end == p_ptrn_lines) {
                    696:                                        if (remove_special_line()) {
                    697:                                                int     len;
                    698:
                    699:                                                len = strlen(p_line[p_end]) - 1;
                    700:                                                (p_line[p_end])[len] = 0;
                    701:                                        }
                    702:                                }
                    703:                                break;
                    704:                        case '\t':
                    705:                        case '\n':      /* assume the 2 spaces got eaten */
                    706:                                if (repl_beginning && repl_could_be_missing &&
                    707:                                    (!ptrn_spaces_eaten ||
                    708:                                    diff_type == NEW_CONTEXT_DIFF)) {
1.28      otto      709:                                        repl_missing = true;
1.17      deraadt   710:                                        goto hunk_done;
                    711:                                }
                    712:                                p_line[p_end] = savestr(buf);
                    713:                                if (out_of_mem) {
                    714:                                        p_end--;
1.28      otto      715:                                        return false;
1.17      deraadt   716:                                }
                    717:                                if (p_end != p_ptrn_lines + 1) {
                    718:                                        ptrn_spaces_eaten |= (repl_beginning != 0);
                    719:                                        context++;
                    720:                                        if (!repl_beginning)
                    721:                                                ptrn_copiable++;
                    722:                                        p_char[p_end] = ' ';
                    723:                                }
                    724:                                break;
                    725:                        case ' ':
                    726:                                if (!isspace(buf[1]) &&
1.23      deraadt   727:                                    repl_beginning && repl_could_be_missing) {
1.28      otto      728:                                        repl_missing = true;
1.17      deraadt   729:                                        goto hunk_done;
                    730:                                }
                    731:                                context++;
                    732:                                if (!repl_beginning)
                    733:                                        ptrn_copiable++;
                    734:                                p_line[p_end] = savestr(buf + 2);
                    735:                                if (out_of_mem) {
                    736:                                        p_end--;
1.28      otto      737:                                        return false;
1.17      deraadt   738:                                }
                    739:                                break;
                    740:                        default:
                    741:                                if (repl_beginning && repl_could_be_missing) {
1.28      otto      742:                                        repl_missing = true;
1.17      deraadt   743:                                        goto hunk_done;
                    744:                                }
                    745:                                malformed();
                    746:                        }
                    747:                        /* set up p_len for strncmp() so we don't have to */
                    748:                        /* assume null termination */
                    749:                        if (p_line[p_end])
                    750:                                p_len[p_end] = strlen(p_line[p_end]);
                    751:                        else
                    752:                                p_len[p_end] = 0;
                    753:                }
                    754:
                    755: hunk_done:
                    756:                if (p_end >= 0 && !repl_beginning)
                    757:                        fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
                    758:
                    759:                if (repl_missing) {
                    760:
                    761:                        /* reset state back to just after --- */
                    762:                        p_input_line = repl_patch_line;
                    763:                        for (p_end--; p_end > repl_beginning; p_end--)
                    764:                                free(p_line[p_end]);
1.21      otto      765:                        fseek(pfp, repl_backtrack_position, SEEK_SET);
1.17      deraadt   766:
                    767:                        /* redundant 'new' context lines were omitted - set */
                    768:                        /* up to fill them in from the old file context */
                    769:                        if (!p_context && p_repl_lines == 1) {
                    770:                                p_repl_lines = 0;
                    771:                                p_max--;
                    772:                        }
                    773:                        fillsrc = 1;
                    774:                        filldst = repl_beginning + 1;
                    775:                        fillcnt = p_repl_lines;
                    776:                        p_end = p_max;
                    777:                } else if (!p_context && fillcnt == 1) {
                    778:                        /* the first hunk was a null hunk with no context */
                    779:                        /* and we were expecting one line -- fix it up. */
                    780:                        while (filldst < p_end) {
                    781:                                p_line[filldst] = p_line[filldst + 1];
                    782:                                p_char[filldst] = p_char[filldst + 1];
                    783:                                p_len[filldst] = p_len[filldst + 1];
                    784:                                filldst++;
                    785:                        }
                    786: #if 0
1.26      deraadt   787:                        repl_beginning--;       /* this doesn't need to be fixed */
1.17      deraadt   788: #endif
                    789:                        p_end--;
                    790:                        p_first++;      /* do append rather than insert */
                    791:                        fillcnt = 0;
                    792:                        p_ptrn_lines = 0;
                    793:                }
                    794:                if (diff_type == CONTEXT_DIFF &&
                    795:                    (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
                    796:                        if (verbose)
                    797:                                say("%s\n%s\n%s\n",
                    798:                                    "(Fascinating--this is really a new-style context diff but without",
                    799:                                    "the telltale extra asterisks on the *** line that usually indicate",
                    800:                                    "the new style...)");
                    801:                        diff_type = NEW_CONTEXT_DIFF;
                    802:                }
                    803:                /* if there were omitted context lines, fill them in now */
                    804:                if (fillcnt) {
1.26      deraadt   805:                        p_bfake = filldst;      /* remember where not to free() */
1.17      deraadt   806:                        p_efake = filldst + fillcnt - 1;
                    807:                        while (fillcnt-- > 0) {
                    808:                                while (fillsrc <= p_end && p_char[fillsrc] != ' ')
                    809:                                        fillsrc++;
                    810:                                if (fillsrc > p_end)
                    811:                                        fatal("replacement text or line numbers mangled in hunk at line %ld\n",
                    812:                                            p_hunk_beg);
                    813:                                p_line[filldst] = p_line[fillsrc];
                    814:                                p_char[filldst] = p_char[fillsrc];
                    815:                                p_len[filldst] = p_len[fillsrc];
                    816:                                fillsrc++;
                    817:                                filldst++;
                    818:                        }
                    819:                        while (fillsrc <= p_end && fillsrc != repl_beginning &&
                    820:                            p_char[fillsrc] != ' ')
                    821:                                fillsrc++;
                    822: #ifdef DEBUGGING
                    823:                        if (debug & 64)
                    824:                                printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
                    825:                                fillsrc, filldst, repl_beginning, p_end + 1);
1.1       deraadt   826: #endif
1.28      otto      827:                        if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
                    828:                                malformed();
                    829:                        if (filldst != p_end + 1 && filldst != repl_beginning)
                    830:                                malformed();
1.1       deraadt   831:                }
1.17      deraadt   832:                if (p_line[p_end] != NULL) {
                    833:                        if (remove_special_line()) {
                    834:                                p_len[p_end] -= 1;
                    835:                                (p_line[p_end])[p_len[p_end]] = 0;
                    836:                        }
                    837:                }
                    838:        } else if (diff_type == UNI_DIFF) {
                    839:                long    line_beginning = ftell(pfp); /* file pos of the current line */
                    840:                LINENUM fillsrc;        /* index of old lines */
                    841:                LINENUM filldst;        /* index of new lines */
                    842:                char    ch;
                    843:
                    844:                ret = pgets(buf, sizeof buf, pfp);
                    845:                p_input_line++;
1.21      otto      846:                if (ret == NULL || strnNE(buf, "@@ -", 4)) {
1.17      deraadt   847:                        next_intuit_at(line_beginning, p_input_line);
1.28      otto      848:                        return false;
1.1       deraadt   849:                }
1.17      deraadt   850:                s = buf + 4;
1.1       deraadt   851:                if (!*s)
1.17      deraadt   852:                        malformed();
1.1       deraadt   853:                p_first = (LINENUM) atol(s);
1.17      deraadt   854:                while (isdigit(*s))
                    855:                        s++;
                    856:                if (*s == ',') {
                    857:                        p_ptrn_lines = (LINENUM) atol(++s);
                    858:                        while (isdigit(*s))
                    859:                                s++;
                    860:                } else
                    861:                        p_ptrn_lines = 1;
                    862:                if (*s == ' ')
                    863:                        s++;
                    864:                if (*s != '+' || !*++s)
                    865:                        malformed();
                    866:                p_newfirst = (LINENUM) atol(s);
                    867:                while (isdigit(*s))
                    868:                        s++;
1.1       deraadt   869:                if (*s == ',') {
1.17      deraadt   870:                        p_repl_lines = (LINENUM) atol(++s);
                    871:                        while (isdigit(*s))
                    872:                                s++;
                    873:                } else
                    874:                        p_repl_lines = 1;
                    875:                if (*s == ' ')
                    876:                        s++;
                    877:                if (*s != '@')
                    878:                        malformed();
                    879:                if (!p_ptrn_lines)
                    880:                        p_first++;      /* do append rather than insert */
                    881:                p_max = p_ptrn_lines + p_repl_lines + 1;
                    882:                while (p_max >= hunkmax)
                    883:                        grow_hunkmax();
                    884:                fillsrc = 1;
                    885:                filldst = fillsrc + p_ptrn_lines;
                    886:                p_end = filldst + p_repl_lines;
                    887:                snprintf(buf, sizeof buf, "*** %ld,%ld ****\n", p_first,
1.26      deraadt   888:                    p_first + p_ptrn_lines - 1);
1.17      deraadt   889:                p_line[0] = savestr(buf);
                    890:                if (out_of_mem) {
                    891:                        p_end = -1;
1.28      otto      892:                        return false;
1.17      deraadt   893:                }
                    894:                p_char[0] = '*';
                    895:                snprintf(buf, sizeof buf, "--- %ld,%ld ----\n", p_newfirst,
1.26      deraadt   896:                    p_newfirst + p_repl_lines - 1);
1.17      deraadt   897:                p_line[filldst] = savestr(buf);
                    898:                if (out_of_mem) {
                    899:                        p_end = 0;
1.28      otto      900:                        return false;
1.1       deraadt   901:                }
1.17      deraadt   902:                p_char[filldst++] = '=';
                    903:                p_context = 100;
                    904:                context = 0;
                    905:                p_hunk_beg = p_input_line + 1;
                    906:                while (fillsrc <= p_ptrn_lines || filldst <= p_end) {
                    907:                        line_beginning = ftell(pfp);
                    908:                        ret = pgets(buf, sizeof buf, pfp);
                    909:                        p_input_line++;
1.21      otto      910:                        if (ret == NULL) {
1.17      deraadt   911:                                if (p_max - filldst < 3) {
                    912:                                        /* assume blank lines got chopped */
                    913:                                        strlcpy(buf, " \n", sizeof buf);
                    914:                                } else {
                    915:                                        fatal("unexpected end of file in patch\n");
                    916:                                }
                    917:                        }
                    918:                        if (*buf == '\t' || *buf == '\n') {
                    919:                                ch = ' ';       /* assume the space got eaten */
                    920:                                s = savestr(buf);
                    921:                        } else {
                    922:                                ch = *buf;
                    923:                                s = savestr(buf + 1);
                    924:                        }
                    925:                        if (out_of_mem) {
                    926:                                while (--filldst > p_ptrn_lines)
                    927:                                        free(p_line[filldst]);
                    928:                                p_end = fillsrc - 1;
1.28      otto      929:                                return false;
1.17      deraadt   930:                        }
                    931:                        switch (ch) {
                    932:                        case '-':
                    933:                                if (fillsrc > p_ptrn_lines) {
                    934:                                        free(s);
                    935:                                        p_end = filldst - 1;
                    936:                                        malformed();
                    937:                                }
                    938:                                p_char[fillsrc] = ch;
                    939:                                p_line[fillsrc] = s;
                    940:                                p_len[fillsrc++] = strlen(s);
                    941:                                if (fillsrc > p_ptrn_lines) {
                    942:                                        if (remove_special_line()) {
                    943:                                                p_len[fillsrc - 1] -= 1;
                    944:                                                s[p_len[fillsrc - 1]] = 0;
                    945:                                        }
                    946:                                }
                    947:                                break;
                    948:                        case '=':
                    949:                                ch = ' ';
                    950:                                /* FALL THROUGH */
                    951:                        case ' ':
                    952:                                if (fillsrc > p_ptrn_lines) {
                    953:                                        free(s);
                    954:                                        while (--filldst > p_ptrn_lines)
                    955:                                                free(p_line[filldst]);
                    956:                                        p_end = fillsrc - 1;
                    957:                                        malformed();
                    958:                                }
                    959:                                context++;
                    960:                                p_char[fillsrc] = ch;
                    961:                                p_line[fillsrc] = s;
                    962:                                p_len[fillsrc++] = strlen(s);
                    963:                                s = savestr(s);
                    964:                                if (out_of_mem) {
                    965:                                        while (--filldst > p_ptrn_lines)
                    966:                                                free(p_line[filldst]);
                    967:                                        p_end = fillsrc - 1;
1.28      otto      968:                                        return false;
1.17      deraadt   969:                                }
                    970:                                /* FALL THROUGH */
                    971:                        case '+':
                    972:                                if (filldst > p_end) {
                    973:                                        free(s);
                    974:                                        while (--filldst > p_ptrn_lines)
                    975:                                                free(p_line[filldst]);
                    976:                                        p_end = fillsrc - 1;
                    977:                                        malformed();
                    978:                                }
                    979:                                p_char[filldst] = ch;
                    980:                                p_line[filldst] = s;
                    981:                                p_len[filldst++] = strlen(s);
                    982:                                if (fillsrc > p_ptrn_lines) {
                    983:                                        if (remove_special_line()) {
                    984:                                                p_len[filldst - 1] -= 1;
                    985:                                                s[p_len[filldst - 1]] = 0;
                    986:                                        }
                    987:                                }
                    988:                                break;
                    989:                        default:
                    990:                                p_end = filldst;
                    991:                                malformed();
1.1       deraadt   992:                        }
1.17      deraadt   993:                        if (ch != ' ' && context > 0) {
                    994:                                if (context < p_context)
                    995:                                        p_context = context;
                    996:                                context = -1000;
1.1       deraadt   997:                        }
1.17      deraadt   998:                }               /* while */
                    999:        } else {                /* normal diff--fake it up */
                   1000:                char    hunk_type;
                   1001:                int     i;
                   1002:                LINENUM min, max;
                   1003:                long    line_beginning = ftell(pfp);
                   1004:
                   1005:                p_context = 0;
                   1006:                ret = pgets(buf, sizeof buf, pfp);
                   1007:                p_input_line++;
1.21      otto     1008:                if (ret == NULL || !isdigit(*buf)) {
1.17      deraadt  1009:                        next_intuit_at(line_beginning, p_input_line);
1.28      otto     1010:                        return false;
1.17      deraadt  1011:                }
                   1012:                p_first = (LINENUM) atol(buf);
1.18      deraadt  1013:                for (s = buf; isdigit(*s); s++)
                   1014:                        ;
1.17      deraadt  1015:                if (*s == ',') {
                   1016:                        p_ptrn_lines = (LINENUM) atol(++s) - p_first + 1;
                   1017:                        while (isdigit(*s))
                   1018:                                s++;
                   1019:                } else
                   1020:                        p_ptrn_lines = (*s != 'a');
                   1021:                hunk_type = *s;
                   1022:                if (hunk_type == 'a')
                   1023:                        p_first++;      /* do append rather than insert */
                   1024:                min = (LINENUM) atol(++s);
1.18      deraadt  1025:                for (; isdigit(*s); s++)
                   1026:                        ;
1.17      deraadt  1027:                if (*s == ',')
                   1028:                        max = (LINENUM) atol(++s);
                   1029:                else
                   1030:                        max = min;
                   1031:                if (hunk_type == 'd')
                   1032:                        min++;
                   1033:                p_end = p_ptrn_lines + 1 + max - min + 1;
                   1034:                if (p_end > MAXHUNKSIZE)
1.16      deraadt  1035:                        fatal("hunk too large (%ld lines) at line %ld: %s",
1.17      deraadt  1036:                            p_end, p_input_line, buf);
                   1037:                while (p_end >= hunkmax)
1.1       deraadt  1038:                        grow_hunkmax();
1.17      deraadt  1039:                p_newfirst = min;
                   1040:                p_repl_lines = max - min + 1;
                   1041:                snprintf(buf, sizeof buf, "*** %ld,%ld\n", p_first,
1.26      deraadt  1042:                    p_first + p_ptrn_lines - 1);
1.17      deraadt  1043:                p_line[0] = savestr(buf);
1.1       deraadt  1044:                if (out_of_mem) {
1.17      deraadt  1045:                        p_end = -1;
1.28      otto     1046:                        return false;
1.1       deraadt  1047:                }
1.17      deraadt  1048:                p_char[0] = '*';
                   1049:                for (i = 1; i <= p_ptrn_lines; i++) {
                   1050:                        ret = pgets(buf, sizeof buf, pfp);
                   1051:                        p_input_line++;
1.21      otto     1052:                        if (ret == NULL)
1.17      deraadt  1053:                                fatal("unexpected end of file in patch at line %ld\n",
                   1054:                                    p_input_line);
                   1055:                        if (*buf != '<')
                   1056:                                fatal("< expected at line %ld of patch\n",
                   1057:                                    p_input_line);
                   1058:                        p_line[i] = savestr(buf + 2);
                   1059:                        if (out_of_mem) {
                   1060:                                p_end = i - 1;
1.28      otto     1061:                                return false;
1.14      otto     1062:                        }
1.17      deraadt  1063:                        p_len[i] = strlen(p_line[i]);
                   1064:                        p_char[i] = '-';
1.14      otto     1065:                }
1.17      deraadt  1066:
                   1067:                if (remove_special_line()) {
                   1068:                        p_len[i - 1] -= 1;
                   1069:                        (p_line[i - 1])[p_len[i - 1]] = 0;
1.1       deraadt  1070:                }
1.17      deraadt  1071:                if (hunk_type == 'c') {
                   1072:                        ret = pgets(buf, sizeof buf, pfp);
                   1073:                        p_input_line++;
1.21      otto     1074:                        if (ret == NULL)
1.17      deraadt  1075:                                fatal("unexpected end of file in patch at line %ld\n",
                   1076:                                    p_input_line);
                   1077:                        if (*buf != '-')
                   1078:                                fatal("--- expected at line %ld of patch\n",
                   1079:                                    p_input_line);
1.1       deraadt  1080:                }
1.17      deraadt  1081:                snprintf(buf, sizeof(buf), "--- %ld,%ld\n", min, max);
                   1082:                p_line[i] = savestr(buf);
1.1       deraadt  1083:                if (out_of_mem) {
1.17      deraadt  1084:                        p_end = i - 1;
1.28      otto     1085:                        return false;
1.1       deraadt  1086:                }
1.17      deraadt  1087:                p_char[i] = '=';
                   1088:                for (i++; i <= p_end; i++) {
                   1089:                        ret = pgets(buf, sizeof buf, pfp);
                   1090:                        p_input_line++;
1.21      otto     1091:                        if (ret == NULL)
1.17      deraadt  1092:                                fatal("unexpected end of file in patch at line %ld\n",
                   1093:                                    p_input_line);
                   1094:                        if (*buf != '>')
                   1095:                                fatal("> expected at line %ld of patch\n",
                   1096:                                    p_input_line);
                   1097:                        p_line[i] = savestr(buf + 2);
                   1098:                        if (out_of_mem) {
                   1099:                                p_end = i - 1;
1.28      otto     1100:                                return false;
1.14      otto     1101:                        }
1.17      deraadt  1102:                        p_len[i] = strlen(p_line[i]);
                   1103:                        p_char[i] = '+';
1.14      otto     1104:                }
1.17      deraadt  1105:
                   1106:                if (remove_special_line()) {
                   1107:                        p_len[i - 1] -= 1;
                   1108:                        (p_line[i - 1])[p_len[i - 1]] = 0;
1.14      otto     1109:                }
1.1       deraadt  1110:        }
1.17      deraadt  1111:        if (reverse)            /* backwards patch? */
                   1112:                if (!pch_swap())
                   1113:                        say("Not enough memory to swap next hunk!\n");
1.1       deraadt  1114: #ifdef DEBUGGING
1.17      deraadt  1115:        if (debug & 2) {
                   1116:                int     i;
                   1117:                char    special;
                   1118:
                   1119:                for (i = 0; i <= p_end; i++) {
                   1120:                        if (i == p_ptrn_lines)
                   1121:                                special = '^';
                   1122:                        else
                   1123:                                special = ' ';
                   1124:                        fprintf(stderr, "%3d %c %c %s", i, p_char[i],
                   1125:                            special, p_line[i]);
                   1126:                        fflush(stderr);
                   1127:                }
1.1       deraadt  1128:        }
                   1129: #endif
1.17      deraadt  1130:        if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
                   1131:                p_char[p_end + 1] = '^';        /* add a stopper for apply_hunk */
1.28      otto     1132:        return true;
1.1       deraadt  1133: }
                   1134:
1.17      deraadt  1135: /*
                   1136:  * Input a line from the patch file, worrying about indentation.
                   1137:  */
1.21      otto     1138: static char *
1.17      deraadt  1139: pgets(char *bf, int sz, FILE *fp)
                   1140: {
                   1141:        char    *s, *ret = fgets(bf, sz, fp);
                   1142:        int     indent = 0;
1.1       deraadt  1143:
1.21      otto     1144:        if (p_indent && ret != NULL) {
1.17      deraadt  1145:                for (s = buf;
                   1146:                    indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
                   1147:                    s++) {
                   1148:                        if (*s == '\t')
                   1149:                                indent += 8 - (indent % 7);
                   1150:                        else
                   1151:                                indent++;
                   1152:                }
                   1153:                if (buf != s && strlcpy(buf, s, sizeof(buf)) >= sizeof(buf))
                   1154:                        fatal("buffer too small in pgets()\n");
                   1155:        }
                   1156:        return ret;
1.1       deraadt  1157: }
                   1158:
1.17      deraadt  1159: /*
                   1160:  * Reverse the old and new portions of the current hunk.
                   1161:  */
1.1       deraadt  1162: bool
1.17      deraadt  1163: pch_swap(void)
1.1       deraadt  1164: {
1.17      deraadt  1165:        char    **tp_line;      /* the text of the hunk */
                   1166:        short   *tp_len;        /* length of each line */
                   1167:        char    *tp_char;       /* +, -, and ! */
                   1168:        LINENUM i;
                   1169:        LINENUM n;
1.28      otto     1170:        bool    blankline = false;
1.17      deraadt  1171:        char    *s;
                   1172:
                   1173:        i = p_first;
                   1174:        p_first = p_newfirst;
                   1175:        p_newfirst = i;
                   1176:
                   1177:        /* make a scratch copy */
                   1178:
                   1179:        tp_line = p_line;
                   1180:        tp_len = p_len;
                   1181:        tp_char = p_char;
1.21      otto     1182:        p_line = NULL;  /* force set_hunkmax to allocate again */
                   1183:        p_len = NULL;
                   1184:        p_char = NULL;
1.17      deraadt  1185:        set_hunkmax();
1.28      otto     1186:        if (p_line == NULL || p_len == NULL || p_char == NULL) {
1.21      otto     1187:
1.28      otto     1188:                free(p_line);
1.17      deraadt  1189:                p_line = tp_line;
1.28      otto     1190:                free(p_len);
1.17      deraadt  1191:                p_len = tp_len;
1.28      otto     1192:                free(p_char);
1.17      deraadt  1193:                p_char = tp_char;
1.28      otto     1194:                return false;   /* not enough memory to swap hunk! */
1.17      deraadt  1195:        }
                   1196:        /* now turn the new into the old */
                   1197:
1.1       deraadt  1198:        i = p_ptrn_lines + 1;
1.17      deraadt  1199:        if (tp_char[i] == '\n') {       /* account for possible blank line */
1.28      otto     1200:                blankline = true;
1.17      deraadt  1201:                i++;
                   1202:        }
                   1203:        if (p_efake >= 0) {     /* fix non-freeable ptr range */
                   1204:                if (p_efake <= i)
                   1205:                        n = p_end - i + 1;
                   1206:                else
                   1207:                        n = -i;
                   1208:                p_efake += n;
                   1209:                p_bfake += n;
                   1210:        }
                   1211:        for (n = 0; i <= p_end; i++, n++) {
                   1212:                p_line[n] = tp_line[i];
                   1213:                p_char[n] = tp_char[i];
                   1214:                if (p_char[n] == '+')
                   1215:                        p_char[n] = '-';
                   1216:                p_len[n] = tp_len[i];
                   1217:        }
                   1218:        if (blankline) {
                   1219:                i = p_ptrn_lines + 1;
                   1220:                p_line[n] = tp_line[i];
                   1221:                p_char[n] = tp_char[i];
                   1222:                p_len[n] = tp_len[i];
                   1223:                n++;
                   1224:        }
1.28      otto     1225:        if (p_char[0] != '=')
1.29      deraadt  1226:                fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1.28      otto     1227:                    p_input_line, p_char[0]);
1.17      deraadt  1228:        p_char[0] = '*';
                   1229:        for (s = p_line[0]; *s; s++)
                   1230:                if (*s == '-')
                   1231:                        *s = '*';
                   1232:
                   1233:        /* now turn the old into the new */
                   1234:
1.28      otto     1235:        if (p_char[0] != '*')
1.29      deraadt  1236:                fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
                   1237:                    p_input_line, p_char[0]);
1.17      deraadt  1238:        tp_char[0] = '=';
                   1239:        for (s = tp_line[0]; *s; s++)
                   1240:                if (*s == '*')
                   1241:                        *s = '-';
                   1242:        for (i = 0; n <= p_end; i++, n++) {
                   1243:                p_line[n] = tp_line[i];
                   1244:                p_char[n] = tp_char[i];
                   1245:                if (p_char[n] == '-')
                   1246:                        p_char[n] = '+';
                   1247:                p_len[n] = tp_len[i];
                   1248:        }
1.28      otto     1249:
                   1250:        if (i != p_ptrn_lines + 1)
                   1251:                fatal("Malformed patch at line %ld: expected %ld lines, "
1.29      deraadt  1252:                    "got %ld\n",
                   1253:                    p_input_line, p_ptrn_lines + 1, i);
1.28      otto     1254:
1.17      deraadt  1255:        i = p_ptrn_lines;
                   1256:        p_ptrn_lines = p_repl_lines;
                   1257:        p_repl_lines = i;
1.21      otto     1258:
1.28      otto     1259:        free(tp_line);
                   1260:        free(tp_len);
                   1261:        free(tp_char);
                   1262:
                   1263:        return true;
1.1       deraadt  1264: }
                   1265:
1.17      deraadt  1266: /*
                   1267:  * Return the specified line position in the old file of the old context.
                   1268:  */
1.1       deraadt  1269: LINENUM
1.17      deraadt  1270: pch_first(void)
1.1       deraadt  1271: {
1.17      deraadt  1272:        return p_first;
1.1       deraadt  1273: }
                   1274:
1.17      deraadt  1275: /*
                   1276:  * Return the number of lines of old context.
                   1277:  */
1.1       deraadt  1278: LINENUM
1.17      deraadt  1279: pch_ptrn_lines(void)
1.1       deraadt  1280: {
1.17      deraadt  1281:        return p_ptrn_lines;
1.1       deraadt  1282: }
                   1283:
1.17      deraadt  1284: /*
                   1285:  * Return the probable line position in the new file of the first line.
                   1286:  */
1.1       deraadt  1287: LINENUM
1.17      deraadt  1288: pch_newfirst(void)
1.1       deraadt  1289: {
1.17      deraadt  1290:        return p_newfirst;
1.1       deraadt  1291: }
                   1292:
1.17      deraadt  1293: /*
                   1294:  * Return the number of lines in the replacement text including context.
                   1295:  */
1.1       deraadt  1296: LINENUM
1.17      deraadt  1297: pch_repl_lines(void)
1.1       deraadt  1298: {
1.17      deraadt  1299:        return p_repl_lines;
1.1       deraadt  1300: }
                   1301:
1.17      deraadt  1302: /*
                   1303:  * Return the number of lines in the whole hunk.
                   1304:  */
1.1       deraadt  1305: LINENUM
1.17      deraadt  1306: pch_end(void)
1.1       deraadt  1307: {
1.17      deraadt  1308:        return p_end;
1.1       deraadt  1309: }
                   1310:
1.17      deraadt  1311: /*
                   1312:  * Return the number of context lines before the first changed line.
                   1313:  */
1.1       deraadt  1314: LINENUM
1.17      deraadt  1315: pch_context(void)
1.1       deraadt  1316: {
1.17      deraadt  1317:        return p_context;
1.1       deraadt  1318: }
                   1319:
1.17      deraadt  1320: /*
                   1321:  * Return the length of a particular patch line.
                   1322:  */
1.1       deraadt  1323: short
1.17      deraadt  1324: pch_line_len(LINENUM line)
1.1       deraadt  1325: {
1.17      deraadt  1326:        return p_len[line];
1.1       deraadt  1327: }
                   1328:
1.17      deraadt  1329: /*
                   1330:  * Return the control character (+, -, *, !, etc) for a patch line.
                   1331:  */
1.1       deraadt  1332: char
1.17      deraadt  1333: pch_char(LINENUM line)
1.1       deraadt  1334: {
1.17      deraadt  1335:        return p_char[line];
1.1       deraadt  1336: }
                   1337:
1.17      deraadt  1338: /*
                   1339:  * Return a pointer to a particular patch line.
                   1340:  */
1.1       deraadt  1341: char *
1.17      deraadt  1342: pfetch(LINENUM line)
1.1       deraadt  1343: {
1.17      deraadt  1344:        return p_line[line];
1.1       deraadt  1345: }
                   1346:
1.17      deraadt  1347: /*
                   1348:  * Return where in the patch file this hunk began, for error messages.
                   1349:  */
1.1       deraadt  1350: LINENUM
1.17      deraadt  1351: pch_hunk_beg(void)
1.1       deraadt  1352: {
1.17      deraadt  1353:        return p_hunk_beg;
1.1       deraadt  1354: }
                   1355:
1.17      deraadt  1356: /*
                   1357:  * Apply an ed script by feeding ed itself.
                   1358:  */
1.1       deraadt  1359: void
1.17      deraadt  1360: do_ed_script(void)
1.1       deraadt  1361: {
1.17      deraadt  1362:        char    *t;
                   1363:        long    beginning_of_this_line;
                   1364:        FILE    *pipefp;
                   1365:
1.28      otto     1366:        pipefp = NULL;
1.17      deraadt  1367:        if (!skip_rest_of_patch) {
1.24      millert  1368:                if (copy_file(filearg[0], TMPOUTNAME) < 0) {
                   1369:                        unlink(TMPOUTNAME);
                   1370:                        fatal("can't create temp file %s", TMPOUTNAME);
                   1371:                }
1.27      millert  1372:                snprintf(buf, sizeof buf, "%s%s%s", _PATH_ED,
                   1373:                    verbose ? " " : " -s ", TMPOUTNAME);
1.17      deraadt  1374:                pipefp = popen(buf, "w");
                   1375:        }
                   1376:        for (;;) {
                   1377:                beginning_of_this_line = ftell(pfp);
1.21      otto     1378:                if (pgets(buf, sizeof buf, pfp) == NULL) {
1.17      deraadt  1379:                        next_intuit_at(beginning_of_this_line, p_input_line);
                   1380:                        break;
                   1381:                }
                   1382:                p_input_line++;
1.18      deraadt  1383:                for (t = buf; isdigit(*t) || *t == ','; t++)
                   1384:                        ;
1.22      millert  1385:                /* POSIX defines allowed commands as {a,c,d,i,s} */
                   1386:                if (isdigit(*buf) && (*t == 'a' || *t == 'c' || *t == 'd' ||
                   1387:                    *t == 'i' || *t == 's')) {
1.28      otto     1388:                        if (pipefp != NULL)
1.17      deraadt  1389:                                fputs(buf, pipefp);
                   1390:                        if (*t != 'd') {
1.21      otto     1391:                                while (pgets(buf, sizeof buf, pfp) != NULL) {
1.17      deraadt  1392:                                        p_input_line++;
1.28      otto     1393:                                        if (pipefp != NULL)
1.17      deraadt  1394:                                                fputs(buf, pipefp);
                   1395:                                        if (strEQ(buf, ".\n"))
                   1396:                                                break;
                   1397:                                }
                   1398:                        }
                   1399:                } else {
                   1400:                        next_intuit_at(beginning_of_this_line, p_input_line);
1.1       deraadt  1401:                        break;
                   1402:                }
                   1403:        }
1.28      otto     1404:        if (pipefp == NULL)
1.17      deraadt  1405:                return;
                   1406:        fprintf(pipefp, "w\n");
                   1407:        fprintf(pipefp, "q\n");
                   1408:        fflush(pipefp);
                   1409:        pclose(pipefp);
                   1410:        ignore_signals();
                   1411:        if (!check_only) {
                   1412:                if (move_file(TMPOUTNAME, outname) < 0) {
1.28      otto     1413:                        toutkeep = true;
1.17      deraadt  1414:                        chmod(TMPOUTNAME, filemode);
                   1415:                } else
                   1416:                        chmod(outname, filemode);
1.1       deraadt  1417:        }
1.17      deraadt  1418:        set_signals(1);
1.32    ! millert  1419: }
        !          1420:
        !          1421: /*
        !          1422:  * Choose the name of the file to be patched based on POSIX rules.
        !          1423:  * NOTE: the POSIX rules are amazingly stupid and we only follow them
        !          1424:  *       if the user specified --posix or set POSIXLY_CORRECT.
        !          1425:  */
        !          1426: static char *
        !          1427: posix_name(const struct file_name *names, bool assume_exists)
        !          1428: {
        !          1429:        char *path = NULL;
        !          1430:        int i;
        !          1431:
        !          1432:        /*
        !          1433:         * POSIX states that the filename will be chosen from one
        !          1434:         * of the old, new and index names (in that order) if
        !          1435:         * the file exists relative to CWD after -p stripping.
        !          1436:         */
        !          1437:        for (i = 0; i < MAX_FILE; i++) {
        !          1438:                if (names[i].path != NULL && names[i].exists) {
        !          1439:                        path = names[i].path;
        !          1440:                        break;
        !          1441:                }
        !          1442:        }
        !          1443:        if (path == NULL && !assume_exists) {
        !          1444:                /*
        !          1445:                 * No files found, look for something we can checkout from
        !          1446:                 * RCS/SCCS dirs.  Same order as above.
        !          1447:                 */
        !          1448:                for (i = 0; i < MAX_FILE; i++) {
        !          1449:                        if (names[i].path != NULL &&
        !          1450:                            (path = checked_in(names[i].path)) != NULL)
        !          1451:                                break;
        !          1452:                }
        !          1453:                /*
        !          1454:                 * Still no match?  Check to see if the diff could be creating
        !          1455:                 * a new file.
        !          1456:                 */
        !          1457:                if (path == NULL && ok_to_create_file &&
        !          1458:                    names[NEW_FILE].path != NULL)
        !          1459:                        path = names[NEW_FILE].path;
        !          1460:        }
        !          1461:
        !          1462:        return path ? savestr(path) : NULL;
        !          1463: }
        !          1464:
        !          1465: /*
        !          1466:  * Choose the name of the file to be patched based the "best" one
        !          1467:  * available.
        !          1468:  */
        !          1469: static char *
        !          1470: best_name(const struct file_name *names, bool assume_exists)
        !          1471: {
        !          1472:        size_t min_components, min_baselen, min_len, tmp;
        !          1473:        char *best = NULL;
        !          1474:        int i;
        !          1475:
        !          1476:        /*
        !          1477:         * The "best" name is the one with the fewest number of path
        !          1478:         * components, the shortest basename length, and the shortest
        !          1479:         * overall length (in that order).  We only use the Index: file
        !          1480:         * if neither of the old or new files could be intuited from
        !          1481:         * the diff header.
        !          1482:         */
        !          1483:        min_components = min_baselen = min_len = SIZE_MAX;
        !          1484:        for (i = INDEX_FILE; i >= OLD_FILE; i--) {
        !          1485:                if (names[i].path == NULL ||
        !          1486:                    (!names[i].exists && !assume_exists))
        !          1487:                        continue;
        !          1488:                if ((tmp = num_components(names[i].path)) > min_components)
        !          1489:                        continue;
        !          1490:                min_components = tmp;
        !          1491:                if ((tmp = strlen(basename(names[i].path))) > min_baselen)
        !          1492:                        continue;
        !          1493:                min_baselen = tmp;
        !          1494:                if ((tmp = strlen(names[i].path)) > min_len)
        !          1495:                        continue;
        !          1496:                min_len = tmp;
        !          1497:                best = names[i].path;
        !          1498:        }
        !          1499:        if (best == NULL) {
        !          1500:                /*
        !          1501:                 * No files found, look for something we can checkout from
        !          1502:                 * RCS/SCCS dirs.  Logic is identical to that above...
        !          1503:                 */
        !          1504:                min_components = min_baselen = min_len = SIZE_MAX;
        !          1505:                for (i = INDEX_FILE; i >= OLD_FILE; i--) {
        !          1506:                        if (names[i].path == NULL ||
        !          1507:                            checked_in(names[i].path) == NULL)
        !          1508:                                continue;
        !          1509:                        if ((tmp = num_components(names[i].path)) > min_components)
        !          1510:                                continue;
        !          1511:                        min_components = tmp;
        !          1512:                        if ((tmp = strlen(basename(names[i].path))) > min_baselen)
        !          1513:                                continue;
        !          1514:                        min_baselen = tmp;
        !          1515:                        if ((tmp = strlen(names[i].path)) > min_len)
        !          1516:                                continue;
        !          1517:                        min_len = tmp;
        !          1518:                        best = names[i].path;
        !          1519:                }
        !          1520:                /*
        !          1521:                 * Still no match?  Check to see if the diff could be creating
        !          1522:                 * a new file.
        !          1523:                 */
        !          1524:                if (best == NULL && ok_to_create_file &&
        !          1525:                    names[NEW_FILE].path != NULL)
        !          1526:                        best = names[NEW_FILE].path;
        !          1527:        }
        !          1528:
        !          1529:        return best ? savestr(best) : NULL;
        !          1530: }
        !          1531:
        !          1532: static size_t
        !          1533: num_components(const char *path)
        !          1534: {
        !          1535:        size_t n;
        !          1536:        const char *cp;
        !          1537:
        !          1538:        for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
        !          1539:                while (*cp == '/')
        !          1540:                        cp++;           /* skip consecutive slashes */
        !          1541:        }
        !          1542:        return n;
1.1       deraadt  1543: }