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