var: avoid a segmentation fault when `HOME` is unset
[git.git] / read-cache.c
blobf4c31a68c85a62705c370b0a34bf021e91538de6
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "cache.h"
7 #include "alloc.h"
8 #include "config.h"
9 #include "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.h"
20 #include "oid-array.h"
21 #include "tree.h"
22 #include "commit.h"
23 #include "blob.h"
24 #include "environment.h"
25 #include "gettext.h"
26 #include "mem-pool.h"
27 #include "object-name.h"
28 #include "resolve-undo.h"
29 #include "run-command.h"
30 #include "strbuf.h"
31 #include "trace2.h"
32 #include "varint.h"
33 #include "split-index.h"
34 #include "symlinks.h"
35 #include "utf8.h"
36 #include "fsmonitor.h"
37 #include "thread-utils.h"
38 #include "progress.h"
39 #include "sparse-index.h"
40 #include "csum-file.h"
41 #include "promisor-remote.h"
42 #include "hook.h"
43 #include "wrapper.h"
45 /* Mask for the name length in ce_flags in the on-disk index */
47 #define CE_NAMEMASK (0x0fff)
49 /* Index extensions.
51 * The first letter should be 'A'..'Z' for extensions that are not
52 * necessary for a correct operation (i.e. optimization data).
53 * When new extensions are added that _needs_ to be understood in
54 * order to correctly interpret the index file, pick character that
55 * is outside the range, to cause the reader to abort.
58 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
59 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
60 #define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
61 #define CACHE_EXT_LINK 0x6c696e6b /* "link" */
62 #define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
63 #define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
64 #define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945 /* "EOIE" */
65 #define CACHE_EXT_INDEXENTRYOFFSETTABLE 0x49454F54 /* "IEOT" */
66 #define CACHE_EXT_SPARSE_DIRECTORIES 0x73646972 /* "sdir" */
68 /* changes that can be kept in $GIT_DIR/index (basically all extensions) */
69 #define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
70 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
71 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
75 * This is an estimate of the pathname length in the index. We use
76 * this for V4 index files to guess the un-deltafied size of the index
77 * in memory because of pathname deltafication. This is not required
78 * for V2/V3 index formats because their pathnames are not compressed.
79 * If the initial amount of memory set aside is not sufficient, the
80 * mem pool will allocate extra memory.
82 #define CACHE_ENTRY_PATH_LENGTH 80
84 enum index_search_mode {
85 NO_EXPAND_SPARSE = 0,
86 EXPAND_SPARSE = 1
89 static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
91 struct cache_entry *ce;
92 ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
93 ce->mem_pool_allocated = 1;
94 return ce;
97 static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
99 struct cache_entry * ce;
100 ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
101 ce->mem_pool_allocated = 1;
102 return ce;
105 static struct mem_pool *find_mem_pool(struct index_state *istate)
107 struct mem_pool **pool_ptr;
109 if (istate->split_index && istate->split_index->base)
110 pool_ptr = &istate->split_index->base->ce_mem_pool;
111 else
112 pool_ptr = &istate->ce_mem_pool;
114 if (!*pool_ptr) {
115 *pool_ptr = xmalloc(sizeof(**pool_ptr));
116 mem_pool_init(*pool_ptr, 0);
119 return *pool_ptr;
122 static const char *alternate_index_output;
124 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
126 if (S_ISSPARSEDIR(ce->ce_mode))
127 istate->sparse_index = INDEX_COLLAPSED;
129 istate->cache[nr] = ce;
130 add_name_hash(istate, ce);
133 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
135 struct cache_entry *old = istate->cache[nr];
137 replace_index_entry_in_base(istate, old, ce);
138 remove_name_hash(istate, old);
139 discard_cache_entry(old);
140 ce->ce_flags &= ~CE_HASHED;
141 set_index_entry(istate, nr, ce);
142 ce->ce_flags |= CE_UPDATE_IN_BASE;
143 mark_fsmonitor_invalid(istate, ce);
144 istate->cache_changed |= CE_ENTRY_CHANGED;
147 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
149 struct cache_entry *old_entry = istate->cache[nr], *new_entry, *refreshed;
150 int namelen = strlen(new_name);
152 new_entry = make_empty_cache_entry(istate, namelen);
153 copy_cache_entry(new_entry, old_entry);
154 new_entry->ce_flags &= ~CE_HASHED;
155 new_entry->ce_namelen = namelen;
156 new_entry->index = 0;
157 memcpy(new_entry->name, new_name, namelen + 1);
159 cache_tree_invalidate_path(istate, old_entry->name);
160 untracked_cache_remove_from_index(istate, old_entry->name);
161 remove_index_entry_at(istate, nr);
164 * Refresh the new index entry. Using 'refresh_cache_entry' ensures
165 * we only update stat info if the entry is otherwise up-to-date (i.e.,
166 * the contents/mode haven't changed). This ensures that we reflect the
167 * 'ctime' of the rename in the index without (incorrectly) updating
168 * the cached stat info to reflect unstaged changes on disk.
170 refreshed = refresh_cache_entry(istate, new_entry, CE_MATCH_REFRESH);
171 if (refreshed && refreshed != new_entry) {
172 add_index_entry(istate, refreshed, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
173 discard_cache_entry(new_entry);
174 } else
175 add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
178 void fill_stat_data(struct stat_data *sd, struct stat *st)
180 sd->sd_ctime.sec = (unsigned int)st->st_ctime;
181 sd->sd_mtime.sec = (unsigned int)st->st_mtime;
182 sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
183 sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
184 sd->sd_dev = st->st_dev;
185 sd->sd_ino = st->st_ino;
186 sd->sd_uid = st->st_uid;
187 sd->sd_gid = st->st_gid;
188 sd->sd_size = st->st_size;
191 int match_stat_data(const struct stat_data *sd, struct stat *st)
193 int changed = 0;
195 if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
196 changed |= MTIME_CHANGED;
197 if (trust_ctime && check_stat &&
198 sd->sd_ctime.sec != (unsigned int)st->st_ctime)
199 changed |= CTIME_CHANGED;
201 #ifdef USE_NSEC
202 if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
203 changed |= MTIME_CHANGED;
204 if (trust_ctime && check_stat &&
205 sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
206 changed |= CTIME_CHANGED;
207 #endif
209 if (check_stat) {
210 if (sd->sd_uid != (unsigned int) st->st_uid ||
211 sd->sd_gid != (unsigned int) st->st_gid)
212 changed |= OWNER_CHANGED;
213 if (sd->sd_ino != (unsigned int) st->st_ino)
214 changed |= INODE_CHANGED;
217 #ifdef USE_STDEV
219 * st_dev breaks on network filesystems where different
220 * clients will have different views of what "device"
221 * the filesystem is on
223 if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
224 changed |= INODE_CHANGED;
225 #endif
227 if (sd->sd_size != (unsigned int) st->st_size)
228 changed |= DATA_CHANGED;
230 return changed;
234 * This only updates the "non-critical" parts of the directory
235 * cache, ie the parts that aren't tracked by GIT, and only used
236 * to validate the cache.
238 void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st)
240 fill_stat_data(&ce->ce_stat_data, st);
242 if (assume_unchanged)
243 ce->ce_flags |= CE_VALID;
245 if (S_ISREG(st->st_mode)) {
246 ce_mark_uptodate(ce);
247 mark_fsmonitor_valid(istate, ce);
251 static int ce_compare_data(struct index_state *istate,
252 const struct cache_entry *ce,
253 struct stat *st)
255 int match = -1;
256 int fd = git_open_cloexec(ce->name, O_RDONLY);
258 if (fd >= 0) {
259 struct object_id oid;
260 if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
261 match = !oideq(&oid, &ce->oid);
262 /* index_fd() closed the file descriptor already */
264 return match;
267 static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
269 int match = -1;
270 void *buffer;
271 unsigned long size;
272 enum object_type type;
273 struct strbuf sb = STRBUF_INIT;
275 if (strbuf_readlink(&sb, ce->name, expected_size))
276 return -1;
278 buffer = repo_read_object_file(the_repository, &ce->oid, &type, &size);
279 if (buffer) {
280 if (size == sb.len)
281 match = memcmp(buffer, sb.buf, size);
282 free(buffer);
284 strbuf_release(&sb);
285 return match;
288 static int ce_compare_gitlink(const struct cache_entry *ce)
290 struct object_id oid;
293 * We don't actually require that the .git directory
294 * under GITLINK directory be a valid git directory. It
295 * might even be missing (in case nobody populated that
296 * sub-project).
298 * If so, we consider it always to match.
300 if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
301 return 0;
302 return !oideq(&oid, &ce->oid);
305 static int ce_modified_check_fs(struct index_state *istate,
306 const struct cache_entry *ce,
307 struct stat *st)
309 switch (st->st_mode & S_IFMT) {
310 case S_IFREG:
311 if (ce_compare_data(istate, ce, st))
312 return DATA_CHANGED;
313 break;
314 case S_IFLNK:
315 if (ce_compare_link(ce, xsize_t(st->st_size)))
316 return DATA_CHANGED;
317 break;
318 case S_IFDIR:
319 if (S_ISGITLINK(ce->ce_mode))
320 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
321 /* else fallthrough */
322 default:
323 return TYPE_CHANGED;
325 return 0;
328 static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
330 unsigned int changed = 0;
332 if (ce->ce_flags & CE_REMOVE)
333 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
335 switch (ce->ce_mode & S_IFMT) {
336 case S_IFREG:
337 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
338 /* We consider only the owner x bit to be relevant for
339 * "mode changes"
341 if (trust_executable_bit &&
342 (0100 & (ce->ce_mode ^ st->st_mode)))
343 changed |= MODE_CHANGED;
344 break;
345 case S_IFLNK:
346 if (!S_ISLNK(st->st_mode) &&
347 (has_symlinks || !S_ISREG(st->st_mode)))
348 changed |= TYPE_CHANGED;
349 break;
350 case S_IFGITLINK:
351 /* We ignore most of the st_xxx fields for gitlinks */
352 if (!S_ISDIR(st->st_mode))
353 changed |= TYPE_CHANGED;
354 else if (ce_compare_gitlink(ce))
355 changed |= DATA_CHANGED;
356 return changed;
357 default:
358 BUG("unsupported ce_mode: %o", ce->ce_mode);
361 changed |= match_stat_data(&ce->ce_stat_data, st);
363 /* Racily smudged entry? */
364 if (!ce->ce_stat_data.sd_size) {
365 if (!is_empty_blob_sha1(ce->oid.hash))
366 changed |= DATA_CHANGED;
369 return changed;
372 static int is_racy_stat(const struct index_state *istate,
373 const struct stat_data *sd)
375 return (istate->timestamp.sec &&
376 #ifdef USE_NSEC
377 /* nanosecond timestamped files can also be racy! */
378 (istate->timestamp.sec < sd->sd_mtime.sec ||
379 (istate->timestamp.sec == sd->sd_mtime.sec &&
380 istate->timestamp.nsec <= sd->sd_mtime.nsec))
381 #else
382 istate->timestamp.sec <= sd->sd_mtime.sec
383 #endif
387 int is_racy_timestamp(const struct index_state *istate,
388 const struct cache_entry *ce)
390 return (!S_ISGITLINK(ce->ce_mode) &&
391 is_racy_stat(istate, &ce->ce_stat_data));
394 int match_stat_data_racy(const struct index_state *istate,
395 const struct stat_data *sd, struct stat *st)
397 if (is_racy_stat(istate, sd))
398 return MTIME_CHANGED;
399 return match_stat_data(sd, st);
402 int ie_match_stat(struct index_state *istate,
403 const struct cache_entry *ce, struct stat *st,
404 unsigned int options)
406 unsigned int changed;
407 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
408 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
409 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
410 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
412 if (!ignore_fsmonitor)
413 refresh_fsmonitor(istate);
415 * If it's marked as always valid in the index, it's
416 * valid whatever the checked-out copy says.
418 * skip-worktree has the same effect with higher precedence
420 if (!ignore_skip_worktree && ce_skip_worktree(ce))
421 return 0;
422 if (!ignore_valid && (ce->ce_flags & CE_VALID))
423 return 0;
424 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
425 return 0;
428 * Intent-to-add entries have not been added, so the index entry
429 * by definition never matches what is in the work tree until it
430 * actually gets added.
432 if (ce_intent_to_add(ce))
433 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
435 changed = ce_match_stat_basic(ce, st);
438 * Within 1 second of this sequence:
439 * echo xyzzy >file && git-update-index --add file
440 * running this command:
441 * echo frotz >file
442 * would give a falsely clean cache entry. The mtime and
443 * length match the cache, and other stat fields do not change.
445 * We could detect this at update-index time (the cache entry
446 * being registered/updated records the same time as "now")
447 * and delay the return from git-update-index, but that would
448 * effectively mean we can make at most one commit per second,
449 * which is not acceptable. Instead, we check cache entries
450 * whose mtime are the same as the index file timestamp more
451 * carefully than others.
453 if (!changed && is_racy_timestamp(istate, ce)) {
454 if (assume_racy_is_modified)
455 changed |= DATA_CHANGED;
456 else
457 changed |= ce_modified_check_fs(istate, ce, st);
460 return changed;
463 int ie_modified(struct index_state *istate,
464 const struct cache_entry *ce,
465 struct stat *st, unsigned int options)
467 int changed, changed_fs;
469 changed = ie_match_stat(istate, ce, st, options);
470 if (!changed)
471 return 0;
473 * If the mode or type has changed, there's no point in trying
474 * to refresh the entry - it's not going to match
476 if (changed & (MODE_CHANGED | TYPE_CHANGED))
477 return changed;
480 * Immediately after read-tree or update-index --cacheinfo,
481 * the length field is zero, as we have never even read the
482 * lstat(2) information once, and we cannot trust DATA_CHANGED
483 * returned by ie_match_stat() which in turn was returned by
484 * ce_match_stat_basic() to signal that the filesize of the
485 * blob changed. We have to actually go to the filesystem to
486 * see if the contents match, and if so, should answer "unchanged".
488 * The logic does not apply to gitlinks, as ce_match_stat_basic()
489 * already has checked the actual HEAD from the filesystem in the
490 * subproject. If ie_match_stat() already said it is different,
491 * then we know it is.
493 if ((changed & DATA_CHANGED) &&
494 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
495 return changed;
497 changed_fs = ce_modified_check_fs(istate, ce, st);
498 if (changed_fs)
499 return changed | changed_fs;
500 return 0;
503 static int cache_name_stage_compare(const char *name1, int len1, int stage1,
504 const char *name2, int len2, int stage2)
506 int cmp;
508 cmp = name_compare(name1, len1, name2, len2);
509 if (cmp)
510 return cmp;
512 if (stage1 < stage2)
513 return -1;
514 if (stage1 > stage2)
515 return 1;
516 return 0;
519 int cmp_cache_name_compare(const void *a_, const void *b_)
521 const struct cache_entry *ce1, *ce2;
523 ce1 = *((const struct cache_entry **)a_);
524 ce2 = *((const struct cache_entry **)b_);
525 return cache_name_stage_compare(ce1->name, ce1->ce_namelen, ce_stage(ce1),
526 ce2->name, ce2->ce_namelen, ce_stage(ce2));
529 static int index_name_stage_pos(struct index_state *istate,
530 const char *name, int namelen,
531 int stage,
532 enum index_search_mode search_mode)
534 int first, last;
536 first = 0;
537 last = istate->cache_nr;
538 while (last > first) {
539 int next = first + ((last - first) >> 1);
540 struct cache_entry *ce = istate->cache[next];
541 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
542 if (!cmp)
543 return next;
544 if (cmp < 0) {
545 last = next;
546 continue;
548 first = next+1;
551 if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
552 first > 0) {
553 /* Note: first <= istate->cache_nr */
554 struct cache_entry *ce = istate->cache[first - 1];
557 * If we are in a sparse-index _and_ the entry before the
558 * insertion position is a sparse-directory entry that is
559 * an ancestor of 'name', then we need to expand the index
560 * and search again. This will only trigger once, because
561 * thereafter the index is fully expanded.
563 if (S_ISSPARSEDIR(ce->ce_mode) &&
564 ce_namelen(ce) < namelen &&
565 !strncmp(name, ce->name, ce_namelen(ce))) {
566 ensure_full_index(istate);
567 return index_name_stage_pos(istate, name, namelen, stage, search_mode);
571 return -first-1;
574 int index_name_pos(struct index_state *istate, const char *name, int namelen)
576 return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
579 int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
581 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
584 int index_entry_exists(struct index_state *istate, const char *name, int namelen)
586 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
589 int remove_index_entry_at(struct index_state *istate, int pos)
591 struct cache_entry *ce = istate->cache[pos];
593 record_resolve_undo(istate, ce);
594 remove_name_hash(istate, ce);
595 save_or_free_index_entry(istate, ce);
596 istate->cache_changed |= CE_ENTRY_REMOVED;
597 istate->cache_nr--;
598 if (pos >= istate->cache_nr)
599 return 0;
600 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
601 istate->cache_nr - pos);
602 return 1;
606 * Remove all cache entries marked for removal, that is where
607 * CE_REMOVE is set in ce_flags. This is much more effective than
608 * calling remove_index_entry_at() for each entry to be removed.
610 void remove_marked_cache_entries(struct index_state *istate, int invalidate)
612 struct cache_entry **ce_array = istate->cache;
613 unsigned int i, j;
615 for (i = j = 0; i < istate->cache_nr; i++) {
616 if (ce_array[i]->ce_flags & CE_REMOVE) {
617 if (invalidate) {
618 cache_tree_invalidate_path(istate,
619 ce_array[i]->name);
620 untracked_cache_remove_from_index(istate,
621 ce_array[i]->name);
623 remove_name_hash(istate, ce_array[i]);
624 save_or_free_index_entry(istate, ce_array[i]);
626 else
627 ce_array[j++] = ce_array[i];
629 if (j == istate->cache_nr)
630 return;
631 istate->cache_changed |= CE_ENTRY_REMOVED;
632 istate->cache_nr = j;
635 int remove_file_from_index(struct index_state *istate, const char *path)
637 int pos = index_name_pos(istate, path, strlen(path));
638 if (pos < 0)
639 pos = -pos-1;
640 cache_tree_invalidate_path(istate, path);
641 untracked_cache_remove_from_index(istate, path);
642 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
643 remove_index_entry_at(istate, pos);
644 return 0;
647 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
649 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
652 static int index_name_pos_also_unmerged(struct index_state *istate,
653 const char *path, int namelen)
655 int pos = index_name_pos(istate, path, namelen);
656 struct cache_entry *ce;
658 if (pos >= 0)
659 return pos;
661 /* maybe unmerged? */
662 pos = -1 - pos;
663 if (pos >= istate->cache_nr ||
664 compare_name((ce = istate->cache[pos]), path, namelen))
665 return -1;
667 /* order of preference: stage 2, 1, 3 */
668 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
669 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
670 !compare_name(ce, path, namelen))
671 pos++;
672 return pos;
675 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
677 int len = ce_namelen(ce);
678 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
682 * If we add a filename that aliases in the cache, we will use the
683 * name that we already have - but we don't want to update the same
684 * alias twice, because that implies that there were actually two
685 * different files with aliasing names!
687 * So we use the CE_ADDED flag to verify that the alias was an old
688 * one before we accept it as
690 static struct cache_entry *create_alias_ce(struct index_state *istate,
691 struct cache_entry *ce,
692 struct cache_entry *alias)
694 int len;
695 struct cache_entry *new_entry;
697 if (alias->ce_flags & CE_ADDED)
698 die(_("will not add file alias '%s' ('%s' already exists in index)"),
699 ce->name, alias->name);
701 /* Ok, create the new entry using the name of the existing alias */
702 len = ce_namelen(alias);
703 new_entry = make_empty_cache_entry(istate, len);
704 memcpy(new_entry->name, alias->name, len);
705 copy_cache_entry(new_entry, ce);
706 save_or_free_index_entry(istate, ce);
707 return new_entry;
710 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
712 struct object_id oid;
713 if (write_object_file("", 0, OBJ_BLOB, &oid))
714 die(_("cannot create an empty blob in the object database"));
715 oidcpy(&ce->oid, &oid);
718 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
720 int namelen, was_same;
721 mode_t st_mode = st->st_mode;
722 struct cache_entry *ce, *alias = NULL;
723 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
724 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
725 int pretend = flags & ADD_CACHE_PRETEND;
726 int intent_only = flags & ADD_CACHE_INTENT;
727 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
728 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
729 unsigned hash_flags = pretend ? 0 : HASH_WRITE_OBJECT;
730 struct object_id oid;
732 if (flags & ADD_CACHE_RENORMALIZE)
733 hash_flags |= HASH_RENORMALIZE;
735 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
736 return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
738 namelen = strlen(path);
739 if (S_ISDIR(st_mode)) {
740 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
741 return error(_("'%s' does not have a commit checked out"), path);
742 while (namelen && path[namelen-1] == '/')
743 namelen--;
745 ce = make_empty_cache_entry(istate, namelen);
746 memcpy(ce->name, path, namelen);
747 ce->ce_namelen = namelen;
748 if (!intent_only)
749 fill_stat_cache_info(istate, ce, st);
750 else
751 ce->ce_flags |= CE_INTENT_TO_ADD;
754 if (trust_executable_bit && has_symlinks) {
755 ce->ce_mode = create_ce_mode(st_mode);
756 } else {
757 /* If there is an existing entry, pick the mode bits and type
758 * from it, otherwise assume unexecutable regular file.
760 struct cache_entry *ent;
761 int pos = index_name_pos_also_unmerged(istate, path, namelen);
763 ent = (0 <= pos) ? istate->cache[pos] : NULL;
764 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
767 /* When core.ignorecase=true, determine if a directory of the same name but differing
768 * case already exists within the Git repository. If it does, ensure the directory
769 * case of the file being added to the repository matches (is folded into) the existing
770 * entry's directory case.
772 if (ignore_case) {
773 adjust_dirname_case(istate, ce->name);
775 if (!(flags & ADD_CACHE_RENORMALIZE)) {
776 alias = index_file_exists(istate, ce->name,
777 ce_namelen(ce), ignore_case);
778 if (alias &&
779 !ce_stage(alias) &&
780 !ie_match_stat(istate, alias, st, ce_option)) {
781 /* Nothing changed, really */
782 if (!S_ISGITLINK(alias->ce_mode))
783 ce_mark_uptodate(alias);
784 alias->ce_flags |= CE_ADDED;
786 discard_cache_entry(ce);
787 return 0;
790 if (!intent_only) {
791 if (index_path(istate, &ce->oid, path, st, hash_flags)) {
792 discard_cache_entry(ce);
793 return error(_("unable to index file '%s'"), path);
795 } else
796 set_object_name_for_intent_to_add_entry(ce);
798 if (ignore_case && alias && different_name(ce, alias))
799 ce = create_alias_ce(istate, ce, alias);
800 ce->ce_flags |= CE_ADDED;
802 /* It was suspected to be racily clean, but it turns out to be Ok */
803 was_same = (alias &&
804 !ce_stage(alias) &&
805 oideq(&alias->oid, &ce->oid) &&
806 ce->ce_mode == alias->ce_mode);
808 if (pretend)
809 discard_cache_entry(ce);
810 else if (add_index_entry(istate, ce, add_option)) {
811 discard_cache_entry(ce);
812 return error(_("unable to add '%s' to index"), path);
814 if (verbose && !was_same)
815 printf("add '%s'\n", path);
816 return 0;
819 int add_file_to_index(struct index_state *istate, const char *path, int flags)
821 struct stat st;
822 if (lstat(path, &st))
823 die_errno(_("unable to stat '%s'"), path);
824 return add_to_index(istate, path, &st, flags);
827 struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
829 return mem_pool__ce_calloc(find_mem_pool(istate), len);
832 struct cache_entry *make_empty_transient_cache_entry(size_t len,
833 struct mem_pool *ce_mem_pool)
835 if (ce_mem_pool)
836 return mem_pool__ce_calloc(ce_mem_pool, len);
837 return xcalloc(1, cache_entry_size(len));
840 enum verify_path_result {
841 PATH_OK,
842 PATH_INVALID,
843 PATH_DIR_WITH_SEP,
846 static enum verify_path_result verify_path_internal(const char *, unsigned);
848 int verify_path(const char *path, unsigned mode)
850 return verify_path_internal(path, mode) == PATH_OK;
853 struct cache_entry *make_cache_entry(struct index_state *istate,
854 unsigned int mode,
855 const struct object_id *oid,
856 const char *path,
857 int stage,
858 unsigned int refresh_options)
860 struct cache_entry *ce, *ret;
861 int len;
863 if (verify_path_internal(path, mode) == PATH_INVALID) {
864 error(_("invalid path '%s'"), path);
865 return NULL;
868 len = strlen(path);
869 ce = make_empty_cache_entry(istate, len);
871 oidcpy(&ce->oid, oid);
872 memcpy(ce->name, path, len);
873 ce->ce_flags = create_ce_flags(stage);
874 ce->ce_namelen = len;
875 ce->ce_mode = create_ce_mode(mode);
877 ret = refresh_cache_entry(istate, ce, refresh_options);
878 if (ret != ce)
879 discard_cache_entry(ce);
880 return ret;
883 struct cache_entry *make_transient_cache_entry(unsigned int mode,
884 const struct object_id *oid,
885 const char *path,
886 int stage,
887 struct mem_pool *ce_mem_pool)
889 struct cache_entry *ce;
890 int len;
892 if (!verify_path(path, mode)) {
893 error(_("invalid path '%s'"), path);
894 return NULL;
897 len = strlen(path);
898 ce = make_empty_transient_cache_entry(len, ce_mem_pool);
900 oidcpy(&ce->oid, oid);
901 memcpy(ce->name, path, len);
902 ce->ce_flags = create_ce_flags(stage);
903 ce->ce_namelen = len;
904 ce->ce_mode = create_ce_mode(mode);
906 return ce;
910 * Chmod an index entry with either +x or -x.
912 * Returns -1 if the chmod for the particular cache entry failed (if it's
913 * not a regular file), -2 if an invalid flip argument is passed in, 0
914 * otherwise.
916 int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
917 char flip)
919 if (!S_ISREG(ce->ce_mode))
920 return -1;
921 switch (flip) {
922 case '+':
923 ce->ce_mode |= 0111;
924 break;
925 case '-':
926 ce->ce_mode &= ~0111;
927 break;
928 default:
929 return -2;
931 cache_tree_invalidate_path(istate, ce->name);
932 ce->ce_flags |= CE_UPDATE_IN_BASE;
933 mark_fsmonitor_invalid(istate, ce);
934 istate->cache_changed |= CE_ENTRY_CHANGED;
936 return 0;
939 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
941 int len = ce_namelen(a);
942 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
946 * We fundamentally don't like some paths: we don't want
947 * dot or dot-dot anywhere, and for obvious reasons don't
948 * want to recurse into ".git" either.
950 * Also, we don't want double slashes or slashes at the
951 * end that can make pathnames ambiguous.
953 static int verify_dotfile(const char *rest, unsigned mode)
956 * The first character was '.', but that
957 * has already been discarded, we now test
958 * the rest.
961 /* "." is not allowed */
962 if (*rest == '\0' || is_dir_sep(*rest))
963 return 0;
965 switch (*rest) {
967 * ".git" followed by NUL or slash is bad. Note that we match
968 * case-insensitively here, even if ignore_case is not set.
969 * This outlaws ".GIT" everywhere out of an abundance of caution,
970 * since there's really no good reason to allow it.
972 * Once we've seen ".git", we can also find ".gitmodules", etc (also
973 * case-insensitively).
975 case 'g':
976 case 'G':
977 if (rest[1] != 'i' && rest[1] != 'I')
978 break;
979 if (rest[2] != 't' && rest[2] != 'T')
980 break;
981 if (rest[3] == '\0' || is_dir_sep(rest[3]))
982 return 0;
983 if (S_ISLNK(mode)) {
984 rest += 3;
985 if (skip_iprefix(rest, "modules", &rest) &&
986 (*rest == '\0' || is_dir_sep(*rest)))
987 return 0;
989 break;
990 case '.':
991 if (rest[1] == '\0' || is_dir_sep(rest[1]))
992 return 0;
994 return 1;
997 static enum verify_path_result verify_path_internal(const char *path,
998 unsigned mode)
1000 char c = 0;
1002 if (has_dos_drive_prefix(path))
1003 return PATH_INVALID;
1005 if (!is_valid_path(path))
1006 return PATH_INVALID;
1008 goto inside;
1009 for (;;) {
1010 if (!c)
1011 return PATH_OK;
1012 if (is_dir_sep(c)) {
1013 inside:
1014 if (protect_hfs) {
1016 if (is_hfs_dotgit(path))
1017 return PATH_INVALID;
1018 if (S_ISLNK(mode)) {
1019 if (is_hfs_dotgitmodules(path))
1020 return PATH_INVALID;
1023 if (protect_ntfs) {
1024 #if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
1025 if (c == '\\')
1026 return PATH_INVALID;
1027 #endif
1028 if (is_ntfs_dotgit(path))
1029 return PATH_INVALID;
1030 if (S_ISLNK(mode)) {
1031 if (is_ntfs_dotgitmodules(path))
1032 return PATH_INVALID;
1036 c = *path++;
1037 if ((c == '.' && !verify_dotfile(path, mode)) ||
1038 is_dir_sep(c))
1039 return PATH_INVALID;
1041 * allow terminating directory separators for
1042 * sparse directory entries.
1044 if (c == '\0')
1045 return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
1046 PATH_INVALID;
1047 } else if (c == '\\' && protect_ntfs) {
1048 if (is_ntfs_dotgit(path))
1049 return PATH_INVALID;
1050 if (S_ISLNK(mode)) {
1051 if (is_ntfs_dotgitmodules(path))
1052 return PATH_INVALID;
1056 c = *path++;
1061 * Do we have another file that has the beginning components being a
1062 * proper superset of the name we're trying to add?
1064 static int has_file_name(struct index_state *istate,
1065 const struct cache_entry *ce, int pos, int ok_to_replace)
1067 int retval = 0;
1068 int len = ce_namelen(ce);
1069 int stage = ce_stage(ce);
1070 const char *name = ce->name;
1072 while (pos < istate->cache_nr) {
1073 struct cache_entry *p = istate->cache[pos++];
1075 if (len >= ce_namelen(p))
1076 break;
1077 if (memcmp(name, p->name, len))
1078 break;
1079 if (ce_stage(p) != stage)
1080 continue;
1081 if (p->name[len] != '/')
1082 continue;
1083 if (p->ce_flags & CE_REMOVE)
1084 continue;
1085 retval = -1;
1086 if (!ok_to_replace)
1087 break;
1088 remove_index_entry_at(istate, --pos);
1090 return retval;
1095 * Like strcmp(), but also return the offset of the first change.
1096 * If strings are equal, return the length.
1098 int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1100 size_t k;
1102 if (!first_change)
1103 return strcmp(s1, s2);
1105 for (k = 0; s1[k] == s2[k]; k++)
1106 if (s1[k] == '\0')
1107 break;
1109 *first_change = k;
1110 return (unsigned char)s1[k] - (unsigned char)s2[k];
1114 * Do we have another file with a pathname that is a proper
1115 * subset of the name we're trying to add?
1117 * That is, is there another file in the index with a path
1118 * that matches a sub-directory in the given entry?
1120 static int has_dir_name(struct index_state *istate,
1121 const struct cache_entry *ce, int pos, int ok_to_replace)
1123 int retval = 0;
1124 int stage = ce_stage(ce);
1125 const char *name = ce->name;
1126 const char *slash = name + ce_namelen(ce);
1127 size_t len_eq_last;
1128 int cmp_last = 0;
1131 * We are frequently called during an iteration on a sorted
1132 * list of pathnames and while building a new index. Therefore,
1133 * there is a high probability that this entry will eventually
1134 * be appended to the index, rather than inserted in the middle.
1135 * If we can confirm that, we can avoid binary searches on the
1136 * components of the pathname.
1138 * Compare the entry's full path with the last path in the index.
1140 if (istate->cache_nr > 0) {
1141 cmp_last = strcmp_offset(name,
1142 istate->cache[istate->cache_nr - 1]->name,
1143 &len_eq_last);
1144 if (cmp_last > 0) {
1145 if (len_eq_last == 0) {
1147 * The entry sorts AFTER the last one in the
1148 * index and their paths have no common prefix,
1149 * so there cannot be a F/D conflict.
1151 return retval;
1152 } else {
1154 * The entry sorts AFTER the last one in the
1155 * index, but has a common prefix. Fall through
1156 * to the loop below to disect the entry's path
1157 * and see where the difference is.
1160 } else if (cmp_last == 0) {
1162 * The entry exactly matches the last one in the
1163 * index, but because of multiple stage and CE_REMOVE
1164 * items, we fall through and let the regular search
1165 * code handle it.
1170 for (;;) {
1171 size_t len;
1173 for (;;) {
1174 if (*--slash == '/')
1175 break;
1176 if (slash <= ce->name)
1177 return retval;
1179 len = slash - name;
1181 if (cmp_last > 0) {
1183 * (len + 1) is a directory boundary (including
1184 * the trailing slash). And since the loop is
1185 * decrementing "slash", the first iteration is
1186 * the longest directory prefix; subsequent
1187 * iterations consider parent directories.
1190 if (len + 1 <= len_eq_last) {
1192 * The directory prefix (including the trailing
1193 * slash) also appears as a prefix in the last
1194 * entry, so the remainder cannot collide (because
1195 * strcmp said the whole path was greater).
1197 * EQ: last: xxx/A
1198 * this: xxx/B
1200 * LT: last: xxx/file_A
1201 * this: xxx/file_B
1203 return retval;
1206 if (len > len_eq_last) {
1208 * This part of the directory prefix (excluding
1209 * the trailing slash) is longer than the known
1210 * equal portions, so this sub-directory cannot
1211 * collide with a file.
1213 * GT: last: xxxA
1214 * this: xxxB/file
1216 return retval;
1220 * This is a possible collision. Fall through and
1221 * let the regular search code handle it.
1223 * last: xxx
1224 * this: xxx/file
1228 pos = index_name_stage_pos(istate, name, len, stage, EXPAND_SPARSE);
1229 if (pos >= 0) {
1231 * Found one, but not so fast. This could
1232 * be a marker that says "I was here, but
1233 * I am being removed". Such an entry is
1234 * not a part of the resulting tree, and
1235 * it is Ok to have a directory at the same
1236 * path.
1238 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1239 retval = -1;
1240 if (!ok_to_replace)
1241 break;
1242 remove_index_entry_at(istate, pos);
1243 continue;
1246 else
1247 pos = -pos-1;
1250 * Trivial optimization: if we find an entry that
1251 * already matches the sub-directory, then we know
1252 * we're ok, and we can exit.
1254 while (pos < istate->cache_nr) {
1255 struct cache_entry *p = istate->cache[pos];
1256 if ((ce_namelen(p) <= len) ||
1257 (p->name[len] != '/') ||
1258 memcmp(p->name, name, len))
1259 break; /* not our subdirectory */
1260 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1262 * p is at the same stage as our entry, and
1263 * is a subdirectory of what we are looking
1264 * at, so we cannot have conflicts at our
1265 * level or anything shorter.
1267 return retval;
1268 pos++;
1271 return retval;
1274 /* We may be in a situation where we already have path/file and path
1275 * is being added, or we already have path and path/file is being
1276 * added. Either one would result in a nonsense tree that has path
1277 * twice when git-write-tree tries to write it out. Prevent it.
1279 * If ok-to-replace is specified, we remove the conflicting entries
1280 * from the cache so the caller should recompute the insert position.
1281 * When this happens, we return non-zero.
1283 static int check_file_directory_conflict(struct index_state *istate,
1284 const struct cache_entry *ce,
1285 int pos, int ok_to_replace)
1287 int retval;
1290 * When ce is an "I am going away" entry, we allow it to be added
1292 if (ce->ce_flags & CE_REMOVE)
1293 return 0;
1296 * We check if the path is a sub-path of a subsequent pathname
1297 * first, since removing those will not change the position
1298 * in the array.
1300 retval = has_file_name(istate, ce, pos, ok_to_replace);
1303 * Then check if the path might have a clashing sub-directory
1304 * before it.
1306 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1309 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1311 int pos;
1312 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1313 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1314 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1315 int new_only = option & ADD_CACHE_NEW_ONLY;
1318 * If this entry's path sorts after the last entry in the index,
1319 * we can avoid searching for it.
1321 if (istate->cache_nr > 0 &&
1322 strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1323 pos = index_pos_to_insert_pos(istate->cache_nr);
1324 else
1325 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1328 * Cache tree path should be invalidated only after index_name_stage_pos,
1329 * in case it expands a sparse index.
1331 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1332 cache_tree_invalidate_path(istate, ce->name);
1334 /* existing match? Just replace it. */
1335 if (pos >= 0) {
1336 if (!new_only)
1337 replace_index_entry(istate, pos, ce);
1338 return 0;
1340 pos = -pos-1;
1342 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1343 untracked_cache_add_to_index(istate, ce->name);
1346 * Inserting a merged entry ("stage 0") into the index
1347 * will always replace all non-merged entries..
1349 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1350 while (ce_same_name(istate->cache[pos], ce)) {
1351 ok_to_add = 1;
1352 if (!remove_index_entry_at(istate, pos))
1353 break;
1357 if (!ok_to_add)
1358 return -1;
1359 if (verify_path_internal(ce->name, ce->ce_mode) == PATH_INVALID)
1360 return error(_("invalid path '%s'"), ce->name);
1362 if (!skip_df_check &&
1363 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1364 if (!ok_to_replace)
1365 return error(_("'%s' appears as both a file and as a directory"),
1366 ce->name);
1367 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1368 pos = -pos-1;
1370 return pos + 1;
1373 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1375 int pos;
1377 if (option & ADD_CACHE_JUST_APPEND)
1378 pos = istate->cache_nr;
1379 else {
1380 int ret;
1381 ret = add_index_entry_with_check(istate, ce, option);
1382 if (ret <= 0)
1383 return ret;
1384 pos = ret - 1;
1387 /* Make sure the array is big enough .. */
1388 ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1390 /* Add it in.. */
1391 istate->cache_nr++;
1392 if (istate->cache_nr > pos + 1)
1393 MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1394 istate->cache_nr - pos - 1);
1395 set_index_entry(istate, pos, ce);
1396 istate->cache_changed |= CE_ENTRY_ADDED;
1397 return 0;
1401 * "refresh" does not calculate a new sha1 file or bring the
1402 * cache up-to-date for mode/content changes. But what it
1403 * _does_ do is to "re-match" the stat information of a file
1404 * with the cache, so that you can refresh the cache for a
1405 * file that hasn't been changed but where the stat entry is
1406 * out of date.
1408 * For example, you'd want to do this after doing a "git-read-tree",
1409 * to link up the stat cache details with the proper files.
1411 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1412 struct cache_entry *ce,
1413 unsigned int options, int *err,
1414 int *changed_ret,
1415 int *t2_did_lstat,
1416 int *t2_did_scan)
1418 struct stat st;
1419 struct cache_entry *updated;
1420 int changed;
1421 int refresh = options & CE_MATCH_REFRESH;
1422 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1423 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1424 int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1425 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
1427 if (!refresh || ce_uptodate(ce))
1428 return ce;
1430 if (!ignore_fsmonitor)
1431 refresh_fsmonitor(istate);
1433 * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1434 * that the change to the work tree does not matter and told
1435 * us not to worry.
1437 if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1438 ce_mark_uptodate(ce);
1439 return ce;
1441 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1442 ce_mark_uptodate(ce);
1443 return ce;
1445 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1446 ce_mark_uptodate(ce);
1447 return ce;
1450 if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1451 if (ignore_missing)
1452 return ce;
1453 if (err)
1454 *err = ENOENT;
1455 return NULL;
1458 if (t2_did_lstat)
1459 *t2_did_lstat = 1;
1460 if (lstat(ce->name, &st) < 0) {
1461 if (ignore_missing && errno == ENOENT)
1462 return ce;
1463 if (err)
1464 *err = errno;
1465 return NULL;
1468 changed = ie_match_stat(istate, ce, &st, options);
1469 if (changed_ret)
1470 *changed_ret = changed;
1471 if (!changed) {
1473 * The path is unchanged. If we were told to ignore
1474 * valid bit, then we did the actual stat check and
1475 * found that the entry is unmodified. If the entry
1476 * is not marked VALID, this is the place to mark it
1477 * valid again, under "assume unchanged" mode.
1479 if (ignore_valid && assume_unchanged &&
1480 !(ce->ce_flags & CE_VALID))
1481 ; /* mark this one VALID again */
1482 else {
1484 * We do not mark the index itself "modified"
1485 * because CE_UPTODATE flag is in-core only;
1486 * we are not going to write this change out.
1488 if (!S_ISGITLINK(ce->ce_mode)) {
1489 ce_mark_uptodate(ce);
1490 mark_fsmonitor_valid(istate, ce);
1492 return ce;
1496 if (t2_did_scan)
1497 *t2_did_scan = 1;
1498 if (ie_modified(istate, ce, &st, options)) {
1499 if (err)
1500 *err = EINVAL;
1501 return NULL;
1504 updated = make_empty_cache_entry(istate, ce_namelen(ce));
1505 copy_cache_entry(updated, ce);
1506 memcpy(updated->name, ce->name, ce->ce_namelen + 1);
1507 fill_stat_cache_info(istate, updated, &st);
1509 * If ignore_valid is not set, we should leave CE_VALID bit
1510 * alone. Otherwise, paths marked with --no-assume-unchanged
1511 * (i.e. things to be edited) will reacquire CE_VALID bit
1512 * automatically, which is not really what we want.
1514 if (!ignore_valid && assume_unchanged &&
1515 !(ce->ce_flags & CE_VALID))
1516 updated->ce_flags &= ~CE_VALID;
1518 /* istate->cache_changed is updated in the caller */
1519 return updated;
1522 static void show_file(const char * fmt, const char * name, int in_porcelain,
1523 int * first, const char *header_msg)
1525 if (in_porcelain && *first && header_msg) {
1526 printf("%s\n", header_msg);
1527 *first = 0;
1529 printf(fmt, name);
1532 int repo_refresh_and_write_index(struct repository *repo,
1533 unsigned int refresh_flags,
1534 unsigned int write_flags,
1535 int gentle,
1536 const struct pathspec *pathspec,
1537 char *seen, const char *header_msg)
1539 struct lock_file lock_file = LOCK_INIT;
1540 int fd, ret = 0;
1542 fd = repo_hold_locked_index(repo, &lock_file, 0);
1543 if (!gentle && fd < 0)
1544 return -1;
1545 if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
1546 ret = 1;
1547 if (0 <= fd && write_locked_index(repo->index, &lock_file, COMMIT_LOCK | write_flags))
1548 ret = -1;
1549 return ret;
1553 int refresh_index(struct index_state *istate, unsigned int flags,
1554 const struct pathspec *pathspec,
1555 char *seen, const char *header_msg)
1557 int i;
1558 int has_errors = 0;
1559 int really = (flags & REFRESH_REALLY) != 0;
1560 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1561 int quiet = (flags & REFRESH_QUIET) != 0;
1562 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1563 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1564 int ignore_skip_worktree = (flags & REFRESH_IGNORE_SKIP_WORKTREE) != 0;
1565 int first = 1;
1566 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1567 unsigned int options = (CE_MATCH_REFRESH |
1568 (really ? CE_MATCH_IGNORE_VALID : 0) |
1569 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1570 const char *modified_fmt;
1571 const char *deleted_fmt;
1572 const char *typechange_fmt;
1573 const char *added_fmt;
1574 const char *unmerged_fmt;
1575 struct progress *progress = NULL;
1576 int t2_sum_lstat = 0;
1577 int t2_sum_scan = 0;
1579 if (flags & REFRESH_PROGRESS && isatty(2))
1580 progress = start_delayed_progress(_("Refresh index"),
1581 istate->cache_nr);
1583 trace_performance_enter();
1584 modified_fmt = in_porcelain ? "M\t%s\n" : "%s: needs update\n";
1585 deleted_fmt = in_porcelain ? "D\t%s\n" : "%s: needs update\n";
1586 typechange_fmt = in_porcelain ? "T\t%s\n" : "%s: needs update\n";
1587 added_fmt = in_porcelain ? "A\t%s\n" : "%s: needs update\n";
1588 unmerged_fmt = in_porcelain ? "U\t%s\n" : "%s: needs merge\n";
1590 * Use the multi-threaded preload_index() to refresh most of the
1591 * cache entries quickly then in the single threaded loop below,
1592 * we only have to do the special cases that are left.
1594 preload_index(istate, pathspec, 0);
1595 trace2_region_enter("index", "refresh", NULL);
1597 for (i = 0; i < istate->cache_nr; i++) {
1598 struct cache_entry *ce, *new_entry;
1599 int cache_errno = 0;
1600 int changed = 0;
1601 int filtered = 0;
1602 int t2_did_lstat = 0;
1603 int t2_did_scan = 0;
1605 ce = istate->cache[i];
1606 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1607 continue;
1608 if (ignore_skip_worktree && ce_skip_worktree(ce))
1609 continue;
1612 * If this entry is a sparse directory, then there isn't
1613 * any stat() information to update. Ignore the entry.
1615 if (S_ISSPARSEDIR(ce->ce_mode))
1616 continue;
1618 if (pathspec && !ce_path_match(istate, ce, pathspec, seen))
1619 filtered = 1;
1621 if (ce_stage(ce)) {
1622 while ((i < istate->cache_nr) &&
1623 ! strcmp(istate->cache[i]->name, ce->name))
1624 i++;
1625 i--;
1626 if (allow_unmerged)
1627 continue;
1628 if (!filtered)
1629 show_file(unmerged_fmt, ce->name, in_porcelain,
1630 &first, header_msg);
1631 has_errors = 1;
1632 continue;
1635 if (filtered)
1636 continue;
1638 new_entry = refresh_cache_ent(istate, ce, options,
1639 &cache_errno, &changed,
1640 &t2_did_lstat, &t2_did_scan);
1641 t2_sum_lstat += t2_did_lstat;
1642 t2_sum_scan += t2_did_scan;
1643 if (new_entry == ce)
1644 continue;
1645 display_progress(progress, i);
1646 if (!new_entry) {
1647 const char *fmt;
1649 if (really && cache_errno == EINVAL) {
1650 /* If we are doing --really-refresh that
1651 * means the index is not valid anymore.
1653 ce->ce_flags &= ~CE_VALID;
1654 ce->ce_flags |= CE_UPDATE_IN_BASE;
1655 mark_fsmonitor_invalid(istate, ce);
1656 istate->cache_changed |= CE_ENTRY_CHANGED;
1658 if (quiet)
1659 continue;
1661 if (cache_errno == ENOENT)
1662 fmt = deleted_fmt;
1663 else if (ce_intent_to_add(ce))
1664 fmt = added_fmt; /* must be before other checks */
1665 else if (changed & TYPE_CHANGED)
1666 fmt = typechange_fmt;
1667 else
1668 fmt = modified_fmt;
1669 show_file(fmt,
1670 ce->name, in_porcelain, &first, header_msg);
1671 has_errors = 1;
1672 continue;
1675 replace_index_entry(istate, i, new_entry);
1677 trace2_data_intmax("index", NULL, "refresh/sum_lstat", t2_sum_lstat);
1678 trace2_data_intmax("index", NULL, "refresh/sum_scan", t2_sum_scan);
1679 trace2_region_leave("index", "refresh", NULL);
1680 display_progress(progress, istate->cache_nr);
1681 stop_progress(&progress);
1682 trace_performance_leave("refresh index");
1683 return has_errors;
1686 struct cache_entry *refresh_cache_entry(struct index_state *istate,
1687 struct cache_entry *ce,
1688 unsigned int options)
1690 return refresh_cache_ent(istate, ce, options, NULL, NULL, NULL, NULL);
1694 /*****************************************************************
1695 * Index File I/O
1696 *****************************************************************/
1698 #define INDEX_FORMAT_DEFAULT 3
1700 static unsigned int get_index_format_default(struct repository *r)
1702 char *envversion = getenv("GIT_INDEX_VERSION");
1703 char *endp;
1704 unsigned int version = INDEX_FORMAT_DEFAULT;
1706 if (!envversion) {
1707 prepare_repo_settings(r);
1709 if (r->settings.index_version >= 0)
1710 version = r->settings.index_version;
1711 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1712 warning(_("index.version set, but the value is invalid.\n"
1713 "Using version %i"), INDEX_FORMAT_DEFAULT);
1714 return INDEX_FORMAT_DEFAULT;
1716 return version;
1719 version = strtoul(envversion, &endp, 10);
1720 if (*endp ||
1721 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1722 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1723 "Using version %i"), INDEX_FORMAT_DEFAULT);
1724 version = INDEX_FORMAT_DEFAULT;
1726 return version;
1730 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1731 * Again - this is just a (very strong in practice) heuristic that
1732 * the inode hasn't changed.
1734 * We save the fields in big-endian order to allow using the
1735 * index file over NFS transparently.
1737 struct ondisk_cache_entry {
1738 struct cache_time ctime;
1739 struct cache_time mtime;
1740 uint32_t dev;
1741 uint32_t ino;
1742 uint32_t mode;
1743 uint32_t uid;
1744 uint32_t gid;
1745 uint32_t size;
1747 * unsigned char hash[hashsz];
1748 * uint16_t flags;
1749 * if (flags & CE_EXTENDED)
1750 * uint16_t flags2;
1752 unsigned char data[GIT_MAX_RAWSZ + 2 * sizeof(uint16_t)];
1753 char name[FLEX_ARRAY];
1756 /* These are only used for v3 or lower */
1757 #define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1758 #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,data) + (len) + 8) & ~7)
1759 #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1760 #define ondisk_data_size(flags, len) (the_hash_algo->rawsz + \
1761 ((flags & CE_EXTENDED) ? 2 : 1) * sizeof(uint16_t) + len)
1762 #define ondisk_data_size_max(len) (ondisk_data_size(CE_EXTENDED, len))
1763 #define ondisk_ce_size(ce) (ondisk_cache_entry_size(ondisk_data_size((ce)->ce_flags, ce_namelen(ce))))
1765 /* Allow fsck to force verification of the index checksum. */
1766 int verify_index_checksum;
1768 /* Allow fsck to force verification of the cache entry order. */
1769 int verify_ce_order;
1771 static int verify_hdr(const struct cache_header *hdr, unsigned long size)
1773 git_hash_ctx c;
1774 unsigned char hash[GIT_MAX_RAWSZ];
1775 int hdr_version;
1776 unsigned char *start, *end;
1777 struct object_id oid;
1779 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1780 return error(_("bad signature 0x%08x"), hdr->hdr_signature);
1781 hdr_version = ntohl(hdr->hdr_version);
1782 if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1783 return error(_("bad index version %d"), hdr_version);
1785 if (!verify_index_checksum)
1786 return 0;
1788 end = (unsigned char *)hdr + size;
1789 start = end - the_hash_algo->rawsz;
1790 oidread(&oid, start);
1791 if (oideq(&oid, null_oid()))
1792 return 0;
1794 the_hash_algo->init_fn(&c);
1795 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1796 the_hash_algo->final_fn(hash, &c);
1797 if (!hasheq(hash, start))
1798 return error(_("bad index file sha1 signature"));
1799 return 0;
1802 static int read_index_extension(struct index_state *istate,
1803 const char *ext, const char *data, unsigned long sz)
1805 switch (CACHE_EXT(ext)) {
1806 case CACHE_EXT_TREE:
1807 istate->cache_tree = cache_tree_read(data, sz);
1808 break;
1809 case CACHE_EXT_RESOLVE_UNDO:
1810 istate->resolve_undo = resolve_undo_read(data, sz);
1811 break;
1812 case CACHE_EXT_LINK:
1813 if (read_link_extension(istate, data, sz))
1814 return -1;
1815 break;
1816 case CACHE_EXT_UNTRACKED:
1817 istate->untracked = read_untracked_extension(data, sz);
1818 break;
1819 case CACHE_EXT_FSMONITOR:
1820 read_fsmonitor_extension(istate, data, sz);
1821 break;
1822 case CACHE_EXT_ENDOFINDEXENTRIES:
1823 case CACHE_EXT_INDEXENTRYOFFSETTABLE:
1824 /* already handled in do_read_index() */
1825 break;
1826 case CACHE_EXT_SPARSE_DIRECTORIES:
1827 /* no content, only an indicator */
1828 istate->sparse_index = INDEX_COLLAPSED;
1829 break;
1830 default:
1831 if (*ext < 'A' || 'Z' < *ext)
1832 return error(_("index uses %.4s extension, which we do not understand"),
1833 ext);
1834 fprintf_ln(stderr, _("ignoring %.4s extension"), ext);
1835 break;
1837 return 0;
1841 * Parses the contents of the cache entry contained within the 'ondisk' buffer
1842 * into a new incore 'cache_entry'.
1844 * Note that 'char *ondisk' may not be aligned to a 4-byte address interval in
1845 * index v4, so we cannot cast it to 'struct ondisk_cache_entry *' and access
1846 * its members. Instead, we use the byte offsets of members within the struct to
1847 * identify where 'get_be16()', 'get_be32()', and 'oidread()' (which can all
1848 * read from an unaligned memory buffer) should read from the 'ondisk' buffer
1849 * into the corresponding incore 'cache_entry' members.
1851 static struct cache_entry *create_from_disk(struct mem_pool *ce_mem_pool,
1852 unsigned int version,
1853 const char *ondisk,
1854 unsigned long *ent_size,
1855 const struct cache_entry *previous_ce)
1857 struct cache_entry *ce;
1858 size_t len;
1859 const char *name;
1860 const unsigned hashsz = the_hash_algo->rawsz;
1861 const char *flagsp = ondisk + offsetof(struct ondisk_cache_entry, data) + hashsz;
1862 unsigned int flags;
1863 size_t copy_len = 0;
1865 * Adjacent cache entries tend to share the leading paths, so it makes
1866 * sense to only store the differences in later entries. In the v4
1867 * on-disk format of the index, each on-disk cache entry stores the
1868 * number of bytes to be stripped from the end of the previous name,
1869 * and the bytes to append to the result, to come up with its name.
1871 int expand_name_field = version == 4;
1873 /* On-disk flags are just 16 bits */
1874 flags = get_be16(flagsp);
1875 len = flags & CE_NAMEMASK;
1877 if (flags & CE_EXTENDED) {
1878 int extended_flags;
1879 extended_flags = get_be16(flagsp + sizeof(uint16_t)) << 16;
1880 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1881 if (extended_flags & ~CE_EXTENDED_FLAGS)
1882 die(_("unknown index entry format 0x%08x"), extended_flags);
1883 flags |= extended_flags;
1884 name = (const char *)(flagsp + 2 * sizeof(uint16_t));
1886 else
1887 name = (const char *)(flagsp + sizeof(uint16_t));
1889 if (expand_name_field) {
1890 const unsigned char *cp = (const unsigned char *)name;
1891 size_t strip_len, previous_len;
1893 /* If we're at the beginning of a block, ignore the previous name */
1894 strip_len = decode_varint(&cp);
1895 if (previous_ce) {
1896 previous_len = previous_ce->ce_namelen;
1897 if (previous_len < strip_len)
1898 die(_("malformed name field in the index, near path '%s'"),
1899 previous_ce->name);
1900 copy_len = previous_len - strip_len;
1902 name = (const char *)cp;
1905 if (len == CE_NAMEMASK) {
1906 len = strlen(name);
1907 if (expand_name_field)
1908 len += copy_len;
1911 ce = mem_pool__ce_alloc(ce_mem_pool, len);
1914 * NEEDSWORK: using 'offsetof()' is cumbersome and should be replaced
1915 * with something more akin to 'load_bitmap_entries_v1()'s use of
1916 * 'read_be16'/'read_be32'. For consistency with the corresponding
1917 * ondisk entry write function ('copy_cache_entry_to_ondisk()'), this
1918 * should be done at the same time as removing references to
1919 * 'ondisk_cache_entry' there.
1921 ce->ce_stat_data.sd_ctime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1922 + offsetof(struct cache_time, sec));
1923 ce->ce_stat_data.sd_mtime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1924 + offsetof(struct cache_time, sec));
1925 ce->ce_stat_data.sd_ctime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1926 + offsetof(struct cache_time, nsec));
1927 ce->ce_stat_data.sd_mtime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1928 + offsetof(struct cache_time, nsec));
1929 ce->ce_stat_data.sd_dev = get_be32(ondisk + offsetof(struct ondisk_cache_entry, dev));
1930 ce->ce_stat_data.sd_ino = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ino));
1931 ce->ce_mode = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mode));
1932 ce->ce_stat_data.sd_uid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, uid));
1933 ce->ce_stat_data.sd_gid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, gid));
1934 ce->ce_stat_data.sd_size = get_be32(ondisk + offsetof(struct ondisk_cache_entry, size));
1935 ce->ce_flags = flags & ~CE_NAMEMASK;
1936 ce->ce_namelen = len;
1937 ce->index = 0;
1938 oidread(&ce->oid, (const unsigned char *)ondisk + offsetof(struct ondisk_cache_entry, data));
1940 if (expand_name_field) {
1941 if (copy_len)
1942 memcpy(ce->name, previous_ce->name, copy_len);
1943 memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1944 *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
1945 } else {
1946 memcpy(ce->name, name, len + 1);
1947 *ent_size = ondisk_ce_size(ce);
1949 return ce;
1952 static void check_ce_order(struct index_state *istate)
1954 unsigned int i;
1956 if (!verify_ce_order)
1957 return;
1959 for (i = 1; i < istate->cache_nr; i++) {
1960 struct cache_entry *ce = istate->cache[i - 1];
1961 struct cache_entry *next_ce = istate->cache[i];
1962 int name_compare = strcmp(ce->name, next_ce->name);
1964 if (0 < name_compare)
1965 die(_("unordered stage entries in index"));
1966 if (!name_compare) {
1967 if (!ce_stage(ce))
1968 die(_("multiple stage entries for merged file '%s'"),
1969 ce->name);
1970 if (ce_stage(ce) > ce_stage(next_ce))
1971 die(_("unordered stage entries for '%s'"),
1972 ce->name);
1977 static void tweak_untracked_cache(struct index_state *istate)
1979 struct repository *r = the_repository;
1981 prepare_repo_settings(r);
1983 switch (r->settings.core_untracked_cache) {
1984 case UNTRACKED_CACHE_REMOVE:
1985 remove_untracked_cache(istate);
1986 break;
1987 case UNTRACKED_CACHE_WRITE:
1988 add_untracked_cache(istate);
1989 break;
1990 case UNTRACKED_CACHE_KEEP:
1992 * Either an explicit "core.untrackedCache=keep", the
1993 * default if "core.untrackedCache" isn't configured,
1994 * or a fallback on an unknown "core.untrackedCache"
1995 * value.
1997 break;
2001 static void tweak_split_index(struct index_state *istate)
2003 switch (git_config_get_split_index()) {
2004 case -1: /* unset: do nothing */
2005 break;
2006 case 0: /* false */
2007 remove_split_index(istate);
2008 break;
2009 case 1: /* true */
2010 add_split_index(istate);
2011 break;
2012 default: /* unknown value: do nothing */
2013 break;
2017 static void post_read_index_from(struct index_state *istate)
2019 check_ce_order(istate);
2020 tweak_untracked_cache(istate);
2021 tweak_split_index(istate);
2022 tweak_fsmonitor(istate);
2025 static size_t estimate_cache_size_from_compressed(unsigned int entries)
2027 return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
2030 static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
2032 long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
2035 * Account for potential alignment differences.
2037 per_entry += align_padding_size(per_entry, 0);
2038 return ondisk_size + entries * per_entry;
2041 struct index_entry_offset
2043 /* starting byte offset into index file, count of index entries in this block */
2044 int offset, nr;
2047 struct index_entry_offset_table
2049 int nr;
2050 struct index_entry_offset entries[FLEX_ARRAY];
2053 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset);
2054 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot);
2056 static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
2057 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset);
2059 struct load_index_extensions
2061 pthread_t pthread;
2062 struct index_state *istate;
2063 const char *mmap;
2064 size_t mmap_size;
2065 unsigned long src_offset;
2068 static void *load_index_extensions(void *_data)
2070 struct load_index_extensions *p = _data;
2071 unsigned long src_offset = p->src_offset;
2073 while (src_offset <= p->mmap_size - the_hash_algo->rawsz - 8) {
2074 /* After an array of active_nr index entries,
2075 * there can be arbitrary number of extended
2076 * sections, each of which is prefixed with
2077 * extension name (4-byte) and section length
2078 * in 4-byte network byte order.
2080 uint32_t extsize = get_be32(p->mmap + src_offset + 4);
2081 if (read_index_extension(p->istate,
2082 p->mmap + src_offset,
2083 p->mmap + src_offset + 8,
2084 extsize) < 0) {
2085 munmap((void *)p->mmap, p->mmap_size);
2086 die(_("index file corrupt"));
2088 src_offset += 8;
2089 src_offset += extsize;
2092 return NULL;
2096 * A helper function that will load the specified range of cache entries
2097 * from the memory mapped file and add them to the given index.
2099 static unsigned long load_cache_entry_block(struct index_state *istate,
2100 struct mem_pool *ce_mem_pool, int offset, int nr, const char *mmap,
2101 unsigned long start_offset, const struct cache_entry *previous_ce)
2103 int i;
2104 unsigned long src_offset = start_offset;
2106 for (i = offset; i < offset + nr; i++) {
2107 struct cache_entry *ce;
2108 unsigned long consumed;
2110 ce = create_from_disk(ce_mem_pool, istate->version,
2111 mmap + src_offset,
2112 &consumed, previous_ce);
2113 set_index_entry(istate, i, ce);
2115 src_offset += consumed;
2116 previous_ce = ce;
2118 return src_offset - start_offset;
2121 static unsigned long load_all_cache_entries(struct index_state *istate,
2122 const char *mmap, size_t mmap_size, unsigned long src_offset)
2124 unsigned long consumed;
2126 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2127 if (istate->version == 4) {
2128 mem_pool_init(istate->ce_mem_pool,
2129 estimate_cache_size_from_compressed(istate->cache_nr));
2130 } else {
2131 mem_pool_init(istate->ce_mem_pool,
2132 estimate_cache_size(mmap_size, istate->cache_nr));
2135 consumed = load_cache_entry_block(istate, istate->ce_mem_pool,
2136 0, istate->cache_nr, mmap, src_offset, NULL);
2137 return consumed;
2141 * Mostly randomly chosen maximum thread counts: we
2142 * cap the parallelism to online_cpus() threads, and we want
2143 * to have at least 10000 cache entries per thread for it to
2144 * be worth starting a thread.
2147 #define THREAD_COST (10000)
2149 struct load_cache_entries_thread_data
2151 pthread_t pthread;
2152 struct index_state *istate;
2153 struct mem_pool *ce_mem_pool;
2154 int offset;
2155 const char *mmap;
2156 struct index_entry_offset_table *ieot;
2157 int ieot_start; /* starting index into the ieot array */
2158 int ieot_blocks; /* count of ieot entries to process */
2159 unsigned long consumed; /* return # of bytes in index file processed */
2163 * A thread proc to run the load_cache_entries() computation
2164 * across multiple background threads.
2166 static void *load_cache_entries_thread(void *_data)
2168 struct load_cache_entries_thread_data *p = _data;
2169 int i;
2171 /* iterate across all ieot blocks assigned to this thread */
2172 for (i = p->ieot_start; i < p->ieot_start + p->ieot_blocks; i++) {
2173 p->consumed += load_cache_entry_block(p->istate, p->ce_mem_pool,
2174 p->offset, p->ieot->entries[i].nr, p->mmap, p->ieot->entries[i].offset, NULL);
2175 p->offset += p->ieot->entries[i].nr;
2177 return NULL;
2180 static unsigned long load_cache_entries_threaded(struct index_state *istate, const char *mmap, size_t mmap_size,
2181 int nr_threads, struct index_entry_offset_table *ieot)
2183 int i, offset, ieot_blocks, ieot_start, err;
2184 struct load_cache_entries_thread_data *data;
2185 unsigned long consumed = 0;
2187 /* a little sanity checking */
2188 if (istate->name_hash_initialized)
2189 BUG("the name hash isn't thread safe");
2191 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2192 mem_pool_init(istate->ce_mem_pool, 0);
2194 /* ensure we have no more threads than we have blocks to process */
2195 if (nr_threads > ieot->nr)
2196 nr_threads = ieot->nr;
2197 CALLOC_ARRAY(data, nr_threads);
2199 offset = ieot_start = 0;
2200 ieot_blocks = DIV_ROUND_UP(ieot->nr, nr_threads);
2201 for (i = 0; i < nr_threads; i++) {
2202 struct load_cache_entries_thread_data *p = &data[i];
2203 int nr, j;
2205 if (ieot_start + ieot_blocks > ieot->nr)
2206 ieot_blocks = ieot->nr - ieot_start;
2208 p->istate = istate;
2209 p->offset = offset;
2210 p->mmap = mmap;
2211 p->ieot = ieot;
2212 p->ieot_start = ieot_start;
2213 p->ieot_blocks = ieot_blocks;
2215 /* create a mem_pool for each thread */
2216 nr = 0;
2217 for (j = p->ieot_start; j < p->ieot_start + p->ieot_blocks; j++)
2218 nr += p->ieot->entries[j].nr;
2219 p->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2220 if (istate->version == 4) {
2221 mem_pool_init(p->ce_mem_pool,
2222 estimate_cache_size_from_compressed(nr));
2223 } else {
2224 mem_pool_init(p->ce_mem_pool,
2225 estimate_cache_size(mmap_size, nr));
2228 err = pthread_create(&p->pthread, NULL, load_cache_entries_thread, p);
2229 if (err)
2230 die(_("unable to create load_cache_entries thread: %s"), strerror(err));
2232 /* increment by the number of cache entries in the ieot block being processed */
2233 for (j = 0; j < ieot_blocks; j++)
2234 offset += ieot->entries[ieot_start + j].nr;
2235 ieot_start += ieot_blocks;
2238 for (i = 0; i < nr_threads; i++) {
2239 struct load_cache_entries_thread_data *p = &data[i];
2241 err = pthread_join(p->pthread, NULL);
2242 if (err)
2243 die(_("unable to join load_cache_entries thread: %s"), strerror(err));
2244 mem_pool_combine(istate->ce_mem_pool, p->ce_mem_pool);
2245 consumed += p->consumed;
2248 free(data);
2250 return consumed;
2253 static void set_new_index_sparsity(struct index_state *istate)
2256 * If the index's repo exists, mark it sparse according to
2257 * repo settings.
2259 prepare_repo_settings(istate->repo);
2260 if (!istate->repo->settings.command_requires_full_index &&
2261 is_sparse_index_allowed(istate, 0))
2262 istate->sparse_index = 1;
2265 /* remember to discard_cache() before reading a different cache! */
2266 int do_read_index(struct index_state *istate, const char *path, int must_exist)
2268 int fd;
2269 struct stat st;
2270 unsigned long src_offset;
2271 const struct cache_header *hdr;
2272 const char *mmap;
2273 size_t mmap_size;
2274 struct load_index_extensions p;
2275 size_t extension_offset = 0;
2276 int nr_threads, cpus;
2277 struct index_entry_offset_table *ieot = NULL;
2279 if (istate->initialized)
2280 return istate->cache_nr;
2282 istate->timestamp.sec = 0;
2283 istate->timestamp.nsec = 0;
2284 fd = open(path, O_RDONLY);
2285 if (fd < 0) {
2286 if (!must_exist && errno == ENOENT) {
2287 set_new_index_sparsity(istate);
2288 return 0;
2290 die_errno(_("%s: index file open failed"), path);
2293 if (fstat(fd, &st))
2294 die_errno(_("%s: cannot stat the open index"), path);
2296 mmap_size = xsize_t(st.st_size);
2297 if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2298 die(_("%s: index file smaller than expected"), path);
2300 mmap = xmmap_gently(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
2301 if (mmap == MAP_FAILED)
2302 die_errno(_("%s: unable to map index file%s"), path,
2303 mmap_os_err());
2304 close(fd);
2306 hdr = (const struct cache_header *)mmap;
2307 if (verify_hdr(hdr, mmap_size) < 0)
2308 goto unmap;
2310 oidread(&istate->oid, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
2311 istate->version = ntohl(hdr->hdr_version);
2312 istate->cache_nr = ntohl(hdr->hdr_entries);
2313 istate->cache_alloc = alloc_nr(istate->cache_nr);
2314 CALLOC_ARRAY(istate->cache, istate->cache_alloc);
2315 istate->initialized = 1;
2317 p.istate = istate;
2318 p.mmap = mmap;
2319 p.mmap_size = mmap_size;
2321 src_offset = sizeof(*hdr);
2323 if (git_config_get_index_threads(&nr_threads))
2324 nr_threads = 1;
2326 /* TODO: does creating more threads than cores help? */
2327 if (!nr_threads) {
2328 nr_threads = istate->cache_nr / THREAD_COST;
2329 cpus = online_cpus();
2330 if (nr_threads > cpus)
2331 nr_threads = cpus;
2334 if (!HAVE_THREADS)
2335 nr_threads = 1;
2337 if (nr_threads > 1) {
2338 extension_offset = read_eoie_extension(mmap, mmap_size);
2339 if (extension_offset) {
2340 int err;
2342 p.src_offset = extension_offset;
2343 err = pthread_create(&p.pthread, NULL, load_index_extensions, &p);
2344 if (err)
2345 die(_("unable to create load_index_extensions thread: %s"), strerror(err));
2347 nr_threads--;
2352 * Locate and read the index entry offset table so that we can use it
2353 * to multi-thread the reading of the cache entries.
2355 if (extension_offset && nr_threads > 1)
2356 ieot = read_ieot_extension(mmap, mmap_size, extension_offset);
2358 if (ieot) {
2359 src_offset += load_cache_entries_threaded(istate, mmap, mmap_size, nr_threads, ieot);
2360 free(ieot);
2361 } else {
2362 src_offset += load_all_cache_entries(istate, mmap, mmap_size, src_offset);
2365 istate->timestamp.sec = st.st_mtime;
2366 istate->timestamp.nsec = ST_MTIME_NSEC(st);
2368 /* if we created a thread, join it otherwise load the extensions on the primary thread */
2369 if (extension_offset) {
2370 int ret = pthread_join(p.pthread, NULL);
2371 if (ret)
2372 die(_("unable to join load_index_extensions thread: %s"), strerror(ret));
2373 } else {
2374 p.src_offset = src_offset;
2375 load_index_extensions(&p);
2377 munmap((void *)mmap, mmap_size);
2380 * TODO trace2: replace "the_repository" with the actual repo instance
2381 * that is associated with the given "istate".
2383 trace2_data_intmax("index", the_repository, "read/version",
2384 istate->version);
2385 trace2_data_intmax("index", the_repository, "read/cache_nr",
2386 istate->cache_nr);
2389 * If the command explicitly requires a full index, force it
2390 * to be full. Otherwise, correct the sparsity based on repository
2391 * settings and other properties of the index (if necessary).
2393 prepare_repo_settings(istate->repo);
2394 if (istate->repo->settings.command_requires_full_index)
2395 ensure_full_index(istate);
2396 else
2397 ensure_correct_sparsity(istate);
2399 return istate->cache_nr;
2401 unmap:
2402 munmap((void *)mmap, mmap_size);
2403 die(_("index file corrupt"));
2407 * Signal that the shared index is used by updating its mtime.
2409 * This way, shared index can be removed if they have not been used
2410 * for some time.
2412 static void freshen_shared_index(const char *shared_index, int warn)
2414 if (!check_and_freshen_file(shared_index, 1) && warn)
2415 warning(_("could not freshen shared index '%s'"), shared_index);
2418 int read_index_from(struct index_state *istate, const char *path,
2419 const char *gitdir)
2421 struct split_index *split_index;
2422 int ret;
2423 char *base_oid_hex;
2424 char *base_path;
2426 /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2427 if (istate->initialized)
2428 return istate->cache_nr;
2431 * TODO trace2: replace "the_repository" with the actual repo instance
2432 * that is associated with the given "istate".
2434 trace2_region_enter_printf("index", "do_read_index", the_repository,
2435 "%s", path);
2436 trace_performance_enter();
2437 ret = do_read_index(istate, path, 0);
2438 trace_performance_leave("read cache %s", path);
2439 trace2_region_leave_printf("index", "do_read_index", the_repository,
2440 "%s", path);
2442 split_index = istate->split_index;
2443 if (!split_index || is_null_oid(&split_index->base_oid)) {
2444 post_read_index_from(istate);
2445 return ret;
2448 trace_performance_enter();
2449 if (split_index->base)
2450 release_index(split_index->base);
2451 else
2452 ALLOC_ARRAY(split_index->base, 1);
2453 index_state_init(split_index->base, istate->repo);
2455 base_oid_hex = oid_to_hex(&split_index->base_oid);
2456 base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
2457 trace2_region_enter_printf("index", "shared/do_read_index",
2458 the_repository, "%s", base_path);
2459 ret = do_read_index(split_index->base, base_path, 0);
2460 trace2_region_leave_printf("index", "shared/do_read_index",
2461 the_repository, "%s", base_path);
2462 if (!ret) {
2463 char *path_copy = xstrdup(path);
2464 char *base_path2 = xstrfmt("%s/sharedindex.%s",
2465 dirname(path_copy), base_oid_hex);
2466 free(path_copy);
2467 trace2_region_enter_printf("index", "shared/do_read_index",
2468 the_repository, "%s", base_path2);
2469 ret = do_read_index(split_index->base, base_path2, 1);
2470 trace2_region_leave_printf("index", "shared/do_read_index",
2471 the_repository, "%s", base_path2);
2472 free(base_path2);
2474 if (!oideq(&split_index->base_oid, &split_index->base->oid))
2475 die(_("broken index, expect %s in %s, got %s"),
2476 base_oid_hex, base_path,
2477 oid_to_hex(&split_index->base->oid));
2479 freshen_shared_index(base_path, 0);
2480 merge_base_index(istate);
2481 post_read_index_from(istate);
2482 trace_performance_leave("read cache %s", base_path);
2483 free(base_path);
2484 return ret;
2487 int is_index_unborn(struct index_state *istate)
2489 return (!istate->cache_nr && !istate->timestamp.sec);
2492 void index_state_init(struct index_state *istate, struct repository *r)
2494 struct index_state blank = INDEX_STATE_INIT(r);
2495 memcpy(istate, &blank, sizeof(*istate));
2498 void release_index(struct index_state *istate)
2501 * Cache entries in istate->cache[] should have been allocated
2502 * from the memory pool associated with this index, or from an
2503 * associated split_index. There is no need to free individual
2504 * cache entries. validate_cache_entries can detect when this
2505 * assertion does not hold.
2507 validate_cache_entries(istate);
2509 resolve_undo_clear_index(istate);
2510 free_name_hash(istate);
2511 cache_tree_free(&(istate->cache_tree));
2512 free(istate->fsmonitor_last_update);
2513 free(istate->cache);
2514 discard_split_index(istate);
2515 free_untracked_cache(istate->untracked);
2517 if (istate->sparse_checkout_patterns) {
2518 clear_pattern_list(istate->sparse_checkout_patterns);
2519 FREE_AND_NULL(istate->sparse_checkout_patterns);
2522 if (istate->ce_mem_pool) {
2523 mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
2524 FREE_AND_NULL(istate->ce_mem_pool);
2528 void discard_index(struct index_state *istate)
2530 release_index(istate);
2531 index_state_init(istate, istate->repo);
2535 * Validate the cache entries of this index.
2536 * All cache entries associated with this index
2537 * should have been allocated by the memory pool
2538 * associated with this index, or by a referenced
2539 * split index.
2541 void validate_cache_entries(const struct index_state *istate)
2543 int i;
2545 if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2546 return;
2548 for (i = 0; i < istate->cache_nr; i++) {
2549 if (!istate) {
2550 BUG("cache entry is not allocated from expected memory pool");
2551 } else if (!istate->ce_mem_pool ||
2552 !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2553 if (!istate->split_index ||
2554 !istate->split_index->base ||
2555 !istate->split_index->base->ce_mem_pool ||
2556 !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2557 BUG("cache entry is not allocated from expected memory pool");
2562 if (istate->split_index)
2563 validate_cache_entries(istate->split_index->base);
2566 int unmerged_index(const struct index_state *istate)
2568 int i;
2569 for (i = 0; i < istate->cache_nr; i++) {
2570 if (ce_stage(istate->cache[i]))
2571 return 1;
2573 return 0;
2576 int repo_index_has_changes(struct repository *repo,
2577 struct tree *tree,
2578 struct strbuf *sb)
2580 struct index_state *istate = repo->index;
2581 struct object_id cmp;
2582 int i;
2584 if (tree)
2585 cmp = tree->object.oid;
2586 if (tree || !repo_get_oid_tree(repo, "HEAD", &cmp)) {
2587 struct diff_options opt;
2589 repo_diff_setup(repo, &opt);
2590 opt.flags.exit_with_status = 1;
2591 if (!sb)
2592 opt.flags.quick = 1;
2593 diff_setup_done(&opt);
2594 do_diff_cache(&cmp, &opt);
2595 diffcore_std(&opt);
2596 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2597 if (i)
2598 strbuf_addch(sb, ' ');
2599 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2601 diff_flush(&opt);
2602 return opt.flags.has_changes != 0;
2603 } else {
2604 /* TODO: audit for interaction with sparse-index. */
2605 ensure_full_index(istate);
2606 for (i = 0; sb && i < istate->cache_nr; i++) {
2607 if (i)
2608 strbuf_addch(sb, ' ');
2609 strbuf_addstr(sb, istate->cache[i]->name);
2611 return !!istate->cache_nr;
2615 static int write_index_ext_header(struct hashfile *f,
2616 git_hash_ctx *eoie_f,
2617 unsigned int ext,
2618 unsigned int sz)
2620 hashwrite_be32(f, ext);
2621 hashwrite_be32(f, sz);
2623 if (eoie_f) {
2624 ext = htonl(ext);
2625 sz = htonl(sz);
2626 the_hash_algo->update_fn(eoie_f, &ext, sizeof(ext));
2627 the_hash_algo->update_fn(eoie_f, &sz, sizeof(sz));
2629 return 0;
2632 static void ce_smudge_racily_clean_entry(struct index_state *istate,
2633 struct cache_entry *ce)
2636 * The only thing we care about in this function is to smudge the
2637 * falsely clean entry due to touch-update-touch race, so we leave
2638 * everything else as they are. We are called for entries whose
2639 * ce_stat_data.sd_mtime match the index file mtime.
2641 * Note that this actually does not do much for gitlinks, for
2642 * which ce_match_stat_basic() always goes to the actual
2643 * contents. The caller checks with is_racy_timestamp() which
2644 * always says "no" for gitlinks, so we are not called for them ;-)
2646 struct stat st;
2648 if (lstat(ce->name, &st) < 0)
2649 return;
2650 if (ce_match_stat_basic(ce, &st))
2651 return;
2652 if (ce_modified_check_fs(istate, ce, &st)) {
2653 /* This is "racily clean"; smudge it. Note that this
2654 * is a tricky code. At first glance, it may appear
2655 * that it can break with this sequence:
2657 * $ echo xyzzy >frotz
2658 * $ git-update-index --add frotz
2659 * $ : >frotz
2660 * $ sleep 3
2661 * $ echo filfre >nitfol
2662 * $ git-update-index --add nitfol
2664 * but it does not. When the second update-index runs,
2665 * it notices that the entry "frotz" has the same timestamp
2666 * as index, and if we were to smudge it by resetting its
2667 * size to zero here, then the object name recorded
2668 * in index is the 6-byte file but the cached stat information
2669 * becomes zero --- which would then match what we would
2670 * obtain from the filesystem next time we stat("frotz").
2672 * However, the second update-index, before calling
2673 * this function, notices that the cached size is 6
2674 * bytes and what is on the filesystem is an empty
2675 * file, and never calls us, so the cached size information
2676 * for "frotz" stays 6 which does not match the filesystem.
2678 ce->ce_stat_data.sd_size = 0;
2682 /* Copy miscellaneous fields but not the name */
2683 static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2684 struct cache_entry *ce)
2686 short flags;
2687 const unsigned hashsz = the_hash_algo->rawsz;
2688 uint16_t *flagsp = (uint16_t *)(ondisk->data + hashsz);
2690 ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2691 ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2692 ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2693 ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2694 ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
2695 ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
2696 ondisk->mode = htonl(ce->ce_mode);
2697 ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
2698 ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
2699 ondisk->size = htonl(ce->ce_stat_data.sd_size);
2700 hashcpy(ondisk->data, ce->oid.hash);
2702 flags = ce->ce_flags & ~CE_NAMEMASK;
2703 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2704 flagsp[0] = htons(flags);
2705 if (ce->ce_flags & CE_EXTENDED) {
2706 flagsp[1] = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2710 static int ce_write_entry(struct hashfile *f, struct cache_entry *ce,
2711 struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2713 int size;
2714 unsigned int saved_namelen;
2715 int stripped_name = 0;
2716 static unsigned char padding[8] = { 0x00 };
2718 if (ce->ce_flags & CE_STRIP_NAME) {
2719 saved_namelen = ce_namelen(ce);
2720 ce->ce_namelen = 0;
2721 stripped_name = 1;
2724 size = offsetof(struct ondisk_cache_entry,data) + ondisk_data_size(ce->ce_flags, 0);
2726 if (!previous_name) {
2727 int len = ce_namelen(ce);
2728 copy_cache_entry_to_ondisk(ondisk, ce);
2729 hashwrite(f, ondisk, size);
2730 hashwrite(f, ce->name, len);
2731 hashwrite(f, padding, align_padding_size(size, len));
2732 } else {
2733 int common, to_remove, prefix_size;
2734 unsigned char to_remove_vi[16];
2735 for (common = 0;
2736 (ce->name[common] &&
2737 common < previous_name->len &&
2738 ce->name[common] == previous_name->buf[common]);
2739 common++)
2740 ; /* still matching */
2741 to_remove = previous_name->len - common;
2742 prefix_size = encode_varint(to_remove, to_remove_vi);
2744 copy_cache_entry_to_ondisk(ondisk, ce);
2745 hashwrite(f, ondisk, size);
2746 hashwrite(f, to_remove_vi, prefix_size);
2747 hashwrite(f, ce->name + common, ce_namelen(ce) - common);
2748 hashwrite(f, padding, 1);
2750 strbuf_splice(previous_name, common, to_remove,
2751 ce->name + common, ce_namelen(ce) - common);
2753 if (stripped_name) {
2754 ce->ce_namelen = saved_namelen;
2755 ce->ce_flags &= ~CE_STRIP_NAME;
2758 return 0;
2762 * This function verifies if index_state has the correct sha1 of the
2763 * index file. Don't die if we have any other failure, just return 0.
2765 static int verify_index_from(const struct index_state *istate, const char *path)
2767 int fd;
2768 ssize_t n;
2769 struct stat st;
2770 unsigned char hash[GIT_MAX_RAWSZ];
2772 if (!istate->initialized)
2773 return 0;
2775 fd = open(path, O_RDONLY);
2776 if (fd < 0)
2777 return 0;
2779 if (fstat(fd, &st))
2780 goto out;
2782 if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2783 goto out;
2785 n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2786 if (n != the_hash_algo->rawsz)
2787 goto out;
2789 if (!hasheq(istate->oid.hash, hash))
2790 goto out;
2792 close(fd);
2793 return 1;
2795 out:
2796 close(fd);
2797 return 0;
2800 static int repo_verify_index(struct repository *repo)
2802 return verify_index_from(repo->index, repo->index_file);
2805 int has_racy_timestamp(struct index_state *istate)
2807 int entries = istate->cache_nr;
2808 int i;
2810 for (i = 0; i < entries; i++) {
2811 struct cache_entry *ce = istate->cache[i];
2812 if (is_racy_timestamp(istate, ce))
2813 return 1;
2815 return 0;
2818 void repo_update_index_if_able(struct repository *repo,
2819 struct lock_file *lockfile)
2821 if ((repo->index->cache_changed ||
2822 has_racy_timestamp(repo->index)) &&
2823 repo_verify_index(repo))
2824 write_locked_index(repo->index, lockfile, COMMIT_LOCK);
2825 else
2826 rollback_lock_file(lockfile);
2829 static int record_eoie(void)
2831 int val;
2833 if (!git_config_get_bool("index.recordendofindexentries", &val))
2834 return val;
2837 * As a convenience, the end of index entries extension
2838 * used for threading is written by default if the user
2839 * explicitly requested threaded index reads.
2841 return !git_config_get_index_threads(&val) && val != 1;
2844 static int record_ieot(void)
2846 int val;
2848 if (!git_config_get_bool("index.recordoffsettable", &val))
2849 return val;
2852 * As a convenience, the offset table used for threading is
2853 * written by default if the user explicitly requested
2854 * threaded index reads.
2856 return !git_config_get_index_threads(&val) && val != 1;
2859 enum write_extensions {
2860 WRITE_NO_EXTENSION = 0,
2861 WRITE_SPLIT_INDEX_EXTENSION = 1<<0,
2862 WRITE_CACHE_TREE_EXTENSION = 1<<1,
2863 WRITE_RESOLVE_UNDO_EXTENSION = 1<<2,
2864 WRITE_UNTRACKED_CACHE_EXTENSION = 1<<3,
2865 WRITE_FSMONITOR_EXTENSION = 1<<4,
2867 #define WRITE_ALL_EXTENSIONS ((enum write_extensions)-1)
2870 * On success, `tempfile` is closed. If it is the temporary file
2871 * of a `struct lock_file`, we will therefore effectively perform
2872 * a 'close_lock_file_gently()`. Since that is an implementation
2873 * detail of lockfiles, callers of `do_write_index()` should not
2874 * rely on it.
2876 static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2877 enum write_extensions write_extensions, unsigned flags)
2879 uint64_t start = getnanotime();
2880 struct hashfile *f;
2881 git_hash_ctx *eoie_c = NULL;
2882 struct cache_header hdr;
2883 int i, err = 0, removed, extended, hdr_version;
2884 struct cache_entry **cache = istate->cache;
2885 int entries = istate->cache_nr;
2886 struct stat st;
2887 struct ondisk_cache_entry ondisk;
2888 struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2889 int drop_cache_tree = istate->drop_cache_tree;
2890 off_t offset;
2891 int csum_fsync_flag;
2892 int ieot_entries = 1;
2893 struct index_entry_offset_table *ieot = NULL;
2894 int nr, nr_threads;
2895 struct repository *r = istate->repo;
2897 f = hashfd(tempfile->fd, tempfile->filename.buf);
2899 prepare_repo_settings(r);
2900 f->skip_hash = r->settings.index_skip_hash;
2902 for (i = removed = extended = 0; i < entries; i++) {
2903 if (cache[i]->ce_flags & CE_REMOVE)
2904 removed++;
2906 /* reduce extended entries if possible */
2907 cache[i]->ce_flags &= ~CE_EXTENDED;
2908 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2909 extended++;
2910 cache[i]->ce_flags |= CE_EXTENDED;
2914 if (!istate->version)
2915 istate->version = get_index_format_default(r);
2917 /* demote version 3 to version 2 when the latter suffices */
2918 if (istate->version == 3 || istate->version == 2)
2919 istate->version = extended ? 3 : 2;
2921 hdr_version = istate->version;
2923 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2924 hdr.hdr_version = htonl(hdr_version);
2925 hdr.hdr_entries = htonl(entries - removed);
2927 hashwrite(f, &hdr, sizeof(hdr));
2929 if (!HAVE_THREADS || git_config_get_index_threads(&nr_threads))
2930 nr_threads = 1;
2932 if (nr_threads != 1 && record_ieot()) {
2933 int ieot_blocks, cpus;
2936 * ensure default number of ieot blocks maps evenly to the
2937 * default number of threads that will process them leaving
2938 * room for the thread to load the index extensions.
2940 if (!nr_threads) {
2941 ieot_blocks = istate->cache_nr / THREAD_COST;
2942 cpus = online_cpus();
2943 if (ieot_blocks > cpus - 1)
2944 ieot_blocks = cpus - 1;
2945 } else {
2946 ieot_blocks = nr_threads;
2947 if (ieot_blocks > istate->cache_nr)
2948 ieot_blocks = istate->cache_nr;
2952 * no reason to write out the IEOT extension if we don't
2953 * have enough blocks to utilize multi-threading
2955 if (ieot_blocks > 1) {
2956 ieot = xcalloc(1, sizeof(struct index_entry_offset_table)
2957 + (ieot_blocks * sizeof(struct index_entry_offset)));
2958 ieot_entries = DIV_ROUND_UP(entries, ieot_blocks);
2962 offset = hashfile_total(f);
2964 nr = 0;
2965 previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
2967 for (i = 0; i < entries; i++) {
2968 struct cache_entry *ce = cache[i];
2969 if (ce->ce_flags & CE_REMOVE)
2970 continue;
2971 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
2972 ce_smudge_racily_clean_entry(istate, ce);
2973 if (is_null_oid(&ce->oid)) {
2974 static const char msg[] = "cache entry has null sha1: %s";
2975 static int allow = -1;
2977 if (allow < 0)
2978 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
2979 if (allow)
2980 warning(msg, ce->name);
2981 else
2982 err = error(msg, ce->name);
2984 drop_cache_tree = 1;
2986 if (ieot && i && (i % ieot_entries == 0)) {
2987 ieot->entries[ieot->nr].nr = nr;
2988 ieot->entries[ieot->nr].offset = offset;
2989 ieot->nr++;
2991 * If we have a V4 index, set the first byte to an invalid
2992 * character to ensure there is nothing common with the previous
2993 * entry
2995 if (previous_name)
2996 previous_name->buf[0] = 0;
2997 nr = 0;
2999 offset = hashfile_total(f);
3001 if (ce_write_entry(f, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
3002 err = -1;
3004 if (err)
3005 break;
3006 nr++;
3008 if (ieot && nr) {
3009 ieot->entries[ieot->nr].nr = nr;
3010 ieot->entries[ieot->nr].offset = offset;
3011 ieot->nr++;
3013 strbuf_release(&previous_name_buf);
3015 if (err) {
3016 free(ieot);
3017 return err;
3020 offset = hashfile_total(f);
3023 * The extension headers must be hashed on their own for the
3024 * EOIE extension. Create a hashfile here to compute that hash.
3026 if (offset && record_eoie()) {
3027 CALLOC_ARRAY(eoie_c, 1);
3028 the_hash_algo->init_fn(eoie_c);
3032 * Lets write out CACHE_EXT_INDEXENTRYOFFSETTABLE first so that we
3033 * can minimize the number of extensions we have to scan through to
3034 * find it during load. Write it out regardless of the
3035 * strip_extensions parameter as we need it when loading the shared
3036 * index.
3038 if (ieot) {
3039 struct strbuf sb = STRBUF_INIT;
3041 write_ieot_extension(&sb, ieot);
3042 err = write_index_ext_header(f, eoie_c, CACHE_EXT_INDEXENTRYOFFSETTABLE, sb.len) < 0;
3043 hashwrite(f, sb.buf, sb.len);
3044 strbuf_release(&sb);
3045 free(ieot);
3046 if (err)
3047 return -1;
3050 if (write_extensions & WRITE_SPLIT_INDEX_EXTENSION &&
3051 istate->split_index) {
3052 struct strbuf sb = STRBUF_INIT;
3054 if (istate->sparse_index)
3055 die(_("cannot write split index for a sparse index"));
3057 err = write_link_extension(&sb, istate) < 0 ||
3058 write_index_ext_header(f, eoie_c, CACHE_EXT_LINK,
3059 sb.len) < 0;
3060 hashwrite(f, sb.buf, sb.len);
3061 strbuf_release(&sb);
3062 if (err)
3063 return -1;
3065 if (write_extensions & WRITE_CACHE_TREE_EXTENSION &&
3066 !drop_cache_tree && istate->cache_tree) {
3067 struct strbuf sb = STRBUF_INIT;
3069 cache_tree_write(&sb, istate->cache_tree);
3070 err = write_index_ext_header(f, eoie_c, CACHE_EXT_TREE, sb.len) < 0;
3071 hashwrite(f, sb.buf, sb.len);
3072 strbuf_release(&sb);
3073 if (err)
3074 return -1;
3076 if (write_extensions & WRITE_RESOLVE_UNDO_EXTENSION &&
3077 istate->resolve_undo) {
3078 struct strbuf sb = STRBUF_INIT;
3080 resolve_undo_write(&sb, istate->resolve_undo);
3081 err = write_index_ext_header(f, eoie_c, CACHE_EXT_RESOLVE_UNDO,
3082 sb.len) < 0;
3083 hashwrite(f, sb.buf, sb.len);
3084 strbuf_release(&sb);
3085 if (err)
3086 return -1;
3088 if (write_extensions & WRITE_UNTRACKED_CACHE_EXTENSION &&
3089 istate->untracked) {
3090 struct strbuf sb = STRBUF_INIT;
3092 write_untracked_extension(&sb, istate->untracked);
3093 err = write_index_ext_header(f, eoie_c, CACHE_EXT_UNTRACKED,
3094 sb.len) < 0;
3095 hashwrite(f, sb.buf, sb.len);
3096 strbuf_release(&sb);
3097 if (err)
3098 return -1;
3100 if (write_extensions & WRITE_FSMONITOR_EXTENSION &&
3101 istate->fsmonitor_last_update) {
3102 struct strbuf sb = STRBUF_INIT;
3104 write_fsmonitor_extension(&sb, istate);
3105 err = write_index_ext_header(f, eoie_c, CACHE_EXT_FSMONITOR, sb.len) < 0;
3106 hashwrite(f, sb.buf, sb.len);
3107 strbuf_release(&sb);
3108 if (err)
3109 return -1;
3111 if (istate->sparse_index) {
3112 if (write_index_ext_header(f, eoie_c, CACHE_EXT_SPARSE_DIRECTORIES, 0) < 0)
3113 return -1;
3117 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
3118 * so that it can be found and processed before all the index entries are
3119 * read. Write it out regardless of the strip_extensions parameter as we need it
3120 * when loading the shared index.
3122 if (eoie_c) {
3123 struct strbuf sb = STRBUF_INIT;
3125 write_eoie_extension(&sb, eoie_c, offset);
3126 err = write_index_ext_header(f, NULL, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0;
3127 hashwrite(f, sb.buf, sb.len);
3128 strbuf_release(&sb);
3129 if (err)
3130 return -1;
3133 csum_fsync_flag = 0;
3134 if (!alternate_index_output && (flags & COMMIT_LOCK))
3135 csum_fsync_flag = CSUM_FSYNC;
3137 finalize_hashfile(f, istate->oid.hash, FSYNC_COMPONENT_INDEX,
3138 CSUM_HASH_IN_STREAM | csum_fsync_flag);
3140 if (close_tempfile_gently(tempfile)) {
3141 error(_("could not close '%s'"), get_tempfile_path(tempfile));
3142 return -1;
3144 if (stat(get_tempfile_path(tempfile), &st))
3145 return -1;
3146 istate->timestamp.sec = (unsigned int)st.st_mtime;
3147 istate->timestamp.nsec = ST_MTIME_NSEC(st);
3148 trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
3151 * TODO trace2: replace "the_repository" with the actual repo instance
3152 * that is associated with the given "istate".
3154 trace2_data_intmax("index", the_repository, "write/version",
3155 istate->version);
3156 trace2_data_intmax("index", the_repository, "write/cache_nr",
3157 istate->cache_nr);
3159 return 0;
3162 void set_alternate_index_output(const char *name)
3164 alternate_index_output = name;
3167 static int commit_locked_index(struct lock_file *lk)
3169 if (alternate_index_output)
3170 return commit_lock_file_to(lk, alternate_index_output);
3171 else
3172 return commit_lock_file(lk);
3175 static int do_write_locked_index(struct index_state *istate,
3176 struct lock_file *lock,
3177 unsigned flags,
3178 enum write_extensions write_extensions)
3180 int ret;
3181 int was_full = istate->sparse_index == INDEX_EXPANDED;
3183 ret = convert_to_sparse(istate, 0);
3185 if (ret) {
3186 warning(_("failed to convert to a sparse-index"));
3187 return ret;
3191 * TODO trace2: replace "the_repository" with the actual repo instance
3192 * that is associated with the given "istate".
3194 trace2_region_enter_printf("index", "do_write_index", the_repository,
3195 "%s", get_lock_file_path(lock));
3196 ret = do_write_index(istate, lock->tempfile, write_extensions, flags);
3197 trace2_region_leave_printf("index", "do_write_index", the_repository,
3198 "%s", get_lock_file_path(lock));
3200 if (was_full)
3201 ensure_full_index(istate);
3203 if (ret)
3204 return ret;
3205 if (flags & COMMIT_LOCK)
3206 ret = commit_locked_index(lock);
3207 else
3208 ret = close_lock_file_gently(lock);
3210 run_hooks_l("post-index-change",
3211 istate->updated_workdir ? "1" : "0",
3212 istate->updated_skipworktree ? "1" : "0", NULL);
3213 istate->updated_workdir = 0;
3214 istate->updated_skipworktree = 0;
3216 return ret;
3219 static int write_split_index(struct index_state *istate,
3220 struct lock_file *lock,
3221 unsigned flags)
3223 int ret;
3224 prepare_to_write_split_index(istate);
3225 ret = do_write_locked_index(istate, lock, flags, WRITE_ALL_EXTENSIONS);
3226 finish_writing_split_index(istate);
3227 return ret;
3230 static const char *shared_index_expire = "2.weeks.ago";
3232 static unsigned long get_shared_index_expire_date(void)
3234 static unsigned long shared_index_expire_date;
3235 static int shared_index_expire_date_prepared;
3237 if (!shared_index_expire_date_prepared) {
3238 git_config_get_expiry("splitindex.sharedindexexpire",
3239 &shared_index_expire);
3240 shared_index_expire_date = approxidate(shared_index_expire);
3241 shared_index_expire_date_prepared = 1;
3244 return shared_index_expire_date;
3247 static int should_delete_shared_index(const char *shared_index_path)
3249 struct stat st;
3250 unsigned long expiration;
3252 /* Check timestamp */
3253 expiration = get_shared_index_expire_date();
3254 if (!expiration)
3255 return 0;
3256 if (stat(shared_index_path, &st))
3257 return error_errno(_("could not stat '%s'"), shared_index_path);
3258 if (st.st_mtime > expiration)
3259 return 0;
3261 return 1;
3264 static int clean_shared_index_files(const char *current_hex)
3266 struct dirent *de;
3267 DIR *dir = opendir(get_git_dir());
3269 if (!dir)
3270 return error_errno(_("unable to open git dir: %s"), get_git_dir());
3272 while ((de = readdir(dir)) != NULL) {
3273 const char *sha1_hex;
3274 const char *shared_index_path;
3275 if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
3276 continue;
3277 if (!strcmp(sha1_hex, current_hex))
3278 continue;
3279 shared_index_path = git_path("%s", de->d_name);
3280 if (should_delete_shared_index(shared_index_path) > 0 &&
3281 unlink(shared_index_path))
3282 warning_errno(_("unable to unlink: %s"), shared_index_path);
3284 closedir(dir);
3286 return 0;
3289 static int write_shared_index(struct index_state *istate,
3290 struct tempfile **temp, unsigned flags)
3292 struct split_index *si = istate->split_index;
3293 int ret, was_full = !istate->sparse_index;
3295 move_cache_to_base_index(istate);
3296 convert_to_sparse(istate, 0);
3298 trace2_region_enter_printf("index", "shared/do_write_index",
3299 the_repository, "%s", get_tempfile_path(*temp));
3300 ret = do_write_index(si->base, *temp, WRITE_NO_EXTENSION, flags);
3301 trace2_region_leave_printf("index", "shared/do_write_index",
3302 the_repository, "%s", get_tempfile_path(*temp));
3304 if (was_full)
3305 ensure_full_index(istate);
3307 if (ret)
3308 return ret;
3309 ret = adjust_shared_perm(get_tempfile_path(*temp));
3310 if (ret) {
3311 error(_("cannot fix permission bits on '%s'"), get_tempfile_path(*temp));
3312 return ret;
3314 ret = rename_tempfile(temp,
3315 git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
3316 if (!ret) {
3317 oidcpy(&si->base_oid, &si->base->oid);
3318 clean_shared_index_files(oid_to_hex(&si->base->oid));
3321 return ret;
3324 static const int default_max_percent_split_change = 20;
3326 static int too_many_not_shared_entries(struct index_state *istate)
3328 int i, not_shared = 0;
3329 int max_split = git_config_get_max_percent_split_change();
3331 switch (max_split) {
3332 case -1:
3333 /* not or badly configured: use the default value */
3334 max_split = default_max_percent_split_change;
3335 break;
3336 case 0:
3337 return 1; /* 0% means always write a new shared index */
3338 case 100:
3339 return 0; /* 100% means never write a new shared index */
3340 default:
3341 break; /* just use the configured value */
3344 /* Count not shared entries */
3345 for (i = 0; i < istate->cache_nr; i++) {
3346 struct cache_entry *ce = istate->cache[i];
3347 if (!ce->index)
3348 not_shared++;
3351 return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
3354 int write_locked_index(struct index_state *istate, struct lock_file *lock,
3355 unsigned flags)
3357 int new_shared_index, ret, test_split_index_env;
3358 struct split_index *si = istate->split_index;
3360 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
3361 cache_tree_verify(the_repository, istate);
3363 if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
3364 if (flags & COMMIT_LOCK)
3365 rollback_lock_file(lock);
3366 return 0;
3369 if (istate->fsmonitor_last_update)
3370 fill_fsmonitor_bitmap(istate);
3372 test_split_index_env = git_env_bool("GIT_TEST_SPLIT_INDEX", 0);
3374 if ((!si && !test_split_index_env) ||
3375 alternate_index_output ||
3376 (istate->cache_changed & ~EXTMASK)) {
3377 ret = do_write_locked_index(istate, lock, flags,
3378 ~WRITE_SPLIT_INDEX_EXTENSION);
3379 goto out;
3382 if (test_split_index_env) {
3383 if (!si) {
3384 si = init_split_index(istate);
3385 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3386 } else {
3387 int v = si->base_oid.hash[0];
3388 if ((v & 15) < 6)
3389 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3392 if (too_many_not_shared_entries(istate))
3393 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3395 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
3397 if (new_shared_index) {
3398 struct tempfile *temp;
3399 int saved_errno;
3401 /* Same initial permissions as the main .git/index file */
3402 temp = mks_tempfile_sm(git_path("sharedindex_XXXXXX"), 0, 0666);
3403 if (!temp) {
3404 ret = do_write_locked_index(istate, lock, flags,
3405 ~WRITE_SPLIT_INDEX_EXTENSION);
3406 goto out;
3408 ret = write_shared_index(istate, &temp, flags);
3410 saved_errno = errno;
3411 if (is_tempfile_active(temp))
3412 delete_tempfile(&temp);
3413 errno = saved_errno;
3415 if (ret)
3416 goto out;
3419 ret = write_split_index(istate, lock, flags);
3421 /* Freshen the shared index only if the split-index was written */
3422 if (!ret && !new_shared_index && !is_null_oid(&si->base_oid)) {
3423 const char *shared_index = git_path("sharedindex.%s",
3424 oid_to_hex(&si->base_oid));
3425 freshen_shared_index(shared_index, 1);
3428 out:
3429 if (flags & COMMIT_LOCK)
3430 rollback_lock_file(lock);
3431 return ret;
3435 * Read the index file that is potentially unmerged into given
3436 * index_state, dropping any unmerged entries to stage #0 (potentially
3437 * resulting in a path appearing as both a file and a directory in the
3438 * index; the caller is responsible to clear out the extra entries
3439 * before writing the index to a tree). Returns true if the index is
3440 * unmerged. Callers who want to refuse to work from an unmerged
3441 * state can call this and check its return value, instead of calling
3442 * read_cache().
3444 int repo_read_index_unmerged(struct repository *repo)
3446 struct index_state *istate;
3447 int i;
3448 int unmerged = 0;
3450 repo_read_index(repo);
3451 istate = repo->index;
3452 for (i = 0; i < istate->cache_nr; i++) {
3453 struct cache_entry *ce = istate->cache[i];
3454 struct cache_entry *new_ce;
3455 int len;
3457 if (!ce_stage(ce))
3458 continue;
3459 unmerged = 1;
3460 len = ce_namelen(ce);
3461 new_ce = make_empty_cache_entry(istate, len);
3462 memcpy(new_ce->name, ce->name, len);
3463 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3464 new_ce->ce_namelen = len;
3465 new_ce->ce_mode = ce->ce_mode;
3466 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3467 return error(_("%s: cannot drop to stage #0"),
3468 new_ce->name);
3470 return unmerged;
3474 * Returns 1 if the path is an "other" path with respect to
3475 * the index; that is, the path is not mentioned in the index at all,
3476 * either as a file, a directory with some files in the index,
3477 * or as an unmerged entry.
3479 * We helpfully remove a trailing "/" from directories so that
3480 * the output of read_directory can be used as-is.
3482 int index_name_is_other(struct index_state *istate, const char *name,
3483 int namelen)
3485 int pos;
3486 if (namelen && name[namelen - 1] == '/')
3487 namelen--;
3488 pos = index_name_pos(istate, name, namelen);
3489 if (0 <= pos)
3490 return 0; /* exact match */
3491 pos = -pos - 1;
3492 if (pos < istate->cache_nr) {
3493 struct cache_entry *ce = istate->cache[pos];
3494 if (ce_namelen(ce) == namelen &&
3495 !memcmp(ce->name, name, namelen))
3496 return 0; /* Yup, this one exists unmerged */
3498 return 1;
3501 void *read_blob_data_from_index(struct index_state *istate,
3502 const char *path, unsigned long *size)
3504 int pos, len;
3505 unsigned long sz;
3506 enum object_type type;
3507 void *data;
3509 len = strlen(path);
3510 pos = index_name_pos(istate, path, len);
3511 if (pos < 0) {
3513 * We might be in the middle of a merge, in which
3514 * case we would read stage #2 (ours).
3516 int i;
3517 for (i = -pos - 1;
3518 (pos < 0 && i < istate->cache_nr &&
3519 !strcmp(istate->cache[i]->name, path));
3520 i++)
3521 if (ce_stage(istate->cache[i]) == 2)
3522 pos = i;
3524 if (pos < 0)
3525 return NULL;
3526 data = repo_read_object_file(the_repository, &istate->cache[pos]->oid,
3527 &type, &sz);
3528 if (!data || type != OBJ_BLOB) {
3529 free(data);
3530 return NULL;
3532 if (size)
3533 *size = sz;
3534 return data;
3537 void stat_validity_clear(struct stat_validity *sv)
3539 FREE_AND_NULL(sv->sd);
3542 int stat_validity_check(struct stat_validity *sv, const char *path)
3544 struct stat st;
3546 if (stat(path, &st) < 0)
3547 return sv->sd == NULL;
3548 if (!sv->sd)
3549 return 0;
3550 return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
3553 void stat_validity_update(struct stat_validity *sv, int fd)
3555 struct stat st;
3557 if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
3558 stat_validity_clear(sv);
3559 else {
3560 if (!sv->sd)
3561 CALLOC_ARRAY(sv->sd, 1);
3562 fill_stat_data(sv->sd, &st);
3566 void move_index_extensions(struct index_state *dst, struct index_state *src)
3568 dst->untracked = src->untracked;
3569 src->untracked = NULL;
3570 dst->cache_tree = src->cache_tree;
3571 src->cache_tree = NULL;
3574 struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3575 struct index_state *istate)
3577 unsigned int size = ce_size(ce);
3578 int mem_pool_allocated;
3579 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3580 mem_pool_allocated = new_entry->mem_pool_allocated;
3582 memcpy(new_entry, ce, size);
3583 new_entry->mem_pool_allocated = mem_pool_allocated;
3584 return new_entry;
3587 void discard_cache_entry(struct cache_entry *ce)
3589 if (ce && should_validate_cache_entries())
3590 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3592 if (ce && ce->mem_pool_allocated)
3593 return;
3595 free(ce);
3598 int should_validate_cache_entries(void)
3600 static int validate_index_cache_entries = -1;
3602 if (validate_index_cache_entries < 0) {
3603 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3604 validate_index_cache_entries = 1;
3605 else
3606 validate_index_cache_entries = 0;
3609 return validate_index_cache_entries;
3612 #define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3613 #define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3615 static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3618 * The end of index entries (EOIE) extension is guaranteed to be last
3619 * so that it can be found by scanning backwards from the EOF.
3621 * "EOIE"
3622 * <4-byte length>
3623 * <4-byte offset>
3624 * <20-byte hash>
3626 const char *index, *eoie;
3627 uint32_t extsize;
3628 size_t offset, src_offset;
3629 unsigned char hash[GIT_MAX_RAWSZ];
3630 git_hash_ctx c;
3632 /* ensure we have an index big enough to contain an EOIE extension */
3633 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3634 return 0;
3636 /* validate the extension signature */
3637 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3638 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3639 return 0;
3640 index += sizeof(uint32_t);
3642 /* validate the extension size */
3643 extsize = get_be32(index);
3644 if (extsize != EOIE_SIZE)
3645 return 0;
3646 index += sizeof(uint32_t);
3649 * Validate the offset we're going to look for the first extension
3650 * signature is after the index header and before the eoie extension.
3652 offset = get_be32(index);
3653 if (mmap + offset < mmap + sizeof(struct cache_header))
3654 return 0;
3655 if (mmap + offset >= eoie)
3656 return 0;
3657 index += sizeof(uint32_t);
3660 * The hash is computed over extension types and their sizes (but not
3661 * their contents). E.g. if we have "TREE" extension that is N-bytes
3662 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3663 * then the hash would be:
3665 * SHA-1("TREE" + <binary representation of N> +
3666 * "REUC" + <binary representation of M>)
3668 src_offset = offset;
3669 the_hash_algo->init_fn(&c);
3670 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3671 /* After an array of active_nr index entries,
3672 * there can be arbitrary number of extended
3673 * sections, each of which is prefixed with
3674 * extension name (4-byte) and section length
3675 * in 4-byte network byte order.
3677 uint32_t extsize;
3678 memcpy(&extsize, mmap + src_offset + 4, 4);
3679 extsize = ntohl(extsize);
3681 /* verify the extension size isn't so large it will wrap around */
3682 if (src_offset + 8 + extsize < src_offset)
3683 return 0;
3685 the_hash_algo->update_fn(&c, mmap + src_offset, 8);
3687 src_offset += 8;
3688 src_offset += extsize;
3690 the_hash_algo->final_fn(hash, &c);
3691 if (!hasheq(hash, (const unsigned char *)index))
3692 return 0;
3694 /* Validate that the extension offsets returned us back to the eoie extension. */
3695 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3696 return 0;
3698 return offset;
3701 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset)
3703 uint32_t buffer;
3704 unsigned char hash[GIT_MAX_RAWSZ];
3706 /* offset */
3707 put_be32(&buffer, offset);
3708 strbuf_add(sb, &buffer, sizeof(uint32_t));
3710 /* hash */
3711 the_hash_algo->final_fn(hash, eoie_context);
3712 strbuf_add(sb, hash, the_hash_algo->rawsz);
3715 #define IEOT_VERSION (1)
3717 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3719 const char *index = NULL;
3720 uint32_t extsize, ext_version;
3721 struct index_entry_offset_table *ieot;
3722 int i, nr;
3724 /* find the IEOT extension */
3725 if (!offset)
3726 return NULL;
3727 while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3728 extsize = get_be32(mmap + offset + 4);
3729 if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3730 index = mmap + offset + 4 + 4;
3731 break;
3733 offset += 8;
3734 offset += extsize;
3736 if (!index)
3737 return NULL;
3739 /* validate the version is IEOT_VERSION */
3740 ext_version = get_be32(index);
3741 if (ext_version != IEOT_VERSION) {
3742 error("invalid IEOT version %d", ext_version);
3743 return NULL;
3745 index += sizeof(uint32_t);
3747 /* extension size - version bytes / bytes per entry */
3748 nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3749 if (!nr) {
3750 error("invalid number of IEOT entries %d", nr);
3751 return NULL;
3753 ieot = xmalloc(sizeof(struct index_entry_offset_table)
3754 + (nr * sizeof(struct index_entry_offset)));
3755 ieot->nr = nr;
3756 for (i = 0; i < nr; i++) {
3757 ieot->entries[i].offset = get_be32(index);
3758 index += sizeof(uint32_t);
3759 ieot->entries[i].nr = get_be32(index);
3760 index += sizeof(uint32_t);
3763 return ieot;
3766 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3768 uint32_t buffer;
3769 int i;
3771 /* version */
3772 put_be32(&buffer, IEOT_VERSION);
3773 strbuf_add(sb, &buffer, sizeof(uint32_t));
3775 /* ieot */
3776 for (i = 0; i < ieot->nr; i++) {
3778 /* offset */
3779 put_be32(&buffer, ieot->entries[i].offset);
3780 strbuf_add(sb, &buffer, sizeof(uint32_t));
3782 /* count */
3783 put_be32(&buffer, ieot->entries[i].nr);
3784 strbuf_add(sb, &buffer, sizeof(uint32_t));
3788 void prefetch_cache_entries(const struct index_state *istate,
3789 must_prefetch_predicate must_prefetch)
3791 int i;
3792 struct oid_array to_fetch = OID_ARRAY_INIT;
3794 for (i = 0; i < istate->cache_nr; i++) {
3795 struct cache_entry *ce = istate->cache[i];
3797 if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce))
3798 continue;
3799 if (!oid_object_info_extended(the_repository, &ce->oid,
3800 NULL,
3801 OBJECT_INFO_FOR_PREFETCH))
3802 continue;
3803 oid_array_append(&to_fetch, &ce->oid);
3805 promisor_remote_get_direct(the_repository,
3806 to_fetch.oid, to_fetch.nr);
3807 oid_array_clear(&to_fetch);