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