2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
17 #include "pack-revindex.h"
18 #include "sha1-lookup.h"
21 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
22 #define O_NOATIME 01000000
30 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
33 static size_t sz_fmt(size_t s) { return s; }
36 const unsigned char null_sha1[20];
38 static int git_open_noatime(const char *name, struct packed_git *p);
41 * This is meant to hold a *small* number of objects that you would
42 * want read_sha1_file() to be able to return, but yet you do not want
43 * to write them into the object store (e.g. a browse-only
46 static struct cached_object {
47 unsigned char sha1[20];
48 enum object_type type;
52 static int cached_object_nr, cached_object_alloc;
54 static struct cached_object empty_tree = {
55 EMPTY_TREE_SHA1_BIN_LITERAL,
61 static struct cached_object *find_cached_object(const unsigned char *sha1)
64 struct cached_object *co = cached_objects;
66 for (i = 0; i < cached_object_nr; i++, co++) {
67 if (!hashcmp(co->sha1, sha1))
70 if (!hashcmp(sha1, empty_tree.sha1))
75 int safe_create_leading_directories(char *path)
77 char *pos = path + offset_1st_component(path);
81 pos = strchr(pos, '/');
89 if (!stat(path, &st)) {
91 if (!S_ISDIR(st.st_mode)) {
96 else if (mkdir(path, 0777)) {
100 else if (adjust_shared_perm(path)) {
109 int safe_create_leading_directories_const(const char *path)
111 /* path points to cache entries, so xstrdup before messing with it */
112 char *buf = xstrdup(path);
113 int result = safe_create_leading_directories(buf);
118 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
121 for (i = 0; i < 20; i++) {
122 static char hex[] = "0123456789abcdef";
123 unsigned int val = sha1[i];
124 char *pos = pathbuf + i*2 + (i > 0);
125 *pos++ = hex[val >> 4];
126 *pos = hex[val & 0xf];
131 * NOTE! This returns a statically allocated buffer, so you have to be
132 * careful about using it. Do an "xstrdup()" if you need to save the
135 * Also note that this returns the location for creating. Reading
136 * SHA1 file can happen from any alternate directory listed in the
137 * DB_ENVIRONMENT environment variable if it is not found in
138 * the primary object database.
140 char *sha1_file_name(const unsigned char *sha1)
142 static char buf[PATH_MAX];
146 objdir = get_object_directory();
147 len = strlen(objdir);
149 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
150 if (len + 43 > PATH_MAX)
151 die("insanely long object directory %s", objdir);
152 memcpy(buf, objdir, len);
156 fill_sha1_path(buf + len + 1, sha1);
160 static char *sha1_get_pack_name(const unsigned char *sha1,
161 char **name, char **base, const char *which)
163 static const char hex[] = "0123456789abcdef";
168 const char *sha1_file_directory = get_object_directory();
169 int len = strlen(sha1_file_directory);
170 *base = xmalloc(len + 60);
171 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
172 sha1_file_directory, which);
173 *name = *base + len + 11;
178 for (i = 0; i < 20; i++) {
179 unsigned int val = *sha1++;
180 *buf++ = hex[val >> 4];
181 *buf++ = hex[val & 0xf];
187 char *sha1_pack_name(const unsigned char *sha1)
189 static char *name, *base;
191 return sha1_get_pack_name(sha1, &name, &base, "pack");
194 char *sha1_pack_index_name(const unsigned char *sha1)
196 static char *name, *base;
198 return sha1_get_pack_name(sha1, &name, &base, "idx");
201 struct alternate_object_database *alt_odb_list;
202 static struct alternate_object_database **alt_odb_tail;
204 static void read_info_alternates(const char * alternates, int depth);
207 * Prepare alternate object database registry.
209 * The variable alt_odb_list points at the list of struct
210 * alternate_object_database. The elements on this list come from
211 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
212 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
213 * whose contents is similar to that environment variable but can be
214 * LF separated. Its base points at a statically allocated buffer that
215 * contains "/the/directory/corresponding/to/.git/objects/...", while
216 * its name points just after the slash at the end of ".git/objects/"
217 * in the example above, and has enough space to hold 40-byte hex
218 * SHA1, an extra slash for the first level indirection, and the
221 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
223 const char *objdir = get_object_directory();
224 struct alternate_object_database *ent;
225 struct alternate_object_database *alt;
226 /* 43 = 40-byte + 2 '/' + terminating NUL */
228 int entlen = pfxlen + 43;
231 if (!is_absolute_path(entry) && relative_base) {
232 /* Relative alt-odb */
234 base_len = strlen(relative_base) + 1;
238 ent = xmalloc(sizeof(*ent) + entlen);
240 if (!is_absolute_path(entry) && relative_base) {
241 memcpy(ent->base, relative_base, base_len - 1);
242 ent->base[base_len - 1] = '/';
243 memcpy(ent->base + base_len, entry, len);
246 memcpy(ent->base, entry, pfxlen);
248 ent->name = ent->base + pfxlen + 1;
249 ent->base[pfxlen + 3] = '/';
250 ent->base[pfxlen] = ent->base[entlen-1] = 0;
252 /* Detect cases where alternate disappeared */
253 if (!is_directory(ent->base)) {
254 error("object directory %s does not exist; "
255 "check .git/objects/info/alternates.",
261 /* Prevent the common mistake of listing the same
262 * thing twice, or object directory itself.
264 for (alt = alt_odb_list; alt; alt = alt->next) {
265 if (!memcmp(ent->base, alt->base, pfxlen)) {
270 if (!memcmp(ent->base, objdir, pfxlen)) {
275 /* add the alternate entry */
277 alt_odb_tail = &(ent->next);
280 /* recursively add alternates */
281 read_info_alternates(ent->base, depth + 1);
283 ent->base[pfxlen] = '/';
288 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
289 const char *relative_base, int depth)
291 const char *cp, *last;
294 error("%s: ignoring alternate object stores, nesting too deep.",
302 if (cp < ep && *cp == '#') {
303 while (cp < ep && *cp != sep)
308 while (cp < ep && *cp != sep)
311 if (!is_absolute_path(last) && depth) {
312 error("%s: ignoring relative alternate object store %s",
313 relative_base, last);
315 link_alt_odb_entry(last, cp - last,
316 relative_base, depth);
319 while (cp < ep && *cp == sep)
325 static void read_info_alternates(const char * relative_base, int depth)
330 const char alt_file_name[] = "info/alternates";
331 /* Given that relative_base is no longer than PATH_MAX,
332 ensure that "path" has enough space to append "/", the
333 file name, "info/alternates", and a trailing NUL. */
334 char path[PATH_MAX + 1 + sizeof alt_file_name];
337 sprintf(path, "%s/%s", relative_base, alt_file_name);
338 fd = git_open_noatime(path, NULL);
341 if (fstat(fd, &st) || (st.st_size == 0)) {
345 mapsz = xsize_t(st.st_size);
346 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
349 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
354 void add_to_alternates_file(const char *reference)
356 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
357 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
358 char *alt = mkpath("%s/objects\n", reference);
359 write_or_die(fd, alt, strlen(alt));
360 if (commit_lock_file(lock))
361 die("could not close alternates file");
363 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
366 void foreach_alt_odb(alt_odb_fn fn, void *cb)
368 struct alternate_object_database *ent;
371 for (ent = alt_odb_list; ent; ent = ent->next)
376 void prepare_alt_odb(void)
383 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
386 alt_odb_tail = &alt_odb_list;
387 link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
389 read_info_alternates(get_object_directory(), 0);
392 static int has_loose_object_local(const unsigned char *sha1)
394 char *name = sha1_file_name(sha1);
395 return !access(name, F_OK);
398 int has_loose_object_nonlocal(const unsigned char *sha1)
400 struct alternate_object_database *alt;
402 for (alt = alt_odb_list; alt; alt = alt->next) {
403 fill_sha1_path(alt->name, sha1);
404 if (!access(alt->base, F_OK))
410 static int has_loose_object(const unsigned char *sha1)
412 return has_loose_object_local(sha1) ||
413 has_loose_object_nonlocal(sha1);
416 static unsigned int pack_used_ctr;
417 static unsigned int pack_mmap_calls;
418 static unsigned int peak_pack_open_windows;
419 static unsigned int pack_open_windows;
420 static unsigned int pack_open_fds;
421 static unsigned int pack_max_fds;
422 static size_t peak_pack_mapped;
423 static size_t pack_mapped;
424 struct packed_git *packed_git;
426 void pack_report(void)
429 "pack_report: getpagesize() = %10" SZ_FMT "\n"
430 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
431 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
432 sz_fmt(getpagesize()),
433 sz_fmt(packed_git_window_size),
434 sz_fmt(packed_git_limit));
436 "pack_report: pack_used_ctr = %10u\n"
437 "pack_report: pack_mmap_calls = %10u\n"
438 "pack_report: pack_open_windows = %10u / %10u\n"
439 "pack_report: pack_mapped = "
440 "%10" SZ_FMT " / %10" SZ_FMT "\n",
443 pack_open_windows, peak_pack_open_windows,
444 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
447 static int check_packed_git_idx(const char *path, struct packed_git *p)
450 struct pack_idx_header *hdr;
452 uint32_t version, nr, i, *index;
453 int fd = git_open_noatime(path, p);
458 if (fstat(fd, &st)) {
462 idx_size = xsize_t(st.st_size);
463 if (idx_size < 4 * 256 + 20 + 20) {
465 return error("index file %s is too small", path);
467 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
471 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
472 version = ntohl(hdr->idx_version);
473 if (version < 2 || version > 2) {
474 munmap(idx_map, idx_size);
475 return error("index file %s is version %"PRIu32
476 " and is not supported by this binary"
477 " (try upgrading GIT to a newer version)",
486 index += 2; /* skip index header */
487 for (i = 0; i < 256; i++) {
488 uint32_t n = ntohl(index[i]);
490 munmap(idx_map, idx_size);
491 return error("non-monotonic index %s", path);
499 * - 256 index entries 4 bytes each
500 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
501 * - 20-byte SHA1 of the packfile
502 * - 20-byte SHA1 file checksum
504 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
505 munmap(idx_map, idx_size);
506 return error("wrong index v1 file size in %s", path);
508 } else if (version == 2) {
511 * - 8 bytes of header
512 * - 256 index entries 4 bytes each
513 * - 20-byte sha1 entry * nr
514 * - 4-byte crc entry * nr
515 * - 4-byte offset entry * nr
516 * - 20-byte SHA1 of the packfile
517 * - 20-byte SHA1 file checksum
518 * And after the 4-byte offset table might be a
519 * variable sized table containing 8-byte entries
520 * for offsets larger than 2^31.
522 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
523 unsigned long max_size = min_size;
525 max_size += (nr - 1)*8;
526 if (idx_size < min_size || idx_size > max_size) {
527 munmap(idx_map, idx_size);
528 return error("wrong index v2 file size in %s", path);
530 if (idx_size != min_size &&
532 * make sure we can deal with large pack offsets.
533 * 31-bit signed offset won't be enough, neither
534 * 32-bit unsigned one will be.
536 (sizeof(off_t) <= 4)) {
537 munmap(idx_map, idx_size);
538 return error("pack too large for current definition of off_t in %s", path);
542 p->index_version = version;
543 p->index_data = idx_map;
544 p->index_size = idx_size;
549 int open_pack_index(struct packed_git *p)
557 idx_name = xstrdup(p->pack_name);
558 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
559 ret = check_packed_git_idx(idx_name, p);
564 static void scan_windows(struct packed_git *p,
565 struct packed_git **lru_p,
566 struct pack_window **lru_w,
567 struct pack_window **lru_l)
569 struct pack_window *w, *w_l;
571 for (w_l = NULL, w = p->windows; w; w = w->next) {
573 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
583 static int unuse_one_window(struct packed_git *current, int keep_fd)
585 struct packed_git *p, *lru_p = NULL;
586 struct pack_window *lru_w = NULL, *lru_l = NULL;
589 scan_windows(current, &lru_p, &lru_w, &lru_l);
590 for (p = packed_git; p; p = p->next)
591 scan_windows(p, &lru_p, &lru_w, &lru_l);
593 munmap(lru_w->base, lru_w->len);
594 pack_mapped -= lru_w->len;
596 lru_l->next = lru_w->next;
598 lru_p->windows = lru_w->next;
599 if (!lru_p->windows && lru_p->pack_fd != -1
600 && lru_p->pack_fd != keep_fd) {
601 close(lru_p->pack_fd);
613 void release_pack_memory(size_t need, int fd)
615 size_t cur = pack_mapped;
616 while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
620 void *xmmap(void *start, size_t length,
621 int prot, int flags, int fd, off_t offset)
623 void *ret = mmap(start, length, prot, flags, fd, offset);
624 if (ret == MAP_FAILED) {
627 release_pack_memory(length, fd);
628 ret = mmap(start, length, prot, flags, fd, offset);
629 if (ret == MAP_FAILED)
630 die_errno("Out of memory? mmap failed");
635 void close_pack_windows(struct packed_git *p)
638 struct pack_window *w = p->windows;
641 die("pack '%s' still has open windows to it",
643 munmap(w->base, w->len);
644 pack_mapped -= w->len;
646 p->windows = w->next;
651 void unuse_pack(struct pack_window **w_cursor)
653 struct pack_window *w = *w_cursor;
660 void close_pack_index(struct packed_git *p)
663 munmap((void *)p->index_data, p->index_size);
664 p->index_data = NULL;
669 * This is used by git-repack in case a newly created pack happens to
670 * contain the same set of objects as an existing one. In that case
671 * the resulting file might be different even if its name would be the
672 * same. It is best to close any reference to the old pack before it is
673 * replaced on disk. Of course no index pointers nor windows for given pack
674 * must subsist at this point. If ever objects from this pack are requested
675 * again, the new version of the pack will be reinitialized through
676 * reprepare_packed_git().
678 void free_pack_by_name(const char *pack_name)
680 struct packed_git *p, **pp = &packed_git;
684 if (strcmp(pack_name, p->pack_name) == 0) {
685 clear_delta_base_cache();
686 close_pack_windows(p);
687 if (p->pack_fd != -1) {
692 free(p->bad_object_sha1);
702 * Do not call this directly as this leaks p->pack_fd on error return;
703 * call open_packed_git() instead.
705 static int open_packed_git_1(struct packed_git *p)
708 struct pack_header hdr;
709 unsigned char sha1[20];
710 unsigned char *idx_sha1;
713 if (!p->index_data && open_pack_index(p))
714 return error("packfile %s index unavailable", p->pack_name);
718 unsigned int max_fds;
720 if (getrlimit(RLIMIT_NOFILE, &lim))
721 die_errno("cannot get RLIMIT_NOFILE");
723 max_fds = lim.rlim_cur;
725 /* Save 3 for stdin/stdout/stderr, 22 for work */
727 pack_max_fds = max_fds - 25;
732 while (pack_max_fds <= pack_open_fds && unuse_one_window(NULL, -1))
735 p->pack_fd = git_open_noatime(p->pack_name, p);
736 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
740 /* If we created the struct before we had the pack we lack size. */
742 if (!S_ISREG(st.st_mode))
743 return error("packfile %s not a regular file", p->pack_name);
744 p->pack_size = st.st_size;
745 } else if (p->pack_size != st.st_size)
746 return error("packfile %s size changed", p->pack_name);
748 /* We leave these file descriptors open with sliding mmap;
749 * there is no point keeping them open across exec(), though.
751 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
753 return error("cannot determine file descriptor flags");
754 fd_flag |= FD_CLOEXEC;
755 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
756 return error("cannot set FD_CLOEXEC");
758 /* Verify we recognize this pack file format. */
759 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
760 return error("file %s is far too short to be a packfile", p->pack_name);
761 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
762 return error("file %s is not a GIT packfile", p->pack_name);
763 if (!pack_version_ok(hdr.hdr_version))
764 return error("packfile %s is version %"PRIu32" and not"
765 " supported (try upgrading GIT to a newer version)",
766 p->pack_name, ntohl(hdr.hdr_version));
768 /* Verify the pack matches its index. */
769 if (p->num_objects != ntohl(hdr.hdr_entries))
770 return error("packfile %s claims to have %"PRIu32" objects"
771 " while index indicates %"PRIu32" objects",
772 p->pack_name, ntohl(hdr.hdr_entries),
774 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
775 return error("end of packfile %s is unavailable", p->pack_name);
776 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
777 return error("packfile %s signature is unavailable", p->pack_name);
778 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
779 if (hashcmp(sha1, idx_sha1))
780 return error("packfile %s does not match index", p->pack_name);
784 static int open_packed_git(struct packed_git *p)
786 if (!open_packed_git_1(p))
788 if (p->pack_fd != -1) {
796 static int in_window(struct pack_window *win, off_t offset)
798 /* We must promise at least 20 bytes (one hash) after the
799 * offset is available from this window, otherwise the offset
800 * is not actually in this window and a different window (which
801 * has that one hash excess) must be used. This is to support
802 * the object header and delta base parsing routines below.
804 off_t win_off = win->offset;
805 return win_off <= offset
806 && (offset + 20) <= (win_off + win->len);
809 unsigned char *use_pack(struct packed_git *p,
810 struct pack_window **w_cursor,
814 struct pack_window *win = *w_cursor;
816 /* Since packfiles end in a hash of their content and it's
817 * pointless to ask for an offset into the middle of that
818 * hash, and the in_window function above wouldn't match
819 * don't allow an offset too close to the end of the file.
821 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
822 die("packfile %s cannot be accessed", p->pack_name);
823 if (offset > (p->pack_size - 20))
824 die("offset beyond end of packfile (truncated pack?)");
826 if (!win || !in_window(win, offset)) {
829 for (win = p->windows; win; win = win->next) {
830 if (in_window(win, offset))
834 size_t window_align = packed_git_window_size / 2;
837 if (p->pack_fd == -1 && open_packed_git(p))
838 die("packfile %s cannot be accessed", p->pack_name);
840 win = xcalloc(1, sizeof(*win));
841 win->offset = (offset / window_align) * window_align;
842 len = p->pack_size - win->offset;
843 if (len > packed_git_window_size)
844 len = packed_git_window_size;
845 win->len = (size_t)len;
846 pack_mapped += win->len;
847 while (packed_git_limit < pack_mapped
848 && unuse_one_window(p, p->pack_fd))
850 win->base = xmmap(NULL, win->len,
851 PROT_READ, MAP_PRIVATE,
852 p->pack_fd, win->offset);
853 if (win->base == MAP_FAILED)
854 die("packfile %s cannot be mapped: %s",
857 if (!win->offset && win->len == p->pack_size
858 && !p->do_not_close) {
865 if (pack_mapped > peak_pack_mapped)
866 peak_pack_mapped = pack_mapped;
867 if (pack_open_windows > peak_pack_open_windows)
868 peak_pack_open_windows = pack_open_windows;
869 win->next = p->windows;
873 if (win != *w_cursor) {
874 win->last_used = pack_used_ctr++;
878 offset -= win->offset;
880 *left = win->len - xsize_t(offset);
881 return win->base + offset;
884 static struct packed_git *alloc_packed_git(int extra)
886 struct packed_git *p = xmalloc(sizeof(*p) + extra);
887 memset(p, 0, sizeof(*p));
892 static void try_to_free_pack_memory(size_t size)
894 release_pack_memory(size, -1);
897 struct packed_git *add_packed_git(const char *path, int path_len, int local)
899 static int have_set_try_to_free_routine;
901 struct packed_git *p = alloc_packed_git(path_len + 2);
903 if (!have_set_try_to_free_routine) {
904 have_set_try_to_free_routine = 1;
905 set_try_to_free_routine(try_to_free_pack_memory);
909 * Make sure a corresponding .pack file exists and that
910 * the index looks sane.
912 path_len -= strlen(".idx");
917 memcpy(p->pack_name, path, path_len);
919 strcpy(p->pack_name + path_len, ".keep");
920 if (!access(p->pack_name, F_OK))
923 strcpy(p->pack_name + path_len, ".pack");
924 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
929 /* ok, it looks sane as far as we can check without
930 * actually mapping the pack file.
932 p->pack_size = st.st_size;
933 p->pack_local = local;
934 p->mtime = st.st_mtime;
935 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
940 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
942 const char *path = sha1_pack_name(sha1);
943 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
945 strcpy(p->pack_name, path);
946 hashcpy(p->sha1, sha1);
947 if (check_packed_git_idx(idx_path, p)) {
955 void install_packed_git(struct packed_git *pack)
957 if (pack->pack_fd != -1)
960 pack->next = packed_git;
964 static void prepare_packed_git_one(char *objdir, int local)
966 /* Ensure that this buffer is large enough so that we can
967 append "/pack/" without clobbering the stack even if
968 strlen(objdir) were PATH_MAX. */
969 char path[PATH_MAX + 1 + 4 + 1 + 1];
974 sprintf(path, "%s/pack", objdir);
979 error("unable to open object pack directory: %s: %s",
980 path, strerror(errno));
984 while ((de = readdir(dir)) != NULL) {
985 int namelen = strlen(de->d_name);
986 struct packed_git *p;
988 if (!has_extension(de->d_name, ".idx"))
991 if (len + namelen + 1 > sizeof(path))
994 /* Don't reopen a pack we already have. */
995 strcpy(path + len, de->d_name);
996 for (p = packed_git; p; p = p->next) {
997 if (!memcmp(path, p->pack_name, len + namelen - 4))
1002 /* See if it really is a valid .idx file with corresponding
1003 * .pack file that we can map.
1005 p = add_packed_git(path, len + namelen, local);
1008 install_packed_git(p);
1013 static int sort_pack(const void *a_, const void *b_)
1015 struct packed_git *a = *((struct packed_git **)a_);
1016 struct packed_git *b = *((struct packed_git **)b_);
1020 * Local packs tend to contain objects specific to our
1021 * variant of the project than remote ones. In addition,
1022 * remote ones could be on a network mounted filesystem.
1023 * Favor local ones for these reasons.
1025 st = a->pack_local - b->pack_local;
1030 * Younger packs tend to contain more recent objects,
1031 * and more recent objects tend to get accessed more
1034 if (a->mtime < b->mtime)
1036 else if (a->mtime == b->mtime)
1041 static void rearrange_packed_git(void)
1043 struct packed_git **ary, *p;
1046 for (n = 0, p = packed_git; p; p = p->next)
1051 /* prepare an array of packed_git for easier sorting */
1052 ary = xcalloc(n, sizeof(struct packed_git *));
1053 for (n = 0, p = packed_git; p; p = p->next)
1056 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1058 /* link them back again */
1059 for (i = 0; i < n - 1; i++)
1060 ary[i]->next = ary[i + 1];
1061 ary[n - 1]->next = NULL;
1062 packed_git = ary[0];
1067 static int prepare_packed_git_run_once = 0;
1068 void prepare_packed_git(void)
1070 struct alternate_object_database *alt;
1072 if (prepare_packed_git_run_once)
1074 prepare_packed_git_one(get_object_directory(), 1);
1076 for (alt = alt_odb_list; alt; alt = alt->next) {
1078 prepare_packed_git_one(alt->base, 0);
1079 alt->name[-1] = '/';
1081 rearrange_packed_git();
1082 prepare_packed_git_run_once = 1;
1085 void reprepare_packed_git(void)
1088 prepare_packed_git_run_once = 0;
1089 prepare_packed_git();
1092 static void mark_bad_packed_object(struct packed_git *p,
1093 const unsigned char *sha1)
1096 for (i = 0; i < p->num_bad_objects; i++)
1097 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1099 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1100 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1101 p->num_bad_objects++;
1104 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1106 struct packed_git *p;
1109 for (p = packed_git; p; p = p->next)
1110 for (i = 0; i < p->num_bad_objects; i++)
1111 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1116 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1118 unsigned char real_sha1[20];
1119 hash_sha1_file(map, size, type, real_sha1);
1120 return hashcmp(sha1, real_sha1) ? -1 : 0;
1123 static int git_open_noatime(const char *name, struct packed_git *p)
1125 static int sha1_file_open_flag = O_NOATIME;
1128 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1132 /* Might the failure be due to O_NOATIME? */
1133 if (errno != ENOENT && sha1_file_open_flag) {
1134 sha1_file_open_flag = 0;
1142 static int open_sha1_file(const unsigned char *sha1)
1145 char *name = sha1_file_name(sha1);
1146 struct alternate_object_database *alt;
1148 fd = git_open_noatime(name, NULL);
1154 for (alt = alt_odb_list; alt; alt = alt->next) {
1156 fill_sha1_path(name, sha1);
1157 fd = git_open_noatime(alt->base, NULL);
1164 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1169 fd = open_sha1_file(sha1);
1174 if (!fstat(fd, &st)) {
1175 *size = xsize_t(st.st_size);
1176 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1183 static int legacy_loose_object(unsigned char *map)
1188 * Is it a zlib-compressed buffer? If so, the first byte
1189 * must be 0x78 (15-bit window size, deflated), and the
1190 * first 16-bit word is evenly divisible by 31
1192 word = (map[0] << 8) + map[1];
1193 if (map[0] == 0x78 && !(word % 31))
1199 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1200 unsigned long len, enum object_type *type, unsigned long *sizep)
1203 unsigned long size, c;
1204 unsigned long used = 0;
1207 *type = (c >> 4) & 7;
1211 if (len <= used || bitsizeof(long) <= shift) {
1212 error("bad object header");
1216 size += (c & 0x7f) << shift;
1223 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1225 unsigned long size, used;
1226 static const char valid_loose_object_type[8] = {
1228 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1229 0, /* "delta" and others are invalid in a loose object */
1231 enum object_type type;
1233 /* Get the data stream */
1234 memset(stream, 0, sizeof(*stream));
1235 stream->next_in = map;
1236 stream->avail_in = mapsize;
1237 stream->next_out = buffer;
1238 stream->avail_out = bufsiz;
1240 if (legacy_loose_object(map)) {
1241 git_inflate_init(stream);
1242 return git_inflate(stream, 0);
1247 * There used to be a second loose object header format which
1248 * was meant to mimic the in-pack format, allowing for direct
1249 * copy of the object data. This format turned up not to be
1250 * really worth it and we don't write it any longer. But we
1251 * can still read it.
1253 used = unpack_object_header_buffer(map, mapsize, &type, &size);
1254 if (!used || !valid_loose_object_type[type])
1259 /* Set up the stream for the rest.. */
1260 stream->next_in = map;
1261 stream->avail_in = mapsize;
1262 git_inflate_init(stream);
1264 /* And generate the fake traditional header */
1265 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1266 typename(type), size);
1270 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1272 int bytes = strlen(buffer) + 1;
1273 unsigned char *buf = xmallocz(size);
1277 n = stream->total_out - bytes;
1280 memcpy(buf, (char *) buffer + bytes, n);
1282 if (bytes <= size) {
1284 * The above condition must be (bytes <= size), not
1285 * (bytes < size). In other words, even though we
1286 * expect no more output and set avail_out to zer0,
1287 * the input zlib stream may have bytes that express
1288 * "this concludes the stream", and we *do* want to
1291 * Otherwise we would not be able to test that we
1292 * consumed all the input to reach the expected size;
1293 * we also want to check that zlib tells us that all
1294 * went well with status == Z_STREAM_END at the end.
1296 stream->next_out = buf + bytes;
1297 stream->avail_out = size - bytes;
1298 while (status == Z_OK)
1299 status = git_inflate(stream, Z_FINISH);
1301 if (status == Z_STREAM_END && !stream->avail_in) {
1302 git_inflate_end(stream);
1307 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1308 else if (stream->avail_in)
1309 error("garbage at end of loose object '%s'",
1316 * We used to just use "sscanf()", but that's actually way
1317 * too permissive for what we want to check. So do an anal
1318 * object header parse by hand.
1320 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1327 * The type can be at most ten bytes (including the
1328 * terminating '\0' that we add), and is followed by
1337 if (i >= sizeof(type))
1343 * The length must follow immediately, and be in canonical
1344 * decimal format (ie "010" is not valid).
1346 size = *hdr++ - '0';
1351 unsigned long c = *hdr - '0';
1355 size = size * 10 + c;
1361 * The length must be followed by a zero byte
1363 return *hdr ? -1 : type_from_string(type);
1366 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1372 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1373 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1376 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1379 unsigned long get_size_from_delta(struct packed_git *p,
1380 struct pack_window **w_curs,
1383 const unsigned char *data;
1384 unsigned char delta_head[20], *in;
1388 memset(&stream, 0, sizeof(stream));
1389 stream.next_out = delta_head;
1390 stream.avail_out = sizeof(delta_head);
1392 git_inflate_init(&stream);
1394 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1395 stream.next_in = in;
1396 st = git_inflate(&stream, Z_FINISH);
1397 curpos += stream.next_in - in;
1398 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1399 stream.total_out < sizeof(delta_head));
1400 git_inflate_end(&stream);
1401 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1402 error("delta data unpack-initial failed");
1406 /* Examine the initial part of the delta to figure out
1411 /* ignore base size */
1412 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1414 /* Read the result size */
1415 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1418 static off_t get_delta_base(struct packed_git *p,
1419 struct pack_window **w_curs,
1421 enum object_type type,
1422 off_t delta_obj_offset)
1424 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1427 /* use_pack() assured us we have [base_info, base_info + 20)
1428 * as a range that we can look at without walking off the
1429 * end of the mapped window. Its actually the hash size
1430 * that is assured. An OFS_DELTA longer than the hash size
1431 * is stupid, as then a REF_DELTA would be smaller to store.
1433 if (type == OBJ_OFS_DELTA) {
1435 unsigned char c = base_info[used++];
1436 base_offset = c & 127;
1439 if (!base_offset || MSB(base_offset, 7))
1440 return 0; /* overflow */
1441 c = base_info[used++];
1442 base_offset = (base_offset << 7) + (c & 127);
1444 base_offset = delta_obj_offset - base_offset;
1445 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1446 return 0; /* out of bound */
1448 } else if (type == OBJ_REF_DELTA) {
1449 /* The base entry _must_ be in the same pack */
1450 base_offset = find_pack_entry_one(base_info, p);
1453 die("I am totally screwed");
1457 /* forward declaration for a mutually recursive function */
1458 static int packed_object_info(struct packed_git *p, off_t offset,
1459 unsigned long *sizep);
1461 static int packed_delta_info(struct packed_git *p,
1462 struct pack_window **w_curs,
1464 enum object_type type,
1466 unsigned long *sizep)
1470 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1473 type = packed_object_info(p, base_offset, NULL);
1474 if (type <= OBJ_NONE) {
1475 struct revindex_entry *revidx;
1476 const unsigned char *base_sha1;
1477 revidx = find_pack_revindex(p, base_offset);
1480 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1481 mark_bad_packed_object(p, base_sha1);
1482 type = sha1_object_info(base_sha1, NULL);
1483 if (type <= OBJ_NONE)
1487 /* We choose to only get the type of the base object and
1488 * ignore potentially corrupt pack file that expects the delta
1489 * based on a base with a wrong size. This saves tons of
1493 *sizep = get_size_from_delta(p, w_curs, curpos);
1501 static int unpack_object_header(struct packed_git *p,
1502 struct pack_window **w_curs,
1504 unsigned long *sizep)
1506 unsigned char *base;
1509 enum object_type type;
1511 /* use_pack() assures us we have [base, base + 20) available
1512 * as a range that we can look at at. (Its actually the hash
1513 * size that is assured.) With our object header encoding
1514 * the maximum deflated object size is 2^137, which is just
1515 * insane, so we know won't exceed what we have been given.
1517 base = use_pack(p, w_curs, *curpos, &left);
1518 used = unpack_object_header_buffer(base, left, &type, sizep);
1527 const char *packed_object_info_detail(struct packed_git *p,
1529 unsigned long *size,
1530 unsigned long *store_size,
1531 unsigned int *delta_chain_length,
1532 unsigned char *base_sha1)
1534 struct pack_window *w_curs = NULL;
1536 unsigned long dummy;
1537 unsigned char *next_sha1;
1538 enum object_type type;
1539 struct revindex_entry *revidx;
1541 *delta_chain_length = 0;
1542 curpos = obj_offset;
1543 type = unpack_object_header(p, &w_curs, &curpos, size);
1545 revidx = find_pack_revindex(p, obj_offset);
1546 *store_size = revidx[1].offset - obj_offset;
1551 die("pack %s contains unknown object type %d",
1552 p->pack_name, type);
1557 unuse_pack(&w_curs);
1558 return typename(type);
1560 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1562 die("pack %s contains bad delta base reference of type %s",
1563 p->pack_name, typename(type));
1564 if (*delta_chain_length == 0) {
1565 revidx = find_pack_revindex(p, obj_offset);
1566 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1570 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1571 if (*delta_chain_length == 0)
1572 hashcpy(base_sha1, next_sha1);
1573 obj_offset = find_pack_entry_one(next_sha1, p);
1576 (*delta_chain_length)++;
1577 curpos = obj_offset;
1578 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1582 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1583 unsigned long *sizep)
1585 struct pack_window *w_curs = NULL;
1587 off_t curpos = obj_offset;
1588 enum object_type type;
1590 type = unpack_object_header(p, &w_curs, &curpos, &size);
1595 type = packed_delta_info(p, &w_curs, curpos,
1596 type, obj_offset, sizep);
1606 error("unknown object type %i at offset %"PRIuMAX" in %s",
1607 type, (uintmax_t)obj_offset, p->pack_name);
1610 unuse_pack(&w_curs);
1614 static void *unpack_compressed_entry(struct packed_git *p,
1615 struct pack_window **w_curs,
1621 unsigned char *buffer, *in;
1623 buffer = xmallocz(size);
1624 memset(&stream, 0, sizeof(stream));
1625 stream.next_out = buffer;
1626 stream.avail_out = size + 1;
1628 git_inflate_init(&stream);
1630 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1631 stream.next_in = in;
1632 st = git_inflate(&stream, Z_FINISH);
1633 if (!stream.avail_out)
1634 break; /* the payload is larger than it should be */
1635 curpos += stream.next_in - in;
1636 } while (st == Z_OK || st == Z_BUF_ERROR);
1637 git_inflate_end(&stream);
1638 if ((st != Z_STREAM_END) || stream.total_out != size) {
1646 #define MAX_DELTA_CACHE (256)
1648 static size_t delta_base_cached;
1650 static struct delta_base_cache_lru_list {
1651 struct delta_base_cache_lru_list *prev;
1652 struct delta_base_cache_lru_list *next;
1653 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1655 static struct delta_base_cache_entry {
1656 struct delta_base_cache_lru_list lru;
1658 struct packed_git *p;
1661 enum object_type type;
1662 } delta_base_cache[MAX_DELTA_CACHE];
1664 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1668 hash = (unsigned long)p + (unsigned long)base_offset;
1669 hash += (hash >> 8) + (hash >> 16);
1670 return hash % MAX_DELTA_CACHE;
1673 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1674 unsigned long *base_size, enum object_type *type, int keep_cache)
1677 unsigned long hash = pack_entry_hash(p, base_offset);
1678 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1681 if (!ret || ent->p != p || ent->base_offset != base_offset)
1682 return unpack_entry(p, base_offset, type, base_size);
1686 ent->lru.next->prev = ent->lru.prev;
1687 ent->lru.prev->next = ent->lru.next;
1688 delta_base_cached -= ent->size;
1690 ret = xmemdupz(ent->data, ent->size);
1693 *base_size = ent->size;
1697 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1702 ent->lru.next->prev = ent->lru.prev;
1703 ent->lru.prev->next = ent->lru.next;
1704 delta_base_cached -= ent->size;
1708 void clear_delta_base_cache(void)
1711 for (p = 0; p < MAX_DELTA_CACHE; p++)
1712 release_delta_base_cache(&delta_base_cache[p]);
1715 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1716 void *base, unsigned long base_size, enum object_type type)
1718 unsigned long hash = pack_entry_hash(p, base_offset);
1719 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1720 struct delta_base_cache_lru_list *lru;
1722 release_delta_base_cache(ent);
1723 delta_base_cached += base_size;
1725 for (lru = delta_base_cache_lru.next;
1726 delta_base_cached > delta_base_cache_limit
1727 && lru != &delta_base_cache_lru;
1729 struct delta_base_cache_entry *f = (void *)lru;
1730 if (f->type == OBJ_BLOB)
1731 release_delta_base_cache(f);
1733 for (lru = delta_base_cache_lru.next;
1734 delta_base_cached > delta_base_cache_limit
1735 && lru != &delta_base_cache_lru;
1737 struct delta_base_cache_entry *f = (void *)lru;
1738 release_delta_base_cache(f);
1742 ent->base_offset = base_offset;
1745 ent->size = base_size;
1746 ent->lru.next = &delta_base_cache_lru;
1747 ent->lru.prev = delta_base_cache_lru.prev;
1748 delta_base_cache_lru.prev->next = &ent->lru;
1749 delta_base_cache_lru.prev = &ent->lru;
1752 static void *read_object(const unsigned char *sha1, enum object_type *type,
1753 unsigned long *size);
1755 static void *unpack_delta_entry(struct packed_git *p,
1756 struct pack_window **w_curs,
1758 unsigned long delta_size,
1760 enum object_type *type,
1761 unsigned long *sizep)
1763 void *delta_data, *result, *base;
1764 unsigned long base_size;
1767 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1769 error("failed to validate delta base reference "
1770 "at offset %"PRIuMAX" from %s",
1771 (uintmax_t)curpos, p->pack_name);
1775 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1778 * We're probably in deep shit, but let's try to fetch
1779 * the required base anyway from another pack or loose.
1780 * This is costly but should happen only in the presence
1781 * of a corrupted pack, and is better than failing outright.
1783 struct revindex_entry *revidx;
1784 const unsigned char *base_sha1;
1785 revidx = find_pack_revindex(p, base_offset);
1788 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1789 error("failed to read delta base object %s"
1790 " at offset %"PRIuMAX" from %s",
1791 sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1793 mark_bad_packed_object(p, base_sha1);
1794 base = read_object(base_sha1, type, &base_size);
1799 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1801 error("failed to unpack compressed delta "
1802 "at offset %"PRIuMAX" from %s",
1803 (uintmax_t)curpos, p->pack_name);
1807 result = patch_delta(base, base_size,
1808 delta_data, delta_size,
1811 die("failed to apply delta");
1813 add_delta_base_cache(p, base_offset, base, base_size, *type);
1817 int do_check_packed_object_crc;
1819 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1820 enum object_type *type, unsigned long *sizep)
1822 struct pack_window *w_curs = NULL;
1823 off_t curpos = obj_offset;
1826 if (do_check_packed_object_crc && p->index_version > 1) {
1827 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1828 unsigned long len = revidx[1].offset - obj_offset;
1829 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1830 const unsigned char *sha1 =
1831 nth_packed_object_sha1(p, revidx->nr);
1832 error("bad packed object CRC for %s",
1834 mark_bad_packed_object(p, sha1);
1835 unuse_pack(&w_curs);
1840 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1844 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1845 obj_offset, type, sizep);
1851 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1855 error("unknown object type %i at offset %"PRIuMAX" in %s",
1856 *type, (uintmax_t)obj_offset, p->pack_name);
1858 unuse_pack(&w_curs);
1862 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1865 const unsigned char *index = p->index_data;
1867 if (open_pack_index(p))
1869 index = p->index_data;
1871 if (n >= p->num_objects)
1874 if (p->index_version == 1) {
1875 return index + 24 * n + 4;
1878 return index + 20 * n;
1882 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1884 const unsigned char *index = p->index_data;
1886 if (p->index_version == 1) {
1887 return ntohl(*((uint32_t *)(index + 24 * n)));
1890 index += 8 + p->num_objects * (20 + 4);
1891 off = ntohl(*((uint32_t *)(index + 4 * n)));
1892 if (!(off & 0x80000000))
1894 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1895 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1896 ntohl(*((uint32_t *)(index + 4)));
1900 off_t find_pack_entry_one(const unsigned char *sha1,
1901 struct packed_git *p)
1903 const uint32_t *level1_ofs = p->index_data;
1904 const unsigned char *index = p->index_data;
1905 unsigned hi, lo, stride;
1906 static int use_lookup = -1;
1907 static int debug_lookup = -1;
1909 if (debug_lookup < 0)
1910 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1913 if (open_pack_index(p))
1915 level1_ofs = p->index_data;
1916 index = p->index_data;
1918 if (p->index_version > 1) {
1923 hi = ntohl(level1_ofs[*sha1]);
1924 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1925 if (p->index_version > 1) {
1933 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1934 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1937 use_lookup = !!getenv("GIT_USE_LOOKUP");
1939 int pos = sha1_entry_pos(index, stride, 0,
1940 lo, hi, p->num_objects, sha1);
1943 return nth_packed_object_offset(p, pos);
1947 unsigned mi = (lo + hi) / 2;
1948 int cmp = hashcmp(index + mi * stride, sha1);
1951 printf("lo %u hi %u rg %u mi %u\n",
1952 lo, hi, hi - lo, mi);
1954 return nth_packed_object_offset(p, mi);
1963 static int is_pack_valid(struct packed_git *p)
1965 /* An already open pack is known to be valid. */
1966 if (p->pack_fd != -1)
1969 /* If the pack has one window completely covering the
1970 * file size, the pack is known to be valid even if
1971 * the descriptor is not currently open.
1974 struct pack_window *w = p->windows;
1976 if (!w->offset && w->len == p->pack_size)
1980 /* Force the pack to open to prove its valid. */
1981 return !open_packed_git(p);
1984 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1986 static struct packed_git *last_found = (void *)1;
1987 struct packed_git *p;
1990 prepare_packed_git();
1993 p = (last_found == (void *)1) ? packed_git : last_found;
1996 if (p->num_bad_objects) {
1998 for (i = 0; i < p->num_bad_objects; i++)
1999 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2003 offset = find_pack_entry_one(sha1, p);
2006 * We are about to tell the caller where they can
2007 * locate the requested object. We better make
2008 * sure the packfile is still here and can be
2009 * accessed before supplying that answer, as
2010 * it may have been deleted since the index
2013 if (!is_pack_valid(p)) {
2014 error("packfile %s cannot be accessed", p->pack_name);
2019 hashcpy(e->sha1, sha1);
2025 if (p == last_found)
2029 if (p == last_found)
2035 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2036 struct packed_git *packs)
2038 struct packed_git *p;
2040 for (p = packs; p; p = p->next) {
2041 if (find_pack_entry_one(sha1, p))
2048 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
2051 unsigned long mapsize, size;
2056 map = map_sha1_file(sha1, &mapsize);
2058 return error("unable to find %s", sha1_to_hex(sha1));
2059 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2060 status = error("unable to unpack %s header",
2062 else if ((status = parse_sha1_header(hdr, &size)) < 0)
2063 status = error("unable to parse %s header", sha1_to_hex(sha1));
2066 git_inflate_end(&stream);
2067 munmap(map, mapsize);
2071 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2073 struct cached_object *co;
2074 struct pack_entry e;
2077 co = find_cached_object(sha1);
2084 if (!find_pack_entry(sha1, &e)) {
2085 /* Most likely it's a loose object. */
2086 status = sha1_loose_object_info(sha1, sizep);
2090 /* Not a loose object; someone else may have just packed it. */
2091 reprepare_packed_git();
2092 if (!find_pack_entry(sha1, &e))
2096 status = packed_object_info(e.p, e.offset, sizep);
2098 mark_bad_packed_object(e.p, sha1);
2099 status = sha1_object_info(sha1, sizep);
2105 static void *read_packed_sha1(const unsigned char *sha1,
2106 enum object_type *type, unsigned long *size)
2108 struct pack_entry e;
2111 if (!find_pack_entry(sha1, &e))
2113 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2116 * We're probably in deep shit, but let's try to fetch
2117 * the required object anyway from another pack or loose.
2118 * This should happen only in the presence of a corrupted
2119 * pack, and is better than failing outright.
2121 error("failed to read object %s at offset %"PRIuMAX" from %s",
2122 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2123 mark_bad_packed_object(e.p, sha1);
2124 data = read_object(sha1, type, size);
2129 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2130 unsigned char *sha1)
2132 struct cached_object *co;
2134 hash_sha1_file(buf, len, typename(type), sha1);
2135 if (has_sha1_file(sha1) || find_cached_object(sha1))
2137 if (cached_object_alloc <= cached_object_nr) {
2138 cached_object_alloc = alloc_nr(cached_object_alloc);
2139 cached_objects = xrealloc(cached_objects,
2140 sizeof(*cached_objects) *
2141 cached_object_alloc);
2143 co = &cached_objects[cached_object_nr++];
2146 co->buf = xmalloc(len);
2147 memcpy(co->buf, buf, len);
2148 hashcpy(co->sha1, sha1);
2152 static void *read_object(const unsigned char *sha1, enum object_type *type,
2153 unsigned long *size)
2155 unsigned long mapsize;
2157 struct cached_object *co;
2159 co = find_cached_object(sha1);
2163 return xmemdupz(co->buf, co->size);
2166 buf = read_packed_sha1(sha1, type, size);
2169 map = map_sha1_file(sha1, &mapsize);
2171 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2172 munmap(map, mapsize);
2175 reprepare_packed_git();
2176 return read_packed_sha1(sha1, type, size);
2180 * This function dies on corrupt objects; the callers who want to
2181 * deal with them should arrange to call read_object() and give error
2182 * messages themselves.
2184 void *read_sha1_file_repl(const unsigned char *sha1,
2185 enum object_type *type,
2186 unsigned long *size,
2187 const unsigned char **replacement)
2189 const unsigned char *repl = lookup_replace_object(sha1);
2192 const struct packed_git *p;
2195 data = read_object(repl, type, size);
2198 *replacement = repl;
2202 if (errno && errno != ENOENT)
2203 die_errno("failed to read object %s", sha1_to_hex(sha1));
2205 /* die if we replaced an object with one that does not exist */
2207 die("replacement %s not found for %s",
2208 sha1_to_hex(repl), sha1_to_hex(sha1));
2210 if (has_loose_object(repl)) {
2211 path = sha1_file_name(sha1);
2212 die("loose object %s (stored in %s) is corrupt",
2213 sha1_to_hex(repl), path);
2216 if ((p = has_packed_and_bad(repl)) != NULL)
2217 die("packed object %s (stored in %s) is corrupt",
2218 sha1_to_hex(repl), p->pack_name);
2223 void *read_object_with_reference(const unsigned char *sha1,
2224 const char *required_type_name,
2225 unsigned long *size,
2226 unsigned char *actual_sha1_return)
2228 enum object_type type, required_type;
2230 unsigned long isize;
2231 unsigned char actual_sha1[20];
2233 required_type = type_from_string(required_type_name);
2234 hashcpy(actual_sha1, sha1);
2236 int ref_length = -1;
2237 const char *ref_type = NULL;
2239 buffer = read_sha1_file(actual_sha1, &type, &isize);
2242 if (type == required_type) {
2244 if (actual_sha1_return)
2245 hashcpy(actual_sha1_return, actual_sha1);
2248 /* Handle references */
2249 else if (type == OBJ_COMMIT)
2251 else if (type == OBJ_TAG)
2252 ref_type = "object ";
2257 ref_length = strlen(ref_type);
2259 if (ref_length + 40 > isize ||
2260 memcmp(buffer, ref_type, ref_length) ||
2261 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2266 /* Now we have the ID of the referred-to object in
2267 * actual_sha1. Check again. */
2271 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2272 const char *type, unsigned char *sha1,
2273 char *hdr, int *hdrlen)
2277 /* Generate the header */
2278 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2282 git_SHA1_Update(&c, hdr, *hdrlen);
2283 git_SHA1_Update(&c, buf, len);
2284 git_SHA1_Final(sha1, &c);
2288 * Move the just written object into its final resting place.
2289 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2290 * "moving" is only a part of what it does, when no patch between
2291 * master to pu changes the call sites of this function.
2293 int move_temp_to_file(const char *tmpfile, const char *filename)
2297 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2299 else if (link(tmpfile, filename))
2303 * Coda hack - coda doesn't like cross-directory links,
2304 * so we fall back to a rename, which will mean that it
2305 * won't be able to check collisions, but that's not a
2308 * The same holds for FAT formatted media.
2310 * When this succeeds, we just return. We have nothing
2313 if (ret && ret != EEXIST) {
2315 if (!rename(tmpfile, filename))
2319 unlink_or_warn(tmpfile);
2321 if (ret != EEXIST) {
2322 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2324 /* FIXME!!! Collision check here ? */
2328 if (adjust_shared_perm(filename))
2329 return error("unable to set permission to '%s'", filename);
2333 static int write_buffer(int fd, const void *buf, size_t len)
2335 if (write_in_full(fd, buf, len) < 0)
2336 return error("file write error (%s)", strerror(errno));
2340 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2341 unsigned char *sha1)
2345 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2349 /* Finalize a file on disk, and close it. */
2350 static void close_sha1_file(int fd)
2352 if (fsync_object_files)
2353 fsync_or_die(fd, "sha1 file");
2355 die_errno("error when closing sha1 file");
2358 /* Size of directory component, including the ending '/' */
2359 static inline int directory_size(const char *filename)
2361 const char *s = strrchr(filename, '/');
2364 return s - filename + 1;
2368 * This creates a temporary file in the same directory as the final
2371 * We want to avoid cross-directory filename renames, because those
2372 * can have problems on various filesystems (FAT, NFS, Coda).
2374 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2376 int fd, dirlen = directory_size(filename);
2378 if (dirlen + 20 > bufsiz) {
2379 errno = ENAMETOOLONG;
2382 memcpy(buffer, filename, dirlen);
2383 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2384 fd = git_mkstemp_mode(buffer, 0444);
2385 if (fd < 0 && dirlen && errno == ENOENT) {
2386 /* Make sure the directory exists */
2387 memcpy(buffer, filename, dirlen);
2388 buffer[dirlen-1] = 0;
2389 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2393 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2394 fd = git_mkstemp_mode(buffer, 0444);
2399 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2400 const void *buf, unsigned long len, time_t mtime)
2403 unsigned char compressed[4096];
2406 unsigned char parano_sha1[20];
2408 static char tmpfile[PATH_MAX];
2410 filename = sha1_file_name(sha1);
2411 fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2413 if (errno == EACCES)
2414 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2416 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2420 memset(&stream, 0, sizeof(stream));
2421 deflateInit(&stream, zlib_compression_level);
2422 stream.next_out = compressed;
2423 stream.avail_out = sizeof(compressed);
2426 /* First header.. */
2427 stream.next_in = (unsigned char *)hdr;
2428 stream.avail_in = hdrlen;
2429 while (deflate(&stream, 0) == Z_OK)
2431 git_SHA1_Update(&c, hdr, hdrlen);
2433 /* Then the data itself.. */
2434 stream.next_in = (void *)buf;
2435 stream.avail_in = len;
2437 unsigned char *in0 = stream.next_in;
2438 ret = deflate(&stream, Z_FINISH);
2439 git_SHA1_Update(&c, in0, stream.next_in - in0);
2440 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2441 die("unable to write sha1 file");
2442 stream.next_out = compressed;
2443 stream.avail_out = sizeof(compressed);
2444 } while (ret == Z_OK);
2446 if (ret != Z_STREAM_END)
2447 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2448 ret = deflateEnd(&stream);
2450 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2451 git_SHA1_Final(parano_sha1, &c);
2452 if (hashcmp(sha1, parano_sha1) != 0)
2453 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2455 close_sha1_file(fd);
2460 utb.modtime = mtime;
2461 if (utime(tmpfile, &utb) < 0)
2462 warning("failed utime() on %s: %s",
2463 tmpfile, strerror(errno));
2466 return move_temp_to_file(tmpfile, filename);
2469 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2471 unsigned char sha1[20];
2475 /* Normally if we have it in the pack then we do not bother writing
2476 * it out into .git/objects/??/?{38} file.
2478 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2480 hashcpy(returnsha1, sha1);
2481 if (has_sha1_file(sha1))
2483 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2486 int force_object_loose(const unsigned char *sha1, time_t mtime)
2490 enum object_type type;
2495 if (has_loose_object(sha1))
2497 buf = read_packed_sha1(sha1, &type, &len);
2499 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2500 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2501 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2507 int has_pack_index(const unsigned char *sha1)
2510 if (stat(sha1_pack_index_name(sha1), &st))
2515 int has_sha1_pack(const unsigned char *sha1)
2517 struct pack_entry e;
2518 return find_pack_entry(sha1, &e);
2521 int has_sha1_file(const unsigned char *sha1)
2523 struct pack_entry e;
2525 if (find_pack_entry(sha1, &e))
2527 return has_loose_object(sha1);
2530 static int index_mem(unsigned char *sha1, void *buf, size_t size,
2531 int write_object, enum object_type type, const char *path)
2533 int ret, re_allocated = 0;
2539 * Convert blobs to git internal format
2541 if ((type == OBJ_BLOB) && path) {
2542 struct strbuf nbuf = STRBUF_INIT;
2543 if (convert_to_git(path, buf, size, &nbuf,
2544 write_object ? safe_crlf : 0)) {
2545 buf = strbuf_detach(&nbuf, &size);
2551 ret = write_sha1_file(buf, size, typename(type), sha1);
2553 ret = hash_sha1_file(buf, size, typename(type), sha1);
2559 #define SMALL_FILE_SIZE (32*1024)
2561 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2562 enum object_type type, const char *path)
2565 size_t size = xsize_t(st->st_size);
2567 if (!S_ISREG(st->st_mode)) {
2568 struct strbuf sbuf = STRBUF_INIT;
2569 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2570 ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object,
2574 strbuf_release(&sbuf);
2576 ret = index_mem(sha1, NULL, size, write_object, type, path);
2577 } else if (size <= SMALL_FILE_SIZE) {
2578 char *buf = xmalloc(size);
2579 if (size == read_in_full(fd, buf, size))
2580 ret = index_mem(sha1, buf, size, write_object, type,
2583 ret = error("short read %s", strerror(errno));
2586 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2587 ret = index_mem(sha1, buf, size, write_object, type, path);
2594 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2597 struct strbuf sb = STRBUF_INIT;
2599 switch (st->st_mode & S_IFMT) {
2601 fd = open(path, O_RDONLY);
2603 return error("open(\"%s\"): %s", path,
2605 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2606 return error("%s: failed to insert into database",
2610 if (strbuf_readlink(&sb, path, st->st_size)) {
2611 char *errstr = strerror(errno);
2612 return error("readlink(\"%s\"): %s", path,
2616 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2617 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2618 return error("%s: failed to insert into database",
2620 strbuf_release(&sb);
2623 return resolve_gitlink_ref(path, "HEAD", sha1);
2625 return error("%s: unsupported file type", path);
2630 int read_pack_header(int fd, struct pack_header *header)
2632 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2633 /* "eof before pack header was fully read" */
2634 return PH_ERROR_EOF;
2636 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2637 /* "protocol error (pack signature mismatch detected)" */
2638 return PH_ERROR_PACK_SIGNATURE;
2639 if (!pack_version_ok(header->hdr_version))
2640 /* "protocol error (pack version unsupported)" */
2641 return PH_ERROR_PROTOCOL;
2645 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2647 enum object_type type = sha1_object_info(sha1, NULL);
2649 die("%s is not a valid object", sha1_to_hex(sha1));
2651 die("%s is not a valid '%s' object", sha1_to_hex(sha1),