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