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