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