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