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