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