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

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