Merge branch 'ab/remove-implicit-use-of-the-repository'
[git.git] / read-cache.c
blob27e4f5ccb33841685129967926fb30f4b3237d4d
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "cache.h"
7 #include "alloc.h"
8 #include "config.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "hex.h"
12 #include "tempfile.h"
13 #include "lockfile.h"
14 #include "cache-tree.h"
15 #include "refs.h"
16 #include "dir.h"
17 #include "object-store.h"
18 #include "tree.h"
19 #include "commit.h"
20 #include "blob.h"
21 #include "resolve-undo.h"
22 #include "run-command.h"
23 #include "strbuf.h"
24 #include "varint.h"
25 #include "split-index.h"
26 #include "utf8.h"
27 #include "fsmonitor.h"
28 #include "thread-utils.h"
29 #include "progress.h"
30 #include "sparse-index.h"
31 #include "csum-file.h"
32 #include "promisor-remote.h"
33 #include "hook.h"
35 /* Mask for the name length in ce_flags in the on-disk index */
37 #define CE_NAMEMASK (0x0fff)
39 /* Index extensions.
41 * The first letter should be 'A'..'Z' for extensions that are not
42 * necessary for a correct operation (i.e. optimization data).
43 * When new extensions are added that _needs_ to be understood in
44 * order to correctly interpret the index file, pick character that
45 * is outside the range, to cause the reader to abort.
48 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
49 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
50 #define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
51 #define CACHE_EXT_LINK 0x6c696e6b /* "link" */
52 #define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
53 #define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
54 #define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945 /* "EOIE" */
55 #define CACHE_EXT_INDEXENTRYOFFSETTABLE 0x49454F54 /* "IEOT" */
56 #define CACHE_EXT_SPARSE_DIRECTORIES 0x73646972 /* "sdir" */
58 /* changes that can be kept in $GIT_DIR/index (basically all extensions) */
59 #define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
60 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
61 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
65 * This is an estimate of the pathname length in the index. We use
66 * this for V4 index files to guess the un-deltafied size of the index
67 * in memory because of pathname deltafication. This is not required
68 * for V2/V3 index formats because their pathnames are not compressed.
69 * If the initial amount of memory set aside is not sufficient, the
70 * mem pool will allocate extra memory.
72 #define CACHE_ENTRY_PATH_LENGTH 80
74 enum index_search_mode {
75 NO_EXPAND_SPARSE = 0,
76 EXPAND_SPARSE = 1
79 static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
81 struct cache_entry *ce;
82 ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
83 ce->mem_pool_allocated = 1;
84 return ce;
87 static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
89 struct cache_entry * ce;
90 ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
91 ce->mem_pool_allocated = 1;
92 return ce;
95 static struct mem_pool *find_mem_pool(struct index_state *istate)
97 struct mem_pool **pool_ptr;
99 if (istate->split_index && istate->split_index->base)
100 pool_ptr = &istate->split_index->base->ce_mem_pool;
101 else
102 pool_ptr = &istate->ce_mem_pool;
104 if (!*pool_ptr) {
105 *pool_ptr = xmalloc(sizeof(**pool_ptr));
106 mem_pool_init(*pool_ptr, 0);
109 return *pool_ptr;
112 static const char *alternate_index_output;
114 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
116 if (S_ISSPARSEDIR(ce->ce_mode))
117 istate->sparse_index = INDEX_COLLAPSED;
119 istate->cache[nr] = ce;
120 add_name_hash(istate, ce);
123 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
125 struct cache_entry *old = istate->cache[nr];
127 replace_index_entry_in_base(istate, old, ce);
128 remove_name_hash(istate, old);
129 discard_cache_entry(old);
130 ce->ce_flags &= ~CE_HASHED;
131 set_index_entry(istate, nr, ce);
132 ce->ce_flags |= CE_UPDATE_IN_BASE;
133 mark_fsmonitor_invalid(istate, ce);
134 istate->cache_changed |= CE_ENTRY_CHANGED;
137 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
139 struct cache_entry *old_entry = istate->cache[nr], *new_entry, *refreshed;
140 int namelen = strlen(new_name);
142 new_entry = make_empty_cache_entry(istate, namelen);
143 copy_cache_entry(new_entry, old_entry);
144 new_entry->ce_flags &= ~CE_HASHED;
145 new_entry->ce_namelen = namelen;
146 new_entry->index = 0;
147 memcpy(new_entry->name, new_name, namelen + 1);
149 cache_tree_invalidate_path(istate, old_entry->name);
150 untracked_cache_remove_from_index(istate, old_entry->name);
151 remove_index_entry_at(istate, nr);
154 * Refresh the new index entry. Using 'refresh_cache_entry' ensures
155 * we only update stat info if the entry is otherwise up-to-date (i.e.,
156 * the contents/mode haven't changed). This ensures that we reflect the
157 * 'ctime' of the rename in the index without (incorrectly) updating
158 * the cached stat info to reflect unstaged changes on disk.
160 refreshed = refresh_cache_entry(istate, new_entry, CE_MATCH_REFRESH);
161 if (refreshed && refreshed != new_entry) {
162 add_index_entry(istate, refreshed, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
163 discard_cache_entry(new_entry);
164 } else
165 add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
168 void fill_stat_data(struct stat_data *sd, struct stat *st)
170 sd->sd_ctime.sec = (unsigned int)st->st_ctime;
171 sd->sd_mtime.sec = (unsigned int)st->st_mtime;
172 sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
173 sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
174 sd->sd_dev = st->st_dev;
175 sd->sd_ino = st->st_ino;
176 sd->sd_uid = st->st_uid;
177 sd->sd_gid = st->st_gid;
178 sd->sd_size = st->st_size;
181 int match_stat_data(const struct stat_data *sd, struct stat *st)
183 int changed = 0;
185 if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
186 changed |= MTIME_CHANGED;
187 if (trust_ctime && check_stat &&
188 sd->sd_ctime.sec != (unsigned int)st->st_ctime)
189 changed |= CTIME_CHANGED;
191 #ifdef USE_NSEC
192 if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
193 changed |= MTIME_CHANGED;
194 if (trust_ctime && check_stat &&
195 sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
196 changed |= CTIME_CHANGED;
197 #endif
199 if (check_stat) {
200 if (sd->sd_uid != (unsigned int) st->st_uid ||
201 sd->sd_gid != (unsigned int) st->st_gid)
202 changed |= OWNER_CHANGED;
203 if (sd->sd_ino != (unsigned int) st->st_ino)
204 changed |= INODE_CHANGED;
207 #ifdef USE_STDEV
209 * st_dev breaks on network filesystems where different
210 * clients will have different views of what "device"
211 * the filesystem is on
213 if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
214 changed |= INODE_CHANGED;
215 #endif
217 if (sd->sd_size != (unsigned int) st->st_size)
218 changed |= DATA_CHANGED;
220 return changed;
224 * This only updates the "non-critical" parts of the directory
225 * cache, ie the parts that aren't tracked by GIT, and only used
226 * to validate the cache.
228 void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st)
230 fill_stat_data(&ce->ce_stat_data, st);
232 if (assume_unchanged)
233 ce->ce_flags |= CE_VALID;
235 if (S_ISREG(st->st_mode)) {
236 ce_mark_uptodate(ce);
237 mark_fsmonitor_valid(istate, ce);
241 static int ce_compare_data(struct index_state *istate,
242 const struct cache_entry *ce,
243 struct stat *st)
245 int match = -1;
246 int fd = git_open_cloexec(ce->name, O_RDONLY);
248 if (fd >= 0) {
249 struct object_id oid;
250 if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
251 match = !oideq(&oid, &ce->oid);
252 /* index_fd() closed the file descriptor already */
254 return match;
257 static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
259 int match = -1;
260 void *buffer;
261 unsigned long size;
262 enum object_type type;
263 struct strbuf sb = STRBUF_INIT;
265 if (strbuf_readlink(&sb, ce->name, expected_size))
266 return -1;
268 buffer = repo_read_object_file(the_repository, &ce->oid, &type, &size);
269 if (buffer) {
270 if (size == sb.len)
271 match = memcmp(buffer, sb.buf, size);
272 free(buffer);
274 strbuf_release(&sb);
275 return match;
278 static int ce_compare_gitlink(const struct cache_entry *ce)
280 struct object_id oid;
283 * We don't actually require that the .git directory
284 * under GITLINK directory be a valid git directory. It
285 * might even be missing (in case nobody populated that
286 * sub-project).
288 * If so, we consider it always to match.
290 if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
291 return 0;
292 return !oideq(&oid, &ce->oid);
295 static int ce_modified_check_fs(struct index_state *istate,
296 const struct cache_entry *ce,
297 struct stat *st)
299 switch (st->st_mode & S_IFMT) {
300 case S_IFREG:
301 if (ce_compare_data(istate, ce, st))
302 return DATA_CHANGED;
303 break;
304 case S_IFLNK:
305 if (ce_compare_link(ce, xsize_t(st->st_size)))
306 return DATA_CHANGED;
307 break;
308 case S_IFDIR:
309 if (S_ISGITLINK(ce->ce_mode))
310 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
311 /* else fallthrough */
312 default:
313 return TYPE_CHANGED;
315 return 0;
318 static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
320 unsigned int changed = 0;
322 if (ce->ce_flags & CE_REMOVE)
323 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
325 switch (ce->ce_mode & S_IFMT) {
326 case S_IFREG:
327 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
328 /* We consider only the owner x bit to be relevant for
329 * "mode changes"
331 if (trust_executable_bit &&
332 (0100 & (ce->ce_mode ^ st->st_mode)))
333 changed |= MODE_CHANGED;
334 break;
335 case S_IFLNK:
336 if (!S_ISLNK(st->st_mode) &&
337 (has_symlinks || !S_ISREG(st->st_mode)))
338 changed |= TYPE_CHANGED;
339 break;
340 case S_IFGITLINK:
341 /* We ignore most of the st_xxx fields for gitlinks */
342 if (!S_ISDIR(st->st_mode))
343 changed |= TYPE_CHANGED;
344 else if (ce_compare_gitlink(ce))
345 changed |= DATA_CHANGED;
346 return changed;
347 default:
348 BUG("unsupported ce_mode: %o", ce->ce_mode);
351 changed |= match_stat_data(&ce->ce_stat_data, st);
353 /* Racily smudged entry? */
354 if (!ce->ce_stat_data.sd_size) {
355 if (!is_empty_blob_sha1(ce->oid.hash))
356 changed |= DATA_CHANGED;
359 return changed;
362 static int is_racy_stat(const struct index_state *istate,
363 const struct stat_data *sd)
365 return (istate->timestamp.sec &&
366 #ifdef USE_NSEC
367 /* nanosecond timestamped files can also be racy! */
368 (istate->timestamp.sec < sd->sd_mtime.sec ||
369 (istate->timestamp.sec == sd->sd_mtime.sec &&
370 istate->timestamp.nsec <= sd->sd_mtime.nsec))
371 #else
372 istate->timestamp.sec <= sd->sd_mtime.sec
373 #endif
377 int is_racy_timestamp(const struct index_state *istate,
378 const struct cache_entry *ce)
380 return (!S_ISGITLINK(ce->ce_mode) &&
381 is_racy_stat(istate, &ce->ce_stat_data));
384 int match_stat_data_racy(const struct index_state *istate,
385 const struct stat_data *sd, struct stat *st)
387 if (is_racy_stat(istate, sd))
388 return MTIME_CHANGED;
389 return match_stat_data(sd, st);
392 int ie_match_stat(struct index_state *istate,
393 const struct cache_entry *ce, struct stat *st,
394 unsigned int options)
396 unsigned int changed;
397 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
398 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
399 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
400 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
402 if (!ignore_fsmonitor)
403 refresh_fsmonitor(istate);
405 * If it's marked as always valid in the index, it's
406 * valid whatever the checked-out copy says.
408 * skip-worktree has the same effect with higher precedence
410 if (!ignore_skip_worktree && ce_skip_worktree(ce))
411 return 0;
412 if (!ignore_valid && (ce->ce_flags & CE_VALID))
413 return 0;
414 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
415 return 0;
418 * Intent-to-add entries have not been added, so the index entry
419 * by definition never matches what is in the work tree until it
420 * actually gets added.
422 if (ce_intent_to_add(ce))
423 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
425 changed = ce_match_stat_basic(ce, st);
428 * Within 1 second of this sequence:
429 * echo xyzzy >file && git-update-index --add file
430 * running this command:
431 * echo frotz >file
432 * would give a falsely clean cache entry. The mtime and
433 * length match the cache, and other stat fields do not change.
435 * We could detect this at update-index time (the cache entry
436 * being registered/updated records the same time as "now")
437 * and delay the return from git-update-index, but that would
438 * effectively mean we can make at most one commit per second,
439 * which is not acceptable. Instead, we check cache entries
440 * whose mtime are the same as the index file timestamp more
441 * carefully than others.
443 if (!changed && is_racy_timestamp(istate, ce)) {
444 if (assume_racy_is_modified)
445 changed |= DATA_CHANGED;
446 else
447 changed |= ce_modified_check_fs(istate, ce, st);
450 return changed;
453 int ie_modified(struct index_state *istate,
454 const struct cache_entry *ce,
455 struct stat *st, unsigned int options)
457 int changed, changed_fs;
459 changed = ie_match_stat(istate, ce, st, options);
460 if (!changed)
461 return 0;
463 * If the mode or type has changed, there's no point in trying
464 * to refresh the entry - it's not going to match
466 if (changed & (MODE_CHANGED | TYPE_CHANGED))
467 return changed;
470 * Immediately after read-tree or update-index --cacheinfo,
471 * the length field is zero, as we have never even read the
472 * lstat(2) information once, and we cannot trust DATA_CHANGED
473 * returned by ie_match_stat() which in turn was returned by
474 * ce_match_stat_basic() to signal that the filesize of the
475 * blob changed. We have to actually go to the filesystem to
476 * see if the contents match, and if so, should answer "unchanged".
478 * The logic does not apply to gitlinks, as ce_match_stat_basic()
479 * already has checked the actual HEAD from the filesystem in the
480 * subproject. If ie_match_stat() already said it is different,
481 * then we know it is.
483 if ((changed & DATA_CHANGED) &&
484 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
485 return changed;
487 changed_fs = ce_modified_check_fs(istate, ce, st);
488 if (changed_fs)
489 return changed | changed_fs;
490 return 0;
493 int base_name_compare(const char *name1, size_t len1, int mode1,
494 const char *name2, size_t len2, int mode2)
496 unsigned char c1, c2;
497 size_t len = len1 < len2 ? len1 : len2;
498 int cmp;
500 cmp = memcmp(name1, name2, len);
501 if (cmp)
502 return cmp;
503 c1 = name1[len];
504 c2 = name2[len];
505 if (!c1 && S_ISDIR(mode1))
506 c1 = '/';
507 if (!c2 && S_ISDIR(mode2))
508 c2 = '/';
509 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
513 * df_name_compare() is identical to base_name_compare(), except it
514 * compares conflicting directory/file entries as equal. Note that
515 * while a directory name compares as equal to a regular file, they
516 * then individually compare _differently_ to a filename that has
517 * a dot after the basename (because '\0' < '.' < '/').
519 * This is used by routines that want to traverse the git namespace
520 * but then handle conflicting entries together when possible.
522 int df_name_compare(const char *name1, size_t len1, int mode1,
523 const char *name2, size_t len2, int mode2)
525 unsigned char c1, c2;
526 size_t len = len1 < len2 ? len1 : len2;
527 int cmp;
529 cmp = memcmp(name1, name2, len);
530 if (cmp)
531 return cmp;
532 /* Directories and files compare equal (same length, same name) */
533 if (len1 == len2)
534 return 0;
535 c1 = name1[len];
536 if (!c1 && S_ISDIR(mode1))
537 c1 = '/';
538 c2 = name2[len];
539 if (!c2 && S_ISDIR(mode2))
540 c2 = '/';
541 if (c1 == '/' && !c2)
542 return 0;
543 if (c2 == '/' && !c1)
544 return 0;
545 return c1 - c2;
548 int name_compare(const char *name1, size_t len1, const char *name2, size_t len2)
550 size_t min_len = (len1 < len2) ? len1 : len2;
551 int cmp = memcmp(name1, name2, min_len);
552 if (cmp)
553 return cmp;
554 if (len1 < len2)
555 return -1;
556 if (len1 > len2)
557 return 1;
558 return 0;
561 int cache_name_stage_compare(const char *name1, int len1, int stage1, const char *name2, int len2, int stage2)
563 int cmp;
565 cmp = name_compare(name1, len1, name2, len2);
566 if (cmp)
567 return cmp;
569 if (stage1 < stage2)
570 return -1;
571 if (stage1 > stage2)
572 return 1;
573 return 0;
576 static int index_name_stage_pos(struct index_state *istate,
577 const char *name, int namelen,
578 int stage,
579 enum index_search_mode search_mode)
581 int first, last;
583 first = 0;
584 last = istate->cache_nr;
585 while (last > first) {
586 int next = first + ((last - first) >> 1);
587 struct cache_entry *ce = istate->cache[next];
588 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
589 if (!cmp)
590 return next;
591 if (cmp < 0) {
592 last = next;
593 continue;
595 first = next+1;
598 if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
599 first > 0) {
600 /* Note: first <= istate->cache_nr */
601 struct cache_entry *ce = istate->cache[first - 1];
604 * If we are in a sparse-index _and_ the entry before the
605 * insertion position is a sparse-directory entry that is
606 * an ancestor of 'name', then we need to expand the index
607 * and search again. This will only trigger once, because
608 * thereafter the index is fully expanded.
610 if (S_ISSPARSEDIR(ce->ce_mode) &&
611 ce_namelen(ce) < namelen &&
612 !strncmp(name, ce->name, ce_namelen(ce))) {
613 ensure_full_index(istate);
614 return index_name_stage_pos(istate, name, namelen, stage, search_mode);
618 return -first-1;
621 int index_name_pos(struct index_state *istate, const char *name, int namelen)
623 return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
626 int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
628 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
631 int index_entry_exists(struct index_state *istate, const char *name, int namelen)
633 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
636 int remove_index_entry_at(struct index_state *istate, int pos)
638 struct cache_entry *ce = istate->cache[pos];
640 record_resolve_undo(istate, ce);
641 remove_name_hash(istate, ce);
642 save_or_free_index_entry(istate, ce);
643 istate->cache_changed |= CE_ENTRY_REMOVED;
644 istate->cache_nr--;
645 if (pos >= istate->cache_nr)
646 return 0;
647 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
648 istate->cache_nr - pos);
649 return 1;
653 * Remove all cache entries marked for removal, that is where
654 * CE_REMOVE is set in ce_flags. This is much more effective than
655 * calling remove_index_entry_at() for each entry to be removed.
657 void remove_marked_cache_entries(struct index_state *istate, int invalidate)
659 struct cache_entry **ce_array = istate->cache;
660 unsigned int i, j;
662 for (i = j = 0; i < istate->cache_nr; i++) {
663 if (ce_array[i]->ce_flags & CE_REMOVE) {
664 if (invalidate) {
665 cache_tree_invalidate_path(istate,
666 ce_array[i]->name);
667 untracked_cache_remove_from_index(istate,
668 ce_array[i]->name);
670 remove_name_hash(istate, ce_array[i]);
671 save_or_free_index_entry(istate, ce_array[i]);
673 else
674 ce_array[j++] = ce_array[i];
676 if (j == istate->cache_nr)
677 return;
678 istate->cache_changed |= CE_ENTRY_REMOVED;
679 istate->cache_nr = j;
682 int remove_file_from_index(struct index_state *istate, const char *path)
684 int pos = index_name_pos(istate, path, strlen(path));
685 if (pos < 0)
686 pos = -pos-1;
687 cache_tree_invalidate_path(istate, path);
688 untracked_cache_remove_from_index(istate, path);
689 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
690 remove_index_entry_at(istate, pos);
691 return 0;
694 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
696 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
699 static int index_name_pos_also_unmerged(struct index_state *istate,
700 const char *path, int namelen)
702 int pos = index_name_pos(istate, path, namelen);
703 struct cache_entry *ce;
705 if (pos >= 0)
706 return pos;
708 /* maybe unmerged? */
709 pos = -1 - pos;
710 if (pos >= istate->cache_nr ||
711 compare_name((ce = istate->cache[pos]), path, namelen))
712 return -1;
714 /* order of preference: stage 2, 1, 3 */
715 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
716 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
717 !compare_name(ce, path, namelen))
718 pos++;
719 return pos;
722 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
724 int len = ce_namelen(ce);
725 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
729 * If we add a filename that aliases in the cache, we will use the
730 * name that we already have - but we don't want to update the same
731 * alias twice, because that implies that there were actually two
732 * different files with aliasing names!
734 * So we use the CE_ADDED flag to verify that the alias was an old
735 * one before we accept it as
737 static struct cache_entry *create_alias_ce(struct index_state *istate,
738 struct cache_entry *ce,
739 struct cache_entry *alias)
741 int len;
742 struct cache_entry *new_entry;
744 if (alias->ce_flags & CE_ADDED)
745 die(_("will not add file alias '%s' ('%s' already exists in index)"),
746 ce->name, alias->name);
748 /* Ok, create the new entry using the name of the existing alias */
749 len = ce_namelen(alias);
750 new_entry = make_empty_cache_entry(istate, len);
751 memcpy(new_entry->name, alias->name, len);
752 copy_cache_entry(new_entry, ce);
753 save_or_free_index_entry(istate, ce);
754 return new_entry;
757 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
759 struct object_id oid;
760 if (write_object_file("", 0, OBJ_BLOB, &oid))
761 die(_("cannot create an empty blob in the object database"));
762 oidcpy(&ce->oid, &oid);
765 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
767 int namelen, was_same;
768 mode_t st_mode = st->st_mode;
769 struct cache_entry *ce, *alias = NULL;
770 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
771 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
772 int pretend = flags & ADD_CACHE_PRETEND;
773 int intent_only = flags & ADD_CACHE_INTENT;
774 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
775 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
776 unsigned hash_flags = pretend ? 0 : HASH_WRITE_OBJECT;
777 struct object_id oid;
779 if (flags & ADD_CACHE_RENORMALIZE)
780 hash_flags |= HASH_RENORMALIZE;
782 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
783 return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
785 namelen = strlen(path);
786 if (S_ISDIR(st_mode)) {
787 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
788 return error(_("'%s' does not have a commit checked out"), path);
789 while (namelen && path[namelen-1] == '/')
790 namelen--;
792 ce = make_empty_cache_entry(istate, namelen);
793 memcpy(ce->name, path, namelen);
794 ce->ce_namelen = namelen;
795 if (!intent_only)
796 fill_stat_cache_info(istate, ce, st);
797 else
798 ce->ce_flags |= CE_INTENT_TO_ADD;
801 if (trust_executable_bit && has_symlinks) {
802 ce->ce_mode = create_ce_mode(st_mode);
803 } else {
804 /* If there is an existing entry, pick the mode bits and type
805 * from it, otherwise assume unexecutable regular file.
807 struct cache_entry *ent;
808 int pos = index_name_pos_also_unmerged(istate, path, namelen);
810 ent = (0 <= pos) ? istate->cache[pos] : NULL;
811 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
814 /* When core.ignorecase=true, determine if a directory of the same name but differing
815 * case already exists within the Git repository. If it does, ensure the directory
816 * case of the file being added to the repository matches (is folded into) the existing
817 * entry's directory case.
819 if (ignore_case) {
820 adjust_dirname_case(istate, ce->name);
822 if (!(flags & ADD_CACHE_RENORMALIZE)) {
823 alias = index_file_exists(istate, ce->name,
824 ce_namelen(ce), ignore_case);
825 if (alias &&
826 !ce_stage(alias) &&
827 !ie_match_stat(istate, alias, st, ce_option)) {
828 /* Nothing changed, really */
829 if (!S_ISGITLINK(alias->ce_mode))
830 ce_mark_uptodate(alias);
831 alias->ce_flags |= CE_ADDED;
833 discard_cache_entry(ce);
834 return 0;
837 if (!intent_only) {
838 if (index_path(istate, &ce->oid, path, st, hash_flags)) {
839 discard_cache_entry(ce);
840 return error(_("unable to index file '%s'"), path);
842 } else
843 set_object_name_for_intent_to_add_entry(ce);
845 if (ignore_case && alias && different_name(ce, alias))
846 ce = create_alias_ce(istate, ce, alias);
847 ce->ce_flags |= CE_ADDED;
849 /* It was suspected to be racily clean, but it turns out to be Ok */
850 was_same = (alias &&
851 !ce_stage(alias) &&
852 oideq(&alias->oid, &ce->oid) &&
853 ce->ce_mode == alias->ce_mode);
855 if (pretend)
856 discard_cache_entry(ce);
857 else if (add_index_entry(istate, ce, add_option)) {
858 discard_cache_entry(ce);
859 return error(_("unable to add '%s' to index"), path);
861 if (verbose && !was_same)
862 printf("add '%s'\n", path);
863 return 0;
866 int add_file_to_index(struct index_state *istate, const char *path, int flags)
868 struct stat st;
869 if (lstat(path, &st))
870 die_errno(_("unable to stat '%s'"), path);
871 return add_to_index(istate, path, &st, flags);
874 struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
876 return mem_pool__ce_calloc(find_mem_pool(istate), len);
879 struct cache_entry *make_empty_transient_cache_entry(size_t len,
880 struct mem_pool *ce_mem_pool)
882 if (ce_mem_pool)
883 return mem_pool__ce_calloc(ce_mem_pool, len);
884 return xcalloc(1, cache_entry_size(len));
887 enum verify_path_result {
888 PATH_OK,
889 PATH_INVALID,
890 PATH_DIR_WITH_SEP,
893 static enum verify_path_result verify_path_internal(const char *, unsigned);
895 int verify_path(const char *path, unsigned mode)
897 return verify_path_internal(path, mode) == PATH_OK;
900 struct cache_entry *make_cache_entry(struct index_state *istate,
901 unsigned int mode,
902 const struct object_id *oid,
903 const char *path,
904 int stage,
905 unsigned int refresh_options)
907 struct cache_entry *ce, *ret;
908 int len;
910 if (verify_path_internal(path, mode) == PATH_INVALID) {
911 error(_("invalid path '%s'"), path);
912 return NULL;
915 len = strlen(path);
916 ce = make_empty_cache_entry(istate, len);
918 oidcpy(&ce->oid, oid);
919 memcpy(ce->name, path, len);
920 ce->ce_flags = create_ce_flags(stage);
921 ce->ce_namelen = len;
922 ce->ce_mode = create_ce_mode(mode);
924 ret = refresh_cache_entry(istate, ce, refresh_options);
925 if (ret != ce)
926 discard_cache_entry(ce);
927 return ret;
930 struct cache_entry *make_transient_cache_entry(unsigned int mode,
931 const struct object_id *oid,
932 const char *path,
933 int stage,
934 struct mem_pool *ce_mem_pool)
936 struct cache_entry *ce;
937 int len;
939 if (!verify_path(path, mode)) {
940 error(_("invalid path '%s'"), path);
941 return NULL;
944 len = strlen(path);
945 ce = make_empty_transient_cache_entry(len, ce_mem_pool);
947 oidcpy(&ce->oid, oid);
948 memcpy(ce->name, path, len);
949 ce->ce_flags = create_ce_flags(stage);
950 ce->ce_namelen = len;
951 ce->ce_mode = create_ce_mode(mode);
953 return ce;
957 * Chmod an index entry with either +x or -x.
959 * Returns -1 if the chmod for the particular cache entry failed (if it's
960 * not a regular file), -2 if an invalid flip argument is passed in, 0
961 * otherwise.
963 int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
964 char flip)
966 if (!S_ISREG(ce->ce_mode))
967 return -1;
968 switch (flip) {
969 case '+':
970 ce->ce_mode |= 0111;
971 break;
972 case '-':
973 ce->ce_mode &= ~0111;
974 break;
975 default:
976 return -2;
978 cache_tree_invalidate_path(istate, ce->name);
979 ce->ce_flags |= CE_UPDATE_IN_BASE;
980 mark_fsmonitor_invalid(istate, ce);
981 istate->cache_changed |= CE_ENTRY_CHANGED;
983 return 0;
986 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
988 int len = ce_namelen(a);
989 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
993 * We fundamentally don't like some paths: we don't want
994 * dot or dot-dot anywhere, and for obvious reasons don't
995 * want to recurse into ".git" either.
997 * Also, we don't want double slashes or slashes at the
998 * end that can make pathnames ambiguous.
1000 static int verify_dotfile(const char *rest, unsigned mode)
1003 * The first character was '.', but that
1004 * has already been discarded, we now test
1005 * the rest.
1008 /* "." is not allowed */
1009 if (*rest == '\0' || is_dir_sep(*rest))
1010 return 0;
1012 switch (*rest) {
1014 * ".git" followed by NUL or slash is bad. Note that we match
1015 * case-insensitively here, even if ignore_case is not set.
1016 * This outlaws ".GIT" everywhere out of an abundance of caution,
1017 * since there's really no good reason to allow it.
1019 * Once we've seen ".git", we can also find ".gitmodules", etc (also
1020 * case-insensitively).
1022 case 'g':
1023 case 'G':
1024 if (rest[1] != 'i' && rest[1] != 'I')
1025 break;
1026 if (rest[2] != 't' && rest[2] != 'T')
1027 break;
1028 if (rest[3] == '\0' || is_dir_sep(rest[3]))
1029 return 0;
1030 if (S_ISLNK(mode)) {
1031 rest += 3;
1032 if (skip_iprefix(rest, "modules", &rest) &&
1033 (*rest == '\0' || is_dir_sep(*rest)))
1034 return 0;
1036 break;
1037 case '.':
1038 if (rest[1] == '\0' || is_dir_sep(rest[1]))
1039 return 0;
1041 return 1;
1044 static enum verify_path_result verify_path_internal(const char *path,
1045 unsigned mode)
1047 char c = 0;
1049 if (has_dos_drive_prefix(path))
1050 return PATH_INVALID;
1052 if (!is_valid_path(path))
1053 return PATH_INVALID;
1055 goto inside;
1056 for (;;) {
1057 if (!c)
1058 return PATH_OK;
1059 if (is_dir_sep(c)) {
1060 inside:
1061 if (protect_hfs) {
1063 if (is_hfs_dotgit(path))
1064 return PATH_INVALID;
1065 if (S_ISLNK(mode)) {
1066 if (is_hfs_dotgitmodules(path))
1067 return PATH_INVALID;
1070 if (protect_ntfs) {
1071 #if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
1072 if (c == '\\')
1073 return PATH_INVALID;
1074 #endif
1075 if (is_ntfs_dotgit(path))
1076 return PATH_INVALID;
1077 if (S_ISLNK(mode)) {
1078 if (is_ntfs_dotgitmodules(path))
1079 return PATH_INVALID;
1083 c = *path++;
1084 if ((c == '.' && !verify_dotfile(path, mode)) ||
1085 is_dir_sep(c))
1086 return PATH_INVALID;
1088 * allow terminating directory separators for
1089 * sparse directory entries.
1091 if (c == '\0')
1092 return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
1093 PATH_INVALID;
1094 } else if (c == '\\' && protect_ntfs) {
1095 if (is_ntfs_dotgit(path))
1096 return PATH_INVALID;
1097 if (S_ISLNK(mode)) {
1098 if (is_ntfs_dotgitmodules(path))
1099 return PATH_INVALID;
1103 c = *path++;
1108 * Do we have another file that has the beginning components being a
1109 * proper superset of the name we're trying to add?
1111 static int has_file_name(struct index_state *istate,
1112 const struct cache_entry *ce, int pos, int ok_to_replace)
1114 int retval = 0;
1115 int len = ce_namelen(ce);
1116 int stage = ce_stage(ce);
1117 const char *name = ce->name;
1119 while (pos < istate->cache_nr) {
1120 struct cache_entry *p = istate->cache[pos++];
1122 if (len >= ce_namelen(p))
1123 break;
1124 if (memcmp(name, p->name, len))
1125 break;
1126 if (ce_stage(p) != stage)
1127 continue;
1128 if (p->name[len] != '/')
1129 continue;
1130 if (p->ce_flags & CE_REMOVE)
1131 continue;
1132 retval = -1;
1133 if (!ok_to_replace)
1134 break;
1135 remove_index_entry_at(istate, --pos);
1137 return retval;
1142 * Like strcmp(), but also return the offset of the first change.
1143 * If strings are equal, return the length.
1145 int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1147 size_t k;
1149 if (!first_change)
1150 return strcmp(s1, s2);
1152 for (k = 0; s1[k] == s2[k]; k++)
1153 if (s1[k] == '\0')
1154 break;
1156 *first_change = k;
1157 return (unsigned char)s1[k] - (unsigned char)s2[k];
1161 * Do we have another file with a pathname that is a proper
1162 * subset of the name we're trying to add?
1164 * That is, is there another file in the index with a path
1165 * that matches a sub-directory in the given entry?
1167 static int has_dir_name(struct index_state *istate,
1168 const struct cache_entry *ce, int pos, int ok_to_replace)
1170 int retval = 0;
1171 int stage = ce_stage(ce);
1172 const char *name = ce->name;
1173 const char *slash = name + ce_namelen(ce);
1174 size_t len_eq_last;
1175 int cmp_last = 0;
1178 * We are frequently called during an iteration on a sorted
1179 * list of pathnames and while building a new index. Therefore,
1180 * there is a high probability that this entry will eventually
1181 * be appended to the index, rather than inserted in the middle.
1182 * If we can confirm that, we can avoid binary searches on the
1183 * components of the pathname.
1185 * Compare the entry's full path with the last path in the index.
1187 if (istate->cache_nr > 0) {
1188 cmp_last = strcmp_offset(name,
1189 istate->cache[istate->cache_nr - 1]->name,
1190 &len_eq_last);
1191 if (cmp_last > 0) {
1192 if (len_eq_last == 0) {
1194 * The entry sorts AFTER the last one in the
1195 * index and their paths have no common prefix,
1196 * so there cannot be a F/D conflict.
1198 return retval;
1199 } else {
1201 * The entry sorts AFTER the last one in the
1202 * index, but has a common prefix. Fall through
1203 * to the loop below to disect the entry's path
1204 * and see where the difference is.
1207 } else if (cmp_last == 0) {
1209 * The entry exactly matches the last one in the
1210 * index, but because of multiple stage and CE_REMOVE
1211 * items, we fall through and let the regular search
1212 * code handle it.
1217 for (;;) {
1218 size_t len;
1220 for (;;) {
1221 if (*--slash == '/')
1222 break;
1223 if (slash <= ce->name)
1224 return retval;
1226 len = slash - name;
1228 if (cmp_last > 0) {
1230 * (len + 1) is a directory boundary (including
1231 * the trailing slash). And since the loop is
1232 * decrementing "slash", the first iteration is
1233 * the longest directory prefix; subsequent
1234 * iterations consider parent directories.
1237 if (len + 1 <= len_eq_last) {
1239 * The directory prefix (including the trailing
1240 * slash) also appears as a prefix in the last
1241 * entry, so the remainder cannot collide (because
1242 * strcmp said the whole path was greater).
1244 * EQ: last: xxx/A
1245 * this: xxx/B
1247 * LT: last: xxx/file_A
1248 * this: xxx/file_B
1250 return retval;
1253 if (len > len_eq_last) {
1255 * This part of the directory prefix (excluding
1256 * the trailing slash) is longer than the known
1257 * equal portions, so this sub-directory cannot
1258 * collide with a file.
1260 * GT: last: xxxA
1261 * this: xxxB/file
1263 return retval;
1267 * This is a possible collision. Fall through and
1268 * let the regular search code handle it.
1270 * last: xxx
1271 * this: xxx/file
1275 pos = index_name_stage_pos(istate, name, len, stage, EXPAND_SPARSE);
1276 if (pos >= 0) {
1278 * Found one, but not so fast. This could
1279 * be a marker that says "I was here, but
1280 * I am being removed". Such an entry is
1281 * not a part of the resulting tree, and
1282 * it is Ok to have a directory at the same
1283 * path.
1285 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1286 retval = -1;
1287 if (!ok_to_replace)
1288 break;
1289 remove_index_entry_at(istate, pos);
1290 continue;
1293 else
1294 pos = -pos-1;
1297 * Trivial optimization: if we find an entry that
1298 * already matches the sub-directory, then we know
1299 * we're ok, and we can exit.
1301 while (pos < istate->cache_nr) {
1302 struct cache_entry *p = istate->cache[pos];
1303 if ((ce_namelen(p) <= len) ||
1304 (p->name[len] != '/') ||
1305 memcmp(p->name, name, len))
1306 break; /* not our subdirectory */
1307 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1309 * p is at the same stage as our entry, and
1310 * is a subdirectory of what we are looking
1311 * at, so we cannot have conflicts at our
1312 * level or anything shorter.
1314 return retval;
1315 pos++;
1318 return retval;
1321 /* We may be in a situation where we already have path/file and path
1322 * is being added, or we already have path and path/file is being
1323 * added. Either one would result in a nonsense tree that has path
1324 * twice when git-write-tree tries to write it out. Prevent it.
1326 * If ok-to-replace is specified, we remove the conflicting entries
1327 * from the cache so the caller should recompute the insert position.
1328 * When this happens, we return non-zero.
1330 static int check_file_directory_conflict(struct index_state *istate,
1331 const struct cache_entry *ce,
1332 int pos, int ok_to_replace)
1334 int retval;
1337 * When ce is an "I am going away" entry, we allow it to be added
1339 if (ce->ce_flags & CE_REMOVE)
1340 return 0;
1343 * We check if the path is a sub-path of a subsequent pathname
1344 * first, since removing those will not change the position
1345 * in the array.
1347 retval = has_file_name(istate, ce, pos, ok_to_replace);
1350 * Then check if the path might have a clashing sub-directory
1351 * before it.
1353 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1356 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1358 int pos;
1359 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1360 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1361 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1362 int new_only = option & ADD_CACHE_NEW_ONLY;
1365 * If this entry's path sorts after the last entry in the index,
1366 * we can avoid searching for it.
1368 if (istate->cache_nr > 0 &&
1369 strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1370 pos = index_pos_to_insert_pos(istate->cache_nr);
1371 else
1372 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1375 * Cache tree path should be invalidated only after index_name_stage_pos,
1376 * in case it expands a sparse index.
1378 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1379 cache_tree_invalidate_path(istate, ce->name);
1381 /* existing match? Just replace it. */
1382 if (pos >= 0) {
1383 if (!new_only)
1384 replace_index_entry(istate, pos, ce);
1385 return 0;
1387 pos = -pos-1;
1389 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1390 untracked_cache_add_to_index(istate, ce->name);
1393 * Inserting a merged entry ("stage 0") into the index
1394 * will always replace all non-merged entries..
1396 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1397 while (ce_same_name(istate->cache[pos], ce)) {
1398 ok_to_add = 1;
1399 if (!remove_index_entry_at(istate, pos))
1400 break;
1404 if (!ok_to_add)
1405 return -1;
1406 if (verify_path_internal(ce->name, ce->ce_mode) == PATH_INVALID)
1407 return error(_("invalid path '%s'"), ce->name);
1409 if (!skip_df_check &&
1410 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1411 if (!ok_to_replace)
1412 return error(_("'%s' appears as both a file and as a directory"),
1413 ce->name);
1414 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1415 pos = -pos-1;
1417 return pos + 1;
1420 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1422 int pos;
1424 if (option & ADD_CACHE_JUST_APPEND)
1425 pos = istate->cache_nr;
1426 else {
1427 int ret;
1428 ret = add_index_entry_with_check(istate, ce, option);
1429 if (ret <= 0)
1430 return ret;
1431 pos = ret - 1;
1434 /* Make sure the array is big enough .. */
1435 ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1437 /* Add it in.. */
1438 istate->cache_nr++;
1439 if (istate->cache_nr > pos + 1)
1440 MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1441 istate->cache_nr - pos - 1);
1442 set_index_entry(istate, pos, ce);
1443 istate->cache_changed |= CE_ENTRY_ADDED;
1444 return 0;
1448 * "refresh" does not calculate a new sha1 file or bring the
1449 * cache up-to-date for mode/content changes. But what it
1450 * _does_ do is to "re-match" the stat information of a file
1451 * with the cache, so that you can refresh the cache for a
1452 * file that hasn't been changed but where the stat entry is
1453 * out of date.
1455 * For example, you'd want to do this after doing a "git-read-tree",
1456 * to link up the stat cache details with the proper files.
1458 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1459 struct cache_entry *ce,
1460 unsigned int options, int *err,
1461 int *changed_ret,
1462 int *t2_did_lstat,
1463 int *t2_did_scan)
1465 struct stat st;
1466 struct cache_entry *updated;
1467 int changed;
1468 int refresh = options & CE_MATCH_REFRESH;
1469 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1470 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1471 int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1472 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
1474 if (!refresh || ce_uptodate(ce))
1475 return ce;
1477 if (!ignore_fsmonitor)
1478 refresh_fsmonitor(istate);
1480 * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1481 * that the change to the work tree does not matter and told
1482 * us not to worry.
1484 if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1485 ce_mark_uptodate(ce);
1486 return ce;
1488 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1489 ce_mark_uptodate(ce);
1490 return ce;
1492 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1493 ce_mark_uptodate(ce);
1494 return ce;
1497 if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1498 if (ignore_missing)
1499 return ce;
1500 if (err)
1501 *err = ENOENT;
1502 return NULL;
1505 if (t2_did_lstat)
1506 *t2_did_lstat = 1;
1507 if (lstat(ce->name, &st) < 0) {
1508 if (ignore_missing && errno == ENOENT)
1509 return ce;
1510 if (err)
1511 *err = errno;
1512 return NULL;
1515 changed = ie_match_stat(istate, ce, &st, options);
1516 if (changed_ret)
1517 *changed_ret = changed;
1518 if (!changed) {
1520 * The path is unchanged. If we were told to ignore
1521 * valid bit, then we did the actual stat check and
1522 * found that the entry is unmodified. If the entry
1523 * is not marked VALID, this is the place to mark it
1524 * valid again, under "assume unchanged" mode.
1526 if (ignore_valid && assume_unchanged &&
1527 !(ce->ce_flags & CE_VALID))
1528 ; /* mark this one VALID again */
1529 else {
1531 * We do not mark the index itself "modified"
1532 * because CE_UPTODATE flag is in-core only;
1533 * we are not going to write this change out.
1535 if (!S_ISGITLINK(ce->ce_mode)) {
1536 ce_mark_uptodate(ce);
1537 mark_fsmonitor_valid(istate, ce);
1539 return ce;
1543 if (t2_did_scan)
1544 *t2_did_scan = 1;
1545 if (ie_modified(istate, ce, &st, options)) {
1546 if (err)
1547 *err = EINVAL;
1548 return NULL;
1551 updated = make_empty_cache_entry(istate, ce_namelen(ce));
1552 copy_cache_entry(updated, ce);
1553 memcpy(updated->name, ce->name, ce->ce_namelen + 1);
1554 fill_stat_cache_info(istate, updated, &st);
1556 * If ignore_valid is not set, we should leave CE_VALID bit
1557 * alone. Otherwise, paths marked with --no-assume-unchanged
1558 * (i.e. things to be edited) will reacquire CE_VALID bit
1559 * automatically, which is not really what we want.
1561 if (!ignore_valid && assume_unchanged &&
1562 !(ce->ce_flags & CE_VALID))
1563 updated->ce_flags &= ~CE_VALID;
1565 /* istate->cache_changed is updated in the caller */
1566 return updated;
1569 static void show_file(const char * fmt, const char * name, int in_porcelain,
1570 int * first, const char *header_msg)
1572 if (in_porcelain && *first && header_msg) {
1573 printf("%s\n", header_msg);
1574 *first = 0;
1576 printf(fmt, name);
1579 int repo_refresh_and_write_index(struct repository *repo,
1580 unsigned int refresh_flags,
1581 unsigned int write_flags,
1582 int gentle,
1583 const struct pathspec *pathspec,
1584 char *seen, const char *header_msg)
1586 struct lock_file lock_file = LOCK_INIT;
1587 int fd, ret = 0;
1589 fd = repo_hold_locked_index(repo, &lock_file, 0);
1590 if (!gentle && fd < 0)
1591 return -1;
1592 if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
1593 ret = 1;
1594 if (0 <= fd && write_locked_index(repo->index, &lock_file, COMMIT_LOCK | write_flags))
1595 ret = -1;
1596 return ret;
1600 int refresh_index(struct index_state *istate, unsigned int flags,
1601 const struct pathspec *pathspec,
1602 char *seen, const char *header_msg)
1604 int i;
1605 int has_errors = 0;
1606 int really = (flags & REFRESH_REALLY) != 0;
1607 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1608 int quiet = (flags & REFRESH_QUIET) != 0;
1609 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1610 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1611 int ignore_skip_worktree = (flags & REFRESH_IGNORE_SKIP_WORKTREE) != 0;
1612 int first = 1;
1613 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1614 unsigned int options = (CE_MATCH_REFRESH |
1615 (really ? CE_MATCH_IGNORE_VALID : 0) |
1616 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1617 const char *modified_fmt;
1618 const char *deleted_fmt;
1619 const char *typechange_fmt;
1620 const char *added_fmt;
1621 const char *unmerged_fmt;
1622 struct progress *progress = NULL;
1623 int t2_sum_lstat = 0;
1624 int t2_sum_scan = 0;
1626 if (flags & REFRESH_PROGRESS && isatty(2))
1627 progress = start_delayed_progress(_("Refresh index"),
1628 istate->cache_nr);
1630 trace_performance_enter();
1631 modified_fmt = in_porcelain ? "M\t%s\n" : "%s: needs update\n";
1632 deleted_fmt = in_porcelain ? "D\t%s\n" : "%s: needs update\n";
1633 typechange_fmt = in_porcelain ? "T\t%s\n" : "%s: needs update\n";
1634 added_fmt = in_porcelain ? "A\t%s\n" : "%s: needs update\n";
1635 unmerged_fmt = in_porcelain ? "U\t%s\n" : "%s: needs merge\n";
1637 * Use the multi-threaded preload_index() to refresh most of the
1638 * cache entries quickly then in the single threaded loop below,
1639 * we only have to do the special cases that are left.
1641 preload_index(istate, pathspec, 0);
1642 trace2_region_enter("index", "refresh", NULL);
1644 for (i = 0; i < istate->cache_nr; i++) {
1645 struct cache_entry *ce, *new_entry;
1646 int cache_errno = 0;
1647 int changed = 0;
1648 int filtered = 0;
1649 int t2_did_lstat = 0;
1650 int t2_did_scan = 0;
1652 ce = istate->cache[i];
1653 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1654 continue;
1655 if (ignore_skip_worktree && ce_skip_worktree(ce))
1656 continue;
1659 * If this entry is a sparse directory, then there isn't
1660 * any stat() information to update. Ignore the entry.
1662 if (S_ISSPARSEDIR(ce->ce_mode))
1663 continue;
1665 if (pathspec && !ce_path_match(istate, ce, pathspec, seen))
1666 filtered = 1;
1668 if (ce_stage(ce)) {
1669 while ((i < istate->cache_nr) &&
1670 ! strcmp(istate->cache[i]->name, ce->name))
1671 i++;
1672 i--;
1673 if (allow_unmerged)
1674 continue;
1675 if (!filtered)
1676 show_file(unmerged_fmt, ce->name, in_porcelain,
1677 &first, header_msg);
1678 has_errors = 1;
1679 continue;
1682 if (filtered)
1683 continue;
1685 new_entry = refresh_cache_ent(istate, ce, options,
1686 &cache_errno, &changed,
1687 &t2_did_lstat, &t2_did_scan);
1688 t2_sum_lstat += t2_did_lstat;
1689 t2_sum_scan += t2_did_scan;
1690 if (new_entry == ce)
1691 continue;
1692 display_progress(progress, i);
1693 if (!new_entry) {
1694 const char *fmt;
1696 if (really && cache_errno == EINVAL) {
1697 /* If we are doing --really-refresh that
1698 * means the index is not valid anymore.
1700 ce->ce_flags &= ~CE_VALID;
1701 ce->ce_flags |= CE_UPDATE_IN_BASE;
1702 mark_fsmonitor_invalid(istate, ce);
1703 istate->cache_changed |= CE_ENTRY_CHANGED;
1705 if (quiet)
1706 continue;
1708 if (cache_errno == ENOENT)
1709 fmt = deleted_fmt;
1710 else if (ce_intent_to_add(ce))
1711 fmt = added_fmt; /* must be before other checks */
1712 else if (changed & TYPE_CHANGED)
1713 fmt = typechange_fmt;
1714 else
1715 fmt = modified_fmt;
1716 show_file(fmt,
1717 ce->name, in_porcelain, &first, header_msg);
1718 has_errors = 1;
1719 continue;
1722 replace_index_entry(istate, i, new_entry);
1724 trace2_data_intmax("index", NULL, "refresh/sum_lstat", t2_sum_lstat);
1725 trace2_data_intmax("index", NULL, "refresh/sum_scan", t2_sum_scan);
1726 trace2_region_leave("index", "refresh", NULL);
1727 display_progress(progress, istate->cache_nr);
1728 stop_progress(&progress);
1729 trace_performance_leave("refresh index");
1730 return has_errors;
1733 struct cache_entry *refresh_cache_entry(struct index_state *istate,
1734 struct cache_entry *ce,
1735 unsigned int options)
1737 return refresh_cache_ent(istate, ce, options, NULL, NULL, NULL, NULL);
1741 /*****************************************************************
1742 * Index File I/O
1743 *****************************************************************/
1745 #define INDEX_FORMAT_DEFAULT 3
1747 static unsigned int get_index_format_default(struct repository *r)
1749 char *envversion = getenv("GIT_INDEX_VERSION");
1750 char *endp;
1751 unsigned int version = INDEX_FORMAT_DEFAULT;
1753 if (!envversion) {
1754 prepare_repo_settings(r);
1756 if (r->settings.index_version >= 0)
1757 version = r->settings.index_version;
1758 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1759 warning(_("index.version set, but the value is invalid.\n"
1760 "Using version %i"), INDEX_FORMAT_DEFAULT);
1761 return INDEX_FORMAT_DEFAULT;
1763 return version;
1766 version = strtoul(envversion, &endp, 10);
1767 if (*endp ||
1768 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1769 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1770 "Using version %i"), INDEX_FORMAT_DEFAULT);
1771 version = INDEX_FORMAT_DEFAULT;
1773 return version;
1777 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1778 * Again - this is just a (very strong in practice) heuristic that
1779 * the inode hasn't changed.
1781 * We save the fields in big-endian order to allow using the
1782 * index file over NFS transparently.
1784 struct ondisk_cache_entry {
1785 struct cache_time ctime;
1786 struct cache_time mtime;
1787 uint32_t dev;
1788 uint32_t ino;
1789 uint32_t mode;
1790 uint32_t uid;
1791 uint32_t gid;
1792 uint32_t size;
1794 * unsigned char hash[hashsz];
1795 * uint16_t flags;
1796 * if (flags & CE_EXTENDED)
1797 * uint16_t flags2;
1799 unsigned char data[GIT_MAX_RAWSZ + 2 * sizeof(uint16_t)];
1800 char name[FLEX_ARRAY];
1803 /* These are only used for v3 or lower */
1804 #define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1805 #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,data) + (len) + 8) & ~7)
1806 #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1807 #define ondisk_data_size(flags, len) (the_hash_algo->rawsz + \
1808 ((flags & CE_EXTENDED) ? 2 : 1) * sizeof(uint16_t) + len)
1809 #define ondisk_data_size_max(len) (ondisk_data_size(CE_EXTENDED, len))
1810 #define ondisk_ce_size(ce) (ondisk_cache_entry_size(ondisk_data_size((ce)->ce_flags, ce_namelen(ce))))
1812 /* Allow fsck to force verification of the index checksum. */
1813 int verify_index_checksum;
1815 /* Allow fsck to force verification of the cache entry order. */
1816 int verify_ce_order;
1818 static int verify_hdr(const struct cache_header *hdr, unsigned long size)
1820 git_hash_ctx c;
1821 unsigned char hash[GIT_MAX_RAWSZ];
1822 int hdr_version;
1823 unsigned char *start, *end;
1824 struct object_id oid;
1826 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1827 return error(_("bad signature 0x%08x"), hdr->hdr_signature);
1828 hdr_version = ntohl(hdr->hdr_version);
1829 if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1830 return error(_("bad index version %d"), hdr_version);
1832 if (!verify_index_checksum)
1833 return 0;
1835 end = (unsigned char *)hdr + size;
1836 start = end - the_hash_algo->rawsz;
1837 oidread(&oid, start);
1838 if (oideq(&oid, null_oid()))
1839 return 0;
1841 the_hash_algo->init_fn(&c);
1842 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1843 the_hash_algo->final_fn(hash, &c);
1844 if (!hasheq(hash, start))
1845 return error(_("bad index file sha1 signature"));
1846 return 0;
1849 static int read_index_extension(struct index_state *istate,
1850 const char *ext, const char *data, unsigned long sz)
1852 switch (CACHE_EXT(ext)) {
1853 case CACHE_EXT_TREE:
1854 istate->cache_tree = cache_tree_read(data, sz);
1855 break;
1856 case CACHE_EXT_RESOLVE_UNDO:
1857 istate->resolve_undo = resolve_undo_read(data, sz);
1858 break;
1859 case CACHE_EXT_LINK:
1860 if (read_link_extension(istate, data, sz))
1861 return -1;
1862 break;
1863 case CACHE_EXT_UNTRACKED:
1864 istate->untracked = read_untracked_extension(data, sz);
1865 break;
1866 case CACHE_EXT_FSMONITOR:
1867 read_fsmonitor_extension(istate, data, sz);
1868 break;
1869 case CACHE_EXT_ENDOFINDEXENTRIES:
1870 case CACHE_EXT_INDEXENTRYOFFSETTABLE:
1871 /* already handled in do_read_index() */
1872 break;
1873 case CACHE_EXT_SPARSE_DIRECTORIES:
1874 /* no content, only an indicator */
1875 istate->sparse_index = INDEX_COLLAPSED;
1876 break;
1877 default:
1878 if (*ext < 'A' || 'Z' < *ext)
1879 return error(_("index uses %.4s extension, which we do not understand"),
1880 ext);
1881 fprintf_ln(stderr, _("ignoring %.4s extension"), ext);
1882 break;
1884 return 0;
1888 * Parses the contents of the cache entry contained within the 'ondisk' buffer
1889 * into a new incore 'cache_entry'.
1891 * Note that 'char *ondisk' may not be aligned to a 4-byte address interval in
1892 * index v4, so we cannot cast it to 'struct ondisk_cache_entry *' and access
1893 * its members. Instead, we use the byte offsets of members within the struct to
1894 * identify where 'get_be16()', 'get_be32()', and 'oidread()' (which can all
1895 * read from an unaligned memory buffer) should read from the 'ondisk' buffer
1896 * into the corresponding incore 'cache_entry' members.
1898 static struct cache_entry *create_from_disk(struct mem_pool *ce_mem_pool,
1899 unsigned int version,
1900 const char *ondisk,
1901 unsigned long *ent_size,
1902 const struct cache_entry *previous_ce)
1904 struct cache_entry *ce;
1905 size_t len;
1906 const char *name;
1907 const unsigned hashsz = the_hash_algo->rawsz;
1908 const char *flagsp = ondisk + offsetof(struct ondisk_cache_entry, data) + hashsz;
1909 unsigned int flags;
1910 size_t copy_len = 0;
1912 * Adjacent cache entries tend to share the leading paths, so it makes
1913 * sense to only store the differences in later entries. In the v4
1914 * on-disk format of the index, each on-disk cache entry stores the
1915 * number of bytes to be stripped from the end of the previous name,
1916 * and the bytes to append to the result, to come up with its name.
1918 int expand_name_field = version == 4;
1920 /* On-disk flags are just 16 bits */
1921 flags = get_be16(flagsp);
1922 len = flags & CE_NAMEMASK;
1924 if (flags & CE_EXTENDED) {
1925 int extended_flags;
1926 extended_flags = get_be16(flagsp + sizeof(uint16_t)) << 16;
1927 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1928 if (extended_flags & ~CE_EXTENDED_FLAGS)
1929 die(_("unknown index entry format 0x%08x"), extended_flags);
1930 flags |= extended_flags;
1931 name = (const char *)(flagsp + 2 * sizeof(uint16_t));
1933 else
1934 name = (const char *)(flagsp + sizeof(uint16_t));
1936 if (expand_name_field) {
1937 const unsigned char *cp = (const unsigned char *)name;
1938 size_t strip_len, previous_len;
1940 /* If we're at the beginning of a block, ignore the previous name */
1941 strip_len = decode_varint(&cp);
1942 if (previous_ce) {
1943 previous_len = previous_ce->ce_namelen;
1944 if (previous_len < strip_len)
1945 die(_("malformed name field in the index, near path '%s'"),
1946 previous_ce->name);
1947 copy_len = previous_len - strip_len;
1949 name = (const char *)cp;
1952 if (len == CE_NAMEMASK) {
1953 len = strlen(name);
1954 if (expand_name_field)
1955 len += copy_len;
1958 ce = mem_pool__ce_alloc(ce_mem_pool, len);
1961 * NEEDSWORK: using 'offsetof()' is cumbersome and should be replaced
1962 * with something more akin to 'load_bitmap_entries_v1()'s use of
1963 * 'read_be16'/'read_be32'. For consistency with the corresponding
1964 * ondisk entry write function ('copy_cache_entry_to_ondisk()'), this
1965 * should be done at the same time as removing references to
1966 * 'ondisk_cache_entry' there.
1968 ce->ce_stat_data.sd_ctime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1969 + offsetof(struct cache_time, sec));
1970 ce->ce_stat_data.sd_mtime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1971 + offsetof(struct cache_time, sec));
1972 ce->ce_stat_data.sd_ctime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1973 + offsetof(struct cache_time, nsec));
1974 ce->ce_stat_data.sd_mtime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1975 + offsetof(struct cache_time, nsec));
1976 ce->ce_stat_data.sd_dev = get_be32(ondisk + offsetof(struct ondisk_cache_entry, dev));
1977 ce->ce_stat_data.sd_ino = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ino));
1978 ce->ce_mode = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mode));
1979 ce->ce_stat_data.sd_uid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, uid));
1980 ce->ce_stat_data.sd_gid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, gid));
1981 ce->ce_stat_data.sd_size = get_be32(ondisk + offsetof(struct ondisk_cache_entry, size));
1982 ce->ce_flags = flags & ~CE_NAMEMASK;
1983 ce->ce_namelen = len;
1984 ce->index = 0;
1985 oidread(&ce->oid, (const unsigned char *)ondisk + offsetof(struct ondisk_cache_entry, data));
1987 if (expand_name_field) {
1988 if (copy_len)
1989 memcpy(ce->name, previous_ce->name, copy_len);
1990 memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1991 *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
1992 } else {
1993 memcpy(ce->name, name, len + 1);
1994 *ent_size = ondisk_ce_size(ce);
1996 return ce;
1999 static void check_ce_order(struct index_state *istate)
2001 unsigned int i;
2003 if (!verify_ce_order)
2004 return;
2006 for (i = 1; i < istate->cache_nr; i++) {
2007 struct cache_entry *ce = istate->cache[i - 1];
2008 struct cache_entry *next_ce = istate->cache[i];
2009 int name_compare = strcmp(ce->name, next_ce->name);
2011 if (0 < name_compare)
2012 die(_("unordered stage entries in index"));
2013 if (!name_compare) {
2014 if (!ce_stage(ce))
2015 die(_("multiple stage entries for merged file '%s'"),
2016 ce->name);
2017 if (ce_stage(ce) > ce_stage(next_ce))
2018 die(_("unordered stage entries for '%s'"),
2019 ce->name);
2024 static void tweak_untracked_cache(struct index_state *istate)
2026 struct repository *r = the_repository;
2028 prepare_repo_settings(r);
2030 switch (r->settings.core_untracked_cache) {
2031 case UNTRACKED_CACHE_REMOVE:
2032 remove_untracked_cache(istate);
2033 break;
2034 case UNTRACKED_CACHE_WRITE:
2035 add_untracked_cache(istate);
2036 break;
2037 case UNTRACKED_CACHE_KEEP:
2039 * Either an explicit "core.untrackedCache=keep", the
2040 * default if "core.untrackedCache" isn't configured,
2041 * or a fallback on an unknown "core.untrackedCache"
2042 * value.
2044 break;
2048 static void tweak_split_index(struct index_state *istate)
2050 switch (git_config_get_split_index()) {
2051 case -1: /* unset: do nothing */
2052 break;
2053 case 0: /* false */
2054 remove_split_index(istate);
2055 break;
2056 case 1: /* true */
2057 add_split_index(istate);
2058 break;
2059 default: /* unknown value: do nothing */
2060 break;
2064 static void post_read_index_from(struct index_state *istate)
2066 check_ce_order(istate);
2067 tweak_untracked_cache(istate);
2068 tweak_split_index(istate);
2069 tweak_fsmonitor(istate);
2072 static size_t estimate_cache_size_from_compressed(unsigned int entries)
2074 return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
2077 static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
2079 long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
2082 * Account for potential alignment differences.
2084 per_entry += align_padding_size(per_entry, 0);
2085 return ondisk_size + entries * per_entry;
2088 struct index_entry_offset
2090 /* starting byte offset into index file, count of index entries in this block */
2091 int offset, nr;
2094 struct index_entry_offset_table
2096 int nr;
2097 struct index_entry_offset entries[FLEX_ARRAY];
2100 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset);
2101 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot);
2103 static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
2104 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset);
2106 struct load_index_extensions
2108 pthread_t pthread;
2109 struct index_state *istate;
2110 const char *mmap;
2111 size_t mmap_size;
2112 unsigned long src_offset;
2115 static void *load_index_extensions(void *_data)
2117 struct load_index_extensions *p = _data;
2118 unsigned long src_offset = p->src_offset;
2120 while (src_offset <= p->mmap_size - the_hash_algo->rawsz - 8) {
2121 /* After an array of active_nr index entries,
2122 * there can be arbitrary number of extended
2123 * sections, each of which is prefixed with
2124 * extension name (4-byte) and section length
2125 * in 4-byte network byte order.
2127 uint32_t extsize = get_be32(p->mmap + src_offset + 4);
2128 if (read_index_extension(p->istate,
2129 p->mmap + src_offset,
2130 p->mmap + src_offset + 8,
2131 extsize) < 0) {
2132 munmap((void *)p->mmap, p->mmap_size);
2133 die(_("index file corrupt"));
2135 src_offset += 8;
2136 src_offset += extsize;
2139 return NULL;
2143 * A helper function that will load the specified range of cache entries
2144 * from the memory mapped file and add them to the given index.
2146 static unsigned long load_cache_entry_block(struct index_state *istate,
2147 struct mem_pool *ce_mem_pool, int offset, int nr, const char *mmap,
2148 unsigned long start_offset, const struct cache_entry *previous_ce)
2150 int i;
2151 unsigned long src_offset = start_offset;
2153 for (i = offset; i < offset + nr; i++) {
2154 struct cache_entry *ce;
2155 unsigned long consumed;
2157 ce = create_from_disk(ce_mem_pool, istate->version,
2158 mmap + src_offset,
2159 &consumed, previous_ce);
2160 set_index_entry(istate, i, ce);
2162 src_offset += consumed;
2163 previous_ce = ce;
2165 return src_offset - start_offset;
2168 static unsigned long load_all_cache_entries(struct index_state *istate,
2169 const char *mmap, size_t mmap_size, unsigned long src_offset)
2171 unsigned long consumed;
2173 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2174 if (istate->version == 4) {
2175 mem_pool_init(istate->ce_mem_pool,
2176 estimate_cache_size_from_compressed(istate->cache_nr));
2177 } else {
2178 mem_pool_init(istate->ce_mem_pool,
2179 estimate_cache_size(mmap_size, istate->cache_nr));
2182 consumed = load_cache_entry_block(istate, istate->ce_mem_pool,
2183 0, istate->cache_nr, mmap, src_offset, NULL);
2184 return consumed;
2188 * Mostly randomly chosen maximum thread counts: we
2189 * cap the parallelism to online_cpus() threads, and we want
2190 * to have at least 10000 cache entries per thread for it to
2191 * be worth starting a thread.
2194 #define THREAD_COST (10000)
2196 struct load_cache_entries_thread_data
2198 pthread_t pthread;
2199 struct index_state *istate;
2200 struct mem_pool *ce_mem_pool;
2201 int offset;
2202 const char *mmap;
2203 struct index_entry_offset_table *ieot;
2204 int ieot_start; /* starting index into the ieot array */
2205 int ieot_blocks; /* count of ieot entries to process */
2206 unsigned long consumed; /* return # of bytes in index file processed */
2210 * A thread proc to run the load_cache_entries() computation
2211 * across multiple background threads.
2213 static void *load_cache_entries_thread(void *_data)
2215 struct load_cache_entries_thread_data *p = _data;
2216 int i;
2218 /* iterate across all ieot blocks assigned to this thread */
2219 for (i = p->ieot_start; i < p->ieot_start + p->ieot_blocks; i++) {
2220 p->consumed += load_cache_entry_block(p->istate, p->ce_mem_pool,
2221 p->offset, p->ieot->entries[i].nr, p->mmap, p->ieot->entries[i].offset, NULL);
2222 p->offset += p->ieot->entries[i].nr;
2224 return NULL;
2227 static unsigned long load_cache_entries_threaded(struct index_state *istate, const char *mmap, size_t mmap_size,
2228 int nr_threads, struct index_entry_offset_table *ieot)
2230 int i, offset, ieot_blocks, ieot_start, err;
2231 struct load_cache_entries_thread_data *data;
2232 unsigned long consumed = 0;
2234 /* a little sanity checking */
2235 if (istate->name_hash_initialized)
2236 BUG("the name hash isn't thread safe");
2238 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2239 mem_pool_init(istate->ce_mem_pool, 0);
2241 /* ensure we have no more threads than we have blocks to process */
2242 if (nr_threads > ieot->nr)
2243 nr_threads = ieot->nr;
2244 CALLOC_ARRAY(data, nr_threads);
2246 offset = ieot_start = 0;
2247 ieot_blocks = DIV_ROUND_UP(ieot->nr, nr_threads);
2248 for (i = 0; i < nr_threads; i++) {
2249 struct load_cache_entries_thread_data *p = &data[i];
2250 int nr, j;
2252 if (ieot_start + ieot_blocks > ieot->nr)
2253 ieot_blocks = ieot->nr - ieot_start;
2255 p->istate = istate;
2256 p->offset = offset;
2257 p->mmap = mmap;
2258 p->ieot = ieot;
2259 p->ieot_start = ieot_start;
2260 p->ieot_blocks = ieot_blocks;
2262 /* create a mem_pool for each thread */
2263 nr = 0;
2264 for (j = p->ieot_start; j < p->ieot_start + p->ieot_blocks; j++)
2265 nr += p->ieot->entries[j].nr;
2266 p->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2267 if (istate->version == 4) {
2268 mem_pool_init(p->ce_mem_pool,
2269 estimate_cache_size_from_compressed(nr));
2270 } else {
2271 mem_pool_init(p->ce_mem_pool,
2272 estimate_cache_size(mmap_size, nr));
2275 err = pthread_create(&p->pthread, NULL, load_cache_entries_thread, p);
2276 if (err)
2277 die(_("unable to create load_cache_entries thread: %s"), strerror(err));
2279 /* increment by the number of cache entries in the ieot block being processed */
2280 for (j = 0; j < ieot_blocks; j++)
2281 offset += ieot->entries[ieot_start + j].nr;
2282 ieot_start += ieot_blocks;
2285 for (i = 0; i < nr_threads; i++) {
2286 struct load_cache_entries_thread_data *p = &data[i];
2288 err = pthread_join(p->pthread, NULL);
2289 if (err)
2290 die(_("unable to join load_cache_entries thread: %s"), strerror(err));
2291 mem_pool_combine(istate->ce_mem_pool, p->ce_mem_pool);
2292 consumed += p->consumed;
2295 free(data);
2297 return consumed;
2300 static void set_new_index_sparsity(struct index_state *istate)
2303 * If the index's repo exists, mark it sparse according to
2304 * repo settings.
2306 prepare_repo_settings(istate->repo);
2307 if (!istate->repo->settings.command_requires_full_index &&
2308 is_sparse_index_allowed(istate, 0))
2309 istate->sparse_index = 1;
2312 /* remember to discard_cache() before reading a different cache! */
2313 int do_read_index(struct index_state *istate, const char *path, int must_exist)
2315 int fd;
2316 struct stat st;
2317 unsigned long src_offset;
2318 const struct cache_header *hdr;
2319 const char *mmap;
2320 size_t mmap_size;
2321 struct load_index_extensions p;
2322 size_t extension_offset = 0;
2323 int nr_threads, cpus;
2324 struct index_entry_offset_table *ieot = NULL;
2326 if (istate->initialized)
2327 return istate->cache_nr;
2329 istate->timestamp.sec = 0;
2330 istate->timestamp.nsec = 0;
2331 fd = open(path, O_RDONLY);
2332 if (fd < 0) {
2333 if (!must_exist && errno == ENOENT) {
2334 set_new_index_sparsity(istate);
2335 return 0;
2337 die_errno(_("%s: index file open failed"), path);
2340 if (fstat(fd, &st))
2341 die_errno(_("%s: cannot stat the open index"), path);
2343 mmap_size = xsize_t(st.st_size);
2344 if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2345 die(_("%s: index file smaller than expected"), path);
2347 mmap = xmmap_gently(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
2348 if (mmap == MAP_FAILED)
2349 die_errno(_("%s: unable to map index file%s"), path,
2350 mmap_os_err());
2351 close(fd);
2353 hdr = (const struct cache_header *)mmap;
2354 if (verify_hdr(hdr, mmap_size) < 0)
2355 goto unmap;
2357 oidread(&istate->oid, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
2358 istate->version = ntohl(hdr->hdr_version);
2359 istate->cache_nr = ntohl(hdr->hdr_entries);
2360 istate->cache_alloc = alloc_nr(istate->cache_nr);
2361 CALLOC_ARRAY(istate->cache, istate->cache_alloc);
2362 istate->initialized = 1;
2364 p.istate = istate;
2365 p.mmap = mmap;
2366 p.mmap_size = mmap_size;
2368 src_offset = sizeof(*hdr);
2370 if (git_config_get_index_threads(&nr_threads))
2371 nr_threads = 1;
2373 /* TODO: does creating more threads than cores help? */
2374 if (!nr_threads) {
2375 nr_threads = istate->cache_nr / THREAD_COST;
2376 cpus = online_cpus();
2377 if (nr_threads > cpus)
2378 nr_threads = cpus;
2381 if (!HAVE_THREADS)
2382 nr_threads = 1;
2384 if (nr_threads > 1) {
2385 extension_offset = read_eoie_extension(mmap, mmap_size);
2386 if (extension_offset) {
2387 int err;
2389 p.src_offset = extension_offset;
2390 err = pthread_create(&p.pthread, NULL, load_index_extensions, &p);
2391 if (err)
2392 die(_("unable to create load_index_extensions thread: %s"), strerror(err));
2394 nr_threads--;
2399 * Locate and read the index entry offset table so that we can use it
2400 * to multi-thread the reading of the cache entries.
2402 if (extension_offset && nr_threads > 1)
2403 ieot = read_ieot_extension(mmap, mmap_size, extension_offset);
2405 if (ieot) {
2406 src_offset += load_cache_entries_threaded(istate, mmap, mmap_size, nr_threads, ieot);
2407 free(ieot);
2408 } else {
2409 src_offset += load_all_cache_entries(istate, mmap, mmap_size, src_offset);
2412 istate->timestamp.sec = st.st_mtime;
2413 istate->timestamp.nsec = ST_MTIME_NSEC(st);
2415 /* if we created a thread, join it otherwise load the extensions on the primary thread */
2416 if (extension_offset) {
2417 int ret = pthread_join(p.pthread, NULL);
2418 if (ret)
2419 die(_("unable to join load_index_extensions thread: %s"), strerror(ret));
2420 } else {
2421 p.src_offset = src_offset;
2422 load_index_extensions(&p);
2424 munmap((void *)mmap, mmap_size);
2427 * TODO trace2: replace "the_repository" with the actual repo instance
2428 * that is associated with the given "istate".
2430 trace2_data_intmax("index", the_repository, "read/version",
2431 istate->version);
2432 trace2_data_intmax("index", the_repository, "read/cache_nr",
2433 istate->cache_nr);
2436 * If the command explicitly requires a full index, force it
2437 * to be full. Otherwise, correct the sparsity based on repository
2438 * settings and other properties of the index (if necessary).
2440 prepare_repo_settings(istate->repo);
2441 if (istate->repo->settings.command_requires_full_index)
2442 ensure_full_index(istate);
2443 else
2444 ensure_correct_sparsity(istate);
2446 return istate->cache_nr;
2448 unmap:
2449 munmap((void *)mmap, mmap_size);
2450 die(_("index file corrupt"));
2454 * Signal that the shared index is used by updating its mtime.
2456 * This way, shared index can be removed if they have not been used
2457 * for some time.
2459 static void freshen_shared_index(const char *shared_index, int warn)
2461 if (!check_and_freshen_file(shared_index, 1) && warn)
2462 warning(_("could not freshen shared index '%s'"), shared_index);
2465 int read_index_from(struct index_state *istate, const char *path,
2466 const char *gitdir)
2468 struct split_index *split_index;
2469 int ret;
2470 char *base_oid_hex;
2471 char *base_path;
2473 /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2474 if (istate->initialized)
2475 return istate->cache_nr;
2478 * TODO trace2: replace "the_repository" with the actual repo instance
2479 * that is associated with the given "istate".
2481 trace2_region_enter_printf("index", "do_read_index", the_repository,
2482 "%s", path);
2483 trace_performance_enter();
2484 ret = do_read_index(istate, path, 0);
2485 trace_performance_leave("read cache %s", path);
2486 trace2_region_leave_printf("index", "do_read_index", the_repository,
2487 "%s", path);
2489 split_index = istate->split_index;
2490 if (!split_index || is_null_oid(&split_index->base_oid)) {
2491 post_read_index_from(istate);
2492 return ret;
2495 trace_performance_enter();
2496 if (split_index->base)
2497 release_index(split_index->base);
2498 else
2499 ALLOC_ARRAY(split_index->base, 1);
2500 index_state_init(split_index->base, istate->repo);
2502 base_oid_hex = oid_to_hex(&split_index->base_oid);
2503 base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
2504 trace2_region_enter_printf("index", "shared/do_read_index",
2505 the_repository, "%s", base_path);
2506 ret = do_read_index(split_index->base, base_path, 0);
2507 trace2_region_leave_printf("index", "shared/do_read_index",
2508 the_repository, "%s", base_path);
2509 if (!ret) {
2510 char *path_copy = xstrdup(path);
2511 char *base_path2 = xstrfmt("%s/sharedindex.%s",
2512 dirname(path_copy), base_oid_hex);
2513 free(path_copy);
2514 trace2_region_enter_printf("index", "shared/do_read_index",
2515 the_repository, "%s", base_path2);
2516 ret = do_read_index(split_index->base, base_path2, 1);
2517 trace2_region_leave_printf("index", "shared/do_read_index",
2518 the_repository, "%s", base_path2);
2519 free(base_path2);
2521 if (!oideq(&split_index->base_oid, &split_index->base->oid))
2522 die(_("broken index, expect %s in %s, got %s"),
2523 base_oid_hex, base_path,
2524 oid_to_hex(&split_index->base->oid));
2526 freshen_shared_index(base_path, 0);
2527 merge_base_index(istate);
2528 post_read_index_from(istate);
2529 trace_performance_leave("read cache %s", base_path);
2530 free(base_path);
2531 return ret;
2534 int is_index_unborn(struct index_state *istate)
2536 return (!istate->cache_nr && !istate->timestamp.sec);
2539 void index_state_init(struct index_state *istate, struct repository *r)
2541 struct index_state blank = INDEX_STATE_INIT(r);
2542 memcpy(istate, &blank, sizeof(*istate));
2545 void release_index(struct index_state *istate)
2548 * Cache entries in istate->cache[] should have been allocated
2549 * from the memory pool associated with this index, or from an
2550 * associated split_index. There is no need to free individual
2551 * cache entries. validate_cache_entries can detect when this
2552 * assertion does not hold.
2554 validate_cache_entries(istate);
2556 resolve_undo_clear_index(istate);
2557 free_name_hash(istate);
2558 cache_tree_free(&(istate->cache_tree));
2559 free(istate->fsmonitor_last_update);
2560 free(istate->cache);
2561 discard_split_index(istate);
2562 free_untracked_cache(istate->untracked);
2564 if (istate->sparse_checkout_patterns) {
2565 clear_pattern_list(istate->sparse_checkout_patterns);
2566 FREE_AND_NULL(istate->sparse_checkout_patterns);
2569 if (istate->ce_mem_pool) {
2570 mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
2571 FREE_AND_NULL(istate->ce_mem_pool);
2575 void discard_index(struct index_state *istate)
2577 release_index(istate);
2578 index_state_init(istate, istate->repo);
2582 * Validate the cache entries of this index.
2583 * All cache entries associated with this index
2584 * should have been allocated by the memory pool
2585 * associated with this index, or by a referenced
2586 * split index.
2588 void validate_cache_entries(const struct index_state *istate)
2590 int i;
2592 if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2593 return;
2595 for (i = 0; i < istate->cache_nr; i++) {
2596 if (!istate) {
2597 BUG("cache entry is not allocated from expected memory pool");
2598 } else if (!istate->ce_mem_pool ||
2599 !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2600 if (!istate->split_index ||
2601 !istate->split_index->base ||
2602 !istate->split_index->base->ce_mem_pool ||
2603 !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2604 BUG("cache entry is not allocated from expected memory pool");
2609 if (istate->split_index)
2610 validate_cache_entries(istate->split_index->base);
2613 int unmerged_index(const struct index_state *istate)
2615 int i;
2616 for (i = 0; i < istate->cache_nr; i++) {
2617 if (ce_stage(istate->cache[i]))
2618 return 1;
2620 return 0;
2623 int repo_index_has_changes(struct repository *repo,
2624 struct tree *tree,
2625 struct strbuf *sb)
2627 struct index_state *istate = repo->index;
2628 struct object_id cmp;
2629 int i;
2631 if (tree)
2632 cmp = tree->object.oid;
2633 if (tree || !repo_get_oid_tree(repo, "HEAD", &cmp)) {
2634 struct diff_options opt;
2636 repo_diff_setup(repo, &opt);
2637 opt.flags.exit_with_status = 1;
2638 if (!sb)
2639 opt.flags.quick = 1;
2640 diff_setup_done(&opt);
2641 do_diff_cache(&cmp, &opt);
2642 diffcore_std(&opt);
2643 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2644 if (i)
2645 strbuf_addch(sb, ' ');
2646 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2648 diff_flush(&opt);
2649 return opt.flags.has_changes != 0;
2650 } else {
2651 /* TODO: audit for interaction with sparse-index. */
2652 ensure_full_index(istate);
2653 for (i = 0; sb && i < istate->cache_nr; i++) {
2654 if (i)
2655 strbuf_addch(sb, ' ');
2656 strbuf_addstr(sb, istate->cache[i]->name);
2658 return !!istate->cache_nr;
2662 static int write_index_ext_header(struct hashfile *f,
2663 git_hash_ctx *eoie_f,
2664 unsigned int ext,
2665 unsigned int sz)
2667 hashwrite_be32(f, ext);
2668 hashwrite_be32(f, sz);
2670 if (eoie_f) {
2671 ext = htonl(ext);
2672 sz = htonl(sz);
2673 the_hash_algo->update_fn(eoie_f, &ext, sizeof(ext));
2674 the_hash_algo->update_fn(eoie_f, &sz, sizeof(sz));
2676 return 0;
2679 static void ce_smudge_racily_clean_entry(struct index_state *istate,
2680 struct cache_entry *ce)
2683 * The only thing we care about in this function is to smudge the
2684 * falsely clean entry due to touch-update-touch race, so we leave
2685 * everything else as they are. We are called for entries whose
2686 * ce_stat_data.sd_mtime match the index file mtime.
2688 * Note that this actually does not do much for gitlinks, for
2689 * which ce_match_stat_basic() always goes to the actual
2690 * contents. The caller checks with is_racy_timestamp() which
2691 * always says "no" for gitlinks, so we are not called for them ;-)
2693 struct stat st;
2695 if (lstat(ce->name, &st) < 0)
2696 return;
2697 if (ce_match_stat_basic(ce, &st))
2698 return;
2699 if (ce_modified_check_fs(istate, ce, &st)) {
2700 /* This is "racily clean"; smudge it. Note that this
2701 * is a tricky code. At first glance, it may appear
2702 * that it can break with this sequence:
2704 * $ echo xyzzy >frotz
2705 * $ git-update-index --add frotz
2706 * $ : >frotz
2707 * $ sleep 3
2708 * $ echo filfre >nitfol
2709 * $ git-update-index --add nitfol
2711 * but it does not. When the second update-index runs,
2712 * it notices that the entry "frotz" has the same timestamp
2713 * as index, and if we were to smudge it by resetting its
2714 * size to zero here, then the object name recorded
2715 * in index is the 6-byte file but the cached stat information
2716 * becomes zero --- which would then match what we would
2717 * obtain from the filesystem next time we stat("frotz").
2719 * However, the second update-index, before calling
2720 * this function, notices that the cached size is 6
2721 * bytes and what is on the filesystem is an empty
2722 * file, and never calls us, so the cached size information
2723 * for "frotz" stays 6 which does not match the filesystem.
2725 ce->ce_stat_data.sd_size = 0;
2729 /* Copy miscellaneous fields but not the name */
2730 static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2731 struct cache_entry *ce)
2733 short flags;
2734 const unsigned hashsz = the_hash_algo->rawsz;
2735 uint16_t *flagsp = (uint16_t *)(ondisk->data + hashsz);
2737 ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2738 ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2739 ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2740 ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2741 ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
2742 ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
2743 ondisk->mode = htonl(ce->ce_mode);
2744 ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
2745 ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
2746 ondisk->size = htonl(ce->ce_stat_data.sd_size);
2747 hashcpy(ondisk->data, ce->oid.hash);
2749 flags = ce->ce_flags & ~CE_NAMEMASK;
2750 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2751 flagsp[0] = htons(flags);
2752 if (ce->ce_flags & CE_EXTENDED) {
2753 flagsp[1] = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2757 static int ce_write_entry(struct hashfile *f, struct cache_entry *ce,
2758 struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2760 int size;
2761 unsigned int saved_namelen;
2762 int stripped_name = 0;
2763 static unsigned char padding[8] = { 0x00 };
2765 if (ce->ce_flags & CE_STRIP_NAME) {
2766 saved_namelen = ce_namelen(ce);
2767 ce->ce_namelen = 0;
2768 stripped_name = 1;
2771 size = offsetof(struct ondisk_cache_entry,data) + ondisk_data_size(ce->ce_flags, 0);
2773 if (!previous_name) {
2774 int len = ce_namelen(ce);
2775 copy_cache_entry_to_ondisk(ondisk, ce);
2776 hashwrite(f, ondisk, size);
2777 hashwrite(f, ce->name, len);
2778 hashwrite(f, padding, align_padding_size(size, len));
2779 } else {
2780 int common, to_remove, prefix_size;
2781 unsigned char to_remove_vi[16];
2782 for (common = 0;
2783 (ce->name[common] &&
2784 common < previous_name->len &&
2785 ce->name[common] == previous_name->buf[common]);
2786 common++)
2787 ; /* still matching */
2788 to_remove = previous_name->len - common;
2789 prefix_size = encode_varint(to_remove, to_remove_vi);
2791 copy_cache_entry_to_ondisk(ondisk, ce);
2792 hashwrite(f, ondisk, size);
2793 hashwrite(f, to_remove_vi, prefix_size);
2794 hashwrite(f, ce->name + common, ce_namelen(ce) - common);
2795 hashwrite(f, padding, 1);
2797 strbuf_splice(previous_name, common, to_remove,
2798 ce->name + common, ce_namelen(ce) - common);
2800 if (stripped_name) {
2801 ce->ce_namelen = saved_namelen;
2802 ce->ce_flags &= ~CE_STRIP_NAME;
2805 return 0;
2809 * This function verifies if index_state has the correct sha1 of the
2810 * index file. Don't die if we have any other failure, just return 0.
2812 static int verify_index_from(const struct index_state *istate, const char *path)
2814 int fd;
2815 ssize_t n;
2816 struct stat st;
2817 unsigned char hash[GIT_MAX_RAWSZ];
2819 if (!istate->initialized)
2820 return 0;
2822 fd = open(path, O_RDONLY);
2823 if (fd < 0)
2824 return 0;
2826 if (fstat(fd, &st))
2827 goto out;
2829 if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2830 goto out;
2832 n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2833 if (n != the_hash_algo->rawsz)
2834 goto out;
2836 if (!hasheq(istate->oid.hash, hash))
2837 goto out;
2839 close(fd);
2840 return 1;
2842 out:
2843 close(fd);
2844 return 0;
2847 static int repo_verify_index(struct repository *repo)
2849 return verify_index_from(repo->index, repo->index_file);
2852 int has_racy_timestamp(struct index_state *istate)
2854 int entries = istate->cache_nr;
2855 int i;
2857 for (i = 0; i < entries; i++) {
2858 struct cache_entry *ce = istate->cache[i];
2859 if (is_racy_timestamp(istate, ce))
2860 return 1;
2862 return 0;
2865 void repo_update_index_if_able(struct repository *repo,
2866 struct lock_file *lockfile)
2868 if ((repo->index->cache_changed ||
2869 has_racy_timestamp(repo->index)) &&
2870 repo_verify_index(repo))
2871 write_locked_index(repo->index, lockfile, COMMIT_LOCK);
2872 else
2873 rollback_lock_file(lockfile);
2876 static int record_eoie(void)
2878 int val;
2880 if (!git_config_get_bool("index.recordendofindexentries", &val))
2881 return val;
2884 * As a convenience, the end of index entries extension
2885 * used for threading is written by default if the user
2886 * explicitly requested threaded index reads.
2888 return !git_config_get_index_threads(&val) && val != 1;
2891 static int record_ieot(void)
2893 int val;
2895 if (!git_config_get_bool("index.recordoffsettable", &val))
2896 return val;
2899 * As a convenience, the offset table used for threading is
2900 * written by default if the user explicitly requested
2901 * threaded index reads.
2903 return !git_config_get_index_threads(&val) && val != 1;
2906 enum write_extensions {
2907 WRITE_NO_EXTENSION = 0,
2908 WRITE_SPLIT_INDEX_EXTENSION = 1<<0,
2909 WRITE_CACHE_TREE_EXTENSION = 1<<1,
2910 WRITE_RESOLVE_UNDO_EXTENSION = 1<<2,
2911 WRITE_UNTRACKED_CACHE_EXTENSION = 1<<3,
2912 WRITE_FSMONITOR_EXTENSION = 1<<4,
2914 #define WRITE_ALL_EXTENSIONS ((enum write_extensions)-1)
2917 * On success, `tempfile` is closed. If it is the temporary file
2918 * of a `struct lock_file`, we will therefore effectively perform
2919 * a 'close_lock_file_gently()`. Since that is an implementation
2920 * detail of lockfiles, callers of `do_write_index()` should not
2921 * rely on it.
2923 static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2924 enum write_extensions write_extensions, unsigned flags)
2926 uint64_t start = getnanotime();
2927 struct hashfile *f;
2928 git_hash_ctx *eoie_c = NULL;
2929 struct cache_header hdr;
2930 int i, err = 0, removed, extended, hdr_version;
2931 struct cache_entry **cache = istate->cache;
2932 int entries = istate->cache_nr;
2933 struct stat st;
2934 struct ondisk_cache_entry ondisk;
2935 struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2936 int drop_cache_tree = istate->drop_cache_tree;
2937 off_t offset;
2938 int csum_fsync_flag;
2939 int ieot_entries = 1;
2940 struct index_entry_offset_table *ieot = NULL;
2941 int nr, nr_threads;
2942 struct repository *r = istate->repo;
2944 f = hashfd(tempfile->fd, tempfile->filename.buf);
2946 prepare_repo_settings(r);
2947 f->skip_hash = r->settings.index_skip_hash;
2949 for (i = removed = extended = 0; i < entries; i++) {
2950 if (cache[i]->ce_flags & CE_REMOVE)
2951 removed++;
2953 /* reduce extended entries if possible */
2954 cache[i]->ce_flags &= ~CE_EXTENDED;
2955 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2956 extended++;
2957 cache[i]->ce_flags |= CE_EXTENDED;
2961 if (!istate->version)
2962 istate->version = get_index_format_default(r);
2964 /* demote version 3 to version 2 when the latter suffices */
2965 if (istate->version == 3 || istate->version == 2)
2966 istate->version = extended ? 3 : 2;
2968 hdr_version = istate->version;
2970 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2971 hdr.hdr_version = htonl(hdr_version);
2972 hdr.hdr_entries = htonl(entries - removed);
2974 hashwrite(f, &hdr, sizeof(hdr));
2976 if (!HAVE_THREADS || git_config_get_index_threads(&nr_threads))
2977 nr_threads = 1;
2979 if (nr_threads != 1 && record_ieot()) {
2980 int ieot_blocks, cpus;
2983 * ensure default number of ieot blocks maps evenly to the
2984 * default number of threads that will process them leaving
2985 * room for the thread to load the index extensions.
2987 if (!nr_threads) {
2988 ieot_blocks = istate->cache_nr / THREAD_COST;
2989 cpus = online_cpus();
2990 if (ieot_blocks > cpus - 1)
2991 ieot_blocks = cpus - 1;
2992 } else {
2993 ieot_blocks = nr_threads;
2994 if (ieot_blocks > istate->cache_nr)
2995 ieot_blocks = istate->cache_nr;
2999 * no reason to write out the IEOT extension if we don't
3000 * have enough blocks to utilize multi-threading
3002 if (ieot_blocks > 1) {
3003 ieot = xcalloc(1, sizeof(struct index_entry_offset_table)
3004 + (ieot_blocks * sizeof(struct index_entry_offset)));
3005 ieot_entries = DIV_ROUND_UP(entries, ieot_blocks);
3009 offset = hashfile_total(f);
3011 nr = 0;
3012 previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
3014 for (i = 0; i < entries; i++) {
3015 struct cache_entry *ce = cache[i];
3016 if (ce->ce_flags & CE_REMOVE)
3017 continue;
3018 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
3019 ce_smudge_racily_clean_entry(istate, ce);
3020 if (is_null_oid(&ce->oid)) {
3021 static const char msg[] = "cache entry has null sha1: %s";
3022 static int allow = -1;
3024 if (allow < 0)
3025 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
3026 if (allow)
3027 warning(msg, ce->name);
3028 else
3029 err = error(msg, ce->name);
3031 drop_cache_tree = 1;
3033 if (ieot && i && (i % ieot_entries == 0)) {
3034 ieot->entries[ieot->nr].nr = nr;
3035 ieot->entries[ieot->nr].offset = offset;
3036 ieot->nr++;
3038 * If we have a V4 index, set the first byte to an invalid
3039 * character to ensure there is nothing common with the previous
3040 * entry
3042 if (previous_name)
3043 previous_name->buf[0] = 0;
3044 nr = 0;
3046 offset = hashfile_total(f);
3048 if (ce_write_entry(f, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
3049 err = -1;
3051 if (err)
3052 break;
3053 nr++;
3055 if (ieot && nr) {
3056 ieot->entries[ieot->nr].nr = nr;
3057 ieot->entries[ieot->nr].offset = offset;
3058 ieot->nr++;
3060 strbuf_release(&previous_name_buf);
3062 if (err) {
3063 free(ieot);
3064 return err;
3067 offset = hashfile_total(f);
3070 * The extension headers must be hashed on their own for the
3071 * EOIE extension. Create a hashfile here to compute that hash.
3073 if (offset && record_eoie()) {
3074 CALLOC_ARRAY(eoie_c, 1);
3075 the_hash_algo->init_fn(eoie_c);
3079 * Lets write out CACHE_EXT_INDEXENTRYOFFSETTABLE first so that we
3080 * can minimize the number of extensions we have to scan through to
3081 * find it during load. Write it out regardless of the
3082 * strip_extensions parameter as we need it when loading the shared
3083 * index.
3085 if (ieot) {
3086 struct strbuf sb = STRBUF_INIT;
3088 write_ieot_extension(&sb, ieot);
3089 err = write_index_ext_header(f, eoie_c, CACHE_EXT_INDEXENTRYOFFSETTABLE, sb.len) < 0;
3090 hashwrite(f, sb.buf, sb.len);
3091 strbuf_release(&sb);
3092 free(ieot);
3093 if (err)
3094 return -1;
3097 if (write_extensions & WRITE_SPLIT_INDEX_EXTENSION &&
3098 istate->split_index) {
3099 struct strbuf sb = STRBUF_INIT;
3101 if (istate->sparse_index)
3102 die(_("cannot write split index for a sparse index"));
3104 err = write_link_extension(&sb, istate) < 0 ||
3105 write_index_ext_header(f, eoie_c, CACHE_EXT_LINK,
3106 sb.len) < 0;
3107 hashwrite(f, sb.buf, sb.len);
3108 strbuf_release(&sb);
3109 if (err)
3110 return -1;
3112 if (write_extensions & WRITE_CACHE_TREE_EXTENSION &&
3113 !drop_cache_tree && istate->cache_tree) {
3114 struct strbuf sb = STRBUF_INIT;
3116 cache_tree_write(&sb, istate->cache_tree);
3117 err = write_index_ext_header(f, eoie_c, CACHE_EXT_TREE, sb.len) < 0;
3118 hashwrite(f, sb.buf, sb.len);
3119 strbuf_release(&sb);
3120 if (err)
3121 return -1;
3123 if (write_extensions & WRITE_RESOLVE_UNDO_EXTENSION &&
3124 istate->resolve_undo) {
3125 struct strbuf sb = STRBUF_INIT;
3127 resolve_undo_write(&sb, istate->resolve_undo);
3128 err = write_index_ext_header(f, eoie_c, CACHE_EXT_RESOLVE_UNDO,
3129 sb.len) < 0;
3130 hashwrite(f, sb.buf, sb.len);
3131 strbuf_release(&sb);
3132 if (err)
3133 return -1;
3135 if (write_extensions & WRITE_UNTRACKED_CACHE_EXTENSION &&
3136 istate->untracked) {
3137 struct strbuf sb = STRBUF_INIT;
3139 write_untracked_extension(&sb, istate->untracked);
3140 err = write_index_ext_header(f, eoie_c, CACHE_EXT_UNTRACKED,
3141 sb.len) < 0;
3142 hashwrite(f, sb.buf, sb.len);
3143 strbuf_release(&sb);
3144 if (err)
3145 return -1;
3147 if (write_extensions & WRITE_FSMONITOR_EXTENSION &&
3148 istate->fsmonitor_last_update) {
3149 struct strbuf sb = STRBUF_INIT;
3151 write_fsmonitor_extension(&sb, istate);
3152 err = write_index_ext_header(f, eoie_c, CACHE_EXT_FSMONITOR, sb.len) < 0;
3153 hashwrite(f, sb.buf, sb.len);
3154 strbuf_release(&sb);
3155 if (err)
3156 return -1;
3158 if (istate->sparse_index) {
3159 if (write_index_ext_header(f, eoie_c, CACHE_EXT_SPARSE_DIRECTORIES, 0) < 0)
3160 return -1;
3164 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
3165 * so that it can be found and processed before all the index entries are
3166 * read. Write it out regardless of the strip_extensions parameter as we need it
3167 * when loading the shared index.
3169 if (eoie_c) {
3170 struct strbuf sb = STRBUF_INIT;
3172 write_eoie_extension(&sb, eoie_c, offset);
3173 err = write_index_ext_header(f, NULL, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0;
3174 hashwrite(f, sb.buf, sb.len);
3175 strbuf_release(&sb);
3176 if (err)
3177 return -1;
3180 csum_fsync_flag = 0;
3181 if (!alternate_index_output && (flags & COMMIT_LOCK))
3182 csum_fsync_flag = CSUM_FSYNC;
3184 finalize_hashfile(f, istate->oid.hash, FSYNC_COMPONENT_INDEX,
3185 CSUM_HASH_IN_STREAM | csum_fsync_flag);
3187 if (close_tempfile_gently(tempfile)) {
3188 error(_("could not close '%s'"), get_tempfile_path(tempfile));
3189 return -1;
3191 if (stat(get_tempfile_path(tempfile), &st))
3192 return -1;
3193 istate->timestamp.sec = (unsigned int)st.st_mtime;
3194 istate->timestamp.nsec = ST_MTIME_NSEC(st);
3195 trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
3198 * TODO trace2: replace "the_repository" with the actual repo instance
3199 * that is associated with the given "istate".
3201 trace2_data_intmax("index", the_repository, "write/version",
3202 istate->version);
3203 trace2_data_intmax("index", the_repository, "write/cache_nr",
3204 istate->cache_nr);
3206 return 0;
3209 void set_alternate_index_output(const char *name)
3211 alternate_index_output = name;
3214 static int commit_locked_index(struct lock_file *lk)
3216 if (alternate_index_output)
3217 return commit_lock_file_to(lk, alternate_index_output);
3218 else
3219 return commit_lock_file(lk);
3222 static int do_write_locked_index(struct index_state *istate,
3223 struct lock_file *lock,
3224 unsigned flags,
3225 enum write_extensions write_extensions)
3227 int ret;
3228 int was_full = istate->sparse_index == INDEX_EXPANDED;
3230 ret = convert_to_sparse(istate, 0);
3232 if (ret) {
3233 warning(_("failed to convert to a sparse-index"));
3234 return ret;
3238 * TODO trace2: replace "the_repository" with the actual repo instance
3239 * that is associated with the given "istate".
3241 trace2_region_enter_printf("index", "do_write_index", the_repository,
3242 "%s", get_lock_file_path(lock));
3243 ret = do_write_index(istate, lock->tempfile, write_extensions, flags);
3244 trace2_region_leave_printf("index", "do_write_index", the_repository,
3245 "%s", get_lock_file_path(lock));
3247 if (was_full)
3248 ensure_full_index(istate);
3250 if (ret)
3251 return ret;
3252 if (flags & COMMIT_LOCK)
3253 ret = commit_locked_index(lock);
3254 else
3255 ret = close_lock_file_gently(lock);
3257 run_hooks_l("post-index-change",
3258 istate->updated_workdir ? "1" : "0",
3259 istate->updated_skipworktree ? "1" : "0", NULL);
3260 istate->updated_workdir = 0;
3261 istate->updated_skipworktree = 0;
3263 return ret;
3266 static int write_split_index(struct index_state *istate,
3267 struct lock_file *lock,
3268 unsigned flags)
3270 int ret;
3271 prepare_to_write_split_index(istate);
3272 ret = do_write_locked_index(istate, lock, flags, WRITE_ALL_EXTENSIONS);
3273 finish_writing_split_index(istate);
3274 return ret;
3277 static const char *shared_index_expire = "2.weeks.ago";
3279 static unsigned long get_shared_index_expire_date(void)
3281 static unsigned long shared_index_expire_date;
3282 static int shared_index_expire_date_prepared;
3284 if (!shared_index_expire_date_prepared) {
3285 git_config_get_expiry("splitindex.sharedindexexpire",
3286 &shared_index_expire);
3287 shared_index_expire_date = approxidate(shared_index_expire);
3288 shared_index_expire_date_prepared = 1;
3291 return shared_index_expire_date;
3294 static int should_delete_shared_index(const char *shared_index_path)
3296 struct stat st;
3297 unsigned long expiration;
3299 /* Check timestamp */
3300 expiration = get_shared_index_expire_date();
3301 if (!expiration)
3302 return 0;
3303 if (stat(shared_index_path, &st))
3304 return error_errno(_("could not stat '%s'"), shared_index_path);
3305 if (st.st_mtime > expiration)
3306 return 0;
3308 return 1;
3311 static int clean_shared_index_files(const char *current_hex)
3313 struct dirent *de;
3314 DIR *dir = opendir(get_git_dir());
3316 if (!dir)
3317 return error_errno(_("unable to open git dir: %s"), get_git_dir());
3319 while ((de = readdir(dir)) != NULL) {
3320 const char *sha1_hex;
3321 const char *shared_index_path;
3322 if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
3323 continue;
3324 if (!strcmp(sha1_hex, current_hex))
3325 continue;
3326 shared_index_path = git_path("%s", de->d_name);
3327 if (should_delete_shared_index(shared_index_path) > 0 &&
3328 unlink(shared_index_path))
3329 warning_errno(_("unable to unlink: %s"), shared_index_path);
3331 closedir(dir);
3333 return 0;
3336 static int write_shared_index(struct index_state *istate,
3337 struct tempfile **temp, unsigned flags)
3339 struct split_index *si = istate->split_index;
3340 int ret, was_full = !istate->sparse_index;
3342 move_cache_to_base_index(istate);
3343 convert_to_sparse(istate, 0);
3345 trace2_region_enter_printf("index", "shared/do_write_index",
3346 the_repository, "%s", get_tempfile_path(*temp));
3347 ret = do_write_index(si->base, *temp, WRITE_NO_EXTENSION, flags);
3348 trace2_region_leave_printf("index", "shared/do_write_index",
3349 the_repository, "%s", get_tempfile_path(*temp));
3351 if (was_full)
3352 ensure_full_index(istate);
3354 if (ret)
3355 return ret;
3356 ret = adjust_shared_perm(get_tempfile_path(*temp));
3357 if (ret) {
3358 error(_("cannot fix permission bits on '%s'"), get_tempfile_path(*temp));
3359 return ret;
3361 ret = rename_tempfile(temp,
3362 git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
3363 if (!ret) {
3364 oidcpy(&si->base_oid, &si->base->oid);
3365 clean_shared_index_files(oid_to_hex(&si->base->oid));
3368 return ret;
3371 static const int default_max_percent_split_change = 20;
3373 static int too_many_not_shared_entries(struct index_state *istate)
3375 int i, not_shared = 0;
3376 int max_split = git_config_get_max_percent_split_change();
3378 switch (max_split) {
3379 case -1:
3380 /* not or badly configured: use the default value */
3381 max_split = default_max_percent_split_change;
3382 break;
3383 case 0:
3384 return 1; /* 0% means always write a new shared index */
3385 case 100:
3386 return 0; /* 100% means never write a new shared index */
3387 default:
3388 break; /* just use the configured value */
3391 /* Count not shared entries */
3392 for (i = 0; i < istate->cache_nr; i++) {
3393 struct cache_entry *ce = istate->cache[i];
3394 if (!ce->index)
3395 not_shared++;
3398 return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
3401 int write_locked_index(struct index_state *istate, struct lock_file *lock,
3402 unsigned flags)
3404 int new_shared_index, ret, test_split_index_env;
3405 struct split_index *si = istate->split_index;
3407 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
3408 cache_tree_verify(the_repository, istate);
3410 if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
3411 if (flags & COMMIT_LOCK)
3412 rollback_lock_file(lock);
3413 return 0;
3416 if (istate->fsmonitor_last_update)
3417 fill_fsmonitor_bitmap(istate);
3419 test_split_index_env = git_env_bool("GIT_TEST_SPLIT_INDEX", 0);
3421 if ((!si && !test_split_index_env) ||
3422 alternate_index_output ||
3423 (istate->cache_changed & ~EXTMASK)) {
3424 ret = do_write_locked_index(istate, lock, flags,
3425 ~WRITE_SPLIT_INDEX_EXTENSION);
3426 goto out;
3429 if (test_split_index_env) {
3430 if (!si) {
3431 si = init_split_index(istate);
3432 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3433 } else {
3434 int v = si->base_oid.hash[0];
3435 if ((v & 15) < 6)
3436 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3439 if (too_many_not_shared_entries(istate))
3440 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3442 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
3444 if (new_shared_index) {
3445 struct tempfile *temp;
3446 int saved_errno;
3448 /* Same initial permissions as the main .git/index file */
3449 temp = mks_tempfile_sm(git_path("sharedindex_XXXXXX"), 0, 0666);
3450 if (!temp) {
3451 ret = do_write_locked_index(istate, lock, flags,
3452 ~WRITE_SPLIT_INDEX_EXTENSION);
3453 goto out;
3455 ret = write_shared_index(istate, &temp, flags);
3457 saved_errno = errno;
3458 if (is_tempfile_active(temp))
3459 delete_tempfile(&temp);
3460 errno = saved_errno;
3462 if (ret)
3463 goto out;
3466 ret = write_split_index(istate, lock, flags);
3468 /* Freshen the shared index only if the split-index was written */
3469 if (!ret && !new_shared_index && !is_null_oid(&si->base_oid)) {
3470 const char *shared_index = git_path("sharedindex.%s",
3471 oid_to_hex(&si->base_oid));
3472 freshen_shared_index(shared_index, 1);
3475 out:
3476 if (flags & COMMIT_LOCK)
3477 rollback_lock_file(lock);
3478 return ret;
3482 * Read the index file that is potentially unmerged into given
3483 * index_state, dropping any unmerged entries to stage #0 (potentially
3484 * resulting in a path appearing as both a file and a directory in the
3485 * index; the caller is responsible to clear out the extra entries
3486 * before writing the index to a tree). Returns true if the index is
3487 * unmerged. Callers who want to refuse to work from an unmerged
3488 * state can call this and check its return value, instead of calling
3489 * read_cache().
3491 int repo_read_index_unmerged(struct repository *repo)
3493 struct index_state *istate;
3494 int i;
3495 int unmerged = 0;
3497 repo_read_index(repo);
3498 istate = repo->index;
3499 for (i = 0; i < istate->cache_nr; i++) {
3500 struct cache_entry *ce = istate->cache[i];
3501 struct cache_entry *new_ce;
3502 int len;
3504 if (!ce_stage(ce))
3505 continue;
3506 unmerged = 1;
3507 len = ce_namelen(ce);
3508 new_ce = make_empty_cache_entry(istate, len);
3509 memcpy(new_ce->name, ce->name, len);
3510 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3511 new_ce->ce_namelen = len;
3512 new_ce->ce_mode = ce->ce_mode;
3513 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3514 return error(_("%s: cannot drop to stage #0"),
3515 new_ce->name);
3517 return unmerged;
3521 * Returns 1 if the path is an "other" path with respect to
3522 * the index; that is, the path is not mentioned in the index at all,
3523 * either as a file, a directory with some files in the index,
3524 * or as an unmerged entry.
3526 * We helpfully remove a trailing "/" from directories so that
3527 * the output of read_directory can be used as-is.
3529 int index_name_is_other(struct index_state *istate, const char *name,
3530 int namelen)
3532 int pos;
3533 if (namelen && name[namelen - 1] == '/')
3534 namelen--;
3535 pos = index_name_pos(istate, name, namelen);
3536 if (0 <= pos)
3537 return 0; /* exact match */
3538 pos = -pos - 1;
3539 if (pos < istate->cache_nr) {
3540 struct cache_entry *ce = istate->cache[pos];
3541 if (ce_namelen(ce) == namelen &&
3542 !memcmp(ce->name, name, namelen))
3543 return 0; /* Yup, this one exists unmerged */
3545 return 1;
3548 void *read_blob_data_from_index(struct index_state *istate,
3549 const char *path, unsigned long *size)
3551 int pos, len;
3552 unsigned long sz;
3553 enum object_type type;
3554 void *data;
3556 len = strlen(path);
3557 pos = index_name_pos(istate, path, len);
3558 if (pos < 0) {
3560 * We might be in the middle of a merge, in which
3561 * case we would read stage #2 (ours).
3563 int i;
3564 for (i = -pos - 1;
3565 (pos < 0 && i < istate->cache_nr &&
3566 !strcmp(istate->cache[i]->name, path));
3567 i++)
3568 if (ce_stage(istate->cache[i]) == 2)
3569 pos = i;
3571 if (pos < 0)
3572 return NULL;
3573 data = repo_read_object_file(the_repository, &istate->cache[pos]->oid,
3574 &type, &sz);
3575 if (!data || type != OBJ_BLOB) {
3576 free(data);
3577 return NULL;
3579 if (size)
3580 *size = sz;
3581 return data;
3584 void stat_validity_clear(struct stat_validity *sv)
3586 FREE_AND_NULL(sv->sd);
3589 int stat_validity_check(struct stat_validity *sv, const char *path)
3591 struct stat st;
3593 if (stat(path, &st) < 0)
3594 return sv->sd == NULL;
3595 if (!sv->sd)
3596 return 0;
3597 return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
3600 void stat_validity_update(struct stat_validity *sv, int fd)
3602 struct stat st;
3604 if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
3605 stat_validity_clear(sv);
3606 else {
3607 if (!sv->sd)
3608 CALLOC_ARRAY(sv->sd, 1);
3609 fill_stat_data(sv->sd, &st);
3613 void move_index_extensions(struct index_state *dst, struct index_state *src)
3615 dst->untracked = src->untracked;
3616 src->untracked = NULL;
3617 dst->cache_tree = src->cache_tree;
3618 src->cache_tree = NULL;
3621 struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3622 struct index_state *istate)
3624 unsigned int size = ce_size(ce);
3625 int mem_pool_allocated;
3626 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3627 mem_pool_allocated = new_entry->mem_pool_allocated;
3629 memcpy(new_entry, ce, size);
3630 new_entry->mem_pool_allocated = mem_pool_allocated;
3631 return new_entry;
3634 void discard_cache_entry(struct cache_entry *ce)
3636 if (ce && should_validate_cache_entries())
3637 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3639 if (ce && ce->mem_pool_allocated)
3640 return;
3642 free(ce);
3645 int should_validate_cache_entries(void)
3647 static int validate_index_cache_entries = -1;
3649 if (validate_index_cache_entries < 0) {
3650 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3651 validate_index_cache_entries = 1;
3652 else
3653 validate_index_cache_entries = 0;
3656 return validate_index_cache_entries;
3659 #define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3660 #define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3662 static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3665 * The end of index entries (EOIE) extension is guaranteed to be last
3666 * so that it can be found by scanning backwards from the EOF.
3668 * "EOIE"
3669 * <4-byte length>
3670 * <4-byte offset>
3671 * <20-byte hash>
3673 const char *index, *eoie;
3674 uint32_t extsize;
3675 size_t offset, src_offset;
3676 unsigned char hash[GIT_MAX_RAWSZ];
3677 git_hash_ctx c;
3679 /* ensure we have an index big enough to contain an EOIE extension */
3680 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3681 return 0;
3683 /* validate the extension signature */
3684 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3685 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3686 return 0;
3687 index += sizeof(uint32_t);
3689 /* validate the extension size */
3690 extsize = get_be32(index);
3691 if (extsize != EOIE_SIZE)
3692 return 0;
3693 index += sizeof(uint32_t);
3696 * Validate the offset we're going to look for the first extension
3697 * signature is after the index header and before the eoie extension.
3699 offset = get_be32(index);
3700 if (mmap + offset < mmap + sizeof(struct cache_header))
3701 return 0;
3702 if (mmap + offset >= eoie)
3703 return 0;
3704 index += sizeof(uint32_t);
3707 * The hash is computed over extension types and their sizes (but not
3708 * their contents). E.g. if we have "TREE" extension that is N-bytes
3709 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3710 * then the hash would be:
3712 * SHA-1("TREE" + <binary representation of N> +
3713 * "REUC" + <binary representation of M>)
3715 src_offset = offset;
3716 the_hash_algo->init_fn(&c);
3717 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3718 /* After an array of active_nr index entries,
3719 * there can be arbitrary number of extended
3720 * sections, each of which is prefixed with
3721 * extension name (4-byte) and section length
3722 * in 4-byte network byte order.
3724 uint32_t extsize;
3725 memcpy(&extsize, mmap + src_offset + 4, 4);
3726 extsize = ntohl(extsize);
3728 /* verify the extension size isn't so large it will wrap around */
3729 if (src_offset + 8 + extsize < src_offset)
3730 return 0;
3732 the_hash_algo->update_fn(&c, mmap + src_offset, 8);
3734 src_offset += 8;
3735 src_offset += extsize;
3737 the_hash_algo->final_fn(hash, &c);
3738 if (!hasheq(hash, (const unsigned char *)index))
3739 return 0;
3741 /* Validate that the extension offsets returned us back to the eoie extension. */
3742 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3743 return 0;
3745 return offset;
3748 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset)
3750 uint32_t buffer;
3751 unsigned char hash[GIT_MAX_RAWSZ];
3753 /* offset */
3754 put_be32(&buffer, offset);
3755 strbuf_add(sb, &buffer, sizeof(uint32_t));
3757 /* hash */
3758 the_hash_algo->final_fn(hash, eoie_context);
3759 strbuf_add(sb, hash, the_hash_algo->rawsz);
3762 #define IEOT_VERSION (1)
3764 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3766 const char *index = NULL;
3767 uint32_t extsize, ext_version;
3768 struct index_entry_offset_table *ieot;
3769 int i, nr;
3771 /* find the IEOT extension */
3772 if (!offset)
3773 return NULL;
3774 while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3775 extsize = get_be32(mmap + offset + 4);
3776 if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3777 index = mmap + offset + 4 + 4;
3778 break;
3780 offset += 8;
3781 offset += extsize;
3783 if (!index)
3784 return NULL;
3786 /* validate the version is IEOT_VERSION */
3787 ext_version = get_be32(index);
3788 if (ext_version != IEOT_VERSION) {
3789 error("invalid IEOT version %d", ext_version);
3790 return NULL;
3792 index += sizeof(uint32_t);
3794 /* extension size - version bytes / bytes per entry */
3795 nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3796 if (!nr) {
3797 error("invalid number of IEOT entries %d", nr);
3798 return NULL;
3800 ieot = xmalloc(sizeof(struct index_entry_offset_table)
3801 + (nr * sizeof(struct index_entry_offset)));
3802 ieot->nr = nr;
3803 for (i = 0; i < nr; i++) {
3804 ieot->entries[i].offset = get_be32(index);
3805 index += sizeof(uint32_t);
3806 ieot->entries[i].nr = get_be32(index);
3807 index += sizeof(uint32_t);
3810 return ieot;
3813 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3815 uint32_t buffer;
3816 int i;
3818 /* version */
3819 put_be32(&buffer, IEOT_VERSION);
3820 strbuf_add(sb, &buffer, sizeof(uint32_t));
3822 /* ieot */
3823 for (i = 0; i < ieot->nr; i++) {
3825 /* offset */
3826 put_be32(&buffer, ieot->entries[i].offset);
3827 strbuf_add(sb, &buffer, sizeof(uint32_t));
3829 /* count */
3830 put_be32(&buffer, ieot->entries[i].nr);
3831 strbuf_add(sb, &buffer, sizeof(uint32_t));
3835 void prefetch_cache_entries(const struct index_state *istate,
3836 must_prefetch_predicate must_prefetch)
3838 int i;
3839 struct oid_array to_fetch = OID_ARRAY_INIT;
3841 for (i = 0; i < istate->cache_nr; i++) {
3842 struct cache_entry *ce = istate->cache[i];
3844 if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce))
3845 continue;
3846 if (!oid_object_info_extended(the_repository, &ce->oid,
3847 NULL,
3848 OBJECT_INFO_FOR_PREFETCH))
3849 continue;
3850 oid_array_append(&to_fetch, &ce->oid);
3852 promisor_remote_get_direct(the_repository,
3853 to_fetch.oid, to_fetch.nr);
3854 oid_array_clear(&to_fetch);