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