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