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