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