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