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