Merge branch 'bd/qsort'
[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
12 /* Index extensions.
13  *
14  * The first letter should be 'A'..'Z' for extensions that are not
15  * necessary for a correct operation (i.e. optimization data).
16  * When new extensions are added that _needs_ to be understood in
17  * order to correctly interpret the index file, pick character that
18  * is outside the range, to cause the reader to abort.
19  */
20
21 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
22 #define CACHE_EXT_TREE 0x54524545       /* "TREE" */
23
24 struct index_state the_index;
25
26 static unsigned int hash_name(const char *name, int namelen)
27 {
28         unsigned int hash = 0x123;
29
30         do {
31                 unsigned char c = *name++;
32                 hash = hash*101 + c;
33         } while (--namelen);
34         return hash;
35 }
36
37 static void hash_index_entry(struct index_state *istate, struct cache_entry *ce)
38 {
39         void **pos;
40         unsigned int hash = hash_name(ce->name, ce_namelen(ce));
41
42         pos = insert_hash(hash, ce, &istate->name_hash);
43         if (pos) {
44                 ce->next = *pos;
45                 *pos = ce;
46         }
47 }
48
49 static void lazy_init_name_hash(struct index_state *istate)
50 {
51         int nr;
52
53         if (istate->name_hash_initialized)
54                 return;
55         for (nr = 0; nr < istate->cache_nr; nr++)
56                 hash_index_entry(istate, istate->cache[nr]);
57         istate->name_hash_initialized = 1;
58 }
59
60 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
61 {
62         istate->cache[nr] = ce;
63         if (istate->name_hash_initialized)
64                 hash_index_entry(istate, ce);
65 }
66
67 /*
68  * We don't actually *remove* it, we can just mark it invalid so that
69  * we won't find it in lookups.
70  *
71  * Not only would we have to search the lists (simple enough), but
72  * we'd also have to rehash other hash buckets in case this makes the
73  * hash bucket empty (common). So it's much better to just mark
74  * it.
75  */
76 static void remove_hash_entry(struct index_state *istate, struct cache_entry *ce)
77 {
78         ce->ce_flags |= CE_UNHASHED;
79 }
80
81 static void replace_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
82 {
83         struct cache_entry *old = istate->cache[nr];
84
85         if (ce != old) {
86                 remove_hash_entry(istate, old);
87                 set_index_entry(istate, nr, ce);
88         }
89         istate->cache_changed = 1;
90 }
91
92 int index_name_exists(struct index_state *istate, const char *name, int namelen)
93 {
94         unsigned int hash = hash_name(name, namelen);
95         struct cache_entry *ce;
96
97         lazy_init_name_hash(istate);
98         ce = lookup_hash(hash, &istate->name_hash);
99
100         while (ce) {
101                 if (!(ce->ce_flags & CE_UNHASHED)) {
102                         if (!cache_name_compare(name, namelen, ce->name, ce->ce_flags))
103                                 return 1;
104                 }
105                 ce = ce->next;
106         }
107         return 0;
108 }
109
110 /*
111  * This only updates the "non-critical" parts of the directory
112  * cache, ie the parts that aren't tracked by GIT, and only used
113  * to validate the cache.
114  */
115 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
116 {
117         ce->ce_ctime = st->st_ctime;
118         ce->ce_mtime = st->st_mtime;
119         ce->ce_dev = st->st_dev;
120         ce->ce_ino = st->st_ino;
121         ce->ce_uid = st->st_uid;
122         ce->ce_gid = st->st_gid;
123         ce->ce_size = st->st_size;
124
125         if (assume_unchanged)
126                 ce->ce_flags |= CE_VALID;
127
128         if (S_ISREG(st->st_mode))
129                 ce_mark_uptodate(ce);
130 }
131
132 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
133 {
134         int match = -1;
135         int fd = open(ce->name, O_RDONLY);
136
137         if (fd >= 0) {
138                 unsigned char sha1[20];
139                 if (!index_fd(sha1, fd, st, 0, OBJ_BLOB, ce->name))
140                         match = hashcmp(sha1, ce->sha1);
141                 /* index_fd() closed the file descriptor already */
142         }
143         return match;
144 }
145
146 static int ce_compare_link(struct cache_entry *ce, size_t expected_size)
147 {
148         int match = -1;
149         char *target;
150         void *buffer;
151         unsigned long size;
152         enum object_type type;
153         int len;
154
155         target = xmalloc(expected_size);
156         len = readlink(ce->name, target, expected_size);
157         if (len != expected_size) {
158                 free(target);
159                 return -1;
160         }
161         buffer = read_sha1_file(ce->sha1, &type, &size);
162         if (!buffer) {
163                 free(target);
164                 return -1;
165         }
166         if (size == expected_size)
167                 match = memcmp(buffer, target, size);
168         free(buffer);
169         free(target);
170         return match;
171 }
172
173 static int ce_compare_gitlink(struct cache_entry *ce)
174 {
175         unsigned char sha1[20];
176
177         /*
178          * We don't actually require that the .git directory
179          * under GITLINK directory be a valid git directory. It
180          * might even be missing (in case nobody populated that
181          * sub-project).
182          *
183          * If so, we consider it always to match.
184          */
185         if (resolve_gitlink_ref(ce->name, "HEAD", sha1) < 0)
186                 return 0;
187         return hashcmp(sha1, ce->sha1);
188 }
189
190 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
191 {
192         switch (st->st_mode & S_IFMT) {
193         case S_IFREG:
194                 if (ce_compare_data(ce, st))
195                         return DATA_CHANGED;
196                 break;
197         case S_IFLNK:
198                 if (ce_compare_link(ce, xsize_t(st->st_size)))
199                         return DATA_CHANGED;
200                 break;
201         case S_IFDIR:
202                 if (S_ISGITLINK(ce->ce_mode))
203                         return 0;
204         default:
205                 return TYPE_CHANGED;
206         }
207         return 0;
208 }
209
210 static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
211 {
212         unsigned int changed = 0;
213
214         if (ce->ce_flags & CE_REMOVE)
215                 return MODE_CHANGED | DATA_CHANGED | TYPE_CHANGED;
216
217         switch (ce->ce_mode & S_IFMT) {
218         case S_IFREG:
219                 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
220                 /* We consider only the owner x bit to be relevant for
221                  * "mode changes"
222                  */
223                 if (trust_executable_bit &&
224                     (0100 & (ce->ce_mode ^ st->st_mode)))
225                         changed |= MODE_CHANGED;
226                 break;
227         case S_IFLNK:
228                 if (!S_ISLNK(st->st_mode) &&
229                     (has_symlinks || !S_ISREG(st->st_mode)))
230                         changed |= TYPE_CHANGED;
231                 break;
232         case S_IFGITLINK:
233                 if (!S_ISDIR(st->st_mode))
234                         changed |= TYPE_CHANGED;
235                 else if (ce_compare_gitlink(ce))
236                         changed |= DATA_CHANGED;
237                 return changed;
238         default:
239                 die("internal error: ce_mode is %o", ce->ce_mode);
240         }
241         if (ce->ce_mtime != (unsigned int) st->st_mtime)
242                 changed |= MTIME_CHANGED;
243         if (ce->ce_ctime != (unsigned int) st->st_ctime)
244                 changed |= CTIME_CHANGED;
245
246         if (ce->ce_uid != (unsigned int) st->st_uid ||
247             ce->ce_gid != (unsigned int) st->st_gid)
248                 changed |= OWNER_CHANGED;
249         if (ce->ce_ino != (unsigned int) st->st_ino)
250                 changed |= INODE_CHANGED;
251
252 #ifdef USE_STDEV
253         /*
254          * st_dev breaks on network filesystems where different
255          * clients will have different views of what "device"
256          * the filesystem is on
257          */
258         if (ce->ce_dev != (unsigned int) st->st_dev)
259                 changed |= INODE_CHANGED;
260 #endif
261
262         if (ce->ce_size != (unsigned int) st->st_size)
263                 changed |= DATA_CHANGED;
264
265         return changed;
266 }
267
268 static int is_racy_timestamp(struct index_state *istate, struct cache_entry *ce)
269 {
270         return (istate->timestamp &&
271                 ((unsigned int)istate->timestamp) <= ce->ce_mtime);
272 }
273
274 int ie_match_stat(struct index_state *istate,
275                   struct cache_entry *ce, struct stat *st,
276                   unsigned int options)
277 {
278         unsigned int changed;
279         int ignore_valid = options & CE_MATCH_IGNORE_VALID;
280         int assume_racy_is_modified = options & CE_MATCH_RACY_IS_DIRTY;
281
282         /*
283          * If it's marked as always valid in the index, it's
284          * valid whatever the checked-out copy says.
285          */
286         if (!ignore_valid && (ce->ce_flags & CE_VALID))
287                 return 0;
288
289         changed = ce_match_stat_basic(ce, st);
290
291         /*
292          * Within 1 second of this sequence:
293          *      echo xyzzy >file && git-update-index --add file
294          * running this command:
295          *      echo frotz >file
296          * would give a falsely clean cache entry.  The mtime and
297          * length match the cache, and other stat fields do not change.
298          *
299          * We could detect this at update-index time (the cache entry
300          * being registered/updated records the same time as "now")
301          * and delay the return from git-update-index, but that would
302          * effectively mean we can make at most one commit per second,
303          * which is not acceptable.  Instead, we check cache entries
304          * whose mtime are the same as the index file timestamp more
305          * carefully than others.
306          */
307         if (!changed && is_racy_timestamp(istate, ce)) {
308                 if (assume_racy_is_modified)
309                         changed |= DATA_CHANGED;
310                 else
311                         changed |= ce_modified_check_fs(ce, st);
312         }
313
314         return changed;
315 }
316
317 int ie_modified(struct index_state *istate,
318                 struct cache_entry *ce, struct stat *st, unsigned int options)
319 {
320         int changed, changed_fs;
321
322         changed = ie_match_stat(istate, ce, st, options);
323         if (!changed)
324                 return 0;
325         /*
326          * If the mode or type has changed, there's no point in trying
327          * to refresh the entry - it's not going to match
328          */
329         if (changed & (MODE_CHANGED | TYPE_CHANGED))
330                 return changed;
331
332         /* Immediately after read-tree or update-index --cacheinfo,
333          * the length field is zero.  For other cases the ce_size
334          * should match the SHA1 recorded in the index entry.
335          */
336         if ((changed & DATA_CHANGED) && ce->ce_size != 0)
337                 return changed;
338
339         changed_fs = ce_modified_check_fs(ce, st);
340         if (changed_fs)
341                 return changed | changed_fs;
342         return 0;
343 }
344
345 int base_name_compare(const char *name1, int len1, int mode1,
346                       const char *name2, int len2, int mode2)
347 {
348         unsigned char c1, c2;
349         int len = len1 < len2 ? len1 : len2;
350         int cmp;
351
352         cmp = memcmp(name1, name2, len);
353         if (cmp)
354                 return cmp;
355         c1 = name1[len];
356         c2 = name2[len];
357         if (!c1 && S_ISDIR(mode1))
358                 c1 = '/';
359         if (!c2 && S_ISDIR(mode2))
360                 c2 = '/';
361         return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
362 }
363
364 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
365 {
366         int len1 = flags1 & CE_NAMEMASK;
367         int len2 = flags2 & CE_NAMEMASK;
368         int len = len1 < len2 ? len1 : len2;
369         int cmp;
370
371         cmp = memcmp(name1, name2, len);
372         if (cmp)
373                 return cmp;
374         if (len1 < len2)
375                 return -1;
376         if (len1 > len2)
377                 return 1;
378
379         /* Compare stages  */
380         flags1 &= CE_STAGEMASK;
381         flags2 &= CE_STAGEMASK;
382
383         if (flags1 < flags2)
384                 return -1;
385         if (flags1 > flags2)
386                 return 1;
387         return 0;
388 }
389
390 int index_name_pos(struct index_state *istate, const char *name, int namelen)
391 {
392         int first, last;
393
394         first = 0;
395         last = istate->cache_nr;
396         while (last > first) {
397                 int next = (last + first) >> 1;
398                 struct cache_entry *ce = istate->cache[next];
399                 int cmp = cache_name_compare(name, namelen, ce->name, ce->ce_flags);
400                 if (!cmp)
401                         return next;
402                 if (cmp < 0) {
403                         last = next;
404                         continue;
405                 }
406                 first = next+1;
407         }
408         return -first-1;
409 }
410
411 /* Remove entry, return true if there are more entries to go.. */
412 int remove_index_entry_at(struct index_state *istate, int pos)
413 {
414         struct cache_entry *ce = istate->cache[pos];
415
416         remove_hash_entry(istate, ce);
417         istate->cache_changed = 1;
418         istate->cache_nr--;
419         if (pos >= istate->cache_nr)
420                 return 0;
421         memmove(istate->cache + pos,
422                 istate->cache + pos + 1,
423                 (istate->cache_nr - pos) * sizeof(struct cache_entry *));
424         return 1;
425 }
426
427 int remove_file_from_index(struct index_state *istate, const char *path)
428 {
429         int pos = index_name_pos(istate, path, strlen(path));
430         if (pos < 0)
431                 pos = -pos-1;
432         cache_tree_invalidate_path(istate->cache_tree, path);
433         while (pos < istate->cache_nr && !strcmp(istate->cache[pos]->name, path))
434                 remove_index_entry_at(istate, pos);
435         return 0;
436 }
437
438 static int compare_name(struct cache_entry *ce, const char *path, int namelen)
439 {
440         return namelen != ce_namelen(ce) || memcmp(path, ce->name, namelen);
441 }
442
443 static int index_name_pos_also_unmerged(struct index_state *istate,
444         const char *path, int namelen)
445 {
446         int pos = index_name_pos(istate, path, namelen);
447         struct cache_entry *ce;
448
449         if (pos >= 0)
450                 return pos;
451
452         /* maybe unmerged? */
453         pos = -1 - pos;
454         if (pos >= istate->cache_nr ||
455                         compare_name((ce = istate->cache[pos]), path, namelen))
456                 return -1;
457
458         /* order of preference: stage 2, 1, 3 */
459         if (ce_stage(ce) == 1 && pos + 1 < istate->cache_nr &&
460                         ce_stage((ce = istate->cache[pos + 1])) == 2 &&
461                         !compare_name(ce, path, namelen))
462                 pos++;
463         return pos;
464 }
465
466 int add_file_to_index(struct index_state *istate, const char *path, int verbose)
467 {
468         int size, namelen, pos;
469         struct stat st;
470         struct cache_entry *ce;
471         unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY;
472
473         if (lstat(path, &st))
474                 die("%s: unable to stat (%s)", path, strerror(errno));
475
476         if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode) && !S_ISDIR(st.st_mode))
477                 die("%s: can only add regular files, symbolic links or git-directories", path);
478
479         namelen = strlen(path);
480         if (S_ISDIR(st.st_mode)) {
481                 while (namelen && path[namelen-1] == '/')
482                         namelen--;
483         }
484         size = cache_entry_size(namelen);
485         ce = xcalloc(1, size);
486         memcpy(ce->name, path, namelen);
487         ce->ce_flags = namelen;
488         fill_stat_cache_info(ce, &st);
489
490         if (trust_executable_bit && has_symlinks)
491                 ce->ce_mode = create_ce_mode(st.st_mode);
492         else {
493                 /* If there is an existing entry, pick the mode bits and type
494                  * from it, otherwise assume unexecutable regular file.
495                  */
496                 struct cache_entry *ent;
497                 int pos = index_name_pos_also_unmerged(istate, path, namelen);
498
499                 ent = (0 <= pos) ? istate->cache[pos] : NULL;
500                 ce->ce_mode = ce_mode_from_stat(ent, st.st_mode);
501         }
502
503         pos = index_name_pos(istate, ce->name, namelen);
504         if (0 <= pos &&
505             !ce_stage(istate->cache[pos]) &&
506             !ie_match_stat(istate, istate->cache[pos], &st, ce_option)) {
507                 /* Nothing changed, really */
508                 free(ce);
509                 ce_mark_uptodate(istate->cache[pos]);
510                 return 0;
511         }
512
513         if (index_path(ce->sha1, path, &st, 1))
514                 die("unable to index file %s", path);
515         if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE))
516                 die("unable to add %s to index",path);
517         if (verbose)
518                 printf("add '%s'\n", path);
519         return 0;
520 }
521
522 struct cache_entry *make_cache_entry(unsigned int mode,
523                 const unsigned char *sha1, const char *path, int stage,
524                 int refresh)
525 {
526         int size, len;
527         struct cache_entry *ce;
528
529         if (!verify_path(path))
530                 return NULL;
531
532         len = strlen(path);
533         size = cache_entry_size(len);
534         ce = xcalloc(1, size);
535
536         hashcpy(ce->sha1, sha1);
537         memcpy(ce->name, path, len);
538         ce->ce_flags = create_ce_flags(len, stage);
539         ce->ce_mode = create_ce_mode(mode);
540
541         if (refresh)
542                 return refresh_cache_entry(ce, 0);
543
544         return ce;
545 }
546
547 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
548 {
549         int len = ce_namelen(a);
550         return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
551 }
552
553 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
554 {
555         const char *match, *name;
556         int len;
557
558         if (!pathspec)
559                 return 1;
560
561         len = ce_namelen(ce);
562         name = ce->name;
563         while ((match = *pathspec++) != NULL) {
564                 int matchlen = strlen(match);
565                 if (matchlen > len)
566                         continue;
567                 if (memcmp(name, match, matchlen))
568                         continue;
569                 if (matchlen && name[matchlen-1] == '/')
570                         return 1;
571                 if (name[matchlen] == '/' || !name[matchlen])
572                         return 1;
573                 if (!matchlen)
574                         return 1;
575         }
576         return 0;
577 }
578
579 /*
580  * We fundamentally don't like some paths: we don't want
581  * dot or dot-dot anywhere, and for obvious reasons don't
582  * want to recurse into ".git" either.
583  *
584  * Also, we don't want double slashes or slashes at the
585  * end that can make pathnames ambiguous.
586  */
587 static int verify_dotfile(const char *rest)
588 {
589         /*
590          * The first character was '.', but that
591          * has already been discarded, we now test
592          * the rest.
593          */
594         switch (*rest) {
595         /* "." is not allowed */
596         case '\0': case '/':
597                 return 0;
598
599         /*
600          * ".git" followed by  NUL or slash is bad. This
601          * shares the path end test with the ".." case.
602          */
603         case 'g':
604                 if (rest[1] != 'i')
605                         break;
606                 if (rest[2] != 't')
607                         break;
608                 rest += 2;
609         /* fallthrough */
610         case '.':
611                 if (rest[1] == '\0' || rest[1] == '/')
612                         return 0;
613         }
614         return 1;
615 }
616
617 int verify_path(const char *path)
618 {
619         char c;
620
621         goto inside;
622         for (;;) {
623                 if (!c)
624                         return 1;
625                 if (c == '/') {
626 inside:
627                         c = *path++;
628                         switch (c) {
629                         default:
630                                 continue;
631                         case '/': case '\0':
632                                 break;
633                         case '.':
634                                 if (verify_dotfile(path))
635                                         continue;
636                         }
637                         return 0;
638                 }
639                 c = *path++;
640         }
641 }
642
643 /*
644  * Do we have another file that has the beginning components being a
645  * proper superset of the name we're trying to add?
646  */
647 static int has_file_name(struct index_state *istate,
648                          const struct cache_entry *ce, int pos, int ok_to_replace)
649 {
650         int retval = 0;
651         int len = ce_namelen(ce);
652         int stage = ce_stage(ce);
653         const char *name = ce->name;
654
655         while (pos < istate->cache_nr) {
656                 struct cache_entry *p = istate->cache[pos++];
657
658                 if (len >= ce_namelen(p))
659                         break;
660                 if (memcmp(name, p->name, len))
661                         break;
662                 if (ce_stage(p) != stage)
663                         continue;
664                 if (p->name[len] != '/')
665                         continue;
666                 if (p->ce_flags & CE_REMOVE)
667                         continue;
668                 retval = -1;
669                 if (!ok_to_replace)
670                         break;
671                 remove_index_entry_at(istate, --pos);
672         }
673         return retval;
674 }
675
676 /*
677  * Do we have another file with a pathname that is a proper
678  * subset of the name we're trying to add?
679  */
680 static int has_dir_name(struct index_state *istate,
681                         const struct cache_entry *ce, int pos, int ok_to_replace)
682 {
683         int retval = 0;
684         int stage = ce_stage(ce);
685         const char *name = ce->name;
686         const char *slash = name + ce_namelen(ce);
687
688         for (;;) {
689                 int len;
690
691                 for (;;) {
692                         if (*--slash == '/')
693                                 break;
694                         if (slash <= ce->name)
695                                 return retval;
696                 }
697                 len = slash - name;
698
699                 pos = index_name_pos(istate, name, create_ce_flags(len, stage));
700                 if (pos >= 0) {
701                         /*
702                          * Found one, but not so fast.  This could
703                          * be a marker that says "I was here, but
704                          * I am being removed".  Such an entry is
705                          * not a part of the resulting tree, and
706                          * it is Ok to have a directory at the same
707                          * path.
708                          */
709                         if (!(istate->cache[pos]->ce_flags & CE_REMOVE)) {
710                                 retval = -1;
711                                 if (!ok_to_replace)
712                                         break;
713                                 remove_index_entry_at(istate, pos);
714                                 continue;
715                         }
716                 }
717                 else
718                         pos = -pos-1;
719
720                 /*
721                  * Trivial optimization: if we find an entry that
722                  * already matches the sub-directory, then we know
723                  * we're ok, and we can exit.
724                  */
725                 while (pos < istate->cache_nr) {
726                         struct cache_entry *p = istate->cache[pos];
727                         if ((ce_namelen(p) <= len) ||
728                             (p->name[len] != '/') ||
729                             memcmp(p->name, name, len))
730                                 break; /* not our subdirectory */
731                         if (ce_stage(p) == stage && !(p->ce_flags & CE_REMOVE))
732                                 /*
733                                  * p is at the same stage as our entry, and
734                                  * is a subdirectory of what we are looking
735                                  * at, so we cannot have conflicts at our
736                                  * level or anything shorter.
737                                  */
738                                 return retval;
739                         pos++;
740                 }
741         }
742         return retval;
743 }
744
745 /* We may be in a situation where we already have path/file and path
746  * is being added, or we already have path and path/file is being
747  * added.  Either one would result in a nonsense tree that has path
748  * twice when git-write-tree tries to write it out.  Prevent it.
749  *
750  * If ok-to-replace is specified, we remove the conflicting entries
751  * from the cache so the caller should recompute the insert position.
752  * When this happens, we return non-zero.
753  */
754 static int check_file_directory_conflict(struct index_state *istate,
755                                          const struct cache_entry *ce,
756                                          int pos, int ok_to_replace)
757 {
758         int retval;
759
760         /*
761          * When ce is an "I am going away" entry, we allow it to be added
762          */
763         if (ce->ce_flags & CE_REMOVE)
764                 return 0;
765
766         /*
767          * We check if the path is a sub-path of a subsequent pathname
768          * first, since removing those will not change the position
769          * in the array.
770          */
771         retval = has_file_name(istate, ce, pos, ok_to_replace);
772
773         /*
774          * Then check if the path might have a clashing sub-directory
775          * before it.
776          */
777         return retval + has_dir_name(istate, ce, pos, ok_to_replace);
778 }
779
780 static int add_index_entry_with_check(struct index_state *istate, struct cache_entry *ce, int option)
781 {
782         int pos;
783         int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
784         int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
785         int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
786
787         cache_tree_invalidate_path(istate->cache_tree, ce->name);
788         pos = index_name_pos(istate, ce->name, ce->ce_flags);
789
790         /* existing match? Just replace it. */
791         if (pos >= 0) {
792                 replace_index_entry(istate, pos, ce);
793                 return 0;
794         }
795         pos = -pos-1;
796
797         /*
798          * Inserting a merged entry ("stage 0") into the index
799          * will always replace all non-merged entries..
800          */
801         if (pos < istate->cache_nr && ce_stage(ce) == 0) {
802                 while (ce_same_name(istate->cache[pos], ce)) {
803                         ok_to_add = 1;
804                         if (!remove_index_entry_at(istate, pos))
805                                 break;
806                 }
807         }
808
809         if (!ok_to_add)
810                 return -1;
811         if (!verify_path(ce->name))
812                 return -1;
813
814         if (!skip_df_check &&
815             check_file_directory_conflict(istate, ce, pos, ok_to_replace)) {
816                 if (!ok_to_replace)
817                         return error("'%s' appears as both a file and as a directory",
818                                      ce->name);
819                 pos = index_name_pos(istate, ce->name, ce->ce_flags);
820                 pos = -pos-1;
821         }
822         return pos + 1;
823 }
824
825 int add_index_entry(struct index_state *istate, struct cache_entry *ce, int option)
826 {
827         int pos;
828
829         if (option & ADD_CACHE_JUST_APPEND)
830                 pos = istate->cache_nr;
831         else {
832                 int ret;
833                 ret = add_index_entry_with_check(istate, ce, option);
834                 if (ret <= 0)
835                         return ret;
836                 pos = ret - 1;
837         }
838
839         /* Make sure the array is big enough .. */
840         if (istate->cache_nr == istate->cache_alloc) {
841                 istate->cache_alloc = alloc_nr(istate->cache_alloc);
842                 istate->cache = xrealloc(istate->cache,
843                                         istate->cache_alloc * sizeof(struct cache_entry *));
844         }
845
846         /* Add it in.. */
847         istate->cache_nr++;
848         if (istate->cache_nr > pos + 1)
849                 memmove(istate->cache + pos + 1,
850                         istate->cache + pos,
851                         (istate->cache_nr - pos - 1) * sizeof(ce));
852         set_index_entry(istate, pos, ce);
853         istate->cache_changed = 1;
854         return 0;
855 }
856
857 /*
858  * "refresh" does not calculate a new sha1 file or bring the
859  * cache up-to-date for mode/content changes. But what it
860  * _does_ do is to "re-match" the stat information of a file
861  * with the cache, so that you can refresh the cache for a
862  * file that hasn't been changed but where the stat entry is
863  * out of date.
864  *
865  * For example, you'd want to do this after doing a "git-read-tree",
866  * to link up the stat cache details with the proper files.
867  */
868 static struct cache_entry *refresh_cache_ent(struct index_state *istate,
869                                              struct cache_entry *ce,
870                                              unsigned int options, int *err)
871 {
872         struct stat st;
873         struct cache_entry *updated;
874         int changed, size;
875         int ignore_valid = options & CE_MATCH_IGNORE_VALID;
876
877         if (ce_uptodate(ce))
878                 return ce;
879
880         if (lstat(ce->name, &st) < 0) {
881                 if (err)
882                         *err = errno;
883                 return NULL;
884         }
885
886         changed = ie_match_stat(istate, ce, &st, options);
887         if (!changed) {
888                 /*
889                  * The path is unchanged.  If we were told to ignore
890                  * valid bit, then we did the actual stat check and
891                  * found that the entry is unmodified.  If the entry
892                  * is not marked VALID, this is the place to mark it
893                  * valid again, under "assume unchanged" mode.
894                  */
895                 if (ignore_valid && assume_unchanged &&
896                     !(ce->ce_flags & CE_VALID))
897                         ; /* mark this one VALID again */
898                 else {
899                         /*
900                          * We do not mark the index itself "modified"
901                          * because CE_UPTODATE flag is in-core only;
902                          * we are not going to write this change out.
903                          */
904                         ce_mark_uptodate(ce);
905                         return ce;
906                 }
907         }
908
909         if (ie_modified(istate, ce, &st, options)) {
910                 if (err)
911                         *err = EINVAL;
912                 return NULL;
913         }
914
915         size = ce_size(ce);
916         updated = xmalloc(size);
917         memcpy(updated, ce, size);
918         fill_stat_cache_info(updated, &st);
919         /*
920          * If ignore_valid is not set, we should leave CE_VALID bit
921          * alone.  Otherwise, paths marked with --no-assume-unchanged
922          * (i.e. things to be edited) will reacquire CE_VALID bit
923          * automatically, which is not really what we want.
924          */
925         if (!ignore_valid && assume_unchanged &&
926             !(ce->ce_flags & CE_VALID))
927                 updated->ce_flags &= ~CE_VALID;
928
929         return updated;
930 }
931
932 int refresh_index(struct index_state *istate, unsigned int flags, const char **pathspec, char *seen)
933 {
934         int i;
935         int has_errors = 0;
936         int really = (flags & REFRESH_REALLY) != 0;
937         int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
938         int quiet = (flags & REFRESH_QUIET) != 0;
939         int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
940         unsigned int options = really ? CE_MATCH_IGNORE_VALID : 0;
941
942         for (i = 0; i < istate->cache_nr; i++) {
943                 struct cache_entry *ce, *new;
944                 int cache_errno = 0;
945
946                 ce = istate->cache[i];
947                 if (ce_stage(ce)) {
948                         while ((i < istate->cache_nr) &&
949                                ! strcmp(istate->cache[i]->name, ce->name))
950                                 i++;
951                         i--;
952                         if (allow_unmerged)
953                                 continue;
954                         printf("%s: needs merge\n", ce->name);
955                         has_errors = 1;
956                         continue;
957                 }
958
959                 if (pathspec && !match_pathspec(pathspec, ce->name, strlen(ce->name), 0, seen))
960                         continue;
961
962                 new = refresh_cache_ent(istate, ce, options, &cache_errno);
963                 if (new == ce)
964                         continue;
965                 if (!new) {
966                         if (not_new && cache_errno == ENOENT)
967                                 continue;
968                         if (really && cache_errno == EINVAL) {
969                                 /* If we are doing --really-refresh that
970                                  * means the index is not valid anymore.
971                                  */
972                                 ce->ce_flags &= ~CE_VALID;
973                                 istate->cache_changed = 1;
974                         }
975                         if (quiet)
976                                 continue;
977                         printf("%s: needs update\n", ce->name);
978                         has_errors = 1;
979                         continue;
980                 }
981
982                 replace_index_entry(istate, i, new);
983         }
984         return has_errors;
985 }
986
987 struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
988 {
989         return refresh_cache_ent(&the_index, ce, really, NULL);
990 }
991
992 static int verify_hdr(struct cache_header *hdr, unsigned long size)
993 {
994         SHA_CTX c;
995         unsigned char sha1[20];
996
997         if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
998                 return error("bad signature");
999         if (hdr->hdr_version != htonl(2))
1000                 return error("bad index version");
1001         SHA1_Init(&c);
1002         SHA1_Update(&c, hdr, size - 20);
1003         SHA1_Final(sha1, &c);
1004         if (hashcmp(sha1, (unsigned char *)hdr + size - 20))
1005                 return error("bad index file sha1 signature");
1006         return 0;
1007 }
1008
1009 static int read_index_extension(struct index_state *istate,
1010                                 const char *ext, void *data, unsigned long sz)
1011 {
1012         switch (CACHE_EXT(ext)) {
1013         case CACHE_EXT_TREE:
1014                 istate->cache_tree = cache_tree_read(data, sz);
1015                 break;
1016         default:
1017                 if (*ext < 'A' || 'Z' < *ext)
1018                         return error("index uses %.4s extension, which we do not understand",
1019                                      ext);
1020                 fprintf(stderr, "ignoring %.4s extension\n", ext);
1021                 break;
1022         }
1023         return 0;
1024 }
1025
1026 int read_index(struct index_state *istate)
1027 {
1028         return read_index_from(istate, get_index_file());
1029 }
1030
1031 static void convert_from_disk(struct ondisk_cache_entry *ondisk, struct cache_entry *ce)
1032 {
1033         size_t len;
1034
1035         ce->ce_ctime = ntohl(ondisk->ctime.sec);
1036         ce->ce_mtime = ntohl(ondisk->mtime.sec);
1037         ce->ce_dev   = ntohl(ondisk->dev);
1038         ce->ce_ino   = ntohl(ondisk->ino);
1039         ce->ce_mode  = ntohl(ondisk->mode);
1040         ce->ce_uid   = ntohl(ondisk->uid);
1041         ce->ce_gid   = ntohl(ondisk->gid);
1042         ce->ce_size  = ntohl(ondisk->size);
1043         /* On-disk flags are just 16 bits */
1044         ce->ce_flags = ntohs(ondisk->flags);
1045         hashcpy(ce->sha1, ondisk->sha1);
1046
1047         len = ce->ce_flags & CE_NAMEMASK;
1048         if (len == CE_NAMEMASK)
1049                 len = strlen(ondisk->name);
1050         /*
1051          * NEEDSWORK: If the original index is crafted, this copy could
1052          * go unchecked.
1053          */
1054         memcpy(ce->name, ondisk->name, len + 1);
1055 }
1056
1057 static inline size_t estimate_cache_size(size_t ondisk_size, unsigned int entries)
1058 {
1059         long per_entry;
1060
1061         per_entry = sizeof(struct cache_entry) - sizeof(struct ondisk_cache_entry);
1062
1063         /*
1064          * Alignment can cause differences. This should be "alignof", but
1065          * since that's a gcc'ism, just use the size of a pointer.
1066          */
1067         per_entry += sizeof(void *);
1068         return ondisk_size + entries*per_entry;
1069 }
1070
1071 /* remember to discard_cache() before reading a different cache! */
1072 int read_index_from(struct index_state *istate, const char *path)
1073 {
1074         int fd, i;
1075         struct stat st;
1076         unsigned long src_offset, dst_offset;
1077         struct cache_header *hdr;
1078         void *mmap;
1079         size_t mmap_size;
1080
1081         errno = EBUSY;
1082         if (istate->alloc)
1083                 return istate->cache_nr;
1084
1085         errno = ENOENT;
1086         istate->timestamp = 0;
1087         fd = open(path, O_RDONLY);
1088         if (fd < 0) {
1089                 if (errno == ENOENT)
1090                         return 0;
1091                 die("index file open failed (%s)", strerror(errno));
1092         }
1093
1094         if (fstat(fd, &st))
1095                 die("cannot stat the open index (%s)", strerror(errno));
1096
1097         errno = EINVAL;
1098         mmap_size = xsize_t(st.st_size);
1099         if (mmap_size < sizeof(struct cache_header) + 20)
1100                 die("index file smaller than expected");
1101
1102         mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
1103         close(fd);
1104         if (mmap == MAP_FAILED)
1105                 die("unable to map index file");
1106
1107         hdr = mmap;
1108         if (verify_hdr(hdr, mmap_size) < 0)
1109                 goto unmap;
1110
1111         istate->cache_nr = ntohl(hdr->hdr_entries);
1112         istate->cache_alloc = alloc_nr(istate->cache_nr);
1113         istate->cache = xcalloc(istate->cache_alloc, sizeof(struct cache_entry *));
1114
1115         /*
1116          * The disk format is actually larger than the in-memory format,
1117          * due to space for nsec etc, so even though the in-memory one
1118          * has room for a few  more flags, we can allocate using the same
1119          * index size
1120          */
1121         istate->alloc = xmalloc(estimate_cache_size(mmap_size, istate->cache_nr));
1122
1123         src_offset = sizeof(*hdr);
1124         dst_offset = 0;
1125         for (i = 0; i < istate->cache_nr; i++) {
1126                 struct ondisk_cache_entry *disk_ce;
1127                 struct cache_entry *ce;
1128
1129                 disk_ce = (struct ondisk_cache_entry *)((char *)mmap + src_offset);
1130                 ce = (struct cache_entry *)((char *)istate->alloc + dst_offset);
1131                 convert_from_disk(disk_ce, ce);
1132                 set_index_entry(istate, i, ce);
1133
1134                 src_offset += ondisk_ce_size(ce);
1135                 dst_offset += ce_size(ce);
1136         }
1137         istate->timestamp = st.st_mtime;
1138         while (src_offset <= mmap_size - 20 - 8) {
1139                 /* After an array of active_nr index entries,
1140                  * there can be arbitrary number of extended
1141                  * sections, each of which is prefixed with
1142                  * extension name (4-byte) and section length
1143                  * in 4-byte network byte order.
1144                  */
1145                 unsigned long extsize;
1146                 memcpy(&extsize, (char *)mmap + src_offset + 4, 4);
1147                 extsize = ntohl(extsize);
1148                 if (read_index_extension(istate,
1149                                          (const char *) mmap + src_offset,
1150                                          (char *) mmap + src_offset + 8,
1151                                          extsize) < 0)
1152                         goto unmap;
1153                 src_offset += 8;
1154                 src_offset += extsize;
1155         }
1156         munmap(mmap, mmap_size);
1157         return istate->cache_nr;
1158
1159 unmap:
1160         munmap(mmap, mmap_size);
1161         errno = EINVAL;
1162         die("index file corrupt");
1163 }
1164
1165 int discard_index(struct index_state *istate)
1166 {
1167         istate->cache_nr = 0;
1168         istate->cache_changed = 0;
1169         istate->timestamp = 0;
1170         free_hash(&istate->name_hash);
1171         cache_tree_free(&(istate->cache_tree));
1172         free(istate->alloc);
1173         istate->alloc = NULL;
1174
1175         /* no need to throw away allocated active_cache */
1176         return 0;
1177 }
1178
1179 #define WRITE_BUFFER_SIZE 8192
1180 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
1181 static unsigned long write_buffer_len;
1182
1183 static int ce_write_flush(SHA_CTX *context, int fd)
1184 {
1185         unsigned int buffered = write_buffer_len;
1186         if (buffered) {
1187                 SHA1_Update(context, write_buffer, buffered);
1188                 if (write_in_full(fd, write_buffer, buffered) != buffered)
1189                         return -1;
1190                 write_buffer_len = 0;
1191         }
1192         return 0;
1193 }
1194
1195 static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
1196 {
1197         while (len) {
1198                 unsigned int buffered = write_buffer_len;
1199                 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
1200                 if (partial > len)
1201                         partial = len;
1202                 memcpy(write_buffer + buffered, data, partial);
1203                 buffered += partial;
1204                 if (buffered == WRITE_BUFFER_SIZE) {
1205                         write_buffer_len = buffered;
1206                         if (ce_write_flush(context, fd))
1207                                 return -1;
1208                         buffered = 0;
1209                 }
1210                 write_buffer_len = buffered;
1211                 len -= partial;
1212                 data = (char *) data + partial;
1213         }
1214         return 0;
1215 }
1216
1217 static int write_index_ext_header(SHA_CTX *context, int fd,
1218                                   unsigned int ext, unsigned int sz)
1219 {
1220         ext = htonl(ext);
1221         sz = htonl(sz);
1222         return ((ce_write(context, fd, &ext, 4) < 0) ||
1223                 (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0;
1224 }
1225
1226 static int ce_flush(SHA_CTX *context, int fd)
1227 {
1228         unsigned int left = write_buffer_len;
1229
1230         if (left) {
1231                 write_buffer_len = 0;
1232                 SHA1_Update(context, write_buffer, left);
1233         }
1234
1235         /* Flush first if not enough space for SHA1 signature */
1236         if (left + 20 > WRITE_BUFFER_SIZE) {
1237                 if (write_in_full(fd, write_buffer, left) != left)
1238                         return -1;
1239                 left = 0;
1240         }
1241
1242         /* Append the SHA1 signature at the end */
1243         SHA1_Final(write_buffer + left, context);
1244         left += 20;
1245         return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0;
1246 }
1247
1248 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
1249 {
1250         /*
1251          * The only thing we care about in this function is to smudge the
1252          * falsely clean entry due to touch-update-touch race, so we leave
1253          * everything else as they are.  We are called for entries whose
1254          * ce_mtime match the index file mtime.
1255          */
1256         struct stat st;
1257
1258         if (lstat(ce->name, &st) < 0)
1259                 return;
1260         if (ce_match_stat_basic(ce, &st))
1261                 return;
1262         if (ce_modified_check_fs(ce, &st)) {
1263                 /* This is "racily clean"; smudge it.  Note that this
1264                  * is a tricky code.  At first glance, it may appear
1265                  * that it can break with this sequence:
1266                  *
1267                  * $ echo xyzzy >frotz
1268                  * $ git-update-index --add frotz
1269                  * $ : >frotz
1270                  * $ sleep 3
1271                  * $ echo filfre >nitfol
1272                  * $ git-update-index --add nitfol
1273                  *
1274                  * but it does not.  When the second update-index runs,
1275                  * it notices that the entry "frotz" has the same timestamp
1276                  * as index, and if we were to smudge it by resetting its
1277                  * size to zero here, then the object name recorded
1278                  * in index is the 6-byte file but the cached stat information
1279                  * becomes zero --- which would then match what we would
1280                  * obtain from the filesystem next time we stat("frotz").
1281                  *
1282                  * However, the second update-index, before calling
1283                  * this function, notices that the cached size is 6
1284                  * bytes and what is on the filesystem is an empty
1285                  * file, and never calls us, so the cached size information
1286                  * for "frotz" stays 6 which does not match the filesystem.
1287                  */
1288                 ce->ce_size = 0;
1289         }
1290 }
1291
1292 static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce)
1293 {
1294         int size = ondisk_ce_size(ce);
1295         struct ondisk_cache_entry *ondisk = xcalloc(1, size);
1296
1297         ondisk->ctime.sec = htonl(ce->ce_ctime);
1298         ondisk->ctime.nsec = 0;
1299         ondisk->mtime.sec = htonl(ce->ce_mtime);
1300         ondisk->mtime.nsec = 0;
1301         ondisk->dev  = htonl(ce->ce_dev);
1302         ondisk->ino  = htonl(ce->ce_ino);
1303         ondisk->mode = htonl(ce->ce_mode);
1304         ondisk->uid  = htonl(ce->ce_uid);
1305         ondisk->gid  = htonl(ce->ce_gid);
1306         ondisk->size = htonl(ce->ce_size);
1307         hashcpy(ondisk->sha1, ce->sha1);
1308         ondisk->flags = htons(ce->ce_flags);
1309         memcpy(ondisk->name, ce->name, ce_namelen(ce));
1310
1311         return ce_write(c, fd, ondisk, size);
1312 }
1313
1314 int write_index(struct index_state *istate, int newfd)
1315 {
1316         SHA_CTX c;
1317         struct cache_header hdr;
1318         int i, err, removed;
1319         struct cache_entry **cache = istate->cache;
1320         int entries = istate->cache_nr;
1321
1322         for (i = removed = 0; i < entries; i++)
1323                 if (cache[i]->ce_flags & CE_REMOVE)
1324                         removed++;
1325
1326         hdr.hdr_signature = htonl(CACHE_SIGNATURE);
1327         hdr.hdr_version = htonl(2);
1328         hdr.hdr_entries = htonl(entries - removed);
1329
1330         SHA1_Init(&c);
1331         if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
1332                 return -1;
1333
1334         for (i = 0; i < entries; i++) {
1335                 struct cache_entry *ce = cache[i];
1336                 if (ce->ce_flags & CE_REMOVE)
1337                         continue;
1338                 if (is_racy_timestamp(istate, ce))
1339                         ce_smudge_racily_clean_entry(ce);
1340                 if (ce_write_entry(&c, newfd, ce) < 0)
1341                         return -1;
1342         }
1343
1344         /* Write extension data here */
1345         if (istate->cache_tree) {
1346                 struct strbuf sb;
1347
1348                 strbuf_init(&sb, 0);
1349                 cache_tree_write(&sb, istate->cache_tree);
1350                 err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0
1351                         || ce_write(&c, newfd, sb.buf, sb.len) < 0;
1352                 strbuf_release(&sb);
1353                 if (err)
1354                         return -1;
1355         }
1356         return ce_flush(&c, newfd);
1357 }