interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / read-cache.c

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