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