2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
11 #include "string-list.h"
17 #include "run-command.h"
20 #include "tree-walk.h"
22 #include "pack-revindex.h"
23 #include "sha1-lookup.h"
24 #include "bulk-checkin.h"
25 #include "streaming.h"
29 #include "mergesort.h"
33 const unsigned char null_sha1
[20];
34 const struct object_id null_oid
;
35 const struct object_id empty_tree_oid
= {
36 EMPTY_TREE_SHA1_BIN_LITERAL
38 const struct object_id empty_blob_oid
= {
39 EMPTY_BLOB_SHA1_BIN_LITERAL
43 * This is meant to hold a *small* number of objects that you would
44 * want read_sha1_file() to be able to return, but yet you do not want
45 * to write them into the object store (e.g. a browse-only
48 static struct cached_object
{
49 unsigned char sha1
[20];
50 enum object_type type
;
54 static int cached_object_nr
, cached_object_alloc
;
56 static struct cached_object empty_tree
= {
57 EMPTY_TREE_SHA1_BIN_LITERAL
,
63 static struct cached_object
*find_cached_object(const unsigned char *sha1
)
66 struct cached_object
*co
= cached_objects
;
68 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
69 if (!hashcmp(co
->sha1
, sha1
))
72 if (!hashcmp(sha1
, empty_tree
.sha1
))
77 int mkdir_in_gitdir(const char *path
)
79 if (mkdir(path
, 0777)) {
80 int saved_errno
= errno
;
82 struct strbuf sb
= STRBUF_INIT
;
87 * Are we looking at a path in a symlinked worktree
88 * whose original repository does not yet have it?
89 * e.g. .git/rr-cache pointing at its original
90 * repository in which the user hasn't performed any
91 * conflict resolution yet?
93 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
94 strbuf_readlink(&sb
, path
, st
.st_size
) ||
95 !is_absolute_path(sb
.buf
) ||
96 mkdir(sb
.buf
, 0777)) {
103 return adjust_shared_perm(path
);
106 enum scld_error
safe_create_leading_directories(char *path
)
108 char *next_component
= path
+ offset_1st_component(path
);
109 enum scld_error ret
= SCLD_OK
;
111 while (ret
== SCLD_OK
&& next_component
) {
113 char *slash
= next_component
, slash_character
;
115 while (*slash
&& !is_dir_sep(*slash
))
121 next_component
= slash
+ 1;
122 while (is_dir_sep(*next_component
))
124 if (!*next_component
)
127 slash_character
= *slash
;
129 if (!stat(path
, &st
)) {
131 if (!S_ISDIR(st
.st_mode
)) {
135 } else if (mkdir(path
, 0777)) {
136 if (errno
== EEXIST
&&
137 !stat(path
, &st
) && S_ISDIR(st
.st_mode
))
138 ; /* somebody created it since we checked */
139 else if (errno
== ENOENT
)
141 * Either mkdir() failed because
142 * somebody just pruned the containing
143 * directory, or stat() failed because
144 * the file that was in our way was
145 * just removed. Either way, inform
146 * the caller that it might be worth
152 } else if (adjust_shared_perm(path
)) {
155 *slash
= slash_character
;
160 enum scld_error
safe_create_leading_directories_const(const char *path
)
163 /* path points to cache entries, so xstrdup before messing with it */
164 char *buf
= xstrdup(path
);
165 enum scld_error result
= safe_create_leading_directories(buf
);
173 int raceproof_create_file(const char *path
, create_file_fn fn
, void *cb
)
176 * The number of times we will try to remove empty directories
177 * in the way of path. This is only 1 because if another
178 * process is racily creating directories that conflict with
179 * us, we don't want to fight against them.
181 int remove_directories_remaining
= 1;
184 * The number of times that we will try to create the
185 * directories containing path. We are willing to attempt this
186 * more than once, because another process could be trying to
187 * clean up empty directories at the same time as we are
188 * trying to create them.
190 int create_directories_remaining
= 3;
192 /* A scratch copy of path, filled lazily if we need it: */
193 struct strbuf path_copy
= STRBUF_INIT
;
206 if (errno
== EISDIR
&& remove_directories_remaining
-- > 0) {
208 * A directory is in the way. Maybe it is empty; try
212 strbuf_addstr(&path_copy
, path
);
214 if (!remove_dir_recursively(&path_copy
, REMOVE_DIR_EMPTY_ONLY
))
216 } else if (errno
== ENOENT
&& create_directories_remaining
-- > 0) {
218 * Maybe the containing directory didn't exist, or
219 * maybe it was just deleted by a process that is
220 * racing with us to clean up empty directories. Try
223 enum scld_error scld_result
;
226 strbuf_addstr(&path_copy
, path
);
229 scld_result
= safe_create_leading_directories(path_copy
.buf
);
230 if (scld_result
== SCLD_OK
)
232 } while (scld_result
== SCLD_VANISHED
&& create_directories_remaining
-- > 0);
236 strbuf_release(&path_copy
);
241 static void fill_sha1_path(struct strbuf
*buf
, const unsigned char *sha1
)
244 for (i
= 0; i
< 20; i
++) {
245 static char hex
[] = "0123456789abcdef";
246 unsigned int val
= sha1
[i
];
247 strbuf_addch(buf
, hex
[val
>> 4]);
248 strbuf_addch(buf
, hex
[val
& 0xf]);
250 strbuf_addch(buf
, '/');
254 const char *sha1_file_name(const unsigned char *sha1
)
256 static struct strbuf buf
= STRBUF_INIT
;
259 strbuf_addf(&buf
, "%s/", get_object_directory());
261 fill_sha1_path(&buf
, sha1
);
265 struct strbuf
*alt_scratch_buf(struct alternate_object_database
*alt
)
267 strbuf_setlen(&alt
->scratch
, alt
->base_len
);
268 return &alt
->scratch
;
271 static const char *alt_sha1_path(struct alternate_object_database
*alt
,
272 const unsigned char *sha1
)
274 struct strbuf
*buf
= alt_scratch_buf(alt
);
275 fill_sha1_path(buf
, sha1
);
279 struct alternate_object_database
*alt_odb_list
;
280 static struct alternate_object_database
**alt_odb_tail
;
283 * Return non-zero iff the path is usable as an alternate object database.
285 static int alt_odb_usable(struct strbuf
*path
, const char *normalized_objdir
)
287 struct alternate_object_database
*alt
;
289 /* Detect cases where alternate disappeared */
290 if (!is_directory(path
->buf
)) {
291 error("object directory %s does not exist; "
292 "check .git/objects/info/alternates.",
298 * Prevent the common mistake of listing the same
299 * thing twice, or object directory itself.
301 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
302 if (!fspathcmp(path
->buf
, alt
->path
))
305 if (!fspathcmp(path
->buf
, normalized_objdir
))
312 * Prepare alternate object database registry.
314 * The variable alt_odb_list points at the list of struct
315 * alternate_object_database. The elements on this list come from
316 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
317 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
318 * whose contents is similar to that environment variable but can be
319 * LF separated. Its base points at a statically allocated buffer that
320 * contains "/the/directory/corresponding/to/.git/objects/...", while
321 * its name points just after the slash at the end of ".git/objects/"
322 * in the example above, and has enough space to hold 40-byte hex
323 * SHA1, an extra slash for the first level indirection, and the
326 static void read_info_alternates(const char * relative_base
, int depth
);
327 static int link_alt_odb_entry(const char *entry
, const char *relative_base
,
328 int depth
, const char *normalized_objdir
)
330 struct alternate_object_database
*ent
;
331 struct strbuf pathbuf
= STRBUF_INIT
;
333 if (!is_absolute_path(entry
) && relative_base
) {
334 strbuf_realpath(&pathbuf
, relative_base
, 1);
335 strbuf_addch(&pathbuf
, '/');
337 strbuf_addstr(&pathbuf
, entry
);
339 if (strbuf_normalize_path(&pathbuf
) < 0 && relative_base
) {
340 error("unable to normalize alternate object path: %s",
342 strbuf_release(&pathbuf
);
347 * The trailing slash after the directory name is given by
348 * this function at the end. Remove duplicates.
350 while (pathbuf
.len
&& pathbuf
.buf
[pathbuf
.len
- 1] == '/')
351 strbuf_setlen(&pathbuf
, pathbuf
.len
- 1);
353 if (!alt_odb_usable(&pathbuf
, normalized_objdir
)) {
354 strbuf_release(&pathbuf
);
358 ent
= alloc_alt_odb(pathbuf
.buf
);
360 /* add the alternate entry */
362 alt_odb_tail
= &(ent
->next
);
365 /* recursively add alternates */
366 read_info_alternates(pathbuf
.buf
, depth
+ 1);
368 strbuf_release(&pathbuf
);
372 static const char *parse_alt_odb_entry(const char *string
,
380 if (*string
== '#') {
381 /* comment; consume up to next separator */
382 end
= strchrnul(string
, sep
);
383 } else if (*string
== '"' && !unquote_c_style(out
, string
, &end
)) {
385 * quoted path; unquote_c_style has copied the
386 * data for us and set "end". Broken quoting (e.g.,
387 * an entry that doesn't end with a quote) falls
388 * back to the unquoted case below.
391 /* normal, unquoted path */
392 end
= strchrnul(string
, sep
);
393 strbuf_add(out
, string
, end
- string
);
401 static void link_alt_odb_entries(const char *alt
, int len
, int sep
,
402 const char *relative_base
, int depth
)
404 struct strbuf objdirbuf
= STRBUF_INIT
;
405 struct strbuf entry
= STRBUF_INIT
;
408 error("%s: ignoring alternate object stores, nesting too deep.",
413 strbuf_add_absolute_path(&objdirbuf
, get_object_directory());
414 if (strbuf_normalize_path(&objdirbuf
) < 0)
415 die("unable to normalize object directory: %s",
419 alt
= parse_alt_odb_entry(alt
, sep
, &entry
);
422 link_alt_odb_entry(entry
.buf
, relative_base
, depth
, objdirbuf
.buf
);
424 strbuf_release(&entry
);
425 strbuf_release(&objdirbuf
);
428 static void read_info_alternates(const char * relative_base
, int depth
)
436 path
= xstrfmt("%s/info/alternates", relative_base
);
441 if (fstat(fd
, &st
) || (st
.st_size
== 0)) {
445 mapsz
= xsize_t(st
.st_size
);
446 map
= xmmap(NULL
, mapsz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
449 link_alt_odb_entries(map
, mapsz
, '\n', relative_base
, depth
);
454 struct alternate_object_database
*alloc_alt_odb(const char *dir
)
456 struct alternate_object_database
*ent
;
458 FLEX_ALLOC_STR(ent
, path
, dir
);
459 strbuf_init(&ent
->scratch
, 0);
460 strbuf_addf(&ent
->scratch
, "%s/", dir
);
461 ent
->base_len
= ent
->scratch
.len
;
466 void add_to_alternates_file(const char *reference
)
468 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
469 char *alts
= git_pathdup("objects/info/alternates");
472 hold_lock_file_for_update(lock
, alts
, LOCK_DIE_ON_ERROR
);
473 out
= fdopen_lock_file(lock
, "w");
475 die_errno("unable to fdopen alternates lockfile");
477 in
= fopen(alts
, "r");
479 struct strbuf line
= STRBUF_INIT
;
482 while (strbuf_getline(&line
, in
) != EOF
) {
483 if (!strcmp(reference
, line
.buf
)) {
487 fprintf_or_die(out
, "%s\n", line
.buf
);
490 strbuf_release(&line
);
494 rollback_lock_file(lock
);
498 else if (errno
!= ENOENT
)
499 die_errno("unable to read alternates file");
502 fprintf_or_die(out
, "%s\n", reference
);
503 if (commit_lock_file(lock
))
504 die_errno("unable to move new alternates file into place");
506 link_alt_odb_entries(reference
, strlen(reference
), '\n', NULL
, 0);
511 void add_to_alternates_memory(const char *reference
)
514 * Make sure alternates are initialized, or else our entry may be
515 * overwritten when they are.
519 link_alt_odb_entries(reference
, strlen(reference
), '\n', NULL
, 0);
523 * Compute the exact path an alternate is at and returns it. In case of
524 * error NULL is returned and the human readable error is added to `err`
525 * `path` may be relative and should point to $GITDIR.
526 * `err` must not be null.
528 char *compute_alternate_path(const char *path
, struct strbuf
*err
)
530 char *ref_git
= NULL
;
531 const char *repo
, *ref_git_s
;
534 ref_git_s
= real_path_if_valid(path
);
537 strbuf_addf(err
, _("path '%s' does not exist"), path
);
541 * Beware: read_gitfile(), real_path() and mkpath()
542 * return static buffer
544 ref_git
= xstrdup(ref_git_s
);
546 repo
= read_gitfile(ref_git
);
548 repo
= read_gitfile(mkpath("%s/.git", ref_git
));
551 ref_git
= xstrdup(repo
);
554 if (!repo
&& is_directory(mkpath("%s/.git/objects", ref_git
))) {
555 char *ref_git_git
= mkpathdup("%s/.git", ref_git
);
557 ref_git
= ref_git_git
;
558 } else if (!is_directory(mkpath("%s/objects", ref_git
))) {
559 struct strbuf sb
= STRBUF_INIT
;
561 if (get_common_dir(&sb
, ref_git
)) {
563 _("reference repository '%s' as a linked "
564 "checkout is not supported yet."),
569 strbuf_addf(err
, _("reference repository '%s' is not a "
570 "local repository."), path
);
574 if (!access(mkpath("%s/shallow", ref_git
), F_OK
)) {
575 strbuf_addf(err
, _("reference repository '%s' is shallow"),
581 if (!access(mkpath("%s/info/grafts", ref_git
), F_OK
)) {
583 _("reference repository '%s' is grafted"),
591 FREE_AND_NULL(ref_git
);
597 int foreach_alt_odb(alt_odb_fn fn
, void *cb
)
599 struct alternate_object_database
*ent
;
603 for (ent
= alt_odb_list
; ent
; ent
= ent
->next
) {
611 void prepare_alt_odb(void)
618 alt
= getenv(ALTERNATE_DB_ENVIRONMENT
);
621 alt_odb_tail
= &alt_odb_list
;
622 link_alt_odb_entries(alt
, strlen(alt
), PATH_SEP
, NULL
, 0);
624 read_info_alternates(get_object_directory(), 0);
627 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
628 static int freshen_file(const char *fn
)
631 t
.actime
= t
.modtime
= time(NULL
);
632 return !utime(fn
, &t
);
636 * All of the check_and_freshen functions return 1 if the file exists and was
637 * freshened (if freshening was requested), 0 otherwise. If they return
638 * 0, you should not assume that it is safe to skip a write of the object (it
639 * either does not exist on disk, or has a stale mtime and may be subject to
642 int check_and_freshen_file(const char *fn
, int freshen
)
644 if (access(fn
, F_OK
))
646 if (freshen
&& !freshen_file(fn
))
651 static int check_and_freshen_local(const unsigned char *sha1
, int freshen
)
653 return check_and_freshen_file(sha1_file_name(sha1
), freshen
);
656 static int check_and_freshen_nonlocal(const unsigned char *sha1
, int freshen
)
658 struct alternate_object_database
*alt
;
660 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
661 const char *path
= alt_sha1_path(alt
, sha1
);
662 if (check_and_freshen_file(path
, freshen
))
668 static int check_and_freshen(const unsigned char *sha1
, int freshen
)
670 return check_and_freshen_local(sha1
, freshen
) ||
671 check_and_freshen_nonlocal(sha1
, freshen
);
674 int has_loose_object_nonlocal(const unsigned char *sha1
)
676 return check_and_freshen_nonlocal(sha1
, 0);
679 static int has_loose_object(const unsigned char *sha1
)
681 return check_and_freshen(sha1
, 0);
684 static void mmap_limit_check(size_t length
)
686 static size_t limit
= 0;
688 limit
= git_env_ulong("GIT_MMAP_LIMIT", 0);
693 die("attempting to mmap %"PRIuMAX
" over limit %"PRIuMAX
,
694 (uintmax_t)length
, (uintmax_t)limit
);
697 void *xmmap_gently(void *start
, size_t length
,
698 int prot
, int flags
, int fd
, off_t offset
)
702 mmap_limit_check(length
);
703 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
704 if (ret
== MAP_FAILED
) {
707 release_pack_memory(length
);
708 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
713 void *xmmap(void *start
, size_t length
,
714 int prot
, int flags
, int fd
, off_t offset
)
716 void *ret
= xmmap_gently(start
, length
, prot
, flags
, fd
, offset
);
717 if (ret
== MAP_FAILED
)
718 die_errno("mmap failed");
723 * The LRU pack is the one with the oldest MRU window, preferring packs
724 * with no used windows, or the oldest mtime if it has no windows allocated.
726 static void find_lru_pack(struct packed_git
*p
, struct packed_git
**lru_p
, struct pack_window
**mru_w
, int *accept_windows_inuse
)
728 struct pack_window
*w
, *this_mru_w
;
729 int has_windows_inuse
= 0;
732 * Reject this pack if it has windows and the previously selected
733 * one does not. If this pack does not have windows, reject
734 * it if the pack file is newer than the previously selected one.
736 if (*lru_p
&& !*mru_w
&& (p
->windows
|| p
->mtime
> (*lru_p
)->mtime
))
739 for (w
= this_mru_w
= p
->windows
; w
; w
= w
->next
) {
741 * Reject this pack if any of its windows are in use,
742 * but the previously selected pack did not have any
743 * inuse windows. Otherwise, record that this pack
744 * has windows in use.
747 if (*accept_windows_inuse
)
748 has_windows_inuse
= 1;
753 if (w
->last_used
> this_mru_w
->last_used
)
757 * Reject this pack if it has windows that have been
758 * used more recently than the previously selected pack.
759 * If the previously selected pack had windows inuse and
760 * we have not encountered a window in this pack that is
761 * inuse, skip this check since we prefer a pack with no
762 * inuse windows to one that has inuse windows.
764 if (*mru_w
&& *accept_windows_inuse
== has_windows_inuse
&&
765 this_mru_w
->last_used
> (*mru_w
)->last_used
)
774 *accept_windows_inuse
= has_windows_inuse
;
777 static int close_one_pack(void)
779 struct packed_git
*p
, *lru_p
= NULL
;
780 struct pack_window
*mru_w
= NULL
;
781 int accept_windows_inuse
= 1;
783 for (p
= packed_git
; p
; p
= p
->next
) {
784 if (p
->pack_fd
== -1)
786 find_lru_pack(p
, &lru_p
, &mru_w
, &accept_windows_inuse
);
790 return close_pack_fd(lru_p
);
795 void unuse_pack(struct pack_window
**w_cursor
)
797 struct pack_window
*w
= *w_cursor
;
804 static unsigned int get_max_fd_limit(void)
810 if (!getrlimit(RLIMIT_NOFILE
, &lim
))
817 long open_max
= sysconf(_SC_OPEN_MAX
);
821 * Otherwise, we got -1 for one of the two
824 * (1) sysconf() did not understand _SC_OPEN_MAX
825 * and signaled an error with -1; or
826 * (2) sysconf() said there is no limit.
828 * We _could_ clear errno before calling sysconf() to
829 * tell these two cases apart and return a huge number
830 * in the latter case to let the caller cap it to a
831 * value that is not so selfish, but letting the
832 * fallback OPEN_MAX codepath take care of these cases
841 return 1; /* see the caller ;-) */
846 * Do not call this directly as this leaks p->pack_fd on error return;
847 * call open_packed_git() instead.
849 static int open_packed_git_1(struct packed_git
*p
)
852 struct pack_header hdr
;
853 unsigned char sha1
[20];
854 unsigned char *idx_sha1
;
857 if (!p
->index_data
&& open_pack_index(p
))
858 return error("packfile %s index unavailable", p
->pack_name
);
861 unsigned int max_fds
= get_max_fd_limit();
863 /* Save 3 for stdin/stdout/stderr, 22 for work */
865 pack_max_fds
= max_fds
- 25;
870 while (pack_max_fds
<= pack_open_fds
&& close_one_pack())
873 p
->pack_fd
= git_open(p
->pack_name
);
874 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
878 /* If we created the struct before we had the pack we lack size. */
880 if (!S_ISREG(st
.st_mode
))
881 return error("packfile %s not a regular file", p
->pack_name
);
882 p
->pack_size
= st
.st_size
;
883 } else if (p
->pack_size
!= st
.st_size
)
884 return error("packfile %s size changed", p
->pack_name
);
886 /* We leave these file descriptors open with sliding mmap;
887 * there is no point keeping them open across exec(), though.
889 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
891 return error("cannot determine file descriptor flags");
892 fd_flag
|= FD_CLOEXEC
;
893 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
894 return error("cannot set FD_CLOEXEC");
896 /* Verify we recognize this pack file format. */
897 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
898 return error("file %s is far too short to be a packfile", p
->pack_name
);
899 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
900 return error("file %s is not a GIT packfile", p
->pack_name
);
901 if (!pack_version_ok(hdr
.hdr_version
))
902 return error("packfile %s is version %"PRIu32
" and not"
903 " supported (try upgrading GIT to a newer version)",
904 p
->pack_name
, ntohl(hdr
.hdr_version
));
906 /* Verify the pack matches its index. */
907 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
908 return error("packfile %s claims to have %"PRIu32
" objects"
909 " while index indicates %"PRIu32
" objects",
910 p
->pack_name
, ntohl(hdr
.hdr_entries
),
912 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
913 return error("end of packfile %s is unavailable", p
->pack_name
);
914 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
915 return error("packfile %s signature is unavailable", p
->pack_name
);
916 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
917 if (hashcmp(sha1
, idx_sha1
))
918 return error("packfile %s does not match index", p
->pack_name
);
922 static int open_packed_git(struct packed_git
*p
)
924 if (!open_packed_git_1(p
))
930 static int in_window(struct pack_window
*win
, off_t offset
)
932 /* We must promise at least 20 bytes (one hash) after the
933 * offset is available from this window, otherwise the offset
934 * is not actually in this window and a different window (which
935 * has that one hash excess) must be used. This is to support
936 * the object header and delta base parsing routines below.
938 off_t win_off
= win
->offset
;
939 return win_off
<= offset
940 && (offset
+ 20) <= (win_off
+ win
->len
);
943 unsigned char *use_pack(struct packed_git
*p
,
944 struct pack_window
**w_cursor
,
948 struct pack_window
*win
= *w_cursor
;
950 /* Since packfiles end in a hash of their content and it's
951 * pointless to ask for an offset into the middle of that
952 * hash, and the in_window function above wouldn't match
953 * don't allow an offset too close to the end of the file.
955 if (!p
->pack_size
&& p
->pack_fd
== -1 && open_packed_git(p
))
956 die("packfile %s cannot be accessed", p
->pack_name
);
957 if (offset
> (p
->pack_size
- 20))
958 die("offset beyond end of packfile (truncated pack?)");
960 die(_("offset before end of packfile (broken .idx?)"));
962 if (!win
|| !in_window(win
, offset
)) {
965 for (win
= p
->windows
; win
; win
= win
->next
) {
966 if (in_window(win
, offset
))
970 size_t window_align
= packed_git_window_size
/ 2;
973 if (p
->pack_fd
== -1 && open_packed_git(p
))
974 die("packfile %s cannot be accessed", p
->pack_name
);
976 win
= xcalloc(1, sizeof(*win
));
977 win
->offset
= (offset
/ window_align
) * window_align
;
978 len
= p
->pack_size
- win
->offset
;
979 if (len
> packed_git_window_size
)
980 len
= packed_git_window_size
;
981 win
->len
= (size_t)len
;
982 pack_mapped
+= win
->len
;
983 while (packed_git_limit
< pack_mapped
984 && unuse_one_window(p
))
986 win
->base
= xmmap(NULL
, win
->len
,
987 PROT_READ
, MAP_PRIVATE
,
988 p
->pack_fd
, win
->offset
);
989 if (win
->base
== MAP_FAILED
)
990 die_errno("packfile %s cannot be mapped",
992 if (!win
->offset
&& win
->len
== p
->pack_size
997 if (pack_mapped
> peak_pack_mapped
)
998 peak_pack_mapped
= pack_mapped
;
999 if (pack_open_windows
> peak_pack_open_windows
)
1000 peak_pack_open_windows
= pack_open_windows
;
1001 win
->next
= p
->windows
;
1005 if (win
!= *w_cursor
) {
1006 win
->last_used
= pack_used_ctr
++;
1010 offset
-= win
->offset
;
1012 *left
= win
->len
- xsize_t(offset
);
1013 return win
->base
+ offset
;
1016 static struct packed_git
*alloc_packed_git(int extra
)
1018 struct packed_git
*p
= xmalloc(st_add(sizeof(*p
), extra
));
1019 memset(p
, 0, sizeof(*p
));
1024 static void try_to_free_pack_memory(size_t size
)
1026 release_pack_memory(size
);
1029 struct packed_git
*add_packed_git(const char *path
, size_t path_len
, int local
)
1031 static int have_set_try_to_free_routine
;
1034 struct packed_git
*p
;
1036 if (!have_set_try_to_free_routine
) {
1037 have_set_try_to_free_routine
= 1;
1038 set_try_to_free_routine(try_to_free_pack_memory
);
1042 * Make sure a corresponding .pack file exists and that
1043 * the index looks sane.
1045 if (!strip_suffix_mem(path
, &path_len
, ".idx"))
1049 * ".pack" is long enough to hold any suffix we're adding (and
1050 * the use xsnprintf double-checks that)
1052 alloc
= st_add3(path_len
, strlen(".pack"), 1);
1053 p
= alloc_packed_git(alloc
);
1054 memcpy(p
->pack_name
, path
, path_len
);
1056 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".keep");
1057 if (!access(p
->pack_name
, F_OK
))
1060 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".pack");
1061 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
1066 /* ok, it looks sane as far as we can check without
1067 * actually mapping the pack file.
1069 p
->pack_size
= st
.st_size
;
1070 p
->pack_local
= local
;
1071 p
->mtime
= st
.st_mtime
;
1072 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
1077 void install_packed_git(struct packed_git
*pack
)
1079 if (pack
->pack_fd
!= -1)
1082 pack
->next
= packed_git
;
1086 void (*report_garbage
)(unsigned seen_bits
, const char *path
);
1088 static void report_helper(const struct string_list
*list
,
1089 int seen_bits
, int first
, int last
)
1091 if (seen_bits
== (PACKDIR_FILE_PACK
|PACKDIR_FILE_IDX
))
1094 for (; first
< last
; first
++)
1095 report_garbage(seen_bits
, list
->items
[first
].string
);
1098 static void report_pack_garbage(struct string_list
*list
)
1100 int i
, baselen
= -1, first
= 0, seen_bits
= 0;
1102 if (!report_garbage
)
1105 string_list_sort(list
);
1107 for (i
= 0; i
< list
->nr
; i
++) {
1108 const char *path
= list
->items
[i
].string
;
1109 if (baselen
!= -1 &&
1110 strncmp(path
, list
->items
[first
].string
, baselen
)) {
1111 report_helper(list
, seen_bits
, first
, i
);
1115 if (baselen
== -1) {
1116 const char *dot
= strrchr(path
, '.');
1118 report_garbage(PACKDIR_FILE_GARBAGE
, path
);
1121 baselen
= dot
- path
+ 1;
1124 if (!strcmp(path
+ baselen
, "pack"))
1126 else if (!strcmp(path
+ baselen
, "idx"))
1129 report_helper(list
, seen_bits
, first
, list
->nr
);
1132 static void prepare_packed_git_one(char *objdir
, int local
)
1134 struct strbuf path
= STRBUF_INIT
;
1138 struct string_list garbage
= STRING_LIST_INIT_DUP
;
1140 strbuf_addstr(&path
, objdir
);
1141 strbuf_addstr(&path
, "/pack");
1142 dir
= opendir(path
.buf
);
1144 if (errno
!= ENOENT
)
1145 error_errno("unable to open object pack directory: %s",
1147 strbuf_release(&path
);
1150 strbuf_addch(&path
, '/');
1151 dirnamelen
= path
.len
;
1152 while ((de
= readdir(dir
)) != NULL
) {
1153 struct packed_git
*p
;
1156 if (is_dot_or_dotdot(de
->d_name
))
1159 strbuf_setlen(&path
, dirnamelen
);
1160 strbuf_addstr(&path
, de
->d_name
);
1162 base_len
= path
.len
;
1163 if (strip_suffix_mem(path
.buf
, &base_len
, ".idx")) {
1164 /* Don't reopen a pack we already have. */
1165 for (p
= packed_git
; p
; p
= p
->next
) {
1167 if (strip_suffix(p
->pack_name
, ".pack", &len
) &&
1169 !memcmp(p
->pack_name
, path
.buf
, len
))
1174 * See if it really is a valid .idx file with
1175 * corresponding .pack file that we can map.
1177 (p
= add_packed_git(path
.buf
, path
.len
, local
)) != NULL
)
1178 install_packed_git(p
);
1181 if (!report_garbage
)
1184 if (ends_with(de
->d_name
, ".idx") ||
1185 ends_with(de
->d_name
, ".pack") ||
1186 ends_with(de
->d_name
, ".bitmap") ||
1187 ends_with(de
->d_name
, ".keep"))
1188 string_list_append(&garbage
, path
.buf
);
1190 report_garbage(PACKDIR_FILE_GARBAGE
, path
.buf
);
1193 report_pack_garbage(&garbage
);
1194 string_list_clear(&garbage
, 0);
1195 strbuf_release(&path
);
1198 static int approximate_object_count_valid
;
1201 * Give a fast, rough count of the number of objects in the repository. This
1202 * ignores loose objects completely. If you have a lot of them, then either
1203 * you should repack because your performance will be awful, or they are
1204 * all unreachable objects about to be pruned, in which case they're not really
1205 * interesting as a measure of repo size in the first place.
1207 unsigned long approximate_object_count(void)
1209 static unsigned long count
;
1210 if (!approximate_object_count_valid
) {
1211 struct packed_git
*p
;
1213 prepare_packed_git();
1215 for (p
= packed_git
; p
; p
= p
->next
) {
1216 if (open_pack_index(p
))
1218 count
+= p
->num_objects
;
1224 static void *get_next_packed_git(const void *p
)
1226 return ((const struct packed_git
*)p
)->next
;
1229 static void set_next_packed_git(void *p
, void *next
)
1231 ((struct packed_git
*)p
)->next
= next
;
1234 static int sort_pack(const void *a_
, const void *b_
)
1236 const struct packed_git
*a
= a_
;
1237 const struct packed_git
*b
= b_
;
1241 * Local packs tend to contain objects specific to our
1242 * variant of the project than remote ones. In addition,
1243 * remote ones could be on a network mounted filesystem.
1244 * Favor local ones for these reasons.
1246 st
= a
->pack_local
- b
->pack_local
;
1251 * Younger packs tend to contain more recent objects,
1252 * and more recent objects tend to get accessed more
1255 if (a
->mtime
< b
->mtime
)
1257 else if (a
->mtime
== b
->mtime
)
1262 static void rearrange_packed_git(void)
1264 packed_git
= llist_mergesort(packed_git
, get_next_packed_git
,
1265 set_next_packed_git
, sort_pack
);
1268 static void prepare_packed_git_mru(void)
1270 struct packed_git
*p
;
1272 mru_clear(packed_git_mru
);
1273 for (p
= packed_git
; p
; p
= p
->next
)
1274 mru_append(packed_git_mru
, p
);
1277 static int prepare_packed_git_run_once
= 0;
1278 void prepare_packed_git(void)
1280 struct alternate_object_database
*alt
;
1282 if (prepare_packed_git_run_once
)
1284 prepare_packed_git_one(get_object_directory(), 1);
1286 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
)
1287 prepare_packed_git_one(alt
->path
, 0);
1288 rearrange_packed_git();
1289 prepare_packed_git_mru();
1290 prepare_packed_git_run_once
= 1;
1293 void reprepare_packed_git(void)
1295 approximate_object_count_valid
= 0;
1296 prepare_packed_git_run_once
= 0;
1297 prepare_packed_git();
1300 static void mark_bad_packed_object(struct packed_git
*p
,
1301 const unsigned char *sha1
)
1304 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1305 if (!hashcmp(sha1
, p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* i
))
1307 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
,
1308 st_mult(GIT_MAX_RAWSZ
,
1309 st_add(p
->num_bad_objects
, 1)));
1310 hashcpy(p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* p
->num_bad_objects
, sha1
);
1311 p
->num_bad_objects
++;
1314 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1316 struct packed_git
*p
;
1319 for (p
= packed_git
; p
; p
= p
->next
)
1320 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1321 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1327 * With an in-core object data in "map", rehash it to make sure the
1328 * object name actually matches "sha1" to detect object corruption.
1329 * With "map" == NULL, try reading the object named with "sha1" using
1330 * the streaming interface and rehash it to do the same.
1332 int check_sha1_signature(const unsigned char *sha1
, void *map
,
1333 unsigned long size
, const char *type
)
1335 unsigned char real_sha1
[20];
1336 enum object_type obj_type
;
1337 struct git_istream
*st
;
1343 hash_sha1_file(map
, size
, type
, real_sha1
);
1344 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1347 st
= open_istream(sha1
, &obj_type
, &size
, NULL
);
1351 /* Generate the header */
1352 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(obj_type
), size
) + 1;
1356 git_SHA1_Update(&c
, hdr
, hdrlen
);
1358 char buf
[1024 * 16];
1359 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
1367 git_SHA1_Update(&c
, buf
, readlen
);
1369 git_SHA1_Final(real_sha1
, &c
);
1371 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1374 int git_open_cloexec(const char *name
, int flags
)
1377 static int o_cloexec
= O_CLOEXEC
;
1379 fd
= open(name
, flags
| o_cloexec
);
1380 if ((o_cloexec
& O_CLOEXEC
) && fd
< 0 && errno
== EINVAL
) {
1381 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1382 o_cloexec
&= ~O_CLOEXEC
;
1383 fd
= open(name
, flags
| o_cloexec
);
1386 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1388 static int fd_cloexec
= FD_CLOEXEC
;
1390 if (!o_cloexec
&& 0 <= fd
&& fd_cloexec
) {
1391 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1392 int flags
= fcntl(fd
, F_GETFD
);
1393 if (fcntl(fd
, F_SETFD
, flags
| fd_cloexec
))
1402 * Find "sha1" as a loose object in the local repository or in an alternate.
1403 * Returns 0 on success, negative on failure.
1405 * The "path" out-parameter will give the path of the object we found (if any).
1406 * Note that it may point to static storage and is only valid until another
1407 * call to sha1_file_name(), etc.
1409 static int stat_sha1_file(const unsigned char *sha1
, struct stat
*st
,
1412 struct alternate_object_database
*alt
;
1414 *path
= sha1_file_name(sha1
);
1415 if (!lstat(*path
, st
))
1420 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1421 *path
= alt_sha1_path(alt
, sha1
);
1422 if (!lstat(*path
, st
))
1430 * Like stat_sha1_file(), but actually open the object and return the
1431 * descriptor. See the caveats on the "path" parameter above.
1433 static int open_sha1_file(const unsigned char *sha1
, const char **path
)
1436 struct alternate_object_database
*alt
;
1437 int most_interesting_errno
;
1439 *path
= sha1_file_name(sha1
);
1440 fd
= git_open(*path
);
1443 most_interesting_errno
= errno
;
1446 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1447 *path
= alt_sha1_path(alt
, sha1
);
1448 fd
= git_open(*path
);
1451 if (most_interesting_errno
== ENOENT
)
1452 most_interesting_errno
= errno
;
1454 errno
= most_interesting_errno
;
1459 * Map the loose object at "path" if it is not NULL, or the path found by
1460 * searching for a loose object named "sha1".
1462 static void *map_sha1_file_1(const char *path
,
1463 const unsigned char *sha1
,
1464 unsigned long *size
)
1470 fd
= git_open(path
);
1472 fd
= open_sha1_file(sha1
, &path
);
1477 if (!fstat(fd
, &st
)) {
1478 *size
= xsize_t(st
.st_size
);
1480 /* mmap() is forbidden on empty files */
1481 error("object file %s is empty", path
);
1484 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1491 void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1493 return map_sha1_file_1(NULL
, sha1
, size
);
1496 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1497 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1500 unsigned long size
, c
;
1501 unsigned long used
= 0;
1504 *type
= (c
>> 4) & 7;
1508 if (len
<= used
|| bitsizeof(long) <= shift
) {
1509 error("bad object header");
1514 size
+= (c
& 0x7f) << shift
;
1521 static int unpack_sha1_short_header(git_zstream
*stream
,
1522 unsigned char *map
, unsigned long mapsize
,
1523 void *buffer
, unsigned long bufsiz
)
1525 /* Get the data stream */
1526 memset(stream
, 0, sizeof(*stream
));
1527 stream
->next_in
= map
;
1528 stream
->avail_in
= mapsize
;
1529 stream
->next_out
= buffer
;
1530 stream
->avail_out
= bufsiz
;
1532 git_inflate_init(stream
);
1533 return git_inflate(stream
, 0);
1536 int unpack_sha1_header(git_zstream
*stream
,
1537 unsigned char *map
, unsigned long mapsize
,
1538 void *buffer
, unsigned long bufsiz
)
1540 int status
= unpack_sha1_short_header(stream
, map
, mapsize
,
1546 /* Make sure we have the terminating NUL */
1547 if (!memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1552 static int unpack_sha1_header_to_strbuf(git_zstream
*stream
, unsigned char *map
,
1553 unsigned long mapsize
, void *buffer
,
1554 unsigned long bufsiz
, struct strbuf
*header
)
1558 status
= unpack_sha1_short_header(stream
, map
, mapsize
, buffer
, bufsiz
);
1563 * Check if entire header is unpacked in the first iteration.
1565 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1569 * buffer[0..bufsiz] was not large enough. Copy the partial
1570 * result out to header, and then append the result of further
1571 * reading the stream.
1573 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1574 stream
->next_out
= buffer
;
1575 stream
->avail_out
= bufsiz
;
1578 status
= git_inflate(stream
, 0);
1579 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1580 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1582 stream
->next_out
= buffer
;
1583 stream
->avail_out
= bufsiz
;
1584 } while (status
!= Z_STREAM_END
);
1588 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1590 int bytes
= strlen(buffer
) + 1;
1591 unsigned char *buf
= xmallocz(size
);
1595 n
= stream
->total_out
- bytes
;
1598 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1600 if (bytes
<= size
) {
1602 * The above condition must be (bytes <= size), not
1603 * (bytes < size). In other words, even though we
1604 * expect no more output and set avail_out to zero,
1605 * the input zlib stream may have bytes that express
1606 * "this concludes the stream", and we *do* want to
1609 * Otherwise we would not be able to test that we
1610 * consumed all the input to reach the expected size;
1611 * we also want to check that zlib tells us that all
1612 * went well with status == Z_STREAM_END at the end.
1614 stream
->next_out
= buf
+ bytes
;
1615 stream
->avail_out
= size
- bytes
;
1616 while (status
== Z_OK
)
1617 status
= git_inflate(stream
, Z_FINISH
);
1619 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1620 git_inflate_end(stream
);
1625 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1626 else if (stream
->avail_in
)
1627 error("garbage at end of loose object '%s'",
1634 * We used to just use "sscanf()", but that's actually way
1635 * too permissive for what we want to check. So do an anal
1636 * object header parse by hand.
1638 static int parse_sha1_header_extended(const char *hdr
, struct object_info
*oi
,
1641 const char *type_buf
= hdr
;
1643 int type
, type_len
= 0;
1646 * The type can be of any size but is followed by
1658 type
= type_from_string_gently(type_buf
, type_len
, 1);
1660 strbuf_add(oi
->typename
, type_buf
, type_len
);
1662 * Set type to 0 if its an unknown object and
1663 * we're obtaining the type using '--allow-unknown-type'
1666 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
) && (type
< 0))
1669 die("invalid object type");
1674 * The length must follow immediately, and be in canonical
1675 * decimal format (ie "010" is not valid).
1677 size
= *hdr
++ - '0';
1682 unsigned long c
= *hdr
- '0';
1686 size
= size
* 10 + c
;
1694 * The length must be followed by a zero byte
1696 return *hdr
? -1 : type
;
1699 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1701 struct object_info oi
= OBJECT_INFO_INIT
;
1704 return parse_sha1_header_extended(hdr
, &oi
, 0);
1707 unsigned long get_size_from_delta(struct packed_git
*p
,
1708 struct pack_window
**w_curs
,
1711 const unsigned char *data
;
1712 unsigned char delta_head
[20], *in
;
1716 memset(&stream
, 0, sizeof(stream
));
1717 stream
.next_out
= delta_head
;
1718 stream
.avail_out
= sizeof(delta_head
);
1720 git_inflate_init(&stream
);
1722 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1723 stream
.next_in
= in
;
1724 st
= git_inflate(&stream
, Z_FINISH
);
1725 curpos
+= stream
.next_in
- in
;
1726 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
1727 stream
.total_out
< sizeof(delta_head
));
1728 git_inflate_end(&stream
);
1729 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
1730 error("delta data unpack-initial failed");
1734 /* Examine the initial part of the delta to figure out
1739 /* ignore base size */
1740 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1742 /* Read the result size */
1743 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1746 static off_t
get_delta_base(struct packed_git
*p
,
1747 struct pack_window
**w_curs
,
1749 enum object_type type
,
1750 off_t delta_obj_offset
)
1752 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
1755 /* use_pack() assured us we have [base_info, base_info + 20)
1756 * as a range that we can look at without walking off the
1757 * end of the mapped window. Its actually the hash size
1758 * that is assured. An OFS_DELTA longer than the hash size
1759 * is stupid, as then a REF_DELTA would be smaller to store.
1761 if (type
== OBJ_OFS_DELTA
) {
1763 unsigned char c
= base_info
[used
++];
1764 base_offset
= c
& 127;
1767 if (!base_offset
|| MSB(base_offset
, 7))
1768 return 0; /* overflow */
1769 c
= base_info
[used
++];
1770 base_offset
= (base_offset
<< 7) + (c
& 127);
1772 base_offset
= delta_obj_offset
- base_offset
;
1773 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
1774 return 0; /* out of bound */
1776 } else if (type
== OBJ_REF_DELTA
) {
1777 /* The base entry _must_ be in the same pack */
1778 base_offset
= find_pack_entry_one(base_info
, p
);
1781 die("I am totally screwed");
1786 * Like get_delta_base above, but we return the sha1 instead of the pack
1787 * offset. This means it is cheaper for REF deltas (we do not have to do
1788 * the final object lookup), but more expensive for OFS deltas (we
1789 * have to load the revidx to convert the offset back into a sha1).
1791 static const unsigned char *get_delta_base_sha1(struct packed_git
*p
,
1792 struct pack_window
**w_curs
,
1794 enum object_type type
,
1795 off_t delta_obj_offset
)
1797 if (type
== OBJ_REF_DELTA
) {
1798 unsigned char *base
= use_pack(p
, w_curs
, curpos
, NULL
);
1800 } else if (type
== OBJ_OFS_DELTA
) {
1801 struct revindex_entry
*revidx
;
1802 off_t base_offset
= get_delta_base(p
, w_curs
, &curpos
,
1803 type
, delta_obj_offset
);
1808 revidx
= find_pack_revindex(p
, base_offset
);
1812 return nth_packed_object_sha1(p
, revidx
->nr
);
1817 int unpack_object_header(struct packed_git
*p
,
1818 struct pack_window
**w_curs
,
1820 unsigned long *sizep
)
1822 unsigned char *base
;
1825 enum object_type type
;
1827 /* use_pack() assures us we have [base, base + 20) available
1828 * as a range that we can look at. (Its actually the hash
1829 * size that is assured.) With our object header encoding
1830 * the maximum deflated object size is 2^137, which is just
1831 * insane, so we know won't exceed what we have been given.
1833 base
= use_pack(p
, w_curs
, *curpos
, &left
);
1834 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
1843 static int retry_bad_packed_offset(struct packed_git
*p
, off_t obj_offset
)
1846 struct revindex_entry
*revidx
;
1847 const unsigned char *sha1
;
1848 revidx
= find_pack_revindex(p
, obj_offset
);
1851 sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1852 mark_bad_packed_object(p
, sha1
);
1853 type
= sha1_object_info(sha1
, NULL
);
1854 if (type
<= OBJ_NONE
)
1859 #define POI_STACK_PREALLOC 64
1861 static enum object_type
packed_to_object_type(struct packed_git
*p
,
1863 enum object_type type
,
1864 struct pack_window
**w_curs
,
1867 off_t small_poi_stack
[POI_STACK_PREALLOC
];
1868 off_t
*poi_stack
= small_poi_stack
;
1869 int poi_stack_nr
= 0, poi_stack_alloc
= POI_STACK_PREALLOC
;
1871 while (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1874 /* Push the object we're going to leave behind */
1875 if (poi_stack_nr
>= poi_stack_alloc
&& poi_stack
== small_poi_stack
) {
1876 poi_stack_alloc
= alloc_nr(poi_stack_nr
);
1877 ALLOC_ARRAY(poi_stack
, poi_stack_alloc
);
1878 memcpy(poi_stack
, small_poi_stack
, sizeof(off_t
)*poi_stack_nr
);
1880 ALLOC_GROW(poi_stack
, poi_stack_nr
+1, poi_stack_alloc
);
1882 poi_stack
[poi_stack_nr
++] = obj_offset
;
1883 /* If parsing the base offset fails, just unwind */
1884 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
1887 curpos
= obj_offset
= base_offset
;
1888 type
= unpack_object_header(p
, w_curs
, &curpos
, &size
);
1889 if (type
<= OBJ_NONE
) {
1890 /* If getting the base itself fails, we first
1891 * retry the base, otherwise unwind */
1892 type
= retry_bad_packed_offset(p
, base_offset
);
1893 if (type
> OBJ_NONE
)
1907 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1908 type
, (uintmax_t)obj_offset
, p
->pack_name
);
1913 if (poi_stack
!= small_poi_stack
)
1918 while (poi_stack_nr
) {
1919 obj_offset
= poi_stack
[--poi_stack_nr
];
1920 type
= retry_bad_packed_offset(p
, obj_offset
);
1921 if (type
> OBJ_NONE
)
1928 static struct hashmap delta_base_cache
;
1929 static size_t delta_base_cached
;
1931 static LIST_HEAD(delta_base_cache_lru
);
1933 struct delta_base_cache_key
{
1934 struct packed_git
*p
;
1938 struct delta_base_cache_entry
{
1939 struct hashmap hash
;
1940 struct delta_base_cache_key key
;
1941 struct list_head lru
;
1944 enum object_type type
;
1947 static unsigned int pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
1951 hash
= (unsigned int)(intptr_t)p
+ (unsigned int)base_offset
;
1952 hash
+= (hash
>> 8) + (hash
>> 16);
1956 static struct delta_base_cache_entry
*
1957 get_delta_base_cache_entry(struct packed_git
*p
, off_t base_offset
)
1959 struct hashmap_entry entry
;
1960 struct delta_base_cache_key key
;
1962 if (!delta_base_cache
.cmpfn
)
1965 hashmap_entry_init(&entry
, pack_entry_hash(p
, base_offset
));
1967 key
.base_offset
= base_offset
;
1968 return hashmap_get(&delta_base_cache
, &entry
, &key
);
1971 static int delta_base_cache_key_eq(const struct delta_base_cache_key
*a
,
1972 const struct delta_base_cache_key
*b
)
1974 return a
->p
== b
->p
&& a
->base_offset
== b
->base_offset
;
1977 static int delta_base_cache_hash_cmp(const void *unused_cmp_data
,
1978 const void *va
, const void *vb
,
1981 const struct delta_base_cache_entry
*a
= va
, *b
= vb
;
1982 const struct delta_base_cache_key
*key
= vkey
;
1984 return !delta_base_cache_key_eq(&a
->key
, key
);
1986 return !delta_base_cache_key_eq(&a
->key
, &b
->key
);
1989 static int in_delta_base_cache(struct packed_git
*p
, off_t base_offset
)
1991 return !!get_delta_base_cache_entry(p
, base_offset
);
1995 * Remove the entry from the cache, but do _not_ free the associated
1996 * entry data. The caller takes ownership of the "data" buffer, and
1997 * should copy out any fields it wants before detaching.
1999 static void detach_delta_base_cache_entry(struct delta_base_cache_entry
*ent
)
2001 hashmap_remove(&delta_base_cache
, ent
, &ent
->key
);
2002 list_del(&ent
->lru
);
2003 delta_base_cached
-= ent
->size
;
2007 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
2008 unsigned long *base_size
, enum object_type
*type
)
2010 struct delta_base_cache_entry
*ent
;
2012 ent
= get_delta_base_cache_entry(p
, base_offset
);
2014 return unpack_entry(p
, base_offset
, type
, base_size
);
2019 *base_size
= ent
->size
;
2020 return xmemdupz(ent
->data
, ent
->size
);
2023 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
2026 detach_delta_base_cache_entry(ent
);
2029 void clear_delta_base_cache(void)
2031 struct list_head
*lru
, *tmp
;
2032 list_for_each_safe(lru
, tmp
, &delta_base_cache_lru
) {
2033 struct delta_base_cache_entry
*entry
=
2034 list_entry(lru
, struct delta_base_cache_entry
, lru
);
2035 release_delta_base_cache(entry
);
2039 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
2040 void *base
, unsigned long base_size
, enum object_type type
)
2042 struct delta_base_cache_entry
*ent
= xmalloc(sizeof(*ent
));
2043 struct list_head
*lru
, *tmp
;
2045 delta_base_cached
+= base_size
;
2047 list_for_each_safe(lru
, tmp
, &delta_base_cache_lru
) {
2048 struct delta_base_cache_entry
*f
=
2049 list_entry(lru
, struct delta_base_cache_entry
, lru
);
2050 if (delta_base_cached
<= delta_base_cache_limit
)
2052 release_delta_base_cache(f
);
2056 ent
->key
.base_offset
= base_offset
;
2059 ent
->size
= base_size
;
2060 list_add_tail(&ent
->lru
, &delta_base_cache_lru
);
2062 if (!delta_base_cache
.cmpfn
)
2063 hashmap_init(&delta_base_cache
, delta_base_cache_hash_cmp
, NULL
, 0);
2064 hashmap_entry_init(ent
, pack_entry_hash(p
, base_offset
));
2065 hashmap_add(&delta_base_cache
, ent
);
2068 int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
2069 struct object_info
*oi
)
2071 struct pack_window
*w_curs
= NULL
;
2073 off_t curpos
= obj_offset
;
2074 enum object_type type
;
2077 * We always get the representation type, but only convert it to
2078 * a "real" type later if the caller is interested.
2081 *oi
->contentp
= cache_or_unpack_entry(p
, obj_offset
, oi
->sizep
,
2086 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2089 if (!oi
->contentp
&& oi
->sizep
) {
2090 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2091 off_t tmp_pos
= curpos
;
2092 off_t base_offset
= get_delta_base(p
, &w_curs
, &tmp_pos
,
2098 *oi
->sizep
= get_size_from_delta(p
, &w_curs
, tmp_pos
);
2099 if (*oi
->sizep
== 0) {
2108 if (oi
->disk_sizep
) {
2109 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2110 *oi
->disk_sizep
= revidx
[1].offset
- obj_offset
;
2113 if (oi
->typep
|| oi
->typename
) {
2114 enum object_type ptot
;
2115 ptot
= packed_to_object_type(p
, obj_offset
, type
, &w_curs
,
2120 const char *tn
= typename(ptot
);
2122 strbuf_addstr(oi
->typename
, tn
);
2130 if (oi
->delta_base_sha1
) {
2131 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2132 const unsigned char *base
;
2134 base
= get_delta_base_sha1(p
, &w_curs
, curpos
,
2141 hashcpy(oi
->delta_base_sha1
, base
);
2143 hashclr(oi
->delta_base_sha1
);
2146 oi
->whence
= in_delta_base_cache(p
, obj_offset
) ? OI_DBCACHED
:
2150 unuse_pack(&w_curs
);
2154 static void *unpack_compressed_entry(struct packed_git
*p
,
2155 struct pack_window
**w_curs
,
2161 unsigned char *buffer
, *in
;
2163 buffer
= xmallocz_gently(size
);
2166 memset(&stream
, 0, sizeof(stream
));
2167 stream
.next_out
= buffer
;
2168 stream
.avail_out
= size
+ 1;
2170 git_inflate_init(&stream
);
2172 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
2173 stream
.next_in
= in
;
2174 st
= git_inflate(&stream
, Z_FINISH
);
2175 if (!stream
.avail_out
)
2176 break; /* the payload is larger than it should be */
2177 curpos
+= stream
.next_in
- in
;
2178 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
2179 git_inflate_end(&stream
);
2180 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
2188 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2189 unsigned long *size
);
2191 static void write_pack_access_log(struct packed_git
*p
, off_t obj_offset
)
2193 static struct trace_key pack_access
= TRACE_KEY_INIT(PACK_ACCESS
);
2194 trace_printf_key(&pack_access
, "%s %"PRIuMAX
"\n",
2195 p
->pack_name
, (uintmax_t)obj_offset
);
2198 int do_check_packed_object_crc
;
2200 #define UNPACK_ENTRY_STACK_PREALLOC 64
2201 struct unpack_entry_stack_ent
{
2207 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
2208 enum object_type
*final_type
, unsigned long *final_size
)
2210 struct pack_window
*w_curs
= NULL
;
2211 off_t curpos
= obj_offset
;
2214 enum object_type type
;
2215 struct unpack_entry_stack_ent small_delta_stack
[UNPACK_ENTRY_STACK_PREALLOC
];
2216 struct unpack_entry_stack_ent
*delta_stack
= small_delta_stack
;
2217 int delta_stack_nr
= 0, delta_stack_alloc
= UNPACK_ENTRY_STACK_PREALLOC
;
2218 int base_from_cache
= 0;
2220 write_pack_access_log(p
, obj_offset
);
2222 /* PHASE 1: drill down to the innermost base object */
2226 struct delta_base_cache_entry
*ent
;
2228 ent
= get_delta_base_cache_entry(p
, curpos
);
2233 detach_delta_base_cache_entry(ent
);
2234 base_from_cache
= 1;
2238 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
2239 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2240 off_t len
= revidx
[1].offset
- obj_offset
;
2241 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
2242 const unsigned char *sha1
=
2243 nth_packed_object_sha1(p
, revidx
->nr
);
2244 error("bad packed object CRC for %s",
2246 mark_bad_packed_object(p
, sha1
);
2252 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2253 if (type
!= OBJ_OFS_DELTA
&& type
!= OBJ_REF_DELTA
)
2256 base_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
2258 error("failed to validate delta base reference "
2259 "at offset %"PRIuMAX
" from %s",
2260 (uintmax_t)curpos
, p
->pack_name
);
2261 /* bail to phase 2, in hopes of recovery */
2266 /* push object, proceed to base */
2267 if (delta_stack_nr
>= delta_stack_alloc
2268 && delta_stack
== small_delta_stack
) {
2269 delta_stack_alloc
= alloc_nr(delta_stack_nr
);
2270 ALLOC_ARRAY(delta_stack
, delta_stack_alloc
);
2271 memcpy(delta_stack
, small_delta_stack
,
2272 sizeof(*delta_stack
)*delta_stack_nr
);
2274 ALLOC_GROW(delta_stack
, delta_stack_nr
+1, delta_stack_alloc
);
2276 i
= delta_stack_nr
++;
2277 delta_stack
[i
].obj_offset
= obj_offset
;
2278 delta_stack
[i
].curpos
= curpos
;
2279 delta_stack
[i
].size
= size
;
2281 curpos
= obj_offset
= base_offset
;
2284 /* PHASE 2: handle the base */
2289 die("BUG: unpack_entry: left loop at a valid delta");
2295 if (!base_from_cache
)
2296 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, size
);
2300 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2301 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2304 /* PHASE 3: apply deltas in order */
2307 * 'data' holds the base data, or NULL if there was corruption
2309 while (delta_stack_nr
) {
2312 void *external_base
= NULL
;
2313 unsigned long delta_size
, base_size
= size
;
2319 add_delta_base_cache(p
, obj_offset
, base
, base_size
, type
);
2323 * We're probably in deep shit, but let's try to fetch
2324 * the required base anyway from another pack or loose.
2325 * This is costly but should happen only in the presence
2326 * of a corrupted pack, and is better than failing outright.
2328 struct revindex_entry
*revidx
;
2329 const unsigned char *base_sha1
;
2330 revidx
= find_pack_revindex(p
, obj_offset
);
2332 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2333 error("failed to read delta base object %s"
2334 " at offset %"PRIuMAX
" from %s",
2335 sha1_to_hex(base_sha1
), (uintmax_t)obj_offset
,
2337 mark_bad_packed_object(p
, base_sha1
);
2338 base
= read_object(base_sha1
, &type
, &base_size
);
2339 external_base
= base
;
2343 i
= --delta_stack_nr
;
2344 obj_offset
= delta_stack
[i
].obj_offset
;
2345 curpos
= delta_stack
[i
].curpos
;
2346 delta_size
= delta_stack
[i
].size
;
2351 delta_data
= unpack_compressed_entry(p
, &w_curs
, curpos
, delta_size
);
2354 error("failed to unpack compressed delta "
2355 "at offset %"PRIuMAX
" from %s",
2356 (uintmax_t)curpos
, p
->pack_name
);
2358 free(external_base
);
2362 data
= patch_delta(base
, base_size
,
2363 delta_data
, delta_size
,
2367 * We could not apply the delta; warn the user, but keep going.
2368 * Our failure will be noticed either in the next iteration of
2369 * the loop, or if this is the final delta, in the caller when
2370 * we return NULL. Those code paths will take care of making
2371 * a more explicit warning and retrying with another copy of
2375 error("failed to apply delta");
2378 free(external_base
);
2387 unuse_pack(&w_curs
);
2389 if (delta_stack
!= small_delta_stack
)
2395 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
2398 const unsigned char *index
= p
->index_data
;
2400 if (open_pack_index(p
))
2402 index
= p
->index_data
;
2404 if (n
>= p
->num_objects
)
2407 if (p
->index_version
== 1) {
2408 return index
+ 24 * n
+ 4;
2411 return index
+ 20 * n
;
2415 const struct object_id
*nth_packed_object_oid(struct object_id
*oid
,
2416 struct packed_git
*p
,
2419 const unsigned char *hash
= nth_packed_object_sha1(p
, n
);
2422 hashcpy(oid
->hash
, hash
);
2426 void check_pack_index_ptr(const struct packed_git
*p
, const void *vptr
)
2428 const unsigned char *ptr
= vptr
;
2429 const unsigned char *start
= p
->index_data
;
2430 const unsigned char *end
= start
+ p
->index_size
;
2432 die(_("offset before start of pack index for %s (corrupt index?)"),
2434 /* No need to check for underflow; .idx files must be at least 8 bytes */
2436 die(_("offset beyond end of pack index for %s (truncated index?)"),
2440 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
2442 const unsigned char *index
= p
->index_data
;
2444 if (p
->index_version
== 1) {
2445 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
2448 index
+= 8 + p
->num_objects
* (20 + 4);
2449 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
2450 if (!(off
& 0x80000000))
2452 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
2453 check_pack_index_ptr(p
, index
);
2454 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
2455 ntohl(*((uint32_t *)(index
+ 4)));
2459 off_t
find_pack_entry_one(const unsigned char *sha1
,
2460 struct packed_git
*p
)
2462 const uint32_t *level1_ofs
= p
->index_data
;
2463 const unsigned char *index
= p
->index_data
;
2464 unsigned hi
, lo
, stride
;
2465 static int debug_lookup
= -1;
2467 if (debug_lookup
< 0)
2468 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
2471 if (open_pack_index(p
))
2473 level1_ofs
= p
->index_data
;
2474 index
= p
->index_data
;
2476 if (p
->index_version
> 1) {
2481 hi
= ntohl(level1_ofs
[*sha1
]);
2482 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
2483 if (p
->index_version
> 1) {
2491 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
2492 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
2495 unsigned mi
= (lo
+ hi
) / 2;
2496 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
2499 printf("lo %u hi %u rg %u mi %u\n",
2500 lo
, hi
, hi
- lo
, mi
);
2502 return nth_packed_object_offset(p
, mi
);
2511 int is_pack_valid(struct packed_git
*p
)
2513 /* An already open pack is known to be valid. */
2514 if (p
->pack_fd
!= -1)
2517 /* If the pack has one window completely covering the
2518 * file size, the pack is known to be valid even if
2519 * the descriptor is not currently open.
2522 struct pack_window
*w
= p
->windows
;
2524 if (!w
->offset
&& w
->len
== p
->pack_size
)
2528 /* Force the pack to open to prove its valid. */
2529 return !open_packed_git(p
);
2532 static int fill_pack_entry(const unsigned char *sha1
,
2533 struct pack_entry
*e
,
2534 struct packed_git
*p
)
2538 if (p
->num_bad_objects
) {
2540 for (i
= 0; i
< p
->num_bad_objects
; i
++)
2541 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
2545 offset
= find_pack_entry_one(sha1
, p
);
2550 * We are about to tell the caller where they can locate the
2551 * requested object. We better make sure the packfile is
2552 * still here and can be accessed before supplying that
2553 * answer, as it may have been deleted since the index was
2556 if (!is_pack_valid(p
))
2560 hashcpy(e
->sha1
, sha1
);
2565 * Iff a pack file contains the object named by sha1, return true and
2566 * store its location to e.
2568 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
2570 struct mru_entry
*p
;
2572 prepare_packed_git();
2576 for (p
= packed_git_mru
->head
; p
; p
= p
->next
) {
2577 if (fill_pack_entry(sha1
, e
, p
->item
)) {
2578 mru_mark(packed_git_mru
, p
);
2585 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
2586 struct packed_git
*packs
)
2588 struct packed_git
*p
;
2590 for (p
= packs
; p
; p
= p
->next
) {
2591 if (find_pack_entry_one(sha1
, p
))
2598 static int sha1_loose_object_info(const unsigned char *sha1
,
2599 struct object_info
*oi
,
2603 unsigned long mapsize
;
2607 struct strbuf hdrbuf
= STRBUF_INIT
;
2608 unsigned long size_scratch
;
2610 if (oi
->delta_base_sha1
)
2611 hashclr(oi
->delta_base_sha1
);
2614 * If we don't care about type or size, then we don't
2615 * need to look inside the object at all. Note that we
2616 * do not optimize out the stat call, even if the
2617 * caller doesn't care about the disk-size, since our
2618 * return value implicitly indicates whether the
2619 * object even exists.
2621 if (!oi
->typep
&& !oi
->typename
&& !oi
->sizep
&& !oi
->contentp
) {
2624 if (stat_sha1_file(sha1
, &st
, &path
) < 0)
2627 *oi
->disk_sizep
= st
.st_size
;
2631 map
= map_sha1_file(sha1
, &mapsize
);
2636 oi
->sizep
= &size_scratch
;
2639 *oi
->disk_sizep
= mapsize
;
2640 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
)) {
2641 if (unpack_sha1_header_to_strbuf(&stream
, map
, mapsize
, hdr
, sizeof(hdr
), &hdrbuf
) < 0)
2642 status
= error("unable to unpack %s header with --allow-unknown-type",
2644 } else if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
2645 status
= error("unable to unpack %s header",
2649 else if (hdrbuf
.len
) {
2650 if ((status
= parse_sha1_header_extended(hdrbuf
.buf
, oi
, flags
)) < 0)
2651 status
= error("unable to parse %s header with --allow-unknown-type",
2653 } else if ((status
= parse_sha1_header_extended(hdr
, oi
, flags
)) < 0)
2654 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
2656 if (status
>= 0 && oi
->contentp
)
2657 *oi
->contentp
= unpack_sha1_rest(&stream
, hdr
,
2660 git_inflate_end(&stream
);
2662 munmap(map
, mapsize
);
2663 if (status
&& oi
->typep
)
2664 *oi
->typep
= status
;
2665 if (oi
->sizep
== &size_scratch
)
2667 strbuf_release(&hdrbuf
);
2668 oi
->whence
= OI_LOOSE
;
2669 return (status
< 0) ? status
: 0;
2672 int sha1_object_info_extended(const unsigned char *sha1
, struct object_info
*oi
, unsigned flags
)
2674 static struct object_info blank_oi
= OBJECT_INFO_INIT
;
2675 struct pack_entry e
;
2677 const unsigned char *real
= (flags
& OBJECT_INFO_LOOKUP_REPLACE
) ?
2678 lookup_replace_object(sha1
) :
2684 if (!(flags
& OBJECT_INFO_SKIP_CACHED
)) {
2685 struct cached_object
*co
= find_cached_object(real
);
2688 *(oi
->typep
) = co
->type
;
2690 *(oi
->sizep
) = co
->size
;
2692 *(oi
->disk_sizep
) = 0;
2693 if (oi
->delta_base_sha1
)
2694 hashclr(oi
->delta_base_sha1
);
2696 strbuf_addstr(oi
->typename
, typename(co
->type
));
2698 *oi
->contentp
= xmemdupz(co
->buf
, co
->size
);
2699 oi
->whence
= OI_CACHED
;
2704 if (!find_pack_entry(real
, &e
)) {
2705 /* Most likely it's a loose object. */
2706 if (!sha1_loose_object_info(real
, oi
, flags
))
2709 /* Not a loose object; someone else may have just packed it. */
2710 if (flags
& OBJECT_INFO_QUICK
) {
2713 reprepare_packed_git();
2714 if (!find_pack_entry(real
, &e
))
2719 if (oi
== &blank_oi
)
2721 * We know that the caller doesn't actually need the
2722 * information below, so return early.
2726 rtype
= packed_object_info(e
.p
, e
.offset
, oi
);
2728 mark_bad_packed_object(e
.p
, real
);
2729 return sha1_object_info_extended(real
, oi
, 0);
2730 } else if (oi
->whence
== OI_PACKED
) {
2731 oi
->u
.packed
.offset
= e
.offset
;
2732 oi
->u
.packed
.pack
= e
.p
;
2733 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
2734 rtype
== OBJ_OFS_DELTA
);
2740 /* returns enum object_type or negative */
2741 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
2743 enum object_type type
;
2744 struct object_info oi
= OBJECT_INFO_INIT
;
2748 if (sha1_object_info_extended(sha1
, &oi
,
2749 OBJECT_INFO_LOOKUP_REPLACE
) < 0)
2754 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
2755 unsigned char *sha1
)
2757 struct cached_object
*co
;
2759 hash_sha1_file(buf
, len
, typename(type
), sha1
);
2760 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
2762 ALLOC_GROW(cached_objects
, cached_object_nr
+ 1, cached_object_alloc
);
2763 co
= &cached_objects
[cached_object_nr
++];
2766 co
->buf
= xmalloc(len
);
2767 memcpy(co
->buf
, buf
, len
);
2768 hashcpy(co
->sha1
, sha1
);
2772 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2773 unsigned long *size
)
2775 struct object_info oi
= OBJECT_INFO_INIT
;
2779 oi
.contentp
= &content
;
2781 if (sha1_object_info_extended(sha1
, &oi
, 0) < 0)
2787 * This function dies on corrupt objects; the callers who want to
2788 * deal with them should arrange to call read_object() and give error
2789 * messages themselves.
2791 void *read_sha1_file_extended(const unsigned char *sha1
,
2792 enum object_type
*type
,
2793 unsigned long *size
,
2797 const struct packed_git
*p
;
2800 const unsigned char *repl
= lookup_replace
? lookup_replace_object(sha1
)
2804 data
= read_object(repl
, type
, size
);
2808 if (errno
&& errno
!= ENOENT
)
2809 die_errno("failed to read object %s", sha1_to_hex(sha1
));
2811 /* die if we replaced an object with one that does not exist */
2813 die("replacement %s not found for %s",
2814 sha1_to_hex(repl
), sha1_to_hex(sha1
));
2816 if (!stat_sha1_file(repl
, &st
, &path
))
2817 die("loose object %s (stored in %s) is corrupt",
2818 sha1_to_hex(repl
), path
);
2820 if ((p
= has_packed_and_bad(repl
)) != NULL
)
2821 die("packed object %s (stored in %s) is corrupt",
2822 sha1_to_hex(repl
), p
->pack_name
);
2827 void *read_object_with_reference(const unsigned char *sha1
,
2828 const char *required_type_name
,
2829 unsigned long *size
,
2830 unsigned char *actual_sha1_return
)
2832 enum object_type type
, required_type
;
2834 unsigned long isize
;
2835 unsigned char actual_sha1
[20];
2837 required_type
= type_from_string(required_type_name
);
2838 hashcpy(actual_sha1
, sha1
);
2840 int ref_length
= -1;
2841 const char *ref_type
= NULL
;
2843 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
2846 if (type
== required_type
) {
2848 if (actual_sha1_return
)
2849 hashcpy(actual_sha1_return
, actual_sha1
);
2852 /* Handle references */
2853 else if (type
== OBJ_COMMIT
)
2855 else if (type
== OBJ_TAG
)
2856 ref_type
= "object ";
2861 ref_length
= strlen(ref_type
);
2863 if (ref_length
+ 40 > isize
||
2864 memcmp(buffer
, ref_type
, ref_length
) ||
2865 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
2870 /* Now we have the ID of the referred-to object in
2871 * actual_sha1. Check again. */
2875 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
2876 const char *type
, unsigned char *sha1
,
2877 char *hdr
, int *hdrlen
)
2881 /* Generate the header */
2882 *hdrlen
= xsnprintf(hdr
, *hdrlen
, "%s %lu", type
, len
)+1;
2886 git_SHA1_Update(&c
, hdr
, *hdrlen
);
2887 git_SHA1_Update(&c
, buf
, len
);
2888 git_SHA1_Final(sha1
, &c
);
2892 * Move the just written object into its final resting place.
2894 int finalize_object_file(const char *tmpfile
, const char *filename
)
2898 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
2900 else if (link(tmpfile
, filename
))
2904 * Coda hack - coda doesn't like cross-directory links,
2905 * so we fall back to a rename, which will mean that it
2906 * won't be able to check collisions, but that's not a
2909 * The same holds for FAT formatted media.
2911 * When this succeeds, we just return. We have nothing
2914 if (ret
&& ret
!= EEXIST
) {
2916 if (!rename(tmpfile
, filename
))
2920 unlink_or_warn(tmpfile
);
2922 if (ret
!= EEXIST
) {
2923 return error_errno("unable to write sha1 filename %s", filename
);
2925 /* FIXME!!! Collision check here ? */
2929 if (adjust_shared_perm(filename
))
2930 return error("unable to set permission to '%s'", filename
);
2934 static int write_buffer(int fd
, const void *buf
, size_t len
)
2936 if (write_in_full(fd
, buf
, len
) < 0)
2937 return error_errno("file write error");
2941 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
2942 unsigned char *sha1
)
2945 int hdrlen
= sizeof(hdr
);
2946 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2950 /* Finalize a file on disk, and close it. */
2951 static void close_sha1_file(int fd
)
2953 if (fsync_object_files
)
2954 fsync_or_die(fd
, "sha1 file");
2956 die_errno("error when closing sha1 file");
2959 /* Size of directory component, including the ending '/' */
2960 static inline int directory_size(const char *filename
)
2962 const char *s
= strrchr(filename
, '/');
2965 return s
- filename
+ 1;
2969 * This creates a temporary file in the same directory as the final
2972 * We want to avoid cross-directory filename renames, because those
2973 * can have problems on various filesystems (FAT, NFS, Coda).
2975 static int create_tmpfile(struct strbuf
*tmp
, const char *filename
)
2977 int fd
, dirlen
= directory_size(filename
);
2980 strbuf_add(tmp
, filename
, dirlen
);
2981 strbuf_addstr(tmp
, "tmp_obj_XXXXXX");
2982 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
2983 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
2985 * Make sure the directory exists; note that the contents
2986 * of the buffer are undefined after mkstemp returns an
2987 * error, so we have to rewrite the whole buffer from
2991 strbuf_add(tmp
, filename
, dirlen
- 1);
2992 if (mkdir(tmp
->buf
, 0777) && errno
!= EEXIST
)
2994 if (adjust_shared_perm(tmp
->buf
))
2998 strbuf_addstr(tmp
, "/tmp_obj_XXXXXX");
2999 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
3004 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
3005 const void *buf
, unsigned long len
, time_t mtime
)
3008 unsigned char compressed
[4096];
3011 unsigned char parano_sha1
[20];
3012 static struct strbuf tmp_file
= STRBUF_INIT
;
3013 const char *filename
= sha1_file_name(sha1
);
3015 fd
= create_tmpfile(&tmp_file
, filename
);
3017 if (errno
== EACCES
)
3018 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3020 return error_errno("unable to create temporary file");
3024 git_deflate_init(&stream
, zlib_compression_level
);
3025 stream
.next_out
= compressed
;
3026 stream
.avail_out
= sizeof(compressed
);
3029 /* First header.. */
3030 stream
.next_in
= (unsigned char *)hdr
;
3031 stream
.avail_in
= hdrlen
;
3032 while (git_deflate(&stream
, 0) == Z_OK
)
3034 git_SHA1_Update(&c
, hdr
, hdrlen
);
3036 /* Then the data itself.. */
3037 stream
.next_in
= (void *)buf
;
3038 stream
.avail_in
= len
;
3040 unsigned char *in0
= stream
.next_in
;
3041 ret
= git_deflate(&stream
, Z_FINISH
);
3042 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
3043 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
3044 die("unable to write sha1 file");
3045 stream
.next_out
= compressed
;
3046 stream
.avail_out
= sizeof(compressed
);
3047 } while (ret
== Z_OK
);
3049 if (ret
!= Z_STREAM_END
)
3050 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
3051 ret
= git_deflate_end_gently(&stream
);
3053 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
3054 git_SHA1_Final(parano_sha1
, &c
);
3055 if (hashcmp(sha1
, parano_sha1
) != 0)
3056 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
3058 close_sha1_file(fd
);
3063 utb
.modtime
= mtime
;
3064 if (utime(tmp_file
.buf
, &utb
) < 0)
3065 warning_errno("failed utime() on %s", tmp_file
.buf
);
3068 return finalize_object_file(tmp_file
.buf
, filename
);
3071 static int freshen_loose_object(const unsigned char *sha1
)
3073 return check_and_freshen(sha1
, 1);
3076 static int freshen_packed_object(const unsigned char *sha1
)
3078 struct pack_entry e
;
3079 if (!find_pack_entry(sha1
, &e
))
3083 if (!freshen_file(e
.p
->pack_name
))
3089 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *sha1
)
3092 int hdrlen
= sizeof(hdr
);
3094 /* Normally if we have it in the pack then we do not bother writing
3095 * it out into .git/objects/??/?{38} file.
3097 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3098 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3100 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
3103 int hash_sha1_file_literally(const void *buf
, unsigned long len
, const char *type
,
3104 unsigned char *sha1
, unsigned flags
)
3107 int hdrlen
, status
= 0;
3109 /* type string, SP, %lu of the length plus NUL must fit this */
3110 hdrlen
= strlen(type
) + 32;
3111 header
= xmalloc(hdrlen
);
3112 write_sha1_file_prepare(buf
, len
, type
, sha1
, header
, &hdrlen
);
3114 if (!(flags
& HASH_WRITE_OBJECT
))
3116 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3118 status
= write_loose_object(sha1
, header
, hdrlen
, buf
, len
, 0);
3125 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
3129 enum object_type type
;
3134 if (has_loose_object(sha1
))
3136 buf
= read_object(sha1
, &type
, &len
);
3138 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
3139 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(type
), len
) + 1;
3140 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
3146 int has_pack_index(const unsigned char *sha1
)
3149 if (stat(sha1_pack_index_name(sha1
), &st
))
3154 int has_sha1_pack(const unsigned char *sha1
)
3156 struct pack_entry e
;
3157 return find_pack_entry(sha1
, &e
);
3160 int has_sha1_file_with_flags(const unsigned char *sha1
, int flags
)
3162 if (!startup_info
->have_repository
)
3164 return sha1_object_info_extended(sha1
, NULL
,
3165 flags
| OBJECT_INFO_SKIP_CACHED
) >= 0;
3168 int has_object_file(const struct object_id
*oid
)
3170 return has_sha1_file(oid
->hash
);
3173 int has_object_file_with_flags(const struct object_id
*oid
, int flags
)
3175 return has_sha1_file_with_flags(oid
->hash
, flags
);
3178 static void check_tree(const void *buf
, size_t size
)
3180 struct tree_desc desc
;
3181 struct name_entry entry
;
3183 init_tree_desc(&desc
, buf
, size
);
3184 while (tree_entry(&desc
, &entry
))
3186 * tree_entry() will die() on malformed entries */
3190 static void check_commit(const void *buf
, size_t size
)
3193 memset(&c
, 0, sizeof(c
));
3194 if (parse_commit_buffer(&c
, buf
, size
))
3195 die("corrupt commit");
3198 static void check_tag(const void *buf
, size_t size
)
3201 memset(&t
, 0, sizeof(t
));
3202 if (parse_tag_buffer(&t
, buf
, size
))
3206 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
3207 enum object_type type
,
3208 const char *path
, unsigned flags
)
3210 int ret
, re_allocated
= 0;
3211 int write_object
= flags
& HASH_WRITE_OBJECT
;
3217 * Convert blobs to git internal format
3219 if ((type
== OBJ_BLOB
) && path
) {
3220 struct strbuf nbuf
= STRBUF_INIT
;
3221 if (convert_to_git(&the_index
, path
, buf
, size
, &nbuf
,
3222 write_object
? safe_crlf
: SAFE_CRLF_FALSE
)) {
3223 buf
= strbuf_detach(&nbuf
, &size
);
3227 if (flags
& HASH_FORMAT_CHECK
) {
3228 if (type
== OBJ_TREE
)
3229 check_tree(buf
, size
);
3230 if (type
== OBJ_COMMIT
)
3231 check_commit(buf
, size
);
3232 if (type
== OBJ_TAG
)
3233 check_tag(buf
, size
);
3237 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
3239 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
3245 static int index_stream_convert_blob(unsigned char *sha1
, int fd
,
3246 const char *path
, unsigned flags
)
3249 const int write_object
= flags
& HASH_WRITE_OBJECT
;
3250 struct strbuf sbuf
= STRBUF_INIT
;
3253 assert(would_convert_to_git_filter_fd(path
));
3255 convert_to_git_filter_fd(&the_index
, path
, fd
, &sbuf
,
3256 write_object
? safe_crlf
: SAFE_CRLF_FALSE
);
3259 ret
= write_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3262 ret
= hash_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3264 strbuf_release(&sbuf
);
3268 static int index_pipe(unsigned char *sha1
, int fd
, enum object_type type
,
3269 const char *path
, unsigned flags
)
3271 struct strbuf sbuf
= STRBUF_INIT
;
3274 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
3275 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
3278 strbuf_release(&sbuf
);
3282 #define SMALL_FILE_SIZE (32*1024)
3284 static int index_core(unsigned char *sha1
, int fd
, size_t size
,
3285 enum object_type type
, const char *path
,
3291 ret
= index_mem(sha1
, "", size
, type
, path
, flags
);
3292 } else if (size
<= SMALL_FILE_SIZE
) {
3293 char *buf
= xmalloc(size
);
3294 if (size
== read_in_full(fd
, buf
, size
))
3295 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3297 ret
= error_errno("short read");
3300 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
3301 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3308 * This creates one packfile per large blob unless bulk-checkin
3309 * machinery is "plugged".
3311 * This also bypasses the usual "convert-to-git" dance, and that is on
3312 * purpose. We could write a streaming version of the converting
3313 * functions and insert that before feeding the data to fast-import
3314 * (or equivalent in-core API described above). However, that is
3315 * somewhat complicated, as we do not know the size of the filter
3316 * result, which we need to know beforehand when writing a git object.
3317 * Since the primary motivation for trying to stream from the working
3318 * tree file and to avoid mmaping it in core is to deal with large
3319 * binary blobs, they generally do not want to get any conversion, and
3320 * callers should avoid this code path when filters are requested.
3322 static int index_stream(unsigned char *sha1
, int fd
, size_t size
,
3323 enum object_type type
, const char *path
,
3326 return index_bulk_checkin(sha1
, fd
, size
, type
, path
, flags
);
3329 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
,
3330 enum object_type type
, const char *path
, unsigned flags
)
3335 * Call xsize_t() only when needed to avoid potentially unnecessary
3336 * die() for large files.
3338 if (type
== OBJ_BLOB
&& path
&& would_convert_to_git_filter_fd(path
))
3339 ret
= index_stream_convert_blob(sha1
, fd
, path
, flags
);
3340 else if (!S_ISREG(st
->st_mode
))
3341 ret
= index_pipe(sha1
, fd
, type
, path
, flags
);
3342 else if (st
->st_size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
3343 (path
&& would_convert_to_git(&the_index
, path
)))
3344 ret
= index_core(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3347 ret
= index_stream(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3353 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, unsigned flags
)
3356 struct strbuf sb
= STRBUF_INIT
;
3358 switch (st
->st_mode
& S_IFMT
) {
3360 fd
= open(path
, O_RDONLY
);
3362 return error_errno("open(\"%s\")", path
);
3363 if (index_fd(sha1
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
3364 return error("%s: failed to insert into database",
3368 if (strbuf_readlink(&sb
, path
, st
->st_size
))
3369 return error_errno("readlink(\"%s\")", path
);
3370 if (!(flags
& HASH_WRITE_OBJECT
))
3371 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
3372 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
3373 return error("%s: failed to insert into database",
3375 strbuf_release(&sb
);
3378 return resolve_gitlink_ref(path
, "HEAD", sha1
);
3380 return error("%s: unsupported file type", path
);
3385 int read_pack_header(int fd
, struct pack_header
*header
)
3387 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
3388 /* "eof before pack header was fully read" */
3389 return PH_ERROR_EOF
;
3391 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
3392 /* "protocol error (pack signature mismatch detected)" */
3393 return PH_ERROR_PACK_SIGNATURE
;
3394 if (!pack_version_ok(header
->hdr_version
))
3395 /* "protocol error (pack version unsupported)" */
3396 return PH_ERROR_PROTOCOL
;
3400 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
3402 enum object_type type
= sha1_object_info(sha1
, NULL
);
3404 die("%s is not a valid object", sha1_to_hex(sha1
));
3406 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),
3410 int for_each_file_in_obj_subdir(unsigned int subdir_nr
,
3411 struct strbuf
*path
,
3412 each_loose_object_fn obj_cb
,
3413 each_loose_cruft_fn cruft_cb
,
3414 each_loose_subdir_fn subdir_cb
,
3417 size_t origlen
, baselen
;
3422 if (subdir_nr
> 0xff)
3423 BUG("invalid loose object subdirectory: %x", subdir_nr
);
3425 origlen
= path
->len
;
3426 strbuf_complete(path
, '/');
3427 strbuf_addf(path
, "%02x", subdir_nr
);
3428 baselen
= path
->len
;
3430 dir
= opendir(path
->buf
);
3432 if (errno
!= ENOENT
)
3433 r
= error_errno("unable to open %s", path
->buf
);
3434 strbuf_setlen(path
, origlen
);
3438 while ((de
= readdir(dir
))) {
3439 if (is_dot_or_dotdot(de
->d_name
))
3442 strbuf_setlen(path
, baselen
);
3443 strbuf_addf(path
, "/%s", de
->d_name
);
3445 if (strlen(de
->d_name
) == GIT_SHA1_HEXSZ
- 2) {
3446 char hex
[GIT_MAX_HEXSZ
+1];
3447 struct object_id oid
;
3449 xsnprintf(hex
, sizeof(hex
), "%02x%s",
3450 subdir_nr
, de
->d_name
);
3451 if (!get_oid_hex(hex
, &oid
)) {
3453 r
= obj_cb(&oid
, path
->buf
, data
);
3462 r
= cruft_cb(de
->d_name
, path
->buf
, data
);
3469 strbuf_setlen(path
, baselen
);
3470 if (!r
&& subdir_cb
)
3471 r
= subdir_cb(subdir_nr
, path
->buf
, data
);
3473 strbuf_setlen(path
, origlen
);
3478 int for_each_loose_file_in_objdir_buf(struct strbuf
*path
,
3479 each_loose_object_fn obj_cb
,
3480 each_loose_cruft_fn cruft_cb
,
3481 each_loose_subdir_fn subdir_cb
,
3487 for (i
= 0; i
< 256; i
++) {
3488 r
= for_each_file_in_obj_subdir(i
, path
, obj_cb
, cruft_cb
,
3497 int for_each_loose_file_in_objdir(const char *path
,
3498 each_loose_object_fn obj_cb
,
3499 each_loose_cruft_fn cruft_cb
,
3500 each_loose_subdir_fn subdir_cb
,
3503 struct strbuf buf
= STRBUF_INIT
;
3506 strbuf_addstr(&buf
, path
);
3507 r
= for_each_loose_file_in_objdir_buf(&buf
, obj_cb
, cruft_cb
,
3509 strbuf_release(&buf
);
3514 struct loose_alt_odb_data
{
3515 each_loose_object_fn
*cb
;
3519 static int loose_from_alt_odb(struct alternate_object_database
*alt
,
3522 struct loose_alt_odb_data
*data
= vdata
;
3523 struct strbuf buf
= STRBUF_INIT
;
3526 strbuf_addstr(&buf
, alt
->path
);
3527 r
= for_each_loose_file_in_objdir_buf(&buf
,
3528 data
->cb
, NULL
, NULL
,
3530 strbuf_release(&buf
);
3534 int for_each_loose_object(each_loose_object_fn cb
, void *data
, unsigned flags
)
3536 struct loose_alt_odb_data alt
;
3539 r
= for_each_loose_file_in_objdir(get_object_directory(),
3540 cb
, NULL
, NULL
, data
);
3544 if (flags
& FOR_EACH_OBJECT_LOCAL_ONLY
)
3549 return foreach_alt_odb(loose_from_alt_odb
, &alt
);
3552 static int for_each_object_in_pack(struct packed_git
*p
, each_packed_object_fn cb
, void *data
)
3557 for (i
= 0; i
< p
->num_objects
; i
++) {
3558 struct object_id oid
;
3560 if (!nth_packed_object_oid(&oid
, p
, i
))
3561 return error("unable to get sha1 of object %u in %s",
3564 r
= cb(&oid
, p
, i
, data
);
3571 int for_each_packed_object(each_packed_object_fn cb
, void *data
, unsigned flags
)
3573 struct packed_git
*p
;
3575 int pack_errors
= 0;
3577 prepare_packed_git();
3578 for (p
= packed_git
; p
; p
= p
->next
) {
3579 if ((flags
& FOR_EACH_OBJECT_LOCAL_ONLY
) && !p
->pack_local
)
3581 if (open_pack_index(p
)) {
3585 r
= for_each_object_in_pack(p
, cb
, data
);
3589 return r
? r
: pack_errors
;
3592 static int check_stream_sha1(git_zstream
*stream
,
3596 const unsigned char *expected_sha1
)
3599 unsigned char real_sha1
[GIT_MAX_RAWSZ
];
3600 unsigned char buf
[4096];
3601 unsigned long total_read
;
3605 git_SHA1_Update(&c
, hdr
, stream
->total_out
);
3608 * We already read some bytes into hdr, but the ones up to the NUL
3609 * do not count against the object's content size.
3611 total_read
= stream
->total_out
- strlen(hdr
) - 1;
3614 * This size comparison must be "<=" to read the final zlib packets;
3615 * see the comment in unpack_sha1_rest for details.
3617 while (total_read
<= size
&&
3618 (status
== Z_OK
|| status
== Z_BUF_ERROR
)) {
3619 stream
->next_out
= buf
;
3620 stream
->avail_out
= sizeof(buf
);
3621 if (size
- total_read
< stream
->avail_out
)
3622 stream
->avail_out
= size
- total_read
;
3623 status
= git_inflate(stream
, Z_FINISH
);
3624 git_SHA1_Update(&c
, buf
, stream
->next_out
- buf
);
3625 total_read
+= stream
->next_out
- buf
;
3627 git_inflate_end(stream
);
3629 if (status
!= Z_STREAM_END
) {
3630 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1
));
3633 if (stream
->avail_in
) {
3634 error("garbage at end of loose object '%s'",
3635 sha1_to_hex(expected_sha1
));
3639 git_SHA1_Final(real_sha1
, &c
);
3640 if (hashcmp(expected_sha1
, real_sha1
)) {
3641 error("sha1 mismatch for %s (expected %s)", path
,
3642 sha1_to_hex(expected_sha1
));
3649 int read_loose_object(const char *path
,
3650 const unsigned char *expected_sha1
,
3651 enum object_type
*type
,
3652 unsigned long *size
,
3657 unsigned long mapsize
;
3663 map
= map_sha1_file_1(path
, NULL
, &mapsize
);
3665 error_errno("unable to mmap %s", path
);
3669 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0) {
3670 error("unable to unpack header of %s", path
);
3674 *type
= parse_sha1_header(hdr
, size
);
3676 error("unable to parse header of %s", path
);
3677 git_inflate_end(&stream
);
3681 if (*type
== OBJ_BLOB
) {
3682 if (check_stream_sha1(&stream
, hdr
, *size
, path
, expected_sha1
) < 0)
3685 *contents
= unpack_sha1_rest(&stream
, hdr
, *size
, expected_sha1
);
3687 error("unable to unpack contents of %s", path
);
3688 git_inflate_end(&stream
);
3691 if (check_sha1_signature(expected_sha1
, *contents
,
3692 *size
, typename(*type
))) {
3693 error("sha1 mismatch for %s (expected %s)", path
,
3694 sha1_to_hex(expected_sha1
));
3700 ret
= 0; /* everything checks out */
3704 munmap(map
, mapsize
);