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