2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
10 #include "string-list.h"
16 #include "run-command.h"
19 #include "tree-walk.h"
21 #include "pack-revindex.h"
22 #include "sha1-lookup.h"
23 #include "bulk-checkin.h"
24 #include "streaming.h"
28 #include "mergesort.h"
32 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
33 #define O_NOATIME 01000000
39 #define SZ_FMT PRIuMAX
40 static inline uintmax_t sz_fmt(size_t s
) { return s
; }
42 const unsigned char null_sha1
[20];
43 const struct object_id null_oid
;
44 const struct object_id empty_tree_oid
= {
45 EMPTY_TREE_SHA1_BIN_LITERAL
47 const struct object_id empty_blob_oid
= {
48 EMPTY_BLOB_SHA1_BIN_LITERAL
52 * This is meant to hold a *small* number of objects that you would
53 * want read_sha1_file() to be able to return, but yet you do not want
54 * to write them into the object store (e.g. a browse-only
57 static struct cached_object
{
58 unsigned char sha1
[20];
59 enum object_type type
;
63 static int cached_object_nr
, cached_object_alloc
;
65 static struct cached_object empty_tree
= {
66 EMPTY_TREE_SHA1_BIN_LITERAL
,
72 static struct cached_object
*find_cached_object(const unsigned char *sha1
)
75 struct cached_object
*co
= cached_objects
;
77 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
78 if (!hashcmp(co
->sha1
, sha1
))
81 if (!hashcmp(sha1
, empty_tree
.sha1
))
86 int mkdir_in_gitdir(const char *path
)
88 if (mkdir(path
, 0777)) {
89 int saved_errno
= errno
;
91 struct strbuf sb
= STRBUF_INIT
;
96 * Are we looking at a path in a symlinked worktree
97 * whose original repository does not yet have it?
98 * e.g. .git/rr-cache pointing at its original
99 * repository in which the user hasn't performed any
100 * conflict resolution yet?
102 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
103 strbuf_readlink(&sb
, path
, st
.st_size
) ||
104 !is_absolute_path(sb
.buf
) ||
105 mkdir(sb
.buf
, 0777)) {
112 return adjust_shared_perm(path
);
115 enum scld_error
safe_create_leading_directories(char *path
)
117 char *next_component
= path
+ offset_1st_component(path
);
118 enum scld_error ret
= SCLD_OK
;
120 while (ret
== SCLD_OK
&& next_component
) {
122 char *slash
= next_component
, slash_character
;
124 while (*slash
&& !is_dir_sep(*slash
))
130 next_component
= slash
+ 1;
131 while (is_dir_sep(*next_component
))
133 if (!*next_component
)
136 slash_character
= *slash
;
138 if (!stat(path
, &st
)) {
140 if (!S_ISDIR(st
.st_mode
)) {
144 } else if (mkdir(path
, 0777)) {
145 if (errno
== EEXIST
&&
146 !stat(path
, &st
) && S_ISDIR(st
.st_mode
))
147 ; /* somebody created it since we checked */
148 else if (errno
== ENOENT
)
150 * Either mkdir() failed because
151 * somebody just pruned the containing
152 * directory, or stat() failed because
153 * the file that was in our way was
154 * just removed. Either way, inform
155 * the caller that it might be worth
161 } else if (adjust_shared_perm(path
)) {
164 *slash
= slash_character
;
169 enum scld_error
safe_create_leading_directories_const(const char *path
)
172 /* path points to cache entries, so xstrdup before messing with it */
173 char *buf
= xstrdup(path
);
174 enum scld_error result
= safe_create_leading_directories(buf
);
182 int raceproof_create_file(const char *path
, create_file_fn fn
, void *cb
)
185 * The number of times we will try to remove empty directories
186 * in the way of path. This is only 1 because if another
187 * process is racily creating directories that conflict with
188 * us, we don't want to fight against them.
190 int remove_directories_remaining
= 1;
193 * The number of times that we will try to create the
194 * directories containing path. We are willing to attempt this
195 * more than once, because another process could be trying to
196 * clean up empty directories at the same time as we are
197 * trying to create them.
199 int create_directories_remaining
= 3;
201 /* A scratch copy of path, filled lazily if we need it: */
202 struct strbuf path_copy
= STRBUF_INIT
;
215 if (errno
== EISDIR
&& remove_directories_remaining
-- > 0) {
217 * A directory is in the way. Maybe it is empty; try
221 strbuf_addstr(&path_copy
, path
);
223 if (!remove_dir_recursively(&path_copy
, REMOVE_DIR_EMPTY_ONLY
))
225 } else if (errno
== ENOENT
&& create_directories_remaining
-- > 0) {
227 * Maybe the containing directory didn't exist, or
228 * maybe it was just deleted by a process that is
229 * racing with us to clean up empty directories. Try
232 enum scld_error scld_result
;
235 strbuf_addstr(&path_copy
, path
);
238 scld_result
= safe_create_leading_directories(path_copy
.buf
);
239 if (scld_result
== SCLD_OK
)
241 } while (scld_result
== SCLD_VANISHED
&& create_directories_remaining
-- > 0);
245 strbuf_release(&path_copy
);
250 static void fill_sha1_path(struct strbuf
*buf
, const unsigned char *sha1
)
253 for (i
= 0; i
< 20; i
++) {
254 static char hex
[] = "0123456789abcdef";
255 unsigned int val
= sha1
[i
];
256 strbuf_addch(buf
, hex
[val
>> 4]);
257 strbuf_addch(buf
, hex
[val
& 0xf]);
259 strbuf_addch(buf
, '/');
263 const char *sha1_file_name(const unsigned char *sha1
)
265 static struct strbuf buf
= STRBUF_INIT
;
268 strbuf_addf(&buf
, "%s/", get_object_directory());
270 fill_sha1_path(&buf
, sha1
);
274 struct strbuf
*alt_scratch_buf(struct alternate_object_database
*alt
)
276 strbuf_setlen(&alt
->scratch
, alt
->base_len
);
277 return &alt
->scratch
;
280 static const char *alt_sha1_path(struct alternate_object_database
*alt
,
281 const unsigned char *sha1
)
283 struct strbuf
*buf
= alt_scratch_buf(alt
);
284 fill_sha1_path(buf
, sha1
);
289 * Return the name of the pack or index file with the specified sha1
290 * in its filename. *base and *name are scratch space that must be
291 * provided by the caller. which should be "pack" or "idx".
293 static char *sha1_get_pack_name(const unsigned char *sha1
,
298 strbuf_addf(buf
, "%s/pack/pack-%s.%s", get_object_directory(),
299 sha1_to_hex(sha1
), which
);
303 char *sha1_pack_name(const unsigned char *sha1
)
305 static struct strbuf buf
= STRBUF_INIT
;
306 return sha1_get_pack_name(sha1
, &buf
, "pack");
309 char *sha1_pack_index_name(const unsigned char *sha1
)
311 static struct strbuf buf
= STRBUF_INIT
;
312 return sha1_get_pack_name(sha1
, &buf
, "idx");
315 struct alternate_object_database
*alt_odb_list
;
316 static struct alternate_object_database
**alt_odb_tail
;
319 * Return non-zero iff the path is usable as an alternate object database.
321 static int alt_odb_usable(struct strbuf
*path
, const char *normalized_objdir
)
323 struct alternate_object_database
*alt
;
325 /* Detect cases where alternate disappeared */
326 if (!is_directory(path
->buf
)) {
327 error("object directory %s does not exist; "
328 "check .git/objects/info/alternates.",
334 * Prevent the common mistake of listing the same
335 * thing twice, or object directory itself.
337 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
338 if (!fspathcmp(path
->buf
, alt
->path
))
341 if (!fspathcmp(path
->buf
, normalized_objdir
))
348 * Prepare alternate object database registry.
350 * The variable alt_odb_list points at the list of struct
351 * alternate_object_database. The elements on this list come from
352 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
353 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
354 * whose contents is similar to that environment variable but can be
355 * LF separated. Its base points at a statically allocated buffer that
356 * contains "/the/directory/corresponding/to/.git/objects/...", while
357 * its name points just after the slash at the end of ".git/objects/"
358 * in the example above, and has enough space to hold 40-byte hex
359 * SHA1, an extra slash for the first level indirection, and the
362 static int link_alt_odb_entry(const char *entry
, const char *relative_base
,
363 int depth
, const char *normalized_objdir
)
365 struct alternate_object_database
*ent
;
366 struct strbuf pathbuf
= STRBUF_INIT
;
368 if (!is_absolute_path(entry
) && relative_base
) {
369 strbuf_addstr(&pathbuf
, real_path(relative_base
));
370 strbuf_addch(&pathbuf
, '/');
372 strbuf_addstr(&pathbuf
, entry
);
374 if (strbuf_normalize_path(&pathbuf
) < 0 && relative_base
) {
375 error("unable to normalize alternate object path: %s",
377 strbuf_release(&pathbuf
);
382 * The trailing slash after the directory name is given by
383 * this function at the end. Remove duplicates.
385 while (pathbuf
.len
&& pathbuf
.buf
[pathbuf
.len
- 1] == '/')
386 strbuf_setlen(&pathbuf
, pathbuf
.len
- 1);
388 if (!alt_odb_usable(&pathbuf
, normalized_objdir
)) {
389 strbuf_release(&pathbuf
);
393 ent
= alloc_alt_odb(pathbuf
.buf
);
395 /* add the alternate entry */
397 alt_odb_tail
= &(ent
->next
);
400 /* recursively add alternates */
401 read_info_alternates(pathbuf
.buf
, depth
+ 1);
403 strbuf_release(&pathbuf
);
407 static const char *parse_alt_odb_entry(const char *string
,
415 if (*string
== '#') {
416 /* comment; consume up to next separator */
417 end
= strchrnul(string
, sep
);
418 } else if (*string
== '"' && !unquote_c_style(out
, string
, &end
)) {
420 * quoted path; unquote_c_style has copied the
421 * data for us and set "end". Broken quoting (e.g.,
422 * an entry that doesn't end with a quote) falls
423 * back to the unquoted case below.
426 /* normal, unquoted path */
427 end
= strchrnul(string
, sep
);
428 strbuf_add(out
, string
, end
- string
);
436 static void link_alt_odb_entries(const char *alt
, int len
, int sep
,
437 const char *relative_base
, int depth
)
439 struct strbuf objdirbuf
= STRBUF_INIT
;
440 struct strbuf entry
= STRBUF_INIT
;
443 error("%s: ignoring alternate object stores, nesting too deep.",
448 strbuf_add_absolute_path(&objdirbuf
, get_object_directory());
449 if (strbuf_normalize_path(&objdirbuf
) < 0)
450 die("unable to normalize object directory: %s",
454 alt
= parse_alt_odb_entry(alt
, sep
, &entry
);
457 link_alt_odb_entry(entry
.buf
, relative_base
, depth
, objdirbuf
.buf
);
459 strbuf_release(&entry
);
460 strbuf_release(&objdirbuf
);
463 void read_info_alternates(const char * relative_base
, int depth
)
471 path
= xstrfmt("%s/info/alternates", relative_base
);
476 if (fstat(fd
, &st
) || (st
.st_size
== 0)) {
480 mapsz
= xsize_t(st
.st_size
);
481 map
= xmmap(NULL
, mapsz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
484 link_alt_odb_entries(map
, mapsz
, '\n', relative_base
, depth
);
489 struct alternate_object_database
*alloc_alt_odb(const char *dir
)
491 struct alternate_object_database
*ent
;
493 FLEX_ALLOC_STR(ent
, path
, dir
);
494 strbuf_init(&ent
->scratch
, 0);
495 strbuf_addf(&ent
->scratch
, "%s/", dir
);
496 ent
->base_len
= ent
->scratch
.len
;
501 void add_to_alternates_file(const char *reference
)
503 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
504 char *alts
= git_pathdup("objects/info/alternates");
507 hold_lock_file_for_update(lock
, alts
, LOCK_DIE_ON_ERROR
);
508 out
= fdopen_lock_file(lock
, "w");
510 die_errno("unable to fdopen alternates lockfile");
512 in
= fopen(alts
, "r");
514 struct strbuf line
= STRBUF_INIT
;
517 while (strbuf_getline(&line
, in
) != EOF
) {
518 if (!strcmp(reference
, line
.buf
)) {
522 fprintf_or_die(out
, "%s\n", line
.buf
);
525 strbuf_release(&line
);
529 rollback_lock_file(lock
);
533 else if (errno
!= ENOENT
)
534 die_errno("unable to read alternates file");
537 fprintf_or_die(out
, "%s\n", reference
);
538 if (commit_lock_file(lock
))
539 die_errno("unable to move new alternates file into place");
541 link_alt_odb_entries(reference
, strlen(reference
), '\n', NULL
, 0);
546 void add_to_alternates_memory(const char *reference
)
549 * Make sure alternates are initialized, or else our entry may be
550 * overwritten when they are.
554 link_alt_odb_entries(reference
, strlen(reference
), '\n', NULL
, 0);
558 * Compute the exact path an alternate is at and returns it. In case of
559 * error NULL is returned and the human readable error is added to `err`
560 * `path` may be relative and should point to $GITDIR.
561 * `err` must not be null.
563 char *compute_alternate_path(const char *path
, struct strbuf
*err
)
565 char *ref_git
= NULL
;
566 const char *repo
, *ref_git_s
;
569 ref_git_s
= real_path_if_valid(path
);
572 strbuf_addf(err
, _("path '%s' does not exist"), path
);
576 * Beware: read_gitfile(), real_path() and mkpath()
577 * return static buffer
579 ref_git
= xstrdup(ref_git_s
);
581 repo
= read_gitfile(ref_git
);
583 repo
= read_gitfile(mkpath("%s/.git", ref_git
));
586 ref_git
= xstrdup(repo
);
589 if (!repo
&& is_directory(mkpath("%s/.git/objects", ref_git
))) {
590 char *ref_git_git
= mkpathdup("%s/.git", ref_git
);
592 ref_git
= ref_git_git
;
593 } else if (!is_directory(mkpath("%s/objects", ref_git
))) {
594 struct strbuf sb
= STRBUF_INIT
;
596 if (get_common_dir(&sb
, ref_git
)) {
598 _("reference repository '%s' as a linked "
599 "checkout is not supported yet."),
604 strbuf_addf(err
, _("reference repository '%s' is not a "
605 "local repository."), path
);
609 if (!access(mkpath("%s/shallow", ref_git
), F_OK
)) {
610 strbuf_addf(err
, _("reference repository '%s' is shallow"),
616 if (!access(mkpath("%s/info/grafts", ref_git
), F_OK
)) {
618 _("reference repository '%s' is grafted"),
633 int foreach_alt_odb(alt_odb_fn fn
, void *cb
)
635 struct alternate_object_database
*ent
;
639 for (ent
= alt_odb_list
; ent
; ent
= ent
->next
) {
647 void prepare_alt_odb(void)
654 alt
= getenv(ALTERNATE_DB_ENVIRONMENT
);
657 alt_odb_tail
= &alt_odb_list
;
658 link_alt_odb_entries(alt
, strlen(alt
), PATH_SEP
, NULL
, 0);
660 read_info_alternates(get_object_directory(), 0);
663 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
664 static int freshen_file(const char *fn
)
667 t
.actime
= t
.modtime
= time(NULL
);
668 return !utime(fn
, &t
);
672 * All of the check_and_freshen functions return 1 if the file exists and was
673 * freshened (if freshening was requested), 0 otherwise. If they return
674 * 0, you should not assume that it is safe to skip a write of the object (it
675 * either does not exist on disk, or has a stale mtime and may be subject to
678 static int check_and_freshen_file(const char *fn
, int freshen
)
680 if (access(fn
, F_OK
))
682 if (freshen
&& !freshen_file(fn
))
687 static int check_and_freshen_local(const unsigned char *sha1
, int freshen
)
689 return check_and_freshen_file(sha1_file_name(sha1
), freshen
);
692 static int check_and_freshen_nonlocal(const unsigned char *sha1
, int freshen
)
694 struct alternate_object_database
*alt
;
696 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
697 const char *path
= alt_sha1_path(alt
, sha1
);
698 if (check_and_freshen_file(path
, freshen
))
704 static int check_and_freshen(const unsigned char *sha1
, int freshen
)
706 return check_and_freshen_local(sha1
, freshen
) ||
707 check_and_freshen_nonlocal(sha1
, freshen
);
710 int has_loose_object_nonlocal(const unsigned char *sha1
)
712 return check_and_freshen_nonlocal(sha1
, 0);
715 static int has_loose_object(const unsigned char *sha1
)
717 return check_and_freshen(sha1
, 0);
720 static unsigned int pack_used_ctr
;
721 static unsigned int pack_mmap_calls
;
722 static unsigned int peak_pack_open_windows
;
723 static unsigned int pack_open_windows
;
724 static unsigned int pack_open_fds
;
725 static unsigned int pack_max_fds
;
726 static size_t peak_pack_mapped
;
727 static size_t pack_mapped
;
728 struct packed_git
*packed_git
;
730 static struct mru packed_git_mru_storage
;
731 struct mru
*packed_git_mru
= &packed_git_mru_storage
;
733 void pack_report(void)
736 "pack_report: getpagesize() = %10" SZ_FMT
"\n"
737 "pack_report: core.packedGitWindowSize = %10" SZ_FMT
"\n"
738 "pack_report: core.packedGitLimit = %10" SZ_FMT
"\n",
739 sz_fmt(getpagesize()),
740 sz_fmt(packed_git_window_size
),
741 sz_fmt(packed_git_limit
));
743 "pack_report: pack_used_ctr = %10u\n"
744 "pack_report: pack_mmap_calls = %10u\n"
745 "pack_report: pack_open_windows = %10u / %10u\n"
746 "pack_report: pack_mapped = "
747 "%10" SZ_FMT
" / %10" SZ_FMT
"\n",
750 pack_open_windows
, peak_pack_open_windows
,
751 sz_fmt(pack_mapped
), sz_fmt(peak_pack_mapped
));
755 * Open and mmap the index file at path, perform a couple of
756 * consistency checks, then record its information to p. Return 0 on
759 static int check_packed_git_idx(const char *path
, struct packed_git
*p
)
762 struct pack_idx_header
*hdr
;
764 uint32_t version
, nr
, i
, *index
;
765 int fd
= git_open(path
);
770 if (fstat(fd
, &st
)) {
774 idx_size
= xsize_t(st
.st_size
);
775 if (idx_size
< 4 * 256 + 20 + 20) {
777 return error("index file %s is too small", path
);
779 idx_map
= xmmap(NULL
, idx_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
783 if (hdr
->idx_signature
== htonl(PACK_IDX_SIGNATURE
)) {
784 version
= ntohl(hdr
->idx_version
);
785 if (version
< 2 || version
> 2) {
786 munmap(idx_map
, idx_size
);
787 return error("index file %s is version %"PRIu32
788 " and is not supported by this binary"
789 " (try upgrading GIT to a newer version)",
798 index
+= 2; /* skip index header */
799 for (i
= 0; i
< 256; i
++) {
800 uint32_t n
= ntohl(index
[i
]);
802 munmap(idx_map
, idx_size
);
803 return error("non-monotonic index %s", path
);
811 * - 256 index entries 4 bytes each
812 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
813 * - 20-byte SHA1 of the packfile
814 * - 20-byte SHA1 file checksum
816 if (idx_size
!= 4*256 + nr
* 24 + 20 + 20) {
817 munmap(idx_map
, idx_size
);
818 return error("wrong index v1 file size in %s", path
);
820 } else if (version
== 2) {
823 * - 8 bytes of header
824 * - 256 index entries 4 bytes each
825 * - 20-byte sha1 entry * nr
826 * - 4-byte crc entry * nr
827 * - 4-byte offset entry * nr
828 * - 20-byte SHA1 of the packfile
829 * - 20-byte SHA1 file checksum
830 * And after the 4-byte offset table might be a
831 * variable sized table containing 8-byte entries
832 * for offsets larger than 2^31.
834 unsigned long min_size
= 8 + 4*256 + nr
*(20 + 4 + 4) + 20 + 20;
835 unsigned long max_size
= min_size
;
837 max_size
+= (nr
- 1)*8;
838 if (idx_size
< min_size
|| idx_size
> max_size
) {
839 munmap(idx_map
, idx_size
);
840 return error("wrong index v2 file size in %s", path
);
842 if (idx_size
!= min_size
&&
844 * make sure we can deal with large pack offsets.
845 * 31-bit signed offset won't be enough, neither
846 * 32-bit unsigned one will be.
848 (sizeof(off_t
) <= 4)) {
849 munmap(idx_map
, idx_size
);
850 return error("pack too large for current definition of off_t in %s", path
);
854 p
->index_version
= version
;
855 p
->index_data
= idx_map
;
856 p
->index_size
= idx_size
;
861 int open_pack_index(struct packed_git
*p
)
870 if (!strip_suffix(p
->pack_name
, ".pack", &len
))
871 die("BUG: pack_name does not end in .pack");
872 idx_name
= xstrfmt("%.*s.idx", (int)len
, p
->pack_name
);
873 ret
= check_packed_git_idx(idx_name
, p
);
878 static void scan_windows(struct packed_git
*p
,
879 struct packed_git
**lru_p
,
880 struct pack_window
**lru_w
,
881 struct pack_window
**lru_l
)
883 struct pack_window
*w
, *w_l
;
885 for (w_l
= NULL
, w
= p
->windows
; w
; w
= w
->next
) {
887 if (!*lru_w
|| w
->last_used
< (*lru_w
)->last_used
) {
897 static int unuse_one_window(struct packed_git
*current
)
899 struct packed_git
*p
, *lru_p
= NULL
;
900 struct pack_window
*lru_w
= NULL
, *lru_l
= NULL
;
903 scan_windows(current
, &lru_p
, &lru_w
, &lru_l
);
904 for (p
= packed_git
; p
; p
= p
->next
)
905 scan_windows(p
, &lru_p
, &lru_w
, &lru_l
);
907 munmap(lru_w
->base
, lru_w
->len
);
908 pack_mapped
-= lru_w
->len
;
910 lru_l
->next
= lru_w
->next
;
912 lru_p
->windows
= lru_w
->next
;
920 void release_pack_memory(size_t need
)
922 size_t cur
= pack_mapped
;
923 while (need
>= (cur
- pack_mapped
) && unuse_one_window(NULL
))
927 static void mmap_limit_check(size_t length
)
929 static size_t limit
= 0;
931 limit
= git_env_ulong("GIT_MMAP_LIMIT", 0);
936 die("attempting to mmap %"PRIuMAX
" over limit %"PRIuMAX
,
937 (uintmax_t)length
, (uintmax_t)limit
);
940 void *xmmap_gently(void *start
, size_t length
,
941 int prot
, int flags
, int fd
, off_t offset
)
945 mmap_limit_check(length
);
946 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
947 if (ret
== MAP_FAILED
) {
950 release_pack_memory(length
);
951 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
956 void *xmmap(void *start
, size_t length
,
957 int prot
, int flags
, int fd
, off_t offset
)
959 void *ret
= xmmap_gently(start
, length
, prot
, flags
, fd
, offset
);
960 if (ret
== MAP_FAILED
)
961 die_errno("mmap failed");
965 void close_pack_windows(struct packed_git
*p
)
968 struct pack_window
*w
= p
->windows
;
971 die("pack '%s' still has open windows to it",
973 munmap(w
->base
, w
->len
);
974 pack_mapped
-= w
->len
;
976 p
->windows
= w
->next
;
981 static int close_pack_fd(struct packed_git
*p
)
993 static void close_pack(struct packed_git
*p
)
995 close_pack_windows(p
);
1000 void close_all_packs(void)
1002 struct packed_git
*p
;
1004 for (p
= packed_git
; p
; p
= p
->next
)
1005 if (p
->do_not_close
)
1006 die("BUG: want to close pack marked 'do-not-close'");
1013 * The LRU pack is the one with the oldest MRU window, preferring packs
1014 * with no used windows, or the oldest mtime if it has no windows allocated.
1016 static void find_lru_pack(struct packed_git
*p
, struct packed_git
**lru_p
, struct pack_window
**mru_w
, int *accept_windows_inuse
)
1018 struct pack_window
*w
, *this_mru_w
;
1019 int has_windows_inuse
= 0;
1022 * Reject this pack if it has windows and the previously selected
1023 * one does not. If this pack does not have windows, reject
1024 * it if the pack file is newer than the previously selected one.
1026 if (*lru_p
&& !*mru_w
&& (p
->windows
|| p
->mtime
> (*lru_p
)->mtime
))
1029 for (w
= this_mru_w
= p
->windows
; w
; w
= w
->next
) {
1031 * Reject this pack if any of its windows are in use,
1032 * but the previously selected pack did not have any
1033 * inuse windows. Otherwise, record that this pack
1034 * has windows in use.
1037 if (*accept_windows_inuse
)
1038 has_windows_inuse
= 1;
1043 if (w
->last_used
> this_mru_w
->last_used
)
1047 * Reject this pack if it has windows that have been
1048 * used more recently than the previously selected pack.
1049 * If the previously selected pack had windows inuse and
1050 * we have not encountered a window in this pack that is
1051 * inuse, skip this check since we prefer a pack with no
1052 * inuse windows to one that has inuse windows.
1054 if (*mru_w
&& *accept_windows_inuse
== has_windows_inuse
&&
1055 this_mru_w
->last_used
> (*mru_w
)->last_used
)
1062 *mru_w
= this_mru_w
;
1064 *accept_windows_inuse
= has_windows_inuse
;
1067 static int close_one_pack(void)
1069 struct packed_git
*p
, *lru_p
= NULL
;
1070 struct pack_window
*mru_w
= NULL
;
1071 int accept_windows_inuse
= 1;
1073 for (p
= packed_git
; p
; p
= p
->next
) {
1074 if (p
->pack_fd
== -1)
1076 find_lru_pack(p
, &lru_p
, &mru_w
, &accept_windows_inuse
);
1080 return close_pack_fd(lru_p
);
1085 void unuse_pack(struct pack_window
**w_cursor
)
1087 struct pack_window
*w
= *w_cursor
;
1094 void close_pack_index(struct packed_git
*p
)
1096 if (p
->index_data
) {
1097 munmap((void *)p
->index_data
, p
->index_size
);
1098 p
->index_data
= NULL
;
1102 static unsigned int get_max_fd_limit(void)
1104 #ifdef RLIMIT_NOFILE
1108 if (!getrlimit(RLIMIT_NOFILE
, &lim
))
1109 return lim
.rlim_cur
;
1115 long open_max
= sysconf(_SC_OPEN_MAX
);
1119 * Otherwise, we got -1 for one of the two
1122 * (1) sysconf() did not understand _SC_OPEN_MAX
1123 * and signaled an error with -1; or
1124 * (2) sysconf() said there is no limit.
1126 * We _could_ clear errno before calling sysconf() to
1127 * tell these two cases apart and return a huge number
1128 * in the latter case to let the caller cap it to a
1129 * value that is not so selfish, but letting the
1130 * fallback OPEN_MAX codepath take care of these cases
1139 return 1; /* see the caller ;-) */
1144 * Do not call this directly as this leaks p->pack_fd on error return;
1145 * call open_packed_git() instead.
1147 static int open_packed_git_1(struct packed_git
*p
)
1150 struct pack_header hdr
;
1151 unsigned char sha1
[20];
1152 unsigned char *idx_sha1
;
1155 if (!p
->index_data
&& open_pack_index(p
))
1156 return error("packfile %s index unavailable", p
->pack_name
);
1158 if (!pack_max_fds
) {
1159 unsigned int max_fds
= get_max_fd_limit();
1161 /* Save 3 for stdin/stdout/stderr, 22 for work */
1163 pack_max_fds
= max_fds
- 25;
1168 while (pack_max_fds
<= pack_open_fds
&& close_one_pack())
1171 p
->pack_fd
= git_open(p
->pack_name
);
1172 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
1176 /* If we created the struct before we had the pack we lack size. */
1177 if (!p
->pack_size
) {
1178 if (!S_ISREG(st
.st_mode
))
1179 return error("packfile %s not a regular file", p
->pack_name
);
1180 p
->pack_size
= st
.st_size
;
1181 } else if (p
->pack_size
!= st
.st_size
)
1182 return error("packfile %s size changed", p
->pack_name
);
1184 /* We leave these file descriptors open with sliding mmap;
1185 * there is no point keeping them open across exec(), though.
1187 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
1189 return error("cannot determine file descriptor flags");
1190 fd_flag
|= FD_CLOEXEC
;
1191 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
1192 return error("cannot set FD_CLOEXEC");
1194 /* Verify we recognize this pack file format. */
1195 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
1196 return error("file %s is far too short to be a packfile", p
->pack_name
);
1197 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
1198 return error("file %s is not a GIT packfile", p
->pack_name
);
1199 if (!pack_version_ok(hdr
.hdr_version
))
1200 return error("packfile %s is version %"PRIu32
" and not"
1201 " supported (try upgrading GIT to a newer version)",
1202 p
->pack_name
, ntohl(hdr
.hdr_version
));
1204 /* Verify the pack matches its index. */
1205 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
1206 return error("packfile %s claims to have %"PRIu32
" objects"
1207 " while index indicates %"PRIu32
" objects",
1208 p
->pack_name
, ntohl(hdr
.hdr_entries
),
1210 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
1211 return error("end of packfile %s is unavailable", p
->pack_name
);
1212 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
1213 return error("packfile %s signature is unavailable", p
->pack_name
);
1214 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
1215 if (hashcmp(sha1
, idx_sha1
))
1216 return error("packfile %s does not match index", p
->pack_name
);
1220 static int open_packed_git(struct packed_git
*p
)
1222 if (!open_packed_git_1(p
))
1228 static int in_window(struct pack_window
*win
, off_t offset
)
1230 /* We must promise at least 20 bytes (one hash) after the
1231 * offset is available from this window, otherwise the offset
1232 * is not actually in this window and a different window (which
1233 * has that one hash excess) must be used. This is to support
1234 * the object header and delta base parsing routines below.
1236 off_t win_off
= win
->offset
;
1237 return win_off
<= offset
1238 && (offset
+ 20) <= (win_off
+ win
->len
);
1241 unsigned char *use_pack(struct packed_git
*p
,
1242 struct pack_window
**w_cursor
,
1244 unsigned long *left
)
1246 struct pack_window
*win
= *w_cursor
;
1248 /* Since packfiles end in a hash of their content and it's
1249 * pointless to ask for an offset into the middle of that
1250 * hash, and the in_window function above wouldn't match
1251 * don't allow an offset too close to the end of the file.
1253 if (!p
->pack_size
&& p
->pack_fd
== -1 && open_packed_git(p
))
1254 die("packfile %s cannot be accessed", p
->pack_name
);
1255 if (offset
> (p
->pack_size
- 20))
1256 die("offset beyond end of packfile (truncated pack?)");
1258 die(_("offset before end of packfile (broken .idx?)"));
1260 if (!win
|| !in_window(win
, offset
)) {
1263 for (win
= p
->windows
; win
; win
= win
->next
) {
1264 if (in_window(win
, offset
))
1268 size_t window_align
= packed_git_window_size
/ 2;
1271 if (p
->pack_fd
== -1 && open_packed_git(p
))
1272 die("packfile %s cannot be accessed", p
->pack_name
);
1274 win
= xcalloc(1, sizeof(*win
));
1275 win
->offset
= (offset
/ window_align
) * window_align
;
1276 len
= p
->pack_size
- win
->offset
;
1277 if (len
> packed_git_window_size
)
1278 len
= packed_git_window_size
;
1279 win
->len
= (size_t)len
;
1280 pack_mapped
+= win
->len
;
1281 while (packed_git_limit
< pack_mapped
1282 && unuse_one_window(p
))
1284 win
->base
= xmmap(NULL
, win
->len
,
1285 PROT_READ
, MAP_PRIVATE
,
1286 p
->pack_fd
, win
->offset
);
1287 if (win
->base
== MAP_FAILED
)
1288 die_errno("packfile %s cannot be mapped",
1290 if (!win
->offset
&& win
->len
== p
->pack_size
1291 && !p
->do_not_close
)
1294 pack_open_windows
++;
1295 if (pack_mapped
> peak_pack_mapped
)
1296 peak_pack_mapped
= pack_mapped
;
1297 if (pack_open_windows
> peak_pack_open_windows
)
1298 peak_pack_open_windows
= pack_open_windows
;
1299 win
->next
= p
->windows
;
1303 if (win
!= *w_cursor
) {
1304 win
->last_used
= pack_used_ctr
++;
1308 offset
-= win
->offset
;
1310 *left
= win
->len
- xsize_t(offset
);
1311 return win
->base
+ offset
;
1314 static struct packed_git
*alloc_packed_git(int extra
)
1316 struct packed_git
*p
= xmalloc(st_add(sizeof(*p
), extra
));
1317 memset(p
, 0, sizeof(*p
));
1322 static void try_to_free_pack_memory(size_t size
)
1324 release_pack_memory(size
);
1327 struct packed_git
*add_packed_git(const char *path
, size_t path_len
, int local
)
1329 static int have_set_try_to_free_routine
;
1332 struct packed_git
*p
;
1334 if (!have_set_try_to_free_routine
) {
1335 have_set_try_to_free_routine
= 1;
1336 set_try_to_free_routine(try_to_free_pack_memory
);
1340 * Make sure a corresponding .pack file exists and that
1341 * the index looks sane.
1343 if (!strip_suffix_mem(path
, &path_len
, ".idx"))
1347 * ".pack" is long enough to hold any suffix we're adding (and
1348 * the use xsnprintf double-checks that)
1350 alloc
= st_add3(path_len
, strlen(".pack"), 1);
1351 p
= alloc_packed_git(alloc
);
1352 memcpy(p
->pack_name
, path
, path_len
);
1354 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".keep");
1355 if (!access(p
->pack_name
, F_OK
))
1358 xsnprintf(p
->pack_name
+ path_len
, alloc
- path_len
, ".pack");
1359 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
1364 /* ok, it looks sane as far as we can check without
1365 * actually mapping the pack file.
1367 p
->pack_size
= st
.st_size
;
1368 p
->pack_local
= local
;
1369 p
->mtime
= st
.st_mtime
;
1370 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
1375 struct packed_git
*parse_pack_index(unsigned char *sha1
, const char *idx_path
)
1377 const char *path
= sha1_pack_name(sha1
);
1378 size_t alloc
= st_add(strlen(path
), 1);
1379 struct packed_git
*p
= alloc_packed_git(alloc
);
1381 memcpy(p
->pack_name
, path
, alloc
); /* includes NUL */
1382 hashcpy(p
->sha1
, sha1
);
1383 if (check_packed_git_idx(idx_path
, p
)) {
1391 void install_packed_git(struct packed_git
*pack
)
1393 if (pack
->pack_fd
!= -1)
1396 pack
->next
= packed_git
;
1400 void (*report_garbage
)(unsigned seen_bits
, const char *path
);
1402 static void report_helper(const struct string_list
*list
,
1403 int seen_bits
, int first
, int last
)
1405 if (seen_bits
== (PACKDIR_FILE_PACK
|PACKDIR_FILE_IDX
))
1408 for (; first
< last
; first
++)
1409 report_garbage(seen_bits
, list
->items
[first
].string
);
1412 static void report_pack_garbage(struct string_list
*list
)
1414 int i
, baselen
= -1, first
= 0, seen_bits
= 0;
1416 if (!report_garbage
)
1419 string_list_sort(list
);
1421 for (i
= 0; i
< list
->nr
; i
++) {
1422 const char *path
= list
->items
[i
].string
;
1423 if (baselen
!= -1 &&
1424 strncmp(path
, list
->items
[first
].string
, baselen
)) {
1425 report_helper(list
, seen_bits
, first
, i
);
1429 if (baselen
== -1) {
1430 const char *dot
= strrchr(path
, '.');
1432 report_garbage(PACKDIR_FILE_GARBAGE
, path
);
1435 baselen
= dot
- path
+ 1;
1438 if (!strcmp(path
+ baselen
, "pack"))
1440 else if (!strcmp(path
+ baselen
, "idx"))
1443 report_helper(list
, seen_bits
, first
, list
->nr
);
1446 static void prepare_packed_git_one(char *objdir
, int local
)
1448 struct strbuf path
= STRBUF_INIT
;
1452 struct string_list garbage
= STRING_LIST_INIT_DUP
;
1454 strbuf_addstr(&path
, objdir
);
1455 strbuf_addstr(&path
, "/pack");
1456 dir
= opendir(path
.buf
);
1458 if (errno
!= ENOENT
)
1459 error_errno("unable to open object pack directory: %s",
1461 strbuf_release(&path
);
1464 strbuf_addch(&path
, '/');
1465 dirnamelen
= path
.len
;
1466 while ((de
= readdir(dir
)) != NULL
) {
1467 struct packed_git
*p
;
1470 if (is_dot_or_dotdot(de
->d_name
))
1473 strbuf_setlen(&path
, dirnamelen
);
1474 strbuf_addstr(&path
, de
->d_name
);
1476 base_len
= path
.len
;
1477 if (strip_suffix_mem(path
.buf
, &base_len
, ".idx")) {
1478 /* Don't reopen a pack we already have. */
1479 for (p
= packed_git
; p
; p
= p
->next
) {
1481 if (strip_suffix(p
->pack_name
, ".pack", &len
) &&
1483 !memcmp(p
->pack_name
, path
.buf
, len
))
1488 * See if it really is a valid .idx file with
1489 * corresponding .pack file that we can map.
1491 (p
= add_packed_git(path
.buf
, path
.len
, local
)) != NULL
)
1492 install_packed_git(p
);
1495 if (!report_garbage
)
1498 if (ends_with(de
->d_name
, ".idx") ||
1499 ends_with(de
->d_name
, ".pack") ||
1500 ends_with(de
->d_name
, ".bitmap") ||
1501 ends_with(de
->d_name
, ".keep"))
1502 string_list_append(&garbage
, path
.buf
);
1504 report_garbage(PACKDIR_FILE_GARBAGE
, path
.buf
);
1507 report_pack_garbage(&garbage
);
1508 string_list_clear(&garbage
, 0);
1509 strbuf_release(&path
);
1512 static int approximate_object_count_valid
;
1515 * Give a fast, rough count of the number of objects in the repository. This
1516 * ignores loose objects completely. If you have a lot of them, then either
1517 * you should repack because your performance will be awful, or they are
1518 * all unreachable objects about to be pruned, in which case they're not really
1519 * interesting as a measure of repo size in the first place.
1521 unsigned long approximate_object_count(void)
1523 static unsigned long count
;
1524 if (!approximate_object_count_valid
) {
1525 struct packed_git
*p
;
1527 prepare_packed_git();
1529 for (p
= packed_git
; p
; p
= p
->next
) {
1530 if (open_pack_index(p
))
1532 count
+= p
->num_objects
;
1538 static void *get_next_packed_git(const void *p
)
1540 return ((const struct packed_git
*)p
)->next
;
1543 static void set_next_packed_git(void *p
, void *next
)
1545 ((struct packed_git
*)p
)->next
= next
;
1548 static int sort_pack(const void *a_
, const void *b_
)
1550 const struct packed_git
*a
= a_
;
1551 const struct packed_git
*b
= b_
;
1555 * Local packs tend to contain objects specific to our
1556 * variant of the project than remote ones. In addition,
1557 * remote ones could be on a network mounted filesystem.
1558 * Favor local ones for these reasons.
1560 st
= a
->pack_local
- b
->pack_local
;
1565 * Younger packs tend to contain more recent objects,
1566 * and more recent objects tend to get accessed more
1569 if (a
->mtime
< b
->mtime
)
1571 else if (a
->mtime
== b
->mtime
)
1576 static void rearrange_packed_git(void)
1578 packed_git
= llist_mergesort(packed_git
, get_next_packed_git
,
1579 set_next_packed_git
, sort_pack
);
1582 static void prepare_packed_git_mru(void)
1584 struct packed_git
*p
;
1586 mru_clear(packed_git_mru
);
1587 for (p
= packed_git
; p
; p
= p
->next
)
1588 mru_append(packed_git_mru
, p
);
1591 static int prepare_packed_git_run_once
= 0;
1592 void prepare_packed_git(void)
1594 struct alternate_object_database
*alt
;
1596 if (prepare_packed_git_run_once
)
1598 prepare_packed_git_one(get_object_directory(), 1);
1600 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
)
1601 prepare_packed_git_one(alt
->path
, 0);
1602 rearrange_packed_git();
1603 prepare_packed_git_mru();
1604 prepare_packed_git_run_once
= 1;
1607 void reprepare_packed_git(void)
1609 approximate_object_count_valid
= 0;
1610 prepare_packed_git_run_once
= 0;
1611 prepare_packed_git();
1614 static void mark_bad_packed_object(struct packed_git
*p
,
1615 const unsigned char *sha1
)
1618 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1619 if (!hashcmp(sha1
, p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* i
))
1621 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
,
1622 st_mult(GIT_SHA1_RAWSZ
,
1623 st_add(p
->num_bad_objects
, 1)));
1624 hashcpy(p
->bad_object_sha1
+ GIT_SHA1_RAWSZ
* p
->num_bad_objects
, sha1
);
1625 p
->num_bad_objects
++;
1628 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1630 struct packed_git
*p
;
1633 for (p
= packed_git
; p
; p
= p
->next
)
1634 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1635 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1641 * With an in-core object data in "map", rehash it to make sure the
1642 * object name actually matches "sha1" to detect object corruption.
1643 * With "map" == NULL, try reading the object named with "sha1" using
1644 * the streaming interface and rehash it to do the same.
1646 int check_sha1_signature(const unsigned char *sha1
, void *map
,
1647 unsigned long size
, const char *type
)
1649 unsigned char real_sha1
[20];
1650 enum object_type obj_type
;
1651 struct git_istream
*st
;
1657 hash_sha1_file(map
, size
, type
, real_sha1
);
1658 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1661 st
= open_istream(sha1
, &obj_type
, &size
, NULL
);
1665 /* Generate the header */
1666 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(obj_type
), size
) + 1;
1670 git_SHA1_Update(&c
, hdr
, hdrlen
);
1672 char buf
[1024 * 16];
1673 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
1681 git_SHA1_Update(&c
, buf
, readlen
);
1683 git_SHA1_Final(real_sha1
, &c
);
1685 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1688 int git_open(const char *name
)
1690 static int sha1_file_open_flag
= O_NOATIME
| O_CLOEXEC
;
1696 fd
= open(name
, O_RDONLY
| sha1_file_open_flag
);
1700 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1701 if ((sha1_file_open_flag
& O_CLOEXEC
) && errno
== EINVAL
) {
1702 sha1_file_open_flag
&= ~O_CLOEXEC
;
1706 /* Might the failure be due to O_NOATIME? */
1707 if (errno
!= ENOENT
&& (sha1_file_open_flag
& O_NOATIME
)) {
1708 sha1_file_open_flag
&= ~O_NOATIME
;
1715 static int stat_sha1_file(const unsigned char *sha1
, struct stat
*st
)
1717 struct alternate_object_database
*alt
;
1719 if (!lstat(sha1_file_name(sha1
), st
))
1724 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1725 const char *path
= alt_sha1_path(alt
, sha1
);
1726 if (!lstat(path
, st
))
1733 static int open_sha1_file(const unsigned char *sha1
)
1736 struct alternate_object_database
*alt
;
1737 int most_interesting_errno
;
1739 fd
= git_open(sha1_file_name(sha1
));
1742 most_interesting_errno
= errno
;
1745 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1746 const char *path
= alt_sha1_path(alt
, sha1
);
1747 fd
= git_open(path
);
1750 if (most_interesting_errno
== ENOENT
)
1751 most_interesting_errno
= errno
;
1753 errno
= most_interesting_errno
;
1757 void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1762 fd
= open_sha1_file(sha1
);
1767 if (!fstat(fd
, &st
)) {
1768 *size
= xsize_t(st
.st_size
);
1770 /* mmap() is forbidden on empty files */
1771 error("object file %s is empty", sha1_file_name(sha1
));
1774 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1781 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1782 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1785 unsigned long size
, c
;
1786 unsigned long used
= 0;
1789 *type
= (c
>> 4) & 7;
1793 if (len
<= used
|| bitsizeof(long) <= shift
) {
1794 error("bad object header");
1799 size
+= (c
& 0x7f) << shift
;
1806 static int unpack_sha1_short_header(git_zstream
*stream
,
1807 unsigned char *map
, unsigned long mapsize
,
1808 void *buffer
, unsigned long bufsiz
)
1810 /* Get the data stream */
1811 memset(stream
, 0, sizeof(*stream
));
1812 stream
->next_in
= map
;
1813 stream
->avail_in
= mapsize
;
1814 stream
->next_out
= buffer
;
1815 stream
->avail_out
= bufsiz
;
1817 git_inflate_init(stream
);
1818 return git_inflate(stream
, 0);
1821 int unpack_sha1_header(git_zstream
*stream
,
1822 unsigned char *map
, unsigned long mapsize
,
1823 void *buffer
, unsigned long bufsiz
)
1825 int status
= unpack_sha1_short_header(stream
, map
, mapsize
,
1831 /* Make sure we have the terminating NUL */
1832 if (!memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1837 static int unpack_sha1_header_to_strbuf(git_zstream
*stream
, unsigned char *map
,
1838 unsigned long mapsize
, void *buffer
,
1839 unsigned long bufsiz
, struct strbuf
*header
)
1843 status
= unpack_sha1_short_header(stream
, map
, mapsize
, buffer
, bufsiz
);
1848 * Check if entire header is unpacked in the first iteration.
1850 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1854 * buffer[0..bufsiz] was not large enough. Copy the partial
1855 * result out to header, and then append the result of further
1856 * reading the stream.
1858 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1859 stream
->next_out
= buffer
;
1860 stream
->avail_out
= bufsiz
;
1863 status
= git_inflate(stream
, 0);
1864 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1865 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1867 stream
->next_out
= buffer
;
1868 stream
->avail_out
= bufsiz
;
1869 } while (status
!= Z_STREAM_END
);
1873 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1875 int bytes
= strlen(buffer
) + 1;
1876 unsigned char *buf
= xmallocz(size
);
1880 n
= stream
->total_out
- bytes
;
1883 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1885 if (bytes
<= size
) {
1887 * The above condition must be (bytes <= size), not
1888 * (bytes < size). In other words, even though we
1889 * expect no more output and set avail_out to zero,
1890 * the input zlib stream may have bytes that express
1891 * "this concludes the stream", and we *do* want to
1894 * Otherwise we would not be able to test that we
1895 * consumed all the input to reach the expected size;
1896 * we also want to check that zlib tells us that all
1897 * went well with status == Z_STREAM_END at the end.
1899 stream
->next_out
= buf
+ bytes
;
1900 stream
->avail_out
= size
- bytes
;
1901 while (status
== Z_OK
)
1902 status
= git_inflate(stream
, Z_FINISH
);
1904 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1905 git_inflate_end(stream
);
1910 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1911 else if (stream
->avail_in
)
1912 error("garbage at end of loose object '%s'",
1919 * We used to just use "sscanf()", but that's actually way
1920 * too permissive for what we want to check. So do an anal
1921 * object header parse by hand.
1923 static int parse_sha1_header_extended(const char *hdr
, struct object_info
*oi
,
1926 const char *type_buf
= hdr
;
1928 int type
, type_len
= 0;
1931 * The type can be of any size but is followed by
1943 type
= type_from_string_gently(type_buf
, type_len
, 1);
1945 strbuf_add(oi
->typename
, type_buf
, type_len
);
1947 * Set type to 0 if its an unknown object and
1948 * we're obtaining the type using '--allow-unknown-type'
1951 if ((flags
& LOOKUP_UNKNOWN_OBJECT
) && (type
< 0))
1954 die("invalid object type");
1959 * The length must follow immediately, and be in canonical
1960 * decimal format (ie "010" is not valid).
1962 size
= *hdr
++ - '0';
1967 unsigned long c
= *hdr
- '0';
1971 size
= size
* 10 + c
;
1979 * The length must be followed by a zero byte
1981 return *hdr
? -1 : type
;
1984 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1986 struct object_info oi
= OBJECT_INFO_INIT
;
1989 return parse_sha1_header_extended(hdr
, &oi
, LOOKUP_REPLACE_OBJECT
);
1992 static void *unpack_sha1_file(void *map
, unsigned long mapsize
, enum object_type
*type
, unsigned long *size
, const unsigned char *sha1
)
1998 ret
= unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
));
1999 if (ret
< Z_OK
|| (*type
= parse_sha1_header(hdr
, size
)) < 0)
2002 return unpack_sha1_rest(&stream
, hdr
, *size
, sha1
);
2005 unsigned long get_size_from_delta(struct packed_git
*p
,
2006 struct pack_window
**w_curs
,
2009 const unsigned char *data
;
2010 unsigned char delta_head
[20], *in
;
2014 memset(&stream
, 0, sizeof(stream
));
2015 stream
.next_out
= delta_head
;
2016 stream
.avail_out
= sizeof(delta_head
);
2018 git_inflate_init(&stream
);
2020 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
2021 stream
.next_in
= in
;
2022 st
= git_inflate(&stream
, Z_FINISH
);
2023 curpos
+= stream
.next_in
- in
;
2024 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
2025 stream
.total_out
< sizeof(delta_head
));
2026 git_inflate_end(&stream
);
2027 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
2028 error("delta data unpack-initial failed");
2032 /* Examine the initial part of the delta to figure out
2037 /* ignore base size */
2038 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
2040 /* Read the result size */
2041 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
2044 static off_t
get_delta_base(struct packed_git
*p
,
2045 struct pack_window
**w_curs
,
2047 enum object_type type
,
2048 off_t delta_obj_offset
)
2050 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
2053 /* use_pack() assured us we have [base_info, base_info + 20)
2054 * as a range that we can look at without walking off the
2055 * end of the mapped window. Its actually the hash size
2056 * that is assured. An OFS_DELTA longer than the hash size
2057 * is stupid, as then a REF_DELTA would be smaller to store.
2059 if (type
== OBJ_OFS_DELTA
) {
2061 unsigned char c
= base_info
[used
++];
2062 base_offset
= c
& 127;
2065 if (!base_offset
|| MSB(base_offset
, 7))
2066 return 0; /* overflow */
2067 c
= base_info
[used
++];
2068 base_offset
= (base_offset
<< 7) + (c
& 127);
2070 base_offset
= delta_obj_offset
- base_offset
;
2071 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
2072 return 0; /* out of bound */
2074 } else if (type
== OBJ_REF_DELTA
) {
2075 /* The base entry _must_ be in the same pack */
2076 base_offset
= find_pack_entry_one(base_info
, p
);
2079 die("I am totally screwed");
2084 * Like get_delta_base above, but we return the sha1 instead of the pack
2085 * offset. This means it is cheaper for REF deltas (we do not have to do
2086 * the final object lookup), but more expensive for OFS deltas (we
2087 * have to load the revidx to convert the offset back into a sha1).
2089 static const unsigned char *get_delta_base_sha1(struct packed_git
*p
,
2090 struct pack_window
**w_curs
,
2092 enum object_type type
,
2093 off_t delta_obj_offset
)
2095 if (type
== OBJ_REF_DELTA
) {
2096 unsigned char *base
= use_pack(p
, w_curs
, curpos
, NULL
);
2098 } else if (type
== OBJ_OFS_DELTA
) {
2099 struct revindex_entry
*revidx
;
2100 off_t base_offset
= get_delta_base(p
, w_curs
, &curpos
,
2101 type
, delta_obj_offset
);
2106 revidx
= find_pack_revindex(p
, base_offset
);
2110 return nth_packed_object_sha1(p
, revidx
->nr
);
2115 int unpack_object_header(struct packed_git
*p
,
2116 struct pack_window
**w_curs
,
2118 unsigned long *sizep
)
2120 unsigned char *base
;
2123 enum object_type type
;
2125 /* use_pack() assures us we have [base, base + 20) available
2126 * as a range that we can look at. (Its actually the hash
2127 * size that is assured.) With our object header encoding
2128 * the maximum deflated object size is 2^137, which is just
2129 * insane, so we know won't exceed what we have been given.
2131 base
= use_pack(p
, w_curs
, *curpos
, &left
);
2132 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
2141 static int retry_bad_packed_offset(struct packed_git
*p
, off_t obj_offset
)
2144 struct revindex_entry
*revidx
;
2145 const unsigned char *sha1
;
2146 revidx
= find_pack_revindex(p
, obj_offset
);
2149 sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2150 mark_bad_packed_object(p
, sha1
);
2151 type
= sha1_object_info(sha1
, NULL
);
2152 if (type
<= OBJ_NONE
)
2157 #define POI_STACK_PREALLOC 64
2159 static enum object_type
packed_to_object_type(struct packed_git
*p
,
2161 enum object_type type
,
2162 struct pack_window
**w_curs
,
2165 off_t small_poi_stack
[POI_STACK_PREALLOC
];
2166 off_t
*poi_stack
= small_poi_stack
;
2167 int poi_stack_nr
= 0, poi_stack_alloc
= POI_STACK_PREALLOC
;
2169 while (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2172 /* Push the object we're going to leave behind */
2173 if (poi_stack_nr
>= poi_stack_alloc
&& poi_stack
== small_poi_stack
) {
2174 poi_stack_alloc
= alloc_nr(poi_stack_nr
);
2175 ALLOC_ARRAY(poi_stack
, poi_stack_alloc
);
2176 memcpy(poi_stack
, small_poi_stack
, sizeof(off_t
)*poi_stack_nr
);
2178 ALLOC_GROW(poi_stack
, poi_stack_nr
+1, poi_stack_alloc
);
2180 poi_stack
[poi_stack_nr
++] = obj_offset
;
2181 /* If parsing the base offset fails, just unwind */
2182 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
2185 curpos
= obj_offset
= base_offset
;
2186 type
= unpack_object_header(p
, w_curs
, &curpos
, &size
);
2187 if (type
<= OBJ_NONE
) {
2188 /* If getting the base itself fails, we first
2189 * retry the base, otherwise unwind */
2190 type
= retry_bad_packed_offset(p
, base_offset
);
2191 if (type
> OBJ_NONE
)
2205 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2206 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2211 if (poi_stack
!= small_poi_stack
)
2216 while (poi_stack_nr
) {
2217 obj_offset
= poi_stack
[--poi_stack_nr
];
2218 type
= retry_bad_packed_offset(p
, obj_offset
);
2219 if (type
> OBJ_NONE
)
2226 int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
2227 struct object_info
*oi
)
2229 struct pack_window
*w_curs
= NULL
;
2231 off_t curpos
= obj_offset
;
2232 enum object_type type
;
2235 * We always get the representation type, but only convert it to
2236 * a "real" type later if the caller is interested.
2238 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2241 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2242 off_t tmp_pos
= curpos
;
2243 off_t base_offset
= get_delta_base(p
, &w_curs
, &tmp_pos
,
2249 *oi
->sizep
= get_size_from_delta(p
, &w_curs
, tmp_pos
);
2250 if (*oi
->sizep
== 0) {
2259 if (oi
->disk_sizep
) {
2260 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2261 *oi
->disk_sizep
= revidx
[1].offset
- obj_offset
;
2265 *oi
->typep
= packed_to_object_type(p
, obj_offset
, type
, &w_curs
, curpos
);
2266 if (*oi
->typep
< 0) {
2272 if (oi
->delta_base_sha1
) {
2273 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
2274 const unsigned char *base
;
2276 base
= get_delta_base_sha1(p
, &w_curs
, curpos
,
2283 hashcpy(oi
->delta_base_sha1
, base
);
2285 hashclr(oi
->delta_base_sha1
);
2289 unuse_pack(&w_curs
);
2293 static void *unpack_compressed_entry(struct packed_git
*p
,
2294 struct pack_window
**w_curs
,
2300 unsigned char *buffer
, *in
;
2302 buffer
= xmallocz_gently(size
);
2305 memset(&stream
, 0, sizeof(stream
));
2306 stream
.next_out
= buffer
;
2307 stream
.avail_out
= size
+ 1;
2309 git_inflate_init(&stream
);
2311 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
2312 stream
.next_in
= in
;
2313 st
= git_inflate(&stream
, Z_FINISH
);
2314 if (!stream
.avail_out
)
2315 break; /* the payload is larger than it should be */
2316 curpos
+= stream
.next_in
- in
;
2317 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
2318 git_inflate_end(&stream
);
2319 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
2327 static struct hashmap delta_base_cache
;
2328 static size_t delta_base_cached
;
2330 static LIST_HEAD(delta_base_cache_lru
);
2332 struct delta_base_cache_key
{
2333 struct packed_git
*p
;
2337 struct delta_base_cache_entry
{
2338 struct hashmap hash
;
2339 struct delta_base_cache_key key
;
2340 struct list_head lru
;
2343 enum object_type type
;
2346 static unsigned int pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
2350 hash
= (unsigned int)(intptr_t)p
+ (unsigned int)base_offset
;
2351 hash
+= (hash
>> 8) + (hash
>> 16);
2355 static struct delta_base_cache_entry
*
2356 get_delta_base_cache_entry(struct packed_git
*p
, off_t base_offset
)
2358 struct hashmap_entry entry
;
2359 struct delta_base_cache_key key
;
2361 if (!delta_base_cache
.cmpfn
)
2364 hashmap_entry_init(&entry
, pack_entry_hash(p
, base_offset
));
2366 key
.base_offset
= base_offset
;
2367 return hashmap_get(&delta_base_cache
, &entry
, &key
);
2370 static int delta_base_cache_key_eq(const struct delta_base_cache_key
*a
,
2371 const struct delta_base_cache_key
*b
)
2373 return a
->p
== b
->p
&& a
->base_offset
== b
->base_offset
;
2376 static int delta_base_cache_hash_cmp(const void *va
, const void *vb
,
2379 const struct delta_base_cache_entry
*a
= va
, *b
= vb
;
2380 const struct delta_base_cache_key
*key
= vkey
;
2382 return !delta_base_cache_key_eq(&a
->key
, key
);
2384 return !delta_base_cache_key_eq(&a
->key
, &b
->key
);
2387 static int in_delta_base_cache(struct packed_git
*p
, off_t base_offset
)
2389 return !!get_delta_base_cache_entry(p
, base_offset
);
2393 * Remove the entry from the cache, but do _not_ free the associated
2394 * entry data. The caller takes ownership of the "data" buffer, and
2395 * should copy out any fields it wants before detaching.
2397 static void detach_delta_base_cache_entry(struct delta_base_cache_entry
*ent
)
2399 hashmap_remove(&delta_base_cache
, ent
, &ent
->key
);
2400 list_del(&ent
->lru
);
2401 delta_base_cached
-= ent
->size
;
2405 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
2406 unsigned long *base_size
, enum object_type
*type
)
2408 struct delta_base_cache_entry
*ent
;
2410 ent
= get_delta_base_cache_entry(p
, base_offset
);
2412 return unpack_entry(p
, base_offset
, type
, base_size
);
2415 *base_size
= ent
->size
;
2416 return xmemdupz(ent
->data
, ent
->size
);
2419 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
2422 detach_delta_base_cache_entry(ent
);
2425 void clear_delta_base_cache(void)
2427 struct hashmap_iter iter
;
2428 struct delta_base_cache_entry
*entry
;
2429 for (entry
= hashmap_iter_first(&delta_base_cache
, &iter
);
2431 entry
= hashmap_iter_next(&iter
)) {
2432 release_delta_base_cache(entry
);
2436 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
2437 void *base
, unsigned long base_size
, enum object_type type
)
2439 struct delta_base_cache_entry
*ent
= xmalloc(sizeof(*ent
));
2440 struct list_head
*lru
, *tmp
;
2442 delta_base_cached
+= base_size
;
2444 list_for_each_safe(lru
, tmp
, &delta_base_cache_lru
) {
2445 struct delta_base_cache_entry
*f
=
2446 list_entry(lru
, struct delta_base_cache_entry
, lru
);
2447 if (delta_base_cached
<= delta_base_cache_limit
)
2449 release_delta_base_cache(f
);
2453 ent
->key
.base_offset
= base_offset
;
2456 ent
->size
= base_size
;
2457 list_add_tail(&ent
->lru
, &delta_base_cache_lru
);
2459 if (!delta_base_cache
.cmpfn
)
2460 hashmap_init(&delta_base_cache
, delta_base_cache_hash_cmp
, 0);
2461 hashmap_entry_init(ent
, pack_entry_hash(p
, base_offset
));
2462 hashmap_add(&delta_base_cache
, ent
);
2465 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2466 unsigned long *size
);
2468 static void write_pack_access_log(struct packed_git
*p
, off_t obj_offset
)
2470 static struct trace_key pack_access
= TRACE_KEY_INIT(PACK_ACCESS
);
2471 trace_printf_key(&pack_access
, "%s %"PRIuMAX
"\n",
2472 p
->pack_name
, (uintmax_t)obj_offset
);
2475 int do_check_packed_object_crc
;
2477 #define UNPACK_ENTRY_STACK_PREALLOC 64
2478 struct unpack_entry_stack_ent
{
2484 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
2485 enum object_type
*final_type
, unsigned long *final_size
)
2487 struct pack_window
*w_curs
= NULL
;
2488 off_t curpos
= obj_offset
;
2491 enum object_type type
;
2492 struct unpack_entry_stack_ent small_delta_stack
[UNPACK_ENTRY_STACK_PREALLOC
];
2493 struct unpack_entry_stack_ent
*delta_stack
= small_delta_stack
;
2494 int delta_stack_nr
= 0, delta_stack_alloc
= UNPACK_ENTRY_STACK_PREALLOC
;
2495 int base_from_cache
= 0;
2497 write_pack_access_log(p
, obj_offset
);
2499 /* PHASE 1: drill down to the innermost base object */
2503 struct delta_base_cache_entry
*ent
;
2505 ent
= get_delta_base_cache_entry(p
, curpos
);
2510 detach_delta_base_cache_entry(ent
);
2511 base_from_cache
= 1;
2515 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
2516 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2517 off_t len
= revidx
[1].offset
- obj_offset
;
2518 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
2519 const unsigned char *sha1
=
2520 nth_packed_object_sha1(p
, revidx
->nr
);
2521 error("bad packed object CRC for %s",
2523 mark_bad_packed_object(p
, sha1
);
2524 unuse_pack(&w_curs
);
2529 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2530 if (type
!= OBJ_OFS_DELTA
&& type
!= OBJ_REF_DELTA
)
2533 base_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
2535 error("failed to validate delta base reference "
2536 "at offset %"PRIuMAX
" from %s",
2537 (uintmax_t)curpos
, p
->pack_name
);
2538 /* bail to phase 2, in hopes of recovery */
2543 /* push object, proceed to base */
2544 if (delta_stack_nr
>= delta_stack_alloc
2545 && delta_stack
== small_delta_stack
) {
2546 delta_stack_alloc
= alloc_nr(delta_stack_nr
);
2547 ALLOC_ARRAY(delta_stack
, delta_stack_alloc
);
2548 memcpy(delta_stack
, small_delta_stack
,
2549 sizeof(*delta_stack
)*delta_stack_nr
);
2551 ALLOC_GROW(delta_stack
, delta_stack_nr
+1, delta_stack_alloc
);
2553 i
= delta_stack_nr
++;
2554 delta_stack
[i
].obj_offset
= obj_offset
;
2555 delta_stack
[i
].curpos
= curpos
;
2556 delta_stack
[i
].size
= size
;
2558 curpos
= obj_offset
= base_offset
;
2561 /* PHASE 2: handle the base */
2566 die("BUG: unpack_entry: left loop at a valid delta");
2572 if (!base_from_cache
)
2573 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, size
);
2577 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2578 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2581 /* PHASE 3: apply deltas in order */
2584 * 'data' holds the base data, or NULL if there was corruption
2586 while (delta_stack_nr
) {
2589 unsigned long delta_size
, base_size
= size
;
2595 add_delta_base_cache(p
, obj_offset
, base
, base_size
, type
);
2599 * We're probably in deep shit, but let's try to fetch
2600 * the required base anyway from another pack or loose.
2601 * This is costly but should happen only in the presence
2602 * of a corrupted pack, and is better than failing outright.
2604 struct revindex_entry
*revidx
;
2605 const unsigned char *base_sha1
;
2606 revidx
= find_pack_revindex(p
, obj_offset
);
2608 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2609 error("failed to read delta base object %s"
2610 " at offset %"PRIuMAX
" from %s",
2611 sha1_to_hex(base_sha1
), (uintmax_t)obj_offset
,
2613 mark_bad_packed_object(p
, base_sha1
);
2614 base
= read_object(base_sha1
, &type
, &base_size
);
2618 i
= --delta_stack_nr
;
2619 obj_offset
= delta_stack
[i
].obj_offset
;
2620 curpos
= delta_stack
[i
].curpos
;
2621 delta_size
= delta_stack
[i
].size
;
2626 delta_data
= unpack_compressed_entry(p
, &w_curs
, curpos
, delta_size
);
2629 error("failed to unpack compressed delta "
2630 "at offset %"PRIuMAX
" from %s",
2631 (uintmax_t)curpos
, p
->pack_name
);
2636 data
= patch_delta(base
, base_size
,
2637 delta_data
, delta_size
,
2641 * We could not apply the delta; warn the user, but keep going.
2642 * Our failure will be noticed either in the next iteration of
2643 * the loop, or if this is the final delta, in the caller when
2644 * we return NULL. Those code paths will take care of making
2645 * a more explicit warning and retrying with another copy of
2649 error("failed to apply delta");
2657 unuse_pack(&w_curs
);
2659 if (delta_stack
!= small_delta_stack
)
2665 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
2668 const unsigned char *index
= p
->index_data
;
2670 if (open_pack_index(p
))
2672 index
= p
->index_data
;
2674 if (n
>= p
->num_objects
)
2677 if (p
->index_version
== 1) {
2678 return index
+ 24 * n
+ 4;
2681 return index
+ 20 * n
;
2685 void check_pack_index_ptr(const struct packed_git
*p
, const void *vptr
)
2687 const unsigned char *ptr
= vptr
;
2688 const unsigned char *start
= p
->index_data
;
2689 const unsigned char *end
= start
+ p
->index_size
;
2691 die(_("offset before start of pack index for %s (corrupt index?)"),
2693 /* No need to check for underflow; .idx files must be at least 8 bytes */
2695 die(_("offset beyond end of pack index for %s (truncated index?)"),
2699 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
2701 const unsigned char *index
= p
->index_data
;
2703 if (p
->index_version
== 1) {
2704 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
2707 index
+= 8 + p
->num_objects
* (20 + 4);
2708 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
2709 if (!(off
& 0x80000000))
2711 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
2712 check_pack_index_ptr(p
, index
);
2713 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
2714 ntohl(*((uint32_t *)(index
+ 4)));
2718 off_t
find_pack_entry_one(const unsigned char *sha1
,
2719 struct packed_git
*p
)
2721 const uint32_t *level1_ofs
= p
->index_data
;
2722 const unsigned char *index
= p
->index_data
;
2723 unsigned hi
, lo
, stride
;
2724 static int use_lookup
= -1;
2725 static int debug_lookup
= -1;
2727 if (debug_lookup
< 0)
2728 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
2731 if (open_pack_index(p
))
2733 level1_ofs
= p
->index_data
;
2734 index
= p
->index_data
;
2736 if (p
->index_version
> 1) {
2741 hi
= ntohl(level1_ofs
[*sha1
]);
2742 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
2743 if (p
->index_version
> 1) {
2751 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
2752 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
2755 use_lookup
= !!getenv("GIT_USE_LOOKUP");
2757 int pos
= sha1_entry_pos(index
, stride
, 0,
2758 lo
, hi
, p
->num_objects
, sha1
);
2761 return nth_packed_object_offset(p
, pos
);
2765 unsigned mi
= (lo
+ hi
) / 2;
2766 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
2769 printf("lo %u hi %u rg %u mi %u\n",
2770 lo
, hi
, hi
- lo
, mi
);
2772 return nth_packed_object_offset(p
, mi
);
2781 int is_pack_valid(struct packed_git
*p
)
2783 /* An already open pack is known to be valid. */
2784 if (p
->pack_fd
!= -1)
2787 /* If the pack has one window completely covering the
2788 * file size, the pack is known to be valid even if
2789 * the descriptor is not currently open.
2792 struct pack_window
*w
= p
->windows
;
2794 if (!w
->offset
&& w
->len
== p
->pack_size
)
2798 /* Force the pack to open to prove its valid. */
2799 return !open_packed_git(p
);
2802 static int fill_pack_entry(const unsigned char *sha1
,
2803 struct pack_entry
*e
,
2804 struct packed_git
*p
)
2808 if (p
->num_bad_objects
) {
2810 for (i
= 0; i
< p
->num_bad_objects
; i
++)
2811 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
2815 offset
= find_pack_entry_one(sha1
, p
);
2820 * We are about to tell the caller where they can locate the
2821 * requested object. We better make sure the packfile is
2822 * still here and can be accessed before supplying that
2823 * answer, as it may have been deleted since the index was
2826 if (!is_pack_valid(p
))
2830 hashcpy(e
->sha1
, sha1
);
2835 * Iff a pack file contains the object named by sha1, return true and
2836 * store its location to e.
2838 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
2840 struct mru_entry
*p
;
2842 prepare_packed_git();
2846 for (p
= packed_git_mru
->head
; p
; p
= p
->next
) {
2847 if (fill_pack_entry(sha1
, e
, p
->item
)) {
2848 mru_mark(packed_git_mru
, p
);
2855 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
2856 struct packed_git
*packs
)
2858 struct packed_git
*p
;
2860 for (p
= packs
; p
; p
= p
->next
) {
2861 if (find_pack_entry_one(sha1
, p
))
2868 static int sha1_loose_object_info(const unsigned char *sha1
,
2869 struct object_info
*oi
,
2873 unsigned long mapsize
;
2877 struct strbuf hdrbuf
= STRBUF_INIT
;
2879 if (oi
->delta_base_sha1
)
2880 hashclr(oi
->delta_base_sha1
);
2883 * If we don't care about type or size, then we don't
2884 * need to look inside the object at all. Note that we
2885 * do not optimize out the stat call, even if the
2886 * caller doesn't care about the disk-size, since our
2887 * return value implicitly indicates whether the
2888 * object even exists.
2890 if (!oi
->typep
&& !oi
->typename
&& !oi
->sizep
) {
2892 if (stat_sha1_file(sha1
, &st
) < 0)
2895 *oi
->disk_sizep
= st
.st_size
;
2899 map
= map_sha1_file(sha1
, &mapsize
);
2903 *oi
->disk_sizep
= mapsize
;
2904 if ((flags
& LOOKUP_UNKNOWN_OBJECT
)) {
2905 if (unpack_sha1_header_to_strbuf(&stream
, map
, mapsize
, hdr
, sizeof(hdr
), &hdrbuf
) < 0)
2906 status
= error("unable to unpack %s header with --allow-unknown-type",
2908 } else if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
2909 status
= error("unable to unpack %s header",
2913 else if (hdrbuf
.len
) {
2914 if ((status
= parse_sha1_header_extended(hdrbuf
.buf
, oi
, flags
)) < 0)
2915 status
= error("unable to parse %s header with --allow-unknown-type",
2917 } else if ((status
= parse_sha1_header_extended(hdr
, oi
, flags
)) < 0)
2918 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
2919 git_inflate_end(&stream
);
2920 munmap(map
, mapsize
);
2921 if (status
&& oi
->typep
)
2922 *oi
->typep
= status
;
2923 strbuf_release(&hdrbuf
);
2927 int sha1_object_info_extended(const unsigned char *sha1
, struct object_info
*oi
, unsigned flags
)
2929 struct cached_object
*co
;
2930 struct pack_entry e
;
2932 enum object_type real_type
;
2933 const unsigned char *real
= lookup_replace_object_extended(sha1
, flags
);
2935 co
= find_cached_object(real
);
2938 *(oi
->typep
) = co
->type
;
2940 *(oi
->sizep
) = co
->size
;
2942 *(oi
->disk_sizep
) = 0;
2943 if (oi
->delta_base_sha1
)
2944 hashclr(oi
->delta_base_sha1
);
2946 strbuf_addstr(oi
->typename
, typename(co
->type
));
2947 oi
->whence
= OI_CACHED
;
2951 if (!find_pack_entry(real
, &e
)) {
2952 /* Most likely it's a loose object. */
2953 if (!sha1_loose_object_info(real
, oi
, flags
)) {
2954 oi
->whence
= OI_LOOSE
;
2958 /* Not a loose object; someone else may have just packed it. */
2959 reprepare_packed_git();
2960 if (!find_pack_entry(real
, &e
))
2965 * packed_object_info() does not follow the delta chain to
2966 * find out the real type, unless it is given oi->typep.
2968 if (oi
->typename
&& !oi
->typep
)
2969 oi
->typep
= &real_type
;
2971 rtype
= packed_object_info(e
.p
, e
.offset
, oi
);
2973 mark_bad_packed_object(e
.p
, real
);
2974 if (oi
->typep
== &real_type
)
2976 return sha1_object_info_extended(real
, oi
, 0);
2977 } else if (in_delta_base_cache(e
.p
, e
.offset
)) {
2978 oi
->whence
= OI_DBCACHED
;
2980 oi
->whence
= OI_PACKED
;
2981 oi
->u
.packed
.offset
= e
.offset
;
2982 oi
->u
.packed
.pack
= e
.p
;
2983 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
2984 rtype
== OBJ_OFS_DELTA
);
2987 strbuf_addstr(oi
->typename
, typename(*oi
->typep
));
2988 if (oi
->typep
== &real_type
)
2994 /* returns enum object_type or negative */
2995 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
2997 enum object_type type
;
2998 struct object_info oi
= OBJECT_INFO_INIT
;
3002 if (sha1_object_info_extended(sha1
, &oi
, LOOKUP_REPLACE_OBJECT
) < 0)
3007 static void *read_packed_sha1(const unsigned char *sha1
,
3008 enum object_type
*type
, unsigned long *size
)
3010 struct pack_entry e
;
3013 if (!find_pack_entry(sha1
, &e
))
3015 data
= cache_or_unpack_entry(e
.p
, e
.offset
, size
, type
);
3018 * We're probably in deep shit, but let's try to fetch
3019 * the required object anyway from another pack or loose.
3020 * This should happen only in the presence of a corrupted
3021 * pack, and is better than failing outright.
3023 error("failed to read object %s at offset %"PRIuMAX
" from %s",
3024 sha1_to_hex(sha1
), (uintmax_t)e
.offset
, e
.p
->pack_name
);
3025 mark_bad_packed_object(e
.p
, sha1
);
3026 data
= read_object(sha1
, type
, size
);
3031 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
3032 unsigned char *sha1
)
3034 struct cached_object
*co
;
3036 hash_sha1_file(buf
, len
, typename(type
), sha1
);
3037 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
3039 ALLOC_GROW(cached_objects
, cached_object_nr
+ 1, cached_object_alloc
);
3040 co
= &cached_objects
[cached_object_nr
++];
3043 co
->buf
= xmalloc(len
);
3044 memcpy(co
->buf
, buf
, len
);
3045 hashcpy(co
->sha1
, sha1
);
3049 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
3050 unsigned long *size
)
3052 unsigned long mapsize
;
3054 struct cached_object
*co
;
3056 co
= find_cached_object(sha1
);
3060 return xmemdupz(co
->buf
, co
->size
);
3063 buf
= read_packed_sha1(sha1
, type
, size
);
3066 map
= map_sha1_file(sha1
, &mapsize
);
3068 buf
= unpack_sha1_file(map
, mapsize
, type
, size
, sha1
);
3069 munmap(map
, mapsize
);
3072 reprepare_packed_git();
3073 return read_packed_sha1(sha1
, type
, size
);
3077 * This function dies on corrupt objects; the callers who want to
3078 * deal with them should arrange to call read_object() and give error
3079 * messages themselves.
3081 void *read_sha1_file_extended(const unsigned char *sha1
,
3082 enum object_type
*type
,
3083 unsigned long *size
,
3087 const struct packed_git
*p
;
3088 const unsigned char *repl
= lookup_replace_object_extended(sha1
, flag
);
3091 data
= read_object(repl
, type
, size
);
3095 if (errno
&& errno
!= ENOENT
)
3096 die_errno("failed to read object %s", sha1_to_hex(sha1
));
3098 /* die if we replaced an object with one that does not exist */
3100 die("replacement %s not found for %s",
3101 sha1_to_hex(repl
), sha1_to_hex(sha1
));
3103 if (has_loose_object(repl
)) {
3104 const char *path
= sha1_file_name(sha1
);
3106 die("loose object %s (stored in %s) is corrupt",
3107 sha1_to_hex(repl
), path
);
3110 if ((p
= has_packed_and_bad(repl
)) != NULL
)
3111 die("packed object %s (stored in %s) is corrupt",
3112 sha1_to_hex(repl
), p
->pack_name
);
3117 void *read_object_with_reference(const unsigned char *sha1
,
3118 const char *required_type_name
,
3119 unsigned long *size
,
3120 unsigned char *actual_sha1_return
)
3122 enum object_type type
, required_type
;
3124 unsigned long isize
;
3125 unsigned char actual_sha1
[20];
3127 required_type
= type_from_string(required_type_name
);
3128 hashcpy(actual_sha1
, sha1
);
3130 int ref_length
= -1;
3131 const char *ref_type
= NULL
;
3133 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
3136 if (type
== required_type
) {
3138 if (actual_sha1_return
)
3139 hashcpy(actual_sha1_return
, actual_sha1
);
3142 /* Handle references */
3143 else if (type
== OBJ_COMMIT
)
3145 else if (type
== OBJ_TAG
)
3146 ref_type
= "object ";
3151 ref_length
= strlen(ref_type
);
3153 if (ref_length
+ 40 > isize
||
3154 memcmp(buffer
, ref_type
, ref_length
) ||
3155 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
3160 /* Now we have the ID of the referred-to object in
3161 * actual_sha1. Check again. */
3165 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
3166 const char *type
, unsigned char *sha1
,
3167 char *hdr
, int *hdrlen
)
3171 /* Generate the header */
3172 *hdrlen
= xsnprintf(hdr
, *hdrlen
, "%s %lu", type
, len
)+1;
3176 git_SHA1_Update(&c
, hdr
, *hdrlen
);
3177 git_SHA1_Update(&c
, buf
, len
);
3178 git_SHA1_Final(sha1
, &c
);
3182 * Move the just written object into its final resting place.
3184 int finalize_object_file(const char *tmpfile
, const char *filename
)
3188 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
3190 else if (link(tmpfile
, filename
))
3194 * Coda hack - coda doesn't like cross-directory links,
3195 * so we fall back to a rename, which will mean that it
3196 * won't be able to check collisions, but that's not a
3199 * The same holds for FAT formatted media.
3201 * When this succeeds, we just return. We have nothing
3204 if (ret
&& ret
!= EEXIST
) {
3206 if (!rename(tmpfile
, filename
))
3210 unlink_or_warn(tmpfile
);
3212 if (ret
!= EEXIST
) {
3213 return error_errno("unable to write sha1 filename %s", filename
);
3215 /* FIXME!!! Collision check here ? */
3219 if (adjust_shared_perm(filename
))
3220 return error("unable to set permission to '%s'", filename
);
3224 static int write_buffer(int fd
, const void *buf
, size_t len
)
3226 if (write_in_full(fd
, buf
, len
) < 0)
3227 return error_errno("file write error");
3231 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
3232 unsigned char *sha1
)
3235 int hdrlen
= sizeof(hdr
);
3236 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3240 /* Finalize a file on disk, and close it. */
3241 static void close_sha1_file(int fd
)
3243 if (fsync_object_files
)
3244 fsync_or_die(fd
, "sha1 file");
3246 die_errno("error when closing sha1 file");
3249 /* Size of directory component, including the ending '/' */
3250 static inline int directory_size(const char *filename
)
3252 const char *s
= strrchr(filename
, '/');
3255 return s
- filename
+ 1;
3259 * This creates a temporary file in the same directory as the final
3262 * We want to avoid cross-directory filename renames, because those
3263 * can have problems on various filesystems (FAT, NFS, Coda).
3265 static int create_tmpfile(struct strbuf
*tmp
, const char *filename
)
3267 int fd
, dirlen
= directory_size(filename
);
3270 strbuf_add(tmp
, filename
, dirlen
);
3271 strbuf_addstr(tmp
, "tmp_obj_XXXXXX");
3272 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
3273 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
3275 * Make sure the directory exists; note that the contents
3276 * of the buffer are undefined after mkstemp returns an
3277 * error, so we have to rewrite the whole buffer from
3281 strbuf_add(tmp
, filename
, dirlen
- 1);
3282 if (mkdir(tmp
->buf
, 0777) && errno
!= EEXIST
)
3284 if (adjust_shared_perm(tmp
->buf
))
3288 strbuf_addstr(tmp
, "/tmp_obj_XXXXXX");
3289 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
3294 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
3295 const void *buf
, unsigned long len
, time_t mtime
)
3298 unsigned char compressed
[4096];
3301 unsigned char parano_sha1
[20];
3302 static struct strbuf tmp_file
= STRBUF_INIT
;
3303 const char *filename
= sha1_file_name(sha1
);
3305 fd
= create_tmpfile(&tmp_file
, filename
);
3307 if (errno
== EACCES
)
3308 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3310 return error_errno("unable to create temporary file");
3314 git_deflate_init(&stream
, zlib_compression_level
);
3315 stream
.next_out
= compressed
;
3316 stream
.avail_out
= sizeof(compressed
);
3319 /* First header.. */
3320 stream
.next_in
= (unsigned char *)hdr
;
3321 stream
.avail_in
= hdrlen
;
3322 while (git_deflate(&stream
, 0) == Z_OK
)
3324 git_SHA1_Update(&c
, hdr
, hdrlen
);
3326 /* Then the data itself.. */
3327 stream
.next_in
= (void *)buf
;
3328 stream
.avail_in
= len
;
3330 unsigned char *in0
= stream
.next_in
;
3331 ret
= git_deflate(&stream
, Z_FINISH
);
3332 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
3333 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
3334 die("unable to write sha1 file");
3335 stream
.next_out
= compressed
;
3336 stream
.avail_out
= sizeof(compressed
);
3337 } while (ret
== Z_OK
);
3339 if (ret
!= Z_STREAM_END
)
3340 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
3341 ret
= git_deflate_end_gently(&stream
);
3343 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
3344 git_SHA1_Final(parano_sha1
, &c
);
3345 if (hashcmp(sha1
, parano_sha1
) != 0)
3346 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
3348 close_sha1_file(fd
);
3353 utb
.modtime
= mtime
;
3354 if (utime(tmp_file
.buf
, &utb
) < 0)
3355 warning_errno("failed utime() on %s", tmp_file
.buf
);
3358 return finalize_object_file(tmp_file
.buf
, filename
);
3361 static int freshen_loose_object(const unsigned char *sha1
)
3363 return check_and_freshen(sha1
, 1);
3366 static int freshen_packed_object(const unsigned char *sha1
)
3368 struct pack_entry e
;
3369 if (!find_pack_entry(sha1
, &e
))
3373 if (!freshen_file(e
.p
->pack_name
))
3379 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *sha1
)
3382 int hdrlen
= sizeof(hdr
);
3384 /* Normally if we have it in the pack then we do not bother writing
3385 * it out into .git/objects/??/?{38} file.
3387 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3388 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3390 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
3393 int hash_sha1_file_literally(const void *buf
, unsigned long len
, const char *type
,
3394 unsigned char *sha1
, unsigned flags
)
3397 int hdrlen
, status
= 0;
3399 /* type string, SP, %lu of the length plus NUL must fit this */
3400 hdrlen
= strlen(type
) + 32;
3401 header
= xmalloc(hdrlen
);
3402 write_sha1_file_prepare(buf
, len
, type
, sha1
, header
, &hdrlen
);
3404 if (!(flags
& HASH_WRITE_OBJECT
))
3406 if (freshen_packed_object(sha1
) || freshen_loose_object(sha1
))
3408 status
= write_loose_object(sha1
, header
, hdrlen
, buf
, len
, 0);
3415 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
3419 enum object_type type
;
3424 if (has_loose_object(sha1
))
3426 buf
= read_packed_sha1(sha1
, &type
, &len
);
3428 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
3429 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", typename(type
), len
) + 1;
3430 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
3436 int has_pack_index(const unsigned char *sha1
)
3439 if (stat(sha1_pack_index_name(sha1
), &st
))
3444 int has_sha1_pack(const unsigned char *sha1
)
3446 struct pack_entry e
;
3447 return find_pack_entry(sha1
, &e
);
3450 int has_sha1_file_with_flags(const unsigned char *sha1
, int flags
)
3452 struct pack_entry e
;
3454 if (find_pack_entry(sha1
, &e
))
3456 if (has_loose_object(sha1
))
3458 if (flags
& HAS_SHA1_QUICK
)
3460 reprepare_packed_git();
3461 return find_pack_entry(sha1
, &e
);
3464 int has_object_file(const struct object_id
*oid
)
3466 return has_sha1_file(oid
->hash
);
3469 int has_object_file_with_flags(const struct object_id
*oid
, int flags
)
3471 return has_sha1_file_with_flags(oid
->hash
, flags
);
3474 static void check_tree(const void *buf
, size_t size
)
3476 struct tree_desc desc
;
3477 struct name_entry entry
;
3479 init_tree_desc(&desc
, buf
, size
);
3480 while (tree_entry(&desc
, &entry
))
3482 * tree_entry() will die() on malformed entries */
3486 static void check_commit(const void *buf
, size_t size
)
3489 memset(&c
, 0, sizeof(c
));
3490 if (parse_commit_buffer(&c
, buf
, size
))
3491 die("corrupt commit");
3494 static void check_tag(const void *buf
, size_t size
)
3497 memset(&t
, 0, sizeof(t
));
3498 if (parse_tag_buffer(&t
, buf
, size
))
3502 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
3503 enum object_type type
,
3504 const char *path
, unsigned flags
)
3506 int ret
, re_allocated
= 0;
3507 int write_object
= flags
& HASH_WRITE_OBJECT
;
3513 * Convert blobs to git internal format
3515 if ((type
== OBJ_BLOB
) && path
) {
3516 struct strbuf nbuf
= STRBUF_INIT
;
3517 if (convert_to_git(path
, buf
, size
, &nbuf
,
3518 write_object
? safe_crlf
: SAFE_CRLF_FALSE
)) {
3519 buf
= strbuf_detach(&nbuf
, &size
);
3523 if (flags
& HASH_FORMAT_CHECK
) {
3524 if (type
== OBJ_TREE
)
3525 check_tree(buf
, size
);
3526 if (type
== OBJ_COMMIT
)
3527 check_commit(buf
, size
);
3528 if (type
== OBJ_TAG
)
3529 check_tag(buf
, size
);
3533 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
3535 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
3541 static int index_stream_convert_blob(unsigned char *sha1
, int fd
,
3542 const char *path
, unsigned flags
)
3545 const int write_object
= flags
& HASH_WRITE_OBJECT
;
3546 struct strbuf sbuf
= STRBUF_INIT
;
3549 assert(would_convert_to_git_filter_fd(path
));
3551 convert_to_git_filter_fd(path
, fd
, &sbuf
,
3552 write_object
? safe_crlf
: SAFE_CRLF_FALSE
);
3555 ret
= write_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3558 ret
= hash_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3560 strbuf_release(&sbuf
);
3564 static int index_pipe(unsigned char *sha1
, int fd
, enum object_type type
,
3565 const char *path
, unsigned flags
)
3567 struct strbuf sbuf
= STRBUF_INIT
;
3570 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
3571 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
3574 strbuf_release(&sbuf
);
3578 #define SMALL_FILE_SIZE (32*1024)
3580 static int index_core(unsigned char *sha1
, int fd
, size_t size
,
3581 enum object_type type
, const char *path
,
3587 ret
= index_mem(sha1
, "", size
, type
, path
, flags
);
3588 } else if (size
<= SMALL_FILE_SIZE
) {
3589 char *buf
= xmalloc(size
);
3590 if (size
== read_in_full(fd
, buf
, size
))
3591 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3593 ret
= error_errno("short read");
3596 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
3597 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3604 * This creates one packfile per large blob unless bulk-checkin
3605 * machinery is "plugged".
3607 * This also bypasses the usual "convert-to-git" dance, and that is on
3608 * purpose. We could write a streaming version of the converting
3609 * functions and insert that before feeding the data to fast-import
3610 * (or equivalent in-core API described above). However, that is
3611 * somewhat complicated, as we do not know the size of the filter
3612 * result, which we need to know beforehand when writing a git object.
3613 * Since the primary motivation for trying to stream from the working
3614 * tree file and to avoid mmaping it in core is to deal with large
3615 * binary blobs, they generally do not want to get any conversion, and
3616 * callers should avoid this code path when filters are requested.
3618 static int index_stream(unsigned char *sha1
, int fd
, size_t size
,
3619 enum object_type type
, const char *path
,
3622 return index_bulk_checkin(sha1
, fd
, size
, type
, path
, flags
);
3625 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
,
3626 enum object_type type
, const char *path
, unsigned flags
)
3631 * Call xsize_t() only when needed to avoid potentially unnecessary
3632 * die() for large files.
3634 if (type
== OBJ_BLOB
&& path
&& would_convert_to_git_filter_fd(path
))
3635 ret
= index_stream_convert_blob(sha1
, fd
, path
, flags
);
3636 else if (!S_ISREG(st
->st_mode
))
3637 ret
= index_pipe(sha1
, fd
, type
, path
, flags
);
3638 else if (st
->st_size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
3639 (path
&& would_convert_to_git(path
)))
3640 ret
= index_core(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3643 ret
= index_stream(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3649 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, unsigned flags
)
3652 struct strbuf sb
= STRBUF_INIT
;
3654 switch (st
->st_mode
& S_IFMT
) {
3656 fd
= open(path
, O_RDONLY
);
3658 return error_errno("open(\"%s\")", path
);
3659 if (index_fd(sha1
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
3660 return error("%s: failed to insert into database",
3664 if (strbuf_readlink(&sb
, path
, st
->st_size
))
3665 return error_errno("readlink(\"%s\")", path
);
3666 if (!(flags
& HASH_WRITE_OBJECT
))
3667 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
3668 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
3669 return error("%s: failed to insert into database",
3671 strbuf_release(&sb
);
3674 return resolve_gitlink_ref(path
, "HEAD", sha1
);
3676 return error("%s: unsupported file type", path
);
3681 int read_pack_header(int fd
, struct pack_header
*header
)
3683 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
3684 /* "eof before pack header was fully read" */
3685 return PH_ERROR_EOF
;
3687 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
3688 /* "protocol error (pack signature mismatch detected)" */
3689 return PH_ERROR_PACK_SIGNATURE
;
3690 if (!pack_version_ok(header
->hdr_version
))
3691 /* "protocol error (pack version unsupported)" */
3692 return PH_ERROR_PROTOCOL
;
3696 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
3698 enum object_type type
= sha1_object_info(sha1
, NULL
);
3700 die("%s is not a valid object", sha1_to_hex(sha1
));
3702 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),
3706 static int for_each_file_in_obj_subdir(int subdir_nr
,
3707 struct strbuf
*path
,
3708 each_loose_object_fn obj_cb
,
3709 each_loose_cruft_fn cruft_cb
,
3710 each_loose_subdir_fn subdir_cb
,
3713 size_t baselen
= path
->len
;
3714 DIR *dir
= opendir(path
->buf
);
3719 if (errno
== ENOENT
)
3721 return error_errno("unable to open %s", path
->buf
);
3724 while ((de
= readdir(dir
))) {
3725 if (is_dot_or_dotdot(de
->d_name
))
3728 strbuf_setlen(path
, baselen
);
3729 strbuf_addf(path
, "/%s", de
->d_name
);
3731 if (strlen(de
->d_name
) == 38) {
3733 unsigned char sha1
[20];
3735 snprintf(hex
, sizeof(hex
), "%02x%s",
3736 subdir_nr
, de
->d_name
);
3737 if (!get_sha1_hex(hex
, sha1
)) {
3739 r
= obj_cb(sha1
, path
->buf
, data
);
3748 r
= cruft_cb(de
->d_name
, path
->buf
, data
);
3755 strbuf_setlen(path
, baselen
);
3756 if (!r
&& subdir_cb
)
3757 r
= subdir_cb(subdir_nr
, path
->buf
, data
);
3762 int for_each_loose_file_in_objdir_buf(struct strbuf
*path
,
3763 each_loose_object_fn obj_cb
,
3764 each_loose_cruft_fn cruft_cb
,
3765 each_loose_subdir_fn subdir_cb
,
3768 size_t baselen
= path
->len
;
3772 for (i
= 0; i
< 256; i
++) {
3773 strbuf_addf(path
, "/%02x", i
);
3774 r
= for_each_file_in_obj_subdir(i
, path
, obj_cb
, cruft_cb
,
3776 strbuf_setlen(path
, baselen
);
3784 int for_each_loose_file_in_objdir(const char *path
,
3785 each_loose_object_fn obj_cb
,
3786 each_loose_cruft_fn cruft_cb
,
3787 each_loose_subdir_fn subdir_cb
,
3790 struct strbuf buf
= STRBUF_INIT
;
3793 strbuf_addstr(&buf
, path
);
3794 r
= for_each_loose_file_in_objdir_buf(&buf
, obj_cb
, cruft_cb
,
3796 strbuf_release(&buf
);
3801 struct loose_alt_odb_data
{
3802 each_loose_object_fn
*cb
;
3806 static int loose_from_alt_odb(struct alternate_object_database
*alt
,
3809 struct loose_alt_odb_data
*data
= vdata
;
3810 struct strbuf buf
= STRBUF_INIT
;
3813 strbuf_addstr(&buf
, alt
->path
);
3814 r
= for_each_loose_file_in_objdir_buf(&buf
,
3815 data
->cb
, NULL
, NULL
,
3817 strbuf_release(&buf
);
3821 int for_each_loose_object(each_loose_object_fn cb
, void *data
, unsigned flags
)
3823 struct loose_alt_odb_data alt
;
3826 r
= for_each_loose_file_in_objdir(get_object_directory(),
3827 cb
, NULL
, NULL
, data
);
3831 if (flags
& FOR_EACH_OBJECT_LOCAL_ONLY
)
3836 return foreach_alt_odb(loose_from_alt_odb
, &alt
);
3839 static int for_each_object_in_pack(struct packed_git
*p
, each_packed_object_fn cb
, void *data
)
3844 for (i
= 0; i
< p
->num_objects
; i
++) {
3845 const unsigned char *sha1
= nth_packed_object_sha1(p
, i
);
3848 return error("unable to get sha1 of object %u in %s",
3851 r
= cb(sha1
, p
, i
, data
);
3858 int for_each_packed_object(each_packed_object_fn cb
, void *data
, unsigned flags
)
3860 struct packed_git
*p
;
3862 int pack_errors
= 0;
3864 prepare_packed_git();
3865 for (p
= packed_git
; p
; p
= p
->next
) {
3866 if ((flags
& FOR_EACH_OBJECT_LOCAL_ONLY
) && !p
->pack_local
)
3868 if (open_pack_index(p
)) {
3872 r
= for_each_object_in_pack(p
, cb
, data
);
3876 return r
? r
: pack_errors
;