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