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