2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
16 #include "tree-walk.h"
18 #include "pack-revindex.h"
19 #include "sha1-lookup.h"
22 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
23 #define O_NOATIME 01000000
31 static unsigned long sz_fmt(size_t s
) { return (unsigned long)s
; }
34 static size_t sz_fmt(size_t s
) { return s
; }
37 const unsigned char null_sha1
[20];
39 static int git_open_noatime(const char *name
, struct packed_git
*p
);
41 int safe_create_leading_directories(char *path
)
43 char *pos
= path
+ offset_1st_component(path
);
47 pos
= strchr(pos
, '/');
55 if (!stat(path
, &st
)) {
57 if (!S_ISDIR(st
.st_mode
)) {
62 else if (mkdir(path
, 0777)) {
66 else if (adjust_shared_perm(path
)) {
75 int safe_create_leading_directories_const(const char *path
)
77 /* path points to cache entries, so xstrdup before messing with it */
78 char *buf
= xstrdup(path
);
79 int result
= safe_create_leading_directories(buf
);
84 static void fill_sha1_path(char *pathbuf
, const unsigned char *sha1
)
87 for (i
= 0; i
< 20; i
++) {
88 static char hex
[] = "0123456789abcdef";
89 unsigned int val
= sha1
[i
];
90 char *pos
= pathbuf
+ i
*2 + (i
> 0);
91 *pos
++ = hex
[val
>> 4];
92 *pos
= hex
[val
& 0xf];
97 * NOTE! This returns a statically allocated buffer, so you have to be
98 * careful about using it. Do an "xstrdup()" if you need to save the
101 * Also note that this returns the location for creating. Reading
102 * SHA1 file can happen from any alternate directory listed in the
103 * DB_ENVIRONMENT environment variable if it is not found in
104 * the primary object database.
106 char *sha1_file_name(const unsigned char *sha1
)
108 static char buf
[PATH_MAX
];
112 objdir
= get_object_directory();
113 len
= strlen(objdir
);
115 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
116 if (len
+ 43 > PATH_MAX
)
117 die("insanely long object directory %s", objdir
);
118 memcpy(buf
, objdir
, len
);
122 fill_sha1_path(buf
+ len
+ 1, sha1
);
126 static char *sha1_get_pack_name(const unsigned char *sha1
,
127 char **name
, char **base
, const char *which
)
129 static const char hex
[] = "0123456789abcdef";
134 const char *sha1_file_directory
= get_object_directory();
135 int len
= strlen(sha1_file_directory
);
136 *base
= xmalloc(len
+ 60);
137 sprintf(*base
, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
138 sha1_file_directory
, which
);
139 *name
= *base
+ len
+ 11;
144 for (i
= 0; i
< 20; i
++) {
145 unsigned int val
= *sha1
++;
146 *buf
++ = hex
[val
>> 4];
147 *buf
++ = hex
[val
& 0xf];
153 char *sha1_pack_name(const unsigned char *sha1
)
155 static char *name
, *base
;
157 return sha1_get_pack_name(sha1
, &name
, &base
, "pack");
160 char *sha1_pack_index_name(const unsigned char *sha1
)
162 static char *name
, *base
;
164 return sha1_get_pack_name(sha1
, &name
, &base
, "idx");
167 struct alternate_object_database
*alt_odb_list
;
168 static struct alternate_object_database
**alt_odb_tail
;
170 static void read_info_alternates(const char * alternates
, int depth
);
173 * Prepare alternate object database registry.
175 * The variable alt_odb_list points at the list of struct
176 * alternate_object_database. The elements on this list come from
177 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
178 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
179 * whose contents is similar to that environment variable but can be
180 * LF separated. Its base points at a statically allocated buffer that
181 * contains "/the/directory/corresponding/to/.git/objects/...", while
182 * its name points just after the slash at the end of ".git/objects/"
183 * in the example above, and has enough space to hold 40-byte hex
184 * SHA1, an extra slash for the first level indirection, and the
187 static int link_alt_odb_entry(const char * entry
, int len
, const char * relative_base
, int depth
)
189 const char *objdir
= get_object_directory();
190 struct alternate_object_database
*ent
;
191 struct alternate_object_database
*alt
;
192 /* 43 = 40-byte + 2 '/' + terminating NUL */
194 int entlen
= pfxlen
+ 43;
197 if (!is_absolute_path(entry
) && relative_base
) {
198 /* Relative alt-odb */
200 base_len
= strlen(relative_base
) + 1;
204 ent
= xmalloc(sizeof(*ent
) + entlen
);
206 if (!is_absolute_path(entry
) && relative_base
) {
207 memcpy(ent
->base
, relative_base
, base_len
- 1);
208 ent
->base
[base_len
- 1] = '/';
209 memcpy(ent
->base
+ base_len
, entry
, len
);
212 memcpy(ent
->base
, entry
, pfxlen
);
214 ent
->name
= ent
->base
+ pfxlen
+ 1;
215 ent
->base
[pfxlen
+ 3] = '/';
216 ent
->base
[pfxlen
] = ent
->base
[entlen
-1] = 0;
218 /* Detect cases where alternate disappeared */
219 if (!is_directory(ent
->base
)) {
220 error("object directory %s does not exist; "
221 "check .git/objects/info/alternates.",
227 /* Prevent the common mistake of listing the same
228 * thing twice, or object directory itself.
230 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
231 if (!memcmp(ent
->base
, alt
->base
, pfxlen
)) {
236 if (!memcmp(ent
->base
, objdir
, pfxlen
)) {
241 /* add the alternate entry */
243 alt_odb_tail
= &(ent
->next
);
246 /* recursively add alternates */
247 read_info_alternates(ent
->base
, depth
+ 1);
249 ent
->base
[pfxlen
] = '/';
254 static void link_alt_odb_entries(const char *alt
, const char *ep
, int sep
,
255 const char *relative_base
, int depth
)
257 const char *cp
, *last
;
260 error("%s: ignoring alternate object stores, nesting too deep.",
268 if (cp
< ep
&& *cp
== '#') {
269 while (cp
< ep
&& *cp
!= sep
)
274 while (cp
< ep
&& *cp
!= sep
)
277 if (!is_absolute_path(last
) && depth
) {
278 error("%s: ignoring relative alternate object store %s",
279 relative_base
, last
);
281 link_alt_odb_entry(last
, cp
- last
,
282 relative_base
, depth
);
285 while (cp
< ep
&& *cp
== sep
)
291 static void read_info_alternates(const char * relative_base
, int depth
)
296 const char alt_file_name
[] = "info/alternates";
297 /* Given that relative_base is no longer than PATH_MAX,
298 ensure that "path" has enough space to append "/", the
299 file name, "info/alternates", and a trailing NUL. */
300 char path
[PATH_MAX
+ 1 + sizeof alt_file_name
];
303 sprintf(path
, "%s/%s", relative_base
, alt_file_name
);
304 fd
= git_open_noatime(path
, NULL
);
307 if (fstat(fd
, &st
) || (st
.st_size
== 0)) {
311 mapsz
= xsize_t(st
.st_size
);
312 map
= xmmap(NULL
, mapsz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
315 link_alt_odb_entries(map
, map
+ mapsz
, '\n', relative_base
, depth
);
320 void add_to_alternates_file(const char *reference
)
322 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
323 int fd
= hold_lock_file_for_append(lock
, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR
);
324 char *alt
= mkpath("%s/objects\n", reference
);
325 write_or_die(fd
, alt
, strlen(alt
));
326 if (commit_lock_file(lock
))
327 die("could not close alternates file");
329 link_alt_odb_entries(alt
, alt
+ strlen(alt
), '\n', NULL
, 0);
332 void foreach_alt_odb(alt_odb_fn fn
, void *cb
)
334 struct alternate_object_database
*ent
;
337 for (ent
= alt_odb_list
; ent
; ent
= ent
->next
)
342 void prepare_alt_odb(void)
349 alt
= getenv(ALTERNATE_DB_ENVIRONMENT
);
352 alt_odb_tail
= &alt_odb_list
;
353 link_alt_odb_entries(alt
, alt
+ strlen(alt
), PATH_SEP
, NULL
, 0);
355 read_info_alternates(get_object_directory(), 0);
358 static int has_loose_object_local(const unsigned char *sha1
)
360 char *name
= sha1_file_name(sha1
);
361 return !access(name
, F_OK
);
364 int has_loose_object_nonlocal(const unsigned char *sha1
)
366 struct alternate_object_database
*alt
;
368 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
369 fill_sha1_path(alt
->name
, sha1
);
370 if (!access(alt
->base
, F_OK
))
376 static int has_loose_object(const unsigned char *sha1
)
378 return has_loose_object_local(sha1
) ||
379 has_loose_object_nonlocal(sha1
);
382 static unsigned int pack_used_ctr
;
383 static unsigned int pack_mmap_calls
;
384 static unsigned int peak_pack_open_windows
;
385 static unsigned int pack_open_windows
;
386 static size_t peak_pack_mapped
;
387 static size_t pack_mapped
;
388 struct packed_git
*packed_git
;
390 void pack_report(void)
393 "pack_report: getpagesize() = %10" SZ_FMT
"\n"
394 "pack_report: core.packedGitWindowSize = %10" SZ_FMT
"\n"
395 "pack_report: core.packedGitLimit = %10" SZ_FMT
"\n",
396 sz_fmt(getpagesize()),
397 sz_fmt(packed_git_window_size
),
398 sz_fmt(packed_git_limit
));
400 "pack_report: pack_used_ctr = %10u\n"
401 "pack_report: pack_mmap_calls = %10u\n"
402 "pack_report: pack_open_windows = %10u / %10u\n"
403 "pack_report: pack_mapped = "
404 "%10" SZ_FMT
" / %10" SZ_FMT
"\n",
407 pack_open_windows
, peak_pack_open_windows
,
408 sz_fmt(pack_mapped
), sz_fmt(peak_pack_mapped
));
411 static int check_packed_git_idx(const char *path
, struct packed_git
*p
)
414 struct pack_idx_header
*hdr
;
416 uint32_t version
, nr
, i
, *index
;
417 int fd
= git_open_noatime(path
, p
);
422 if (fstat(fd
, &st
)) {
426 idx_size
= xsize_t(st
.st_size
);
427 if (idx_size
< 4 * 256 + 20 + 20) {
429 return error("index file %s is too small", path
);
431 idx_map
= xmmap(NULL
, idx_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
435 if (hdr
->idx_signature
== htonl(PACK_IDX_SIGNATURE
)) {
436 version
= ntohl(hdr
->idx_version
);
437 if (version
< 2 || version
> 2) {
438 munmap(idx_map
, idx_size
);
439 return error("index file %s is version %"PRIu32
440 " and is not supported by this binary"
441 " (try upgrading GIT to a newer version)",
450 index
+= 2; /* skip index header */
451 for (i
= 0; i
< 256; i
++) {
452 uint32_t n
= ntohl(index
[i
]);
454 munmap(idx_map
, idx_size
);
455 return error("non-monotonic index %s", path
);
463 * - 256 index entries 4 bytes each
464 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
465 * - 20-byte SHA1 of the packfile
466 * - 20-byte SHA1 file checksum
468 if (idx_size
!= 4*256 + nr
* 24 + 20 + 20) {
469 munmap(idx_map
, idx_size
);
470 return error("wrong index v1 file size in %s", path
);
472 } else if (version
== 2) {
475 * - 8 bytes of header
476 * - 256 index entries 4 bytes each
477 * - 20-byte sha1 entry * nr
478 * - 4-byte crc entry * nr
479 * - 4-byte offset entry * nr
480 * - 20-byte SHA1 of the packfile
481 * - 20-byte SHA1 file checksum
482 * And after the 4-byte offset table might be a
483 * variable sized table containing 8-byte entries
484 * for offsets larger than 2^31.
486 unsigned long min_size
= 8 + 4*256 + nr
*(20 + 4 + 4) + 20 + 20;
487 unsigned long max_size
= min_size
;
489 max_size
+= (nr
- 1)*8;
490 if (idx_size
< min_size
|| idx_size
> max_size
) {
491 munmap(idx_map
, idx_size
);
492 return error("wrong index v2 file size in %s", path
);
494 if (idx_size
!= min_size
&&
496 * make sure we can deal with large pack offsets.
497 * 31-bit signed offset won't be enough, neither
498 * 32-bit unsigned one will be.
500 (sizeof(off_t
) <= 4)) {
501 munmap(idx_map
, idx_size
);
502 return error("pack too large for current definition of off_t in %s", path
);
506 p
->index_version
= version
;
507 p
->index_data
= idx_map
;
508 p
->index_size
= idx_size
;
513 int open_pack_index(struct packed_git
*p
)
521 idx_name
= xstrdup(p
->pack_name
);
522 strcpy(idx_name
+ strlen(idx_name
) - strlen(".pack"), ".idx");
523 ret
= check_packed_git_idx(idx_name
, p
);
528 static void scan_windows(struct packed_git
*p
,
529 struct packed_git
**lru_p
,
530 struct pack_window
**lru_w
,
531 struct pack_window
**lru_l
)
533 struct pack_window
*w
, *w_l
;
535 for (w_l
= NULL
, w
= p
->windows
; w
; w
= w
->next
) {
537 if (!*lru_w
|| w
->last_used
< (*lru_w
)->last_used
) {
547 static int unuse_one_window(struct packed_git
*current
, int keep_fd
)
549 struct packed_git
*p
, *lru_p
= NULL
;
550 struct pack_window
*lru_w
= NULL
, *lru_l
= NULL
;
553 scan_windows(current
, &lru_p
, &lru_w
, &lru_l
);
554 for (p
= packed_git
; p
; p
= p
->next
)
555 scan_windows(p
, &lru_p
, &lru_w
, &lru_l
);
557 munmap(lru_w
->base
, lru_w
->len
);
558 pack_mapped
-= lru_w
->len
;
560 lru_l
->next
= lru_w
->next
;
562 lru_p
->windows
= lru_w
->next
;
563 if (!lru_p
->windows
&& lru_p
->pack_fd
!= keep_fd
) {
564 close(lru_p
->pack_fd
);
575 void release_pack_memory(size_t need
, int fd
)
577 size_t cur
= pack_mapped
;
578 while (need
>= (cur
- pack_mapped
) && unuse_one_window(NULL
, fd
))
582 void *xmmap(void *start
, size_t length
,
583 int prot
, int flags
, int fd
, off_t offset
)
585 void *ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
586 if (ret
== MAP_FAILED
) {
589 release_pack_memory(length
, fd
);
590 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
591 if (ret
== MAP_FAILED
)
592 die_errno("Out of memory? mmap failed");
597 void close_pack_windows(struct packed_git
*p
)
600 struct pack_window
*w
= p
->windows
;
603 die("pack '%s' still has open windows to it",
605 munmap(w
->base
, w
->len
);
606 pack_mapped
-= w
->len
;
608 p
->windows
= w
->next
;
613 void unuse_pack(struct pack_window
**w_cursor
)
615 struct pack_window
*w
= *w_cursor
;
622 void close_pack_index(struct packed_git
*p
)
625 munmap((void *)p
->index_data
, p
->index_size
);
626 p
->index_data
= NULL
;
631 * This is used by git-repack in case a newly created pack happens to
632 * contain the same set of objects as an existing one. In that case
633 * the resulting file might be different even if its name would be the
634 * same. It is best to close any reference to the old pack before it is
635 * replaced on disk. Of course no index pointers nor windows for given pack
636 * must subsist at this point. If ever objects from this pack are requested
637 * again, the new version of the pack will be reinitialized through
638 * reprepare_packed_git().
640 void free_pack_by_name(const char *pack_name
)
642 struct packed_git
*p
, **pp
= &packed_git
;
646 if (strcmp(pack_name
, p
->pack_name
) == 0) {
647 clear_delta_base_cache();
648 close_pack_windows(p
);
649 if (p
->pack_fd
!= -1)
652 free(p
->bad_object_sha1
);
662 * Do not call this directly as this leaks p->pack_fd on error return;
663 * call open_packed_git() instead.
665 static int open_packed_git_1(struct packed_git
*p
)
668 struct pack_header hdr
;
669 unsigned char sha1
[20];
670 unsigned char *idx_sha1
;
673 if (!p
->index_data
&& open_pack_index(p
))
674 return error("packfile %s index unavailable", p
->pack_name
);
676 p
->pack_fd
= git_open_noatime(p
->pack_name
, p
);
677 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
680 /* If we created the struct before we had the pack we lack size. */
682 if (!S_ISREG(st
.st_mode
))
683 return error("packfile %s not a regular file", p
->pack_name
);
684 p
->pack_size
= st
.st_size
;
685 } else if (p
->pack_size
!= st
.st_size
)
686 return error("packfile %s size changed", p
->pack_name
);
688 /* We leave these file descriptors open with sliding mmap;
689 * there is no point keeping them open across exec(), though.
691 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
693 return error("cannot determine file descriptor flags");
694 fd_flag
|= FD_CLOEXEC
;
695 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
696 return error("cannot set FD_CLOEXEC");
698 /* Verify we recognize this pack file format. */
699 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
700 return error("file %s is far too short to be a packfile", p
->pack_name
);
701 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
702 return error("file %s is not a GIT packfile", p
->pack_name
);
703 if (!pack_version_ok(hdr
.hdr_version
))
704 return error("packfile %s is version %"PRIu32
" and not"
705 " supported (try upgrading GIT to a newer version)",
706 p
->pack_name
, ntohl(hdr
.hdr_version
));
708 /* Verify the pack matches its index. */
709 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
710 return error("packfile %s claims to have %"PRIu32
" objects"
711 " while index indicates %"PRIu32
" objects",
712 p
->pack_name
, ntohl(hdr
.hdr_entries
),
714 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
715 return error("end of packfile %s is unavailable", p
->pack_name
);
716 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
717 return error("packfile %s signature is unavailable", p
->pack_name
);
718 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
719 if (hashcmp(sha1
, idx_sha1
))
720 return error("packfile %s does not match index", p
->pack_name
);
724 static int open_packed_git(struct packed_git
*p
)
726 if (!open_packed_git_1(p
))
728 if (p
->pack_fd
!= -1) {
735 static int in_window(struct pack_window
*win
, off_t offset
)
737 /* We must promise at least 20 bytes (one hash) after the
738 * offset is available from this window, otherwise the offset
739 * is not actually in this window and a different window (which
740 * has that one hash excess) must be used. This is to support
741 * the object header and delta base parsing routines below.
743 off_t win_off
= win
->offset
;
744 return win_off
<= offset
745 && (offset
+ 20) <= (win_off
+ win
->len
);
748 unsigned char *use_pack(struct packed_git
*p
,
749 struct pack_window
**w_cursor
,
753 struct pack_window
*win
= *w_cursor
;
755 if (p
->pack_fd
== -1 && open_packed_git(p
))
756 die("packfile %s cannot be accessed", p
->pack_name
);
758 /* Since packfiles end in a hash of their content and it's
759 * pointless to ask for an offset into the middle of that
760 * hash, and the in_window function above wouldn't match
761 * don't allow an offset too close to the end of the file.
763 if (offset
> (p
->pack_size
- 20))
764 die("offset beyond end of packfile (truncated pack?)");
766 if (!win
|| !in_window(win
, offset
)) {
769 for (win
= p
->windows
; win
; win
= win
->next
) {
770 if (in_window(win
, offset
))
774 size_t window_align
= packed_git_window_size
/ 2;
776 win
= xcalloc(1, sizeof(*win
));
777 win
->offset
= (offset
/ window_align
) * window_align
;
778 len
= p
->pack_size
- win
->offset
;
779 if (len
> packed_git_window_size
)
780 len
= packed_git_window_size
;
781 win
->len
= (size_t)len
;
782 pack_mapped
+= win
->len
;
783 while (packed_git_limit
< pack_mapped
784 && unuse_one_window(p
, p
->pack_fd
))
786 win
->base
= xmmap(NULL
, win
->len
,
787 PROT_READ
, MAP_PRIVATE
,
788 p
->pack_fd
, win
->offset
);
789 if (win
->base
== MAP_FAILED
)
790 die("packfile %s cannot be mapped: %s",
795 if (pack_mapped
> peak_pack_mapped
)
796 peak_pack_mapped
= pack_mapped
;
797 if (pack_open_windows
> peak_pack_open_windows
)
798 peak_pack_open_windows
= pack_open_windows
;
799 win
->next
= p
->windows
;
803 if (win
!= *w_cursor
) {
804 win
->last_used
= pack_used_ctr
++;
808 offset
-= win
->offset
;
810 *left
= win
->len
- xsize_t(offset
);
811 return win
->base
+ offset
;
814 static struct packed_git
*alloc_packed_git(int extra
)
816 struct packed_git
*p
= xmalloc(sizeof(*p
) + extra
);
817 memset(p
, 0, sizeof(*p
));
822 static void try_to_free_pack_memory(size_t size
)
824 release_pack_memory(size
, -1);
827 struct packed_git
*add_packed_git(const char *path
, int path_len
, int local
)
829 static int have_set_try_to_free_routine
;
831 struct packed_git
*p
= alloc_packed_git(path_len
+ 2);
833 if (!have_set_try_to_free_routine
) {
834 have_set_try_to_free_routine
= 1;
835 set_try_to_free_routine(try_to_free_pack_memory
);
839 * Make sure a corresponding .pack file exists and that
840 * the index looks sane.
842 path_len
-= strlen(".idx");
847 memcpy(p
->pack_name
, path
, path_len
);
849 strcpy(p
->pack_name
+ path_len
, ".keep");
850 if (!access(p
->pack_name
, F_OK
))
853 strcpy(p
->pack_name
+ path_len
, ".pack");
854 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
859 /* ok, it looks sane as far as we can check without
860 * actually mapping the pack file.
862 p
->pack_size
= st
.st_size
;
863 p
->pack_local
= local
;
864 p
->mtime
= st
.st_mtime
;
865 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
870 struct packed_git
*parse_pack_index(unsigned char *sha1
, const char *idx_path
)
872 const char *path
= sha1_pack_name(sha1
);
873 struct packed_git
*p
= alloc_packed_git(strlen(path
) + 1);
875 strcpy(p
->pack_name
, path
);
876 hashcpy(p
->sha1
, sha1
);
877 if (check_packed_git_idx(idx_path
, p
)) {
885 void install_packed_git(struct packed_git
*pack
)
887 pack
->next
= packed_git
;
891 static void prepare_packed_git_one(char *objdir
, int local
)
893 /* Ensure that this buffer is large enough so that we can
894 append "/pack/" without clobbering the stack even if
895 strlen(objdir) were PATH_MAX. */
896 char path
[PATH_MAX
+ 1 + 4 + 1 + 1];
901 sprintf(path
, "%s/pack", objdir
);
904 while (!dir
&& errno
== EMFILE
&& unuse_one_window(NULL
, -1))
908 error("unable to open object pack directory: %s: %s",
909 path
, strerror(errno
));
913 while ((de
= readdir(dir
)) != NULL
) {
914 int namelen
= strlen(de
->d_name
);
915 struct packed_git
*p
;
917 if (!has_extension(de
->d_name
, ".idx"))
920 if (len
+ namelen
+ 1 > sizeof(path
))
923 /* Don't reopen a pack we already have. */
924 strcpy(path
+ len
, de
->d_name
);
925 for (p
= packed_git
; p
; p
= p
->next
) {
926 if (!memcmp(path
, p
->pack_name
, len
+ namelen
- 4))
931 /* See if it really is a valid .idx file with corresponding
932 * .pack file that we can map.
934 p
= add_packed_git(path
, len
+ namelen
, local
);
937 install_packed_git(p
);
942 static int sort_pack(const void *a_
, const void *b_
)
944 struct packed_git
*a
= *((struct packed_git
**)a_
);
945 struct packed_git
*b
= *((struct packed_git
**)b_
);
949 * Local packs tend to contain objects specific to our
950 * variant of the project than remote ones. In addition,
951 * remote ones could be on a network mounted filesystem.
952 * Favor local ones for these reasons.
954 st
= a
->pack_local
- b
->pack_local
;
959 * Younger packs tend to contain more recent objects,
960 * and more recent objects tend to get accessed more
963 if (a
->mtime
< b
->mtime
)
965 else if (a
->mtime
== b
->mtime
)
970 static void rearrange_packed_git(void)
972 struct packed_git
**ary
, *p
;
975 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
980 /* prepare an array of packed_git for easier sorting */
981 ary
= xcalloc(n
, sizeof(struct packed_git
*));
982 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
985 qsort(ary
, n
, sizeof(struct packed_git
*), sort_pack
);
987 /* link them back again */
988 for (i
= 0; i
< n
- 1; i
++)
989 ary
[i
]->next
= ary
[i
+ 1];
990 ary
[n
- 1]->next
= NULL
;
996 static int prepare_packed_git_run_once
= 0;
997 void prepare_packed_git(void)
999 struct alternate_object_database
*alt
;
1001 if (prepare_packed_git_run_once
)
1003 prepare_packed_git_one(get_object_directory(), 1);
1005 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1007 prepare_packed_git_one(alt
->base
, 0);
1008 alt
->name
[-1] = '/';
1010 rearrange_packed_git();
1011 prepare_packed_git_run_once
= 1;
1014 void reprepare_packed_git(void)
1017 prepare_packed_git_run_once
= 0;
1018 prepare_packed_git();
1021 static void mark_bad_packed_object(struct packed_git
*p
,
1022 const unsigned char *sha1
)
1025 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1026 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1028 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
, 20 * (p
->num_bad_objects
+ 1));
1029 hashcpy(p
->bad_object_sha1
+ 20 * p
->num_bad_objects
, sha1
);
1030 p
->num_bad_objects
++;
1033 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1035 struct packed_git
*p
;
1038 for (p
= packed_git
; p
; p
= p
->next
)
1039 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1040 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1045 int check_sha1_signature(const unsigned char *sha1
, void *map
, unsigned long size
, const char *type
)
1047 unsigned char real_sha1
[20];
1048 hash_sha1_file(map
, size
, type
, real_sha1
);
1049 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1052 static int git_open_noatime(const char *name
, struct packed_git
*p
)
1054 static int sha1_file_open_flag
= O_NOATIME
;
1057 int fd
= open(name
, O_RDONLY
| sha1_file_open_flag
);
1061 /* Might the failure be insufficient file descriptors? */
1062 if (errno
== EMFILE
) {
1063 if (unuse_one_window(p
, -1))
1069 /* Might the failure be due to O_NOATIME? */
1070 if (errno
!= ENOENT
&& sha1_file_open_flag
) {
1071 sha1_file_open_flag
= 0;
1079 static int open_sha1_file(const unsigned char *sha1
)
1082 char *name
= sha1_file_name(sha1
);
1083 struct alternate_object_database
*alt
;
1085 fd
= git_open_noatime(name
, NULL
);
1091 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1093 fill_sha1_path(name
, sha1
);
1094 fd
= git_open_noatime(alt
->base
, NULL
);
1101 static void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1106 fd
= open_sha1_file(sha1
);
1111 if (!fstat(fd
, &st
)) {
1112 *size
= xsize_t(st
.st_size
);
1113 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1120 static int legacy_loose_object(unsigned char *map
)
1125 * Is it a zlib-compressed buffer? If so, the first byte
1126 * must be 0x78 (15-bit window size, deflated), and the
1127 * first 16-bit word is evenly divisible by 31
1129 word
= (map
[0] << 8) + map
[1];
1130 if (map
[0] == 0x78 && !(word
% 31))
1136 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1137 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1140 unsigned long size
, c
;
1141 unsigned long used
= 0;
1144 *type
= (c
>> 4) & 7;
1148 if (len
<= used
|| bitsizeof(long) <= shift
) {
1149 error("bad object header");
1153 size
+= (c
& 0x7f) << shift
;
1160 static int unpack_sha1_header(z_stream
*stream
, unsigned char *map
, unsigned long mapsize
, void *buffer
, unsigned long bufsiz
)
1162 unsigned long size
, used
;
1163 static const char valid_loose_object_type
[8] = {
1165 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1166 0, /* "delta" and others are invalid in a loose object */
1168 enum object_type type
;
1170 /* Get the data stream */
1171 memset(stream
, 0, sizeof(*stream
));
1172 stream
->next_in
= map
;
1173 stream
->avail_in
= mapsize
;
1174 stream
->next_out
= buffer
;
1175 stream
->avail_out
= bufsiz
;
1177 if (legacy_loose_object(map
)) {
1178 git_inflate_init(stream
);
1179 return git_inflate(stream
, 0);
1184 * There used to be a second loose object header format which
1185 * was meant to mimic the in-pack format, allowing for direct
1186 * copy of the object data. This format turned up not to be
1187 * really worth it and we don't write it any longer. But we
1188 * can still read it.
1190 used
= unpack_object_header_buffer(map
, mapsize
, &type
, &size
);
1191 if (!used
|| !valid_loose_object_type
[type
])
1196 /* Set up the stream for the rest.. */
1197 stream
->next_in
= map
;
1198 stream
->avail_in
= mapsize
;
1199 git_inflate_init(stream
);
1201 /* And generate the fake traditional header */
1202 stream
->total_out
= 1 + snprintf(buffer
, bufsiz
, "%s %lu",
1203 typename(type
), size
);
1207 static void *unpack_sha1_rest(z_stream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1209 int bytes
= strlen(buffer
) + 1;
1210 unsigned char *buf
= xmallocz(size
);
1214 n
= stream
->total_out
- bytes
;
1217 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1219 if (bytes
<= size
) {
1221 * The above condition must be (bytes <= size), not
1222 * (bytes < size). In other words, even though we
1223 * expect no more output and set avail_out to zer0,
1224 * the input zlib stream may have bytes that express
1225 * "this concludes the stream", and we *do* want to
1228 * Otherwise we would not be able to test that we
1229 * consumed all the input to reach the expected size;
1230 * we also want to check that zlib tells us that all
1231 * went well with status == Z_STREAM_END at the end.
1233 stream
->next_out
= buf
+ bytes
;
1234 stream
->avail_out
= size
- bytes
;
1235 while (status
== Z_OK
)
1236 status
= git_inflate(stream
, Z_FINISH
);
1238 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1239 git_inflate_end(stream
);
1244 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1245 else if (stream
->avail_in
)
1246 error("garbage at end of loose object '%s'",
1253 * We used to just use "sscanf()", but that's actually way
1254 * too permissive for what we want to check. So do an anal
1255 * object header parse by hand.
1257 static int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1264 * The type can be at most ten bytes (including the
1265 * terminating '\0' that we add), and is followed by
1274 if (i
>= sizeof(type
))
1280 * The length must follow immediately, and be in canonical
1281 * decimal format (ie "010" is not valid).
1283 size
= *hdr
++ - '0';
1288 unsigned long c
= *hdr
- '0';
1292 size
= size
* 10 + c
;
1298 * The length must be followed by a zero byte
1300 return *hdr
? -1 : type_from_string(type
);
1303 static void *unpack_sha1_file(void *map
, unsigned long mapsize
, enum object_type
*type
, unsigned long *size
, const unsigned char *sha1
)
1309 ret
= unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
));
1310 if (ret
< Z_OK
|| (*type
= parse_sha1_header(hdr
, size
)) < 0)
1313 return unpack_sha1_rest(&stream
, hdr
, *size
, sha1
);
1316 unsigned long get_size_from_delta(struct packed_git
*p
,
1317 struct pack_window
**w_curs
,
1320 const unsigned char *data
;
1321 unsigned char delta_head
[20], *in
;
1325 memset(&stream
, 0, sizeof(stream
));
1326 stream
.next_out
= delta_head
;
1327 stream
.avail_out
= sizeof(delta_head
);
1329 git_inflate_init(&stream
);
1331 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1332 stream
.next_in
= in
;
1333 st
= git_inflate(&stream
, Z_FINISH
);
1334 curpos
+= stream
.next_in
- in
;
1335 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
1336 stream
.total_out
< sizeof(delta_head
));
1337 git_inflate_end(&stream
);
1338 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
1339 error("delta data unpack-initial failed");
1343 /* Examine the initial part of the delta to figure out
1348 /* ignore base size */
1349 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1351 /* Read the result size */
1352 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1355 static off_t
get_delta_base(struct packed_git
*p
,
1356 struct pack_window
**w_curs
,
1358 enum object_type type
,
1359 off_t delta_obj_offset
)
1361 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
1364 /* use_pack() assured us we have [base_info, base_info + 20)
1365 * as a range that we can look at without walking off the
1366 * end of the mapped window. Its actually the hash size
1367 * that is assured. An OFS_DELTA longer than the hash size
1368 * is stupid, as then a REF_DELTA would be smaller to store.
1370 if (type
== OBJ_OFS_DELTA
) {
1372 unsigned char c
= base_info
[used
++];
1373 base_offset
= c
& 127;
1376 if (!base_offset
|| MSB(base_offset
, 7))
1377 return 0; /* overflow */
1378 c
= base_info
[used
++];
1379 base_offset
= (base_offset
<< 7) + (c
& 127);
1381 base_offset
= delta_obj_offset
- base_offset
;
1382 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
1383 return 0; /* out of bound */
1385 } else if (type
== OBJ_REF_DELTA
) {
1386 /* The base entry _must_ be in the same pack */
1387 base_offset
= find_pack_entry_one(base_info
, p
);
1390 die("I am totally screwed");
1394 /* forward declaration for a mutually recursive function */
1395 static int packed_object_info(struct packed_git
*p
, off_t offset
,
1396 unsigned long *sizep
);
1398 static int packed_delta_info(struct packed_git
*p
,
1399 struct pack_window
**w_curs
,
1401 enum object_type type
,
1403 unsigned long *sizep
)
1407 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
1410 type
= packed_object_info(p
, base_offset
, NULL
);
1411 if (type
<= OBJ_NONE
) {
1412 struct revindex_entry
*revidx
;
1413 const unsigned char *base_sha1
;
1414 revidx
= find_pack_revindex(p
, base_offset
);
1417 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1418 mark_bad_packed_object(p
, base_sha1
);
1419 type
= sha1_object_info(base_sha1
, NULL
);
1420 if (type
<= OBJ_NONE
)
1424 /* We choose to only get the type of the base object and
1425 * ignore potentially corrupt pack file that expects the delta
1426 * based on a base with a wrong size. This saves tons of
1430 *sizep
= get_size_from_delta(p
, w_curs
, curpos
);
1438 static int unpack_object_header(struct packed_git
*p
,
1439 struct pack_window
**w_curs
,
1441 unsigned long *sizep
)
1443 unsigned char *base
;
1446 enum object_type type
;
1448 /* use_pack() assures us we have [base, base + 20) available
1449 * as a range that we can look at at. (Its actually the hash
1450 * size that is assured.) With our object header encoding
1451 * the maximum deflated object size is 2^137, which is just
1452 * insane, so we know won't exceed what we have been given.
1454 base
= use_pack(p
, w_curs
, *curpos
, &left
);
1455 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
1464 const char *packed_object_info_detail(struct packed_git
*p
,
1466 unsigned long *size
,
1467 unsigned long *store_size
,
1468 unsigned int *delta_chain_length
,
1469 unsigned char *base_sha1
)
1471 struct pack_window
*w_curs
= NULL
;
1473 unsigned long dummy
;
1474 unsigned char *next_sha1
;
1475 enum object_type type
;
1476 struct revindex_entry
*revidx
;
1478 *delta_chain_length
= 0;
1479 curpos
= obj_offset
;
1480 type
= unpack_object_header(p
, &w_curs
, &curpos
, size
);
1482 revidx
= find_pack_revindex(p
, obj_offset
);
1483 *store_size
= revidx
[1].offset
- obj_offset
;
1488 die("pack %s contains unknown object type %d",
1489 p
->pack_name
, type
);
1494 unuse_pack(&w_curs
);
1495 return typename(type
);
1497 obj_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
1499 die("pack %s contains bad delta base reference of type %s",
1500 p
->pack_name
, typename(type
));
1501 if (*delta_chain_length
== 0) {
1502 revidx
= find_pack_revindex(p
, obj_offset
);
1503 hashcpy(base_sha1
, nth_packed_object_sha1(p
, revidx
->nr
));
1507 next_sha1
= use_pack(p
, &w_curs
, curpos
, NULL
);
1508 if (*delta_chain_length
== 0)
1509 hashcpy(base_sha1
, next_sha1
);
1510 obj_offset
= find_pack_entry_one(next_sha1
, p
);
1513 (*delta_chain_length
)++;
1514 curpos
= obj_offset
;
1515 type
= unpack_object_header(p
, &w_curs
, &curpos
, &dummy
);
1519 static int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
1520 unsigned long *sizep
)
1522 struct pack_window
*w_curs
= NULL
;
1524 off_t curpos
= obj_offset
;
1525 enum object_type type
;
1527 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
1532 type
= packed_delta_info(p
, &w_curs
, curpos
,
1533 type
, obj_offset
, sizep
);
1543 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1544 type
, (uintmax_t)obj_offset
, p
->pack_name
);
1547 unuse_pack(&w_curs
);
1551 static void *unpack_compressed_entry(struct packed_git
*p
,
1552 struct pack_window
**w_curs
,
1558 unsigned char *buffer
, *in
;
1560 buffer
= xmallocz(size
);
1561 memset(&stream
, 0, sizeof(stream
));
1562 stream
.next_out
= buffer
;
1563 stream
.avail_out
= size
+ 1;
1565 git_inflate_init(&stream
);
1567 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1568 stream
.next_in
= in
;
1569 st
= git_inflate(&stream
, Z_FINISH
);
1570 if (!stream
.avail_out
)
1571 break; /* the payload is larger than it should be */
1572 curpos
+= stream
.next_in
- in
;
1573 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
1574 git_inflate_end(&stream
);
1575 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
1583 #define MAX_DELTA_CACHE (256)
1585 static size_t delta_base_cached
;
1587 static struct delta_base_cache_lru_list
{
1588 struct delta_base_cache_lru_list
*prev
;
1589 struct delta_base_cache_lru_list
*next
;
1590 } delta_base_cache_lru
= { &delta_base_cache_lru
, &delta_base_cache_lru
};
1592 static struct delta_base_cache_entry
{
1593 struct delta_base_cache_lru_list lru
;
1595 struct packed_git
*p
;
1598 enum object_type type
;
1599 } delta_base_cache
[MAX_DELTA_CACHE
];
1601 static unsigned long pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
1605 hash
= (unsigned long)p
+ (unsigned long)base_offset
;
1606 hash
+= (hash
>> 8) + (hash
>> 16);
1607 return hash
% MAX_DELTA_CACHE
;
1610 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
1611 unsigned long *base_size
, enum object_type
*type
, int keep_cache
)
1614 unsigned long hash
= pack_entry_hash(p
, base_offset
);
1615 struct delta_base_cache_entry
*ent
= delta_base_cache
+ hash
;
1618 if (!ret
|| ent
->p
!= p
|| ent
->base_offset
!= base_offset
)
1619 return unpack_entry(p
, base_offset
, type
, base_size
);
1623 ent
->lru
.next
->prev
= ent
->lru
.prev
;
1624 ent
->lru
.prev
->next
= ent
->lru
.next
;
1625 delta_base_cached
-= ent
->size
;
1627 ret
= xmemdupz(ent
->data
, ent
->size
);
1630 *base_size
= ent
->size
;
1634 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
1639 ent
->lru
.next
->prev
= ent
->lru
.prev
;
1640 ent
->lru
.prev
->next
= ent
->lru
.next
;
1641 delta_base_cached
-= ent
->size
;
1645 void clear_delta_base_cache(void)
1648 for (p
= 0; p
< MAX_DELTA_CACHE
; p
++)
1649 release_delta_base_cache(&delta_base_cache
[p
]);
1652 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
1653 void *base
, unsigned long base_size
, enum object_type type
)
1655 unsigned long hash
= pack_entry_hash(p
, base_offset
);
1656 struct delta_base_cache_entry
*ent
= delta_base_cache
+ hash
;
1657 struct delta_base_cache_lru_list
*lru
;
1659 release_delta_base_cache(ent
);
1660 delta_base_cached
+= base_size
;
1662 for (lru
= delta_base_cache_lru
.next
;
1663 delta_base_cached
> delta_base_cache_limit
1664 && lru
!= &delta_base_cache_lru
;
1666 struct delta_base_cache_entry
*f
= (void *)lru
;
1667 if (f
->type
== OBJ_BLOB
)
1668 release_delta_base_cache(f
);
1670 for (lru
= delta_base_cache_lru
.next
;
1671 delta_base_cached
> delta_base_cache_limit
1672 && lru
!= &delta_base_cache_lru
;
1674 struct delta_base_cache_entry
*f
= (void *)lru
;
1675 release_delta_base_cache(f
);
1679 ent
->base_offset
= base_offset
;
1682 ent
->size
= base_size
;
1683 ent
->lru
.next
= &delta_base_cache_lru
;
1684 ent
->lru
.prev
= delta_base_cache_lru
.prev
;
1685 delta_base_cache_lru
.prev
->next
= &ent
->lru
;
1686 delta_base_cache_lru
.prev
= &ent
->lru
;
1689 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
1690 unsigned long *size
);
1692 static void *unpack_delta_entry(struct packed_git
*p
,
1693 struct pack_window
**w_curs
,
1695 unsigned long delta_size
,
1697 enum object_type
*type
,
1698 unsigned long *sizep
)
1700 void *delta_data
, *result
, *base
;
1701 unsigned long base_size
;
1704 base_offset
= get_delta_base(p
, w_curs
, &curpos
, *type
, obj_offset
);
1706 error("failed to validate delta base reference "
1707 "at offset %"PRIuMAX
" from %s",
1708 (uintmax_t)curpos
, p
->pack_name
);
1712 base
= cache_or_unpack_entry(p
, base_offset
, &base_size
, type
, 0);
1715 * We're probably in deep shit, but let's try to fetch
1716 * the required base anyway from another pack or loose.
1717 * This is costly but should happen only in the presence
1718 * of a corrupted pack, and is better than failing outright.
1720 struct revindex_entry
*revidx
;
1721 const unsigned char *base_sha1
;
1722 revidx
= find_pack_revindex(p
, base_offset
);
1725 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1726 error("failed to read delta base object %s"
1727 " at offset %"PRIuMAX
" from %s",
1728 sha1_to_hex(base_sha1
), (uintmax_t)base_offset
,
1730 mark_bad_packed_object(p
, base_sha1
);
1731 base
= read_object(base_sha1
, type
, &base_size
);
1736 delta_data
= unpack_compressed_entry(p
, w_curs
, curpos
, delta_size
);
1738 error("failed to unpack compressed delta "
1739 "at offset %"PRIuMAX
" from %s",
1740 (uintmax_t)curpos
, p
->pack_name
);
1744 result
= patch_delta(base
, base_size
,
1745 delta_data
, delta_size
,
1748 die("failed to apply delta");
1750 add_delta_base_cache(p
, base_offset
, base
, base_size
, *type
);
1754 int do_check_packed_object_crc
;
1756 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
1757 enum object_type
*type
, unsigned long *sizep
)
1759 struct pack_window
*w_curs
= NULL
;
1760 off_t curpos
= obj_offset
;
1763 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
1764 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
1765 unsigned long len
= revidx
[1].offset
- obj_offset
;
1766 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
1767 const unsigned char *sha1
=
1768 nth_packed_object_sha1(p
, revidx
->nr
);
1769 error("bad packed object CRC for %s",
1771 mark_bad_packed_object(p
, sha1
);
1772 unuse_pack(&w_curs
);
1777 *type
= unpack_object_header(p
, &w_curs
, &curpos
, sizep
);
1781 data
= unpack_delta_entry(p
, &w_curs
, curpos
, *sizep
,
1782 obj_offset
, type
, sizep
);
1788 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, *sizep
);
1792 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1793 *type
, (uintmax_t)obj_offset
, p
->pack_name
);
1795 unuse_pack(&w_curs
);
1799 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
1802 const unsigned char *index
= p
->index_data
;
1804 if (open_pack_index(p
))
1806 index
= p
->index_data
;
1808 if (n
>= p
->num_objects
)
1811 if (p
->index_version
== 1) {
1812 return index
+ 24 * n
+ 4;
1815 return index
+ 20 * n
;
1819 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
1821 const unsigned char *index
= p
->index_data
;
1823 if (p
->index_version
== 1) {
1824 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
1827 index
+= 8 + p
->num_objects
* (20 + 4);
1828 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
1829 if (!(off
& 0x80000000))
1831 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
1832 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
1833 ntohl(*((uint32_t *)(index
+ 4)));
1837 off_t
find_pack_entry_one(const unsigned char *sha1
,
1838 struct packed_git
*p
)
1840 const uint32_t *level1_ofs
= p
->index_data
;
1841 const unsigned char *index
= p
->index_data
;
1842 unsigned hi
, lo
, stride
;
1843 static int use_lookup
= -1;
1844 static int debug_lookup
= -1;
1846 if (debug_lookup
< 0)
1847 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
1850 if (open_pack_index(p
))
1852 level1_ofs
= p
->index_data
;
1853 index
= p
->index_data
;
1855 if (p
->index_version
> 1) {
1860 hi
= ntohl(level1_ofs
[*sha1
]);
1861 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
1862 if (p
->index_version
> 1) {
1870 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
1871 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
1874 use_lookup
= !!getenv("GIT_USE_LOOKUP");
1876 int pos
= sha1_entry_pos(index
, stride
, 0,
1877 lo
, hi
, p
->num_objects
, sha1
);
1880 return nth_packed_object_offset(p
, pos
);
1884 unsigned mi
= (lo
+ hi
) / 2;
1885 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
1888 printf("lo %u hi %u rg %u mi %u\n",
1889 lo
, hi
, hi
- lo
, mi
);
1891 return nth_packed_object_offset(p
, mi
);
1900 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
1902 static struct packed_git
*last_found
= (void *)1;
1903 struct packed_git
*p
;
1906 prepare_packed_git();
1909 p
= (last_found
== (void *)1) ? packed_git
: last_found
;
1912 if (p
->num_bad_objects
) {
1914 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1915 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1919 offset
= find_pack_entry_one(sha1
, p
);
1922 * We are about to tell the caller where they can
1923 * locate the requested object. We better make
1924 * sure the packfile is still here and can be
1925 * accessed before supplying that answer, as
1926 * it may have been deleted since the index
1929 if (p
->pack_fd
== -1 && open_packed_git(p
)) {
1930 error("packfile %s cannot be accessed", p
->pack_name
);
1935 hashcpy(e
->sha1
, sha1
);
1941 if (p
== last_found
)
1945 if (p
== last_found
)
1951 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
1952 struct packed_git
*packs
)
1954 struct packed_git
*p
;
1956 for (p
= packs
; p
; p
= p
->next
) {
1957 if (find_pack_entry_one(sha1
, p
))
1964 static int sha1_loose_object_info(const unsigned char *sha1
, unsigned long *sizep
)
1967 unsigned long mapsize
, size
;
1972 map
= map_sha1_file(sha1
, &mapsize
);
1974 return error("unable to find %s", sha1_to_hex(sha1
));
1975 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
1976 status
= error("unable to unpack %s header",
1978 else if ((status
= parse_sha1_header(hdr
, &size
)) < 0)
1979 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
1982 git_inflate_end(&stream
);
1983 munmap(map
, mapsize
);
1987 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
1989 struct pack_entry e
;
1992 if (!find_pack_entry(sha1
, &e
)) {
1993 /* Most likely it's a loose object. */
1994 status
= sha1_loose_object_info(sha1
, sizep
);
1998 /* Not a loose object; someone else may have just packed it. */
1999 reprepare_packed_git();
2000 if (!find_pack_entry(sha1
, &e
))
2004 status
= packed_object_info(e
.p
, e
.offset
, sizep
);
2006 mark_bad_packed_object(e
.p
, sha1
);
2007 status
= sha1_object_info(sha1
, sizep
);
2013 static void *read_packed_sha1(const unsigned char *sha1
,
2014 enum object_type
*type
, unsigned long *size
)
2016 struct pack_entry e
;
2019 if (!find_pack_entry(sha1
, &e
))
2021 data
= cache_or_unpack_entry(e
.p
, e
.offset
, size
, type
, 1);
2024 * We're probably in deep shit, but let's try to fetch
2025 * the required object anyway from another pack or loose.
2026 * This should happen only in the presence of a corrupted
2027 * pack, and is better than failing outright.
2029 error("failed to read object %s at offset %"PRIuMAX
" from %s",
2030 sha1_to_hex(sha1
), (uintmax_t)e
.offset
, e
.p
->pack_name
);
2031 mark_bad_packed_object(e
.p
, sha1
);
2032 data
= read_object(sha1
, type
, size
);
2038 * This is meant to hold a *small* number of objects that you would
2039 * want read_sha1_file() to be able to return, but yet you do not want
2040 * to write them into the object store (e.g. a browse-only
2043 static struct cached_object
{
2044 unsigned char sha1
[20];
2045 enum object_type type
;
2049 static int cached_object_nr
, cached_object_alloc
;
2051 static struct cached_object empty_tree
= {
2052 EMPTY_TREE_SHA1_BIN
,
2058 static struct cached_object
*find_cached_object(const unsigned char *sha1
)
2061 struct cached_object
*co
= cached_objects
;
2063 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
2064 if (!hashcmp(co
->sha1
, sha1
))
2067 if (!hashcmp(sha1
, empty_tree
.sha1
))
2072 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
2073 unsigned char *sha1
)
2075 struct cached_object
*co
;
2077 hash_sha1_file(buf
, len
, typename(type
), sha1
);
2078 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
2080 if (cached_object_alloc
<= cached_object_nr
) {
2081 cached_object_alloc
= alloc_nr(cached_object_alloc
);
2082 cached_objects
= xrealloc(cached_objects
,
2083 sizeof(*cached_objects
) *
2084 cached_object_alloc
);
2086 co
= &cached_objects
[cached_object_nr
++];
2089 co
->buf
= xmalloc(len
);
2090 memcpy(co
->buf
, buf
, len
);
2091 hashcpy(co
->sha1
, sha1
);
2095 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2096 unsigned long *size
)
2098 unsigned long mapsize
;
2100 struct cached_object
*co
;
2102 co
= find_cached_object(sha1
);
2106 return xmemdupz(co
->buf
, co
->size
);
2109 buf
= read_packed_sha1(sha1
, type
, size
);
2112 map
= map_sha1_file(sha1
, &mapsize
);
2114 buf
= unpack_sha1_file(map
, mapsize
, type
, size
, sha1
);
2115 munmap(map
, mapsize
);
2118 reprepare_packed_git();
2119 return read_packed_sha1(sha1
, type
, size
);
2123 * This function dies on corrupt objects; the callers who want to
2124 * deal with them should arrange to call read_object() and give error
2125 * messages themselves.
2127 void *read_sha1_file_repl(const unsigned char *sha1
,
2128 enum object_type
*type
,
2129 unsigned long *size
,
2130 const unsigned char **replacement
)
2132 const unsigned char *repl
= lookup_replace_object(sha1
);
2135 const struct packed_git
*p
;
2138 data
= read_object(repl
, type
, size
);
2141 *replacement
= repl
;
2145 if (errno
&& errno
!= ENOENT
)
2146 die_errno("failed to read object %s", sha1_to_hex(sha1
));
2148 /* die if we replaced an object with one that does not exist */
2150 die("replacement %s not found for %s",
2151 sha1_to_hex(repl
), sha1_to_hex(sha1
));
2153 if (has_loose_object(repl
)) {
2154 path
= sha1_file_name(sha1
);
2155 die("loose object %s (stored in %s) is corrupt",
2156 sha1_to_hex(repl
), path
);
2159 if ((p
= has_packed_and_bad(repl
)) != NULL
)
2160 die("packed object %s (stored in %s) is corrupt",
2161 sha1_to_hex(repl
), p
->pack_name
);
2166 void *read_object_with_reference(const unsigned char *sha1
,
2167 const char *required_type_name
,
2168 unsigned long *size
,
2169 unsigned char *actual_sha1_return
)
2171 enum object_type type
, required_type
;
2173 unsigned long isize
;
2174 unsigned char actual_sha1
[20];
2176 required_type
= type_from_string(required_type_name
);
2177 hashcpy(actual_sha1
, sha1
);
2179 int ref_length
= -1;
2180 const char *ref_type
= NULL
;
2182 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
2185 if (type
== required_type
) {
2187 if (actual_sha1_return
)
2188 hashcpy(actual_sha1_return
, actual_sha1
);
2191 /* Handle references */
2192 else if (type
== OBJ_COMMIT
)
2194 else if (type
== OBJ_TAG
)
2195 ref_type
= "object ";
2200 ref_length
= strlen(ref_type
);
2202 if (ref_length
+ 40 > isize
||
2203 memcmp(buffer
, ref_type
, ref_length
) ||
2204 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
2209 /* Now we have the ID of the referred-to object in
2210 * actual_sha1. Check again. */
2214 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
2215 const char *type
, unsigned char *sha1
,
2216 char *hdr
, int *hdrlen
)
2220 /* Generate the header */
2221 *hdrlen
= sprintf(hdr
, "%s %lu", type
, len
)+1;
2225 git_SHA1_Update(&c
, hdr
, *hdrlen
);
2226 git_SHA1_Update(&c
, buf
, len
);
2227 git_SHA1_Final(sha1
, &c
);
2231 * Move the just written object into its final resting place.
2232 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2233 * "moving" is only a part of what it does, when no patch between
2234 * master to pu changes the call sites of this function.
2236 int move_temp_to_file(const char *tmpfile
, const char *filename
)
2240 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
2242 else if (link(tmpfile
, filename
))
2246 * Coda hack - coda doesn't like cross-directory links,
2247 * so we fall back to a rename, which will mean that it
2248 * won't be able to check collisions, but that's not a
2251 * The same holds for FAT formatted media.
2253 * When this succeeds, we just return. We have nothing
2256 if (ret
&& ret
!= EEXIST
) {
2258 if (!rename(tmpfile
, filename
))
2262 unlink_or_warn(tmpfile
);
2264 if (ret
!= EEXIST
) {
2265 return error("unable to write sha1 filename %s: %s\n", filename
, strerror(ret
));
2267 /* FIXME!!! Collision check here ? */
2271 if (adjust_shared_perm(filename
))
2272 return error("unable to set permission to '%s'", filename
);
2276 static int write_buffer(int fd
, const void *buf
, size_t len
)
2278 if (write_in_full(fd
, buf
, len
) < 0)
2279 return error("file write error (%s)", strerror(errno
));
2283 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
2284 unsigned char *sha1
)
2288 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2292 /* Finalize a file on disk, and close it. */
2293 static void close_sha1_file(int fd
)
2295 if (fsync_object_files
)
2296 fsync_or_die(fd
, "sha1 file");
2298 die_errno("error when closing sha1 file");
2301 /* Size of directory component, including the ending '/' */
2302 static inline int directory_size(const char *filename
)
2304 const char *s
= strrchr(filename
, '/');
2307 return s
- filename
+ 1;
2311 * This creates a temporary file in the same directory as the final
2314 * We want to avoid cross-directory filename renames, because those
2315 * can have problems on various filesystems (FAT, NFS, Coda).
2317 static int create_tmpfile(char *buffer
, size_t bufsiz
, const char *filename
)
2319 int fd
, dirlen
= directory_size(filename
);
2321 if (dirlen
+ 20 > bufsiz
) {
2322 errno
= ENAMETOOLONG
;
2325 memcpy(buffer
, filename
, dirlen
);
2326 strcpy(buffer
+ dirlen
, "tmp_obj_XXXXXX");
2327 fd
= git_mkstemp_mode(buffer
, 0444);
2328 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
2329 /* Make sure the directory exists */
2330 memcpy(buffer
, filename
, dirlen
);
2331 buffer
[dirlen
-1] = 0;
2332 if (mkdir(buffer
, 0777) || adjust_shared_perm(buffer
))
2336 strcpy(buffer
+ dirlen
- 1, "/tmp_obj_XXXXXX");
2337 fd
= git_mkstemp_mode(buffer
, 0444);
2342 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
2343 const void *buf
, unsigned long len
, time_t mtime
)
2346 unsigned char compressed
[4096];
2349 unsigned char parano_sha1
[20];
2351 static char tmpfile
[PATH_MAX
];
2353 filename
= sha1_file_name(sha1
);
2354 fd
= create_tmpfile(tmpfile
, sizeof(tmpfile
), filename
);
2355 while (fd
< 0 && errno
== EMFILE
&& unuse_one_window(NULL
, -1))
2356 fd
= create_tmpfile(tmpfile
, sizeof(tmpfile
), filename
);
2358 if (errno
== EACCES
)
2359 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2361 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile
, strerror(errno
));
2365 memset(&stream
, 0, sizeof(stream
));
2366 deflateInit(&stream
, zlib_compression_level
);
2367 stream
.next_out
= compressed
;
2368 stream
.avail_out
= sizeof(compressed
);
2371 /* First header.. */
2372 stream
.next_in
= (unsigned char *)hdr
;
2373 stream
.avail_in
= hdrlen
;
2374 while (deflate(&stream
, 0) == Z_OK
)
2376 git_SHA1_Update(&c
, hdr
, hdrlen
);
2378 /* Then the data itself.. */
2379 stream
.next_in
= (void *)buf
;
2380 stream
.avail_in
= len
;
2382 unsigned char *in0
= stream
.next_in
;
2383 ret
= deflate(&stream
, Z_FINISH
);
2384 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
2385 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
2386 die("unable to write sha1 file");
2387 stream
.next_out
= compressed
;
2388 stream
.avail_out
= sizeof(compressed
);
2389 } while (ret
== Z_OK
);
2391 if (ret
!= Z_STREAM_END
)
2392 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
2393 ret
= deflateEnd(&stream
);
2395 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
2396 git_SHA1_Final(parano_sha1
, &c
);
2397 if (hashcmp(sha1
, parano_sha1
) != 0)
2398 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
2400 close_sha1_file(fd
);
2405 utb
.modtime
= mtime
;
2406 if (utime(tmpfile
, &utb
) < 0)
2407 warning("failed utime() on %s: %s",
2408 tmpfile
, strerror(errno
));
2411 return move_temp_to_file(tmpfile
, filename
);
2414 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *returnsha1
)
2416 unsigned char sha1
[20];
2420 /* Normally if we have it in the pack then we do not bother writing
2421 * it out into .git/objects/??/?{38} file.
2423 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2425 hashcpy(returnsha1
, sha1
);
2426 if (has_sha1_file(sha1
))
2428 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
2431 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
2435 enum object_type type
;
2440 if (has_loose_object(sha1
))
2442 buf
= read_packed_sha1(sha1
, &type
, &len
);
2444 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
2445 hdrlen
= sprintf(hdr
, "%s %lu", typename(type
), len
) + 1;
2446 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
2452 int has_pack_index(const unsigned char *sha1
)
2455 if (stat(sha1_pack_index_name(sha1
), &st
))
2460 int has_sha1_pack(const unsigned char *sha1
)
2462 struct pack_entry e
;
2463 return find_pack_entry(sha1
, &e
);
2466 int has_sha1_file(const unsigned char *sha1
)
2468 struct pack_entry e
;
2470 if (find_pack_entry(sha1
, &e
))
2472 return has_loose_object(sha1
);
2475 static void check_tree(const void *buf
, size_t size
)
2477 struct tree_desc desc
;
2478 struct name_entry entry
;
2480 init_tree_desc(&desc
, buf
, size
);
2481 while (tree_entry(&desc
, &entry
))
2483 * tree_entry() will die() on malformed entries */
2487 static void check_commit(const void *buf
, size_t size
)
2490 memset(&c
, 0, sizeof(c
));
2491 if (parse_commit_buffer(&c
, buf
, size
))
2492 die("corrupt commit");
2495 static void check_tag(const void *buf
, size_t size
)
2498 memset(&t
, 0, sizeof(t
));
2499 if (parse_tag_buffer(&t
, buf
, size
))
2503 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
2504 int write_object
, enum object_type type
,
2505 const char *path
, int format_check
)
2507 int ret
, re_allocated
= 0;
2513 * Convert blobs to git internal format
2515 if ((type
== OBJ_BLOB
) && path
) {
2516 struct strbuf nbuf
= STRBUF_INIT
;
2517 if (convert_to_git(path
, buf
, size
, &nbuf
,
2518 write_object
? safe_crlf
: 0)) {
2519 buf
= strbuf_detach(&nbuf
, &size
);
2524 if (type
== OBJ_TREE
)
2525 check_tree(buf
, size
);
2526 if (type
== OBJ_COMMIT
)
2527 check_commit(buf
, size
);
2528 if (type
== OBJ_TAG
)
2529 check_tag(buf
, size
);
2533 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
2535 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
2541 #define SMALL_FILE_SIZE (32*1024)
2543 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
, int write_object
,
2544 enum object_type type
, const char *path
, int format_check
)
2547 size_t size
= xsize_t(st
->st_size
);
2549 if (!S_ISREG(st
->st_mode
)) {
2550 struct strbuf sbuf
= STRBUF_INIT
;
2551 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
2552 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, write_object
,
2553 type
, path
, format_check
);
2556 strbuf_release(&sbuf
);
2558 ret
= index_mem(sha1
, NULL
, size
, write_object
, type
, path
,
2560 } else if (size
<= SMALL_FILE_SIZE
) {
2561 char *buf
= xmalloc(size
);
2562 if (size
== read_in_full(fd
, buf
, size
))
2563 ret
= index_mem(sha1
, buf
, size
, write_object
, type
,
2564 path
, format_check
);
2566 ret
= error("short read %s", strerror(errno
));
2569 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
2570 ret
= index_mem(sha1
, buf
, size
, write_object
, type
, path
,
2578 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, int write_object
)
2581 struct strbuf sb
= STRBUF_INIT
;
2583 switch (st
->st_mode
& S_IFMT
) {
2585 fd
= open(path
, O_RDONLY
);
2587 return error("open(\"%s\"): %s", path
,
2589 if (index_fd(sha1
, fd
, st
, write_object
, OBJ_BLOB
, path
, 0) < 0)
2590 return error("%s: failed to insert into database",
2594 if (strbuf_readlink(&sb
, path
, st
->st_size
)) {
2595 char *errstr
= strerror(errno
);
2596 return error("readlink(\"%s\"): %s", path
,
2600 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
2601 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
2602 return error("%s: failed to insert into database",
2604 strbuf_release(&sb
);
2607 return resolve_gitlink_ref(path
, "HEAD", sha1
);
2609 return error("%s: unsupported file type", path
);
2614 int read_pack_header(int fd
, struct pack_header
*header
)
2616 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
2617 /* "eof before pack header was fully read" */
2618 return PH_ERROR_EOF
;
2620 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
2621 /* "protocol error (pack signature mismatch detected)" */
2622 return PH_ERROR_PACK_SIGNATURE
;
2623 if (!pack_version_ok(header
->hdr_version
))
2624 /* "protocol error (pack version unsupported)" */
2625 return PH_ERROR_PROTOCOL
;
2629 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
2631 enum object_type type
= sha1_object_info(sha1
, NULL
);
2633 die("%s is not a valid object", sha1_to_hex(sha1
));
2635 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),