Coverage Report

Created: 2026-03-31 06:24

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