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