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