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