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

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