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