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 extern int trust_executable_bit, has_symlinks;
209
210 switch (ce->ce_mode & S_IFMT) {
211 case S_IFLNK:
212 return has_symlinks ? S_IFLNK : (S_IFREG | 0644);
213 case S_IFREG:
214 return (ce->ce_mode & (trust_executable_bit ? 0755 : 0644)) | S_IFREG;
215 case S_IFGITLINK:
216 return S_IFDIR | 0755;
217 case S_IFDIR:
218 return ce->ce_mode;
219 default:
220 BUG("unsupported ce_mode: %o", ce->ce_mode);
221 }
222 }
223
224 int fake_lstat(const struct cache_entry *ce, struct stat *st)
225 {
226 fake_lstat_data(&ce->ce_stat_data, st);
227 st->st_mode = st_mode_from_ce(ce);
228
229 /* always succeed as lstat() replacement */
230 return 0;
231 }
232
233 static int ce_compare_data(struct index_state *istate,
234 const struct cache_entry *ce,
235 struct stat *st)
236 {
237 int match = -1;
238 int fd = git_open_cloexec(ce->name, O_RDONLY);
239
240 if (fd >= 0) {
241 struct object_id oid;
242 if (!index_fd(istate, &oid, fd, st, OBJ_BLOB, ce->name, 0))
243 match = !oideq(&oid, &ce->oid);
244 /* index_fd() closed the file descriptor already */
245 }
246 return match;
247 }
248
249 static int ce_compare_link(const struct cache_entry *ce, size_t expected_size)
250 {
251 int match = -1;
252 void *buffer;
253 unsigned long size;
254 enum object_type type;
255 struct strbuf sb = STRBUF_INIT;
256
257 if (strbuf_readlink(&sb, ce->name, expected_size))
258 return -1;
259
260 buffer = odb_read_object(the_repository->objects, &ce->oid, &type, &size);
261 if (buffer) {
262 if (size == sb.len)
263 match = memcmp(buffer, sb.buf, size);
264 free(buffer);
265 }
266 strbuf_release(&sb);
267 return match;
268 }
269
270 static int ce_compare_gitlink(const struct cache_entry *ce)
271 {
272 struct object_id oid;
273
274 /*
275 * We don't actually require that the .git directory
276 * under GITLINK directory be a valid git directory. It
277 * might even be missing (in case nobody populated that
278 * sub-project).
279 *
280 * If so, we consider it always to match.
281 */
282 if (repo_resolve_gitlink_ref(the_repository, ce->name,
283 "HEAD", &oid) < 0)
284 return 0;
285 return !oideq(&oid, &ce->oid);
286 }
287
288 static int ce_modified_check_fs(struct index_state *istate,
289 const struct cache_entry *ce,
290 struct stat *st)
291 {
292 switch (st->st_mode & S_IFMT) {
293 case S_IFREG:
294 if (ce_compare_data(istate, ce, st))
295 return DATA_CHANGED;
296 break;
297 case S_IFLNK:
298 if (ce_compare_link(ce, xsize_t(st->st_size)))
299 return DATA_CHANGED;
300 break;
301 case S_IFDIR:
302 if (S_ISGITLINK(ce->ce_mode))
303 return ce_compare_gitlink(ce) ? DATA_CHANGED : 0;
304 /* else fallthrough */
305 default:
306 return TYPE_CHANGED;
307 }
308 return 0;
309 }
310
311 static int ce_match_stat_basic(const struct cache_entry *ce, struct stat *st)
312 {
313 unsigned int changed = 0;
314
315 if (ce->ce_flags & CE_REMOVE)
316 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
317
318 switch (ce->ce_mode & S_IFMT) {
319 case S_IFREG:
320 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
321 /* We consider only the owner x bit to be relevant for
322 * "mode changes"
323 */
324 if (trust_executable_bit &&
325 (0100 & (ce->ce_mode ^ st->st_mode)))
326 changed |= MODE_CHANGED;
327 break;
328 case S_IFLNK:
329 if (!S_ISLNK(st->st_mode) &&
330 (has_symlinks || !S_ISREG(st->st_mode)))
331 changed |= TYPE_CHANGED;
332 break;
333 case S_IFGITLINK:
334 /* We ignore most of the st_xxx fields for gitlinks */
335 if (!S_ISDIR(st->st_mode))
336 changed |= TYPE_CHANGED;
337 else if (ce_compare_gitlink(ce))
338 changed |= DATA_CHANGED;
339 return changed;
340 default:
341 BUG("unsupported ce_mode: %o", ce->ce_mode);
342 }
343
344 changed |= match_stat_data(&ce->ce_stat_data, st);
345
346 /* Racily smudged entry? */
347 if (!ce->ce_stat_data.sd_size) {
348 if (!is_empty_blob_oid(&ce->oid, the_repository->hash_algo))
349 changed |= DATA_CHANGED;
350 }
351
352 return changed;
353 }
354
355 static int is_racy_stat(const struct index_state *istate,
356 const struct stat_data *sd)
357 {
358 return (istate->timestamp.sec &&
359 #ifdef USE_NSEC
360 /* nanosecond timestamped files can also be racy! */
361 (istate->timestamp.sec < sd->sd_mtime.sec ||
362 (istate->timestamp.sec == sd->sd_mtime.sec &&
363 istate->timestamp.nsec <= sd->sd_mtime.nsec))
364 #else
365 istate->timestamp.sec <= sd->sd_mtime.sec
366 #endif
367 );
368 }
369
370 int is_racy_timestamp(const struct index_state *istate,
371 const struct cache_entry *ce)
372 {
373 return (!S_ISGITLINK(ce->ce_mode) &&
374 is_racy_stat(istate, &ce->ce_stat_data));
375 }
376
377 int match_stat_data_racy(const struct index_state *istate,
378 const struct stat_data *sd, struct stat *st)
379 {
380 if (is_racy_stat(istate, sd))
381 return MTIME_CHANGED;
382 return match_stat_data(sd, st);
383 }
384
385 int ie_match_stat(struct index_state *istate,
386 const struct cache_entry *ce, struct stat *st,
387 unsigned int options)
388 {
389 unsigned int changed;
390 int ignore_valid = options & CE_MATCH_IGNORE_VALID;
391 int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
392 int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
393 int ignore_fsmonitor = options & CE_MATCH_IGNORE_FSMONITOR;
394
395 if (!ignore_fsmonitor)
396 refresh_fsmonitor(istate);
397 /*
398 * If it's marked as always valid in the index, it's
399 * valid whatever the checked-out copy says.
400 *
401 * skip-worktree has the same effect with higher precedence
402 */
403 if (!ignore_skip_worktree && ce_skip_worktree(ce))
404 return 0;
405 if (!ignore_valid && (ce->ce_flags & CE_VALID))
406 return 0;
407 if (!ignore_fsmonitor && (ce->ce_flags & CE_FSMONITOR_VALID))
408 return 0;
409
410 /*
411 * Intent-to-add entries have not been added, so the index entry
412 * by definition never matches what is in the work tree until it
413 * actually gets added.
414 */
415 if (ce_intent_to_add(ce))
416 return DATA_CHANGED | TYPE_CHANGED | MODE_CHANGED;
417
418 changed = ce_match_stat_basic(ce, st);
419
420 /*
421 * Within 1 second of this sequence:
422 * echo xyzzy >file && git-update-index --add file
423 * running this command:
424 * echo frotz >file
425 * would give a falsely clean cache entry. The mtime and
426 * length match the cache, and other stat fields do not change.
427 *
428 * We could detect this at update-index time (the cache entry
429 * being registered/updated records the same time as "now")
430 * and delay the return from git-update-index, but that would
431 * effectively mean we can make at most one commit per second,
432 * which is not acceptable. Instead, we check cache entries
433 * whose mtime are the same as the index file timestamp more
434 * carefully than others.
435 */
436 if (!changed && is_racy_timestamp(istate, ce)) {
437 if (assume_racy_is_modified)
438 changed |= DATA_CHANGED;
439 else
440 changed |= ce_modified_check_fs(istate, ce, st);
441 }
442
443 return changed;
444 }
445
446 int ie_modified(struct index_state *istate,
447 const struct cache_entry *ce,
448 struct stat *st, unsigned int options)
449 {
450 int changed, changed_fs;
451
452 changed = ie_match_stat(istate, ce, st, options);
453 if (!changed)
454 return 0;
455 /*
456 * If the mode or type has changed, there's no point in trying
457 * to refresh the entry - it's not going to match
458 */
459 if (changed & (MODE_CHANGED | TYPE_CHANGED))
460 return changed;
461
462 /*
463 * Immediately after read-tree or update-index --cacheinfo,
464 * the length field is zero, as we have never even read the
465 * lstat(2) information once, and we cannot trust DATA_CHANGED
466 * returned by ie_match_stat() which in turn was returned by
467 * ce_match_stat_basic() to signal that the filesize of the
468 * blob changed. We have to actually go to the filesystem to
469 * see if the contents match, and if so, should answer "unchanged".
470 *
471 * The logic does not apply to gitlinks, as ce_match_stat_basic()
472 * already has checked the actual HEAD from the filesystem in the
473 * subproject. If ie_match_stat() already said it is different,
474 * then we know it is.
475 */
476 if ((changed & DATA_CHANGED) &&
477 #ifdef GIT_WINDOWS_NATIVE
478 /*
479 * Work around Git for Windows v2.27.0 fixing a bug where symlinks'
480 * target path lengths were not read at all, and instead recorded
481 * as 4096: now, all symlinks would appear as modified.
482 *
483 * So let's just special-case symlinks with a target path length
484 * (i.e. `sd_size`) of 4096 and force them to be re-checked.
485 */
486 (!S_ISLNK(st->st_mode) || ce->ce_stat_data.sd_size != MAX_PATH) &&
487 #endif
488 (S_ISGITLINK(ce->ce_mode) || ce->ce_stat_data.sd_size != 0))
489 return changed;
490
491 changed_fs = ce_modified_check_fs(istate, ce, st);
492 if (changed_fs)
493 return changed | changed_fs;
494 return 0;
495 }
496
497 static int cache_name_stage_compare(const char *name1, int len1, int stage1,
498 const char *name2, int len2, int stage2)
499 {
500 int cmp;
501
502 cmp = name_compare(name1, len1, name2, len2);
503 if (cmp)
504 return cmp;
505
506 if (stage1 < stage2)
507 return -1;
508 if (stage1 > stage2)
509 return 1;
510 return 0;
511 }
512
513 int cmp_cache_name_compare(const void *a_, const void *b_)
514 {
515 const struct cache_entry *ce1, *ce2;
516
517 ce1 = *((const struct cache_entry **)a_);
518 ce2 = *((const struct cache_entry **)b_);
519 return cache_name_stage_compare(ce1->name, ce1->ce_namelen, ce_stage(ce1),
520 ce2->name, ce2->ce_namelen, ce_stage(ce2));
521 }
522
523 static int index_name_stage_pos(struct index_state *istate,
524 const char *name, int namelen,
525 int stage,
526 enum index_search_mode search_mode)
527 {
528 int first, last;
529
530 first = 0;
531 last = istate->cache_nr;
532 while (last > first) {
533 int next = first + ((last - first) >> 1);
534 struct cache_entry *ce = istate->cache[next];
535 int cmp = cache_name_stage_compare(name, namelen, stage, ce->name, ce_namelen(ce), ce_stage(ce));
536 if (!cmp)
537 return next;
538 if (cmp < 0) {
539 last = next;
540 continue;
541 }
542 first = next+1;
543 }
544
545 if (search_mode == EXPAND_SPARSE && istate->sparse_index &&
546 first > 0) {
547 /* Note: first <= istate->cache_nr */
548 struct cache_entry *ce = istate->cache[first - 1];
549
550 /*
551 * If we are in a sparse-index _and_ the entry before the
552 * insertion position is a sparse-directory entry that is
553 * an ancestor of 'name', then we need to expand the index
554 * and search again. This will only trigger once, because
555 * thereafter the index is fully expanded.
556 */
557 if (S_ISSPARSEDIR(ce->ce_mode) &&
558 ce_namelen(ce) < namelen &&
559 !strncmp(name, ce->name, ce_namelen(ce))) {
560 ensure_full_index(istate);
561 return index_name_stage_pos(istate, name, namelen, stage, search_mode);
562 }
563 }
564
565 return -first-1;
566 }
567
568 int index_name_pos(struct index_state *istate, const char *name, int namelen)
569 {
570 return index_name_stage_pos(istate, name, namelen, 0, EXPAND_SPARSE);
571 }
572
573 int index_name_pos_sparse(struct index_state *istate, const char *name, int namelen)
574 {
575 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE);
576 }
577
578 int index_entry_exists(struct index_state *istate, const char *name, int namelen)
579 {
580 return index_name_stage_pos(istate, name, namelen, 0, NO_EXPAND_SPARSE) >= 0;
581 }
582
583 int remove_index_entry_at(struct index_state *istate, int pos)
584 {
585 struct cache_entry *ce = istate->cache[pos];
586
587 record_resolve_undo(istate, ce);
588 remove_name_hash(istate, ce);
589 save_or_free_index_entry(istate, ce);
590 istate->cache_changed |= CE_ENTRY_REMOVED;
591 istate->cache_nr--;
592 if (pos >= istate->cache_nr)
593 return 0;
594 MOVE_ARRAY(istate->cache + pos, istate->cache + pos + 1,
595 istate->cache_nr - pos);
596 return 1;
597 }
598
599 /*
600 * Remove all cache entries marked for removal, that is where
601 * CE_REMOVE is set in ce_flags. This is much more effective than
602 * calling remove_index_entry_at() for each entry to be removed.
603 */
604 void remove_marked_cache_entries(struct index_state *istate, int invalidate)
605 {
606 struct cache_entry **ce_array = istate->cache;
607 unsigned int i, j;
608
609 for (i = j = 0; i < istate->cache_nr; i++) {
610 if (ce_array[i]->ce_flags & CE_REMOVE) {
611 if (invalidate) {
612 cache_tree_invalidate_path(istate,
613 ce_array[i]->name);
614 untracked_cache_remove_from_index(istate,
615 ce_array[i]->name);
616 }
617 remove_name_hash(istate, ce_array[i]);
618 save_or_free_index_entry(istate, ce_array[i]);
619 }
620 else
621 ce_array[j++] = ce_array[i];
622 }
623 if (j == istate->cache_nr)
624 return;
625 istate->cache_changed |= CE_ENTRY_REMOVED;
626 istate->cache_nr = j;
627 }
628
629 int remove_file_from_index(struct index_state *istate, const char *path)
630 {
631 int pos = index_name_pos(istate, path, strlen(path));
632 if (pos < 0)
633 pos = -pos-1;
634 cache_tree_invalidate_path(istate, path);
635 untracked_cache_remove_from_index(istate, path);
636 while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
637 remove_index_entry_at(istate, pos);
638 return 0;
639 }
640
641 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
642 {
643 return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
644 }
645
646 static int index_name_pos_also_unmerged(struct index_state *istate,
647 const char *path, int namelen)
648 {
649 int pos = index_name_pos(istate, path, namelen);
650 struct cache_entry *ce;
651
652 if (pos >= 0)
653 return pos;
654
655 /* maybe unmerged? */
656 pos = -1 - pos;
657 if (pos >= istate->cache_nr ||
658 compare_name((ce = istate->cache[pos]), path, namelen))
659 return -1;
660
661 /* order of preference: stage 2, 1, 3 */
662 if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
663 ce_stage((ce = istate->cache[pos + 1])) == 2 &&
664 !compare_name(ce, path, namelen))
665 pos++;
666 return pos;
667 }
668
669 static int different_name(struct cache_entry *ce, struct cache_entry *alias)
670 {
671 int len = ce_namelen(ce);
672 return ce_namelen(alias) != len || memcmp(ce->name, alias->name, len);
673 }
674
675 /*
676 * If we add a filename that aliases in the cache, we will use the
677 * name that we already have - but we don't want to update the same
678 * alias twice, because that implies that there were actually two
679 * different files with aliasing names!
680 *
681 * So we use the CE_ADDED flag to verify that the alias was an old
682 * one before we accept it as
683 */
684 static struct cache_entry *create_alias_ce(struct index_state *istate,
685 struct cache_entry *ce,
686 struct cache_entry *alias)
687 {
688 int len;
689 struct cache_entry *new_entry;
690
691 if (alias->ce_flags & CE_ADDED)
692 die(_("will not add file alias '%s' ('%s' already exists in index)"),
693 ce->name, alias->name);
694
695 /* Ok, create the new entry using the name of the existing alias */
696 len = ce_namelen(alias);
697 new_entry = make_empty_cache_entry(istate, len);
698 memcpy(new_entry->name, alias->name, len);
699 copy_cache_entry(new_entry, ce);
700 save_or_free_index_entry(istate, ce);
701 return new_entry;
702 }
703
704 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
705 {
706 struct object_id oid;
707 if (odb_write_object(the_repository->objects, "", 0, OBJ_BLOB, &oid))
708 die(_("cannot create an empty blob in the object database"));
709 oidcpy(&ce->oid, &oid);
710 }
711
712 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
713 {
714 int namelen, was_same;
715 mode_t st_mode = st->st_mode;
716 struct cache_entry *ce, *alias = NULL;
717 unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
718 int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
719 int pretend = flags & ADD_CACHE_PRETEND;
720 int intent_only = flags & ADD_CACHE_INTENT;
721 int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
722 (intent_only ? ADD_CACHE_NEW_ONLY : 0));
723 unsigned hash_flags = pretend ? 0 : INDEX_WRITE_OBJECT;
724
725 if (flags & ADD_CACHE_RENORMALIZE)
726 hash_flags |= INDEX_RENORMALIZE;
727
728 if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
729 return error(_("%s: can only add regular files, symbolic links or git-directories"), path);
730
731 namelen = strlen(path);
732 if (S_ISDIR(st_mode)) {
733 while (namelen && path[namelen-1] == '/')
734 namelen--;
735 }
736 ce = make_empty_cache_entry(istate, namelen);
737 memcpy(ce->name, path, namelen);
738 ce->ce_namelen = namelen;
739 if (!intent_only)
740 fill_stat_cache_info(istate, ce, st);
741 else
742 ce->ce_flags |= CE_INTENT_TO_ADD;
743
744
745 if (trust_executable_bit && has_symlinks) {
746 ce->ce_mode = create_ce_mode(st_mode);
747 } else {
748 /* If there is an existing entry, pick the mode bits and type
749 * from it, otherwise assume unexecutable regular file.
750 */
751 struct cache_entry *ent;
752 int pos = index_name_pos_also_unmerged(istate, path, namelen);
753
754 ent = (0 <= pos) ? istate->cache[pos] : NULL;
755 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
756 }
757
758 /* When core.ignorecase=true, determine if a directory of the same name but differing
759 * case already exists within the Git repository. If it does, ensure the directory
760 * case of the file being added to the repository matches (is folded into) the existing
761 * entry's directory case.
762 */
763 if (ignore_case) {
764 adjust_dirname_case(istate, ce->name);
765 }
766 if (!(flags & ADD_CACHE_RENORMALIZE)) {
767 alias = index_file_exists(istate, ce->name,
768 ce_namelen(ce), ignore_case);
769 if (alias &&
770 !ce_stage(alias) &&
771 !ie_match_stat(istate, alias, st, ce_option)) {
772 /* Nothing changed, really */
773 if (!S_ISGITLINK(alias->ce_mode))
774 ce_mark_uptodate(alias);
775 alias->ce_flags |= CE_ADDED;
776
777 discard_cache_entry(ce);
778 return 0;
779 }
780 }
781 if (!intent_only) {
782 if (index_path(istate, &ce->oid, path, st, hash_flags)) {
783 discard_cache_entry(ce);
784 return error(_("unable to index file '%s'"), path);
785 }
786 } else
787 set_object_name_for_intent_to_add_entry(ce);
788
789 if (ignore_case && alias && different_name(ce, alias))
790 ce = create_alias_ce(istate, ce, alias);
791 ce->ce_flags |= CE_ADDED;
792
793 /* It was suspected to be racily clean, but it turns out to be Ok */
794 was_same = (alias &&
795 !ce_stage(alias) &&
796 oideq(&alias->oid, &ce->oid) &&
797 ce->ce_mode == alias->ce_mode);
798
799 if (pretend)
800 discard_cache_entry(ce);
801 else if (add_index_entry(istate, ce, add_option)) {
802 discard_cache_entry(ce);
803 return error(_("unable to add '%s' to index"), path);
804 }
805 if (verbose && !was_same)
806 printf("add '%s'\n", path);
807 return 0;
808 }
809
810 int add_file_to_index(struct index_state *istate, const char *path, int flags)
811 {
812 struct stat st;
813 if (lstat(path, &st))
814 die_errno(_("unable to stat '%s'"), path);
815 return add_to_index(istate, path, &st, flags);
816 }
817
818 struct cache_entry *make_empty_cache_entry(struct index_state *istate, size_t len)
819 {
820 return mem_pool__ce_calloc(find_mem_pool(istate), len);
821 }
822
823 struct cache_entry *make_empty_transient_cache_entry(size_t len,
824 struct mem_pool *ce_mem_pool)
825 {
826 if (ce_mem_pool)
827 return mem_pool__ce_calloc(ce_mem_pool, len);
828 return xcalloc(1, cache_entry_size(len));
829 }
830
831 enum verify_path_result {
832 PATH_OK,
833 PATH_INVALID,
834 PATH_DIR_WITH_SEP,
835 };
836
837 static enum verify_path_result verify_path_internal(const char *, unsigned);
838
839 int verify_path(const char *path, unsigned mode)
840 {
841 return verify_path_internal(path, mode) == PATH_OK;
842 }
843
844 struct cache_entry *make_cache_entry(struct index_state *istate,
845 unsigned int mode,
846 const struct object_id *oid,
847 const char *path,
848 int stage,
849 unsigned int refresh_options)
850 {
851 struct cache_entry *ce, *ret;
852 int len;
853
854 if (verify_path_internal(path, mode) == PATH_INVALID) {
855 error(_("invalid path '%s'"), path);
856 return NULL;
857 }
858
859 len = strlen(path);
860 ce = make_empty_cache_entry(istate, len);
861
862 oidcpy(&ce->oid, oid);
863 memcpy(ce->name, path, len);
864 ce->ce_flags = create_ce_flags(stage);
865 ce->ce_namelen = len;
866 ce->ce_mode = create_ce_mode(mode);
867
868 ret = refresh_cache_entry(istate, ce, refresh_options);
869 if (ret != ce)
870 discard_cache_entry(ce);
871 return ret;
872 }
873
874 struct cache_entry *make_transient_cache_entry(unsigned int mode,
875 const struct object_id *oid,
876 const char *path,
877 int stage,
878 struct mem_pool *ce_mem_pool)
879 {
880 struct cache_entry *ce;
881 int len;
882
883 if (!verify_path(path, mode)) {
884 error(_("invalid path '%s'"), path);
885 return NULL;
886 }
887
888 len = strlen(path);
889 ce = make_empty_transient_cache_entry(len, ce_mem_pool);
890
891 oidcpy(&ce->oid, oid);
892 memcpy(ce->name, path, len);
893 ce->ce_flags = create_ce_flags(stage);
894 ce->ce_namelen = len;
895 ce->ce_mode = create_ce_mode(mode);
896
897 return ce;
898 }
899
900 /*
901 * Chmod an index entry with either +x or -x.
902 *
903 * Returns -1 if the chmod for the particular cache entry failed (if it's
904 * not a regular file), -2 if an invalid flip argument is passed in, 0
905 * otherwise.
906 */
907 int chmod_index_entry(struct index_state *istate, struct cache_entry *ce,
908 char flip)
909 {
910 if (!S_ISREG(ce->ce_mode))
911 return -1;
912 switch (flip) {
913 case '+':
914 ce->ce_mode |= 0111;
915 break;
916 case '-':
917 ce->ce_mode &= ~0111;
918 break;
919 default:
920 return -2;
921 }
922 cache_tree_invalidate_path(istate, ce->name);
923 ce->ce_flags |= CE_UPDATE_IN_BASE;
924 mark_fsmonitor_invalid(istate, ce);
925 istate->cache_changed |= CE_ENTRY_CHANGED;
926
927 return 0;
928 }
929
930 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
931 {
932 int len = ce_namelen(a);
933 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
934 }
935
936 /*
937 * We fundamentally don't like some paths: we don't want
938 * dot or dot-dot anywhere, and for obvious reasons don't
939 * want to recurse into ".git" either.
940 *
941 * Also, we don't want double slashes or slashes at the
942 * end that can make pathnames ambiguous.
943 */
944 static int verify_dotfile(const char *rest, unsigned mode)
945 {
946 /*
947 * The first character was '.', but that
948 * has already been discarded, we now test
949 * the rest.
950 */
951
952 /* "." is not allowed */
953 if (*rest == '\0' || is_dir_sep(*rest))
954 return 0;
955
956 switch (*rest) {
957 /*
958 * ".git" followed by NUL or slash is bad. Note that we match
959 * case-insensitively here, even if ignore_case is not set.
960 * This outlaws ".GIT" everywhere out of an abundance of caution,
961 * since there's really no good reason to allow it.
962 *
963 * Once we've seen ".git", we can also find ".gitmodules", etc (also
964 * case-insensitively).
965 */
966 case 'g':
967 case 'G':
968 if (rest[1] != 'i' && rest[1] != 'I')
969 break;
970 if (rest[2] != 't' && rest[2] != 'T')
971 break;
972 if (rest[3] == '\0' || is_dir_sep(rest[3]))
973 return 0;
974 if (S_ISLNK(mode)) {
975 rest += 3;
976 if (skip_iprefix(rest, "modules", &rest) &&
977 (*rest == '\0' || is_dir_sep(*rest)))
978 return 0;
979 }
980 break;
981 case '.':
982 if (rest[1] == '\0' || is_dir_sep(rest[1]))
983 return 0;
984 }
985 return 1;
986 }
987
988 static enum verify_path_result verify_path_internal(const char *path,
989 unsigned mode)
990 {
991 char c = 0;
992
993 if (has_dos_drive_prefix(path))
994 return PATH_INVALID;
995
996 if (!is_valid_path(path))
997 return PATH_INVALID;
998
999 goto inside;
1000 for (;;) {
1001 if (!c)
1002 return PATH_OK;
1003 if (is_dir_sep(c)) {
1004 inside:
1005 if (protect_hfs) {
1006
1007 if (is_hfs_dotgit(path))
1008 return PATH_INVALID;
1009 if (S_ISLNK(mode)) {
1010 if (is_hfs_dotgitmodules(path))
1011 return PATH_INVALID;
1012 }
1013 }
1014 if (protect_ntfs) {
1015 #if defined GIT_WINDOWS_NATIVE || defined __CYGWIN__
1016 if (c == '\\')
1017 return PATH_INVALID;
1018 #endif
1019 if (is_ntfs_dotgit(path))
1020 return PATH_INVALID;
1021 if (S_ISLNK(mode)) {
1022 if (is_ntfs_dotgitmodules(path))
1023 return PATH_INVALID;
1024 }
1025 }
1026
1027 c = *path++;
1028 if ((c == '.' && !verify_dotfile(path, mode)) ||
1029 is_dir_sep(c))
1030 return PATH_INVALID;
1031 /*
1032 * allow terminating directory separators for
1033 * sparse directory entries.
1034 */
1035 if (c == '\0')
1036 return S_ISDIR(mode) ? PATH_DIR_WITH_SEP :
1037 PATH_INVALID;
1038 } else if (c == '\\' && protect_ntfs) {
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 the_hash_algo->init_fn(&c);
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) && 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 the_hash_algo->init_fn(eoie_c);
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 struct index_state *istate;
3407 int i;
3408 int unmerged = 0;
3409
3410 repo_read_index(repo);
3411 istate = repo->index;
3412 for (i = 0; i < istate->cache_nr; i++) {
3413 struct cache_entry *ce = istate->cache[i];
3414 struct cache_entry *new_ce;
3415 int len;
3416
3417 if (!ce_stage(ce))
3418 continue;
3419 unmerged = 1;
3420 len = ce_namelen(ce);
3421 new_ce = make_empty_cache_entry(istate, len);
3422 memcpy(new_ce->name, ce->name, len);
3423 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
3424 new_ce->ce_namelen = len;
3425 new_ce->ce_mode = ce->ce_mode;
3426 if (add_index_entry(istate, new_ce, ADD_CACHE_SKIP_DFCHECK))
3427 return error(_("%s: cannot drop to stage #0"),
3428 new_ce->name);
3429 }
3430 return unmerged;
3431 }
3432
3433 /*
3434 * Returns 1 if the path is an "other" path with respect to
3435 * the index; that is, the path is not mentioned in the index at all,
3436 * either as a file, a directory with some files in the index,
3437 * or as an unmerged entry.
3438 *
3439 * We helpfully remove a trailing "/" from directories so that
3440 * the output of read_directory can be used as-is.
3441 */
3442 int index_name_is_other(struct index_state *istate, const char *name,
3443 int namelen)
3444 {
3445 int pos;
3446 if (namelen && name[namelen - 1] == '/')
3447 namelen--;
3448 pos = index_name_pos(istate, name, namelen);
3449 if (0 <= pos)
3450 return 0; /* exact match */
3451 pos = -pos - 1;
3452 if (pos < istate->cache_nr) {
3453 struct cache_entry *ce = istate->cache[pos];
3454 if (ce_namelen(ce) == namelen &&
3455 !memcmp(ce->name, name, namelen))
3456 return 0; /* Yup, this one exists unmerged */
3457 }
3458 return 1;
3459 }
3460
3461 void *read_blob_data_from_index(struct index_state *istate,
3462 const char *path, unsigned long *size)
3463 {
3464 int pos, len;
3465 unsigned long sz;
3466 enum object_type type;
3467 void *data;
3468
3469 len = strlen(path);
3470 pos = index_name_pos(istate, path, len);
3471 if (pos < 0) {
3472 /*
3473 * We might be in the middle of a merge, in which
3474 * case we would read stage #2 (ours).
3475 */
3476 int i;
3477 for (i = -pos - 1;
3478 (pos < 0 && i < istate->cache_nr &&
3479 !strcmp(istate->cache[i]->name, path));
3480 i++)
3481 if (ce_stage(istate->cache[i]) == 2)
3482 pos = i;
3483 }
3484 if (pos < 0)
3485 return NULL;
3486 data = odb_read_object(the_repository->objects, &istate->cache[pos]->oid,
3487 &type, &sz);
3488 if (!data || type != OBJ_BLOB) {
3489 free(data);
3490 return NULL;
3491 }
3492 if (size)
3493 *size = sz;
3494 return data;
3495 }
3496
3497 void move_index_extensions(struct index_state *dst, struct index_state *src)
3498 {
3499 dst->untracked = src->untracked;
3500 src->untracked = NULL;
3501 dst->cache_tree = src->cache_tree;
3502 src->cache_tree = NULL;
3503 }
3504
3505 struct cache_entry *dup_cache_entry(const struct cache_entry *ce,
3506 struct index_state *istate)
3507 {
3508 unsigned int size = ce_size(ce);
3509 int mem_pool_allocated;
3510 struct cache_entry *new_entry = make_empty_cache_entry(istate, ce_namelen(ce));
3511 mem_pool_allocated = new_entry->mem_pool_allocated;
3512
3513 memcpy(new_entry, ce, size);
3514 new_entry->mem_pool_allocated = mem_pool_allocated;
3515 return new_entry;
3516 }
3517
3518 void discard_cache_entry(struct cache_entry *ce)
3519 {
3520 if (ce && should_validate_cache_entries())
3521 memset(ce, 0xCD, cache_entry_size(ce->ce_namelen));
3522
3523 if (ce && ce->mem_pool_allocated)
3524 return;
3525
3526 free(ce);
3527 }
3528
3529 int should_validate_cache_entries(void)
3530 {
3531 static int validate_index_cache_entries = -1;
3532
3533 if (validate_index_cache_entries < 0) {
3534 if (getenv("GIT_TEST_VALIDATE_INDEX_CACHE_ENTRIES"))
3535 validate_index_cache_entries = 1;
3536 else
3537 validate_index_cache_entries = 0;
3538 }
3539
3540 return validate_index_cache_entries;
3541 }
3542
3543 #define EOIE_SIZE (4 + GIT_SHA1_RAWSZ) /* <4-byte offset> + <20-byte hash> */
3544 #define EOIE_SIZE_WITH_HEADER (4 + 4 + EOIE_SIZE) /* <4-byte signature> + <4-byte length> + EOIE_SIZE */
3545
3546 static size_t read_eoie_extension(const char *mmap, size_t mmap_size)
3547 {
3548 /*
3549 * The end of index entries (EOIE) extension is guaranteed to be last
3550 * so that it can be found by scanning backwards from the EOF.
3551 *
3552 * "EOIE"
3553 * <4-byte length>
3554 * <4-byte offset>
3555 * <20-byte hash>
3556 */
3557 const char *index, *eoie;
3558 uint32_t extsize;
3559 size_t offset, src_offset;
3560 unsigned char hash[GIT_MAX_RAWSZ];
3561 struct git_hash_ctx c;
3562
3563 /* ensure we have an index big enough to contain an EOIE extension */
3564 if (mmap_size < sizeof(struct cache_header) + EOIE_SIZE_WITH_HEADER + the_hash_algo->rawsz)
3565 return 0;
3566
3567 /* validate the extension signature */
3568 index = eoie = mmap + mmap_size - EOIE_SIZE_WITH_HEADER - the_hash_algo->rawsz;
3569 if (CACHE_EXT(index) != CACHE_EXT_ENDOFINDEXENTRIES)
3570 return 0;
3571 index += sizeof(uint32_t);
3572
3573 /* validate the extension size */
3574 extsize = get_be32(index);
3575 if (extsize != EOIE_SIZE)
3576 return 0;
3577 index += sizeof(uint32_t);
3578
3579 /*
3580 * Validate the offset we're going to look for the first extension
3581 * signature is after the index header and before the eoie extension.
3582 */
3583 offset = get_be32(index);
3584 if (mmap + offset < mmap + sizeof(struct cache_header))
3585 return 0;
3586 if (mmap + offset >= eoie)
3587 return 0;
3588 index += sizeof(uint32_t);
3589
3590 /*
3591 * The hash is computed over extension types and their sizes (but not
3592 * their contents). E.g. if we have "TREE" extension that is N-bytes
3593 * long, "REUC" extension that is M-bytes long, followed by "EOIE",
3594 * then the hash would be:
3595 *
3596 * SHA-1("TREE" + <binary representation of N> +
3597 * "REUC" + <binary representation of M>)
3598 */
3599 src_offset = offset;
3600 the_hash_algo->init_fn(&c);
3601 while (src_offset < mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER) {
3602 /* After an array of active_nr index entries,
3603 * there can be arbitrary number of extended
3604 * sections, each of which is prefixed with
3605 * extension name (4-byte) and section length
3606 * in 4-byte network byte order.
3607 */
3608 uint32_t extsize;
3609 memcpy(&extsize, mmap + src_offset + 4, 4);
3610 extsize = ntohl(extsize);
3611
3612 /* verify the extension size isn't so large it will wrap around */
3613 if (src_offset + 8 + extsize < src_offset)
3614 return 0;
3615
3616 git_hash_update(&c, mmap + src_offset, 8);
3617
3618 src_offset += 8;
3619 src_offset += extsize;
3620 }
3621 git_hash_final(hash, &c);
3622 if (!hasheq(hash, (const unsigned char *)index, the_repository->hash_algo))
3623 return 0;
3624
3625 /* Validate that the extension offsets returned us back to the eoie extension. */
3626 if (src_offset != mmap_size - the_hash_algo->rawsz - EOIE_SIZE_WITH_HEADER)
3627 return 0;
3628
3629 return offset;
3630 }
3631
3632 static void write_eoie_extension(struct strbuf *sb, struct git_hash_ctx *eoie_context, size_t offset)
3633 {
3634 uint32_t buffer;
3635 unsigned char hash[GIT_MAX_RAWSZ];
3636
3637 /* offset */
3638 put_be32(&buffer, offset);
3639 strbuf_add(sb, &buffer, sizeof(uint32_t));
3640
3641 /* hash */
3642 git_hash_final(hash, eoie_context);
3643 strbuf_add(sb, hash, the_hash_algo->rawsz);
3644 }
3645
3646 #define IEOT_VERSION (1)
3647
3648 static struct index_entry_offset_table *read_ieot_extension(const char *mmap, size_t mmap_size, size_t offset)
3649 {
3650 const char *index = NULL;
3651 uint32_t extsize, ext_version;
3652 struct index_entry_offset_table *ieot;
3653 int i, nr;
3654
3655 /* find the IEOT extension */
3656 if (!offset)
3657 return NULL;
3658 while (offset <= mmap_size - the_hash_algo->rawsz - 8) {
3659 extsize = get_be32(mmap + offset + 4);
3660 if (CACHE_EXT((mmap + offset)) == CACHE_EXT_INDEXENTRYOFFSETTABLE) {
3661 index = mmap + offset + 4 + 4;
3662 break;
3663 }
3664 offset += 8;
3665 offset += extsize;
3666 }
3667 if (!index)
3668 return NULL;
3669
3670 /* validate the version is IEOT_VERSION */
3671 ext_version = get_be32(index);
3672 if (ext_version != IEOT_VERSION) {
3673 error("invalid IEOT version %d", ext_version);
3674 return NULL;
3675 }
3676 index += sizeof(uint32_t);
3677
3678 /* extension size - version bytes / bytes per entry */
3679 nr = (extsize - sizeof(uint32_t)) / (sizeof(uint32_t) + sizeof(uint32_t));
3680 if (!nr) {
3681 error("invalid number of IEOT entries %d", nr);
3682 return NULL;
3683 }
3684 ieot = xmalloc(sizeof(struct index_entry_offset_table)
3685 + (nr * sizeof(struct index_entry_offset)));
3686 ieot->nr = nr;
3687 for (i = 0; i < nr; i++) {
3688 ieot->entries[i].offset = get_be32(index);
3689 index += sizeof(uint32_t);
3690 ieot->entries[i].nr = get_be32(index);
3691 index += sizeof(uint32_t);
3692 }
3693
3694 return ieot;
3695 }
3696
3697 static void write_ieot_extension(struct strbuf *sb, struct index_entry_offset_table *ieot)
3698 {
3699 uint32_t buffer;
3700 int i;
3701
3702 /* version */
3703 put_be32(&buffer, IEOT_VERSION);
3704 strbuf_add(sb, &buffer, sizeof(uint32_t));
3705
3706 /* ieot */
3707 for (i = 0; i < ieot->nr; i++) {
3708
3709 /* offset */
3710 put_be32(&buffer, ieot->entries[i].offset);
3711 strbuf_add(sb, &buffer, sizeof(uint32_t));
3712
3713 /* count */
3714 put_be32(&buffer, ieot->entries[i].nr);
3715 strbuf_add(sb, &buffer, sizeof(uint32_t));
3716 }
3717 }
3718
3719 void prefetch_cache_entries(const struct index_state *istate,
3720 must_prefetch_predicate must_prefetch)
3721 {
3722 int i;
3723 struct oid_array to_fetch = OID_ARRAY_INIT;
3724
3725 for (i = 0; i < istate->cache_nr; i++) {
3726 struct cache_entry *ce = istate->cache[i];
3727
3728 if (S_ISGITLINK(ce->ce_mode) || !must_prefetch(ce))
3729 continue;
3730 if (!odb_read_object_info_extended(the_repository->objects,
3731 &ce->oid, NULL,
3732 OBJECT_INFO_FOR_PREFETCH))
3733 continue;
3734 oid_array_append(&to_fetch, &ce->oid);
3735 }
3736 promisor_remote_get_direct(the_repository,
3737 to_fetch.oid, to_fetch.nr);
3738 oid_array_clear(&to_fetch);
3739 }
3740
3741 static int read_one_entry_opt(struct index_state *istate,
3742 const struct object_id *oid,
3743 struct strbuf *base,
3744 const char *pathname,
3745 unsigned mode, int opt)
3746 {
3747 int len;
3748 struct cache_entry *ce;
3749
3750 if (S_ISDIR(mode))
3751 return READ_TREE_RECURSIVE;
3752
3753 len = strlen(pathname);
3754 ce = make_empty_cache_entry(istate, base->len + len);
3755
3756 ce->ce_mode = create_ce_mode(mode);
3757 ce->ce_flags = create_ce_flags(1);
3758 ce->ce_namelen = base->len + len;
3759 memcpy(ce->name, base->buf, base->len);
3760 memcpy(ce->name + base->len, pathname, len+1);
3761 oidcpy(&ce->oid, oid);
3762 return add_index_entry(istate, ce, opt);
3763 }
3764
3765 static int read_one_entry(const struct object_id *oid, struct strbuf *base,
3766 const char *pathname, unsigned mode,
3767 void *context)
3768 {
3769 struct index_state *istate = context;
3770 return read_one_entry_opt(istate, oid, base, pathname,
3771 mode,
3772 ADD_CACHE_OK_TO_ADD|ADD_CACHE_SKIP_DFCHECK);
3773 }
3774
3775 /*
3776 * This is used when the caller knows there is no existing entries at
3777 * the stage that will conflict with the entry being added.
3778 */
3779 static int read_one_entry_quick(const struct object_id *oid, struct strbuf *base,
3780 const char *pathname, unsigned mode,
3781 void *context)
3782 {
3783 struct index_state *istate = context;
3784 return read_one_entry_opt(istate, oid, base, pathname,
3785 mode, ADD_CACHE_JUST_APPEND);
3786 }
3787
3788 /*
3789 * Read the tree specified with --with-tree option
3790 * (typically, HEAD) into stage #1 and then
3791 * squash them down to stage #0. This is used for
3792 * --error-unmatch to list and check the path patterns
3793 * that were given from the command line. We are not
3794 * going to write this index out.
3795 */
3796 void overlay_tree_on_index(struct index_state *istate,
3797 const char *tree_name, const char *prefix)
3798 {
3799 struct tree *tree;
3800 struct object_id oid;
3801 struct pathspec pathspec;
3802 struct cache_entry *last_stage0 = NULL;
3803 int i;
3804 read_tree_fn_t fn = NULL;
3805 int err;
3806
3807 if (repo_get_oid(the_repository, tree_name, &oid))
3808 die("tree-ish %s not found.", tree_name);
3809 tree = repo_parse_tree_indirect(the_repository, &oid);
3810 if (!tree)
3811 die("bad tree-ish %s", tree_name);
3812
3813 /* Hoist the unmerged entries up to stage #3 to make room */
3814 /* TODO: audit for interaction with sparse-index. */
3815 ensure_full_index(istate);
3816 for (i = 0; i < istate->cache_nr; i++) {
3817 struct cache_entry *ce = istate->cache[i];
3818 if (!ce_stage(ce))
3819 continue;
3820 ce->ce_flags |= CE_STAGEMASK;
3821 }
3822
3823 if (prefix) {
3824 static const char *(matchbuf[1]);
3825 matchbuf[0] = NULL;
3826 parse_pathspec(&pathspec, PATHSPEC_ALL_MAGIC,
3827 PATHSPEC_PREFER_CWD, prefix, matchbuf);
3828 } else
3829 memset(&pathspec, 0, sizeof(pathspec));
3830
3831 /*
3832 * See if we have cache entry at the stage. If so,
3833 * do it the original slow way, otherwise, append and then
3834 * sort at the end.
3835 */
3836 for (i = 0; !fn && i < istate->cache_nr; i++) {
3837 const struct cache_entry *ce = istate->cache[i];
3838 if (ce_stage(ce) == 1)
3839 fn = read_one_entry;
3840 }
3841
3842 if (!fn)
3843 fn = read_one_entry_quick;
3844 err = read_tree(the_repository, tree, &pathspec, fn, istate);
3845 clear_pathspec(&pathspec);
3846 if (err)
3847 die("unable to read tree entries %s", tree_name);
3848
3849 /*
3850 * Sort the cache entry -- we need to nuke the cache tree, though.
3851 */
3852 if (fn == read_one_entry_quick) {
3853 cache_tree_free(&istate->cache_tree);
3854 QSORT(istate->cache, istate->cache_nr, cmp_cache_name_compare);
3855 }
3856
3857 for (i = 0; i < istate->cache_nr; i++) {
3858 struct cache_entry *ce = istate->cache[i];
3859 switch (ce_stage(ce)) {
3860 case 0:
3861 last_stage0 = ce;
3862 /* fallthru */
3863 default:
3864 continue;
3865 case 1:
3866 /*
3867 * If there is stage #0 entry for this, we do not
3868 * need to show it. We use CE_UPDATE bit to mark
3869 * such an entry.
3870 */
3871 if (last_stage0 &&
3872 !strcmp(last_stage0->name, ce->name))
3873 ce->ce_flags |= CE_UPDATE;
3874 }
3875 }
3876 }
3877
3878 struct update_callback_data {
3879 struct index_state *index;
3880 struct repository *repo;
3881 struct pathspec *pathspec;
3882 int include_sparse;
3883 int flags;
3884 int add_errors;
3885 int ignored_too;
3886 };
3887
3888 static int fix_unmerged_status(struct diff_filepair *p,
3889 struct update_callback_data *data)
3890 {
3891 if (p->status != DIFF_STATUS_UNMERGED)
3892 return p->status;
3893 if (!(data->flags & ADD_CACHE_IGNORE_REMOVAL) && !p->two->mode)
3894 /*
3895 * This is not an explicit add request, and the
3896 * path is missing from the working tree (deleted)
3897 */
3898 return DIFF_STATUS_DELETED;
3899 else
3900 /*
3901 * Either an explicit add request, or path exists
3902 * in the working tree. An attempt to explicitly
3903 * add a path that does not exist in the working tree
3904 * will be caught as an error by the caller immediately.
3905 */
3906 return DIFF_STATUS_MODIFIED;
3907 }
3908
3909 static int skip_submodule(const char *path,
3910 struct repository *repo,
3911 struct pathspec *pathspec,
3912 int ignored_too)
3913 {
3914 struct stat st;
3915 const struct submodule *sub;
3916 int pathspec_matches = 0;
3917 int ps_i;
3918 char *norm_pathspec = NULL;
3919
3920 /* Only consider if path is a directory */
3921 if (lstat(path, &st) || !S_ISDIR(st.st_mode))
3922 return 0;
3923
3924 /* Check if it's a submodule with ignore=all */
3925 sub = submodule_from_path(repo, null_oid(the_hash_algo), path);
3926 if (!sub || !sub->name || !sub->ignore || strcmp(sub->ignore, "all"))
3927 return 0;
3928
3929 trace_printf("ignore=all: %s\n", path);
3930 trace_printf("pathspec %s\n", (pathspec && pathspec->nr)
3931 ? "has pathspec"
3932 : "no pathspec");
3933
3934 /* Check if submodule path is explicitly mentioned in pathspec */
3935 if (pathspec) {
3936 for (ps_i = 0; ps_i < pathspec->nr; ps_i++) {
3937 const char *m = pathspec->items[ps_i].match;
3938 if (!m)
3939 continue;
3940 norm_pathspec = xstrdup(m);
3941 strip_dir_trailing_slashes(norm_pathspec);
3942 if (!strcmp(path, norm_pathspec)) {
3943 pathspec_matches = 1;
3944 FREE_AND_NULL(norm_pathspec);
3945 break;
3946 }
3947 FREE_AND_NULL(norm_pathspec);
3948 }
3949 }
3950
3951 /* If explicitly matched and forced, allow adding */
3952 if (pathspec_matches) {
3953 if (ignored_too && ignored_too > 0) {
3954 trace_printf("Add submodule due to --force: %s\n", path);
3955 return 0;
3956 } else {
3957 advise_if_enabled(ADVICE_ADD_IGNORED_FILE,
3958 _("Skipping submodule due to ignore=all: %s\n"
3959 "Use --force if you really want to add the submodule."), path);
3960 return 1;
3961 }
3962 }
3963
3964 /* No explicit pathspec match -> skip silently */
3965 trace_printf("Pathspec to submodule does not match explicitly: %s\n", path);
3966 return 1;
3967 }
3968
3969 static void update_callback(struct diff_queue_struct *q,
3970 struct diff_options *opt UNUSED, void *cbdata)
3971 {
3972 int i;
3973 struct update_callback_data *data = cbdata;
3974
3975 for (i = 0; i < q->nr; i++) {
3976 struct diff_filepair *p = q->queue[i];
3977 const char *path = p->one->path;
3978
3979 if (!data->include_sparse &&
3980 !path_in_sparse_checkout(path, data->index))
3981 continue;
3982
3983 switch (fix_unmerged_status(p, data)) {
3984 default:
3985 die(_("unexpected diff status %c"), p->status);
3986 case DIFF_STATUS_MODIFIED:
3987 case DIFF_STATUS_TYPE_CHANGED:
3988 if (skip_submodule(path, data->repo,
3989 data->pathspec,
3990 data->ignored_too))
3991 continue;
3992
3993 if (add_file_to_index(data->index, path, data->flags)) {
3994 if (!(data->flags & ADD_CACHE_IGNORE_ERRORS))
3995 die(_("updating files failed"));
3996 data->add_errors++;
3997 }
3998 break;
3999 case DIFF_STATUS_DELETED:
4000 if (data->flags & ADD_CACHE_IGNORE_REMOVAL)
4001 break;
4002 if (!(data->flags & ADD_CACHE_PRETEND))
4003 remove_file_from_index(data->index, path);
4004 if (data->flags & (ADD_CACHE_PRETEND|ADD_CACHE_VERBOSE))
4005 printf(_("remove '%s'\n"), path);
4006 break;
4007 }
4008 }
4009 }
4010
4011 int add_files_to_cache(struct repository *repo, const char *prefix,
4012 const struct pathspec *pathspec, char *ps_matched,
4013 int include_sparse, int flags, int ignored_too )
4014 {
4015 struct odb_transaction *transaction;
4016 struct update_callback_data data;
4017 struct rev_info rev;
4018
4019 memset(&data, 0, sizeof(data));
4020 data.index = repo->index;
4021 data.include_sparse = include_sparse;
4022 data.flags = flags;
4023 data.repo = repo;
4024 data.ignored_too = ignored_too;
4025 data.pathspec = (struct pathspec *)pathspec;
4026
4027 repo_init_revisions(repo, &rev, prefix);
4028 setup_revisions(0, NULL, &rev, NULL);
4029 if (pathspec) {
4030 copy_pathspec(&rev.prune_data, pathspec);
4031 rev.ps_matched = ps_matched;
4032 }
4033 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
4034 rev.diffopt.format_callback = update_callback;
4035 rev.diffopt.format_callback_data = &data;
4036 rev.diffopt.flags.override_submodule_config = 1;
4037 rev.diffopt.detect_rename = 0; /* staging worktree changes does not need renames */
4038 rev.max_count = 0; /* do not compare unmerged paths with stage #2 */
4039
4040 /*
4041 * Use an ODB transaction to optimize adding multiple objects.
4042 * This function is invoked from commands other than 'add', which
4043 * may not have their own transaction active.
4044 */
4045 transaction = odb_transaction_begin(repo->objects);
4046 run_diff_files(&rev, DIFF_RACY_IS_MODIFIED);
4047 odb_transaction_commit(transaction);
4048
4049 release_revisions(&rev);
4050 return !!data.add_errors;
4051 }