2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
7 #include "cache-tree.h"
11 * The first letter should be 'A'..'Z' for extensions that are not
12 * necessary for a correct operation (i.e. optimization data).
13 * When new extensions are added that _needs_ to be understood in
14 * order to correctly interpret the index file, pick character that
15 * is outside the range, to cause the reader to abort.
18 #define CACHE_EXT(s) ( (s[0]<<24)|(s[1]<<16)|(s[2]<<8)|(s[3]) )
19 #define CACHE_EXT_TREE 0x54524545 /* "TREE" */
21 struct cache_entry **active_cache = NULL;
22 static time_t index_file_timestamp;
23 unsigned int active_nr = 0, active_alloc = 0, active_cache_changed = 0;
25 struct cache_tree *active_cache_tree = NULL;
29 static void *cache_mmap = NULL;
30 static size_t cache_mmap_size = 0;
33 * This only updates the "non-critical" parts of the directory
34 * cache, ie the parts that aren't tracked by GIT, and only used
35 * to validate the cache.
37 void fill_stat_cache_info(struct cache_entry *ce, struct stat *st)
39 ce->ce_ctime.sec = htonl(st->st_ctime);
40 ce->ce_mtime.sec = htonl(st->st_mtime);
42 ce->ce_ctime.nsec = htonl(st->st_ctim.tv_nsec);
43 ce->ce_mtime.nsec = htonl(st->st_mtim.tv_nsec);
45 ce->ce_dev = htonl(st->st_dev);
46 ce->ce_ino = htonl(st->st_ino);
47 ce->ce_uid = htonl(st->st_uid);
48 ce->ce_gid = htonl(st->st_gid);
49 ce->ce_size = htonl(st->st_size);
52 ce->ce_flags |= htons(CE_VALID);
55 static int ce_compare_data(struct cache_entry *ce, struct stat *st)
58 int fd = open(ce->name, O_RDONLY);
61 unsigned char sha1[20];
62 if (!index_fd(sha1, fd, st, 0, NULL))
63 match = memcmp(sha1, ce->sha1, 20);
64 /* index_fd() closed the file descriptor already */
69 static int ce_compare_link(struct cache_entry *ce, unsigned long expected_size)
78 target = xmalloc(expected_size);
79 len = readlink(ce->name, target, expected_size);
80 if (len != expected_size) {
84 buffer = read_sha1_file(ce->sha1, type, &size);
89 if (size == expected_size)
90 match = memcmp(buffer, target, size);
96 static int ce_modified_check_fs(struct cache_entry *ce, struct stat *st)
98 switch (st->st_mode & S_IFMT) {
100 if (ce_compare_data(ce, st))
104 if (ce_compare_link(ce, st->st_size))
113 static int ce_match_stat_basic(struct cache_entry *ce, struct stat *st)
115 unsigned int changed = 0;
117 switch (ntohl(ce->ce_mode) & S_IFMT) {
119 changed |= !S_ISREG(st->st_mode) ? TYPE_CHANGED : 0;
120 /* We consider only the owner x bit to be relevant for
123 if (trust_executable_bit &&
124 (0100 & (ntohl(ce->ce_mode) ^ st->st_mode)))
125 changed |= MODE_CHANGED;
128 changed |= !S_ISLNK(st->st_mode) ? TYPE_CHANGED : 0;
131 die("internal error: ce_mode is %o", ntohl(ce->ce_mode));
133 if (ce->ce_mtime.sec != htonl(st->st_mtime))
134 changed |= MTIME_CHANGED;
135 if (ce->ce_ctime.sec != htonl(st->st_ctime))
136 changed |= CTIME_CHANGED;
140 * nsec seems unreliable - not all filesystems support it, so
141 * as long as it is in the inode cache you get right nsec
142 * but after it gets flushed, you get zero nsec.
144 if (ce->ce_mtime.nsec != htonl(st->st_mtim.tv_nsec))
145 changed |= MTIME_CHANGED;
146 if (ce->ce_ctime.nsec != htonl(st->st_ctim.tv_nsec))
147 changed |= CTIME_CHANGED;
150 if (ce->ce_uid != htonl(st->st_uid) ||
151 ce->ce_gid != htonl(st->st_gid))
152 changed |= OWNER_CHANGED;
153 if (ce->ce_ino != htonl(st->st_ino))
154 changed |= INODE_CHANGED;
158 * st_dev breaks on network filesystems where different
159 * clients will have different views of what "device"
160 * the filesystem is on
162 if (ce->ce_dev != htonl(st->st_dev))
163 changed |= INODE_CHANGED;
166 if (ce->ce_size != htonl(st->st_size))
167 changed |= DATA_CHANGED;
172 int ce_match_stat(struct cache_entry *ce, struct stat *st, int ignore_valid)
174 unsigned int changed;
177 * If it's marked as always valid in the index, it's
178 * valid whatever the checked-out copy says.
180 if (!ignore_valid && (ce->ce_flags & htons(CE_VALID)))
183 changed = ce_match_stat_basic(ce, st);
186 * Within 1 second of this sequence:
187 * echo xyzzy >file && git-update-index --add file
188 * running this command:
190 * would give a falsely clean cache entry. The mtime and
191 * length match the cache, and other stat fields do not change.
193 * We could detect this at update-index time (the cache entry
194 * being registered/updated records the same time as "now")
195 * and delay the return from git-update-index, but that would
196 * effectively mean we can make at most one commit per second,
197 * which is not acceptable. Instead, we check cache entries
198 * whose mtime are the same as the index file timestamp more
199 * carefully than others.
202 index_file_timestamp &&
203 index_file_timestamp <= ntohl(ce->ce_mtime.sec))
204 changed |= ce_modified_check_fs(ce, st);
209 int ce_modified(struct cache_entry *ce, struct stat *st, int really)
211 int changed, changed_fs;
212 changed = ce_match_stat(ce, st, really);
216 * If the mode or type has changed, there's no point in trying
217 * to refresh the entry - it's not going to match
219 if (changed & (MODE_CHANGED | TYPE_CHANGED))
222 /* Immediately after read-tree or update-index --cacheinfo,
223 * the length field is zero. For other cases the ce_size
224 * should match the SHA1 recorded in the index entry.
226 if ((changed & DATA_CHANGED) && ce->ce_size != htonl(0))
229 changed_fs = ce_modified_check_fs(ce, st);
231 return changed | changed_fs;
235 int base_name_compare(const char *name1, int len1, int mode1,
236 const char *name2, int len2, int mode2)
238 unsigned char c1, c2;
239 int len = len1 < len2 ? len1 : len2;
242 cmp = memcmp(name1, name2, len);
247 if (!c1 && S_ISDIR(mode1))
249 if (!c2 && S_ISDIR(mode2))
251 return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
254 int cache_name_compare(const char *name1, int flags1, const char *name2, int flags2)
256 int len1 = flags1 & CE_NAMEMASK;
257 int len2 = flags2 & CE_NAMEMASK;
258 int len = len1 < len2 ? len1 : len2;
261 cmp = memcmp(name1, name2, len);
270 flags1 &= CE_STAGEMASK;
271 flags2 &= CE_STAGEMASK;
280 int cache_name_pos(const char *name, int namelen)
286 while (last > first) {
287 int next = (last + first) >> 1;
288 struct cache_entry *ce = active_cache[next];
289 int cmp = cache_name_compare(name, namelen, ce->name, ntohs(ce->ce_flags));
301 /* Remove entry, return true if there are more entries to go.. */
302 int remove_cache_entry_at(int pos)
304 active_cache_changed = 1;
306 if (pos >= active_nr)
308 memmove(active_cache + pos, active_cache + pos + 1, (active_nr - pos) * sizeof(struct cache_entry *));
312 int remove_file_from_cache(const char *path)
314 int pos = cache_name_pos(path, strlen(path));
317 while (pos < active_nr && !strcmp(active_cache[pos]->name, path))
318 remove_cache_entry_at(pos);
322 int add_file_to_index(const char *path, int verbose)
326 struct cache_entry *ce;
328 if (lstat(path, &st))
329 die("%s: unable to stat (%s)", path, strerror(errno));
331 if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode))
332 die("%s: can only add regular files or symbolic links", path);
334 namelen = strlen(path);
335 size = cache_entry_size(namelen);
336 ce = xcalloc(1, size);
337 memcpy(ce->name, path, namelen);
338 ce->ce_flags = htons(namelen);
339 fill_stat_cache_info(ce, &st);
341 ce->ce_mode = create_ce_mode(st.st_mode);
342 if (!trust_executable_bit) {
343 /* If there is an existing entry, pick the mode bits
346 int pos = cache_name_pos(path, namelen);
348 ce->ce_mode = active_cache[pos]->ce_mode;
351 if (index_path(ce->sha1, path, &st, 1))
352 die("unable to index file %s", path);
353 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD))
354 die("unable to add %s to index",path);
356 printf("add '%s'\n", path);
357 cache_tree_invalidate_path(active_cache_tree, path);
361 int ce_same_name(struct cache_entry *a, struct cache_entry *b)
363 int len = ce_namelen(a);
364 return ce_namelen(b) == len && !memcmp(a->name, b->name, len);
367 int ce_path_match(const struct cache_entry *ce, const char **pathspec)
369 const char *match, *name;
375 len = ce_namelen(ce);
377 while ((match = *pathspec++) != NULL) {
378 int matchlen = strlen(match);
381 if (memcmp(name, match, matchlen))
383 if (matchlen && name[matchlen-1] == '/')
385 if (name[matchlen] == '/' || !name[matchlen])
394 * We fundamentally don't like some paths: we don't want
395 * dot or dot-dot anywhere, and for obvious reasons don't
396 * want to recurse into ".git" either.
398 * Also, we don't want double slashes or slashes at the
399 * end that can make pathnames ambiguous.
401 static int verify_dotfile(const char *rest)
404 * The first character was '.', but that
405 * has already been discarded, we now test
409 /* "." is not allowed */
414 * ".git" followed by NUL or slash is bad. This
415 * shares the path end test with the ".." case.
425 if (rest[1] == '\0' || rest[1] == '/')
431 int verify_path(const char *path)
448 if (verify_dotfile(path))
458 * Do we have another file that has the beginning components being a
459 * proper superset of the name we're trying to add?
461 static int has_file_name(const struct cache_entry *ce, int pos, int ok_to_replace)
464 int len = ce_namelen(ce);
465 int stage = ce_stage(ce);
466 const char *name = ce->name;
468 while (pos < active_nr) {
469 struct cache_entry *p = active_cache[pos++];
471 if (len >= ce_namelen(p))
473 if (memcmp(name, p->name, len))
475 if (ce_stage(p) != stage)
477 if (p->name[len] != '/')
482 remove_cache_entry_at(--pos);
488 * Do we have another file with a pathname that is a proper
489 * subset of the name we're trying to add?
491 static int has_dir_name(const struct cache_entry *ce, int pos, int ok_to_replace)
494 int stage = ce_stage(ce);
495 const char *name = ce->name;
496 const char *slash = name + ce_namelen(ce);
504 if (slash <= ce->name)
509 pos = cache_name_pos(name, ntohs(create_ce_flags(len, stage)));
514 remove_cache_entry_at(pos);
519 * Trivial optimization: if we find an entry that
520 * already matches the sub-directory, then we know
521 * we're ok, and we can exit.
524 while (pos < active_nr) {
525 struct cache_entry *p = active_cache[pos];
526 if ((ce_namelen(p) <= len) ||
527 (p->name[len] != '/') ||
528 memcmp(p->name, name, len))
529 break; /* not our subdirectory */
530 if (ce_stage(p) == stage)
531 /* p is at the same stage as our entry, and
532 * is a subdirectory of what we are looking
533 * at, so we cannot have conflicts at our
534 * level or anything shorter.
543 /* We may be in a situation where we already have path/file and path
544 * is being added, or we already have path and path/file is being
545 * added. Either one would result in a nonsense tree that has path
546 * twice when git-write-tree tries to write it out. Prevent it.
548 * If ok-to-replace is specified, we remove the conflicting entries
549 * from the cache so the caller should recompute the insert position.
550 * When this happens, we return non-zero.
552 static int check_file_directory_conflict(const struct cache_entry *ce, int pos, int ok_to_replace)
555 * We check if the path is a sub-path of a subsequent pathname
556 * first, since removing those will not change the position
559 int retval = has_file_name(ce, pos, ok_to_replace);
561 * Then check if the path might have a clashing sub-directory
564 return retval + has_dir_name(ce, pos, ok_to_replace);
567 int add_cache_entry(struct cache_entry *ce, int option)
570 int ok_to_add = option & ADD_CACHE_OK_TO_ADD;
571 int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE;
572 int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK;
574 pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
576 /* existing match? Just replace it. */
578 active_cache_changed = 1;
579 active_cache[pos] = ce;
585 * Inserting a merged entry ("stage 0") into the index
586 * will always replace all non-merged entries..
588 if (pos < active_nr && ce_stage(ce) == 0) {
589 while (ce_same_name(active_cache[pos], ce)) {
591 if (!remove_cache_entry_at(pos))
598 if (!verify_path(ce->name))
601 if (!skip_df_check &&
602 check_file_directory_conflict(ce, pos, ok_to_replace)) {
605 pos = cache_name_pos(ce->name, ntohs(ce->ce_flags));
609 /* Make sure the array is big enough .. */
610 if (active_nr == active_alloc) {
611 active_alloc = alloc_nr(active_alloc);
612 active_cache = xrealloc(active_cache, active_alloc * sizeof(struct cache_entry *));
618 memmove(active_cache + pos + 1, active_cache + pos, (active_nr - pos - 1) * sizeof(ce));
619 active_cache[pos] = ce;
620 active_cache_changed = 1;
625 * "refresh" does not calculate a new sha1 file or bring the
626 * cache up-to-date for mode/content changes. But what it
627 * _does_ do is to "re-match" the stat information of a file
628 * with the cache, so that you can refresh the cache for a
629 * file that hasn't been changed but where the stat entry is
632 * For example, you'd want to do this after doing a "git-read-tree",
633 * to link up the stat cache details with the proper files.
635 struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really)
638 struct cache_entry *updated;
641 if (lstat(ce->name, &st) < 0) {
646 changed = ce_match_stat(ce, &st, really);
648 if (really && assume_unchanged &&
649 !(ce->ce_flags & htons(CE_VALID)))
650 ; /* mark this one VALID again */
655 if (ce_modified(ce, &st, really)) {
656 cache_errno = EINVAL;
661 updated = xmalloc(size);
662 memcpy(updated, ce, size);
663 fill_stat_cache_info(updated, &st);
665 /* In this case, if really is not set, we should leave
666 * CE_VALID bit alone. Otherwise, paths marked with
667 * --no-assume-unchanged (i.e. things to be edited) will
668 * reacquire CE_VALID bit automatically, which is not
669 * really what we want.
671 if (!really && assume_unchanged && !(ce->ce_flags & htons(CE_VALID)))
672 updated->ce_flags &= ~htons(CE_VALID);
677 int refresh_cache(unsigned int flags)
681 int really = (flags & REFRESH_REALLY) != 0;
682 int allow_unmerged = (flags & REFRESH_UNMERGED) != 0;
683 int quiet = (flags & REFRESH_QUIET) != 0;
684 int not_new = (flags & REFRESH_IGNORE_MISSING) != 0;
686 for (i = 0; i < active_nr; i++) {
687 struct cache_entry *ce, *new;
688 ce = active_cache[i];
690 while ((i < active_nr) &&
691 ! strcmp(active_cache[i]->name, ce->name))
696 printf("%s: needs merge\n", ce->name);
701 new = refresh_cache_entry(ce, really);
705 if (not_new && cache_errno == ENOENT)
707 if (really && cache_errno == EINVAL) {
708 /* If we are doing --really-refresh that
709 * means the index is not valid anymore.
711 ce->ce_flags &= ~htons(CE_VALID);
712 active_cache_changed = 1;
716 printf("%s: needs update\n", ce->name);
720 active_cache_changed = 1;
721 /* You can NOT just free active_cache[i] here, since it
722 * might not be necessarily malloc()ed but can also come
724 active_cache[i] = new;
729 static int verify_hdr(struct cache_header *hdr, unsigned long size)
732 unsigned char sha1[20];
734 if (hdr->hdr_signature != htonl(CACHE_SIGNATURE))
735 return error("bad signature");
736 if (hdr->hdr_version != htonl(2))
737 return error("bad index version");
739 SHA1_Update(&c, hdr, size - 20);
740 SHA1_Final(sha1, &c);
741 if (memcmp(sha1, (char *) hdr + size - 20, 20))
742 return error("bad index file sha1 signature");
746 static int read_index_extension(const char *ext, void *data, unsigned long sz)
748 switch (CACHE_EXT(ext)) {
750 active_cache_tree = cache_tree_read(data, sz);
753 if (*ext < 'A' || 'Z' < *ext)
754 return error("index uses %.4s extension, which we do not understand",
756 fprintf(stderr, "ignoring %.4s extension\n", ext);
764 return read_cache_from(get_index_file());
767 /* remember to discard_cache() before reading a different cache! */
768 int read_cache_from(const char *path)
772 unsigned long offset;
773 struct cache_header *hdr;
780 index_file_timestamp = 0;
781 fd = open(path, O_RDONLY);
785 die("index file open failed (%s)", strerror(errno));
788 cache_mmap = MAP_FAILED;
789 if (!fstat(fd, &st)) {
790 cache_mmap_size = st.st_size;
792 if (cache_mmap_size >= sizeof(struct cache_header) + 20)
793 cache_mmap = mmap(NULL, cache_mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
796 if (cache_mmap == MAP_FAILED)
797 die("index file mmap failed (%s)", strerror(errno));
800 if (verify_hdr(hdr, cache_mmap_size) < 0)
803 active_nr = ntohl(hdr->hdr_entries);
804 active_alloc = alloc_nr(active_nr);
805 active_cache = xcalloc(active_alloc, sizeof(struct cache_entry *));
807 offset = sizeof(*hdr);
808 for (i = 0; i < active_nr; i++) {
809 struct cache_entry *ce = (struct cache_entry *) ((char *) cache_mmap + offset);
810 offset = offset + ce_size(ce);
811 active_cache[i] = ce;
813 index_file_timestamp = st.st_mtime;
814 while (offset <= cache_mmap_size - 20 - 8) {
815 /* After an array of active_nr index entries,
816 * there can be arbitrary number of extended
817 * sections, each of which is prefixed with
818 * extension name (4-byte) and section length
819 * in 4-byte network byte order.
821 unsigned long extsize;
822 memcpy(&extsize, (char *) cache_mmap + offset + 4, 4);
823 extsize = ntohl(extsize);
824 if (read_index_extension(((const char *) cache_mmap) + offset,
825 (char *) cache_mmap + offset + 8,
834 munmap(cache_mmap, cache_mmap_size);
836 die("index file corrupt");
839 #define WRITE_BUFFER_SIZE 8192
840 static unsigned char write_buffer[WRITE_BUFFER_SIZE];
841 static unsigned long write_buffer_len;
843 static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len)
846 unsigned int buffered = write_buffer_len;
847 unsigned int partial = WRITE_BUFFER_SIZE - buffered;
850 memcpy(write_buffer + buffered, data, partial);
852 if (buffered == WRITE_BUFFER_SIZE) {
853 SHA1_Update(context, write_buffer, WRITE_BUFFER_SIZE);
854 if (write(fd, write_buffer, WRITE_BUFFER_SIZE) != WRITE_BUFFER_SIZE)
858 write_buffer_len = buffered;
860 data = (char *) data + partial;
865 static int write_index_ext_header(SHA_CTX *context, int fd,
866 unsigned int ext, unsigned int sz)
870 if ((ce_write(context, fd, &ext, 4) < 0) ||
871 (ce_write(context, fd, &sz, 4) < 0))
876 static int ce_flush(SHA_CTX *context, int fd)
878 unsigned int left = write_buffer_len;
881 write_buffer_len = 0;
882 SHA1_Update(context, write_buffer, left);
885 /* Flush first if not enough space for SHA1 signature */
886 if (left + 20 > WRITE_BUFFER_SIZE) {
887 if (write(fd, write_buffer, left) != left)
892 /* Append the SHA1 signature at the end */
893 SHA1_Final(write_buffer + left, context);
895 if (write(fd, write_buffer, left) != left)
900 static void ce_smudge_racily_clean_entry(struct cache_entry *ce)
903 * The only thing we care about in this function is to smudge the
904 * falsely clean entry due to touch-update-touch race, so we leave
905 * everything else as they are. We are called for entries whose
906 * ce_mtime match the index file mtime.
910 if (lstat(ce->name, &st) < 0)
912 if (ce_match_stat_basic(ce, &st))
914 if (ce_modified_check_fs(ce, &st)) {
915 /* This is "racily clean"; smudge it. Note that this
916 * is a tricky code. At first glance, it may appear
917 * that it can break with this sequence:
919 * $ echo xyzzy >frotz
920 * $ git-update-index --add frotz
923 * $ echo filfre >nitfol
924 * $ git-update-index --add nitfol
926 * but it does not. Whe the second update-index runs,
927 * it notices that the entry "frotz" has the same timestamp
928 * as index, and if we were to smudge it by resetting its
929 * size to zero here, then the object name recorded
930 * in index is the 6-byte file but the cached stat information
931 * becomes zero --- which would then match what we would
932 * obtain from the filesystem next time we stat("frotz").
934 * However, the second update-index, before calling
935 * this function, notices that the cached size is 6
936 * bytes and what is on the filesystem is an empty
937 * file, and never calls us, so the cached size information
938 * for "frotz" stays 6 which does not match the filesystem.
940 ce->ce_size = htonl(0);
944 int write_cache(int newfd, struct cache_entry **cache, int entries)
947 struct cache_header hdr;
950 for (i = removed = 0; i < entries; i++)
951 if (!cache[i]->ce_mode)
954 hdr.hdr_signature = htonl(CACHE_SIGNATURE);
955 hdr.hdr_version = htonl(2);
956 hdr.hdr_entries = htonl(entries - removed);
959 if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0)
962 for (i = 0; i < entries; i++) {
963 struct cache_entry *ce = cache[i];
966 if (index_file_timestamp &&
967 index_file_timestamp <= ntohl(ce->ce_mtime.sec))
968 ce_smudge_racily_clean_entry(ce);
969 if (ce_write(&c, newfd, ce, ce_size(ce)) < 0)
973 /* Write extension data here */
974 if (active_cache_tree) {
976 void *data = cache_tree_write(active_cache_tree, &sz);
978 !write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sz) &&
979 !ce_write(&c, newfd, data, sz))
986 return ce_flush(&c, newfd);