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