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