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