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