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