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