read-cache: mark new entries for 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)
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         free(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                         free(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 cache_entry *ce, struct cache_entry *alias)
581 {
582         int len;
583         struct cache_entry *new;
584
585         if (alias->ce_flags & CE_ADDED)
586                 die("Will not add file alias '%s' ('%s' already exists in index)", ce->name, alias->name);
587
588         /* Ok, create the new entry using the name of the existing alias */
589         len = ce_namelen(alias);
590         new = xcalloc(1, cache_entry_size(len));
591         memcpy(new->name, alias->name, len);
592         copy_cache_entry(new, ce);
593         free(ce);
594         return new;
595 }
596
597 void set_object_name_for_intent_to_add_entry(struct cache_entry *ce)
598 {
599         unsigned char sha1[20];
600         if (write_sha1_file("", 0, blob_type, sha1))
601                 die("cannot create an empty blob in the object database");
602         hashcpy(ce->sha1, sha1);
603 }
604
605 int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags)
606 {
607         int size, namelen, was_same;
608         mode_t st_mode = st->st_mode;
609         struct cache_entry *ce, *alias;
610         unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE|CE_MATCH_RACY_IS_DIRTY;
611         int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND);
612         int pretend = flags & ADD_CACHE_PRETEND;
613         int intent_only = flags & ADD_CACHE_INTENT;
614         int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|
615                           (intent_only ? ADD_CACHE_NEW_ONLY : 0));
616
617         if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode))
618                 return error("%s: can only add regular files, symbolic links or git-directories", path);
619
620         namelen = strlen(path);
621         if (S_ISDIR(st_mode)) {
622                 while (namelen && path[namelen-1] == '/')
623                         namelen--;
624         }
625         size = cache_entry_size(namelen);
626         ce = xcalloc(1, size);
627         memcpy(ce->name, path, namelen);
628         ce->ce_namelen = namelen;
629         if (!intent_only)
630                 fill_stat_cache_info(ce, st);
631         else
632                 ce->ce_flags |= CE_INTENT_TO_ADD;
633
634         if (trust_executable_bit && has_symlinks)
635                 ce->ce_mode = create_ce_mode(st_mode);
636         else {
637                 /* If there is an existing entry, pick the mode bits and type
638                  * from it, otherwise assume unexecutable regular file.
639                  */
640                 struct cache_entry *ent;
641                 int pos = index_name_pos_also_unmerged(istate, path, namelen);
642
643                 ent = (0 <= pos) ? istate->cache[pos] : NULL;
644                 ce->ce_mode = ce_mode_from_stat(ent, st_mode);
645         }
646
647         /* When core.ignorecase=true, determine if a directory of the same name but differing
648          * case already exists within the Git repository.  If it does, ensure the directory
649          * case of the file being added to the repository matches (is folded into) the existing
650          * entry's directory case.
651          */
652         if (ignore_case) {
653                 const char *startPtr = ce->name;
654                 const char *ptr = startPtr;
655                 while (*ptr) {
656                         while (*ptr && *ptr != '/')
657                                 ++ptr;
658                         if (*ptr == '/') {
659                                 struct cache_entry *foundce;
660                                 ++ptr;
661                                 foundce = index_dir_exists(istate, ce->name, ptr - ce->name - 1);
662                                 if (foundce) {
663                                         memcpy((void *)startPtr, foundce->name + (startPtr - ce->name), ptr - startPtr);
664                                         startPtr = ptr;
665                                 }
666                         }
667                 }
668         }
669
670         alias = index_file_exists(istate, ce->name, ce_namelen(ce), ignore_case);
671         if (alias && !ce_stage(alias) && !ie_match_stat(istate, alias, st, ce_option)) {
672                 /* Nothing changed, really */
673                 free(ce);
674                 if (!S_ISGITLINK(alias->ce_mode))
675                         ce_mark_uptodate(alias);
676                 alias->ce_flags |= CE_ADDED;
677                 return 0;
678         }
679         if (!intent_only) {
680                 if (index_path(ce->sha1, path, st, HASH_WRITE_OBJECT))
681                         return error("unable to index file %s", path);
682         } else
683                 set_object_name_for_intent_to_add_entry(ce);
684
685         if (ignore_case && alias && different_name(ce, alias))
686                 ce = create_alias_ce(ce, alias);
687         ce->ce_flags |= CE_ADDED;
688
689         /* It was suspected to be racily clean, but it turns out to be Ok */
690         was_same = (alias &&
691                     !ce_stage(alias) &&
692                     !hashcmp(alias->sha1, ce->sha1) &&
693                     ce->ce_mode == alias->ce_mode);
694
695         if (pretend)
696                 ;
697         else if (add_index_entry(istate, ce, add_option))
698                 return error("unable to add %s to index",path);
699         if (verbose && !was_same)
700                 printf("add '%s'\n", path);
701         return 0;
702 }
703
704 int add_file_to_index(struct index_state *istate, const char *path, int flags)
705 {
706         struct stat st;
707         if (lstat(path, &st))
708                 die_errno("unable to stat '%s'", path);
709         return add_to_index(istate, path, &st, flags);
710 }
711
712 struct cache_entry *make_cache_entry(unsigned int mode,
713                 const unsigned char *sha1, const char *path, int stage,
714                 unsigned int refresh_options)
715 {
716         int size, len;
717         struct cache_entry *ce;
718
719         if (!verify_path(path)) {
720                 error("Invalid path '%s'", path);
721                 return NULL;
722         }
723
724         len = strlen(path);
725         size = cache_entry_size(len);
726         ce = xcalloc(1, size);
727
728         hashcpy(ce->sha1, sha1);
729         memcpy(ce->name, path, len);
730         ce->ce_flags = create_ce_flags(stage);
731         ce->ce_namelen = len;
732         ce->ce_mode = create_ce_mode(mode);
733
734         return refresh_cache_entry(ce, refresh_options);
735 }
736
737 int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
738 {
739         int len = ce_namelen(a);
740         return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
741 }
742
743 /*
744  * We fundamentally don't like some paths: we don't want
745  * dot or dot-dot anywhere, and for obvious reasons don't
746  * want to recurse into ".git" either.
747  *
748  * Also, we don't want double slashes or slashes at the
749  * end that can make pathnames ambiguous.
750  */
751 static int verify_dotfile(const char *rest)
752 {
753         /*
754          * The first character was '.', but that
755          * has already been discarded, we now test
756          * the rest.
757          */
758
759         /* "." is not allowed */
760         if (*rest == '\0' || is_dir_sep(*rest))
761                 return 0;
762
763         switch (*rest) {
764         /*
765          * ".git" followed by  NUL or slash is bad. This
766          * shares the path end test with the ".." case.
767          */
768         case 'g':
769                 if (rest[1] != 'i')
770                         break;
771                 if (rest[2] != 't')
772                         break;
773                 rest += 2;
774         /* fallthrough */
775         case '.':
776                 if (rest[1] == '\0' || is_dir_sep(rest[1]))
777                         return 0;
778         }
779         return 1;
780 }
781
782 int verify_path(const char *path)
783 {
784         char c;
785
786         if (has_dos_drive_prefix(path))
787                 return 0;
788
789         goto inside;
790         for (;;) {
791                 if (!c)
792                         return 1;
793                 if (is_dir_sep(c)) {
794 inside:
795                         c = *path++;
796                         if ((c == '.' && !verify_dotfile(path)) ||
797                             is_dir_sep(c) || c == '\0')
798                                 return 0;
799                 }
800                 c = *path++;
801         }
802 }
803
804 /*
805  * Do we have another file that has the beginning components being a
806  * proper superset of the name we're trying to add?
807  */
808 static int has_file_name(struct index_state *istate,
809                          const struct cache_entry *ce, int pos, int ok_to_replace)
810 {
811         int retval = 0;
812         int len = ce_namelen(ce);
813         int stage = ce_stage(ce);
814         const char *name = ce->name;
815
816         while (pos < istate->cache_nr) {
817                 struct cache_entry *p = istate->cache[pos++];
818
819                 if (len >= ce_namelen(p))
820                         break;
821                 if (memcmp(name, p->name, len))
822                         break;
823                 if (ce_stage(p) != stage)
824                         continue;
825                 if (p->name[len] != '/')
826                         continue;
827                 if (p->ce_flags & CE_REMOVE)
828                         continue;
829                 retval = -1;
830                 if (!ok_to_replace)
831                         break;
832                 remove_index_entry_at(istate, --pos);
833         }
834         return retval;
835 }
836
837 /*
838  * Do we have another file with a pathname that is a proper
839  * subset of the name we're trying to add?
840  */
841 static int has_dir_name(struct index_state *istate,
842                         const struct cache_entry *ce, int pos, int ok_to_replace)
843 {
844         int retval = 0;
845         int stage = ce_stage(ce);
846         const char *name = ce->name;
847         const char *slash = name + ce_namelen(ce);
848
849         for (;;) {
850                 int len;
851
852                 for (;;) {
853                         if (*--slash == '/')
854                                 break;
855                         if (slash <= ce->name)
856                                 return retval;
857                 }
858                 len = slash - name;
859
860                 pos = index_name_stage_pos(istate, name, len, stage);
861                 if (pos >= 0) {
862                         /*
863                          * Found one, but not so fast.  This could
864                          * be a marker that says "I was here, but
865                          * I am being removed".  Such an entry is
866                          * not a part of the resulting tree, and
867                          * it is Ok to have a directory at the same
868                          * path.
869                          */
870                         if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
871                                 retval = -1;
872                                 if (!ok_to_replace)
873                                         break;
874                                 remove_index_entry_at(istate, pos);
875                                 continue;
876                         }
877                 }
878                 else
879                         pos = -pos-1;
880
881                 /*
882                  * Trivial optimization: if we find an entry that
883                  * already matches the sub-directory, then we know
884                  * we're ok, and we can exit.
885                  */
886                 while (pos < istate->cache_nr) {
887                         struct cache_entry *p = istate->cache[pos];
888                         if ((ce_namelen(p) <= len) ||
889                             (p->name[len] != '/') ||
890                             memcmp(p->name, name, len))
891                                 break; /* not our subdirectory */
892                         if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
893                                 /*
894                                  * p is at the same stage as our entry, and
895                                  * is a subdirectory of what we are looking
896                                  * at, so we cannot have conflicts at our
897                                  * level or anything shorter.
898                                  */
899                                 return retval;
900                         pos++;
901                 }
902         }
903         return retval;
904 }
905
906 /* We may be in a situation where we already have path/file and path
907  * is being added, or we already have path and path/file is being
908  * added.  Either one would result in a nonsense tree that has path
909  * twice when git-write-tree tries to write it out.  Prevent it.
910  *
911  * If ok-to-replace is specified, we remove the conflicting entries
912  * from the cache so the caller should recompute the insert position.
913  * When this happens, we return non-zero.
914  */
915 static int check_file_directory_conflict(struct index_state *istate,
916                                          const struct cache_entry *ce,
917                                          int pos, int ok_to_replace)
918 {
919         int retval;
920
921         /*
922          * When ce is an "I am going away" entry, we allow it to be added
923          */
924         if (ce->ce_flags & CE_REMOVE)
925                 return 0;
926
927         /*
928          * We check if the path is a sub-path of a subsequent pathname
929          * first, since removing those will not change the position
930          * in the array.
931          */
932         retval = has_file_name(istate, ce, pos, ok_to_replace);
933
934         /*
935          * Then check if the path might have a clashing sub-directory
936          * before it.
937          */
938         return retval + has_dir_name(istate, ce, pos, ok_to_replace);
939 }
940
941 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
942 {
943         int pos;
944         int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
945         int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
946         int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
947         int new_only = option & ADD_CACHE_NEW_ONLY;
948
949         cache_tree_invalidate_path(istate, ce->name);
950         pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
951
952         /* existing match? Just replace it. */
953         if (pos >= 0) {
954                 if (!new_only)
955                         replace_index_entry(istate, pos, ce);
956                 return 0;
957         }
958         pos = -pos-1;
959
960         /*
961          * Inserting a merged entry ("stage 0") into the index
962          * will always replace all non-merged entries..
963          */
964         if (pos < istate->cache_nr && ce_stage(ce) == 0) {
965                 while (ce_same_name(istate->cache[pos], ce)) {
966                         ok_to_add = 1;
967                         if (!remove_index_entry_at(istate, pos))
968                                 break;
969                 }
970         }
971
972         if (!ok_to_add)
973                 return -1;
974         if (!verify_path(ce->name))
975                 return error("Invalid path '%s'", ce->name);
976
977         if (!skip_df_check &&
978             check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
979                 if (!ok_to_replace)
980                         return error("'%s' appears as both a file and as a directory",
981                                      ce->name);
982                 pos = index_name_stage_pos(istate, ce->name, ce_namelen(ce), ce_stage(ce));
983                 pos = -pos-1;
984         }
985         return pos + 1;
986 }
987
988 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
989 {
990         int pos;
991
992         if (option & ADD_CACHE_JUST_APPEND)
993                 pos = istate->cache_nr;
994         else {
995                 int ret;
996                 ret = add_index_entry_with_check(istate, ce, option);
997                 if (ret <= 0)
998                         return ret;
999                 pos = ret - 1;
1000         }
1001
1002         /* Make sure the array is big enough .. */
1003         ALLOC_GROW(istate->cache, istate->cache_nr + 1, istate->cache_alloc);
1004
1005         /* Add it in.. */
1006         istate->cache_nr++;
1007         if (istate->cache_nr > pos + 1)
1008                 memmove(istate->cache + pos + 1,
1009                         istate->cache + pos,
1010                         (istate->cache_nr - pos - 1) * sizeof(ce));
1011         set_index_entry(istate, pos, ce);
1012         istate->cache_changed |= CE_ENTRY_ADDED;
1013         return 0;
1014 }
1015
1016 /*
1017  * "refresh" does not calculate a new sha1 file or bring the
1018  * cache up-to-date for mode/content changes. But what it
1019  * _does_ do is to "re-match" the stat information of a file
1020  * with the cache, so that you can refresh the cache for a
1021  * file that hasn't been changed but where the stat entry is
1022  * out of date.
1023  *
1024  * For example, you'd want to do this after doing a "git-read-tree",
1025  * to link up the stat cache details with the proper files.
1026  */
1027 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
1028                                              struct cache_entry *ce,
1029                                              unsigned int options, int *err,
1030                                              int *changed_ret)
1031 {
1032         struct stat st;
1033         struct cache_entry *updated;
1034         int changed, size;
1035         int refresh = options & CE_MATCH_REFRESH;
1036         int ignore_valid = options & CE_MATCH_IGNORE_VALID;
1037         int ignore_skip_worktree = options & CE_MATCH_IGNORE_SKIP_WORKTREE;
1038         int ignore_missing = options & CE_MATCH_IGNORE_MISSING;
1039
1040         if (!refresh || ce_uptodate(ce))
1041                 return ce;
1042
1043         /*
1044          * CE_VALID or CE_SKIP_WORKTREE means the user promised us
1045          * that the change to the work tree does not matter and told
1046          * us not to worry.
1047          */
1048         if (!ignore_skip_worktree && ce_skip_worktree(ce)) {
1049                 ce_mark_uptodate(ce);
1050                 return ce;
1051         }
1052         if (!ignore_valid && (ce->ce_flags & CE_VALID)) {
1053                 ce_mark_uptodate(ce);
1054                 return ce;
1055         }
1056
1057         if (lstat(ce->name, &st) < 0) {
1058                 if (ignore_missing && errno == ENOENT)
1059                         return ce;
1060                 if (err)
1061                         *err = errno;
1062                 return NULL;
1063         }
1064
1065         changed = ie_match_stat(istate, ce, &st, options);
1066         if (changed_ret)
1067                 *changed_ret = changed;
1068         if (!changed) {
1069                 /*
1070                  * The path is unchanged.  If we were told to ignore
1071                  * valid bit, then we did the actual stat check and
1072                  * found that the entry is unmodified.  If the entry
1073                  * is not marked VALID, this is the place to mark it
1074                  * valid again, under "assume unchanged" mode.
1075                  */
1076                 if (ignore_valid && assume_unchanged &&
1077                     !(ce->ce_flags & CE_VALID))
1078                         ; /* mark this one VALID again */
1079                 else {
1080                         /*
1081                          * We do not mark the index itself "modified"
1082                          * because CE_UPTODATE flag is in-core only;
1083                          * we are not going to write this change out.
1084                          */
1085                         if (!S_ISGITLINK(ce->ce_mode))
1086                                 ce_mark_uptodate(ce);
1087                         return ce;
1088                 }
1089         }
1090
1091         if (ie_modified(istate, ce, &st, options)) {
1092                 if (err)
1093                         *err = EINVAL;
1094                 return NULL;
1095         }
1096
1097         size = ce_size(ce);
1098         updated = xmalloc(size);
1099         memcpy(updated, ce, size);
1100         fill_stat_cache_info(updated, &st);
1101         /*
1102          * If ignore_valid is not set, we should leave CE_VALID bit
1103          * alone.  Otherwise, paths marked with --no-assume-unchanged
1104          * (i.e. things to be edited) will reacquire CE_VALID bit
1105          * automatically, which is not really what we want.
1106          */
1107         if (!ignore_valid && assume_unchanged &&
1108             !(ce->ce_flags & CE_VALID))
1109                 updated->ce_flags &= ~CE_VALID;
1110
1111         /* istate->cache_changed is updated in the caller */
1112         return updated;
1113 }
1114
1115 static void show_file(const char * fmt, const char * name, int in_porcelain,
1116                       int * first, const char *header_msg)
1117 {
1118         if (in_porcelain && *first && header_msg) {
1119                 printf("%s\n", header_msg);
1120                 *first = 0;
1121         }
1122         printf(fmt, name);
1123 }
1124
1125 int refresh_index(struct index_state *istate, unsigned int flags,
1126                   const struct pathspec *pathspec,
1127                   char *seen, const char *header_msg)
1128 {
1129         int i;
1130         int has_errors = 0;
1131         int really = (flags & REFRESH_REALLY) != 0;
1132         int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
1133         int quiet = (flags & REFRESH_QUIET) != 0;
1134         int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
1135         int ignore_submodules = (flags & REFRESH_IGNORE_SUBMODULES) != 0;
1136         int first = 1;
1137         int in_porcelain = (flags & REFRESH_IN_PORCELAIN);
1138         unsigned int options = (CE_MATCH_REFRESH |
1139                                 (really ? CE_MATCH_IGNORE_VALID : 0) |
1140                                 (not_new ? CE_MATCH_IGNORE_MISSING : 0));
1141         const char *modified_fmt;
1142         const char *deleted_fmt;
1143         const char *typechange_fmt;
1144         const char *added_fmt;
1145         const char *unmerged_fmt;
1146
1147         modified_fmt = (in_porcelain ? "M\t%s\n" : "%s: needs update\n");
1148         deleted_fmt = (in_porcelain ? "D\t%s\n" : "%s: needs update\n");
1149         typechange_fmt = (in_porcelain ? "T\t%s\n" : "%s needs update\n");
1150         added_fmt = (in_porcelain ? "A\t%s\n" : "%s needs update\n");
1151         unmerged_fmt = (in_porcelain ? "U\t%s\n" : "%s: needs merge\n");
1152         for (i = 0; i < istate->cache_nr; i++) {
1153                 struct cache_entry *ce, *new;
1154                 int cache_errno = 0;
1155                 int changed = 0;
1156                 int filtered = 0;
1157
1158                 ce = istate->cache[i];
1159                 if (ignore_submodules && S_ISGITLINK(ce->ce_mode))
1160                         continue;
1161
1162                 if (pathspec && !ce_path_match(ce, pathspec, seen))
1163                         filtered = 1;
1164
1165                 if (ce_stage(ce)) {
1166                         while ((i < istate->cache_nr) &&
1167                                ! strcmp(istate->cache[i]->name, ce->name))
1168                                 i++;
1169                         i--;
1170                         if (allow_unmerged)
1171                                 continue;
1172                         if (!filtered)
1173                                 show_file(unmerged_fmt, ce->name, in_porcelain,
1174                                           &first, header_msg);
1175                         has_errors = 1;
1176                         continue;
1177                 }
1178
1179                 if (filtered)
1180                         continue;
1181
1182                 new = refresh_cache_ent(istate, ce, options, &cache_errno, &changed);
1183                 if (new == ce)
1184                         continue;
1185                 if (!new) {
1186                         const char *fmt;
1187
1188                         if (really && cache_errno == EINVAL) {
1189                                 /* If we are doing --really-refresh that
1190                                  * means the index is not valid anymore.
1191                                  */
1192                                 ce->ce_flags &= ~CE_VALID;
1193                                 istate->cache_changed |= CE_ENTRY_CHANGED;
1194                         }
1195                         if (quiet)
1196                                 continue;
1197
1198                         if (cache_errno == ENOENT)
1199                                 fmt = deleted_fmt;
1200                         else if (ce->ce_flags & CE_INTENT_TO_ADD)
1201                                 fmt = added_fmt; /* must be before other checks */
1202                         else if (changed & TYPE_CHANGED)
1203                                 fmt = typechange_fmt;
1204                         else
1205                                 fmt = modified_fmt;
1206                         show_file(fmt,
1207                                   ce->name, in_porcelain, &first, header_msg);
1208                         has_errors = 1;
1209                         continue;
1210                 }
1211
1212                 replace_index_entry(istate, i, new);
1213         }
1214         return has_errors;
1215 }
1216
1217 static struct cache_entry *refresh_cache_entry(struct cache_entry *ce,
1218                                                unsigned int options)
1219 {
1220         return refresh_cache_ent(&the_index, ce, options, NULL, NULL);
1221 }
1222
1223
1224 /*****************************************************************
1225  * Index File I/O
1226  *****************************************************************/
1227
1228 #define INDEX_FORMAT_DEFAULT 3
1229
1230 static int index_format_config(const char *var, const char *value, void *cb)
1231 {
1232         unsigned int *version = cb;
1233         if (!strcmp(var, "index.version")) {
1234                 *version = git_config_int(var, value);
1235                 return 0;
1236         }
1237         return 1;
1238 }
1239
1240 static unsigned int get_index_format_default(void)
1241 {
1242         char *envversion = getenv("GIT_INDEX_VERSION");
1243         char *endp;
1244         unsigned int version = INDEX_FORMAT_DEFAULT;
1245
1246         if (!envversion) {
1247                 git_config(index_format_config, &version);
1248                 if (version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1249                         warning(_("index.version set, but the value is invalid.\n"
1250                                   "Using version %i"), INDEX_FORMAT_DEFAULT);
1251                         return INDEX_FORMAT_DEFAULT;
1252                 }
1253                 return version;
1254         }
1255
1256         version = strtoul(envversion, &endp, 10);
1257         if (*endp ||
1258             version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < version) {
1259                 warning(_("GIT_INDEX_VERSION set, but the value is invalid.\n"
1260                           "Using version %i"), INDEX_FORMAT_DEFAULT);
1261                 version = INDEX_FORMAT_DEFAULT;
1262         }
1263         return version;
1264 }
1265
1266 /*
1267  * dev/ino/uid/gid/size are also just tracked to the low 32 bits
1268  * Again - this is just a (very strong in practice) heuristic that
1269  * the inode hasn't changed.
1270  *
1271  * We save the fields in big-endian order to allow using the
1272  * index file over NFS transparently.
1273  */
1274 struct ondisk_cache_entry {
1275         struct cache_time ctime;
1276         struct cache_time mtime;
1277         uint32_t dev;
1278         uint32_t ino;
1279         uint32_t mode;
1280         uint32_t uid;
1281         uint32_t gid;
1282         uint32_t size;
1283         unsigned char sha1[20];
1284         uint16_t flags;
1285         char name[FLEX_ARRAY]; /* more */
1286 };
1287
1288 /*
1289  * This struct is used when CE_EXTENDED bit is 1
1290  * The struct must match ondisk_cache_entry exactly from
1291  * ctime till flags
1292  */
1293 struct ondisk_cache_entry_extended {
1294         struct cache_time ctime;
1295         struct cache_time mtime;
1296         uint32_t dev;
1297         uint32_t ino;
1298         uint32_t mode;
1299         uint32_t uid;
1300         uint32_t gid;
1301         uint32_t size;
1302         unsigned char sha1[20];
1303         uint16_t flags;
1304         uint16_t flags2;
1305         char name[FLEX_ARRAY]; /* more */
1306 };
1307
1308 /* These are only used for v3 or lower */
1309 #define align_flex_name(STRUCT,len) ((offsetof(struct STRUCT,name) + (len) + 8) & ~7)
1310 #define ondisk_cache_entry_size(len) align_flex_name(ondisk_cache_entry,len)
1311 #define ondisk_cache_entry_extended_size(len) align_flex_name(ondisk_cache_entry_extended,len)
1312 #define ondisk_ce_size(ce) (((ce)->ce_flags & CE_EXTENDED) ? \
1313                             ondisk_cache_entry_extended_size(ce_namelen(ce)) : \
1314                             ondisk_cache_entry_size(ce_namelen(ce)))
1315
1316 static int verify_hdr(struct cache_header *hdr, unsigned long size)
1317 {
1318         git_SHA_CTX c;
1319         unsigned char sha1[20];
1320         int hdr_version;
1321
1322         if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
1323                 return error("bad signature");
1324         hdr_version = ntohl(hdr->hdr_version);
1325         if (hdr_version < INDEX_FORMAT_LB || INDEX_FORMAT_UB < hdr_version)
1326                 return error("bad index version %d", hdr_version);
1327         git_SHA1_Init(&c);
1328         git_SHA1_Update(&c, hdr, size - 20);
1329         git_SHA1_Final(sha1, &c);
1330         if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1331                 return error("bad index file sha1 signature");
1332         return 0;
1333 }
1334
1335 static int read_index_extension(struct index_state *istate,
1336                                 const char *ext, void *data, unsigned long sz)
1337 {
1338         switch (CACHE_EXT(ext)) {
1339         case CACHE_EXT_TREE:
1340                 istate->cache_tree = cache_tree_read(data, sz);
1341                 break;
1342         case CACHE_EXT_RESOLVE_UNDO:
1343                 istate->resolve_undo = resolve_undo_read(data, sz);
1344                 break;
1345         case CACHE_EXT_LINK:
1346                 if (read_link_extension(istate, data, sz))
1347                         return -1;
1348                 break;
1349         default:
1350                 if (*ext < 'A' || 'Z' < *ext)
1351                         return error("index uses %.4s extension, which we do not understand",
1352                                      ext);
1353                 fprintf(stderr, "ignoring %.4s extension\n", ext);
1354                 break;
1355         }
1356         return 0;
1357 }
1358
1359 int read_index(struct index_state *istate)
1360 {
1361         return read_index_from(istate, get_index_file());
1362 }
1363
1364 static struct cache_entry *cache_entry_from_ondisk(struct ondisk_cache_entry *ondisk,
1365                                                    unsigned int flags,
1366                                                    const char *name,
1367                                                    size_t len)
1368 {
1369         struct cache_entry *ce = xmalloc(cache_entry_size(len));
1370
1371         ce->ce_stat_data.sd_ctime.sec = get_be32(&ondisk->ctime.sec);
1372         ce->ce_stat_data.sd_mtime.sec = get_be32(&ondisk->mtime.sec);
1373         ce->ce_stat_data.sd_ctime.nsec = get_be32(&ondisk->ctime.nsec);
1374         ce->ce_stat_data.sd_mtime.nsec = get_be32(&ondisk->mtime.nsec);
1375         ce->ce_stat_data.sd_dev   = get_be32(&ondisk->dev);
1376         ce->ce_stat_data.sd_ino   = get_be32(&ondisk->ino);
1377         ce->ce_mode  = get_be32(&ondisk->mode);
1378         ce->ce_stat_data.sd_uid   = get_be32(&ondisk->uid);
1379         ce->ce_stat_data.sd_gid   = get_be32(&ondisk->gid);
1380         ce->ce_stat_data.sd_size  = get_be32(&ondisk->size);
1381         ce->ce_flags = flags & ~CE_NAMEMASK;
1382         ce->ce_namelen = len;
1383         ce->index = 0;
1384         hashcpy(ce->sha1, ondisk->sha1);
1385         memcpy(ce->name, name, len);
1386         ce->name[len] = '\0';
1387         return ce;
1388 }
1389
1390 /*
1391  * Adjacent cache entries tend to share the leading paths, so it makes
1392  * sense to only store the differences in later entries.  In the v4
1393  * on-disk format of the index, each on-disk cache entry stores the
1394  * number of bytes to be stripped from the end of the previous name,
1395  * and the bytes to append to the result, to come up with its name.
1396  */
1397 static unsigned long expand_name_field(struct strbuf *name, const char *cp_)
1398 {
1399         const unsigned char *ep, *cp = (const unsigned char *)cp_;
1400         size_t len = decode_varint(&cp);
1401
1402         if (name->len < len)
1403                 die("malformed name field in the index");
1404         strbuf_remove(name, name->len - len, len);
1405         for (ep = cp; *ep; ep++)
1406                 ; /* find the end */
1407         strbuf_add(name, cp, ep - cp);
1408         return (const char *)ep + 1 - cp_;
1409 }
1410
1411 static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk,
1412                                             unsigned long *ent_size,
1413                                             struct strbuf *previous_name)
1414 {
1415         struct cache_entry *ce;
1416         size_t len;
1417         const char *name;
1418         unsigned int flags;
1419
1420         /* On-disk flags are just 16 bits */
1421         flags = get_be16(&ondisk->flags);
1422         len = flags & CE_NAMEMASK;
1423
1424         if (flags & CE_EXTENDED) {
1425                 struct ondisk_cache_entry_extended *ondisk2;
1426                 int extended_flags;
1427                 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
1428                 extended_flags = get_be16(&ondisk2->flags2) << 16;
1429                 /* We do not yet understand any bit out of CE_EXTENDED_FLAGS */
1430                 if (extended_flags & ~CE_EXTENDED_FLAGS)
1431                         die("Unknown index entry format %08x", extended_flags);
1432                 flags |= extended_flags;
1433                 name = ondisk2->name;
1434         }
1435         else
1436                 name = ondisk->name;
1437
1438         if (!previous_name) {
1439                 /* v3 and earlier */
1440                 if (len == CE_NAMEMASK)
1441                         len = strlen(name);
1442                 ce = cache_entry_from_ondisk(ondisk, flags, name, len);
1443
1444                 *ent_size = ondisk_ce_size(ce);
1445         } else {
1446                 unsigned long consumed;
1447                 consumed = expand_name_field(previous_name, name);
1448                 ce = cache_entry_from_ondisk(ondisk, flags,
1449                                              previous_name->buf,
1450                                              previous_name->len);
1451
1452                 *ent_size = (name - ((char *)ondisk)) + consumed;
1453         }
1454         return ce;
1455 }
1456
1457 /* remember to discard_cache() before reading a different cache! */
1458 static int do_read_index(struct index_state *istate, const char *path,
1459                          int must_exist)
1460 {
1461         int fd, i;
1462         struct stat st;
1463         unsigned long src_offset;
1464         struct cache_header *hdr;
1465         void *mmap;
1466         size_t mmap_size;
1467         struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
1468
1469         if (istate->initialized)
1470                 return istate->cache_nr;
1471
1472         istate->timestamp.sec = 0;
1473         istate->timestamp.nsec = 0;
1474         fd = open(path, O_RDONLY);
1475         if (fd < 0) {
1476                 if (!must_exist && errno == ENOENT)
1477                         return 0;
1478                 die_errno("%s: index file open failed", path);
1479         }
1480
1481         if (fstat(fd, &st))
1482                 die_errno("cannot stat the open index");
1483
1484         mmap_size = xsize_t(st.st_size);
1485         if (mmap_size < sizeof(struct cache_header) + 20)
1486                 die("index file smaller than expected");
1487
1488         mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1489         if (mmap == MAP_FAILED)
1490                 die_errno("unable to map index file");
1491         close(fd);
1492
1493         hdr = mmap;
1494         if (verify_hdr(hdr, mmap_size) < 0)
1495                 goto unmap;
1496
1497         hashcpy(istate->sha1, (const unsigned char *)hdr + mmap_size - 20);
1498         istate->version = ntohl(hdr->hdr_version);
1499         istate->cache_nr = ntohl(hdr->hdr_entries);
1500         istate->cache_alloc = alloc_nr(istate->cache_nr);
1501         istate->cache = xcalloc(istate->cache_alloc, sizeof(*istate->cache));
1502         istate->initialized = 1;
1503
1504         if (istate->version == 4)
1505                 previous_name = &previous_name_buf;
1506         else
1507                 previous_name = NULL;
1508
1509         src_offset = sizeof(*hdr);
1510         for (i = 0; i < istate->cache_nr; i++) {
1511                 struct ondisk_cache_entry *disk_ce;
1512                 struct cache_entry *ce;
1513                 unsigned long consumed;
1514
1515                 disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1516                 ce = create_from_disk(disk_ce, &consumed, previous_name);
1517                 set_index_entry(istate, i, ce);
1518
1519                 src_offset += consumed;
1520         }
1521         strbuf_release(&previous_name_buf);
1522         istate->timestamp.sec = st.st_mtime;
1523         istate->timestamp.nsec = ST_MTIME_NSEC(st);
1524
1525         while (src_offset <= mmap_size - 20 - 8) {
1526                 /* After an array of active_nr index entries,
1527                  * there can be arbitrary number of extended
1528                  * sections, each of which is prefixed with
1529                  * extension name (4-byte) and section length
1530                  * in 4-byte network byte order.
1531                  */
1532                 uint32_t extsize;
1533                 memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1534                 extsize = ntohl(extsize);
1535                 if (read_index_extension(istate,
1536                                          (const char *) mmap + src_offset,
1537                                          (char *) mmap + src_offset + 8,
1538                                          extsize) < 0)
1539                         goto unmap;
1540                 src_offset += 8;
1541                 src_offset += extsize;
1542         }
1543         munmap(mmap, mmap_size);
1544         return istate->cache_nr;
1545
1546 unmap:
1547         munmap(mmap, mmap_size);
1548         die("index file corrupt");
1549 }
1550
1551 int read_index_from(struct index_state *istate, const char *path)
1552 {
1553         struct split_index *split_index;
1554         int ret;
1555
1556         /* istate->initialized covers both .git/index and .git/sharedindex.xxx */
1557         if (istate->initialized)
1558                 return istate->cache_nr;
1559
1560         ret = do_read_index(istate, path, 0);
1561         split_index = istate->split_index;
1562         if (!split_index)
1563                 return ret;
1564
1565         if (is_null_sha1(split_index->base_sha1))
1566                 return ret;
1567         if (istate->cache_nr)
1568                 die("index in split-index mode must contain no entries");
1569
1570         if (split_index->base)
1571                 discard_index(split_index->base);
1572         else
1573                 split_index->base = xcalloc(1, sizeof(*split_index->base));
1574         ret = do_read_index(split_index->base,
1575                             git_path("sharedindex.%s",
1576                                      sha1_to_hex(split_index->base_sha1)), 1);
1577         if (hashcmp(split_index->base_sha1, split_index->base->sha1))
1578                 die("broken index, expect %s in %s, got %s",
1579                     sha1_to_hex(split_index->base_sha1),
1580                     git_path("sharedindex.%s",
1581                                      sha1_to_hex(split_index->base_sha1)),
1582                     sha1_to_hex(split_index->base->sha1));
1583         merge_base_index(istate);
1584         return ret;
1585 }
1586
1587 int is_index_unborn(struct index_state *istate)
1588 {
1589         return (!istate->cache_nr && !istate->timestamp.sec);
1590 }
1591
1592 int discard_index(struct index_state *istate)
1593 {
1594         int i;
1595
1596         for (i = 0; i < istate->cache_nr; i++) {
1597                 if (istate->cache[i]->index &&
1598                     istate->split_index &&
1599                     istate->split_index->base &&
1600                     istate->cache[i]->index <= istate->split_index->base->cache_nr &&
1601                     istate->cache[i] == istate->split_index->base->cache[istate->cache[i]->index - 1])
1602                         continue;
1603                 free(istate->cache[i]);
1604         }
1605         resolve_undo_clear_index(istate);
1606         istate->cache_nr = 0;
1607         istate->cache_changed = 0;
1608         istate->timestamp.sec = 0;
1609         istate->timestamp.nsec = 0;
1610         free_name_hash(istate);
1611         cache_tree_free(&(istate->cache_tree));
1612         istate->initialized = 0;
1613         free(istate->cache);
1614         istate->cache = NULL;
1615         istate->cache_alloc = 0;
1616         discard_split_index(istate);
1617         return 0;
1618 }
1619
1620 int unmerged_index(const struct index_state *istate)
1621 {
1622         int i;
1623         for (i = 0; i < istate->cache_nr; i++) {
1624                 if (ce_stage(istate->cache[i]))
1625                         return 1;
1626         }
1627         return 0;
1628 }
1629
1630 #define WRITE_BUFFER_SIZE 8192
1631 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1632 static unsigned long write_buffer_len;
1633
1634 static int ce_write_flush(git_SHA_CTX *context, int fd)
1635 {
1636         unsigned int buffered = write_buffer_len;
1637         if (buffered) {
1638                 git_SHA1_Update(context, write_buffer, buffered);
1639                 if (write_in_full(fd, write_buffer, buffered) != buffered)
1640                         return -1;
1641                 write_buffer_len = 0;
1642         }
1643         return 0;
1644 }
1645
1646 static int ce_write(git_SHA_CTX *context, int fd, void *data, unsigned int len)
1647 {
1648         while (len) {
1649                 unsigned int buffered = write_buffer_len;
1650                 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1651                 if (partial > len)
1652                         partial = len;
1653                 memcpy(write_buffer + buffered, data, partial);
1654                 buffered += partial;
1655                 if (buffered == WRITE_BUFFER_SIZE) {
1656                         write_buffer_len = buffered;
1657                         if (ce_write_flush(context, fd))
1658                                 return -1;
1659                         buffered = 0;
1660                 }
1661                 write_buffer_len = buffered;
1662                 len -= partial;
1663                 data = (char *) data + partial;
1664         }
1665         return 0;
1666 }
1667
1668 static int write_index_ext_header(git_SHA_CTX *context, int fd,
1669                                   unsigned int ext, unsigned int sz)
1670 {
1671         ext = htonl(ext);
1672         sz = htonl(sz);
1673         return ((ce_write(context, fd, &ext, 4) < 0) ||
1674                 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1675 }
1676
1677 static int ce_flush(git_SHA_CTX *context, int fd, unsigned char *sha1)
1678 {
1679         unsigned int left = write_buffer_len;
1680
1681         if (left) {
1682                 write_buffer_len = 0;
1683                 git_SHA1_Update(context, write_buffer, left);
1684         }
1685
1686         /* Flush first if not enough space for SHA1 signature */
1687         if (left + 20 > WRITE_BUFFER_SIZE) {
1688                 if (write_in_full(fd, write_buffer, left) != left)
1689                         return -1;
1690                 left = 0;
1691         }
1692
1693         /* Append the SHA1 signature at the end */
1694         git_SHA1_Final(write_buffer + left, context);
1695         hashcpy(sha1, write_buffer + left);
1696         left += 20;
1697         return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1698 }
1699
1700 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1701 {
1702         /*
1703          * The only thing we care about in this function is to smudge the
1704          * falsely clean entry due to touch-update-touch race, so we leave
1705          * everything else as they are.  We are called for entries whose
1706          * ce_stat_data.sd_mtime match the index file mtime.
1707          *
1708          * Note that this actually does not do much for gitlinks, for
1709          * which ce_match_stat_basic() always goes to the actual
1710          * contents.  The caller checks with is_racy_timestamp() which
1711          * always says "no" for gitlinks, so we are not called for them ;-)
1712          */
1713         struct stat st;
1714
1715         if (lstat(ce->name, &st) < 0)
1716                 return;
1717         if (ce_match_stat_basic(ce, &st))
1718                 return;
1719         if (ce_modified_check_fs(ce, &st)) {
1720                 /* This is "racily clean"; smudge it.  Note that this
1721                  * is a tricky code.  At first glance, it may appear
1722                  * that it can break with this sequence:
1723                  *
1724                  * $ echo xyzzy >frotz
1725                  * $ git-update-index --add frotz
1726                  * $ : >frotz
1727                  * $ sleep 3
1728                  * $ echo filfre >nitfol
1729                  * $ git-update-index --add nitfol
1730                  *
1731                  * but it does not.  When the second update-index runs,
1732                  * it notices that the entry "frotz" has the same timestamp
1733                  * as index, and if we were to smudge it by resetting its
1734                  * size to zero here, then the object name recorded
1735                  * in index is the 6-byte file but the cached stat information
1736                  * becomes zero --- which would then match what we would
1737                  * obtain from the filesystem next time we stat("frotz").
1738                  *
1739                  * However, the second update-index, before calling
1740                  * this function, notices that the cached size is 6
1741                  * bytes and what is on the filesystem is an empty
1742                  * file, and never calls us, so the cached size information
1743                  * for "frotz" stays 6 which does not match the filesystem.
1744                  */
1745                 ce->ce_stat_data.sd_size = 0;
1746         }
1747 }
1748
1749 /* Copy miscellaneous fields but not the name */
1750 static char *copy_cache_entry_to_ondisk(struct ondisk_cache_entry *ondisk,
1751                                        struct cache_entry *ce)
1752 {
1753         short flags;
1754
1755         ondisk->ctime.sec = htonl(ce->ce_stat_data.sd_ctime.sec);
1756         ondisk->mtime.sec = htonl(ce->ce_stat_data.sd_mtime.sec);
1757         ondisk->ctime.nsec = htonl(ce->ce_stat_data.sd_ctime.nsec);
1758         ondisk->mtime.nsec = htonl(ce->ce_stat_data.sd_mtime.nsec);
1759         ondisk->dev  = htonl(ce->ce_stat_data.sd_dev);
1760         ondisk->ino  = htonl(ce->ce_stat_data.sd_ino);
1761         ondisk->mode = htonl(ce->ce_mode);
1762         ondisk->uid  = htonl(ce->ce_stat_data.sd_uid);
1763         ondisk->gid  = htonl(ce->ce_stat_data.sd_gid);
1764         ondisk->size = htonl(ce->ce_stat_data.sd_size);
1765         hashcpy(ondisk->sha1, ce->sha1);
1766
1767         flags = ce->ce_flags & ~CE_NAMEMASK;
1768         flags |= (ce_namelen(ce) >= CE_NAMEMASK ? CE_NAMEMASK : ce_namelen(ce));
1769         ondisk->flags = htons(flags);
1770         if (ce->ce_flags & CE_EXTENDED) {
1771                 struct ondisk_cache_entry_extended *ondisk2;
1772                 ondisk2 = (struct ondisk_cache_entry_extended *)ondisk;
1773                 ondisk2->flags2 = htons((ce->ce_flags & CE_EXTENDED_FLAGS) >> 16);
1774                 return ondisk2->name;
1775         }
1776         else {
1777                 return ondisk->name;
1778         }
1779 }
1780
1781 static int ce_write_entry(git_SHA_CTX *c, int fd, struct cache_entry *ce,
1782                           struct strbuf *previous_name)
1783 {
1784         int size;
1785         struct ondisk_cache_entry *ondisk;
1786         char *name;
1787         int result;
1788
1789         if (!previous_name) {
1790                 size = ondisk_ce_size(ce);
1791                 ondisk = xcalloc(1, size);
1792                 name = copy_cache_entry_to_ondisk(ondisk, ce);
1793                 memcpy(name, ce->name, ce_namelen(ce));
1794         } else {
1795                 int common, to_remove, prefix_size;
1796                 unsigned char to_remove_vi[16];
1797                 for (common = 0;
1798                      (ce->name[common] &&
1799                       common < previous_name->len &&
1800                       ce->name[common] == previous_name->buf[common]);
1801                      common++)
1802                         ; /* still matching */
1803                 to_remove = previous_name->len - common;
1804                 prefix_size = encode_varint(to_remove, to_remove_vi);
1805
1806                 if (ce->ce_flags & CE_EXTENDED)
1807                         size = offsetof(struct ondisk_cache_entry_extended, name);
1808                 else
1809                         size = offsetof(struct ondisk_cache_entry, name);
1810                 size += prefix_size + (ce_namelen(ce) - common + 1);
1811
1812                 ondisk = xcalloc(1, size);
1813                 name = copy_cache_entry_to_ondisk(ondisk, ce);
1814                 memcpy(name, to_remove_vi, prefix_size);
1815                 memcpy(name + prefix_size, ce->name + common, ce_namelen(ce) - common);
1816
1817                 strbuf_splice(previous_name, common, to_remove,
1818                               ce->name + common, ce_namelen(ce) - common);
1819         }
1820
1821         result = ce_write(c, fd, ondisk, size);
1822         free(ondisk);
1823         return result;
1824 }
1825
1826 static int has_racy_timestamp(struct index_state *istate)
1827 {
1828         int entries = istate->cache_nr;
1829         int i;
1830
1831         for (i = 0; i < entries; i++) {
1832                 struct cache_entry *ce = istate->cache[i];
1833                 if (is_racy_timestamp(istate, ce))
1834                         return 1;
1835         }
1836         return 0;
1837 }
1838
1839 /*
1840  * Opportunistically update the index but do not complain if we can't
1841  */
1842 void update_index_if_able(struct index_state *istate, struct lock_file *lockfile)
1843 {
1844         if ((istate->cache_changed || has_racy_timestamp(istate)) &&
1845             write_locked_index(istate, lockfile, COMMIT_LOCK))
1846                 rollback_lock_file(lockfile);
1847 }
1848
1849 static int do_write_index(struct index_state *istate, int newfd)
1850 {
1851         git_SHA_CTX c;
1852         struct cache_header hdr;
1853         int i, err, removed, extended, hdr_version;
1854         struct cache_entry **cache = istate->cache;
1855         int entries = istate->cache_nr;
1856         struct stat st;
1857         struct strbuf previous_name_buf = STRBUF_INIT, *previous_name;
1858
1859         for (i = removed = extended = 0; i < entries; i++) {
1860                 if (cache[i]->ce_flags & CE_REMOVE)
1861                         removed++;
1862
1863                 /* reduce extended entries if possible */
1864                 cache[i]->ce_flags &= ~CE_EXTENDED;
1865                 if (cache[i]->ce_flags & CE_EXTENDED_FLAGS) {
1866                         extended++;
1867                         cache[i]->ce_flags |= CE_EXTENDED;
1868                 }
1869         }
1870
1871         if (!istate->version)
1872                 istate->version = get_index_format_default();
1873
1874         /* demote version 3 to version 2 when the latter suffices */
1875         if (istate->version == 3 || istate->version == 2)
1876                 istate->version = extended ? 3 : 2;
1877
1878         hdr_version = istate->version;
1879
1880         hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1881         hdr.hdr_version = htonl(hdr_version);
1882         hdr.hdr_entries = htonl(entries - removed);
1883
1884         git_SHA1_Init(&c);
1885         if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1886                 return -1;
1887
1888         previous_name = (hdr_version == 4) ? &previous_name_buf : NULL;
1889         for (i = 0; i < entries; i++) {
1890                 struct cache_entry *ce = cache[i];
1891                 if (ce->ce_flags & CE_REMOVE)
1892                         continue;
1893                 if (!ce_uptodate(ce) && is_racy_timestamp(istate, ce))
1894                         ce_smudge_racily_clean_entry(ce);
1895                 if (is_null_sha1(ce->sha1)) {
1896                         static const char msg[] = "cache entry has null sha1: %s";
1897                         static int allow = -1;
1898
1899                         if (allow < 0)
1900                                 allow = git_env_bool("GIT_ALLOW_NULL_SHA1", 0);
1901                         if (allow)
1902                                 warning(msg, ce->name);
1903                         else
1904                                 return error(msg, ce->name);
1905                 }
1906                 if (ce_write_entry(&c, newfd, ce, previous_name) < 0)
1907                         return -1;
1908         }
1909         strbuf_release(&previous_name_buf);
1910
1911         /* Write extension data here */
1912         if (istate->split_index) {
1913                 struct strbuf sb = STRBUF_INIT;
1914
1915                 err = write_link_extension(&sb, istate) < 0 ||
1916                         write_index_ext_header(&c, newfd, CACHE_EXT_LINK,
1917                                                sb.len) < 0 ||
1918                         ce_write(&c, newfd, sb.buf, sb.len) < 0;
1919                 strbuf_release(&sb);
1920                 if (err)
1921                         return -1;
1922         }
1923         if (istate->cache_tree) {
1924                 struct strbuf sb = STRBUF_INIT;
1925
1926                 cache_tree_write(&sb, istate->cache_tree);
1927                 err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1928                         || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1929                 strbuf_release(&sb);
1930                 if (err)
1931                         return -1;
1932         }
1933         if (istate->resolve_undo) {
1934                 struct strbuf sb = STRBUF_INIT;
1935
1936                 resolve_undo_write(&sb, istate->resolve_undo);
1937                 err = write_index_ext_header(&c, newfd, CACHE_EXT_RESOLVE_UNDO,
1938                                              sb.len) < 0
1939                         || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1940                 strbuf_release(&sb);
1941                 if (err)
1942                         return -1;
1943         }
1944
1945         if (ce_flush(&c, newfd, istate->sha1) || fstat(newfd, &st))
1946                 return -1;
1947         istate->timestamp.sec = (unsigned int)st.st_mtime;
1948         istate->timestamp.nsec = ST_MTIME_NSEC(st);
1949         return 0;
1950 }
1951
1952 void set_alternate_index_output(const char *name)
1953 {
1954         alternate_index_output = name;
1955 }
1956
1957 static int commit_locked_index(struct lock_file *lk)
1958 {
1959         if (alternate_index_output) {
1960                 if (lk->fd >= 0 && close_lock_file(lk))
1961                         return -1;
1962                 if (rename(lk->filename, alternate_index_output))
1963                         return -1;
1964                 lk->filename[0] = 0;
1965                 return 0;
1966         } else {
1967                 return commit_lock_file(lk);
1968         }
1969 }
1970
1971 static int do_write_locked_index(struct index_state *istate, struct lock_file *lock,
1972                                  unsigned flags)
1973 {
1974         int ret = do_write_index(istate, lock->fd);
1975         if (ret)
1976                 return ret;
1977         assert((flags & (COMMIT_LOCK | CLOSE_LOCK)) !=
1978                (COMMIT_LOCK | CLOSE_LOCK));
1979         if (flags & COMMIT_LOCK)
1980                 return commit_locked_index(lock);
1981         else if (flags & CLOSE_LOCK)
1982                 return close_lock_file(lock);
1983         else
1984                 return ret;
1985 }
1986
1987 static int write_split_index(struct index_state *istate,
1988                              struct lock_file *lock,
1989                              unsigned flags)
1990 {
1991         int ret;
1992         prepare_to_write_split_index(istate);
1993         ret = do_write_locked_index(istate, lock, flags);
1994         finish_writing_split_index(istate);
1995         return ret;
1996 }
1997
1998 int write_locked_index(struct index_state *istate, struct lock_file *lock,
1999                        unsigned flags)
2000 {
2001         struct split_index *si = istate->split_index;
2002
2003         if (!si || (istate->cache_changed & ~EXTMASK)) {
2004                 if (si)
2005                         hashclr(si->base_sha1);
2006                 return do_write_locked_index(istate, lock, flags);
2007         }
2008
2009         return write_split_index(istate, lock, flags);
2010 }
2011
2012 /*
2013  * Read the index file that is potentially unmerged into given
2014  * index_state, dropping any unmerged entries.  Returns true if
2015  * the index is unmerged.  Callers who want to refuse to work
2016  * from an unmerged state can call this and check its return value,
2017  * instead of calling read_cache().
2018  */
2019 int read_index_unmerged(struct index_state *istate)
2020 {
2021         int i;
2022         int unmerged = 0;
2023
2024         read_index(istate);
2025         for (i = 0; i < istate->cache_nr; i++) {
2026                 struct cache_entry *ce = istate->cache[i];
2027                 struct cache_entry *new_ce;
2028                 int size, len;
2029
2030                 if (!ce_stage(ce))
2031                         continue;
2032                 unmerged = 1;
2033                 len = ce_namelen(ce);
2034                 size = cache_entry_size(len);
2035                 new_ce = xcalloc(1, size);
2036                 memcpy(new_ce->name, ce->name, len);
2037                 new_ce->ce_flags = create_ce_flags(0) | CE_CONFLICTED;
2038                 new_ce->ce_namelen = len;
2039                 new_ce->ce_mode = ce->ce_mode;
2040                 if (add_index_entry(istate, new_ce, 0))
2041                         return error("%s: cannot drop to stage #0",
2042                                      new_ce->name);
2043                 i = index_name_pos(istate, new_ce->name, len);
2044         }
2045         return unmerged;
2046 }
2047
2048 /*
2049  * Returns 1 if the path is an "other" path with respect to
2050  * the index; that is, the path is not mentioned in the index at all,
2051  * either as a file, a directory with some files in the index,
2052  * or as an unmerged entry.
2053  *
2054  * We helpfully remove a trailing "/" from directories so that
2055  * the output of read_directory can be used as-is.
2056  */
2057 int index_name_is_other(const struct index_state *istate, const char *name,
2058                 int namelen)
2059 {
2060         int pos;
2061         if (namelen && name[namelen - 1] == '/')
2062                 namelen--;
2063         pos = index_name_pos(istate, name, namelen);
2064         if (0 <= pos)
2065                 return 0;       /* exact match */
2066         pos = -pos - 1;
2067         if (pos < istate->cache_nr) {
2068                 struct cache_entry *ce = istate->cache[pos];
2069                 if (ce_namelen(ce) == namelen &&
2070                     !memcmp(ce->name, name, namelen))
2071                         return 0; /* Yup, this one exists unmerged */
2072         }
2073         return 1;
2074 }
2075
2076 void *read_blob_data_from_index(struct index_state *istate, const char *path, unsigned long *size)
2077 {
2078         int pos, len;
2079         unsigned long sz;
2080         enum object_type type;
2081         void *data;
2082
2083         len = strlen(path);
2084         pos = index_name_pos(istate, path, len);
2085         if (pos < 0) {
2086                 /*
2087                  * We might be in the middle of a merge, in which
2088                  * case we would read stage #2 (ours).
2089                  */
2090                 int i;
2091                 for (i = -pos - 1;
2092                      (pos < 0 && i < istate->cache_nr &&
2093                       !strcmp(istate->cache[i]->name, path));
2094                      i++)
2095                         if (ce_stage(istate->cache[i]) == 2)
2096                                 pos = i;
2097         }
2098         if (pos < 0)
2099                 return NULL;
2100         data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
2101         if (!data || type != OBJ_BLOB) {
2102                 free(data);
2103                 return NULL;
2104         }
2105         if (size)
2106                 *size = sz;
2107         return data;
2108 }
2109
2110 void stat_validity_clear(struct stat_validity *sv)
2111 {
2112         free(sv->sd);
2113         sv->sd = NULL;
2114 }
2115
2116 int stat_validity_check(struct stat_validity *sv, const char *path)
2117 {
2118         struct stat st;
2119
2120         if (stat(path, &st) < 0)
2121                 return sv->sd == NULL;
2122         if (!sv->sd)
2123                 return 0;
2124         return S_ISREG(st.st_mode) && !match_stat_data(sv->sd, &st);
2125 }
2126
2127 void stat_validity_update(struct stat_validity *sv, int fd)
2128 {
2129         struct stat st;
2130
2131         if (fstat(fd, &st) < 0 || !S_ISREG(st.st_mode))
2132                 stat_validity_clear(sv);
2133         else {
2134                 if (!sv->sd)
2135                         sv->sd = xcalloc(1, sizeof(struct stat_data));
2136                 fill_stat_data(sv->sd, &st);
2137         }
2138 }