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