d940125ee20d02e52a16065832d3d681d3e44f61
   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 cached; /* apply to the index only */
  30        int check; /* preimage must match working tree, don't actually apply */
  31        int check_index; /* preimage must match the indexed version */
  32        int update_index; /* check_index && apply */
  33
  34        /* These control cosmetic aspect of the output */
  35        int diffstat; /* just show a diffstat, and don't actually apply */
  36
  37        /* These boolean parameters control how the apply is done */
  38        int allow_overlap;
  39        int apply_in_reverse;
  40        int apply_with_reject;
  41        int apply_verbosely;
  42        int unidiff_zero;
  43};
  44
  45/*
  46 *  --numstat does numeric diffstat, and doesn't actually apply
  47 *  --index-info shows the old and new index info for paths if available.
  48 */
  49static int newfd = -1;
  50
  51static int state_p_value = 1;
  52static int p_value_known;
  53static int numstat;
  54static int summary;
  55static int apply = 1;
  56static int no_add;
  57static int threeway;
  58static int unsafe_paths;
  59static const char *fake_ancestor;
  60static int line_termination = '\n';
  61static unsigned int p_context = UINT_MAX;
  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 const char *patch_input_file;
  84static struct strbuf root = STRBUF_INIT;
  85
  86static void parse_whitespace_option(const char *option)
  87{
  88        if (!option) {
  89                ws_error_action = warn_on_ws_error;
  90                return;
  91        }
  92        if (!strcmp(option, "warn")) {
  93                ws_error_action = warn_on_ws_error;
  94                return;
  95        }
  96        if (!strcmp(option, "nowarn")) {
  97                ws_error_action = nowarn_ws_error;
  98                return;
  99        }
 100        if (!strcmp(option, "error")) {
 101                ws_error_action = die_on_ws_error;
 102                return;
 103        }
 104        if (!strcmp(option, "error-all")) {
 105                ws_error_action = die_on_ws_error;
 106                squelch_whitespace_errors = 0;
 107                return;
 108        }
 109        if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
 110                ws_error_action = correct_ws_error;
 111                return;
 112        }
 113        die(_("unrecognized whitespace option '%s'"), option);
 114}
 115
 116static void parse_ignorewhitespace_option(const char *option)
 117{
 118        if (!option || !strcmp(option, "no") ||
 119            !strcmp(option, "false") || !strcmp(option, "never") ||
 120            !strcmp(option, "none")) {
 121                ws_ignore_action = ignore_ws_none;
 122                return;
 123        }
 124        if (!strcmp(option, "change")) {
 125                ws_ignore_action = ignore_ws_change;
 126                return;
 127        }
 128        die(_("unrecognized whitespace ignore option '%s'"), option);
 129}
 130
 131static void set_default_whitespace_mode(const char *whitespace_option)
 132{
 133        if (!whitespace_option && !apply_default_whitespace)
 134                ws_error_action = (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(unsigned result, const char *line, int len, int linenr)
1529{
1530        char *err;
1531
1532        if (!result)
1533                return;
1534
1535        whitespace_error++;
1536        if (squelch_whitespace_errors &&
1537            squelch_whitespace_errors < whitespace_error)
1538                return;
1539
1540        err = whitespace_error_string(result);
1541        fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1542                patch_input_file, linenr, err, len, line);
1543        free(err);
1544}
1545
1546static void check_whitespace(const char *line, int len, unsigned ws_rule)
1547{
1548        unsigned result = ws_check(line + 1, len - 1, ws_rule);
1549
1550        record_ws_error(result, line + 1, len - 2, state_linenr);
1551}
1552
1553/*
1554 * Parse a unified diff. Note that this really needs to parse each
1555 * fragment separately, since the only way to know the difference
1556 * between a "---" that is part of a patch, and a "---" that starts
1557 * the next patch is to look at the line counts..
1558 */
1559static int parse_fragment(struct apply_state *state,
1560                          const char *line,
1561                          unsigned long size,
1562                          struct patch *patch,
1563                          struct fragment *fragment)
1564{
1565        int added, deleted;
1566        int len = linelen(line, size), offset;
1567        unsigned long oldlines, newlines;
1568        unsigned long leading, trailing;
1569
1570        offset = parse_fragment_header(line, len, fragment);
1571        if (offset < 0)
1572                return -1;
1573        if (offset > 0 && patch->recount)
1574                recount_diff(line + offset, size - offset, fragment);
1575        oldlines = fragment->oldlines;
1576        newlines = fragment->newlines;
1577        leading = 0;
1578        trailing = 0;
1579
1580        /* Parse the thing.. */
1581        line += len;
1582        size -= len;
1583        state_linenr++;
1584        added = deleted = 0;
1585        for (offset = len;
1586             0 < size;
1587             offset += len, size -= len, line += len, state_linenr++) {
1588                if (!oldlines && !newlines)
1589                        break;
1590                len = linelen(line, size);
1591                if (!len || line[len-1] != '\n')
1592                        return -1;
1593                switch (*line) {
1594                default:
1595                        return -1;
1596                case '\n': /* newer GNU diff, an empty context line */
1597                case ' ':
1598                        oldlines--;
1599                        newlines--;
1600                        if (!deleted && !added)
1601                                leading++;
1602                        trailing++;
1603                        if (!state->apply_in_reverse &&
1604                            ws_error_action == correct_ws_error)
1605                                check_whitespace(line, len, patch->ws_rule);
1606                        break;
1607                case '-':
1608                        if (state->apply_in_reverse &&
1609                            ws_error_action != nowarn_ws_error)
1610                                check_whitespace(line, len, patch->ws_rule);
1611                        deleted++;
1612                        oldlines--;
1613                        trailing = 0;
1614                        break;
1615                case '+':
1616                        if (!state->apply_in_reverse &&
1617                            ws_error_action != nowarn_ws_error)
1618                                check_whitespace(line, len, patch->ws_rule);
1619                        added++;
1620                        newlines--;
1621                        trailing = 0;
1622                        break;
1623
1624                /*
1625                 * We allow "\ No newline at end of file". Depending
1626                 * on locale settings when the patch was produced we
1627                 * don't know what this line looks like. The only
1628                 * thing we do know is that it begins with "\ ".
1629                 * Checking for 12 is just for sanity check -- any
1630                 * l10n of "\ No newline..." is at least that long.
1631                 */
1632                case '\\':
1633                        if (len < 12 || memcmp(line, "\\ ", 2))
1634                                return -1;
1635                        break;
1636                }
1637        }
1638        if (oldlines || newlines)
1639                return -1;
1640        if (!deleted && !added)
1641                return -1;
1642
1643        fragment->leading = leading;
1644        fragment->trailing = trailing;
1645
1646        /*
1647         * If a fragment ends with an incomplete line, we failed to include
1648         * it in the above loop because we hit oldlines == newlines == 0
1649         * before seeing it.
1650         */
1651        if (12 < size && !memcmp(line, "\\ ", 2))
1652                offset += linelen(line, size);
1653
1654        patch->lines_added += added;
1655        patch->lines_deleted += deleted;
1656
1657        if (0 < patch->is_new && oldlines)
1658                return error(_("new file depends on old contents"));
1659        if (0 < patch->is_delete && newlines)
1660                return error(_("deleted file still has contents"));
1661        return offset;
1662}
1663
1664/*
1665 * We have seen "diff --git a/... b/..." header (or a traditional patch
1666 * header).  Read hunks that belong to this patch into fragments and hang
1667 * them to the given patch structure.
1668 *
1669 * The (fragment->patch, fragment->size) pair points into the memory given
1670 * by the caller, not a copy, when we return.
1671 */
1672static int parse_single_patch(struct apply_state *state,
1673                              const char *line,
1674                              unsigned long size,
1675                              struct patch *patch)
1676{
1677        unsigned long offset = 0;
1678        unsigned long oldlines = 0, newlines = 0, context = 0;
1679        struct fragment **fragp = &patch->fragments;
1680
1681        while (size > 4 && !memcmp(line, "@@ -", 4)) {
1682                struct fragment *fragment;
1683                int len;
1684
1685                fragment = xcalloc(1, sizeof(*fragment));
1686                fragment->linenr = state_linenr;
1687                len = parse_fragment(state, line, size, patch, fragment);
1688                if (len <= 0)
1689                        die(_("corrupt patch at line %d"), state_linenr);
1690                fragment->patch = line;
1691                fragment->size = len;
1692                oldlines += fragment->oldlines;
1693                newlines += fragment->newlines;
1694                context += fragment->leading + fragment->trailing;
1695
1696                *fragp = fragment;
1697                fragp = &fragment->next;
1698
1699                offset += len;
1700                line += len;
1701                size -= len;
1702        }
1703
1704        /*
1705         * If something was removed (i.e. we have old-lines) it cannot
1706         * be creation, and if something was added it cannot be
1707         * deletion.  However, the reverse is not true; --unified=0
1708         * patches that only add are not necessarily creation even
1709         * though they do not have any old lines, and ones that only
1710         * delete are not necessarily deletion.
1711         *
1712         * Unfortunately, a real creation/deletion patch do _not_ have
1713         * any context line by definition, so we cannot safely tell it
1714         * apart with --unified=0 insanity.  At least if the patch has
1715         * more than one hunk it is not creation or deletion.
1716         */
1717        if (patch->is_new < 0 &&
1718            (oldlines || (patch->fragments && patch->fragments->next)))
1719                patch->is_new = 0;
1720        if (patch->is_delete < 0 &&
1721            (newlines || (patch->fragments && patch->fragments->next)))
1722                patch->is_delete = 0;
1723
1724        if (0 < patch->is_new && oldlines)
1725                die(_("new file %s depends on old contents"), patch->new_name);
1726        if (0 < patch->is_delete && newlines)
1727                die(_("deleted file %s still has contents"), patch->old_name);
1728        if (!patch->is_delete && !newlines && context)
1729                fprintf_ln(stderr,
1730                           _("** warning: "
1731                             "file %s becomes empty but is not deleted"),
1732                           patch->new_name);
1733
1734        return offset;
1735}
1736
1737static inline int metadata_changes(struct patch *patch)
1738{
1739        return  patch->is_rename > 0 ||
1740                patch->is_copy > 0 ||
1741                patch->is_new > 0 ||
1742                patch->is_delete ||
1743                (patch->old_mode && patch->new_mode &&
1744                 patch->old_mode != patch->new_mode);
1745}
1746
1747static char *inflate_it(const void *data, unsigned long size,
1748                        unsigned long inflated_size)
1749{
1750        git_zstream stream;
1751        void *out;
1752        int st;
1753
1754        memset(&stream, 0, sizeof(stream));
1755
1756        stream.next_in = (unsigned char *)data;
1757        stream.avail_in = size;
1758        stream.next_out = out = xmalloc(inflated_size);
1759        stream.avail_out = inflated_size;
1760        git_inflate_init(&stream);
1761        st = git_inflate(&stream, Z_FINISH);
1762        git_inflate_end(&stream);
1763        if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1764                free(out);
1765                return NULL;
1766        }
1767        return out;
1768}
1769
1770/*
1771 * Read a binary hunk and return a new fragment; fragment->patch
1772 * points at an allocated memory that the caller must free, so
1773 * it is marked as "->free_patch = 1".
1774 */
1775static struct fragment *parse_binary_hunk(char **buf_p,
1776                                          unsigned long *sz_p,
1777                                          int *status_p,
1778                                          int *used_p)
1779{
1780        /*
1781         * Expect a line that begins with binary patch method ("literal"
1782         * or "delta"), followed by the length of data before deflating.
1783         * a sequence of 'length-byte' followed by base-85 encoded data
1784         * should follow, terminated by a newline.
1785         *
1786         * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1787         * and we would limit the patch line to 66 characters,
1788         * so one line can fit up to 13 groups that would decode
1789         * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1790         * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1791         */
1792        int llen, used;
1793        unsigned long size = *sz_p;
1794        char *buffer = *buf_p;
1795        int patch_method;
1796        unsigned long origlen;
1797        char *data = NULL;
1798        int hunk_size = 0;
1799        struct fragment *frag;
1800
1801        llen = linelen(buffer, size);
1802        used = llen;
1803
1804        *status_p = 0;
1805
1806        if (starts_with(buffer, "delta ")) {
1807                patch_method = BINARY_DELTA_DEFLATED;
1808                origlen = strtoul(buffer + 6, NULL, 10);
1809        }
1810        else if (starts_with(buffer, "literal ")) {
1811                patch_method = BINARY_LITERAL_DEFLATED;
1812                origlen = strtoul(buffer + 8, NULL, 10);
1813        }
1814        else
1815                return NULL;
1816
1817        state_linenr++;
1818        buffer += llen;
1819        while (1) {
1820                int byte_length, max_byte_length, newsize;
1821                llen = linelen(buffer, size);
1822                used += llen;
1823                state_linenr++;
1824                if (llen == 1) {
1825                        /* consume the blank line */
1826                        buffer++;
1827                        size--;
1828                        break;
1829                }
1830                /*
1831                 * Minimum line is "A00000\n" which is 7-byte long,
1832                 * and the line length must be multiple of 5 plus 2.
1833                 */
1834                if ((llen < 7) || (llen-2) % 5)
1835                        goto corrupt;
1836                max_byte_length = (llen - 2) / 5 * 4;
1837                byte_length = *buffer;
1838                if ('A' <= byte_length && byte_length <= 'Z')
1839                        byte_length = byte_length - 'A' + 1;
1840                else if ('a' <= byte_length && byte_length <= 'z')
1841                        byte_length = byte_length - 'a' + 27;
1842                else
1843                        goto corrupt;
1844                /* if the input length was not multiple of 4, we would
1845                 * have filler at the end but the filler should never
1846                 * exceed 3 bytes
1847                 */
1848                if (max_byte_length < byte_length ||
1849                    byte_length <= max_byte_length - 4)
1850                        goto corrupt;
1851                newsize = hunk_size + byte_length;
1852                data = xrealloc(data, newsize);
1853                if (decode_85(data + hunk_size, buffer + 1, byte_length))
1854                        goto corrupt;
1855                hunk_size = newsize;
1856                buffer += llen;
1857                size -= llen;
1858        }
1859
1860        frag = xcalloc(1, sizeof(*frag));
1861        frag->patch = inflate_it(data, hunk_size, origlen);
1862        frag->free_patch = 1;
1863        if (!frag->patch)
1864                goto corrupt;
1865        free(data);
1866        frag->size = origlen;
1867        *buf_p = buffer;
1868        *sz_p = size;
1869        *used_p = used;
1870        frag->binary_patch_method = patch_method;
1871        return frag;
1872
1873 corrupt:
1874        free(data);
1875        *status_p = -1;
1876        error(_("corrupt binary patch at line %d: %.*s"),
1877              state_linenr-1, llen-1, buffer);
1878        return NULL;
1879}
1880
1881/*
1882 * Returns:
1883 *   -1 in case of error,
1884 *   the length of the parsed binary patch otherwise
1885 */
1886static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1887{
1888        /*
1889         * We have read "GIT binary patch\n"; what follows is a line
1890         * that says the patch method (currently, either "literal" or
1891         * "delta") and the length of data before deflating; a
1892         * sequence of 'length-byte' followed by base-85 encoded data
1893         * follows.
1894         *
1895         * When a binary patch is reversible, there is another binary
1896         * hunk in the same format, starting with patch method (either
1897         * "literal" or "delta") with the length of data, and a sequence
1898         * of length-byte + base-85 encoded data, terminated with another
1899         * empty line.  This data, when applied to the postimage, produces
1900         * the preimage.
1901         */
1902        struct fragment *forward;
1903        struct fragment *reverse;
1904        int status;
1905        int used, used_1;
1906
1907        forward = parse_binary_hunk(&buffer, &size, &status, &used);
1908        if (!forward && !status)
1909                /* there has to be one hunk (forward hunk) */
1910                return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1911        if (status)
1912                /* otherwise we already gave an error message */
1913                return status;
1914
1915        reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1916        if (reverse)
1917                used += used_1;
1918        else if (status) {
1919                /*
1920                 * Not having reverse hunk is not an error, but having
1921                 * a corrupt reverse hunk is.
1922                 */
1923                free((void*) forward->patch);
1924                free(forward);
1925                return status;
1926        }
1927        forward->next = reverse;
1928        patch->fragments = forward;
1929        patch->is_binary = 1;
1930        return used;
1931}
1932
1933static void prefix_one(struct apply_state *state, char **name)
1934{
1935        char *old_name = *name;
1936        if (!old_name)
1937                return;
1938        *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1939        free(old_name);
1940}
1941
1942static void prefix_patch(struct apply_state *state, struct patch *p)
1943{
1944        if (!state->prefix || p->is_toplevel_relative)
1945                return;
1946        prefix_one(state, &p->new_name);
1947        prefix_one(state, &p->old_name);
1948}
1949
1950/*
1951 * include/exclude
1952 */
1953
1954static struct string_list limit_by_name;
1955static int has_include;
1956static void add_name_limit(const char *name, int exclude)
1957{
1958        struct string_list_item *it;
1959
1960        it = string_list_append(&limit_by_name, name);
1961        it->util = exclude ? NULL : (void *) 1;
1962}
1963
1964static int use_patch(struct apply_state *state, struct patch *p)
1965{
1966        const char *pathname = p->new_name ? p->new_name : p->old_name;
1967        int i;
1968
1969        /* Paths outside are not touched regardless of "--include" */
1970        if (0 < state->prefix_length) {
1971                int pathlen = strlen(pathname);
1972                if (pathlen <= state->prefix_length ||
1973                    memcmp(state->prefix, pathname, state->prefix_length))
1974                        return 0;
1975        }
1976
1977        /* See if it matches any of exclude/include rule */
1978        for (i = 0; i < limit_by_name.nr; i++) {
1979                struct string_list_item *it = &limit_by_name.items[i];
1980                if (!wildmatch(it->string, pathname, 0, NULL))
1981                        return (it->util != NULL);
1982        }
1983
1984        /*
1985         * If we had any include, a path that does not match any rule is
1986         * not used.  Otherwise, we saw bunch of exclude rules (or none)
1987         * and such a path is used.
1988         */
1989        return !has_include;
1990}
1991
1992
1993/*
1994 * Read the patch text in "buffer" that extends for "size" bytes; stop
1995 * reading after seeing a single patch (i.e. changes to a single file).
1996 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1997 * Return the number of bytes consumed, so that the caller can call us
1998 * again for the next patch.
1999 */
2000static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2001{
2002        int hdrsize, patchsize;
2003        int offset = find_header(state, buffer, size, &hdrsize, patch);
2004
2005        if (offset < 0)
2006                return offset;
2007
2008        prefix_patch(state, patch);
2009
2010        if (!use_patch(state, patch))
2011                patch->ws_rule = 0;
2012        else
2013                patch->ws_rule = whitespace_rule(patch->new_name
2014                                                 ? patch->new_name
2015                                                 : patch->old_name);
2016
2017        patchsize = parse_single_patch(state,
2018                                       buffer + offset + hdrsize,
2019                                       size - offset - hdrsize,
2020                                       patch);
2021
2022        if (!patchsize) {
2023                static const char git_binary[] = "GIT binary patch\n";
2024                int hd = hdrsize + offset;
2025                unsigned long llen = linelen(buffer + hd, size - hd);
2026
2027                if (llen == sizeof(git_binary) - 1 &&
2028                    !memcmp(git_binary, buffer + hd, llen)) {
2029                        int used;
2030                        state_linenr++;
2031                        used = parse_binary(buffer + hd + llen,
2032                                            size - hd - llen, patch);
2033                        if (used < 0)
2034                                return -1;
2035                        if (used)
2036                                patchsize = used + llen;
2037                        else
2038                                patchsize = 0;
2039                }
2040                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2041                        static const char *binhdr[] = {
2042                                "Binary files ",
2043                                "Files ",
2044                                NULL,
2045                        };
2046                        int i;
2047                        for (i = 0; binhdr[i]; i++) {
2048                                int len = strlen(binhdr[i]);
2049                                if (len < size - hd &&
2050                                    !memcmp(binhdr[i], buffer + hd, len)) {
2051                                        state_linenr++;
2052                                        patch->is_binary = 1;
2053                                        patchsize = llen;
2054                                        break;
2055                                }
2056                        }
2057                }
2058
2059                /* Empty patch cannot be applied if it is a text patch
2060                 * without metadata change.  A binary patch appears
2061                 * empty to us here.
2062                 */
2063                if ((apply || state->check) &&
2064                    (!patch->is_binary && !metadata_changes(patch)))
2065                        die(_("patch with only garbage at line %d"), state_linenr);
2066        }
2067
2068        return offset + hdrsize + patchsize;
2069}
2070
2071#define swap(a,b) myswap((a),(b),sizeof(a))
2072
2073#define myswap(a, b, size) do {         \
2074        unsigned char mytmp[size];      \
2075        memcpy(mytmp, &a, size);                \
2076        memcpy(&a, &b, size);           \
2077        memcpy(&b, mytmp, size);                \
2078} while (0)
2079
2080static void reverse_patches(struct patch *p)
2081{
2082        for (; p; p = p->next) {
2083                struct fragment *frag = p->fragments;
2084
2085                swap(p->new_name, p->old_name);
2086                swap(p->new_mode, p->old_mode);
2087                swap(p->is_new, p->is_delete);
2088                swap(p->lines_added, p->lines_deleted);
2089                swap(p->old_sha1_prefix, p->new_sha1_prefix);
2090
2091                for (; frag; frag = frag->next) {
2092                        swap(frag->newpos, frag->oldpos);
2093                        swap(frag->newlines, frag->oldlines);
2094                }
2095        }
2096}
2097
2098static const char pluses[] =
2099"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2100static const char minuses[]=
2101"----------------------------------------------------------------------";
2102
2103static void show_stats(struct patch *patch)
2104{
2105        struct strbuf qname = STRBUF_INIT;
2106        char *cp = patch->new_name ? patch->new_name : patch->old_name;
2107        int max, add, del;
2108
2109        quote_c_style(cp, &qname, NULL, 0);
2110
2111        /*
2112         * "scale" the filename
2113         */
2114        max = max_len;
2115        if (max > 50)
2116                max = 50;
2117
2118        if (qname.len > max) {
2119                cp = strchr(qname.buf + qname.len + 3 - max, '/');
2120                if (!cp)
2121                        cp = qname.buf + qname.len + 3 - max;
2122                strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2123        }
2124
2125        if (patch->is_binary) {
2126                printf(" %-*s |  Bin\n", max, qname.buf);
2127                strbuf_release(&qname);
2128                return;
2129        }
2130
2131        printf(" %-*s |", max, qname.buf);
2132        strbuf_release(&qname);
2133
2134        /*
2135         * scale the add/delete
2136         */
2137        max = max + max_change > 70 ? 70 - max : max_change;
2138        add = patch->lines_added;
2139        del = patch->lines_deleted;
2140
2141        if (max_change > 0) {
2142                int total = ((add + del) * max + max_change / 2) / max_change;
2143                add = (add * max + max_change / 2) / max_change;
2144                del = total - add;
2145        }
2146        printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2147                add, pluses, del, minuses);
2148}
2149
2150static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2151{
2152        switch (st->st_mode & S_IFMT) {
2153        case S_IFLNK:
2154                if (strbuf_readlink(buf, path, st->st_size) < 0)
2155                        return error(_("unable to read symlink %s"), path);
2156                return 0;
2157        case S_IFREG:
2158                if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2159                        return error(_("unable to open or read %s"), path);
2160                convert_to_git(path, buf->buf, buf->len, buf, 0);
2161                return 0;
2162        default:
2163                return -1;
2164        }
2165}
2166
2167/*
2168 * Update the preimage, and the common lines in postimage,
2169 * from buffer buf of length len. If postlen is 0 the postimage
2170 * is updated in place, otherwise it's updated on a new buffer
2171 * of length postlen
2172 */
2173
2174static void update_pre_post_images(struct image *preimage,
2175                                   struct image *postimage,
2176                                   char *buf,
2177                                   size_t len, size_t postlen)
2178{
2179        int i, ctx, reduced;
2180        char *new, *old, *fixed;
2181        struct image fixed_preimage;
2182
2183        /*
2184         * Update the preimage with whitespace fixes.  Note that we
2185         * are not losing preimage->buf -- apply_one_fragment() will
2186         * free "oldlines".
2187         */
2188        prepare_image(&fixed_preimage, buf, len, 1);
2189        assert(postlen
2190               ? fixed_preimage.nr == preimage->nr
2191               : fixed_preimage.nr <= preimage->nr);
2192        for (i = 0; i < fixed_preimage.nr; i++)
2193                fixed_preimage.line[i].flag = preimage->line[i].flag;
2194        free(preimage->line_allocated);
2195        *preimage = fixed_preimage;
2196
2197        /*
2198         * Adjust the common context lines in postimage. This can be
2199         * done in-place when we are shrinking it with whitespace
2200         * fixing, but needs a new buffer when ignoring whitespace or
2201         * expanding leading tabs to spaces.
2202         *
2203         * We trust the caller to tell us if the update can be done
2204         * in place (postlen==0) or not.
2205         */
2206        old = postimage->buf;
2207        if (postlen)
2208                new = postimage->buf = xmalloc(postlen);
2209        else
2210                new = old;
2211        fixed = preimage->buf;
2212
2213        for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2214                size_t l_len = postimage->line[i].len;
2215                if (!(postimage->line[i].flag & LINE_COMMON)) {
2216                        /* an added line -- no counterparts in preimage */
2217                        memmove(new, old, l_len);
2218                        old += l_len;
2219                        new += l_len;
2220                        continue;
2221                }
2222
2223                /* a common context -- skip it in the original postimage */
2224                old += l_len;
2225
2226                /* and find the corresponding one in the fixed preimage */
2227                while (ctx < preimage->nr &&
2228                       !(preimage->line[ctx].flag & LINE_COMMON)) {
2229                        fixed += preimage->line[ctx].len;
2230                        ctx++;
2231                }
2232
2233                /*
2234                 * preimage is expected to run out, if the caller
2235                 * fixed addition of trailing blank lines.
2236                 */
2237                if (preimage->nr <= ctx) {
2238                        reduced++;
2239                        continue;
2240                }
2241
2242                /* and copy it in, while fixing the line length */
2243                l_len = preimage->line[ctx].len;
2244                memcpy(new, fixed, l_len);
2245                new += l_len;
2246                fixed += l_len;
2247                postimage->line[i].len = l_len;
2248                ctx++;
2249        }
2250
2251        if (postlen
2252            ? postlen < new - postimage->buf
2253            : postimage->len < new - postimage->buf)
2254                die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2255                    (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2256
2257        /* Fix the length of the whole thing */
2258        postimage->len = new - postimage->buf;
2259        postimage->nr -= reduced;
2260}
2261
2262static int line_by_line_fuzzy_match(struct image *img,
2263                                    struct image *preimage,
2264                                    struct image *postimage,
2265                                    unsigned long try,
2266                                    int try_lno,
2267                                    int preimage_limit)
2268{
2269        int i;
2270        size_t imgoff = 0;
2271        size_t preoff = 0;
2272        size_t postlen = postimage->len;
2273        size_t extra_chars;
2274        char *buf;
2275        char *preimage_eof;
2276        char *preimage_end;
2277        struct strbuf fixed;
2278        char *fixed_buf;
2279        size_t fixed_len;
2280
2281        for (i = 0; i < preimage_limit; i++) {
2282                size_t prelen = preimage->line[i].len;
2283                size_t imglen = img->line[try_lno+i].len;
2284
2285                if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2286                                      preimage->buf + preoff, prelen))
2287                        return 0;
2288                if (preimage->line[i].flag & LINE_COMMON)
2289                        postlen += imglen - prelen;
2290                imgoff += imglen;
2291                preoff += prelen;
2292        }
2293
2294        /*
2295         * Ok, the preimage matches with whitespace fuzz.
2296         *
2297         * imgoff now holds the true length of the target that
2298         * matches the preimage before the end of the file.
2299         *
2300         * Count the number of characters in the preimage that fall
2301         * beyond the end of the file and make sure that all of them
2302         * are whitespace characters. (This can only happen if
2303         * we are removing blank lines at the end of the file.)
2304         */
2305        buf = preimage_eof = preimage->buf + preoff;
2306        for ( ; i < preimage->nr; i++)
2307                preoff += preimage->line[i].len;
2308        preimage_end = preimage->buf + preoff;
2309        for ( ; buf < preimage_end; buf++)
2310                if (!isspace(*buf))
2311                        return 0;
2312
2313        /*
2314         * Update the preimage and the common postimage context
2315         * lines to use the same whitespace as the target.
2316         * If whitespace is missing in the target (i.e.
2317         * if the preimage extends beyond the end of the file),
2318         * use the whitespace from the preimage.
2319         */
2320        extra_chars = preimage_end - preimage_eof;
2321        strbuf_init(&fixed, imgoff + extra_chars);
2322        strbuf_add(&fixed, img->buf + try, imgoff);
2323        strbuf_add(&fixed, preimage_eof, extra_chars);
2324        fixed_buf = strbuf_detach(&fixed, &fixed_len);
2325        update_pre_post_images(preimage, postimage,
2326                               fixed_buf, fixed_len, postlen);
2327        return 1;
2328}
2329
2330static int match_fragment(struct image *img,
2331                          struct image *preimage,
2332                          struct image *postimage,
2333                          unsigned long try,
2334                          int try_lno,
2335                          unsigned ws_rule,
2336                          int match_beginning, int match_end)
2337{
2338        int i;
2339        char *fixed_buf, *buf, *orig, *target;
2340        struct strbuf fixed;
2341        size_t fixed_len, postlen;
2342        int preimage_limit;
2343
2344        if (preimage->nr + try_lno <= img->nr) {
2345                /*
2346                 * The hunk falls within the boundaries of img.
2347                 */
2348                preimage_limit = preimage->nr;
2349                if (match_end && (preimage->nr + try_lno != img->nr))
2350                        return 0;
2351        } else if (ws_error_action == correct_ws_error &&
2352                   (ws_rule & WS_BLANK_AT_EOF)) {
2353                /*
2354                 * This hunk extends beyond the end of img, and we are
2355                 * removing blank lines at the end of the file.  This
2356                 * many lines from the beginning of the preimage must
2357                 * match with img, and the remainder of the preimage
2358                 * must be blank.
2359                 */
2360                preimage_limit = img->nr - try_lno;
2361        } else {
2362                /*
2363                 * The hunk extends beyond the end of the img and
2364                 * we are not removing blanks at the end, so we
2365                 * should reject the hunk at this position.
2366                 */
2367                return 0;
2368        }
2369
2370        if (match_beginning && try_lno)
2371                return 0;
2372
2373        /* Quick hash check */
2374        for (i = 0; i < preimage_limit; i++)
2375                if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2376                    (preimage->line[i].hash != img->line[try_lno + i].hash))
2377                        return 0;
2378
2379        if (preimage_limit == preimage->nr) {
2380                /*
2381                 * Do we have an exact match?  If we were told to match
2382                 * at the end, size must be exactly at try+fragsize,
2383                 * otherwise try+fragsize must be still within the preimage,
2384                 * and either case, the old piece should match the preimage
2385                 * exactly.
2386                 */
2387                if ((match_end
2388                     ? (try + preimage->len == img->len)
2389                     : (try + preimage->len <= img->len)) &&
2390                    !memcmp(img->buf + try, preimage->buf, preimage->len))
2391                        return 1;
2392        } else {
2393                /*
2394                 * The preimage extends beyond the end of img, so
2395                 * there cannot be an exact match.
2396                 *
2397                 * There must be one non-blank context line that match
2398                 * a line before the end of img.
2399                 */
2400                char *buf_end;
2401
2402                buf = preimage->buf;
2403                buf_end = buf;
2404                for (i = 0; i < preimage_limit; i++)
2405                        buf_end += preimage->line[i].len;
2406
2407                for ( ; buf < buf_end; buf++)
2408                        if (!isspace(*buf))
2409                                break;
2410                if (buf == buf_end)
2411                        return 0;
2412        }
2413
2414        /*
2415         * No exact match. If we are ignoring whitespace, run a line-by-line
2416         * fuzzy matching. We collect all the line length information because
2417         * we need it to adjust whitespace if we match.
2418         */
2419        if (ws_ignore_action == ignore_ws_change)
2420                return line_by_line_fuzzy_match(img, preimage, postimage,
2421                                                try, try_lno, preimage_limit);
2422
2423        if (ws_error_action != correct_ws_error)
2424                return 0;
2425
2426        /*
2427         * The hunk does not apply byte-by-byte, but the hash says
2428         * it might with whitespace fuzz. We weren't asked to
2429         * ignore whitespace, we were asked to correct whitespace
2430         * errors, so let's try matching after whitespace correction.
2431         *
2432         * While checking the preimage against the target, whitespace
2433         * errors in both fixed, we count how large the corresponding
2434         * postimage needs to be.  The postimage prepared by
2435         * apply_one_fragment() has whitespace errors fixed on added
2436         * lines already, but the common lines were propagated as-is,
2437         * which may become longer when their whitespace errors are
2438         * fixed.
2439         */
2440
2441        /* First count added lines in postimage */
2442        postlen = 0;
2443        for (i = 0; i < postimage->nr; i++) {
2444                if (!(postimage->line[i].flag & LINE_COMMON))
2445                        postlen += postimage->line[i].len;
2446        }
2447
2448        /*
2449         * The preimage may extend beyond the end of the file,
2450         * but in this loop we will only handle the part of the
2451         * preimage that falls within the file.
2452         */
2453        strbuf_init(&fixed, preimage->len + 1);
2454        orig = preimage->buf;
2455        target = img->buf + try;
2456        for (i = 0; i < preimage_limit; i++) {
2457                size_t oldlen = preimage->line[i].len;
2458                size_t tgtlen = img->line[try_lno + i].len;
2459                size_t fixstart = fixed.len;
2460                struct strbuf tgtfix;
2461                int match;
2462
2463                /* Try fixing the line in the preimage */
2464                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2465
2466                /* Try fixing the line in the target */
2467                strbuf_init(&tgtfix, tgtlen);
2468                ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2469
2470                /*
2471                 * If they match, either the preimage was based on
2472                 * a version before our tree fixed whitespace breakage,
2473                 * or we are lacking a whitespace-fix patch the tree
2474                 * the preimage was based on already had (i.e. target
2475                 * has whitespace breakage, the preimage doesn't).
2476                 * In either case, we are fixing the whitespace breakages
2477                 * so we might as well take the fix together with their
2478                 * real change.
2479                 */
2480                match = (tgtfix.len == fixed.len - fixstart &&
2481                         !memcmp(tgtfix.buf, fixed.buf + fixstart,
2482                                             fixed.len - fixstart));
2483
2484                /* Add the length if this is common with the postimage */
2485                if (preimage->line[i].flag & LINE_COMMON)
2486                        postlen += tgtfix.len;
2487
2488                strbuf_release(&tgtfix);
2489                if (!match)
2490                        goto unmatch_exit;
2491
2492                orig += oldlen;
2493                target += tgtlen;
2494        }
2495
2496
2497        /*
2498         * Now handle the lines in the preimage that falls beyond the
2499         * end of the file (if any). They will only match if they are
2500         * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2501         * false).
2502         */
2503        for ( ; i < preimage->nr; i++) {
2504                size_t fixstart = fixed.len; /* start of the fixed preimage */
2505                size_t oldlen = preimage->line[i].len;
2506                int j;
2507
2508                /* Try fixing the line in the preimage */
2509                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2510
2511                for (j = fixstart; j < fixed.len; j++)
2512                        if (!isspace(fixed.buf[j]))
2513                                goto unmatch_exit;
2514
2515                orig += oldlen;
2516        }
2517
2518        /*
2519         * Yes, the preimage is based on an older version that still
2520         * has whitespace breakages unfixed, and fixing them makes the
2521         * hunk match.  Update the context lines in the postimage.
2522         */
2523        fixed_buf = strbuf_detach(&fixed, &fixed_len);
2524        if (postlen < postimage->len)
2525                postlen = 0;
2526        update_pre_post_images(preimage, postimage,
2527                               fixed_buf, fixed_len, postlen);
2528        return 1;
2529
2530 unmatch_exit:
2531        strbuf_release(&fixed);
2532        return 0;
2533}
2534
2535static int find_pos(struct image *img,
2536                    struct image *preimage,
2537                    struct image *postimage,
2538                    int line,
2539                    unsigned ws_rule,
2540                    int match_beginning, int match_end)
2541{
2542        int i;
2543        unsigned long backwards, forwards, try;
2544        int backwards_lno, forwards_lno, try_lno;
2545
2546        /*
2547         * If match_beginning or match_end is specified, there is no
2548         * point starting from a wrong line that will never match and
2549         * wander around and wait for a match at the specified end.
2550         */
2551        if (match_beginning)
2552                line = 0;
2553        else if (match_end)
2554                line = img->nr - preimage->nr;
2555
2556        /*
2557         * Because the comparison is unsigned, the following test
2558         * will also take care of a negative line number that can
2559         * result when match_end and preimage is larger than the target.
2560         */
2561        if ((size_t) line > img->nr)
2562                line = img->nr;
2563
2564        try = 0;
2565        for (i = 0; i < line; i++)
2566                try += img->line[i].len;
2567
2568        /*
2569         * There's probably some smart way to do this, but I'll leave
2570         * that to the smart and beautiful people. I'm simple and stupid.
2571         */
2572        backwards = try;
2573        backwards_lno = line;
2574        forwards = try;
2575        forwards_lno = line;
2576        try_lno = line;
2577
2578        for (i = 0; ; i++) {
2579                if (match_fragment(img, preimage, postimage,
2580                                   try, try_lno, ws_rule,
2581                                   match_beginning, match_end))
2582                        return try_lno;
2583
2584        again:
2585                if (backwards_lno == 0 && forwards_lno == img->nr)
2586                        break;
2587
2588                if (i & 1) {
2589                        if (backwards_lno == 0) {
2590                                i++;
2591                                goto again;
2592                        }
2593                        backwards_lno--;
2594                        backwards -= img->line[backwards_lno].len;
2595                        try = backwards;
2596                        try_lno = backwards_lno;
2597                } else {
2598                        if (forwards_lno == img->nr) {
2599                                i++;
2600                                goto again;
2601                        }
2602                        forwards += img->line[forwards_lno].len;
2603                        forwards_lno++;
2604                        try = forwards;
2605                        try_lno = forwards_lno;
2606                }
2607
2608        }
2609        return -1;
2610}
2611
2612static void remove_first_line(struct image *img)
2613{
2614        img->buf += img->line[0].len;
2615        img->len -= img->line[0].len;
2616        img->line++;
2617        img->nr--;
2618}
2619
2620static void remove_last_line(struct image *img)
2621{
2622        img->len -= img->line[--img->nr].len;
2623}
2624
2625/*
2626 * The change from "preimage" and "postimage" has been found to
2627 * apply at applied_pos (counts in line numbers) in "img".
2628 * Update "img" to remove "preimage" and replace it with "postimage".
2629 */
2630static void update_image(struct apply_state *state,
2631                         struct image *img,
2632                         int applied_pos,
2633                         struct image *preimage,
2634                         struct image *postimage)
2635{
2636        /*
2637         * remove the copy of preimage at offset in img
2638         * and replace it with postimage
2639         */
2640        int i, nr;
2641        size_t remove_count, insert_count, applied_at = 0;
2642        char *result;
2643        int preimage_limit;
2644
2645        /*
2646         * If we are removing blank lines at the end of img,
2647         * the preimage may extend beyond the end.
2648         * If that is the case, we must be careful only to
2649         * remove the part of the preimage that falls within
2650         * the boundaries of img. Initialize preimage_limit
2651         * to the number of lines in the preimage that falls
2652         * within the boundaries.
2653         */
2654        preimage_limit = preimage->nr;
2655        if (preimage_limit > img->nr - applied_pos)
2656                preimage_limit = img->nr - applied_pos;
2657
2658        for (i = 0; i < applied_pos; i++)
2659                applied_at += img->line[i].len;
2660
2661        remove_count = 0;
2662        for (i = 0; i < preimage_limit; i++)
2663                remove_count += img->line[applied_pos + i].len;
2664        insert_count = postimage->len;
2665
2666        /* Adjust the contents */
2667        result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2668        memcpy(result, img->buf, applied_at);
2669        memcpy(result + applied_at, postimage->buf, postimage->len);
2670        memcpy(result + applied_at + postimage->len,
2671               img->buf + (applied_at + remove_count),
2672               img->len - (applied_at + remove_count));
2673        free(img->buf);
2674        img->buf = result;
2675        img->len += insert_count - remove_count;
2676        result[img->len] = '\0';
2677
2678        /* Adjust the line table */
2679        nr = img->nr + postimage->nr - preimage_limit;
2680        if (preimage_limit < postimage->nr) {
2681                /*
2682                 * NOTE: this knows that we never call remove_first_line()
2683                 * on anything other than pre/post image.
2684                 */
2685                REALLOC_ARRAY(img->line, nr);
2686                img->line_allocated = img->line;
2687        }
2688        if (preimage_limit != postimage->nr)
2689                memmove(img->line + applied_pos + postimage->nr,
2690                        img->line + applied_pos + preimage_limit,
2691                        (img->nr - (applied_pos + preimage_limit)) *
2692                        sizeof(*img->line));
2693        memcpy(img->line + applied_pos,
2694               postimage->line,
2695               postimage->nr * sizeof(*img->line));
2696        if (!state->allow_overlap)
2697                for (i = 0; i < postimage->nr; i++)
2698                        img->line[applied_pos + i].flag |= LINE_PATCHED;
2699        img->nr = nr;
2700}
2701
2702/*
2703 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2704 * postimage) for the hunk.  Find lines that match "preimage" in "img" and
2705 * replace the part of "img" with "postimage" text.
2706 */
2707static int apply_one_fragment(struct apply_state *state,
2708                              struct image *img, struct fragment *frag,
2709                              int inaccurate_eof, unsigned ws_rule,
2710                              int nth_fragment)
2711{
2712        int match_beginning, match_end;
2713        const char *patch = frag->patch;
2714        int size = frag->size;
2715        char *old, *oldlines;
2716        struct strbuf newlines;
2717        int new_blank_lines_at_end = 0;
2718        int found_new_blank_lines_at_end = 0;
2719        int hunk_linenr = frag->linenr;
2720        unsigned long leading, trailing;
2721        int pos, applied_pos;
2722        struct image preimage;
2723        struct image postimage;
2724
2725        memset(&preimage, 0, sizeof(preimage));
2726        memset(&postimage, 0, sizeof(postimage));
2727        oldlines = xmalloc(size);
2728        strbuf_init(&newlines, size);
2729
2730        old = oldlines;
2731        while (size > 0) {
2732                char first;
2733                int len = linelen(patch, size);
2734                int plen;
2735                int added_blank_line = 0;
2736                int is_blank_context = 0;
2737                size_t start;
2738
2739                if (!len)
2740                        break;
2741
2742                /*
2743                 * "plen" is how much of the line we should use for
2744                 * the actual patch data. Normally we just remove the
2745                 * first character on the line, but if the line is
2746                 * followed by "\ No newline", then we also remove the
2747                 * last one (which is the newline, of course).
2748                 */
2749                plen = len - 1;
2750                if (len < size && patch[len] == '\\')
2751                        plen--;
2752                first = *patch;
2753                if (state->apply_in_reverse) {
2754                        if (first == '-')
2755                                first = '+';
2756                        else if (first == '+')
2757                                first = '-';
2758                }
2759
2760                switch (first) {
2761                case '\n':
2762                        /* Newer GNU diff, empty context line */
2763                        if (plen < 0)
2764                                /* ... followed by '\No newline'; nothing */
2765                                break;
2766                        *old++ = '\n';
2767                        strbuf_addch(&newlines, '\n');
2768                        add_line_info(&preimage, "\n", 1, LINE_COMMON);
2769                        add_line_info(&postimage, "\n", 1, LINE_COMMON);
2770                        is_blank_context = 1;
2771                        break;
2772                case ' ':
2773                        if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2774                            ws_blank_line(patch + 1, plen, ws_rule))
2775                                is_blank_context = 1;
2776                case '-':
2777                        memcpy(old, patch + 1, plen);
2778                        add_line_info(&preimage, old, plen,
2779                                      (first == ' ' ? LINE_COMMON : 0));
2780                        old += plen;
2781                        if (first == '-')
2782                                break;
2783                /* Fall-through for ' ' */
2784                case '+':
2785                        /* --no-add does not add new lines */
2786                        if (first == '+' && no_add)
2787                                break;
2788
2789                        start = newlines.len;
2790                        if (first != '+' ||
2791                            !whitespace_error ||
2792                            ws_error_action != correct_ws_error) {
2793                                strbuf_add(&newlines, patch + 1, plen);
2794                        }
2795                        else {
2796                                ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2797                        }
2798                        add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2799                                      (first == '+' ? 0 : LINE_COMMON));
2800                        if (first == '+' &&
2801                            (ws_rule & WS_BLANK_AT_EOF) &&
2802                            ws_blank_line(patch + 1, plen, ws_rule))
2803                                added_blank_line = 1;
2804                        break;
2805                case '@': case '\\':
2806                        /* Ignore it, we already handled it */
2807                        break;
2808                default:
2809                        if (state->apply_verbosely)
2810                                error(_("invalid start of line: '%c'"), first);
2811                        applied_pos = -1;
2812                        goto out;
2813                }
2814                if (added_blank_line) {
2815                        if (!new_blank_lines_at_end)
2816                                found_new_blank_lines_at_end = hunk_linenr;
2817                        new_blank_lines_at_end++;
2818                }
2819                else if (is_blank_context)
2820                        ;
2821                else
2822                        new_blank_lines_at_end = 0;
2823                patch += len;
2824                size -= len;
2825                hunk_linenr++;
2826        }
2827        if (inaccurate_eof &&
2828            old > oldlines && old[-1] == '\n' &&
2829            newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2830                old--;
2831                strbuf_setlen(&newlines, newlines.len - 1);
2832        }
2833
2834        leading = frag->leading;
2835        trailing = frag->trailing;
2836
2837        /*
2838         * A hunk to change lines at the beginning would begin with
2839         * @@ -1,L +N,M @@
2840         * but we need to be careful.  -U0 that inserts before the second
2841         * line also has this pattern.
2842         *
2843         * And a hunk to add to an empty file would begin with
2844         * @@ -0,0 +N,M @@
2845         *
2846         * In other words, a hunk that is (frag->oldpos <= 1) with or
2847         * without leading context must match at the beginning.
2848         */
2849        match_beginning = (!frag->oldpos ||
2850                           (frag->oldpos == 1 && !state->unidiff_zero));
2851
2852        /*
2853         * A hunk without trailing lines must match at the end.
2854         * However, we simply cannot tell if a hunk must match end
2855         * from the lack of trailing lines if the patch was generated
2856         * with unidiff without any context.
2857         */
2858        match_end = !state->unidiff_zero && !trailing;
2859
2860        pos = frag->newpos ? (frag->newpos - 1) : 0;
2861        preimage.buf = oldlines;
2862        preimage.len = old - oldlines;
2863        postimage.buf = newlines.buf;
2864        postimage.len = newlines.len;
2865        preimage.line = preimage.line_allocated;
2866        postimage.line = postimage.line_allocated;
2867
2868        for (;;) {
2869
2870                applied_pos = find_pos(img, &preimage, &postimage, pos,
2871                                       ws_rule, match_beginning, match_end);
2872
2873                if (applied_pos >= 0)
2874                        break;
2875
2876                /* Am I at my context limits? */
2877                if ((leading <= p_context) && (trailing <= p_context))
2878                        break;
2879                if (match_beginning || match_end) {
2880                        match_beginning = match_end = 0;
2881                        continue;
2882                }
2883
2884                /*
2885                 * Reduce the number of context lines; reduce both
2886                 * leading and trailing if they are equal otherwise
2887                 * just reduce the larger context.
2888                 */
2889                if (leading >= trailing) {
2890                        remove_first_line(&preimage);
2891                        remove_first_line(&postimage);
2892                        pos--;
2893                        leading--;
2894                }
2895                if (trailing > leading) {
2896                        remove_last_line(&preimage);
2897                        remove_last_line(&postimage);
2898                        trailing--;
2899                }
2900        }
2901
2902        if (applied_pos >= 0) {
2903                if (new_blank_lines_at_end &&
2904                    preimage.nr + applied_pos >= img->nr &&
2905                    (ws_rule & WS_BLANK_AT_EOF) &&
2906                    ws_error_action != nowarn_ws_error) {
2907                        record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2908                                        found_new_blank_lines_at_end);
2909                        if (ws_error_action == correct_ws_error) {
2910                                while (new_blank_lines_at_end--)
2911                                        remove_last_line(&postimage);
2912                        }
2913                        /*
2914                         * We would want to prevent write_out_results()
2915                         * from taking place in apply_patch() that follows
2916                         * the callchain led us here, which is:
2917                         * apply_patch->check_patch_list->check_patch->
2918                         * apply_data->apply_fragments->apply_one_fragment
2919                         */
2920                        if (ws_error_action == die_on_ws_error)
2921                                apply = 0;
2922                }
2923
2924                if (state->apply_verbosely && applied_pos != pos) {
2925                        int offset = applied_pos - pos;
2926                        if (state->apply_in_reverse)
2927                                offset = 0 - offset;
2928                        fprintf_ln(stderr,
2929                                   Q_("Hunk #%d succeeded at %d (offset %d line).",
2930                                      "Hunk #%d succeeded at %d (offset %d lines).",
2931                                      offset),
2932                                   nth_fragment, applied_pos + 1, offset);
2933                }
2934
2935                /*
2936                 * Warn if it was necessary to reduce the number
2937                 * of context lines.
2938                 */
2939                if ((leading != frag->leading) ||
2940                    (trailing != frag->trailing))
2941                        fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2942                                             " to apply fragment at %d"),
2943                                   leading, trailing, applied_pos+1);
2944                update_image(state, img, applied_pos, &preimage, &postimage);
2945        } else {
2946                if (state->apply_verbosely)
2947                        error(_("while searching for:\n%.*s"),
2948                              (int)(old - oldlines), oldlines);
2949        }
2950
2951out:
2952        free(oldlines);
2953        strbuf_release(&newlines);
2954        free(preimage.line_allocated);
2955        free(postimage.line_allocated);
2956
2957        return (applied_pos < 0);
2958}
2959
2960static int apply_binary_fragment(struct apply_state *state,
2961                                 struct image *img,
2962                                 struct patch *patch)
2963{
2964        struct fragment *fragment = patch->fragments;
2965        unsigned long len;
2966        void *dst;
2967
2968        if (!fragment)
2969                return error(_("missing binary patch data for '%s'"),
2970                             patch->new_name ?
2971                             patch->new_name :
2972                             patch->old_name);
2973
2974        /* Binary patch is irreversible without the optional second hunk */
2975        if (state->apply_in_reverse) {
2976                if (!fragment->next)
2977                        return error("cannot reverse-apply a binary patch "
2978                                     "without the reverse hunk to '%s'",
2979                                     patch->new_name
2980                                     ? patch->new_name : patch->old_name);
2981                fragment = fragment->next;
2982        }
2983        switch (fragment->binary_patch_method) {
2984        case BINARY_DELTA_DEFLATED:
2985                dst = patch_delta(img->buf, img->len, fragment->patch,
2986                                  fragment->size, &len);
2987                if (!dst)
2988                        return -1;
2989                clear_image(img);
2990                img->buf = dst;
2991                img->len = len;
2992                return 0;
2993        case BINARY_LITERAL_DEFLATED:
2994                clear_image(img);
2995                img->len = fragment->size;
2996                img->buf = xmemdupz(fragment->patch, img->len);
2997                return 0;
2998        }
2999        return -1;
3000}
3001
3002/*
3003 * Replace "img" with the result of applying the binary patch.
3004 * The binary patch data itself in patch->fragment is still kept
3005 * but the preimage prepared by the caller in "img" is freed here
3006 * or in the helper function apply_binary_fragment() this calls.
3007 */
3008static int apply_binary(struct apply_state *state,
3009                        struct image *img,
3010                        struct patch *patch)
3011{
3012        const char *name = patch->old_name ? patch->old_name : patch->new_name;
3013        unsigned char sha1[20];
3014
3015        /*
3016         * For safety, we require patch index line to contain
3017         * full 40-byte textual SHA1 for old and new, at least for now.
3018         */
3019        if (strlen(patch->old_sha1_prefix) != 40 ||
3020            strlen(patch->new_sha1_prefix) != 40 ||
3021            get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3022            get_sha1_hex(patch->new_sha1_prefix, sha1))
3023                return error("cannot apply binary patch to '%s' "
3024                             "without full index line", name);
3025
3026        if (patch->old_name) {
3027                /*
3028                 * See if the old one matches what the patch
3029                 * applies to.
3030                 */
3031                hash_sha1_file(img->buf, img->len, blob_type, sha1);
3032                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3033                        return error("the patch applies to '%s' (%s), "
3034                                     "which does not match the "
3035                                     "current contents.",
3036                                     name, sha1_to_hex(sha1));
3037        }
3038        else {
3039                /* Otherwise, the old one must be empty. */
3040                if (img->len)
3041                        return error("the patch applies to an empty "
3042                                     "'%s' but it is not empty", name);
3043        }
3044
3045        get_sha1_hex(patch->new_sha1_prefix, sha1);
3046        if (is_null_sha1(sha1)) {
3047                clear_image(img);
3048                return 0; /* deletion patch */
3049        }
3050
3051        if (has_sha1_file(sha1)) {
3052                /* We already have the postimage */
3053                enum object_type type;
3054                unsigned long size;
3055                char *result;
3056
3057                result = read_sha1_file(sha1, &type, &size);
3058                if (!result)
3059                        return error("the necessary postimage %s for "
3060                                     "'%s' cannot be read",
3061                                     patch->new_sha1_prefix, name);
3062                clear_image(img);
3063                img->buf = result;
3064                img->len = size;
3065        } else {
3066                /*
3067                 * We have verified buf matches the preimage;
3068                 * apply the patch data to it, which is stored
3069                 * in the patch->fragments->{patch,size}.
3070                 */
3071                if (apply_binary_fragment(state, img, patch))
3072                        return error(_("binary patch does not apply to '%s'"),
3073                                     name);
3074
3075                /* verify that the result matches */
3076                hash_sha1_file(img->buf, img->len, blob_type, sha1);
3077                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3078                        return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3079                                name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3080        }
3081
3082        return 0;
3083}
3084
3085static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3086{
3087        struct fragment *frag = patch->fragments;
3088        const char *name = patch->old_name ? patch->old_name : patch->new_name;
3089        unsigned ws_rule = patch->ws_rule;
3090        unsigned inaccurate_eof = patch->inaccurate_eof;
3091        int nth = 0;
3092
3093        if (patch->is_binary)
3094                return apply_binary(state, img, patch);
3095
3096        while (frag) {
3097                nth++;
3098                if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3099                        error(_("patch failed: %s:%ld"), name, frag->oldpos);
3100                        if (!state->apply_with_reject)
3101                                return -1;
3102                        frag->rejected = 1;
3103                }
3104                frag = frag->next;
3105        }
3106        return 0;
3107}
3108
3109static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3110{
3111        if (S_ISGITLINK(mode)) {
3112                strbuf_grow(buf, 100);
3113                strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3114        } else {
3115                enum object_type type;
3116                unsigned long sz;
3117                char *result;
3118
3119                result = read_sha1_file(sha1, &type, &sz);
3120                if (!result)
3121                        return -1;
3122                /* XXX read_sha1_file NUL-terminates */
3123                strbuf_attach(buf, result, sz, sz + 1);
3124        }
3125        return 0;
3126}
3127
3128static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3129{
3130        if (!ce)
3131                return 0;
3132        return read_blob_object(buf, ce->sha1, ce->ce_mode);
3133}
3134
3135static struct patch *in_fn_table(const char *name)
3136{
3137        struct string_list_item *item;
3138
3139        if (name == NULL)
3140                return NULL;
3141
3142        item = string_list_lookup(&fn_table, name);
3143        if (item != NULL)
3144                return (struct patch *)item->util;
3145
3146        return NULL;
3147}
3148
3149/*
3150 * item->util in the filename table records the status of the path.
3151 * Usually it points at a patch (whose result records the contents
3152 * of it after applying it), but it could be PATH_WAS_DELETED for a
3153 * path that a previously applied patch has already removed, or
3154 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3155 *
3156 * The latter is needed to deal with a case where two paths A and B
3157 * are swapped by first renaming A to B and then renaming B to A;
3158 * moving A to B should not be prevented due to presence of B as we
3159 * will remove it in a later patch.
3160 */
3161#define PATH_TO_BE_DELETED ((struct patch *) -2)
3162#define PATH_WAS_DELETED ((struct patch *) -1)
3163
3164static int to_be_deleted(struct patch *patch)
3165{
3166        return patch == PATH_TO_BE_DELETED;
3167}
3168
3169static int was_deleted(struct patch *patch)
3170{
3171        return patch == PATH_WAS_DELETED;
3172}
3173
3174static void add_to_fn_table(struct patch *patch)
3175{
3176        struct string_list_item *item;
3177
3178        /*
3179         * Always add new_name unless patch is a deletion
3180         * This should cover the cases for normal diffs,
3181         * file creations and copies
3182         */
3183        if (patch->new_name != NULL) {
3184                item = string_list_insert(&fn_table, patch->new_name);
3185                item->util = patch;
3186        }
3187
3188        /*
3189         * store a failure on rename/deletion cases because
3190         * later chunks shouldn't patch old names
3191         */
3192        if ((patch->new_name == NULL) || (patch->is_rename)) {
3193                item = string_list_insert(&fn_table, patch->old_name);
3194                item->util = PATH_WAS_DELETED;
3195        }
3196}
3197
3198static void prepare_fn_table(struct patch *patch)
3199{
3200        /*
3201         * store information about incoming file deletion
3202         */
3203        while (patch) {
3204                if ((patch->new_name == NULL) || (patch->is_rename)) {
3205                        struct string_list_item *item;
3206                        item = string_list_insert(&fn_table, patch->old_name);
3207                        item->util = PATH_TO_BE_DELETED;
3208                }
3209                patch = patch->next;
3210        }
3211}
3212
3213static int checkout_target(struct index_state *istate,
3214                           struct cache_entry *ce, struct stat *st)
3215{
3216        struct checkout costate;
3217
3218        memset(&costate, 0, sizeof(costate));
3219        costate.base_dir = "";
3220        costate.refresh_cache = 1;
3221        costate.istate = istate;
3222        if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3223                return error(_("cannot checkout %s"), ce->name);
3224        return 0;
3225}
3226
3227static struct patch *previous_patch(struct patch *patch, int *gone)
3228{
3229        struct patch *previous;
3230
3231        *gone = 0;
3232        if (patch->is_copy || patch->is_rename)
3233                return NULL; /* "git" patches do not depend on the order */
3234
3235        previous = in_fn_table(patch->old_name);
3236        if (!previous)
3237                return NULL;
3238
3239        if (to_be_deleted(previous))
3240                return NULL; /* the deletion hasn't happened yet */
3241
3242        if (was_deleted(previous))
3243                *gone = 1;
3244
3245        return previous;
3246}
3247
3248static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3249{
3250        if (S_ISGITLINK(ce->ce_mode)) {
3251                if (!S_ISDIR(st->st_mode))
3252                        return -1;
3253                return 0;
3254        }
3255        return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3256}
3257
3258#define SUBMODULE_PATCH_WITHOUT_INDEX 1
3259
3260static int load_patch_target(struct apply_state *state,
3261                             struct strbuf *buf,
3262                             const struct cache_entry *ce,
3263                             struct stat *st,
3264                             const char *name,
3265                             unsigned expected_mode)
3266{
3267        if (state->cached || state->check_index) {
3268                if (read_file_or_gitlink(ce, buf))
3269                        return error(_("read of %s failed"), name);
3270        } else if (name) {
3271                if (S_ISGITLINK(expected_mode)) {
3272                        if (ce)
3273                                return read_file_or_gitlink(ce, buf);
3274                        else
3275                                return SUBMODULE_PATCH_WITHOUT_INDEX;
3276                } else if (has_symlink_leading_path(name, strlen(name))) {
3277                        return error(_("reading from '%s' beyond a symbolic link"), name);
3278                } else {
3279                        if (read_old_data(st, name, buf))
3280                                return error(_("read of %s failed"), name);
3281                }
3282        }
3283        return 0;
3284}
3285
3286/*
3287 * We are about to apply "patch"; populate the "image" with the
3288 * current version we have, from the working tree or from the index,
3289 * depending on the situation e.g. --cached/--index.  If we are
3290 * applying a non-git patch that incrementally updates the tree,
3291 * we read from the result of a previous diff.
3292 */
3293static int load_preimage(struct apply_state *state,
3294                         struct image *image,
3295                         struct patch *patch, struct stat *st,
3296                         const struct cache_entry *ce)
3297{
3298        struct strbuf buf = STRBUF_INIT;
3299        size_t len;
3300        char *img;
3301        struct patch *previous;
3302        int status;
3303
3304        previous = previous_patch(patch, &status);
3305        if (status)
3306                return error(_("path %s has been renamed/deleted"),
3307                             patch->old_name);
3308        if (previous) {
3309                /* We have a patched copy in memory; use that. */
3310                strbuf_add(&buf, previous->result, previous->resultsize);
3311        } else {
3312                status = load_patch_target(state, &buf, ce, st,
3313                                           patch->old_name, patch->old_mode);
3314                if (status < 0)
3315                        return status;
3316                else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3317                        /*
3318                         * There is no way to apply subproject
3319                         * patch without looking at the index.
3320                         * NEEDSWORK: shouldn't this be flagged
3321                         * as an error???
3322                         */
3323                        free_fragment_list(patch->fragments);
3324                        patch->fragments = NULL;
3325                } else if (status) {
3326                        return error(_("read of %s failed"), patch->old_name);
3327                }
3328        }
3329
3330        img = strbuf_detach(&buf, &len);
3331        prepare_image(image, img, len, !patch->is_binary);
3332        return 0;
3333}
3334
3335static int three_way_merge(struct image *image,
3336                           char *path,
3337                           const unsigned char *base,
3338                           const unsigned char *ours,
3339                           const unsigned char *theirs)
3340{
3341        mmfile_t base_file, our_file, their_file;
3342        mmbuffer_t result = { NULL };
3343        int status;
3344
3345        read_mmblob(&base_file, base);
3346        read_mmblob(&our_file, ours);
3347        read_mmblob(&their_file, theirs);
3348        status = ll_merge(&result, path,
3349                          &base_file, "base",
3350                          &our_file, "ours",
3351                          &their_file, "theirs", NULL);
3352        free(base_file.ptr);
3353        free(our_file.ptr);
3354        free(their_file.ptr);
3355        if (status < 0 || !result.ptr) {
3356                free(result.ptr);
3357                return -1;
3358        }
3359        clear_image(image);
3360        image->buf = result.ptr;
3361        image->len = result.size;
3362
3363        return status;
3364}
3365
3366/*
3367 * When directly falling back to add/add three-way merge, we read from
3368 * the current contents of the new_name.  In no cases other than that
3369 * this function will be called.
3370 */
3371static int load_current(struct apply_state *state,
3372                        struct image *image,
3373                        struct patch *patch)
3374{
3375        struct strbuf buf = STRBUF_INIT;
3376        int status, pos;
3377        size_t len;
3378        char *img;
3379        struct stat st;
3380        struct cache_entry *ce;
3381        char *name = patch->new_name;
3382        unsigned mode = patch->new_mode;
3383
3384        if (!patch->is_new)
3385                die("BUG: patch to %s is not a creation", patch->old_name);
3386
3387        pos = cache_name_pos(name, strlen(name));
3388        if (pos < 0)
3389                return error(_("%s: does not exist in index"), name);
3390        ce = active_cache[pos];
3391        if (lstat(name, &st)) {
3392                if (errno != ENOENT)
3393                        return error(_("%s: %s"), name, strerror(errno));
3394                if (checkout_target(&the_index, ce, &st))
3395                        return -1;
3396        }
3397        if (verify_index_match(ce, &st))
3398                return error(_("%s: does not match index"), name);
3399
3400        status = load_patch_target(state, &buf, ce, &st, name, mode);
3401        if (status < 0)
3402                return status;
3403        else if (status)
3404                return -1;
3405        img = strbuf_detach(&buf, &len);
3406        prepare_image(image, img, len, !patch->is_binary);
3407        return 0;
3408}
3409
3410static int try_threeway(struct apply_state *state,
3411                        struct image *image,
3412                        struct patch *patch,
3413                        struct stat *st,
3414                        const struct cache_entry *ce)
3415{
3416        unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3417        struct strbuf buf = STRBUF_INIT;
3418        size_t len;
3419        int status;
3420        char *img;
3421        struct image tmp_image;
3422
3423        /* No point falling back to 3-way merge in these cases */
3424        if (patch->is_delete ||
3425            S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3426                return -1;
3427
3428        /* Preimage the patch was prepared for */
3429        if (patch->is_new)
3430                write_sha1_file("", 0, blob_type, pre_sha1);
3431        else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3432                 read_blob_object(&buf, pre_sha1, patch->old_mode))
3433                return error("repository lacks the necessary blob to fall back on 3-way merge.");
3434
3435        fprintf(stderr, "Falling back to three-way merge...\n");
3436
3437        img = strbuf_detach(&buf, &len);
3438        prepare_image(&tmp_image, img, len, 1);
3439        /* Apply the patch to get the post image */
3440        if (apply_fragments(state, &tmp_image, patch) < 0) {
3441                clear_image(&tmp_image);
3442                return -1;
3443        }
3444        /* post_sha1[] is theirs */
3445        write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3446        clear_image(&tmp_image);
3447
3448        /* our_sha1[] is ours */
3449        if (patch->is_new) {
3450                if (load_current(state, &tmp_image, patch))
3451                        return error("cannot read the current contents of '%s'",
3452                                     patch->new_name);
3453        } else {
3454                if (load_preimage(state, &tmp_image, patch, st, ce))
3455                        return error("cannot read the current contents of '%s'",
3456                                     patch->old_name);
3457        }
3458        write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3459        clear_image(&tmp_image);
3460
3461        /* in-core three-way merge between post and our using pre as base */
3462        status = three_way_merge(image, patch->new_name,
3463                                 pre_sha1, our_sha1, post_sha1);
3464        if (status < 0) {
3465                fprintf(stderr, "Failed to fall back on three-way merge...\n");
3466                return status;
3467        }
3468
3469        if (status) {
3470                patch->conflicted_threeway = 1;
3471                if (patch->is_new)
3472                        oidclr(&patch->threeway_stage[0]);
3473                else
3474                        hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3475                hashcpy(patch->threeway_stage[1].hash, our_sha1);
3476                hashcpy(patch->threeway_stage[2].hash, post_sha1);
3477                fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3478        } else {
3479                fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3480        }
3481        return 0;
3482}
3483
3484static int apply_data(struct apply_state *state, struct patch *patch,
3485                      struct stat *st, const struct cache_entry *ce)
3486{
3487        struct image image;
3488
3489        if (load_preimage(state, &image, patch, st, ce) < 0)
3490                return -1;
3491
3492        if (patch->direct_to_threeway ||
3493            apply_fragments(state, &image, patch) < 0) {
3494                /* Note: with --reject, apply_fragments() returns 0 */
3495                if (!threeway || try_threeway(state, &image, patch, st, ce) < 0)
3496                        return -1;
3497        }
3498        patch->result = image.buf;
3499        patch->resultsize = image.len;
3500        add_to_fn_table(patch);
3501        free(image.line_allocated);
3502
3503        if (0 < patch->is_delete && patch->resultsize)
3504                return error(_("removal patch leaves file contents"));
3505
3506        return 0;
3507}
3508
3509/*
3510 * If "patch" that we are looking at modifies or deletes what we have,
3511 * we would want it not to lose any local modification we have, either
3512 * in the working tree or in the index.
3513 *
3514 * This also decides if a non-git patch is a creation patch or a
3515 * modification to an existing empty file.  We do not check the state
3516 * of the current tree for a creation patch in this function; the caller
3517 * check_patch() separately makes sure (and errors out otherwise) that
3518 * the path the patch creates does not exist in the current tree.
3519 */
3520static int check_preimage(struct apply_state *state,
3521                          struct patch *patch,
3522                          struct cache_entry **ce,
3523                          struct stat *st)
3524{
3525        const char *old_name = patch->old_name;
3526        struct patch *previous = NULL;
3527        int stat_ret = 0, status;
3528        unsigned st_mode = 0;
3529
3530        if (!old_name)
3531                return 0;
3532
3533        assert(patch->is_new <= 0);
3534        previous = previous_patch(patch, &status);
3535
3536        if (status)
3537                return error(_("path %s has been renamed/deleted"), old_name);
3538        if (previous) {
3539                st_mode = previous->new_mode;
3540        } else if (!state->cached) {
3541                stat_ret = lstat(old_name, st);
3542                if (stat_ret && errno != ENOENT)
3543                        return error(_("%s: %s"), old_name, strerror(errno));
3544        }
3545
3546        if (state->check_index && !previous) {
3547                int pos = cache_name_pos(old_name, strlen(old_name));
3548                if (pos < 0) {
3549                        if (patch->is_new < 0)
3550                                goto is_new;
3551                        return error(_("%s: does not exist in index"), old_name);
3552                }
3553                *ce = active_cache[pos];
3554                if (stat_ret < 0) {
3555                        if (checkout_target(&the_index, *ce, st))
3556                                return -1;
3557                }
3558                if (!state->cached && verify_index_match(*ce, st))
3559                        return error(_("%s: does not match index"), old_name);
3560                if (state->cached)
3561                        st_mode = (*ce)->ce_mode;
3562        } else if (stat_ret < 0) {
3563                if (patch->is_new < 0)
3564                        goto is_new;
3565                return error(_("%s: %s"), old_name, strerror(errno));
3566        }
3567
3568        if (!state->cached && !previous)
3569                st_mode = ce_mode_from_stat(*ce, st->st_mode);
3570
3571        if (patch->is_new < 0)
3572                patch->is_new = 0;
3573        if (!patch->old_mode)
3574                patch->old_mode = st_mode;
3575        if ((st_mode ^ patch->old_mode) & S_IFMT)
3576                return error(_("%s: wrong type"), old_name);
3577        if (st_mode != patch->old_mode)
3578                warning(_("%s has type %o, expected %o"),
3579                        old_name, st_mode, patch->old_mode);
3580        if (!patch->new_mode && !patch->is_delete)
3581                patch->new_mode = st_mode;
3582        return 0;
3583
3584 is_new:
3585        patch->is_new = 1;
3586        patch->is_delete = 0;
3587        free(patch->old_name);
3588        patch->old_name = NULL;
3589        return 0;
3590}
3591
3592
3593#define EXISTS_IN_INDEX 1
3594#define EXISTS_IN_WORKTREE 2
3595
3596static int check_to_create(struct apply_state *state,
3597                           const char *new_name,
3598                           int ok_if_exists)
3599{
3600        struct stat nst;
3601
3602        if (state->check_index &&
3603            cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3604            !ok_if_exists)
3605                return EXISTS_IN_INDEX;
3606        if (state->cached)
3607                return 0;
3608
3609        if (!lstat(new_name, &nst)) {
3610                if (S_ISDIR(nst.st_mode) || ok_if_exists)
3611                        return 0;
3612                /*
3613                 * A leading component of new_name might be a symlink
3614                 * that is going to be removed with this patch, but
3615                 * still pointing at somewhere that has the path.
3616                 * In such a case, path "new_name" does not exist as
3617                 * far as git is concerned.
3618                 */
3619                if (has_symlink_leading_path(new_name, strlen(new_name)))
3620                        return 0;
3621
3622                return EXISTS_IN_WORKTREE;
3623        } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3624                return error("%s: %s", new_name, strerror(errno));
3625        }
3626        return 0;
3627}
3628
3629/*
3630 * We need to keep track of how symlinks in the preimage are
3631 * manipulated by the patches.  A patch to add a/b/c where a/b
3632 * is a symlink should not be allowed to affect the directory
3633 * the symlink points at, but if the same patch removes a/b,
3634 * it is perfectly fine, as the patch removes a/b to make room
3635 * to create a directory a/b so that a/b/c can be created.
3636 */
3637static struct string_list symlink_changes;
3638#define SYMLINK_GOES_AWAY 01
3639#define SYMLINK_IN_RESULT 02
3640
3641static uintptr_t register_symlink_changes(const char *path, uintptr_t what)
3642{
3643        struct string_list_item *ent;
3644
3645        ent = string_list_lookup(&symlink_changes, path);
3646        if (!ent) {
3647                ent = string_list_insert(&symlink_changes, path);
3648                ent->util = (void *)0;
3649        }
3650        ent->util = (void *)(what | ((uintptr_t)ent->util));
3651        return (uintptr_t)ent->util;
3652}
3653
3654static uintptr_t check_symlink_changes(const char *path)
3655{
3656        struct string_list_item *ent;
3657
3658        ent = string_list_lookup(&symlink_changes, path);
3659        if (!ent)
3660                return 0;
3661        return (uintptr_t)ent->util;
3662}
3663
3664static void prepare_symlink_changes(struct patch *patch)
3665{
3666        for ( ; patch; patch = patch->next) {
3667                if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3668                    (patch->is_rename || patch->is_delete))
3669                        /* the symlink at patch->old_name is removed */
3670                        register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);
3671
3672                if (patch->new_name && S_ISLNK(patch->new_mode))
3673                        /* the symlink at patch->new_name is created or remains */
3674                        register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);
3675        }
3676}
3677
3678static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3679{
3680        do {
3681                unsigned int change;
3682
3683                while (--name->len && name->buf[name->len] != '/')
3684                        ; /* scan backwards */
3685                if (!name->len)
3686                        break;
3687                name->buf[name->len] = '\0';
3688                change = check_symlink_changes(name->buf);
3689                if (change & SYMLINK_IN_RESULT)
3690                        return 1;
3691                if (change & SYMLINK_GOES_AWAY)
3692                        /*
3693                         * This cannot be "return 0", because we may
3694                         * see a new one created at a higher level.
3695                         */
3696                        continue;
3697
3698                /* otherwise, check the preimage */
3699                if (state->check_index) {
3700                        struct cache_entry *ce;
3701
3702                        ce = cache_file_exists(name->buf, name->len, ignore_case);
3703                        if (ce && S_ISLNK(ce->ce_mode))
3704                                return 1;
3705                } else {
3706                        struct stat st;
3707                        if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3708                                return 1;
3709                }
3710        } while (1);
3711        return 0;
3712}
3713
3714static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3715{
3716        int ret;
3717        struct strbuf name = STRBUF_INIT;
3718
3719        assert(*name_ != '\0');
3720        strbuf_addstr(&name, name_);
3721        ret = path_is_beyond_symlink_1(state, &name);
3722        strbuf_release(&name);
3723
3724        return ret;
3725}
3726
3727static void die_on_unsafe_path(struct patch *patch)
3728{
3729        const char *old_name = NULL;
3730        const char *new_name = NULL;
3731        if (patch->is_delete)
3732                old_name = patch->old_name;
3733        else if (!patch->is_new && !patch->is_copy)
3734                old_name = patch->old_name;
3735        if (!patch->is_delete)
3736                new_name = patch->new_name;
3737
3738        if (old_name && !verify_path(old_name))
3739                die(_("invalid path '%s'"), old_name);
3740        if (new_name && !verify_path(new_name))
3741                die(_("invalid path '%s'"), new_name);
3742}
3743
3744/*
3745 * Check and apply the patch in-core; leave the result in patch->result
3746 * for the caller to write it out to the final destination.
3747 */
3748static int check_patch(struct apply_state *state, struct patch *patch)
3749{
3750        struct stat st;
3751        const char *old_name = patch->old_name;
3752        const char *new_name = patch->new_name;
3753        const char *name = old_name ? old_name : new_name;
3754        struct cache_entry *ce = NULL;
3755        struct patch *tpatch;
3756        int ok_if_exists;
3757        int status;
3758
3759        patch->rejected = 1; /* we will drop this after we succeed */
3760
3761        status = check_preimage(state, patch, &ce, &st);
3762        if (status)
3763                return status;
3764        old_name = patch->old_name;
3765
3766        /*
3767         * A type-change diff is always split into a patch to delete
3768         * old, immediately followed by a patch to create new (see
3769         * diff.c::run_diff()); in such a case it is Ok that the entry
3770         * to be deleted by the previous patch is still in the working
3771         * tree and in the index.
3772         *
3773         * A patch to swap-rename between A and B would first rename A
3774         * to B and then rename B to A.  While applying the first one,
3775         * the presence of B should not stop A from getting renamed to
3776         * B; ask to_be_deleted() about the later rename.  Removal of
3777         * B and rename from A to B is handled the same way by asking
3778         * was_deleted().
3779         */
3780        if ((tpatch = in_fn_table(new_name)) &&
3781            (was_deleted(tpatch) || to_be_deleted(tpatch)))
3782                ok_if_exists = 1;
3783        else
3784                ok_if_exists = 0;
3785
3786        if (new_name &&
3787            ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3788                int err = check_to_create(state, new_name, ok_if_exists);
3789
3790                if (err && threeway) {
3791                        patch->direct_to_threeway = 1;
3792                } else switch (err) {
3793                case 0:
3794                        break; /* happy */
3795                case EXISTS_IN_INDEX:
3796                        return error(_("%s: already exists in index"), new_name);
3797                        break;
3798                case EXISTS_IN_WORKTREE:
3799                        return error(_("%s: already exists in working directory"),
3800                                     new_name);
3801                default:
3802                        return err;
3803                }
3804
3805                if (!patch->new_mode) {
3806                        if (0 < patch->is_new)
3807                                patch->new_mode = S_IFREG | 0644;
3808                        else
3809                                patch->new_mode = patch->old_mode;
3810                }
3811        }
3812
3813        if (new_name && old_name) {
3814                int same = !strcmp(old_name, new_name);
3815                if (!patch->new_mode)
3816                        patch->new_mode = patch->old_mode;
3817                if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3818                        if (same)
3819                                return error(_("new mode (%o) of %s does not "
3820                                               "match old mode (%o)"),
3821                                        patch->new_mode, new_name,
3822                                        patch->old_mode);
3823                        else
3824                                return error(_("new mode (%o) of %s does not "
3825                                               "match old mode (%o) of %s"),
3826                                        patch->new_mode, new_name,
3827                                        patch->old_mode, old_name);
3828                }
3829        }
3830
3831        if (!unsafe_paths)
3832                die_on_unsafe_path(patch);
3833
3834        /*
3835         * An attempt to read from or delete a path that is beyond a
3836         * symbolic link will be prevented by load_patch_target() that
3837         * is called at the beginning of apply_data() so we do not
3838         * have to worry about a patch marked with "is_delete" bit
3839         * here.  We however need to make sure that the patch result
3840         * is not deposited to a path that is beyond a symbolic link
3841         * here.
3842         */
3843        if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3844                return error(_("affected file '%s' is beyond a symbolic link"),
3845                             patch->new_name);
3846
3847        if (apply_data(state, patch, &st, ce) < 0)
3848                return error(_("%s: patch does not apply"), name);
3849        patch->rejected = 0;
3850        return 0;
3851}
3852
3853static int check_patch_list(struct apply_state *state, struct patch *patch)
3854{
3855        int err = 0;
3856
3857        prepare_symlink_changes(patch);
3858        prepare_fn_table(patch);
3859        while (patch) {
3860                if (state->apply_verbosely)
3861                        say_patch_name(stderr,
3862                                       _("Checking patch %s..."), patch);
3863                err |= check_patch(state, patch);
3864                patch = patch->next;
3865        }
3866        return err;
3867}
3868
3869/* This function tries to read the sha1 from the current index */
3870static int get_current_sha1(const char *path, unsigned char *sha1)
3871{
3872        int pos;
3873
3874        if (read_cache() < 0)
3875                return -1;
3876        pos = cache_name_pos(path, strlen(path));
3877        if (pos < 0)
3878                return -1;
3879        hashcpy(sha1, active_cache[pos]->sha1);
3880        return 0;
3881}
3882
3883static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3884{
3885        /*
3886         * A usable gitlink patch has only one fragment (hunk) that looks like:
3887         * @@ -1 +1 @@
3888         * -Subproject commit <old sha1>
3889         * +Subproject commit <new sha1>
3890         * or
3891         * @@ -1 +0,0 @@
3892         * -Subproject commit <old sha1>
3893         * for a removal patch.
3894         */
3895        struct fragment *hunk = p->fragments;
3896        static const char heading[] = "-Subproject commit ";
3897        char *preimage;
3898
3899        if (/* does the patch have only one hunk? */
3900            hunk && !hunk->next &&
3901            /* is its preimage one line? */
3902            hunk->oldpos == 1 && hunk->oldlines == 1 &&
3903            /* does preimage begin with the heading? */
3904            (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3905            starts_with(++preimage, heading) &&
3906            /* does it record full SHA-1? */
3907            !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3908            preimage[sizeof(heading) + 40 - 1] == '\n' &&
3909            /* does the abbreviated name on the index line agree with it? */
3910            starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3911                return 0; /* it all looks fine */
3912
3913        /* we may have full object name on the index line */
3914        return get_sha1_hex(p->old_sha1_prefix, sha1);
3915}
3916
3917/* Build an index that contains the just the files needed for a 3way merge */
3918static void build_fake_ancestor(struct patch *list, const char *filename)
3919{
3920        struct patch *patch;
3921        struct index_state result = { NULL };
3922        static struct lock_file lock;
3923
3924        /* Once we start supporting the reverse patch, it may be
3925         * worth showing the new sha1 prefix, but until then...
3926         */
3927        for (patch = list; patch; patch = patch->next) {
3928                unsigned char sha1[20];
3929                struct cache_entry *ce;
3930                const char *name;
3931
3932                name = patch->old_name ? patch->old_name : patch->new_name;
3933                if (0 < patch->is_new)
3934                        continue;
3935
3936                if (S_ISGITLINK(patch->old_mode)) {
3937                        if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3938                                ; /* ok, the textual part looks sane */
3939                        else
3940                                die("sha1 information is lacking or useless for submodule %s",
3941                                    name);
3942                } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3943                        ; /* ok */
3944                } else if (!patch->lines_added && !patch->lines_deleted) {
3945                        /* mode-only change: update the current */
3946                        if (get_current_sha1(patch->old_name, sha1))
3947                                die("mode change for %s, which is not "
3948                                    "in current HEAD", name);
3949                } else
3950                        die("sha1 information is lacking or useless "
3951                            "(%s).", name);
3952
3953                ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3954                if (!ce)
3955                        die(_("make_cache_entry failed for path '%s'"), name);
3956                if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3957                        die ("Could not add %s to temporary index", name);
3958        }
3959
3960        hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3961        if (write_locked_index(&result, &lock, COMMIT_LOCK))
3962                die ("Could not write temporary index to %s", filename);
3963
3964        discard_index(&result);
3965}
3966
3967static void stat_patch_list(struct patch *patch)
3968{
3969        int files, adds, dels;
3970
3971        for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3972                files++;
3973                adds += patch->lines_added;
3974                dels += patch->lines_deleted;
3975                show_stats(patch);
3976        }
3977
3978        print_stat_summary(stdout, files, adds, dels);
3979}
3980
3981static void numstat_patch_list(struct patch *patch)
3982{
3983        for ( ; patch; patch = patch->next) {
3984                const char *name;
3985                name = patch->new_name ? patch->new_name : patch->old_name;
3986                if (patch->is_binary)
3987                        printf("-\t-\t");
3988                else
3989                        printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3990                write_name_quoted(name, stdout, line_termination);
3991        }
3992}
3993
3994static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3995{
3996        if (mode)
3997                printf(" %s mode %06o %s\n", newdelete, mode, name);
3998        else
3999                printf(" %s %s\n", newdelete, name);
4000}
4001
4002static void show_mode_change(struct patch *p, int show_name)
4003{
4004        if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4005                if (show_name)
4006                        printf(" mode change %06o => %06o %s\n",
4007                               p->old_mode, p->new_mode, p->new_name);
4008                else
4009                        printf(" mode change %06o => %06o\n",
4010                               p->old_mode, p->new_mode);
4011        }
4012}
4013
4014static void show_rename_copy(struct patch *p)
4015{
4016        const char *renamecopy = p->is_rename ? "rename" : "copy";
4017        const char *old, *new;
4018
4019        /* Find common prefix */
4020        old = p->old_name;
4021        new = p->new_name;
4022        while (1) {
4023                const char *slash_old, *slash_new;
4024                slash_old = strchr(old, '/');
4025                slash_new = strchr(new, '/');
4026                if (!slash_old ||
4027                    !slash_new ||
4028                    slash_old - old != slash_new - new ||
4029                    memcmp(old, new, slash_new - new))
4030                        break;
4031                old = slash_old + 1;
4032                new = slash_new + 1;
4033        }
4034        /* p->old_name thru old is the common prefix, and old and new
4035         * through the end of names are renames
4036         */
4037        if (old != p->old_name)
4038                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4039                       (int)(old - p->old_name), p->old_name,
4040                       old, new, p->score);
4041        else
4042                printf(" %s %s => %s (%d%%)\n", renamecopy,
4043                       p->old_name, p->new_name, p->score);
4044        show_mode_change(p, 0);
4045}
4046
4047static void summary_patch_list(struct patch *patch)
4048{
4049        struct patch *p;
4050
4051        for (p = patch; p; p = p->next) {
4052                if (p->is_new)
4053                        show_file_mode_name("create", p->new_mode, p->new_name);
4054                else if (p->is_delete)
4055                        show_file_mode_name("delete", p->old_mode, p->old_name);
4056                else {
4057                        if (p->is_rename || p->is_copy)
4058                                show_rename_copy(p);
4059                        else {
4060                                if (p->score) {
4061                                        printf(" rewrite %s (%d%%)\n",
4062                                               p->new_name, p->score);
4063                                        show_mode_change(p, 0);
4064                                }
4065                                else
4066                                        show_mode_change(p, 1);
4067                        }
4068                }
4069        }
4070}
4071
4072static void patch_stats(struct patch *patch)
4073{
4074        int lines = patch->lines_added + patch->lines_deleted;
4075
4076        if (lines > max_change)
4077                max_change = lines;
4078        if (patch->old_name) {
4079                int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4080                if (!len)
4081                        len = strlen(patch->old_name);
4082                if (len > max_len)
4083                        max_len = len;
4084        }
4085        if (patch->new_name) {
4086                int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4087                if (!len)
4088                        len = strlen(patch->new_name);
4089                if (len > max_len)
4090                        max_len = len;
4091        }
4092}
4093
4094static void remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4095{
4096        if (state->update_index) {
4097                if (remove_file_from_cache(patch->old_name) < 0)
4098                        die(_("unable to remove %s from index"), patch->old_name);
4099        }
4100        if (!state->cached) {
4101                if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4102                        remove_path(patch->old_name);
4103                }
4104        }
4105}
4106
4107static void add_index_file(struct apply_state *state,
4108                           const char *path,
4109                           unsigned mode,
4110                           void *buf,
4111                           unsigned long size)
4112{
4113        struct stat st;
4114        struct cache_entry *ce;
4115        int namelen = strlen(path);
4116        unsigned ce_size = cache_entry_size(namelen);
4117
4118        if (!state->update_index)
4119                return;
4120
4121        ce = xcalloc(1, ce_size);
4122        memcpy(ce->name, path, namelen);
4123        ce->ce_mode = create_ce_mode(mode);
4124        ce->ce_flags = create_ce_flags(0);
4125        ce->ce_namelen = namelen;
4126        if (S_ISGITLINK(mode)) {
4127                const char *s;
4128
4129                if (!skip_prefix(buf, "Subproject commit ", &s) ||
4130                    get_sha1_hex(s, ce->sha1))
4131                        die(_("corrupt patch for submodule %s"), path);
4132        } else {
4133                if (!state->cached) {
4134                        if (lstat(path, &st) < 0)
4135                                die_errno(_("unable to stat newly created file '%s'"),
4136                                          path);
4137                        fill_stat_cache_info(ce, &st);
4138                }
4139                if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4140                        die(_("unable to create backing store for newly created file %s"), path);
4141        }
4142        if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4143                die(_("unable to add cache entry for %s"), path);
4144}
4145
4146static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4147{
4148        int fd;
4149        struct strbuf nbuf = STRBUF_INIT;
4150
4151        if (S_ISGITLINK(mode)) {
4152                struct stat st;
4153                if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4154                        return 0;
4155                return mkdir(path, 0777);
4156        }
4157
4158        if (has_symlinks && S_ISLNK(mode))
4159                /* Although buf:size is counted string, it also is NUL
4160                 * terminated.
4161                 */
4162                return symlink(buf, path);
4163
4164        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4165        if (fd < 0)
4166                return -1;
4167
4168        if (convert_to_working_tree(path, buf, size, &nbuf)) {
4169                size = nbuf.len;
4170                buf  = nbuf.buf;
4171        }
4172        write_or_die(fd, buf, size);
4173        strbuf_release(&nbuf);
4174
4175        if (close(fd) < 0)
4176                die_errno(_("closing file '%s'"), path);
4177        return 0;
4178}
4179
4180/*
4181 * We optimistically assume that the directories exist,
4182 * which is true 99% of the time anyway. If they don't,
4183 * we create them and try again.
4184 */
4185static void create_one_file(struct apply_state *state,
4186                            char *path,
4187                            unsigned mode,
4188                            const char *buf,
4189                            unsigned long size)
4190{
4191        if (state->cached)
4192                return;
4193        if (!try_create_file(path, mode, buf, size))
4194                return;
4195
4196        if (errno == ENOENT) {
4197                if (safe_create_leading_directories(path))
4198                        return;
4199                if (!try_create_file(path, mode, buf, size))
4200                        return;
4201        }
4202
4203        if (errno == EEXIST || errno == EACCES) {
4204                /* We may be trying to create a file where a directory
4205                 * used to be.
4206                 */
4207                struct stat st;
4208                if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4209                        errno = EEXIST;
4210        }
4211
4212        if (errno == EEXIST) {
4213                unsigned int nr = getpid();
4214
4215                for (;;) {
4216                        char newpath[PATH_MAX];
4217                        mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4218                        if (!try_create_file(newpath, mode, buf, size)) {
4219                                if (!rename(newpath, path))
4220                                        return;
4221                                unlink_or_warn(newpath);
4222                                break;
4223                        }
4224                        if (errno != EEXIST)
4225                                break;
4226                        ++nr;
4227                }
4228        }
4229        die_errno(_("unable to write file '%s' mode %o"), path, mode);
4230}
4231
4232static void add_conflicted_stages_file(struct apply_state *state,
4233                                       struct patch *patch)
4234{
4235        int stage, namelen;
4236        unsigned ce_size, mode;
4237        struct cache_entry *ce;
4238
4239        if (!state->update_index)
4240                return;
4241        namelen = strlen(patch->new_name);
4242        ce_size = cache_entry_size(namelen);
4243        mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4244
4245        remove_file_from_cache(patch->new_name);
4246        for (stage = 1; stage < 4; stage++) {
4247                if (is_null_oid(&patch->threeway_stage[stage - 1]))
4248                        continue;
4249                ce = xcalloc(1, ce_size);
4250                memcpy(ce->name, patch->new_name, namelen);
4251                ce->ce_mode = create_ce_mode(mode);
4252                ce->ce_flags = create_ce_flags(stage);
4253                ce->ce_namelen = namelen;
4254                hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4255                if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4256                        die(_("unable to add cache entry for %s"), patch->new_name);
4257        }
4258}
4259
4260static void create_file(struct apply_state *state, struct patch *patch)
4261{
4262        char *path = patch->new_name;
4263        unsigned mode = patch->new_mode;
4264        unsigned long size = patch->resultsize;
4265        char *buf = patch->result;
4266
4267        if (!mode)
4268                mode = S_IFREG | 0644;
4269        create_one_file(state, path, mode, buf, size);
4270
4271        if (patch->conflicted_threeway)
4272                add_conflicted_stages_file(state, patch);
4273        else
4274                add_index_file(state, path, mode, buf, size);
4275}
4276
4277/* phase zero is to remove, phase one is to create */
4278static void write_out_one_result(struct apply_state *state,
4279                                 struct patch *patch,
4280                                 int phase)
4281{
4282        if (patch->is_delete > 0) {
4283                if (phase == 0)
4284                        remove_file(state, patch, 1);
4285                return;
4286        }
4287        if (patch->is_new > 0 || patch->is_copy) {
4288                if (phase == 1)
4289                        create_file(state, patch);
4290                return;
4291        }
4292        /*
4293         * Rename or modification boils down to the same
4294         * thing: remove the old, write the new
4295         */
4296        if (phase == 0)
4297                remove_file(state, patch, patch->is_rename);
4298        if (phase == 1)
4299                create_file(state, patch);
4300}
4301
4302static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4303{
4304        FILE *rej;
4305        char namebuf[PATH_MAX];
4306        struct fragment *frag;
4307        int cnt = 0;
4308        struct strbuf sb = STRBUF_INIT;
4309
4310        for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4311                if (!frag->rejected)
4312                        continue;
4313                cnt++;
4314        }
4315
4316        if (!cnt) {
4317                if (state->apply_verbosely)
4318                        say_patch_name(stderr,
4319                                       _("Applied patch %s cleanly."), patch);
4320                return 0;
4321        }
4322
4323        /* This should not happen, because a removal patch that leaves
4324         * contents are marked "rejected" at the patch level.
4325         */
4326        if (!patch->new_name)
4327                die(_("internal error"));
4328
4329        /* Say this even without --verbose */
4330        strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4331                            "Applying patch %%s with %d rejects...",
4332                            cnt),
4333                    cnt);
4334        say_patch_name(stderr, sb.buf, patch);
4335        strbuf_release(&sb);
4336
4337        cnt = strlen(patch->new_name);
4338        if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4339                cnt = ARRAY_SIZE(namebuf) - 5;
4340                warning(_("truncating .rej filename to %.*s.rej"),
4341                        cnt - 1, patch->new_name);
4342        }
4343        memcpy(namebuf, patch->new_name, cnt);
4344        memcpy(namebuf + cnt, ".rej", 5);
4345
4346        rej = fopen(namebuf, "w");
4347        if (!rej)
4348                return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4349
4350        /* Normal git tools never deal with .rej, so do not pretend
4351         * this is a git patch by saying --git or giving extended
4352         * headers.  While at it, maybe please "kompare" that wants
4353         * the trailing TAB and some garbage at the end of line ;-).
4354         */
4355        fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4356                patch->new_name, patch->new_name);
4357        for (cnt = 1, frag = patch->fragments;
4358             frag;
4359             cnt++, frag = frag->next) {
4360                if (!frag->rejected) {
4361                        fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4362                        continue;
4363                }
4364                fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4365                fprintf(rej, "%.*s", frag->size, frag->patch);
4366                if (frag->patch[frag->size-1] != '\n')
4367                        fputc('\n', rej);
4368        }
4369        fclose(rej);
4370        return -1;
4371}
4372
4373static int write_out_results(struct apply_state *state, struct patch *list)
4374{
4375        int phase;
4376        int errs = 0;
4377        struct patch *l;
4378        struct string_list cpath = STRING_LIST_INIT_DUP;
4379
4380        for (phase = 0; phase < 2; phase++) {
4381                l = list;
4382                while (l) {
4383                        if (l->rejected)
4384                                errs = 1;
4385                        else {
4386                                write_out_one_result(state, l, phase);
4387                                if (phase == 1) {
4388                                        if (write_out_one_reject(state, l))
4389                                                errs = 1;
4390                                        if (l->conflicted_threeway) {
4391                                                string_list_append(&cpath, l->new_name);
4392                                                errs = 1;
4393                                        }
4394                                }
4395                        }
4396                        l = l->next;
4397                }
4398        }
4399
4400        if (cpath.nr) {
4401                struct string_list_item *item;
4402
4403                string_list_sort(&cpath);
4404                for_each_string_list_item(item, &cpath)
4405                        fprintf(stderr, "U %s\n", item->string);
4406                string_list_clear(&cpath, 0);
4407
4408                rerere(0);
4409        }
4410
4411        return errs;
4412}
4413
4414static struct lock_file lock_file;
4415
4416#define INACCURATE_EOF  (1<<0)
4417#define RECOUNT         (1<<1)
4418
4419static int apply_patch(struct apply_state *state,
4420                       int fd,
4421                       const char *filename,
4422                       int options)
4423{
4424        size_t offset;
4425        struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4426        struct patch *list = NULL, **listp = &list;
4427        int skipped_patch = 0;
4428
4429        patch_input_file = filename;
4430        read_patch_file(&buf, fd);
4431        offset = 0;
4432        while (offset < buf.len) {
4433                struct patch *patch;
4434                int nr;
4435
4436                patch = xcalloc(1, sizeof(*patch));
4437                patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4438                patch->recount =  !!(options & RECOUNT);
4439                nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4440                if (nr < 0) {
4441                        free_patch(patch);
4442                        break;
4443                }
4444                if (state->apply_in_reverse)
4445                        reverse_patches(patch);
4446                if (use_patch(state, patch)) {
4447                        patch_stats(patch);
4448                        *listp = patch;
4449                        listp = &patch->next;
4450                }
4451                else {
4452                        if (state->apply_verbosely)
4453                                say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4454                        free_patch(patch);
4455                        skipped_patch++;
4456                }
4457                offset += nr;
4458        }
4459
4460        if (!list && !skipped_patch)
4461                die(_("unrecognized input"));
4462
4463        if (whitespace_error && (ws_error_action == die_on_ws_error))
4464                apply = 0;
4465
4466        state->update_index = state->check_index && apply;
4467        if (state->update_index && newfd < 0)
4468                newfd = hold_locked_index(&lock_file, 1);
4469
4470        if (state->check_index) {
4471                if (read_cache() < 0)
4472                        die(_("unable to read index file"));
4473        }
4474
4475        if ((state->check || apply) &&
4476            check_patch_list(state, list) < 0 &&
4477            !state->apply_with_reject)
4478                exit(1);
4479
4480        if (apply && write_out_results(state, list)) {
4481                if (state->apply_with_reject)
4482                        exit(1);
4483                /* with --3way, we still need to write the index out */
4484                return 1;
4485        }
4486
4487        if (fake_ancestor)
4488                build_fake_ancestor(list, fake_ancestor);
4489
4490        if (state->diffstat)
4491                stat_patch_list(list);
4492
4493        if (numstat)
4494                numstat_patch_list(list);
4495
4496        if (summary)
4497                summary_patch_list(list);
4498
4499        free_patch_list(list);
4500        strbuf_release(&buf);
4501        string_list_clear(&fn_table, 0);
4502        return 0;
4503}
4504
4505static void git_apply_config(void)
4506{
4507        git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4508        git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4509        git_config(git_default_config, NULL);
4510}
4511
4512static int option_parse_exclude(const struct option *opt,
4513                                const char *arg, int unset)
4514{
4515        add_name_limit(arg, 1);
4516        return 0;
4517}
4518
4519static int option_parse_include(const struct option *opt,
4520                                const char *arg, int unset)
4521{
4522        add_name_limit(arg, 0);
4523        has_include = 1;
4524        return 0;
4525}
4526
4527static int option_parse_p(const struct option *opt,
4528                          const char *arg, int unset)
4529{
4530        state_p_value = atoi(arg);
4531        p_value_known = 1;
4532        return 0;
4533}
4534
4535static int option_parse_space_change(const struct option *opt,
4536                          const char *arg, int unset)
4537{
4538        if (unset)
4539                ws_ignore_action = ignore_ws_none;
4540        else
4541                ws_ignore_action = ignore_ws_change;
4542        return 0;
4543}
4544
4545static int option_parse_whitespace(const struct option *opt,
4546                                   const char *arg, int unset)
4547{
4548        const char **whitespace_option = opt->value;
4549
4550        *whitespace_option = arg;
4551        parse_whitespace_option(arg);
4552        return 0;
4553}
4554
4555static int option_parse_directory(const struct option *opt,
4556                                  const char *arg, int unset)
4557{
4558        strbuf_reset(&root);
4559        strbuf_addstr(&root, arg);
4560        strbuf_complete(&root, '/');
4561        return 0;
4562}
4563
4564static void init_apply_state(struct apply_state *state, const char *prefix)
4565{
4566        memset(state, 0, sizeof(*state));
4567        state->prefix = prefix;
4568        state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
4569
4570        git_apply_config();
4571        if (apply_default_whitespace)
4572                parse_whitespace_option(apply_default_whitespace);
4573        if (apply_default_ignorewhitespace)
4574                parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4575}
4576
4577static void clear_apply_state(struct apply_state *state)
4578{
4579        /* empty for now */
4580}
4581
4582int cmd_apply(int argc, const char **argv, const char *prefix)
4583{
4584        int i;
4585        int errs = 0;
4586        int is_not_gitdir = !startup_info->have_repository;
4587        int force_apply = 0;
4588        int options = 0;
4589        int read_stdin = 1;
4590        struct apply_state state;
4591
4592        const char *whitespace_option = NULL;
4593
4594        struct option builtin_apply_options[] = {
4595                { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4596                        N_("don't apply changes matching the given path"),
4597                        0, option_parse_exclude },
4598                { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4599                        N_("apply changes matching the given path"),
4600                        0, option_parse_include },
4601                { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4602                        N_("remove <num> leading slashes from traditional diff paths"),
4603                        0, option_parse_p },
4604                OPT_BOOL(0, "no-add", &no_add,
4605                        N_("ignore additions made by the patch")),
4606                OPT_BOOL(0, "stat", &state.diffstat,
4607                        N_("instead of applying the patch, output diffstat for the input")),
4608                OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4609                OPT_NOOP_NOARG(0, "binary"),
4610                OPT_BOOL(0, "numstat", &numstat,
4611                        N_("show number of added and deleted lines in decimal notation")),
4612                OPT_BOOL(0, "summary", &summary,
4613                        N_("instead of applying the patch, output a summary for the input")),
4614                OPT_BOOL(0, "check", &state.check,
4615                        N_("instead of applying the patch, see if the patch is applicable")),
4616                OPT_BOOL(0, "index", &state.check_index,
4617                        N_("make sure the patch is applicable to the current index")),
4618                OPT_BOOL(0, "cached", &state.cached,
4619                        N_("apply a patch without touching the working tree")),
4620                OPT_BOOL(0, "unsafe-paths", &unsafe_paths,
4621                        N_("accept a patch that touches outside the working area")),
4622                OPT_BOOL(0, "apply", &force_apply,
4623                        N_("also apply the patch (use with --stat/--summary/--check)")),
4624                OPT_BOOL('3', "3way", &threeway,
4625                         N_( "attempt three-way merge if a patch does not apply")),
4626                OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4627                        N_("build a temporary index based on embedded index information")),
4628                /* Think twice before adding "--nul" synonym to this */
4629                OPT_SET_INT('z', NULL, &line_termination,
4630                        N_("paths are separated with NUL character"), '\0'),
4631                OPT_INTEGER('C', NULL, &p_context,
4632                                N_("ensure at least <n> lines of context match")),
4633                { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4634                        N_("detect new or modified lines that have whitespace errors"),
4635                        0, option_parse_whitespace },
4636                { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4637                        N_("ignore changes in whitespace when finding context"),
4638                        PARSE_OPT_NOARG, option_parse_space_change },
4639                { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4640                        N_("ignore changes in whitespace when finding context"),
4641                        PARSE_OPT_NOARG, option_parse_space_change },
4642                OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4643                        N_("apply the patch in reverse")),
4644                OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4645                        N_("don't expect at least one line of context")),
4646                OPT_BOOL(0, "reject", &state.apply_with_reject,
4647                        N_("leave the rejected hunks in corresponding *.rej files")),
4648                OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4649                        N_("allow overlapping hunks")),
4650                OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4651                OPT_BIT(0, "inaccurate-eof", &options,
4652                        N_("tolerate incorrectly detected missing new-line at the end of file"),
4653                        INACCURATE_EOF),
4654                OPT_BIT(0, "recount", &options,
4655                        N_("do not trust the line counts in the hunk headers"),
4656                        RECOUNT),
4657                { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4658                        N_("prepend <root> to all filenames"),
4659                        0, option_parse_directory },
4660                OPT_END()
4661        };
4662
4663        init_apply_state(&state, prefix);
4664
4665        argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4666                        apply_usage, 0);
4667
4668        if (state.apply_with_reject && threeway)
4669                die("--reject and --3way cannot be used together.");
4670        if (state.cached && threeway)
4671                die("--cached and --3way cannot be used together.");
4672        if (threeway) {
4673                if (is_not_gitdir)
4674                        die(_("--3way outside a repository"));
4675                state.check_index = 1;
4676        }
4677        if (state.apply_with_reject)
4678                apply = state.apply_verbosely = 1;
4679        if (!force_apply && (state.diffstat || numstat || summary || state.check || fake_ancestor))
4680                apply = 0;
4681        if (state.check_index && is_not_gitdir)
4682                die(_("--index outside a repository"));
4683        if (state.cached) {
4684                if (is_not_gitdir)
4685                        die(_("--cached outside a repository"));
4686                state.check_index = 1;
4687        }
4688        if (state.check_index)
4689                unsafe_paths = 0;
4690
4691        for (i = 0; i < argc; i++) {
4692                const char *arg = argv[i];
4693                int fd;
4694
4695                if (!strcmp(arg, "-")) {
4696                        errs |= apply_patch(&state, 0, "<stdin>", options);
4697                        read_stdin = 0;
4698                        continue;
4699                } else if (0 < state.prefix_length)
4700                        arg = prefix_filename(state.prefix,
4701                                              state.prefix_length,
4702                                              arg);
4703
4704                fd = open(arg, O_RDONLY);
4705                if (fd < 0)
4706                        die_errno(_("can't open patch '%s'"), arg);
4707                read_stdin = 0;
4708                set_default_whitespace_mode(whitespace_option);
4709                errs |= apply_patch(&state, fd, arg, options);
4710                close(fd);
4711        }
4712        set_default_whitespace_mode(whitespace_option);
4713        if (read_stdin)
4714                errs |= apply_patch(&state, 0, "<stdin>", options);
4715        if (whitespace_error) {
4716                if (squelch_whitespace_errors &&
4717                    squelch_whitespace_errors < whitespace_error) {
4718                        int squelched =
4719                                whitespace_error - squelch_whitespace_errors;
4720                        warning(Q_("squelched %d whitespace error",
4721                                   "squelched %d whitespace errors",
4722                                   squelched),
4723                                squelched);
4724                }
4725                if (ws_error_action == die_on_ws_error)
4726                        die(Q_("%d line adds whitespace errors.",
4727                               "%d lines add whitespace errors.",
4728                               whitespace_error),
4729                            whitespace_error);
4730                if (applied_after_fixing_ws && apply)
4731                        warning("%d line%s applied after"
4732                                " fixing whitespace errors.",
4733                                applied_after_fixing_ws,
4734                                applied_after_fixing_ws == 1 ? "" : "s");
4735                else if (whitespace_error)
4736                        warning(Q_("%d line adds whitespace errors.",
4737                                   "%d lines add whitespace errors.",
4738                                   whitespace_error),
4739                                whitespace_error);
4740        }
4741
4742        if (state.update_index) {
4743                if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4744                        die(_("Unable to write new index file"));
4745        }
4746
4747        clear_apply_state(&state);
4748
4749        return !!errs;
4750}