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