Coverage Report

Created: 2026-11-12 06:03

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