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"
20 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
21 #define O_NOATIME 01000000
29 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
32 static size_t sz_fmt(size_t s) { return s; }
35 const unsigned char null_sha1[20];
37 static unsigned int sha1_file_open_flag = O_NOATIME;
39 const signed char hexval_table[256] = {
40 -1, -1, -1, -1, -1, -1, -1, -1, /* 00-07 */
41 -1, -1, -1, -1, -1, -1, -1, -1, /* 08-0f */
42 -1, -1, -1, -1, -1, -1, -1, -1, /* 10-17 */
43 -1, -1, -1, -1, -1, -1, -1, -1, /* 18-1f */
44 -1, -1, -1, -1, -1, -1, -1, -1, /* 20-27 */
45 -1, -1, -1, -1, -1, -1, -1, -1, /* 28-2f */
46 0, 1, 2, 3, 4, 5, 6, 7, /* 30-37 */
47 8, 9, -1, -1, -1, -1, -1, -1, /* 38-3f */
48 -1, 10, 11, 12, 13, 14, 15, -1, /* 40-47 */
49 -1, -1, -1, -1, -1, -1, -1, -1, /* 48-4f */
50 -1, -1, -1, -1, -1, -1, -1, -1, /* 50-57 */
51 -1, -1, -1, -1, -1, -1, -1, -1, /* 58-5f */
52 -1, 10, 11, 12, 13, 14, 15, -1, /* 60-67 */
53 -1, -1, -1, -1, -1, -1, -1, -1, /* 68-67 */
54 -1, -1, -1, -1, -1, -1, -1, -1, /* 70-77 */
55 -1, -1, -1, -1, -1, -1, -1, -1, /* 78-7f */
56 -1, -1, -1, -1, -1, -1, -1, -1, /* 80-87 */
57 -1, -1, -1, -1, -1, -1, -1, -1, /* 88-8f */
58 -1, -1, -1, -1, -1, -1, -1, -1, /* 90-97 */
59 -1, -1, -1, -1, -1, -1, -1, -1, /* 98-9f */
60 -1, -1, -1, -1, -1, -1, -1, -1, /* a0-a7 */
61 -1, -1, -1, -1, -1, -1, -1, -1, /* a8-af */
62 -1, -1, -1, -1, -1, -1, -1, -1, /* b0-b7 */
63 -1, -1, -1, -1, -1, -1, -1, -1, /* b8-bf */
64 -1, -1, -1, -1, -1, -1, -1, -1, /* c0-c7 */
65 -1, -1, -1, -1, -1, -1, -1, -1, /* c8-cf */
66 -1, -1, -1, -1, -1, -1, -1, -1, /* d0-d7 */
67 -1, -1, -1, -1, -1, -1, -1, -1, /* d8-df */
68 -1, -1, -1, -1, -1, -1, -1, -1, /* e0-e7 */
69 -1, -1, -1, -1, -1, -1, -1, -1, /* e8-ef */
70 -1, -1, -1, -1, -1, -1, -1, -1, /* f0-f7 */
71 -1, -1, -1, -1, -1, -1, -1, -1, /* f8-ff */
74 int get_sha1_hex(const char *hex, unsigned char *sha1)
77 for (i = 0; i < 20; i++) {
78 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
87 int safe_create_leading_directories(char *path)
92 if (is_absolute_path(path))
96 pos = strchr(pos, '/');
100 if (!stat(path, &st)) {
102 if (!S_ISDIR(st.st_mode)) {
107 else if (mkdir(path, 0777)) {
111 else if (adjust_shared_perm(path)) {
120 char * sha1_to_hex(const unsigned char *sha1)
123 static char hexbuffer[4][50];
124 static const char hex[] = "0123456789abcdef";
125 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
128 for (i = 0; i < 20; i++) {
129 unsigned int val = *sha1++;
130 *buf++ = hex[val >> 4];
131 *buf++ = hex[val & 0xf];
138 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
141 for (i = 0; i < 20; i++) {
142 static char hex[] = "0123456789abcdef";
143 unsigned int val = sha1[i];
144 char *pos = pathbuf + i*2 + (i > 0);
145 *pos++ = hex[val >> 4];
146 *pos = hex[val & 0xf];
151 * NOTE! This returns a statically allocated buffer, so you have to be
152 * careful about using it. Do an "xstrdup()" if you need to save the
155 * Also note that this returns the location for creating. Reading
156 * SHA1 file can happen from any alternate directory listed in the
157 * DB_ENVIRONMENT environment variable if it is not found in
158 * the primary object database.
160 char *sha1_file_name(const unsigned char *sha1)
162 static char *name, *base;
165 const char *sha1_file_directory = get_object_directory();
166 int len = strlen(sha1_file_directory);
167 base = xmalloc(len + 60);
168 memcpy(base, sha1_file_directory, len);
169 memset(base+len, 0, 60);
172 name = base + len + 1;
174 fill_sha1_path(name, sha1);
178 char *sha1_pack_name(const unsigned char *sha1)
180 static const char hex[] = "0123456789abcdef";
181 static char *name, *base, *buf;
185 const char *sha1_file_directory = get_object_directory();
186 int len = strlen(sha1_file_directory);
187 base = xmalloc(len + 60);
188 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
189 name = base + len + 11;
194 for (i = 0; i < 20; i++) {
195 unsigned int val = *sha1++;
196 *buf++ = hex[val >> 4];
197 *buf++ = hex[val & 0xf];
203 char *sha1_pack_index_name(const unsigned char *sha1)
205 static const char hex[] = "0123456789abcdef";
206 static char *name, *base, *buf;
210 const char *sha1_file_directory = get_object_directory();
211 int len = strlen(sha1_file_directory);
212 base = xmalloc(len + 60);
213 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
214 name = base + len + 11;
219 for (i = 0; i < 20; i++) {
220 unsigned int val = *sha1++;
221 *buf++ = hex[val >> 4];
222 *buf++ = hex[val & 0xf];
228 struct alternate_object_database *alt_odb_list;
229 static struct alternate_object_database **alt_odb_tail;
231 static void read_info_alternates(const char * alternates, int depth);
234 * Prepare alternate object database registry.
236 * The variable alt_odb_list points at the list of struct
237 * alternate_object_database. The elements on this list come from
238 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
239 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
240 * whose contents is similar to that environment variable but can be
241 * LF separated. Its base points at a statically allocated buffer that
242 * contains "/the/directory/corresponding/to/.git/objects/...", while
243 * its name points just after the slash at the end of ".git/objects/"
244 * in the example above, and has enough space to hold 40-byte hex
245 * SHA1, an extra slash for the first level indirection, and the
248 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
251 const char *objdir = get_object_directory();
252 struct alternate_object_database *ent;
253 struct alternate_object_database *alt;
254 /* 43 = 40-byte + 2 '/' + terminating NUL */
256 int entlen = pfxlen + 43;
259 if (!is_absolute_path(entry) && relative_base) {
260 /* Relative alt-odb */
262 base_len = strlen(relative_base) + 1;
266 ent = xmalloc(sizeof(*ent) + entlen);
268 if (!is_absolute_path(entry) && relative_base) {
269 memcpy(ent->base, relative_base, base_len - 1);
270 ent->base[base_len - 1] = '/';
271 memcpy(ent->base + base_len, entry, len);
274 memcpy(ent->base, entry, pfxlen);
276 ent->name = ent->base + pfxlen + 1;
277 ent->base[pfxlen + 3] = '/';
278 ent->base[pfxlen] = ent->base[entlen-1] = 0;
280 /* Detect cases where alternate disappeared */
281 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
282 error("object directory %s does not exist; "
283 "check .git/objects/info/alternates.",
289 /* Prevent the common mistake of listing the same
290 * thing twice, or object directory itself.
292 for (alt = alt_odb_list; alt; alt = alt->next) {
293 if (!memcmp(ent->base, alt->base, pfxlen)) {
298 if (!memcmp(ent->base, objdir, pfxlen)) {
303 /* add the alternate entry */
305 alt_odb_tail = &(ent->next);
308 /* recursively add alternates */
309 read_info_alternates(ent->base, depth + 1);
311 ent->base[pfxlen] = '/';
316 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
317 const char *relative_base, int depth)
319 const char *cp, *last;
322 error("%s: ignoring alternate object stores, nesting too deep.",
330 if (cp < ep && *cp == '#') {
331 while (cp < ep && *cp != sep)
336 while (cp < ep && *cp != sep)
339 if (!is_absolute_path(last) && depth) {
340 error("%s: ignoring relative alternate object store %s",
341 relative_base, last);
343 link_alt_odb_entry(last, cp - last,
344 relative_base, depth);
347 while (cp < ep && *cp == sep)
353 static void read_info_alternates(const char * relative_base, int depth)
358 const char alt_file_name[] = "info/alternates";
359 /* Given that relative_base is no longer than PATH_MAX,
360 ensure that "path" has enough space to append "/", the
361 file name, "info/alternates", and a trailing NUL. */
362 char path[PATH_MAX + 1 + sizeof alt_file_name];
365 sprintf(path, "%s/%s", relative_base, alt_file_name);
366 fd = open(path, O_RDONLY);
369 if (fstat(fd, &st) || (st.st_size == 0)) {
373 mapsz = xsize_t(st.st_size);
374 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
377 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
382 void prepare_alt_odb(void)
389 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
392 alt_odb_tail = &alt_odb_list;
393 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
395 read_info_alternates(get_object_directory(), 0);
398 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
400 char *name = sha1_file_name(sha1);
401 struct alternate_object_database *alt;
406 for (alt = alt_odb_list; alt; alt = alt->next) {
408 fill_sha1_path(name, sha1);
409 if (!stat(alt->base, st))
415 static unsigned int pack_used_ctr;
416 static unsigned int pack_mmap_calls;
417 static unsigned int peak_pack_open_windows;
418 static unsigned int pack_open_windows;
419 static size_t peak_pack_mapped;
420 static size_t pack_mapped;
421 struct packed_git *packed_git;
423 void pack_report(void)
426 "pack_report: getpagesize() = %10" SZ_FMT "\n"
427 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
428 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
429 sz_fmt(getpagesize()),
430 sz_fmt(packed_git_window_size),
431 sz_fmt(packed_git_limit));
433 "pack_report: pack_used_ctr = %10u\n"
434 "pack_report: pack_mmap_calls = %10u\n"
435 "pack_report: pack_open_windows = %10u / %10u\n"
436 "pack_report: pack_mapped = "
437 "%10" SZ_FMT " / %10" SZ_FMT "\n",
440 pack_open_windows, peak_pack_open_windows,
441 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
444 static int check_packed_git_idx(const char *path, struct packed_git *p)
447 struct pack_idx_header *hdr;
449 uint32_t version, nr, i, *index;
450 int fd = open(path, O_RDONLY);
455 if (fstat(fd, &st)) {
459 idx_size = xsize_t(st.st_size);
460 if (idx_size < 4 * 256 + 20 + 20) {
462 return error("index file %s is too small", path);
464 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
468 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
469 version = ntohl(hdr->idx_version);
470 if (version < 2 || version > 2) {
471 munmap(idx_map, idx_size);
472 return error("index file %s is version %d"
473 " and is not supported by this binary"
474 " (try upgrading GIT to a newer version)",
483 index += 2; /* skip index header */
484 for (i = 0; i < 256; i++) {
485 uint32_t n = ntohl(index[i]);
487 munmap(idx_map, idx_size);
488 return error("non-monotonic index %s", path);
496 * - 256 index entries 4 bytes each
497 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
498 * - 20-byte SHA1 of the packfile
499 * - 20-byte SHA1 file checksum
501 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
502 munmap(idx_map, idx_size);
503 return error("wrong index v1 file size in %s", path);
505 } else if (version == 2) {
508 * - 8 bytes of header
509 * - 256 index entries 4 bytes each
510 * - 20-byte sha1 entry * nr
511 * - 4-byte crc entry * nr
512 * - 4-byte offset entry * nr
513 * - 20-byte SHA1 of the packfile
514 * - 20-byte SHA1 file checksum
515 * And after the 4-byte offset table might be a
516 * variable sized table containing 8-byte entries
517 * for offsets larger than 2^31.
519 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
520 unsigned long max_size = min_size;
522 max_size += (nr - 1)*8;
523 if (idx_size < min_size || idx_size > max_size) {
524 munmap(idx_map, idx_size);
525 return error("wrong index v2 file size in %s", path);
527 if (idx_size != min_size &&
529 * make sure we can deal with large pack offsets.
530 * 31-bit signed offset won't be enough, neither
531 * 32-bit unsigned one will be.
533 (sizeof(off_t) <= 4)) {
534 munmap(idx_map, idx_size);
535 return error("pack too large for current definition of off_t in %s", path);
539 p->index_version = version;
540 p->index_data = idx_map;
541 p->index_size = idx_size;
546 int open_pack_index(struct packed_git *p)
554 idx_name = xstrdup(p->pack_name);
555 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
556 ret = check_packed_git_idx(idx_name, p);
561 static void scan_windows(struct packed_git *p,
562 struct packed_git **lru_p,
563 struct pack_window **lru_w,
564 struct pack_window **lru_l)
566 struct pack_window *w, *w_l;
568 for (w_l = NULL, w = p->windows; w; w = w->next) {
570 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
580 static int unuse_one_window(struct packed_git *current, int keep_fd)
582 struct packed_git *p, *lru_p = NULL;
583 struct pack_window *lru_w = NULL, *lru_l = NULL;
586 scan_windows(current, &lru_p, &lru_w, &lru_l);
587 for (p = packed_git; p; p = p->next)
588 scan_windows(p, &lru_p, &lru_w, &lru_l);
590 munmap(lru_w->base, lru_w->len);
591 pack_mapped -= lru_w->len;
593 lru_l->next = lru_w->next;
595 lru_p->windows = lru_w->next;
596 if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
597 close(lru_p->pack_fd);
608 void release_pack_memory(size_t need, int fd)
610 size_t cur = pack_mapped;
611 while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
615 void close_pack_windows(struct packed_git *p)
618 struct pack_window *w = p->windows;
621 die("pack '%s' still has open windows to it",
623 munmap(w->base, w->len);
624 pack_mapped -= w->len;
626 p->windows = w->next;
631 void unuse_pack(struct pack_window **w_cursor)
633 struct pack_window *w = *w_cursor;
641 * Do not call this directly as this leaks p->pack_fd on error return;
642 * call open_packed_git() instead.
644 static int open_packed_git_1(struct packed_git *p)
647 struct pack_header hdr;
648 unsigned char sha1[20];
649 unsigned char *idx_sha1;
652 if (!p->index_data && open_pack_index(p))
653 return error("packfile %s index unavailable", p->pack_name);
655 p->pack_fd = open(p->pack_name, O_RDONLY);
656 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
659 /* If we created the struct before we had the pack we lack size. */
661 if (!S_ISREG(st.st_mode))
662 return error("packfile %s not a regular file", p->pack_name);
663 p->pack_size = st.st_size;
664 } else if (p->pack_size != st.st_size)
665 return error("packfile %s size changed", p->pack_name);
667 /* We leave these file descriptors open with sliding mmap;
668 * there is no point keeping them open across exec(), though.
670 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
672 return error("cannot determine file descriptor flags");
673 fd_flag |= FD_CLOEXEC;
674 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
675 return error("cannot set FD_CLOEXEC");
677 /* Verify we recognize this pack file format. */
678 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
679 return error("file %s is far too short to be a packfile", p->pack_name);
680 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
681 return error("file %s is not a GIT packfile", p->pack_name);
682 if (!pack_version_ok(hdr.hdr_version))
683 return error("packfile %s is version %u and not supported"
684 " (try upgrading GIT to a newer version)",
685 p->pack_name, ntohl(hdr.hdr_version));
687 /* Verify the pack matches its index. */
688 if (p->num_objects != ntohl(hdr.hdr_entries))
689 return error("packfile %s claims to have %u objects"
690 " while index indicates %u objects",
691 p->pack_name, ntohl(hdr.hdr_entries),
693 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
694 return error("end of packfile %s is unavailable", p->pack_name);
695 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
696 return error("packfile %s signature is unavailable", p->pack_name);
697 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
698 if (hashcmp(sha1, idx_sha1))
699 return error("packfile %s does not match index", p->pack_name);
703 static int open_packed_git(struct packed_git *p)
705 if (!open_packed_git_1(p))
707 if (p->pack_fd != -1) {
714 static int in_window(struct pack_window *win, off_t offset)
716 /* We must promise at least 20 bytes (one hash) after the
717 * offset is available from this window, otherwise the offset
718 * is not actually in this window and a different window (which
719 * has that one hash excess) must be used. This is to support
720 * the object header and delta base parsing routines below.
722 off_t win_off = win->offset;
723 return win_off <= offset
724 && (offset + 20) <= (win_off + win->len);
727 unsigned char* use_pack(struct packed_git *p,
728 struct pack_window **w_cursor,
732 struct pack_window *win = *w_cursor;
734 if (p->pack_fd == -1 && open_packed_git(p))
735 die("packfile %s cannot be accessed", p->pack_name);
737 /* Since packfiles end in a hash of their content and its
738 * pointless to ask for an offset into the middle of that
739 * hash, and the in_window function above wouldn't match
740 * don't allow an offset too close to the end of the file.
742 if (offset > (p->pack_size - 20))
743 die("offset beyond end of packfile (truncated pack?)");
745 if (!win || !in_window(win, offset)) {
748 for (win = p->windows; win; win = win->next) {
749 if (in_window(win, offset))
753 size_t window_align = packed_git_window_size / 2;
755 win = xcalloc(1, sizeof(*win));
756 win->offset = (offset / window_align) * window_align;
757 len = p->pack_size - win->offset;
758 if (len > packed_git_window_size)
759 len = packed_git_window_size;
760 win->len = (size_t)len;
761 pack_mapped += win->len;
762 while (packed_git_limit < pack_mapped
763 && unuse_one_window(p, p->pack_fd))
765 win->base = xmmap(NULL, win->len,
766 PROT_READ, MAP_PRIVATE,
767 p->pack_fd, win->offset);
768 if (win->base == MAP_FAILED)
769 die("packfile %s cannot be mapped: %s",
774 if (pack_mapped > peak_pack_mapped)
775 peak_pack_mapped = pack_mapped;
776 if (pack_open_windows > peak_pack_open_windows)
777 peak_pack_open_windows = pack_open_windows;
778 win->next = p->windows;
782 if (win != *w_cursor) {
783 win->last_used = pack_used_ctr++;
787 offset -= win->offset;
789 *left = win->len - xsize_t(offset);
790 return win->base + offset;
793 struct packed_git *add_packed_git(const char *path, int path_len, int local)
796 struct packed_git *p = xmalloc(sizeof(*p) + path_len + 2);
799 * Make sure a corresponding .pack file exists and that
800 * the index looks sane.
802 path_len -= strlen(".idx");
805 memcpy(p->pack_name, path, path_len);
806 strcpy(p->pack_name + path_len, ".pack");
807 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
812 /* ok, it looks sane as far as we can check without
813 * actually mapping the pack file.
815 p->index_version = 0;
816 p->index_data = NULL;
819 p->pack_size = st.st_size;
823 p->pack_local = local;
824 p->mtime = st.st_mtime;
825 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
830 struct packed_git *parse_pack_index(unsigned char *sha1)
832 char *path = sha1_pack_index_name(sha1);
833 return parse_pack_index_file(sha1, path);
836 struct packed_git *parse_pack_index_file(const unsigned char *sha1,
837 const char *idx_path)
839 const char *path = sha1_pack_name(sha1);
840 struct packed_git *p = xmalloc(sizeof(*p) + strlen(path) + 2);
842 if (check_packed_git_idx(idx_path, p)) {
847 strcpy(p->pack_name, path);
852 hashcpy(p->sha1, sha1);
856 void install_packed_git(struct packed_git *pack)
858 pack->next = packed_git;
862 static void prepare_packed_git_one(char *objdir, int local)
864 /* Ensure that this buffer is large enough so that we can
865 append "/pack/" without clobbering the stack even if
866 strlen(objdir) were PATH_MAX. */
867 char path[PATH_MAX + 1 + 4 + 1 + 1];
872 sprintf(path, "%s/pack", objdir);
877 error("unable to open object pack directory: %s: %s",
878 path, strerror(errno));
882 while ((de = readdir(dir)) != NULL) {
883 int namelen = strlen(de->d_name);
884 struct packed_git *p;
886 if (!has_extension(de->d_name, ".idx"))
889 if (len + namelen + 1 > sizeof(path))
892 /* Don't reopen a pack we already have. */
893 strcpy(path + len, de->d_name);
894 for (p = packed_git; p; p = p->next) {
895 if (!memcmp(path, p->pack_name, len + namelen - 4))
900 /* See if it really is a valid .idx file with corresponding
901 * .pack file that we can map.
903 p = add_packed_git(path, len + namelen, local);
906 install_packed_git(p);
911 static int sort_pack(const void *a_, const void *b_)
913 struct packed_git *a = *((struct packed_git **)a_);
914 struct packed_git *b = *((struct packed_git **)b_);
918 * Local packs tend to contain objects specific to our
919 * variant of the project than remote ones. In addition,
920 * remote ones could be on a network mounted filesystem.
921 * Favor local ones for these reasons.
923 st = a->pack_local - b->pack_local;
928 * Younger packs tend to contain more recent objects,
929 * and more recent objects tend to get accessed more
932 if (a->mtime < b->mtime)
934 else if (a->mtime == b->mtime)
939 static void rearrange_packed_git(void)
941 struct packed_git **ary, *p;
944 for (n = 0, p = packed_git; p; p = p->next)
949 /* prepare an array of packed_git for easier sorting */
950 ary = xcalloc(n, sizeof(struct packed_git *));
951 for (n = 0, p = packed_git; p; p = p->next)
954 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
956 /* link them back again */
957 for (i = 0; i < n - 1; i++)
958 ary[i]->next = ary[i + 1];
959 ary[n - 1]->next = NULL;
965 static int prepare_packed_git_run_once = 0;
966 void prepare_packed_git(void)
968 struct alternate_object_database *alt;
970 if (prepare_packed_git_run_once)
972 prepare_packed_git_one(get_object_directory(), 1);
974 for (alt = alt_odb_list; alt; alt = alt->next) {
976 prepare_packed_git_one(alt->base, 0);
979 rearrange_packed_git();
980 prepare_packed_git_run_once = 1;
983 void reprepare_packed_git(void)
985 prepare_packed_git_run_once = 0;
986 prepare_packed_git();
989 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
991 unsigned char real_sha1[20];
992 hash_sha1_file(map, size, type, real_sha1);
993 return hashcmp(sha1, real_sha1) ? -1 : 0;
996 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1001 char *filename = find_sha1_file(sha1, &st);
1007 fd = open(filename, O_RDONLY | sha1_file_open_flag);
1009 /* See if it works without O_NOATIME */
1010 switch (sha1_file_open_flag) {
1012 fd = open(filename, O_RDONLY);
1020 /* If it failed once, it will probably fail again.
1021 * Stop using O_NOATIME
1023 sha1_file_open_flag = 0;
1025 *size = xsize_t(st.st_size);
1026 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1031 static int legacy_loose_object(unsigned char *map)
1036 * Is it a zlib-compressed buffer? If so, the first byte
1037 * must be 0x78 (15-bit window size, deflated), and the
1038 * first 16-bit word is evenly divisible by 31
1040 word = (map[0] << 8) + map[1];
1041 if (map[0] == 0x78 && !(word % 31))
1047 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1052 unsigned long used = 0;
1055 *type = (c >> 4) & 7;
1061 if (sizeof(long) * 8 <= shift)
1064 size += (c & 0x7f) << shift;
1071 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1073 unsigned long size, used;
1074 static const char valid_loose_object_type[8] = {
1076 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1077 0, /* "delta" and others are invalid in a loose object */
1079 enum object_type type;
1081 /* Get the data stream */
1082 memset(stream, 0, sizeof(*stream));
1083 stream->next_in = map;
1084 stream->avail_in = mapsize;
1085 stream->next_out = buffer;
1086 stream->avail_out = bufsiz;
1088 if (legacy_loose_object(map)) {
1089 inflateInit(stream);
1090 return inflate(stream, 0);
1095 * There used to be a second loose object header format which
1096 * was meant to mimic the in-pack format, allowing for direct
1097 * copy of the object data. This format turned up not to be
1098 * really worth it and we don't write it any longer. But we
1099 * can still read it.
1101 used = unpack_object_header_gently(map, mapsize, &type, &size);
1102 if (!used || !valid_loose_object_type[type])
1107 /* Set up the stream for the rest.. */
1108 stream->next_in = map;
1109 stream->avail_in = mapsize;
1110 inflateInit(stream);
1112 /* And generate the fake traditional header */
1113 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1114 typename(type), size);
1118 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1120 int bytes = strlen(buffer) + 1;
1121 unsigned char *buf = xmalloc(1+size);
1125 n = stream->total_out - bytes;
1128 memcpy(buf, (char *) buffer + bytes, n);
1130 if (bytes <= size) {
1132 * The above condition must be (bytes <= size), not
1133 * (bytes < size). In other words, even though we
1134 * expect no more output and set avail_out to zer0,
1135 * the input zlib stream may have bytes that express
1136 * "this concludes the stream", and we *do* want to
1139 * Otherwise we would not be able to test that we
1140 * consumed all the input to reach the expected size;
1141 * we also want to check that zlib tells us that all
1142 * went well with status == Z_STREAM_END at the end.
1144 stream->next_out = buf + bytes;
1145 stream->avail_out = size - bytes;
1146 while (status == Z_OK)
1147 status = inflate(stream, Z_FINISH);
1150 if (status == Z_STREAM_END && !stream->avail_in) {
1156 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1157 else if (stream->avail_in)
1158 error("garbage at end of loose object '%s'",
1165 * We used to just use "sscanf()", but that's actually way
1166 * too permissive for what we want to check. So do an anal
1167 * object header parse by hand.
1169 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1176 * The type can be at most ten bytes (including the
1177 * terminating '\0' that we add), and is followed by
1186 if (i >= sizeof(type))
1192 * The length must follow immediately, and be in canonical
1193 * decimal format (ie "010" is not valid).
1195 size = *hdr++ - '0';
1200 unsigned long c = *hdr - '0';
1204 size = size * 10 + c;
1210 * The length must be followed by a zero byte
1212 return *hdr ? -1 : type_from_string(type);
1215 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1221 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1222 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1225 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1228 unsigned long get_size_from_delta(struct packed_git *p,
1229 struct pack_window **w_curs,
1232 const unsigned char *data;
1233 unsigned char delta_head[20], *in;
1237 memset(&stream, 0, sizeof(stream));
1238 stream.next_out = delta_head;
1239 stream.avail_out = sizeof(delta_head);
1241 inflateInit(&stream);
1243 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1244 stream.next_in = in;
1245 st = inflate(&stream, Z_FINISH);
1246 curpos += stream.next_in - in;
1247 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1248 stream.total_out < sizeof(delta_head));
1249 inflateEnd(&stream);
1250 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1251 die("delta data unpack-initial failed");
1253 /* Examine the initial part of the delta to figure out
1258 /* ignore base size */
1259 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1261 /* Read the result size */
1262 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1265 static off_t get_delta_base(struct packed_git *p,
1266 struct pack_window **w_curs,
1268 enum object_type type,
1269 off_t delta_obj_offset)
1271 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1274 /* use_pack() assured us we have [base_info, base_info + 20)
1275 * as a range that we can look at without walking off the
1276 * end of the mapped window. Its actually the hash size
1277 * that is assured. An OFS_DELTA longer than the hash size
1278 * is stupid, as then a REF_DELTA would be smaller to store.
1280 if (type == OBJ_OFS_DELTA) {
1282 unsigned char c = base_info[used++];
1283 base_offset = c & 127;
1286 if (!base_offset || MSB(base_offset, 7))
1287 die("offset value overflow for delta base object");
1288 c = base_info[used++];
1289 base_offset = (base_offset << 7) + (c & 127);
1291 base_offset = delta_obj_offset - base_offset;
1292 if (base_offset >= delta_obj_offset)
1293 die("delta base offset out of bound");
1295 } else if (type == OBJ_REF_DELTA) {
1296 /* The base entry _must_ be in the same pack */
1297 base_offset = find_pack_entry_one(base_info, p);
1299 die("failed to find delta-pack base object %s",
1300 sha1_to_hex(base_info));
1303 die("I am totally screwed");
1307 /* forward declaration for a mutually recursive function */
1308 static int packed_object_info(struct packed_git *p, off_t offset,
1309 unsigned long *sizep);
1311 static int packed_delta_info(struct packed_git *p,
1312 struct pack_window **w_curs,
1314 enum object_type type,
1316 unsigned long *sizep)
1320 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1321 type = packed_object_info(p, base_offset, NULL);
1323 /* We choose to only get the type of the base object and
1324 * ignore potentially corrupt pack file that expects the delta
1325 * based on a base with a wrong size. This saves tons of
1329 *sizep = get_size_from_delta(p, w_curs, curpos);
1334 static int unpack_object_header(struct packed_git *p,
1335 struct pack_window **w_curs,
1337 unsigned long *sizep)
1339 unsigned char *base;
1342 enum object_type type;
1344 /* use_pack() assures us we have [base, base + 20) available
1345 * as a range that we can look at at. (Its actually the hash
1346 * size that is assured.) With our object header encoding
1347 * the maximum deflated object size is 2^137, which is just
1348 * insane, so we know won't exceed what we have been given.
1350 base = use_pack(p, w_curs, *curpos, &left);
1351 used = unpack_object_header_gently(base, left, &type, sizep);
1353 die("object offset outside of pack file");
1359 const char *packed_object_info_detail(struct packed_git *p,
1361 unsigned long *size,
1362 unsigned long *store_size,
1363 unsigned int *delta_chain_length,
1364 unsigned char *base_sha1)
1366 struct pack_window *w_curs = NULL;
1368 unsigned long dummy;
1369 unsigned char *next_sha1;
1370 enum object_type type;
1371 struct revindex_entry *revidx;
1373 *delta_chain_length = 0;
1374 curpos = obj_offset;
1375 type = unpack_object_header(p, &w_curs, &curpos, size);
1377 revidx = find_pack_revindex(p, obj_offset);
1378 *store_size = revidx[1].offset - obj_offset;
1383 die("pack %s contains unknown object type %d",
1384 p->pack_name, type);
1389 unuse_pack(&w_curs);
1390 return typename(type);
1392 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1393 if (*delta_chain_length == 0) {
1394 revidx = find_pack_revindex(p, obj_offset);
1395 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1399 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1400 if (*delta_chain_length == 0)
1401 hashcpy(base_sha1, next_sha1);
1402 obj_offset = find_pack_entry_one(next_sha1, p);
1405 (*delta_chain_length)++;
1406 curpos = obj_offset;
1407 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1411 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1412 unsigned long *sizep)
1414 struct pack_window *w_curs = NULL;
1416 off_t curpos = obj_offset;
1417 enum object_type type;
1419 type = unpack_object_header(p, &w_curs, &curpos, &size);
1424 type = packed_delta_info(p, &w_curs, curpos,
1425 type, obj_offset, sizep);
1435 die("pack %s contains unknown object type %d",
1436 p->pack_name, type);
1438 unuse_pack(&w_curs);
1442 static void *unpack_compressed_entry(struct packed_git *p,
1443 struct pack_window **w_curs,
1449 unsigned char *buffer, *in;
1451 buffer = xmalloc(size + 1);
1453 memset(&stream, 0, sizeof(stream));
1454 stream.next_out = buffer;
1455 stream.avail_out = size;
1457 inflateInit(&stream);
1459 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1460 stream.next_in = in;
1461 st = inflate(&stream, Z_FINISH);
1462 curpos += stream.next_in - in;
1463 } while (st == Z_OK || st == Z_BUF_ERROR);
1464 inflateEnd(&stream);
1465 if ((st != Z_STREAM_END) || stream.total_out != size) {
1473 #define MAX_DELTA_CACHE (256)
1475 static size_t delta_base_cached;
1477 static struct delta_base_cache_lru_list {
1478 struct delta_base_cache_lru_list *prev;
1479 struct delta_base_cache_lru_list *next;
1480 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1482 static struct delta_base_cache_entry {
1483 struct delta_base_cache_lru_list lru;
1485 struct packed_git *p;
1488 enum object_type type;
1489 } delta_base_cache[MAX_DELTA_CACHE];
1491 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1495 hash = (unsigned long)p + (unsigned long)base_offset;
1496 hash += (hash >> 8) + (hash >> 16);
1497 return hash % MAX_DELTA_CACHE;
1500 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1501 unsigned long *base_size, enum object_type *type, int keep_cache)
1504 unsigned long hash = pack_entry_hash(p, base_offset);
1505 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1508 if (ret && ent->p == p && ent->base_offset == base_offset)
1509 goto found_cache_entry;
1510 return unpack_entry(p, base_offset, type, base_size);
1515 ent->lru.next->prev = ent->lru.prev;
1516 ent->lru.prev->next = ent->lru.next;
1517 delta_base_cached -= ent->size;
1519 ret = xmemdupz(ent->data, ent->size);
1522 *base_size = ent->size;
1526 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1531 ent->lru.next->prev = ent->lru.prev;
1532 ent->lru.prev->next = ent->lru.next;
1533 delta_base_cached -= ent->size;
1537 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1538 void *base, unsigned long base_size, enum object_type type)
1540 unsigned long hash = pack_entry_hash(p, base_offset);
1541 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1542 struct delta_base_cache_lru_list *lru;
1544 release_delta_base_cache(ent);
1545 delta_base_cached += base_size;
1547 for (lru = delta_base_cache_lru.next;
1548 delta_base_cached > delta_base_cache_limit
1549 && lru != &delta_base_cache_lru;
1551 struct delta_base_cache_entry *f = (void *)lru;
1552 if (f->type == OBJ_BLOB)
1553 release_delta_base_cache(f);
1555 for (lru = delta_base_cache_lru.next;
1556 delta_base_cached > delta_base_cache_limit
1557 && lru != &delta_base_cache_lru;
1559 struct delta_base_cache_entry *f = (void *)lru;
1560 release_delta_base_cache(f);
1564 ent->base_offset = base_offset;
1567 ent->size = base_size;
1568 ent->lru.next = &delta_base_cache_lru;
1569 ent->lru.prev = delta_base_cache_lru.prev;
1570 delta_base_cache_lru.prev->next = &ent->lru;
1571 delta_base_cache_lru.prev = &ent->lru;
1574 static void *unpack_delta_entry(struct packed_git *p,
1575 struct pack_window **w_curs,
1577 unsigned long delta_size,
1579 enum object_type *type,
1580 unsigned long *sizep)
1582 void *delta_data, *result, *base;
1583 unsigned long base_size;
1586 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1587 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1589 die("failed to read delta base object"
1590 " at %"PRIuMAX" from %s",
1591 (uintmax_t)base_offset, p->pack_name);
1593 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1595 die("failed to unpack compressed delta"
1596 " at %"PRIuMAX" from %s",
1597 (uintmax_t)curpos, p->pack_name);
1598 result = patch_delta(base, base_size,
1599 delta_data, delta_size,
1602 die("failed to apply delta");
1604 add_delta_base_cache(p, base_offset, base, base_size, *type);
1608 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1609 enum object_type *type, unsigned long *sizep)
1611 struct pack_window *w_curs = NULL;
1612 off_t curpos = obj_offset;
1615 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1619 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1620 obj_offset, type, sizep);
1626 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1629 die("unknown object type %i in %s", *type, p->pack_name);
1631 unuse_pack(&w_curs);
1635 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1638 const unsigned char *index = p->index_data;
1640 if (open_pack_index(p))
1642 index = p->index_data;
1644 if (n >= p->num_objects)
1647 if (p->index_version == 1) {
1648 return index + 24 * n + 4;
1651 return index + 20 * n;
1655 static off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1657 const unsigned char *index = p->index_data;
1659 if (p->index_version == 1) {
1660 return ntohl(*((uint32_t *)(index + 24 * n)));
1663 index += 8 + p->num_objects * (20 + 4);
1664 off = ntohl(*((uint32_t *)(index + 4 * n)));
1665 if (!(off & 0x80000000))
1667 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1668 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1669 ntohl(*((uint32_t *)(index + 4)));
1673 off_t find_pack_entry_one(const unsigned char *sha1,
1674 struct packed_git *p)
1676 const uint32_t *level1_ofs = p->index_data;
1677 const unsigned char *index = p->index_data;
1681 if (open_pack_index(p))
1683 level1_ofs = p->index_data;
1684 index = p->index_data;
1686 if (p->index_version > 1) {
1691 hi = ntohl(level1_ofs[*sha1]);
1692 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1695 unsigned mi = (lo + hi) / 2;
1696 unsigned x = (p->index_version > 1) ? (mi * 20) : (mi * 24 + 4);
1697 int cmp = hashcmp(index + x, sha1);
1699 return nth_packed_object_offset(p, mi);
1708 int matches_pack_name(struct packed_git *p, const char *name)
1710 const char *last_c, *c;
1712 if (!strcmp(p->pack_name, name))
1715 for (c = p->pack_name, last_c = c; *c;)
1720 if (!strcmp(last_c, name))
1726 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1728 static struct packed_git *last_found = (void *)1;
1729 struct packed_git *p;
1732 prepare_packed_git();
1735 p = (last_found == (void *)1) ? packed_git : last_found;
1738 if (ignore_packed) {
1740 for (ig = ignore_packed; *ig; ig++)
1741 if (matches_pack_name(p, *ig))
1747 offset = find_pack_entry_one(sha1, p);
1750 * We are about to tell the caller where they can
1751 * locate the requested object. We better make
1752 * sure the packfile is still here and can be
1753 * accessed before supplying that answer, as
1754 * it may have been deleted since the index
1757 if (p->pack_fd == -1 && open_packed_git(p)) {
1758 error("packfile %s cannot be accessed", p->pack_name);
1763 hashcpy(e->sha1, sha1);
1769 if (p == last_found)
1773 if (p == last_found)
1779 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1780 struct packed_git *packs)
1782 struct packed_git *p;
1784 for (p = packs; p; p = p->next) {
1785 if (find_pack_entry_one(sha1, p))
1792 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1795 unsigned long mapsize, size;
1800 map = map_sha1_file(sha1, &mapsize);
1802 return error("unable to find %s", sha1_to_hex(sha1));
1803 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1804 status = error("unable to unpack %s header",
1806 else if ((status = parse_sha1_header(hdr, &size)) < 0)
1807 status = error("unable to parse %s header", sha1_to_hex(sha1));
1810 inflateEnd(&stream);
1811 munmap(map, mapsize);
1815 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1817 struct pack_entry e;
1819 if (!find_pack_entry(sha1, &e, NULL)) {
1820 reprepare_packed_git();
1821 if (!find_pack_entry(sha1, &e, NULL))
1822 return sha1_loose_object_info(sha1, sizep);
1824 return packed_object_info(e.p, e.offset, sizep);
1827 static void *read_packed_sha1(const unsigned char *sha1,
1828 enum object_type *type, unsigned long *size)
1830 struct pack_entry e;
1832 if (!find_pack_entry(sha1, &e, NULL))
1835 return cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1839 * This is meant to hold a *small* number of objects that you would
1840 * want read_sha1_file() to be able to return, but yet you do not want
1841 * to write them into the object store (e.g. a browse-only
1844 static struct cached_object {
1845 unsigned char sha1[20];
1846 enum object_type type;
1850 static int cached_object_nr, cached_object_alloc;
1852 static struct cached_object empty_tree = {
1853 /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
1854 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
1855 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
1861 static struct cached_object *find_cached_object(const unsigned char *sha1)
1864 struct cached_object *co = cached_objects;
1866 for (i = 0; i < cached_object_nr; i++, co++) {
1867 if (!hashcmp(co->sha1, sha1))
1870 if (!hashcmp(sha1, empty_tree.sha1))
1875 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
1876 unsigned char *sha1)
1878 struct cached_object *co;
1880 hash_sha1_file(buf, len, typename(type), sha1);
1881 if (has_sha1_file(sha1) || find_cached_object(sha1))
1883 if (cached_object_alloc <= cached_object_nr) {
1884 cached_object_alloc = alloc_nr(cached_object_alloc);
1885 cached_objects = xrealloc(cached_objects,
1886 sizeof(*cached_objects) *
1887 cached_object_alloc);
1889 co = &cached_objects[cached_object_nr++];
1892 co->buf = xmalloc(len);
1893 memcpy(co->buf, buf, len);
1894 hashcpy(co->sha1, sha1);
1898 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
1899 unsigned long *size)
1901 unsigned long mapsize;
1903 struct cached_object *co;
1905 co = find_cached_object(sha1);
1909 return xmemdupz(co->buf, co->size);
1912 buf = read_packed_sha1(sha1, type, size);
1915 map = map_sha1_file(sha1, &mapsize);
1917 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
1918 munmap(map, mapsize);
1921 reprepare_packed_git();
1922 return read_packed_sha1(sha1, type, size);
1925 void *read_object_with_reference(const unsigned char *sha1,
1926 const char *required_type_name,
1927 unsigned long *size,
1928 unsigned char *actual_sha1_return)
1930 enum object_type type, required_type;
1932 unsigned long isize;
1933 unsigned char actual_sha1[20];
1935 required_type = type_from_string(required_type_name);
1936 hashcpy(actual_sha1, sha1);
1938 int ref_length = -1;
1939 const char *ref_type = NULL;
1941 buffer = read_sha1_file(actual_sha1, &type, &isize);
1944 if (type == required_type) {
1946 if (actual_sha1_return)
1947 hashcpy(actual_sha1_return, actual_sha1);
1950 /* Handle references */
1951 else if (type == OBJ_COMMIT)
1953 else if (type == OBJ_TAG)
1954 ref_type = "object ";
1959 ref_length = strlen(ref_type);
1961 if (ref_length + 40 > isize ||
1962 memcmp(buffer, ref_type, ref_length) ||
1963 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1968 /* Now we have the ID of the referred-to object in
1969 * actual_sha1. Check again. */
1973 static void write_sha1_file_prepare(const void *buf, unsigned long len,
1974 const char *type, unsigned char *sha1,
1975 char *hdr, int *hdrlen)
1979 /* Generate the header */
1980 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
1984 SHA1_Update(&c, hdr, *hdrlen);
1985 SHA1_Update(&c, buf, len);
1986 SHA1_Final(sha1, &c);
1990 * Link the tempfile to the final place, possibly creating the
1991 * last directory level as you do so.
1993 * Returns the errno on failure, 0 on success.
1995 static int link_temp_to_file(const char *tmpfile, const char *filename)
2000 if (!link(tmpfile, filename))
2004 * Try to mkdir the last path component if that failed.
2006 * Re-try the "link()" regardless of whether the mkdir
2007 * succeeds, since a race might mean that somebody
2011 dir = strrchr(filename, '/');
2014 if (!mkdir(filename, 0777) && adjust_shared_perm(filename)) {
2019 if (!link(tmpfile, filename))
2027 * Move the just written object into its final resting place
2029 int move_temp_to_file(const char *tmpfile, const char *filename)
2031 int ret = link_temp_to_file(tmpfile, filename);
2034 * Coda hack - coda doesn't like cross-directory links,
2035 * so we fall back to a rename, which will mean that it
2036 * won't be able to check collisions, but that's not a
2039 * The same holds for FAT formatted media.
2041 * When this succeeds, we just return 0. We have nothing
2044 if (ret && ret != EEXIST) {
2045 if (!rename(tmpfile, filename))
2051 if (ret != EEXIST) {
2052 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2054 /* FIXME!!! Collision check here ? */
2060 static int write_buffer(int fd, const void *buf, size_t len)
2062 if (write_in_full(fd, buf, len) < 0)
2063 return error("file write error (%s)", strerror(errno));
2067 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2068 unsigned char *sha1)
2072 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2076 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2079 unsigned char *compressed;
2081 unsigned char sha1[20];
2083 static char tmpfile[PATH_MAX];
2087 /* Normally if we have it in the pack then we do not bother writing
2088 * it out into .git/objects/??/?{38} file.
2090 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2091 filename = sha1_file_name(sha1);
2093 hashcpy(returnsha1, sha1);
2094 if (has_sha1_file(sha1))
2096 fd = open(filename, O_RDONLY);
2099 * FIXME!!! We might do collision checking here, but we'd
2100 * need to uncompress the old file and check it. Later.
2106 if (errno != ENOENT) {
2107 return error("sha1 file %s: %s\n", filename, strerror(errno));
2110 snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2112 fd = mkstemp(tmpfile);
2115 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2117 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2121 memset(&stream, 0, sizeof(stream));
2122 deflateInit(&stream, zlib_compression_level);
2123 size = 8 + deflateBound(&stream, len+hdrlen);
2124 compressed = xmalloc(size);
2127 stream.next_out = compressed;
2128 stream.avail_out = size;
2130 /* First header.. */
2131 stream.next_in = (unsigned char *)hdr;
2132 stream.avail_in = hdrlen;
2133 while (deflate(&stream, 0) == Z_OK)
2136 /* Then the data itself.. */
2137 stream.next_in = buf;
2138 stream.avail_in = len;
2139 ret = deflate(&stream, Z_FINISH);
2140 if (ret != Z_STREAM_END)
2141 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2143 ret = deflateEnd(&stream);
2145 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2147 size = stream.total_out;
2149 if (write_buffer(fd, compressed, size) < 0)
2150 die("unable to write sha1 file");
2153 die("unable to write sha1 file");
2156 return move_temp_to_file(tmpfile, filename);
2160 * We need to unpack and recompress the object for writing
2161 * it out to a different file.
2163 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
2167 unsigned char *unpacked;
2169 enum object_type type;
2174 /* need to unpack and recompress it by itself */
2175 unpacked = read_packed_sha1(sha1, &type, &len);
2177 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2179 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2182 memset(&stream, 0, sizeof(stream));
2183 deflateInit(&stream, zlib_compression_level);
2184 size = deflateBound(&stream, len + hdrlen);
2185 buf = xmalloc(size);
2188 stream.next_out = buf;
2189 stream.avail_out = size;
2191 /* First header.. */
2192 stream.next_in = (void *)hdr;
2193 stream.avail_in = hdrlen;
2194 while (deflate(&stream, 0) == Z_OK)
2197 /* Then the data itself.. */
2198 stream.next_in = unpacked;
2199 stream.avail_in = len;
2200 while (deflate(&stream, Z_FINISH) == Z_OK)
2202 deflateEnd(&stream);
2205 *objsize = stream.total_out;
2209 int write_sha1_to_fd(int fd, const unsigned char *sha1)
2212 unsigned long objsize;
2213 void *buf = map_sha1_file(sha1, &objsize);
2216 retval = write_buffer(fd, buf, objsize);
2217 munmap(buf, objsize);
2221 buf = repack_object(sha1, &objsize);
2222 retval = write_buffer(fd, buf, objsize);
2227 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
2228 size_t bufsize, size_t *bufposn)
2230 char tmpfile[PATH_MAX];
2233 unsigned char real_sha1[20];
2234 unsigned char discard[4096];
2238 snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2240 local = mkstemp(tmpfile);
2243 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2245 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2248 memset(&stream, 0, sizeof(stream));
2250 inflateInit(&stream);
2257 stream.avail_in = *bufposn;
2258 stream.next_in = (unsigned char *) buffer;
2260 stream.next_out = discard;
2261 stream.avail_out = sizeof(discard);
2262 ret = inflate(&stream, Z_SYNC_FLUSH);
2263 SHA1_Update(&c, discard, sizeof(discard) -
2265 } while (stream.avail_in && ret == Z_OK);
2266 if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
2267 die("unable to write sha1 file");
2268 memmove(buffer, buffer + *bufposn - stream.avail_in,
2270 *bufposn = stream.avail_in;
2274 size = xread(fd, buffer + *bufposn, bufsize - *bufposn);
2279 return error("Connection closed?");
2280 perror("Reading from connection");
2285 inflateEnd(&stream);
2287 fchmod(local, 0444);
2288 if (close(local) != 0)
2289 die("unable to write sha1 file");
2290 SHA1_Final(real_sha1, &c);
2291 if (ret != Z_STREAM_END) {
2293 return error("File %s corrupted", sha1_to_hex(sha1));
2295 if (hashcmp(sha1, real_sha1)) {
2297 return error("File %s has bad hash", sha1_to_hex(sha1));
2300 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
2303 int has_pack_index(const unsigned char *sha1)
2306 if (stat(sha1_pack_index_name(sha1), &st))
2311 int has_pack_file(const unsigned char *sha1)
2314 if (stat(sha1_pack_name(sha1), &st))
2319 int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2321 struct pack_entry e;
2322 return find_pack_entry(sha1, &e, ignore_packed);
2325 int has_sha1_file(const unsigned char *sha1)
2328 struct pack_entry e;
2330 if (find_pack_entry(sha1, &e, NULL))
2332 return find_sha1_file(sha1, &st) ? 1 : 0;
2335 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2340 strbuf_init(&buf, 0);
2341 if (strbuf_read(&buf, fd, 4096) < 0) {
2342 strbuf_release(&buf);
2349 ret = write_sha1_file(buf.buf, buf.len, type, sha1);
2351 ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2352 strbuf_release(&buf);
2357 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2358 enum object_type type, const char *path)
2360 size_t size = xsize_t(st->st_size);
2362 int ret, re_allocated = 0;
2365 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2372 * Convert blobs to git internal format
2374 if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2376 strbuf_init(&nbuf, 0);
2377 if (convert_to_git(path, buf, size, &nbuf,
2378 write_object ? safe_crlf : 0)) {
2380 buf = strbuf_detach(&nbuf, &size);
2386 ret = write_sha1_file(buf, size, typename(type), sha1);
2388 ret = hash_sha1_file(buf, size, typename(type), sha1);
2398 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2404 switch (st->st_mode & S_IFMT) {
2406 fd = open(path, O_RDONLY);
2408 return error("open(\"%s\"): %s", path,
2410 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2411 return error("%s: failed to insert into database",
2415 len = xsize_t(st->st_size);
2416 target = xmalloc(len + 1);
2417 if (readlink(path, target, len + 1) != st->st_size) {
2418 char *errstr = strerror(errno);
2420 return error("readlink(\"%s\"): %s", path,
2424 hash_sha1_file(target, len, blob_type, sha1);
2425 else if (write_sha1_file(target, len, blob_type, sha1))
2426 return error("%s: failed to insert into database",
2431 return resolve_gitlink_ref(path, "HEAD", sha1);
2433 return error("%s: unsupported file type", path);
2438 int read_pack_header(int fd, struct pack_header *header)
2440 char *c = (char*)header;
2441 ssize_t remaining = sizeof(struct pack_header);
2443 ssize_t r = xread(fd, c, remaining);
2445 /* "eof before pack header was fully read" */
2446 return PH_ERROR_EOF;
2449 } while (remaining > 0);
2450 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2451 /* "protocol error (pack signature mismatch detected)" */
2452 return PH_ERROR_PACK_SIGNATURE;
2453 if (!pack_version_ok(header->hdr_version))
2454 /* "protocol error (pack version unsupported)" */
2455 return PH_ERROR_PROTOCOL;