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