Coverage Report

Created: 2026-11-12 06:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/read-cache.c
Line
Count
Source
1
/*
2
 * GIT - The information manager from hell
3
 *
4
 * Copyright (C) Linus Torvalds, 2005
5
 */
6
7
#define USE_THE_REPOSITORY_VARIABLE
8
#define DISABLE_SIGN_COMPARE_WARNINGS
9
10
#include "git-compat-util.h"
11
#include "config.h"
12
#include "date.h"
13
#include "diff.h"
14
#include "diffcore.h"
15
#include "hex.h"
16
#include "tempfile.h"
17
#include "lockfile.h"
18
#include "cache-tree.h"
19
#include "refs.h"
20
#include "dir.h"
21
#include "object-file.h"
22
#include "odb.h"
23
#include "odb/transaction.h"
24
#include "oid-array.h"
25
#include "tree.h"
26
#include "commit.h"
27
#include "environment.h"
28
#include "gettext.h"
29
#include "mem-pool.h"
30
#include "name-hash.h"
31
#include "object-name.h"
32
#include "path.h"
33
#include "preload-index.h"
34
#include "read-cache.h"
35
#include "repository.h"
36
#include "resolve-undo.h"
37
#include "revision.h"
38
#include "strbuf.h"
39
#include "trace2.h"
40
#include "varint.h"
41
#include "split-index.h"
42
#include "symlinks.h"
43
#include "utf8.h"
44
#include "fsmonitor.h"
45
#include "thread-utils.h"
46
#include "progress.h"
47
#include "sparse-index.h"
48
#include "csum-file.h"
49
#include "promisor-remote.h"
50
#include "hook.h"
51
#include "submodule.h"
52
#include "submodule-config.h"
53
#include "advice.h"
54
55
/* Mask for the name length in ce_flags in the on-disk index */
56
57
0
#define CE_NAMEMASK  (0x0fff)
58
59
/* Index extensions.
60
 *
61
 * The first letter should be 'A'..'Z' for extensions that are not
62
 * necessary for a correct operation (i.e. optimization data).
63
 * When new extensions are added that _needs_ to be understood in
64
 * order to correctly interpret the index file, pick character that
65
 * is outside the range, to cause the reader to abort.
66
 */
67
68
0
#define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
69
0
#define CACHE_EXT_TREE 0x54524545  /* "TREE" */
70
0
#define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
71
0
#define CACHE_EXT_LINK 0x6c696e6b    /* "link" */
72
0
#define CACHE_EXT_UNTRACKED 0x554E5452    /* "UNTR" */
73
0
#define CACHE_EXT_FSMONITOR 0x46534D4E    /* "FSMN" */
74
0
#define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945  /* "EOIE" */
75
0
#define CACHE_EXT_INDEXENTRYOFFSETTABLE 0x49454F54 /* "IEOT" */
76
0
#define CACHE_EXT_SPARSE_DIRECTORIES 0x73646972 /* "sdir" */
77
78
/* changes that can be kept in $GIT_DIR/index (basically all extensions) */
79
0
#define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
80
0
     CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
81
0
     SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
82
83
84
/*
85
 * This is an estimate of the pathname length in the index.  We use
86
 * this for V4 index files to guess the un-deltafied size of the index
87
 * in memory because of pathname deltafication.  This is not required
88
 * for V2/V3 index formats because their pathnames are not compressed.
89
 * If the initial amount of memory set aside is not sufficient, the
90
 * mem pool will allocate extra memory.
91
 */
92
0
#define CACHE_ENTRY_PATH_LENGTH 80
93
94
enum index_search_mode {
95
  NO_EXPAND_SPARSE = 0,
96
  EXPAND_SPARSE = 1
97
};
98
99
static inline void verify_ce_namelen(size_t len)
100
0
{
101
0
  if (len > INT_MAX)
102
0
    die(_("index entry path is too long (%"PRIuMAX" bytes)"),
103
0
        (uintmax_t)len);
104
0
}
105
106
static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
107
0
{
108
0
  struct cache_entry *ce;
109
0
  verify_ce_namelen(len);
110
0
  ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
111
0
  ce->mem_pool_allocated = 1;
112
0
  return ce;
113
0
}
114
115
static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
116
0
{
117
0
  struct cache_entry * ce;
118
0
  verify_ce_namelen(len);
119
0
  ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
120
0
  ce->mem_pool_allocated = 1;
121
0
  return ce;
122
0
}
123
124
static struct mem_pool *find_mem_pool(struct index_state *istate)
125
0
{
126
0
  struct mem_pool **pool_ptr;
127
128
0
  if (istate->split_index && istate->split_index->base)
129
0
    pool_ptr = &istate->split_index->base->ce_mem_pool;
130
0
  else
131
0
    pool_ptr = &istate->ce_mem_pool;
132
133
0
  if (!*pool_ptr) {
134
0
    *pool_ptr = xmalloc(sizeof(**pool_ptr));
135
0
    mem_pool_init(*pool_ptr, 0);
136
0
  }
137
138
0
  return *pool_ptr;
139
0
}
140
141
/*
142
 * "refresh" does not calculate a new sha1 file or bring the
143
 * cache up-to-date for mode/content changes. But what it
144
 * _does_ do is to "re-match" the stat information of a file
145
 * with the cache, so that you can refresh the cache for a
146
 * file that hasn't been changed but where the stat entry is
147
 * out of date.
148
 *
149
 * For example, you'd want to do this after doing a "git-read-tree",
150
 * to link up the stat cache details with the proper files.
151
 */
152
static struct cache_entry *refresh_cache_ent(struct index_state *istate,
153
               struct cache_entry *ce,
154
               unsigned int options, int *err,
155
               int *changed_ret,
156
               int *t2_did_lstat,
157
               int *t2_did_scan)
158
0
{
159
0
  struct stat st;
160
0
  struct cache_entry *updated;
161
0
  int changed;
162
0
  int refresh = options & CE_MATCH_REFRESH;
163
0
  int ignore_valid = options & CE_MATCH_IGNORE_VALID;
164
0
  int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
165
0
  int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
166
0
  int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
167
168
0
  if (!refresh || ce_uptodate(ce))
169
0
    return ce;
170
171
0
  if (!ignore_fsmonitor)
172
0
    refresh_fsmonitor(istate);
173
  /*
174
   * CE_VALID or CE_SKIP_WORKTREE means the user promised us
175
   * that the change to the work tree does not matter and told
176
   * us not to worry.
177
   */
178
0
  if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
179
0
    ce_mark_uptodate(ce);
180
0
    return ce;
181
0
  }
182
0
  if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
183
0
    ce_mark_uptodate(ce);
184
0
    return ce;
185
0
  }
186
0
  if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
187
0
    ce_mark_uptodate(ce);
188
0
    return ce;
189
0
  }
190
191
0
  if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
192
0
    if (ignore_missing)
193
0
      return ce;
194
0
    if (err)
195
0
      *err = ENOENT;
196
0
    return NULL;
197
0
  }
198
199
0
  if (t2_did_lstat)
200
0
    *t2_did_lstat = 1;
201
0
  if (lstat(ce->name, &st) < 0) {
202
0
    if (ignore_missing && errno == ENOENT)
203
0
      return ce;
204
0
    if (err)
205
0
      *err = errno;
206
0
    return NULL;
207
0
  }
208
209
0
  changed = ie_match_stat(istate, ce, &st, options);
210
0
  if (changed_ret)
211
0
    *changed_ret = changed;
212
0
  if (!changed) {
213
    /*
214
     * The path is unchanged.  If we were told to ignore
215
     * valid bit, then we did the actual stat check and
216
     * found that the entry is unmodified.  If the entry
217
     * is not marked VALID, this is the place to mark it
218
     * valid again, under "assume unchanged" mode.
219
     */
220
0
    if (ignore_valid && assume_unchanged &&
221
0
        !(ce->ce_flags & CE_VALID))
222
0
      ; /* mark this one VALID again */
223
0
    else {
224
      /*
225
       * We do not mark the index itself "modified"
226
       * because CE_UPTODATE flag is in-core only;
227
       * we are not going to write this change out.
228
       */
229
0
      if (!S_ISGITLINK(ce->ce_mode)) {
230
0
        ce_mark_uptodate(ce);
231
0
        mark_fsmonitor_valid(istate, ce);
232
0
      }
233
0
      return ce;
234
0
    }
235
0
  }
236
237
0
  if (t2_did_scan)
238
0
    *t2_did_scan = 1;
239
0
  if (ie_modified(istate, ce, &st, options)) {
240
0
    if (err)
241
0
      *err = EINVAL;
242
0
    return NULL;
243
0
  }
244
245
0
  updated = make_empty_cache_entry(istate, ce_namelen(ce));
246
0
  copy_cache_entry(updated, ce);
247
0
  memcpy(updated->name, ce->name, ce->ce_namelen + 1);
248
0
  fill_stat_cache_info(istate, updated, &st);
249
  /*
250
   * If ignore_valid is not set, we should leave CE_VALID bit
251
   * alone.  Otherwise, paths marked with --no-assume-unchanged
252
   * (i.e. things to be edited) will reacquire CE_VALID bit
253
   * automatically, which is not really what we want.
254
   */
255
0
  if (!ignore_valid && assume_unchanged &&
256
0
      !(ce->ce_flags & CE_VALID))
257
0
    updated->ce_flags &= ~CE_VALID;
258
259
  /* istate->cache_changed is updated in the caller */
260
0
  return updated;
261
0
}
262
263
static struct cache_entry *refresh_cache_entry(struct index_state *istate,
264
                 struct cache_entry *ce,
265
                 unsigned int options)
266
0
{
267
0
  return refresh_cache_ent(istate, ce, options, NULL, NULL, NULL, NULL);
268
0
}
269
270
static const char *alternate_index_output;
271
272
static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
273
0
{
274
0
  if (S_ISSPARSEDIR(ce->ce_mode))
275
0
    istate->sparse_index = INDEX_COLLAPSED;
276
277
0
  istate->cache[nr] = ce;
278
0
  add_name_hash(istate, ce);
279
0
}
280
281
static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
282
0
{
283
0
  struct cache_entry *old = istate->cache[nr];
284
285
0
  replace_index_entry_in_base(istate, old, ce);
286
0
  remove_name_hash(istate, old);
287
0
  discard_cache_entry(old);
288
0
  ce->ce_flags &= ~CE_HASHED;
289
0
  set_index_entry(istate, nr, ce);
290
0
  ce->ce_flags |= CE_UPDATE_IN_BASE;
291
0
  mark_fsmonitor_invalid(istate, ce);
292
0
  istate->cache_changed |= CE_ENTRY_CHANGED;
293
0
}
294
295
void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
296
0
{
297
0
  struct cache_entry *old_entry = istate->cache[nr], *new_entry, *refreshed;
298
0
  int namelen = strlen(new_name);
299
300
0
  new_entry = make_empty_cache_entry(istate, namelen);
301
0
  copy_cache_entry(new_entry, old_entry);
302
0
  new_entry->ce_flags &= ~CE_HASHED;
303
0
  new_entry->ce_namelen = namelen;
304
0
  new_entry->index = 0;
305
0
  memcpy(new_entry->name, new_name, namelen + 1);
306
307
0
  cache_tree_invalidate_path(istate, old_entry->name);
308
0
  untracked_cache_remove_from_index(istate, old_entry->name);
309
0
  remove_index_entry_at(istate, nr);
310
311
  /*
312
   * Refresh the new index entry. Using 'refresh_cache_entry' ensures
313
   * we only update stat info if the entry is otherwise up-to-date (i.e.,
314
   * the contents/mode haven't changed). This ensures that we reflect the
315
   * 'ctime' of the rename in the index without (incorrectly) updating
316
   * the cached stat info to reflect unstaged changes on disk.
317
   */
318
0
  refreshed = refresh_cache_entry(istate, new_entry, CE_MATCH_REFRESH);
319
0
  if (refreshed && refreshed != new_entry) {
320
0
    add_index_entry(istate, refreshed, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
321
0
    discard_cache_entry(new_entry);
322
0
  } else
323
0
    add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
324
0
}
325
326
/*
327
 * This only updates the "non-critical" parts of the directory
328
 * cache, ie the parts that aren't tracked by GIT, and only used
329
 * to validate the cache.
330
 */
331
void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st)
332
0
{
333
0
  fill_stat_data(&ce->ce_stat_data, st);
334
335
0
  if (assume_unchanged)
336
0
    ce->ce_flags |= CE_VALID;
337
338
0
  if (S_ISREG(st->st_mode)) {
339
0
    ce_mark_uptodate(ce);
340
0
    mark_fsmonitor_valid(istate, ce);
341
0
  }
342
0
}
343
344
static unsigned int st_mode_from_ce(const struct cache_entry *ce)
345
0
{
346
0
  switch (ce->ce_mode & S_IFMT) {
347
0
  case S_IFLNK:
348
0
    return repo_has_symlinks(the_repository) ? S_IFLNK : (S_IFREG | 0644);
349
0
  case S_IFREG:
350
0
    return (ce->ce_mode & (repo_trust_executable_bit(the_repository) ? 0755 : 0644)) | S_IFREG;
351
0
  case S_IFGITLINK:
352
0
    return S_IFDIR | 0755;
353
0
  case S_IFDIR:
354
0
    return ce->ce_mode;
355
0
  default:
356
0
    BUG("unsupported ce_mode: %o", ce->ce_mode);
357
0
  }
358
0
}
359
360
int fake_lstat(const struct cache_entry *ce, struct stat *st)
361
0
{
362
0
  fake_lstat_data(&ce->ce_stat_data, st);
363
0
  st->st_mode = st_mode_from_ce(ce);
364
365
  /* always succeed as lstat() replacement */
366
0
  return 0;
367
0
}
368
369
static int ce_compare_data(struct index_state *istate,
370
         const struct cache_entry *ce,
371
         struct stat *st)
372
0
{
373
0
  int match = -1;
374
0
  int fd = git_open_cloexec(ce->name, O_RDONLY);
375
376
0
  if (fd >= 0) {
377
0
    struct object_id oid;
378
0
    if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
379
0
      match = !oideq(&oid, &ce->oid);
380
    /* index_fd() closed the file descriptor already */
381
0
  }
382
0
  return match;
383
0
}
384
385
static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
386
0
{
387
0
  int match = -1;
388
0
  void *buffer;
389
0
  size_t size;
390
0
  enum object_type type;
391
0
  struct strbuf sb = STRBUF_INIT;
392
393
0
  if (strbuf_readlink(&sb, ce->name, expected_size))
394
0
    return -1;
395
396
0
  buffer = odb_read_object(the_repository->objects, &ce->oid, &type, &size);
397
0
  if (buffer) {
398
0
    if (size == sb.len)
399
0
      match = memcmp(buffer, sb.buf, size);
400
0
    free(buffer);
401
0
  }
402
0
  strbuf_release(&sb);
403
0
  return match;
404
0
}
405
406
static int ce_compare_gitlink(const struct cache_entry *ce)
407
0
{
408
0
  struct object_id oid;
409
410
  /*
411
   * We don't actually require that the .git directory
412
   * under GITLINK directory be a valid git directory. It
413
   * might even be missing (in case nobody populated that
414
   * sub-project).
415
   *
416
   * If so, we consider it always to match.
417
   */
418
0
  if (repo_resolve_gitlink_ref(the_repository, ce->name,
419
0
             "HEAD", &oid) < 0)
420
0
    return 0;
421
0
  return !oideq(&oid, &ce->oid);
422
0
}
423
424
static int ce_modified_check_fs(struct index_state *istate,
425
        const struct cache_entry *ce,
426
        struct stat *st)
427
0
{
428
0
  switch (st->st_mode & S_IFMT) {
429
0
  case S_IFREG:
430
0
    if (ce_compare_data(istate, ce, st))
431
0
      return DATA_CHANGED;
432
0
    break;
433
0
  case S_IFLNK:
434
0
    if (ce_compare_link(ce, xsize_t(st->st_size)))
435
0
      return DATA_CHANGED;
436
0
    break;
437
0
  case S_IFDIR:
438
0
    if (S_ISGITLINK(ce->ce_mode))
439
0
      return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
440
    /* else fallthrough */
441
0
  default:
442
0
    return TYPE_CHANGED;
443
0
  }
444
0
  return 0;
445
0
}
446
447
static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
448
0
{
449
0
  unsigned int changed = 0;
450
451
0
  if (ce->ce_flags & CE_REMOVE)
452
0
    return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
453
454
0
  switch (ce->ce_mode & S_IFMT) {
455
0
  case S_IFREG:
456
0
    changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
457
    /* We consider only the owner x bit to be relevant for
458
     * "mode changes"
459
     */
460
0
    if (repo_trust_executable_bit(the_repository) &&
461
0
        (0100 & (ce->ce_mode ^ st->st_mode)))
462
0
      changed |= MODE_CHANGED;
463
0
    break;
464
0
  case S_IFLNK:
465
0
    if (!S_ISLNK(st->st_mode) &&
466
0
        (repo_has_symlinks(the_repository) || !S_ISREG(st->st_mode)))
467
0
      changed |= TYPE_CHANGED;
468
0
    break;
469
0
  case S_IFGITLINK:
470
    /* We ignore most of the st_xxx fields for gitlinks */
471
0
    if (!S_ISDIR(st->st_mode))
472
0
      changed |= TYPE_CHANGED;
473
0
    else if (ce_compare_gitlink(ce))
474
0
      changed |= DATA_CHANGED;
475
0
    return changed;
476
0
  default:
477
0
    BUG("unsupported ce_mode: %o", ce->ce_mode);
478
0
  }
479
480
0
  changed |= match_stat_data(&ce->ce_stat_data, st);
481
482
  /* Racily smudged entry? */
483
0
  if (!ce->ce_stat_data.sd_size) {
484
0
    if (!is_empty_blob_oid(&ce->oid, the_repository->hash_algo))
485
0
      changed |= DATA_CHANGED;
486
0
  }
487
488
0
  return changed;
489
0
}
490
491
static int is_racy_stat(const struct index_state *istate,
492
      const struct stat_data *sd)
493
0
{
494
0
  return (istate->timestamp.sec &&
495
    /* nanosecond timestamped files can also be racy! */
496
0
    (repo_config_values(istate->repo)->use_nanosec
497
0
     ? (istate->timestamp.sec < sd->sd_mtime.sec ||
498
0
        (istate->timestamp.sec == sd->sd_mtime.sec &&
499
0
         istate->timestamp.nsec <= sd->sd_mtime.nsec))
500
0
     : istate->timestamp.sec <= sd->sd_mtime.sec));
501
0
}
502
503
int is_racy_timestamp(const struct index_state *istate,
504
           const struct cache_entry *ce)
505
0
{
506
0
  return (!S_ISGITLINK(ce->ce_mode) &&
507
0
    is_racy_stat(istate, &ce->ce_stat_data));
508
0
}
509
510
int match_stat_data_racy(const struct index_state *istate,
511
       const struct stat_data *sd, struct stat *st)
512
0
{
513
0
  if (is_racy_stat(istate, sd))
514
0
    return MTIME_CHANGED;
515
0
  return match_stat_data(sd, st);
516
0
}
517
518
int ie_match_stat(struct index_state *istate,
519
      const struct cache_entry *ce, struct stat *st,
520
      unsigned int options)
521
0
{
522
0
  unsigned int changed;
523
0
  int ignore_valid = options & CE_MATCH_IGNORE_VALID;
524
0
  int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
525
0
  int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
526
0
  int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
527
528
0
  if (!ignore_fsmonitor)
529
0
    refresh_fsmonitor(istate);
530
  /*
531
   * If it's marked as always valid in the index, it's
532
   * valid whatever the checked-out copy says.
533
   *
534
   * skip-worktree has the same effect with higher precedence
535
   */
536
0
  if (!ignore_skip_worktree && ce_skip_worktree(ce))
537
0
    return 0;
538
0
  if (!ignore_valid && (ce->ce_flags & CE_VALID))
539
0
    return 0;
540
0
  if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
541
0
    return 0;
542
543
  /*
544
   * Intent-to-add entries have not been added, so the index entry
545
   * by definition never matches what is in the work tree until it
546
   * actually gets added.
547
   */
548
0
  if (ce_intent_to_add(ce))
549
0
    return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
550
551
0
  changed = ce_match_stat_basic(ce, st);
552
553
  /*
554
   * Within 1 second of this sequence:
555
   *  echo xyzzy >file && git-update-index --add file
556
   * running this command:
557
   *  echo frotz >file
558
   * would give a falsely clean cache entry.  The mtime and
559
   * length match the cache, and other stat fields do not change.
560
   *
561
   * We could detect this at update-index time (the cache entry
562
   * being registered/updated records the same time as "now")
563
   * and delay the return from git-update-index, but that would
564
   * effectively mean we can make at most one commit per second,
565
   * which is not acceptable.  Instead, we check cache entries
566
   * whose mtime are the same as the index file timestamp more
567
   * carefully than others.
568
   */
569
0
  if (!changed && is_racy_timestamp(istate, ce)) {
570
0
    if (assume_racy_is_modified)
571
0
      changed |= DATA_CHANGED;
572
0
    else
573
0
      changed |= ce_modified_check_fs(istate, ce, st);
574
0
  }
575
576
0
  return changed;
577
0
}
578
579
int ie_modified(struct index_state *istate,
580
    const struct cache_entry *ce,
581
    struct stat *st, unsigned int options)
582
0
{
583
0
  int changed, changed_fs;
584
585
0
  changed = ie_match_stat(istate, ce, st, options);
586
0
  if (!changed)
587
0
    return 0;
588
  /*
589
   * If the mode or type has changed, there's no point in trying
590
   * to refresh the entry - it's not going to match
591
   */
592
0
  if (changed & (MODE_CHANGED | TYPE_CHANGED))
593
0
    return changed;
594
595
  /*
596
   * Immediately after read-tree or update-index --cacheinfo,
597
   * the length field is zero, as we have never even read the
598
   * lstat(2) information once, and we cannot trust DATA_CHANGED
599
   * returned by ie_match_stat() which in turn was returned by
600
   * ce_match_stat_basic() to signal that the filesize of the
601
   * blob changed.  We have to actually go to the filesystem to
602
   * see if the contents match, and if so, should answer "unchanged".
603
   *
604
   * The logic does not apply to gitlinks, as ce_match_stat_basic()
605
   * already has checked the actual HEAD from the filesystem in the
606
   * subproject.  If ie_match_stat() already said it is different,
607
   * then we know it is.
608
   */
609
0
  if ((changed & DATA_CHANGED) &&
610
#ifdef GIT_WINDOWS_NATIVE
611
      /*
612
       * Work around Git for Windows v2.27.0 fixing a bug where symlinks'
613
       * target path lengths were not read at all, and instead recorded
614
       * as 4096: now, all symlinks would appear as modified.
615
       *
616
       * So let's just special-case symlinks with a target path length
617
       * (i.e. `sd_size`) of 4096 and force them to be re-checked.
618
       */
619
      (!S_ISLNK(st->st_mode) || ce->ce_stat_data.sd_size != MAX_PATH) &&
620
#endif
621
0
      (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
622
0
    return changed;
623
624
0
  changed_fs = ce_modified_check_fs(istate, ce, st);
625
0
  if (changed_fs)
626
0
    return changed | changed_fs;
627
0
  return 0;
628
0
}
629
630
static int cache_name_stage_compare(const char *name1, int len1, int stage1,
631
            const char *name2, int len2, int stage2)
632
0
{
633
0
  int cmp;
634
635
0
  cmp = name_compare(name1, len1, name2, len2);
636
0
  if (cmp)
637
0
    return cmp;
638
639
0
  if (stage1 < stage2)
640
0
    return -1;
641
0
  if (stage1 > stage2)
642
0
    return 1;
643
0
  return 0;
644
0
}
645
646
int cmp_cache_name_compare(const void *a_, const void *b_)
647
0
{
648
0
  const struct cache_entry *ce1, *ce2;
649
650
0
  ce1 = *((const struct cache_entry **)a_);
651
0
  ce2 = *((const struct cache_entry **)b_);
652
0
  return cache_name_stage_compare(ce1->name, ce1->ce_namelen, ce_stage(ce1),
653
0
          ce2->name, ce2->ce_namelen, ce_stage(ce2));
654
0
}
655
656
static int index_name_stage_pos(struct index_state *istate,
657
        const char *name, int namelen,
658
        int stage,
659
        enum index_search_mode search_mode)
660
0
{
661
0
  int first, last;
662
663
0
  first = 0;
664
0
  last = istate->cache_nr;
665
0
  while (last > first) {
666
0
    int next = first + ((last - first) >> 1);
667
0
    struct cache_entry *ce = istate->cache[next];
668
0
    int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
669
0
    if (!cmp)
670
0
      return next;
671
0
    if (cmp < 0) {
672
0
      last = next;
673
0
      continue;
674
0
    }
675
0
    first = next+1;
676
0
  }
677
678
0
  if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
679
0
      first > 0) {
680
    /* Note: first <= istate->cache_nr */
681
0
    struct cache_entry *ce = istate->cache[first - 1];
682
683
    /*
684
     * If we are in a sparse-index _and_ the entry before the
685
     * insertion position is a sparse-directory entry that is
686
     * an ancestor of 'name', then we need to expand the index
687
     * and search again. This will only trigger once, because
688
     * thereafter the index is fully expanded.
689
     */
690
0
    if (S_ISSPARSEDIR(ce->ce_mode) &&
691
0
        ce_namelen(ce) < namelen &&
692
0
        !strncmp(name, ce->name, ce_namelen(ce))) {
693
0
      ensure_full_index(istate);
694
0
      return index_name_stage_pos(istate, name, namelen, stage, search_mode);
695
0
    }
696
0
  }
697
698
0
  return -first-1;
699
0
}
700
701
int index_name_pos(struct index_state *istate, const char *name, int namelen)
702
0
{
703
0
  return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
704
0
}
705
706
int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
707
0
{
708
0
  return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
709
0
}
710
711
int index_entry_exists(struct index_state *istate, const char *name, int namelen)
712
0
{
713
0
  return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
714
0
}
715
716
int remove_index_entry_at(struct index_state *istate, int pos)
717
0
{
718
0
  struct cache_entry *ce = istate->cache[pos];
719
720
0
  record_resolve_undo(istate, ce);
721
0
  remove_name_hash(istate, ce);
722
0
  save_or_free_index_entry(istate, ce);
723
0
  istate->cache_changed |= CE_ENTRY_REMOVED;
724
0
  istate->cache_nr--;
725
0
  if (pos >= istate->cache_nr)
726
0
    return 0;
727
0
  MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
728
0
       istate->cache_nr - pos);
729
0
  return 1;
730
0
}
731
732
/*
733
 * Remove all cache entries marked for removal, that is where
734
 * CE_REMOVE is set in ce_flags.  This is much more effective than
735
 * calling remove_index_entry_at() for each entry to be removed.
736
 */
737
void remove_marked_cache_entries(struct index_state *istate, int invalidate)
738
0
{
739
0
  struct cache_entry **ce_array = istate->cache;
740
0
  unsigned int i, j;
741
742
0
  for (i = j = 0; i < istate->cache_nr; i++) {
743
0
    if (ce_array[i]->ce_flags & CE_REMOVE) {
744
0
      if (invalidate) {
745
0
        cache_tree_invalidate_path(istate,
746
0
                 ce_array[i]->name);
747
0
        untracked_cache_remove_from_index(istate,
748
0
                  ce_array[i]->name);
749
0
      }
750
0
      remove_name_hash(istate, ce_array[i]);
751
0
      save_or_free_index_entry(istate, ce_array[i]);
752
0
    }
753
0
    else
754
0
      ce_array[j++] = ce_array[i];
755
0
  }
756
0
  if (j == istate->cache_nr)
757
0
    return;
758
0
  istate->cache_changed |= CE_ENTRY_REMOVED;
759
0
  istate->cache_nr = j;
760
0
}
761
762
int remove_file_from_index(struct index_state *istate, const char *path)
763
0
{
764
0
  int pos = index_name_pos(istate, path, strlen(path));
765
0
  if (pos < 0)
766
0
    pos = -pos-1;
767
0
  cache_tree_invalidate_path(istate, path);
768
0
  untracked_cache_remove_from_index(istate, path);
769
0
  while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
770
0
    remove_index_entry_at(istate, pos);
771
0
  return 0;
772
0
}
773
774
int remove_file_from_index_with_flags(struct index_state *istate,
775
              const char *path,
776
              int flags)
777
0
{
778
0
  int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
779
0
  int pretend = flags & ADD_CACHE_PRETEND;
780
781
0
  if (verbose)
782
0
    printf(_("remove '%s'\n"), path);
783
0
  if (pretend)
784
0
    return 0;
785
0
  return remove_file_from_index(istate, path);
786
0
}
787
788
static int compare_name(struct cache_entry *ce, const char *path, int namelen)
789
0
{
790
0
  return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
791
0
}
792
793
static int index_name_pos_also_unmerged(struct index_state *istate,
794
  const char *path, int namelen)
795
0
{
796
0
  int pos = index_name_pos(istate, path, namelen);
797
0
  struct cache_entry *ce;
798
799
0
  if (pos >= 0)
800
0
    return pos;
801
802
  /* maybe unmerged? */
803
0
  pos = -1 - pos;
804
0
  if (pos >= istate->cache_nr ||
805
0
      compare_name((ce = istate->cache[pos]), path, namelen))
806
0
    return -1;
807
808
  /* order of preference: stage 2, 1, 3 */
809
0
  if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
810
0
      ce_stage((ce = istate->cache[pos + 1])) == 2 &&
811
0
      !compare_name(ce, path, namelen))
812
0
    pos++;
813
0
  return pos;
814
0
}
815
816
static int different_name(struct cache_entry *ce, struct cache_entry *alias)
817
0
{
818
0
  int len = ce_namelen(ce);
819
0
  return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
820
0
}
821
822
/*
823
 * If we add a filename that aliases in the cache, we will use the
824
 * name that we already have - but we don't want to update the same
825
 * alias twice, because that implies that there were actually two
826
 * different files with aliasing names!
827
 *
828
 * So we use the CE_ADDED flag to verify that the alias was an old
829
 * one before we accept it as
830
 */
831
static struct cache_entry *create_alias_ce(struct index_state *istate,
832
             struct cache_entry *ce,
833
             struct cache_entry *alias)
834
0
{
835
0
  int len;
836
0
  struct cache_entry *new_entry;
837
838
0
  if (alias->ce_flags & CE_ADDED)
839
0
    die(_("will not add file alias '%s' ('%s' already exists in index)"),
840
0
        ce->name, alias->name);
841
842
  /* Ok, create the new entry using the name of the existing alias */
843
0
  len = ce_namelen(alias);
844
0
  new_entry = make_empty_cache_entry(istate, len);
845
0
  memcpy(new_entry->name, alias->name, len);
846
0
  copy_cache_entry(new_entry, ce);
847
0
  save_or_free_index_entry(istate, ce);
848
0
  return new_entry;
849
0
}
850
851
void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
852
0
{
853
0
  struct object_id oid;
854
0
  if (odb_write_object(the_repository->objects, "", 0, OBJ_BLOB, &oid))
855
0
    die(_("cannot create an empty blob in the object database"));
856
0
  oidcpy(&ce->oid, &oid);
857
0
}
858
859
int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
860
0
{
861
0
  int namelen, was_same;
862
0
  mode_t st_mode = st->st_mode;
863
0
  struct cache_entry *ce, *alias = NULL;
864
0
  unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
865
0
  int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
866
0
  int pretend = flags & ADD_CACHE_PRETEND;
867
0
  int intent_only = flags & ADD_CACHE_INTENT;
868
0
  int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
869
0
        (intent_only ? ADD_CACHE_NEW_ONLY : 0));
870
0
  unsigned hash_flags = pretend ? 0 : INDEX_WRITE_OBJECT;
871
872
0
  if (flags & ADD_CACHE_RENORMALIZE)
873
0
    hash_flags |= INDEX_RENORMALIZE;
874
875
0
  if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
876
0
    return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
877
878
0
  namelen = strlen(path);
879
0
  if (S_ISDIR(st_mode)) {
880
0
    while (namelen && path[namelen-1] == '/')
881
0
      namelen--;
882
0
  }
883
0
  ce = make_empty_cache_entry(istate, namelen);
884
0
  memcpy(ce->name, path, namelen);
885
0
  ce->ce_namelen = namelen;
886
0
  if (!intent_only)
887
0
    fill_stat_cache_info(istate, ce, st);
888
0
  else
889
0
    ce->ce_flags |= CE_INTENT_TO_ADD;
890
891
892
0
  if (repo_trust_executable_bit(istate->repo) &&
893
0
      repo_has_symlinks(istate->repo)) {
894
0
    ce->ce_mode = create_ce_mode(st_mode);
895
0
  } else {
896
    /* If there is an existing entry, pick the mode bits and type
897
     * from it, otherwise assume unexecutable regular file.
898
     */
899
0
    struct cache_entry *ent;
900
0
    int pos = index_name_pos_also_unmerged(istate, path, namelen);
901
902
0
    ent = (0 <= pos) ? istate->cache[pos] : NULL;
903
0
    ce->ce_mode = ce_mode_from_stat(istate->repo, ent, st_mode);
904
0
  }
905
906
  /* When core.ignorecase=true, determine if a directory of the same name but differing
907
   * case already exists within the Git repository.  If it does, ensure the directory
908
   * case of the file being added to the repository matches (is folded into) the existing
909
   * entry's directory case.
910
   */
911
0
  if (repo_ignore_case(the_repository)) {
912
0
    adjust_dirname_case(istate, ce->name);
913
0
  }
914
0
  if (!(flags & ADD_CACHE_RENORMALIZE)) {
915
0
    alias = index_file_exists(istate, ce->name,
916
0
            ce_namelen(ce), repo_ignore_case(the_repository));
917
0
    if (alias &&
918
0
        !ce_stage(alias) &&
919
0
        !ie_match_stat(istate, alias, st, ce_option)) {
920
      /* Nothing changed, really */
921
0
      if (!S_ISGITLINK(alias->ce_mode))
922
0
        ce_mark_uptodate(alias);
923
0
      alias->ce_flags |= CE_ADDED;
924
925
0
      discard_cache_entry(ce);
926
0
      return 0;
927
0
    }
928
0
  }
929
0
  if (!intent_only) {
930
0
    if (index_path(istate, &ce->oid, path, st, hash_flags)) {
931
0
      discard_cache_entry(ce);
932
0
      return error(_("unable to index file '%s'"), path);
933
0
    }
934
0
  } else
935
0
    set_object_name_for_intent_to_add_entry(ce);
936
937
0
  if (repo_ignore_case(the_repository) && alias && different_name(ce, alias))
938
0
    ce = create_alias_ce(istate, ce, alias);
939
0
  ce->ce_flags |= CE_ADDED;
940
941
  /* It was suspected to be racily clean, but it turns out to be Ok */
942
0
  was_same = (alias &&
943
0
        !ce_stage(alias) &&
944
0
        oideq(&alias->oid, &ce->oid) &&
945
0
        ce->ce_mode == alias->ce_mode);
946
947
0
  if (pretend)
948
0
    discard_cache_entry(ce);
949
0
  else if (add_index_entry(istate, ce, add_option)) {
950
0
    discard_cache_entry(ce);
951
0
    return error(_("unable to add '%s' to index"), path);
952
0
  }
953
0
  if (verbose && !was_same)
954
0
    printf("add '%s'\n", path);
955
0
  return 0;
956
0
}
957
958
int add_file_to_index(struct index_state *istate, const char *path, int flags)
959
0
{
960
0
  struct stat st;
961
0
  if (lstat(path, &st))
962
0
    die_errno(_("unable to stat '%s'"), path);
963
0
  return add_to_index(istate, path, &st, flags);
964
0
}
965
966
struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
967
0
{
968
0
  return mem_pool__ce_calloc(find_mem_pool(istate), len);
969
0
}
970
971
struct cache_entry *make_empty_transient_cache_entry(size_t len,
972
                 struct mem_pool *ce_mem_pool)
973
0
{
974
0
  if (ce_mem_pool)
975
0
    return mem_pool__ce_calloc(ce_mem_pool, len);
976
0
  verify_ce_namelen(len);
977
0
  return xcalloc(1, cache_entry_size(len));
978
0
}
979
980
enum verify_path_result {
981
  PATH_OK,
982
  PATH_INVALID,
983
  PATH_DIR_WITH_SEP,
984
};
985
986
static enum verify_path_result verify_path_internal(const char *, unsigned);
987
988
int verify_path(const char *path, unsigned mode)
989
0
{
990
0
  return verify_path_internal(path, mode) == PATH_OK;
991
0
}
992
993
struct cache_entry *make_cache_entry(struct index_state *istate,
994
             unsigned int mode,
995
             const struct object_id *oid,
996
             const char *path,
997
             int stage,
998
             unsigned int refresh_options)
999
0
{
1000
0
  struct cache_entry *ce, *ret;
1001
0
  size_t len;
1002
1003
0
  if (verify_path_internal(path, mode) == PATH_INVALID) {
1004
0
    error(_("invalid path '%s'"), path);
1005
0
    return NULL;
1006
0
  }
1007
1008
0
  len = strlen(path);
1009
0
  ce = make_empty_cache_entry(istate, len);
1010
1011
0
  oidcpy(&ce->oid, oid);
1012
0
  memcpy(ce->name, path, len);
1013
0
  ce->ce_flags = create_ce_flags(stage);
1014
0
  ce->ce_namelen = len;
1015
0
  ce->ce_mode = create_ce_mode(mode);
1016
1017
0
  ret = refresh_cache_entry(istate, ce, refresh_options);
1018
0
  if (ret != ce)
1019
0
    discard_cache_entry(ce);
1020
0
  return ret;
1021
0
}
1022
1023
struct cache_entry *make_transient_cache_entry(unsigned int mode,
1024
                 const struct object_id *oid,
1025
                 const char *path,
1026
                 int stage,
1027
                 struct mem_pool *ce_mem_pool)
1028
0
{
1029
0
  struct cache_entry *ce;
1030
0
  size_t len;
1031
1032
0
  if (!verify_path(path, mode)) {
1033
0
    error(_("invalid path '%s'"), path);
1034
0
    return NULL;
1035
0
  }
1036
1037
0
  len = strlen(path);
1038
0
  ce = make_empty_transient_cache_entry(len, ce_mem_pool);
1039
1040
0
  oidcpy(&ce->oid, oid);
1041
0
  memcpy(ce->name, path, len);
1042
0
  ce->ce_flags = create_ce_flags(stage);
1043
0
  ce->ce_namelen = len;
1044
0
  ce->ce_mode = create_ce_mode(mode);
1045
1046
0
  return ce;
1047
0
}
1048
1049
/*
1050
 * Chmod an index entry with either +x or -x.
1051
 *
1052
 * Returns -1 if the chmod for the particular cache entry failed (if it's
1053
 * not a regular file), -2 if an invalid flip argument is passed in, 0
1054
 * otherwise.
1055
 */
1056
int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
1057
          char flip)
1058
0
{
1059
0
  if (!S_ISREG(ce->ce_mode))
1060
0
    return -1;
1061
0
  switch (flip) {
1062
0
  case '+':
1063
0
    ce->ce_mode |= 0111;
1064
0
    break;
1065
0
  case '-':
1066
0
    ce->ce_mode &= ~0111;
1067
0
    break;
1068
0
  default:
1069
0
    return -2;
1070
0
  }
1071
0
  cache_tree_invalidate_path(istate, ce->name);
1072
0
  ce->ce_flags |= CE_UPDATE_IN_BASE;
1073
0
  mark_fsmonitor_invalid(istate, ce);
1074
0
  istate->cache_changed |= CE_ENTRY_CHANGED;
1075
1076
0
  return 0;
1077
0
}
1078
1079
int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
1080
0
{
1081
0
  int len = ce_namelen(a);
1082
0
  return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
1083
0
}
1084
1085
/*
1086
 * We fundamentally don't like some paths: we don't want
1087
 * dot or dot-dot anywhere, and for obvious reasons don't
1088
 * want to recurse into ".git" either.
1089
 *
1090
 * Also, we don't want double slashes or slashes at the
1091
 * end that can make pathnames ambiguous.
1092
 */
1093
static int verify_dotfile(const char *rest, unsigned mode)
1094
0
{
1095
  /*
1096
   * The first character was '.', but that
1097
   * has already been discarded, we now test
1098
   * the rest.
1099
   */
1100
1101
  /* "." is not allowed */
1102
0
  if (*rest == '\0' || is_dir_sep(*rest))
1103
0
    return 0;
1104
1105
0
  switch (*rest) {
1106
  /*
1107
   * ".git" followed by NUL or slash is bad. Note that we match
1108
   * case-insensitively here, even if ignore_case is not set.
1109
   * This outlaws ".GIT" everywhere out of an abundance of caution,
1110
   * since there's really no good reason to allow it.
1111
   *
1112
   * Once we've seen ".git", we can also find ".gitmodules", etc (also
1113
   * case-insensitively).
1114
   */
1115
0
  case 'g':
1116
0
  case 'G':
1117
0
    if (rest[1] != 'i' && rest[1] != 'I')
1118
0
      break;
1119
0
    if (rest[2] != 't' && rest[2] != 'T')
1120
0
      break;
1121
0
    if (rest[3] == '\0' || is_dir_sep(rest[3]))
1122
0
      return 0;
1123
0
    if (S_ISLNK(mode)) {
1124
0
      rest += 3;
1125
0
      if (skip_iprefix(rest, "modules", &rest) &&
1126
0
          (*rest == '\0' || is_dir_sep(*rest)))
1127
0
        return 0;
1128
0
    }
1129
0
    break;
1130
0
  case '.':
1131
0
    if (rest[1] == '\0' || is_dir_sep(rest[1]))
1132
0
      return 0;
1133
0
  }
1134
0
  return 1;
1135
0
}
1136
1137
static enum verify_path_result verify_path_internal(const char *path,
1138
                unsigned mode)
1139
0
{
1140
0
  char c = 0;
1141
1142
0
  if (has_dos_drive_prefix(path))
1143
0
    return PATH_INVALID;
1144
1145
0
  if (!is_valid_path(path))
1146
0
    return PATH_INVALID;
1147
1148
0
  if (strlen(path) > repo_config_values(the_repository)->max_ce_namelen)
1149
0
    return PATH_INVALID;
1150
1151
0
  goto inside;
1152
0
  for (;;) {
1153
0
    if (!c)
1154
0
      return PATH_OK;
1155
0
    if (is_dir_sep(c)) {
1156
0
inside:
1157
0
      if (repo_protect_hfs(the_repository)) {
1158
1159
0
        if (is_hfs_dotgit(path))
1160
0
          return PATH_INVALID;
1161
0
        if (S_ISLNK(mode)) {
1162
0
          if (is_hfs_dotgitmodules(path))
1163
0
            return PATH_INVALID;
1164
0
        }
1165
0
      }
1166
0
      if (repo_protect_ntfs(the_repository)) {
1167
#if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
1168
        if (c == '\\')
1169
          return PATH_INVALID;
1170
#endif
1171
0
        if (is_ntfs_dotgit(path))
1172
0
          return PATH_INVALID;
1173
0
        if (S_ISLNK(mode)) {
1174
0
          if (is_ntfs_dotgitmodules(path))
1175
0
            return PATH_INVALID;
1176
0
        }
1177
0
      }
1178
1179
0
      c = *path++;
1180
0
      if ((c == '.' && !verify_dotfile(path, mode)) ||
1181
0
          is_dir_sep(c))
1182
0
        return PATH_INVALID;
1183
      /*
1184
       * allow terminating directory separators for
1185
       * sparse directory entries.
1186
       */
1187
0
      if (c == '\0')
1188
0
        return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
1189
0
                   PATH_INVALID;
1190
0
    } else if (c == '\\' &&
1191
0
         repo_protect_ntfs(the_repository)) {
1192
0
      if (is_ntfs_dotgit(path))
1193
0
        return PATH_INVALID;
1194
0
      if (S_ISLNK(mode)) {
1195
0
        if (is_ntfs_dotgitmodules(path))
1196
0
          return PATH_INVALID;
1197
0
      }
1198
0
    }
1199
1200
0
    c = *path++;
1201
0
  }
1202
0
}
1203
1204
/*
1205
 * Do we have another file that has the beginning components being a
1206
 * proper superset of the name we're trying to add?
1207
 */
1208
static int has_file_name(struct index_state *istate,
1209
       const struct cache_entry *ce, int pos, int ok_to_replace)
1210
0
{
1211
0
  int retval = 0;
1212
0
  int len = ce_namelen(ce);
1213
0
  int stage = ce_stage(ce);
1214
0
  const char *name = ce->name;
1215
1216
0
  while (pos < istate->cache_nr) {
1217
0
    struct cache_entry *p = istate->cache[pos++];
1218
1219
0
    if (len >= ce_namelen(p))
1220
0
      break;
1221
0
    if (memcmp(name, p->name, len))
1222
0
      break;
1223
0
    if (ce_stage(p) != stage)
1224
0
      continue;
1225
0
    if (p->name[len] != '/')
1226
0
      continue;
1227
0
    if (p->ce_flags & CE_REMOVE)
1228
0
      continue;
1229
0
    retval = -1;
1230
0
    if (!ok_to_replace)
1231
0
      break;
1232
0
    remove_index_entry_at(istate, --pos);
1233
0
  }
1234
0
  return retval;
1235
0
}
1236
1237
1238
/*
1239
 * Like strcmp(), but also return the offset of the first change.
1240
 * If strings are equal, return the length.
1241
 */
1242
int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1243
0
{
1244
0
  size_t k;
1245
1246
0
  if (!first_change)
1247
0
    return strcmp(s1, s2);
1248
1249
0
  for (k = 0; s1[k] == s2[k]; k++)
1250
0
    if (s1[k] == '\0')
1251
0
      break;
1252
1253
0
  *first_change = k;
1254
0
  return (unsigned char)s1[k] - (unsigned char)s2[k];
1255
0
}
1256
1257
/*
1258
 * Do we have another file with a pathname that is a proper
1259
 * subset of the name we're trying to add?
1260
 *
1261
 * That is, is there another file in the index with a path
1262
 * that matches a sub-directory in the given entry?
1263
 */
1264
static int has_dir_name(struct index_state *istate,
1265
      const struct cache_entry *ce, int pos, int ok_to_replace)
1266
0
{
1267
0
  int retval = 0;
1268
0
  int stage = ce_stage(ce);
1269
0
  const char *name = ce->name;
1270
0
  const char *slash = name + ce_namelen(ce);
1271
0
  size_t len_eq_last;
1272
0
  int cmp_last = 0;
1273
1274
  /*
1275
   * We are frequently called during an iteration on a sorted
1276
   * list of pathnames and while building a new index.  Therefore,
1277
   * there is a high probability that this entry will eventually
1278
   * be appended to the index, rather than inserted in the middle.
1279
   * If we can confirm that, we can avoid binary searches on the
1280
   * components of the pathname.
1281
   *
1282
   * Compare the entry's full path with the last path in the index.
1283
   */
1284
0
  if (!istate->cache_nr)
1285
0
    return 0;
1286
1287
0
  cmp_last = strcmp_offset(name,
1288
0
         istate->cache[istate->cache_nr - 1]->name,
1289
0
         &len_eq_last);
1290
0
  if (cmp_last > 0 && name[len_eq_last] != '/')
1291
    /*
1292
     * The entry sorts AFTER the last one in the
1293
     * index and their paths have no common prefix,
1294
     * so there cannot be a F/D conflict.
1295
     */
1296
0
    return 0;
1297
1298
0
  for (;;) {
1299
0
    size_t len;
1300
1301
0
    for (;;) {
1302
0
      if (*--slash == '/')
1303
0
        break;
1304
0
      if (slash <= ce->name)
1305
0
        return retval;
1306
0
    }
1307
0
    len = slash - name;
1308
1309
0
    pos = index_name_stage_pos(istate, name, len, stage, EXPAND_SPARSE);
1310
0
    if (pos >= 0) {
1311
      /*
1312
       * Found one, but not so fast.  This could
1313
       * be a marker that says "I was here, but
1314
       * I am being removed".  Such an entry is
1315
       * not a part of the resulting tree, and
1316
       * it is Ok to have a directory at the same
1317
       * path.
1318
       */
1319
0
      if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1320
0
        retval = -1;
1321
0
        if (!ok_to_replace)
1322
0
          break;
1323
0
        remove_index_entry_at(istate, pos);
1324
0
        continue;
1325
0
      }
1326
0
    }
1327
0
    else
1328
0
      pos = -pos-1;
1329
1330
    /*
1331
     * Trivial optimization: if we find an entry that
1332
     * already matches the sub-directory, then we know
1333
     * we're ok, and we can exit.
1334
     */
1335
0
    while (pos < istate->cache_nr) {
1336
0
      struct cache_entry *p = istate->cache[pos];
1337
0
      if ((ce_namelen(p) <= len) ||
1338
0
          (p->name[len] != '/') ||
1339
0
          memcmp(p->name, name, len))
1340
0
        break; /* not our subdirectory */
1341
0
      if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1342
        /*
1343
         * p is at the same stage as our entry, and
1344
         * is a subdirectory of what we are looking
1345
         * at, so we cannot have conflicts at our
1346
         * level or anything shorter.
1347
         */
1348
0
        return retval;
1349
0
      pos++;
1350
0
    }
1351
0
  }
1352
0
  return retval;
1353
0
}
1354
1355
/* We may be in a situation where we already have path/file and path
1356
 * is being added, or we already have path and path/file is being
1357
 * added.  Either one would result in a nonsense tree that has path
1358
 * twice when git-write-tree tries to write it out.  Prevent it.
1359
 *
1360
 * If ok-to-replace is specified, we remove the conflicting entries
1361
 * from the cache so the caller should recompute the insert position.
1362
 * When this happens, we return non-zero.
1363
 */
1364
static int check_file_directory_conflict(struct index_state *istate,
1365
           const struct cache_entry *ce,
1366
           int pos, int ok_to_replace)
1367
0
{
1368
0
  int retval;
1369
1370
  /*
1371
   * When ce is an "I am going away" entry, we allow it to be added
1372
   */
1373
0
  if (ce->ce_flags & CE_REMOVE)
1374
0
    return 0;
1375
1376
  /*
1377
   * We check if the path is a sub-path of a subsequent pathname
1378
   * first, since removing those will not change the position
1379
   * in the array.
1380
   */
1381
0
  retval = has_file_name(istate, ce, pos, ok_to_replace);
1382
1383
  /*
1384
   * Then check if the path might have a clashing sub-directory
1385
   * before it.
1386
   */
1387
0
  return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1388
0
}
1389
1390
static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1391
0
{
1392
0
  int pos;
1393
0
  int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1394
0
  int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1395
0
  int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1396
0
  int new_only = option & ADD_CACHE_NEW_ONLY;
1397
1398
  /*
1399
   * If this entry's path sorts after the last entry in the index,
1400
   * we can avoid searching for it.
1401
   */
1402
0
  if (istate->cache_nr > 0 &&
1403
0
    strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1404
0
    pos = index_pos_to_insert_pos(istate->cache_nr);
1405
0
  else
1406
0
    pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1407
1408
  /*
1409
   * Cache tree path should be invalidated only after index_name_stage_pos,
1410
   * in case it expands a sparse index.
1411
   */
1412
0
  if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1413
0
    cache_tree_invalidate_path(istate, ce->name);
1414
1415
  /* existing match? Just replace it. */
1416
0
  if (pos >= 0) {
1417
0
    if (!new_only)
1418
0
      replace_index_entry(istate, pos, ce);
1419
0
    return 0;
1420
0
  }
1421
0
  pos = -pos-1;
1422
1423
0
  if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1424
0
    untracked_cache_add_to_index(istate, ce->name);
1425
1426
  /*
1427
   * Inserting a merged entry ("stage 0") into the index
1428
   * will always replace all non-merged entries..
1429
   */
1430
0
  if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1431
0
    while (ce_same_name(istate->cache[pos], ce)) {
1432
0
      ok_to_add = 1;
1433
0
      if (!remove_index_entry_at(istate, pos))
1434
0
        break;
1435
0
    }
1436
0
  }
1437
1438
0
  if (!ok_to_add)
1439
0
    return -1;
1440
0
  if (verify_path_internal(ce->name, ce->ce_mode) == PATH_INVALID)
1441
0
    return error(_("invalid path '%s'"), ce->name);
1442
1443
0
  if (!skip_df_check &&
1444
0
      check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1445
0
    if (!ok_to_replace)
1446
0
      return error(_("'%s' appears as both a file and as a directory"),
1447
0
             ce->name);
1448
0
    pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1449
0
    pos = -pos-1;
1450
0
  }
1451
0
  return pos + 1;
1452
0
}
1453
1454
int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1455
0
{
1456
0
  int pos;
1457
1458
0
  if (option & ADD_CACHE_JUST_APPEND)
1459
0
    pos = istate->cache_nr;
1460
0
  else {
1461
0
    int ret;
1462
0
    ret = add_index_entry_with_check(istate, ce, option);
1463
0
    if (ret <= 0)
1464
0
      return ret;
1465
0
    pos = ret - 1;
1466
0
  }
1467
1468
  /* Make sure the array is big enough .. */
1469
0
  ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1470
1471
  /* Add it in.. */
1472
0
  istate->cache_nr++;
1473
0
  if (istate->cache_nr > pos + 1)
1474
0
    MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1475
0
         istate->cache_nr - pos - 1);
1476
0
  set_index_entry(istate, pos, ce);
1477
0
  istate->cache_changed |= CE_ENTRY_ADDED;
1478
0
  return 0;
1479
0
}
1480
1481
static void show_file(const char * fmt, const char * name, int in_porcelain,
1482
          int * first, const char *header_msg)
1483
0
{
1484
0
  if (in_porcelain && *first && header_msg) {
1485
0
    printf("%s\n", header_msg);
1486
0
    *first = 0;
1487
0
  }
1488
0
  printf(fmt, name);
1489
0
}
1490
1491
int repo_refresh_and_write_index(struct repository *repo,
1492
         unsigned int refresh_flags,
1493
         unsigned int write_flags,
1494
         int gentle,
1495
         const struct pathspec *pathspec,
1496
         char *seen, const char *header_msg)
1497
0
{
1498
0
  struct lock_file lock_file = LOCK_INIT;
1499
0
  int fd, ret = 0;
1500
1501
0
  fd = repo_hold_locked_index(repo, &lock_file,
1502
0
            gentle ? 0 : LOCK_REPORT_ON_ERROR);
1503
0
  if (!gentle && fd < 0)
1504
0
    return -1;
1505
0
  if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
1506
0
    ret = 1;
1507
0
  if (0 <= fd && write_locked_index(repo->index, &lock_file, COMMIT_LOCK | write_flags))
1508
0
    ret = -1;
1509
0
  return ret;
1510
0
}
1511
1512
1513
int refresh_index(struct index_state *istate, unsigned int flags,
1514
      const struct pathspec *pathspec,
1515
      char *seen, const char *header_msg)
1516
0
{
1517
0
  int i;
1518
0
  int has_errors = 0;
1519
0
  int really = (flags & REFRESH_REALLY) != 0;
1520
0
  int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1521
0
  int quiet = (flags & REFRESH_QUIET) != 0;
1522
0
  int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1523
0
  int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1524
0
  int ignore_skip_worktree = (flags & REFRESH_IGNORE_SKIP_WORKTREE) != 0;
1525
0
  int first = 1;
1526
0
  int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1527
0
  unsigned int options = (CE_MATCH_REFRESH |
1528
0
        (really ? CE_MATCH_IGNORE_VALID : 0) |
1529
0
        (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1530
0
  const char *modified_fmt;
1531
0
  const char *deleted_fmt;
1532
0
  const char *typechange_fmt;
1533
0
  const char *added_fmt;
1534
0
  const char *unmerged_fmt;
1535
0
  struct progress *progress = NULL;
1536
0
  int t2_sum_lstat = 0;
1537
0
  int t2_sum_scan = 0;
1538
1539
0
  if (flags & REFRESH_PROGRESS && isatty(2))
1540
0
    progress = start_delayed_progress(the_repository,
1541
0
              _("Refresh index"),
1542
0
              istate->cache_nr);
1543
1544
0
  trace_performance_enter();
1545
0
  modified_fmt   = in_porcelain ? "M\t%s\n" : "%s: needs update\n";
1546
0
  deleted_fmt    = in_porcelain ? "D\t%s\n" : "%s: needs update\n";
1547
0
  typechange_fmt = in_porcelain ? "T\t%s\n" : "%s: needs update\n";
1548
0
  added_fmt      = in_porcelain ? "A\t%s\n" : "%s: needs update\n";
1549
0
  unmerged_fmt   = in_porcelain ? "U\t%s\n" : "%s: needs merge\n";
1550
  /*
1551
   * Use the multi-threaded preload_index() to refresh most of the
1552
   * cache entries quickly then in the single threaded loop below,
1553
   * we only have to do the special cases that are left.
1554
   */
1555
0
  preload_index(istate, pathspec, 0);
1556
0
  trace2_region_enter("index", "refresh", NULL);
1557
1558
0
  for (i = 0; i < istate->cache_nr; i++) {
1559
0
    struct cache_entry *ce, *new_entry;
1560
0
    int cache_errno = 0;
1561
0
    int changed = 0;
1562
0
    int filtered = 0;
1563
0
    int t2_did_lstat = 0;
1564
0
    int t2_did_scan = 0;
1565
1566
0
    ce = istate->cache[i];
1567
0
    if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1568
0
      continue;
1569
0
    if (ignore_skip_worktree && ce_skip_worktree(ce))
1570
0
      continue;
1571
1572
    /*
1573
     * If this entry is a sparse directory, then there isn't
1574
     * any stat() information to update. Ignore the entry.
1575
     */
1576
0
    if (S_ISSPARSEDIR(ce->ce_mode))
1577
0
      continue;
1578
1579
0
    if (pathspec && !ce_path_match(istate, ce, pathspec, seen))
1580
0
      filtered = 1;
1581
1582
0
    if (ce_stage(ce)) {
1583
0
      while ((i < istate->cache_nr) &&
1584
0
             ! strcmp(istate->cache[i]->name, ce->name))
1585
0
        i++;
1586
0
      i--;
1587
0
      if (allow_unmerged)
1588
0
        continue;
1589
0
      if (!filtered)
1590
0
        show_file(unmerged_fmt, ce->name, in_porcelain,
1591
0
            &first, header_msg);
1592
0
      has_errors = 1;
1593
0
      continue;
1594
0
    }
1595
1596
0
    if (filtered)
1597
0
      continue;
1598
1599
0
    new_entry = refresh_cache_ent(istate, ce, options,
1600
0
                &cache_errno, &changed,
1601
0
                &t2_did_lstat, &t2_did_scan);
1602
0
    t2_sum_lstat += t2_did_lstat;
1603
0
    t2_sum_scan += t2_did_scan;
1604
0
    if (new_entry == ce)
1605
0
      continue;
1606
0
    display_progress(progress, i);
1607
0
    if (!new_entry) {
1608
0
      const char *fmt;
1609
1610
0
      if (really && cache_errno == EINVAL) {
1611
        /* If we are doing --really-refresh that
1612
         * means the index is not valid anymore.
1613
         */
1614
0
        ce->ce_flags &= ~CE_VALID;
1615
0
        ce->ce_flags |= CE_UPDATE_IN_BASE;
1616
0
        mark_fsmonitor_invalid(istate, ce);
1617
0
        istate->cache_changed |= CE_ENTRY_CHANGED;
1618
0
      }
1619
0
      if (quiet)
1620
0
        continue;
1621
1622
0
      if (cache_errno == ENOENT)
1623
0
        fmt = deleted_fmt;
1624
0
      else if (ce_intent_to_add(ce))
1625
0
        fmt = added_fmt; /* must be before other checks */
1626
0
      else if (changed & TYPE_CHANGED)
1627
0
        fmt = typechange_fmt;
1628
0
      else
1629
0
        fmt = modified_fmt;
1630
0
      show_file(fmt,
1631
0
          ce->name, in_porcelain, &first, header_msg);
1632
0
      has_errors = 1;
1633
0
      continue;
1634
0
    }
1635
1636
0
    replace_index_entry(istate, i, new_entry);
1637
0
  }
1638
0
  trace2_data_intmax("index", NULL, "refresh/sum_lstat", t2_sum_lstat);
1639
0
  trace2_data_intmax("index", NULL, "refresh/sum_scan", t2_sum_scan);
1640
0
  trace2_region_leave("index", "refresh", NULL);
1641
0
  display_progress(progress, istate->cache_nr);
1642
0
  stop_progress(&progress);
1643
0
  trace_performance_leave("refresh index");
1644
0
  return has_errors;
1645
0
}
1646
1647
1648
/*****************************************************************
1649
 * Index File I/O
1650
 *****************************************************************/
1651
1652
0
#define INDEX_FORMAT_DEFAULT 3
1653
1654
static unsigned int get_index_format_default(struct repository *r)
1655
0
{
1656
0
  char *envversion = getenv("GIT_INDEX_VERSION");
1657
0
  char *endp;
1658
0
  unsigned int version = INDEX_FORMAT_DEFAULT;
1659
1660
0
  if (!envversion) {
1661
0
    prepare_repo_settings(r);
1662
1663
0
    if (r->settings.index_version >= 0)
1664
0
      version = r->settings.index_version;
1665
0
    if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1666
0
      warning(_("index.version set, but the value is invalid.\n"
1667
0
          "Using version %i"), INDEX_FORMAT_DEFAULT);
1668
0
      return INDEX_FORMAT_DEFAULT;
1669
0
    }
1670
0
    return version;
1671
0
  }
1672
1673
0
  version = strtoul(envversion, &endp, 10);
1674
0
  if (*endp ||
1675
0
      version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1676
0
    warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1677
0
        "Using version %i"), INDEX_FORMAT_DEFAULT);
1678
0
    version = INDEX_FORMAT_DEFAULT;
1679
0
  }
1680
0
  return version;
1681
0
}
1682
1683
/*
1684
 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1685
 * Again - this is just a (very strong in practice) heuristic that
1686
 * the inode hasn't changed.
1687
 *
1688
 * We save the fields in big-endian order to allow using the
1689
 * index file over NFS transparently.
1690
 */
1691
struct ondisk_cache_entry {
1692
  struct cache_time ctime;
1693
  struct cache_time mtime;
1694
  uint32_t dev;
1695
  uint32_t ino;
1696
  uint32_t mode;
1697
  uint32_t uid;
1698
  uint32_t gid;
1699
  uint32_t size;
1700
  /*
1701
   * unsigned char hash[hashsz];
1702
   * uint16_t flags;
1703
   * if (flags & CE_EXTENDED)
1704
   *  uint16_t flags2;
1705
   */
1706
  unsigned char data[GIT_MAX_RAWSZ + 2 * sizeof(uint16_t)];
1707
  char name[FLEX_ARRAY];
1708
};
1709
1710
/* These are only used for v3 or lower */
1711
0
#define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1712
0
#define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,data) + (len) + 8) & ~7)
1713
0
#define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1714
0
#define ondisk_data_size(flags, len) (the_hash_algo->rawsz + \
1715
0
             ((flags & CE_EXTENDED) ? 2 : 1) * sizeof(uint16_t) + len)
1716
#define ondisk_data_size_max(len) (ondisk_data_size(CE_EXTENDED, len))
1717
0
#define ondisk_ce_size(ce) (ondisk_cache_entry_size(ondisk_data_size((ce)->ce_flags, ce_namelen(ce))))
1718
1719
/* Allow fsck to force verification of the index checksum. */
1720
int verify_index_checksum;
1721
1722
/* Allow fsck to force verification of the cache entry order. */
1723
int verify_ce_order;
1724
1725
static int verify_hdr(const struct cache_header *hdr, unsigned long size)
1726
0
{
1727
0
  struct git_hash_ctx c;
1728
0
  unsigned char hash[GIT_MAX_RAWSZ];
1729
0
  int hdr_version;
1730
0
  unsigned char *start, *end;
1731
0
  struct object_id oid;
1732
1733
0
  if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1734
0
    return error(_("bad signature 0x%08x"), hdr->hdr_signature);
1735
0
  hdr_version = ntohl(hdr->hdr_version);
1736
0
  if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1737
0
    return error(_("bad index version %d"), hdr_version);
1738
1739
0
  if (!verify_index_checksum)
1740
0
    return 0;
1741
1742
0
  end = (unsigned char *)hdr + size;
1743
0
  start = end - the_hash_algo->rawsz;
1744
0
  oidread(&oid, start, the_repository->hash_algo);
1745
0
  if (oideq(&oid, null_oid(the_hash_algo)))
1746
0
    return 0;
1747
1748
0
  git_hash_init(&c, the_hash_algo);
1749
0
  git_hash_update(&c, hdr, size - the_hash_algo->rawsz);
1750
0
  git_hash_final(hash, &c);
1751
0
  if (!hasheq(hash, start, the_repository->hash_algo))
1752
0
    return error(_("bad index file sha1 signature"));
1753
0
  return 0;
1754
0
}
1755
1756
static int read_index_extension(struct index_state *istate,
1757
        const char *ext, const char *data, unsigned long sz)
1758
0
{
1759
0
  switch (CACHE_EXT(ext)) {
1760
0
  case CACHE_EXT_TREE:
1761
0
    istate->cache_tree = cache_tree_read(istate->repo, data, sz);
1762
0
    break;
1763
0
  case CACHE_EXT_RESOLVE_UNDO:
1764
0
    istate->resolve_undo = resolve_undo_read(data, sz, the_hash_algo);
1765
0
    break;
1766
0
  case CACHE_EXT_LINK:
1767
0
    if (read_link_extension(istate, data, sz))
1768
0
      return -1;
1769
0
    break;
1770
0
  case CACHE_EXT_UNTRACKED:
1771
0
    istate->untracked = read_untracked_extension(data, sz);
1772
0
    break;
1773
0
  case CACHE_EXT_FSMONITOR:
1774
0
    read_fsmonitor_extension(istate, data, sz);
1775
0
    break;
1776
0
  case CACHE_EXT_ENDOFINDEXENTRIES:
1777
0
  case CACHE_EXT_INDEXENTRYOFFSETTABLE:
1778
    /* already handled in do_read_index() */
1779
0
    break;
1780
0
  case CACHE_EXT_SPARSE_DIRECTORIES:
1781
    /* no content, only an indicator */
1782
0
    istate->sparse_index = INDEX_COLLAPSED;
1783
0
    break;
1784
0
  default:
1785
0
    if (*ext < 'A' || 'Z' < *ext)
1786
0
      return error(_("index uses %.4s extension, which we do not understand"),
1787
0
             ext);
1788
0
    fprintf_ln(stderr, _("ignoring %.4s extension"), ext);
1789
0
    break;
1790
0
  }
1791
0
  return 0;
1792
0
}
1793
1794
/*
1795
 * Parses the contents of the cache entry contained within the 'ondisk' buffer
1796
 * into a new incore 'cache_entry'.
1797
 *
1798
 * Note that 'char *ondisk' may not be aligned to a 4-byte address interval in
1799
 * index v4, so we cannot cast it to 'struct ondisk_cache_entry *' and access
1800
 * its members. Instead, we use the byte offsets of members within the struct to
1801
 * identify where 'get_be16()', 'get_be32()', and 'oidread()' (which can all
1802
 * read from an unaligned memory buffer) should read from the 'ondisk' buffer
1803
 * into the corresponding incore 'cache_entry' members.
1804
 */
1805
static struct cache_entry *create_from_disk(struct mem_pool *ce_mem_pool,
1806
              unsigned int version,
1807
              const char *ondisk,
1808
              unsigned long *ent_size,
1809
              const struct cache_entry *previous_ce)
1810
0
{
1811
0
  struct cache_entry *ce;
1812
0
  size_t len;
1813
0
  const char *name;
1814
0
  const unsigned hashsz = the_hash_algo->rawsz;
1815
0
  const char *flagsp = ondisk + offsetof(struct ondisk_cache_entry, data) + hashsz;
1816
0
  unsigned int flags;
1817
0
  size_t copy_len = 0;
1818
  /*
1819
   * Adjacent cache entries tend to share the leading paths, so it makes
1820
   * sense to only store the differences in later entries.  In the v4
1821
   * on-disk format of the index, each on-disk cache entry stores the
1822
   * number of bytes to be stripped from the end of the previous name,
1823
   * and the bytes to append to the result, to come up with its name.
1824
   */
1825
0
  int expand_name_field = version == 4;
1826
1827
  /* On-disk flags are just 16 bits */
1828
0
  flags = get_be16(flagsp);
1829
0
  len = flags & CE_NAMEMASK;
1830
1831
0
  if (flags & CE_EXTENDED) {
1832
0
    int extended_flags;
1833
0
    extended_flags = get_be16(flagsp + sizeof(uint16_t)) << 16;
1834
    /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1835
0
    if (extended_flags & ~CE_EXTENDED_FLAGS)
1836
0
      die(_("unknown index entry format 0x%08x"), extended_flags);
1837
0
    flags |= extended_flags;
1838
0
    name = (const char *)(flagsp + 2 * sizeof(uint16_t));
1839
0
  }
1840
0
  else
1841
0
    name = (const char *)(flagsp + sizeof(uint16_t));
1842
1843
0
  if (expand_name_field) {
1844
0
    const unsigned char *cp = (const unsigned char *)name;
1845
0
    uint64_t strip_len, previous_len;
1846
1847
    /* If we're at the beginning of a block, ignore the previous name */
1848
0
    strip_len = decode_varint(&cp);
1849
0
    if (previous_ce) {
1850
0
      previous_len = previous_ce->ce_namelen;
1851
0
      if (previous_len < strip_len)
1852
0
        die(_("malformed name field in the index, near path '%s'"),
1853
0
          previous_ce->name);
1854
0
      copy_len = previous_len - strip_len;
1855
0
    }
1856
0
    name = (const char *)cp;
1857
0
  }
1858
1859
0
  if (len == CE_NAMEMASK) {
1860
0
    len = strlen(name);
1861
0
    if (expand_name_field)
1862
0
      len += copy_len;
1863
0
  }
1864
1865
0
  ce = mem_pool__ce_alloc(ce_mem_pool, len);
1866
1867
  /*
1868
   * NEEDSWORK: using 'offsetof()' is cumbersome and should be replaced
1869
   * with something more akin to 'load_bitmap_entries_v1()'s use of
1870
   * 'read_be16'/'read_be32'. For consistency with the corresponding
1871
   * ondisk entry write function ('copy_cache_entry_to_ondisk()'), this
1872
   * should be done at the same time as removing references to
1873
   * 'ondisk_cache_entry' there.
1874
   */
1875
0
  ce->ce_stat_data.sd_ctime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1876
0
              + offsetof(struct cache_time, sec));
1877
0
  ce->ce_stat_data.sd_mtime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1878
0
              + offsetof(struct cache_time, sec));
1879
0
  ce->ce_stat_data.sd_ctime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1880
0
               + offsetof(struct cache_time, nsec));
1881
0
  ce->ce_stat_data.sd_mtime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1882
0
               + offsetof(struct cache_time, nsec));
1883
0
  ce->ce_stat_data.sd_dev   = get_be32(ondisk + offsetof(struct ondisk_cache_entry, dev));
1884
0
  ce->ce_stat_data.sd_ino   = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ino));
1885
0
  ce->ce_mode  = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mode));
1886
0
  ce->ce_stat_data.sd_uid   = get_be32(ondisk + offsetof(struct ondisk_cache_entry, uid));
1887
0
  ce->ce_stat_data.sd_gid   = get_be32(ondisk + offsetof(struct ondisk_cache_entry, gid));
1888
0
  ce->ce_stat_data.sd_size  = get_be32(ondisk + offsetof(struct ondisk_cache_entry, size));
1889
0
  ce->ce_flags = flags & ~CE_NAMEMASK;
1890
0
  ce->ce_namelen = len;
1891
0
  ce->index = 0;
1892
0
  oidread(&ce->oid, (const unsigned char *)ondisk + offsetof(struct ondisk_cache_entry, data),
1893
0
    the_repository->hash_algo);
1894
1895
0
  if (expand_name_field) {
1896
0
    if (copy_len)
1897
0
      memcpy(ce->name, previous_ce->name, copy_len);
1898
0
    memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1899
0
    *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
1900
0
  } else {
1901
0
    memcpy(ce->name, name, len + 1);
1902
0
    *ent_size = ondisk_ce_size(ce);
1903
0
  }
1904
0
  return ce;
1905
0
}
1906
1907
static void check_ce_order(struct index_state *istate)
1908
0
{
1909
0
  unsigned int i;
1910
1911
0
  if (!verify_ce_order)
1912
0
    return;
1913
1914
0
  for (i = 1; i < istate->cache_nr; i++) {
1915
0
    struct cache_entry *ce = istate->cache[i - 1];
1916
0
    struct cache_entry *next_ce = istate->cache[i];
1917
0
    int name_compare = strcmp(ce->name, next_ce->name);
1918
1919
0
    if (0 < name_compare)
1920
0
      die(_("unordered stage entries in index"));
1921
0
    if (!name_compare) {
1922
0
      if (!ce_stage(ce))
1923
0
        die(_("multiple stage entries for merged file '%s'"),
1924
0
            ce->name);
1925
0
      if (ce_stage(ce) > ce_stage(next_ce))
1926
0
        die(_("unordered stage entries for '%s'"),
1927
0
            ce->name);
1928
0
    }
1929
0
  }
1930
0
}
1931
1932
static void tweak_untracked_cache(struct index_state *istate)
1933
0
{
1934
0
  struct repository *r = the_repository;
1935
1936
0
  prepare_repo_settings(r);
1937
1938
0
  switch (r->settings.core_untracked_cache) {
1939
0
  case UNTRACKED_CACHE_REMOVE:
1940
0
    remove_untracked_cache(istate);
1941
0
    break;
1942
0
  case UNTRACKED_CACHE_WRITE:
1943
0
    add_untracked_cache(istate);
1944
0
    break;
1945
0
  case UNTRACKED_CACHE_KEEP:
1946
    /*
1947
     * Either an explicit "core.untrackedCache=keep", the
1948
     * default if "core.untrackedCache" isn't configured,
1949
     * or a fallback on an unknown "core.untrackedCache"
1950
     * value.
1951
     */
1952
0
    break;
1953
0
  }
1954
0
}
1955
1956
static void tweak_split_index(struct index_state *istate)
1957
0
{
1958
0
  switch (repo_config_get_split_index(the_repository)) {
1959
0
  case -1: /* unset: do nothing */
1960
0
    break;
1961
0
  case 0: /* false */
1962
0
    remove_split_index(istate);
1963
0
    break;
1964
0
  case 1: /* true */
1965
0
    add_split_index(istate);
1966
0
    break;
1967
0
  default: /* unknown value: do nothing */
1968
0
    break;
1969
0
  }
1970
0
}
1971
1972
static void post_read_index_from(struct index_state *istate)
1973
0
{
1974
0
  check_ce_order(istate);
1975
0
  tweak_untracked_cache(istate);
1976
0
  tweak_split_index(istate);
1977
0
  tweak_fsmonitor(istate);
1978
0
}
1979
1980
static size_t estimate_cache_size_from_compressed(unsigned int entries)
1981
0
{
1982
0
  return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
1983
0
}
1984
1985
static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1986
0
{
1987
0
  long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1988
1989
  /*
1990
   * Account for potential alignment differences.
1991
   */
1992
0
  per_entry += align_padding_size(per_entry, 0);
1993
0
  return ondisk_size + entries * per_entry;
1994
0
}
1995
1996
struct index_entry_offset
1997
{
1998
  /* starting byte offset into index file, count of index entries in this block */
1999
  int offset, nr;
2000
};
2001
2002
struct index_entry_offset_table
2003
{
2004
  int nr;
2005
  struct index_entry_offset entries[FLEX_ARRAY];
2006
};
2007
2008
static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset);
2009
static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot);
2010
2011
static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
2012
static void write_eoie_extension(struct strbuf *sb, struct git_hash_ctx *eoie_context, size_t offset);
2013
2014
struct load_index_extensions
2015
{
2016
  pthread_t pthread;
2017
  struct index_state *istate;
2018
  const char *mmap;
2019
  size_t mmap_size;
2020
  unsigned long src_offset;
2021
};
2022
2023
static void *load_index_extensions(void *_data)
2024
0
{
2025
0
  struct load_index_extensions *p = _data;
2026
0
  unsigned long src_offset = p->src_offset;
2027
2028
0
  while (src_offset <= p->mmap_size - the_hash_algo->rawsz - 8) {
2029
    /* After an array of active_nr index entries,
2030
     * there can be arbitrary number of extended
2031
     * sections, each of which is prefixed with
2032
     * extension name (4-byte) and section length
2033
     * in 4-byte network byte order.
2034
     */
2035
0
    uint32_t extsize = get_be32(p->mmap + src_offset + 4);
2036
0
    if (read_index_extension(p->istate,
2037
0
           p->mmap + src_offset,
2038
0
           p->mmap + src_offset + 8,
2039
0
           extsize) < 0) {
2040
0
      munmap((void *)p->mmap, p->mmap_size);
2041
0
      die(_("index file corrupt"));
2042
0
    }
2043
0
    src_offset += 8;
2044
0
    src_offset += extsize;
2045
0
  }
2046
2047
0
  return NULL;
2048
0
}
2049
2050
/*
2051
 * A helper function that will load the specified range of cache entries
2052
 * from the memory mapped file and add them to the given index.
2053
 */
2054
static unsigned long load_cache_entry_block(struct index_state *istate,
2055
      struct mem_pool *ce_mem_pool, int offset, int nr, const char *mmap,
2056
      unsigned long start_offset, const struct cache_entry *previous_ce)
2057
0
{
2058
0
  int i;
2059
0
  unsigned long src_offset = start_offset;
2060
2061
0
  for (i = offset; i < offset + nr; i++) {
2062
0
    struct cache_entry *ce;
2063
0
    unsigned long consumed;
2064
2065
0
    ce = create_from_disk(ce_mem_pool, istate->version,
2066
0
              mmap + src_offset,
2067
0
              &consumed, previous_ce);
2068
0
    set_index_entry(istate, i, ce);
2069
2070
0
    src_offset += consumed;
2071
0
    previous_ce = ce;
2072
0
  }
2073
0
  return src_offset - start_offset;
2074
0
}
2075
2076
static unsigned long load_all_cache_entries(struct index_state *istate,
2077
      const char *mmap, size_t mmap_size, unsigned long src_offset)
2078
0
{
2079
0
  unsigned long consumed;
2080
2081
0
  istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2082
0
  if (istate->version == 4) {
2083
0
    mem_pool_init(istate->ce_mem_pool,
2084
0
        estimate_cache_size_from_compressed(istate->cache_nr));
2085
0
  } else {
2086
0
    mem_pool_init(istate->ce_mem_pool,
2087
0
        estimate_cache_size(mmap_size, istate->cache_nr));
2088
0
  }
2089
2090
0
  consumed = load_cache_entry_block(istate, istate->ce_mem_pool,
2091
0
          0, istate->cache_nr, mmap, src_offset, NULL);
2092
0
  return consumed;
2093
0
}
2094
2095
/*
2096
 * Mostly randomly chosen maximum thread counts: we
2097
 * cap the parallelism to online_cpus() threads, and we want
2098
 * to have at least 10000 cache entries per thread for it to
2099
 * be worth starting a thread.
2100
 */
2101
2102
0
#define THREAD_COST   (10000)
2103
2104
struct load_cache_entries_thread_data
2105
{
2106
  pthread_t pthread;
2107
  struct index_state *istate;
2108
  struct mem_pool *ce_mem_pool;
2109
  int offset;
2110
  const char *mmap;
2111
  struct index_entry_offset_table *ieot;
2112
  int ieot_start;   /* starting index into the ieot array */
2113
  int ieot_blocks;  /* count of ieot entries to process */
2114
  unsigned long consumed; /* return # of bytes in index file processed */
2115
};
2116
2117
/*
2118
 * A thread proc to run the load_cache_entries() computation
2119
 * across multiple background threads.
2120
 */
2121
static void *load_cache_entries_thread(void *_data)
2122
0
{
2123
0
  struct load_cache_entries_thread_data *p = _data;
2124
0
  int i;
2125
2126
  /* iterate across all ieot blocks assigned to this thread */
2127
0
  for (i = p->ieot_start; i < p->ieot_start + p->ieot_blocks; i++) {
2128
0
    p->consumed += load_cache_entry_block(p->istate, p->ce_mem_pool,
2129
0
      p->offset, p->ieot->entries[i].nr, p->mmap, p->ieot->entries[i].offset, NULL);
2130
0
    p->offset += p->ieot->entries[i].nr;
2131
0
  }
2132
0
  return NULL;
2133
0
}
2134
2135
static unsigned long load_cache_entries_threaded(struct index_state *istate, const char *mmap, size_t mmap_size,
2136
             int nr_threads, struct index_entry_offset_table *ieot)
2137
0
{
2138
0
  int i, offset, ieot_blocks, ieot_start, err;
2139
0
  struct load_cache_entries_thread_data *data;
2140
0
  unsigned long consumed = 0;
2141
2142
  /* a little sanity checking */
2143
0
  if (istate->name_hash_initialized)
2144
0
    BUG("the name hash isn't thread safe");
2145
2146
0
  istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2147
0
  mem_pool_init(istate->ce_mem_pool, 0);
2148
2149
  /* ensure we have no more threads than we have blocks to process */
2150
0
  if (nr_threads > ieot->nr)
2151
0
    nr_threads = ieot->nr;
2152
0
  CALLOC_ARRAY(data, nr_threads);
2153
2154
0
  offset = ieot_start = 0;
2155
0
  ieot_blocks = DIV_ROUND_UP(ieot->nr, nr_threads);
2156
0
  for (i = 0; i < nr_threads; i++) {
2157
0
    struct load_cache_entries_thread_data *p = &data[i];
2158
0
    int nr, j;
2159
2160
0
    if (ieot_start + ieot_blocks > ieot->nr)
2161
0
      ieot_blocks = ieot->nr - ieot_start;
2162
2163
0
    p->istate = istate;
2164
0
    p->offset = offset;
2165
0
    p->mmap = mmap;
2166
0
    p->ieot = ieot;
2167
0
    p->ieot_start = ieot_start;
2168
0
    p->ieot_blocks = ieot_blocks;
2169
2170
    /* create a mem_pool for each thread */
2171
0
    nr = 0;
2172
0
    for (j = p->ieot_start; j < p->ieot_start + p->ieot_blocks; j++)
2173
0
      nr += p->ieot->entries[j].nr;
2174
0
    p->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2175
0
    if (istate->version == 4) {
2176
0
      mem_pool_init(p->ce_mem_pool,
2177
0
        estimate_cache_size_from_compressed(nr));
2178
0
    } else {
2179
0
      mem_pool_init(p->ce_mem_pool,
2180
0
        estimate_cache_size(mmap_size, nr));
2181
0
    }
2182
2183
0
    err = pthread_create(&p->pthread, NULL, load_cache_entries_thread, p);
2184
0
    if (err)
2185
0
      die(_("unable to create load_cache_entries thread: %s"), strerror(err));
2186
2187
    /* increment by the number of cache entries in the ieot block being processed */
2188
0
    for (j = 0; j < ieot_blocks; j++)
2189
0
      offset += ieot->entries[ieot_start + j].nr;
2190
0
    ieot_start += ieot_blocks;
2191
0
  }
2192
2193
0
  for (i = 0; i < nr_threads; i++) {
2194
0
    struct load_cache_entries_thread_data *p = &data[i];
2195
2196
0
    err = pthread_join(p->pthread, NULL);
2197
0
    if (err)
2198
0
      die(_("unable to join load_cache_entries thread: %s"), strerror(err));
2199
0
    mem_pool_combine(istate->ce_mem_pool, p->ce_mem_pool);
2200
0
    free(p->ce_mem_pool);
2201
0
    consumed += p->consumed;
2202
0
  }
2203
2204
0
  free(data);
2205
2206
0
  return consumed;
2207
0
}
2208
2209
static void set_new_index_sparsity(struct index_state *istate)
2210
0
{
2211
  /*
2212
   * If the index's repo exists, mark it sparse according to
2213
   * repo settings.
2214
   */
2215
0
  prepare_repo_settings(istate->repo);
2216
0
  if (!istate->repo->settings.command_requires_full_index &&
2217
0
      is_sparse_index_allowed(istate, 0))
2218
0
    istate->sparse_index = 1;
2219
0
}
2220
2221
/* remember to discard_cache() before reading a different cache! */
2222
int do_read_index(struct index_state *istate, const char *path, int must_exist)
2223
0
{
2224
0
  int fd;
2225
0
  struct stat st;
2226
0
  unsigned long src_offset;
2227
0
  const struct cache_header *hdr;
2228
0
  const char *mmap;
2229
0
  size_t mmap_size;
2230
0
  struct load_index_extensions p;
2231
0
  size_t extension_offset = 0;
2232
0
  int nr_threads, cpus;
2233
0
  struct index_entry_offset_table *ieot = NULL;
2234
2235
0
  if (istate->initialized)
2236
0
    return istate->cache_nr;
2237
2238
0
  istate->timestamp.sec = 0;
2239
0
  istate->timestamp.nsec = 0;
2240
0
  fd = open(path, O_RDONLY);
2241
0
  if (fd < 0) {
2242
0
    if (!must_exist && errno == ENOENT) {
2243
0
      set_new_index_sparsity(istate);
2244
0
      istate->initialized = 1;
2245
0
      return 0;
2246
0
    }
2247
0
    die_errno(_("%s: index file open failed"), path);
2248
0
  }
2249
2250
0
  if (fstat(fd, &st))
2251
0
    die_errno(_("%s: cannot stat the open index"), path);
2252
2253
0
  mmap_size = xsize_t(st.st_size);
2254
0
  if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2255
0
    die(_("%s: index file smaller than expected"), path);
2256
2257
0
  mmap = xmmap_gently(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
2258
0
  if (mmap == MAP_FAILED)
2259
0
    die_errno(_("%s: unable to map index file%s"), path,
2260
0
      mmap_os_err());
2261
0
  close(fd);
2262
2263
0
  hdr = (const struct cache_header *)mmap;
2264
0
  if (verify_hdr(hdr, mmap_size) < 0)
2265
0
    goto unmap;
2266
2267
0
  oidread(&istate->oid, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz,
2268
0
    the_repository->hash_algo);
2269
0
  istate->version = ntohl(hdr->hdr_version);
2270
0
  istate->cache_nr = ntohl(hdr->hdr_entries);
2271
0
  istate->cache_alloc = alloc_nr(istate->cache_nr);
2272
0
  CALLOC_ARRAY(istate->cache, istate->cache_alloc);
2273
0
  istate->initialized = 1;
2274
2275
0
  p.istate = istate;
2276
0
  p.mmap = mmap;
2277
0
  p.mmap_size = mmap_size;
2278
2279
0
  src_offset = sizeof(*hdr);
2280
2281
0
  if (repo_config_get_index_threads(the_repository, &nr_threads))
2282
0
    nr_threads = 1;
2283
2284
  /* TODO: does creating more threads than cores help? */
2285
0
  if (!nr_threads) {
2286
0
    nr_threads = istate->cache_nr / THREAD_COST;
2287
0
    cpus = online_cpus();
2288
0
    if (nr_threads > cpus)
2289
0
      nr_threads = cpus;
2290
0
  }
2291
2292
0
  if (!HAVE_THREADS)
2293
0
    nr_threads = 1;
2294
2295
0
  if (nr_threads > 1) {
2296
0
    extension_offset = read_eoie_extension(mmap, mmap_size);
2297
0
    if (extension_offset) {
2298
0
      int err;
2299
2300
0
      p.src_offset = extension_offset;
2301
0
      err = pthread_create(&p.pthread, NULL, load_index_extensions, &p);
2302
0
      if (err)
2303
0
        die(_("unable to create load_index_extensions thread: %s"), strerror(err));
2304
2305
0
      nr_threads--;
2306
0
    }
2307
0
  }
2308
2309
  /*
2310
   * Locate and read the index entry offset table so that we can use it
2311
   * to multi-thread the reading of the cache entries.
2312
   */
2313
0
  if (extension_offset && nr_threads > 1)
2314
0
    ieot = read_ieot_extension(mmap, mmap_size, extension_offset);
2315
2316
0
  if (ieot) {
2317
0
    src_offset += load_cache_entries_threaded(istate, mmap, mmap_size, nr_threads, ieot);
2318
0
    free(ieot);
2319
0
  } else {
2320
0
    src_offset += load_all_cache_entries(istate, mmap, mmap_size, src_offset);
2321
0
  }
2322
2323
0
  istate->timestamp.sec = st.st_mtime;
2324
0
  istate->timestamp.nsec = ST_MTIME_NSEC(st);
2325
0
  fill_stat_data(&istate->file_stat, &st);
2326
2327
  /* if we created a thread, join it otherwise load the extensions on the primary thread */
2328
0
  if (extension_offset) {
2329
0
    int ret = pthread_join(p.pthread, NULL);
2330
0
    if (ret)
2331
0
      die(_("unable to join load_index_extensions thread: %s"), strerror(ret));
2332
0
  } else {
2333
0
    p.src_offset = src_offset;
2334
0
    load_index_extensions(&p);
2335
0
  }
2336
0
  munmap((void *)mmap, mmap_size);
2337
2338
0
  trace2_data_intmax("index", istate->repo, "read/version",
2339
0
         istate->version);
2340
0
  trace2_data_intmax("index", istate->repo, "read/cache_nr",
2341
0
         istate->cache_nr);
2342
2343
  /*
2344
   * If the command explicitly requires a full index, force it
2345
   * to be full. Otherwise, correct the sparsity based on repository
2346
   * settings and other properties of the index (if necessary).
2347
   */
2348
0
  prepare_repo_settings(istate->repo);
2349
0
  if (istate->repo->settings.command_requires_full_index)
2350
0
    ensure_full_index(istate);
2351
0
  else
2352
0
    ensure_correct_sparsity(istate);
2353
2354
0
  return istate->cache_nr;
2355
2356
0
unmap:
2357
0
  munmap((void *)mmap, mmap_size);
2358
0
  die(_("index file corrupt"));
2359
0
}
2360
2361
/*
2362
 * Signal that the shared index is used by updating its mtime.
2363
 *
2364
 * This way, shared index can be removed if they have not been used
2365
 * for some time.
2366
 */
2367
static void freshen_shared_index(const char *shared_index, int warn)
2368
0
{
2369
0
  if (!check_and_freshen_file(shared_index, 1, NULL) && warn)
2370
0
    warning(_("could not freshen shared index '%s'"), shared_index);
2371
0
}
2372
2373
int read_index_from(struct index_state *istate, const char *path,
2374
        const char *gitdir)
2375
0
{
2376
0
  struct split_index *split_index;
2377
0
  int ret;
2378
0
  char *base_oid_hex;
2379
0
  char *base_path;
2380
2381
  /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2382
0
  if (istate->initialized)
2383
0
    return istate->cache_nr;
2384
2385
0
  trace2_region_enter_printf("index", "do_read_index", istate->repo,
2386
0
           "%s", path);
2387
0
  trace_performance_enter();
2388
0
  ret = do_read_index(istate, path, 0);
2389
0
  trace_performance_leave("read cache %s", path);
2390
0
  trace2_region_leave_printf("index", "do_read_index", istate->repo,
2391
0
           "%s", path);
2392
2393
0
  split_index = istate->split_index;
2394
0
  if (!split_index || is_null_oid(&split_index->base_oid)) {
2395
0
    post_read_index_from(istate);
2396
0
    return ret;
2397
0
  }
2398
2399
0
  trace_performance_enter();
2400
0
  if (split_index->base)
2401
0
    release_index(split_index->base);
2402
0
  else
2403
0
    ALLOC_ARRAY(split_index->base, 1);
2404
0
  index_state_init(split_index->base, istate->repo);
2405
2406
0
  base_oid_hex = oid_to_hex(&split_index->base_oid);
2407
0
  base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
2408
0
  if (file_exists(base_path)) {
2409
0
    trace2_region_enter_printf("index", "shared/do_read_index",
2410
0
          the_repository, "%s", base_path);
2411
2412
0
    ret = do_read_index(split_index->base, base_path, 0);
2413
0
    trace2_region_leave_printf("index", "shared/do_read_index",
2414
0
          the_repository, "%s", base_path);
2415
0
  } else {
2416
0
    char *path_copy = xstrdup(path);
2417
0
    char *base_path2 = xstrfmt("%s/sharedindex.%s",
2418
0
             dirname(path_copy), base_oid_hex);
2419
0
    free(path_copy);
2420
0
    trace2_region_enter_printf("index", "shared/do_read_index",
2421
0
             the_repository, "%s", base_path2);
2422
0
    ret = do_read_index(split_index->base, base_path2, 1);
2423
0
    trace2_region_leave_printf("index", "shared/do_read_index",
2424
0
             the_repository, "%s", base_path2);
2425
0
    free(base_path2);
2426
0
  }
2427
0
  if (!oideq(&split_index->base_oid, &split_index->base->oid))
2428
0
    die(_("broken index, expect %s in %s, got %s"),
2429
0
        base_oid_hex, base_path,
2430
0
        oid_to_hex(&split_index->base->oid));
2431
2432
0
  freshen_shared_index(base_path, 0);
2433
0
  merge_base_index(istate);
2434
0
  post_read_index_from(istate);
2435
0
  trace_performance_leave("read cache %s", base_path);
2436
0
  free(base_path);
2437
0
  return ret;
2438
0
}
2439
2440
int is_index_unborn(struct index_state *istate)
2441
0
{
2442
0
  return (!istate->cache_nr && !istate->timestamp.sec);
2443
0
}
2444
2445
void index_state_init(struct index_state *istate, struct repository *r)
2446
0
{
2447
0
  struct index_state blank = INDEX_STATE_INIT(r);
2448
0
  memcpy(istate, &blank, sizeof(*istate));
2449
0
}
2450
2451
void release_index(struct index_state *istate)
2452
0
{
2453
  /*
2454
   * Cache entries in istate->cache[] should have been allocated
2455
   * from the memory pool associated with this index, or from an
2456
   * associated split_index. There is no need to free individual
2457
   * cache entries. validate_cache_entries can detect when this
2458
   * assertion does not hold.
2459
   */
2460
0
  validate_cache_entries(istate);
2461
2462
0
  resolve_undo_clear_index(istate);
2463
0
  free_name_hash(istate);
2464
0
  cache_tree_free(&(istate->cache_tree));
2465
0
  free(istate->fsmonitor_last_update);
2466
0
  free(istate->cache);
2467
0
  discard_split_index(istate);
2468
0
  free_untracked_cache(istate->untracked);
2469
2470
0
  if (istate->sparse_checkout_patterns) {
2471
0
    clear_pattern_list(istate->sparse_checkout_patterns);
2472
0
    FREE_AND_NULL(istate->sparse_checkout_patterns);
2473
0
  }
2474
2475
0
  if (istate->ce_mem_pool) {
2476
0
    mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
2477
0
    FREE_AND_NULL(istate->ce_mem_pool);
2478
0
  }
2479
0
}
2480
2481
void discard_index(struct index_state *istate)
2482
0
{
2483
0
  release_index(istate);
2484
0
  index_state_init(istate, istate->repo);
2485
0
}
2486
2487
/*
2488
 * Validate the cache entries of this index.
2489
 * All cache entries associated with this index
2490
 * should have been allocated by the memory pool
2491
 * associated with this index, or by a referenced
2492
 * split index.
2493
 */
2494
void validate_cache_entries(const struct index_state *istate)
2495
0
{
2496
0
  int i;
2497
2498
0
  if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2499
0
    return;
2500
2501
0
  for (i = 0; i < istate->cache_nr; i++) {
2502
0
    if (!istate) {
2503
0
      BUG("cache entry is not allocated from expected memory pool");
2504
0
    } else if (!istate->ce_mem_pool ||
2505
0
      !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2506
0
      if (!istate->split_index ||
2507
0
        !istate->split_index->base ||
2508
0
        !istate->split_index->base->ce_mem_pool ||
2509
0
        !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2510
0
        BUG("cache entry is not allocated from expected memory pool");
2511
0
      }
2512
0
    }
2513
0
  }
2514
2515
0
  if (istate->split_index)
2516
0
    validate_cache_entries(istate->split_index->base);
2517
0
}
2518
2519
int unmerged_index(const struct index_state *istate)
2520
0
{
2521
0
  int i;
2522
0
  for (i = 0; i < istate->cache_nr; i++) {
2523
0
    if (ce_stage(istate->cache[i]))
2524
0
      return 1;
2525
0
  }
2526
0
  return 0;
2527
0
}
2528
2529
int repo_index_has_changes(struct repository *repo,
2530
         struct tree *tree,
2531
         struct strbuf *sb)
2532
0
{
2533
0
  struct index_state *istate = repo->index;
2534
0
  struct object_id cmp;
2535
0
  int i;
2536
2537
0
  if (tree)
2538
0
    cmp = tree->object.oid;
2539
0
  if (tree || !repo_get_oid_tree(repo, "HEAD", &cmp)) {
2540
0
    struct diff_options opt;
2541
2542
0
    repo_diff_setup(repo, &opt);
2543
0
    opt.flags.exit_with_status = 1;
2544
0
    if (!sb)
2545
0
      opt.flags.quick = 1;
2546
0
    diff_setup_done(&opt);
2547
0
    do_diff_cache(&cmp, &opt);
2548
0
    diffcore_std(&opt);
2549
0
    for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2550
0
      if (i)
2551
0
        strbuf_addch(sb, ' ');
2552
0
      strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2553
0
    }
2554
0
    diff_flush(&opt);
2555
0
    return opt.flags.has_changes != 0;
2556
0
  } else {
2557
    /* TODO: audit for interaction with sparse-index. */
2558
0
    ensure_full_index(istate);
2559
0
    for (i = 0; sb && i < istate->cache_nr; i++) {
2560
0
      if (i)
2561
0
        strbuf_addch(sb, ' ');
2562
0
      strbuf_addstr(sb, istate->cache[i]->name);
2563
0
    }
2564
0
    return !!istate->cache_nr;
2565
0
  }
2566
0
}
2567
2568
static int write_index_ext_header(struct hashfile *f,
2569
          struct git_hash_ctx *eoie_f,
2570
          unsigned int ext,
2571
          unsigned int sz)
2572
0
{
2573
0
  hashwrite_be32(f, ext);
2574
0
  hashwrite_be32(f, sz);
2575
2576
0
  if (eoie_f) {
2577
0
    ext = htonl(ext);
2578
0
    sz = htonl(sz);
2579
0
    git_hash_update(eoie_f, &ext, sizeof(ext));
2580
0
    git_hash_update(eoie_f, &sz, sizeof(sz));
2581
0
  }
2582
0
  return 0;
2583
0
}
2584
2585
static void ce_smudge_racily_clean_entry(struct index_state *istate,
2586
           struct cache_entry *ce)
2587
0
{
2588
  /*
2589
   * The only thing we care about in this function is to smudge the
2590
   * falsely clean entry due to touch-update-touch race, so we leave
2591
   * everything else as they are.  We are called for entries whose
2592
   * ce_stat_data.sd_mtime match the index file mtime.
2593
   *
2594
   * Note that this actually does not do much for gitlinks, for
2595
   * which ce_match_stat_basic() always goes to the actual
2596
   * contents.  The caller checks with is_racy_timestamp() which
2597
   * always says "no" for gitlinks, so we are not called for them ;-)
2598
   */
2599
0
  struct stat st;
2600
2601
0
  if (lstat(ce->name, &st) < 0)
2602
0
    return;
2603
0
  if (ce_match_stat_basic(ce, &st))
2604
0
    return;
2605
0
  if (ce_modified_check_fs(istate, ce, &st)) {
2606
    /* This is "racily clean"; smudge it.  Note that this
2607
     * is a tricky code.  At first glance, it may appear
2608
     * that it can break with this sequence:
2609
     *
2610
     * $ echo xyzzy >frotz
2611
     * $ git-update-index --add frotz
2612
     * $ : >frotz
2613
     * $ sleep 3
2614
     * $ echo filfre >nitfol
2615
     * $ git-update-index --add nitfol
2616
     *
2617
     * but it does not.  When the second update-index runs,
2618
     * it notices that the entry "frotz" has the same timestamp
2619
     * as index, and if we were to smudge it by resetting its
2620
     * size to zero here, then the object name recorded
2621
     * in index is the 6-byte file but the cached stat information
2622
     * becomes zero --- which would then match what we would
2623
     * obtain from the filesystem next time we stat("frotz").
2624
     *
2625
     * However, the second update-index, before calling
2626
     * this function, notices that the cached size is 6
2627
     * bytes and what is on the filesystem is an empty
2628
     * file, and never calls us, so the cached size information
2629
     * for "frotz" stays 6 which does not match the filesystem.
2630
     */
2631
0
    ce->ce_stat_data.sd_size = 0;
2632
0
  }
2633
0
}
2634
2635
/* Copy miscellaneous fields but not the name */
2636
static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2637
               struct cache_entry *ce)
2638
0
{
2639
0
  short flags;
2640
0
  const unsigned hashsz = the_hash_algo->rawsz;
2641
0
  uint16_t *flagsp = (uint16_t *)(ondisk->data + hashsz);
2642
2643
0
  ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2644
0
  ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2645
0
  ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2646
0
  ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2647
0
  ondisk->dev  = htonl(ce->ce_stat_data.sd_dev);
2648
0
  ondisk->ino  = htonl(ce->ce_stat_data.sd_ino);
2649
0
  ondisk->mode = htonl(ce->ce_mode);
2650
0
  ondisk->uid  = htonl(ce->ce_stat_data.sd_uid);
2651
0
  ondisk->gid  = htonl(ce->ce_stat_data.sd_gid);
2652
0
  ondisk->size = htonl(ce->ce_stat_data.sd_size);
2653
0
  hashcpy(ondisk->data, ce->oid.hash, the_repository->hash_algo);
2654
2655
0
  flags = ce->ce_flags & ~CE_NAMEMASK;
2656
0
  flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2657
0
  flagsp[0] = htons(flags);
2658
0
  if (ce->ce_flags & CE_EXTENDED) {
2659
0
    flagsp[1] = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2660
0
  }
2661
0
}
2662
2663
static int ce_write_entry(struct hashfile *f, struct cache_entry *ce,
2664
        struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2665
0
{
2666
0
  int size;
2667
0
  unsigned int saved_namelen;
2668
0
  int stripped_name = 0;
2669
0
  static unsigned char padding[8] = { 0x00 };
2670
2671
0
  if (ce->ce_flags & CE_STRIP_NAME) {
2672
0
    saved_namelen = ce_namelen(ce);
2673
0
    ce->ce_namelen = 0;
2674
0
    stripped_name = 1;
2675
0
  }
2676
2677
0
  size = offsetof(struct ondisk_cache_entry,data) + ondisk_data_size(ce->ce_flags, 0);
2678
2679
0
  if (!previous_name) {
2680
0
    int len = ce_namelen(ce);
2681
0
    copy_cache_entry_to_ondisk(ondisk, ce);
2682
0
    hashwrite(f, ondisk, size);
2683
0
    hashwrite(f, ce->name, len);
2684
0
    hashwrite(f, padding, align_padding_size(size, len));
2685
0
  } else {
2686
0
    int common, to_remove;
2687
0
    uint8_t prefix_size;
2688
0
    unsigned char to_remove_vi[16];
2689
2690
0
    for (common = 0;
2691
0
         (common < previous_name->len &&
2692
0
          ce->name[common] &&
2693
0
          ce->name[common] == previous_name->buf[common]);
2694
0
         common++)
2695
0
      ; /* still matching */
2696
0
    to_remove = previous_name->len - common;
2697
0
    prefix_size = encode_varint(to_remove, to_remove_vi);
2698
2699
0
    copy_cache_entry_to_ondisk(ondisk, ce);
2700
0
    hashwrite(f, ondisk, size);
2701
0
    hashwrite(f, to_remove_vi, prefix_size);
2702
0
    hashwrite(f, ce->name + common, ce_namelen(ce) - common);
2703
0
    hashwrite(f, padding, 1);
2704
2705
0
    strbuf_splice(previous_name, common, to_remove,
2706
0
            ce->name + common, ce_namelen(ce) - common);
2707
0
  }
2708
0
  if (stripped_name) {
2709
0
    ce->ce_namelen = saved_namelen;
2710
0
    ce->ce_flags &= ~CE_STRIP_NAME;
2711
0
  }
2712
2713
0
  return 0;
2714
0
}
2715
2716
/*
2717
 * Whether the index file is still the one whose stat data was recorded
2718
 * when the index was read or written. This stands in for the checksum
2719
 * of an index written without one, so unlike match_stat_data() it
2720
 * always compares the inode and the mtime to the nanosecond, whatever
2721
 * core.checkStat and core.useNanosec say: a false "unchanged" would
2722
 * discard an update made by another process, while a false "changed"
2723
 * only skips an opportunistic write. The ctime is left out because
2724
 * renaming the written lockfile into place changes it.
2725
 */
2726
static int index_file_unchanged(const struct stat_data *sd, struct stat *st)
2727
0
{
2728
0
  struct stat_data now;
2729
2730
0
  fill_stat_data(&now, st);
2731
0
  return sd->sd_mtime.sec == now.sd_mtime.sec &&
2732
0
         sd->sd_mtime.nsec == now.sd_mtime.nsec &&
2733
0
         sd->sd_dev == now.sd_dev &&
2734
0
         sd->sd_ino == now.sd_ino &&
2735
0
         sd->sd_uid == now.sd_uid &&
2736
0
         sd->sd_gid == now.sd_gid &&
2737
0
         sd->sd_size == now.sd_size;
2738
0
}
2739
2740
/*
2741
 * This function verifies if index_state has the correct sha1 of the
2742
 * index file, or, when the index was written without a checksum
2743
 * (index.skipHash), that the file's stat data has not changed. Don't
2744
 * die if we have any other failure, just return 0.
2745
 */
2746
static int verify_index_from(const struct index_state *istate, const char *path)
2747
0
{
2748
0
  int fd;
2749
0
  ssize_t n;
2750
0
  struct stat st;
2751
0
  unsigned char hash[GIT_MAX_RAWSZ];
2752
2753
0
  if (!istate->initialized)
2754
0
    return 0;
2755
2756
0
  fd = open(path, O_RDONLY);
2757
0
  if (fd < 0)
2758
0
    return 0;
2759
2760
0
  if (fstat(fd, &st))
2761
0
    goto out;
2762
2763
0
  if (is_null_oid(&istate->oid)) {
2764
0
    if (!index_file_unchanged(&istate->file_stat, &st))
2765
0
      goto out;
2766
0
    close(fd);
2767
0
    return 1;
2768
0
  }
2769
2770
0
  if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2771
0
    goto out;
2772
2773
0
  n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2774
0
  if (n != the_hash_algo->rawsz)
2775
0
    goto out;
2776
2777
0
  if (!hasheq(istate->oid.hash, hash, the_repository->hash_algo))
2778
0
    goto out;
2779
2780
0
  close(fd);
2781
0
  return 1;
2782
2783
0
out:
2784
0
  close(fd);
2785
0
  return 0;
2786
0
}
2787
2788
static int repo_verify_index(struct repository *repo)
2789
0
{
2790
0
  return verify_index_from(repo->index, repo->index_file);
2791
0
}
2792
2793
int has_racy_timestamp(struct index_state *istate)
2794
0
{
2795
0
  int entries = istate->cache_nr;
2796
0
  int i;
2797
2798
0
  for (i = 0; i < entries; i++) {
2799
0
    struct cache_entry *ce = istate->cache[i];
2800
0
    if (is_racy_timestamp(istate, ce))
2801
0
      return 1;
2802
0
  }
2803
0
  return 0;
2804
0
}
2805
2806
static int index_needs_write(struct index_state *istate)
2807
0
{
2808
0
  return istate->cache_changed || has_racy_timestamp(istate);
2809
0
}
2810
2811
void repo_update_index_if_able(struct repository *repo,
2812
             struct lock_file *lockfile)
2813
0
{
2814
0
  if (index_needs_write(repo->index) && repo_verify_index(repo))
2815
0
    write_locked_index(repo->index, lockfile, COMMIT_LOCK);
2816
0
  else
2817
0
    rollback_lock_file(lockfile);
2818
0
}
2819
2820
void repo_lock_and_update_index_if_able(struct repository *repo)
2821
0
{
2822
0
  struct lock_file lock = LOCK_INIT;
2823
2824
0
  if (!index_needs_write(repo->index) ||
2825
0
      repo_hold_locked_index(repo, &lock, 0) < 0)
2826
0
    return;
2827
0
  if (repo_verify_index(repo))
2828
0
    write_locked_index(repo->index, &lock, COMMIT_LOCK);
2829
0
  else
2830
0
    rollback_lock_file(&lock);
2831
0
}
2832
2833
static int record_eoie(void)
2834
0
{
2835
0
  int val;
2836
2837
0
  if (!repo_config_get_bool(the_repository, "index.recordendofindexentries", &val))
2838
0
    return val;
2839
2840
  /*
2841
   * As a convenience, the end of index entries extension
2842
   * used for threading is written by default if the user
2843
   * explicitly requested threaded index reads.
2844
   */
2845
0
  return !repo_config_get_index_threads(the_repository, &val) && val != 1;
2846
0
}
2847
2848
static int record_ieot(void)
2849
0
{
2850
0
  int val;
2851
2852
0
  if (!repo_config_get_bool(the_repository, "index.recordoffsettable", &val))
2853
0
    return val;
2854
2855
  /*
2856
   * As a convenience, the offset table used for threading is
2857
   * written by default if the user explicitly requested
2858
   * threaded index reads.
2859
   */
2860
0
  return !repo_config_get_index_threads(the_repository, &val) && val != 1;
2861
0
}
2862
2863
enum write_extensions {
2864
  WRITE_NO_EXTENSION =              0,
2865
  WRITE_SPLIT_INDEX_EXTENSION =     1<<0,
2866
  WRITE_CACHE_TREE_EXTENSION =      1<<1,
2867
  WRITE_RESOLVE_UNDO_EXTENSION =    1<<2,
2868
  WRITE_UNTRACKED_CACHE_EXTENSION = 1<<3,
2869
  WRITE_FSMONITOR_EXTENSION =       1<<4,
2870
};
2871
0
#define WRITE_ALL_EXTENSIONS ((enum write_extensions)-1)
2872
2873
/*
2874
 * On success, `tempfile` is closed. If it is the temporary file
2875
 * of a `struct lock_file`, we will therefore effectively perform
2876
 * a 'close_lock_file_gently()`. Since that is an implementation
2877
 * detail of lockfiles, callers of `do_write_index()` should not
2878
 * rely on it.
2879
 */
2880
static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2881
        enum write_extensions write_extensions, unsigned flags)
2882
0
{
2883
0
  uint64_t start = getnanotime();
2884
0
  struct hashfile *f;
2885
0
  struct git_hash_ctx *eoie_c = NULL;
2886
0
  struct cache_header hdr;
2887
0
  int i, err = 0, removed, extended, hdr_version;
2888
0
  struct cache_entry **cache = istate->cache;
2889
0
  int entries = istate->cache_nr;
2890
0
  struct stat st;
2891
0
  struct ondisk_cache_entry ondisk;
2892
0
  struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2893
0
  int drop_cache_tree = istate->drop_cache_tree;
2894
0
  off_t offset;
2895
0
  int csum_fsync_flag;
2896
0
  int ieot_entries = 1;
2897
0
  struct index_entry_offset_table *ieot = NULL;
2898
0
  struct repository *r = istate->repo;
2899
0
  struct strbuf sb = STRBUF_INIT;
2900
0
  int nr, nr_threads, ret;
2901
2902
0
  f = hashfd(the_repository->hash_algo, tempfile->fd, tempfile->filename.buf);
2903
2904
0
  prepare_repo_settings(r);
2905
0
  f->skip_hash = r->settings.index_skip_hash;
2906
2907
0
  for (i = removed = extended = 0; i < entries; i++) {
2908
0
    if (cache[i]->ce_flags & CE_REMOVE)
2909
0
      removed++;
2910
2911
    /* reduce extended entries if possible */
2912
0
    cache[i]->ce_flags &= ~CE_EXTENDED;
2913
0
    if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2914
0
      extended++;
2915
0
      cache[i]->ce_flags |= CE_EXTENDED;
2916
0
    }
2917
0
  }
2918
2919
0
  if (!istate->version)
2920
0
    istate->version = get_index_format_default(r);
2921
2922
  /* demote version 3 to version 2 when the latter suffices */
2923
0
  if (istate->version == 3 || istate->version == 2)
2924
0
    istate->version = extended ? 3 : 2;
2925
2926
0
  hdr_version = istate->version;
2927
2928
0
  hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2929
0
  hdr.hdr_version = htonl(hdr_version);
2930
0
  hdr.hdr_entries = htonl(entries - removed);
2931
2932
0
  hashwrite(f, &hdr, sizeof(hdr));
2933
2934
0
  if (!HAVE_THREADS || repo_config_get_index_threads(the_repository, &nr_threads))
2935
0
    nr_threads = 1;
2936
2937
0
  if (nr_threads != 1 && record_ieot()) {
2938
0
    int ieot_blocks, cpus;
2939
2940
    /*
2941
     * ensure default number of ieot blocks maps evenly to the
2942
     * default number of threads that will process them leaving
2943
     * room for the thread to load the index extensions.
2944
     */
2945
0
    if (!nr_threads) {
2946
0
      ieot_blocks = istate->cache_nr / THREAD_COST;
2947
0
      cpus = online_cpus();
2948
0
      if (ieot_blocks > cpus - 1)
2949
0
        ieot_blocks = cpus - 1;
2950
0
    } else {
2951
0
      ieot_blocks = nr_threads;
2952
0
      if (ieot_blocks > istate->cache_nr)
2953
0
        ieot_blocks = istate->cache_nr;
2954
0
    }
2955
2956
    /*
2957
     * no reason to write out the IEOT extension if we don't
2958
     * have enough blocks to utilize multi-threading
2959
     */
2960
0
    if (ieot_blocks > 1) {
2961
0
      ieot = xcalloc(1, sizeof(struct index_entry_offset_table)
2962
0
        + (ieot_blocks * sizeof(struct index_entry_offset)));
2963
0
      ieot_entries = DIV_ROUND_UP(entries, ieot_blocks);
2964
0
    }
2965
0
  }
2966
2967
0
  offset = hashfile_total(f);
2968
2969
0
  nr = 0;
2970
0
  previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
2971
2972
0
  for (i = 0; i < entries; i++) {
2973
0
    struct cache_entry *ce = cache[i];
2974
0
    if (ce->ce_flags & CE_REMOVE)
2975
0
      continue;
2976
0
    if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
2977
0
      ce_smudge_racily_clean_entry(istate, ce);
2978
0
    if (is_null_oid(&ce->oid)) {
2979
0
      static const char msg[] = "cache entry has null sha1: %s";
2980
0
      static int allow = -1;
2981
2982
0
      if (allow < 0)
2983
0
        allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
2984
0
      if (allow)
2985
0
        warning(msg, ce->name);
2986
0
      else
2987
0
        err = error(msg, ce->name);
2988
2989
0
      drop_cache_tree = 1;
2990
0
    }
2991
0
    if (ieot && i && (i % ieot_entries == 0)) {
2992
0
      ieot->entries[ieot->nr].nr = nr;
2993
0
      ieot->entries[ieot->nr].offset = offset;
2994
0
      ieot->nr++;
2995
      /*
2996
       * If we have a V4 index, set the first byte to an invalid
2997
       * character to ensure there is nothing common with the previous
2998
       * entry
2999
       */
3000
0
      if (previous_name)
3001
0
        previous_name->buf[0] = 0;
3002
0
      nr = 0;
3003
3004
0
      offset = hashfile_total(f);
3005
0
    }
3006
0
    if (ce_write_entry(f, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
3007
0
      err = -1;
3008
3009
0
    if (err)
3010
0
      break;
3011
0
    nr++;
3012
0
  }
3013
0
  if (ieot && nr) {
3014
0
    ieot->entries[ieot->nr].nr = nr;
3015
0
    ieot->entries[ieot->nr].offset = offset;
3016
0
    ieot->nr++;
3017
0
  }
3018
0
  strbuf_release(&previous_name_buf);
3019
3020
0
  if (err) {
3021
0
    ret = err;
3022
0
    goto out;
3023
0
  }
3024
3025
0
  offset = hashfile_total(f);
3026
3027
  /*
3028
   * The extension headers must be hashed on their own for the
3029
   * EOIE extension. Create a hashfile here to compute that hash.
3030
   */
3031
0
  if (offset && record_eoie()) {
3032
0
    CALLOC_ARRAY(eoie_c, 1);
3033
0
    git_hash_init(eoie_c, the_hash_algo);
3034
0
  }
3035
3036
  /*
3037
   * Lets write out CACHE_EXT_INDEXENTRYOFFSETTABLE first so that we
3038
   * can minimize the number of extensions we have to scan through to
3039
   * find it during load.  Write it out regardless of the
3040
   * strip_extensions parameter as we need it when loading the shared
3041
   * index.
3042
   */
3043
0
  if (ieot) {
3044
0
    strbuf_reset(&sb);
3045
3046
0
    write_ieot_extension(&sb, ieot);
3047
0
    err = write_index_ext_header(f, eoie_c, CACHE_EXT_INDEXENTRYOFFSETTABLE, sb.len) < 0;
3048
0
    hashwrite(f, sb.buf, sb.len);
3049
0
    if (err) {
3050
0
      ret = -1;
3051
0
      goto out;
3052
0
    }
3053
0
  }
3054
3055
0
  if (write_extensions & WRITE_SPLIT_INDEX_EXTENSION &&
3056
0
      istate->split_index) {
3057
0
    strbuf_reset(&sb);
3058
3059
0
    if (istate->sparse_index)
3060
0
      die(_("cannot write split index for a sparse index"));
3061
3062
0
    err = write_link_extension(&sb, istate) < 0 ||
3063
0
      write_index_ext_header(f, eoie_c, CACHE_EXT_LINK,
3064
0
                 sb.len) < 0;
3065
0
    hashwrite(f, sb.buf, sb.len);
3066
0
    if (err) {
3067
0
      ret = -1;
3068
0
      goto out;
3069
0
    }
3070
0
  }
3071
0
  if (write_extensions & WRITE_CACHE_TREE_EXTENSION &&
3072
0
      !drop_cache_tree && istate->cache_tree) {
3073
0
    strbuf_reset(&sb);
3074
3075
0
    cache_tree_write(istate->repo, &sb, istate->cache_tree);
3076
0
    err = write_index_ext_header(f, eoie_c, CACHE_EXT_TREE, sb.len) < 0;
3077
0
    hashwrite(f, sb.buf, sb.len);
3078
0
    if (err) {
3079
0
      ret = -1;
3080
0
      goto out;
3081
0
    }
3082
0
  }
3083
0
  if (write_extensions & WRITE_RESOLVE_UNDO_EXTENSION &&
3084
0
      istate->resolve_undo) {
3085
0
    strbuf_reset(&sb);
3086
3087
0
    resolve_undo_write(&sb, istate->resolve_undo, the_hash_algo);
3088
0
    err = write_index_ext_header(f, eoie_c, CACHE_EXT_RESOLVE_UNDO,
3089
0
               sb.len) < 0;
3090
0
    hashwrite(f, sb.buf, sb.len);
3091
0
    if (err) {
3092
0
      ret = -1;
3093
0
      goto out;
3094
0
    }
3095
0
  }
3096
0
  if (write_extensions & WRITE_UNTRACKED_CACHE_EXTENSION &&
3097
0
      istate->untracked) {
3098
0
    strbuf_reset(&sb);
3099
3100
0
    write_untracked_extension(&sb, istate->untracked);
3101
0
    err = write_index_ext_header(f, eoie_c, CACHE_EXT_UNTRACKED,
3102
0
               sb.len) < 0;
3103
0
    hashwrite(f, sb.buf, sb.len);
3104
0
    if (err) {
3105
0
      ret = -1;
3106
0
      goto out;
3107
0
    }
3108
0
  }
3109
0
  if (write_extensions & WRITE_FSMONITOR_EXTENSION &&
3110
0
      istate->fsmonitor_last_update) {
3111
0
    strbuf_reset(&sb);
3112
3113
0
    write_fsmonitor_extension(&sb, istate);
3114
0
    err = write_index_ext_header(f, eoie_c, CACHE_EXT_FSMONITOR, sb.len) < 0;
3115
0
    hashwrite(f, sb.buf, sb.len);
3116
0
    if (err) {
3117
0
      ret = -1;
3118
0
      goto out;
3119
0
    }
3120
0
  }
3121
0
  if (istate->sparse_index) {
3122
0
    if (write_index_ext_header(f, eoie_c, CACHE_EXT_SPARSE_DIRECTORIES, 0) < 0) {
3123
0
      ret = -1;
3124
0
      goto out;
3125
0
    }
3126
0
  }
3127
3128
  /*
3129
   * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
3130
   * so that it can be found and processed before all the index entries are
3131
   * read.  Write it out regardless of the strip_extensions parameter as we need it
3132
   * when loading the shared index.
3133
   */
3134
0
  if (eoie_c) {
3135
0
    strbuf_reset(&sb);
3136
3137
0
    write_eoie_extension(&sb, eoie_c, offset);
3138
0
    err = write_index_ext_header(f, NULL, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0;
3139
0
    hashwrite(f, sb.buf, sb.len);
3140
0
    if (err) {
3141
0
      ret = -1;
3142
0
      goto out;
3143
0
    }
3144
0
  }
3145
3146
0
  csum_fsync_flag = 0;
3147
0
  if (!alternate_index_output && (flags & COMMIT_LOCK))
3148
0
    csum_fsync_flag = CSUM_FSYNC;
3149
3150
0
  finalize_hashfile(f, istate->oid.hash, FSYNC_COMPONENT_INDEX,
3151
0
        CSUM_HASH_IN_STREAM | csum_fsync_flag);
3152
0
  f = NULL;
3153
3154
0
  if (close_tempfile_gently(tempfile)) {
3155
0
    ret = error(_("could not close '%s'"), get_tempfile_path(tempfile));
3156
0
    goto out;
3157
0
  }
3158
0
  if (stat(get_tempfile_path(tempfile), &st)) {
3159
0
    ret = -1;
3160
0
    goto out;
3161
0
  }
3162
0
  istate->timestamp.sec = (unsigned int)st.st_mtime;
3163
0
  istate->timestamp.nsec = ST_MTIME_NSEC(st);
3164
0
  fill_stat_data(&istate->file_stat, &st);
3165
0
  trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
3166
3167
0
  trace2_data_intmax("index", istate->repo, "write/version",
3168
0
         istate->version);
3169
0
  trace2_data_intmax("index", istate->repo, "write/cache_nr",
3170
0
         istate->cache_nr);
3171
3172
0
  ret = 0;
3173
3174
0
out:
3175
0
  if (f)
3176
0
    free_hashfile(f);
3177
0
  strbuf_release(&sb);
3178
0
  free(eoie_c);
3179
0
  free(ieot);
3180
0
  return ret;
3181
0
}
3182
3183
void set_alternate_index_output(const char *name)
3184
0
{
3185
0
  alternate_index_output = name;
3186
0
}
3187
3188
static int commit_locked_index(struct lock_file *lk)
3189
0
{
3190
0
  if (alternate_index_output)
3191
0
    return commit_lock_file_to(lk, alternate_index_output);
3192
0
  else
3193
0
    return commit_lock_file(lk);
3194
0
}
3195
3196
static int do_write_locked_index(struct index_state *istate,
3197
         struct lock_file *lock,
3198
         unsigned flags,
3199
         enum write_extensions write_extensions)
3200
0
{
3201
0
  int ret;
3202
0
  int was_full = istate->sparse_index == INDEX_EXPANDED;
3203
3204
0
  ret = convert_to_sparse(istate, 0);
3205
3206
0
  if (ret) {
3207
0
    warning(_("failed to convert to a sparse-index"));
3208
0
    return ret;
3209
0
  }
3210
3211
0
  trace2_region_enter_printf("index", "do_write_index", istate->repo,
3212
0
           "%s", get_lock_file_path(lock));
3213
0
  ret = do_write_index(istate, lock->tempfile, write_extensions, flags);
3214
0
  trace2_region_leave_printf("index", "do_write_index", istate->repo,
3215
0
           "%s", get_lock_file_path(lock));
3216
3217
0
  if (was_full)
3218
0
    ensure_full_index(istate);
3219
3220
0
  if (ret)
3221
0
    return ret;
3222
0
  if (flags & COMMIT_LOCK)
3223
0
    ret = commit_locked_index(lock);
3224
0
  else
3225
0
    ret = close_lock_file_gently(lock);
3226
3227
0
  run_hooks_l(the_repository, "post-index-change",
3228
0
        istate->updated_workdir ? "1" : "0",
3229
0
        istate->updated_skipworktree ? "1" : "0", NULL);
3230
0
  istate->updated_workdir = 0;
3231
0
  istate->updated_skipworktree = 0;
3232
3233
0
  return ret;
3234
0
}
3235
3236
static int write_split_index(struct index_state *istate,
3237
           struct lock_file *lock,
3238
           unsigned flags)
3239
0
{
3240
0
  int ret;
3241
0
  prepare_to_write_split_index(istate);
3242
0
  ret = do_write_locked_index(istate, lock, flags, WRITE_ALL_EXTENSIONS);
3243
0
  finish_writing_split_index(istate);
3244
0
  return ret;
3245
0
}
3246
3247
static unsigned long get_shared_index_expire_date(void)
3248
0
{
3249
0
  static unsigned long shared_index_expire_date;
3250
0
  static int shared_index_expire_date_prepared;
3251
3252
0
  if (!shared_index_expire_date_prepared) {
3253
0
    const char *shared_index_expire = "2.weeks.ago";
3254
0
    char *value = NULL;
3255
3256
0
    repo_config_get_expiry(the_repository, "splitindex.sharedindexexpire",
3257
0
               &value);
3258
0
    if (value)
3259
0
      shared_index_expire = value;
3260
3261
0
    shared_index_expire_date = approxidate(shared_index_expire);
3262
0
    shared_index_expire_date_prepared = 1;
3263
3264
0
    free(value);
3265
0
  }
3266
3267
0
  return shared_index_expire_date;
3268
0
}
3269
3270
static int should_delete_shared_index(const char *shared_index_path)
3271
0
{
3272
0
  struct stat st;
3273
0
  unsigned long expiration;
3274
3275
  /* Check timestamp */
3276
0
  expiration = get_shared_index_expire_date();
3277
0
  if (!expiration)
3278
0
    return 0;
3279
0
  if (stat(shared_index_path, &st))
3280
0
    return error_errno(_("could not stat '%s'"), shared_index_path);
3281
0
  if (st.st_mtime > expiration)
3282
0
    return 0;
3283
3284
0
  return 1;
3285
0
}
3286
3287
static int clean_shared_index_files(const char *current_hex)
3288
0
{
3289
0
  struct dirent *de;
3290
0
  DIR *dir = opendir(repo_get_git_dir(the_repository));
3291
3292
0
  if (!dir)
3293
0
    return error_errno(_("unable to open git dir: %s"),
3294
0
           repo_get_git_dir(the_repository));
3295
3296
0
  while ((de = readdir(dir)) != NULL) {
3297
0
    const char *sha1_hex;
3298
0
    char *shared_index_path;
3299
0
    if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
3300
0
      continue;
3301
0
    if (!strcmp(sha1_hex, current_hex))
3302
0
      continue;
3303
3304
0
    shared_index_path = repo_git_path(the_repository, "%s", de->d_name);
3305
0
    if (should_delete_shared_index(shared_index_path) > 0 &&
3306
0
        unlink(shared_index_path))
3307
0
      warning_errno(_("unable to unlink: %s"), shared_index_path);
3308
3309
0
    free(shared_index_path);
3310
0
  }
3311
0
  closedir(dir);
3312
3313
0
  return 0;
3314
0
}
3315
3316
static int write_shared_index(struct index_state *istate,
3317
            struct tempfile **temp, unsigned flags)
3318
0
{
3319
0
  struct split_index *si = istate->split_index;
3320
0
  int ret, was_full = !istate->sparse_index;
3321
0
  char *path;
3322
3323
0
  move_cache_to_base_index(istate);
3324
0
  convert_to_sparse(istate, 0);
3325
3326
0
  trace2_region_enter_printf("index", "shared/do_write_index",
3327
0
           the_repository, "%s", get_tempfile_path(*temp));
3328
0
  ret = do_write_index(si->base, *temp, WRITE_NO_EXTENSION, flags);
3329
0
  trace2_region_leave_printf("index", "shared/do_write_index",
3330
0
           the_repository, "%s", get_tempfile_path(*temp));
3331
3332
0
  if (was_full)
3333
0
    ensure_full_index(istate);
3334
3335
0
  if (ret)
3336
0
    return ret;
3337
0
  ret = adjust_shared_perm(the_repository, get_tempfile_path(*temp));
3338
0
  if (ret) {
3339
0
    error(_("cannot fix permission bits on '%s'"), get_tempfile_path(*temp));
3340
0
    return ret;
3341
0
  }
3342
3343
0
  path = repo_git_path(the_repository, "sharedindex.%s", oid_to_hex(&si->base->oid));
3344
0
  ret = rename_tempfile(temp, path);
3345
0
  if (!ret) {
3346
0
    oidcpy(&si->base_oid, &si->base->oid);
3347
0
    clean_shared_index_files(oid_to_hex(&si->base->oid));
3348
0
  }
3349
3350
0
  free(path);
3351
0
  return ret;
3352
0
}
3353
3354
static const int default_max_percent_split_change = 20;
3355
3356
static int too_many_not_shared_entries(struct index_state *istate)
3357
0
{
3358
0
  int i, not_shared = 0;
3359
0
  int max_split = repo_config_get_max_percent_split_change(the_repository);
3360
3361
0
  switch (max_split) {
3362
0
  case -1:
3363
    /* not or badly configured: use the default value */
3364
0
    max_split = default_max_percent_split_change;
3365
0
    break;
3366
0
  case 0:
3367
0
    return 1; /* 0% means always write a new shared index */
3368
0
  case 100:
3369
0
    return 0; /* 100% means never write a new shared index */
3370
0
  default:
3371
0
    break; /* just use the configured value */
3372
0
  }
3373
3374
  /* Count not shared entries */
3375
0
  for (i = 0; i < istate->cache_nr; i++) {
3376
0
    struct cache_entry *ce = istate->cache[i];
3377
0
    if (!ce->index)
3378
0
      not_shared++;
3379
0
  }
3380
3381
0
  return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
3382
0
}
3383
3384
int write_locked_index(struct index_state *istate, struct lock_file *lock,
3385
           unsigned flags)
3386
0
{
3387
0
  int new_shared_index, ret, test_split_index_env;
3388
0
  struct split_index *si = istate->split_index;
3389
3390
0
  if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0) &&
3391
0
      cache_tree_verify(the_repository, istate) < 0)
3392
0
    return -1;
3393
3394
0
  if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
3395
0
    if (flags & COMMIT_LOCK)
3396
0
      rollback_lock_file(lock);
3397
0
    return 0;
3398
0
  }
3399
3400
0
  if (istate->fsmonitor_last_update)
3401
0
    fill_fsmonitor_bitmap(istate);
3402
3403
0
  test_split_index_env = git_env_bool("GIT_TEST_SPLIT_INDEX", 0);
3404
3405
0
  if ((!si && !test_split_index_env) ||
3406
0
      alternate_index_output ||
3407
0
      (istate->cache_changed & ~EXTMASK)) {
3408
0
    ret = do_write_locked_index(istate, lock, flags,
3409
0
              ~WRITE_SPLIT_INDEX_EXTENSION);
3410
0
    goto out;
3411
0
  }
3412
3413
0
  if (test_split_index_env) {
3414
0
    if (!si) {
3415
0
      si = init_split_index(istate);
3416
0
      istate->cache_changed |= SPLIT_INDEX_ORDERED;
3417
0
    } else {
3418
0
      int v = si->base_oid.hash[0];
3419
0
      if ((v & 15) < 6)
3420
0
        istate->cache_changed |= SPLIT_INDEX_ORDERED;
3421
0
    }
3422
0
  }
3423
0
  if (too_many_not_shared_entries(istate))
3424
0
    istate->cache_changed |= SPLIT_INDEX_ORDERED;
3425
3426
0
  new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
3427
3428
0
  if (new_shared_index) {
3429
0
    struct tempfile *temp;
3430
0
    int saved_errno;
3431
0
    char *path;
3432
3433
    /* Same initial permissions as the main .git/index file */
3434
0
    path = repo_git_path(the_repository, "sharedindex_XXXXXX");
3435
0
    temp = mks_tempfile_sm(path, 0, 0666);
3436
0
    free(path);
3437
0
    if (!temp) {
3438
0
      ret = do_write_locked_index(istate, lock, flags,
3439
0
                ~WRITE_SPLIT_INDEX_EXTENSION);
3440
0
      goto out;
3441
0
    }
3442
0
    ret = write_shared_index(istate, &temp, flags);
3443
3444
0
    saved_errno = errno;
3445
0
    if (is_tempfile_active(temp))
3446
0
      delete_tempfile(&temp);
3447
0
    errno = saved_errno;
3448
3449
0
    if (ret)
3450
0
      goto out;
3451
0
  }
3452
3453
0
  ret = write_split_index(istate, lock, flags);
3454
3455
  /* Freshen the shared index only if the split-index was written */
3456
0
  if (!ret && !new_shared_index && !is_null_oid(&si->base_oid)) {
3457
0
    char *shared_index = repo_git_path(the_repository, "sharedindex.%s",
3458
0
               oid_to_hex(&si->base_oid));
3459
0
    freshen_shared_index(shared_index, 1);
3460
0
    free(shared_index);
3461
0
  }
3462
3463
0
out:
3464
0
  if (flags & COMMIT_LOCK)
3465
0
    rollback_lock_file(lock);
3466
0
  return ret;
3467
0
}
3468
3469
/*
3470
 * Read the index file that is potentially unmerged into given
3471
 * index_state, dropping any unmerged entries to stage #0 (potentially
3472
 * resulting in a path appearing as both a file and a directory in the
3473
 * index; the caller is responsible to clear out the extra entries
3474
 * before writing the index to a tree).  Returns true if the index is
3475
 * unmerged.  Callers who want to refuse to work from an unmerged
3476
 * state can call this and check its return value, instead of calling
3477
 * read_cache().
3478
 */
3479
int repo_read_index_unmerged(struct repository *repo)
3480
0
{
3481
0
  repo_read_index(repo);
3482
0
  return index_state_unmerged_to_stage0(repo->index);
3483
0
}
3484
3485
int index_state_unmerged_to_stage0(struct index_state *istate)
3486
0
{
3487
0
  int unmerged = 0;
3488
3489
0
  for (unsigned int i = 0; i < istate->cache_nr; i++) {
3490
0
    struct cache_entry *ce = istate->cache[i];
3491
0
    struct cache_entry *new_ce;
3492
0
    int len;
3493
3494
0
    if (!ce_stage(ce))
3495
0
      continue;
3496
0
    unmerged = 1;
3497
0
    len = ce_namelen(ce);
3498
0
    new_ce = make_empty_cache_entry(istate, len);
3499
0
    memcpy(new_ce->name, ce->name, len);
3500
0
    new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3501
0
    new_ce->ce_namelen = len;
3502
0
    new_ce->ce_mode = ce->ce_mode;
3503
0
    if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3504
0
      return error(_("%s: cannot drop to stage #0"),
3505
0
             new_ce->name);
3506
0
  }
3507
0
  return unmerged;
3508
0
}
3509
3510
/*
3511
 * Returns 1 if the path is an "other" path with respect to
3512
 * the index; that is, the path is not mentioned in the index at all,
3513
 * either as a file, a directory with some files in the index,
3514
 * or as an unmerged entry.
3515
 *
3516
 * We helpfully remove a trailing "/" from directories so that
3517
 * the output of read_directory can be used as-is.
3518
 */
3519
int index_name_is_other(struct index_state *istate, const char *name,
3520
      int namelen)
3521
0
{
3522
0
  int pos;
3523
0
  if (namelen && name[namelen - 1] == '/')
3524
0
    namelen--;
3525
0
  pos = index_name_pos(istate, name, namelen);
3526
0
  if (0 <= pos)
3527
0
    return 0; /* exact match */
3528
0
  pos = -pos - 1;
3529
0
  if (pos < istate->cache_nr) {
3530
0
    struct cache_entry *ce = istate->cache[pos];
3531
0
    if (ce_namelen(ce) == namelen &&
3532
0
        !memcmp(ce->name, name, namelen))
3533
0
      return 0; /* Yup, this one exists unmerged */
3534
0
  }
3535
0
  return 1;
3536
0
}
3537
3538
void *read_blob_data_from_index(struct index_state *istate,
3539
        const char *path, unsigned long *size)
3540
0
{
3541
0
  int pos, len;
3542
0
  size_t sz;
3543
0
  enum object_type type;
3544
0
  void *data;
3545
3546
0
  len = strlen(path);
3547
0
  pos = index_name_pos(istate, path, len);
3548
0
  if (pos < 0) {
3549
    /*
3550
     * We might be in the middle of a merge, in which
3551
     * case we would read stage #2 (ours).
3552
     */
3553
0
    int i;
3554
0
    for (i = -pos - 1;
3555
0
         (pos < 0 && i < istate->cache_nr &&
3556
0
          !strcmp(istate->cache[i]->name, path));
3557
0
         i++)
3558
0
      if (ce_stage(istate->cache[i]) == 2)
3559
0
        pos = i;
3560
0
  }
3561
0
  if (pos < 0)
3562
0
    return NULL;
3563
0
  data = odb_read_object(the_repository->objects, &istate->cache[pos]->oid,
3564
0
             &type, &sz);
3565
0
  if (!data || type != OBJ_BLOB) {
3566
0
    free(data);
3567
0
    return NULL;
3568
0
  }
3569
0
  if (size)
3570
0
    *size = cast_size_t_to_ulong(sz);
3571
0
  return data;
3572
0
}
3573
3574
void move_index_extensions(struct index_state *dst, struct index_state *src)
3575
0
{
3576
0
  dst->untracked = src->untracked;
3577
0
  src->untracked = NULL;
3578
0
  dst->cache_tree = src->cache_tree;
3579
0
  src->cache_tree = NULL;
3580
0
}
3581
3582
struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3583
            struct index_state *istate)
3584
0
{
3585
0
  unsigned int size = ce_size(ce);
3586
0
  int mem_pool_allocated;
3587
0
  struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3588
0
  mem_pool_allocated = new_entry->mem_pool_allocated;
3589
3590
0
  memcpy(new_entry, ce, size);
3591
0
  new_entry->mem_pool_allocated = mem_pool_allocated;
3592
0
  return new_entry;
3593
0
}
3594
3595
void discard_cache_entry(struct cache_entry *ce)
3596
0
{
3597
0
  if (ce && should_validate_cache_entries())
3598
0
    memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3599
3600
0
  if (ce && ce->mem_pool_allocated)
3601
0
    return;
3602
3603
0
  free(ce);
3604
0
}
3605
3606
int should_validate_cache_entries(void)
3607
0
{
3608
0
  static int validate_index_cache_entries = -1;
3609
3610
0
  if (validate_index_cache_entries < 0) {
3611
0
    if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3612
0
      validate_index_cache_entries = 1;
3613
0
    else
3614
0
      validate_index_cache_entries = 0;
3615
0
  }
3616
3617
0
  return validate_index_cache_entries;
3618
0
}
3619
3620
0
#define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3621
0
#define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3622
3623
static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3624
0
{
3625
  /*
3626
   * The end of index entries (EOIE) extension is guaranteed to be last
3627
   * so that it can be found by scanning backwards from the EOF.
3628
   *
3629
   * "EOIE"
3630
   * <4-byte length>
3631
   * <4-byte offset>
3632
   * <20-byte hash>
3633
   */
3634
0
  const char *index, *eoie;
3635
0
  uint32_t extsize;
3636
0
  size_t offset, src_offset;
3637
0
  unsigned char hash[GIT_MAX_RAWSZ];
3638
0
  struct git_hash_ctx c;
3639
3640
  /* ensure we have an index big enough to contain an EOIE extension */
3641
0
  if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3642
0
    return 0;
3643
3644
  /* validate the extension signature */
3645
0
  index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3646
0
  if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3647
0
    return 0;
3648
0
  index += sizeof(uint32_t);
3649
3650
  /* validate the extension size */
3651
0
  extsize = get_be32(index);
3652
0
  if (extsize != EOIE_SIZE)
3653
0
    return 0;
3654
0
  index += sizeof(uint32_t);
3655
3656
  /*
3657
   * Validate the offset we're going to look for the first extension
3658
   * signature is after the index header and before the eoie extension.
3659
   */
3660
0
  offset = get_be32(index);
3661
0
  if (mmap + offset < mmap + sizeof(struct cache_header))
3662
0
    return 0;
3663
0
  if (mmap + offset >= eoie)
3664
0
    return 0;
3665
0
  index += sizeof(uint32_t);
3666
3667
  /*
3668
   * The hash is computed over extension types and their sizes (but not
3669
   * their contents).  E.g. if we have "TREE" extension that is N-bytes
3670
   * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3671
   * then the hash would be:
3672
   *
3673
   * SHA-1("TREE" + <binary representation of N> +
3674
   *   "REUC" + <binary representation of M>)
3675
   */
3676
0
  src_offset = offset;
3677
0
  git_hash_init(&c, the_hash_algo);
3678
0
  while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3679
    /* After an array of active_nr index entries,
3680
     * there can be arbitrary number of extended
3681
     * sections, each of which is prefixed with
3682
     * extension name (4-byte) and section length
3683
     * in 4-byte network byte order.
3684
     */
3685
0
    uint32_t extsize;
3686
0
    memcpy(&extsize, mmap + src_offset + 4, 4);
3687
0
    extsize = ntohl(extsize);
3688
3689
    /* verify the extension size isn't so large it will wrap around */
3690
0
    if (src_offset + 8 + extsize < src_offset)
3691
0
      return 0;
3692
3693
0
    git_hash_update(&c, mmap + src_offset, 8);
3694
3695
0
    src_offset += 8;
3696
0
    src_offset += extsize;
3697
0
  }
3698
0
  git_hash_final(hash, &c);
3699
0
  if (!hasheq(hash, (const unsigned char *)index, the_repository->hash_algo))
3700
0
    return 0;
3701
3702
  /* Validate that the extension offsets returned us back to the eoie extension. */
3703
0
  if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3704
0
    return 0;
3705
3706
0
  return offset;
3707
0
}
3708
3709
static void write_eoie_extension(struct strbuf *sb, struct git_hash_ctx *eoie_context, size_t offset)
3710
0
{
3711
0
  uint32_t buffer;
3712
0
  unsigned char hash[GIT_MAX_RAWSZ];
3713
3714
  /* offset */
3715
0
  put_be32(&buffer, offset);
3716
0
  strbuf_add(sb, &buffer, sizeof(uint32_t));
3717
3718
  /* hash */
3719
0
  git_hash_final(hash, eoie_context);
3720
0
  strbuf_add(sb, hash, the_hash_algo->rawsz);
3721
0
}
3722
3723
0
#define IEOT_VERSION  (1)
3724
3725
static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3726
0
{
3727
0
  const char *index = NULL;
3728
0
  uint32_t extsize, ext_version;
3729
0
  struct index_entry_offset_table *ieot;
3730
0
  int i, nr;
3731
3732
  /* find the IEOT extension */
3733
0
  if (!offset)
3734
0
    return NULL;
3735
0
  while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3736
0
    extsize = get_be32(mmap + offset + 4);
3737
0
    if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3738
0
      index = mmap + offset + 4 + 4;
3739
0
      break;
3740
0
    }
3741
0
    offset += 8;
3742
0
    offset += extsize;
3743
0
  }
3744
0
  if (!index)
3745
0
    return NULL;
3746
3747
  /* validate the version is IEOT_VERSION */
3748
0
  ext_version = get_be32(index);
3749
0
  if (ext_version != IEOT_VERSION) {
3750
0
    error("invalid IEOT version %d", ext_version);
3751
0
    return NULL;
3752
0
  }
3753
0
  index += sizeof(uint32_t);
3754
3755
  /* extension size - version bytes / bytes per entry */
3756
0
  nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3757
0
  if (!nr) {
3758
0
    error("invalid number of IEOT entries %d", nr);
3759
0
    return NULL;
3760
0
  }
3761
0
  ieot = xmalloc(sizeof(struct index_entry_offset_table)
3762
0
           + (nr * sizeof(struct index_entry_offset)));
3763
0
  ieot->nr = nr;
3764
0
  for (i = 0; i < nr; i++) {
3765
0
    ieot->entries[i].offset = get_be32(index);
3766
0
    index += sizeof(uint32_t);
3767
0
    ieot->entries[i].nr = get_be32(index);
3768
0
    index += sizeof(uint32_t);
3769
0
  }
3770
3771
0
  return ieot;
3772
0
}
3773
3774
static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3775
0
{
3776
0
  uint32_t buffer;
3777
0
  int i;
3778
3779
  /* version */
3780
0
  put_be32(&buffer, IEOT_VERSION);
3781
0
  strbuf_add(sb, &buffer, sizeof(uint32_t));
3782
3783
  /* ieot */
3784
0
  for (i = 0; i < ieot->nr; i++) {
3785
3786
    /* offset */
3787
0
    put_be32(&buffer, ieot->entries[i].offset);
3788
0
    strbuf_add(sb, &buffer, sizeof(uint32_t));
3789
3790
    /* count */
3791
0
    put_be32(&buffer, ieot->entries[i].nr);
3792
0
    strbuf_add(sb, &buffer, sizeof(uint32_t));
3793
0
  }
3794
0
}
3795
3796
void prefetch_cache_entries(const struct index_state *istate,
3797
          must_prefetch_predicate must_prefetch,
3798
          void *cb_data)
3799
0
{
3800
0
  int i;
3801
0
  struct oid_array to_fetch = OID_ARRAY_INIT;
3802
3803
0
  for (i = 0; i < istate->cache_nr; i++) {
3804
0
    struct cache_entry *ce = istate->cache[i];
3805
3806
0
    if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce, cb_data))
3807
0
      continue;
3808
0
    if (!odb_read_object_info_extended(the_repository->objects,
3809
0
               &ce->oid, NULL,
3810
0
               OBJECT_INFO_FOR_PREFETCH))
3811
0
      continue;
3812
0
    oid_array_append(&to_fetch, &ce->oid);
3813
0
  }
3814
0
  promisor_remote_get_direct(the_repository,
3815
0
           to_fetch.oid, to_fetch.nr);
3816
0
  oid_array_clear(&to_fetch);
3817
0
}
3818
3819
static int read_one_entry_opt(struct index_state *istate,
3820
            const struct object_id *oid,
3821
            struct strbuf *base,
3822
            const char *pathname,
3823
            unsigned mode, int opt)
3824
0
{
3825
0
  size_t len;
3826
0
  struct cache_entry *ce;
3827
3828
0
  if (S_ISDIR(mode))
3829
0
    return READ_TREE_RECURSIVE;
3830
3831
0
  len = strlen(pathname);
3832
0
  ce = make_empty_cache_entry(istate, st_add(base->len, len));
3833
3834
0
  ce->ce_mode = create_ce_mode(mode);
3835
0
  ce->ce_flags = create_ce_flags(1);
3836
0
  ce->ce_namelen = base->len + len;
3837
0
  memcpy(ce->name, base->buf, base->len);
3838
0
  memcpy(ce->name + base->len, pathname, len+1);
3839
0
  oidcpy(&ce->oid, oid);
3840
0
  return add_index_entry(istate, ce, opt);
3841
0
}
3842
3843
static int read_one_entry(const struct object_id *oid, struct strbuf *base,
3844
        const char *pathname, unsigned mode,
3845
        void *context)
3846
0
{
3847
0
  struct index_state *istate = context;
3848
0
  return read_one_entry_opt(istate, oid, base, pathname,
3849
0
          mode,
3850
0
          ADD_CACHE_OK_TO_ADD|ADD_CACHE_SKIP_DFCHECK);
3851
0
}
3852
3853
/*
3854
 * This is used when the caller knows there is no existing entries at
3855
 * the stage that will conflict with the entry being added.
3856
 */
3857
static int read_one_entry_quick(const struct object_id *oid, struct strbuf *base,
3858
        const char *pathname, unsigned mode,
3859
        void *context)
3860
0
{
3861
0
  struct index_state *istate = context;
3862
0
  return read_one_entry_opt(istate, oid, base, pathname,
3863
0
          mode, ADD_CACHE_JUST_APPEND);
3864
0
}
3865
3866
/*
3867
 * Read the tree specified with --with-tree option
3868
 * (typically, HEAD) into stage #1 and then
3869
 * squash them down to stage #0.  This is used for
3870
 * --error-unmatch to list and check the path patterns
3871
 * that were given from the command line.  We are not
3872
 * going to write this index out.
3873
 */
3874
void overlay_tree_on_index(struct index_state *istate,
3875
         const char *tree_name, const char *prefix)
3876
0
{
3877
0
  struct tree *tree;
3878
0
  struct object_id oid;
3879
0
  struct pathspec pathspec;
3880
0
  struct cache_entry *last_stage0 = NULL;
3881
0
  int i;
3882
0
  read_tree_fn_t fn = NULL;
3883
0
  int err;
3884
3885
0
  if (repo_get_oid(the_repository, tree_name, &oid))
3886
0
    die("tree-ish %s not found.", tree_name);
3887
0
  tree = repo_parse_tree_indirect(the_repository, &oid);
3888
0
  if (!tree)
3889
0
    die("bad tree-ish %s", tree_name);
3890
3891
  /* Hoist the unmerged entries up to stage #3 to make room */
3892
  /* TODO: audit for interaction with sparse-index. */
3893
0
  ensure_full_index(istate);
3894
0
  for (i = 0; i < istate->cache_nr; i++) {
3895
0
    struct cache_entry *ce = istate->cache[i];
3896
0
    if (!ce_stage(ce))
3897
0
      continue;
3898
0
    ce->ce_flags |= CE_STAGEMASK;
3899
0
  }
3900
3901
0
  if (prefix) {
3902
0
    static const char *(matchbuf[1]);
3903
0
    matchbuf[0] = NULL;
3904
0
    parse_pathspec(&pathspec, PATHSPEC_ALL_MAGIC,
3905
0
             PATHSPEC_PREFER_CWD, prefix, matchbuf);
3906
0
  } else
3907
0
    memset(&pathspec, 0, sizeof(pathspec));
3908
3909
  /*
3910
   * See if we have cache entry at the stage.  If so,
3911
   * do it the original slow way, otherwise, append and then
3912
   * sort at the end.
3913
   */
3914
0
  for (i = 0; !fn && i < istate->cache_nr; i++) {
3915
0
    const struct cache_entry *ce = istate->cache[i];
3916
0
    if (ce_stage(ce) == 1)
3917
0
      fn = read_one_entry;
3918
0
  }
3919
3920
0
  if (!fn)
3921
0
    fn = read_one_entry_quick;
3922
0
  err = read_tree(the_repository, tree, &pathspec, fn, istate);
3923
0
  clear_pathspec(&pathspec);
3924
0
  if (err)
3925
0
    die("unable to read tree entries %s", tree_name);
3926
3927
  /*
3928
   * Sort the cache entry -- we need to nuke the cache tree, though.
3929
   */
3930
0
  if (fn == read_one_entry_quick) {
3931
0
    cache_tree_free(&istate->cache_tree);
3932
0
    QSORT(istate->cache, istate->cache_nr, cmp_cache_name_compare);
3933
0
  }
3934
3935
0
  for (i = 0; i < istate->cache_nr; i++) {
3936
0
    struct cache_entry *ce = istate->cache[i];
3937
0
    switch (ce_stage(ce)) {
3938
0
    case 0:
3939
0
      last_stage0 = ce;
3940
      /* fallthru */
3941
0
    default:
3942
0
      continue;
3943
0
    case 1:
3944
      /*
3945
       * If there is stage #0 entry for this, we do not
3946
       * need to show it.  We use CE_UPDATE bit to mark
3947
       * such an entry.
3948
       */
3949
0
      if (last_stage0 &&
3950
0
          !strcmp(last_stage0->name, ce->name))
3951
0
        ce->ce_flags |= CE_UPDATE;
3952
0
    }
3953
0
  }
3954
0
}
3955
3956
struct update_callback_data {
3957
  struct index_state *index;
3958
  struct repository *repo;
3959
  struct pathspec *pathspec;
3960
  int include_sparse;
3961
  int flags;
3962
  int add_errors;
3963
  int ignored_too;
3964
};
3965
3966
static int fix_unmerged_status(struct diff_filepair *p,
3967
             struct update_callback_data *data)
3968
0
{
3969
0
  if (p->status != DIFF_STATUS_UNMERGED)
3970
0
    return p->status;
3971
0
  if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
3972
    /*
3973
     * This is not an explicit add request, and the
3974
     * path is missing from the working tree (deleted)
3975
     */
3976
0
    return DIFF_STATUS_DELETED;
3977
0
  else
3978
    /*
3979
     * Either an explicit add request, or path exists
3980
     * in the working tree.  An attempt to explicitly
3981
     * add a path that does not exist in the working tree
3982
     * will be caught as an error by the caller immediately.
3983
     */
3984
0
    return DIFF_STATUS_MODIFIED;
3985
0
}
3986
3987
static int skip_submodule(const char *path,
3988
        struct repository *repo,
3989
        struct pathspec *pathspec,
3990
        int ignored_too)
3991
0
{
3992
0
  struct stat st;
3993
0
  const struct submodule *sub;
3994
0
  int pathspec_matches = 0;
3995
0
  int ps_i;
3996
0
  char *norm_pathspec = NULL;
3997
3998
  /* Only consider if path is a directory */
3999
0
  if (lstat(path, &st) || !S_ISDIR(st.st_mode))
4000
0
    return 0;
4001
4002
  /* Check if it's a submodule with ignore=all */
4003
0
  sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
4004
0
  if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
4005
0
    return 0;
4006
4007
0
  trace_printf("ignore=all: %s\n", path);
4008
0
  trace_printf("pathspec %s\n",
4009
0
         ((pathspec && pathspec->nr)
4010
0
          ? "has pathspec"
4011
0
          : "no pathspec"));
4012
4013
  /* Check if submodule path is explicitly mentioned in pathspec */
4014
0
  if (pathspec) {
4015
0
    for (ps_i = 0; ps_i < pathspec->nr; ps_i++) {
4016
0
      const char *m = pathspec->items[ps_i].match;
4017
0
      if (!m)
4018
0
        continue;
4019
0
      norm_pathspec = xstrdup(m);
4020
0
      strip_dir_trailing_slashes(norm_pathspec);
4021
0
      if (!strcmp(path, norm_pathspec)) {
4022
0
        pathspec_matches = 1;
4023
0
        FREE_AND_NULL(norm_pathspec);
4024
0
        break;
4025
0
      }
4026
0
      FREE_AND_NULL(norm_pathspec);
4027
0
    }
4028
0
  }
4029
4030
  /* If explicitly matched and forced, allow adding */
4031
0
  if (pathspec_matches) {
4032
0
    if (ignored_too && ignored_too > 0) {
4033
0
      trace_printf("Add submodule due to --force: %s\n", path);
4034
0
      return 0;
4035
0
    } else {
4036
0
      advise_if_enabled(ADVICE_ADD_IGNORED_FILE,
4037
0
          _("Skipping submodule due to ignore=all: %s\n"
4038
0
            "Use --force if you really want to "
4039
0
            "add the submodule."), path);
4040
0
      return 1;
4041
0
    }
4042
0
  }
4043
4044
  /* No explicit pathspec match -> skip silently */
4045
0
  trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
4046
0
  return 1;
4047
0
}
4048
4049
static void update_callback(struct diff_queue_struct *q,
4050
          struct diff_options *opt UNUSED, void *cbdata)
4051
0
{
4052
0
  int i;
4053
0
  struct update_callback_data *data = cbdata;
4054
4055
0
  for (i = 0; i < q->nr; i++) {
4056
0
    struct diff_filepair *p = q->queue[i];
4057
0
    const char *path = p->one->path;
4058
4059
0
    if (!data->include_sparse &&
4060
0
        !path_in_sparse_checkout(path, data->index))
4061
0
      continue;
4062
4063
0
    switch (fix_unmerged_status(p, data)) {
4064
0
    default:
4065
0
      die(_("unexpected diff status %c"), p->status);
4066
0
    case DIFF_STATUS_MODIFIED:
4067
0
    case DIFF_STATUS_TYPE_CHANGED:
4068
0
      if (skip_submodule(path, data->repo,
4069
0
             data->pathspec,
4070
0
             data->ignored_too))
4071
0
        continue;
4072
4073
0
      if (add_file_to_index(data->index, path, data->flags)) {
4074
0
        if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
4075
0
          die(_("updating files failed"));
4076
0
        data->add_errors++;
4077
0
      }
4078
0
      break;
4079
0
    case DIFF_STATUS_DELETED:
4080
0
      if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
4081
0
        break;
4082
0
      remove_file_from_index_with_flags(data->index, path, data->flags);
4083
0
      break;
4084
0
    }
4085
0
  }
4086
0
}
4087
4088
int add_files_to_cache(struct repository *repo, const char *prefix,
4089
           const struct pathspec *pathspec, char *ps_matched,
4090
           int include_sparse, int flags, int ignored_too )
4091
0
{
4092
0
  int inflight = !!repo->objects->transaction;
4093
0
  struct odb_transaction *transaction;
4094
0
  struct update_callback_data data;
4095
0
  struct rev_info rev;
4096
4097
0
  memset(&data, 0, sizeof(data));
4098
0
  data.index = repo->index;
4099
0
  data.include_sparse = include_sparse;
4100
0
  data.flags = flags;
4101
0
  data.repo = repo;
4102
0
  data.ignored_too = ignored_too;
4103
0
  data.pathspec = (struct pathspec *)pathspec;
4104
4105
0
  repo_init_revisions(repo, &rev, prefix);
4106
0
  setup_revisions(0, NULL, &rev, NULL);
4107
0
  if (pathspec) {
4108
0
    copy_pathspec(&rev.prune_data, pathspec);
4109
0
    rev.ps_matched = ps_matched;
4110
0
  }
4111
0
  rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
4112
0
  rev.diffopt.format_callback = update_callback;
4113
0
  rev.diffopt.format_callback_data = &data;
4114
0
  rev.diffopt.flags.override_submodule_config = 1;
4115
0
  rev.diffopt.detect_rename = 0; /* staging worktree changes does not need renames */
4116
0
  rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
4117
4118
  /*
4119
   * Use an ODB transaction to optimize adding multiple objects.
4120
   * This function is invoked from commands other than 'add', which
4121
   * may not have their own transaction active.
4122
   */
4123
0
  if (!inflight)
4124
0
    odb_transaction_begin_or_die(repo->objects, &transaction, 0);
4125
0
  run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
4126
0
  if (!inflight)
4127
0
    odb_transaction_commit_and_finalize_or_die(transaction);
4128
4129
0
  release_revisions(&rev);
4130
0
  return !!data.add_errors;
4131
0
}