Sync with 2.42.2
[git.git] / read-cache.c
blob7be3bb3449f920608044af9c6c3cfb45824948b8
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "git-compat-util.h"
7 #include "bulk-checkin.h"
8 #include "config.h"
9 #include "date.h"
10 #include "diff.h"
11 #include "diffcore.h"
12 #include "hex.h"
13 #include "tempfile.h"
14 #include "lockfile.h"
15 #include "cache-tree.h"
16 #include "refs.h"
17 #include "dir.h"
18 #include "object-file.h"
19 #include "object-store-ll.h"
20 #include "oid-array.h"
21 #include "tree.h"
22 #include "commit.h"
23 #include "environment.h"
24 #include "gettext.h"
25 #include "mem-pool.h"
26 #include "name-hash.h"
27 #include "object-name.h"
28 #include "path.h"
29 #include "preload-index.h"
30 #include "read-cache.h"
31 #include "resolve-undo.h"
32 #include "revision.h"
33 #include "strbuf.h"
34 #include "trace2.h"
35 #include "varint.h"
36 #include "split-index.h"
37 #include "symlinks.h"
38 #include "utf8.h"
39 #include "fsmonitor.h"
40 #include "thread-utils.h"
41 #include "progress.h"
42 #include "sparse-index.h"
43 #include "csum-file.h"
44 #include "promisor-remote.h"
45 #include "hook.h"
47 /* Mask for the name length in ce_flags in the on-disk index */
49 #define CE_NAMEMASK (0x0fff)
51 /* Index extensions.
53 * The first letter should be 'A'..'Z' for extensions that are not
54 * necessary for a correct operation (i.e. optimization data).
55 * When new extensions are added that _needs_ to be understood in
56 * order to correctly interpret the index file, pick character that
57 * is outside the range, to cause the reader to abort.
60 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
61 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
62 #define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
63 #define CACHE_EXT_LINK 0x6c696e6b /* "link" */
64 #define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
65 #define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
66 #define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945 /* "EOIE" */
67 #define CACHE_EXT_INDEXENTRYOFFSETTABLE 0x49454F54 /* "IEOT" */
68 #define CACHE_EXT_SPARSE_DIRECTORIES 0x73646972 /* "sdir" */
70 /* changes that can be kept in $GIT_DIR/index (basically all extensions) */
71 #define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
72 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
73 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
77 * This is an estimate of the pathname length in the index. We use
78 * this for V4 index files to guess the un-deltafied size of the index
79 * in memory because of pathname deltafication. This is not required
80 * for V2/V3 index formats because their pathnames are not compressed.
81 * If the initial amount of memory set aside is not sufficient, the
82 * mem pool will allocate extra memory.
84 #define CACHE_ENTRY_PATH_LENGTH 80
86 enum index_search_mode {
87 NO_EXPAND_SPARSE = 0,
88 EXPAND_SPARSE = 1
91 static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
93 struct cache_entry *ce;
94 ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
95 ce->mem_pool_allocated = 1;
96 return ce;
99 static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
101 struct cache_entry * ce;
102 ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
103 ce->mem_pool_allocated = 1;
104 return ce;
107 static struct mem_pool *find_mem_pool(struct index_state *istate)
109 struct mem_pool **pool_ptr;
111 if (istate->split_index && istate->split_index->base)
112 pool_ptr = &istate->split_index->base->ce_mem_pool;
113 else
114 pool_ptr = &istate->ce_mem_pool;
116 if (!*pool_ptr) {
117 *pool_ptr = xmalloc(sizeof(**pool_ptr));
118 mem_pool_init(*pool_ptr, 0);
121 return *pool_ptr;
124 static const char *alternate_index_output;
126 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
128 if (S_ISSPARSEDIR(ce->ce_mode))
129 istate->sparse_index = INDEX_COLLAPSED;
131 istate->cache[nr] = ce;
132 add_name_hash(istate, ce);
135 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
137 struct cache_entry *old = istate->cache[nr];
139 replace_index_entry_in_base(istate, old, ce);
140 remove_name_hash(istate, old);
141 discard_cache_entry(old);
142 ce->ce_flags &= ~CE_HASHED;
143 set_index_entry(istate, nr, ce);
144 ce->ce_flags |= CE_UPDATE_IN_BASE;
145 mark_fsmonitor_invalid(istate, ce);
146 istate->cache_changed |= CE_ENTRY_CHANGED;
149 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
151 struct cache_entry *old_entry = istate->cache[nr], *new_entry, *refreshed;
152 int namelen = strlen(new_name);
154 new_entry = make_empty_cache_entry(istate, namelen);
155 copy_cache_entry(new_entry, old_entry);
156 new_entry->ce_flags &= ~CE_HASHED;
157 new_entry->ce_namelen = namelen;
158 new_entry->index = 0;
159 memcpy(new_entry->name, new_name, namelen + 1);
161 cache_tree_invalidate_path(istate, old_entry->name);
162 untracked_cache_remove_from_index(istate, old_entry->name);
163 remove_index_entry_at(istate, nr);
166 * Refresh the new index entry. Using 'refresh_cache_entry' ensures
167 * we only update stat info if the entry is otherwise up-to-date (i.e.,
168 * the contents/mode haven't changed). This ensures that we reflect the
169 * 'ctime' of the rename in the index without (incorrectly) updating
170 * the cached stat info to reflect unstaged changes on disk.
172 refreshed = refresh_cache_entry(istate, new_entry, CE_MATCH_REFRESH);
173 if (refreshed && refreshed != new_entry) {
174 add_index_entry(istate, refreshed, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
175 discard_cache_entry(new_entry);
176 } else
177 add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
181 * This only updates the "non-critical" parts of the directory
182 * cache, ie the parts that aren't tracked by GIT, and only used
183 * to validate the cache.
185 void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st)
187 fill_stat_data(&ce->ce_stat_data, st);
189 if (assume_unchanged)
190 ce->ce_flags |= CE_VALID;
192 if (S_ISREG(st->st_mode)) {
193 ce_mark_uptodate(ce);
194 mark_fsmonitor_valid(istate, ce);
198 static int ce_compare_data(struct index_state *istate,
199 const struct cache_entry *ce,
200 struct stat *st)
202 int match = -1;
203 int fd = git_open_cloexec(ce->name, O_RDONLY);
205 if (fd >= 0) {
206 struct object_id oid;
207 if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
208 match = !oideq(&oid, &ce->oid);
209 /* index_fd() closed the file descriptor already */
211 return match;
214 static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
216 int match = -1;
217 void *buffer;
218 unsigned long size;
219 enum object_type type;
220 struct strbuf sb = STRBUF_INIT;
222 if (strbuf_readlink(&sb, ce->name, expected_size))
223 return -1;
225 buffer = repo_read_object_file(the_repository, &ce->oid, &type, &size);
226 if (buffer) {
227 if (size == sb.len)
228 match = memcmp(buffer, sb.buf, size);
229 free(buffer);
231 strbuf_release(&sb);
232 return match;
235 static int ce_compare_gitlink(const struct cache_entry *ce)
237 struct object_id oid;
240 * We don't actually require that the .git directory
241 * under GITLINK directory be a valid git directory. It
242 * might even be missing (in case nobody populated that
243 * sub-project).
245 * If so, we consider it always to match.
247 if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
248 return 0;
249 return !oideq(&oid, &ce->oid);
252 static int ce_modified_check_fs(struct index_state *istate,
253 const struct cache_entry *ce,
254 struct stat *st)
256 switch (st->st_mode & S_IFMT) {
257 case S_IFREG:
258 if (ce_compare_data(istate, ce, st))
259 return DATA_CHANGED;
260 break;
261 case S_IFLNK:
262 if (ce_compare_link(ce, xsize_t(st->st_size)))
263 return DATA_CHANGED;
264 break;
265 case S_IFDIR:
266 if (S_ISGITLINK(ce->ce_mode))
267 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
268 /* else fallthrough */
269 default:
270 return TYPE_CHANGED;
272 return 0;
275 static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
277 unsigned int changed = 0;
279 if (ce->ce_flags & CE_REMOVE)
280 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
282 switch (ce->ce_mode & S_IFMT) {
283 case S_IFREG:
284 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
285 /* We consider only the owner x bit to be relevant for
286 * "mode changes"
288 if (trust_executable_bit &&
289 (0100 & (ce->ce_mode ^ st->st_mode)))
290 changed |= MODE_CHANGED;
291 break;
292 case S_IFLNK:
293 if (!S_ISLNK(st->st_mode) &&
294 (has_symlinks || !S_ISREG(st->st_mode)))
295 changed |= TYPE_CHANGED;
296 break;
297 case S_IFGITLINK:
298 /* We ignore most of the st_xxx fields for gitlinks */
299 if (!S_ISDIR(st->st_mode))
300 changed |= TYPE_CHANGED;
301 else if (ce_compare_gitlink(ce))
302 changed |= DATA_CHANGED;
303 return changed;
304 default:
305 BUG("unsupported ce_mode: %o", ce->ce_mode);
308 changed |= match_stat_data(&ce->ce_stat_data, st);
310 /* Racily smudged entry? */
311 if (!ce->ce_stat_data.sd_size) {
312 if (!is_empty_blob_sha1(ce->oid.hash))
313 changed |= DATA_CHANGED;
316 return changed;
319 static int is_racy_stat(const struct index_state *istate,
320 const struct stat_data *sd)
322 return (istate->timestamp.sec &&
323 #ifdef USE_NSEC
324 /* nanosecond timestamped files can also be racy! */
325 (istate->timestamp.sec < sd->sd_mtime.sec ||
326 (istate->timestamp.sec == sd->sd_mtime.sec &&
327 istate->timestamp.nsec <= sd->sd_mtime.nsec))
328 #else
329 istate->timestamp.sec <= sd->sd_mtime.sec
330 #endif
334 int is_racy_timestamp(const struct index_state *istate,
335 const struct cache_entry *ce)
337 return (!S_ISGITLINK(ce->ce_mode) &&
338 is_racy_stat(istate, &ce->ce_stat_data));
341 int match_stat_data_racy(const struct index_state *istate,
342 const struct stat_data *sd, struct stat *st)
344 if (is_racy_stat(istate, sd))
345 return MTIME_CHANGED;
346 return match_stat_data(sd, st);
349 int ie_match_stat(struct index_state *istate,
350 const struct cache_entry *ce, struct stat *st,
351 unsigned int options)
353 unsigned int changed;
354 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
355 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
356 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
357 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
359 if (!ignore_fsmonitor)
360 refresh_fsmonitor(istate);
362 * If it's marked as always valid in the index, it's
363 * valid whatever the checked-out copy says.
365 * skip-worktree has the same effect with higher precedence
367 if (!ignore_skip_worktree && ce_skip_worktree(ce))
368 return 0;
369 if (!ignore_valid && (ce->ce_flags & CE_VALID))
370 return 0;
371 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
372 return 0;
375 * Intent-to-add entries have not been added, so the index entry
376 * by definition never matches what is in the work tree until it
377 * actually gets added.
379 if (ce_intent_to_add(ce))
380 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
382 changed = ce_match_stat_basic(ce, st);
385 * Within 1 second of this sequence:
386 * echo xyzzy >file && git-update-index --add file
387 * running this command:
388 * echo frotz >file
389 * would give a falsely clean cache entry. The mtime and
390 * length match the cache, and other stat fields do not change.
392 * We could detect this at update-index time (the cache entry
393 * being registered/updated records the same time as "now")
394 * and delay the return from git-update-index, but that would
395 * effectively mean we can make at most one commit per second,
396 * which is not acceptable. Instead, we check cache entries
397 * whose mtime are the same as the index file timestamp more
398 * carefully than others.
400 if (!changed && is_racy_timestamp(istate, ce)) {
401 if (assume_racy_is_modified)
402 changed |= DATA_CHANGED;
403 else
404 changed |= ce_modified_check_fs(istate, ce, st);
407 return changed;
410 int ie_modified(struct index_state *istate,
411 const struct cache_entry *ce,
412 struct stat *st, unsigned int options)
414 int changed, changed_fs;
416 changed = ie_match_stat(istate, ce, st, options);
417 if (!changed)
418 return 0;
420 * If the mode or type has changed, there's no point in trying
421 * to refresh the entry - it's not going to match
423 if (changed & (MODE_CHANGED | TYPE_CHANGED))
424 return changed;
427 * Immediately after read-tree or update-index --cacheinfo,
428 * the length field is zero, as we have never even read the
429 * lstat(2) information once, and we cannot trust DATA_CHANGED
430 * returned by ie_match_stat() which in turn was returned by
431 * ce_match_stat_basic() to signal that the filesize of the
432 * blob changed. We have to actually go to the filesystem to
433 * see if the contents match, and if so, should answer "unchanged".
435 * The logic does not apply to gitlinks, as ce_match_stat_basic()
436 * already has checked the actual HEAD from the filesystem in the
437 * subproject. If ie_match_stat() already said it is different,
438 * then we know it is.
440 if ((changed & DATA_CHANGED) &&
441 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
442 return changed;
444 changed_fs = ce_modified_check_fs(istate, ce, st);
445 if (changed_fs)
446 return changed | changed_fs;
447 return 0;
450 static int cache_name_stage_compare(const char *name1, int len1, int stage1,
451 const char *name2, int len2, int stage2)
453 int cmp;
455 cmp = name_compare(name1, len1, name2, len2);
456 if (cmp)
457 return cmp;
459 if (stage1 < stage2)
460 return -1;
461 if (stage1 > stage2)
462 return 1;
463 return 0;
466 int cmp_cache_name_compare(const void *a_, const void *b_)
468 const struct cache_entry *ce1, *ce2;
470 ce1 = *((const struct cache_entry **)a_);
471 ce2 = *((const struct cache_entry **)b_);
472 return cache_name_stage_compare(ce1->name, ce1->ce_namelen, ce_stage(ce1),
473 ce2->name, ce2->ce_namelen, ce_stage(ce2));
476 static int index_name_stage_pos(struct index_state *istate,
477 const char *name, int namelen,
478 int stage,
479 enum index_search_mode search_mode)
481 int first, last;
483 first = 0;
484 last = istate->cache_nr;
485 while (last > first) {
486 int next = first + ((last - first) >> 1);
487 struct cache_entry *ce = istate->cache[next];
488 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
489 if (!cmp)
490 return next;
491 if (cmp < 0) {
492 last = next;
493 continue;
495 first = next+1;
498 if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
499 first > 0) {
500 /* Note: first <= istate->cache_nr */
501 struct cache_entry *ce = istate->cache[first - 1];
504 * If we are in a sparse-index _and_ the entry before the
505 * insertion position is a sparse-directory entry that is
506 * an ancestor of 'name', then we need to expand the index
507 * and search again. This will only trigger once, because
508 * thereafter the index is fully expanded.
510 if (S_ISSPARSEDIR(ce->ce_mode) &&
511 ce_namelen(ce) < namelen &&
512 !strncmp(name, ce->name, ce_namelen(ce))) {
513 ensure_full_index(istate);
514 return index_name_stage_pos(istate, name, namelen, stage, search_mode);
518 return -first-1;
521 int index_name_pos(struct index_state *istate, const char *name, int namelen)
523 return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
526 int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
528 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
531 int index_entry_exists(struct index_state *istate, const char *name, int namelen)
533 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
536 int remove_index_entry_at(struct index_state *istate, int pos)
538 struct cache_entry *ce = istate->cache[pos];
540 record_resolve_undo(istate, ce);
541 remove_name_hash(istate, ce);
542 save_or_free_index_entry(istate, ce);
543 istate->cache_changed |= CE_ENTRY_REMOVED;
544 istate->cache_nr--;
545 if (pos >= istate->cache_nr)
546 return 0;
547 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
548 istate->cache_nr - pos);
549 return 1;
553 * Remove all cache entries marked for removal, that is where
554 * CE_REMOVE is set in ce_flags. This is much more effective than
555 * calling remove_index_entry_at() for each entry to be removed.
557 void remove_marked_cache_entries(struct index_state *istate, int invalidate)
559 struct cache_entry **ce_array = istate->cache;
560 unsigned int i, j;
562 for (i = j = 0; i < istate->cache_nr; i++) {
563 if (ce_array[i]->ce_flags & CE_REMOVE) {
564 if (invalidate) {
565 cache_tree_invalidate_path(istate,
566 ce_array[i]->name);
567 untracked_cache_remove_from_index(istate,
568 ce_array[i]->name);
570 remove_name_hash(istate, ce_array[i]);
571 save_or_free_index_entry(istate, ce_array[i]);
573 else
574 ce_array[j++] = ce_array[i];
576 if (j == istate->cache_nr)
577 return;
578 istate->cache_changed |= CE_ENTRY_REMOVED;
579 istate->cache_nr = j;
582 int remove_file_from_index(struct index_state *istate, const char *path)
584 int pos = index_name_pos(istate, path, strlen(path));
585 if (pos < 0)
586 pos = -pos-1;
587 cache_tree_invalidate_path(istate, path);
588 untracked_cache_remove_from_index(istate, path);
589 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
590 remove_index_entry_at(istate, pos);
591 return 0;
594 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
596 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
599 static int index_name_pos_also_unmerged(struct index_state *istate,
600 const char *path, int namelen)
602 int pos = index_name_pos(istate, path, namelen);
603 struct cache_entry *ce;
605 if (pos >= 0)
606 return pos;
608 /* maybe unmerged? */
609 pos = -1 - pos;
610 if (pos >= istate->cache_nr ||
611 compare_name((ce = istate->cache[pos]), path, namelen))
612 return -1;
614 /* order of preference: stage 2, 1, 3 */
615 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
616 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
617 !compare_name(ce, path, namelen))
618 pos++;
619 return pos;
622 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
624 int len = ce_namelen(ce);
625 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
629 * If we add a filename that aliases in the cache, we will use the
630 * name that we already have - but we don't want to update the same
631 * alias twice, because that implies that there were actually two
632 * different files with aliasing names!
634 * So we use the CE_ADDED flag to verify that the alias was an old
635 * one before we accept it as
637 static struct cache_entry *create_alias_ce(struct index_state *istate,
638 struct cache_entry *ce,
639 struct cache_entry *alias)
641 int len;
642 struct cache_entry *new_entry;
644 if (alias->ce_flags & CE_ADDED)
645 die(_("will not add file alias '%s' ('%s' already exists in index)"),
646 ce->name, alias->name);
648 /* Ok, create the new entry using the name of the existing alias */
649 len = ce_namelen(alias);
650 new_entry = make_empty_cache_entry(istate, len);
651 memcpy(new_entry->name, alias->name, len);
652 copy_cache_entry(new_entry, ce);
653 save_or_free_index_entry(istate, ce);
654 return new_entry;
657 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
659 struct object_id oid;
660 if (write_object_file("", 0, OBJ_BLOB, &oid))
661 die(_("cannot create an empty blob in the object database"));
662 oidcpy(&ce->oid, &oid);
665 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
667 int namelen, was_same;
668 mode_t st_mode = st->st_mode;
669 struct cache_entry *ce, *alias = NULL;
670 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
671 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
672 int pretend = flags & ADD_CACHE_PRETEND;
673 int intent_only = flags & ADD_CACHE_INTENT;
674 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
675 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
676 unsigned hash_flags = pretend ? 0 : HASH_WRITE_OBJECT;
677 struct object_id oid;
679 if (flags & ADD_CACHE_RENORMALIZE)
680 hash_flags |= HASH_RENORMALIZE;
682 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
683 return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
685 namelen = strlen(path);
686 if (S_ISDIR(st_mode)) {
687 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
688 return error(_("'%s' does not have a commit checked out"), path);
689 while (namelen && path[namelen-1] == '/')
690 namelen--;
692 ce = make_empty_cache_entry(istate, namelen);
693 memcpy(ce->name, path, namelen);
694 ce->ce_namelen = namelen;
695 if (!intent_only)
696 fill_stat_cache_info(istate, ce, st);
697 else
698 ce->ce_flags |= CE_INTENT_TO_ADD;
701 if (trust_executable_bit && has_symlinks) {
702 ce->ce_mode = create_ce_mode(st_mode);
703 } else {
704 /* If there is an existing entry, pick the mode bits and type
705 * from it, otherwise assume unexecutable regular file.
707 struct cache_entry *ent;
708 int pos = index_name_pos_also_unmerged(istate, path, namelen);
710 ent = (0 <= pos) ? istate->cache[pos] : NULL;
711 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
714 /* When core.ignorecase=true, determine if a directory of the same name but differing
715 * case already exists within the Git repository. If it does, ensure the directory
716 * case of the file being added to the repository matches (is folded into) the existing
717 * entry's directory case.
719 if (ignore_case) {
720 adjust_dirname_case(istate, ce->name);
722 if (!(flags & ADD_CACHE_RENORMALIZE)) {
723 alias = index_file_exists(istate, ce->name,
724 ce_namelen(ce), ignore_case);
725 if (alias &&
726 !ce_stage(alias) &&
727 !ie_match_stat(istate, alias, st, ce_option)) {
728 /* Nothing changed, really */
729 if (!S_ISGITLINK(alias->ce_mode))
730 ce_mark_uptodate(alias);
731 alias->ce_flags |= CE_ADDED;
733 discard_cache_entry(ce);
734 return 0;
737 if (!intent_only) {
738 if (index_path(istate, &ce->oid, path, st, hash_flags)) {
739 discard_cache_entry(ce);
740 return error(_("unable to index file '%s'"), path);
742 } else
743 set_object_name_for_intent_to_add_entry(ce);
745 if (ignore_case && alias && different_name(ce, alias))
746 ce = create_alias_ce(istate, ce, alias);
747 ce->ce_flags |= CE_ADDED;
749 /* It was suspected to be racily clean, but it turns out to be Ok */
750 was_same = (alias &&
751 !ce_stage(alias) &&
752 oideq(&alias->oid, &ce->oid) &&
753 ce->ce_mode == alias->ce_mode);
755 if (pretend)
756 discard_cache_entry(ce);
757 else if (add_index_entry(istate, ce, add_option)) {
758 discard_cache_entry(ce);
759 return error(_("unable to add '%s' to index"), path);
761 if (verbose && !was_same)
762 printf("add '%s'\n", path);
763 return 0;
766 int add_file_to_index(struct index_state *istate, const char *path, int flags)
768 struct stat st;
769 if (lstat(path, &st))
770 die_errno(_("unable to stat '%s'"), path);
771 return add_to_index(istate, path, &st, flags);
774 struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
776 return mem_pool__ce_calloc(find_mem_pool(istate), len);
779 struct cache_entry *make_empty_transient_cache_entry(size_t len,
780 struct mem_pool *ce_mem_pool)
782 if (ce_mem_pool)
783 return mem_pool__ce_calloc(ce_mem_pool, len);
784 return xcalloc(1, cache_entry_size(len));
787 enum verify_path_result {
788 PATH_OK,
789 PATH_INVALID,
790 PATH_DIR_WITH_SEP,
793 static enum verify_path_result verify_path_internal(const char *, unsigned);
795 int verify_path(const char *path, unsigned mode)
797 return verify_path_internal(path, mode) == PATH_OK;
800 struct cache_entry *make_cache_entry(struct index_state *istate,
801 unsigned int mode,
802 const struct object_id *oid,
803 const char *path,
804 int stage,
805 unsigned int refresh_options)
807 struct cache_entry *ce, *ret;
808 int len;
810 if (verify_path_internal(path, mode) == PATH_INVALID) {
811 error(_("invalid path '%s'"), path);
812 return NULL;
815 len = strlen(path);
816 ce = make_empty_cache_entry(istate, len);
818 oidcpy(&ce->oid, oid);
819 memcpy(ce->name, path, len);
820 ce->ce_flags = create_ce_flags(stage);
821 ce->ce_namelen = len;
822 ce->ce_mode = create_ce_mode(mode);
824 ret = refresh_cache_entry(istate, ce, refresh_options);
825 if (ret != ce)
826 discard_cache_entry(ce);
827 return ret;
830 struct cache_entry *make_transient_cache_entry(unsigned int mode,
831 const struct object_id *oid,
832 const char *path,
833 int stage,
834 struct mem_pool *ce_mem_pool)
836 struct cache_entry *ce;
837 int len;
839 if (!verify_path(path, mode)) {
840 error(_("invalid path '%s'"), path);
841 return NULL;
844 len = strlen(path);
845 ce = make_empty_transient_cache_entry(len, ce_mem_pool);
847 oidcpy(&ce->oid, oid);
848 memcpy(ce->name, path, len);
849 ce->ce_flags = create_ce_flags(stage);
850 ce->ce_namelen = len;
851 ce->ce_mode = create_ce_mode(mode);
853 return ce;
857 * Chmod an index entry with either +x or -x.
859 * Returns -1 if the chmod for the particular cache entry failed (if it's
860 * not a regular file), -2 if an invalid flip argument is passed in, 0
861 * otherwise.
863 int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
864 char flip)
866 if (!S_ISREG(ce->ce_mode))
867 return -1;
868 switch (flip) {
869 case '+':
870 ce->ce_mode |= 0111;
871 break;
872 case '-':
873 ce->ce_mode &= ~0111;
874 break;
875 default:
876 return -2;
878 cache_tree_invalidate_path(istate, ce->name);
879 ce->ce_flags |= CE_UPDATE_IN_BASE;
880 mark_fsmonitor_invalid(istate, ce);
881 istate->cache_changed |= CE_ENTRY_CHANGED;
883 return 0;
886 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
888 int len = ce_namelen(a);
889 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
893 * We fundamentally don't like some paths: we don't want
894 * dot or dot-dot anywhere, and for obvious reasons don't
895 * want to recurse into ".git" either.
897 * Also, we don't want double slashes or slashes at the
898 * end that can make pathnames ambiguous.
900 static int verify_dotfile(const char *rest, unsigned mode)
903 * The first character was '.', but that
904 * has already been discarded, we now test
905 * the rest.
908 /* "." is not allowed */
909 if (*rest == '\0' || is_dir_sep(*rest))
910 return 0;
912 switch (*rest) {
914 * ".git" followed by NUL or slash is bad. Note that we match
915 * case-insensitively here, even if ignore_case is not set.
916 * This outlaws ".GIT" everywhere out of an abundance of caution,
917 * since there's really no good reason to allow it.
919 * Once we've seen ".git", we can also find ".gitmodules", etc (also
920 * case-insensitively).
922 case 'g':
923 case 'G':
924 if (rest[1] != 'i' && rest[1] != 'I')
925 break;
926 if (rest[2] != 't' && rest[2] != 'T')
927 break;
928 if (rest[3] == '\0' || is_dir_sep(rest[3]))
929 return 0;
930 if (S_ISLNK(mode)) {
931 rest += 3;
932 if (skip_iprefix(rest, "modules", &rest) &&
933 (*rest == '\0' || is_dir_sep(*rest)))
934 return 0;
936 break;
937 case '.':
938 if (rest[1] == '\0' || is_dir_sep(rest[1]))
939 return 0;
941 return 1;
944 static enum verify_path_result verify_path_internal(const char *path,
945 unsigned mode)
947 char c = 0;
949 if (has_dos_drive_prefix(path))
950 return PATH_INVALID;
952 if (!is_valid_path(path))
953 return PATH_INVALID;
955 goto inside;
956 for (;;) {
957 if (!c)
958 return PATH_OK;
959 if (is_dir_sep(c)) {
960 inside:
961 if (protect_hfs) {
963 if (is_hfs_dotgit(path))
964 return PATH_INVALID;
965 if (S_ISLNK(mode)) {
966 if (is_hfs_dotgitmodules(path))
967 return PATH_INVALID;
970 if (protect_ntfs) {
971 #if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
972 if (c == '\\')
973 return PATH_INVALID;
974 #endif
975 if (is_ntfs_dotgit(path))
976 return PATH_INVALID;
977 if (S_ISLNK(mode)) {
978 if (is_ntfs_dotgitmodules(path))
979 return PATH_INVALID;
983 c = *path++;
984 if ((c == '.' && !verify_dotfile(path, mode)) ||
985 is_dir_sep(c))
986 return PATH_INVALID;
988 * allow terminating directory separators for
989 * sparse directory entries.
991 if (c == '\0')
992 return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
993 PATH_INVALID;
994 } else if (c == '\\' && protect_ntfs) {
995 if (is_ntfs_dotgit(path))
996 return PATH_INVALID;
997 if (S_ISLNK(mode)) {
998 if (is_ntfs_dotgitmodules(path))
999 return PATH_INVALID;
1003 c = *path++;
1008 * Do we have another file that has the beginning components being a
1009 * proper superset of the name we're trying to add?
1011 static int has_file_name(struct index_state *istate,
1012 const struct cache_entry *ce, int pos, int ok_to_replace)
1014 int retval = 0;
1015 int len = ce_namelen(ce);
1016 int stage = ce_stage(ce);
1017 const char *name = ce->name;
1019 while (pos < istate->cache_nr) {
1020 struct cache_entry *p = istate->cache[pos++];
1022 if (len >= ce_namelen(p))
1023 break;
1024 if (memcmp(name, p->name, len))
1025 break;
1026 if (ce_stage(p) != stage)
1027 continue;
1028 if (p->name[len] != '/')
1029 continue;
1030 if (p->ce_flags & CE_REMOVE)
1031 continue;
1032 retval = -1;
1033 if (!ok_to_replace)
1034 break;
1035 remove_index_entry_at(istate, --pos);
1037 return retval;
1042 * Like strcmp(), but also return the offset of the first change.
1043 * If strings are equal, return the length.
1045 int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1047 size_t k;
1049 if (!first_change)
1050 return strcmp(s1, s2);
1052 for (k = 0; s1[k] == s2[k]; k++)
1053 if (s1[k] == '\0')
1054 break;
1056 *first_change = k;
1057 return (unsigned char)s1[k] - (unsigned char)s2[k];
1061 * Do we have another file with a pathname that is a proper
1062 * subset of the name we're trying to add?
1064 * That is, is there another file in the index with a path
1065 * that matches a sub-directory in the given entry?
1067 static int has_dir_name(struct index_state *istate,
1068 const struct cache_entry *ce, int pos, int ok_to_replace)
1070 int retval = 0;
1071 int stage = ce_stage(ce);
1072 const char *name = ce->name;
1073 const char *slash = name + ce_namelen(ce);
1074 size_t len_eq_last;
1075 int cmp_last = 0;
1078 * We are frequently called during an iteration on a sorted
1079 * list of pathnames and while building a new index. Therefore,
1080 * there is a high probability that this entry will eventually
1081 * be appended to the index, rather than inserted in the middle.
1082 * If we can confirm that, we can avoid binary searches on the
1083 * components of the pathname.
1085 * Compare the entry's full path with the last path in the index.
1087 if (istate->cache_nr > 0) {
1088 cmp_last = strcmp_offset(name,
1089 istate->cache[istate->cache_nr - 1]->name,
1090 &len_eq_last);
1091 if (cmp_last > 0) {
1092 if (name[len_eq_last] != '/') {
1094 * The entry sorts AFTER the last one in the
1095 * index.
1097 * If there were a conflict with "file", then our
1098 * name would start with "file/" and the last index
1099 * entry would start with "file" but not "file/".
1101 * The next character after common prefix is
1102 * not '/', so there can be no conflict.
1104 return retval;
1105 } else {
1107 * The entry sorts AFTER the last one in the
1108 * index, and the next character after common
1109 * prefix is '/'.
1111 * Either the last index entry is a file in
1112 * conflict with this entry, or it has a name
1113 * which sorts between this entry and the
1114 * potential conflicting file.
1116 * In both cases, we fall through to the loop
1117 * below and let the regular search code handle it.
1120 } else if (cmp_last == 0) {
1122 * The entry exactly matches the last one in the
1123 * index, but because of multiple stage and CE_REMOVE
1124 * items, we fall through and let the regular search
1125 * code handle it.
1130 for (;;) {
1131 size_t len;
1133 for (;;) {
1134 if (*--slash == '/')
1135 break;
1136 if (slash <= ce->name)
1137 return retval;
1139 len = slash - name;
1141 pos = index_name_stage_pos(istate, name, len, stage, EXPAND_SPARSE);
1142 if (pos >= 0) {
1144 * Found one, but not so fast. This could
1145 * be a marker that says "I was here, but
1146 * I am being removed". Such an entry is
1147 * not a part of the resulting tree, and
1148 * it is Ok to have a directory at the same
1149 * path.
1151 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1152 retval = -1;
1153 if (!ok_to_replace)
1154 break;
1155 remove_index_entry_at(istate, pos);
1156 continue;
1159 else
1160 pos = -pos-1;
1163 * Trivial optimization: if we find an entry that
1164 * already matches the sub-directory, then we know
1165 * we're ok, and we can exit.
1167 while (pos < istate->cache_nr) {
1168 struct cache_entry *p = istate->cache[pos];
1169 if ((ce_namelen(p) <= len) ||
1170 (p->name[len] != '/') ||
1171 memcmp(p->name, name, len))
1172 break; /* not our subdirectory */
1173 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1175 * p is at the same stage as our entry, and
1176 * is a subdirectory of what we are looking
1177 * at, so we cannot have conflicts at our
1178 * level or anything shorter.
1180 return retval;
1181 pos++;
1184 return retval;
1187 /* We may be in a situation where we already have path/file and path
1188 * is being added, or we already have path and path/file is being
1189 * added. Either one would result in a nonsense tree that has path
1190 * twice when git-write-tree tries to write it out. Prevent it.
1192 * If ok-to-replace is specified, we remove the conflicting entries
1193 * from the cache so the caller should recompute the insert position.
1194 * When this happens, we return non-zero.
1196 static int check_file_directory_conflict(struct index_state *istate,
1197 const struct cache_entry *ce,
1198 int pos, int ok_to_replace)
1200 int retval;
1203 * When ce is an "I am going away" entry, we allow it to be added
1205 if (ce->ce_flags & CE_REMOVE)
1206 return 0;
1209 * We check if the path is a sub-path of a subsequent pathname
1210 * first, since removing those will not change the position
1211 * in the array.
1213 retval = has_file_name(istate, ce, pos, ok_to_replace);
1216 * Then check if the path might have a clashing sub-directory
1217 * before it.
1219 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1222 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1224 int pos;
1225 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1226 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1227 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1228 int new_only = option & ADD_CACHE_NEW_ONLY;
1231 * If this entry's path sorts after the last entry in the index,
1232 * we can avoid searching for it.
1234 if (istate->cache_nr > 0 &&
1235 strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1236 pos = index_pos_to_insert_pos(istate->cache_nr);
1237 else
1238 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1241 * Cache tree path should be invalidated only after index_name_stage_pos,
1242 * in case it expands a sparse index.
1244 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1245 cache_tree_invalidate_path(istate, ce->name);
1247 /* existing match? Just replace it. */
1248 if (pos >= 0) {
1249 if (!new_only)
1250 replace_index_entry(istate, pos, ce);
1251 return 0;
1253 pos = -pos-1;
1255 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1256 untracked_cache_add_to_index(istate, ce->name);
1259 * Inserting a merged entry ("stage 0") into the index
1260 * will always replace all non-merged entries..
1262 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1263 while (ce_same_name(istate->cache[pos], ce)) {
1264 ok_to_add = 1;
1265 if (!remove_index_entry_at(istate, pos))
1266 break;
1270 if (!ok_to_add)
1271 return -1;
1272 if (verify_path_internal(ce->name, ce->ce_mode) == PATH_INVALID)
1273 return error(_("invalid path '%s'"), ce->name);
1275 if (!skip_df_check &&
1276 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1277 if (!ok_to_replace)
1278 return error(_("'%s' appears as both a file and as a directory"),
1279 ce->name);
1280 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1281 pos = -pos-1;
1283 return pos + 1;
1286 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1288 int pos;
1290 if (option & ADD_CACHE_JUST_APPEND)
1291 pos = istate->cache_nr;
1292 else {
1293 int ret;
1294 ret = add_index_entry_with_check(istate, ce, option);
1295 if (ret <= 0)
1296 return ret;
1297 pos = ret - 1;
1300 /* Make sure the array is big enough .. */
1301 ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1303 /* Add it in.. */
1304 istate->cache_nr++;
1305 if (istate->cache_nr > pos + 1)
1306 MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1307 istate->cache_nr - pos - 1);
1308 set_index_entry(istate, pos, ce);
1309 istate->cache_changed |= CE_ENTRY_ADDED;
1310 return 0;
1314 * "refresh" does not calculate a new sha1 file or bring the
1315 * cache up-to-date for mode/content changes. But what it
1316 * _does_ do is to "re-match" the stat information of a file
1317 * with the cache, so that you can refresh the cache for a
1318 * file that hasn't been changed but where the stat entry is
1319 * out of date.
1321 * For example, you'd want to do this after doing a "git-read-tree",
1322 * to link up the stat cache details with the proper files.
1324 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1325 struct cache_entry *ce,
1326 unsigned int options, int *err,
1327 int *changed_ret,
1328 int *t2_did_lstat,
1329 int *t2_did_scan)
1331 struct stat st;
1332 struct cache_entry *updated;
1333 int changed;
1334 int refresh = options & CE_MATCH_REFRESH;
1335 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1336 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1337 int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1338 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
1340 if (!refresh || ce_uptodate(ce))
1341 return ce;
1343 if (!ignore_fsmonitor)
1344 refresh_fsmonitor(istate);
1346 * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1347 * that the change to the work tree does not matter and told
1348 * us not to worry.
1350 if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1351 ce_mark_uptodate(ce);
1352 return ce;
1354 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1355 ce_mark_uptodate(ce);
1356 return ce;
1358 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1359 ce_mark_uptodate(ce);
1360 return ce;
1363 if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1364 if (ignore_missing)
1365 return ce;
1366 if (err)
1367 *err = ENOENT;
1368 return NULL;
1371 if (t2_did_lstat)
1372 *t2_did_lstat = 1;
1373 if (lstat(ce->name, &st) < 0) {
1374 if (ignore_missing && errno == ENOENT)
1375 return ce;
1376 if (err)
1377 *err = errno;
1378 return NULL;
1381 changed = ie_match_stat(istate, ce, &st, options);
1382 if (changed_ret)
1383 *changed_ret = changed;
1384 if (!changed) {
1386 * The path is unchanged. If we were told to ignore
1387 * valid bit, then we did the actual stat check and
1388 * found that the entry is unmodified. If the entry
1389 * is not marked VALID, this is the place to mark it
1390 * valid again, under "assume unchanged" mode.
1392 if (ignore_valid && assume_unchanged &&
1393 !(ce->ce_flags & CE_VALID))
1394 ; /* mark this one VALID again */
1395 else {
1397 * We do not mark the index itself "modified"
1398 * because CE_UPTODATE flag is in-core only;
1399 * we are not going to write this change out.
1401 if (!S_ISGITLINK(ce->ce_mode)) {
1402 ce_mark_uptodate(ce);
1403 mark_fsmonitor_valid(istate, ce);
1405 return ce;
1409 if (t2_did_scan)
1410 *t2_did_scan = 1;
1411 if (ie_modified(istate, ce, &st, options)) {
1412 if (err)
1413 *err = EINVAL;
1414 return NULL;
1417 updated = make_empty_cache_entry(istate, ce_namelen(ce));
1418 copy_cache_entry(updated, ce);
1419 memcpy(updated->name, ce->name, ce->ce_namelen + 1);
1420 fill_stat_cache_info(istate, updated, &st);
1422 * If ignore_valid is not set, we should leave CE_VALID bit
1423 * alone. Otherwise, paths marked with --no-assume-unchanged
1424 * (i.e. things to be edited) will reacquire CE_VALID bit
1425 * automatically, which is not really what we want.
1427 if (!ignore_valid && assume_unchanged &&
1428 !(ce->ce_flags & CE_VALID))
1429 updated->ce_flags &= ~CE_VALID;
1431 /* istate->cache_changed is updated in the caller */
1432 return updated;
1435 static void show_file(const char * fmt, const char * name, int in_porcelain,
1436 int * first, const char *header_msg)
1438 if (in_porcelain && *first && header_msg) {
1439 printf("%s\n", header_msg);
1440 *first = 0;
1442 printf(fmt, name);
1445 int repo_refresh_and_write_index(struct repository *repo,
1446 unsigned int refresh_flags,
1447 unsigned int write_flags,
1448 int gentle,
1449 const struct pathspec *pathspec,
1450 char *seen, const char *header_msg)
1452 struct lock_file lock_file = LOCK_INIT;
1453 int fd, ret = 0;
1455 fd = repo_hold_locked_index(repo, &lock_file, 0);
1456 if (!gentle && fd < 0)
1457 return -1;
1458 if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
1459 ret = 1;
1460 if (0 <= fd && write_locked_index(repo->index, &lock_file, COMMIT_LOCK | write_flags))
1461 ret = -1;
1462 return ret;
1466 int refresh_index(struct index_state *istate, unsigned int flags,
1467 const struct pathspec *pathspec,
1468 char *seen, const char *header_msg)
1470 int i;
1471 int has_errors = 0;
1472 int really = (flags & REFRESH_REALLY) != 0;
1473 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1474 int quiet = (flags & REFRESH_QUIET) != 0;
1475 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1476 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1477 int ignore_skip_worktree = (flags & REFRESH_IGNORE_SKIP_WORKTREE) != 0;
1478 int first = 1;
1479 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1480 unsigned int options = (CE_MATCH_REFRESH |
1481 (really ? CE_MATCH_IGNORE_VALID : 0) |
1482 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1483 const char *modified_fmt;
1484 const char *deleted_fmt;
1485 const char *typechange_fmt;
1486 const char *added_fmt;
1487 const char *unmerged_fmt;
1488 struct progress *progress = NULL;
1489 int t2_sum_lstat = 0;
1490 int t2_sum_scan = 0;
1492 if (flags & REFRESH_PROGRESS && isatty(2))
1493 progress = start_delayed_progress(_("Refresh index"),
1494 istate->cache_nr);
1496 trace_performance_enter();
1497 modified_fmt = in_porcelain ? "M\t%s\n" : "%s: needs update\n";
1498 deleted_fmt = in_porcelain ? "D\t%s\n" : "%s: needs update\n";
1499 typechange_fmt = in_porcelain ? "T\t%s\n" : "%s: needs update\n";
1500 added_fmt = in_porcelain ? "A\t%s\n" : "%s: needs update\n";
1501 unmerged_fmt = in_porcelain ? "U\t%s\n" : "%s: needs merge\n";
1503 * Use the multi-threaded preload_index() to refresh most of the
1504 * cache entries quickly then in the single threaded loop below,
1505 * we only have to do the special cases that are left.
1507 preload_index(istate, pathspec, 0);
1508 trace2_region_enter("index", "refresh", NULL);
1510 for (i = 0; i < istate->cache_nr; i++) {
1511 struct cache_entry *ce, *new_entry;
1512 int cache_errno = 0;
1513 int changed = 0;
1514 int filtered = 0;
1515 int t2_did_lstat = 0;
1516 int t2_did_scan = 0;
1518 ce = istate->cache[i];
1519 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1520 continue;
1521 if (ignore_skip_worktree && ce_skip_worktree(ce))
1522 continue;
1525 * If this entry is a sparse directory, then there isn't
1526 * any stat() information to update. Ignore the entry.
1528 if (S_ISSPARSEDIR(ce->ce_mode))
1529 continue;
1531 if (pathspec && !ce_path_match(istate, ce, pathspec, seen))
1532 filtered = 1;
1534 if (ce_stage(ce)) {
1535 while ((i < istate->cache_nr) &&
1536 ! strcmp(istate->cache[i]->name, ce->name))
1537 i++;
1538 i--;
1539 if (allow_unmerged)
1540 continue;
1541 if (!filtered)
1542 show_file(unmerged_fmt, ce->name, in_porcelain,
1543 &first, header_msg);
1544 has_errors = 1;
1545 continue;
1548 if (filtered)
1549 continue;
1551 new_entry = refresh_cache_ent(istate, ce, options,
1552 &cache_errno, &changed,
1553 &t2_did_lstat, &t2_did_scan);
1554 t2_sum_lstat += t2_did_lstat;
1555 t2_sum_scan += t2_did_scan;
1556 if (new_entry == ce)
1557 continue;
1558 display_progress(progress, i);
1559 if (!new_entry) {
1560 const char *fmt;
1562 if (really && cache_errno == EINVAL) {
1563 /* If we are doing --really-refresh that
1564 * means the index is not valid anymore.
1566 ce->ce_flags &= ~CE_VALID;
1567 ce->ce_flags |= CE_UPDATE_IN_BASE;
1568 mark_fsmonitor_invalid(istate, ce);
1569 istate->cache_changed |= CE_ENTRY_CHANGED;
1571 if (quiet)
1572 continue;
1574 if (cache_errno == ENOENT)
1575 fmt = deleted_fmt;
1576 else if (ce_intent_to_add(ce))
1577 fmt = added_fmt; /* must be before other checks */
1578 else if (changed & TYPE_CHANGED)
1579 fmt = typechange_fmt;
1580 else
1581 fmt = modified_fmt;
1582 show_file(fmt,
1583 ce->name, in_porcelain, &first, header_msg);
1584 has_errors = 1;
1585 continue;
1588 replace_index_entry(istate, i, new_entry);
1590 trace2_data_intmax("index", NULL, "refresh/sum_lstat", t2_sum_lstat);
1591 trace2_data_intmax("index", NULL, "refresh/sum_scan", t2_sum_scan);
1592 trace2_region_leave("index", "refresh", NULL);
1593 display_progress(progress, istate->cache_nr);
1594 stop_progress(&progress);
1595 trace_performance_leave("refresh index");
1596 return has_errors;
1599 struct cache_entry *refresh_cache_entry(struct index_state *istate,
1600 struct cache_entry *ce,
1601 unsigned int options)
1603 return refresh_cache_ent(istate, ce, options, NULL, NULL, NULL, NULL);
1607 /*****************************************************************
1608 * Index File I/O
1609 *****************************************************************/
1611 #define INDEX_FORMAT_DEFAULT 3
1613 static unsigned int get_index_format_default(struct repository *r)
1615 char *envversion = getenv("GIT_INDEX_VERSION");
1616 char *endp;
1617 unsigned int version = INDEX_FORMAT_DEFAULT;
1619 if (!envversion) {
1620 prepare_repo_settings(r);
1622 if (r->settings.index_version >= 0)
1623 version = r->settings.index_version;
1624 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1625 warning(_("index.version set, but the value is invalid.\n"
1626 "Using version %i"), INDEX_FORMAT_DEFAULT);
1627 return INDEX_FORMAT_DEFAULT;
1629 return version;
1632 version = strtoul(envversion, &endp, 10);
1633 if (*endp ||
1634 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1635 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1636 "Using version %i"), INDEX_FORMAT_DEFAULT);
1637 version = INDEX_FORMAT_DEFAULT;
1639 return version;
1643 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1644 * Again - this is just a (very strong in practice) heuristic that
1645 * the inode hasn't changed.
1647 * We save the fields in big-endian order to allow using the
1648 * index file over NFS transparently.
1650 struct ondisk_cache_entry {
1651 struct cache_time ctime;
1652 struct cache_time mtime;
1653 uint32_t dev;
1654 uint32_t ino;
1655 uint32_t mode;
1656 uint32_t uid;
1657 uint32_t gid;
1658 uint32_t size;
1660 * unsigned char hash[hashsz];
1661 * uint16_t flags;
1662 * if (flags & CE_EXTENDED)
1663 * uint16_t flags2;
1665 unsigned char data[GIT_MAX_RAWSZ + 2 * sizeof(uint16_t)];
1666 char name[FLEX_ARRAY];
1669 /* These are only used for v3 or lower */
1670 #define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1671 #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,data) + (len) + 8) & ~7)
1672 #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1673 #define ondisk_data_size(flags, len) (the_hash_algo->rawsz + \
1674 ((flags & CE_EXTENDED) ? 2 : 1) * sizeof(uint16_t) + len)
1675 #define ondisk_data_size_max(len) (ondisk_data_size(CE_EXTENDED, len))
1676 #define ondisk_ce_size(ce) (ondisk_cache_entry_size(ondisk_data_size((ce)->ce_flags, ce_namelen(ce))))
1678 /* Allow fsck to force verification of the index checksum. */
1679 int verify_index_checksum;
1681 /* Allow fsck to force verification of the cache entry order. */
1682 int verify_ce_order;
1684 static int verify_hdr(const struct cache_header *hdr, unsigned long size)
1686 git_hash_ctx c;
1687 unsigned char hash[GIT_MAX_RAWSZ];
1688 int hdr_version;
1689 unsigned char *start, *end;
1690 struct object_id oid;
1692 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1693 return error(_("bad signature 0x%08x"), hdr->hdr_signature);
1694 hdr_version = ntohl(hdr->hdr_version);
1695 if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1696 return error(_("bad index version %d"), hdr_version);
1698 if (!verify_index_checksum)
1699 return 0;
1701 end = (unsigned char *)hdr + size;
1702 start = end - the_hash_algo->rawsz;
1703 oidread(&oid, start);
1704 if (oideq(&oid, null_oid()))
1705 return 0;
1707 the_hash_algo->init_fn(&c);
1708 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1709 the_hash_algo->final_fn(hash, &c);
1710 if (!hasheq(hash, start))
1711 return error(_("bad index file sha1 signature"));
1712 return 0;
1715 static int read_index_extension(struct index_state *istate,
1716 const char *ext, const char *data, unsigned long sz)
1718 switch (CACHE_EXT(ext)) {
1719 case CACHE_EXT_TREE:
1720 istate->cache_tree = cache_tree_read(data, sz);
1721 break;
1722 case CACHE_EXT_RESOLVE_UNDO:
1723 istate->resolve_undo = resolve_undo_read(data, sz);
1724 break;
1725 case CACHE_EXT_LINK:
1726 if (read_link_extension(istate, data, sz))
1727 return -1;
1728 break;
1729 case CACHE_EXT_UNTRACKED:
1730 istate->untracked = read_untracked_extension(data, sz);
1731 break;
1732 case CACHE_EXT_FSMONITOR:
1733 read_fsmonitor_extension(istate, data, sz);
1734 break;
1735 case CACHE_EXT_ENDOFINDEXENTRIES:
1736 case CACHE_EXT_INDEXENTRYOFFSETTABLE:
1737 /* already handled in do_read_index() */
1738 break;
1739 case CACHE_EXT_SPARSE_DIRECTORIES:
1740 /* no content, only an indicator */
1741 istate->sparse_index = INDEX_COLLAPSED;
1742 break;
1743 default:
1744 if (*ext < 'A' || 'Z' < *ext)
1745 return error(_("index uses %.4s extension, which we do not understand"),
1746 ext);
1747 fprintf_ln(stderr, _("ignoring %.4s extension"), ext);
1748 break;
1750 return 0;
1754 * Parses the contents of the cache entry contained within the 'ondisk' buffer
1755 * into a new incore 'cache_entry'.
1757 * Note that 'char *ondisk' may not be aligned to a 4-byte address interval in
1758 * index v4, so we cannot cast it to 'struct ondisk_cache_entry *' and access
1759 * its members. Instead, we use the byte offsets of members within the struct to
1760 * identify where 'get_be16()', 'get_be32()', and 'oidread()' (which can all
1761 * read from an unaligned memory buffer) should read from the 'ondisk' buffer
1762 * into the corresponding incore 'cache_entry' members.
1764 static struct cache_entry *create_from_disk(struct mem_pool *ce_mem_pool,
1765 unsigned int version,
1766 const char *ondisk,
1767 unsigned long *ent_size,
1768 const struct cache_entry *previous_ce)
1770 struct cache_entry *ce;
1771 size_t len;
1772 const char *name;
1773 const unsigned hashsz = the_hash_algo->rawsz;
1774 const char *flagsp = ondisk + offsetof(struct ondisk_cache_entry, data) + hashsz;
1775 unsigned int flags;
1776 size_t copy_len = 0;
1778 * Adjacent cache entries tend to share the leading paths, so it makes
1779 * sense to only store the differences in later entries. In the v4
1780 * on-disk format of the index, each on-disk cache entry stores the
1781 * number of bytes to be stripped from the end of the previous name,
1782 * and the bytes to append to the result, to come up with its name.
1784 int expand_name_field = version == 4;
1786 /* On-disk flags are just 16 bits */
1787 flags = get_be16(flagsp);
1788 len = flags & CE_NAMEMASK;
1790 if (flags & CE_EXTENDED) {
1791 int extended_flags;
1792 extended_flags = get_be16(flagsp + sizeof(uint16_t)) << 16;
1793 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1794 if (extended_flags & ~CE_EXTENDED_FLAGS)
1795 die(_("unknown index entry format 0x%08x"), extended_flags);
1796 flags |= extended_flags;
1797 name = (const char *)(flagsp + 2 * sizeof(uint16_t));
1799 else
1800 name = (const char *)(flagsp + sizeof(uint16_t));
1802 if (expand_name_field) {
1803 const unsigned char *cp = (const unsigned char *)name;
1804 size_t strip_len, previous_len;
1806 /* If we're at the beginning of a block, ignore the previous name */
1807 strip_len = decode_varint(&cp);
1808 if (previous_ce) {
1809 previous_len = previous_ce->ce_namelen;
1810 if (previous_len < strip_len)
1811 die(_("malformed name field in the index, near path '%s'"),
1812 previous_ce->name);
1813 copy_len = previous_len - strip_len;
1815 name = (const char *)cp;
1818 if (len == CE_NAMEMASK) {
1819 len = strlen(name);
1820 if (expand_name_field)
1821 len += copy_len;
1824 ce = mem_pool__ce_alloc(ce_mem_pool, len);
1827 * NEEDSWORK: using 'offsetof()' is cumbersome and should be replaced
1828 * with something more akin to 'load_bitmap_entries_v1()'s use of
1829 * 'read_be16'/'read_be32'. For consistency with the corresponding
1830 * ondisk entry write function ('copy_cache_entry_to_ondisk()'), this
1831 * should be done at the same time as removing references to
1832 * 'ondisk_cache_entry' there.
1834 ce->ce_stat_data.sd_ctime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1835 + offsetof(struct cache_time, sec));
1836 ce->ce_stat_data.sd_mtime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1837 + offsetof(struct cache_time, sec));
1838 ce->ce_stat_data.sd_ctime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1839 + offsetof(struct cache_time, nsec));
1840 ce->ce_stat_data.sd_mtime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1841 + offsetof(struct cache_time, nsec));
1842 ce->ce_stat_data.sd_dev = get_be32(ondisk + offsetof(struct ondisk_cache_entry, dev));
1843 ce->ce_stat_data.sd_ino = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ino));
1844 ce->ce_mode = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mode));
1845 ce->ce_stat_data.sd_uid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, uid));
1846 ce->ce_stat_data.sd_gid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, gid));
1847 ce->ce_stat_data.sd_size = get_be32(ondisk + offsetof(struct ondisk_cache_entry, size));
1848 ce->ce_flags = flags & ~CE_NAMEMASK;
1849 ce->ce_namelen = len;
1850 ce->index = 0;
1851 oidread(&ce->oid, (const unsigned char *)ondisk + offsetof(struct ondisk_cache_entry, data));
1853 if (expand_name_field) {
1854 if (copy_len)
1855 memcpy(ce->name, previous_ce->name, copy_len);
1856 memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1857 *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
1858 } else {
1859 memcpy(ce->name, name, len + 1);
1860 *ent_size = ondisk_ce_size(ce);
1862 return ce;
1865 static void check_ce_order(struct index_state *istate)
1867 unsigned int i;
1869 if (!verify_ce_order)
1870 return;
1872 for (i = 1; i < istate->cache_nr; i++) {
1873 struct cache_entry *ce = istate->cache[i - 1];
1874 struct cache_entry *next_ce = istate->cache[i];
1875 int name_compare = strcmp(ce->name, next_ce->name);
1877 if (0 < name_compare)
1878 die(_("unordered stage entries in index"));
1879 if (!name_compare) {
1880 if (!ce_stage(ce))
1881 die(_("multiple stage entries for merged file '%s'"),
1882 ce->name);
1883 if (ce_stage(ce) > ce_stage(next_ce))
1884 die(_("unordered stage entries for '%s'"),
1885 ce->name);
1890 static void tweak_untracked_cache(struct index_state *istate)
1892 struct repository *r = the_repository;
1894 prepare_repo_settings(r);
1896 switch (r->settings.core_untracked_cache) {
1897 case UNTRACKED_CACHE_REMOVE:
1898 remove_untracked_cache(istate);
1899 break;
1900 case UNTRACKED_CACHE_WRITE:
1901 add_untracked_cache(istate);
1902 break;
1903 case UNTRACKED_CACHE_KEEP:
1905 * Either an explicit "core.untrackedCache=keep", the
1906 * default if "core.untrackedCache" isn't configured,
1907 * or a fallback on an unknown "core.untrackedCache"
1908 * value.
1910 break;
1914 static void tweak_split_index(struct index_state *istate)
1916 switch (git_config_get_split_index()) {
1917 case -1: /* unset: do nothing */
1918 break;
1919 case 0: /* false */
1920 remove_split_index(istate);
1921 break;
1922 case 1: /* true */
1923 add_split_index(istate);
1924 break;
1925 default: /* unknown value: do nothing */
1926 break;
1930 static void post_read_index_from(struct index_state *istate)
1932 check_ce_order(istate);
1933 tweak_untracked_cache(istate);
1934 tweak_split_index(istate);
1935 tweak_fsmonitor(istate);
1938 static size_t estimate_cache_size_from_compressed(unsigned int entries)
1940 return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
1943 static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1945 long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1948 * Account for potential alignment differences.
1950 per_entry += align_padding_size(per_entry, 0);
1951 return ondisk_size + entries * per_entry;
1954 struct index_entry_offset
1956 /* starting byte offset into index file, count of index entries in this block */
1957 int offset, nr;
1960 struct index_entry_offset_table
1962 int nr;
1963 struct index_entry_offset entries[FLEX_ARRAY];
1966 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset);
1967 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot);
1969 static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
1970 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset);
1972 struct load_index_extensions
1974 pthread_t pthread;
1975 struct index_state *istate;
1976 const char *mmap;
1977 size_t mmap_size;
1978 unsigned long src_offset;
1981 static void *load_index_extensions(void *_data)
1983 struct load_index_extensions *p = _data;
1984 unsigned long src_offset = p->src_offset;
1986 while (src_offset <= p->mmap_size - the_hash_algo->rawsz - 8) {
1987 /* After an array of active_nr index entries,
1988 * there can be arbitrary number of extended
1989 * sections, each of which is prefixed with
1990 * extension name (4-byte) and section length
1991 * in 4-byte network byte order.
1993 uint32_t extsize = get_be32(p->mmap + src_offset + 4);
1994 if (read_index_extension(p->istate,
1995 p->mmap + src_offset,
1996 p->mmap + src_offset + 8,
1997 extsize) < 0) {
1998 munmap((void *)p->mmap, p->mmap_size);
1999 die(_("index file corrupt"));
2001 src_offset += 8;
2002 src_offset += extsize;
2005 return NULL;
2009 * A helper function that will load the specified range of cache entries
2010 * from the memory mapped file and add them to the given index.
2012 static unsigned long load_cache_entry_block(struct index_state *istate,
2013 struct mem_pool *ce_mem_pool, int offset, int nr, const char *mmap,
2014 unsigned long start_offset, const struct cache_entry *previous_ce)
2016 int i;
2017 unsigned long src_offset = start_offset;
2019 for (i = offset; i < offset + nr; i++) {
2020 struct cache_entry *ce;
2021 unsigned long consumed;
2023 ce = create_from_disk(ce_mem_pool, istate->version,
2024 mmap + src_offset,
2025 &consumed, previous_ce);
2026 set_index_entry(istate, i, ce);
2028 src_offset += consumed;
2029 previous_ce = ce;
2031 return src_offset - start_offset;
2034 static unsigned long load_all_cache_entries(struct index_state *istate,
2035 const char *mmap, size_t mmap_size, unsigned long src_offset)
2037 unsigned long consumed;
2039 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2040 if (istate->version == 4) {
2041 mem_pool_init(istate->ce_mem_pool,
2042 estimate_cache_size_from_compressed(istate->cache_nr));
2043 } else {
2044 mem_pool_init(istate->ce_mem_pool,
2045 estimate_cache_size(mmap_size, istate->cache_nr));
2048 consumed = load_cache_entry_block(istate, istate->ce_mem_pool,
2049 0, istate->cache_nr, mmap, src_offset, NULL);
2050 return consumed;
2054 * Mostly randomly chosen maximum thread counts: we
2055 * cap the parallelism to online_cpus() threads, and we want
2056 * to have at least 10000 cache entries per thread for it to
2057 * be worth starting a thread.
2060 #define THREAD_COST (10000)
2062 struct load_cache_entries_thread_data
2064 pthread_t pthread;
2065 struct index_state *istate;
2066 struct mem_pool *ce_mem_pool;
2067 int offset;
2068 const char *mmap;
2069 struct index_entry_offset_table *ieot;
2070 int ieot_start; /* starting index into the ieot array */
2071 int ieot_blocks; /* count of ieot entries to process */
2072 unsigned long consumed; /* return # of bytes in index file processed */
2076 * A thread proc to run the load_cache_entries() computation
2077 * across multiple background threads.
2079 static void *load_cache_entries_thread(void *_data)
2081 struct load_cache_entries_thread_data *p = _data;
2082 int i;
2084 /* iterate across all ieot blocks assigned to this thread */
2085 for (i = p->ieot_start; i < p->ieot_start + p->ieot_blocks; i++) {
2086 p->consumed += load_cache_entry_block(p->istate, p->ce_mem_pool,
2087 p->offset, p->ieot->entries[i].nr, p->mmap, p->ieot->entries[i].offset, NULL);
2088 p->offset += p->ieot->entries[i].nr;
2090 return NULL;
2093 static unsigned long load_cache_entries_threaded(struct index_state *istate, const char *mmap, size_t mmap_size,
2094 int nr_threads, struct index_entry_offset_table *ieot)
2096 int i, offset, ieot_blocks, ieot_start, err;
2097 struct load_cache_entries_thread_data *data;
2098 unsigned long consumed = 0;
2100 /* a little sanity checking */
2101 if (istate->name_hash_initialized)
2102 BUG("the name hash isn't thread safe");
2104 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2105 mem_pool_init(istate->ce_mem_pool, 0);
2107 /* ensure we have no more threads than we have blocks to process */
2108 if (nr_threads > ieot->nr)
2109 nr_threads = ieot->nr;
2110 CALLOC_ARRAY(data, nr_threads);
2112 offset = ieot_start = 0;
2113 ieot_blocks = DIV_ROUND_UP(ieot->nr, nr_threads);
2114 for (i = 0; i < nr_threads; i++) {
2115 struct load_cache_entries_thread_data *p = &data[i];
2116 int nr, j;
2118 if (ieot_start + ieot_blocks > ieot->nr)
2119 ieot_blocks = ieot->nr - ieot_start;
2121 p->istate = istate;
2122 p->offset = offset;
2123 p->mmap = mmap;
2124 p->ieot = ieot;
2125 p->ieot_start = ieot_start;
2126 p->ieot_blocks = ieot_blocks;
2128 /* create a mem_pool for each thread */
2129 nr = 0;
2130 for (j = p->ieot_start; j < p->ieot_start + p->ieot_blocks; j++)
2131 nr += p->ieot->entries[j].nr;
2132 p->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2133 if (istate->version == 4) {
2134 mem_pool_init(p->ce_mem_pool,
2135 estimate_cache_size_from_compressed(nr));
2136 } else {
2137 mem_pool_init(p->ce_mem_pool,
2138 estimate_cache_size(mmap_size, nr));
2141 err = pthread_create(&p->pthread, NULL, load_cache_entries_thread, p);
2142 if (err)
2143 die(_("unable to create load_cache_entries thread: %s"), strerror(err));
2145 /* increment by the number of cache entries in the ieot block being processed */
2146 for (j = 0; j < ieot_blocks; j++)
2147 offset += ieot->entries[ieot_start + j].nr;
2148 ieot_start += ieot_blocks;
2151 for (i = 0; i < nr_threads; i++) {
2152 struct load_cache_entries_thread_data *p = &data[i];
2154 err = pthread_join(p->pthread, NULL);
2155 if (err)
2156 die(_("unable to join load_cache_entries thread: %s"), strerror(err));
2157 mem_pool_combine(istate->ce_mem_pool, p->ce_mem_pool);
2158 consumed += p->consumed;
2161 free(data);
2163 return consumed;
2166 static void set_new_index_sparsity(struct index_state *istate)
2169 * If the index's repo exists, mark it sparse according to
2170 * repo settings.
2172 prepare_repo_settings(istate->repo);
2173 if (!istate->repo->settings.command_requires_full_index &&
2174 is_sparse_index_allowed(istate, 0))
2175 istate->sparse_index = 1;
2178 /* remember to discard_cache() before reading a different cache! */
2179 int do_read_index(struct index_state *istate, const char *path, int must_exist)
2181 int fd;
2182 struct stat st;
2183 unsigned long src_offset;
2184 const struct cache_header *hdr;
2185 const char *mmap;
2186 size_t mmap_size;
2187 struct load_index_extensions p;
2188 size_t extension_offset = 0;
2189 int nr_threads, cpus;
2190 struct index_entry_offset_table *ieot = NULL;
2192 if (istate->initialized)
2193 return istate->cache_nr;
2195 istate->timestamp.sec = 0;
2196 istate->timestamp.nsec = 0;
2197 fd = open(path, O_RDONLY);
2198 if (fd < 0) {
2199 if (!must_exist && errno == ENOENT) {
2200 set_new_index_sparsity(istate);
2201 istate->initialized = 1;
2202 return 0;
2204 die_errno(_("%s: index file open failed"), path);
2207 if (fstat(fd, &st))
2208 die_errno(_("%s: cannot stat the open index"), path);
2210 mmap_size = xsize_t(st.st_size);
2211 if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2212 die(_("%s: index file smaller than expected"), path);
2214 mmap = xmmap_gently(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
2215 if (mmap == MAP_FAILED)
2216 die_errno(_("%s: unable to map index file%s"), path,
2217 mmap_os_err());
2218 close(fd);
2220 hdr = (const struct cache_header *)mmap;
2221 if (verify_hdr(hdr, mmap_size) < 0)
2222 goto unmap;
2224 oidread(&istate->oid, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
2225 istate->version = ntohl(hdr->hdr_version);
2226 istate->cache_nr = ntohl(hdr->hdr_entries);
2227 istate->cache_alloc = alloc_nr(istate->cache_nr);
2228 CALLOC_ARRAY(istate->cache, istate->cache_alloc);
2229 istate->initialized = 1;
2231 p.istate = istate;
2232 p.mmap = mmap;
2233 p.mmap_size = mmap_size;
2235 src_offset = sizeof(*hdr);
2237 if (git_config_get_index_threads(&nr_threads))
2238 nr_threads = 1;
2240 /* TODO: does creating more threads than cores help? */
2241 if (!nr_threads) {
2242 nr_threads = istate->cache_nr / THREAD_COST;
2243 cpus = online_cpus();
2244 if (nr_threads > cpus)
2245 nr_threads = cpus;
2248 if (!HAVE_THREADS)
2249 nr_threads = 1;
2251 if (nr_threads > 1) {
2252 extension_offset = read_eoie_extension(mmap, mmap_size);
2253 if (extension_offset) {
2254 int err;
2256 p.src_offset = extension_offset;
2257 err = pthread_create(&p.pthread, NULL, load_index_extensions, &p);
2258 if (err)
2259 die(_("unable to create load_index_extensions thread: %s"), strerror(err));
2261 nr_threads--;
2266 * Locate and read the index entry offset table so that we can use it
2267 * to multi-thread the reading of the cache entries.
2269 if (extension_offset && nr_threads > 1)
2270 ieot = read_ieot_extension(mmap, mmap_size, extension_offset);
2272 if (ieot) {
2273 src_offset += load_cache_entries_threaded(istate, mmap, mmap_size, nr_threads, ieot);
2274 free(ieot);
2275 } else {
2276 src_offset += load_all_cache_entries(istate, mmap, mmap_size, src_offset);
2279 istate->timestamp.sec = st.st_mtime;
2280 istate->timestamp.nsec = ST_MTIME_NSEC(st);
2282 /* if we created a thread, join it otherwise load the extensions on the primary thread */
2283 if (extension_offset) {
2284 int ret = pthread_join(p.pthread, NULL);
2285 if (ret)
2286 die(_("unable to join load_index_extensions thread: %s"), strerror(ret));
2287 } else {
2288 p.src_offset = src_offset;
2289 load_index_extensions(&p);
2291 munmap((void *)mmap, mmap_size);
2294 * TODO trace2: replace "the_repository" with the actual repo instance
2295 * that is associated with the given "istate".
2297 trace2_data_intmax("index", the_repository, "read/version",
2298 istate->version);
2299 trace2_data_intmax("index", the_repository, "read/cache_nr",
2300 istate->cache_nr);
2303 * If the command explicitly requires a full index, force it
2304 * to be full. Otherwise, correct the sparsity based on repository
2305 * settings and other properties of the index (if necessary).
2307 prepare_repo_settings(istate->repo);
2308 if (istate->repo->settings.command_requires_full_index)
2309 ensure_full_index(istate);
2310 else
2311 ensure_correct_sparsity(istate);
2313 return istate->cache_nr;
2315 unmap:
2316 munmap((void *)mmap, mmap_size);
2317 die(_("index file corrupt"));
2321 * Signal that the shared index is used by updating its mtime.
2323 * This way, shared index can be removed if they have not been used
2324 * for some time.
2326 static void freshen_shared_index(const char *shared_index, int warn)
2328 if (!check_and_freshen_file(shared_index, 1) && warn)
2329 warning(_("could not freshen shared index '%s'"), shared_index);
2332 int read_index_from(struct index_state *istate, const char *path,
2333 const char *gitdir)
2335 struct split_index *split_index;
2336 int ret;
2337 char *base_oid_hex;
2338 char *base_path;
2340 /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2341 if (istate->initialized)
2342 return istate->cache_nr;
2345 * TODO trace2: replace "the_repository" with the actual repo instance
2346 * that is associated with the given "istate".
2348 trace2_region_enter_printf("index", "do_read_index", the_repository,
2349 "%s", path);
2350 trace_performance_enter();
2351 ret = do_read_index(istate, path, 0);
2352 trace_performance_leave("read cache %s", path);
2353 trace2_region_leave_printf("index", "do_read_index", the_repository,
2354 "%s", path);
2356 split_index = istate->split_index;
2357 if (!split_index || is_null_oid(&split_index->base_oid)) {
2358 post_read_index_from(istate);
2359 return ret;
2362 trace_performance_enter();
2363 if (split_index->base)
2364 release_index(split_index->base);
2365 else
2366 ALLOC_ARRAY(split_index->base, 1);
2367 index_state_init(split_index->base, istate->repo);
2369 base_oid_hex = oid_to_hex(&split_index->base_oid);
2370 base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
2371 if (file_exists(base_path)) {
2372 trace2_region_enter_printf("index", "shared/do_read_index",
2373 the_repository, "%s", base_path);
2375 ret = do_read_index(split_index->base, base_path, 0);
2376 trace2_region_leave_printf("index", "shared/do_read_index",
2377 the_repository, "%s", base_path);
2378 } else {
2379 char *path_copy = xstrdup(path);
2380 char *base_path2 = xstrfmt("%s/sharedindex.%s",
2381 dirname(path_copy), base_oid_hex);
2382 free(path_copy);
2383 trace2_region_enter_printf("index", "shared/do_read_index",
2384 the_repository, "%s", base_path2);
2385 ret = do_read_index(split_index->base, base_path2, 1);
2386 trace2_region_leave_printf("index", "shared/do_read_index",
2387 the_repository, "%s", base_path2);
2388 free(base_path2);
2390 if (!oideq(&split_index->base_oid, &split_index->base->oid))
2391 die(_("broken index, expect %s in %s, got %s"),
2392 base_oid_hex, base_path,
2393 oid_to_hex(&split_index->base->oid));
2395 freshen_shared_index(base_path, 0);
2396 merge_base_index(istate);
2397 post_read_index_from(istate);
2398 trace_performance_leave("read cache %s", base_path);
2399 free(base_path);
2400 return ret;
2403 int is_index_unborn(struct index_state *istate)
2405 return (!istate->cache_nr && !istate->timestamp.sec);
2408 void index_state_init(struct index_state *istate, struct repository *r)
2410 struct index_state blank = INDEX_STATE_INIT(r);
2411 memcpy(istate, &blank, sizeof(*istate));
2414 void release_index(struct index_state *istate)
2417 * Cache entries in istate->cache[] should have been allocated
2418 * from the memory pool associated with this index, or from an
2419 * associated split_index. There is no need to free individual
2420 * cache entries. validate_cache_entries can detect when this
2421 * assertion does not hold.
2423 validate_cache_entries(istate);
2425 resolve_undo_clear_index(istate);
2426 free_name_hash(istate);
2427 cache_tree_free(&(istate->cache_tree));
2428 free(istate->fsmonitor_last_update);
2429 free(istate->cache);
2430 discard_split_index(istate);
2431 free_untracked_cache(istate->untracked);
2433 if (istate->sparse_checkout_patterns) {
2434 clear_pattern_list(istate->sparse_checkout_patterns);
2435 FREE_AND_NULL(istate->sparse_checkout_patterns);
2438 if (istate->ce_mem_pool) {
2439 mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
2440 FREE_AND_NULL(istate->ce_mem_pool);
2444 void discard_index(struct index_state *istate)
2446 release_index(istate);
2447 index_state_init(istate, istate->repo);
2451 * Validate the cache entries of this index.
2452 * All cache entries associated with this index
2453 * should have been allocated by the memory pool
2454 * associated with this index, or by a referenced
2455 * split index.
2457 void validate_cache_entries(const struct index_state *istate)
2459 int i;
2461 if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2462 return;
2464 for (i = 0; i < istate->cache_nr; i++) {
2465 if (!istate) {
2466 BUG("cache entry is not allocated from expected memory pool");
2467 } else if (!istate->ce_mem_pool ||
2468 !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2469 if (!istate->split_index ||
2470 !istate->split_index->base ||
2471 !istate->split_index->base->ce_mem_pool ||
2472 !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2473 BUG("cache entry is not allocated from expected memory pool");
2478 if (istate->split_index)
2479 validate_cache_entries(istate->split_index->base);
2482 int unmerged_index(const struct index_state *istate)
2484 int i;
2485 for (i = 0; i < istate->cache_nr; i++) {
2486 if (ce_stage(istate->cache[i]))
2487 return 1;
2489 return 0;
2492 int repo_index_has_changes(struct repository *repo,
2493 struct tree *tree,
2494 struct strbuf *sb)
2496 struct index_state *istate = repo->index;
2497 struct object_id cmp;
2498 int i;
2500 if (tree)
2501 cmp = tree->object.oid;
2502 if (tree || !repo_get_oid_tree(repo, "HEAD", &cmp)) {
2503 struct diff_options opt;
2505 repo_diff_setup(repo, &opt);
2506 opt.flags.exit_with_status = 1;
2507 if (!sb)
2508 opt.flags.quick = 1;
2509 diff_setup_done(&opt);
2510 do_diff_cache(&cmp, &opt);
2511 diffcore_std(&opt);
2512 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2513 if (i)
2514 strbuf_addch(sb, ' ');
2515 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2517 diff_flush(&opt);
2518 return opt.flags.has_changes != 0;
2519 } else {
2520 /* TODO: audit for interaction with sparse-index. */
2521 ensure_full_index(istate);
2522 for (i = 0; sb && i < istate->cache_nr; i++) {
2523 if (i)
2524 strbuf_addch(sb, ' ');
2525 strbuf_addstr(sb, istate->cache[i]->name);
2527 return !!istate->cache_nr;
2531 static int write_index_ext_header(struct hashfile *f,
2532 git_hash_ctx *eoie_f,
2533 unsigned int ext,
2534 unsigned int sz)
2536 hashwrite_be32(f, ext);
2537 hashwrite_be32(f, sz);
2539 if (eoie_f) {
2540 ext = htonl(ext);
2541 sz = htonl(sz);
2542 the_hash_algo->update_fn(eoie_f, &ext, sizeof(ext));
2543 the_hash_algo->update_fn(eoie_f, &sz, sizeof(sz));
2545 return 0;
2548 static void ce_smudge_racily_clean_entry(struct index_state *istate,
2549 struct cache_entry *ce)
2552 * The only thing we care about in this function is to smudge the
2553 * falsely clean entry due to touch-update-touch race, so we leave
2554 * everything else as they are. We are called for entries whose
2555 * ce_stat_data.sd_mtime match the index file mtime.
2557 * Note that this actually does not do much for gitlinks, for
2558 * which ce_match_stat_basic() always goes to the actual
2559 * contents. The caller checks with is_racy_timestamp() which
2560 * always says "no" for gitlinks, so we are not called for them ;-)
2562 struct stat st;
2564 if (lstat(ce->name, &st) < 0)
2565 return;
2566 if (ce_match_stat_basic(ce, &st))
2567 return;
2568 if (ce_modified_check_fs(istate, ce, &st)) {
2569 /* This is "racily clean"; smudge it. Note that this
2570 * is a tricky code. At first glance, it may appear
2571 * that it can break with this sequence:
2573 * $ echo xyzzy >frotz
2574 * $ git-update-index --add frotz
2575 * $ : >frotz
2576 * $ sleep 3
2577 * $ echo filfre >nitfol
2578 * $ git-update-index --add nitfol
2580 * but it does not. When the second update-index runs,
2581 * it notices that the entry "frotz" has the same timestamp
2582 * as index, and if we were to smudge it by resetting its
2583 * size to zero here, then the object name recorded
2584 * in index is the 6-byte file but the cached stat information
2585 * becomes zero --- which would then match what we would
2586 * obtain from the filesystem next time we stat("frotz").
2588 * However, the second update-index, before calling
2589 * this function, notices that the cached size is 6
2590 * bytes and what is on the filesystem is an empty
2591 * file, and never calls us, so the cached size information
2592 * for "frotz" stays 6 which does not match the filesystem.
2594 ce->ce_stat_data.sd_size = 0;
2598 /* Copy miscellaneous fields but not the name */
2599 static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2600 struct cache_entry *ce)
2602 short flags;
2603 const unsigned hashsz = the_hash_algo->rawsz;
2604 uint16_t *flagsp = (uint16_t *)(ondisk->data + hashsz);
2606 ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2607 ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2608 ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2609 ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2610 ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
2611 ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
2612 ondisk->mode = htonl(ce->ce_mode);
2613 ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
2614 ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
2615 ondisk->size = htonl(ce->ce_stat_data.sd_size);
2616 hashcpy(ondisk->data, ce->oid.hash);
2618 flags = ce->ce_flags & ~CE_NAMEMASK;
2619 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2620 flagsp[0] = htons(flags);
2621 if (ce->ce_flags & CE_EXTENDED) {
2622 flagsp[1] = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2626 static int ce_write_entry(struct hashfile *f, struct cache_entry *ce,
2627 struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2629 int size;
2630 unsigned int saved_namelen;
2631 int stripped_name = 0;
2632 static unsigned char padding[8] = { 0x00 };
2634 if (ce->ce_flags & CE_STRIP_NAME) {
2635 saved_namelen = ce_namelen(ce);
2636 ce->ce_namelen = 0;
2637 stripped_name = 1;
2640 size = offsetof(struct ondisk_cache_entry,data) + ondisk_data_size(ce->ce_flags, 0);
2642 if (!previous_name) {
2643 int len = ce_namelen(ce);
2644 copy_cache_entry_to_ondisk(ondisk, ce);
2645 hashwrite(f, ondisk, size);
2646 hashwrite(f, ce->name, len);
2647 hashwrite(f, padding, align_padding_size(size, len));
2648 } else {
2649 int common, to_remove, prefix_size;
2650 unsigned char to_remove_vi[16];
2651 for (common = 0;
2652 (ce->name[common] &&
2653 common < previous_name->len &&
2654 ce->name[common] == previous_name->buf[common]);
2655 common++)
2656 ; /* still matching */
2657 to_remove = previous_name->len - common;
2658 prefix_size = encode_varint(to_remove, to_remove_vi);
2660 copy_cache_entry_to_ondisk(ondisk, ce);
2661 hashwrite(f, ondisk, size);
2662 hashwrite(f, to_remove_vi, prefix_size);
2663 hashwrite(f, ce->name + common, ce_namelen(ce) - common);
2664 hashwrite(f, padding, 1);
2666 strbuf_splice(previous_name, common, to_remove,
2667 ce->name + common, ce_namelen(ce) - common);
2669 if (stripped_name) {
2670 ce->ce_namelen = saved_namelen;
2671 ce->ce_flags &= ~CE_STRIP_NAME;
2674 return 0;
2678 * This function verifies if index_state has the correct sha1 of the
2679 * index file. Don't die if we have any other failure, just return 0.
2681 static int verify_index_from(const struct index_state *istate, const char *path)
2683 int fd;
2684 ssize_t n;
2685 struct stat st;
2686 unsigned char hash[GIT_MAX_RAWSZ];
2688 if (!istate->initialized)
2689 return 0;
2691 fd = open(path, O_RDONLY);
2692 if (fd < 0)
2693 return 0;
2695 if (fstat(fd, &st))
2696 goto out;
2698 if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2699 goto out;
2701 n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2702 if (n != the_hash_algo->rawsz)
2703 goto out;
2705 if (!hasheq(istate->oid.hash, hash))
2706 goto out;
2708 close(fd);
2709 return 1;
2711 out:
2712 close(fd);
2713 return 0;
2716 static int repo_verify_index(struct repository *repo)
2718 return verify_index_from(repo->index, repo->index_file);
2721 int has_racy_timestamp(struct index_state *istate)
2723 int entries = istate->cache_nr;
2724 int i;
2726 for (i = 0; i < entries; i++) {
2727 struct cache_entry *ce = istate->cache[i];
2728 if (is_racy_timestamp(istate, ce))
2729 return 1;
2731 return 0;
2734 void repo_update_index_if_able(struct repository *repo,
2735 struct lock_file *lockfile)
2737 if ((repo->index->cache_changed ||
2738 has_racy_timestamp(repo->index)) &&
2739 repo_verify_index(repo))
2740 write_locked_index(repo->index, lockfile, COMMIT_LOCK);
2741 else
2742 rollback_lock_file(lockfile);
2745 static int record_eoie(void)
2747 int val;
2749 if (!git_config_get_bool("index.recordendofindexentries", &val))
2750 return val;
2753 * As a convenience, the end of index entries extension
2754 * used for threading is written by default if the user
2755 * explicitly requested threaded index reads.
2757 return !git_config_get_index_threads(&val) && val != 1;
2760 static int record_ieot(void)
2762 int val;
2764 if (!git_config_get_bool("index.recordoffsettable", &val))
2765 return val;
2768 * As a convenience, the offset table used for threading is
2769 * written by default if the user explicitly requested
2770 * threaded index reads.
2772 return !git_config_get_index_threads(&val) && val != 1;
2775 enum write_extensions {
2776 WRITE_NO_EXTENSION = 0,
2777 WRITE_SPLIT_INDEX_EXTENSION = 1<<0,
2778 WRITE_CACHE_TREE_EXTENSION = 1<<1,
2779 WRITE_RESOLVE_UNDO_EXTENSION = 1<<2,
2780 WRITE_UNTRACKED_CACHE_EXTENSION = 1<<3,
2781 WRITE_FSMONITOR_EXTENSION = 1<<4,
2783 #define WRITE_ALL_EXTENSIONS ((enum write_extensions)-1)
2786 * On success, `tempfile` is closed. If it is the temporary file
2787 * of a `struct lock_file`, we will therefore effectively perform
2788 * a 'close_lock_file_gently()`. Since that is an implementation
2789 * detail of lockfiles, callers of `do_write_index()` should not
2790 * rely on it.
2792 static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2793 enum write_extensions write_extensions, unsigned flags)
2795 uint64_t start = getnanotime();
2796 struct hashfile *f;
2797 git_hash_ctx *eoie_c = NULL;
2798 struct cache_header hdr;
2799 int i, err = 0, removed, extended, hdr_version;
2800 struct cache_entry **cache = istate->cache;
2801 int entries = istate->cache_nr;
2802 struct stat st;
2803 struct ondisk_cache_entry ondisk;
2804 struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2805 int drop_cache_tree = istate->drop_cache_tree;
2806 off_t offset;
2807 int csum_fsync_flag;
2808 int ieot_entries = 1;
2809 struct index_entry_offset_table *ieot = NULL;
2810 int nr, nr_threads;
2811 struct repository *r = istate->repo;
2813 f = hashfd(tempfile->fd, tempfile->filename.buf);
2815 prepare_repo_settings(r);
2816 f->skip_hash = r->settings.index_skip_hash;
2818 for (i = removed = extended = 0; i < entries; i++) {
2819 if (cache[i]->ce_flags & CE_REMOVE)
2820 removed++;
2822 /* reduce extended entries if possible */
2823 cache[i]->ce_flags &= ~CE_EXTENDED;
2824 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2825 extended++;
2826 cache[i]->ce_flags |= CE_EXTENDED;
2830 if (!istate->version)
2831 istate->version = get_index_format_default(r);
2833 /* demote version 3 to version 2 when the latter suffices */
2834 if (istate->version == 3 || istate->version == 2)
2835 istate->version = extended ? 3 : 2;
2837 hdr_version = istate->version;
2839 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2840 hdr.hdr_version = htonl(hdr_version);
2841 hdr.hdr_entries = htonl(entries - removed);
2843 hashwrite(f, &hdr, sizeof(hdr));
2845 if (!HAVE_THREADS || git_config_get_index_threads(&nr_threads))
2846 nr_threads = 1;
2848 if (nr_threads != 1 && record_ieot()) {
2849 int ieot_blocks, cpus;
2852 * ensure default number of ieot blocks maps evenly to the
2853 * default number of threads that will process them leaving
2854 * room for the thread to load the index extensions.
2856 if (!nr_threads) {
2857 ieot_blocks = istate->cache_nr / THREAD_COST;
2858 cpus = online_cpus();
2859 if (ieot_blocks > cpus - 1)
2860 ieot_blocks = cpus - 1;
2861 } else {
2862 ieot_blocks = nr_threads;
2863 if (ieot_blocks > istate->cache_nr)
2864 ieot_blocks = istate->cache_nr;
2868 * no reason to write out the IEOT extension if we don't
2869 * have enough blocks to utilize multi-threading
2871 if (ieot_blocks > 1) {
2872 ieot = xcalloc(1, sizeof(struct index_entry_offset_table)
2873 + (ieot_blocks * sizeof(struct index_entry_offset)));
2874 ieot_entries = DIV_ROUND_UP(entries, ieot_blocks);
2878 offset = hashfile_total(f);
2880 nr = 0;
2881 previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
2883 for (i = 0; i < entries; i++) {
2884 struct cache_entry *ce = cache[i];
2885 if (ce->ce_flags & CE_REMOVE)
2886 continue;
2887 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
2888 ce_smudge_racily_clean_entry(istate, ce);
2889 if (is_null_oid(&ce->oid)) {
2890 static const char msg[] = "cache entry has null sha1: %s";
2891 static int allow = -1;
2893 if (allow < 0)
2894 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
2895 if (allow)
2896 warning(msg, ce->name);
2897 else
2898 err = error(msg, ce->name);
2900 drop_cache_tree = 1;
2902 if (ieot && i && (i % ieot_entries == 0)) {
2903 ieot->entries[ieot->nr].nr = nr;
2904 ieot->entries[ieot->nr].offset = offset;
2905 ieot->nr++;
2907 * If we have a V4 index, set the first byte to an invalid
2908 * character to ensure there is nothing common with the previous
2909 * entry
2911 if (previous_name)
2912 previous_name->buf[0] = 0;
2913 nr = 0;
2915 offset = hashfile_total(f);
2917 if (ce_write_entry(f, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
2918 err = -1;
2920 if (err)
2921 break;
2922 nr++;
2924 if (ieot && nr) {
2925 ieot->entries[ieot->nr].nr = nr;
2926 ieot->entries[ieot->nr].offset = offset;
2927 ieot->nr++;
2929 strbuf_release(&previous_name_buf);
2931 if (err) {
2932 free(ieot);
2933 return err;
2936 offset = hashfile_total(f);
2939 * The extension headers must be hashed on their own for the
2940 * EOIE extension. Create a hashfile here to compute that hash.
2942 if (offset && record_eoie()) {
2943 CALLOC_ARRAY(eoie_c, 1);
2944 the_hash_algo->init_fn(eoie_c);
2948 * Lets write out CACHE_EXT_INDEXENTRYOFFSETTABLE first so that we
2949 * can minimize the number of extensions we have to scan through to
2950 * find it during load. Write it out regardless of the
2951 * strip_extensions parameter as we need it when loading the shared
2952 * index.
2954 if (ieot) {
2955 struct strbuf sb = STRBUF_INIT;
2957 write_ieot_extension(&sb, ieot);
2958 err = write_index_ext_header(f, eoie_c, CACHE_EXT_INDEXENTRYOFFSETTABLE, sb.len) < 0;
2959 hashwrite(f, sb.buf, sb.len);
2960 strbuf_release(&sb);
2961 free(ieot);
2962 if (err)
2963 return -1;
2966 if (write_extensions & WRITE_SPLIT_INDEX_EXTENSION &&
2967 istate->split_index) {
2968 struct strbuf sb = STRBUF_INIT;
2970 if (istate->sparse_index)
2971 die(_("cannot write split index for a sparse index"));
2973 err = write_link_extension(&sb, istate) < 0 ||
2974 write_index_ext_header(f, eoie_c, CACHE_EXT_LINK,
2975 sb.len) < 0;
2976 hashwrite(f, sb.buf, sb.len);
2977 strbuf_release(&sb);
2978 if (err)
2979 return -1;
2981 if (write_extensions & WRITE_CACHE_TREE_EXTENSION &&
2982 !drop_cache_tree && istate->cache_tree) {
2983 struct strbuf sb = STRBUF_INIT;
2985 cache_tree_write(&sb, istate->cache_tree);
2986 err = write_index_ext_header(f, eoie_c, CACHE_EXT_TREE, sb.len) < 0;
2987 hashwrite(f, sb.buf, sb.len);
2988 strbuf_release(&sb);
2989 if (err)
2990 return -1;
2992 if (write_extensions & WRITE_RESOLVE_UNDO_EXTENSION &&
2993 istate->resolve_undo) {
2994 struct strbuf sb = STRBUF_INIT;
2996 resolve_undo_write(&sb, istate->resolve_undo);
2997 err = write_index_ext_header(f, eoie_c, CACHE_EXT_RESOLVE_UNDO,
2998 sb.len) < 0;
2999 hashwrite(f, sb.buf, sb.len);
3000 strbuf_release(&sb);
3001 if (err)
3002 return -1;
3004 if (write_extensions & WRITE_UNTRACKED_CACHE_EXTENSION &&
3005 istate->untracked) {
3006 struct strbuf sb = STRBUF_INIT;
3008 write_untracked_extension(&sb, istate->untracked);
3009 err = write_index_ext_header(f, eoie_c, CACHE_EXT_UNTRACKED,
3010 sb.len) < 0;
3011 hashwrite(f, sb.buf, sb.len);
3012 strbuf_release(&sb);
3013 if (err)
3014 return -1;
3016 if (write_extensions & WRITE_FSMONITOR_EXTENSION &&
3017 istate->fsmonitor_last_update) {
3018 struct strbuf sb = STRBUF_INIT;
3020 write_fsmonitor_extension(&sb, istate);
3021 err = write_index_ext_header(f, eoie_c, CACHE_EXT_FSMONITOR, sb.len) < 0;
3022 hashwrite(f, sb.buf, sb.len);
3023 strbuf_release(&sb);
3024 if (err)
3025 return -1;
3027 if (istate->sparse_index) {
3028 if (write_index_ext_header(f, eoie_c, CACHE_EXT_SPARSE_DIRECTORIES, 0) < 0)
3029 return -1;
3033 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
3034 * so that it can be found and processed before all the index entries are
3035 * read. Write it out regardless of the strip_extensions parameter as we need it
3036 * when loading the shared index.
3038 if (eoie_c) {
3039 struct strbuf sb = STRBUF_INIT;
3041 write_eoie_extension(&sb, eoie_c, offset);
3042 err = write_index_ext_header(f, NULL, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0;
3043 hashwrite(f, sb.buf, sb.len);
3044 strbuf_release(&sb);
3045 if (err)
3046 return -1;
3049 csum_fsync_flag = 0;
3050 if (!alternate_index_output && (flags & COMMIT_LOCK))
3051 csum_fsync_flag = CSUM_FSYNC;
3053 finalize_hashfile(f, istate->oid.hash, FSYNC_COMPONENT_INDEX,
3054 CSUM_HASH_IN_STREAM | csum_fsync_flag);
3056 if (close_tempfile_gently(tempfile)) {
3057 error(_("could not close '%s'"), get_tempfile_path(tempfile));
3058 return -1;
3060 if (stat(get_tempfile_path(tempfile), &st))
3061 return -1;
3062 istate->timestamp.sec = (unsigned int)st.st_mtime;
3063 istate->timestamp.nsec = ST_MTIME_NSEC(st);
3064 trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
3067 * TODO trace2: replace "the_repository" with the actual repo instance
3068 * that is associated with the given "istate".
3070 trace2_data_intmax("index", the_repository, "write/version",
3071 istate->version);
3072 trace2_data_intmax("index", the_repository, "write/cache_nr",
3073 istate->cache_nr);
3075 return 0;
3078 void set_alternate_index_output(const char *name)
3080 alternate_index_output = name;
3083 static int commit_locked_index(struct lock_file *lk)
3085 if (alternate_index_output)
3086 return commit_lock_file_to(lk, alternate_index_output);
3087 else
3088 return commit_lock_file(lk);
3091 static int do_write_locked_index(struct index_state *istate,
3092 struct lock_file *lock,
3093 unsigned flags,
3094 enum write_extensions write_extensions)
3096 int ret;
3097 int was_full = istate->sparse_index == INDEX_EXPANDED;
3099 ret = convert_to_sparse(istate, 0);
3101 if (ret) {
3102 warning(_("failed to convert to a sparse-index"));
3103 return ret;
3107 * TODO trace2: replace "the_repository" with the actual repo instance
3108 * that is associated with the given "istate".
3110 trace2_region_enter_printf("index", "do_write_index", the_repository,
3111 "%s", get_lock_file_path(lock));
3112 ret = do_write_index(istate, lock->tempfile, write_extensions, flags);
3113 trace2_region_leave_printf("index", "do_write_index", the_repository,
3114 "%s", get_lock_file_path(lock));
3116 if (was_full)
3117 ensure_full_index(istate);
3119 if (ret)
3120 return ret;
3121 if (flags & COMMIT_LOCK)
3122 ret = commit_locked_index(lock);
3123 else
3124 ret = close_lock_file_gently(lock);
3126 run_hooks_l("post-index-change",
3127 istate->updated_workdir ? "1" : "0",
3128 istate->updated_skipworktree ? "1" : "0", NULL);
3129 istate->updated_workdir = 0;
3130 istate->updated_skipworktree = 0;
3132 return ret;
3135 static int write_split_index(struct index_state *istate,
3136 struct lock_file *lock,
3137 unsigned flags)
3139 int ret;
3140 prepare_to_write_split_index(istate);
3141 ret = do_write_locked_index(istate, lock, flags, WRITE_ALL_EXTENSIONS);
3142 finish_writing_split_index(istate);
3143 return ret;
3146 static const char *shared_index_expire = "2.weeks.ago";
3148 static unsigned long get_shared_index_expire_date(void)
3150 static unsigned long shared_index_expire_date;
3151 static int shared_index_expire_date_prepared;
3153 if (!shared_index_expire_date_prepared) {
3154 git_config_get_expiry("splitindex.sharedindexexpire",
3155 &shared_index_expire);
3156 shared_index_expire_date = approxidate(shared_index_expire);
3157 shared_index_expire_date_prepared = 1;
3160 return shared_index_expire_date;
3163 static int should_delete_shared_index(const char *shared_index_path)
3165 struct stat st;
3166 unsigned long expiration;
3168 /* Check timestamp */
3169 expiration = get_shared_index_expire_date();
3170 if (!expiration)
3171 return 0;
3172 if (stat(shared_index_path, &st))
3173 return error_errno(_("could not stat '%s'"), shared_index_path);
3174 if (st.st_mtime > expiration)
3175 return 0;
3177 return 1;
3180 static int clean_shared_index_files(const char *current_hex)
3182 struct dirent *de;
3183 DIR *dir = opendir(get_git_dir());
3185 if (!dir)
3186 return error_errno(_("unable to open git dir: %s"), get_git_dir());
3188 while ((de = readdir(dir)) != NULL) {
3189 const char *sha1_hex;
3190 const char *shared_index_path;
3191 if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
3192 continue;
3193 if (!strcmp(sha1_hex, current_hex))
3194 continue;
3195 shared_index_path = git_path("%s", de->d_name);
3196 if (should_delete_shared_index(shared_index_path) > 0 &&
3197 unlink(shared_index_path))
3198 warning_errno(_("unable to unlink: %s"), shared_index_path);
3200 closedir(dir);
3202 return 0;
3205 static int write_shared_index(struct index_state *istate,
3206 struct tempfile **temp, unsigned flags)
3208 struct split_index *si = istate->split_index;
3209 int ret, was_full = !istate->sparse_index;
3211 move_cache_to_base_index(istate);
3212 convert_to_sparse(istate, 0);
3214 trace2_region_enter_printf("index", "shared/do_write_index",
3215 the_repository, "%s", get_tempfile_path(*temp));
3216 ret = do_write_index(si->base, *temp, WRITE_NO_EXTENSION, flags);
3217 trace2_region_leave_printf("index", "shared/do_write_index",
3218 the_repository, "%s", get_tempfile_path(*temp));
3220 if (was_full)
3221 ensure_full_index(istate);
3223 if (ret)
3224 return ret;
3225 ret = adjust_shared_perm(get_tempfile_path(*temp));
3226 if (ret) {
3227 error(_("cannot fix permission bits on '%s'"), get_tempfile_path(*temp));
3228 return ret;
3230 ret = rename_tempfile(temp,
3231 git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
3232 if (!ret) {
3233 oidcpy(&si->base_oid, &si->base->oid);
3234 clean_shared_index_files(oid_to_hex(&si->base->oid));
3237 return ret;
3240 static const int default_max_percent_split_change = 20;
3242 static int too_many_not_shared_entries(struct index_state *istate)
3244 int i, not_shared = 0;
3245 int max_split = git_config_get_max_percent_split_change();
3247 switch (max_split) {
3248 case -1:
3249 /* not or badly configured: use the default value */
3250 max_split = default_max_percent_split_change;
3251 break;
3252 case 0:
3253 return 1; /* 0% means always write a new shared index */
3254 case 100:
3255 return 0; /* 100% means never write a new shared index */
3256 default:
3257 break; /* just use the configured value */
3260 /* Count not shared entries */
3261 for (i = 0; i < istate->cache_nr; i++) {
3262 struct cache_entry *ce = istate->cache[i];
3263 if (!ce->index)
3264 not_shared++;
3267 return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
3270 int write_locked_index(struct index_state *istate, struct lock_file *lock,
3271 unsigned flags)
3273 int new_shared_index, ret, test_split_index_env;
3274 struct split_index *si = istate->split_index;
3276 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
3277 cache_tree_verify(the_repository, istate);
3279 if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
3280 if (flags & COMMIT_LOCK)
3281 rollback_lock_file(lock);
3282 return 0;
3285 if (istate->fsmonitor_last_update)
3286 fill_fsmonitor_bitmap(istate);
3288 test_split_index_env = git_env_bool("GIT_TEST_SPLIT_INDEX", 0);
3290 if ((!si && !test_split_index_env) ||
3291 alternate_index_output ||
3292 (istate->cache_changed & ~EXTMASK)) {
3293 ret = do_write_locked_index(istate, lock, flags,
3294 ~WRITE_SPLIT_INDEX_EXTENSION);
3295 goto out;
3298 if (test_split_index_env) {
3299 if (!si) {
3300 si = init_split_index(istate);
3301 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3302 } else {
3303 int v = si->base_oid.hash[0];
3304 if ((v & 15) < 6)
3305 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3308 if (too_many_not_shared_entries(istate))
3309 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3311 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
3313 if (new_shared_index) {
3314 struct tempfile *temp;
3315 int saved_errno;
3317 /* Same initial permissions as the main .git/index file */
3318 temp = mks_tempfile_sm(git_path("sharedindex_XXXXXX"), 0, 0666);
3319 if (!temp) {
3320 ret = do_write_locked_index(istate, lock, flags,
3321 ~WRITE_SPLIT_INDEX_EXTENSION);
3322 goto out;
3324 ret = write_shared_index(istate, &temp, flags);
3326 saved_errno = errno;
3327 if (is_tempfile_active(temp))
3328 delete_tempfile(&temp);
3329 errno = saved_errno;
3331 if (ret)
3332 goto out;
3335 ret = write_split_index(istate, lock, flags);
3337 /* Freshen the shared index only if the split-index was written */
3338 if (!ret && !new_shared_index && !is_null_oid(&si->base_oid)) {
3339 const char *shared_index = git_path("sharedindex.%s",
3340 oid_to_hex(&si->base_oid));
3341 freshen_shared_index(shared_index, 1);
3344 out:
3345 if (flags & COMMIT_LOCK)
3346 rollback_lock_file(lock);
3347 return ret;
3351 * Read the index file that is potentially unmerged into given
3352 * index_state, dropping any unmerged entries to stage #0 (potentially
3353 * resulting in a path appearing as both a file and a directory in the
3354 * index; the caller is responsible to clear out the extra entries
3355 * before writing the index to a tree). Returns true if the index is
3356 * unmerged. Callers who want to refuse to work from an unmerged
3357 * state can call this and check its return value, instead of calling
3358 * read_cache().
3360 int repo_read_index_unmerged(struct repository *repo)
3362 struct index_state *istate;
3363 int i;
3364 int unmerged = 0;
3366 repo_read_index(repo);
3367 istate = repo->index;
3368 for (i = 0; i < istate->cache_nr; i++) {
3369 struct cache_entry *ce = istate->cache[i];
3370 struct cache_entry *new_ce;
3371 int len;
3373 if (!ce_stage(ce))
3374 continue;
3375 unmerged = 1;
3376 len = ce_namelen(ce);
3377 new_ce = make_empty_cache_entry(istate, len);
3378 memcpy(new_ce->name, ce->name, len);
3379 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3380 new_ce->ce_namelen = len;
3381 new_ce->ce_mode = ce->ce_mode;
3382 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3383 return error(_("%s: cannot drop to stage #0"),
3384 new_ce->name);
3386 return unmerged;
3390 * Returns 1 if the path is an "other" path with respect to
3391 * the index; that is, the path is not mentioned in the index at all,
3392 * either as a file, a directory with some files in the index,
3393 * or as an unmerged entry.
3395 * We helpfully remove a trailing "/" from directories so that
3396 * the output of read_directory can be used as-is.
3398 int index_name_is_other(struct index_state *istate, const char *name,
3399 int namelen)
3401 int pos;
3402 if (namelen && name[namelen - 1] == '/')
3403 namelen--;
3404 pos = index_name_pos(istate, name, namelen);
3405 if (0 <= pos)
3406 return 0; /* exact match */
3407 pos = -pos - 1;
3408 if (pos < istate->cache_nr) {
3409 struct cache_entry *ce = istate->cache[pos];
3410 if (ce_namelen(ce) == namelen &&
3411 !memcmp(ce->name, name, namelen))
3412 return 0; /* Yup, this one exists unmerged */
3414 return 1;
3417 void *read_blob_data_from_index(struct index_state *istate,
3418 const char *path, unsigned long *size)
3420 int pos, len;
3421 unsigned long sz;
3422 enum object_type type;
3423 void *data;
3425 len = strlen(path);
3426 pos = index_name_pos(istate, path, len);
3427 if (pos < 0) {
3429 * We might be in the middle of a merge, in which
3430 * case we would read stage #2 (ours).
3432 int i;
3433 for (i = -pos - 1;
3434 (pos < 0 && i < istate->cache_nr &&
3435 !strcmp(istate->cache[i]->name, path));
3436 i++)
3437 if (ce_stage(istate->cache[i]) == 2)
3438 pos = i;
3440 if (pos < 0)
3441 return NULL;
3442 data = repo_read_object_file(the_repository, &istate->cache[pos]->oid,
3443 &type, &sz);
3444 if (!data || type != OBJ_BLOB) {
3445 free(data);
3446 return NULL;
3448 if (size)
3449 *size = sz;
3450 return data;
3453 void move_index_extensions(struct index_state *dst, struct index_state *src)
3455 dst->untracked = src->untracked;
3456 src->untracked = NULL;
3457 dst->cache_tree = src->cache_tree;
3458 src->cache_tree = NULL;
3461 struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3462 struct index_state *istate)
3464 unsigned int size = ce_size(ce);
3465 int mem_pool_allocated;
3466 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3467 mem_pool_allocated = new_entry->mem_pool_allocated;
3469 memcpy(new_entry, ce, size);
3470 new_entry->mem_pool_allocated = mem_pool_allocated;
3471 return new_entry;
3474 void discard_cache_entry(struct cache_entry *ce)
3476 if (ce && should_validate_cache_entries())
3477 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3479 if (ce && ce->mem_pool_allocated)
3480 return;
3482 free(ce);
3485 int should_validate_cache_entries(void)
3487 static int validate_index_cache_entries = -1;
3489 if (validate_index_cache_entries < 0) {
3490 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3491 validate_index_cache_entries = 1;
3492 else
3493 validate_index_cache_entries = 0;
3496 return validate_index_cache_entries;
3499 #define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3500 #define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3502 static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3505 * The end of index entries (EOIE) extension is guaranteed to be last
3506 * so that it can be found by scanning backwards from the EOF.
3508 * "EOIE"
3509 * <4-byte length>
3510 * <4-byte offset>
3511 * <20-byte hash>
3513 const char *index, *eoie;
3514 uint32_t extsize;
3515 size_t offset, src_offset;
3516 unsigned char hash[GIT_MAX_RAWSZ];
3517 git_hash_ctx c;
3519 /* ensure we have an index big enough to contain an EOIE extension */
3520 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3521 return 0;
3523 /* validate the extension signature */
3524 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3525 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3526 return 0;
3527 index += sizeof(uint32_t);
3529 /* validate the extension size */
3530 extsize = get_be32(index);
3531 if (extsize != EOIE_SIZE)
3532 return 0;
3533 index += sizeof(uint32_t);
3536 * Validate the offset we're going to look for the first extension
3537 * signature is after the index header and before the eoie extension.
3539 offset = get_be32(index);
3540 if (mmap + offset < mmap + sizeof(struct cache_header))
3541 return 0;
3542 if (mmap + offset >= eoie)
3543 return 0;
3544 index += sizeof(uint32_t);
3547 * The hash is computed over extension types and their sizes (but not
3548 * their contents). E.g. if we have "TREE" extension that is N-bytes
3549 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3550 * then the hash would be:
3552 * SHA-1("TREE" + <binary representation of N> +
3553 * "REUC" + <binary representation of M>)
3555 src_offset = offset;
3556 the_hash_algo->init_fn(&c);
3557 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3558 /* After an array of active_nr index entries,
3559 * there can be arbitrary number of extended
3560 * sections, each of which is prefixed with
3561 * extension name (4-byte) and section length
3562 * in 4-byte network byte order.
3564 uint32_t extsize;
3565 memcpy(&extsize, mmap + src_offset + 4, 4);
3566 extsize = ntohl(extsize);
3568 /* verify the extension size isn't so large it will wrap around */
3569 if (src_offset + 8 + extsize < src_offset)
3570 return 0;
3572 the_hash_algo->update_fn(&c, mmap + src_offset, 8);
3574 src_offset += 8;
3575 src_offset += extsize;
3577 the_hash_algo->final_fn(hash, &c);
3578 if (!hasheq(hash, (const unsigned char *)index))
3579 return 0;
3581 /* Validate that the extension offsets returned us back to the eoie extension. */
3582 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3583 return 0;
3585 return offset;
3588 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset)
3590 uint32_t buffer;
3591 unsigned char hash[GIT_MAX_RAWSZ];
3593 /* offset */
3594 put_be32(&buffer, offset);
3595 strbuf_add(sb, &buffer, sizeof(uint32_t));
3597 /* hash */
3598 the_hash_algo->final_fn(hash, eoie_context);
3599 strbuf_add(sb, hash, the_hash_algo->rawsz);
3602 #define IEOT_VERSION (1)
3604 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3606 const char *index = NULL;
3607 uint32_t extsize, ext_version;
3608 struct index_entry_offset_table *ieot;
3609 int i, nr;
3611 /* find the IEOT extension */
3612 if (!offset)
3613 return NULL;
3614 while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3615 extsize = get_be32(mmap + offset + 4);
3616 if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3617 index = mmap + offset + 4 + 4;
3618 break;
3620 offset += 8;
3621 offset += extsize;
3623 if (!index)
3624 return NULL;
3626 /* validate the version is IEOT_VERSION */
3627 ext_version = get_be32(index);
3628 if (ext_version != IEOT_VERSION) {
3629 error("invalid IEOT version %d", ext_version);
3630 return NULL;
3632 index += sizeof(uint32_t);
3634 /* extension size - version bytes / bytes per entry */
3635 nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3636 if (!nr) {
3637 error("invalid number of IEOT entries %d", nr);
3638 return NULL;
3640 ieot = xmalloc(sizeof(struct index_entry_offset_table)
3641 + (nr * sizeof(struct index_entry_offset)));
3642 ieot->nr = nr;
3643 for (i = 0; i < nr; i++) {
3644 ieot->entries[i].offset = get_be32(index);
3645 index += sizeof(uint32_t);
3646 ieot->entries[i].nr = get_be32(index);
3647 index += sizeof(uint32_t);
3650 return ieot;
3653 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3655 uint32_t buffer;
3656 int i;
3658 /* version */
3659 put_be32(&buffer, IEOT_VERSION);
3660 strbuf_add(sb, &buffer, sizeof(uint32_t));
3662 /* ieot */
3663 for (i = 0; i < ieot->nr; i++) {
3665 /* offset */
3666 put_be32(&buffer, ieot->entries[i].offset);
3667 strbuf_add(sb, &buffer, sizeof(uint32_t));
3669 /* count */
3670 put_be32(&buffer, ieot->entries[i].nr);
3671 strbuf_add(sb, &buffer, sizeof(uint32_t));
3675 void prefetch_cache_entries(const struct index_state *istate,
3676 must_prefetch_predicate must_prefetch)
3678 int i;
3679 struct oid_array to_fetch = OID_ARRAY_INIT;
3681 for (i = 0; i < istate->cache_nr; i++) {
3682 struct cache_entry *ce = istate->cache[i];
3684 if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce))
3685 continue;
3686 if (!oid_object_info_extended(the_repository, &ce->oid,
3687 NULL,
3688 OBJECT_INFO_FOR_PREFETCH))
3689 continue;
3690 oid_array_append(&to_fetch, &ce->oid);
3692 promisor_remote_get_direct(the_repository,
3693 to_fetch.oid, to_fetch.nr);
3694 oid_array_clear(&to_fetch);
3697 static int read_one_entry_opt(struct index_state *istate,
3698 const struct object_id *oid,
3699 struct strbuf *base,
3700 const char *pathname,
3701 unsigned mode, int opt)
3703 int len;
3704 struct cache_entry *ce;
3706 if (S_ISDIR(mode))
3707 return READ_TREE_RECURSIVE;
3709 len = strlen(pathname);
3710 ce = make_empty_cache_entry(istate, base->len + len);
3712 ce->ce_mode = create_ce_mode(mode);
3713 ce->ce_flags = create_ce_flags(1);
3714 ce->ce_namelen = base->len + len;
3715 memcpy(ce->name, base->buf, base->len);
3716 memcpy(ce->name + base->len, pathname, len+1);
3717 oidcpy(&ce->oid, oid);
3718 return add_index_entry(istate, ce, opt);
3721 static int read_one_entry(const struct object_id *oid, struct strbuf *base,
3722 const char *pathname, unsigned mode,
3723 void *context)
3725 struct index_state *istate = context;
3726 return read_one_entry_opt(istate, oid, base, pathname,
3727 mode,
3728 ADD_CACHE_OK_TO_ADD|ADD_CACHE_SKIP_DFCHECK);
3732 * This is used when the caller knows there is no existing entries at
3733 * the stage that will conflict with the entry being added.
3735 static int read_one_entry_quick(const struct object_id *oid, struct strbuf *base,
3736 const char *pathname, unsigned mode,
3737 void *context)
3739 struct index_state *istate = context;
3740 return read_one_entry_opt(istate, oid, base, pathname,
3741 mode, ADD_CACHE_JUST_APPEND);
3745 * Read the tree specified with --with-tree option
3746 * (typically, HEAD) into stage #1 and then
3747 * squash them down to stage #0. This is used for
3748 * --error-unmatch to list and check the path patterns
3749 * that were given from the command line. We are not
3750 * going to write this index out.
3752 void overlay_tree_on_index(struct index_state *istate,
3753 const char *tree_name, const char *prefix)
3755 struct tree *tree;
3756 struct object_id oid;
3757 struct pathspec pathspec;
3758 struct cache_entry *last_stage0 = NULL;
3759 int i;
3760 read_tree_fn_t fn = NULL;
3761 int err;
3763 if (repo_get_oid(the_repository, tree_name, &oid))
3764 die("tree-ish %s not found.", tree_name);
3765 tree = parse_tree_indirect(&oid);
3766 if (!tree)
3767 die("bad tree-ish %s", tree_name);
3769 /* Hoist the unmerged entries up to stage #3 to make room */
3770 /* TODO: audit for interaction with sparse-index. */
3771 ensure_full_index(istate);
3772 for (i = 0; i < istate->cache_nr; i++) {
3773 struct cache_entry *ce = istate->cache[i];
3774 if (!ce_stage(ce))
3775 continue;
3776 ce->ce_flags |= CE_STAGEMASK;
3779 if (prefix) {
3780 static const char *(matchbuf[1]);
3781 matchbuf[0] = NULL;
3782 parse_pathspec(&pathspec, PATHSPEC_ALL_MAGIC,
3783 PATHSPEC_PREFER_CWD, prefix, matchbuf);
3784 } else
3785 memset(&pathspec, 0, sizeof(pathspec));
3788 * See if we have cache entry at the stage. If so,
3789 * do it the original slow way, otherwise, append and then
3790 * sort at the end.
3792 for (i = 0; !fn && i < istate->cache_nr; i++) {
3793 const struct cache_entry *ce = istate->cache[i];
3794 if (ce_stage(ce) == 1)
3795 fn = read_one_entry;
3798 if (!fn)
3799 fn = read_one_entry_quick;
3800 err = read_tree(the_repository, tree, &pathspec, fn, istate);
3801 clear_pathspec(&pathspec);
3802 if (err)
3803 die("unable to read tree entries %s", tree_name);
3806 * Sort the cache entry -- we need to nuke the cache tree, though.
3808 if (fn == read_one_entry_quick) {
3809 cache_tree_free(&istate->cache_tree);
3810 QSORT(istate->cache, istate->cache_nr, cmp_cache_name_compare);
3813 for (i = 0; i < istate->cache_nr; i++) {
3814 struct cache_entry *ce = istate->cache[i];
3815 switch (ce_stage(ce)) {
3816 case 0:
3817 last_stage0 = ce;
3818 /* fallthru */
3819 default:
3820 continue;
3821 case 1:
3823 * If there is stage #0 entry for this, we do not
3824 * need to show it. We use CE_UPDATE bit to mark
3825 * such an entry.
3827 if (last_stage0 &&
3828 !strcmp(last_stage0->name, ce->name))
3829 ce->ce_flags |= CE_UPDATE;
3834 struct update_callback_data {
3835 struct index_state *index;
3836 int include_sparse;
3837 int flags;
3838 int add_errors;
3841 static int fix_unmerged_status(struct diff_filepair *p,
3842 struct update_callback_data *data)
3844 if (p->status != DIFF_STATUS_UNMERGED)
3845 return p->status;
3846 if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
3848 * This is not an explicit add request, and the
3849 * path is missing from the working tree (deleted)
3851 return DIFF_STATUS_DELETED;
3852 else
3854 * Either an explicit add request, or path exists
3855 * in the working tree. An attempt to explicitly
3856 * add a path that does not exist in the working tree
3857 * will be caught as an error by the caller immediately.
3859 return DIFF_STATUS_MODIFIED;
3862 static void update_callback(struct diff_queue_struct *q,
3863 struct diff_options *opt UNUSED, void *cbdata)
3865 int i;
3866 struct update_callback_data *data = cbdata;
3868 for (i = 0; i < q->nr; i++) {
3869 struct diff_filepair *p = q->queue[i];
3870 const char *path = p->one->path;
3872 if (!data->include_sparse &&
3873 !path_in_sparse_checkout(path, data->index))
3874 continue;
3876 switch (fix_unmerged_status(p, data)) {
3877 default:
3878 die(_("unexpected diff status %c"), p->status);
3879 case DIFF_STATUS_MODIFIED:
3880 case DIFF_STATUS_TYPE_CHANGED:
3881 if (add_file_to_index(data->index, path, data->flags)) {
3882 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
3883 die(_("updating files failed"));
3884 data->add_errors++;
3886 break;
3887 case DIFF_STATUS_DELETED:
3888 if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
3889 break;
3890 if (!(data->flags & ADD_CACHE_PRETEND))
3891 remove_file_from_index(data->index, path);
3892 if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
3893 printf(_("remove '%s'\n"), path);
3894 break;
3899 int add_files_to_cache(struct repository *repo, const char *prefix,
3900 const struct pathspec *pathspec, int include_sparse,
3901 int flags)
3903 struct update_callback_data data;
3904 struct rev_info rev;
3906 memset(&data, 0, sizeof(data));
3907 data.index = repo->index;
3908 data.include_sparse = include_sparse;
3909 data.flags = flags;
3911 repo_init_revisions(repo, &rev, prefix);
3912 setup_revisions(0, NULL, &rev, NULL);
3913 if (pathspec)
3914 copy_pathspec(&rev.prune_data, pathspec);
3915 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
3916 rev.diffopt.format_callback = update_callback;
3917 rev.diffopt.format_callback_data = &data;
3918 rev.diffopt.flags.override_submodule_config = 1;
3919 rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
3922 * Use an ODB transaction to optimize adding multiple objects.
3923 * This function is invoked from commands other than 'add', which
3924 * may not have their own transaction active.
3926 begin_odb_transaction();
3927 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
3928 end_odb_transaction();
3930 release_revisions(&rev);
3931 return !!data.add_errors;