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