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

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