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