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