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