Coverage Report

Created: 2026-04-29 06:54

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