treewide: reduce includes of cache.h in other headers
[git.git] / read-cache.c
blobf225bf44cd0b5fd05cf74db20023f0161c9d1c89
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
6 #include "cache.h"
7 #include "alloc.h"
8 #include "config.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "hex.h"
12 #include "tempfile.h"
13 #include "lockfile.h"
14 #include "cache-tree.h"
15 #include "refs.h"
16 #include "dir.h"
17 #include "object-file.h"
18 #include "object-store.h"
19 #include "oid-array.h"
20 #include "tree.h"
21 #include "commit.h"
22 #include "blob.h"
23 #include "environment.h"
24 #include "gettext.h"
25 #include "mem-pool.h"
26 #include "object-name.h"
27 #include "resolve-undo.h"
28 #include "run-command.h"
29 #include "strbuf.h"
30 #include "trace2.h"
31 #include "varint.h"
32 #include "split-index.h"
33 #include "utf8.h"
34 #include "fsmonitor.h"
35 #include "thread-utils.h"
36 #include "progress.h"
37 #include "sparse-index.h"
38 #include "csum-file.h"
39 #include "promisor-remote.h"
40 #include "hook.h"
41 #include "wrapper.h"
43 /* Mask for the name length in ce_flags in the on-disk index */
45 #define CE_NAMEMASK (0x0fff)
47 /* Index extensions.
49 * The first letter should be 'A'..'Z' for extensions that are not
50 * necessary for a correct operation (i.e. optimization data).
51 * When new extensions are added that _needs_ to be understood in
52 * order to correctly interpret the index file, pick character that
53 * is outside the range, to cause the reader to abort.
56 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
57 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
58 #define CACHE_EXT_RESOLVE_UNDO 0x52455543 /* "REUC" */
59 #define CACHE_EXT_LINK 0x6c696e6b /* "link" */
60 #define CACHE_EXT_UNTRACKED 0x554E5452 /* "UNTR" */
61 #define CACHE_EXT_FSMONITOR 0x46534D4E /* "FSMN" */
62 #define CACHE_EXT_ENDOFINDEXENTRIES 0x454F4945 /* "EOIE" */
63 #define CACHE_EXT_INDEXENTRYOFFSETTABLE 0x49454F54 /* "IEOT" */
64 #define CACHE_EXT_SPARSE_DIRECTORIES 0x73646972 /* "sdir" */
66 /* changes that can be kept in $GIT_DIR/index (basically all extensions) */
67 #define EXTMASK (RESOLVE_UNDO_CHANGED | CACHE_TREE_CHANGED | \
68 CE_ENTRY_ADDED | CE_ENTRY_REMOVED | CE_ENTRY_CHANGED | \
69 SPLIT_INDEX_ORDERED | UNTRACKED_CHANGED | FSMONITOR_CHANGED)
73 * This is an estimate of the pathname length in the index. We use
74 * this for V4 index files to guess the un-deltafied size of the index
75 * in memory because of pathname deltafication. This is not required
76 * for V2/V3 index formats because their pathnames are not compressed.
77 * If the initial amount of memory set aside is not sufficient, the
78 * mem pool will allocate extra memory.
80 #define CACHE_ENTRY_PATH_LENGTH 80
82 enum index_search_mode {
83 NO_EXPAND_SPARSE = 0,
84 EXPAND_SPARSE = 1
87 static inline struct cache_entry *mem_pool__ce_alloc(struct mem_pool *mem_pool, size_t len)
89 struct cache_entry *ce;
90 ce = mem_pool_alloc(mem_pool, cache_entry_size(len));
91 ce->mem_pool_allocated = 1;
92 return ce;
95 static inline struct cache_entry *mem_pool__ce_calloc(struct mem_pool *mem_pool, size_t len)
97 struct cache_entry * ce;
98 ce = mem_pool_calloc(mem_pool, 1, cache_entry_size(len));
99 ce->mem_pool_allocated = 1;
100 return ce;
103 static struct mem_pool *find_mem_pool(struct index_state *istate)
105 struct mem_pool **pool_ptr;
107 if (istate->split_index && istate->split_index->base)
108 pool_ptr = &istate->split_index->base->ce_mem_pool;
109 else
110 pool_ptr = &istate->ce_mem_pool;
112 if (!*pool_ptr) {
113 *pool_ptr = xmalloc(sizeof(**pool_ptr));
114 mem_pool_init(*pool_ptr, 0);
117 return *pool_ptr;
120 static const char *alternate_index_output;
122 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
124 if (S_ISSPARSEDIR(ce->ce_mode))
125 istate->sparse_index = INDEX_COLLAPSED;
127 istate->cache[nr] = ce;
128 add_name_hash(istate, ce);
131 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
133 struct cache_entry *old = istate->cache[nr];
135 replace_index_entry_in_base(istate, old, ce);
136 remove_name_hash(istate, old);
137 discard_cache_entry(old);
138 ce->ce_flags &= ~CE_HASHED;
139 set_index_entry(istate, nr, ce);
140 ce->ce_flags |= CE_UPDATE_IN_BASE;
141 mark_fsmonitor_invalid(istate, ce);
142 istate->cache_changed |= CE_ENTRY_CHANGED;
145 void rename_index_entry_at(struct index_state *istate, int nr, const char *new_name)
147 struct cache_entry *old_entry = istate->cache[nr], *new_entry, *refreshed;
148 int namelen = strlen(new_name);
150 new_entry = make_empty_cache_entry(istate, namelen);
151 copy_cache_entry(new_entry, old_entry);
152 new_entry->ce_flags &= ~CE_HASHED;
153 new_entry->ce_namelen = namelen;
154 new_entry->index = 0;
155 memcpy(new_entry->name, new_name, namelen + 1);
157 cache_tree_invalidate_path(istate, old_entry->name);
158 untracked_cache_remove_from_index(istate, old_entry->name);
159 remove_index_entry_at(istate, nr);
162 * Refresh the new index entry. Using 'refresh_cache_entry' ensures
163 * we only update stat info if the entry is otherwise up-to-date (i.e.,
164 * the contents/mode haven't changed). This ensures that we reflect the
165 * 'ctime' of the rename in the index without (incorrectly) updating
166 * the cached stat info to reflect unstaged changes on disk.
168 refreshed = refresh_cache_entry(istate, new_entry, CE_MATCH_REFRESH);
169 if (refreshed && refreshed != new_entry) {
170 add_index_entry(istate, refreshed, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
171 discard_cache_entry(new_entry);
172 } else
173 add_index_entry(istate, new_entry, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
176 void fill_stat_data(struct stat_data *sd, struct stat *st)
178 sd->sd_ctime.sec = (unsigned int)st->st_ctime;
179 sd->sd_mtime.sec = (unsigned int)st->st_mtime;
180 sd->sd_ctime.nsec = ST_CTIME_NSEC(*st);
181 sd->sd_mtime.nsec = ST_MTIME_NSEC(*st);
182 sd->sd_dev = st->st_dev;
183 sd->sd_ino = st->st_ino;
184 sd->sd_uid = st->st_uid;
185 sd->sd_gid = st->st_gid;
186 sd->sd_size = st->st_size;
189 int match_stat_data(const struct stat_data *sd, struct stat *st)
191 int changed = 0;
193 if (sd->sd_mtime.sec != (unsigned int)st->st_mtime)
194 changed |= MTIME_CHANGED;
195 if (trust_ctime && check_stat &&
196 sd->sd_ctime.sec != (unsigned int)st->st_ctime)
197 changed |= CTIME_CHANGED;
199 #ifdef USE_NSEC
200 if (check_stat && sd->sd_mtime.nsec != ST_MTIME_NSEC(*st))
201 changed |= MTIME_CHANGED;
202 if (trust_ctime && check_stat &&
203 sd->sd_ctime.nsec != ST_CTIME_NSEC(*st))
204 changed |= CTIME_CHANGED;
205 #endif
207 if (check_stat) {
208 if (sd->sd_uid != (unsigned int) st->st_uid ||
209 sd->sd_gid != (unsigned int) st->st_gid)
210 changed |= OWNER_CHANGED;
211 if (sd->sd_ino != (unsigned int) st->st_ino)
212 changed |= INODE_CHANGED;
215 #ifdef USE_STDEV
217 * st_dev breaks on network filesystems where different
218 * clients will have different views of what "device"
219 * the filesystem is on
221 if (check_stat && sd->sd_dev != (unsigned int) st->st_dev)
222 changed |= INODE_CHANGED;
223 #endif
225 if (sd->sd_size != (unsigned int) st->st_size)
226 changed |= DATA_CHANGED;
228 return changed;
232 * This only updates the "non-critical" parts of the directory
233 * cache, ie the parts that aren't tracked by GIT, and only used
234 * to validate the cache.
236 void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st)
238 fill_stat_data(&ce->ce_stat_data, st);
240 if (assume_unchanged)
241 ce->ce_flags |= CE_VALID;
243 if (S_ISREG(st->st_mode)) {
244 ce_mark_uptodate(ce);
245 mark_fsmonitor_valid(istate, ce);
249 static int ce_compare_data(struct index_state *istate,
250 const struct cache_entry *ce,
251 struct stat *st)
253 int match = -1;
254 int fd = git_open_cloexec(ce->name, O_RDONLY);
256 if (fd >= 0) {
257 struct object_id oid;
258 if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
259 match = !oideq(&oid, &ce->oid);
260 /* index_fd() closed the file descriptor already */
262 return match;
265 static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
267 int match = -1;
268 void *buffer;
269 unsigned long size;
270 enum object_type type;
271 struct strbuf sb = STRBUF_INIT;
273 if (strbuf_readlink(&sb, ce->name, expected_size))
274 return -1;
276 buffer = repo_read_object_file(the_repository, &ce->oid, &type, &size);
277 if (buffer) {
278 if (size == sb.len)
279 match = memcmp(buffer, sb.buf, size);
280 free(buffer);
282 strbuf_release(&sb);
283 return match;
286 static int ce_compare_gitlink(const struct cache_entry *ce)
288 struct object_id oid;
291 * We don't actually require that the .git directory
292 * under GITLINK directory be a valid git directory. It
293 * might even be missing (in case nobody populated that
294 * sub-project).
296 * If so, we consider it always to match.
298 if (resolve_gitlink_ref(ce->name, "HEAD", &oid) < 0)
299 return 0;
300 return !oideq(&oid, &ce->oid);
303 static int ce_modified_check_fs(struct index_state *istate,
304 const struct cache_entry *ce,
305 struct stat *st)
307 switch (st->st_mode & S_IFMT) {
308 case S_IFREG:
309 if (ce_compare_data(istate, ce, st))
310 return DATA_CHANGED;
311 break;
312 case S_IFLNK:
313 if (ce_compare_link(ce, xsize_t(st->st_size)))
314 return DATA_CHANGED;
315 break;
316 case S_IFDIR:
317 if (S_ISGITLINK(ce->ce_mode))
318 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
319 /* else fallthrough */
320 default:
321 return TYPE_CHANGED;
323 return 0;
326 static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
328 unsigned int changed = 0;
330 if (ce->ce_flags & CE_REMOVE)
331 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
333 switch (ce->ce_mode & S_IFMT) {
334 case S_IFREG:
335 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
336 /* We consider only the owner x bit to be relevant for
337 * "mode changes"
339 if (trust_executable_bit &&
340 (0100 & (ce->ce_mode ^ st->st_mode)))
341 changed |= MODE_CHANGED;
342 break;
343 case S_IFLNK:
344 if (!S_ISLNK(st->st_mode) &&
345 (has_symlinks || !S_ISREG(st->st_mode)))
346 changed |= TYPE_CHANGED;
347 break;
348 case S_IFGITLINK:
349 /* We ignore most of the st_xxx fields for gitlinks */
350 if (!S_ISDIR(st->st_mode))
351 changed |= TYPE_CHANGED;
352 else if (ce_compare_gitlink(ce))
353 changed |= DATA_CHANGED;
354 return changed;
355 default:
356 BUG("unsupported ce_mode: %o", ce->ce_mode);
359 changed |= match_stat_data(&ce->ce_stat_data, st);
361 /* Racily smudged entry? */
362 if (!ce->ce_stat_data.sd_size) {
363 if (!is_empty_blob_sha1(ce->oid.hash))
364 changed |= DATA_CHANGED;
367 return changed;
370 static int is_racy_stat(const struct index_state *istate,
371 const struct stat_data *sd)
373 return (istate->timestamp.sec &&
374 #ifdef USE_NSEC
375 /* nanosecond timestamped files can also be racy! */
376 (istate->timestamp.sec < sd->sd_mtime.sec ||
377 (istate->timestamp.sec == sd->sd_mtime.sec &&
378 istate->timestamp.nsec <= sd->sd_mtime.nsec))
379 #else
380 istate->timestamp.sec <= sd->sd_mtime.sec
381 #endif
385 int is_racy_timestamp(const struct index_state *istate,
386 const struct cache_entry *ce)
388 return (!S_ISGITLINK(ce->ce_mode) &&
389 is_racy_stat(istate, &ce->ce_stat_data));
392 int match_stat_data_racy(const struct index_state *istate,
393 const struct stat_data *sd, struct stat *st)
395 if (is_racy_stat(istate, sd))
396 return MTIME_CHANGED;
397 return match_stat_data(sd, st);
400 int ie_match_stat(struct index_state *istate,
401 const struct cache_entry *ce, struct stat *st,
402 unsigned int options)
404 unsigned int changed;
405 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
406 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
407 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
408 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
410 if (!ignore_fsmonitor)
411 refresh_fsmonitor(istate);
413 * If it's marked as always valid in the index, it's
414 * valid whatever the checked-out copy says.
416 * skip-worktree has the same effect with higher precedence
418 if (!ignore_skip_worktree && ce_skip_worktree(ce))
419 return 0;
420 if (!ignore_valid && (ce->ce_flags & CE_VALID))
421 return 0;
422 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
423 return 0;
426 * Intent-to-add entries have not been added, so the index entry
427 * by definition never matches what is in the work tree until it
428 * actually gets added.
430 if (ce_intent_to_add(ce))
431 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
433 changed = ce_match_stat_basic(ce, st);
436 * Within 1 second of this sequence:
437 * echo xyzzy >file && git-update-index --add file
438 * running this command:
439 * echo frotz >file
440 * would give a falsely clean cache entry. The mtime and
441 * length match the cache, and other stat fields do not change.
443 * We could detect this at update-index time (the cache entry
444 * being registered/updated records the same time as "now")
445 * and delay the return from git-update-index, but that would
446 * effectively mean we can make at most one commit per second,
447 * which is not acceptable. Instead, we check cache entries
448 * whose mtime are the same as the index file timestamp more
449 * carefully than others.
451 if (!changed && is_racy_timestamp(istate, ce)) {
452 if (assume_racy_is_modified)
453 changed |= DATA_CHANGED;
454 else
455 changed |= ce_modified_check_fs(istate, ce, st);
458 return changed;
461 int ie_modified(struct index_state *istate,
462 const struct cache_entry *ce,
463 struct stat *st, unsigned int options)
465 int changed, changed_fs;
467 changed = ie_match_stat(istate, ce, st, options);
468 if (!changed)
469 return 0;
471 * If the mode or type has changed, there's no point in trying
472 * to refresh the entry - it's not going to match
474 if (changed & (MODE_CHANGED | TYPE_CHANGED))
475 return changed;
478 * Immediately after read-tree or update-index --cacheinfo,
479 * the length field is zero, as we have never even read the
480 * lstat(2) information once, and we cannot trust DATA_CHANGED
481 * returned by ie_match_stat() which in turn was returned by
482 * ce_match_stat_basic() to signal that the filesize of the
483 * blob changed. We have to actually go to the filesystem to
484 * see if the contents match, and if so, should answer "unchanged".
486 * The logic does not apply to gitlinks, as ce_match_stat_basic()
487 * already has checked the actual HEAD from the filesystem in the
488 * subproject. If ie_match_stat() already said it is different,
489 * then we know it is.
491 if ((changed & DATA_CHANGED) &&
492 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
493 return changed;
495 changed_fs = ce_modified_check_fs(istate, ce, st);
496 if (changed_fs)
497 return changed | changed_fs;
498 return 0;
501 int base_name_compare(const char *name1, size_t len1, int mode1,
502 const char *name2, size_t len2, int mode2)
504 unsigned char c1, c2;
505 size_t len = len1 < len2 ? len1 : len2;
506 int cmp;
508 cmp = memcmp(name1, name2, len);
509 if (cmp)
510 return cmp;
511 c1 = name1[len];
512 c2 = name2[len];
513 if (!c1 && S_ISDIR(mode1))
514 c1 = '/';
515 if (!c2 && S_ISDIR(mode2))
516 c2 = '/';
517 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
521 * df_name_compare() is identical to base_name_compare(), except it
522 * compares conflicting directory/file entries as equal. Note that
523 * while a directory name compares as equal to a regular file, they
524 * then individually compare _differently_ to a filename that has
525 * a dot after the basename (because '\0' < '.' < '/').
527 * This is used by routines that want to traverse the git namespace
528 * but then handle conflicting entries together when possible.
530 int df_name_compare(const char *name1, size_t len1, int mode1,
531 const char *name2, size_t len2, int mode2)
533 unsigned char c1, c2;
534 size_t len = len1 < len2 ? len1 : len2;
535 int cmp;
537 cmp = memcmp(name1, name2, len);
538 if (cmp)
539 return cmp;
540 /* Directories and files compare equal (same length, same name) */
541 if (len1 == len2)
542 return 0;
543 c1 = name1[len];
544 if (!c1 && S_ISDIR(mode1))
545 c1 = '/';
546 c2 = name2[len];
547 if (!c2 && S_ISDIR(mode2))
548 c2 = '/';
549 if (c1 == '/' && !c2)
550 return 0;
551 if (c2 == '/' && !c1)
552 return 0;
553 return c1 - c2;
556 int name_compare(const char *name1, size_t len1, const char *name2, size_t len2)
558 size_t min_len = (len1 < len2) ? len1 : len2;
559 int cmp = memcmp(name1, name2, min_len);
560 if (cmp)
561 return cmp;
562 if (len1 < len2)
563 return -1;
564 if (len1 > len2)
565 return 1;
566 return 0;
569 int cache_name_stage_compare(const char *name1, int len1, int stage1, const char *name2, int len2, int stage2)
571 int cmp;
573 cmp = name_compare(name1, len1, name2, len2);
574 if (cmp)
575 return cmp;
577 if (stage1 < stage2)
578 return -1;
579 if (stage1 > stage2)
580 return 1;
581 return 0;
584 static int index_name_stage_pos(struct index_state *istate,
585 const char *name, int namelen,
586 int stage,
587 enum index_search_mode search_mode)
589 int first, last;
591 first = 0;
592 last = istate->cache_nr;
593 while (last > first) {
594 int next = first + ((last - first) >> 1);
595 struct cache_entry *ce = istate->cache[next];
596 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
597 if (!cmp)
598 return next;
599 if (cmp < 0) {
600 last = next;
601 continue;
603 first = next+1;
606 if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
607 first > 0) {
608 /* Note: first <= istate->cache_nr */
609 struct cache_entry *ce = istate->cache[first - 1];
612 * If we are in a sparse-index _and_ the entry before the
613 * insertion position is a sparse-directory entry that is
614 * an ancestor of 'name', then we need to expand the index
615 * and search again. This will only trigger once, because
616 * thereafter the index is fully expanded.
618 if (S_ISSPARSEDIR(ce->ce_mode) &&
619 ce_namelen(ce) < namelen &&
620 !strncmp(name, ce->name, ce_namelen(ce))) {
621 ensure_full_index(istate);
622 return index_name_stage_pos(istate, name, namelen, stage, search_mode);
626 return -first-1;
629 int index_name_pos(struct index_state *istate, const char *name, int namelen)
631 return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
634 int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
636 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
639 int index_entry_exists(struct index_state *istate, const char *name, int namelen)
641 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
644 int remove_index_entry_at(struct index_state *istate, int pos)
646 struct cache_entry *ce = istate->cache[pos];
648 record_resolve_undo(istate, ce);
649 remove_name_hash(istate, ce);
650 save_or_free_index_entry(istate, ce);
651 istate->cache_changed |= CE_ENTRY_REMOVED;
652 istate->cache_nr--;
653 if (pos >= istate->cache_nr)
654 return 0;
655 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
656 istate->cache_nr - pos);
657 return 1;
661 * Remove all cache entries marked for removal, that is where
662 * CE_REMOVE is set in ce_flags. This is much more effective than
663 * calling remove_index_entry_at() for each entry to be removed.
665 void remove_marked_cache_entries(struct index_state *istate, int invalidate)
667 struct cache_entry **ce_array = istate->cache;
668 unsigned int i, j;
670 for (i = j = 0; i < istate->cache_nr; i++) {
671 if (ce_array[i]->ce_flags & CE_REMOVE) {
672 if (invalidate) {
673 cache_tree_invalidate_path(istate,
674 ce_array[i]->name);
675 untracked_cache_remove_from_index(istate,
676 ce_array[i]->name);
678 remove_name_hash(istate, ce_array[i]);
679 save_or_free_index_entry(istate, ce_array[i]);
681 else
682 ce_array[j++] = ce_array[i];
684 if (j == istate->cache_nr)
685 return;
686 istate->cache_changed |= CE_ENTRY_REMOVED;
687 istate->cache_nr = j;
690 int remove_file_from_index(struct index_state *istate, const char *path)
692 int pos = index_name_pos(istate, path, strlen(path));
693 if (pos < 0)
694 pos = -pos-1;
695 cache_tree_invalidate_path(istate, path);
696 untracked_cache_remove_from_index(istate, path);
697 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
698 remove_index_entry_at(istate, pos);
699 return 0;
702 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
704 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
707 static int index_name_pos_also_unmerged(struct index_state *istate,
708 const char *path, int namelen)
710 int pos = index_name_pos(istate, path, namelen);
711 struct cache_entry *ce;
713 if (pos >= 0)
714 return pos;
716 /* maybe unmerged? */
717 pos = -1 - pos;
718 if (pos >= istate->cache_nr ||
719 compare_name((ce = istate->cache[pos]), path, namelen))
720 return -1;
722 /* order of preference: stage 2, 1, 3 */
723 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
724 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
725 !compare_name(ce, path, namelen))
726 pos++;
727 return pos;
730 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
732 int len = ce_namelen(ce);
733 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
737 * If we add a filename that aliases in the cache, we will use the
738 * name that we already have - but we don't want to update the same
739 * alias twice, because that implies that there were actually two
740 * different files with aliasing names!
742 * So we use the CE_ADDED flag to verify that the alias was an old
743 * one before we accept it as
745 static struct cache_entry *create_alias_ce(struct index_state *istate,
746 struct cache_entry *ce,
747 struct cache_entry *alias)
749 int len;
750 struct cache_entry *new_entry;
752 if (alias->ce_flags & CE_ADDED)
753 die(_("will not add file alias '%s' ('%s' already exists in index)"),
754 ce->name, alias->name);
756 /* Ok, create the new entry using the name of the existing alias */
757 len = ce_namelen(alias);
758 new_entry = make_empty_cache_entry(istate, len);
759 memcpy(new_entry->name, alias->name, len);
760 copy_cache_entry(new_entry, ce);
761 save_or_free_index_entry(istate, ce);
762 return new_entry;
765 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
767 struct object_id oid;
768 if (write_object_file("", 0, OBJ_BLOB, &oid))
769 die(_("cannot create an empty blob in the object database"));
770 oidcpy(&ce->oid, &oid);
773 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
775 int namelen, was_same;
776 mode_t st_mode = st->st_mode;
777 struct cache_entry *ce, *alias = NULL;
778 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
779 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
780 int pretend = flags & ADD_CACHE_PRETEND;
781 int intent_only = flags & ADD_CACHE_INTENT;
782 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
783 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
784 unsigned hash_flags = pretend ? 0 : HASH_WRITE_OBJECT;
785 struct object_id oid;
787 if (flags & ADD_CACHE_RENORMALIZE)
788 hash_flags |= HASH_RENORMALIZE;
790 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
791 return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
793 namelen = strlen(path);
794 if (S_ISDIR(st_mode)) {
795 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
796 return error(_("'%s' does not have a commit checked out"), path);
797 while (namelen && path[namelen-1] == '/')
798 namelen--;
800 ce = make_empty_cache_entry(istate, namelen);
801 memcpy(ce->name, path, namelen);
802 ce->ce_namelen = namelen;
803 if (!intent_only)
804 fill_stat_cache_info(istate, ce, st);
805 else
806 ce->ce_flags |= CE_INTENT_TO_ADD;
809 if (trust_executable_bit && has_symlinks) {
810 ce->ce_mode = create_ce_mode(st_mode);
811 } else {
812 /* If there is an existing entry, pick the mode bits and type
813 * from it, otherwise assume unexecutable regular file.
815 struct cache_entry *ent;
816 int pos = index_name_pos_also_unmerged(istate, path, namelen);
818 ent = (0 <= pos) ? istate->cache[pos] : NULL;
819 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
822 /* When core.ignorecase=true, determine if a directory of the same name but differing
823 * case already exists within the Git repository. If it does, ensure the directory
824 * case of the file being added to the repository matches (is folded into) the existing
825 * entry's directory case.
827 if (ignore_case) {
828 adjust_dirname_case(istate, ce->name);
830 if (!(flags & ADD_CACHE_RENORMALIZE)) {
831 alias = index_file_exists(istate, ce->name,
832 ce_namelen(ce), ignore_case);
833 if (alias &&
834 !ce_stage(alias) &&
835 !ie_match_stat(istate, alias, st, ce_option)) {
836 /* Nothing changed, really */
837 if (!S_ISGITLINK(alias->ce_mode))
838 ce_mark_uptodate(alias);
839 alias->ce_flags |= CE_ADDED;
841 discard_cache_entry(ce);
842 return 0;
845 if (!intent_only) {
846 if (index_path(istate, &ce->oid, path, st, hash_flags)) {
847 discard_cache_entry(ce);
848 return error(_("unable to index file '%s'"), path);
850 } else
851 set_object_name_for_intent_to_add_entry(ce);
853 if (ignore_case && alias && different_name(ce, alias))
854 ce = create_alias_ce(istate, ce, alias);
855 ce->ce_flags |= CE_ADDED;
857 /* It was suspected to be racily clean, but it turns out to be Ok */
858 was_same = (alias &&
859 !ce_stage(alias) &&
860 oideq(&alias->oid, &ce->oid) &&
861 ce->ce_mode == alias->ce_mode);
863 if (pretend)
864 discard_cache_entry(ce);
865 else if (add_index_entry(istate, ce, add_option)) {
866 discard_cache_entry(ce);
867 return error(_("unable to add '%s' to index"), path);
869 if (verbose && !was_same)
870 printf("add '%s'\n", path);
871 return 0;
874 int add_file_to_index(struct index_state *istate, const char *path, int flags)
876 struct stat st;
877 if (lstat(path, &st))
878 die_errno(_("unable to stat '%s'"), path);
879 return add_to_index(istate, path, &st, flags);
882 struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
884 return mem_pool__ce_calloc(find_mem_pool(istate), len);
887 struct cache_entry *make_empty_transient_cache_entry(size_t len,
888 struct mem_pool *ce_mem_pool)
890 if (ce_mem_pool)
891 return mem_pool__ce_calloc(ce_mem_pool, len);
892 return xcalloc(1, cache_entry_size(len));
895 enum verify_path_result {
896 PATH_OK,
897 PATH_INVALID,
898 PATH_DIR_WITH_SEP,
901 static enum verify_path_result verify_path_internal(const char *, unsigned);
903 int verify_path(const char *path, unsigned mode)
905 return verify_path_internal(path, mode) == PATH_OK;
908 struct cache_entry *make_cache_entry(struct index_state *istate,
909 unsigned int mode,
910 const struct object_id *oid,
911 const char *path,
912 int stage,
913 unsigned int refresh_options)
915 struct cache_entry *ce, *ret;
916 int len;
918 if (verify_path_internal(path, mode) == PATH_INVALID) {
919 error(_("invalid path '%s'"), path);
920 return NULL;
923 len = strlen(path);
924 ce = make_empty_cache_entry(istate, len);
926 oidcpy(&ce->oid, oid);
927 memcpy(ce->name, path, len);
928 ce->ce_flags = create_ce_flags(stage);
929 ce->ce_namelen = len;
930 ce->ce_mode = create_ce_mode(mode);
932 ret = refresh_cache_entry(istate, ce, refresh_options);
933 if (ret != ce)
934 discard_cache_entry(ce);
935 return ret;
938 struct cache_entry *make_transient_cache_entry(unsigned int mode,
939 const struct object_id *oid,
940 const char *path,
941 int stage,
942 struct mem_pool *ce_mem_pool)
944 struct cache_entry *ce;
945 int len;
947 if (!verify_path(path, mode)) {
948 error(_("invalid path '%s'"), path);
949 return NULL;
952 len = strlen(path);
953 ce = make_empty_transient_cache_entry(len, ce_mem_pool);
955 oidcpy(&ce->oid, oid);
956 memcpy(ce->name, path, len);
957 ce->ce_flags = create_ce_flags(stage);
958 ce->ce_namelen = len;
959 ce->ce_mode = create_ce_mode(mode);
961 return ce;
965 * Chmod an index entry with either +x or -x.
967 * Returns -1 if the chmod for the particular cache entry failed (if it's
968 * not a regular file), -2 if an invalid flip argument is passed in, 0
969 * otherwise.
971 int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
972 char flip)
974 if (!S_ISREG(ce->ce_mode))
975 return -1;
976 switch (flip) {
977 case '+':
978 ce->ce_mode |= 0111;
979 break;
980 case '-':
981 ce->ce_mode &= ~0111;
982 break;
983 default:
984 return -2;
986 cache_tree_invalidate_path(istate, ce->name);
987 ce->ce_flags |= CE_UPDATE_IN_BASE;
988 mark_fsmonitor_invalid(istate, ce);
989 istate->cache_changed |= CE_ENTRY_CHANGED;
991 return 0;
994 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
996 int len = ce_namelen(a);
997 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
1001 * We fundamentally don't like some paths: we don't want
1002 * dot or dot-dot anywhere, and for obvious reasons don't
1003 * want to recurse into ".git" either.
1005 * Also, we don't want double slashes or slashes at the
1006 * end that can make pathnames ambiguous.
1008 static int verify_dotfile(const char *rest, unsigned mode)
1011 * The first character was '.', but that
1012 * has already been discarded, we now test
1013 * the rest.
1016 /* "." is not allowed */
1017 if (*rest == '\0' || is_dir_sep(*rest))
1018 return 0;
1020 switch (*rest) {
1022 * ".git" followed by NUL or slash is bad. Note that we match
1023 * case-insensitively here, even if ignore_case is not set.
1024 * This outlaws ".GIT" everywhere out of an abundance of caution,
1025 * since there's really no good reason to allow it.
1027 * Once we've seen ".git", we can also find ".gitmodules", etc (also
1028 * case-insensitively).
1030 case 'g':
1031 case 'G':
1032 if (rest[1] != 'i' && rest[1] != 'I')
1033 break;
1034 if (rest[2] != 't' && rest[2] != 'T')
1035 break;
1036 if (rest[3] == '\0' || is_dir_sep(rest[3]))
1037 return 0;
1038 if (S_ISLNK(mode)) {
1039 rest += 3;
1040 if (skip_iprefix(rest, "modules", &rest) &&
1041 (*rest == '\0' || is_dir_sep(*rest)))
1042 return 0;
1044 break;
1045 case '.':
1046 if (rest[1] == '\0' || is_dir_sep(rest[1]))
1047 return 0;
1049 return 1;
1052 static enum verify_path_result verify_path_internal(const char *path,
1053 unsigned mode)
1055 char c = 0;
1057 if (has_dos_drive_prefix(path))
1058 return PATH_INVALID;
1060 if (!is_valid_path(path))
1061 return PATH_INVALID;
1063 goto inside;
1064 for (;;) {
1065 if (!c)
1066 return PATH_OK;
1067 if (is_dir_sep(c)) {
1068 inside:
1069 if (protect_hfs) {
1071 if (is_hfs_dotgit(path))
1072 return PATH_INVALID;
1073 if (S_ISLNK(mode)) {
1074 if (is_hfs_dotgitmodules(path))
1075 return PATH_INVALID;
1078 if (protect_ntfs) {
1079 #if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
1080 if (c == '\\')
1081 return PATH_INVALID;
1082 #endif
1083 if (is_ntfs_dotgit(path))
1084 return PATH_INVALID;
1085 if (S_ISLNK(mode)) {
1086 if (is_ntfs_dotgitmodules(path))
1087 return PATH_INVALID;
1091 c = *path++;
1092 if ((c == '.' && !verify_dotfile(path, mode)) ||
1093 is_dir_sep(c))
1094 return PATH_INVALID;
1096 * allow terminating directory separators for
1097 * sparse directory entries.
1099 if (c == '\0')
1100 return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
1101 PATH_INVALID;
1102 } else if (c == '\\' && protect_ntfs) {
1103 if (is_ntfs_dotgit(path))
1104 return PATH_INVALID;
1105 if (S_ISLNK(mode)) {
1106 if (is_ntfs_dotgitmodules(path))
1107 return PATH_INVALID;
1111 c = *path++;
1116 * Do we have another file that has the beginning components being a
1117 * proper superset of the name we're trying to add?
1119 static int has_file_name(struct index_state *istate,
1120 const struct cache_entry *ce, int pos, int ok_to_replace)
1122 int retval = 0;
1123 int len = ce_namelen(ce);
1124 int stage = ce_stage(ce);
1125 const char *name = ce->name;
1127 while (pos < istate->cache_nr) {
1128 struct cache_entry *p = istate->cache[pos++];
1130 if (len >= ce_namelen(p))
1131 break;
1132 if (memcmp(name, p->name, len))
1133 break;
1134 if (ce_stage(p) != stage)
1135 continue;
1136 if (p->name[len] != '/')
1137 continue;
1138 if (p->ce_flags & CE_REMOVE)
1139 continue;
1140 retval = -1;
1141 if (!ok_to_replace)
1142 break;
1143 remove_index_entry_at(istate, --pos);
1145 return retval;
1150 * Like strcmp(), but also return the offset of the first change.
1151 * If strings are equal, return the length.
1153 int strcmp_offset(const char *s1, const char *s2, size_t *first_change)
1155 size_t k;
1157 if (!first_change)
1158 return strcmp(s1, s2);
1160 for (k = 0; s1[k] == s2[k]; k++)
1161 if (s1[k] == '\0')
1162 break;
1164 *first_change = k;
1165 return (unsigned char)s1[k] - (unsigned char)s2[k];
1169 * Do we have another file with a pathname that is a proper
1170 * subset of the name we're trying to add?
1172 * That is, is there another file in the index with a path
1173 * that matches a sub-directory in the given entry?
1175 static int has_dir_name(struct index_state *istate,
1176 const struct cache_entry *ce, int pos, int ok_to_replace)
1178 int retval = 0;
1179 int stage = ce_stage(ce);
1180 const char *name = ce->name;
1181 const char *slash = name + ce_namelen(ce);
1182 size_t len_eq_last;
1183 int cmp_last = 0;
1186 * We are frequently called during an iteration on a sorted
1187 * list of pathnames and while building a new index. Therefore,
1188 * there is a high probability that this entry will eventually
1189 * be appended to the index, rather than inserted in the middle.
1190 * If we can confirm that, we can avoid binary searches on the
1191 * components of the pathname.
1193 * Compare the entry's full path with the last path in the index.
1195 if (istate->cache_nr > 0) {
1196 cmp_last = strcmp_offset(name,
1197 istate->cache[istate->cache_nr - 1]->name,
1198 &len_eq_last);
1199 if (cmp_last > 0) {
1200 if (len_eq_last == 0) {
1202 * The entry sorts AFTER the last one in the
1203 * index and their paths have no common prefix,
1204 * so there cannot be a F/D conflict.
1206 return retval;
1207 } else {
1209 * The entry sorts AFTER the last one in the
1210 * index, but has a common prefix. Fall through
1211 * to the loop below to disect the entry's path
1212 * and see where the difference is.
1215 } else if (cmp_last == 0) {
1217 * The entry exactly matches the last one in the
1218 * index, but because of multiple stage and CE_REMOVE
1219 * items, we fall through and let the regular search
1220 * code handle it.
1225 for (;;) {
1226 size_t len;
1228 for (;;) {
1229 if (*--slash == '/')
1230 break;
1231 if (slash <= ce->name)
1232 return retval;
1234 len = slash - name;
1236 if (cmp_last > 0) {
1238 * (len + 1) is a directory boundary (including
1239 * the trailing slash). And since the loop is
1240 * decrementing "slash", the first iteration is
1241 * the longest directory prefix; subsequent
1242 * iterations consider parent directories.
1245 if (len + 1 <= len_eq_last) {
1247 * The directory prefix (including the trailing
1248 * slash) also appears as a prefix in the last
1249 * entry, so the remainder cannot collide (because
1250 * strcmp said the whole path was greater).
1252 * EQ: last: xxx/A
1253 * this: xxx/B
1255 * LT: last: xxx/file_A
1256 * this: xxx/file_B
1258 return retval;
1261 if (len > len_eq_last) {
1263 * This part of the directory prefix (excluding
1264 * the trailing slash) is longer than the known
1265 * equal portions, so this sub-directory cannot
1266 * collide with a file.
1268 * GT: last: xxxA
1269 * this: xxxB/file
1271 return retval;
1275 * This is a possible collision. Fall through and
1276 * let the regular search code handle it.
1278 * last: xxx
1279 * this: xxx/file
1283 pos = index_name_stage_pos(istate, name, len, stage, EXPAND_SPARSE);
1284 if (pos >= 0) {
1286 * Found one, but not so fast. This could
1287 * be a marker that says "I was here, but
1288 * I am being removed". Such an entry is
1289 * not a part of the resulting tree, and
1290 * it is Ok to have a directory at the same
1291 * path.
1293 if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
1294 retval = -1;
1295 if (!ok_to_replace)
1296 break;
1297 remove_index_entry_at(istate, pos);
1298 continue;
1301 else
1302 pos = -pos-1;
1305 * Trivial optimization: if we find an entry that
1306 * already matches the sub-directory, then we know
1307 * we're ok, and we can exit.
1309 while (pos < istate->cache_nr) {
1310 struct cache_entry *p = istate->cache[pos];
1311 if ((ce_namelen(p) <= len) ||
1312 (p->name[len] != '/') ||
1313 memcmp(p->name, name, len))
1314 break; /* not our subdirectory */
1315 if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
1317 * p is at the same stage as our entry, and
1318 * is a subdirectory of what we are looking
1319 * at, so we cannot have conflicts at our
1320 * level or anything shorter.
1322 return retval;
1323 pos++;
1326 return retval;
1329 /* We may be in a situation where we already have path/file and path
1330 * is being added, or we already have path and path/file is being
1331 * added. Either one would result in a nonsense tree that has path
1332 * twice when git-write-tree tries to write it out. Prevent it.
1334 * If ok-to-replace is specified, we remove the conflicting entries
1335 * from the cache so the caller should recompute the insert position.
1336 * When this happens, we return non-zero.
1338 static int check_file_directory_conflict(struct index_state *istate,
1339 const struct cache_entry *ce,
1340 int pos, int ok_to_replace)
1342 int retval;
1345 * When ce is an "I am going away" entry, we allow it to be added
1347 if (ce->ce_flags & CE_REMOVE)
1348 return 0;
1351 * We check if the path is a sub-path of a subsequent pathname
1352 * first, since removing those will not change the position
1353 * in the array.
1355 retval = has_file_name(istate, ce, pos, ok_to_replace);
1358 * Then check if the path might have a clashing sub-directory
1359 * before it.
1361 return retval + has_dir_name(istate, ce, pos, ok_to_replace);
1364 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
1366 int pos;
1367 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
1368 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
1369 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
1370 int new_only = option & ADD_CACHE_NEW_ONLY;
1373 * If this entry's path sorts after the last entry in the index,
1374 * we can avoid searching for it.
1376 if (istate->cache_nr > 0 &&
1377 strcmp(ce->name, istate->cache[istate->cache_nr - 1]->name) > 0)
1378 pos = index_pos_to_insert_pos(istate->cache_nr);
1379 else
1380 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1383 * Cache tree path should be invalidated only after index_name_stage_pos,
1384 * in case it expands a sparse index.
1386 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1387 cache_tree_invalidate_path(istate, ce->name);
1389 /* existing match? Just replace it. */
1390 if (pos >= 0) {
1391 if (!new_only)
1392 replace_index_entry(istate, pos, ce);
1393 return 0;
1395 pos = -pos-1;
1397 if (!(option & ADD_CACHE_KEEP_CACHE_TREE))
1398 untracked_cache_add_to_index(istate, ce->name);
1401 * Inserting a merged entry ("stage 0") into the index
1402 * will always replace all non-merged entries..
1404 if (pos < istate->cache_nr && ce_stage(ce) == 0) {
1405 while (ce_same_name(istate->cache[pos], ce)) {
1406 ok_to_add = 1;
1407 if (!remove_index_entry_at(istate, pos))
1408 break;
1412 if (!ok_to_add)
1413 return -1;
1414 if (verify_path_internal(ce->name, ce->ce_mode) == PATH_INVALID)
1415 return error(_("invalid path '%s'"), ce->name);
1417 if (!skip_df_check &&
1418 check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
1419 if (!ok_to_replace)
1420 return error(_("'%s' appears as both a file and as a directory"),
1421 ce->name);
1422 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce), EXPAND_SPARSE);
1423 pos = -pos-1;
1425 return pos + 1;
1428 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
1430 int pos;
1432 if (option & ADD_CACHE_JUST_APPEND)
1433 pos = istate->cache_nr;
1434 else {
1435 int ret;
1436 ret = add_index_entry_with_check(istate, ce, option);
1437 if (ret <= 0)
1438 return ret;
1439 pos = ret - 1;
1442 /* Make sure the array is big enough .. */
1443 ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1445 /* Add it in.. */
1446 istate->cache_nr++;
1447 if (istate->cache_nr > pos + 1)
1448 MOVE_ARRAY(istate->cache + pos + 1, istate->cache + pos,
1449 istate->cache_nr - pos - 1);
1450 set_index_entry(istate, pos, ce);
1451 istate->cache_changed |= CE_ENTRY_ADDED;
1452 return 0;
1456 * "refresh" does not calculate a new sha1 file or bring the
1457 * cache up-to-date for mode/content changes. But what it
1458 * _does_ do is to "re-match" the stat information of a file
1459 * with the cache, so that you can refresh the cache for a
1460 * file that hasn't been changed but where the stat entry is
1461 * out of date.
1463 * For example, you'd want to do this after doing a "git-read-tree",
1464 * to link up the stat cache details with the proper files.
1466 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1467 struct cache_entry *ce,
1468 unsigned int options, int *err,
1469 int *changed_ret,
1470 int *t2_did_lstat,
1471 int *t2_did_scan)
1473 struct stat st;
1474 struct cache_entry *updated;
1475 int changed;
1476 int refresh = options & CE_MATCH_REFRESH;
1477 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1478 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1479 int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1480 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
1482 if (!refresh || ce_uptodate(ce))
1483 return ce;
1485 if (!ignore_fsmonitor)
1486 refresh_fsmonitor(istate);
1488 * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1489 * that the change to the work tree does not matter and told
1490 * us not to worry.
1492 if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1493 ce_mark_uptodate(ce);
1494 return ce;
1496 if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1497 ce_mark_uptodate(ce);
1498 return ce;
1500 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID)) {
1501 ce_mark_uptodate(ce);
1502 return ce;
1505 if (has_symlink_leading_path(ce->name, ce_namelen(ce))) {
1506 if (ignore_missing)
1507 return ce;
1508 if (err)
1509 *err = ENOENT;
1510 return NULL;
1513 if (t2_did_lstat)
1514 *t2_did_lstat = 1;
1515 if (lstat(ce->name, &st) < 0) {
1516 if (ignore_missing && errno == ENOENT)
1517 return ce;
1518 if (err)
1519 *err = errno;
1520 return NULL;
1523 changed = ie_match_stat(istate, ce, &st, options);
1524 if (changed_ret)
1525 *changed_ret = changed;
1526 if (!changed) {
1528 * The path is unchanged. If we were told to ignore
1529 * valid bit, then we did the actual stat check and
1530 * found that the entry is unmodified. If the entry
1531 * is not marked VALID, this is the place to mark it
1532 * valid again, under "assume unchanged" mode.
1534 if (ignore_valid && assume_unchanged &&
1535 !(ce->ce_flags & CE_VALID))
1536 ; /* mark this one VALID again */
1537 else {
1539 * We do not mark the index itself "modified"
1540 * because CE_UPTODATE flag is in-core only;
1541 * we are not going to write this change out.
1543 if (!S_ISGITLINK(ce->ce_mode)) {
1544 ce_mark_uptodate(ce);
1545 mark_fsmonitor_valid(istate, ce);
1547 return ce;
1551 if (t2_did_scan)
1552 *t2_did_scan = 1;
1553 if (ie_modified(istate, ce, &st, options)) {
1554 if (err)
1555 *err = EINVAL;
1556 return NULL;
1559 updated = make_empty_cache_entry(istate, ce_namelen(ce));
1560 copy_cache_entry(updated, ce);
1561 memcpy(updated->name, ce->name, ce->ce_namelen + 1);
1562 fill_stat_cache_info(istate, updated, &st);
1564 * If ignore_valid is not set, we should leave CE_VALID bit
1565 * alone. Otherwise, paths marked with --no-assume-unchanged
1566 * (i.e. things to be edited) will reacquire CE_VALID bit
1567 * automatically, which is not really what we want.
1569 if (!ignore_valid && assume_unchanged &&
1570 !(ce->ce_flags & CE_VALID))
1571 updated->ce_flags &= ~CE_VALID;
1573 /* istate->cache_changed is updated in the caller */
1574 return updated;
1577 static void show_file(const char * fmt, const char * name, int in_porcelain,
1578 int * first, const char *header_msg)
1580 if (in_porcelain && *first && header_msg) {
1581 printf("%s\n", header_msg);
1582 *first = 0;
1584 printf(fmt, name);
1587 int repo_refresh_and_write_index(struct repository *repo,
1588 unsigned int refresh_flags,
1589 unsigned int write_flags,
1590 int gentle,
1591 const struct pathspec *pathspec,
1592 char *seen, const char *header_msg)
1594 struct lock_file lock_file = LOCK_INIT;
1595 int fd, ret = 0;
1597 fd = repo_hold_locked_index(repo, &lock_file, 0);
1598 if (!gentle && fd < 0)
1599 return -1;
1600 if (refresh_index(repo->index, refresh_flags, pathspec, seen, header_msg))
1601 ret = 1;
1602 if (0 <= fd && write_locked_index(repo->index, &lock_file, COMMIT_LOCK | write_flags))
1603 ret = -1;
1604 return ret;
1608 int refresh_index(struct index_state *istate, unsigned int flags,
1609 const struct pathspec *pathspec,
1610 char *seen, const char *header_msg)
1612 int i;
1613 int has_errors = 0;
1614 int really = (flags & REFRESH_REALLY) != 0;
1615 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1616 int quiet = (flags & REFRESH_QUIET) != 0;
1617 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1618 int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1619 int ignore_skip_worktree = (flags & REFRESH_IGNORE_SKIP_WORKTREE) != 0;
1620 int first = 1;
1621 int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1622 unsigned int options = (CE_MATCH_REFRESH |
1623 (really ? CE_MATCH_IGNORE_VALID : 0) |
1624 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1625 const char *modified_fmt;
1626 const char *deleted_fmt;
1627 const char *typechange_fmt;
1628 const char *added_fmt;
1629 const char *unmerged_fmt;
1630 struct progress *progress = NULL;
1631 int t2_sum_lstat = 0;
1632 int t2_sum_scan = 0;
1634 if (flags & REFRESH_PROGRESS && isatty(2))
1635 progress = start_delayed_progress(_("Refresh index"),
1636 istate->cache_nr);
1638 trace_performance_enter();
1639 modified_fmt = in_porcelain ? "M\t%s\n" : "%s: needs update\n";
1640 deleted_fmt = in_porcelain ? "D\t%s\n" : "%s: needs update\n";
1641 typechange_fmt = in_porcelain ? "T\t%s\n" : "%s: needs update\n";
1642 added_fmt = in_porcelain ? "A\t%s\n" : "%s: needs update\n";
1643 unmerged_fmt = in_porcelain ? "U\t%s\n" : "%s: needs merge\n";
1645 * Use the multi-threaded preload_index() to refresh most of the
1646 * cache entries quickly then in the single threaded loop below,
1647 * we only have to do the special cases that are left.
1649 preload_index(istate, pathspec, 0);
1650 trace2_region_enter("index", "refresh", NULL);
1652 for (i = 0; i < istate->cache_nr; i++) {
1653 struct cache_entry *ce, *new_entry;
1654 int cache_errno = 0;
1655 int changed = 0;
1656 int filtered = 0;
1657 int t2_did_lstat = 0;
1658 int t2_did_scan = 0;
1660 ce = istate->cache[i];
1661 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1662 continue;
1663 if (ignore_skip_worktree && ce_skip_worktree(ce))
1664 continue;
1667 * If this entry is a sparse directory, then there isn't
1668 * any stat() information to update. Ignore the entry.
1670 if (S_ISSPARSEDIR(ce->ce_mode))
1671 continue;
1673 if (pathspec && !ce_path_match(istate, ce, pathspec, seen))
1674 filtered = 1;
1676 if (ce_stage(ce)) {
1677 while ((i < istate->cache_nr) &&
1678 ! strcmp(istate->cache[i]->name, ce->name))
1679 i++;
1680 i--;
1681 if (allow_unmerged)
1682 continue;
1683 if (!filtered)
1684 show_file(unmerged_fmt, ce->name, in_porcelain,
1685 &first, header_msg);
1686 has_errors = 1;
1687 continue;
1690 if (filtered)
1691 continue;
1693 new_entry = refresh_cache_ent(istate, ce, options,
1694 &cache_errno, &changed,
1695 &t2_did_lstat, &t2_did_scan);
1696 t2_sum_lstat += t2_did_lstat;
1697 t2_sum_scan += t2_did_scan;
1698 if (new_entry == ce)
1699 continue;
1700 display_progress(progress, i);
1701 if (!new_entry) {
1702 const char *fmt;
1704 if (really && cache_errno == EINVAL) {
1705 /* If we are doing --really-refresh that
1706 * means the index is not valid anymore.
1708 ce->ce_flags &= ~CE_VALID;
1709 ce->ce_flags |= CE_UPDATE_IN_BASE;
1710 mark_fsmonitor_invalid(istate, ce);
1711 istate->cache_changed |= CE_ENTRY_CHANGED;
1713 if (quiet)
1714 continue;
1716 if (cache_errno == ENOENT)
1717 fmt = deleted_fmt;
1718 else if (ce_intent_to_add(ce))
1719 fmt = added_fmt; /* must be before other checks */
1720 else if (changed & TYPE_CHANGED)
1721 fmt = typechange_fmt;
1722 else
1723 fmt = modified_fmt;
1724 show_file(fmt,
1725 ce->name, in_porcelain, &first, header_msg);
1726 has_errors = 1;
1727 continue;
1730 replace_index_entry(istate, i, new_entry);
1732 trace2_data_intmax("index", NULL, "refresh/sum_lstat", t2_sum_lstat);
1733 trace2_data_intmax("index", NULL, "refresh/sum_scan", t2_sum_scan);
1734 trace2_region_leave("index", "refresh", NULL);
1735 display_progress(progress, istate->cache_nr);
1736 stop_progress(&progress);
1737 trace_performance_leave("refresh index");
1738 return has_errors;
1741 struct cache_entry *refresh_cache_entry(struct index_state *istate,
1742 struct cache_entry *ce,
1743 unsigned int options)
1745 return refresh_cache_ent(istate, ce, options, NULL, NULL, NULL, NULL);
1749 /*****************************************************************
1750 * Index File I/O
1751 *****************************************************************/
1753 #define INDEX_FORMAT_DEFAULT 3
1755 static unsigned int get_index_format_default(struct repository *r)
1757 char *envversion = getenv("GIT_INDEX_VERSION");
1758 char *endp;
1759 unsigned int version = INDEX_FORMAT_DEFAULT;
1761 if (!envversion) {
1762 prepare_repo_settings(r);
1764 if (r->settings.index_version >= 0)
1765 version = r->settings.index_version;
1766 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1767 warning(_("index.version set, but the value is invalid.\n"
1768 "Using version %i"), INDEX_FORMAT_DEFAULT);
1769 return INDEX_FORMAT_DEFAULT;
1771 return version;
1774 version = strtoul(envversion, &endp, 10);
1775 if (*endp ||
1776 version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1777 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1778 "Using version %i"), INDEX_FORMAT_DEFAULT);
1779 version = INDEX_FORMAT_DEFAULT;
1781 return version;
1785 * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1786 * Again - this is just a (very strong in practice) heuristic that
1787 * the inode hasn't changed.
1789 * We save the fields in big-endian order to allow using the
1790 * index file over NFS transparently.
1792 struct ondisk_cache_entry {
1793 struct cache_time ctime;
1794 struct cache_time mtime;
1795 uint32_t dev;
1796 uint32_t ino;
1797 uint32_t mode;
1798 uint32_t uid;
1799 uint32_t gid;
1800 uint32_t size;
1802 * unsigned char hash[hashsz];
1803 * uint16_t flags;
1804 * if (flags & CE_EXTENDED)
1805 * uint16_t flags2;
1807 unsigned char data[GIT_MAX_RAWSZ + 2 * sizeof(uint16_t)];
1808 char name[FLEX_ARRAY];
1811 /* These are only used for v3 or lower */
1812 #define align_padding_size(size, len) ((size + (len) + 8) & ~7) - (size + len)
1813 #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,data) + (len) + 8) & ~7)
1814 #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1815 #define ondisk_data_size(flags, len) (the_hash_algo->rawsz + \
1816 ((flags & CE_EXTENDED) ? 2 : 1) * sizeof(uint16_t) + len)
1817 #define ondisk_data_size_max(len) (ondisk_data_size(CE_EXTENDED, len))
1818 #define ondisk_ce_size(ce) (ondisk_cache_entry_size(ondisk_data_size((ce)->ce_flags, ce_namelen(ce))))
1820 /* Allow fsck to force verification of the index checksum. */
1821 int verify_index_checksum;
1823 /* Allow fsck to force verification of the cache entry order. */
1824 int verify_ce_order;
1826 static int verify_hdr(const struct cache_header *hdr, unsigned long size)
1828 git_hash_ctx c;
1829 unsigned char hash[GIT_MAX_RAWSZ];
1830 int hdr_version;
1831 unsigned char *start, *end;
1832 struct object_id oid;
1834 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1835 return error(_("bad signature 0x%08x"), hdr->hdr_signature);
1836 hdr_version = ntohl(hdr->hdr_version);
1837 if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1838 return error(_("bad index version %d"), hdr_version);
1840 if (!verify_index_checksum)
1841 return 0;
1843 end = (unsigned char *)hdr + size;
1844 start = end - the_hash_algo->rawsz;
1845 oidread(&oid, start);
1846 if (oideq(&oid, null_oid()))
1847 return 0;
1849 the_hash_algo->init_fn(&c);
1850 the_hash_algo->update_fn(&c, hdr, size - the_hash_algo->rawsz);
1851 the_hash_algo->final_fn(hash, &c);
1852 if (!hasheq(hash, start))
1853 return error(_("bad index file sha1 signature"));
1854 return 0;
1857 static int read_index_extension(struct index_state *istate,
1858 const char *ext, const char *data, unsigned long sz)
1860 switch (CACHE_EXT(ext)) {
1861 case CACHE_EXT_TREE:
1862 istate->cache_tree = cache_tree_read(data, sz);
1863 break;
1864 case CACHE_EXT_RESOLVE_UNDO:
1865 istate->resolve_undo = resolve_undo_read(data, sz);
1866 break;
1867 case CACHE_EXT_LINK:
1868 if (read_link_extension(istate, data, sz))
1869 return -1;
1870 break;
1871 case CACHE_EXT_UNTRACKED:
1872 istate->untracked = read_untracked_extension(data, sz);
1873 break;
1874 case CACHE_EXT_FSMONITOR:
1875 read_fsmonitor_extension(istate, data, sz);
1876 break;
1877 case CACHE_EXT_ENDOFINDEXENTRIES:
1878 case CACHE_EXT_INDEXENTRYOFFSETTABLE:
1879 /* already handled in do_read_index() */
1880 break;
1881 case CACHE_EXT_SPARSE_DIRECTORIES:
1882 /* no content, only an indicator */
1883 istate->sparse_index = INDEX_COLLAPSED;
1884 break;
1885 default:
1886 if (*ext < 'A' || 'Z' < *ext)
1887 return error(_("index uses %.4s extension, which we do not understand"),
1888 ext);
1889 fprintf_ln(stderr, _("ignoring %.4s extension"), ext);
1890 break;
1892 return 0;
1896 * Parses the contents of the cache entry contained within the 'ondisk' buffer
1897 * into a new incore 'cache_entry'.
1899 * Note that 'char *ondisk' may not be aligned to a 4-byte address interval in
1900 * index v4, so we cannot cast it to 'struct ondisk_cache_entry *' and access
1901 * its members. Instead, we use the byte offsets of members within the struct to
1902 * identify where 'get_be16()', 'get_be32()', and 'oidread()' (which can all
1903 * read from an unaligned memory buffer) should read from the 'ondisk' buffer
1904 * into the corresponding incore 'cache_entry' members.
1906 static struct cache_entry *create_from_disk(struct mem_pool *ce_mem_pool,
1907 unsigned int version,
1908 const char *ondisk,
1909 unsigned long *ent_size,
1910 const struct cache_entry *previous_ce)
1912 struct cache_entry *ce;
1913 size_t len;
1914 const char *name;
1915 const unsigned hashsz = the_hash_algo->rawsz;
1916 const char *flagsp = ondisk + offsetof(struct ondisk_cache_entry, data) + hashsz;
1917 unsigned int flags;
1918 size_t copy_len = 0;
1920 * Adjacent cache entries tend to share the leading paths, so it makes
1921 * sense to only store the differences in later entries. In the v4
1922 * on-disk format of the index, each on-disk cache entry stores the
1923 * number of bytes to be stripped from the end of the previous name,
1924 * and the bytes to append to the result, to come up with its name.
1926 int expand_name_field = version == 4;
1928 /* On-disk flags are just 16 bits */
1929 flags = get_be16(flagsp);
1930 len = flags & CE_NAMEMASK;
1932 if (flags & CE_EXTENDED) {
1933 int extended_flags;
1934 extended_flags = get_be16(flagsp + sizeof(uint16_t)) << 16;
1935 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1936 if (extended_flags & ~CE_EXTENDED_FLAGS)
1937 die(_("unknown index entry format 0x%08x"), extended_flags);
1938 flags |= extended_flags;
1939 name = (const char *)(flagsp + 2 * sizeof(uint16_t));
1941 else
1942 name = (const char *)(flagsp + sizeof(uint16_t));
1944 if (expand_name_field) {
1945 const unsigned char *cp = (const unsigned char *)name;
1946 size_t strip_len, previous_len;
1948 /* If we're at the beginning of a block, ignore the previous name */
1949 strip_len = decode_varint(&cp);
1950 if (previous_ce) {
1951 previous_len = previous_ce->ce_namelen;
1952 if (previous_len < strip_len)
1953 die(_("malformed name field in the index, near path '%s'"),
1954 previous_ce->name);
1955 copy_len = previous_len - strip_len;
1957 name = (const char *)cp;
1960 if (len == CE_NAMEMASK) {
1961 len = strlen(name);
1962 if (expand_name_field)
1963 len += copy_len;
1966 ce = mem_pool__ce_alloc(ce_mem_pool, len);
1969 * NEEDSWORK: using 'offsetof()' is cumbersome and should be replaced
1970 * with something more akin to 'load_bitmap_entries_v1()'s use of
1971 * 'read_be16'/'read_be32'. For consistency with the corresponding
1972 * ondisk entry write function ('copy_cache_entry_to_ondisk()'), this
1973 * should be done at the same time as removing references to
1974 * 'ondisk_cache_entry' there.
1976 ce->ce_stat_data.sd_ctime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1977 + offsetof(struct cache_time, sec));
1978 ce->ce_stat_data.sd_mtime.sec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1979 + offsetof(struct cache_time, sec));
1980 ce->ce_stat_data.sd_ctime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ctime)
1981 + offsetof(struct cache_time, nsec));
1982 ce->ce_stat_data.sd_mtime.nsec = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mtime)
1983 + offsetof(struct cache_time, nsec));
1984 ce->ce_stat_data.sd_dev = get_be32(ondisk + offsetof(struct ondisk_cache_entry, dev));
1985 ce->ce_stat_data.sd_ino = get_be32(ondisk + offsetof(struct ondisk_cache_entry, ino));
1986 ce->ce_mode = get_be32(ondisk + offsetof(struct ondisk_cache_entry, mode));
1987 ce->ce_stat_data.sd_uid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, uid));
1988 ce->ce_stat_data.sd_gid = get_be32(ondisk + offsetof(struct ondisk_cache_entry, gid));
1989 ce->ce_stat_data.sd_size = get_be32(ondisk + offsetof(struct ondisk_cache_entry, size));
1990 ce->ce_flags = flags & ~CE_NAMEMASK;
1991 ce->ce_namelen = len;
1992 ce->index = 0;
1993 oidread(&ce->oid, (const unsigned char *)ondisk + offsetof(struct ondisk_cache_entry, data));
1995 if (expand_name_field) {
1996 if (copy_len)
1997 memcpy(ce->name, previous_ce->name, copy_len);
1998 memcpy(ce->name + copy_len, name, len + 1 - copy_len);
1999 *ent_size = (name - ((char *)ondisk)) + len + 1 - copy_len;
2000 } else {
2001 memcpy(ce->name, name, len + 1);
2002 *ent_size = ondisk_ce_size(ce);
2004 return ce;
2007 static void check_ce_order(struct index_state *istate)
2009 unsigned int i;
2011 if (!verify_ce_order)
2012 return;
2014 for (i = 1; i < istate->cache_nr; i++) {
2015 struct cache_entry *ce = istate->cache[i - 1];
2016 struct cache_entry *next_ce = istate->cache[i];
2017 int name_compare = strcmp(ce->name, next_ce->name);
2019 if (0 < name_compare)
2020 die(_("unordered stage entries in index"));
2021 if (!name_compare) {
2022 if (!ce_stage(ce))
2023 die(_("multiple stage entries for merged file '%s'"),
2024 ce->name);
2025 if (ce_stage(ce) > ce_stage(next_ce))
2026 die(_("unordered stage entries for '%s'"),
2027 ce->name);
2032 static void tweak_untracked_cache(struct index_state *istate)
2034 struct repository *r = the_repository;
2036 prepare_repo_settings(r);
2038 switch (r->settings.core_untracked_cache) {
2039 case UNTRACKED_CACHE_REMOVE:
2040 remove_untracked_cache(istate);
2041 break;
2042 case UNTRACKED_CACHE_WRITE:
2043 add_untracked_cache(istate);
2044 break;
2045 case UNTRACKED_CACHE_KEEP:
2047 * Either an explicit "core.untrackedCache=keep", the
2048 * default if "core.untrackedCache" isn't configured,
2049 * or a fallback on an unknown "core.untrackedCache"
2050 * value.
2052 break;
2056 static void tweak_split_index(struct index_state *istate)
2058 switch (git_config_get_split_index()) {
2059 case -1: /* unset: do nothing */
2060 break;
2061 case 0: /* false */
2062 remove_split_index(istate);
2063 break;
2064 case 1: /* true */
2065 add_split_index(istate);
2066 break;
2067 default: /* unknown value: do nothing */
2068 break;
2072 static void post_read_index_from(struct index_state *istate)
2074 check_ce_order(istate);
2075 tweak_untracked_cache(istate);
2076 tweak_split_index(istate);
2077 tweak_fsmonitor(istate);
2080 static size_t estimate_cache_size_from_compressed(unsigned int entries)
2082 return entries * (sizeof(struct cache_entry) + CACHE_ENTRY_PATH_LENGTH);
2085 static size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
2087 long per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
2090 * Account for potential alignment differences.
2092 per_entry += align_padding_size(per_entry, 0);
2093 return ondisk_size + entries * per_entry;
2096 struct index_entry_offset
2098 /* starting byte offset into index file, count of index entries in this block */
2099 int offset, nr;
2102 struct index_entry_offset_table
2104 int nr;
2105 struct index_entry_offset entries[FLEX_ARRAY];
2108 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset);
2109 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot);
2111 static size_t read_eoie_extension(const char *mmap, size_t mmap_size);
2112 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset);
2114 struct load_index_extensions
2116 pthread_t pthread;
2117 struct index_state *istate;
2118 const char *mmap;
2119 size_t mmap_size;
2120 unsigned long src_offset;
2123 static void *load_index_extensions(void *_data)
2125 struct load_index_extensions *p = _data;
2126 unsigned long src_offset = p->src_offset;
2128 while (src_offset <= p->mmap_size - the_hash_algo->rawsz - 8) {
2129 /* After an array of active_nr index entries,
2130 * there can be arbitrary number of extended
2131 * sections, each of which is prefixed with
2132 * extension name (4-byte) and section length
2133 * in 4-byte network byte order.
2135 uint32_t extsize = get_be32(p->mmap + src_offset + 4);
2136 if (read_index_extension(p->istate,
2137 p->mmap + src_offset,
2138 p->mmap + src_offset + 8,
2139 extsize) < 0) {
2140 munmap((void *)p->mmap, p->mmap_size);
2141 die(_("index file corrupt"));
2143 src_offset += 8;
2144 src_offset += extsize;
2147 return NULL;
2151 * A helper function that will load the specified range of cache entries
2152 * from the memory mapped file and add them to the given index.
2154 static unsigned long load_cache_entry_block(struct index_state *istate,
2155 struct mem_pool *ce_mem_pool, int offset, int nr, const char *mmap,
2156 unsigned long start_offset, const struct cache_entry *previous_ce)
2158 int i;
2159 unsigned long src_offset = start_offset;
2161 for (i = offset; i < offset + nr; i++) {
2162 struct cache_entry *ce;
2163 unsigned long consumed;
2165 ce = create_from_disk(ce_mem_pool, istate->version,
2166 mmap + src_offset,
2167 &consumed, previous_ce);
2168 set_index_entry(istate, i, ce);
2170 src_offset += consumed;
2171 previous_ce = ce;
2173 return src_offset - start_offset;
2176 static unsigned long load_all_cache_entries(struct index_state *istate,
2177 const char *mmap, size_t mmap_size, unsigned long src_offset)
2179 unsigned long consumed;
2181 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2182 if (istate->version == 4) {
2183 mem_pool_init(istate->ce_mem_pool,
2184 estimate_cache_size_from_compressed(istate->cache_nr));
2185 } else {
2186 mem_pool_init(istate->ce_mem_pool,
2187 estimate_cache_size(mmap_size, istate->cache_nr));
2190 consumed = load_cache_entry_block(istate, istate->ce_mem_pool,
2191 0, istate->cache_nr, mmap, src_offset, NULL);
2192 return consumed;
2196 * Mostly randomly chosen maximum thread counts: we
2197 * cap the parallelism to online_cpus() threads, and we want
2198 * to have at least 10000 cache entries per thread for it to
2199 * be worth starting a thread.
2202 #define THREAD_COST (10000)
2204 struct load_cache_entries_thread_data
2206 pthread_t pthread;
2207 struct index_state *istate;
2208 struct mem_pool *ce_mem_pool;
2209 int offset;
2210 const char *mmap;
2211 struct index_entry_offset_table *ieot;
2212 int ieot_start; /* starting index into the ieot array */
2213 int ieot_blocks; /* count of ieot entries to process */
2214 unsigned long consumed; /* return # of bytes in index file processed */
2218 * A thread proc to run the load_cache_entries() computation
2219 * across multiple background threads.
2221 static void *load_cache_entries_thread(void *_data)
2223 struct load_cache_entries_thread_data *p = _data;
2224 int i;
2226 /* iterate across all ieot blocks assigned to this thread */
2227 for (i = p->ieot_start; i < p->ieot_start + p->ieot_blocks; i++) {
2228 p->consumed += load_cache_entry_block(p->istate, p->ce_mem_pool,
2229 p->offset, p->ieot->entries[i].nr, p->mmap, p->ieot->entries[i].offset, NULL);
2230 p->offset += p->ieot->entries[i].nr;
2232 return NULL;
2235 static unsigned long load_cache_entries_threaded(struct index_state *istate, const char *mmap, size_t mmap_size,
2236 int nr_threads, struct index_entry_offset_table *ieot)
2238 int i, offset, ieot_blocks, ieot_start, err;
2239 struct load_cache_entries_thread_data *data;
2240 unsigned long consumed = 0;
2242 /* a little sanity checking */
2243 if (istate->name_hash_initialized)
2244 BUG("the name hash isn't thread safe");
2246 istate->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2247 mem_pool_init(istate->ce_mem_pool, 0);
2249 /* ensure we have no more threads than we have blocks to process */
2250 if (nr_threads > ieot->nr)
2251 nr_threads = ieot->nr;
2252 CALLOC_ARRAY(data, nr_threads);
2254 offset = ieot_start = 0;
2255 ieot_blocks = DIV_ROUND_UP(ieot->nr, nr_threads);
2256 for (i = 0; i < nr_threads; i++) {
2257 struct load_cache_entries_thread_data *p = &data[i];
2258 int nr, j;
2260 if (ieot_start + ieot_blocks > ieot->nr)
2261 ieot_blocks = ieot->nr - ieot_start;
2263 p->istate = istate;
2264 p->offset = offset;
2265 p->mmap = mmap;
2266 p->ieot = ieot;
2267 p->ieot_start = ieot_start;
2268 p->ieot_blocks = ieot_blocks;
2270 /* create a mem_pool for each thread */
2271 nr = 0;
2272 for (j = p->ieot_start; j < p->ieot_start + p->ieot_blocks; j++)
2273 nr += p->ieot->entries[j].nr;
2274 p->ce_mem_pool = xmalloc(sizeof(*istate->ce_mem_pool));
2275 if (istate->version == 4) {
2276 mem_pool_init(p->ce_mem_pool,
2277 estimate_cache_size_from_compressed(nr));
2278 } else {
2279 mem_pool_init(p->ce_mem_pool,
2280 estimate_cache_size(mmap_size, nr));
2283 err = pthread_create(&p->pthread, NULL, load_cache_entries_thread, p);
2284 if (err)
2285 die(_("unable to create load_cache_entries thread: %s"), strerror(err));
2287 /* increment by the number of cache entries in the ieot block being processed */
2288 for (j = 0; j < ieot_blocks; j++)
2289 offset += ieot->entries[ieot_start + j].nr;
2290 ieot_start += ieot_blocks;
2293 for (i = 0; i < nr_threads; i++) {
2294 struct load_cache_entries_thread_data *p = &data[i];
2296 err = pthread_join(p->pthread, NULL);
2297 if (err)
2298 die(_("unable to join load_cache_entries thread: %s"), strerror(err));
2299 mem_pool_combine(istate->ce_mem_pool, p->ce_mem_pool);
2300 consumed += p->consumed;
2303 free(data);
2305 return consumed;
2308 static void set_new_index_sparsity(struct index_state *istate)
2311 * If the index's repo exists, mark it sparse according to
2312 * repo settings.
2314 prepare_repo_settings(istate->repo);
2315 if (!istate->repo->settings.command_requires_full_index &&
2316 is_sparse_index_allowed(istate, 0))
2317 istate->sparse_index = 1;
2320 /* remember to discard_cache() before reading a different cache! */
2321 int do_read_index(struct index_state *istate, const char *path, int must_exist)
2323 int fd;
2324 struct stat st;
2325 unsigned long src_offset;
2326 const struct cache_header *hdr;
2327 const char *mmap;
2328 size_t mmap_size;
2329 struct load_index_extensions p;
2330 size_t extension_offset = 0;
2331 int nr_threads, cpus;
2332 struct index_entry_offset_table *ieot = NULL;
2334 if (istate->initialized)
2335 return istate->cache_nr;
2337 istate->timestamp.sec = 0;
2338 istate->timestamp.nsec = 0;
2339 fd = open(path, O_RDONLY);
2340 if (fd < 0) {
2341 if (!must_exist && errno == ENOENT) {
2342 set_new_index_sparsity(istate);
2343 return 0;
2345 die_errno(_("%s: index file open failed"), path);
2348 if (fstat(fd, &st))
2349 die_errno(_("%s: cannot stat the open index"), path);
2351 mmap_size = xsize_t(st.st_size);
2352 if (mmap_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2353 die(_("%s: index file smaller than expected"), path);
2355 mmap = xmmap_gently(NULL, mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
2356 if (mmap == MAP_FAILED)
2357 die_errno(_("%s: unable to map index file%s"), path,
2358 mmap_os_err());
2359 close(fd);
2361 hdr = (const struct cache_header *)mmap;
2362 if (verify_hdr(hdr, mmap_size) < 0)
2363 goto unmap;
2365 oidread(&istate->oid, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
2366 istate->version = ntohl(hdr->hdr_version);
2367 istate->cache_nr = ntohl(hdr->hdr_entries);
2368 istate->cache_alloc = alloc_nr(istate->cache_nr);
2369 CALLOC_ARRAY(istate->cache, istate->cache_alloc);
2370 istate->initialized = 1;
2372 p.istate = istate;
2373 p.mmap = mmap;
2374 p.mmap_size = mmap_size;
2376 src_offset = sizeof(*hdr);
2378 if (git_config_get_index_threads(&nr_threads))
2379 nr_threads = 1;
2381 /* TODO: does creating more threads than cores help? */
2382 if (!nr_threads) {
2383 nr_threads = istate->cache_nr / THREAD_COST;
2384 cpus = online_cpus();
2385 if (nr_threads > cpus)
2386 nr_threads = cpus;
2389 if (!HAVE_THREADS)
2390 nr_threads = 1;
2392 if (nr_threads > 1) {
2393 extension_offset = read_eoie_extension(mmap, mmap_size);
2394 if (extension_offset) {
2395 int err;
2397 p.src_offset = extension_offset;
2398 err = pthread_create(&p.pthread, NULL, load_index_extensions, &p);
2399 if (err)
2400 die(_("unable to create load_index_extensions thread: %s"), strerror(err));
2402 nr_threads--;
2407 * Locate and read the index entry offset table so that we can use it
2408 * to multi-thread the reading of the cache entries.
2410 if (extension_offset && nr_threads > 1)
2411 ieot = read_ieot_extension(mmap, mmap_size, extension_offset);
2413 if (ieot) {
2414 src_offset += load_cache_entries_threaded(istate, mmap, mmap_size, nr_threads, ieot);
2415 free(ieot);
2416 } else {
2417 src_offset += load_all_cache_entries(istate, mmap, mmap_size, src_offset);
2420 istate->timestamp.sec = st.st_mtime;
2421 istate->timestamp.nsec = ST_MTIME_NSEC(st);
2423 /* if we created a thread, join it otherwise load the extensions on the primary thread */
2424 if (extension_offset) {
2425 int ret = pthread_join(p.pthread, NULL);
2426 if (ret)
2427 die(_("unable to join load_index_extensions thread: %s"), strerror(ret));
2428 } else {
2429 p.src_offset = src_offset;
2430 load_index_extensions(&p);
2432 munmap((void *)mmap, mmap_size);
2435 * TODO trace2: replace "the_repository" with the actual repo instance
2436 * that is associated with the given "istate".
2438 trace2_data_intmax("index", the_repository, "read/version",
2439 istate->version);
2440 trace2_data_intmax("index", the_repository, "read/cache_nr",
2441 istate->cache_nr);
2444 * If the command explicitly requires a full index, force it
2445 * to be full. Otherwise, correct the sparsity based on repository
2446 * settings and other properties of the index (if necessary).
2448 prepare_repo_settings(istate->repo);
2449 if (istate->repo->settings.command_requires_full_index)
2450 ensure_full_index(istate);
2451 else
2452 ensure_correct_sparsity(istate);
2454 return istate->cache_nr;
2456 unmap:
2457 munmap((void *)mmap, mmap_size);
2458 die(_("index file corrupt"));
2462 * Signal that the shared index is used by updating its mtime.
2464 * This way, shared index can be removed if they have not been used
2465 * for some time.
2467 static void freshen_shared_index(const char *shared_index, int warn)
2469 if (!check_and_freshen_file(shared_index, 1) && warn)
2470 warning(_("could not freshen shared index '%s'"), shared_index);
2473 int read_index_from(struct index_state *istate, const char *path,
2474 const char *gitdir)
2476 struct split_index *split_index;
2477 int ret;
2478 char *base_oid_hex;
2479 char *base_path;
2481 /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
2482 if (istate->initialized)
2483 return istate->cache_nr;
2486 * TODO trace2: replace "the_repository" with the actual repo instance
2487 * that is associated with the given "istate".
2489 trace2_region_enter_printf("index", "do_read_index", the_repository,
2490 "%s", path);
2491 trace_performance_enter();
2492 ret = do_read_index(istate, path, 0);
2493 trace_performance_leave("read cache %s", path);
2494 trace2_region_leave_printf("index", "do_read_index", the_repository,
2495 "%s", path);
2497 split_index = istate->split_index;
2498 if (!split_index || is_null_oid(&split_index->base_oid)) {
2499 post_read_index_from(istate);
2500 return ret;
2503 trace_performance_enter();
2504 if (split_index->base)
2505 release_index(split_index->base);
2506 else
2507 ALLOC_ARRAY(split_index->base, 1);
2508 index_state_init(split_index->base, istate->repo);
2510 base_oid_hex = oid_to_hex(&split_index->base_oid);
2511 base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
2512 trace2_region_enter_printf("index", "shared/do_read_index",
2513 the_repository, "%s", base_path);
2514 ret = do_read_index(split_index->base, base_path, 0);
2515 trace2_region_leave_printf("index", "shared/do_read_index",
2516 the_repository, "%s", base_path);
2517 if (!ret) {
2518 char *path_copy = xstrdup(path);
2519 char *base_path2 = xstrfmt("%s/sharedindex.%s",
2520 dirname(path_copy), base_oid_hex);
2521 free(path_copy);
2522 trace2_region_enter_printf("index", "shared/do_read_index",
2523 the_repository, "%s", base_path2);
2524 ret = do_read_index(split_index->base, base_path2, 1);
2525 trace2_region_leave_printf("index", "shared/do_read_index",
2526 the_repository, "%s", base_path2);
2527 free(base_path2);
2529 if (!oideq(&split_index->base_oid, &split_index->base->oid))
2530 die(_("broken index, expect %s in %s, got %s"),
2531 base_oid_hex, base_path,
2532 oid_to_hex(&split_index->base->oid));
2534 freshen_shared_index(base_path, 0);
2535 merge_base_index(istate);
2536 post_read_index_from(istate);
2537 trace_performance_leave("read cache %s", base_path);
2538 free(base_path);
2539 return ret;
2542 int is_index_unborn(struct index_state *istate)
2544 return (!istate->cache_nr && !istate->timestamp.sec);
2547 void index_state_init(struct index_state *istate, struct repository *r)
2549 struct index_state blank = INDEX_STATE_INIT(r);
2550 memcpy(istate, &blank, sizeof(*istate));
2553 void release_index(struct index_state *istate)
2556 * Cache entries in istate->cache[] should have been allocated
2557 * from the memory pool associated with this index, or from an
2558 * associated split_index. There is no need to free individual
2559 * cache entries. validate_cache_entries can detect when this
2560 * assertion does not hold.
2562 validate_cache_entries(istate);
2564 resolve_undo_clear_index(istate);
2565 free_name_hash(istate);
2566 cache_tree_free(&(istate->cache_tree));
2567 free(istate->fsmonitor_last_update);
2568 free(istate->cache);
2569 discard_split_index(istate);
2570 free_untracked_cache(istate->untracked);
2572 if (istate->sparse_checkout_patterns) {
2573 clear_pattern_list(istate->sparse_checkout_patterns);
2574 FREE_AND_NULL(istate->sparse_checkout_patterns);
2577 if (istate->ce_mem_pool) {
2578 mem_pool_discard(istate->ce_mem_pool, should_validate_cache_entries());
2579 FREE_AND_NULL(istate->ce_mem_pool);
2583 void discard_index(struct index_state *istate)
2585 release_index(istate);
2586 index_state_init(istate, istate->repo);
2590 * Validate the cache entries of this index.
2591 * All cache entries associated with this index
2592 * should have been allocated by the memory pool
2593 * associated with this index, or by a referenced
2594 * split index.
2596 void validate_cache_entries(const struct index_state *istate)
2598 int i;
2600 if (!should_validate_cache_entries() ||!istate || !istate->initialized)
2601 return;
2603 for (i = 0; i < istate->cache_nr; i++) {
2604 if (!istate) {
2605 BUG("cache entry is not allocated from expected memory pool");
2606 } else if (!istate->ce_mem_pool ||
2607 !mem_pool_contains(istate->ce_mem_pool, istate->cache[i])) {
2608 if (!istate->split_index ||
2609 !istate->split_index->base ||
2610 !istate->split_index->base->ce_mem_pool ||
2611 !mem_pool_contains(istate->split_index->base->ce_mem_pool, istate->cache[i])) {
2612 BUG("cache entry is not allocated from expected memory pool");
2617 if (istate->split_index)
2618 validate_cache_entries(istate->split_index->base);
2621 int unmerged_index(const struct index_state *istate)
2623 int i;
2624 for (i = 0; i < istate->cache_nr; i++) {
2625 if (ce_stage(istate->cache[i]))
2626 return 1;
2628 return 0;
2631 int repo_index_has_changes(struct repository *repo,
2632 struct tree *tree,
2633 struct strbuf *sb)
2635 struct index_state *istate = repo->index;
2636 struct object_id cmp;
2637 int i;
2639 if (tree)
2640 cmp = tree->object.oid;
2641 if (tree || !repo_get_oid_tree(repo, "HEAD", &cmp)) {
2642 struct diff_options opt;
2644 repo_diff_setup(repo, &opt);
2645 opt.flags.exit_with_status = 1;
2646 if (!sb)
2647 opt.flags.quick = 1;
2648 diff_setup_done(&opt);
2649 do_diff_cache(&cmp, &opt);
2650 diffcore_std(&opt);
2651 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
2652 if (i)
2653 strbuf_addch(sb, ' ');
2654 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
2656 diff_flush(&opt);
2657 return opt.flags.has_changes != 0;
2658 } else {
2659 /* TODO: audit for interaction with sparse-index. */
2660 ensure_full_index(istate);
2661 for (i = 0; sb && i < istate->cache_nr; i++) {
2662 if (i)
2663 strbuf_addch(sb, ' ');
2664 strbuf_addstr(sb, istate->cache[i]->name);
2666 return !!istate->cache_nr;
2670 static int write_index_ext_header(struct hashfile *f,
2671 git_hash_ctx *eoie_f,
2672 unsigned int ext,
2673 unsigned int sz)
2675 hashwrite_be32(f, ext);
2676 hashwrite_be32(f, sz);
2678 if (eoie_f) {
2679 ext = htonl(ext);
2680 sz = htonl(sz);
2681 the_hash_algo->update_fn(eoie_f, &ext, sizeof(ext));
2682 the_hash_algo->update_fn(eoie_f, &sz, sizeof(sz));
2684 return 0;
2687 static void ce_smudge_racily_clean_entry(struct index_state *istate,
2688 struct cache_entry *ce)
2691 * The only thing we care about in this function is to smudge the
2692 * falsely clean entry due to touch-update-touch race, so we leave
2693 * everything else as they are. We are called for entries whose
2694 * ce_stat_data.sd_mtime match the index file mtime.
2696 * Note that this actually does not do much for gitlinks, for
2697 * which ce_match_stat_basic() always goes to the actual
2698 * contents. The caller checks with is_racy_timestamp() which
2699 * always says "no" for gitlinks, so we are not called for them ;-)
2701 struct stat st;
2703 if (lstat(ce->name, &st) < 0)
2704 return;
2705 if (ce_match_stat_basic(ce, &st))
2706 return;
2707 if (ce_modified_check_fs(istate, ce, &st)) {
2708 /* This is "racily clean"; smudge it. Note that this
2709 * is a tricky code. At first glance, it may appear
2710 * that it can break with this sequence:
2712 * $ echo xyzzy >frotz
2713 * $ git-update-index --add frotz
2714 * $ : >frotz
2715 * $ sleep 3
2716 * $ echo filfre >nitfol
2717 * $ git-update-index --add nitfol
2719 * but it does not. When the second update-index runs,
2720 * it notices that the entry "frotz" has the same timestamp
2721 * as index, and if we were to smudge it by resetting its
2722 * size to zero here, then the object name recorded
2723 * in index is the 6-byte file but the cached stat information
2724 * becomes zero --- which would then match what we would
2725 * obtain from the filesystem next time we stat("frotz").
2727 * However, the second update-index, before calling
2728 * this function, notices that the cached size is 6
2729 * bytes and what is on the filesystem is an empty
2730 * file, and never calls us, so the cached size information
2731 * for "frotz" stays 6 which does not match the filesystem.
2733 ce->ce_stat_data.sd_size = 0;
2737 /* Copy miscellaneous fields but not the name */
2738 static void copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
2739 struct cache_entry *ce)
2741 short flags;
2742 const unsigned hashsz = the_hash_algo->rawsz;
2743 uint16_t *flagsp = (uint16_t *)(ondisk->data + hashsz);
2745 ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
2746 ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
2747 ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
2748 ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
2749 ondisk->dev = htonl(ce->ce_stat_data.sd_dev);
2750 ondisk->ino = htonl(ce->ce_stat_data.sd_ino);
2751 ondisk->mode = htonl(ce->ce_mode);
2752 ondisk->uid = htonl(ce->ce_stat_data.sd_uid);
2753 ondisk->gid = htonl(ce->ce_stat_data.sd_gid);
2754 ondisk->size = htonl(ce->ce_stat_data.sd_size);
2755 hashcpy(ondisk->data, ce->oid.hash);
2757 flags = ce->ce_flags & ~CE_NAMEMASK;
2758 flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
2759 flagsp[0] = htons(flags);
2760 if (ce->ce_flags & CE_EXTENDED) {
2761 flagsp[1] = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
2765 static int ce_write_entry(struct hashfile *f, struct cache_entry *ce,
2766 struct strbuf *previous_name, struct ondisk_cache_entry *ondisk)
2768 int size;
2769 unsigned int saved_namelen;
2770 int stripped_name = 0;
2771 static unsigned char padding[8] = { 0x00 };
2773 if (ce->ce_flags & CE_STRIP_NAME) {
2774 saved_namelen = ce_namelen(ce);
2775 ce->ce_namelen = 0;
2776 stripped_name = 1;
2779 size = offsetof(struct ondisk_cache_entry,data) + ondisk_data_size(ce->ce_flags, 0);
2781 if (!previous_name) {
2782 int len = ce_namelen(ce);
2783 copy_cache_entry_to_ondisk(ondisk, ce);
2784 hashwrite(f, ondisk, size);
2785 hashwrite(f, ce->name, len);
2786 hashwrite(f, padding, align_padding_size(size, len));
2787 } else {
2788 int common, to_remove, prefix_size;
2789 unsigned char to_remove_vi[16];
2790 for (common = 0;
2791 (ce->name[common] &&
2792 common < previous_name->len &&
2793 ce->name[common] == previous_name->buf[common]);
2794 common++)
2795 ; /* still matching */
2796 to_remove = previous_name->len - common;
2797 prefix_size = encode_varint(to_remove, to_remove_vi);
2799 copy_cache_entry_to_ondisk(ondisk, ce);
2800 hashwrite(f, ondisk, size);
2801 hashwrite(f, to_remove_vi, prefix_size);
2802 hashwrite(f, ce->name + common, ce_namelen(ce) - common);
2803 hashwrite(f, padding, 1);
2805 strbuf_splice(previous_name, common, to_remove,
2806 ce->name + common, ce_namelen(ce) - common);
2808 if (stripped_name) {
2809 ce->ce_namelen = saved_namelen;
2810 ce->ce_flags &= ~CE_STRIP_NAME;
2813 return 0;
2817 * This function verifies if index_state has the correct sha1 of the
2818 * index file. Don't die if we have any other failure, just return 0.
2820 static int verify_index_from(const struct index_state *istate, const char *path)
2822 int fd;
2823 ssize_t n;
2824 struct stat st;
2825 unsigned char hash[GIT_MAX_RAWSZ];
2827 if (!istate->initialized)
2828 return 0;
2830 fd = open(path, O_RDONLY);
2831 if (fd < 0)
2832 return 0;
2834 if (fstat(fd, &st))
2835 goto out;
2837 if (st.st_size < sizeof(struct cache_header) + the_hash_algo->rawsz)
2838 goto out;
2840 n = pread_in_full(fd, hash, the_hash_algo->rawsz, st.st_size - the_hash_algo->rawsz);
2841 if (n != the_hash_algo->rawsz)
2842 goto out;
2844 if (!hasheq(istate->oid.hash, hash))
2845 goto out;
2847 close(fd);
2848 return 1;
2850 out:
2851 close(fd);
2852 return 0;
2855 static int repo_verify_index(struct repository *repo)
2857 return verify_index_from(repo->index, repo->index_file);
2860 int has_racy_timestamp(struct index_state *istate)
2862 int entries = istate->cache_nr;
2863 int i;
2865 for (i = 0; i < entries; i++) {
2866 struct cache_entry *ce = istate->cache[i];
2867 if (is_racy_timestamp(istate, ce))
2868 return 1;
2870 return 0;
2873 void repo_update_index_if_able(struct repository *repo,
2874 struct lock_file *lockfile)
2876 if ((repo->index->cache_changed ||
2877 has_racy_timestamp(repo->index)) &&
2878 repo_verify_index(repo))
2879 write_locked_index(repo->index, lockfile, COMMIT_LOCK);
2880 else
2881 rollback_lock_file(lockfile);
2884 static int record_eoie(void)
2886 int val;
2888 if (!git_config_get_bool("index.recordendofindexentries", &val))
2889 return val;
2892 * As a convenience, the end of index entries extension
2893 * used for threading is written by default if the user
2894 * explicitly requested threaded index reads.
2896 return !git_config_get_index_threads(&val) && val != 1;
2899 static int record_ieot(void)
2901 int val;
2903 if (!git_config_get_bool("index.recordoffsettable", &val))
2904 return val;
2907 * As a convenience, the offset table used for threading is
2908 * written by default if the user explicitly requested
2909 * threaded index reads.
2911 return !git_config_get_index_threads(&val) && val != 1;
2915 * On success, `tempfile` is closed. If it is the temporary file
2916 * of a `struct lock_file`, we will therefore effectively perform
2917 * a 'close_lock_file_gently()`. Since that is an implementation
2918 * detail of lockfiles, callers of `do_write_index()` should not
2919 * rely on it.
2921 static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
2922 int strip_extensions, unsigned flags)
2924 uint64_t start = getnanotime();
2925 struct hashfile *f;
2926 git_hash_ctx *eoie_c = NULL;
2927 struct cache_header hdr;
2928 int i, err = 0, removed, extended, hdr_version;
2929 struct cache_entry **cache = istate->cache;
2930 int entries = istate->cache_nr;
2931 struct stat st;
2932 struct ondisk_cache_entry ondisk;
2933 struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
2934 int drop_cache_tree = istate->drop_cache_tree;
2935 off_t offset;
2936 int csum_fsync_flag;
2937 int ieot_entries = 1;
2938 struct index_entry_offset_table *ieot = NULL;
2939 int nr, nr_threads;
2940 struct repository *r = istate->repo;
2942 f = hashfd(tempfile->fd, tempfile->filename.buf);
2944 prepare_repo_settings(r);
2945 f->skip_hash = r->settings.index_skip_hash;
2947 for (i = removed = extended = 0; i < entries; i++) {
2948 if (cache[i]->ce_flags & CE_REMOVE)
2949 removed++;
2951 /* reduce extended entries if possible */
2952 cache[i]->ce_flags &= ~CE_EXTENDED;
2953 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
2954 extended++;
2955 cache[i]->ce_flags |= CE_EXTENDED;
2959 if (!istate->version)
2960 istate->version = get_index_format_default(r);
2962 /* demote version 3 to version 2 when the latter suffices */
2963 if (istate->version == 3 || istate->version == 2)
2964 istate->version = extended ? 3 : 2;
2966 hdr_version = istate->version;
2968 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
2969 hdr.hdr_version = htonl(hdr_version);
2970 hdr.hdr_entries = htonl(entries - removed);
2972 hashwrite(f, &hdr, sizeof(hdr));
2974 if (!HAVE_THREADS || git_config_get_index_threads(&nr_threads))
2975 nr_threads = 1;
2977 if (nr_threads != 1 && record_ieot()) {
2978 int ieot_blocks, cpus;
2981 * ensure default number of ieot blocks maps evenly to the
2982 * default number of threads that will process them leaving
2983 * room for the thread to load the index extensions.
2985 if (!nr_threads) {
2986 ieot_blocks = istate->cache_nr / THREAD_COST;
2987 cpus = online_cpus();
2988 if (ieot_blocks > cpus - 1)
2989 ieot_blocks = cpus - 1;
2990 } else {
2991 ieot_blocks = nr_threads;
2992 if (ieot_blocks > istate->cache_nr)
2993 ieot_blocks = istate->cache_nr;
2997 * no reason to write out the IEOT extension if we don't
2998 * have enough blocks to utilize multi-threading
3000 if (ieot_blocks > 1) {
3001 ieot = xcalloc(1, sizeof(struct index_entry_offset_table)
3002 + (ieot_blocks * sizeof(struct index_entry_offset)));
3003 ieot_entries = DIV_ROUND_UP(entries, ieot_blocks);
3007 offset = hashfile_total(f);
3009 nr = 0;
3010 previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
3012 for (i = 0; i < entries; i++) {
3013 struct cache_entry *ce = cache[i];
3014 if (ce->ce_flags & CE_REMOVE)
3015 continue;
3016 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
3017 ce_smudge_racily_clean_entry(istate, ce);
3018 if (is_null_oid(&ce->oid)) {
3019 static const char msg[] = "cache entry has null sha1: %s";
3020 static int allow = -1;
3022 if (allow < 0)
3023 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
3024 if (allow)
3025 warning(msg, ce->name);
3026 else
3027 err = error(msg, ce->name);
3029 drop_cache_tree = 1;
3031 if (ieot && i && (i % ieot_entries == 0)) {
3032 ieot->entries[ieot->nr].nr = nr;
3033 ieot->entries[ieot->nr].offset = offset;
3034 ieot->nr++;
3036 * If we have a V4 index, set the first byte to an invalid
3037 * character to ensure there is nothing common with the previous
3038 * entry
3040 if (previous_name)
3041 previous_name->buf[0] = 0;
3042 nr = 0;
3044 offset = hashfile_total(f);
3046 if (ce_write_entry(f, ce, previous_name, (struct ondisk_cache_entry *)&ondisk) < 0)
3047 err = -1;
3049 if (err)
3050 break;
3051 nr++;
3053 if (ieot && nr) {
3054 ieot->entries[ieot->nr].nr = nr;
3055 ieot->entries[ieot->nr].offset = offset;
3056 ieot->nr++;
3058 strbuf_release(&previous_name_buf);
3060 if (err) {
3061 free(ieot);
3062 return err;
3065 offset = hashfile_total(f);
3068 * The extension headers must be hashed on their own for the
3069 * EOIE extension. Create a hashfile here to compute that hash.
3071 if (offset && record_eoie()) {
3072 CALLOC_ARRAY(eoie_c, 1);
3073 the_hash_algo->init_fn(eoie_c);
3077 * Lets write out CACHE_EXT_INDEXENTRYOFFSETTABLE first so that we
3078 * can minimize the number of extensions we have to scan through to
3079 * find it during load. Write it out regardless of the
3080 * strip_extensions parameter as we need it when loading the shared
3081 * index.
3083 if (ieot) {
3084 struct strbuf sb = STRBUF_INIT;
3086 write_ieot_extension(&sb, ieot);
3087 err = write_index_ext_header(f, eoie_c, CACHE_EXT_INDEXENTRYOFFSETTABLE, sb.len) < 0;
3088 hashwrite(f, sb.buf, sb.len);
3089 strbuf_release(&sb);
3090 free(ieot);
3091 if (err)
3092 return -1;
3095 if (!strip_extensions && istate->split_index &&
3096 !is_null_oid(&istate->split_index->base_oid)) {
3097 struct strbuf sb = STRBUF_INIT;
3099 if (istate->sparse_index)
3100 die(_("cannot write split index for a sparse index"));
3102 err = write_link_extension(&sb, istate) < 0 ||
3103 write_index_ext_header(f, eoie_c, CACHE_EXT_LINK,
3104 sb.len) < 0;
3105 hashwrite(f, sb.buf, sb.len);
3106 strbuf_release(&sb);
3107 if (err)
3108 return -1;
3110 if (!strip_extensions && !drop_cache_tree && istate->cache_tree) {
3111 struct strbuf sb = STRBUF_INIT;
3113 cache_tree_write(&sb, istate->cache_tree);
3114 err = write_index_ext_header(f, eoie_c, CACHE_EXT_TREE, sb.len) < 0;
3115 hashwrite(f, sb.buf, sb.len);
3116 strbuf_release(&sb);
3117 if (err)
3118 return -1;
3120 if (!strip_extensions && istate->resolve_undo) {
3121 struct strbuf sb = STRBUF_INIT;
3123 resolve_undo_write(&sb, istate->resolve_undo);
3124 err = write_index_ext_header(f, eoie_c, CACHE_EXT_RESOLVE_UNDO,
3125 sb.len) < 0;
3126 hashwrite(f, sb.buf, sb.len);
3127 strbuf_release(&sb);
3128 if (err)
3129 return -1;
3131 if (!strip_extensions && istate->untracked) {
3132 struct strbuf sb = STRBUF_INIT;
3134 write_untracked_extension(&sb, istate->untracked);
3135 err = write_index_ext_header(f, eoie_c, CACHE_EXT_UNTRACKED,
3136 sb.len) < 0;
3137 hashwrite(f, sb.buf, sb.len);
3138 strbuf_release(&sb);
3139 if (err)
3140 return -1;
3142 if (!strip_extensions && istate->fsmonitor_last_update) {
3143 struct strbuf sb = STRBUF_INIT;
3145 write_fsmonitor_extension(&sb, istate);
3146 err = write_index_ext_header(f, eoie_c, CACHE_EXT_FSMONITOR, sb.len) < 0;
3147 hashwrite(f, sb.buf, sb.len);
3148 strbuf_release(&sb);
3149 if (err)
3150 return -1;
3152 if (istate->sparse_index) {
3153 if (write_index_ext_header(f, eoie_c, CACHE_EXT_SPARSE_DIRECTORIES, 0) < 0)
3154 return -1;
3158 * CACHE_EXT_ENDOFINDEXENTRIES must be written as the last entry before the SHA1
3159 * so that it can be found and processed before all the index entries are
3160 * read. Write it out regardless of the strip_extensions parameter as we need it
3161 * when loading the shared index.
3163 if (eoie_c) {
3164 struct strbuf sb = STRBUF_INIT;
3166 write_eoie_extension(&sb, eoie_c, offset);
3167 err = write_index_ext_header(f, NULL, CACHE_EXT_ENDOFINDEXENTRIES, sb.len) < 0;
3168 hashwrite(f, sb.buf, sb.len);
3169 strbuf_release(&sb);
3170 if (err)
3171 return -1;
3174 csum_fsync_flag = 0;
3175 if (!alternate_index_output && (flags & COMMIT_LOCK))
3176 csum_fsync_flag = CSUM_FSYNC;
3178 finalize_hashfile(f, istate->oid.hash, FSYNC_COMPONENT_INDEX,
3179 CSUM_HASH_IN_STREAM | csum_fsync_flag);
3181 if (close_tempfile_gently(tempfile)) {
3182 error(_("could not close '%s'"), get_tempfile_path(tempfile));
3183 return -1;
3185 if (stat(get_tempfile_path(tempfile), &st))
3186 return -1;
3187 istate->timestamp.sec = (unsigned int)st.st_mtime;
3188 istate->timestamp.nsec = ST_MTIME_NSEC(st);
3189 trace_performance_since(start, "write index, changed mask = %x", istate->cache_changed);
3192 * TODO trace2: replace "the_repository" with the actual repo instance
3193 * that is associated with the given "istate".
3195 trace2_data_intmax("index", the_repository, "write/version",
3196 istate->version);
3197 trace2_data_intmax("index", the_repository, "write/cache_nr",
3198 istate->cache_nr);
3200 return 0;
3203 void set_alternate_index_output(const char *name)
3205 alternate_index_output = name;
3208 static int commit_locked_index(struct lock_file *lk)
3210 if (alternate_index_output)
3211 return commit_lock_file_to(lk, alternate_index_output);
3212 else
3213 return commit_lock_file(lk);
3216 static int do_write_locked_index(struct index_state *istate, struct lock_file *lock,
3217 unsigned flags)
3219 int ret;
3220 int was_full = istate->sparse_index == INDEX_EXPANDED;
3222 ret = convert_to_sparse(istate, 0);
3224 if (ret) {
3225 warning(_("failed to convert to a sparse-index"));
3226 return ret;
3230 * TODO trace2: replace "the_repository" with the actual repo instance
3231 * that is associated with the given "istate".
3233 trace2_region_enter_printf("index", "do_write_index", the_repository,
3234 "%s", get_lock_file_path(lock));
3235 ret = do_write_index(istate, lock->tempfile, 0, flags);
3236 trace2_region_leave_printf("index", "do_write_index", the_repository,
3237 "%s", get_lock_file_path(lock));
3239 if (was_full)
3240 ensure_full_index(istate);
3242 if (ret)
3243 return ret;
3244 if (flags & COMMIT_LOCK)
3245 ret = commit_locked_index(lock);
3246 else
3247 ret = close_lock_file_gently(lock);
3249 run_hooks_l("post-index-change",
3250 istate->updated_workdir ? "1" : "0",
3251 istate->updated_skipworktree ? "1" : "0", NULL);
3252 istate->updated_workdir = 0;
3253 istate->updated_skipworktree = 0;
3255 return ret;
3258 static int write_split_index(struct index_state *istate,
3259 struct lock_file *lock,
3260 unsigned flags)
3262 int ret;
3263 prepare_to_write_split_index(istate);
3264 ret = do_write_locked_index(istate, lock, flags);
3265 finish_writing_split_index(istate);
3266 return ret;
3269 static const char *shared_index_expire = "2.weeks.ago";
3271 static unsigned long get_shared_index_expire_date(void)
3273 static unsigned long shared_index_expire_date;
3274 static int shared_index_expire_date_prepared;
3276 if (!shared_index_expire_date_prepared) {
3277 git_config_get_expiry("splitindex.sharedindexexpire",
3278 &shared_index_expire);
3279 shared_index_expire_date = approxidate(shared_index_expire);
3280 shared_index_expire_date_prepared = 1;
3283 return shared_index_expire_date;
3286 static int should_delete_shared_index(const char *shared_index_path)
3288 struct stat st;
3289 unsigned long expiration;
3291 /* Check timestamp */
3292 expiration = get_shared_index_expire_date();
3293 if (!expiration)
3294 return 0;
3295 if (stat(shared_index_path, &st))
3296 return error_errno(_("could not stat '%s'"), shared_index_path);
3297 if (st.st_mtime > expiration)
3298 return 0;
3300 return 1;
3303 static int clean_shared_index_files(const char *current_hex)
3305 struct dirent *de;
3306 DIR *dir = opendir(get_git_dir());
3308 if (!dir)
3309 return error_errno(_("unable to open git dir: %s"), get_git_dir());
3311 while ((de = readdir(dir)) != NULL) {
3312 const char *sha1_hex;
3313 const char *shared_index_path;
3314 if (!skip_prefix(de->d_name, "sharedindex.", &sha1_hex))
3315 continue;
3316 if (!strcmp(sha1_hex, current_hex))
3317 continue;
3318 shared_index_path = git_path("%s", de->d_name);
3319 if (should_delete_shared_index(shared_index_path) > 0 &&
3320 unlink(shared_index_path))
3321 warning_errno(_("unable to unlink: %s"), shared_index_path);
3323 closedir(dir);
3325 return 0;
3328 static int write_shared_index(struct index_state *istate,
3329 struct tempfile **temp, unsigned flags)
3331 struct split_index *si = istate->split_index;
3332 int ret, was_full = !istate->sparse_index;
3334 move_cache_to_base_index(istate);
3335 convert_to_sparse(istate, 0);
3337 trace2_region_enter_printf("index", "shared/do_write_index",
3338 the_repository, "%s", get_tempfile_path(*temp));
3339 ret = do_write_index(si->base, *temp, 1, flags);
3340 trace2_region_leave_printf("index", "shared/do_write_index",
3341 the_repository, "%s", get_tempfile_path(*temp));
3343 if (was_full)
3344 ensure_full_index(istate);
3346 if (ret)
3347 return ret;
3348 ret = adjust_shared_perm(get_tempfile_path(*temp));
3349 if (ret) {
3350 error(_("cannot fix permission bits on '%s'"), get_tempfile_path(*temp));
3351 return ret;
3353 ret = rename_tempfile(temp,
3354 git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
3355 if (!ret) {
3356 oidcpy(&si->base_oid, &si->base->oid);
3357 clean_shared_index_files(oid_to_hex(&si->base->oid));
3360 return ret;
3363 static const int default_max_percent_split_change = 20;
3365 static int too_many_not_shared_entries(struct index_state *istate)
3367 int i, not_shared = 0;
3368 int max_split = git_config_get_max_percent_split_change();
3370 switch (max_split) {
3371 case -1:
3372 /* not or badly configured: use the default value */
3373 max_split = default_max_percent_split_change;
3374 break;
3375 case 0:
3376 return 1; /* 0% means always write a new shared index */
3377 case 100:
3378 return 0; /* 100% means never write a new shared index */
3379 default:
3380 break; /* just use the configured value */
3383 /* Count not shared entries */
3384 for (i = 0; i < istate->cache_nr; i++) {
3385 struct cache_entry *ce = istate->cache[i];
3386 if (!ce->index)
3387 not_shared++;
3390 return (int64_t)istate->cache_nr * max_split < (int64_t)not_shared * 100;
3393 int write_locked_index(struct index_state *istate, struct lock_file *lock,
3394 unsigned flags)
3396 int new_shared_index, ret, test_split_index_env;
3397 struct split_index *si = istate->split_index;
3399 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
3400 cache_tree_verify(the_repository, istate);
3402 if ((flags & SKIP_IF_UNCHANGED) && !istate->cache_changed) {
3403 if (flags & COMMIT_LOCK)
3404 rollback_lock_file(lock);
3405 return 0;
3408 if (istate->fsmonitor_last_update)
3409 fill_fsmonitor_bitmap(istate);
3411 test_split_index_env = git_env_bool("GIT_TEST_SPLIT_INDEX", 0);
3413 if ((!si && !test_split_index_env) ||
3414 alternate_index_output ||
3415 (istate->cache_changed & ~EXTMASK)) {
3416 if (si)
3417 oidclr(&si->base_oid);
3418 ret = do_write_locked_index(istate, lock, flags);
3419 goto out;
3422 if (test_split_index_env) {
3423 if (!si) {
3424 si = init_split_index(istate);
3425 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3426 } else {
3427 int v = si->base_oid.hash[0];
3428 if ((v & 15) < 6)
3429 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3432 if (too_many_not_shared_entries(istate))
3433 istate->cache_changed |= SPLIT_INDEX_ORDERED;
3435 new_shared_index = istate->cache_changed & SPLIT_INDEX_ORDERED;
3437 if (new_shared_index) {
3438 struct tempfile *temp;
3439 int saved_errno;
3441 /* Same initial permissions as the main .git/index file */
3442 temp = mks_tempfile_sm(git_path("sharedindex_XXXXXX"), 0, 0666);
3443 if (!temp) {
3444 oidclr(&si->base_oid);
3445 ret = do_write_locked_index(istate, lock, flags);
3446 goto out;
3448 ret = write_shared_index(istate, &temp, flags);
3450 saved_errno = errno;
3451 if (is_tempfile_active(temp))
3452 delete_tempfile(&temp);
3453 errno = saved_errno;
3455 if (ret)
3456 goto out;
3459 ret = write_split_index(istate, lock, flags);
3461 /* Freshen the shared index only if the split-index was written */
3462 if (!ret && !new_shared_index && !is_null_oid(&si->base_oid)) {
3463 const char *shared_index = git_path("sharedindex.%s",
3464 oid_to_hex(&si->base_oid));
3465 freshen_shared_index(shared_index, 1);
3468 out:
3469 if (flags & COMMIT_LOCK)
3470 rollback_lock_file(lock);
3471 return ret;
3475 * Read the index file that is potentially unmerged into given
3476 * index_state, dropping any unmerged entries to stage #0 (potentially
3477 * resulting in a path appearing as both a file and a directory in the
3478 * index; the caller is responsible to clear out the extra entries
3479 * before writing the index to a tree). Returns true if the index is
3480 * unmerged. Callers who want to refuse to work from an unmerged
3481 * state can call this and check its return value, instead of calling
3482 * read_cache().
3484 int repo_read_index_unmerged(struct repository *repo)
3486 struct index_state *istate;
3487 int i;
3488 int unmerged = 0;
3490 repo_read_index(repo);
3491 istate = repo->index;
3492 for (i = 0; i < istate->cache_nr; i++) {
3493 struct cache_entry *ce = istate->cache[i];
3494 struct cache_entry *new_ce;
3495 int len;
3497 if (!ce_stage(ce))
3498 continue;
3499 unmerged = 1;
3500 len = ce_namelen(ce);
3501 new_ce = make_empty_cache_entry(istate, len);
3502 memcpy(new_ce->name, ce->name, len);
3503 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3504 new_ce->ce_namelen = len;
3505 new_ce->ce_mode = ce->ce_mode;
3506 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3507 return error(_("%s: cannot drop to stage #0"),
3508 new_ce->name);
3510 return unmerged;
3514 * Returns 1 if the path is an "other" path with respect to
3515 * the index; that is, the path is not mentioned in the index at all,
3516 * either as a file, a directory with some files in the index,
3517 * or as an unmerged entry.
3519 * We helpfully remove a trailing "/" from directories so that
3520 * the output of read_directory can be used as-is.
3522 int index_name_is_other(struct index_state *istate, const char *name,
3523 int namelen)
3525 int pos;
3526 if (namelen && name[namelen - 1] == '/')
3527 namelen--;
3528 pos = index_name_pos(istate, name, namelen);
3529 if (0 <= pos)
3530 return 0; /* exact match */
3531 pos = -pos - 1;
3532 if (pos < istate->cache_nr) {
3533 struct cache_entry *ce = istate->cache[pos];
3534 if (ce_namelen(ce) == namelen &&
3535 !memcmp(ce->name, name, namelen))
3536 return 0; /* Yup, this one exists unmerged */
3538 return 1;
3541 void *read_blob_data_from_index(struct index_state *istate,
3542 const char *path, unsigned long *size)
3544 int pos, len;
3545 unsigned long sz;
3546 enum object_type type;
3547 void *data;
3549 len = strlen(path);
3550 pos = index_name_pos(istate, path, len);
3551 if (pos < 0) {
3553 * We might be in the middle of a merge, in which
3554 * case we would read stage #2 (ours).
3556 int i;
3557 for (i = -pos - 1;
3558 (pos < 0 && i < istate->cache_nr &&
3559 !strcmp(istate->cache[i]->name, path));
3560 i++)
3561 if (ce_stage(istate->cache[i]) == 2)
3562 pos = i;
3564 if (pos < 0)
3565 return NULL;
3566 data = repo_read_object_file(the_repository, &istate->cache[pos]->oid,
3567 &type, &sz);
3568 if (!data || type != OBJ_BLOB) {
3569 free(data);
3570 return NULL;
3572 if (size)
3573 *size = sz;
3574 return data;
3577 void stat_validity_clear(struct stat_validity *sv)
3579 FREE_AND_NULL(sv->sd);
3582 int stat_validity_check(struct stat_validity *sv, const char *path)
3584 struct stat st;
3586 if (stat(path, &st) < 0)
3587 return sv->sd == NULL;
3588 if (!sv->sd)
3589 return 0;
3590 return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
3593 void stat_validity_update(struct stat_validity *sv, int fd)
3595 struct stat st;
3597 if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
3598 stat_validity_clear(sv);
3599 else {
3600 if (!sv->sd)
3601 CALLOC_ARRAY(sv->sd, 1);
3602 fill_stat_data(sv->sd, &st);
3606 void move_index_extensions(struct index_state *dst, struct index_state *src)
3608 dst->untracked = src->untracked;
3609 src->untracked = NULL;
3610 dst->cache_tree = src->cache_tree;
3611 src->cache_tree = NULL;
3614 struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3615 struct index_state *istate)
3617 unsigned int size = ce_size(ce);
3618 int mem_pool_allocated;
3619 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3620 mem_pool_allocated = new_entry->mem_pool_allocated;
3622 memcpy(new_entry, ce, size);
3623 new_entry->mem_pool_allocated = mem_pool_allocated;
3624 return new_entry;
3627 void discard_cache_entry(struct cache_entry *ce)
3629 if (ce && should_validate_cache_entries())
3630 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3632 if (ce && ce->mem_pool_allocated)
3633 return;
3635 free(ce);
3638 int should_validate_cache_entries(void)
3640 static int validate_index_cache_entries = -1;
3642 if (validate_index_cache_entries < 0) {
3643 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3644 validate_index_cache_entries = 1;
3645 else
3646 validate_index_cache_entries = 0;
3649 return validate_index_cache_entries;
3652 #define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3653 #define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3655 static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3658 * The end of index entries (EOIE) extension is guaranteed to be last
3659 * so that it can be found by scanning backwards from the EOF.
3661 * "EOIE"
3662 * <4-byte length>
3663 * <4-byte offset>
3664 * <20-byte hash>
3666 const char *index, *eoie;
3667 uint32_t extsize;
3668 size_t offset, src_offset;
3669 unsigned char hash[GIT_MAX_RAWSZ];
3670 git_hash_ctx c;
3672 /* ensure we have an index big enough to contain an EOIE extension */
3673 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3674 return 0;
3676 /* validate the extension signature */
3677 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3678 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3679 return 0;
3680 index += sizeof(uint32_t);
3682 /* validate the extension size */
3683 extsize = get_be32(index);
3684 if (extsize != EOIE_SIZE)
3685 return 0;
3686 index += sizeof(uint32_t);
3689 * Validate the offset we're going to look for the first extension
3690 * signature is after the index header and before the eoie extension.
3692 offset = get_be32(index);
3693 if (mmap + offset < mmap + sizeof(struct cache_header))
3694 return 0;
3695 if (mmap + offset >= eoie)
3696 return 0;
3697 index += sizeof(uint32_t);
3700 * The hash is computed over extension types and their sizes (but not
3701 * their contents). E.g. if we have "TREE" extension that is N-bytes
3702 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3703 * then the hash would be:
3705 * SHA-1("TREE" + <binary representation of N> +
3706 * "REUC" + <binary representation of M>)
3708 src_offset = offset;
3709 the_hash_algo->init_fn(&c);
3710 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3711 /* After an array of active_nr index entries,
3712 * there can be arbitrary number of extended
3713 * sections, each of which is prefixed with
3714 * extension name (4-byte) and section length
3715 * in 4-byte network byte order.
3717 uint32_t extsize;
3718 memcpy(&extsize, mmap + src_offset + 4, 4);
3719 extsize = ntohl(extsize);
3721 /* verify the extension size isn't so large it will wrap around */
3722 if (src_offset + 8 + extsize < src_offset)
3723 return 0;
3725 the_hash_algo->update_fn(&c, mmap + src_offset, 8);
3727 src_offset += 8;
3728 src_offset += extsize;
3730 the_hash_algo->final_fn(hash, &c);
3731 if (!hasheq(hash, (const unsigned char *)index))
3732 return 0;
3734 /* Validate that the extension offsets returned us back to the eoie extension. */
3735 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3736 return 0;
3738 return offset;
3741 static void write_eoie_extension(struct strbuf *sb, git_hash_ctx *eoie_context, size_t offset)
3743 uint32_t buffer;
3744 unsigned char hash[GIT_MAX_RAWSZ];
3746 /* offset */
3747 put_be32(&buffer, offset);
3748 strbuf_add(sb, &buffer, sizeof(uint32_t));
3750 /* hash */
3751 the_hash_algo->final_fn(hash, eoie_context);
3752 strbuf_add(sb, hash, the_hash_algo->rawsz);
3755 #define IEOT_VERSION (1)
3757 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3759 const char *index = NULL;
3760 uint32_t extsize, ext_version;
3761 struct index_entry_offset_table *ieot;
3762 int i, nr;
3764 /* find the IEOT extension */
3765 if (!offset)
3766 return NULL;
3767 while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3768 extsize = get_be32(mmap + offset + 4);
3769 if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3770 index = mmap + offset + 4 + 4;
3771 break;
3773 offset += 8;
3774 offset += extsize;
3776 if (!index)
3777 return NULL;
3779 /* validate the version is IEOT_VERSION */
3780 ext_version = get_be32(index);
3781 if (ext_version != IEOT_VERSION) {
3782 error("invalid IEOT version %d", ext_version);
3783 return NULL;
3785 index += sizeof(uint32_t);
3787 /* extension size - version bytes / bytes per entry */
3788 nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3789 if (!nr) {
3790 error("invalid number of IEOT entries %d", nr);
3791 return NULL;
3793 ieot = xmalloc(sizeof(struct index_entry_offset_table)
3794 + (nr * sizeof(struct index_entry_offset)));
3795 ieot->nr = nr;
3796 for (i = 0; i < nr; i++) {
3797 ieot->entries[i].offset = get_be32(index);
3798 index += sizeof(uint32_t);
3799 ieot->entries[i].nr = get_be32(index);
3800 index += sizeof(uint32_t);
3803 return ieot;
3806 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3808 uint32_t buffer;
3809 int i;
3811 /* version */
3812 put_be32(&buffer, IEOT_VERSION);
3813 strbuf_add(sb, &buffer, sizeof(uint32_t));
3815 /* ieot */
3816 for (i = 0; i < ieot->nr; i++) {
3818 /* offset */
3819 put_be32(&buffer, ieot->entries[i].offset);
3820 strbuf_add(sb, &buffer, sizeof(uint32_t));
3822 /* count */
3823 put_be32(&buffer, ieot->entries[i].nr);
3824 strbuf_add(sb, &buffer, sizeof(uint32_t));
3828 void prefetch_cache_entries(const struct index_state *istate,
3829 must_prefetch_predicate must_prefetch)
3831 int i;
3832 struct oid_array to_fetch = OID_ARRAY_INIT;
3834 for (i = 0; i < istate->cache_nr; i++) {
3835 struct cache_entry *ce = istate->cache[i];
3837 if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce))
3838 continue;
3839 if (!oid_object_info_extended(the_repository, &ce->oid,
3840 NULL,
3841 OBJECT_INFO_FOR_PREFETCH))
3842 continue;
3843 oid_array_append(&to_fetch, &ce->oid);
3845 promisor_remote_get_direct(the_repository,
3846 to_fetch.oid, to_fetch.nr);
3847 oid_array_clear(&to_fetch);