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");
722 void close_pack_windows(struct packed_git
*p
)
725 struct pack_window
*w
= p
->windows
;
728 die("pack '%s' still has open windows to it",
730 munmap(w
->base
, w
->len
);
731 pack_mapped
-= w
->len
;
733 p
->windows
= w
->next
;
738 static int close_pack_fd(struct packed_git
*p
)
750 static void close_pack(struct packed_git
*p
)
752 close_pack_windows(p
);
757 void close_all_packs(void)
759 struct packed_git
*p
;
761 for (p
= packed_git
; p
; p
= p
->next
)
763 die("BUG: want to close pack marked 'do-not-close'");
770 * The LRU pack is the one with the oldest MRU window, preferring packs
771 * with no used windows, or the oldest mtime if it has no windows allocated.
773 static void find_lru_pack(struct packed_git
*p
, struct packed_git
**lru_p
, struct pack_window
**mru_w
, int *accept_windows_inuse
)
775 struct pack_window
*w
, *this_mru_w
;
776 int has_windows_inuse
= 0;
779 * Reject this pack if it has windows and the previously selected
780 * one does not. If this pack does not have windows, reject
781 * it if the pack file is newer than the previously selected one.
783 if (*lru_p
&& !*mru_w
&& (p
->windows
|| p
->mtime
> (*lru_p
)->mtime
))
786 for (w
= this_mru_w
= p
->windows
; w
; w
= w
->next
) {
788 * Reject this pack if any of its windows are in use,
789 * but the previously selected pack did not have any
790 * inuse windows. Otherwise, record that this pack
791 * has windows in use.
794 if (*accept_windows_inuse
)
795 has_windows_inuse
= 1;
800 if (w
->last_used
> this_mru_w
->last_used
)
804 * Reject this pack if it has windows that have been
805 * used more recently than the previously selected pack.
806 * If the previously selected pack had windows inuse and
807 * we have not encountered a window in this pack that is
808 * inuse, skip this check since we prefer a pack with no
809 * inuse windows to one that has inuse windows.
811 if (*mru_w
&& *accept_windows_inuse
== has_windows_inuse
&&
812 this_mru_w
->last_used
> (*mru_w
)->last_used
)
821 *accept_windows_inuse
= has_windows_inuse
;
824 static int close_one_pack(void)
826 struct packed_git
*p
, *lru_p
= NULL
;
827 struct pack_window
*mru_w
= NULL
;
828 int accept_windows_inuse
= 1;
830 for (p
= packed_git
; p
; p
= p
->next
) {
831 if (p
->pack_fd
== -1)
833 find_lru_pack(p
, &lru_p
, &mru_w
, &accept_windows_inuse
);
837 return close_pack_fd(lru_p
);
842 void unuse_pack(struct pack_window
**w_cursor
)
844 struct pack_window
*w
= *w_cursor
;
851 void close_pack_index(struct packed_git
*p
)
854 munmap((void *)p
->index_data
, p
->index_size
);
855 p
->index_data
= NULL
;
859 static unsigned int get_max_fd_limit(void)
865 if (!getrlimit(RLIMIT_NOFILE
, &lim
))
872 long open_max
= sysconf(_SC_OPEN_MAX
);
876 * Otherwise, we got -1 for one of the two
879 * (1) sysconf() did not understand _SC_OPEN_MAX
880 * and signaled an error with -1; or
881 * (2) sysconf() said there is no limit.
883 * We _could_ clear errno before calling sysconf() to
884 * tell these two cases apart and return a huge number
885 * in the latter case to let the caller cap it to a
886 * value that is not so selfish, but letting the
887 * fallback OPEN_MAX codepath take care of these cases
896 return 1; /* see the caller ;-) */
901 * Do not call this directly as this leaks p->pack_fd on error return;
902 * call open_packed_git() instead.
904 static int open_packed_git_1(struct packed_git
*p
)
907 struct pack_header hdr
;
908 unsigned char sha1
[20];
909 unsigned char *idx_sha1
;
912 if (!p
->index_data
&& open_pack_index(p
))
913 return error("packfile %s index unavailable", p
->pack_name
);
916 unsigned int max_fds
= get_max_fd_limit();
918 /* Save 3 for stdin/stdout/stderr, 22 for work */
920 pack_max_fds
= max_fds
- 25;
925 while (pack_max_fds
<= pack_open_fds
&& close_one_pack())
928 p
->pack_fd
= git_open(p
->pack_name
);
929 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
933 /* If we created the struct before we had the pack we lack size. */
935 if (!S_ISREG(st
.st_mode
))
936 return error("packfile %s not a regular file", p
->pack_name
);
937 p
->pack_size
= st
.st_size
;
938 } else if (p
->pack_size
!= st
.st_size
)
939 return error("packfile %s size changed", p
->pack_name
);
941 /* We leave these file descriptors open with sliding mmap;
942 * there is no point keeping them open across exec(), though.
944 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
946 return error("cannot determine file descriptor flags");
947 fd_flag
|= FD_CLOEXEC
;
948 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
949 return error("cannot set FD_CLOEXEC");
951 /* Verify we recognize this pack file format. */
952 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
953 return error("file %s is far too short to be a packfile", p
->pack_name
);
954 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
955 return error("file %s is not a GIT packfile", p
->pack_name
);
956 if (!pack_version_ok(hdr
.hdr_version
))
957 return error("packfile %s is version %"PRIu32
" and not"
958 " supported (try upgrading GIT to a newer version)",
959 p
->pack_name
, ntohl(hdr
.hdr_version
));
961 /* Verify the pack matches its index. */
962 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
963 return error("packfile %s claims to have %"PRIu32
" objects"
964 " while index indicates %"PRIu32
" objects",
965 p
->pack_name
, ntohl(hdr
.hdr_entries
),
967 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
968 return error("end of packfile %s is unavailable", p
->pack_name
);
969 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
970 return error("packfile %s signature is unavailable", p
->pack_name
);
971 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
972 if (hashcmp(sha1
, idx_sha1
))
973 return error("packfile %s does not match index", p
->pack_name
);
977 static int open_packed_git(struct packed_git
*p
)
979 if (!open_packed_git_1(p
))
985 static int in_window(struct pack_window
*win
, off_t offset
)
987 /* We must promise at least 20 bytes (one hash) after the
988 * offset is available from this window, otherwise the offset
989 * is not actually in this window and a different window (which
990 * has that one hash excess) must be used. This is to support
991 * the object header and delta base parsing routines below.
993 off_t win_off
= win
->offset
;
994 return win_off
<= offset
995 && (offset
+ 20) <= (win_off
+ win
->len
);
998 unsigned char *use_pack(struct packed_git
*p
,
999 struct pack_window
**w_cursor
,
1001 unsigned long *left
)
1003 struct pack_window
*win
= *w_cursor
;
1005 /* Since packfiles end in a hash of their content and it's
1006 * pointless to ask for an offset into the middle of that
1007 * hash, and the in_window function above wouldn't match
1008 * don't allow an offset too close to the end of the file.
1010 if (!p
->pack_size
&& p
->pack_fd
== -1 && open_packed_git(p
))
1011 die("packfile %s cannot be accessed", p
->pack_name
);
1012 if (offset
> (p
->pack_size
- 20))
1013 die("offset beyond end of packfile (truncated pack?)");
1015 die(_("offset before end of packfile (broken .idx?)"));
1017 if (!win
|| !in_window(win
, offset
)) {
1020 for (win
= p
->windows
; win
; win
= win
->next
) {
1021 if (in_window(win
, offset
))
1025 size_t window_align
= packed_git_window_size
/ 2;
1028 if (p
->pack_fd
== -1 && open_packed_git(p
))
1029 die("packfile %s cannot be accessed", p
->pack_name
);
1031 win
= xcalloc(1, sizeof(*win
));
1032 win
->offset
= (offset
/ window_align
) * window_align
;
1033 len
= p
->pack_size
- win
->offset
;
1034 if (len
> packed_git_window_size
)
1035 len
= packed_git_window_size
;
1036 win
->len
= (size_t)len
;
1037 pack_mapped
+= win
->len
;
1038 while (packed_git_limit
< pack_mapped
1039 && unuse_one_window(p
))
1041 win
->base
= xmmap(NULL
, win
->len
,
1042 PROT_READ
, MAP_PRIVATE
,
1043 p
->pack_fd
, win
->offset
);
1044 if (win
->base
== MAP_FAILED
)
1045 die_errno("packfile %s cannot be mapped",
1047 if (!win
->offset
&& win
->len
== p
->pack_size
1048 && !p
->do_not_close
)
1051 pack_open_windows
++;
1052 if (pack_mapped
> peak_pack_mapped
)
1053 peak_pack_mapped
= pack_mapped
;
1054 if (pack_open_windows
> peak_pack_open_windows
)
1055 peak_pack_open_windows
= pack_open_windows
;
1056 win
->next
= p
->windows
;
1060 if (win
!= *w_cursor
) {
1061 win
->last_used
= pack_used_ctr
++;
1065 offset
-= win
->offset
;
1067 *left
= win
->len
- xsize_t(offset
);
1068 return win
->base
+ offset
;
1071 static struct packed_git
*alloc_packed_git(int extra
)
1073 struct packed_git
*p
= xmalloc(st_add(sizeof(*p
), extra
));
1074 memset(p
, 0, sizeof(*p
));
1079 static void try_to_free_pack_memory(size_t size
)
1081 release_pack_memory(size
);
1084 struct packed_git
*add_packed_git(const char *path
, size_t path_len
, int local
)
1086 static int have_set_try_to_free_routine
;
1089 struct packed_git
*p
;
1091 if (!have_set_try_to_free_routine
) {
1092 have_set_try_to_free_routine
= 1;
1093 set_try_to_free_routine(try_to_free_pack_memory
);
1097 * Make sure a corresponding .pack file exists and that
1098 * the index looks sane.
1100 if (!strip_suffix_mem(path
, &path_len
, ".idx"))
1104 * ".pack" is long enough to hold any suffix we're adding (and
1105 * the use xsnprintf double-checks that)
1107 alloc
= st_add3(path_len
, strlen(".pack"), 1);
1108 p
= alloc_packed_git(alloc
);
1109 memcpy(p
->pack_name
, path
, path_len
);
1111 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".keep");
1112 if (!access(p
->pack_name
, F_OK
))
1115 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".pack");
1116 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
1121 /* ok, it looks sane as far as we can check without
1122 * actually mapping the pack file.
1124 p
->pack_size
= st
.st_size
;
1125 p
->pack_local
= local
;
1126 p
->mtime
= st
.st_mtime
;
1127 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
1132 void install_packed_git(struct packed_git
*pack
)
1134 if (pack
->pack_fd
!= -1)
1137 pack
->next
= packed_git
;
1141 void (*report_garbage
)(unsigned seen_bits
, const char *path
);
1143 static void report_helper(const struct string_list
*list
,
1144 int seen_bits
, int first
, int last
)
1146 if (seen_bits
== (PACKDIR_FILE_PACK
|PACKDIR_FILE_IDX
))
1149 for (; first
< last
; first
++)
1150 report_garbage(seen_bits
, list
->items
[first
].string
);
1153 static void report_pack_garbage(struct string_list
*list
)
1155 int i
, baselen
= -1, first
= 0, seen_bits
= 0;
1157 if (!report_garbage
)
1160 string_list_sort(list
);
1162 for (i
= 0; i
< list
->nr
; i
++) {
1163 const char *path
= list
->items
[i
].string
;
1164 if (baselen
!= -1 &&
1165 strncmp(path
, list
->items
[first
].string
, baselen
)) {
1166 report_helper(list
, seen_bits
, first
, i
);
1170 if (baselen
== -1) {
1171 const char *dot
= strrchr(path
, '.');
1173 report_garbage(PACKDIR_FILE_GARBAGE
, path
);
1176 baselen
= dot
- path
+ 1;
1179 if (!strcmp(path
+ baselen
, "pack"))
1181 else if (!strcmp(path
+ baselen
, "idx"))
1184 report_helper(list
, seen_bits
, first
, list
->nr
);
1187 static void prepare_packed_git_one(char *objdir
, int local
)
1189 struct strbuf path
= STRBUF_INIT
;
1193 struct string_list garbage
= STRING_LIST_INIT_DUP
;
1195 strbuf_addstr(&path
, objdir
);
1196 strbuf_addstr(&path
, "/pack");
1197 dir
= opendir(path
.buf
);
1199 if (errno
!= ENOENT
)
1200 error_errno("unable to open object pack directory: %s",
1202 strbuf_release(&path
);
1205 strbuf_addch(&path
, '/');
1206 dirnamelen
= path
.len
;
1207 while ((de
= readdir(dir
)) != NULL
) {
1208 struct packed_git
*p
;
1211 if (is_dot_or_dotdot(de
->d_name
))
1214 strbuf_setlen(&path
, dirnamelen
);
1215 strbuf_addstr(&path
, de
->d_name
);
1217 base_len
= path
.len
;
1218 if (strip_suffix_mem(path
.buf
, &base_len
, ".idx")) {
1219 /* Don't reopen a pack we already have. */
1220 for (p
= packed_git
; p
; p
= p
->next
) {
1222 if (strip_suffix(p
->pack_name
, ".pack", &len
) &&
1224 !memcmp(p
->pack_name
, path
.buf
, len
))
1229 * See if it really is a valid .idx file with
1230 * corresponding .pack file that we can map.
1232 (p
= add_packed_git(path
.buf
, path
.len
, local
)) != NULL
)
1233 install_packed_git(p
);
1236 if (!report_garbage
)
1239 if (ends_with(de
->d_name
, ".idx") ||
1240 ends_with(de
->d_name
, ".pack") ||
1241 ends_with(de
->d_name
, ".bitmap") ||
1242 ends_with(de
->d_name
, ".keep"))
1243 string_list_append(&garbage
, path
.buf
);
1245 report_garbage(PACKDIR_FILE_GARBAGE
, path
.buf
);
1248 report_pack_garbage(&garbage
);
1249 string_list_clear(&garbage
, 0);
1250 strbuf_release(&path
);
1253 static int approximate_object_count_valid
;
1256 * Give a fast, rough count of the number of objects in the repository. This
1257 * ignores loose objects completely. If you have a lot of them, then either
1258 * you should repack because your performance will be awful, or they are
1259 * all unreachable objects about to be pruned, in which case they're not really
1260 * interesting as a measure of repo size in the first place.
1262 unsigned long approximate_object_count(void)
1264 static unsigned long count
;
1265 if (!approximate_object_count_valid
) {
1266 struct packed_git
*p
;
1268 prepare_packed_git();
1270 for (p
= packed_git
; p
; p
= p
->next
) {
1271 if (open_pack_index(p
))
1273 count
+= p
->num_objects
;
1279 static void *get_next_packed_git(const void *p
)
1281 return ((const struct packed_git
*)p
)->next
;
1284 static void set_next_packed_git(void *p
, void *next
)
1286 ((struct packed_git
*)p
)->next
= next
;
1289 static int sort_pack(const void *a_
, const void *b_
)
1291 const struct packed_git
*a
= a_
;
1292 const struct packed_git
*b
= b_
;
1296 * Local packs tend to contain objects specific to our
1297 * variant of the project than remote ones. In addition,
1298 * remote ones could be on a network mounted filesystem.
1299 * Favor local ones for these reasons.
1301 st
= a
->pack_local
- b
->pack_local
;
1306 * Younger packs tend to contain more recent objects,
1307 * and more recent objects tend to get accessed more
1310 if (a
->mtime
< b
->mtime
)
1312 else if (a
->mtime
== b
->mtime
)
1317 static void rearrange_packed_git(void)
1319 packed_git
= llist_mergesort(packed_git
, get_next_packed_git
,
1320 set_next_packed_git
, sort_pack
);
1323 static void prepare_packed_git_mru(void)
1325 struct packed_git
*p
;
1327 mru_clear(packed_git_mru
);
1328 for (p
= packed_git
; p
; p
= p
->next
)
1329 mru_append(packed_git_mru
, p
);
1332 static int prepare_packed_git_run_once
= 0;
1333 void prepare_packed_git(void)
1335 struct alternate_object_database
*alt
;
1337 if (prepare_packed_git_run_once
)
1339 prepare_packed_git_one(get_object_directory(), 1);
1341 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
)
1342 prepare_packed_git_one(alt
->path
, 0);
1343 rearrange_packed_git();
1344 prepare_packed_git_mru();
1345 prepare_packed_git_run_once
= 1;
1348 void reprepare_packed_git(void)
1350 approximate_object_count_valid
= 0;
1351 prepare_packed_git_run_once
= 0;
1352 prepare_packed_git();
1355 static void mark_bad_packed_object(struct packed_git
*p
,
1356 const unsigned char *sha1
)
1359 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1360 if (!hashcmp(sha1
, p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* i
))
1362 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
,
1363 st_mult(GIT_MAX_RAWSZ
,
1364 st_add(p
->num_bad_objects
, 1)));
1365 hashcpy(p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* p
->num_bad_objects
, sha1
);
1366 p
->num_bad_objects
++;
1369 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1371 struct packed_git
*p
;
1374 for (p
= packed_git
; p
; p
= p
->next
)
1375 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1376 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1382 * With an in-core object data in "map", rehash it to make sure the
1383 * object name actually matches "sha1" to detect object corruption.
1384 * With "map" == NULL, try reading the object named with "sha1" using
1385 * the streaming interface and rehash it to do the same.
1387 int check_sha1_signature(const unsigned char *sha1
, void *map
,
1388 unsigned long size
, const char *type
)
1390 unsigned char real_sha1
[20];
1391 enum object_type obj_type
;
1392 struct git_istream
*st
;
1398 hash_sha1_file(map
, size
, type
, real_sha1
);
1399 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1402 st
= open_istream(sha1
, &obj_type
, &size
, NULL
);
1406 /* Generate the header */
1407 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(obj_type
), size
) + 1;
1411 git_SHA1_Update(&c
, hdr
, hdrlen
);
1413 char buf
[1024 * 16];
1414 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
1422 git_SHA1_Update(&c
, buf
, readlen
);
1424 git_SHA1_Final(real_sha1
, &c
);
1426 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1429 int git_open_cloexec(const char *name
, int flags
)
1432 static int o_cloexec
= O_CLOEXEC
;
1434 fd
= open(name
, flags
| o_cloexec
);
1435 if ((o_cloexec
& O_CLOEXEC
) && fd
< 0 && errno
== EINVAL
) {
1436 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1437 o_cloexec
&= ~O_CLOEXEC
;
1438 fd
= open(name
, flags
| o_cloexec
);
1441 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1443 static int fd_cloexec
= FD_CLOEXEC
;
1445 if (!o_cloexec
&& 0 <= fd
&& fd_cloexec
) {
1446 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1447 int flags
= fcntl(fd
, F_GETFD
);
1448 if (fcntl(fd
, F_SETFD
, flags
| fd_cloexec
))
1457 * Find "sha1" as a loose object in the local repository or in an alternate.
1458 * Returns 0 on success, negative on failure.
1460 * The "path" out-parameter will give the path of the object we found (if any).
1461 * Note that it may point to static storage and is only valid until another
1462 * call to sha1_file_name(), etc.
1464 static int stat_sha1_file(const unsigned char *sha1
, struct stat
*st
,
1467 struct alternate_object_database
*alt
;
1469 *path
= sha1_file_name(sha1
);
1470 if (!lstat(*path
, st
))
1475 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1476 *path
= alt_sha1_path(alt
, sha1
);
1477 if (!lstat(*path
, st
))
1485 * Like stat_sha1_file(), but actually open the object and return the
1486 * descriptor. See the caveats on the "path" parameter above.
1488 static int open_sha1_file(const unsigned char *sha1
, const char **path
)
1491 struct alternate_object_database
*alt
;
1492 int most_interesting_errno
;
1494 *path
= sha1_file_name(sha1
);
1495 fd
= git_open(*path
);
1498 most_interesting_errno
= errno
;
1501 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1502 *path
= alt_sha1_path(alt
, sha1
);
1503 fd
= git_open(*path
);
1506 if (most_interesting_errno
== ENOENT
)
1507 most_interesting_errno
= errno
;
1509 errno
= most_interesting_errno
;
1514 * Map the loose object at "path" if it is not NULL, or the path found by
1515 * searching for a loose object named "sha1".
1517 static void *map_sha1_file_1(const char *path
,
1518 const unsigned char *sha1
,
1519 unsigned long *size
)
1525 fd
= git_open(path
);
1527 fd
= open_sha1_file(sha1
, &path
);
1532 if (!fstat(fd
, &st
)) {
1533 *size
= xsize_t(st
.st_size
);
1535 /* mmap() is forbidden on empty files */
1536 error("object file %s is empty", path
);
1539 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1546 void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1548 return map_sha1_file_1(NULL
, sha1
, size
);
1551 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1552 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1555 unsigned long size
, c
;
1556 unsigned long used
= 0;
1559 *type
= (c
>> 4) & 7;
1563 if (len
<= used
|| bitsizeof(long) <= shift
) {
1564 error("bad object header");
1569 size
+= (c
& 0x7f) << shift
;
1576 static int unpack_sha1_short_header(git_zstream
*stream
,
1577 unsigned char *map
, unsigned long mapsize
,
1578 void *buffer
, unsigned long bufsiz
)
1580 /* Get the data stream */
1581 memset(stream
, 0, sizeof(*stream
));
1582 stream
->next_in
= map
;
1583 stream
->avail_in
= mapsize
;
1584 stream
->next_out
= buffer
;
1585 stream
->avail_out
= bufsiz
;
1587 git_inflate_init(stream
);
1588 return git_inflate(stream
, 0);
1591 int unpack_sha1_header(git_zstream
*stream
,
1592 unsigned char *map
, unsigned long mapsize
,
1593 void *buffer
, unsigned long bufsiz
)
1595 int status
= unpack_sha1_short_header(stream
, map
, mapsize
,
1601 /* Make sure we have the terminating NUL */
1602 if (!memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1607 static int unpack_sha1_header_to_strbuf(git_zstream
*stream
, unsigned char *map
,
1608 unsigned long mapsize
, void *buffer
,
1609 unsigned long bufsiz
, struct strbuf
*header
)
1613 status
= unpack_sha1_short_header(stream
, map
, mapsize
, buffer
, bufsiz
);
1618 * Check if entire header is unpacked in the first iteration.
1620 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1624 * buffer[0..bufsiz] was not large enough. Copy the partial
1625 * result out to header, and then append the result of further
1626 * reading the stream.
1628 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1629 stream
->next_out
= buffer
;
1630 stream
->avail_out
= bufsiz
;
1633 status
= git_inflate(stream
, 0);
1634 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1635 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1637 stream
->next_out
= buffer
;
1638 stream
->avail_out
= bufsiz
;
1639 } while (status
!= Z_STREAM_END
);
1643 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1645 int bytes
= strlen(buffer
) + 1;
1646 unsigned char *buf
= xmallocz(size
);
1650 n
= stream
->total_out
- bytes
;
1653 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1655 if (bytes
<= size
) {
1657 * The above condition must be (bytes <= size), not
1658 * (bytes < size). In other words, even though we
1659 * expect no more output and set avail_out to zero,
1660 * the input zlib stream may have bytes that express
1661 * "this concludes the stream", and we *do* want to
1664 * Otherwise we would not be able to test that we
1665 * consumed all the input to reach the expected size;
1666 * we also want to check that zlib tells us that all
1667 * went well with status == Z_STREAM_END at the end.
1669 stream
->next_out
= buf
+ bytes
;
1670 stream
->avail_out
= size
- bytes
;
1671 while (status
== Z_OK
)
1672 status
= git_inflate(stream
, Z_FINISH
);
1674 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1675 git_inflate_end(stream
);
1680 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1681 else if (stream
->avail_in
)
1682 error("garbage at end of loose object '%s'",
1689 * We used to just use "sscanf()", but that's actually way
1690 * too permissive for what we want to check. So do an anal
1691 * object header parse by hand.
1693 static int parse_sha1_header_extended(const char *hdr
, struct object_info
*oi
,
1696 const char *type_buf
= hdr
;
1698 int type
, type_len
= 0;
1701 * The type can be of any size but is followed by
1713 type
= type_from_string_gently(type_buf
, type_len
, 1);
1715 strbuf_add(oi
->typename
, type_buf
, type_len
);
1717 * Set type to 0 if its an unknown object and
1718 * we're obtaining the type using '--allow-unknown-type'
1721 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
) && (type
< 0))
1724 die("invalid object type");
1729 * The length must follow immediately, and be in canonical
1730 * decimal format (ie "010" is not valid).
1732 size
= *hdr
++ - '0';
1737 unsigned long c
= *hdr
- '0';
1741 size
= size
* 10 + c
;
1749 * The length must be followed by a zero byte
1751 return *hdr
? -1 : type
;
1754 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1756 struct object_info oi
= OBJECT_INFO_INIT
;
1759 return parse_sha1_header_extended(hdr
, &oi
, 0);
1762 unsigned long get_size_from_delta(struct packed_git
*p
,
1763 struct pack_window
**w_curs
,
1766 const unsigned char *data
;
1767 unsigned char delta_head
[20], *in
;
1771 memset(&stream
, 0, sizeof(stream
));
1772 stream
.next_out
= delta_head
;
1773 stream
.avail_out
= sizeof(delta_head
);
1775 git_inflate_init(&stream
);
1777 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1778 stream
.next_in
= in
;
1779 st
= git_inflate(&stream
, Z_FINISH
);
1780 curpos
+= stream
.next_in
- in
;
1781 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
1782 stream
.total_out
< sizeof(delta_head
));
1783 git_inflate_end(&stream
);
1784 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
1785 error("delta data unpack-initial failed");
1789 /* Examine the initial part of the delta to figure out
1794 /* ignore base size */
1795 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1797 /* Read the result size */
1798 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1801 static off_t
get_delta_base(struct packed_git
*p
,
1802 struct pack_window
**w_curs
,
1804 enum object_type type
,
1805 off_t delta_obj_offset
)
1807 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
1810 /* use_pack() assured us we have [base_info, base_info + 20)
1811 * as a range that we can look at without walking off the
1812 * end of the mapped window. Its actually the hash size
1813 * that is assured. An OFS_DELTA longer than the hash size
1814 * is stupid, as then a REF_DELTA would be smaller to store.
1816 if (type
== OBJ_OFS_DELTA
) {
1818 unsigned char c
= base_info
[used
++];
1819 base_offset
= c
& 127;
1822 if (!base_offset
|| MSB(base_offset
, 7))
1823 return 0; /* overflow */
1824 c
= base_info
[used
++];
1825 base_offset
= (base_offset
<< 7) + (c
& 127);
1827 base_offset
= delta_obj_offset
- base_offset
;
1828 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
1829 return 0; /* out of bound */
1831 } else if (type
== OBJ_REF_DELTA
) {
1832 /* The base entry _must_ be in the same pack */
1833 base_offset
= find_pack_entry_one(base_info
, p
);
1836 die("I am totally screwed");
1841 * Like get_delta_base above, but we return the sha1 instead of the pack
1842 * offset. This means it is cheaper for REF deltas (we do not have to do
1843 * the final object lookup), but more expensive for OFS deltas (we
1844 * have to load the revidx to convert the offset back into a sha1).
1846 static const unsigned char *get_delta_base_sha1(struct packed_git
*p
,
1847 struct pack_window
**w_curs
,
1849 enum object_type type
,
1850 off_t delta_obj_offset
)
1852 if (type
== OBJ_REF_DELTA
) {
1853 unsigned char *base
= use_pack(p
, w_curs
, curpos
, NULL
);
1855 } else if (type
== OBJ_OFS_DELTA
) {
1856 struct revindex_entry
*revidx
;
1857 off_t base_offset
= get_delta_base(p
, w_curs
, &curpos
,
1858 type
, delta_obj_offset
);
1863 revidx
= find_pack_revindex(p
, base_offset
);
1867 return nth_packed_object_sha1(p
, revidx
->nr
);
1872 int unpack_object_header(struct packed_git
*p
,
1873 struct pack_window
**w_curs
,
1875 unsigned long *sizep
)
1877 unsigned char *base
;
1880 enum object_type type
;
1882 /* use_pack() assures us we have [base, base + 20) available
1883 * as a range that we can look at. (Its actually the hash
1884 * size that is assured.) With our object header encoding
1885 * the maximum deflated object size is 2^137, which is just
1886 * insane, so we know won't exceed what we have been given.
1888 base
= use_pack(p
, w_curs
, *curpos
, &left
);
1889 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
1898 static int retry_bad_packed_offset(struct packed_git
*p
, off_t obj_offset
)
1901 struct revindex_entry
*revidx
;
1902 const unsigned char *sha1
;
1903 revidx
= find_pack_revindex(p
, obj_offset
);
1906 sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1907 mark_bad_packed_object(p
, sha1
);
1908 type
= sha1_object_info(sha1
, NULL
);
1909 if (type
<= OBJ_NONE
)
1914 #define POI_STACK_PREALLOC 64
1916 static enum object_type
packed_to_object_type(struct packed_git
*p
,
1918 enum object_type type
,
1919 struct pack_window
**w_curs
,
1922 off_t small_poi_stack
[POI_STACK_PREALLOC
];
1923 off_t
*poi_stack
= small_poi_stack
;
1924 int poi_stack_nr
= 0, poi_stack_alloc
= POI_STACK_PREALLOC
;
1926 while (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1929 /* Push the object we're going to leave behind */
1930 if (poi_stack_nr
>= poi_stack_alloc
&& poi_stack
== small_poi_stack
) {
1931 poi_stack_alloc
= alloc_nr(poi_stack_nr
);
1932 ALLOC_ARRAY(poi_stack
, poi_stack_alloc
);
1933 memcpy(poi_stack
, small_poi_stack
, sizeof(off_t
)*poi_stack_nr
);
1935 ALLOC_GROW(poi_stack
, poi_stack_nr
+1, poi_stack_alloc
);
1937 poi_stack
[poi_stack_nr
++] = obj_offset
;
1938 /* If parsing the base offset fails, just unwind */
1939 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
1942 curpos
= obj_offset
= base_offset
;
1943 type
= unpack_object_header(p
, w_curs
, &curpos
, &size
);
1944 if (type
<= OBJ_NONE
) {
1945 /* If getting the base itself fails, we first
1946 * retry the base, otherwise unwind */
1947 type
= retry_bad_packed_offset(p
, base_offset
);
1948 if (type
> OBJ_NONE
)
1962 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1963 type
, (uintmax_t)obj_offset
, p
->pack_name
);
1968 if (poi_stack
!= small_poi_stack
)
1973 while (poi_stack_nr
) {
1974 obj_offset
= poi_stack
[--poi_stack_nr
];
1975 type
= retry_bad_packed_offset(p
, obj_offset
);
1976 if (type
> OBJ_NONE
)
1983 static struct hashmap delta_base_cache
;
1984 static size_t delta_base_cached
;
1986 static LIST_HEAD(delta_base_cache_lru
);
1988 struct delta_base_cache_key
{
1989 struct packed_git
*p
;
1993 struct delta_base_cache_entry
{
1994 struct hashmap hash
;
1995 struct delta_base_cache_key key
;
1996 struct list_head lru
;
1999 enum object_type type
;
2002 static unsigned int pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
2006 hash
= (unsigned int)(intptr_t)p
+ (unsigned int)base_offset
;
2007 hash
+= (hash
>> 8) + (hash
>> 16);
2011 static struct delta_base_cache_entry
*
2012 get_delta_base_cache_entry(struct packed_git
*p
, off_t base_offset
)
2014 struct hashmap_entry entry
;
2015 struct delta_base_cache_key key
;
2017 if (!delta_base_cache
.cmpfn
)
2020 hashmap_entry_init(&entry
, pack_entry_hash(p
, base_offset
));
2022 key
.base_offset
= base_offset
;
2023 return hashmap_get(&delta_base_cache
, &entry
, &key
);
2026 static int delta_base_cache_key_eq(const struct delta_base_cache_key
*a
,
2027 const struct delta_base_cache_key
*b
)
2029 return a
->p
== b
->p
&& a
->base_offset
== b
->base_offset
;
2032 static int delta_base_cache_hash_cmp(const void *unused_cmp_data
,
2033 const void *va
, const void *vb
,
2036 const struct delta_base_cache_entry
*a
= va
, *b
= vb
;
2037 const struct delta_base_cache_key
*key
= vkey
;
2039 return !delta_base_cache_key_eq(&a
->key
, key
);
2041 return !delta_base_cache_key_eq(&a
->key
, &b
->key
);
2044 static int in_delta_base_cache(struct packed_git
*p
, off_t base_offset
)
2046 return !!get_delta_base_cache_entry(p
, base_offset
);
2050 * Remove the entry from the cache, but do _not_ free the associated
2051 * entry data. The caller takes ownership of the "data" buffer, and
2052 * should copy out any fields it wants before detaching.
2054 static void detach_delta_base_cache_entry(struct delta_base_cache_entry
*ent
)
2056 hashmap_remove(&delta_base_cache
, ent
, &ent
->key
);
2057 list_del(&ent
->lru
);
2058 delta_base_cached
-= ent
->size
;
2062 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
2063 unsigned long *base_size
, enum object_type
*type
)
2065 struct delta_base_cache_entry
*ent
;
2067 ent
= get_delta_base_cache_entry(p
, base_offset
);
2069 return unpack_entry(p
, base_offset
, type
, base_size
);
2074 *base_size
= ent
->size
;
2075 return xmemdupz(ent
->data
, ent
->size
);
2078 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
2081 detach_delta_base_cache_entry(ent
);
2084 void clear_delta_base_cache(void)
2086 struct list_head
*lru
, *tmp
;
2087 list_for_each_safe(lru
, tmp
, &delta_base_cache_lru
) {
2088 struct delta_base_cache_entry
*entry
=
2089 list_entry(lru
, struct delta_base_cache_entry
, lru
);
2090 release_delta_base_cache(entry
);
2094 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
2095 void *base
, unsigned long base_size
, enum object_type type
)
2097 struct delta_base_cache_entry
*ent
= xmalloc(sizeof(*ent
));
2098 struct list_head
*lru
, *tmp
;
2100 delta_base_cached
+= base_size
;
2102 list_for_each_safe(lru
, tmp
, &delta_base_cache_lru
) {
2103 struct delta_base_cache_entry
*f
=
2104 list_entry(lru
, struct delta_base_cache_entry
, lru
);
2105 if (delta_base_cached
<= delta_base_cache_limit
)
2107 release_delta_base_cache(f
);
2111 ent
->key
.base_offset
= base_offset
;
2114 ent
->size
= base_size
;
2115 list_add_tail(&ent
->lru
, &delta_base_cache_lru
);
2117 if (!delta_base_cache
.cmpfn
)
2118 hashmap_init(&delta_base_cache
, delta_base_cache_hash_cmp
, NULL
, 0);
2119 hashmap_entry_init(ent
, pack_entry_hash(p
, base_offset
));
2120 hashmap_add(&delta_base_cache
, ent
);
2123 int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
2124 struct object_info
*oi
)
2126 struct pack_window
*w_curs
= NULL
;
2128 off_t curpos
= obj_offset
;
2129 enum object_type type
;
2132 * We always get the representation type, but only convert it to
2133 * a "real" type later if the caller is interested.
2136 *oi
->contentp
= cache_or_unpack_entry(p
, obj_offset
, oi
->sizep
,
2141 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2144 if (!oi
->contentp
&& oi
->sizep
) {
2145 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2146 off_t tmp_pos
= curpos
;
2147 off_t base_offset
= get_delta_base(p
, &w_curs
, &tmp_pos
,
2153 *oi
->sizep
= get_size_from_delta(p
, &w_curs
, tmp_pos
);
2154 if (*oi
->sizep
== 0) {
2163 if (oi
->disk_sizep
) {
2164 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2165 *oi
->disk_sizep
= revidx
[1].offset
- obj_offset
;
2168 if (oi
->typep
|| oi
->typename
) {
2169 enum object_type ptot
;
2170 ptot
= packed_to_object_type(p
, obj_offset
, type
, &w_curs
,
2175 const char *tn
= typename(ptot
);
2177 strbuf_addstr(oi
->typename
, tn
);
2185 if (oi
->delta_base_sha1
) {
2186 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2187 const unsigned char *base
;
2189 base
= get_delta_base_sha1(p
, &w_curs
, curpos
,
2196 hashcpy(oi
->delta_base_sha1
, base
);
2198 hashclr(oi
->delta_base_sha1
);
2201 oi
->whence
= in_delta_base_cache(p
, obj_offset
) ? OI_DBCACHED
:
2205 unuse_pack(&w_curs
);
2209 static void *unpack_compressed_entry(struct packed_git
*p
,
2210 struct pack_window
**w_curs
,
2216 unsigned char *buffer
, *in
;
2218 buffer
= xmallocz_gently(size
);
2221 memset(&stream
, 0, sizeof(stream
));
2222 stream
.next_out
= buffer
;
2223 stream
.avail_out
= size
+ 1;
2225 git_inflate_init(&stream
);
2227 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
2228 stream
.next_in
= in
;
2229 st
= git_inflate(&stream
, Z_FINISH
);
2230 if (!stream
.avail_out
)
2231 break; /* the payload is larger than it should be */
2232 curpos
+= stream
.next_in
- in
;
2233 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
2234 git_inflate_end(&stream
);
2235 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
2243 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2244 unsigned long *size
);
2246 static void write_pack_access_log(struct packed_git
*p
, off_t obj_offset
)
2248 static struct trace_key pack_access
= TRACE_KEY_INIT(PACK_ACCESS
);
2249 trace_printf_key(&pack_access
, "%s %"PRIuMAX
"\n",
2250 p
->pack_name
, (uintmax_t)obj_offset
);
2253 int do_check_packed_object_crc
;
2255 #define UNPACK_ENTRY_STACK_PREALLOC 64
2256 struct unpack_entry_stack_ent
{
2262 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
2263 enum object_type
*final_type
, unsigned long *final_size
)
2265 struct pack_window
*w_curs
= NULL
;
2266 off_t curpos
= obj_offset
;
2269 enum object_type type
;
2270 struct unpack_entry_stack_ent small_delta_stack
[UNPACK_ENTRY_STACK_PREALLOC
];
2271 struct unpack_entry_stack_ent
*delta_stack
= small_delta_stack
;
2272 int delta_stack_nr
= 0, delta_stack_alloc
= UNPACK_ENTRY_STACK_PREALLOC
;
2273 int base_from_cache
= 0;
2275 write_pack_access_log(p
, obj_offset
);
2277 /* PHASE 1: drill down to the innermost base object */
2281 struct delta_base_cache_entry
*ent
;
2283 ent
= get_delta_base_cache_entry(p
, curpos
);
2288 detach_delta_base_cache_entry(ent
);
2289 base_from_cache
= 1;
2293 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
2294 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2295 off_t len
= revidx
[1].offset
- obj_offset
;
2296 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
2297 const unsigned char *sha1
=
2298 nth_packed_object_sha1(p
, revidx
->nr
);
2299 error("bad packed object CRC for %s",
2301 mark_bad_packed_object(p
, sha1
);
2307 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2308 if (type
!= OBJ_OFS_DELTA
&& type
!= OBJ_REF_DELTA
)
2311 base_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
2313 error("failed to validate delta base reference "
2314 "at offset %"PRIuMAX
" from %s",
2315 (uintmax_t)curpos
, p
->pack_name
);
2316 /* bail to phase 2, in hopes of recovery */
2321 /* push object, proceed to base */
2322 if (delta_stack_nr
>= delta_stack_alloc
2323 && delta_stack
== small_delta_stack
) {
2324 delta_stack_alloc
= alloc_nr(delta_stack_nr
);
2325 ALLOC_ARRAY(delta_stack
, delta_stack_alloc
);
2326 memcpy(delta_stack
, small_delta_stack
,
2327 sizeof(*delta_stack
)*delta_stack_nr
);
2329 ALLOC_GROW(delta_stack
, delta_stack_nr
+1, delta_stack_alloc
);
2331 i
= delta_stack_nr
++;
2332 delta_stack
[i
].obj_offset
= obj_offset
;
2333 delta_stack
[i
].curpos
= curpos
;
2334 delta_stack
[i
].size
= size
;
2336 curpos
= obj_offset
= base_offset
;
2339 /* PHASE 2: handle the base */
2344 die("BUG: unpack_entry: left loop at a valid delta");
2350 if (!base_from_cache
)
2351 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, size
);
2355 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2356 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2359 /* PHASE 3: apply deltas in order */
2362 * 'data' holds the base data, or NULL if there was corruption
2364 while (delta_stack_nr
) {
2367 void *external_base
= NULL
;
2368 unsigned long delta_size
, base_size
= size
;
2374 add_delta_base_cache(p
, obj_offset
, base
, base_size
, type
);
2378 * We're probably in deep shit, but let's try to fetch
2379 * the required base anyway from another pack or loose.
2380 * This is costly but should happen only in the presence
2381 * of a corrupted pack, and is better than failing outright.
2383 struct revindex_entry
*revidx
;
2384 const unsigned char *base_sha1
;
2385 revidx
= find_pack_revindex(p
, obj_offset
);
2387 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2388 error("failed to read delta base object %s"
2389 " at offset %"PRIuMAX
" from %s",
2390 sha1_to_hex(base_sha1
), (uintmax_t)obj_offset
,
2392 mark_bad_packed_object(p
, base_sha1
);
2393 base
= read_object(base_sha1
, &type
, &base_size
);
2394 external_base
= base
;
2398 i
= --delta_stack_nr
;
2399 obj_offset
= delta_stack
[i
].obj_offset
;
2400 curpos
= delta_stack
[i
].curpos
;
2401 delta_size
= delta_stack
[i
].size
;
2406 delta_data
= unpack_compressed_entry(p
, &w_curs
, curpos
, delta_size
);
2409 error("failed to unpack compressed delta "
2410 "at offset %"PRIuMAX
" from %s",
2411 (uintmax_t)curpos
, p
->pack_name
);
2413 free(external_base
);
2417 data
= patch_delta(base
, base_size
,
2418 delta_data
, delta_size
,
2422 * We could not apply the delta; warn the user, but keep going.
2423 * Our failure will be noticed either in the next iteration of
2424 * the loop, or if this is the final delta, in the caller when
2425 * we return NULL. Those code paths will take care of making
2426 * a more explicit warning and retrying with another copy of
2430 error("failed to apply delta");
2433 free(external_base
);
2442 unuse_pack(&w_curs
);
2444 if (delta_stack
!= small_delta_stack
)
2450 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
2453 const unsigned char *index
= p
->index_data
;
2455 if (open_pack_index(p
))
2457 index
= p
->index_data
;
2459 if (n
>= p
->num_objects
)
2462 if (p
->index_version
== 1) {
2463 return index
+ 24 * n
+ 4;
2466 return index
+ 20 * n
;
2470 const struct object_id
*nth_packed_object_oid(struct object_id
*oid
,
2471 struct packed_git
*p
,
2474 const unsigned char *hash
= nth_packed_object_sha1(p
, n
);
2477 hashcpy(oid
->hash
, hash
);
2481 void check_pack_index_ptr(const struct packed_git
*p
, const void *vptr
)
2483 const unsigned char *ptr
= vptr
;
2484 const unsigned char *start
= p
->index_data
;
2485 const unsigned char *end
= start
+ p
->index_size
;
2487 die(_("offset before start of pack index for %s (corrupt index?)"),
2489 /* No need to check for underflow; .idx files must be at least 8 bytes */
2491 die(_("offset beyond end of pack index for %s (truncated index?)"),
2495 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
2497 const unsigned char *index
= p
->index_data
;
2499 if (p
->index_version
== 1) {
2500 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
2503 index
+= 8 + p
->num_objects
* (20 + 4);
2504 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
2505 if (!(off
& 0x80000000))
2507 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
2508 check_pack_index_ptr(p
, index
);
2509 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
2510 ntohl(*((uint32_t *)(index
+ 4)));
2514 off_t
find_pack_entry_one(const unsigned char *sha1
,
2515 struct packed_git
*p
)
2517 const uint32_t *level1_ofs
= p
->index_data
;
2518 const unsigned char *index
= p
->index_data
;
2519 unsigned hi
, lo
, stride
;
2520 static int debug_lookup
= -1;
2522 if (debug_lookup
< 0)
2523 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
2526 if (open_pack_index(p
))
2528 level1_ofs
= p
->index_data
;
2529 index
= p
->index_data
;
2531 if (p
->index_version
> 1) {
2536 hi
= ntohl(level1_ofs
[*sha1
]);
2537 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
2538 if (p
->index_version
> 1) {
2546 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
2547 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
2550 unsigned mi
= (lo
+ hi
) / 2;
2551 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
2554 printf("lo %u hi %u rg %u mi %u\n",
2555 lo
, hi
, hi
- lo
, mi
);
2557 return nth_packed_object_offset(p
, mi
);
2566 int is_pack_valid(struct packed_git
*p
)
2568 /* An already open pack is known to be valid. */
2569 if (p
->pack_fd
!= -1)
2572 /* If the pack has one window completely covering the
2573 * file size, the pack is known to be valid even if
2574 * the descriptor is not currently open.
2577 struct pack_window
*w
= p
->windows
;
2579 if (!w
->offset
&& w
->len
== p
->pack_size
)
2583 /* Force the pack to open to prove its valid. */
2584 return !open_packed_git(p
);
2587 static int fill_pack_entry(const unsigned char *sha1
,
2588 struct pack_entry
*e
,
2589 struct packed_git
*p
)
2593 if (p
->num_bad_objects
) {
2595 for (i
= 0; i
< p
->num_bad_objects
; i
++)
2596 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
2600 offset
= find_pack_entry_one(sha1
, p
);
2605 * We are about to tell the caller where they can locate the
2606 * requested object. We better make sure the packfile is
2607 * still here and can be accessed before supplying that
2608 * answer, as it may have been deleted since the index was
2611 if (!is_pack_valid(p
))
2615 hashcpy(e
->sha1
, sha1
);
2620 * Iff a pack file contains the object named by sha1, return true and
2621 * store its location to e.
2623 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
2625 struct mru_entry
*p
;
2627 prepare_packed_git();
2631 for (p
= packed_git_mru
->head
; p
; p
= p
->next
) {
2632 if (fill_pack_entry(sha1
, e
, p
->item
)) {
2633 mru_mark(packed_git_mru
, p
);
2640 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
2641 struct packed_git
*packs
)
2643 struct packed_git
*p
;
2645 for (p
= packs
; p
; p
= p
->next
) {
2646 if (find_pack_entry_one(sha1
, p
))
2653 static int sha1_loose_object_info(const unsigned char *sha1
,
2654 struct object_info
*oi
,
2658 unsigned long mapsize
;
2662 struct strbuf hdrbuf
= STRBUF_INIT
;
2663 unsigned long size_scratch
;
2665 if (oi
->delta_base_sha1
)
2666 hashclr(oi
->delta_base_sha1
);
2669 * If we don't care about type or size, then we don't
2670 * need to look inside the object at all. Note that we
2671 * do not optimize out the stat call, even if the
2672 * caller doesn't care about the disk-size, since our
2673 * return value implicitly indicates whether the
2674 * object even exists.
2676 if (!oi
->typep
&& !oi
->typename
&& !oi
->sizep
&& !oi
->contentp
) {
2679 if (stat_sha1_file(sha1
, &st
, &path
) < 0)
2682 *oi
->disk_sizep
= st
.st_size
;
2686 map
= map_sha1_file(sha1
, &mapsize
);
2691 oi
->sizep
= &size_scratch
;
2694 *oi
->disk_sizep
= mapsize
;
2695 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
)) {
2696 if (unpack_sha1_header_to_strbuf(&stream
, map
, mapsize
, hdr
, sizeof(hdr
), &hdrbuf
) < 0)
2697 status
= error("unable to unpack %s header with --allow-unknown-type",
2699 } else if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
2700 status
= error("unable to unpack %s header",
2704 else if (hdrbuf
.len
) {
2705 if ((status
= parse_sha1_header_extended(hdrbuf
.buf
, oi
, flags
)) < 0)
2706 status
= error("unable to parse %s header with --allow-unknown-type",
2708 } else if ((status
= parse_sha1_header_extended(hdr
, oi
, flags
)) < 0)
2709 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
2711 if (status
>= 0 && oi
->contentp
)
2712 *oi
->contentp
= unpack_sha1_rest(&stream
, hdr
,
2715 git_inflate_end(&stream
);
2717 munmap(map
, mapsize
);
2718 if (status
&& oi
->typep
)
2719 *oi
->typep
= status
;
2720 if (oi
->sizep
== &size_scratch
)
2722 strbuf_release(&hdrbuf
);
2723 oi
->whence
= OI_LOOSE
;
2724 return (status
< 0) ? status
: 0;
2727 int sha1_object_info_extended(const unsigned char *sha1
, struct object_info
*oi
, unsigned flags
)
2729 static struct object_info blank_oi
= OBJECT_INFO_INIT
;
2730 struct pack_entry e
;
2732 const unsigned char *real
= (flags
& OBJECT_INFO_LOOKUP_REPLACE
) ?
2733 lookup_replace_object(sha1
) :
2739 if (!(flags
& OBJECT_INFO_SKIP_CACHED
)) {
2740 struct cached_object
*co
= find_cached_object(real
);
2743 *(oi
->typep
) = co
->type
;
2745 *(oi
->sizep
) = co
->size
;
2747 *(oi
->disk_sizep
) = 0;
2748 if (oi
->delta_base_sha1
)
2749 hashclr(oi
->delta_base_sha1
);
2751 strbuf_addstr(oi
->typename
, typename(co
->type
));
2753 *oi
->contentp
= xmemdupz(co
->buf
, co
->size
);
2754 oi
->whence
= OI_CACHED
;
2759 if (!find_pack_entry(real
, &e
)) {
2760 /* Most likely it's a loose object. */
2761 if (!sha1_loose_object_info(real
, oi
, flags
))
2764 /* Not a loose object; someone else may have just packed it. */
2765 if (flags
& OBJECT_INFO_QUICK
) {
2768 reprepare_packed_git();
2769 if (!find_pack_entry(real
, &e
))
2774 if (oi
== &blank_oi
)
2776 * We know that the caller doesn't actually need the
2777 * information below, so return early.
2781 rtype
= packed_object_info(e
.p
, e
.offset
, oi
);
2783 mark_bad_packed_object(e
.p
, real
);
2784 return sha1_object_info_extended(real
, oi
, 0);
2785 } else if (oi
->whence
== OI_PACKED
) {
2786 oi
->u
.packed
.offset
= e
.offset
;
2787 oi
->u
.packed
.pack
= e
.p
;
2788 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
2789 rtype
== OBJ_OFS_DELTA
);
2795 /* returns enum object_type or negative */
2796 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
2798 enum object_type type
;
2799 struct object_info oi
= OBJECT_INFO_INIT
;
2803 if (sha1_object_info_extended(sha1
, &oi
,
2804 OBJECT_INFO_LOOKUP_REPLACE
) < 0)
2809 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
2810 unsigned char *sha1
)
2812 struct cached_object
*co
;
2814 hash_sha1_file(buf
, len
, typename(type
), sha1
);
2815 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
2817 ALLOC_GROW(cached_objects
, cached_object_nr
+ 1, cached_object_alloc
);
2818 co
= &cached_objects
[cached_object_nr
++];
2821 co
->buf
= xmalloc(len
);
2822 memcpy(co
->buf
, buf
, len
);
2823 hashcpy(co
->sha1
, sha1
);
2827 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2828 unsigned long *size
)
2830 struct object_info oi
= OBJECT_INFO_INIT
;
2834 oi
.contentp
= &content
;
2836 if (sha1_object_info_extended(sha1
, &oi
, 0) < 0)
2842 * This function dies on corrupt objects; the callers who want to
2843 * deal with them should arrange to call read_object() and give error
2844 * messages themselves.
2846 void *read_sha1_file_extended(const unsigned char *sha1
,
2847 enum object_type
*type
,
2848 unsigned long *size
,
2852 const struct packed_git
*p
;
2855 const unsigned char *repl
= lookup_replace
? lookup_replace_object(sha1
)
2859 data
= read_object(repl
, type
, size
);
2863 if (errno
&& errno
!= ENOENT
)
2864 die_errno("failed to read object %s", sha1_to_hex(sha1
));
2866 /* die if we replaced an object with one that does not exist */
2868 die("replacement %s not found for %s",
2869 sha1_to_hex(repl
), sha1_to_hex(sha1
));
2871 if (!stat_sha1_file(repl
, &st
, &path
))
2872 die("loose object %s (stored in %s) is corrupt",
2873 sha1_to_hex(repl
), path
);
2875 if ((p
= has_packed_and_bad(repl
)) != NULL
)
2876 die("packed object %s (stored in %s) is corrupt",
2877 sha1_to_hex(repl
), p
->pack_name
);
2882 void *read_object_with_reference(const unsigned char *sha1
,
2883 const char *required_type_name
,
2884 unsigned long *size
,
2885 unsigned char *actual_sha1_return
)
2887 enum object_type type
, required_type
;
2889 unsigned long isize
;
2890 unsigned char actual_sha1
[20];
2892 required_type
= type_from_string(required_type_name
);
2893 hashcpy(actual_sha1
, sha1
);
2895 int ref_length
= -1;
2896 const char *ref_type
= NULL
;
2898 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
2901 if (type
== required_type
) {
2903 if (actual_sha1_return
)
2904 hashcpy(actual_sha1_return
, actual_sha1
);
2907 /* Handle references */
2908 else if (type
== OBJ_COMMIT
)
2910 else if (type
== OBJ_TAG
)
2911 ref_type
= "object ";
2916 ref_length
= strlen(ref_type
);
2918 if (ref_length
+ 40 > isize
||
2919 memcmp(buffer
, ref_type
, ref_length
) ||
2920 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
2925 /* Now we have the ID of the referred-to object in
2926 * actual_sha1. Check again. */
2930 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
2931 const char *type
, unsigned char *sha1
,
2932 char *hdr
, int *hdrlen
)
2936 /* Generate the header */
2937 *hdrlen
= xsnprintf(hdr
, *hdrlen
, "%s %lu", type
, len
)+1;
2941 git_SHA1_Update(&c
, hdr
, *hdrlen
);
2942 git_SHA1_Update(&c
, buf
, len
);
2943 git_SHA1_Final(sha1
, &c
);
2947 * Move the just written object into its final resting place.
2949 int finalize_object_file(const char *tmpfile
, const char *filename
)
2953 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
2955 else if (link(tmpfile
, filename
))
2959 * Coda hack - coda doesn't like cross-directory links,
2960 * so we fall back to a rename, which will mean that it
2961 * won't be able to check collisions, but that's not a
2964 * The same holds for FAT formatted media.
2966 * When this succeeds, we just return. We have nothing
2969 if (ret
&& ret
!= EEXIST
) {
2971 if (!rename(tmpfile
, filename
))
2975 unlink_or_warn(tmpfile
);
2977 if (ret
!= EEXIST
) {
2978 return error_errno("unable to write sha1 filename %s", filename
);
2980 /* FIXME!!! Collision check here ? */
2984 if (adjust_shared_perm(filename
))
2985 return error("unable to set permission to '%s'", filename
);
2989 static int write_buffer(int fd
, const void *buf
, size_t len
)
2991 if (write_in_full(fd
, buf
, len
) < 0)
2992 return error_errno("file write error");
2996 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
2997 unsigned char *sha1
)
3000 int hdrlen
= sizeof(hdr
);
3001 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3005 /* Finalize a file on disk, and close it. */
3006 static void close_sha1_file(int fd
)
3008 if (fsync_object_files
)
3009 fsync_or_die(fd
, "sha1 file");
3011 die_errno("error when closing sha1 file");
3014 /* Size of directory component, including the ending '/' */
3015 static inline int directory_size(const char *filename
)
3017 const char *s
= strrchr(filename
, '/');
3020 return s
- filename
+ 1;
3024 * This creates a temporary file in the same directory as the final
3027 * We want to avoid cross-directory filename renames, because those
3028 * can have problems on various filesystems (FAT, NFS, Coda).
3030 static int create_tmpfile(struct strbuf
*tmp
, const char *filename
)
3032 int fd
, dirlen
= directory_size(filename
);
3035 strbuf_add(tmp
, filename
, dirlen
);
3036 strbuf_addstr(tmp
, "tmp_obj_XXXXXX");
3037 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
3038 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
3040 * Make sure the directory exists; note that the contents
3041 * of the buffer are undefined after mkstemp returns an
3042 * error, so we have to rewrite the whole buffer from
3046 strbuf_add(tmp
, filename
, dirlen
- 1);
3047 if (mkdir(tmp
->buf
, 0777) && errno
!= EEXIST
)
3049 if (adjust_shared_perm(tmp
->buf
))
3053 strbuf_addstr(tmp
, "/tmp_obj_XXXXXX");
3054 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
3059 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
3060 const void *buf
, unsigned long len
, time_t mtime
)
3063 unsigned char compressed
[4096];
3066 unsigned char parano_sha1
[20];
3067 static struct strbuf tmp_file
= STRBUF_INIT
;
3068 const char *filename
= sha1_file_name(sha1
);
3070 fd
= create_tmpfile(&tmp_file
, filename
);
3072 if (errno
== EACCES
)
3073 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3075 return error_errno("unable to create temporary file");
3079 git_deflate_init(&stream
, zlib_compression_level
);
3080 stream
.next_out
= compressed
;
3081 stream
.avail_out
= sizeof(compressed
);
3084 /* First header.. */
3085 stream
.next_in
= (unsigned char *)hdr
;
3086 stream
.avail_in
= hdrlen
;
3087 while (git_deflate(&stream
, 0) == Z_OK
)
3089 git_SHA1_Update(&c
, hdr
, hdrlen
);
3091 /* Then the data itself.. */
3092 stream
.next_in
= (void *)buf
;
3093 stream
.avail_in
= len
;
3095 unsigned char *in0
= stream
.next_in
;
3096 ret
= git_deflate(&stream
, Z_FINISH
);
3097 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
3098 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
3099 die("unable to write sha1 file");
3100 stream
.next_out
= compressed
;
3101 stream
.avail_out
= sizeof(compressed
);
3102 } while (ret
== Z_OK
);
3104 if (ret
!= Z_STREAM_END
)
3105 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
3106 ret
= git_deflate_end_gently(&stream
);
3108 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
3109 git_SHA1_Final(parano_sha1
, &c
);
3110 if (hashcmp(sha1
, parano_sha1
) != 0)
3111 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
3113 close_sha1_file(fd
);
3118 utb
.modtime
= mtime
;
3119 if (utime(tmp_file
.buf
, &utb
) < 0)
3120 warning_errno("failed utime() on %s", tmp_file
.buf
);
3123 return finalize_object_file(tmp_file
.buf
, filename
);
3126 static int freshen_loose_object(const unsigned char *sha1
)
3128 return check_and_freshen(sha1
, 1);
3131 static int freshen_packed_object(const unsigned char *sha1
)
3133 struct pack_entry e
;
3134 if (!find_pack_entry(sha1
, &e
))
3138 if (!freshen_file(e
.p
->pack_name
))
3144 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *sha1
)
3147 int hdrlen
= sizeof(hdr
);
3149 /* Normally if we have it in the pack then we do not bother writing
3150 * it out into .git/objects/??/?{38} file.
3152 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3153 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3155 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
3158 int hash_sha1_file_literally(const void *buf
, unsigned long len
, const char *type
,
3159 unsigned char *sha1
, unsigned flags
)
3162 int hdrlen
, status
= 0;
3164 /* type string, SP, %lu of the length plus NUL must fit this */
3165 hdrlen
= strlen(type
) + 32;
3166 header
= xmalloc(hdrlen
);
3167 write_sha1_file_prepare(buf
, len
, type
, sha1
, header
, &hdrlen
);
3169 if (!(flags
& HASH_WRITE_OBJECT
))
3171 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3173 status
= write_loose_object(sha1
, header
, hdrlen
, buf
, len
, 0);
3180 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
3184 enum object_type type
;
3189 if (has_loose_object(sha1
))
3191 buf
= read_object(sha1
, &type
, &len
);
3193 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
3194 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(type
), len
) + 1;
3195 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
3201 int has_pack_index(const unsigned char *sha1
)
3204 if (stat(sha1_pack_index_name(sha1
), &st
))
3209 int has_sha1_pack(const unsigned char *sha1
)
3211 struct pack_entry e
;
3212 return find_pack_entry(sha1
, &e
);
3215 int has_sha1_file_with_flags(const unsigned char *sha1
, int flags
)
3217 if (!startup_info
->have_repository
)
3219 return sha1_object_info_extended(sha1
, NULL
,
3220 flags
| OBJECT_INFO_SKIP_CACHED
) >= 0;
3223 int has_object_file(const struct object_id
*oid
)
3225 return has_sha1_file(oid
->hash
);
3228 int has_object_file_with_flags(const struct object_id
*oid
, int flags
)
3230 return has_sha1_file_with_flags(oid
->hash
, flags
);
3233 static void check_tree(const void *buf
, size_t size
)
3235 struct tree_desc desc
;
3236 struct name_entry entry
;
3238 init_tree_desc(&desc
, buf
, size
);
3239 while (tree_entry(&desc
, &entry
))
3241 * tree_entry() will die() on malformed entries */
3245 static void check_commit(const void *buf
, size_t size
)
3248 memset(&c
, 0, sizeof(c
));
3249 if (parse_commit_buffer(&c
, buf
, size
))
3250 die("corrupt commit");
3253 static void check_tag(const void *buf
, size_t size
)
3256 memset(&t
, 0, sizeof(t
));
3257 if (parse_tag_buffer(&t
, buf
, size
))
3261 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
3262 enum object_type type
,
3263 const char *path
, unsigned flags
)
3265 int ret
, re_allocated
= 0;
3266 int write_object
= flags
& HASH_WRITE_OBJECT
;
3272 * Convert blobs to git internal format
3274 if ((type
== OBJ_BLOB
) && path
) {
3275 struct strbuf nbuf
= STRBUF_INIT
;
3276 if (convert_to_git(&the_index
, path
, buf
, size
, &nbuf
,
3277 write_object
? safe_crlf
: SAFE_CRLF_FALSE
)) {
3278 buf
= strbuf_detach(&nbuf
, &size
);
3282 if (flags
& HASH_FORMAT_CHECK
) {
3283 if (type
== OBJ_TREE
)
3284 check_tree(buf
, size
);
3285 if (type
== OBJ_COMMIT
)
3286 check_commit(buf
, size
);
3287 if (type
== OBJ_TAG
)
3288 check_tag(buf
, size
);
3292 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
3294 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
3300 static int index_stream_convert_blob(unsigned char *sha1
, int fd
,
3301 const char *path
, unsigned flags
)
3304 const int write_object
= flags
& HASH_WRITE_OBJECT
;
3305 struct strbuf sbuf
= STRBUF_INIT
;
3308 assert(would_convert_to_git_filter_fd(path
));
3310 convert_to_git_filter_fd(&the_index
, path
, fd
, &sbuf
,
3311 write_object
? safe_crlf
: SAFE_CRLF_FALSE
);
3314 ret
= write_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3317 ret
= hash_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3319 strbuf_release(&sbuf
);
3323 static int index_pipe(unsigned char *sha1
, int fd
, enum object_type type
,
3324 const char *path
, unsigned flags
)
3326 struct strbuf sbuf
= STRBUF_INIT
;
3329 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
3330 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
3333 strbuf_release(&sbuf
);
3337 #define SMALL_FILE_SIZE (32*1024)
3339 static int index_core(unsigned char *sha1
, int fd
, size_t size
,
3340 enum object_type type
, const char *path
,
3346 ret
= index_mem(sha1
, "", size
, type
, path
, flags
);
3347 } else if (size
<= SMALL_FILE_SIZE
) {
3348 char *buf
= xmalloc(size
);
3349 if (size
== read_in_full(fd
, buf
, size
))
3350 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3352 ret
= error_errno("short read");
3355 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
3356 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3363 * This creates one packfile per large blob unless bulk-checkin
3364 * machinery is "plugged".
3366 * This also bypasses the usual "convert-to-git" dance, and that is on
3367 * purpose. We could write a streaming version of the converting
3368 * functions and insert that before feeding the data to fast-import
3369 * (or equivalent in-core API described above). However, that is
3370 * somewhat complicated, as we do not know the size of the filter
3371 * result, which we need to know beforehand when writing a git object.
3372 * Since the primary motivation for trying to stream from the working
3373 * tree file and to avoid mmaping it in core is to deal with large
3374 * binary blobs, they generally do not want to get any conversion, and
3375 * callers should avoid this code path when filters are requested.
3377 static int index_stream(unsigned char *sha1
, int fd
, size_t size
,
3378 enum object_type type
, const char *path
,
3381 return index_bulk_checkin(sha1
, fd
, size
, type
, path
, flags
);
3384 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
,
3385 enum object_type type
, const char *path
, unsigned flags
)
3390 * Call xsize_t() only when needed to avoid potentially unnecessary
3391 * die() for large files.
3393 if (type
== OBJ_BLOB
&& path
&& would_convert_to_git_filter_fd(path
))
3394 ret
= index_stream_convert_blob(sha1
, fd
, path
, flags
);
3395 else if (!S_ISREG(st
->st_mode
))
3396 ret
= index_pipe(sha1
, fd
, type
, path
, flags
);
3397 else if (st
->st_size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
3398 (path
&& would_convert_to_git(&the_index
, path
)))
3399 ret
= index_core(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3402 ret
= index_stream(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3408 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, unsigned flags
)
3411 struct strbuf sb
= STRBUF_INIT
;
3413 switch (st
->st_mode
& S_IFMT
) {
3415 fd
= open(path
, O_RDONLY
);
3417 return error_errno("open(\"%s\")", path
);
3418 if (index_fd(sha1
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
3419 return error("%s: failed to insert into database",
3423 if (strbuf_readlink(&sb
, path
, st
->st_size
))
3424 return error_errno("readlink(\"%s\")", path
);
3425 if (!(flags
& HASH_WRITE_OBJECT
))
3426 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
3427 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
3428 return error("%s: failed to insert into database",
3430 strbuf_release(&sb
);
3433 return resolve_gitlink_ref(path
, "HEAD", sha1
);
3435 return error("%s: unsupported file type", path
);
3440 int read_pack_header(int fd
, struct pack_header
*header
)
3442 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
3443 /* "eof before pack header was fully read" */
3444 return PH_ERROR_EOF
;
3446 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
3447 /* "protocol error (pack signature mismatch detected)" */
3448 return PH_ERROR_PACK_SIGNATURE
;
3449 if (!pack_version_ok(header
->hdr_version
))
3450 /* "protocol error (pack version unsupported)" */
3451 return PH_ERROR_PROTOCOL
;
3455 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
3457 enum object_type type
= sha1_object_info(sha1
, NULL
);
3459 die("%s is not a valid object", sha1_to_hex(sha1
));
3461 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),
3465 int for_each_file_in_obj_subdir(unsigned int subdir_nr
,
3466 struct strbuf
*path
,
3467 each_loose_object_fn obj_cb
,
3468 each_loose_cruft_fn cruft_cb
,
3469 each_loose_subdir_fn subdir_cb
,
3472 size_t origlen
, baselen
;
3477 if (subdir_nr
> 0xff)
3478 BUG("invalid loose object subdirectory: %x", subdir_nr
);
3480 origlen
= path
->len
;
3481 strbuf_complete(path
, '/');
3482 strbuf_addf(path
, "%02x", subdir_nr
);
3483 baselen
= path
->len
;
3485 dir
= opendir(path
->buf
);
3487 if (errno
!= ENOENT
)
3488 r
= error_errno("unable to open %s", path
->buf
);
3489 strbuf_setlen(path
, origlen
);
3493 while ((de
= readdir(dir
))) {
3494 if (is_dot_or_dotdot(de
->d_name
))
3497 strbuf_setlen(path
, baselen
);
3498 strbuf_addf(path
, "/%s", de
->d_name
);
3500 if (strlen(de
->d_name
) == GIT_SHA1_HEXSZ
- 2) {
3501 char hex
[GIT_MAX_HEXSZ
+1];
3502 struct object_id oid
;
3504 xsnprintf(hex
, sizeof(hex
), "%02x%s",
3505 subdir_nr
, de
->d_name
);
3506 if (!get_oid_hex(hex
, &oid
)) {
3508 r
= obj_cb(&oid
, path
->buf
, data
);
3517 r
= cruft_cb(de
->d_name
, path
->buf
, data
);
3524 strbuf_setlen(path
, baselen
);
3525 if (!r
&& subdir_cb
)
3526 r
= subdir_cb(subdir_nr
, path
->buf
, data
);
3528 strbuf_setlen(path
, origlen
);
3533 int for_each_loose_file_in_objdir_buf(struct strbuf
*path
,
3534 each_loose_object_fn obj_cb
,
3535 each_loose_cruft_fn cruft_cb
,
3536 each_loose_subdir_fn subdir_cb
,
3542 for (i
= 0; i
< 256; i
++) {
3543 r
= for_each_file_in_obj_subdir(i
, path
, obj_cb
, cruft_cb
,
3552 int for_each_loose_file_in_objdir(const char *path
,
3553 each_loose_object_fn obj_cb
,
3554 each_loose_cruft_fn cruft_cb
,
3555 each_loose_subdir_fn subdir_cb
,
3558 struct strbuf buf
= STRBUF_INIT
;
3561 strbuf_addstr(&buf
, path
);
3562 r
= for_each_loose_file_in_objdir_buf(&buf
, obj_cb
, cruft_cb
,
3564 strbuf_release(&buf
);
3569 struct loose_alt_odb_data
{
3570 each_loose_object_fn
*cb
;
3574 static int loose_from_alt_odb(struct alternate_object_database
*alt
,
3577 struct loose_alt_odb_data
*data
= vdata
;
3578 struct strbuf buf
= STRBUF_INIT
;
3581 strbuf_addstr(&buf
, alt
->path
);
3582 r
= for_each_loose_file_in_objdir_buf(&buf
,
3583 data
->cb
, NULL
, NULL
,
3585 strbuf_release(&buf
);
3589 int for_each_loose_object(each_loose_object_fn cb
, void *data
, unsigned flags
)
3591 struct loose_alt_odb_data alt
;
3594 r
= for_each_loose_file_in_objdir(get_object_directory(),
3595 cb
, NULL
, NULL
, data
);
3599 if (flags
& FOR_EACH_OBJECT_LOCAL_ONLY
)
3604 return foreach_alt_odb(loose_from_alt_odb
, &alt
);
3607 static int for_each_object_in_pack(struct packed_git
*p
, each_packed_object_fn cb
, void *data
)
3612 for (i
= 0; i
< p
->num_objects
; i
++) {
3613 struct object_id oid
;
3615 if (!nth_packed_object_oid(&oid
, p
, i
))
3616 return error("unable to get sha1 of object %u in %s",
3619 r
= cb(&oid
, p
, i
, data
);
3626 int for_each_packed_object(each_packed_object_fn cb
, void *data
, unsigned flags
)
3628 struct packed_git
*p
;
3630 int pack_errors
= 0;
3632 prepare_packed_git();
3633 for (p
= packed_git
; p
; p
= p
->next
) {
3634 if ((flags
& FOR_EACH_OBJECT_LOCAL_ONLY
) && !p
->pack_local
)
3636 if (open_pack_index(p
)) {
3640 r
= for_each_object_in_pack(p
, cb
, data
);
3644 return r
? r
: pack_errors
;
3647 static int check_stream_sha1(git_zstream
*stream
,
3651 const unsigned char *expected_sha1
)
3654 unsigned char real_sha1
[GIT_MAX_RAWSZ
];
3655 unsigned char buf
[4096];
3656 unsigned long total_read
;
3660 git_SHA1_Update(&c
, hdr
, stream
->total_out
);
3663 * We already read some bytes into hdr, but the ones up to the NUL
3664 * do not count against the object's content size.
3666 total_read
= stream
->total_out
- strlen(hdr
) - 1;
3669 * This size comparison must be "<=" to read the final zlib packets;
3670 * see the comment in unpack_sha1_rest for details.
3672 while (total_read
<= size
&&
3673 (status
== Z_OK
|| status
== Z_BUF_ERROR
)) {
3674 stream
->next_out
= buf
;
3675 stream
->avail_out
= sizeof(buf
);
3676 if (size
- total_read
< stream
->avail_out
)
3677 stream
->avail_out
= size
- total_read
;
3678 status
= git_inflate(stream
, Z_FINISH
);
3679 git_SHA1_Update(&c
, buf
, stream
->next_out
- buf
);
3680 total_read
+= stream
->next_out
- buf
;
3682 git_inflate_end(stream
);
3684 if (status
!= Z_STREAM_END
) {
3685 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1
));
3688 if (stream
->avail_in
) {
3689 error("garbage at end of loose object '%s'",
3690 sha1_to_hex(expected_sha1
));
3694 git_SHA1_Final(real_sha1
, &c
);
3695 if (hashcmp(expected_sha1
, real_sha1
)) {
3696 error("sha1 mismatch for %s (expected %s)", path
,
3697 sha1_to_hex(expected_sha1
));
3704 int read_loose_object(const char *path
,
3705 const unsigned char *expected_sha1
,
3706 enum object_type
*type
,
3707 unsigned long *size
,
3712 unsigned long mapsize
;
3718 map
= map_sha1_file_1(path
, NULL
, &mapsize
);
3720 error_errno("unable to mmap %s", path
);
3724 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0) {
3725 error("unable to unpack header of %s", path
);
3729 *type
= parse_sha1_header(hdr
, size
);
3731 error("unable to parse header of %s", path
);
3732 git_inflate_end(&stream
);
3736 if (*type
== OBJ_BLOB
) {
3737 if (check_stream_sha1(&stream
, hdr
, *size
, path
, expected_sha1
) < 0)
3740 *contents
= unpack_sha1_rest(&stream
, hdr
, *size
, expected_sha1
);
3742 error("unable to unpack contents of %s", path
);
3743 git_inflate_end(&stream
);
3746 if (check_sha1_signature(expected_sha1
, *contents
,
3747 *size
, typename(*type
))) {
3748 error("sha1 mismatch for %s (expected %s)", path
,
3749 sha1_to_hex(expected_sha1
));
3755 ret
= 0; /* everything checks out */
3759 munmap(map
, mapsize
);