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