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