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"
15 #include "run-command.h"
18 #include "tree-walk.h"
20 #include "pack-revindex.h"
21 #include "sha1-lookup.h"
22 #include "bulk-checkin.h"
23 #include "streaming.h"
27 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
28 #define O_NOATIME 01000000
34 #define SZ_FMT PRIuMAX
35 static inline uintmax_t sz_fmt(size_t s
) { return s
; }
37 const unsigned char null_sha1
[20];
39 static const char *no_log_pack_access
= "no_log_pack_access";
40 static const char *log_pack_access
;
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 packed_git
*last_found_pack
;
65 static struct cached_object
*find_cached_object(const unsigned char *sha1
)
68 struct cached_object
*co
= cached_objects
;
70 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
71 if (!hashcmp(co
->sha1
, sha1
))
74 if (!hashcmp(sha1
, empty_tree
.sha1
))
79 int mkdir_in_gitdir(const char *path
)
81 if (mkdir(path
, 0777)) {
82 int saved_errno
= errno
;
84 struct strbuf sb
= STRBUF_INIT
;
89 * Are we looking at a path in a symlinked worktree
90 * whose original repository does not yet have it?
91 * e.g. .git/rr-cache pointing at its original
92 * repository in which the user hasn't performed any
93 * conflict resolution yet?
95 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
96 strbuf_readlink(&sb
, path
, st
.st_size
) ||
97 !is_absolute_path(sb
.buf
) ||
98 mkdir(sb
.buf
, 0777)) {
105 return adjust_shared_perm(path
);
108 enum scld_error
safe_create_leading_directories(char *path
)
110 char *next_component
= path
+ offset_1st_component(path
);
111 enum scld_error ret
= SCLD_OK
;
113 while (ret
== SCLD_OK
&& next_component
) {
115 char *slash
= next_component
, slash_character
;
117 while (*slash
&& !is_dir_sep(*slash
))
123 next_component
= slash
+ 1;
124 while (is_dir_sep(*next_component
))
126 if (!*next_component
)
129 slash_character
= *slash
;
131 if (!stat(path
, &st
)) {
133 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
)
162 /* path points to cache entries, so xstrdup before messing with it */
163 char *buf
= xstrdup(path
);
164 enum scld_error result
= safe_create_leading_directories(buf
);
169 static void fill_sha1_path(char *pathbuf
, const unsigned char *sha1
)
172 for (i
= 0; i
< 20; i
++) {
173 static char hex
[] = "0123456789abcdef";
174 unsigned int val
= sha1
[i
];
175 char *pos
= pathbuf
+ i
*2 + (i
> 0);
176 *pos
++ = hex
[val
>> 4];
177 *pos
= hex
[val
& 0xf];
182 * NOTE! This returns a statically allocated buffer, so you have to be
183 * careful about using it. Do an "xstrdup()" if you need to save the
186 * Also note that this returns the location for creating. Reading
187 * SHA1 file can happen from any alternate directory listed in the
188 * DB_ENVIRONMENT environment variable if it is not found in
189 * the primary object database.
191 char *sha1_file_name(const unsigned char *sha1
)
193 static char buf
[PATH_MAX
];
197 objdir
= get_object_directory();
198 len
= strlen(objdir
);
200 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
201 if (len
+ 43 > PATH_MAX
)
202 die("insanely long object directory %s", objdir
);
203 memcpy(buf
, objdir
, len
);
207 fill_sha1_path(buf
+ len
+ 1, sha1
);
211 static char *sha1_get_pack_name(const unsigned char *sha1
,
212 char **name
, char **base
, const char *which
)
214 static const char hex
[] = "0123456789abcdef";
219 const char *sha1_file_directory
= get_object_directory();
220 int len
= strlen(sha1_file_directory
);
221 *base
= xmalloc(len
+ 60);
222 sprintf(*base
, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
223 sha1_file_directory
, which
);
224 *name
= *base
+ len
+ 11;
229 for (i
= 0; i
< 20; i
++) {
230 unsigned int val
= *sha1
++;
231 *buf
++ = hex
[val
>> 4];
232 *buf
++ = hex
[val
& 0xf];
238 char *sha1_pack_name(const unsigned char *sha1
)
240 static char *name
, *base
;
242 return sha1_get_pack_name(sha1
, &name
, &base
, "pack");
245 char *sha1_pack_index_name(const unsigned char *sha1
)
247 static char *name
, *base
;
249 return sha1_get_pack_name(sha1
, &name
, &base
, "idx");
252 struct alternate_object_database
*alt_odb_list
;
253 static struct alternate_object_database
**alt_odb_tail
;
255 static int git_open_noatime(const char *name
);
258 * Prepare alternate object database registry.
260 * The variable alt_odb_list points at the list of struct
261 * alternate_object_database. The elements on this list come from
262 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
263 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
264 * whose contents is similar to that environment variable but can be
265 * LF separated. Its base points at a statically allocated buffer that
266 * contains "/the/directory/corresponding/to/.git/objects/...", while
267 * its name points just after the slash at the end of ".git/objects/"
268 * in the example above, and has enough space to hold 40-byte hex
269 * SHA1, an extra slash for the first level indirection, and the
272 static int link_alt_odb_entry(const char *entry
, const char *relative_base
, int depth
)
274 const char *objdir
= get_object_directory();
275 struct alternate_object_database
*ent
;
276 struct alternate_object_database
*alt
;
278 struct strbuf pathbuf
= STRBUF_INIT
;
280 if (!is_absolute_path(entry
) && relative_base
) {
281 strbuf_addstr(&pathbuf
, real_path(relative_base
));
282 strbuf_addch(&pathbuf
, '/');
284 strbuf_addstr(&pathbuf
, entry
);
286 normalize_path_copy(pathbuf
.buf
, pathbuf
.buf
);
288 pfxlen
= strlen(pathbuf
.buf
);
291 * The trailing slash after the directory name is given by
292 * this function at the end. Remove duplicates.
294 while (pfxlen
&& pathbuf
.buf
[pfxlen
-1] == '/')
297 entlen
= pfxlen
+ 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
298 ent
= xmalloc(sizeof(*ent
) + entlen
);
299 memcpy(ent
->base
, pathbuf
.buf
, pfxlen
);
300 strbuf_release(&pathbuf
);
302 ent
->name
= ent
->base
+ pfxlen
+ 1;
303 ent
->base
[pfxlen
+ 3] = '/';
304 ent
->base
[pfxlen
] = ent
->base
[entlen
-1] = 0;
306 /* Detect cases where alternate disappeared */
307 if (!is_directory(ent
->base
)) {
308 error("object directory %s does not exist; "
309 "check .git/objects/info/alternates.",
315 /* Prevent the common mistake of listing the same
316 * thing twice, or object directory itself.
318 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
319 if (!memcmp(ent
->base
, alt
->base
, pfxlen
)) {
324 if (!strcmp(ent
->base
, objdir
)) {
329 /* add the alternate entry */
331 alt_odb_tail
= &(ent
->next
);
334 /* recursively add alternates */
335 read_info_alternates(ent
->base
, depth
+ 1);
337 ent
->base
[pfxlen
] = '/';
342 static void link_alt_odb_entries(const char *alt
, int len
, int sep
,
343 const char *relative_base
, int depth
)
345 struct string_list entries
= STRING_LIST_INIT_NODUP
;
350 error("%s: ignoring alternate object stores, nesting too deep.",
355 alt_copy
= xmemdupz(alt
, len
);
356 string_list_split_in_place(&entries
, alt_copy
, sep
, -1);
357 for (i
= 0; i
< entries
.nr
; i
++) {
358 const char *entry
= entries
.items
[i
].string
;
359 if (entry
[0] == '\0' || entry
[0] == '#')
361 if (!is_absolute_path(entry
) && depth
) {
362 error("%s: ignoring relative alternate object store %s",
363 relative_base
, entry
);
365 link_alt_odb_entry(entry
, relative_base
, depth
);
368 string_list_clear(&entries
, 0);
372 void read_info_alternates(const char * relative_base
, int depth
)
377 const char alt_file_name
[] = "info/alternates";
378 /* Given that relative_base is no longer than PATH_MAX,
379 ensure that "path" has enough space to append "/", the
380 file name, "info/alternates", and a trailing NUL. */
381 char path
[PATH_MAX
+ 1 + sizeof alt_file_name
];
384 sprintf(path
, "%s/%s", relative_base
, alt_file_name
);
385 fd
= git_open_noatime(path
);
388 if (fstat(fd
, &st
) || (st
.st_size
== 0)) {
392 mapsz
= xsize_t(st
.st_size
);
393 map
= xmmap(NULL
, mapsz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
396 link_alt_odb_entries(map
, mapsz
, '\n', relative_base
, depth
);
401 void add_to_alternates_file(const char *reference
)
403 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
404 int fd
= hold_lock_file_for_append(lock
, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR
);
405 char *alt
= mkpath("%s\n", reference
);
406 write_or_die(fd
, alt
, strlen(alt
));
407 if (commit_lock_file(lock
))
408 die("could not close alternates file");
410 link_alt_odb_entries(alt
, strlen(alt
), '\n', NULL
, 0);
413 void foreach_alt_odb(alt_odb_fn fn
, void *cb
)
415 struct alternate_object_database
*ent
;
418 for (ent
= alt_odb_list
; ent
; ent
= ent
->next
)
423 void prepare_alt_odb(void)
430 alt
= getenv(ALTERNATE_DB_ENVIRONMENT
);
433 alt_odb_tail
= &alt_odb_list
;
434 link_alt_odb_entries(alt
, strlen(alt
), PATH_SEP
, NULL
, 0);
436 read_info_alternates(get_object_directory(), 0);
439 static int has_loose_object_local(const unsigned char *sha1
)
441 char *name
= sha1_file_name(sha1
);
442 return !access(name
, F_OK
);
445 int has_loose_object_nonlocal(const unsigned char *sha1
)
447 struct alternate_object_database
*alt
;
449 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
450 fill_sha1_path(alt
->name
, sha1
);
451 if (!access(alt
->base
, F_OK
))
457 static int has_loose_object(const unsigned char *sha1
)
459 return has_loose_object_local(sha1
) ||
460 has_loose_object_nonlocal(sha1
);
463 static unsigned int pack_used_ctr
;
464 static unsigned int pack_mmap_calls
;
465 static unsigned int peak_pack_open_windows
;
466 static unsigned int pack_open_windows
;
467 static unsigned int pack_open_fds
;
468 static unsigned int pack_max_fds
;
469 static size_t peak_pack_mapped
;
470 static size_t pack_mapped
;
471 struct packed_git
*packed_git
;
473 void pack_report(void)
476 "pack_report: getpagesize() = %10" SZ_FMT
"\n"
477 "pack_report: core.packedGitWindowSize = %10" SZ_FMT
"\n"
478 "pack_report: core.packedGitLimit = %10" SZ_FMT
"\n",
479 sz_fmt(getpagesize()),
480 sz_fmt(packed_git_window_size
),
481 sz_fmt(packed_git_limit
));
483 "pack_report: pack_used_ctr = %10u\n"
484 "pack_report: pack_mmap_calls = %10u\n"
485 "pack_report: pack_open_windows = %10u / %10u\n"
486 "pack_report: pack_mapped = "
487 "%10" SZ_FMT
" / %10" SZ_FMT
"\n",
490 pack_open_windows
, peak_pack_open_windows
,
491 sz_fmt(pack_mapped
), sz_fmt(peak_pack_mapped
));
494 static int check_packed_git_idx(const char *path
, struct packed_git
*p
)
497 struct pack_idx_header
*hdr
;
499 uint32_t version
, nr
, i
, *index
;
500 int fd
= git_open_noatime(path
);
505 if (fstat(fd
, &st
)) {
509 idx_size
= xsize_t(st
.st_size
);
510 if (idx_size
< 4 * 256 + 20 + 20) {
512 return error("index file %s is too small", path
);
514 idx_map
= xmmap(NULL
, idx_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
518 if (hdr
->idx_signature
== htonl(PACK_IDX_SIGNATURE
)) {
519 version
= ntohl(hdr
->idx_version
);
520 if (version
< 2 || version
> 2) {
521 munmap(idx_map
, idx_size
);
522 return error("index file %s is version %"PRIu32
523 " and is not supported by this binary"
524 " (try upgrading GIT to a newer version)",
533 index
+= 2; /* skip index header */
534 for (i
= 0; i
< 256; i
++) {
535 uint32_t n
= ntohl(index
[i
]);
537 munmap(idx_map
, idx_size
);
538 return error("non-monotonic index %s", path
);
546 * - 256 index entries 4 bytes each
547 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
548 * - 20-byte SHA1 of the packfile
549 * - 20-byte SHA1 file checksum
551 if (idx_size
!= 4*256 + nr
* 24 + 20 + 20) {
552 munmap(idx_map
, idx_size
);
553 return error("wrong index v1 file size in %s", path
);
555 } else if (version
== 2) {
558 * - 8 bytes of header
559 * - 256 index entries 4 bytes each
560 * - 20-byte sha1 entry * nr
561 * - 4-byte crc entry * nr
562 * - 4-byte offset entry * nr
563 * - 20-byte SHA1 of the packfile
564 * - 20-byte SHA1 file checksum
565 * And after the 4-byte offset table might be a
566 * variable sized table containing 8-byte entries
567 * for offsets larger than 2^31.
569 unsigned long min_size
= 8 + 4*256 + nr
*(20 + 4 + 4) + 20 + 20;
570 unsigned long max_size
= min_size
;
572 max_size
+= (nr
- 1)*8;
573 if (idx_size
< min_size
|| idx_size
> max_size
) {
574 munmap(idx_map
, idx_size
);
575 return error("wrong index v2 file size in %s", path
);
577 if (idx_size
!= min_size
&&
579 * make sure we can deal with large pack offsets.
580 * 31-bit signed offset won't be enough, neither
581 * 32-bit unsigned one will be.
583 (sizeof(off_t
) <= 4)) {
584 munmap(idx_map
, idx_size
);
585 return error("pack too large for current definition of off_t in %s", path
);
589 p
->index_version
= version
;
590 p
->index_data
= idx_map
;
591 p
->index_size
= idx_size
;
596 int open_pack_index(struct packed_git
*p
)
604 idx_name
= xstrdup(p
->pack_name
);
605 strcpy(idx_name
+ strlen(idx_name
) - strlen(".pack"), ".idx");
606 ret
= check_packed_git_idx(idx_name
, p
);
611 static void scan_windows(struct packed_git
*p
,
612 struct packed_git
**lru_p
,
613 struct pack_window
**lru_w
,
614 struct pack_window
**lru_l
)
616 struct pack_window
*w
, *w_l
;
618 for (w_l
= NULL
, w
= p
->windows
; w
; w
= w
->next
) {
620 if (!*lru_w
|| w
->last_used
< (*lru_w
)->last_used
) {
630 static int unuse_one_window(struct packed_git
*current
)
632 struct packed_git
*p
, *lru_p
= NULL
;
633 struct pack_window
*lru_w
= NULL
, *lru_l
= NULL
;
636 scan_windows(current
, &lru_p
, &lru_w
, &lru_l
);
637 for (p
= packed_git
; p
; p
= p
->next
)
638 scan_windows(p
, &lru_p
, &lru_w
, &lru_l
);
640 munmap(lru_w
->base
, lru_w
->len
);
641 pack_mapped
-= lru_w
->len
;
643 lru_l
->next
= lru_w
->next
;
645 lru_p
->windows
= lru_w
->next
;
653 void release_pack_memory(size_t need
)
655 size_t cur
= pack_mapped
;
656 while (need
>= (cur
- pack_mapped
) && unuse_one_window(NULL
))
660 void *xmmap(void *start
, size_t length
,
661 int prot
, int flags
, int fd
, off_t offset
)
663 void *ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
664 if (ret
== MAP_FAILED
) {
667 release_pack_memory(length
);
668 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
669 if (ret
== MAP_FAILED
)
670 die_errno("Out of memory? mmap failed");
675 void close_pack_windows(struct packed_git
*p
)
678 struct pack_window
*w
= p
->windows
;
681 die("pack '%s' still has open windows to it",
683 munmap(w
->base
, w
->len
);
684 pack_mapped
-= w
->len
;
686 p
->windows
= w
->next
;
692 * The LRU pack is the one with the oldest MRU window, preferring packs
693 * with no used windows, or the oldest mtime if it has no windows allocated.
695 static void find_lru_pack(struct packed_git
*p
, struct packed_git
**lru_p
, struct pack_window
**mru_w
, int *accept_windows_inuse
)
697 struct pack_window
*w
, *this_mru_w
;
698 int has_windows_inuse
= 0;
701 * Reject this pack if it has windows and the previously selected
702 * one does not. If this pack does not have windows, reject
703 * it if the pack file is newer than the previously selected one.
705 if (*lru_p
&& !*mru_w
&& (p
->windows
|| p
->mtime
> (*lru_p
)->mtime
))
708 for (w
= this_mru_w
= p
->windows
; w
; w
= w
->next
) {
710 * Reject this pack if any of its windows are in use,
711 * but the previously selected pack did not have any
712 * inuse windows. Otherwise, record that this pack
713 * has windows in use.
716 if (*accept_windows_inuse
)
717 has_windows_inuse
= 1;
722 if (w
->last_used
> this_mru_w
->last_used
)
726 * Reject this pack if it has windows that have been
727 * used more recently than the previously selected pack.
728 * If the previously selected pack had windows inuse and
729 * we have not encountered a window in this pack that is
730 * inuse, skip this check since we prefer a pack with no
731 * inuse windows to one that has inuse windows.
733 if (*mru_w
&& *accept_windows_inuse
== has_windows_inuse
&&
734 this_mru_w
->last_used
> (*mru_w
)->last_used
)
743 *accept_windows_inuse
= has_windows_inuse
;
746 static int close_one_pack(void)
748 struct packed_git
*p
, *lru_p
= NULL
;
749 struct pack_window
*mru_w
= NULL
;
750 int accept_windows_inuse
= 1;
752 for (p
= packed_git
; p
; p
= p
->next
) {
753 if (p
->pack_fd
== -1)
755 find_lru_pack(p
, &lru_p
, &mru_w
, &accept_windows_inuse
);
759 close(lru_p
->pack_fd
);
768 void unuse_pack(struct pack_window
**w_cursor
)
770 struct pack_window
*w
= *w_cursor
;
777 void close_pack_index(struct packed_git
*p
)
780 munmap((void *)p
->index_data
, p
->index_size
);
781 p
->index_data
= NULL
;
786 * This is used by git-repack in case a newly created pack happens to
787 * contain the same set of objects as an existing one. In that case
788 * the resulting file might be different even if its name would be the
789 * same. It is best to close any reference to the old pack before it is
790 * replaced on disk. Of course no index pointers nor windows for given pack
791 * must subsist at this point. If ever objects from this pack are requested
792 * again, the new version of the pack will be reinitialized through
793 * reprepare_packed_git().
795 void free_pack_by_name(const char *pack_name
)
797 struct packed_git
*p
, **pp
= &packed_git
;
801 if (strcmp(pack_name
, p
->pack_name
) == 0) {
802 clear_delta_base_cache();
803 close_pack_windows(p
);
804 if (p
->pack_fd
!= -1) {
809 free(p
->bad_object_sha1
);
811 if (last_found_pack
== p
)
812 last_found_pack
= NULL
;
820 static unsigned int get_max_fd_limit(void)
826 if (!getrlimit(RLIMIT_NOFILE
, &lim
))
833 long open_max
= sysconf(_SC_OPEN_MAX
);
837 * Otherwise, we got -1 for one of the two
840 * (1) sysconf() did not understand _SC_OPEN_MAX
841 * and signaled an error with -1; or
842 * (2) sysconf() said there is no limit.
844 * We _could_ clear errno before calling sysconf() to
845 * tell these two cases apart and return a huge number
846 * in the latter case to let the caller cap it to a
847 * value that is not so selfish, but letting the
848 * fallback OPEN_MAX codepath take care of these cases
857 return 1; /* see the caller ;-) */
862 * Do not call this directly as this leaks p->pack_fd on error return;
863 * call open_packed_git() instead.
865 static int open_packed_git_1(struct packed_git
*p
)
868 struct pack_header hdr
;
869 unsigned char sha1
[20];
870 unsigned char *idx_sha1
;
873 if (!p
->index_data
&& open_pack_index(p
))
874 return error("packfile %s index unavailable", p
->pack_name
);
877 unsigned int max_fds
= get_max_fd_limit();
879 /* Save 3 for stdin/stdout/stderr, 22 for work */
881 pack_max_fds
= max_fds
- 25;
886 while (pack_max_fds
<= pack_open_fds
&& close_one_pack())
889 p
->pack_fd
= git_open_noatime(p
->pack_name
);
890 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
894 /* If we created the struct before we had the pack we lack size. */
896 if (!S_ISREG(st
.st_mode
))
897 return error("packfile %s not a regular file", p
->pack_name
);
898 p
->pack_size
= st
.st_size
;
899 } else if (p
->pack_size
!= st
.st_size
)
900 return error("packfile %s size changed", p
->pack_name
);
902 /* We leave these file descriptors open with sliding mmap;
903 * there is no point keeping them open across exec(), though.
905 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
907 return error("cannot determine file descriptor flags");
908 fd_flag
|= FD_CLOEXEC
;
909 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
910 return error("cannot set FD_CLOEXEC");
912 /* Verify we recognize this pack file format. */
913 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
914 return error("file %s is far too short to be a packfile", p
->pack_name
);
915 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
916 return error("file %s is not a GIT packfile", p
->pack_name
);
917 if (!pack_version_ok(hdr
.hdr_version
))
918 return error("packfile %s is version %"PRIu32
" and not"
919 " supported (try upgrading GIT to a newer version)",
920 p
->pack_name
, ntohl(hdr
.hdr_version
));
922 /* Verify the pack matches its index. */
923 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
924 return error("packfile %s claims to have %"PRIu32
" objects"
925 " while index indicates %"PRIu32
" objects",
926 p
->pack_name
, ntohl(hdr
.hdr_entries
),
928 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
929 return error("end of packfile %s is unavailable", p
->pack_name
);
930 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
931 return error("packfile %s signature is unavailable", p
->pack_name
);
932 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
933 if (hashcmp(sha1
, idx_sha1
))
934 return error("packfile %s does not match index", p
->pack_name
);
938 static int open_packed_git(struct packed_git
*p
)
940 if (!open_packed_git_1(p
))
942 if (p
->pack_fd
!= -1) {
950 static int in_window(struct pack_window
*win
, off_t offset
)
952 /* We must promise at least 20 bytes (one hash) after the
953 * offset is available from this window, otherwise the offset
954 * is not actually in this window and a different window (which
955 * has that one hash excess) must be used. This is to support
956 * the object header and delta base parsing routines below.
958 off_t win_off
= win
->offset
;
959 return win_off
<= offset
960 && (offset
+ 20) <= (win_off
+ win
->len
);
963 unsigned char *use_pack(struct packed_git
*p
,
964 struct pack_window
**w_cursor
,
968 struct pack_window
*win
= *w_cursor
;
970 /* Since packfiles end in a hash of their content and it's
971 * pointless to ask for an offset into the middle of that
972 * hash, and the in_window function above wouldn't match
973 * don't allow an offset too close to the end of the file.
975 if (!p
->pack_size
&& p
->pack_fd
== -1 && open_packed_git(p
))
976 die("packfile %s cannot be accessed", p
->pack_name
);
977 if (offset
> (p
->pack_size
- 20))
978 die("offset beyond end of packfile (truncated pack?)");
980 if (!win
|| !in_window(win
, offset
)) {
983 for (win
= p
->windows
; win
; win
= win
->next
) {
984 if (in_window(win
, offset
))
988 size_t window_align
= packed_git_window_size
/ 2;
991 if (p
->pack_fd
== -1 && open_packed_git(p
))
992 die("packfile %s cannot be accessed", p
->pack_name
);
994 win
= xcalloc(1, sizeof(*win
));
995 win
->offset
= (offset
/ window_align
) * window_align
;
996 len
= p
->pack_size
- win
->offset
;
997 if (len
> packed_git_window_size
)
998 len
= packed_git_window_size
;
999 win
->len
= (size_t)len
;
1000 pack_mapped
+= win
->len
;
1001 while (packed_git_limit
< pack_mapped
1002 && unuse_one_window(p
))
1004 win
->base
= xmmap(NULL
, win
->len
,
1005 PROT_READ
, MAP_PRIVATE
,
1006 p
->pack_fd
, win
->offset
);
1007 if (win
->base
== MAP_FAILED
)
1008 die("packfile %s cannot be mapped: %s",
1011 if (!win
->offset
&& win
->len
== p
->pack_size
1012 && !p
->do_not_close
) {
1018 pack_open_windows
++;
1019 if (pack_mapped
> peak_pack_mapped
)
1020 peak_pack_mapped
= pack_mapped
;
1021 if (pack_open_windows
> peak_pack_open_windows
)
1022 peak_pack_open_windows
= pack_open_windows
;
1023 win
->next
= p
->windows
;
1027 if (win
!= *w_cursor
) {
1028 win
->last_used
= pack_used_ctr
++;
1032 offset
-= win
->offset
;
1034 *left
= win
->len
- xsize_t(offset
);
1035 return win
->base
+ offset
;
1038 static struct packed_git
*alloc_packed_git(int extra
)
1040 struct packed_git
*p
= xmalloc(sizeof(*p
) + extra
);
1041 memset(p
, 0, sizeof(*p
));
1046 static void try_to_free_pack_memory(size_t size
)
1048 release_pack_memory(size
);
1051 struct packed_git
*add_packed_git(const char *path
, int path_len
, int local
)
1053 static int have_set_try_to_free_routine
;
1055 struct packed_git
*p
= alloc_packed_git(path_len
+ 2);
1057 if (!have_set_try_to_free_routine
) {
1058 have_set_try_to_free_routine
= 1;
1059 set_try_to_free_routine(try_to_free_pack_memory
);
1063 * Make sure a corresponding .pack file exists and that
1064 * the index looks sane.
1066 path_len
-= strlen(".idx");
1071 memcpy(p
->pack_name
, path
, path_len
);
1073 strcpy(p
->pack_name
+ path_len
, ".keep");
1074 if (!access(p
->pack_name
, F_OK
))
1077 strcpy(p
->pack_name
+ path_len
, ".pack");
1078 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
1083 /* ok, it looks sane as far as we can check without
1084 * actually mapping the pack file.
1086 p
->pack_size
= st
.st_size
;
1087 p
->pack_local
= local
;
1088 p
->mtime
= st
.st_mtime
;
1089 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
1094 struct packed_git
*parse_pack_index(unsigned char *sha1
, const char *idx_path
)
1096 const char *path
= sha1_pack_name(sha1
);
1097 struct packed_git
*p
= alloc_packed_git(strlen(path
) + 1);
1099 strcpy(p
->pack_name
, path
);
1100 hashcpy(p
->sha1
, sha1
);
1101 if (check_packed_git_idx(idx_path
, p
)) {
1109 void install_packed_git(struct packed_git
*pack
)
1111 if (pack
->pack_fd
!= -1)
1114 pack
->next
= packed_git
;
1118 void (*report_garbage
)(const char *desc
, const char *path
);
1120 static void report_helper(const struct string_list
*list
,
1121 int seen_bits
, int first
, int last
)
1124 switch (seen_bits
) {
1126 msg
= "no corresponding .idx nor .pack";
1129 msg
= "no corresponding .idx";
1132 msg
= "no corresponding .pack";
1137 for (; first
< last
; first
++)
1138 report_garbage(msg
, list
->items
[first
].string
);
1141 static void report_pack_garbage(struct string_list
*list
)
1143 int i
, baselen
= -1, first
= 0, seen_bits
= 0;
1145 if (!report_garbage
)
1148 sort_string_list(list
);
1150 for (i
= 0; i
< list
->nr
; i
++) {
1151 const char *path
= list
->items
[i
].string
;
1152 if (baselen
!= -1 &&
1153 strncmp(path
, list
->items
[first
].string
, baselen
)) {
1154 report_helper(list
, seen_bits
, first
, i
);
1158 if (baselen
== -1) {
1159 const char *dot
= strrchr(path
, '.');
1161 report_garbage("garbage found", path
);
1164 baselen
= dot
- path
+ 1;
1167 if (!strcmp(path
+ baselen
, "pack"))
1169 else if (!strcmp(path
+ baselen
, "idx"))
1172 report_helper(list
, seen_bits
, first
, list
->nr
);
1175 static void prepare_packed_git_one(char *objdir
, int local
)
1177 /* Ensure that this buffer is large enough so that we can
1178 append "/pack/" without clobbering the stack even if
1179 strlen(objdir) were PATH_MAX. */
1180 char path
[PATH_MAX
+ 1 + 4 + 1 + 1];
1184 struct string_list garbage
= STRING_LIST_INIT_DUP
;
1186 sprintf(path
, "%s/pack", objdir
);
1188 dir
= opendir(path
);
1190 if (errno
!= ENOENT
)
1191 error("unable to open object pack directory: %s: %s",
1192 path
, strerror(errno
));
1196 while ((de
= readdir(dir
)) != NULL
) {
1197 int namelen
= strlen(de
->d_name
);
1198 struct packed_git
*p
;
1200 if (len
+ namelen
+ 1 > sizeof(path
)) {
1201 if (report_garbage
) {
1202 struct strbuf sb
= STRBUF_INIT
;
1203 strbuf_addf(&sb
, "%.*s/%s", len
- 1, path
, de
->d_name
);
1204 report_garbage("path too long", sb
.buf
);
1205 strbuf_release(&sb
);
1210 if (is_dot_or_dotdot(de
->d_name
))
1213 strcpy(path
+ len
, de
->d_name
);
1215 if (has_extension(de
->d_name
, ".idx")) {
1216 /* Don't reopen a pack we already have. */
1217 for (p
= packed_git
; p
; p
= p
->next
) {
1218 if (!memcmp(path
, p
->pack_name
, len
+ namelen
- 4))
1223 * See if it really is a valid .idx file with
1224 * corresponding .pack file that we can map.
1226 (p
= add_packed_git(path
, len
+ namelen
, local
)) != NULL
)
1227 install_packed_git(p
);
1230 if (!report_garbage
)
1233 if (has_extension(de
->d_name
, ".idx") ||
1234 has_extension(de
->d_name
, ".pack") ||
1235 has_extension(de
->d_name
, ".keep"))
1236 string_list_append(&garbage
, path
);
1238 report_garbage("garbage found", path
);
1241 report_pack_garbage(&garbage
);
1242 string_list_clear(&garbage
, 0);
1245 static int sort_pack(const void *a_
, const void *b_
)
1247 struct packed_git
*a
= *((struct packed_git
**)a_
);
1248 struct packed_git
*b
= *((struct packed_git
**)b_
);
1252 * Local packs tend to contain objects specific to our
1253 * variant of the project than remote ones. In addition,
1254 * remote ones could be on a network mounted filesystem.
1255 * Favor local ones for these reasons.
1257 st
= a
->pack_local
- b
->pack_local
;
1262 * Younger packs tend to contain more recent objects,
1263 * and more recent objects tend to get accessed more
1266 if (a
->mtime
< b
->mtime
)
1268 else if (a
->mtime
== b
->mtime
)
1273 static void rearrange_packed_git(void)
1275 struct packed_git
**ary
, *p
;
1278 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
1283 /* prepare an array of packed_git for easier sorting */
1284 ary
= xcalloc(n
, sizeof(struct packed_git
*));
1285 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
1288 qsort(ary
, n
, sizeof(struct packed_git
*), sort_pack
);
1290 /* link them back again */
1291 for (i
= 0; i
< n
- 1; i
++)
1292 ary
[i
]->next
= ary
[i
+ 1];
1293 ary
[n
- 1]->next
= NULL
;
1294 packed_git
= ary
[0];
1299 static int prepare_packed_git_run_once
= 0;
1300 void prepare_packed_git(void)
1302 struct alternate_object_database
*alt
;
1304 if (prepare_packed_git_run_once
)
1306 prepare_packed_git_one(get_object_directory(), 1);
1308 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1310 prepare_packed_git_one(alt
->base
, 0);
1311 alt
->name
[-1] = '/';
1313 rearrange_packed_git();
1314 prepare_packed_git_run_once
= 1;
1317 void reprepare_packed_git(void)
1320 prepare_packed_git_run_once
= 0;
1321 prepare_packed_git();
1324 static void mark_bad_packed_object(struct packed_git
*p
,
1325 const unsigned char *sha1
)
1328 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1329 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1331 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
, 20 * (p
->num_bad_objects
+ 1));
1332 hashcpy(p
->bad_object_sha1
+ 20 * p
->num_bad_objects
, sha1
);
1333 p
->num_bad_objects
++;
1336 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1338 struct packed_git
*p
;
1341 for (p
= packed_git
; p
; p
= p
->next
)
1342 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1343 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1349 * With an in-core object data in "map", rehash it to make sure the
1350 * object name actually matches "sha1" to detect object corruption.
1351 * With "map" == NULL, try reading the object named with "sha1" using
1352 * the streaming interface and rehash it to do the same.
1354 int check_sha1_signature(const unsigned char *sha1
, void *map
,
1355 unsigned long size
, const char *type
)
1357 unsigned char real_sha1
[20];
1358 enum object_type obj_type
;
1359 struct git_istream
*st
;
1365 hash_sha1_file(map
, size
, type
, real_sha1
);
1366 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1369 st
= open_istream(sha1
, &obj_type
, &size
, NULL
);
1373 /* Generate the header */
1374 hdrlen
= sprintf(hdr
, "%s %lu", typename(obj_type
), size
) + 1;
1378 git_SHA1_Update(&c
, hdr
, hdrlen
);
1380 char buf
[1024 * 16];
1381 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
1389 git_SHA1_Update(&c
, buf
, readlen
);
1391 git_SHA1_Final(real_sha1
, &c
);
1393 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1396 static int git_open_noatime(const char *name
)
1398 static int sha1_file_open_flag
= O_NOATIME
;
1401 int fd
= open(name
, O_RDONLY
| sha1_file_open_flag
);
1405 /* Might the failure be due to O_NOATIME? */
1406 if (errno
!= ENOENT
&& sha1_file_open_flag
) {
1407 sha1_file_open_flag
= 0;
1415 static int stat_sha1_file(const unsigned char *sha1
, struct stat
*st
)
1417 char *name
= sha1_file_name(sha1
);
1418 struct alternate_object_database
*alt
;
1420 if (!lstat(name
, st
))
1425 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1427 fill_sha1_path(name
, sha1
);
1428 if (!lstat(alt
->base
, st
))
1435 static int open_sha1_file(const unsigned char *sha1
)
1438 char *name
= sha1_file_name(sha1
);
1439 struct alternate_object_database
*alt
;
1441 fd
= git_open_noatime(name
);
1447 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1449 fill_sha1_path(name
, sha1
);
1450 fd
= git_open_noatime(alt
->base
);
1457 void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1462 fd
= open_sha1_file(sha1
);
1467 if (!fstat(fd
, &st
)) {
1468 *size
= xsize_t(st
.st_size
);
1470 /* mmap() is forbidden on empty files */
1471 error("object file %s is empty", sha1_file_name(sha1
));
1474 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1481 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1482 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1485 unsigned long size
, c
;
1486 unsigned long used
= 0;
1489 *type
= (c
>> 4) & 7;
1493 if (len
<= used
|| bitsizeof(long) <= shift
) {
1494 error("bad object header");
1499 size
+= (c
& 0x7f) << shift
;
1506 int unpack_sha1_header(git_zstream
*stream
, unsigned char *map
, unsigned long mapsize
, void *buffer
, unsigned long bufsiz
)
1508 /* Get the data stream */
1509 memset(stream
, 0, sizeof(*stream
));
1510 stream
->next_in
= map
;
1511 stream
->avail_in
= mapsize
;
1512 stream
->next_out
= buffer
;
1513 stream
->avail_out
= bufsiz
;
1515 git_inflate_init(stream
);
1516 return git_inflate(stream
, 0);
1519 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1521 int bytes
= strlen(buffer
) + 1;
1522 unsigned char *buf
= xmallocz(size
);
1526 n
= stream
->total_out
- bytes
;
1529 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1531 if (bytes
<= size
) {
1533 * The above condition must be (bytes <= size), not
1534 * (bytes < size). In other words, even though we
1535 * expect no more output and set avail_out to zero,
1536 * the input zlib stream may have bytes that express
1537 * "this concludes the stream", and we *do* want to
1540 * Otherwise we would not be able to test that we
1541 * consumed all the input to reach the expected size;
1542 * we also want to check that zlib tells us that all
1543 * went well with status == Z_STREAM_END at the end.
1545 stream
->next_out
= buf
+ bytes
;
1546 stream
->avail_out
= size
- bytes
;
1547 while (status
== Z_OK
)
1548 status
= git_inflate(stream
, Z_FINISH
);
1550 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1551 git_inflate_end(stream
);
1556 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1557 else if (stream
->avail_in
)
1558 error("garbage at end of loose object '%s'",
1565 * We used to just use "sscanf()", but that's actually way
1566 * too permissive for what we want to check. So do an anal
1567 * object header parse by hand.
1569 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1576 * The type can be at most ten bytes (including the
1577 * terminating '\0' that we add), and is followed by
1586 if (i
>= sizeof(type
))
1592 * The length must follow immediately, and be in canonical
1593 * decimal format (ie "010" is not valid).
1595 size
= *hdr
++ - '0';
1600 unsigned long c
= *hdr
- '0';
1604 size
= size
* 10 + c
;
1610 * The length must be followed by a zero byte
1612 return *hdr
? -1 : type_from_string(type
);
1615 static void *unpack_sha1_file(void *map
, unsigned long mapsize
, enum object_type
*type
, unsigned long *size
, const unsigned char *sha1
)
1621 ret
= unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
));
1622 if (ret
< Z_OK
|| (*type
= parse_sha1_header(hdr
, size
)) < 0)
1625 return unpack_sha1_rest(&stream
, hdr
, *size
, sha1
);
1628 unsigned long get_size_from_delta(struct packed_git
*p
,
1629 struct pack_window
**w_curs
,
1632 const unsigned char *data
;
1633 unsigned char delta_head
[20], *in
;
1637 memset(&stream
, 0, sizeof(stream
));
1638 stream
.next_out
= delta_head
;
1639 stream
.avail_out
= sizeof(delta_head
);
1641 git_inflate_init(&stream
);
1643 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1644 stream
.next_in
= in
;
1645 st
= git_inflate(&stream
, Z_FINISH
);
1646 curpos
+= stream
.next_in
- in
;
1647 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
1648 stream
.total_out
< sizeof(delta_head
));
1649 git_inflate_end(&stream
);
1650 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
1651 error("delta data unpack-initial failed");
1655 /* Examine the initial part of the delta to figure out
1660 /* ignore base size */
1661 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1663 /* Read the result size */
1664 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1667 static off_t
get_delta_base(struct packed_git
*p
,
1668 struct pack_window
**w_curs
,
1670 enum object_type type
,
1671 off_t delta_obj_offset
)
1673 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
1676 /* use_pack() assured us we have [base_info, base_info + 20)
1677 * as a range that we can look at without walking off the
1678 * end of the mapped window. Its actually the hash size
1679 * that is assured. An OFS_DELTA longer than the hash size
1680 * is stupid, as then a REF_DELTA would be smaller to store.
1682 if (type
== OBJ_OFS_DELTA
) {
1684 unsigned char c
= base_info
[used
++];
1685 base_offset
= c
& 127;
1688 if (!base_offset
|| MSB(base_offset
, 7))
1689 return 0; /* overflow */
1690 c
= base_info
[used
++];
1691 base_offset
= (base_offset
<< 7) + (c
& 127);
1693 base_offset
= delta_obj_offset
- base_offset
;
1694 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
1695 return 0; /* out of bound */
1697 } else if (type
== OBJ_REF_DELTA
) {
1698 /* The base entry _must_ be in the same pack */
1699 base_offset
= find_pack_entry_one(base_info
, p
);
1702 die("I am totally screwed");
1707 * Like get_delta_base above, but we return the sha1 instead of the pack
1708 * offset. This means it is cheaper for REF deltas (we do not have to do
1709 * the final object lookup), but more expensive for OFS deltas (we
1710 * have to load the revidx to convert the offset back into a sha1).
1712 static const unsigned char *get_delta_base_sha1(struct packed_git
*p
,
1713 struct pack_window
**w_curs
,
1715 enum object_type type
,
1716 off_t delta_obj_offset
)
1718 if (type
== OBJ_REF_DELTA
) {
1719 unsigned char *base
= use_pack(p
, w_curs
, curpos
, NULL
);
1721 } else if (type
== OBJ_OFS_DELTA
) {
1722 struct revindex_entry
*revidx
;
1723 off_t base_offset
= get_delta_base(p
, w_curs
, &curpos
,
1724 type
, delta_obj_offset
);
1729 revidx
= find_pack_revindex(p
, base_offset
);
1733 return nth_packed_object_sha1(p
, revidx
->nr
);
1738 int unpack_object_header(struct packed_git
*p
,
1739 struct pack_window
**w_curs
,
1741 unsigned long *sizep
)
1743 unsigned char *base
;
1746 enum object_type type
;
1748 /* use_pack() assures us we have [base, base + 20) available
1749 * as a range that we can look at. (Its actually the hash
1750 * size that is assured.) With our object header encoding
1751 * the maximum deflated object size is 2^137, which is just
1752 * insane, so we know won't exceed what we have been given.
1754 base
= use_pack(p
, w_curs
, *curpos
, &left
);
1755 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
1764 static int retry_bad_packed_offset(struct packed_git
*p
, off_t obj_offset
)
1767 struct revindex_entry
*revidx
;
1768 const unsigned char *sha1
;
1769 revidx
= find_pack_revindex(p
, obj_offset
);
1772 sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1773 mark_bad_packed_object(p
, sha1
);
1774 type
= sha1_object_info(sha1
, NULL
);
1775 if (type
<= OBJ_NONE
)
1780 #define POI_STACK_PREALLOC 64
1782 static enum object_type
packed_to_object_type(struct packed_git
*p
,
1784 enum object_type type
,
1785 struct pack_window
**w_curs
,
1788 off_t small_poi_stack
[POI_STACK_PREALLOC
];
1789 off_t
*poi_stack
= small_poi_stack
;
1790 int poi_stack_nr
= 0, poi_stack_alloc
= POI_STACK_PREALLOC
;
1792 while (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1795 /* Push the object we're going to leave behind */
1796 if (poi_stack_nr
>= poi_stack_alloc
&& poi_stack
== small_poi_stack
) {
1797 poi_stack_alloc
= alloc_nr(poi_stack_nr
);
1798 poi_stack
= xmalloc(sizeof(off_t
)*poi_stack_alloc
);
1799 memcpy(poi_stack
, small_poi_stack
, sizeof(off_t
)*poi_stack_nr
);
1801 ALLOC_GROW(poi_stack
, poi_stack_nr
+1, poi_stack_alloc
);
1803 poi_stack
[poi_stack_nr
++] = obj_offset
;
1804 /* If parsing the base offset fails, just unwind */
1805 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
1808 curpos
= obj_offset
= base_offset
;
1809 type
= unpack_object_header(p
, w_curs
, &curpos
, &size
);
1810 if (type
<= OBJ_NONE
) {
1811 /* If getting the base itself fails, we first
1812 * retry the base, otherwise unwind */
1813 type
= retry_bad_packed_offset(p
, base_offset
);
1814 if (type
> OBJ_NONE
)
1828 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1829 type
, (uintmax_t)obj_offset
, p
->pack_name
);
1834 if (poi_stack
!= small_poi_stack
)
1839 while (poi_stack_nr
) {
1840 obj_offset
= poi_stack
[--poi_stack_nr
];
1841 type
= retry_bad_packed_offset(p
, obj_offset
);
1842 if (type
> OBJ_NONE
)
1849 static int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
1850 struct object_info
*oi
)
1852 struct pack_window
*w_curs
= NULL
;
1854 off_t curpos
= obj_offset
;
1855 enum object_type type
;
1858 * We always get the representation type, but only convert it to
1859 * a "real" type later if the caller is interested.
1861 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
1864 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1865 off_t tmp_pos
= curpos
;
1866 off_t base_offset
= get_delta_base(p
, &w_curs
, &tmp_pos
,
1872 *oi
->sizep
= get_size_from_delta(p
, &w_curs
, tmp_pos
);
1873 if (*oi
->sizep
== 0) {
1882 if (oi
->disk_sizep
) {
1883 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
1884 *oi
->disk_sizep
= revidx
[1].offset
- obj_offset
;
1888 *oi
->typep
= packed_to_object_type(p
, obj_offset
, type
, &w_curs
, curpos
);
1889 if (*oi
->typep
< 0) {
1895 if (oi
->delta_base_sha1
) {
1896 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1897 const unsigned char *base
;
1899 base
= get_delta_base_sha1(p
, &w_curs
, curpos
,
1906 hashcpy(oi
->delta_base_sha1
, base
);
1908 hashclr(oi
->delta_base_sha1
);
1912 unuse_pack(&w_curs
);
1916 static void *unpack_compressed_entry(struct packed_git
*p
,
1917 struct pack_window
**w_curs
,
1923 unsigned char *buffer
, *in
;
1925 buffer
= xmallocz(size
);
1926 memset(&stream
, 0, sizeof(stream
));
1927 stream
.next_out
= buffer
;
1928 stream
.avail_out
= size
+ 1;
1930 git_inflate_init(&stream
);
1932 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1933 stream
.next_in
= in
;
1934 st
= git_inflate(&stream
, Z_FINISH
);
1935 if (!stream
.avail_out
)
1936 break; /* the payload is larger than it should be */
1937 curpos
+= stream
.next_in
- in
;
1938 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
1939 git_inflate_end(&stream
);
1940 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
1948 #define MAX_DELTA_CACHE (256)
1950 static size_t delta_base_cached
;
1952 static struct delta_base_cache_lru_list
{
1953 struct delta_base_cache_lru_list
*prev
;
1954 struct delta_base_cache_lru_list
*next
;
1955 } delta_base_cache_lru
= { &delta_base_cache_lru
, &delta_base_cache_lru
};
1957 static struct delta_base_cache_entry
{
1958 struct delta_base_cache_lru_list lru
;
1960 struct packed_git
*p
;
1963 enum object_type type
;
1964 } delta_base_cache
[MAX_DELTA_CACHE
];
1966 static unsigned long pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
1970 hash
= (unsigned long)p
+ (unsigned long)base_offset
;
1971 hash
+= (hash
>> 8) + (hash
>> 16);
1972 return hash
% MAX_DELTA_CACHE
;
1975 static struct delta_base_cache_entry
*
1976 get_delta_base_cache_entry(struct packed_git
*p
, off_t base_offset
)
1978 unsigned long hash
= pack_entry_hash(p
, base_offset
);
1979 return delta_base_cache
+ hash
;
1982 static int eq_delta_base_cache_entry(struct delta_base_cache_entry
*ent
,
1983 struct packed_git
*p
, off_t base_offset
)
1985 return (ent
->data
&& ent
->p
== p
&& ent
->base_offset
== base_offset
);
1988 static int in_delta_base_cache(struct packed_git
*p
, off_t base_offset
)
1990 struct delta_base_cache_entry
*ent
;
1991 ent
= get_delta_base_cache_entry(p
, base_offset
);
1992 return eq_delta_base_cache_entry(ent
, p
, base_offset
);
1995 static void clear_delta_base_cache_entry(struct delta_base_cache_entry
*ent
)
1998 ent
->lru
.next
->prev
= ent
->lru
.prev
;
1999 ent
->lru
.prev
->next
= ent
->lru
.next
;
2000 delta_base_cached
-= ent
->size
;
2003 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
2004 unsigned long *base_size
, enum object_type
*type
, int keep_cache
)
2006 struct delta_base_cache_entry
*ent
;
2009 ent
= get_delta_base_cache_entry(p
, base_offset
);
2011 if (!eq_delta_base_cache_entry(ent
, p
, base_offset
))
2012 return unpack_entry(p
, base_offset
, type
, base_size
);
2017 clear_delta_base_cache_entry(ent
);
2019 ret
= xmemdupz(ent
->data
, ent
->size
);
2021 *base_size
= ent
->size
;
2025 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
2030 ent
->lru
.next
->prev
= ent
->lru
.prev
;
2031 ent
->lru
.prev
->next
= ent
->lru
.next
;
2032 delta_base_cached
-= ent
->size
;
2036 void clear_delta_base_cache(void)
2039 for (p
= 0; p
< MAX_DELTA_CACHE
; p
++)
2040 release_delta_base_cache(&delta_base_cache
[p
]);
2043 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
2044 void *base
, unsigned long base_size
, enum object_type type
)
2046 unsigned long hash
= pack_entry_hash(p
, base_offset
);
2047 struct delta_base_cache_entry
*ent
= delta_base_cache
+ hash
;
2048 struct delta_base_cache_lru_list
*lru
;
2050 release_delta_base_cache(ent
);
2051 delta_base_cached
+= base_size
;
2053 for (lru
= delta_base_cache_lru
.next
;
2054 delta_base_cached
> delta_base_cache_limit
2055 && lru
!= &delta_base_cache_lru
;
2057 struct delta_base_cache_entry
*f
= (void *)lru
;
2058 if (f
->type
== OBJ_BLOB
)
2059 release_delta_base_cache(f
);
2061 for (lru
= delta_base_cache_lru
.next
;
2062 delta_base_cached
> delta_base_cache_limit
2063 && lru
!= &delta_base_cache_lru
;
2065 struct delta_base_cache_entry
*f
= (void *)lru
;
2066 release_delta_base_cache(f
);
2070 ent
->base_offset
= base_offset
;
2073 ent
->size
= base_size
;
2074 ent
->lru
.next
= &delta_base_cache_lru
;
2075 ent
->lru
.prev
= delta_base_cache_lru
.prev
;
2076 delta_base_cache_lru
.prev
->next
= &ent
->lru
;
2077 delta_base_cache_lru
.prev
= &ent
->lru
;
2080 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2081 unsigned long *size
);
2083 static void write_pack_access_log(struct packed_git
*p
, off_t obj_offset
)
2085 static FILE *log_file
;
2087 if (!log_pack_access
)
2088 log_pack_access
= getenv("GIT_TRACE_PACK_ACCESS");
2089 if (!log_pack_access
)
2090 log_pack_access
= no_log_pack_access
;
2091 if (log_pack_access
== no_log_pack_access
)
2095 log_file
= fopen(log_pack_access
, "w");
2097 error("cannot open pack access log '%s' for writing: %s",
2098 log_pack_access
, strerror(errno
));
2099 log_pack_access
= no_log_pack_access
;
2103 fprintf(log_file
, "%s %"PRIuMAX
"\n",
2104 p
->pack_name
, (uintmax_t)obj_offset
);
2108 int do_check_packed_object_crc
;
2110 #define UNPACK_ENTRY_STACK_PREALLOC 64
2111 struct unpack_entry_stack_ent
{
2117 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
2118 enum object_type
*final_type
, unsigned long *final_size
)
2120 struct pack_window
*w_curs
= NULL
;
2121 off_t curpos
= obj_offset
;
2124 enum object_type type
;
2125 struct unpack_entry_stack_ent small_delta_stack
[UNPACK_ENTRY_STACK_PREALLOC
];
2126 struct unpack_entry_stack_ent
*delta_stack
= small_delta_stack
;
2127 int delta_stack_nr
= 0, delta_stack_alloc
= UNPACK_ENTRY_STACK_PREALLOC
;
2128 int base_from_cache
= 0;
2130 if (log_pack_access
!= no_log_pack_access
)
2131 write_pack_access_log(p
, obj_offset
);
2133 /* PHASE 1: drill down to the innermost base object */
2137 struct delta_base_cache_entry
*ent
;
2139 ent
= get_delta_base_cache_entry(p
, curpos
);
2140 if (eq_delta_base_cache_entry(ent
, p
, curpos
)) {
2144 clear_delta_base_cache_entry(ent
);
2145 base_from_cache
= 1;
2149 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
2150 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2151 unsigned long len
= revidx
[1].offset
- obj_offset
;
2152 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
2153 const unsigned char *sha1
=
2154 nth_packed_object_sha1(p
, revidx
->nr
);
2155 error("bad packed object CRC for %s",
2157 mark_bad_packed_object(p
, sha1
);
2158 unuse_pack(&w_curs
);
2163 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2164 if (type
!= OBJ_OFS_DELTA
&& type
!= OBJ_REF_DELTA
)
2167 base_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
2169 error("failed to validate delta base reference "
2170 "at offset %"PRIuMAX
" from %s",
2171 (uintmax_t)curpos
, p
->pack_name
);
2172 /* bail to phase 2, in hopes of recovery */
2177 /* push object, proceed to base */
2178 if (delta_stack_nr
>= delta_stack_alloc
2179 && delta_stack
== small_delta_stack
) {
2180 delta_stack_alloc
= alloc_nr(delta_stack_nr
);
2181 delta_stack
= xmalloc(sizeof(*delta_stack
)*delta_stack_alloc
);
2182 memcpy(delta_stack
, small_delta_stack
,
2183 sizeof(*delta_stack
)*delta_stack_nr
);
2185 ALLOC_GROW(delta_stack
, delta_stack_nr
+1, delta_stack_alloc
);
2187 i
= delta_stack_nr
++;
2188 delta_stack
[i
].obj_offset
= obj_offset
;
2189 delta_stack
[i
].curpos
= curpos
;
2190 delta_stack
[i
].size
= size
;
2192 curpos
= obj_offset
= base_offset
;
2195 /* PHASE 2: handle the base */
2200 die("BUG in unpack_entry: left loop at a valid delta");
2206 if (!base_from_cache
)
2207 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, size
);
2211 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2212 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2215 /* PHASE 3: apply deltas in order */
2218 * 'data' holds the base data, or NULL if there was corruption
2220 while (delta_stack_nr
) {
2223 unsigned long delta_size
, base_size
= size
;
2229 add_delta_base_cache(p
, obj_offset
, base
, base_size
, type
);
2233 * We're probably in deep shit, but let's try to fetch
2234 * the required base anyway from another pack or loose.
2235 * This is costly but should happen only in the presence
2236 * of a corrupted pack, and is better than failing outright.
2238 struct revindex_entry
*revidx
;
2239 const unsigned char *base_sha1
;
2240 revidx
= find_pack_revindex(p
, obj_offset
);
2242 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2243 error("failed to read delta base object %s"
2244 " at offset %"PRIuMAX
" from %s",
2245 sha1_to_hex(base_sha1
), (uintmax_t)obj_offset
,
2247 mark_bad_packed_object(p
, base_sha1
);
2248 base
= read_object(base_sha1
, &type
, &base_size
);
2252 i
= --delta_stack_nr
;
2253 obj_offset
= delta_stack
[i
].obj_offset
;
2254 curpos
= delta_stack
[i
].curpos
;
2255 delta_size
= delta_stack
[i
].size
;
2260 delta_data
= unpack_compressed_entry(p
, &w_curs
, curpos
, delta_size
);
2263 error("failed to unpack compressed delta "
2264 "at offset %"PRIuMAX
" from %s",
2265 (uintmax_t)curpos
, p
->pack_name
);
2270 data
= patch_delta(base
, base_size
,
2271 delta_data
, delta_size
,
2275 * We could not apply the delta; warn the user, but keep going.
2276 * Our failure will be noticed either in the next iteration of
2277 * the loop, or if this is the final delta, in the caller when
2278 * we return NULL. Those code paths will take care of making
2279 * a more explicit warning and retrying with another copy of
2283 error("failed to apply delta");
2291 unuse_pack(&w_curs
);
2295 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
2298 const unsigned char *index
= p
->index_data
;
2300 if (open_pack_index(p
))
2302 index
= p
->index_data
;
2304 if (n
>= p
->num_objects
)
2307 if (p
->index_version
== 1) {
2308 return index
+ 24 * n
+ 4;
2311 return index
+ 20 * n
;
2315 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
2317 const unsigned char *index
= p
->index_data
;
2319 if (p
->index_version
== 1) {
2320 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
2323 index
+= 8 + p
->num_objects
* (20 + 4);
2324 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
2325 if (!(off
& 0x80000000))
2327 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
2328 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
2329 ntohl(*((uint32_t *)(index
+ 4)));
2333 off_t
find_pack_entry_one(const unsigned char *sha1
,
2334 struct packed_git
*p
)
2336 const uint32_t *level1_ofs
= p
->index_data
;
2337 const unsigned char *index
= p
->index_data
;
2338 unsigned hi
, lo
, stride
;
2339 static int use_lookup
= -1;
2340 static int debug_lookup
= -1;
2342 if (debug_lookup
< 0)
2343 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
2346 if (open_pack_index(p
))
2348 level1_ofs
= p
->index_data
;
2349 index
= p
->index_data
;
2351 if (p
->index_version
> 1) {
2356 hi
= ntohl(level1_ofs
[*sha1
]);
2357 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
2358 if (p
->index_version
> 1) {
2366 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
2367 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
2370 use_lookup
= !!getenv("GIT_USE_LOOKUP");
2372 int pos
= sha1_entry_pos(index
, stride
, 0,
2373 lo
, hi
, p
->num_objects
, sha1
);
2376 return nth_packed_object_offset(p
, pos
);
2380 unsigned mi
= (lo
+ hi
) / 2;
2381 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
2384 printf("lo %u hi %u rg %u mi %u\n",
2385 lo
, hi
, hi
- lo
, mi
);
2387 return nth_packed_object_offset(p
, mi
);
2396 int is_pack_valid(struct packed_git
*p
)
2398 /* An already open pack is known to be valid. */
2399 if (p
->pack_fd
!= -1)
2402 /* If the pack has one window completely covering the
2403 * file size, the pack is known to be valid even if
2404 * the descriptor is not currently open.
2407 struct pack_window
*w
= p
->windows
;
2409 if (!w
->offset
&& w
->len
== p
->pack_size
)
2413 /* Force the pack to open to prove its valid. */
2414 return !open_packed_git(p
);
2417 static int fill_pack_entry(const unsigned char *sha1
,
2418 struct pack_entry
*e
,
2419 struct packed_git
*p
)
2423 if (p
->num_bad_objects
) {
2425 for (i
= 0; i
< p
->num_bad_objects
; i
++)
2426 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
2430 offset
= find_pack_entry_one(sha1
, p
);
2435 * We are about to tell the caller where they can locate the
2436 * requested object. We better make sure the packfile is
2437 * still here and can be accessed before supplying that
2438 * answer, as it may have been deleted since the index was
2441 if (!is_pack_valid(p
)) {
2442 warning("packfile %s cannot be accessed", p
->pack_name
);
2447 hashcpy(e
->sha1
, sha1
);
2451 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
2453 struct packed_git
*p
;
2455 prepare_packed_git();
2459 if (last_found_pack
&& fill_pack_entry(sha1
, e
, last_found_pack
))
2462 for (p
= packed_git
; p
; p
= p
->next
) {
2463 if (p
== last_found_pack
|| !fill_pack_entry(sha1
, e
, p
))
2466 last_found_pack
= p
;
2472 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
2473 struct packed_git
*packs
)
2475 struct packed_git
*p
;
2477 for (p
= packs
; p
; p
= p
->next
) {
2478 if (find_pack_entry_one(sha1
, p
))
2485 static int sha1_loose_object_info(const unsigned char *sha1
,
2486 struct object_info
*oi
)
2489 unsigned long mapsize
, size
;
2494 if (oi
->delta_base_sha1
)
2495 hashclr(oi
->delta_base_sha1
);
2498 * If we don't care about type or size, then we don't
2499 * need to look inside the object at all. Note that we
2500 * do not optimize out the stat call, even if the
2501 * caller doesn't care about the disk-size, since our
2502 * return value implicitly indicates whether the
2503 * object even exists.
2505 if (!oi
->typep
&& !oi
->sizep
) {
2507 if (stat_sha1_file(sha1
, &st
) < 0)
2510 *oi
->disk_sizep
= st
.st_size
;
2514 map
= map_sha1_file(sha1
, &mapsize
);
2518 *oi
->disk_sizep
= mapsize
;
2519 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
2520 status
= error("unable to unpack %s header",
2522 else if ((status
= parse_sha1_header(hdr
, &size
)) < 0)
2523 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
2526 git_inflate_end(&stream
);
2527 munmap(map
, mapsize
);
2529 *oi
->typep
= status
;
2533 int sha1_object_info_extended(const unsigned char *sha1
, struct object_info
*oi
, unsigned flags
)
2535 struct cached_object
*co
;
2536 struct pack_entry e
;
2538 const unsigned char *real
= lookup_replace_object_extended(sha1
, flags
);
2540 co
= find_cached_object(real
);
2543 *(oi
->typep
) = co
->type
;
2545 *(oi
->sizep
) = co
->size
;
2547 *(oi
->disk_sizep
) = 0;
2548 if (oi
->delta_base_sha1
)
2549 hashclr(oi
->delta_base_sha1
);
2550 oi
->whence
= OI_CACHED
;
2554 if (!find_pack_entry(real
, &e
)) {
2555 /* Most likely it's a loose object. */
2556 if (!sha1_loose_object_info(real
, oi
)) {
2557 oi
->whence
= OI_LOOSE
;
2561 /* Not a loose object; someone else may have just packed it. */
2562 reprepare_packed_git();
2563 if (!find_pack_entry(real
, &e
))
2567 rtype
= packed_object_info(e
.p
, e
.offset
, oi
);
2569 mark_bad_packed_object(e
.p
, real
);
2570 return sha1_object_info_extended(real
, oi
, 0);
2571 } else if (in_delta_base_cache(e
.p
, e
.offset
)) {
2572 oi
->whence
= OI_DBCACHED
;
2574 oi
->whence
= OI_PACKED
;
2575 oi
->u
.packed
.offset
= e
.offset
;
2576 oi
->u
.packed
.pack
= e
.p
;
2577 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
2578 rtype
== OBJ_OFS_DELTA
);
2584 /* returns enum object_type or negative */
2585 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
2587 enum object_type type
;
2588 struct object_info oi
= {NULL
};
2592 if (sha1_object_info_extended(sha1
, &oi
, LOOKUP_REPLACE_OBJECT
) < 0)
2597 static void *read_packed_sha1(const unsigned char *sha1
,
2598 enum object_type
*type
, unsigned long *size
)
2600 struct pack_entry e
;
2603 if (!find_pack_entry(sha1
, &e
))
2605 data
= cache_or_unpack_entry(e
.p
, e
.offset
, size
, type
, 1);
2608 * We're probably in deep shit, but let's try to fetch
2609 * the required object anyway from another pack or loose.
2610 * This should happen only in the presence of a corrupted
2611 * pack, and is better than failing outright.
2613 error("failed to read object %s at offset %"PRIuMAX
" from %s",
2614 sha1_to_hex(sha1
), (uintmax_t)e
.offset
, e
.p
->pack_name
);
2615 mark_bad_packed_object(e
.p
, sha1
);
2616 data
= read_object(sha1
, type
, size
);
2621 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
2622 unsigned char *sha1
)
2624 struct cached_object
*co
;
2626 hash_sha1_file(buf
, len
, typename(type
), sha1
);
2627 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
2629 if (cached_object_alloc
<= cached_object_nr
) {
2630 cached_object_alloc
= alloc_nr(cached_object_alloc
);
2631 cached_objects
= xrealloc(cached_objects
,
2632 sizeof(*cached_objects
) *
2633 cached_object_alloc
);
2635 co
= &cached_objects
[cached_object_nr
++];
2638 co
->buf
= xmalloc(len
);
2639 memcpy(co
->buf
, buf
, len
);
2640 hashcpy(co
->sha1
, sha1
);
2644 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2645 unsigned long *size
)
2647 unsigned long mapsize
;
2649 struct cached_object
*co
;
2651 co
= find_cached_object(sha1
);
2655 return xmemdupz(co
->buf
, co
->size
);
2658 buf
= read_packed_sha1(sha1
, type
, size
);
2661 map
= map_sha1_file(sha1
, &mapsize
);
2663 buf
= unpack_sha1_file(map
, mapsize
, type
, size
, sha1
);
2664 munmap(map
, mapsize
);
2667 reprepare_packed_git();
2668 return read_packed_sha1(sha1
, type
, size
);
2672 * This function dies on corrupt objects; the callers who want to
2673 * deal with them should arrange to call read_object() and give error
2674 * messages themselves.
2676 void *read_sha1_file_extended(const unsigned char *sha1
,
2677 enum object_type
*type
,
2678 unsigned long *size
,
2683 const struct packed_git
*p
;
2684 const unsigned char *repl
= lookup_replace_object_extended(sha1
, flag
);
2687 data
= read_object(repl
, type
, size
);
2691 if (errno
&& errno
!= ENOENT
)
2692 die_errno("failed to read object %s", sha1_to_hex(sha1
));
2694 /* die if we replaced an object with one that does not exist */
2696 die("replacement %s not found for %s",
2697 sha1_to_hex(repl
), sha1_to_hex(sha1
));
2699 if (has_loose_object(repl
)) {
2700 path
= sha1_file_name(sha1
);
2701 die("loose object %s (stored in %s) is corrupt",
2702 sha1_to_hex(repl
), path
);
2705 if ((p
= has_packed_and_bad(repl
)) != NULL
)
2706 die("packed object %s (stored in %s) is corrupt",
2707 sha1_to_hex(repl
), p
->pack_name
);
2712 void *read_object_with_reference(const unsigned char *sha1
,
2713 const char *required_type_name
,
2714 unsigned long *size
,
2715 unsigned char *actual_sha1_return
)
2717 enum object_type type
, required_type
;
2719 unsigned long isize
;
2720 unsigned char actual_sha1
[20];
2722 required_type
= type_from_string(required_type_name
);
2723 hashcpy(actual_sha1
, sha1
);
2725 int ref_length
= -1;
2726 const char *ref_type
= NULL
;
2728 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
2731 if (type
== required_type
) {
2733 if (actual_sha1_return
)
2734 hashcpy(actual_sha1_return
, actual_sha1
);
2737 /* Handle references */
2738 else if (type
== OBJ_COMMIT
)
2740 else if (type
== OBJ_TAG
)
2741 ref_type
= "object ";
2746 ref_length
= strlen(ref_type
);
2748 if (ref_length
+ 40 > isize
||
2749 memcmp(buffer
, ref_type
, ref_length
) ||
2750 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
2755 /* Now we have the ID of the referred-to object in
2756 * actual_sha1. Check again. */
2760 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
2761 const char *type
, unsigned char *sha1
,
2762 char *hdr
, int *hdrlen
)
2766 /* Generate the header */
2767 *hdrlen
= sprintf(hdr
, "%s %lu", type
, len
)+1;
2771 git_SHA1_Update(&c
, hdr
, *hdrlen
);
2772 git_SHA1_Update(&c
, buf
, len
);
2773 git_SHA1_Final(sha1
, &c
);
2777 * Move the just written object into its final resting place.
2778 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2779 * "moving" is only a part of what it does, when no patch between
2780 * master to pu changes the call sites of this function.
2782 int move_temp_to_file(const char *tmpfile
, const char *filename
)
2786 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
2788 else if (link(tmpfile
, filename
))
2792 * Coda hack - coda doesn't like cross-directory links,
2793 * so we fall back to a rename, which will mean that it
2794 * won't be able to check collisions, but that's not a
2797 * The same holds for FAT formatted media.
2799 * When this succeeds, we just return. We have nothing
2802 if (ret
&& ret
!= EEXIST
) {
2804 if (!rename(tmpfile
, filename
))
2808 unlink_or_warn(tmpfile
);
2810 if (ret
!= EEXIST
) {
2811 return error("unable to write sha1 filename %s: %s", filename
, strerror(ret
));
2813 /* FIXME!!! Collision check here ? */
2817 if (adjust_shared_perm(filename
))
2818 return error("unable to set permission to '%s'", filename
);
2822 static int write_buffer(int fd
, const void *buf
, size_t len
)
2824 if (write_in_full(fd
, buf
, len
) < 0)
2825 return error("file write error (%s)", strerror(errno
));
2829 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
2830 unsigned char *sha1
)
2834 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2838 /* Finalize a file on disk, and close it. */
2839 static void close_sha1_file(int fd
)
2841 if (fsync_object_files
)
2842 fsync_or_die(fd
, "sha1 file");
2844 die_errno("error when closing sha1 file");
2847 /* Size of directory component, including the ending '/' */
2848 static inline int directory_size(const char *filename
)
2850 const char *s
= strrchr(filename
, '/');
2853 return s
- filename
+ 1;
2857 * This creates a temporary file in the same directory as the final
2860 * We want to avoid cross-directory filename renames, because those
2861 * can have problems on various filesystems (FAT, NFS, Coda).
2863 static int create_tmpfile(char *buffer
, size_t bufsiz
, const char *filename
)
2865 int fd
, dirlen
= directory_size(filename
);
2867 if (dirlen
+ 20 > bufsiz
) {
2868 errno
= ENAMETOOLONG
;
2871 memcpy(buffer
, filename
, dirlen
);
2872 strcpy(buffer
+ dirlen
, "tmp_obj_XXXXXX");
2873 fd
= git_mkstemp_mode(buffer
, 0444);
2874 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
2875 /* Make sure the directory exists */
2876 memcpy(buffer
, filename
, dirlen
);
2877 buffer
[dirlen
-1] = 0;
2878 if (mkdir(buffer
, 0777) && errno
!= EEXIST
)
2880 if (adjust_shared_perm(buffer
))
2884 strcpy(buffer
+ dirlen
- 1, "/tmp_obj_XXXXXX");
2885 fd
= git_mkstemp_mode(buffer
, 0444);
2890 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
2891 const void *buf
, unsigned long len
, time_t mtime
)
2894 unsigned char compressed
[4096];
2897 unsigned char parano_sha1
[20];
2899 static char tmp_file
[PATH_MAX
];
2901 filename
= sha1_file_name(sha1
);
2902 fd
= create_tmpfile(tmp_file
, sizeof(tmp_file
), filename
);
2904 if (errno
== EACCES
)
2905 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2907 return error("unable to create temporary file: %s", strerror(errno
));
2911 memset(&stream
, 0, sizeof(stream
));
2912 git_deflate_init(&stream
, zlib_compression_level
);
2913 stream
.next_out
= compressed
;
2914 stream
.avail_out
= sizeof(compressed
);
2917 /* First header.. */
2918 stream
.next_in
= (unsigned char *)hdr
;
2919 stream
.avail_in
= hdrlen
;
2920 while (git_deflate(&stream
, 0) == Z_OK
)
2922 git_SHA1_Update(&c
, hdr
, hdrlen
);
2924 /* Then the data itself.. */
2925 stream
.next_in
= (void *)buf
;
2926 stream
.avail_in
= len
;
2928 unsigned char *in0
= stream
.next_in
;
2929 ret
= git_deflate(&stream
, Z_FINISH
);
2930 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
2931 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
2932 die("unable to write sha1 file");
2933 stream
.next_out
= compressed
;
2934 stream
.avail_out
= sizeof(compressed
);
2935 } while (ret
== Z_OK
);
2937 if (ret
!= Z_STREAM_END
)
2938 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
2939 ret
= git_deflate_end_gently(&stream
);
2941 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
2942 git_SHA1_Final(parano_sha1
, &c
);
2943 if (hashcmp(sha1
, parano_sha1
) != 0)
2944 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
2946 close_sha1_file(fd
);
2951 utb
.modtime
= mtime
;
2952 if (utime(tmp_file
, &utb
) < 0)
2953 warning("failed utime() on %s: %s",
2954 tmp_file
, strerror(errno
));
2957 return move_temp_to_file(tmp_file
, filename
);
2960 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *returnsha1
)
2962 unsigned char sha1
[20];
2966 /* Normally if we have it in the pack then we do not bother writing
2967 * it out into .git/objects/??/?{38} file.
2969 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2971 hashcpy(returnsha1
, sha1
);
2972 if (has_sha1_file(sha1
))
2974 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
2977 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
2981 enum object_type type
;
2986 if (has_loose_object(sha1
))
2988 buf
= read_packed_sha1(sha1
, &type
, &len
);
2990 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
2991 hdrlen
= sprintf(hdr
, "%s %lu", typename(type
), len
) + 1;
2992 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
2998 int has_pack_index(const unsigned char *sha1
)
3001 if (stat(sha1_pack_index_name(sha1
), &st
))
3006 int has_sha1_pack(const unsigned char *sha1
)
3008 struct pack_entry e
;
3009 return find_pack_entry(sha1
, &e
);
3012 int has_sha1_file(const unsigned char *sha1
)
3014 struct pack_entry e
;
3016 if (find_pack_entry(sha1
, &e
))
3018 if (has_loose_object(sha1
))
3020 reprepare_packed_git();
3021 return find_pack_entry(sha1
, &e
);
3024 static void check_tree(const void *buf
, size_t size
)
3026 struct tree_desc desc
;
3027 struct name_entry entry
;
3029 init_tree_desc(&desc
, buf
, size
);
3030 while (tree_entry(&desc
, &entry
))
3032 * tree_entry() will die() on malformed entries */
3036 static void check_commit(const void *buf
, size_t size
)
3039 memset(&c
, 0, sizeof(c
));
3040 if (parse_commit_buffer(&c
, buf
, size
))
3041 die("corrupt commit");
3044 static void check_tag(const void *buf
, size_t size
)
3047 memset(&t
, 0, sizeof(t
));
3048 if (parse_tag_buffer(&t
, buf
, size
))
3052 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
3053 enum object_type type
,
3054 const char *path
, unsigned flags
)
3056 int ret
, re_allocated
= 0;
3057 int write_object
= flags
& HASH_WRITE_OBJECT
;
3063 * Convert blobs to git internal format
3065 if ((type
== OBJ_BLOB
) && path
) {
3066 struct strbuf nbuf
= STRBUF_INIT
;
3067 if (convert_to_git(path
, buf
, size
, &nbuf
,
3068 write_object
? safe_crlf
: SAFE_CRLF_FALSE
)) {
3069 buf
= strbuf_detach(&nbuf
, &size
);
3073 if (flags
& HASH_FORMAT_CHECK
) {
3074 if (type
== OBJ_TREE
)
3075 check_tree(buf
, size
);
3076 if (type
== OBJ_COMMIT
)
3077 check_commit(buf
, size
);
3078 if (type
== OBJ_TAG
)
3079 check_tag(buf
, size
);
3083 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
3085 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
3091 static int index_pipe(unsigned char *sha1
, int fd
, enum object_type type
,
3092 const char *path
, unsigned flags
)
3094 struct strbuf sbuf
= STRBUF_INIT
;
3097 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
3098 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
3101 strbuf_release(&sbuf
);
3105 #define SMALL_FILE_SIZE (32*1024)
3107 static int index_core(unsigned char *sha1
, int fd
, size_t size
,
3108 enum object_type type
, const char *path
,
3114 ret
= index_mem(sha1
, NULL
, size
, type
, path
, flags
);
3115 } else if (size
<= SMALL_FILE_SIZE
) {
3116 char *buf
= xmalloc(size
);
3117 if (size
== read_in_full(fd
, buf
, size
))
3118 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3120 ret
= error("short read %s", strerror(errno
));
3123 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
3124 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3131 * This creates one packfile per large blob unless bulk-checkin
3132 * machinery is "plugged".
3134 * This also bypasses the usual "convert-to-git" dance, and that is on
3135 * purpose. We could write a streaming version of the converting
3136 * functions and insert that before feeding the data to fast-import
3137 * (or equivalent in-core API described above). However, that is
3138 * somewhat complicated, as we do not know the size of the filter
3139 * result, which we need to know beforehand when writing a git object.
3140 * Since the primary motivation for trying to stream from the working
3141 * tree file and to avoid mmaping it in core is to deal with large
3142 * binary blobs, they generally do not want to get any conversion, and
3143 * callers should avoid this code path when filters are requested.
3145 static int index_stream(unsigned char *sha1
, int fd
, size_t size
,
3146 enum object_type type
, const char *path
,
3149 return index_bulk_checkin(sha1
, fd
, size
, type
, path
, flags
);
3152 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
,
3153 enum object_type type
, const char *path
, unsigned flags
)
3156 size_t size
= xsize_t(st
->st_size
);
3158 if (!S_ISREG(st
->st_mode
))
3159 ret
= index_pipe(sha1
, fd
, type
, path
, flags
);
3160 else if (size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
3161 (path
&& would_convert_to_git(path
, NULL
, 0, 0)))
3162 ret
= index_core(sha1
, fd
, size
, type
, path
, flags
);
3164 ret
= index_stream(sha1
, fd
, size
, type
, path
, flags
);
3169 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, unsigned flags
)
3172 struct strbuf sb
= STRBUF_INIT
;
3174 switch (st
->st_mode
& S_IFMT
) {
3176 fd
= open(path
, O_RDONLY
);
3178 return error("open(\"%s\"): %s", path
,
3180 if (index_fd(sha1
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
3181 return error("%s: failed to insert into database",
3185 if (strbuf_readlink(&sb
, path
, st
->st_size
)) {
3186 char *errstr
= strerror(errno
);
3187 return error("readlink(\"%s\"): %s", path
,
3190 if (!(flags
& HASH_WRITE_OBJECT
))
3191 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
3192 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
3193 return error("%s: failed to insert into database",
3195 strbuf_release(&sb
);
3198 return resolve_gitlink_ref(path
, "HEAD", sha1
);
3200 return error("%s: unsupported file type", path
);
3205 int read_pack_header(int fd
, struct pack_header
*header
)
3207 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
3208 /* "eof before pack header was fully read" */
3209 return PH_ERROR_EOF
;
3211 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
3212 /* "protocol error (pack signature mismatch detected)" */
3213 return PH_ERROR_PACK_SIGNATURE
;
3214 if (!pack_version_ok(header
->hdr_version
))
3215 /* "protocol error (pack version unsupported)" */
3216 return PH_ERROR_PROTOCOL
;
3220 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
3222 enum object_type type
= sha1_object_info(sha1
, NULL
);
3224 die("%s is not a valid object", sha1_to_hex(sha1
));
3226 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),