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