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