f99498b5cb07d5df15c4c0afb037fd435a0e42f5
   1/*
   2 * apply.c
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 *
   6 * This applies patches on top of some (arbitrary) version of the SCM.
   7 *
   8 */
   9#include "cache.h"
  10#include "lockfile.h"
  11#include "cache-tree.h"
  12#include "quote.h"
  13#include "blob.h"
  14#include "delta.h"
  15#include "builtin.h"
  16#include "string-list.h"
  17#include "dir.h"
  18#include "diff.h"
  19#include "parse-options.h"
  20#include "xdiff-interface.h"
  21#include "ll-merge.h"
  22#include "rerere.h"
  23#include "apply.h"
  24
  25static const char * const apply_usage[] = {
  26        N_("git apply [<options>] [<patch>...]"),
  27        NULL
  28};
  29
  30static void set_default_whitespace_mode(struct apply_state *state)
  31{
  32        if (!state->whitespace_option && !apply_default_whitespace)
  33                state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
  34}
  35
  36/*
  37 * This represents one "hunk" from a patch, starting with
  38 * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
  39 * patch text is pointed at by patch, and its byte length
  40 * is stored in size.  leading and trailing are the number
  41 * of context lines.
  42 */
  43struct fragment {
  44        unsigned long leading, trailing;
  45        unsigned long oldpos, oldlines;
  46        unsigned long newpos, newlines;
  47        /*
  48         * 'patch' is usually borrowed from buf in apply_patch(),
  49         * but some codepaths store an allocated buffer.
  50         */
  51        const char *patch;
  52        unsigned free_patch:1,
  53                rejected:1;
  54        int size;
  55        int linenr;
  56        struct fragment *next;
  57};
  58
  59/*
  60 * When dealing with a binary patch, we reuse "leading" field
  61 * to store the type of the binary hunk, either deflated "delta"
  62 * or deflated "literal".
  63 */
  64#define binary_patch_method leading
  65#define BINARY_DELTA_DEFLATED   1
  66#define BINARY_LITERAL_DEFLATED 2
  67
  68/*
  69 * This represents a "patch" to a file, both metainfo changes
  70 * such as creation/deletion, filemode and content changes represented
  71 * as a series of fragments.
  72 */
  73struct patch {
  74        char *new_name, *old_name, *def_name;
  75        unsigned int old_mode, new_mode;
  76        int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
  77        int rejected;
  78        unsigned ws_rule;
  79        int lines_added, lines_deleted;
  80        int score;
  81        unsigned int is_toplevel_relative:1;
  82        unsigned int inaccurate_eof:1;
  83        unsigned int is_binary:1;
  84        unsigned int is_copy:1;
  85        unsigned int is_rename:1;
  86        unsigned int recount:1;
  87        unsigned int conflicted_threeway:1;
  88        unsigned int direct_to_threeway:1;
  89        struct fragment *fragments;
  90        char *result;
  91        size_t resultsize;
  92        char old_sha1_prefix[41];
  93        char new_sha1_prefix[41];
  94        struct patch *next;
  95
  96        /* three-way fallback result */
  97        struct object_id threeway_stage[3];
  98};
  99
 100static void free_fragment_list(struct fragment *list)
 101{
 102        while (list) {
 103                struct fragment *next = list->next;
 104                if (list->free_patch)
 105                        free((char *)list->patch);
 106                free(list);
 107                list = next;
 108        }
 109}
 110
 111static void free_patch(struct patch *patch)
 112{
 113        free_fragment_list(patch->fragments);
 114        free(patch->def_name);
 115        free(patch->old_name);
 116        free(patch->new_name);
 117        free(patch->result);
 118        free(patch);
 119}
 120
 121static void free_patch_list(struct patch *list)
 122{
 123        while (list) {
 124                struct patch *next = list->next;
 125                free_patch(list);
 126                list = next;
 127        }
 128}
 129
 130/*
 131 * A line in a file, len-bytes long (includes the terminating LF,
 132 * except for an incomplete line at the end if the file ends with
 133 * one), and its contents hashes to 'hash'.
 134 */
 135struct line {
 136        size_t len;
 137        unsigned hash : 24;
 138        unsigned flag : 8;
 139#define LINE_COMMON     1
 140#define LINE_PATCHED    2
 141};
 142
 143/*
 144 * This represents a "file", which is an array of "lines".
 145 */
 146struct image {
 147        char *buf;
 148        size_t len;
 149        size_t nr;
 150        size_t alloc;
 151        struct line *line_allocated;
 152        struct line *line;
 153};
 154
 155static uint32_t hash_line(const char *cp, size_t len)
 156{
 157        size_t i;
 158        uint32_t h;
 159        for (i = 0, h = 0; i < len; i++) {
 160                if (!isspace(cp[i])) {
 161                        h = h * 3 + (cp[i] & 0xff);
 162                }
 163        }
 164        return h;
 165}
 166
 167/*
 168 * Compare lines s1 of length n1 and s2 of length n2, ignoring
 169 * whitespace difference. Returns 1 if they match, 0 otherwise
 170 */
 171static int fuzzy_matchlines(const char *s1, size_t n1,
 172                            const char *s2, size_t n2)
 173{
 174        const char *last1 = s1 + n1 - 1;
 175        const char *last2 = s2 + n2 - 1;
 176        int result = 0;
 177
 178        /* ignore line endings */
 179        while ((*last1 == '\r') || (*last1 == '\n'))
 180                last1--;
 181        while ((*last2 == '\r') || (*last2 == '\n'))
 182                last2--;
 183
 184        /* skip leading whitespaces, if both begin with whitespace */
 185        if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
 186                while (isspace(*s1) && (s1 <= last1))
 187                        s1++;
 188                while (isspace(*s2) && (s2 <= last2))
 189                        s2++;
 190        }
 191        /* early return if both lines are empty */
 192        if ((s1 > last1) && (s2 > last2))
 193                return 1;
 194        while (!result) {
 195                result = *s1++ - *s2++;
 196                /*
 197                 * Skip whitespace inside. We check for whitespace on
 198                 * both buffers because we don't want "a b" to match
 199                 * "ab"
 200                 */
 201                if (isspace(*s1) && isspace(*s2)) {
 202                        while (isspace(*s1) && s1 <= last1)
 203                                s1++;
 204                        while (isspace(*s2) && s2 <= last2)
 205                                s2++;
 206                }
 207                /*
 208                 * If we reached the end on one side only,
 209                 * lines don't match
 210                 */
 211                if (
 212                    ((s2 > last2) && (s1 <= last1)) ||
 213                    ((s1 > last1) && (s2 <= last2)))
 214                        return 0;
 215                if ((s1 > last1) && (s2 > last2))
 216                        break;
 217        }
 218
 219        return !result;
 220}
 221
 222static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
 223{
 224        ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
 225        img->line_allocated[img->nr].len = len;
 226        img->line_allocated[img->nr].hash = hash_line(bol, len);
 227        img->line_allocated[img->nr].flag = flag;
 228        img->nr++;
 229}
 230
 231/*
 232 * "buf" has the file contents to be patched (read from various sources).
 233 * attach it to "image" and add line-based index to it.
 234 * "image" now owns the "buf".
 235 */
 236static void prepare_image(struct image *image, char *buf, size_t len,
 237                          int prepare_linetable)
 238{
 239        const char *cp, *ep;
 240
 241        memset(image, 0, sizeof(*image));
 242        image->buf = buf;
 243        image->len = len;
 244
 245        if (!prepare_linetable)
 246                return;
 247
 248        ep = image->buf + image->len;
 249        cp = image->buf;
 250        while (cp < ep) {
 251                const char *next;
 252                for (next = cp; next < ep && *next != '\n'; next++)
 253                        ;
 254                if (next < ep)
 255                        next++;
 256                add_line_info(image, cp, next - cp, 0);
 257                cp = next;
 258        }
 259        image->line = image->line_allocated;
 260}
 261
 262static void clear_image(struct image *image)
 263{
 264        free(image->buf);
 265        free(image->line_allocated);
 266        memset(image, 0, sizeof(*image));
 267}
 268
 269/* fmt must contain _one_ %s and no other substitution */
 270static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
 271{
 272        struct strbuf sb = STRBUF_INIT;
 273
 274        if (patch->old_name && patch->new_name &&
 275            strcmp(patch->old_name, patch->new_name)) {
 276                quote_c_style(patch->old_name, &sb, NULL, 0);
 277                strbuf_addstr(&sb, " => ");
 278                quote_c_style(patch->new_name, &sb, NULL, 0);
 279        } else {
 280                const char *n = patch->new_name;
 281                if (!n)
 282                        n = patch->old_name;
 283                quote_c_style(n, &sb, NULL, 0);
 284        }
 285        fprintf(output, fmt, sb.buf);
 286        fputc('\n', output);
 287        strbuf_release(&sb);
 288}
 289
 290#define SLOP (16)
 291
 292static int read_patch_file(struct strbuf *sb, int fd)
 293{
 294        if (strbuf_read(sb, fd, 0) < 0)
 295                return error_errno("git apply: failed to read");
 296
 297        /*
 298         * Make sure that we have some slop in the buffer
 299         * so that we can do speculative "memcmp" etc, and
 300         * see to it that it is NUL-filled.
 301         */
 302        strbuf_grow(sb, SLOP);
 303        memset(sb->buf + sb->len, 0, SLOP);
 304        return 0;
 305}
 306
 307static unsigned long linelen(const char *buffer, unsigned long size)
 308{
 309        unsigned long len = 0;
 310        while (size--) {
 311                len++;
 312                if (*buffer++ == '\n')
 313                        break;
 314        }
 315        return len;
 316}
 317
 318static int is_dev_null(const char *str)
 319{
 320        return skip_prefix(str, "/dev/null", &str) && isspace(*str);
 321}
 322
 323#define TERM_SPACE      1
 324#define TERM_TAB        2
 325
 326static int name_terminate(int c, int terminate)
 327{
 328        if (c == ' ' && !(terminate & TERM_SPACE))
 329                return 0;
 330        if (c == '\t' && !(terminate & TERM_TAB))
 331                return 0;
 332
 333        return 1;
 334}
 335
 336/* remove double slashes to make --index work with such filenames */
 337static char *squash_slash(char *name)
 338{
 339        int i = 0, j = 0;
 340
 341        if (!name)
 342                return NULL;
 343
 344        while (name[i]) {
 345                if ((name[j++] = name[i++]) == '/')
 346                        while (name[i] == '/')
 347                                i++;
 348        }
 349        name[j] = '\0';
 350        return name;
 351}
 352
 353static char *find_name_gnu(struct apply_state *state,
 354                           const char *line,
 355                           const char *def,
 356                           int p_value)
 357{
 358        struct strbuf name = STRBUF_INIT;
 359        char *cp;
 360
 361        /*
 362         * Proposed "new-style" GNU patch/diff format; see
 363         * http://marc.info/?l=git&m=112927316408690&w=2
 364         */
 365        if (unquote_c_style(&name, line, NULL)) {
 366                strbuf_release(&name);
 367                return NULL;
 368        }
 369
 370        for (cp = name.buf; p_value; p_value--) {
 371                cp = strchr(cp, '/');
 372                if (!cp) {
 373                        strbuf_release(&name);
 374                        return NULL;
 375                }
 376                cp++;
 377        }
 378
 379        strbuf_remove(&name, 0, cp - name.buf);
 380        if (state->root.len)
 381                strbuf_insert(&name, 0, state->root.buf, state->root.len);
 382        return squash_slash(strbuf_detach(&name, NULL));
 383}
 384
 385static size_t sane_tz_len(const char *line, size_t len)
 386{
 387        const char *tz, *p;
 388
 389        if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
 390                return 0;
 391        tz = line + len - strlen(" +0500");
 392
 393        if (tz[1] != '+' && tz[1] != '-')
 394                return 0;
 395
 396        for (p = tz + 2; p != line + len; p++)
 397                if (!isdigit(*p))
 398                        return 0;
 399
 400        return line + len - tz;
 401}
 402
 403static size_t tz_with_colon_len(const char *line, size_t len)
 404{
 405        const char *tz, *p;
 406
 407        if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
 408                return 0;
 409        tz = line + len - strlen(" +08:00");
 410
 411        if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
 412                return 0;
 413        p = tz + 2;
 414        if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 415            !isdigit(*p++) || !isdigit(*p++))
 416                return 0;
 417
 418        return line + len - tz;
 419}
 420
 421static size_t date_len(const char *line, size_t len)
 422{
 423        const char *date, *p;
 424
 425        if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
 426                return 0;
 427        p = date = line + len - strlen("72-02-05");
 428
 429        if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
 430            !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
 431            !isdigit(*p++) || !isdigit(*p++))   /* Not a date. */
 432                return 0;
 433
 434        if (date - line >= strlen("19") &&
 435            isdigit(date[-1]) && isdigit(date[-2]))     /* 4-digit year */
 436                date -= strlen("19");
 437
 438        return line + len - date;
 439}
 440
 441static size_t short_time_len(const char *line, size_t len)
 442{
 443        const char *time, *p;
 444
 445        if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
 446                return 0;
 447        p = time = line + len - strlen(" 07:01:32");
 448
 449        /* Permit 1-digit hours? */
 450        if (*p++ != ' ' ||
 451            !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 452            !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 453            !isdigit(*p++) || !isdigit(*p++))   /* Not a time. */
 454                return 0;
 455
 456        return line + len - time;
 457}
 458
 459static size_t fractional_time_len(const char *line, size_t len)
 460{
 461        const char *p;
 462        size_t n;
 463
 464        /* Expected format: 19:41:17.620000023 */
 465        if (!len || !isdigit(line[len - 1]))
 466                return 0;
 467        p = line + len - 1;
 468
 469        /* Fractional seconds. */
 470        while (p > line && isdigit(*p))
 471                p--;
 472        if (*p != '.')
 473                return 0;
 474
 475        /* Hours, minutes, and whole seconds. */
 476        n = short_time_len(line, p - line);
 477        if (!n)
 478                return 0;
 479
 480        return line + len - p + n;
 481}
 482
 483static size_t trailing_spaces_len(const char *line, size_t len)
 484{
 485        const char *p;
 486
 487        /* Expected format: ' ' x (1 or more)  */
 488        if (!len || line[len - 1] != ' ')
 489                return 0;
 490
 491        p = line + len;
 492        while (p != line) {
 493                p--;
 494                if (*p != ' ')
 495                        return line + len - (p + 1);
 496        }
 497
 498        /* All spaces! */
 499        return len;
 500}
 501
 502static size_t diff_timestamp_len(const char *line, size_t len)
 503{
 504        const char *end = line + len;
 505        size_t n;
 506
 507        /*
 508         * Posix: 2010-07-05 19:41:17
 509         * GNU: 2010-07-05 19:41:17.620000023 -0500
 510         */
 511
 512        if (!isdigit(end[-1]))
 513                return 0;
 514
 515        n = sane_tz_len(line, end - line);
 516        if (!n)
 517                n = tz_with_colon_len(line, end - line);
 518        end -= n;
 519
 520        n = short_time_len(line, end - line);
 521        if (!n)
 522                n = fractional_time_len(line, end - line);
 523        end -= n;
 524
 525        n = date_len(line, end - line);
 526        if (!n) /* No date.  Too bad. */
 527                return 0;
 528        end -= n;
 529
 530        if (end == line)        /* No space before date. */
 531                return 0;
 532        if (end[-1] == '\t') {  /* Success! */
 533                end--;
 534                return line + len - end;
 535        }
 536        if (end[-1] != ' ')     /* No space before date. */
 537                return 0;
 538
 539        /* Whitespace damage. */
 540        end -= trailing_spaces_len(line, end - line);
 541        return line + len - end;
 542}
 543
 544static char *find_name_common(struct apply_state *state,
 545                              const char *line,
 546                              const char *def,
 547                              int p_value,
 548                              const char *end,
 549                              int terminate)
 550{
 551        int len;
 552        const char *start = NULL;
 553
 554        if (p_value == 0)
 555                start = line;
 556        while (line != end) {
 557                char c = *line;
 558
 559                if (!end && isspace(c)) {
 560                        if (c == '\n')
 561                                break;
 562                        if (name_terminate(c, terminate))
 563                                break;
 564                }
 565                line++;
 566                if (c == '/' && !--p_value)
 567                        start = line;
 568        }
 569        if (!start)
 570                return squash_slash(xstrdup_or_null(def));
 571        len = line - start;
 572        if (!len)
 573                return squash_slash(xstrdup_or_null(def));
 574
 575        /*
 576         * Generally we prefer the shorter name, especially
 577         * if the other one is just a variation of that with
 578         * something else tacked on to the end (ie "file.orig"
 579         * or "file~").
 580         */
 581        if (def) {
 582                int deflen = strlen(def);
 583                if (deflen < len && !strncmp(start, def, deflen))
 584                        return squash_slash(xstrdup(def));
 585        }
 586
 587        if (state->root.len) {
 588                char *ret = xstrfmt("%s%.*s", state->root.buf, len, start);
 589                return squash_slash(ret);
 590        }
 591
 592        return squash_slash(xmemdupz(start, len));
 593}
 594
 595static char *find_name(struct apply_state *state,
 596                       const char *line,
 597                       char *def,
 598                       int p_value,
 599                       int terminate)
 600{
 601        if (*line == '"') {
 602                char *name = find_name_gnu(state, line, def, p_value);
 603                if (name)
 604                        return name;
 605        }
 606
 607        return find_name_common(state, line, def, p_value, NULL, terminate);
 608}
 609
 610static char *find_name_traditional(struct apply_state *state,
 611                                   const char *line,
 612                                   char *def,
 613                                   int p_value)
 614{
 615        size_t len;
 616        size_t date_len;
 617
 618        if (*line == '"') {
 619                char *name = find_name_gnu(state, line, def, p_value);
 620                if (name)
 621                        return name;
 622        }
 623
 624        len = strchrnul(line, '\n') - line;
 625        date_len = diff_timestamp_len(line, len);
 626        if (!date_len)
 627                return find_name_common(state, line, def, p_value, NULL, TERM_TAB);
 628        len -= date_len;
 629
 630        return find_name_common(state, line, def, p_value, line + len, 0);
 631}
 632
 633static int count_slashes(const char *cp)
 634{
 635        int cnt = 0;
 636        char ch;
 637
 638        while ((ch = *cp++))
 639                if (ch == '/')
 640                        cnt++;
 641        return cnt;
 642}
 643
 644/*
 645 * Given the string after "--- " or "+++ ", guess the appropriate
 646 * p_value for the given patch.
 647 */
 648static int guess_p_value(struct apply_state *state, const char *nameline)
 649{
 650        char *name, *cp;
 651        int val = -1;
 652
 653        if (is_dev_null(nameline))
 654                return -1;
 655        name = find_name_traditional(state, nameline, NULL, 0);
 656        if (!name)
 657                return -1;
 658        cp = strchr(name, '/');
 659        if (!cp)
 660                val = 0;
 661        else if (state->prefix) {
 662                /*
 663                 * Does it begin with "a/$our-prefix" and such?  Then this is
 664                 * very likely to apply to our directory.
 665                 */
 666                if (!strncmp(name, state->prefix, state->prefix_length))
 667                        val = count_slashes(state->prefix);
 668                else {
 669                        cp++;
 670                        if (!strncmp(cp, state->prefix, state->prefix_length))
 671                                val = count_slashes(state->prefix) + 1;
 672                }
 673        }
 674        free(name);
 675        return val;
 676}
 677
 678/*
 679 * Does the ---/+++ line have the POSIX timestamp after the last HT?
 680 * GNU diff puts epoch there to signal a creation/deletion event.  Is
 681 * this such a timestamp?
 682 */
 683static int has_epoch_timestamp(const char *nameline)
 684{
 685        /*
 686         * We are only interested in epoch timestamp; any non-zero
 687         * fraction cannot be one, hence "(\.0+)?" in the regexp below.
 688         * For the same reason, the date must be either 1969-12-31 or
 689         * 1970-01-01, and the seconds part must be "00".
 690         */
 691        const char stamp_regexp[] =
 692                "^(1969-12-31|1970-01-01)"
 693                " "
 694                "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
 695                " "
 696                "([-+][0-2][0-9]:?[0-5][0-9])\n";
 697        const char *timestamp = NULL, *cp, *colon;
 698        static regex_t *stamp;
 699        regmatch_t m[10];
 700        int zoneoffset;
 701        int hourminute;
 702        int status;
 703
 704        for (cp = nameline; *cp != '\n'; cp++) {
 705                if (*cp == '\t')
 706                        timestamp = cp + 1;
 707        }
 708        if (!timestamp)
 709                return 0;
 710        if (!stamp) {
 711                stamp = xmalloc(sizeof(*stamp));
 712                if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
 713                        warning(_("Cannot prepare timestamp regexp %s"),
 714                                stamp_regexp);
 715                        return 0;
 716                }
 717        }
 718
 719        status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
 720        if (status) {
 721                if (status != REG_NOMATCH)
 722                        warning(_("regexec returned %d for input: %s"),
 723                                status, timestamp);
 724                return 0;
 725        }
 726
 727        zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
 728        if (*colon == ':')
 729                zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
 730        else
 731                zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
 732        if (timestamp[m[3].rm_so] == '-')
 733                zoneoffset = -zoneoffset;
 734
 735        /*
 736         * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
 737         * (west of GMT) or 1970-01-01 (east of GMT)
 738         */
 739        if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
 740            (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
 741                return 0;
 742
 743        hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
 744                      strtol(timestamp + 14, NULL, 10) -
 745                      zoneoffset);
 746
 747        return ((zoneoffset < 0 && hourminute == 1440) ||
 748                (0 <= zoneoffset && !hourminute));
 749}
 750
 751/*
 752 * Get the name etc info from the ---/+++ lines of a traditional patch header
 753 *
 754 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
 755 * files, we can happily check the index for a match, but for creating a
 756 * new file we should try to match whatever "patch" does. I have no idea.
 757 */
 758static int parse_traditional_patch(struct apply_state *state,
 759                                   const char *first,
 760                                   const char *second,
 761                                   struct patch *patch)
 762{
 763        char *name;
 764
 765        first += 4;     /* skip "--- " */
 766        second += 4;    /* skip "+++ " */
 767        if (!state->p_value_known) {
 768                int p, q;
 769                p = guess_p_value(state, first);
 770                q = guess_p_value(state, second);
 771                if (p < 0) p = q;
 772                if (0 <= p && p == q) {
 773                        state->p_value = p;
 774                        state->p_value_known = 1;
 775                }
 776        }
 777        if (is_dev_null(first)) {
 778                patch->is_new = 1;
 779                patch->is_delete = 0;
 780                name = find_name_traditional(state, second, NULL, state->p_value);
 781                patch->new_name = name;
 782        } else if (is_dev_null(second)) {
 783                patch->is_new = 0;
 784                patch->is_delete = 1;
 785                name = find_name_traditional(state, first, NULL, state->p_value);
 786                patch->old_name = name;
 787        } else {
 788                char *first_name;
 789                first_name = find_name_traditional(state, first, NULL, state->p_value);
 790                name = find_name_traditional(state, second, first_name, state->p_value);
 791                free(first_name);
 792                if (has_epoch_timestamp(first)) {
 793                        patch->is_new = 1;
 794                        patch->is_delete = 0;
 795                        patch->new_name = name;
 796                } else if (has_epoch_timestamp(second)) {
 797                        patch->is_new = 0;
 798                        patch->is_delete = 1;
 799                        patch->old_name = name;
 800                } else {
 801                        patch->old_name = name;
 802                        patch->new_name = xstrdup_or_null(name);
 803                }
 804        }
 805        if (!name)
 806                return error(_("unable to find filename in patch at line %d"), state->linenr);
 807
 808        return 0;
 809}
 810
 811static int gitdiff_hdrend(struct apply_state *state,
 812                          const char *line,
 813                          struct patch *patch)
 814{
 815        return -1;
 816}
 817
 818/*
 819 * We're anal about diff header consistency, to make
 820 * sure that we don't end up having strange ambiguous
 821 * patches floating around.
 822 *
 823 * As a result, gitdiff_{old|new}name() will check
 824 * their names against any previous information, just
 825 * to make sure..
 826 */
 827#define DIFF_OLD_NAME 0
 828#define DIFF_NEW_NAME 1
 829
 830static void gitdiff_verify_name(struct apply_state *state,
 831                                const char *line,
 832                                int isnull,
 833                                char **name,
 834                                int side)
 835{
 836        if (!*name && !isnull) {
 837                *name = find_name(state, line, NULL, state->p_value, TERM_TAB);
 838                return;
 839        }
 840
 841        if (*name) {
 842                int len = strlen(*name);
 843                char *another;
 844                if (isnull)
 845                        die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
 846                            *name, state->linenr);
 847                another = find_name(state, line, NULL, state->p_value, TERM_TAB);
 848                if (!another || memcmp(another, *name, len + 1))
 849                        die((side == DIFF_NEW_NAME) ?
 850                            _("git apply: bad git-diff - inconsistent new filename on line %d") :
 851                            _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
 852                free(another);
 853        } else {
 854                /* expect "/dev/null" */
 855                if (memcmp("/dev/null", line, 9) || line[9] != '\n')
 856                        die(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
 857        }
 858}
 859
 860static int gitdiff_oldname(struct apply_state *state,
 861                           const char *line,
 862                           struct patch *patch)
 863{
 864        gitdiff_verify_name(state, line,
 865                            patch->is_new, &patch->old_name,
 866                            DIFF_OLD_NAME);
 867        return 0;
 868}
 869
 870static int gitdiff_newname(struct apply_state *state,
 871                           const char *line,
 872                           struct patch *patch)
 873{
 874        gitdiff_verify_name(state, line,
 875                            patch->is_delete, &patch->new_name,
 876                            DIFF_NEW_NAME);
 877        return 0;
 878}
 879
 880static int gitdiff_oldmode(struct apply_state *state,
 881                           const char *line,
 882                           struct patch *patch)
 883{
 884        patch->old_mode = strtoul(line, NULL, 8);
 885        return 0;
 886}
 887
 888static int gitdiff_newmode(struct apply_state *state,
 889                           const char *line,
 890                           struct patch *patch)
 891{
 892        patch->new_mode = strtoul(line, NULL, 8);
 893        return 0;
 894}
 895
 896static int gitdiff_delete(struct apply_state *state,
 897                          const char *line,
 898                          struct patch *patch)
 899{
 900        patch->is_delete = 1;
 901        free(patch->old_name);
 902        patch->old_name = xstrdup_or_null(patch->def_name);
 903        return gitdiff_oldmode(state, line, patch);
 904}
 905
 906static int gitdiff_newfile(struct apply_state *state,
 907                           const char *line,
 908                           struct patch *patch)
 909{
 910        patch->is_new = 1;
 911        free(patch->new_name);
 912        patch->new_name = xstrdup_or_null(patch->def_name);
 913        return gitdiff_newmode(state, line, patch);
 914}
 915
 916static int gitdiff_copysrc(struct apply_state *state,
 917                           const char *line,
 918                           struct patch *patch)
 919{
 920        patch->is_copy = 1;
 921        free(patch->old_name);
 922        patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
 923        return 0;
 924}
 925
 926static int gitdiff_copydst(struct apply_state *state,
 927                           const char *line,
 928                           struct patch *patch)
 929{
 930        patch->is_copy = 1;
 931        free(patch->new_name);
 932        patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
 933        return 0;
 934}
 935
 936static int gitdiff_renamesrc(struct apply_state *state,
 937                             const char *line,
 938                             struct patch *patch)
 939{
 940        patch->is_rename = 1;
 941        free(patch->old_name);
 942        patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
 943        return 0;
 944}
 945
 946static int gitdiff_renamedst(struct apply_state *state,
 947                             const char *line,
 948                             struct patch *patch)
 949{
 950        patch->is_rename = 1;
 951        free(patch->new_name);
 952        patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
 953        return 0;
 954}
 955
 956static int gitdiff_similarity(struct apply_state *state,
 957                              const char *line,
 958                              struct patch *patch)
 959{
 960        unsigned long val = strtoul(line, NULL, 10);
 961        if (val <= 100)
 962                patch->score = val;
 963        return 0;
 964}
 965
 966static int gitdiff_dissimilarity(struct apply_state *state,
 967                                 const char *line,
 968                                 struct patch *patch)
 969{
 970        unsigned long val = strtoul(line, NULL, 10);
 971        if (val <= 100)
 972                patch->score = val;
 973        return 0;
 974}
 975
 976static int gitdiff_index(struct apply_state *state,
 977                         const char *line,
 978                         struct patch *patch)
 979{
 980        /*
 981         * index line is N hexadecimal, "..", N hexadecimal,
 982         * and optional space with octal mode.
 983         */
 984        const char *ptr, *eol;
 985        int len;
 986
 987        ptr = strchr(line, '.');
 988        if (!ptr || ptr[1] != '.' || 40 < ptr - line)
 989                return 0;
 990        len = ptr - line;
 991        memcpy(patch->old_sha1_prefix, line, len);
 992        patch->old_sha1_prefix[len] = 0;
 993
 994        line = ptr + 2;
 995        ptr = strchr(line, ' ');
 996        eol = strchrnul(line, '\n');
 997
 998        if (!ptr || eol < ptr)
 999                ptr = eol;
1000        len = ptr - line;
1001
1002        if (40 < len)
1003                return 0;
1004        memcpy(patch->new_sha1_prefix, line, len);
1005        patch->new_sha1_prefix[len] = 0;
1006        if (*ptr == ' ')
1007                patch->old_mode = strtoul(ptr+1, NULL, 8);
1008        return 0;
1009}
1010
1011/*
1012 * This is normal for a diff that doesn't change anything: we'll fall through
1013 * into the next diff. Tell the parser to break out.
1014 */
1015static int gitdiff_unrecognized(struct apply_state *state,
1016                                const char *line,
1017                                struct patch *patch)
1018{
1019        return -1;
1020}
1021
1022/*
1023 * Skip p_value leading components from "line"; as we do not accept
1024 * absolute paths, return NULL in that case.
1025 */
1026static const char *skip_tree_prefix(struct apply_state *state,
1027                                    const char *line,
1028                                    int llen)
1029{
1030        int nslash;
1031        int i;
1032
1033        if (!state->p_value)
1034                return (llen && line[0] == '/') ? NULL : line;
1035
1036        nslash = state->p_value;
1037        for (i = 0; i < llen; i++) {
1038                int ch = line[i];
1039                if (ch == '/' && --nslash <= 0)
1040                        return (i == 0) ? NULL : &line[i + 1];
1041        }
1042        return NULL;
1043}
1044
1045/*
1046 * This is to extract the same name that appears on "diff --git"
1047 * line.  We do not find and return anything if it is a rename
1048 * patch, and it is OK because we will find the name elsewhere.
1049 * We need to reliably find name only when it is mode-change only,
1050 * creation or deletion of an empty file.  In any of these cases,
1051 * both sides are the same name under a/ and b/ respectively.
1052 */
1053static char *git_header_name(struct apply_state *state,
1054                             const char *line,
1055                             int llen)
1056{
1057        const char *name;
1058        const char *second = NULL;
1059        size_t len, line_len;
1060
1061        line += strlen("diff --git ");
1062        llen -= strlen("diff --git ");
1063
1064        if (*line == '"') {
1065                const char *cp;
1066                struct strbuf first = STRBUF_INIT;
1067                struct strbuf sp = STRBUF_INIT;
1068
1069                if (unquote_c_style(&first, line, &second))
1070                        goto free_and_fail1;
1071
1072                /* strip the a/b prefix including trailing slash */
1073                cp = skip_tree_prefix(state, first.buf, first.len);
1074                if (!cp)
1075                        goto free_and_fail1;
1076                strbuf_remove(&first, 0, cp - first.buf);
1077
1078                /*
1079                 * second points at one past closing dq of name.
1080                 * find the second name.
1081                 */
1082                while ((second < line + llen) && isspace(*second))
1083                        second++;
1084
1085                if (line + llen <= second)
1086                        goto free_and_fail1;
1087                if (*second == '"') {
1088                        if (unquote_c_style(&sp, second, NULL))
1089                                goto free_and_fail1;
1090                        cp = skip_tree_prefix(state, sp.buf, sp.len);
1091                        if (!cp)
1092                                goto free_and_fail1;
1093                        /* They must match, otherwise ignore */
1094                        if (strcmp(cp, first.buf))
1095                                goto free_and_fail1;
1096                        strbuf_release(&sp);
1097                        return strbuf_detach(&first, NULL);
1098                }
1099
1100                /* unquoted second */
1101                cp = skip_tree_prefix(state, second, line + llen - second);
1102                if (!cp)
1103                        goto free_and_fail1;
1104                if (line + llen - cp != first.len ||
1105                    memcmp(first.buf, cp, first.len))
1106                        goto free_and_fail1;
1107                return strbuf_detach(&first, NULL);
1108
1109        free_and_fail1:
1110                strbuf_release(&first);
1111                strbuf_release(&sp);
1112                return NULL;
1113        }
1114
1115        /* unquoted first name */
1116        name = skip_tree_prefix(state, line, llen);
1117        if (!name)
1118                return NULL;
1119
1120        /*
1121         * since the first name is unquoted, a dq if exists must be
1122         * the beginning of the second name.
1123         */
1124        for (second = name; second < line + llen; second++) {
1125                if (*second == '"') {
1126                        struct strbuf sp = STRBUF_INIT;
1127                        const char *np;
1128
1129                        if (unquote_c_style(&sp, second, NULL))
1130                                goto free_and_fail2;
1131
1132                        np = skip_tree_prefix(state, sp.buf, sp.len);
1133                        if (!np)
1134                                goto free_and_fail2;
1135
1136                        len = sp.buf + sp.len - np;
1137                        if (len < second - name &&
1138                            !strncmp(np, name, len) &&
1139                            isspace(name[len])) {
1140                                /* Good */
1141                                strbuf_remove(&sp, 0, np - sp.buf);
1142                                return strbuf_detach(&sp, NULL);
1143                        }
1144
1145                free_and_fail2:
1146                        strbuf_release(&sp);
1147                        return NULL;
1148                }
1149        }
1150
1151        /*
1152         * Accept a name only if it shows up twice, exactly the same
1153         * form.
1154         */
1155        second = strchr(name, '\n');
1156        if (!second)
1157                return NULL;
1158        line_len = second - name;
1159        for (len = 0 ; ; len++) {
1160                switch (name[len]) {
1161                default:
1162                        continue;
1163                case '\n':
1164                        return NULL;
1165                case '\t': case ' ':
1166                        /*
1167                         * Is this the separator between the preimage
1168                         * and the postimage pathname?  Again, we are
1169                         * only interested in the case where there is
1170                         * no rename, as this is only to set def_name
1171                         * and a rename patch has the names elsewhere
1172                         * in an unambiguous form.
1173                         */
1174                        if (!name[len + 1])
1175                                return NULL; /* no postimage name */
1176                        second = skip_tree_prefix(state, name + len + 1,
1177                                                  line_len - (len + 1));
1178                        if (!second)
1179                                return NULL;
1180                        /*
1181                         * Does len bytes starting at "name" and "second"
1182                         * (that are separated by one HT or SP we just
1183                         * found) exactly match?
1184                         */
1185                        if (second[len] == '\n' && !strncmp(name, second, len))
1186                                return xmemdupz(name, len);
1187                }
1188        }
1189}
1190
1191/* Verify that we recognize the lines following a git header */
1192static int parse_git_header(struct apply_state *state,
1193                            const char *line,
1194                            int len,
1195                            unsigned int size,
1196                            struct patch *patch)
1197{
1198        unsigned long offset;
1199
1200        /* A git diff has explicit new/delete information, so we don't guess */
1201        patch->is_new = 0;
1202        patch->is_delete = 0;
1203
1204        /*
1205         * Some things may not have the old name in the
1206         * rest of the headers anywhere (pure mode changes,
1207         * or removing or adding empty files), so we get
1208         * the default name from the header.
1209         */
1210        patch->def_name = git_header_name(state, line, len);
1211        if (patch->def_name && state->root.len) {
1212                char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);
1213                free(patch->def_name);
1214                patch->def_name = s;
1215        }
1216
1217        line += len;
1218        size -= len;
1219        state->linenr++;
1220        for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state->linenr++) {
1221                static const struct opentry {
1222                        const char *str;
1223                        int (*fn)(struct apply_state *, const char *, struct patch *);
1224                } optable[] = {
1225                        { "@@ -", gitdiff_hdrend },
1226                        { "--- ", gitdiff_oldname },
1227                        { "+++ ", gitdiff_newname },
1228                        { "old mode ", gitdiff_oldmode },
1229                        { "new mode ", gitdiff_newmode },
1230                        { "deleted file mode ", gitdiff_delete },
1231                        { "new file mode ", gitdiff_newfile },
1232                        { "copy from ", gitdiff_copysrc },
1233                        { "copy to ", gitdiff_copydst },
1234                        { "rename old ", gitdiff_renamesrc },
1235                        { "rename new ", gitdiff_renamedst },
1236                        { "rename from ", gitdiff_renamesrc },
1237                        { "rename to ", gitdiff_renamedst },
1238                        { "similarity index ", gitdiff_similarity },
1239                        { "dissimilarity index ", gitdiff_dissimilarity },
1240                        { "index ", gitdiff_index },
1241                        { "", gitdiff_unrecognized },
1242                };
1243                int i;
1244
1245                len = linelen(line, size);
1246                if (!len || line[len-1] != '\n')
1247                        break;
1248                for (i = 0; i < ARRAY_SIZE(optable); i++) {
1249                        const struct opentry *p = optable + i;
1250                        int oplen = strlen(p->str);
1251                        if (len < oplen || memcmp(p->str, line, oplen))
1252                                continue;
1253                        if (p->fn(state, line + oplen, patch) < 0)
1254                                return offset;
1255                        break;
1256                }
1257        }
1258
1259        return offset;
1260}
1261
1262static int parse_num(const char *line, unsigned long *p)
1263{
1264        char *ptr;
1265
1266        if (!isdigit(*line))
1267                return 0;
1268        *p = strtoul(line, &ptr, 10);
1269        return ptr - line;
1270}
1271
1272static int parse_range(const char *line, int len, int offset, const char *expect,
1273                       unsigned long *p1, unsigned long *p2)
1274{
1275        int digits, ex;
1276
1277        if (offset < 0 || offset >= len)
1278                return -1;
1279        line += offset;
1280        len -= offset;
1281
1282        digits = parse_num(line, p1);
1283        if (!digits)
1284                return -1;
1285
1286        offset += digits;
1287        line += digits;
1288        len -= digits;
1289
1290        *p2 = 1;
1291        if (*line == ',') {
1292                digits = parse_num(line+1, p2);
1293                if (!digits)
1294                        return -1;
1295
1296                offset += digits+1;
1297                line += digits+1;
1298                len -= digits+1;
1299        }
1300
1301        ex = strlen(expect);
1302        if (ex > len)
1303                return -1;
1304        if (memcmp(line, expect, ex))
1305                return -1;
1306
1307        return offset + ex;
1308}
1309
1310static void recount_diff(const char *line, int size, struct fragment *fragment)
1311{
1312        int oldlines = 0, newlines = 0, ret = 0;
1313
1314        if (size < 1) {
1315                warning("recount: ignore empty hunk");
1316                return;
1317        }
1318
1319        for (;;) {
1320                int len = linelen(line, size);
1321                size -= len;
1322                line += len;
1323
1324                if (size < 1)
1325                        break;
1326
1327                switch (*line) {
1328                case ' ': case '\n':
1329                        newlines++;
1330                        /* fall through */
1331                case '-':
1332                        oldlines++;
1333                        continue;
1334                case '+':
1335                        newlines++;
1336                        continue;
1337                case '\\':
1338                        continue;
1339                case '@':
1340                        ret = size < 3 || !starts_with(line, "@@ ");
1341                        break;
1342                case 'd':
1343                        ret = size < 5 || !starts_with(line, "diff ");
1344                        break;
1345                default:
1346                        ret = -1;
1347                        break;
1348                }
1349                if (ret) {
1350                        warning(_("recount: unexpected line: %.*s"),
1351                                (int)linelen(line, size), line);
1352                        return;
1353                }
1354                break;
1355        }
1356        fragment->oldlines = oldlines;
1357        fragment->newlines = newlines;
1358}
1359
1360/*
1361 * Parse a unified diff fragment header of the
1362 * form "@@ -a,b +c,d @@"
1363 */
1364static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1365{
1366        int offset;
1367
1368        if (!len || line[len-1] != '\n')
1369                return -1;
1370
1371        /* Figure out the number of lines in a fragment */
1372        offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1373        offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1374
1375        return offset;
1376}
1377
1378/*
1379 * Find file diff header
1380 *
1381 * Returns:
1382 *  -1 if no header was found
1383 *  -128 in case of error
1384 *   the size of the header in bytes (called "offset") otherwise
1385 */
1386static int find_header(struct apply_state *state,
1387                       const char *line,
1388                       unsigned long size,
1389                       int *hdrsize,
1390                       struct patch *patch)
1391{
1392        unsigned long offset, len;
1393
1394        patch->is_toplevel_relative = 0;
1395        patch->is_rename = patch->is_copy = 0;
1396        patch->is_new = patch->is_delete = -1;
1397        patch->old_mode = patch->new_mode = 0;
1398        patch->old_name = patch->new_name = NULL;
1399        for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1400                unsigned long nextlen;
1401
1402                len = linelen(line, size);
1403                if (!len)
1404                        break;
1405
1406                /* Testing this early allows us to take a few shortcuts.. */
1407                if (len < 6)
1408                        continue;
1409
1410                /*
1411                 * Make sure we don't find any unconnected patch fragments.
1412                 * That's a sign that we didn't find a header, and that a
1413                 * patch has become corrupted/broken up.
1414                 */
1415                if (!memcmp("@@ -", line, 4)) {
1416                        struct fragment dummy;
1417                        if (parse_fragment_header(line, len, &dummy) < 0)
1418                                continue;
1419                        error(_("patch fragment without header at line %d: %.*s"),
1420                                     state->linenr, (int)len-1, line);
1421                        return -128;
1422                }
1423
1424                if (size < len + 6)
1425                        break;
1426
1427                /*
1428                 * Git patch? It might not have a real patch, just a rename
1429                 * or mode change, so we handle that specially
1430                 */
1431                if (!memcmp("diff --git ", line, 11)) {
1432                        int git_hdr_len = parse_git_header(state, line, len, size, patch);
1433                        if (git_hdr_len <= len)
1434                                continue;
1435                        if (!patch->old_name && !patch->new_name) {
1436                                if (!patch->def_name) {
1437                                        error(Q_("git diff header lacks filename information when removing "
1438                                                        "%d leading pathname component (line %d)",
1439                                                        "git diff header lacks filename information when removing "
1440                                                        "%d leading pathname components (line %d)",
1441                                                        state->p_value),
1442                                                     state->p_value, state->linenr);
1443                                        return -128;
1444                                }
1445                                patch->old_name = xstrdup(patch->def_name);
1446                                patch->new_name = xstrdup(patch->def_name);
1447                        }
1448                        if (!patch->is_delete && !patch->new_name) {
1449                                error("git diff header lacks filename information "
1450                                             "(line %d)", state->linenr);
1451                                return -128;
1452                        }
1453                        patch->is_toplevel_relative = 1;
1454                        *hdrsize = git_hdr_len;
1455                        return offset;
1456                }
1457
1458                /* --- followed by +++ ? */
1459                if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
1460                        continue;
1461
1462                /*
1463                 * We only accept unified patches, so we want it to
1464                 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1465                 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1466                 */
1467                nextlen = linelen(line + len, size - len);
1468                if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1469                        continue;
1470
1471                /* Ok, we'll consider it a patch */
1472                if (parse_traditional_patch(state, line, line+len, patch))
1473                        return -128;
1474                *hdrsize = len + nextlen;
1475                state->linenr += 2;
1476                return offset;
1477        }
1478        return -1;
1479}
1480
1481static void record_ws_error(struct apply_state *state,
1482                            unsigned result,
1483                            const char *line,
1484                            int len,
1485                            int linenr)
1486{
1487        char *err;
1488
1489        if (!result)
1490                return;
1491
1492        state->whitespace_error++;
1493        if (state->squelch_whitespace_errors &&
1494            state->squelch_whitespace_errors < state->whitespace_error)
1495                return;
1496
1497        err = whitespace_error_string(result);
1498        fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1499                state->patch_input_file, linenr, err, len, line);
1500        free(err);
1501}
1502
1503static void check_whitespace(struct apply_state *state,
1504                             const char *line,
1505                             int len,
1506                             unsigned ws_rule)
1507{
1508        unsigned result = ws_check(line + 1, len - 1, ws_rule);
1509
1510        record_ws_error(state, result, line + 1, len - 2, state->linenr);
1511}
1512
1513/*
1514 * Parse a unified diff. Note that this really needs to parse each
1515 * fragment separately, since the only way to know the difference
1516 * between a "---" that is part of a patch, and a "---" that starts
1517 * the next patch is to look at the line counts..
1518 */
1519static int parse_fragment(struct apply_state *state,
1520                          const char *line,
1521                          unsigned long size,
1522                          struct patch *patch,
1523                          struct fragment *fragment)
1524{
1525        int added, deleted;
1526        int len = linelen(line, size), offset;
1527        unsigned long oldlines, newlines;
1528        unsigned long leading, trailing;
1529
1530        offset = parse_fragment_header(line, len, fragment);
1531        if (offset < 0)
1532                return -1;
1533        if (offset > 0 && patch->recount)
1534                recount_diff(line + offset, size - offset, fragment);
1535        oldlines = fragment->oldlines;
1536        newlines = fragment->newlines;
1537        leading = 0;
1538        trailing = 0;
1539
1540        /* Parse the thing.. */
1541        line += len;
1542        size -= len;
1543        state->linenr++;
1544        added = deleted = 0;
1545        for (offset = len;
1546             0 < size;
1547             offset += len, size -= len, line += len, state->linenr++) {
1548                if (!oldlines && !newlines)
1549                        break;
1550                len = linelen(line, size);
1551                if (!len || line[len-1] != '\n')
1552                        return -1;
1553                switch (*line) {
1554                default:
1555                        return -1;
1556                case '\n': /* newer GNU diff, an empty context line */
1557                case ' ':
1558                        oldlines--;
1559                        newlines--;
1560                        if (!deleted && !added)
1561                                leading++;
1562                        trailing++;
1563                        if (!state->apply_in_reverse &&
1564                            state->ws_error_action == correct_ws_error)
1565                                check_whitespace(state, line, len, patch->ws_rule);
1566                        break;
1567                case '-':
1568                        if (state->apply_in_reverse &&
1569                            state->ws_error_action != nowarn_ws_error)
1570                                check_whitespace(state, line, len, patch->ws_rule);
1571                        deleted++;
1572                        oldlines--;
1573                        trailing = 0;
1574                        break;
1575                case '+':
1576                        if (!state->apply_in_reverse &&
1577                            state->ws_error_action != nowarn_ws_error)
1578                                check_whitespace(state, line, len, patch->ws_rule);
1579                        added++;
1580                        newlines--;
1581                        trailing = 0;
1582                        break;
1583
1584                /*
1585                 * We allow "\ No newline at end of file". Depending
1586                 * on locale settings when the patch was produced we
1587                 * don't know what this line looks like. The only
1588                 * thing we do know is that it begins with "\ ".
1589                 * Checking for 12 is just for sanity check -- any
1590                 * l10n of "\ No newline..." is at least that long.
1591                 */
1592                case '\\':
1593                        if (len < 12 || memcmp(line, "\\ ", 2))
1594                                return -1;
1595                        break;
1596                }
1597        }
1598        if (oldlines || newlines)
1599                return -1;
1600        if (!deleted && !added)
1601                return -1;
1602
1603        fragment->leading = leading;
1604        fragment->trailing = trailing;
1605
1606        /*
1607         * If a fragment ends with an incomplete line, we failed to include
1608         * it in the above loop because we hit oldlines == newlines == 0
1609         * before seeing it.
1610         */
1611        if (12 < size && !memcmp(line, "\\ ", 2))
1612                offset += linelen(line, size);
1613
1614        patch->lines_added += added;
1615        patch->lines_deleted += deleted;
1616
1617        if (0 < patch->is_new && oldlines)
1618                return error(_("new file depends on old contents"));
1619        if (0 < patch->is_delete && newlines)
1620                return error(_("deleted file still has contents"));
1621        return offset;
1622}
1623
1624/*
1625 * We have seen "diff --git a/... b/..." header (or a traditional patch
1626 * header).  Read hunks that belong to this patch into fragments and hang
1627 * them to the given patch structure.
1628 *
1629 * The (fragment->patch, fragment->size) pair points into the memory given
1630 * by the caller, not a copy, when we return.
1631 *
1632 * Returns:
1633 *   -1 in case of error,
1634 *   the number of bytes in the patch otherwise.
1635 */
1636static int parse_single_patch(struct apply_state *state,
1637                              const char *line,
1638                              unsigned long size,
1639                              struct patch *patch)
1640{
1641        unsigned long offset = 0;
1642        unsigned long oldlines = 0, newlines = 0, context = 0;
1643        struct fragment **fragp = &patch->fragments;
1644
1645        while (size > 4 && !memcmp(line, "@@ -", 4)) {
1646                struct fragment *fragment;
1647                int len;
1648
1649                fragment = xcalloc(1, sizeof(*fragment));
1650                fragment->linenr = state->linenr;
1651                len = parse_fragment(state, line, size, patch, fragment);
1652                if (len <= 0) {
1653                        free(fragment);
1654                        return error(_("corrupt patch at line %d"), state->linenr);
1655                }
1656                fragment->patch = line;
1657                fragment->size = len;
1658                oldlines += fragment->oldlines;
1659                newlines += fragment->newlines;
1660                context += fragment->leading + fragment->trailing;
1661
1662                *fragp = fragment;
1663                fragp = &fragment->next;
1664
1665                offset += len;
1666                line += len;
1667                size -= len;
1668        }
1669
1670        /*
1671         * If something was removed (i.e. we have old-lines) it cannot
1672         * be creation, and if something was added it cannot be
1673         * deletion.  However, the reverse is not true; --unified=0
1674         * patches that only add are not necessarily creation even
1675         * though they do not have any old lines, and ones that only
1676         * delete are not necessarily deletion.
1677         *
1678         * Unfortunately, a real creation/deletion patch do _not_ have
1679         * any context line by definition, so we cannot safely tell it
1680         * apart with --unified=0 insanity.  At least if the patch has
1681         * more than one hunk it is not creation or deletion.
1682         */
1683        if (patch->is_new < 0 &&
1684            (oldlines || (patch->fragments && patch->fragments->next)))
1685                patch->is_new = 0;
1686        if (patch->is_delete < 0 &&
1687            (newlines || (patch->fragments && patch->fragments->next)))
1688                patch->is_delete = 0;
1689
1690        if (0 < patch->is_new && oldlines)
1691                return error(_("new file %s depends on old contents"), patch->new_name);
1692        if (0 < patch->is_delete && newlines)
1693                return error(_("deleted file %s still has contents"), patch->old_name);
1694        if (!patch->is_delete && !newlines && context)
1695                fprintf_ln(stderr,
1696                           _("** warning: "
1697                             "file %s becomes empty but is not deleted"),
1698                           patch->new_name);
1699
1700        return offset;
1701}
1702
1703static inline int metadata_changes(struct patch *patch)
1704{
1705        return  patch->is_rename > 0 ||
1706                patch->is_copy > 0 ||
1707                patch->is_new > 0 ||
1708                patch->is_delete ||
1709                (patch->old_mode && patch->new_mode &&
1710                 patch->old_mode != patch->new_mode);
1711}
1712
1713static char *inflate_it(const void *data, unsigned long size,
1714                        unsigned long inflated_size)
1715{
1716        git_zstream stream;
1717        void *out;
1718        int st;
1719
1720        memset(&stream, 0, sizeof(stream));
1721
1722        stream.next_in = (unsigned char *)data;
1723        stream.avail_in = size;
1724        stream.next_out = out = xmalloc(inflated_size);
1725        stream.avail_out = inflated_size;
1726        git_inflate_init(&stream);
1727        st = git_inflate(&stream, Z_FINISH);
1728        git_inflate_end(&stream);
1729        if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1730                free(out);
1731                return NULL;
1732        }
1733        return out;
1734}
1735
1736/*
1737 * Read a binary hunk and return a new fragment; fragment->patch
1738 * points at an allocated memory that the caller must free, so
1739 * it is marked as "->free_patch = 1".
1740 */
1741static struct fragment *parse_binary_hunk(struct apply_state *state,
1742                                          char **buf_p,
1743                                          unsigned long *sz_p,
1744                                          int *status_p,
1745                                          int *used_p)
1746{
1747        /*
1748         * Expect a line that begins with binary patch method ("literal"
1749         * or "delta"), followed by the length of data before deflating.
1750         * a sequence of 'length-byte' followed by base-85 encoded data
1751         * should follow, terminated by a newline.
1752         *
1753         * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1754         * and we would limit the patch line to 66 characters,
1755         * so one line can fit up to 13 groups that would decode
1756         * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1757         * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1758         */
1759        int llen, used;
1760        unsigned long size = *sz_p;
1761        char *buffer = *buf_p;
1762        int patch_method;
1763        unsigned long origlen;
1764        char *data = NULL;
1765        int hunk_size = 0;
1766        struct fragment *frag;
1767
1768        llen = linelen(buffer, size);
1769        used = llen;
1770
1771        *status_p = 0;
1772
1773        if (starts_with(buffer, "delta ")) {
1774                patch_method = BINARY_DELTA_DEFLATED;
1775                origlen = strtoul(buffer + 6, NULL, 10);
1776        }
1777        else if (starts_with(buffer, "literal ")) {
1778                patch_method = BINARY_LITERAL_DEFLATED;
1779                origlen = strtoul(buffer + 8, NULL, 10);
1780        }
1781        else
1782                return NULL;
1783
1784        state->linenr++;
1785        buffer += llen;
1786        while (1) {
1787                int byte_length, max_byte_length, newsize;
1788                llen = linelen(buffer, size);
1789                used += llen;
1790                state->linenr++;
1791                if (llen == 1) {
1792                        /* consume the blank line */
1793                        buffer++;
1794                        size--;
1795                        break;
1796                }
1797                /*
1798                 * Minimum line is "A00000\n" which is 7-byte long,
1799                 * and the line length must be multiple of 5 plus 2.
1800                 */
1801                if ((llen < 7) || (llen-2) % 5)
1802                        goto corrupt;
1803                max_byte_length = (llen - 2) / 5 * 4;
1804                byte_length = *buffer;
1805                if ('A' <= byte_length && byte_length <= 'Z')
1806                        byte_length = byte_length - 'A' + 1;
1807                else if ('a' <= byte_length && byte_length <= 'z')
1808                        byte_length = byte_length - 'a' + 27;
1809                else
1810                        goto corrupt;
1811                /* if the input length was not multiple of 4, we would
1812                 * have filler at the end but the filler should never
1813                 * exceed 3 bytes
1814                 */
1815                if (max_byte_length < byte_length ||
1816                    byte_length <= max_byte_length - 4)
1817                        goto corrupt;
1818                newsize = hunk_size + byte_length;
1819                data = xrealloc(data, newsize);
1820                if (decode_85(data + hunk_size, buffer + 1, byte_length))
1821                        goto corrupt;
1822                hunk_size = newsize;
1823                buffer += llen;
1824                size -= llen;
1825        }
1826
1827        frag = xcalloc(1, sizeof(*frag));
1828        frag->patch = inflate_it(data, hunk_size, origlen);
1829        frag->free_patch = 1;
1830        if (!frag->patch)
1831                goto corrupt;
1832        free(data);
1833        frag->size = origlen;
1834        *buf_p = buffer;
1835        *sz_p = size;
1836        *used_p = used;
1837        frag->binary_patch_method = patch_method;
1838        return frag;
1839
1840 corrupt:
1841        free(data);
1842        *status_p = -1;
1843        error(_("corrupt binary patch at line %d: %.*s"),
1844              state->linenr-1, llen-1, buffer);
1845        return NULL;
1846}
1847
1848/*
1849 * Returns:
1850 *   -1 in case of error,
1851 *   the length of the parsed binary patch otherwise
1852 */
1853static int parse_binary(struct apply_state *state,
1854                        char *buffer,
1855                        unsigned long size,
1856                        struct patch *patch)
1857{
1858        /*
1859         * We have read "GIT binary patch\n"; what follows is a line
1860         * that says the patch method (currently, either "literal" or
1861         * "delta") and the length of data before deflating; a
1862         * sequence of 'length-byte' followed by base-85 encoded data
1863         * follows.
1864         *
1865         * When a binary patch is reversible, there is another binary
1866         * hunk in the same format, starting with patch method (either
1867         * "literal" or "delta") with the length of data, and a sequence
1868         * of length-byte + base-85 encoded data, terminated with another
1869         * empty line.  This data, when applied to the postimage, produces
1870         * the preimage.
1871         */
1872        struct fragment *forward;
1873        struct fragment *reverse;
1874        int status;
1875        int used, used_1;
1876
1877        forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
1878        if (!forward && !status)
1879                /* there has to be one hunk (forward hunk) */
1880                return error(_("unrecognized binary patch at line %d"), state->linenr-1);
1881        if (status)
1882                /* otherwise we already gave an error message */
1883                return status;
1884
1885        reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
1886        if (reverse)
1887                used += used_1;
1888        else if (status) {
1889                /*
1890                 * Not having reverse hunk is not an error, but having
1891                 * a corrupt reverse hunk is.
1892                 */
1893                free((void*) forward->patch);
1894                free(forward);
1895                return status;
1896        }
1897        forward->next = reverse;
1898        patch->fragments = forward;
1899        patch->is_binary = 1;
1900        return used;
1901}
1902
1903static void prefix_one(struct apply_state *state, char **name)
1904{
1905        char *old_name = *name;
1906        if (!old_name)
1907                return;
1908        *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1909        free(old_name);
1910}
1911
1912static void prefix_patch(struct apply_state *state, struct patch *p)
1913{
1914        if (!state->prefix || p->is_toplevel_relative)
1915                return;
1916        prefix_one(state, &p->new_name);
1917        prefix_one(state, &p->old_name);
1918}
1919
1920/*
1921 * include/exclude
1922 */
1923
1924static void add_name_limit(struct apply_state *state,
1925                           const char *name,
1926                           int exclude)
1927{
1928        struct string_list_item *it;
1929
1930        it = string_list_append(&state->limit_by_name, name);
1931        it->util = exclude ? NULL : (void *) 1;
1932}
1933
1934static int use_patch(struct apply_state *state, struct patch *p)
1935{
1936        const char *pathname = p->new_name ? p->new_name : p->old_name;
1937        int i;
1938
1939        /* Paths outside are not touched regardless of "--include" */
1940        if (0 < state->prefix_length) {
1941                int pathlen = strlen(pathname);
1942                if (pathlen <= state->prefix_length ||
1943                    memcmp(state->prefix, pathname, state->prefix_length))
1944                        return 0;
1945        }
1946
1947        /* See if it matches any of exclude/include rule */
1948        for (i = 0; i < state->limit_by_name.nr; i++) {
1949                struct string_list_item *it = &state->limit_by_name.items[i];
1950                if (!wildmatch(it->string, pathname, 0, NULL))
1951                        return (it->util != NULL);
1952        }
1953
1954        /*
1955         * If we had any include, a path that does not match any rule is
1956         * not used.  Otherwise, we saw bunch of exclude rules (or none)
1957         * and such a path is used.
1958         */
1959        return !state->has_include;
1960}
1961
1962/*
1963 * Read the patch text in "buffer" that extends for "size" bytes; stop
1964 * reading after seeing a single patch (i.e. changes to a single file).
1965 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1966 *
1967 * Returns:
1968 *   -1 if no header was found or parse_binary() failed,
1969 *   -128 on another error,
1970 *   the number of bytes consumed otherwise,
1971 *     so that the caller can call us again for the next patch.
1972 */
1973static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
1974{
1975        int hdrsize, patchsize;
1976        int offset = find_header(state, buffer, size, &hdrsize, patch);
1977
1978        if (offset < 0)
1979                return offset;
1980
1981        prefix_patch(state, patch);
1982
1983        if (!use_patch(state, patch))
1984                patch->ws_rule = 0;
1985        else
1986                patch->ws_rule = whitespace_rule(patch->new_name
1987                                                 ? patch->new_name
1988                                                 : patch->old_name);
1989
1990        patchsize = parse_single_patch(state,
1991                                       buffer + offset + hdrsize,
1992                                       size - offset - hdrsize,
1993                                       patch);
1994
1995        if (patchsize < 0)
1996                return -128;
1997
1998        if (!patchsize) {
1999                static const char git_binary[] = "GIT binary patch\n";
2000                int hd = hdrsize + offset;
2001                unsigned long llen = linelen(buffer + hd, size - hd);
2002
2003                if (llen == sizeof(git_binary) - 1 &&
2004                    !memcmp(git_binary, buffer + hd, llen)) {
2005                        int used;
2006                        state->linenr++;
2007                        used = parse_binary(state, buffer + hd + llen,
2008                                            size - hd - llen, patch);
2009                        if (used < 0)
2010                                return -1;
2011                        if (used)
2012                                patchsize = used + llen;
2013                        else
2014                                patchsize = 0;
2015                }
2016                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2017                        static const char *binhdr[] = {
2018                                "Binary files ",
2019                                "Files ",
2020                                NULL,
2021                        };
2022                        int i;
2023                        for (i = 0; binhdr[i]; i++) {
2024                                int len = strlen(binhdr[i]);
2025                                if (len < size - hd &&
2026                                    !memcmp(binhdr[i], buffer + hd, len)) {
2027                                        state->linenr++;
2028                                        patch->is_binary = 1;
2029                                        patchsize = llen;
2030                                        break;
2031                                }
2032                        }
2033                }
2034
2035                /* Empty patch cannot be applied if it is a text patch
2036                 * without metadata change.  A binary patch appears
2037                 * empty to us here.
2038                 */
2039                if ((state->apply || state->check) &&
2040                    (!patch->is_binary && !metadata_changes(patch))) {
2041                        error(_("patch with only garbage at line %d"), state->linenr);
2042                        return -128;
2043                }
2044        }
2045
2046        return offset + hdrsize + patchsize;
2047}
2048
2049#define swap(a,b) myswap((a),(b),sizeof(a))
2050
2051#define myswap(a, b, size) do {         \
2052        unsigned char mytmp[size];      \
2053        memcpy(mytmp, &a, size);                \
2054        memcpy(&a, &b, size);           \
2055        memcpy(&b, mytmp, size);                \
2056} while (0)
2057
2058static void reverse_patches(struct patch *p)
2059{
2060        for (; p; p = p->next) {
2061                struct fragment *frag = p->fragments;
2062
2063                swap(p->new_name, p->old_name);
2064                swap(p->new_mode, p->old_mode);
2065                swap(p->is_new, p->is_delete);
2066                swap(p->lines_added, p->lines_deleted);
2067                swap(p->old_sha1_prefix, p->new_sha1_prefix);
2068
2069                for (; frag; frag = frag->next) {
2070                        swap(frag->newpos, frag->oldpos);
2071                        swap(frag->newlines, frag->oldlines);
2072                }
2073        }
2074}
2075
2076static const char pluses[] =
2077"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2078static const char minuses[]=
2079"----------------------------------------------------------------------";
2080
2081static void show_stats(struct apply_state *state, struct patch *patch)
2082{
2083        struct strbuf qname = STRBUF_INIT;
2084        char *cp = patch->new_name ? patch->new_name : patch->old_name;
2085        int max, add, del;
2086
2087        quote_c_style(cp, &qname, NULL, 0);
2088
2089        /*
2090         * "scale" the filename
2091         */
2092        max = state->max_len;
2093        if (max > 50)
2094                max = 50;
2095
2096        if (qname.len > max) {
2097                cp = strchr(qname.buf + qname.len + 3 - max, '/');
2098                if (!cp)
2099                        cp = qname.buf + qname.len + 3 - max;
2100                strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2101        }
2102
2103        if (patch->is_binary) {
2104                printf(" %-*s |  Bin\n", max, qname.buf);
2105                strbuf_release(&qname);
2106                return;
2107        }
2108
2109        printf(" %-*s |", max, qname.buf);
2110        strbuf_release(&qname);
2111
2112        /*
2113         * scale the add/delete
2114         */
2115        max = max + state->max_change > 70 ? 70 - max : state->max_change;
2116        add = patch->lines_added;
2117        del = patch->lines_deleted;
2118
2119        if (state->max_change > 0) {
2120                int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2121                add = (add * max + state->max_change / 2) / state->max_change;
2122                del = total - add;
2123        }
2124        printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2125                add, pluses, del, minuses);
2126}
2127
2128static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2129{
2130        switch (st->st_mode & S_IFMT) {
2131        case S_IFLNK:
2132                if (strbuf_readlink(buf, path, st->st_size) < 0)
2133                        return error(_("unable to read symlink %s"), path);
2134                return 0;
2135        case S_IFREG:
2136                if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2137                        return error(_("unable to open or read %s"), path);
2138                convert_to_git(path, buf->buf, buf->len, buf, 0);
2139                return 0;
2140        default:
2141                return -1;
2142        }
2143}
2144
2145/*
2146 * Update the preimage, and the common lines in postimage,
2147 * from buffer buf of length len. If postlen is 0 the postimage
2148 * is updated in place, otherwise it's updated on a new buffer
2149 * of length postlen
2150 */
2151
2152static void update_pre_post_images(struct image *preimage,
2153                                   struct image *postimage,
2154                                   char *buf,
2155                                   size_t len, size_t postlen)
2156{
2157        int i, ctx, reduced;
2158        char *new, *old, *fixed;
2159        struct image fixed_preimage;
2160
2161        /*
2162         * Update the preimage with whitespace fixes.  Note that we
2163         * are not losing preimage->buf -- apply_one_fragment() will
2164         * free "oldlines".
2165         */
2166        prepare_image(&fixed_preimage, buf, len, 1);
2167        assert(postlen
2168               ? fixed_preimage.nr == preimage->nr
2169               : fixed_preimage.nr <= preimage->nr);
2170        for (i = 0; i < fixed_preimage.nr; i++)
2171                fixed_preimage.line[i].flag = preimage->line[i].flag;
2172        free(preimage->line_allocated);
2173        *preimage = fixed_preimage;
2174
2175        /*
2176         * Adjust the common context lines in postimage. This can be
2177         * done in-place when we are shrinking it with whitespace
2178         * fixing, but needs a new buffer when ignoring whitespace or
2179         * expanding leading tabs to spaces.
2180         *
2181         * We trust the caller to tell us if the update can be done
2182         * in place (postlen==0) or not.
2183         */
2184        old = postimage->buf;
2185        if (postlen)
2186                new = postimage->buf = xmalloc(postlen);
2187        else
2188                new = old;
2189        fixed = preimage->buf;
2190
2191        for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2192                size_t l_len = postimage->line[i].len;
2193                if (!(postimage->line[i].flag & LINE_COMMON)) {
2194                        /* an added line -- no counterparts in preimage */
2195                        memmove(new, old, l_len);
2196                        old += l_len;
2197                        new += l_len;
2198                        continue;
2199                }
2200
2201                /* a common context -- skip it in the original postimage */
2202                old += l_len;
2203
2204                /* and find the corresponding one in the fixed preimage */
2205                while (ctx < preimage->nr &&
2206                       !(preimage->line[ctx].flag & LINE_COMMON)) {
2207                        fixed += preimage->line[ctx].len;
2208                        ctx++;
2209                }
2210
2211                /*
2212                 * preimage is expected to run out, if the caller
2213                 * fixed addition of trailing blank lines.
2214                 */
2215                if (preimage->nr <= ctx) {
2216                        reduced++;
2217                        continue;
2218                }
2219
2220                /* and copy it in, while fixing the line length */
2221                l_len = preimage->line[ctx].len;
2222                memcpy(new, fixed, l_len);
2223                new += l_len;
2224                fixed += l_len;
2225                postimage->line[i].len = l_len;
2226                ctx++;
2227        }
2228
2229        if (postlen
2230            ? postlen < new - postimage->buf
2231            : postimage->len < new - postimage->buf)
2232                die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2233                    (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2234
2235        /* Fix the length of the whole thing */
2236        postimage->len = new - postimage->buf;
2237        postimage->nr -= reduced;
2238}
2239
2240static int line_by_line_fuzzy_match(struct image *img,
2241                                    struct image *preimage,
2242                                    struct image *postimage,
2243                                    unsigned long try,
2244                                    int try_lno,
2245                                    int preimage_limit)
2246{
2247        int i;
2248        size_t imgoff = 0;
2249        size_t preoff = 0;
2250        size_t postlen = postimage->len;
2251        size_t extra_chars;
2252        char *buf;
2253        char *preimage_eof;
2254        char *preimage_end;
2255        struct strbuf fixed;
2256        char *fixed_buf;
2257        size_t fixed_len;
2258
2259        for (i = 0; i < preimage_limit; i++) {
2260                size_t prelen = preimage->line[i].len;
2261                size_t imglen = img->line[try_lno+i].len;
2262
2263                if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2264                                      preimage->buf + preoff, prelen))
2265                        return 0;
2266                if (preimage->line[i].flag & LINE_COMMON)
2267                        postlen += imglen - prelen;
2268                imgoff += imglen;
2269                preoff += prelen;
2270        }
2271
2272        /*
2273         * Ok, the preimage matches with whitespace fuzz.
2274         *
2275         * imgoff now holds the true length of the target that
2276         * matches the preimage before the end of the file.
2277         *
2278         * Count the number of characters in the preimage that fall
2279         * beyond the end of the file and make sure that all of them
2280         * are whitespace characters. (This can only happen if
2281         * we are removing blank lines at the end of the file.)
2282         */
2283        buf = preimage_eof = preimage->buf + preoff;
2284        for ( ; i < preimage->nr; i++)
2285                preoff += preimage->line[i].len;
2286        preimage_end = preimage->buf + preoff;
2287        for ( ; buf < preimage_end; buf++)
2288                if (!isspace(*buf))
2289                        return 0;
2290
2291        /*
2292         * Update the preimage and the common postimage context
2293         * lines to use the same whitespace as the target.
2294         * If whitespace is missing in the target (i.e.
2295         * if the preimage extends beyond the end of the file),
2296         * use the whitespace from the preimage.
2297         */
2298        extra_chars = preimage_end - preimage_eof;
2299        strbuf_init(&fixed, imgoff + extra_chars);
2300        strbuf_add(&fixed, img->buf + try, imgoff);
2301        strbuf_add(&fixed, preimage_eof, extra_chars);
2302        fixed_buf = strbuf_detach(&fixed, &fixed_len);
2303        update_pre_post_images(preimage, postimage,
2304                               fixed_buf, fixed_len, postlen);
2305        return 1;
2306}
2307
2308static int match_fragment(struct apply_state *state,
2309                          struct image *img,
2310                          struct image *preimage,
2311                          struct image *postimage,
2312                          unsigned long try,
2313                          int try_lno,
2314                          unsigned ws_rule,
2315                          int match_beginning, int match_end)
2316{
2317        int i;
2318        char *fixed_buf, *buf, *orig, *target;
2319        struct strbuf fixed;
2320        size_t fixed_len, postlen;
2321        int preimage_limit;
2322
2323        if (preimage->nr + try_lno <= img->nr) {
2324                /*
2325                 * The hunk falls within the boundaries of img.
2326                 */
2327                preimage_limit = preimage->nr;
2328                if (match_end && (preimage->nr + try_lno != img->nr))
2329                        return 0;
2330        } else if (state->ws_error_action == correct_ws_error &&
2331                   (ws_rule & WS_BLANK_AT_EOF)) {
2332                /*
2333                 * This hunk extends beyond the end of img, and we are
2334                 * removing blank lines at the end of the file.  This
2335                 * many lines from the beginning of the preimage must
2336                 * match with img, and the remainder of the preimage
2337                 * must be blank.
2338                 */
2339                preimage_limit = img->nr - try_lno;
2340        } else {
2341                /*
2342                 * The hunk extends beyond the end of the img and
2343                 * we are not removing blanks at the end, so we
2344                 * should reject the hunk at this position.
2345                 */
2346                return 0;
2347        }
2348
2349        if (match_beginning && try_lno)
2350                return 0;
2351
2352        /* Quick hash check */
2353        for (i = 0; i < preimage_limit; i++)
2354                if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2355                    (preimage->line[i].hash != img->line[try_lno + i].hash))
2356                        return 0;
2357
2358        if (preimage_limit == preimage->nr) {
2359                /*
2360                 * Do we have an exact match?  If we were told to match
2361                 * at the end, size must be exactly at try+fragsize,
2362                 * otherwise try+fragsize must be still within the preimage,
2363                 * and either case, the old piece should match the preimage
2364                 * exactly.
2365                 */
2366                if ((match_end
2367                     ? (try + preimage->len == img->len)
2368                     : (try + preimage->len <= img->len)) &&
2369                    !memcmp(img->buf + try, preimage->buf, preimage->len))
2370                        return 1;
2371        } else {
2372                /*
2373                 * The preimage extends beyond the end of img, so
2374                 * there cannot be an exact match.
2375                 *
2376                 * There must be one non-blank context line that match
2377                 * a line before the end of img.
2378                 */
2379                char *buf_end;
2380
2381                buf = preimage->buf;
2382                buf_end = buf;
2383                for (i = 0; i < preimage_limit; i++)
2384                        buf_end += preimage->line[i].len;
2385
2386                for ( ; buf < buf_end; buf++)
2387                        if (!isspace(*buf))
2388                                break;
2389                if (buf == buf_end)
2390                        return 0;
2391        }
2392
2393        /*
2394         * No exact match. If we are ignoring whitespace, run a line-by-line
2395         * fuzzy matching. We collect all the line length information because
2396         * we need it to adjust whitespace if we match.
2397         */
2398        if (state->ws_ignore_action == ignore_ws_change)
2399                return line_by_line_fuzzy_match(img, preimage, postimage,
2400                                                try, try_lno, preimage_limit);
2401
2402        if (state->ws_error_action != correct_ws_error)
2403                return 0;
2404
2405        /*
2406         * The hunk does not apply byte-by-byte, but the hash says
2407         * it might with whitespace fuzz. We weren't asked to
2408         * ignore whitespace, we were asked to correct whitespace
2409         * errors, so let's try matching after whitespace correction.
2410         *
2411         * While checking the preimage against the target, whitespace
2412         * errors in both fixed, we count how large the corresponding
2413         * postimage needs to be.  The postimage prepared by
2414         * apply_one_fragment() has whitespace errors fixed on added
2415         * lines already, but the common lines were propagated as-is,
2416         * which may become longer when their whitespace errors are
2417         * fixed.
2418         */
2419
2420        /* First count added lines in postimage */
2421        postlen = 0;
2422        for (i = 0; i < postimage->nr; i++) {
2423                if (!(postimage->line[i].flag & LINE_COMMON))
2424                        postlen += postimage->line[i].len;
2425        }
2426
2427        /*
2428         * The preimage may extend beyond the end of the file,
2429         * but in this loop we will only handle the part of the
2430         * preimage that falls within the file.
2431         */
2432        strbuf_init(&fixed, preimage->len + 1);
2433        orig = preimage->buf;
2434        target = img->buf + try;
2435        for (i = 0; i < preimage_limit; i++) {
2436                size_t oldlen = preimage->line[i].len;
2437                size_t tgtlen = img->line[try_lno + i].len;
2438                size_t fixstart = fixed.len;
2439                struct strbuf tgtfix;
2440                int match;
2441
2442                /* Try fixing the line in the preimage */
2443                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2444
2445                /* Try fixing the line in the target */
2446                strbuf_init(&tgtfix, tgtlen);
2447                ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2448
2449                /*
2450                 * If they match, either the preimage was based on
2451                 * a version before our tree fixed whitespace breakage,
2452                 * or we are lacking a whitespace-fix patch the tree
2453                 * the preimage was based on already had (i.e. target
2454                 * has whitespace breakage, the preimage doesn't).
2455                 * In either case, we are fixing the whitespace breakages
2456                 * so we might as well take the fix together with their
2457                 * real change.
2458                 */
2459                match = (tgtfix.len == fixed.len - fixstart &&
2460                         !memcmp(tgtfix.buf, fixed.buf + fixstart,
2461                                             fixed.len - fixstart));
2462
2463                /* Add the length if this is common with the postimage */
2464                if (preimage->line[i].flag & LINE_COMMON)
2465                        postlen += tgtfix.len;
2466
2467                strbuf_release(&tgtfix);
2468                if (!match)
2469                        goto unmatch_exit;
2470
2471                orig += oldlen;
2472                target += tgtlen;
2473        }
2474
2475
2476        /*
2477         * Now handle the lines in the preimage that falls beyond the
2478         * end of the file (if any). They will only match if they are
2479         * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2480         * false).
2481         */
2482        for ( ; i < preimage->nr; i++) {
2483                size_t fixstart = fixed.len; /* start of the fixed preimage */
2484                size_t oldlen = preimage->line[i].len;
2485                int j;
2486
2487                /* Try fixing the line in the preimage */
2488                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2489
2490                for (j = fixstart; j < fixed.len; j++)
2491                        if (!isspace(fixed.buf[j]))
2492                                goto unmatch_exit;
2493
2494                orig += oldlen;
2495        }
2496
2497        /*
2498         * Yes, the preimage is based on an older version that still
2499         * has whitespace breakages unfixed, and fixing them makes the
2500         * hunk match.  Update the context lines in the postimage.
2501         */
2502        fixed_buf = strbuf_detach(&fixed, &fixed_len);
2503        if (postlen < postimage->len)
2504                postlen = 0;
2505        update_pre_post_images(preimage, postimage,
2506                               fixed_buf, fixed_len, postlen);
2507        return 1;
2508
2509 unmatch_exit:
2510        strbuf_release(&fixed);
2511        return 0;
2512}
2513
2514static int find_pos(struct apply_state *state,
2515                    struct image *img,
2516                    struct image *preimage,
2517                    struct image *postimage,
2518                    int line,
2519                    unsigned ws_rule,
2520                    int match_beginning, int match_end)
2521{
2522        int i;
2523        unsigned long backwards, forwards, try;
2524        int backwards_lno, forwards_lno, try_lno;
2525
2526        /*
2527         * If match_beginning or match_end is specified, there is no
2528         * point starting from a wrong line that will never match and
2529         * wander around and wait for a match at the specified end.
2530         */
2531        if (match_beginning)
2532                line = 0;
2533        else if (match_end)
2534                line = img->nr - preimage->nr;
2535
2536        /*
2537         * Because the comparison is unsigned, the following test
2538         * will also take care of a negative line number that can
2539         * result when match_end and preimage is larger than the target.
2540         */
2541        if ((size_t) line > img->nr)
2542                line = img->nr;
2543
2544        try = 0;
2545        for (i = 0; i < line; i++)
2546                try += img->line[i].len;
2547
2548        /*
2549         * There's probably some smart way to do this, but I'll leave
2550         * that to the smart and beautiful people. I'm simple and stupid.
2551         */
2552        backwards = try;
2553        backwards_lno = line;
2554        forwards = try;
2555        forwards_lno = line;
2556        try_lno = line;
2557
2558        for (i = 0; ; i++) {
2559                if (match_fragment(state, img, preimage, postimage,
2560                                   try, try_lno, ws_rule,
2561                                   match_beginning, match_end))
2562                        return try_lno;
2563
2564        again:
2565                if (backwards_lno == 0 && forwards_lno == img->nr)
2566                        break;
2567
2568                if (i & 1) {
2569                        if (backwards_lno == 0) {
2570                                i++;
2571                                goto again;
2572                        }
2573                        backwards_lno--;
2574                        backwards -= img->line[backwards_lno].len;
2575                        try = backwards;
2576                        try_lno = backwards_lno;
2577                } else {
2578                        if (forwards_lno == img->nr) {
2579                                i++;
2580                                goto again;
2581                        }
2582                        forwards += img->line[forwards_lno].len;
2583                        forwards_lno++;
2584                        try = forwards;
2585                        try_lno = forwards_lno;
2586                }
2587
2588        }
2589        return -1;
2590}
2591
2592static void remove_first_line(struct image *img)
2593{
2594        img->buf += img->line[0].len;
2595        img->len -= img->line[0].len;
2596        img->line++;
2597        img->nr--;
2598}
2599
2600static void remove_last_line(struct image *img)
2601{
2602        img->len -= img->line[--img->nr].len;
2603}
2604
2605/*
2606 * The change from "preimage" and "postimage" has been found to
2607 * apply at applied_pos (counts in line numbers) in "img".
2608 * Update "img" to remove "preimage" and replace it with "postimage".
2609 */
2610static void update_image(struct apply_state *state,
2611                         struct image *img,
2612                         int applied_pos,
2613                         struct image *preimage,
2614                         struct image *postimage)
2615{
2616        /*
2617         * remove the copy of preimage at offset in img
2618         * and replace it with postimage
2619         */
2620        int i, nr;
2621        size_t remove_count, insert_count, applied_at = 0;
2622        char *result;
2623        int preimage_limit;
2624
2625        /*
2626         * If we are removing blank lines at the end of img,
2627         * the preimage may extend beyond the end.
2628         * If that is the case, we must be careful only to
2629         * remove the part of the preimage that falls within
2630         * the boundaries of img. Initialize preimage_limit
2631         * to the number of lines in the preimage that falls
2632         * within the boundaries.
2633         */
2634        preimage_limit = preimage->nr;
2635        if (preimage_limit > img->nr - applied_pos)
2636                preimage_limit = img->nr - applied_pos;
2637
2638        for (i = 0; i < applied_pos; i++)
2639                applied_at += img->line[i].len;
2640
2641        remove_count = 0;
2642        for (i = 0; i < preimage_limit; i++)
2643                remove_count += img->line[applied_pos + i].len;
2644        insert_count = postimage->len;
2645
2646        /* Adjust the contents */
2647        result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2648        memcpy(result, img->buf, applied_at);
2649        memcpy(result + applied_at, postimage->buf, postimage->len);
2650        memcpy(result + applied_at + postimage->len,
2651               img->buf + (applied_at + remove_count),
2652               img->len - (applied_at + remove_count));
2653        free(img->buf);
2654        img->buf = result;
2655        img->len += insert_count - remove_count;
2656        result[img->len] = '\0';
2657
2658        /* Adjust the line table */
2659        nr = img->nr + postimage->nr - preimage_limit;
2660        if (preimage_limit < postimage->nr) {
2661                /*
2662                 * NOTE: this knows that we never call remove_first_line()
2663                 * on anything other than pre/post image.
2664                 */
2665                REALLOC_ARRAY(img->line, nr);
2666                img->line_allocated = img->line;
2667        }
2668        if (preimage_limit != postimage->nr)
2669                memmove(img->line + applied_pos + postimage->nr,
2670                        img->line + applied_pos + preimage_limit,
2671                        (img->nr - (applied_pos + preimage_limit)) *
2672                        sizeof(*img->line));
2673        memcpy(img->line + applied_pos,
2674               postimage->line,
2675               postimage->nr * sizeof(*img->line));
2676        if (!state->allow_overlap)
2677                for (i = 0; i < postimage->nr; i++)
2678                        img->line[applied_pos + i].flag |= LINE_PATCHED;
2679        img->nr = nr;
2680}
2681
2682/*
2683 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2684 * postimage) for the hunk.  Find lines that match "preimage" in "img" and
2685 * replace the part of "img" with "postimage" text.
2686 */
2687static int apply_one_fragment(struct apply_state *state,
2688                              struct image *img, struct fragment *frag,
2689                              int inaccurate_eof, unsigned ws_rule,
2690                              int nth_fragment)
2691{
2692        int match_beginning, match_end;
2693        const char *patch = frag->patch;
2694        int size = frag->size;
2695        char *old, *oldlines;
2696        struct strbuf newlines;
2697        int new_blank_lines_at_end = 0;
2698        int found_new_blank_lines_at_end = 0;
2699        int hunk_linenr = frag->linenr;
2700        unsigned long leading, trailing;
2701        int pos, applied_pos;
2702        struct image preimage;
2703        struct image postimage;
2704
2705        memset(&preimage, 0, sizeof(preimage));
2706        memset(&postimage, 0, sizeof(postimage));
2707        oldlines = xmalloc(size);
2708        strbuf_init(&newlines, size);
2709
2710        old = oldlines;
2711        while (size > 0) {
2712                char first;
2713                int len = linelen(patch, size);
2714                int plen;
2715                int added_blank_line = 0;
2716                int is_blank_context = 0;
2717                size_t start;
2718
2719                if (!len)
2720                        break;
2721
2722                /*
2723                 * "plen" is how much of the line we should use for
2724                 * the actual patch data. Normally we just remove the
2725                 * first character on the line, but if the line is
2726                 * followed by "\ No newline", then we also remove the
2727                 * last one (which is the newline, of course).
2728                 */
2729                plen = len - 1;
2730                if (len < size && patch[len] == '\\')
2731                        plen--;
2732                first = *patch;
2733                if (state->apply_in_reverse) {
2734                        if (first == '-')
2735                                first = '+';
2736                        else if (first == '+')
2737                                first = '-';
2738                }
2739
2740                switch (first) {
2741                case '\n':
2742                        /* Newer GNU diff, empty context line */
2743                        if (plen < 0)
2744                                /* ... followed by '\No newline'; nothing */
2745                                break;
2746                        *old++ = '\n';
2747                        strbuf_addch(&newlines, '\n');
2748                        add_line_info(&preimage, "\n", 1, LINE_COMMON);
2749                        add_line_info(&postimage, "\n", 1, LINE_COMMON);
2750                        is_blank_context = 1;
2751                        break;
2752                case ' ':
2753                        if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2754                            ws_blank_line(patch + 1, plen, ws_rule))
2755                                is_blank_context = 1;
2756                case '-':
2757                        memcpy(old, patch + 1, plen);
2758                        add_line_info(&preimage, old, plen,
2759                                      (first == ' ' ? LINE_COMMON : 0));
2760                        old += plen;
2761                        if (first == '-')
2762                                break;
2763                /* Fall-through for ' ' */
2764                case '+':
2765                        /* --no-add does not add new lines */
2766                        if (first == '+' && state->no_add)
2767                                break;
2768
2769                        start = newlines.len;
2770                        if (first != '+' ||
2771                            !state->whitespace_error ||
2772                            state->ws_error_action != correct_ws_error) {
2773                                strbuf_add(&newlines, patch + 1, plen);
2774                        }
2775                        else {
2776                                ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2777                        }
2778                        add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2779                                      (first == '+' ? 0 : LINE_COMMON));
2780                        if (first == '+' &&
2781                            (ws_rule & WS_BLANK_AT_EOF) &&
2782                            ws_blank_line(patch + 1, plen, ws_rule))
2783                                added_blank_line = 1;
2784                        break;
2785                case '@': case '\\':
2786                        /* Ignore it, we already handled it */
2787                        break;
2788                default:
2789                        if (state->apply_verbosely)
2790                                error(_("invalid start of line: '%c'"), first);
2791                        applied_pos = -1;
2792                        goto out;
2793                }
2794                if (added_blank_line) {
2795                        if (!new_blank_lines_at_end)
2796                                found_new_blank_lines_at_end = hunk_linenr;
2797                        new_blank_lines_at_end++;
2798                }
2799                else if (is_blank_context)
2800                        ;
2801                else
2802                        new_blank_lines_at_end = 0;
2803                patch += len;
2804                size -= len;
2805                hunk_linenr++;
2806        }
2807        if (inaccurate_eof &&
2808            old > oldlines && old[-1] == '\n' &&
2809            newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2810                old--;
2811                strbuf_setlen(&newlines, newlines.len - 1);
2812        }
2813
2814        leading = frag->leading;
2815        trailing = frag->trailing;
2816
2817        /*
2818         * A hunk to change lines at the beginning would begin with
2819         * @@ -1,L +N,M @@
2820         * but we need to be careful.  -U0 that inserts before the second
2821         * line also has this pattern.
2822         *
2823         * And a hunk to add to an empty file would begin with
2824         * @@ -0,0 +N,M @@
2825         *
2826         * In other words, a hunk that is (frag->oldpos <= 1) with or
2827         * without leading context must match at the beginning.
2828         */
2829        match_beginning = (!frag->oldpos ||
2830                           (frag->oldpos == 1 && !state->unidiff_zero));
2831
2832        /*
2833         * A hunk without trailing lines must match at the end.
2834         * However, we simply cannot tell if a hunk must match end
2835         * from the lack of trailing lines if the patch was generated
2836         * with unidiff without any context.
2837         */
2838        match_end = !state->unidiff_zero && !trailing;
2839
2840        pos = frag->newpos ? (frag->newpos - 1) : 0;
2841        preimage.buf = oldlines;
2842        preimage.len = old - oldlines;
2843        postimage.buf = newlines.buf;
2844        postimage.len = newlines.len;
2845        preimage.line = preimage.line_allocated;
2846        postimage.line = postimage.line_allocated;
2847
2848        for (;;) {
2849
2850                applied_pos = find_pos(state, img, &preimage, &postimage, pos,
2851                                       ws_rule, match_beginning, match_end);
2852
2853                if (applied_pos >= 0)
2854                        break;
2855
2856                /* Am I at my context limits? */
2857                if ((leading <= state->p_context) && (trailing <= state->p_context))
2858                        break;
2859                if (match_beginning || match_end) {
2860                        match_beginning = match_end = 0;
2861                        continue;
2862                }
2863
2864                /*
2865                 * Reduce the number of context lines; reduce both
2866                 * leading and trailing if they are equal otherwise
2867                 * just reduce the larger context.
2868                 */
2869                if (leading >= trailing) {
2870                        remove_first_line(&preimage);
2871                        remove_first_line(&postimage);
2872                        pos--;
2873                        leading--;
2874                }
2875                if (trailing > leading) {
2876                        remove_last_line(&preimage);
2877                        remove_last_line(&postimage);
2878                        trailing--;
2879                }
2880        }
2881
2882        if (applied_pos >= 0) {
2883                if (new_blank_lines_at_end &&
2884                    preimage.nr + applied_pos >= img->nr &&
2885                    (ws_rule & WS_BLANK_AT_EOF) &&
2886                    state->ws_error_action != nowarn_ws_error) {
2887                        record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
2888                                        found_new_blank_lines_at_end);
2889                        if (state->ws_error_action == correct_ws_error) {
2890                                while (new_blank_lines_at_end--)
2891                                        remove_last_line(&postimage);
2892                        }
2893                        /*
2894                         * We would want to prevent write_out_results()
2895                         * from taking place in apply_patch() that follows
2896                         * the callchain led us here, which is:
2897                         * apply_patch->check_patch_list->check_patch->
2898                         * apply_data->apply_fragments->apply_one_fragment
2899                         */
2900                        if (state->ws_error_action == die_on_ws_error)
2901                                state->apply = 0;
2902                }
2903
2904                if (state->apply_verbosely && applied_pos != pos) {
2905                        int offset = applied_pos - pos;
2906                        if (state->apply_in_reverse)
2907                                offset = 0 - offset;
2908                        fprintf_ln(stderr,
2909                                   Q_("Hunk #%d succeeded at %d (offset %d line).",
2910                                      "Hunk #%d succeeded at %d (offset %d lines).",
2911                                      offset),
2912                                   nth_fragment, applied_pos + 1, offset);
2913                }
2914
2915                /*
2916                 * Warn if it was necessary to reduce the number
2917                 * of context lines.
2918                 */
2919                if ((leading != frag->leading) ||
2920                    (trailing != frag->trailing))
2921                        fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2922                                             " to apply fragment at %d"),
2923                                   leading, trailing, applied_pos+1);
2924                update_image(state, img, applied_pos, &preimage, &postimage);
2925        } else {
2926                if (state->apply_verbosely)
2927                        error(_("while searching for:\n%.*s"),
2928                              (int)(old - oldlines), oldlines);
2929        }
2930
2931out:
2932        free(oldlines);
2933        strbuf_release(&newlines);
2934        free(preimage.line_allocated);
2935        free(postimage.line_allocated);
2936
2937        return (applied_pos < 0);
2938}
2939
2940static int apply_binary_fragment(struct apply_state *state,
2941                                 struct image *img,
2942                                 struct patch *patch)
2943{
2944        struct fragment *fragment = patch->fragments;
2945        unsigned long len;
2946        void *dst;
2947
2948        if (!fragment)
2949                return error(_("missing binary patch data for '%s'"),
2950                             patch->new_name ?
2951                             patch->new_name :
2952                             patch->old_name);
2953
2954        /* Binary patch is irreversible without the optional second hunk */
2955        if (state->apply_in_reverse) {
2956                if (!fragment->next)
2957                        return error("cannot reverse-apply a binary patch "
2958                                     "without the reverse hunk to '%s'",
2959                                     patch->new_name
2960                                     ? patch->new_name : patch->old_name);
2961                fragment = fragment->next;
2962        }
2963        switch (fragment->binary_patch_method) {
2964        case BINARY_DELTA_DEFLATED:
2965                dst = patch_delta(img->buf, img->len, fragment->patch,
2966                                  fragment->size, &len);
2967                if (!dst)
2968                        return -1;
2969                clear_image(img);
2970                img->buf = dst;
2971                img->len = len;
2972                return 0;
2973        case BINARY_LITERAL_DEFLATED:
2974                clear_image(img);
2975                img->len = fragment->size;
2976                img->buf = xmemdupz(fragment->patch, img->len);
2977                return 0;
2978        }
2979        return -1;
2980}
2981
2982/*
2983 * Replace "img" with the result of applying the binary patch.
2984 * The binary patch data itself in patch->fragment is still kept
2985 * but the preimage prepared by the caller in "img" is freed here
2986 * or in the helper function apply_binary_fragment() this calls.
2987 */
2988static int apply_binary(struct apply_state *state,
2989                        struct image *img,
2990                        struct patch *patch)
2991{
2992        const char *name = patch->old_name ? patch->old_name : patch->new_name;
2993        unsigned char sha1[20];
2994
2995        /*
2996         * For safety, we require patch index line to contain
2997         * full 40-byte textual SHA1 for old and new, at least for now.
2998         */
2999        if (strlen(patch->old_sha1_prefix) != 40 ||
3000            strlen(patch->new_sha1_prefix) != 40 ||
3001            get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3002            get_sha1_hex(patch->new_sha1_prefix, sha1))
3003                return error("cannot apply binary patch to '%s' "
3004                             "without full index line", name);
3005
3006        if (patch->old_name) {
3007                /*
3008                 * See if the old one matches what the patch
3009                 * applies to.
3010                 */
3011                hash_sha1_file(img->buf, img->len, blob_type, sha1);
3012                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3013                        return error("the patch applies to '%s' (%s), "
3014                                     "which does not match the "
3015                                     "current contents.",
3016                                     name, sha1_to_hex(sha1));
3017        }
3018        else {
3019                /* Otherwise, the old one must be empty. */
3020                if (img->len)
3021                        return error("the patch applies to an empty "
3022                                     "'%s' but it is not empty", name);
3023        }
3024
3025        get_sha1_hex(patch->new_sha1_prefix, sha1);
3026        if (is_null_sha1(sha1)) {
3027                clear_image(img);
3028                return 0; /* deletion patch */
3029        }
3030
3031        if (has_sha1_file(sha1)) {
3032                /* We already have the postimage */
3033                enum object_type type;
3034                unsigned long size;
3035                char *result;
3036
3037                result = read_sha1_file(sha1, &type, &size);
3038                if (!result)
3039                        return error("the necessary postimage %s for "
3040                                     "'%s' cannot be read",
3041                                     patch->new_sha1_prefix, name);
3042                clear_image(img);
3043                img->buf = result;
3044                img->len = size;
3045        } else {
3046                /*
3047                 * We have verified buf matches the preimage;
3048                 * apply the patch data to it, which is stored
3049                 * in the patch->fragments->{patch,size}.
3050                 */
3051                if (apply_binary_fragment(state, img, patch))
3052                        return error(_("binary patch does not apply to '%s'"),
3053                                     name);
3054
3055                /* verify that the result matches */
3056                hash_sha1_file(img->buf, img->len, blob_type, sha1);
3057                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3058                        return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3059                                name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3060        }
3061
3062        return 0;
3063}
3064
3065static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3066{
3067        struct fragment *frag = patch->fragments;
3068        const char *name = patch->old_name ? patch->old_name : patch->new_name;
3069        unsigned ws_rule = patch->ws_rule;
3070        unsigned inaccurate_eof = patch->inaccurate_eof;
3071        int nth = 0;
3072
3073        if (patch->is_binary)
3074                return apply_binary(state, img, patch);
3075
3076        while (frag) {
3077                nth++;
3078                if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3079                        error(_("patch failed: %s:%ld"), name, frag->oldpos);
3080                        if (!state->apply_with_reject)
3081                                return -1;
3082                        frag->rejected = 1;
3083                }
3084                frag = frag->next;
3085        }
3086        return 0;
3087}
3088
3089static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3090{
3091        if (S_ISGITLINK(mode)) {
3092                strbuf_grow(buf, 100);
3093                strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3094        } else {
3095                enum object_type type;
3096                unsigned long sz;
3097                char *result;
3098
3099                result = read_sha1_file(sha1, &type, &sz);
3100                if (!result)
3101                        return -1;
3102                /* XXX read_sha1_file NUL-terminates */
3103                strbuf_attach(buf, result, sz, sz + 1);
3104        }
3105        return 0;
3106}
3107
3108static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3109{
3110        if (!ce)
3111                return 0;
3112        return read_blob_object(buf, ce->sha1, ce->ce_mode);
3113}
3114
3115static struct patch *in_fn_table(struct apply_state *state, const char *name)
3116{
3117        struct string_list_item *item;
3118
3119        if (name == NULL)
3120                return NULL;
3121
3122        item = string_list_lookup(&state->fn_table, name);
3123        if (item != NULL)
3124                return (struct patch *)item->util;
3125
3126        return NULL;
3127}
3128
3129/*
3130 * item->util in the filename table records the status of the path.
3131 * Usually it points at a patch (whose result records the contents
3132 * of it after applying it), but it could be PATH_WAS_DELETED for a
3133 * path that a previously applied patch has already removed, or
3134 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3135 *
3136 * The latter is needed to deal with a case where two paths A and B
3137 * are swapped by first renaming A to B and then renaming B to A;
3138 * moving A to B should not be prevented due to presence of B as we
3139 * will remove it in a later patch.
3140 */
3141#define PATH_TO_BE_DELETED ((struct patch *) -2)
3142#define PATH_WAS_DELETED ((struct patch *) -1)
3143
3144static int to_be_deleted(struct patch *patch)
3145{
3146        return patch == PATH_TO_BE_DELETED;
3147}
3148
3149static int was_deleted(struct patch *patch)
3150{
3151        return patch == PATH_WAS_DELETED;
3152}
3153
3154static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3155{
3156        struct string_list_item *item;
3157
3158        /*
3159         * Always add new_name unless patch is a deletion
3160         * This should cover the cases for normal diffs,
3161         * file creations and copies
3162         */
3163        if (patch->new_name != NULL) {
3164                item = string_list_insert(&state->fn_table, patch->new_name);
3165                item->util = patch;
3166        }
3167
3168        /*
3169         * store a failure on rename/deletion cases because
3170         * later chunks shouldn't patch old names
3171         */
3172        if ((patch->new_name == NULL) || (patch->is_rename)) {
3173                item = string_list_insert(&state->fn_table, patch->old_name);
3174                item->util = PATH_WAS_DELETED;
3175        }
3176}
3177
3178static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3179{
3180        /*
3181         * store information about incoming file deletion
3182         */
3183        while (patch) {
3184                if ((patch->new_name == NULL) || (patch->is_rename)) {
3185                        struct string_list_item *item;
3186                        item = string_list_insert(&state->fn_table, patch->old_name);
3187                        item->util = PATH_TO_BE_DELETED;
3188                }
3189                patch = patch->next;
3190        }
3191}
3192
3193static int checkout_target(struct index_state *istate,
3194                           struct cache_entry *ce, struct stat *st)
3195{
3196        struct checkout costate;
3197
3198        memset(&costate, 0, sizeof(costate));
3199        costate.base_dir = "";
3200        costate.refresh_cache = 1;
3201        costate.istate = istate;
3202        if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3203                return error(_("cannot checkout %s"), ce->name);
3204        return 0;
3205}
3206
3207static struct patch *previous_patch(struct apply_state *state,
3208                                    struct patch *patch,
3209                                    int *gone)
3210{
3211        struct patch *previous;
3212
3213        *gone = 0;
3214        if (patch->is_copy || patch->is_rename)
3215                return NULL; /* "git" patches do not depend on the order */
3216
3217        previous = in_fn_table(state, patch->old_name);
3218        if (!previous)
3219                return NULL;
3220
3221        if (to_be_deleted(previous))
3222                return NULL; /* the deletion hasn't happened yet */
3223
3224        if (was_deleted(previous))
3225                *gone = 1;
3226
3227        return previous;
3228}
3229
3230static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3231{
3232        if (S_ISGITLINK(ce->ce_mode)) {
3233                if (!S_ISDIR(st->st_mode))
3234                        return -1;
3235                return 0;
3236        }
3237        return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3238}
3239
3240#define SUBMODULE_PATCH_WITHOUT_INDEX 1
3241
3242static int load_patch_target(struct apply_state *state,
3243                             struct strbuf *buf,
3244                             const struct cache_entry *ce,
3245                             struct stat *st,
3246                             const char *name,
3247                             unsigned expected_mode)
3248{
3249        if (state->cached || state->check_index) {
3250                if (read_file_or_gitlink(ce, buf))
3251                        return error(_("failed to read %s"), name);
3252        } else if (name) {
3253                if (S_ISGITLINK(expected_mode)) {
3254                        if (ce)
3255                                return read_file_or_gitlink(ce, buf);
3256                        else
3257                                return SUBMODULE_PATCH_WITHOUT_INDEX;
3258                } else if (has_symlink_leading_path(name, strlen(name))) {
3259                        return error(_("reading from '%s' beyond a symbolic link"), name);
3260                } else {
3261                        if (read_old_data(st, name, buf))
3262                                return error(_("failed to read %s"), name);
3263                }
3264        }
3265        return 0;
3266}
3267
3268/*
3269 * We are about to apply "patch"; populate the "image" with the
3270 * current version we have, from the working tree or from the index,
3271 * depending on the situation e.g. --cached/--index.  If we are
3272 * applying a non-git patch that incrementally updates the tree,
3273 * we read from the result of a previous diff.
3274 */
3275static int load_preimage(struct apply_state *state,
3276                         struct image *image,
3277                         struct patch *patch, struct stat *st,
3278                         const struct cache_entry *ce)
3279{
3280        struct strbuf buf = STRBUF_INIT;
3281        size_t len;
3282        char *img;
3283        struct patch *previous;
3284        int status;
3285
3286        previous = previous_patch(state, patch, &status);
3287        if (status)
3288                return error(_("path %s has been renamed/deleted"),
3289                             patch->old_name);
3290        if (previous) {
3291                /* We have a patched copy in memory; use that. */
3292                strbuf_add(&buf, previous->result, previous->resultsize);
3293        } else {
3294                status = load_patch_target(state, &buf, ce, st,
3295                                           patch->old_name, patch->old_mode);
3296                if (status < 0)
3297                        return status;
3298                else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3299                        /*
3300                         * There is no way to apply subproject
3301                         * patch without looking at the index.
3302                         * NEEDSWORK: shouldn't this be flagged
3303                         * as an error???
3304                         */
3305                        free_fragment_list(patch->fragments);
3306                        patch->fragments = NULL;
3307                } else if (status) {
3308                        return error(_("failed to read %s"), patch->old_name);
3309                }
3310        }
3311
3312        img = strbuf_detach(&buf, &len);
3313        prepare_image(image, img, len, !patch->is_binary);
3314        return 0;
3315}
3316
3317static int three_way_merge(struct image *image,
3318                           char *path,
3319                           const unsigned char *base,
3320                           const unsigned char *ours,
3321                           const unsigned char *theirs)
3322{
3323        mmfile_t base_file, our_file, their_file;
3324        mmbuffer_t result = { NULL };
3325        int status;
3326
3327        read_mmblob(&base_file, base);
3328        read_mmblob(&our_file, ours);
3329        read_mmblob(&their_file, theirs);
3330        status = ll_merge(&result, path,
3331                          &base_file, "base",
3332                          &our_file, "ours",
3333                          &their_file, "theirs", NULL);
3334        free(base_file.ptr);
3335        free(our_file.ptr);
3336        free(their_file.ptr);
3337        if (status < 0 || !result.ptr) {
3338                free(result.ptr);
3339                return -1;
3340        }
3341        clear_image(image);
3342        image->buf = result.ptr;
3343        image->len = result.size;
3344
3345        return status;
3346}
3347
3348/*
3349 * When directly falling back to add/add three-way merge, we read from
3350 * the current contents of the new_name.  In no cases other than that
3351 * this function will be called.
3352 */
3353static int load_current(struct apply_state *state,
3354                        struct image *image,
3355                        struct patch *patch)
3356{
3357        struct strbuf buf = STRBUF_INIT;
3358        int status, pos;
3359        size_t len;
3360        char *img;
3361        struct stat st;
3362        struct cache_entry *ce;
3363        char *name = patch->new_name;
3364        unsigned mode = patch->new_mode;
3365
3366        if (!patch->is_new)
3367                die("BUG: patch to %s is not a creation", patch->old_name);
3368
3369        pos = cache_name_pos(name, strlen(name));
3370        if (pos < 0)
3371                return error(_("%s: does not exist in index"), name);
3372        ce = active_cache[pos];
3373        if (lstat(name, &st)) {
3374                if (errno != ENOENT)
3375                        return error(_("%s: %s"), name, strerror(errno));
3376                if (checkout_target(&the_index, ce, &st))
3377                        return -1;
3378        }
3379        if (verify_index_match(ce, &st))
3380                return error(_("%s: does not match index"), name);
3381
3382        status = load_patch_target(state, &buf, ce, &st, name, mode);
3383        if (status < 0)
3384                return status;
3385        else if (status)
3386                return -1;
3387        img = strbuf_detach(&buf, &len);
3388        prepare_image(image, img, len, !patch->is_binary);
3389        return 0;
3390}
3391
3392static int try_threeway(struct apply_state *state,
3393                        struct image *image,
3394                        struct patch *patch,
3395                        struct stat *st,
3396                        const struct cache_entry *ce)
3397{
3398        unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3399        struct strbuf buf = STRBUF_INIT;
3400        size_t len;
3401        int status;
3402        char *img;
3403        struct image tmp_image;
3404
3405        /* No point falling back to 3-way merge in these cases */
3406        if (patch->is_delete ||
3407            S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3408                return -1;
3409
3410        /* Preimage the patch was prepared for */
3411        if (patch->is_new)
3412                write_sha1_file("", 0, blob_type, pre_sha1);
3413        else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3414                 read_blob_object(&buf, pre_sha1, patch->old_mode))
3415                return error("repository lacks the necessary blob to fall back on 3-way merge.");
3416
3417        fprintf(stderr, "Falling back to three-way merge...\n");
3418
3419        img = strbuf_detach(&buf, &len);
3420        prepare_image(&tmp_image, img, len, 1);
3421        /* Apply the patch to get the post image */
3422        if (apply_fragments(state, &tmp_image, patch) < 0) {
3423                clear_image(&tmp_image);
3424                return -1;
3425        }
3426        /* post_sha1[] is theirs */
3427        write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3428        clear_image(&tmp_image);
3429
3430        /* our_sha1[] is ours */
3431        if (patch->is_new) {
3432                if (load_current(state, &tmp_image, patch))
3433                        return error("cannot read the current contents of '%s'",
3434                                     patch->new_name);
3435        } else {
3436                if (load_preimage(state, &tmp_image, patch, st, ce))
3437                        return error("cannot read the current contents of '%s'",
3438                                     patch->old_name);
3439        }
3440        write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3441        clear_image(&tmp_image);
3442
3443        /* in-core three-way merge between post and our using pre as base */
3444        status = three_way_merge(image, patch->new_name,
3445                                 pre_sha1, our_sha1, post_sha1);
3446        if (status < 0) {
3447                fprintf(stderr, "Failed to fall back on three-way merge...\n");
3448                return status;
3449        }
3450
3451        if (status) {
3452                patch->conflicted_threeway = 1;
3453                if (patch->is_new)
3454                        oidclr(&patch->threeway_stage[0]);
3455                else
3456                        hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3457                hashcpy(patch->threeway_stage[1].hash, our_sha1);
3458                hashcpy(patch->threeway_stage[2].hash, post_sha1);
3459                fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3460        } else {
3461                fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3462        }
3463        return 0;
3464}
3465
3466static int apply_data(struct apply_state *state, struct patch *patch,
3467                      struct stat *st, const struct cache_entry *ce)
3468{
3469        struct image image;
3470
3471        if (load_preimage(state, &image, patch, st, ce) < 0)
3472                return -1;
3473
3474        if (patch->direct_to_threeway ||
3475            apply_fragments(state, &image, patch) < 0) {
3476                /* Note: with --reject, apply_fragments() returns 0 */
3477                if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)
3478                        return -1;
3479        }
3480        patch->result = image.buf;
3481        patch->resultsize = image.len;
3482        add_to_fn_table(state, patch);
3483        free(image.line_allocated);
3484
3485        if (0 < patch->is_delete && patch->resultsize)
3486                return error(_("removal patch leaves file contents"));
3487
3488        return 0;
3489}
3490
3491/*
3492 * If "patch" that we are looking at modifies or deletes what we have,
3493 * we would want it not to lose any local modification we have, either
3494 * in the working tree or in the index.
3495 *
3496 * This also decides if a non-git patch is a creation patch or a
3497 * modification to an existing empty file.  We do not check the state
3498 * of the current tree for a creation patch in this function; the caller
3499 * check_patch() separately makes sure (and errors out otherwise) that
3500 * the path the patch creates does not exist in the current tree.
3501 */
3502static int check_preimage(struct apply_state *state,
3503                          struct patch *patch,
3504                          struct cache_entry **ce,
3505                          struct stat *st)
3506{
3507        const char *old_name = patch->old_name;
3508        struct patch *previous = NULL;
3509        int stat_ret = 0, status;
3510        unsigned st_mode = 0;
3511
3512        if (!old_name)
3513                return 0;
3514
3515        assert(patch->is_new <= 0);
3516        previous = previous_patch(state, patch, &status);
3517
3518        if (status)
3519                return error(_("path %s has been renamed/deleted"), old_name);
3520        if (previous) {
3521                st_mode = previous->new_mode;
3522        } else if (!state->cached) {
3523                stat_ret = lstat(old_name, st);
3524                if (stat_ret && errno != ENOENT)
3525                        return error(_("%s: %s"), old_name, strerror(errno));
3526        }
3527
3528        if (state->check_index && !previous) {
3529                int pos = cache_name_pos(old_name, strlen(old_name));
3530                if (pos < 0) {
3531                        if (patch->is_new < 0)
3532                                goto is_new;
3533                        return error(_("%s: does not exist in index"), old_name);
3534                }
3535                *ce = active_cache[pos];
3536                if (stat_ret < 0) {
3537                        if (checkout_target(&the_index, *ce, st))
3538                                return -1;
3539                }
3540                if (!state->cached && verify_index_match(*ce, st))
3541                        return error(_("%s: does not match index"), old_name);
3542                if (state->cached)
3543                        st_mode = (*ce)->ce_mode;
3544        } else if (stat_ret < 0) {
3545                if (patch->is_new < 0)
3546                        goto is_new;
3547                return error(_("%s: %s"), old_name, strerror(errno));
3548        }
3549
3550        if (!state->cached && !previous)
3551                st_mode = ce_mode_from_stat(*ce, st->st_mode);
3552
3553        if (patch->is_new < 0)
3554                patch->is_new = 0;
3555        if (!patch->old_mode)
3556                patch->old_mode = st_mode;
3557        if ((st_mode ^ patch->old_mode) & S_IFMT)
3558                return error(_("%s: wrong type"), old_name);
3559        if (st_mode != patch->old_mode)
3560                warning(_("%s has type %o, expected %o"),
3561                        old_name, st_mode, patch->old_mode);
3562        if (!patch->new_mode && !patch->is_delete)
3563                patch->new_mode = st_mode;
3564        return 0;
3565
3566 is_new:
3567        patch->is_new = 1;
3568        patch->is_delete = 0;
3569        free(patch->old_name);
3570        patch->old_name = NULL;
3571        return 0;
3572}
3573
3574
3575#define EXISTS_IN_INDEX 1
3576#define EXISTS_IN_WORKTREE 2
3577
3578static int check_to_create(struct apply_state *state,
3579                           const char *new_name,
3580                           int ok_if_exists)
3581{
3582        struct stat nst;
3583
3584        if (state->check_index &&
3585            cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3586            !ok_if_exists)
3587                return EXISTS_IN_INDEX;
3588        if (state->cached)
3589                return 0;
3590
3591        if (!lstat(new_name, &nst)) {
3592                if (S_ISDIR(nst.st_mode) || ok_if_exists)
3593                        return 0;
3594                /*
3595                 * A leading component of new_name might be a symlink
3596                 * that is going to be removed with this patch, but
3597                 * still pointing at somewhere that has the path.
3598                 * In such a case, path "new_name" does not exist as
3599                 * far as git is concerned.
3600                 */
3601                if (has_symlink_leading_path(new_name, strlen(new_name)))
3602                        return 0;
3603
3604                return EXISTS_IN_WORKTREE;
3605        } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3606                return error("%s: %s", new_name, strerror(errno));
3607        }
3608        return 0;
3609}
3610
3611static uintptr_t register_symlink_changes(struct apply_state *state,
3612                                          const char *path,
3613                                          uintptr_t what)
3614{
3615        struct string_list_item *ent;
3616
3617        ent = string_list_lookup(&state->symlink_changes, path);
3618        if (!ent) {
3619                ent = string_list_insert(&state->symlink_changes, path);
3620                ent->util = (void *)0;
3621        }
3622        ent->util = (void *)(what | ((uintptr_t)ent->util));
3623        return (uintptr_t)ent->util;
3624}
3625
3626static uintptr_t check_symlink_changes(struct apply_state *state, const char *path)
3627{
3628        struct string_list_item *ent;
3629
3630        ent = string_list_lookup(&state->symlink_changes, path);
3631        if (!ent)
3632                return 0;
3633        return (uintptr_t)ent->util;
3634}
3635
3636static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3637{
3638        for ( ; patch; patch = patch->next) {
3639                if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3640                    (patch->is_rename || patch->is_delete))
3641                        /* the symlink at patch->old_name is removed */
3642                        register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);
3643
3644                if (patch->new_name && S_ISLNK(patch->new_mode))
3645                        /* the symlink at patch->new_name is created or remains */
3646                        register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);
3647        }
3648}
3649
3650static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3651{
3652        do {
3653                unsigned int change;
3654
3655                while (--name->len && name->buf[name->len] != '/')
3656                        ; /* scan backwards */
3657                if (!name->len)
3658                        break;
3659                name->buf[name->len] = '\0';
3660                change = check_symlink_changes(state, name->buf);
3661                if (change & APPLY_SYMLINK_IN_RESULT)
3662                        return 1;
3663                if (change & APPLY_SYMLINK_GOES_AWAY)
3664                        /*
3665                         * This cannot be "return 0", because we may
3666                         * see a new one created at a higher level.
3667                         */
3668                        continue;
3669
3670                /* otherwise, check the preimage */
3671                if (state->check_index) {
3672                        struct cache_entry *ce;
3673
3674                        ce = cache_file_exists(name->buf, name->len, ignore_case);
3675                        if (ce && S_ISLNK(ce->ce_mode))
3676                                return 1;
3677                } else {
3678                        struct stat st;
3679                        if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3680                                return 1;
3681                }
3682        } while (1);
3683        return 0;
3684}
3685
3686static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3687{
3688        int ret;
3689        struct strbuf name = STRBUF_INIT;
3690
3691        assert(*name_ != '\0');
3692        strbuf_addstr(&name, name_);
3693        ret = path_is_beyond_symlink_1(state, &name);
3694        strbuf_release(&name);
3695
3696        return ret;
3697}
3698
3699static void die_on_unsafe_path(struct patch *patch)
3700{
3701        const char *old_name = NULL;
3702        const char *new_name = NULL;
3703        if (patch->is_delete)
3704                old_name = patch->old_name;
3705        else if (!patch->is_new && !patch->is_copy)
3706                old_name = patch->old_name;
3707        if (!patch->is_delete)
3708                new_name = patch->new_name;
3709
3710        if (old_name && !verify_path(old_name))
3711                die(_("invalid path '%s'"), old_name);
3712        if (new_name && !verify_path(new_name))
3713                die(_("invalid path '%s'"), new_name);
3714}
3715
3716/*
3717 * Check and apply the patch in-core; leave the result in patch->result
3718 * for the caller to write it out to the final destination.
3719 */
3720static int check_patch(struct apply_state *state, struct patch *patch)
3721{
3722        struct stat st;
3723        const char *old_name = patch->old_name;
3724        const char *new_name = patch->new_name;
3725        const char *name = old_name ? old_name : new_name;
3726        struct cache_entry *ce = NULL;
3727        struct patch *tpatch;
3728        int ok_if_exists;
3729        int status;
3730
3731        patch->rejected = 1; /* we will drop this after we succeed */
3732
3733        status = check_preimage(state, patch, &ce, &st);
3734        if (status)
3735                return status;
3736        old_name = patch->old_name;
3737
3738        /*
3739         * A type-change diff is always split into a patch to delete
3740         * old, immediately followed by a patch to create new (see
3741         * diff.c::run_diff()); in such a case it is Ok that the entry
3742         * to be deleted by the previous patch is still in the working
3743         * tree and in the index.
3744         *
3745         * A patch to swap-rename between A and B would first rename A
3746         * to B and then rename B to A.  While applying the first one,
3747         * the presence of B should not stop A from getting renamed to
3748         * B; ask to_be_deleted() about the later rename.  Removal of
3749         * B and rename from A to B is handled the same way by asking
3750         * was_deleted().
3751         */
3752        if ((tpatch = in_fn_table(state, new_name)) &&
3753            (was_deleted(tpatch) || to_be_deleted(tpatch)))
3754                ok_if_exists = 1;
3755        else
3756                ok_if_exists = 0;
3757
3758        if (new_name &&
3759            ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3760                int err = check_to_create(state, new_name, ok_if_exists);
3761
3762                if (err && state->threeway) {
3763                        patch->direct_to_threeway = 1;
3764                } else switch (err) {
3765                case 0:
3766                        break; /* happy */
3767                case EXISTS_IN_INDEX:
3768                        return error(_("%s: already exists in index"), new_name);
3769                        break;
3770                case EXISTS_IN_WORKTREE:
3771                        return error(_("%s: already exists in working directory"),
3772                                     new_name);
3773                default:
3774                        return err;
3775                }
3776
3777                if (!patch->new_mode) {
3778                        if (0 < patch->is_new)
3779                                patch->new_mode = S_IFREG | 0644;
3780                        else
3781                                patch->new_mode = patch->old_mode;
3782                }
3783        }
3784
3785        if (new_name && old_name) {
3786                int same = !strcmp(old_name, new_name);
3787                if (!patch->new_mode)
3788                        patch->new_mode = patch->old_mode;
3789                if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3790                        if (same)
3791                                return error(_("new mode (%o) of %s does not "
3792                                               "match old mode (%o)"),
3793                                        patch->new_mode, new_name,
3794                                        patch->old_mode);
3795                        else
3796                                return error(_("new mode (%o) of %s does not "
3797                                               "match old mode (%o) of %s"),
3798                                        patch->new_mode, new_name,
3799                                        patch->old_mode, old_name);
3800                }
3801        }
3802
3803        if (!state->unsafe_paths)
3804                die_on_unsafe_path(patch);
3805
3806        /*
3807         * An attempt to read from or delete a path that is beyond a
3808         * symbolic link will be prevented by load_patch_target() that
3809         * is called at the beginning of apply_data() so we do not
3810         * have to worry about a patch marked with "is_delete" bit
3811         * here.  We however need to make sure that the patch result
3812         * is not deposited to a path that is beyond a symbolic link
3813         * here.
3814         */
3815        if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3816                return error(_("affected file '%s' is beyond a symbolic link"),
3817                             patch->new_name);
3818
3819        if (apply_data(state, patch, &st, ce) < 0)
3820                return error(_("%s: patch does not apply"), name);
3821        patch->rejected = 0;
3822        return 0;
3823}
3824
3825static int check_patch_list(struct apply_state *state, struct patch *patch)
3826{
3827        int err = 0;
3828
3829        prepare_symlink_changes(state, patch);
3830        prepare_fn_table(state, patch);
3831        while (patch) {
3832                if (state->apply_verbosely)
3833                        say_patch_name(stderr,
3834                                       _("Checking patch %s..."), patch);
3835                err |= check_patch(state, patch);
3836                patch = patch->next;
3837        }
3838        return err;
3839}
3840
3841/* This function tries to read the sha1 from the current index */
3842static int get_current_sha1(const char *path, unsigned char *sha1)
3843{
3844        int pos;
3845
3846        if (read_cache() < 0)
3847                return -1;
3848        pos = cache_name_pos(path, strlen(path));
3849        if (pos < 0)
3850                return -1;
3851        hashcpy(sha1, active_cache[pos]->sha1);
3852        return 0;
3853}
3854
3855static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3856{
3857        /*
3858         * A usable gitlink patch has only one fragment (hunk) that looks like:
3859         * @@ -1 +1 @@
3860         * -Subproject commit <old sha1>
3861         * +Subproject commit <new sha1>
3862         * or
3863         * @@ -1 +0,0 @@
3864         * -Subproject commit <old sha1>
3865         * for a removal patch.
3866         */
3867        struct fragment *hunk = p->fragments;
3868        static const char heading[] = "-Subproject commit ";
3869        char *preimage;
3870
3871        if (/* does the patch have only one hunk? */
3872            hunk && !hunk->next &&
3873            /* is its preimage one line? */
3874            hunk->oldpos == 1 && hunk->oldlines == 1 &&
3875            /* does preimage begin with the heading? */
3876            (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3877            starts_with(++preimage, heading) &&
3878            /* does it record full SHA-1? */
3879            !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3880            preimage[sizeof(heading) + 40 - 1] == '\n' &&
3881            /* does the abbreviated name on the index line agree with it? */
3882            starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3883                return 0; /* it all looks fine */
3884
3885        /* we may have full object name on the index line */
3886        return get_sha1_hex(p->old_sha1_prefix, sha1);
3887}
3888
3889/* Build an index that contains the just the files needed for a 3way merge */
3890static void build_fake_ancestor(struct patch *list, const char *filename)
3891{
3892        struct patch *patch;
3893        struct index_state result = { NULL };
3894        static struct lock_file lock;
3895
3896        /* Once we start supporting the reverse patch, it may be
3897         * worth showing the new sha1 prefix, but until then...
3898         */
3899        for (patch = list; patch; patch = patch->next) {
3900                unsigned char sha1[20];
3901                struct cache_entry *ce;
3902                const char *name;
3903
3904                name = patch->old_name ? patch->old_name : patch->new_name;
3905                if (0 < patch->is_new)
3906                        continue;
3907
3908                if (S_ISGITLINK(patch->old_mode)) {
3909                        if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3910                                ; /* ok, the textual part looks sane */
3911                        else
3912                                die("sha1 information is lacking or useless for submodule %s",
3913                                    name);
3914                } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3915                        ; /* ok */
3916                } else if (!patch->lines_added && !patch->lines_deleted) {
3917                        /* mode-only change: update the current */
3918                        if (get_current_sha1(patch->old_name, sha1))
3919                                die("mode change for %s, which is not "
3920                                    "in current HEAD", name);
3921                } else
3922                        die("sha1 information is lacking or useless "
3923                            "(%s).", name);
3924
3925                ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3926                if (!ce)
3927                        die(_("make_cache_entry failed for path '%s'"), name);
3928                if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3929                        die ("Could not add %s to temporary index", name);
3930        }
3931
3932        hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3933        if (write_locked_index(&result, &lock, COMMIT_LOCK))
3934                die ("Could not write temporary index to %s", filename);
3935
3936        discard_index(&result);
3937}
3938
3939static void stat_patch_list(struct apply_state *state, struct patch *patch)
3940{
3941        int files, adds, dels;
3942
3943        for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3944                files++;
3945                adds += patch->lines_added;
3946                dels += patch->lines_deleted;
3947                show_stats(state, patch);
3948        }
3949
3950        print_stat_summary(stdout, files, adds, dels);
3951}
3952
3953static void numstat_patch_list(struct apply_state *state,
3954                               struct patch *patch)
3955{
3956        for ( ; patch; patch = patch->next) {
3957                const char *name;
3958                name = patch->new_name ? patch->new_name : patch->old_name;
3959                if (patch->is_binary)
3960                        printf("-\t-\t");
3961                else
3962                        printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3963                write_name_quoted(name, stdout, state->line_termination);
3964        }
3965}
3966
3967static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3968{
3969        if (mode)
3970                printf(" %s mode %06o %s\n", newdelete, mode, name);
3971        else
3972                printf(" %s %s\n", newdelete, name);
3973}
3974
3975static void show_mode_change(struct patch *p, int show_name)
3976{
3977        if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3978                if (show_name)
3979                        printf(" mode change %06o => %06o %s\n",
3980                               p->old_mode, p->new_mode, p->new_name);
3981                else
3982                        printf(" mode change %06o => %06o\n",
3983                               p->old_mode, p->new_mode);
3984        }
3985}
3986
3987static void show_rename_copy(struct patch *p)
3988{
3989        const char *renamecopy = p->is_rename ? "rename" : "copy";
3990        const char *old, *new;
3991
3992        /* Find common prefix */
3993        old = p->old_name;
3994        new = p->new_name;
3995        while (1) {
3996                const char *slash_old, *slash_new;
3997                slash_old = strchr(old, '/');
3998                slash_new = strchr(new, '/');
3999                if (!slash_old ||
4000                    !slash_new ||
4001                    slash_old - old != slash_new - new ||
4002                    memcmp(old, new, slash_new - new))
4003                        break;
4004                old = slash_old + 1;
4005                new = slash_new + 1;
4006        }
4007        /* p->old_name thru old is the common prefix, and old and new
4008         * through the end of names are renames
4009         */
4010        if (old != p->old_name)
4011                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4012                       (int)(old - p->old_name), p->old_name,
4013                       old, new, p->score);
4014        else
4015                printf(" %s %s => %s (%d%%)\n", renamecopy,
4016                       p->old_name, p->new_name, p->score);
4017        show_mode_change(p, 0);
4018}
4019
4020static void summary_patch_list(struct patch *patch)
4021{
4022        struct patch *p;
4023
4024        for (p = patch; p; p = p->next) {
4025                if (p->is_new)
4026                        show_file_mode_name("create", p->new_mode, p->new_name);
4027                else if (p->is_delete)
4028                        show_file_mode_name("delete", p->old_mode, p->old_name);
4029                else {
4030                        if (p->is_rename || p->is_copy)
4031                                show_rename_copy(p);
4032                        else {
4033                                if (p->score) {
4034                                        printf(" rewrite %s (%d%%)\n",
4035                                               p->new_name, p->score);
4036                                        show_mode_change(p, 0);
4037                                }
4038                                else
4039                                        show_mode_change(p, 1);
4040                        }
4041                }
4042        }
4043}
4044
4045static void patch_stats(struct apply_state *state, struct patch *patch)
4046{
4047        int lines = patch->lines_added + patch->lines_deleted;
4048
4049        if (lines > state->max_change)
4050                state->max_change = lines;
4051        if (patch->old_name) {
4052                int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4053                if (!len)
4054                        len = strlen(patch->old_name);
4055                if (len > state->max_len)
4056                        state->max_len = len;
4057        }
4058        if (patch->new_name) {
4059                int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4060                if (!len)
4061                        len = strlen(patch->new_name);
4062                if (len > state->max_len)
4063                        state->max_len = len;
4064        }
4065}
4066
4067static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4068{
4069        if (state->update_index) {
4070                if (remove_file_from_cache(patch->old_name) < 0)
4071                        die(_("unable to remove %s from index"), patch->old_name);
4072        }
4073        if (!state->cached) {
4074                if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4075                        remove_path(patch->old_name);
4076                }
4077        }
4078}
4079
4080static void add_index_file(struct apply_state *state,
4081                           const char *path,
4082                           unsigned mode,
4083                           void *buf,
4084                           unsigned long size)
4085{
4086        struct stat st;
4087        struct cache_entry *ce;
4088        int namelen = strlen(path);
4089        unsigned ce_size = cache_entry_size(namelen);
4090
4091        if (!state->update_index)
4092                return;
4093
4094        ce = xcalloc(1, ce_size);
4095        memcpy(ce->name, path, namelen);
4096        ce->ce_mode = create_ce_mode(mode);
4097        ce->ce_flags = create_ce_flags(0);
4098        ce->ce_namelen = namelen;
4099        if (S_ISGITLINK(mode)) {
4100                const char *s;
4101
4102                if (!skip_prefix(buf, "Subproject commit ", &s) ||
4103                    get_sha1_hex(s, ce->sha1))
4104                        die(_("corrupt patch for submodule %s"), path);
4105        } else {
4106                if (!state->cached) {
4107                        if (lstat(path, &st) < 0)
4108                                die_errno(_("unable to stat newly created file '%s'"),
4109                                          path);
4110                        fill_stat_cache_info(ce, &st);
4111                }
4112                if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4113                        die(_("unable to create backing store for newly created file %s"), path);
4114        }
4115        if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4116                die(_("unable to add cache entry for %s"), path);
4117}
4118
4119static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4120{
4121        int fd;
4122        struct strbuf nbuf = STRBUF_INIT;
4123
4124        if (S_ISGITLINK(mode)) {
4125                struct stat st;
4126                if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4127                        return 0;
4128                return mkdir(path, 0777);
4129        }
4130
4131        if (has_symlinks && S_ISLNK(mode))
4132                /* Although buf:size is counted string, it also is NUL
4133                 * terminated.
4134                 */
4135                return symlink(buf, path);
4136
4137        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4138        if (fd < 0)
4139                return -1;
4140
4141        if (convert_to_working_tree(path, buf, size, &nbuf)) {
4142                size = nbuf.len;
4143                buf  = nbuf.buf;
4144        }
4145        write_or_die(fd, buf, size);
4146        strbuf_release(&nbuf);
4147
4148        if (close(fd) < 0)
4149                die_errno(_("closing file '%s'"), path);
4150        return 0;
4151}
4152
4153/*
4154 * We optimistically assume that the directories exist,
4155 * which is true 99% of the time anyway. If they don't,
4156 * we create them and try again.
4157 */
4158static void create_one_file(struct apply_state *state,
4159                            char *path,
4160                            unsigned mode,
4161                            const char *buf,
4162                            unsigned long size)
4163{
4164        if (state->cached)
4165                return;
4166        if (!try_create_file(path, mode, buf, size))
4167                return;
4168
4169        if (errno == ENOENT) {
4170                if (safe_create_leading_directories(path))
4171                        return;
4172                if (!try_create_file(path, mode, buf, size))
4173                        return;
4174        }
4175
4176        if (errno == EEXIST || errno == EACCES) {
4177                /* We may be trying to create a file where a directory
4178                 * used to be.
4179                 */
4180                struct stat st;
4181                if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4182                        errno = EEXIST;
4183        }
4184
4185        if (errno == EEXIST) {
4186                unsigned int nr = getpid();
4187
4188                for (;;) {
4189                        char newpath[PATH_MAX];
4190                        mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4191                        if (!try_create_file(newpath, mode, buf, size)) {
4192                                if (!rename(newpath, path))
4193                                        return;
4194                                unlink_or_warn(newpath);
4195                                break;
4196                        }
4197                        if (errno != EEXIST)
4198                                break;
4199                        ++nr;
4200                }
4201        }
4202        die_errno(_("unable to write file '%s' mode %o"), path, mode);
4203}
4204
4205static void add_conflicted_stages_file(struct apply_state *state,
4206                                       struct patch *patch)
4207{
4208        int stage, namelen;
4209        unsigned ce_size, mode;
4210        struct cache_entry *ce;
4211
4212        if (!state->update_index)
4213                return;
4214        namelen = strlen(patch->new_name);
4215        ce_size = cache_entry_size(namelen);
4216        mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4217
4218        remove_file_from_cache(patch->new_name);
4219        for (stage = 1; stage < 4; stage++) {
4220                if (is_null_oid(&patch->threeway_stage[stage - 1]))
4221                        continue;
4222                ce = xcalloc(1, ce_size);
4223                memcpy(ce->name, patch->new_name, namelen);
4224                ce->ce_mode = create_ce_mode(mode);
4225                ce->ce_flags = create_ce_flags(stage);
4226                ce->ce_namelen = namelen;
4227                hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4228                if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4229                        die(_("unable to add cache entry for %s"), patch->new_name);
4230        }
4231}
4232
4233static void create_file(struct apply_state *state, struct patch *patch)
4234{
4235        char *path = patch->new_name;
4236        unsigned mode = patch->new_mode;
4237        unsigned long size = patch->resultsize;
4238        char *buf = patch->result;
4239
4240        if (!mode)
4241                mode = S_IFREG | 0644;
4242        create_one_file(state, path, mode, buf, size);
4243
4244        if (patch->conflicted_threeway)
4245                add_conflicted_stages_file(state, patch);
4246        else
4247                add_index_file(state, path, mode, buf, size);
4248}
4249
4250/* phase zero is to remove, phase one is to create */
4251static void write_out_one_result(struct apply_state *state,
4252                                 struct patch *patch,
4253                                 int phase)
4254{
4255        if (patch->is_delete > 0) {
4256                if (phase == 0)
4257                        remove_file(state, patch, 1);
4258                return;
4259        }
4260        if (patch->is_new > 0 || patch->is_copy) {
4261                if (phase == 1)
4262                        create_file(state, patch);
4263                return;
4264        }
4265        /*
4266         * Rename or modification boils down to the same
4267         * thing: remove the old, write the new
4268         */
4269        if (phase == 0)
4270                remove_file(state, patch, patch->is_rename);
4271        if (phase == 1)
4272                create_file(state, patch);
4273}
4274
4275static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4276{
4277        FILE *rej;
4278        char namebuf[PATH_MAX];
4279        struct fragment *frag;
4280        int cnt = 0;
4281        struct strbuf sb = STRBUF_INIT;
4282
4283        for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4284                if (!frag->rejected)
4285                        continue;
4286                cnt++;
4287        }
4288
4289        if (!cnt) {
4290                if (state->apply_verbosely)
4291                        say_patch_name(stderr,
4292                                       _("Applied patch %s cleanly."), patch);
4293                return 0;
4294        }
4295
4296        /* This should not happen, because a removal patch that leaves
4297         * contents are marked "rejected" at the patch level.
4298         */
4299        if (!patch->new_name)
4300                die(_("internal error"));
4301
4302        /* Say this even without --verbose */
4303        strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4304                            "Applying patch %%s with %d rejects...",
4305                            cnt),
4306                    cnt);
4307        say_patch_name(stderr, sb.buf, patch);
4308        strbuf_release(&sb);
4309
4310        cnt = strlen(patch->new_name);
4311        if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4312                cnt = ARRAY_SIZE(namebuf) - 5;
4313                warning(_("truncating .rej filename to %.*s.rej"),
4314                        cnt - 1, patch->new_name);
4315        }
4316        memcpy(namebuf, patch->new_name, cnt);
4317        memcpy(namebuf + cnt, ".rej", 5);
4318
4319        rej = fopen(namebuf, "w");
4320        if (!rej)
4321                return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4322
4323        /* Normal git tools never deal with .rej, so do not pretend
4324         * this is a git patch by saying --git or giving extended
4325         * headers.  While at it, maybe please "kompare" that wants
4326         * the trailing TAB and some garbage at the end of line ;-).
4327         */
4328        fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4329                patch->new_name, patch->new_name);
4330        for (cnt = 1, frag = patch->fragments;
4331             frag;
4332             cnt++, frag = frag->next) {
4333                if (!frag->rejected) {
4334                        fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4335                        continue;
4336                }
4337                fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4338                fprintf(rej, "%.*s", frag->size, frag->patch);
4339                if (frag->patch[frag->size-1] != '\n')
4340                        fputc('\n', rej);
4341        }
4342        fclose(rej);
4343        return -1;
4344}
4345
4346static int write_out_results(struct apply_state *state, struct patch *list)
4347{
4348        int phase;
4349        int errs = 0;
4350        struct patch *l;
4351        struct string_list cpath = STRING_LIST_INIT_DUP;
4352
4353        for (phase = 0; phase < 2; phase++) {
4354                l = list;
4355                while (l) {
4356                        if (l->rejected)
4357                                errs = 1;
4358                        else {
4359                                write_out_one_result(state, l, phase);
4360                                if (phase == 1) {
4361                                        if (write_out_one_reject(state, l))
4362                                                errs = 1;
4363                                        if (l->conflicted_threeway) {
4364                                                string_list_append(&cpath, l->new_name);
4365                                                errs = 1;
4366                                        }
4367                                }
4368                        }
4369                        l = l->next;
4370                }
4371        }
4372
4373        if (cpath.nr) {
4374                struct string_list_item *item;
4375
4376                string_list_sort(&cpath);
4377                for_each_string_list_item(item, &cpath)
4378                        fprintf(stderr, "U %s\n", item->string);
4379                string_list_clear(&cpath, 0);
4380
4381                rerere(0);
4382        }
4383
4384        return errs;
4385}
4386
4387static struct lock_file lock_file;
4388
4389#define INACCURATE_EOF  (1<<0)
4390#define RECOUNT         (1<<1)
4391
4392/*
4393 * Try to apply a patch.
4394 *
4395 * Returns:
4396 *  -128 if a bad error happened (like patch unreadable)
4397 *  -1 if patch did not apply and user cannot deal with it
4398 *   0 if the patch applied
4399 *   1 if the patch did not apply but user might fix it
4400 */
4401static int apply_patch(struct apply_state *state,
4402                       int fd,
4403                       const char *filename,
4404                       int options)
4405{
4406        size_t offset;
4407        struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4408        struct patch *list = NULL, **listp = &list;
4409        int skipped_patch = 0;
4410        int res = 0;
4411
4412        state->patch_input_file = filename;
4413        if (read_patch_file(&buf, fd) < 0)
4414                return -128;
4415        offset = 0;
4416        while (offset < buf.len) {
4417                struct patch *patch;
4418                int nr;
4419
4420                patch = xcalloc(1, sizeof(*patch));
4421                patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4422                patch->recount =  !!(options & RECOUNT);
4423                nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4424                if (nr < 0) {
4425                        free_patch(patch);
4426                        if (nr == -128) {
4427                                res = -128;
4428                                goto end;
4429                        }
4430                        break;
4431                }
4432                if (state->apply_in_reverse)
4433                        reverse_patches(patch);
4434                if (use_patch(state, patch)) {
4435                        patch_stats(state, patch);
4436                        *listp = patch;
4437                        listp = &patch->next;
4438                }
4439                else {
4440                        if (state->apply_verbosely)
4441                                say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4442                        free_patch(patch);
4443                        skipped_patch++;
4444                }
4445                offset += nr;
4446        }
4447
4448        if (!list && !skipped_patch) {
4449                error(_("unrecognized input"));
4450                res = -128;
4451                goto end;
4452        }
4453
4454        if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4455                state->apply = 0;
4456
4457        state->update_index = state->check_index && state->apply;
4458        if (state->update_index && state->newfd < 0)
4459                state->newfd = hold_locked_index(state->lock_file, 1);
4460
4461        if (state->check_index && read_cache() < 0) {
4462                error(_("unable to read index file"));
4463                res = -128;
4464                goto end;
4465        }
4466
4467        if ((state->check || state->apply) &&
4468            check_patch_list(state, list) < 0 &&
4469            !state->apply_with_reject) {
4470                res = -1;
4471                goto end;
4472        }
4473
4474        if (state->apply && write_out_results(state, list)) {
4475                /* with --3way, we still need to write the index out */
4476                res = state->apply_with_reject ? -1 : 1;
4477                goto end;
4478        }
4479
4480        if (state->fake_ancestor)
4481                build_fake_ancestor(list, state->fake_ancestor);
4482
4483        if (state->diffstat)
4484                stat_patch_list(state, list);
4485
4486        if (state->numstat)
4487                numstat_patch_list(state, list);
4488
4489        if (state->summary)
4490                summary_patch_list(list);
4491
4492end:
4493        free_patch_list(list);
4494        strbuf_release(&buf);
4495        string_list_clear(&state->fn_table, 0);
4496        return res;
4497}
4498
4499static int option_parse_exclude(const struct option *opt,
4500                                const char *arg, int unset)
4501{
4502        struct apply_state *state = opt->value;
4503        add_name_limit(state, arg, 1);
4504        return 0;
4505}
4506
4507static int option_parse_include(const struct option *opt,
4508                                const char *arg, int unset)
4509{
4510        struct apply_state *state = opt->value;
4511        add_name_limit(state, arg, 0);
4512        state->has_include = 1;
4513        return 0;
4514}
4515
4516static int option_parse_p(const struct option *opt,
4517                          const char *arg,
4518                          int unset)
4519{
4520        struct apply_state *state = opt->value;
4521        state->p_value = atoi(arg);
4522        state->p_value_known = 1;
4523        return 0;
4524}
4525
4526static int option_parse_space_change(const struct option *opt,
4527                                     const char *arg, int unset)
4528{
4529        struct apply_state *state = opt->value;
4530        if (unset)
4531                state->ws_ignore_action = ignore_ws_none;
4532        else
4533                state->ws_ignore_action = ignore_ws_change;
4534        return 0;
4535}
4536
4537static int option_parse_whitespace(const struct option *opt,
4538                                   const char *arg, int unset)
4539{
4540        struct apply_state *state = opt->value;
4541        state->whitespace_option = arg;
4542        if (parse_whitespace_option(state, arg))
4543                exit(1);
4544        return 0;
4545}
4546
4547static int option_parse_directory(const struct option *opt,
4548                                  const char *arg, int unset)
4549{
4550        struct apply_state *state = opt->value;
4551        strbuf_reset(&state->root);
4552        strbuf_addstr(&state->root, arg);
4553        strbuf_complete(&state->root, '/');
4554        return 0;
4555}
4556
4557static int apply_all_patches(struct apply_state *state,
4558                             int argc,
4559                             const char **argv,
4560                             int options)
4561{
4562        int i;
4563        int res;
4564        int errs = 0;
4565        int read_stdin = 1;
4566
4567        for (i = 0; i < argc; i++) {
4568                const char *arg = argv[i];
4569                int fd;
4570
4571                if (!strcmp(arg, "-")) {
4572                        res = apply_patch(state, 0, "<stdin>", options);
4573                        if (res < 0)
4574                                goto end;
4575                        errs |= res;
4576                        read_stdin = 0;
4577                        continue;
4578                } else if (0 < state->prefix_length)
4579                        arg = prefix_filename(state->prefix,
4580                                              state->prefix_length,
4581                                              arg);
4582
4583                fd = open(arg, O_RDONLY);
4584                if (fd < 0) {
4585                        error(_("can't open patch '%s': %s"), arg, strerror(errno));
4586                        res = -128;
4587                        goto end;
4588                }
4589                read_stdin = 0;
4590                set_default_whitespace_mode(state);
4591                res = apply_patch(state, fd, arg, options);
4592                close(fd);
4593                if (res < 0)
4594                        goto end;
4595                errs |= res;
4596        }
4597        set_default_whitespace_mode(state);
4598        if (read_stdin) {
4599                res = apply_patch(state, 0, "<stdin>", options);
4600                if (res < 0)
4601                        goto end;
4602                errs |= res;
4603        }
4604
4605        if (state->whitespace_error) {
4606                if (state->squelch_whitespace_errors &&
4607                    state->squelch_whitespace_errors < state->whitespace_error) {
4608                        int squelched =
4609                                state->whitespace_error - state->squelch_whitespace_errors;
4610                        warning(Q_("squelched %d whitespace error",
4611                                   "squelched %d whitespace errors",
4612                                   squelched),
4613                                squelched);
4614                }
4615                if (state->ws_error_action == die_on_ws_error) {
4616                        error(Q_("%d line adds whitespace errors.",
4617                                 "%d lines add whitespace errors.",
4618                                 state->whitespace_error),
4619                              state->whitespace_error);
4620                        res = -128;
4621                        goto end;
4622                }
4623                if (state->applied_after_fixing_ws && state->apply)
4624                        warning("%d line%s applied after"
4625                                " fixing whitespace errors.",
4626                                state->applied_after_fixing_ws,
4627                                state->applied_after_fixing_ws == 1 ? "" : "s");
4628                else if (state->whitespace_error)
4629                        warning(Q_("%d line adds whitespace errors.",
4630                                   "%d lines add whitespace errors.",
4631                                   state->whitespace_error),
4632                                state->whitespace_error);
4633        }
4634
4635        if (state->update_index) {
4636                res = write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);
4637                if (res) {
4638                        error(_("Unable to write new index file"));
4639                        res = -128;
4640                        goto end;
4641                }
4642                state->newfd = -1;
4643        }
4644
4645        return !!errs;
4646
4647end:
4648        if (state->newfd >= 0) {
4649                rollback_lock_file(state->lock_file);
4650                state->newfd = -1;
4651        }
4652
4653        return (res == -1 ? 1 : 128);
4654}
4655
4656int cmd_apply(int argc, const char **argv, const char *prefix)
4657{
4658        int force_apply = 0;
4659        int options = 0;
4660        int ret;
4661        struct apply_state state;
4662
4663        struct option builtin_apply_options[] = {
4664                { OPTION_CALLBACK, 0, "exclude", &state, N_("path"),
4665                        N_("don't apply changes matching the given path"),
4666                        0, option_parse_exclude },
4667                { OPTION_CALLBACK, 0, "include", &state, N_("path"),
4668                        N_("apply changes matching the given path"),
4669                        0, option_parse_include },
4670                { OPTION_CALLBACK, 'p', NULL, &state, N_("num"),
4671                        N_("remove <num> leading slashes from traditional diff paths"),
4672                        0, option_parse_p },
4673                OPT_BOOL(0, "no-add", &state.no_add,
4674                        N_("ignore additions made by the patch")),
4675                OPT_BOOL(0, "stat", &state.diffstat,
4676                        N_("instead of applying the patch, output diffstat for the input")),
4677                OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4678                OPT_NOOP_NOARG(0, "binary"),
4679                OPT_BOOL(0, "numstat", &state.numstat,
4680                        N_("show number of added and deleted lines in decimal notation")),
4681                OPT_BOOL(0, "summary", &state.summary,
4682                        N_("instead of applying the patch, output a summary for the input")),
4683                OPT_BOOL(0, "check", &state.check,
4684                        N_("instead of applying the patch, see if the patch is applicable")),
4685                OPT_BOOL(0, "index", &state.check_index,
4686                        N_("make sure the patch is applicable to the current index")),
4687                OPT_BOOL(0, "cached", &state.cached,
4688                        N_("apply a patch without touching the working tree")),
4689                OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,
4690                        N_("accept a patch that touches outside the working area")),
4691                OPT_BOOL(0, "apply", &force_apply,
4692                        N_("also apply the patch (use with --stat/--summary/--check)")),
4693                OPT_BOOL('3', "3way", &state.threeway,
4694                         N_( "attempt three-way merge if a patch does not apply")),
4695                OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,
4696                        N_("build a temporary index based on embedded index information")),
4697                /* Think twice before adding "--nul" synonym to this */
4698                OPT_SET_INT('z', NULL, &state.line_termination,
4699                        N_("paths are separated with NUL character"), '\0'),
4700                OPT_INTEGER('C', NULL, &state.p_context,
4701                                N_("ensure at least <n> lines of context match")),
4702                { OPTION_CALLBACK, 0, "whitespace", &state, N_("action"),
4703                        N_("detect new or modified lines that have whitespace errors"),
4704                        0, option_parse_whitespace },
4705                { OPTION_CALLBACK, 0, "ignore-space-change", &state, NULL,
4706                        N_("ignore changes in whitespace when finding context"),
4707                        PARSE_OPT_NOARG, option_parse_space_change },
4708                { OPTION_CALLBACK, 0, "ignore-whitespace", &state, NULL,
4709                        N_("ignore changes in whitespace when finding context"),
4710                        PARSE_OPT_NOARG, option_parse_space_change },
4711                OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4712                        N_("apply the patch in reverse")),
4713                OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4714                        N_("don't expect at least one line of context")),
4715                OPT_BOOL(0, "reject", &state.apply_with_reject,
4716                        N_("leave the rejected hunks in corresponding *.rej files")),
4717                OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4718                        N_("allow overlapping hunks")),
4719                OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4720                OPT_BIT(0, "inaccurate-eof", &options,
4721                        N_("tolerate incorrectly detected missing new-line at the end of file"),
4722                        INACCURATE_EOF),
4723                OPT_BIT(0, "recount", &options,
4724                        N_("do not trust the line counts in the hunk headers"),
4725                        RECOUNT),
4726                { OPTION_CALLBACK, 0, "directory", &state, N_("root"),
4727                        N_("prepend <root> to all filenames"),
4728                        0, option_parse_directory },
4729                OPT_END()
4730        };
4731
4732        if (init_apply_state(&state, prefix, &lock_file))
4733                exit(128);
4734
4735        argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4736                        apply_usage, 0);
4737
4738        if (check_apply_state(&state, force_apply))
4739                exit(128);
4740
4741        ret = apply_all_patches(&state, argc, argv, options);
4742
4743        clear_apply_state(&state);
4744
4745        return ret;
4746}