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