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];
40 * This is meant to hold a *small* number of objects that you would
41 * want read_sha1_file() to be able to return, but yet you do not want
42 * to write them into the object store (e.g. a browse-only
45 static struct cached_object
{
46 unsigned char sha1
[20];
47 enum object_type type
;
51 static int cached_object_nr
, cached_object_alloc
;
53 static struct cached_object empty_tree
= {
54 EMPTY_TREE_SHA1_BIN_LITERAL
,
61 * A pointer to the last packed_git in which an object was found.
62 * When an object is sought, we look in this packfile first, because
63 * objects that are looked up at similar times are often in the same
64 * packfile as one another.
66 static struct packed_git
*last_found_pack
;
68 static struct cached_object
*find_cached_object(const unsigned char *sha1
)
71 struct cached_object
*co
= cached_objects
;
73 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
74 if (!hashcmp(co
->sha1
, sha1
))
77 if (!hashcmp(sha1
, empty_tree
.sha1
))
82 int mkdir_in_gitdir(const char *path
)
84 if (mkdir(path
, 0777)) {
85 int saved_errno
= errno
;
87 struct strbuf sb
= STRBUF_INIT
;
92 * Are we looking at a path in a symlinked worktree
93 * whose original repository does not yet have it?
94 * e.g. .git/rr-cache pointing at its original
95 * repository in which the user hasn't performed any
96 * conflict resolution yet?
98 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
99 strbuf_readlink(&sb
, path
, st
.st_size
) ||
100 !is_absolute_path(sb
.buf
) ||
101 mkdir(sb
.buf
, 0777)) {
108 return adjust_shared_perm(path
);
111 enum scld_error
safe_create_leading_directories(char *path
)
113 char *next_component
= path
+ offset_1st_component(path
);
114 enum scld_error ret
= SCLD_OK
;
116 while (ret
== SCLD_OK
&& next_component
) {
118 char *slash
= next_component
, slash_character
;
120 while (*slash
&& !is_dir_sep(*slash
))
126 next_component
= slash
+ 1;
127 while (is_dir_sep(*next_component
))
129 if (!*next_component
)
132 slash_character
= *slash
;
134 if (!stat(path
, &st
)) {
136 if (!S_ISDIR(st
.st_mode
))
138 } else if (mkdir(path
, 0777)) {
139 if (errno
== EEXIST
&&
140 !stat(path
, &st
) && S_ISDIR(st
.st_mode
))
141 ; /* somebody created it since we checked */
142 else if (errno
== ENOENT
)
144 * Either mkdir() failed because
145 * somebody just pruned the containing
146 * directory, or stat() failed because
147 * the file that was in our way was
148 * just removed. Either way, inform
149 * the caller that it might be worth
155 } else if (adjust_shared_perm(path
)) {
158 *slash
= slash_character
;
163 enum scld_error
safe_create_leading_directories_const(const char *path
)
165 /* path points to cache entries, so xstrdup before messing with it */
166 char *buf
= xstrdup(path
);
167 enum scld_error result
= safe_create_leading_directories(buf
);
172 static void fill_sha1_path(char *pathbuf
, const unsigned char *sha1
)
175 for (i
= 0; i
< 20; i
++) {
176 static char hex
[] = "0123456789abcdef";
177 unsigned int val
= sha1
[i
];
178 char *pos
= pathbuf
+ i
*2 + (i
> 0);
179 *pos
++ = hex
[val
>> 4];
180 *pos
= hex
[val
& 0xf];
184 const char *sha1_file_name(const unsigned char *sha1
)
186 static char buf
[PATH_MAX
];
190 objdir
= get_object_directory();
191 len
= strlen(objdir
);
193 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
194 if (len
+ 43 > PATH_MAX
)
195 die("insanely long object directory %s", objdir
);
196 memcpy(buf
, objdir
, len
);
200 fill_sha1_path(buf
+ len
+ 1, sha1
);
205 * Return the name of the pack or index file with the specified sha1
206 * in its filename. *base and *name are scratch space that must be
207 * provided by the caller. which should be "pack" or "idx".
209 static char *sha1_get_pack_name(const unsigned char *sha1
,
210 char **name
, char **base
, const char *which
)
212 static const char hex
[] = "0123456789abcdef";
217 const char *sha1_file_directory
= get_object_directory();
218 int len
= strlen(sha1_file_directory
);
219 *base
= xmalloc(len
+ 60);
220 sprintf(*base
, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
221 sha1_file_directory
, which
);
222 *name
= *base
+ len
+ 11;
227 for (i
= 0; i
< 20; i
++) {
228 unsigned int val
= *sha1
++;
229 *buf
++ = hex
[val
>> 4];
230 *buf
++ = hex
[val
& 0xf];
236 char *sha1_pack_name(const unsigned char *sha1
)
238 static char *name
, *base
;
240 return sha1_get_pack_name(sha1
, &name
, &base
, "pack");
243 char *sha1_pack_index_name(const unsigned char *sha1
)
245 static char *name
, *base
;
247 return sha1_get_pack_name(sha1
, &name
, &base
, "idx");
250 struct alternate_object_database
*alt_odb_list
;
251 static struct alternate_object_database
**alt_odb_tail
;
254 * Prepare alternate object database registry.
256 * The variable alt_odb_list points at the list of struct
257 * alternate_object_database. The elements on this list come from
258 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
259 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
260 * whose contents is similar to that environment variable but can be
261 * LF separated. Its base points at a statically allocated buffer that
262 * contains "/the/directory/corresponding/to/.git/objects/...", while
263 * its name points just after the slash at the end of ".git/objects/"
264 * in the example above, and has enough space to hold 40-byte hex
265 * SHA1, an extra slash for the first level indirection, and the
268 static int link_alt_odb_entry(const char *entry
, const char *relative_base
,
269 int depth
, const char *normalized_objdir
)
271 struct alternate_object_database
*ent
;
272 struct alternate_object_database
*alt
;
274 struct strbuf pathbuf
= STRBUF_INIT
;
276 if (!is_absolute_path(entry
) && relative_base
) {
277 strbuf_addstr(&pathbuf
, real_path(relative_base
));
278 strbuf_addch(&pathbuf
, '/');
280 strbuf_addstr(&pathbuf
, entry
);
282 normalize_path_copy(pathbuf
.buf
, pathbuf
.buf
);
284 pfxlen
= strlen(pathbuf
.buf
);
287 * The trailing slash after the directory name is given by
288 * this function at the end. Remove duplicates.
290 while (pfxlen
&& pathbuf
.buf
[pfxlen
-1] == '/')
293 entlen
= pfxlen
+ 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
294 ent
= xmalloc(sizeof(*ent
) + entlen
);
295 memcpy(ent
->base
, pathbuf
.buf
, pfxlen
);
296 strbuf_release(&pathbuf
);
298 ent
->name
= ent
->base
+ pfxlen
+ 1;
299 ent
->base
[pfxlen
+ 3] = '/';
300 ent
->base
[pfxlen
] = ent
->base
[entlen
-1] = 0;
302 /* Detect cases where alternate disappeared */
303 if (!is_directory(ent
->base
)) {
304 error("object directory %s does not exist; "
305 "check .git/objects/info/alternates.",
311 /* Prevent the common mistake of listing the same
312 * thing twice, or object directory itself.
314 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
315 if (pfxlen
== alt
->name
- alt
->base
- 1 &&
316 !memcmp(ent
->base
, alt
->base
, pfxlen
)) {
321 if (!strcmp_icase(ent
->base
, normalized_objdir
)) {
326 /* add the alternate entry */
328 alt_odb_tail
= &(ent
->next
);
331 /* recursively add alternates */
332 read_info_alternates(ent
->base
, depth
+ 1);
334 ent
->base
[pfxlen
] = '/';
339 static void link_alt_odb_entries(const char *alt
, int len
, int sep
,
340 const char *relative_base
, int depth
)
342 struct string_list entries
= STRING_LIST_INIT_NODUP
;
345 struct strbuf objdirbuf
= STRBUF_INIT
;
348 error("%s: ignoring alternate object stores, nesting too deep.",
353 strbuf_add_absolute_path(&objdirbuf
, get_object_directory());
354 normalize_path_copy(objdirbuf
.buf
, objdirbuf
.buf
);
356 alt_copy
= xmemdupz(alt
, len
);
357 string_list_split_in_place(&entries
, alt_copy
, sep
, -1);
358 for (i
= 0; i
< entries
.nr
; i
++) {
359 const char *entry
= entries
.items
[i
].string
;
360 if (entry
[0] == '\0' || entry
[0] == '#')
362 if (!is_absolute_path(entry
) && depth
) {
363 error("%s: ignoring relative alternate object store %s",
364 relative_base
, entry
);
366 link_alt_odb_entry(entry
, relative_base
, depth
, objdirbuf
.buf
);
369 string_list_clear(&entries
, 0);
371 strbuf_release(&objdirbuf
);
374 void read_info_alternates(const char * relative_base
, int depth
)
379 const char alt_file_name
[] = "info/alternates";
380 /* Given that relative_base is no longer than PATH_MAX,
381 ensure that "path" has enough space to append "/", the
382 file name, "info/alternates", and a trailing NUL. */
383 char path
[PATH_MAX
+ 1 + sizeof alt_file_name
];
386 sprintf(path
, "%s/%s", relative_base
, alt_file_name
);
387 fd
= git_open_noatime(path
);
390 if (fstat(fd
, &st
) || (st
.st_size
== 0)) {
394 mapsz
= xsize_t(st
.st_size
);
395 map
= xmmap(NULL
, mapsz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
398 link_alt_odb_entries(map
, mapsz
, '\n', relative_base
, depth
);
403 void add_to_alternates_file(const char *reference
)
405 struct lock_file
*lock
= xcalloc(1, sizeof(struct lock_file
));
406 int fd
= hold_lock_file_for_append(lock
, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR
);
407 char *alt
= mkpath("%s\n", reference
);
408 write_or_die(fd
, alt
, strlen(alt
));
409 if (commit_lock_file(lock
))
410 die("could not close alternates file");
412 link_alt_odb_entries(alt
, strlen(alt
), '\n', NULL
, 0);
415 int foreach_alt_odb(alt_odb_fn fn
, void *cb
)
417 struct alternate_object_database
*ent
;
421 for (ent
= alt_odb_list
; ent
; ent
= ent
->next
) {
429 void prepare_alt_odb(void)
436 alt
= getenv(ALTERNATE_DB_ENVIRONMENT
);
439 alt_odb_tail
= &alt_odb_list
;
440 link_alt_odb_entries(alt
, strlen(alt
), PATH_SEP
, NULL
, 0);
442 read_info_alternates(get_object_directory(), 0);
445 static int freshen_file(const char *fn
)
448 t
.actime
= t
.modtime
= time(NULL
);
449 return !utime(fn
, &t
);
452 static int check_and_freshen_file(const char *fn
, int freshen
)
454 if (access(fn
, F_OK
))
456 if (freshen
&& freshen_file(fn
))
461 static int check_and_freshen_local(const unsigned char *sha1
, int freshen
)
463 return check_and_freshen_file(sha1_file_name(sha1
), freshen
);
466 static int check_and_freshen_nonlocal(const unsigned char *sha1
, int freshen
)
468 struct alternate_object_database
*alt
;
470 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
471 fill_sha1_path(alt
->name
, sha1
);
472 if (check_and_freshen_file(alt
->base
, freshen
))
478 static int check_and_freshen(const unsigned char *sha1
, int freshen
)
480 return check_and_freshen_local(sha1
, freshen
) ||
481 check_and_freshen_nonlocal(sha1
, freshen
);
484 int has_loose_object_nonlocal(const unsigned char *sha1
)
486 return check_and_freshen_nonlocal(sha1
, 0);
489 static int has_loose_object(const unsigned char *sha1
)
491 return check_and_freshen(sha1
, 0);
494 static unsigned int pack_used_ctr
;
495 static unsigned int pack_mmap_calls
;
496 static unsigned int peak_pack_open_windows
;
497 static unsigned int pack_open_windows
;
498 static unsigned int pack_open_fds
;
499 static unsigned int pack_max_fds
;
500 static size_t peak_pack_mapped
;
501 static size_t pack_mapped
;
502 struct packed_git
*packed_git
;
504 void pack_report(void)
507 "pack_report: getpagesize() = %10" SZ_FMT
"\n"
508 "pack_report: core.packedGitWindowSize = %10" SZ_FMT
"\n"
509 "pack_report: core.packedGitLimit = %10" SZ_FMT
"\n",
510 sz_fmt(getpagesize()),
511 sz_fmt(packed_git_window_size
),
512 sz_fmt(packed_git_limit
));
514 "pack_report: pack_used_ctr = %10u\n"
515 "pack_report: pack_mmap_calls = %10u\n"
516 "pack_report: pack_open_windows = %10u / %10u\n"
517 "pack_report: pack_mapped = "
518 "%10" SZ_FMT
" / %10" SZ_FMT
"\n",
521 pack_open_windows
, peak_pack_open_windows
,
522 sz_fmt(pack_mapped
), sz_fmt(peak_pack_mapped
));
526 * Open and mmap the index file at path, perform a couple of
527 * consistency checks, then record its information to p. Return 0 on
530 static int check_packed_git_idx(const char *path
, struct packed_git
*p
)
533 struct pack_idx_header
*hdr
;
535 uint32_t version
, nr
, i
, *index
;
536 int fd
= git_open_noatime(path
);
541 if (fstat(fd
, &st
)) {
545 idx_size
= xsize_t(st
.st_size
);
546 if (idx_size
< 4 * 256 + 20 + 20) {
548 return error("index file %s is too small", path
);
550 idx_map
= xmmap(NULL
, idx_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
554 if (hdr
->idx_signature
== htonl(PACK_IDX_SIGNATURE
)) {
555 version
= ntohl(hdr
->idx_version
);
556 if (version
< 2 || version
> 2) {
557 munmap(idx_map
, idx_size
);
558 return error("index file %s is version %"PRIu32
559 " and is not supported by this binary"
560 " (try upgrading GIT to a newer version)",
569 index
+= 2; /* skip index header */
570 for (i
= 0; i
< 256; i
++) {
571 uint32_t n
= ntohl(index
[i
]);
573 munmap(idx_map
, idx_size
);
574 return error("non-monotonic index %s", path
);
582 * - 256 index entries 4 bytes each
583 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
584 * - 20-byte SHA1 of the packfile
585 * - 20-byte SHA1 file checksum
587 if (idx_size
!= 4*256 + nr
* 24 + 20 + 20) {
588 munmap(idx_map
, idx_size
);
589 return error("wrong index v1 file size in %s", path
);
591 } else if (version
== 2) {
594 * - 8 bytes of header
595 * - 256 index entries 4 bytes each
596 * - 20-byte sha1 entry * nr
597 * - 4-byte crc entry * nr
598 * - 4-byte offset entry * nr
599 * - 20-byte SHA1 of the packfile
600 * - 20-byte SHA1 file checksum
601 * And after the 4-byte offset table might be a
602 * variable sized table containing 8-byte entries
603 * for offsets larger than 2^31.
605 unsigned long min_size
= 8 + 4*256 + nr
*(20 + 4 + 4) + 20 + 20;
606 unsigned long max_size
= min_size
;
608 max_size
+= (nr
- 1)*8;
609 if (idx_size
< min_size
|| idx_size
> max_size
) {
610 munmap(idx_map
, idx_size
);
611 return error("wrong index v2 file size in %s", path
);
613 if (idx_size
!= min_size
&&
615 * make sure we can deal with large pack offsets.
616 * 31-bit signed offset won't be enough, neither
617 * 32-bit unsigned one will be.
619 (sizeof(off_t
) <= 4)) {
620 munmap(idx_map
, idx_size
);
621 return error("pack too large for current definition of off_t in %s", path
);
625 p
->index_version
= version
;
626 p
->index_data
= idx_map
;
627 p
->index_size
= idx_size
;
632 int open_pack_index(struct packed_git
*p
)
640 idx_name
= xstrdup(p
->pack_name
);
641 strcpy(idx_name
+ strlen(idx_name
) - strlen(".pack"), ".idx");
642 ret
= check_packed_git_idx(idx_name
, p
);
647 static void scan_windows(struct packed_git
*p
,
648 struct packed_git
**lru_p
,
649 struct pack_window
**lru_w
,
650 struct pack_window
**lru_l
)
652 struct pack_window
*w
, *w_l
;
654 for (w_l
= NULL
, w
= p
->windows
; w
; w
= w
->next
) {
656 if (!*lru_w
|| w
->last_used
< (*lru_w
)->last_used
) {
666 static int unuse_one_window(struct packed_git
*current
)
668 struct packed_git
*p
, *lru_p
= NULL
;
669 struct pack_window
*lru_w
= NULL
, *lru_l
= NULL
;
672 scan_windows(current
, &lru_p
, &lru_w
, &lru_l
);
673 for (p
= packed_git
; p
; p
= p
->next
)
674 scan_windows(p
, &lru_p
, &lru_w
, &lru_l
);
676 munmap(lru_w
->base
, lru_w
->len
);
677 pack_mapped
-= lru_w
->len
;
679 lru_l
->next
= lru_w
->next
;
681 lru_p
->windows
= lru_w
->next
;
689 void release_pack_memory(size_t need
)
691 size_t cur
= pack_mapped
;
692 while (need
>= (cur
- pack_mapped
) && unuse_one_window(NULL
))
696 static void mmap_limit_check(size_t length
)
698 static size_t limit
= 0;
700 limit
= git_env_ulong("GIT_MMAP_LIMIT", 0);
705 die("attempting to mmap %"PRIuMAX
" over limit %"PRIuMAX
,
706 (uintmax_t)length
, (uintmax_t)limit
);
709 void *xmmap(void *start
, size_t length
,
710 int prot
, int flags
, int fd
, off_t offset
)
714 mmap_limit_check(length
);
715 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
716 if (ret
== MAP_FAILED
) {
719 release_pack_memory(length
);
720 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
721 if (ret
== MAP_FAILED
)
722 die_errno("Out of memory? mmap failed");
727 void close_pack_windows(struct packed_git
*p
)
730 struct pack_window
*w
= p
->windows
;
733 die("pack '%s' still has open windows to it",
735 munmap(w
->base
, w
->len
);
736 pack_mapped
-= w
->len
;
738 p
->windows
= w
->next
;
744 * The LRU pack is the one with the oldest MRU window, preferring packs
745 * with no used windows, or the oldest mtime if it has no windows allocated.
747 static void find_lru_pack(struct packed_git
*p
, struct packed_git
**lru_p
, struct pack_window
**mru_w
, int *accept_windows_inuse
)
749 struct pack_window
*w
, *this_mru_w
;
750 int has_windows_inuse
= 0;
753 * Reject this pack if it has windows and the previously selected
754 * one does not. If this pack does not have windows, reject
755 * it if the pack file is newer than the previously selected one.
757 if (*lru_p
&& !*mru_w
&& (p
->windows
|| p
->mtime
> (*lru_p
)->mtime
))
760 for (w
= this_mru_w
= p
->windows
; w
; w
= w
->next
) {
762 * Reject this pack if any of its windows are in use,
763 * but the previously selected pack did not have any
764 * inuse windows. Otherwise, record that this pack
765 * has windows in use.
768 if (*accept_windows_inuse
)
769 has_windows_inuse
= 1;
774 if (w
->last_used
> this_mru_w
->last_used
)
778 * Reject this pack if it has windows that have been
779 * used more recently than the previously selected pack.
780 * If the previously selected pack had windows inuse and
781 * we have not encountered a window in this pack that is
782 * inuse, skip this check since we prefer a pack with no
783 * inuse windows to one that has inuse windows.
785 if (*mru_w
&& *accept_windows_inuse
== has_windows_inuse
&&
786 this_mru_w
->last_used
> (*mru_w
)->last_used
)
795 *accept_windows_inuse
= has_windows_inuse
;
798 static int close_one_pack(void)
800 struct packed_git
*p
, *lru_p
= NULL
;
801 struct pack_window
*mru_w
= NULL
;
802 int accept_windows_inuse
= 1;
804 for (p
= packed_git
; p
; p
= p
->next
) {
805 if (p
->pack_fd
== -1)
807 find_lru_pack(p
, &lru_p
, &mru_w
, &accept_windows_inuse
);
811 close(lru_p
->pack_fd
);
820 void unuse_pack(struct pack_window
**w_cursor
)
822 struct pack_window
*w
= *w_cursor
;
829 void close_pack_index(struct packed_git
*p
)
832 munmap((void *)p
->index_data
, p
->index_size
);
833 p
->index_data
= NULL
;
838 * This is used by git-repack in case a newly created pack happens to
839 * contain the same set of objects as an existing one. In that case
840 * the resulting file might be different even if its name would be the
841 * same. It is best to close any reference to the old pack before it is
842 * replaced on disk. Of course no index pointers or windows for given pack
843 * must subsist at this point. If ever objects from this pack are requested
844 * again, the new version of the pack will be reinitialized through
845 * reprepare_packed_git().
847 void free_pack_by_name(const char *pack_name
)
849 struct packed_git
*p
, **pp
= &packed_git
;
853 if (strcmp(pack_name
, p
->pack_name
) == 0) {
854 clear_delta_base_cache();
855 close_pack_windows(p
);
856 if (p
->pack_fd
!= -1) {
861 free(p
->bad_object_sha1
);
863 if (last_found_pack
== p
)
864 last_found_pack
= NULL
;
872 static unsigned int get_max_fd_limit(void)
878 if (!getrlimit(RLIMIT_NOFILE
, &lim
))
885 long open_max
= sysconf(_SC_OPEN_MAX
);
889 * Otherwise, we got -1 for one of the two
892 * (1) sysconf() did not understand _SC_OPEN_MAX
893 * and signaled an error with -1; or
894 * (2) sysconf() said there is no limit.
896 * We _could_ clear errno before calling sysconf() to
897 * tell these two cases apart and return a huge number
898 * in the latter case to let the caller cap it to a
899 * value that is not so selfish, but letting the
900 * fallback OPEN_MAX codepath take care of these cases
909 return 1; /* see the caller ;-) */
914 * Do not call this directly as this leaks p->pack_fd on error return;
915 * call open_packed_git() instead.
917 static int open_packed_git_1(struct packed_git
*p
)
920 struct pack_header hdr
;
921 unsigned char sha1
[20];
922 unsigned char *idx_sha1
;
925 if (!p
->index_data
&& open_pack_index(p
))
926 return error("packfile %s index unavailable", p
->pack_name
);
929 unsigned int max_fds
= get_max_fd_limit();
931 /* Save 3 for stdin/stdout/stderr, 22 for work */
933 pack_max_fds
= max_fds
- 25;
938 while (pack_max_fds
<= pack_open_fds
&& close_one_pack())
941 p
->pack_fd
= git_open_noatime(p
->pack_name
);
942 if (p
->pack_fd
< 0 || fstat(p
->pack_fd
, &st
))
946 /* If we created the struct before we had the pack we lack size. */
948 if (!S_ISREG(st
.st_mode
))
949 return error("packfile %s not a regular file", p
->pack_name
);
950 p
->pack_size
= st
.st_size
;
951 } else if (p
->pack_size
!= st
.st_size
)
952 return error("packfile %s size changed", p
->pack_name
);
954 /* We leave these file descriptors open with sliding mmap;
955 * there is no point keeping them open across exec(), though.
957 fd_flag
= fcntl(p
->pack_fd
, F_GETFD
, 0);
959 return error("cannot determine file descriptor flags");
960 fd_flag
|= FD_CLOEXEC
;
961 if (fcntl(p
->pack_fd
, F_SETFD
, fd_flag
) == -1)
962 return error("cannot set FD_CLOEXEC");
964 /* Verify we recognize this pack file format. */
965 if (read_in_full(p
->pack_fd
, &hdr
, sizeof(hdr
)) != sizeof(hdr
))
966 return error("file %s is far too short to be a packfile", p
->pack_name
);
967 if (hdr
.hdr_signature
!= htonl(PACK_SIGNATURE
))
968 return error("file %s is not a GIT packfile", p
->pack_name
);
969 if (!pack_version_ok(hdr
.hdr_version
))
970 return error("packfile %s is version %"PRIu32
" and not"
971 " supported (try upgrading GIT to a newer version)",
972 p
->pack_name
, ntohl(hdr
.hdr_version
));
974 /* Verify the pack matches its index. */
975 if (p
->num_objects
!= ntohl(hdr
.hdr_entries
))
976 return error("packfile %s claims to have %"PRIu32
" objects"
977 " while index indicates %"PRIu32
" objects",
978 p
->pack_name
, ntohl(hdr
.hdr_entries
),
980 if (lseek(p
->pack_fd
, p
->pack_size
- sizeof(sha1
), SEEK_SET
) == -1)
981 return error("end of packfile %s is unavailable", p
->pack_name
);
982 if (read_in_full(p
->pack_fd
, sha1
, sizeof(sha1
)) != sizeof(sha1
))
983 return error("packfile %s signature is unavailable", p
->pack_name
);
984 idx_sha1
= ((unsigned char *)p
->index_data
) + p
->index_size
- 40;
985 if (hashcmp(sha1
, idx_sha1
))
986 return error("packfile %s does not match index", p
->pack_name
);
990 static int open_packed_git(struct packed_git
*p
)
992 if (!open_packed_git_1(p
))
994 if (p
->pack_fd
!= -1) {
1002 static int in_window(struct pack_window
*win
, off_t offset
)
1004 /* We must promise at least 20 bytes (one hash) after the
1005 * offset is available from this window, otherwise the offset
1006 * is not actually in this window and a different window (which
1007 * has that one hash excess) must be used. This is to support
1008 * the object header and delta base parsing routines below.
1010 off_t win_off
= win
->offset
;
1011 return win_off
<= offset
1012 && (offset
+ 20) <= (win_off
+ win
->len
);
1015 unsigned char *use_pack(struct packed_git
*p
,
1016 struct pack_window
**w_cursor
,
1018 unsigned long *left
)
1020 struct pack_window
*win
= *w_cursor
;
1022 /* Since packfiles end in a hash of their content and it's
1023 * pointless to ask for an offset into the middle of that
1024 * hash, and the in_window function above wouldn't match
1025 * don't allow an offset too close to the end of the file.
1027 if (!p
->pack_size
&& p
->pack_fd
== -1 && open_packed_git(p
))
1028 die("packfile %s cannot be accessed", p
->pack_name
);
1029 if (offset
> (p
->pack_size
- 20))
1030 die("offset beyond end of packfile (truncated pack?)");
1032 if (!win
|| !in_window(win
, offset
)) {
1035 for (win
= p
->windows
; win
; win
= win
->next
) {
1036 if (in_window(win
, offset
))
1040 size_t window_align
= packed_git_window_size
/ 2;
1043 if (p
->pack_fd
== -1 && open_packed_git(p
))
1044 die("packfile %s cannot be accessed", p
->pack_name
);
1046 win
= xcalloc(1, sizeof(*win
));
1047 win
->offset
= (offset
/ window_align
) * window_align
;
1048 len
= p
->pack_size
- win
->offset
;
1049 if (len
> packed_git_window_size
)
1050 len
= packed_git_window_size
;
1051 win
->len
= (size_t)len
;
1052 pack_mapped
+= win
->len
;
1053 while (packed_git_limit
< pack_mapped
1054 && unuse_one_window(p
))
1056 win
->base
= xmmap(NULL
, win
->len
,
1057 PROT_READ
, MAP_PRIVATE
,
1058 p
->pack_fd
, win
->offset
);
1059 if (win
->base
== MAP_FAILED
)
1060 die("packfile %s cannot be mapped: %s",
1063 if (!win
->offset
&& win
->len
== p
->pack_size
1064 && !p
->do_not_close
) {
1070 pack_open_windows
++;
1071 if (pack_mapped
> peak_pack_mapped
)
1072 peak_pack_mapped
= pack_mapped
;
1073 if (pack_open_windows
> peak_pack_open_windows
)
1074 peak_pack_open_windows
= pack_open_windows
;
1075 win
->next
= p
->windows
;
1079 if (win
!= *w_cursor
) {
1080 win
->last_used
= pack_used_ctr
++;
1084 offset
-= win
->offset
;
1086 *left
= win
->len
- xsize_t(offset
);
1087 return win
->base
+ offset
;
1090 static struct packed_git
*alloc_packed_git(int extra
)
1092 struct packed_git
*p
= xmalloc(sizeof(*p
) + extra
);
1093 memset(p
, 0, sizeof(*p
));
1098 static void try_to_free_pack_memory(size_t size
)
1100 release_pack_memory(size
);
1103 struct packed_git
*add_packed_git(const char *path
, int path_len
, int local
)
1105 static int have_set_try_to_free_routine
;
1107 struct packed_git
*p
= alloc_packed_git(path_len
+ 2);
1109 if (!have_set_try_to_free_routine
) {
1110 have_set_try_to_free_routine
= 1;
1111 set_try_to_free_routine(try_to_free_pack_memory
);
1115 * Make sure a corresponding .pack file exists and that
1116 * the index looks sane.
1118 path_len
-= strlen(".idx");
1123 memcpy(p
->pack_name
, path
, path_len
);
1125 strcpy(p
->pack_name
+ path_len
, ".keep");
1126 if (!access(p
->pack_name
, F_OK
))
1129 strcpy(p
->pack_name
+ path_len
, ".pack");
1130 if (stat(p
->pack_name
, &st
) || !S_ISREG(st
.st_mode
)) {
1135 /* ok, it looks sane as far as we can check without
1136 * actually mapping the pack file.
1138 p
->pack_size
= st
.st_size
;
1139 p
->pack_local
= local
;
1140 p
->mtime
= st
.st_mtime
;
1141 if (path_len
< 40 || get_sha1_hex(path
+ path_len
- 40, p
->sha1
))
1146 struct packed_git
*parse_pack_index(unsigned char *sha1
, const char *idx_path
)
1148 const char *path
= sha1_pack_name(sha1
);
1149 struct packed_git
*p
= alloc_packed_git(strlen(path
) + 1);
1151 strcpy(p
->pack_name
, path
);
1152 hashcpy(p
->sha1
, sha1
);
1153 if (check_packed_git_idx(idx_path
, p
)) {
1161 void install_packed_git(struct packed_git
*pack
)
1163 if (pack
->pack_fd
!= -1)
1166 pack
->next
= packed_git
;
1170 void (*report_garbage
)(const char *desc
, const char *path
);
1172 static void report_helper(const struct string_list
*list
,
1173 int seen_bits
, int first
, int last
)
1176 switch (seen_bits
) {
1178 msg
= "no corresponding .idx or .pack";
1181 msg
= "no corresponding .idx";
1184 msg
= "no corresponding .pack";
1189 for (; first
< last
; first
++)
1190 report_garbage(msg
, list
->items
[first
].string
);
1193 static void report_pack_garbage(struct string_list
*list
)
1195 int i
, baselen
= -1, first
= 0, seen_bits
= 0;
1197 if (!report_garbage
)
1200 sort_string_list(list
);
1202 for (i
= 0; i
< list
->nr
; i
++) {
1203 const char *path
= list
->items
[i
].string
;
1204 if (baselen
!= -1 &&
1205 strncmp(path
, list
->items
[first
].string
, baselen
)) {
1206 report_helper(list
, seen_bits
, first
, i
);
1210 if (baselen
== -1) {
1211 const char *dot
= strrchr(path
, '.');
1213 report_garbage("garbage found", path
);
1216 baselen
= dot
- path
+ 1;
1219 if (!strcmp(path
+ baselen
, "pack"))
1221 else if (!strcmp(path
+ baselen
, "idx"))
1224 report_helper(list
, seen_bits
, first
, list
->nr
);
1227 static void prepare_packed_git_one(char *objdir
, int local
)
1229 struct strbuf path
= STRBUF_INIT
;
1233 struct string_list garbage
= STRING_LIST_INIT_DUP
;
1235 strbuf_addstr(&path
, objdir
);
1236 strbuf_addstr(&path
, "/pack");
1237 dir
= opendir(path
.buf
);
1239 if (errno
!= ENOENT
)
1240 error("unable to open object pack directory: %s: %s",
1241 path
.buf
, strerror(errno
));
1242 strbuf_release(&path
);
1245 strbuf_addch(&path
, '/');
1246 dirnamelen
= path
.len
;
1247 while ((de
= readdir(dir
)) != NULL
) {
1248 struct packed_git
*p
;
1251 if (is_dot_or_dotdot(de
->d_name
))
1254 strbuf_setlen(&path
, dirnamelen
);
1255 strbuf_addstr(&path
, de
->d_name
);
1257 base_len
= path
.len
;
1258 if (strip_suffix_mem(path
.buf
, &base_len
, ".idx")) {
1259 /* Don't reopen a pack we already have. */
1260 for (p
= packed_git
; p
; p
= p
->next
) {
1262 if (strip_suffix(p
->pack_name
, ".pack", &len
) &&
1264 !memcmp(p
->pack_name
, path
.buf
, len
))
1269 * See if it really is a valid .idx file with
1270 * corresponding .pack file that we can map.
1272 (p
= add_packed_git(path
.buf
, path
.len
, local
)) != NULL
)
1273 install_packed_git(p
);
1276 if (!report_garbage
)
1279 if (ends_with(de
->d_name
, ".idx") ||
1280 ends_with(de
->d_name
, ".pack") ||
1281 ends_with(de
->d_name
, ".bitmap") ||
1282 ends_with(de
->d_name
, ".keep"))
1283 string_list_append(&garbage
, path
.buf
);
1285 report_garbage("garbage found", path
.buf
);
1288 report_pack_garbage(&garbage
);
1289 string_list_clear(&garbage
, 0);
1290 strbuf_release(&path
);
1293 static int sort_pack(const void *a_
, const void *b_
)
1295 struct packed_git
*a
= *((struct packed_git
**)a_
);
1296 struct packed_git
*b
= *((struct packed_git
**)b_
);
1300 * Local packs tend to contain objects specific to our
1301 * variant of the project than remote ones. In addition,
1302 * remote ones could be on a network mounted filesystem.
1303 * Favor local ones for these reasons.
1305 st
= a
->pack_local
- b
->pack_local
;
1310 * Younger packs tend to contain more recent objects,
1311 * and more recent objects tend to get accessed more
1314 if (a
->mtime
< b
->mtime
)
1316 else if (a
->mtime
== b
->mtime
)
1321 static void rearrange_packed_git(void)
1323 struct packed_git
**ary
, *p
;
1326 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
1331 /* prepare an array of packed_git for easier sorting */
1332 ary
= xcalloc(n
, sizeof(struct packed_git
*));
1333 for (n
= 0, p
= packed_git
; p
; p
= p
->next
)
1336 qsort(ary
, n
, sizeof(struct packed_git
*), sort_pack
);
1338 /* link them back again */
1339 for (i
= 0; i
< n
- 1; i
++)
1340 ary
[i
]->next
= ary
[i
+ 1];
1341 ary
[n
- 1]->next
= NULL
;
1342 packed_git
= ary
[0];
1347 static int prepare_packed_git_run_once
= 0;
1348 void prepare_packed_git(void)
1350 struct alternate_object_database
*alt
;
1352 if (prepare_packed_git_run_once
)
1354 prepare_packed_git_one(get_object_directory(), 1);
1356 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1358 prepare_packed_git_one(alt
->base
, 0);
1359 alt
->name
[-1] = '/';
1361 rearrange_packed_git();
1362 prepare_packed_git_run_once
= 1;
1365 void reprepare_packed_git(void)
1367 prepare_packed_git_run_once
= 0;
1368 prepare_packed_git();
1371 static void mark_bad_packed_object(struct packed_git
*p
,
1372 const unsigned char *sha1
)
1375 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1376 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1378 p
->bad_object_sha1
= xrealloc(p
->bad_object_sha1
, 20 * (p
->num_bad_objects
+ 1));
1379 hashcpy(p
->bad_object_sha1
+ 20 * p
->num_bad_objects
, sha1
);
1380 p
->num_bad_objects
++;
1383 static const struct packed_git
*has_packed_and_bad(const unsigned char *sha1
)
1385 struct packed_git
*p
;
1388 for (p
= packed_git
; p
; p
= p
->next
)
1389 for (i
= 0; i
< p
->num_bad_objects
; i
++)
1390 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
1396 * With an in-core object data in "map", rehash it to make sure the
1397 * object name actually matches "sha1" to detect object corruption.
1398 * With "map" == NULL, try reading the object named with "sha1" using
1399 * the streaming interface and rehash it to do the same.
1401 int check_sha1_signature(const unsigned char *sha1
, void *map
,
1402 unsigned long size
, const char *type
)
1404 unsigned char real_sha1
[20];
1405 enum object_type obj_type
;
1406 struct git_istream
*st
;
1412 hash_sha1_file(map
, size
, type
, real_sha1
);
1413 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1416 st
= open_istream(sha1
, &obj_type
, &size
, NULL
);
1420 /* Generate the header */
1421 hdrlen
= sprintf(hdr
, "%s %lu", typename(obj_type
), size
) + 1;
1425 git_SHA1_Update(&c
, hdr
, hdrlen
);
1427 char buf
[1024 * 16];
1428 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
1436 git_SHA1_Update(&c
, buf
, readlen
);
1438 git_SHA1_Final(real_sha1
, &c
);
1440 return hashcmp(sha1
, real_sha1
) ? -1 : 0;
1443 int git_open_noatime(const char *name
)
1445 static int sha1_file_open_flag
= O_NOATIME
;
1448 int fd
= open(name
, O_RDONLY
| sha1_file_open_flag
);
1452 /* Might the failure be due to O_NOATIME? */
1453 if (errno
!= ENOENT
&& sha1_file_open_flag
) {
1454 sha1_file_open_flag
= 0;
1462 static int stat_sha1_file(const unsigned char *sha1
, struct stat
*st
)
1464 struct alternate_object_database
*alt
;
1466 if (!lstat(sha1_file_name(sha1
), st
))
1471 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1472 fill_sha1_path(alt
->name
, sha1
);
1473 if (!lstat(alt
->base
, st
))
1480 static int open_sha1_file(const unsigned char *sha1
)
1483 struct alternate_object_database
*alt
;
1484 int most_interesting_errno
;
1486 fd
= git_open_noatime(sha1_file_name(sha1
));
1489 most_interesting_errno
= errno
;
1492 for (alt
= alt_odb_list
; alt
; alt
= alt
->next
) {
1493 fill_sha1_path(alt
->name
, sha1
);
1494 fd
= git_open_noatime(alt
->base
);
1497 if (most_interesting_errno
== ENOENT
)
1498 most_interesting_errno
= errno
;
1500 errno
= most_interesting_errno
;
1504 void *map_sha1_file(const unsigned char *sha1
, unsigned long *size
)
1509 fd
= open_sha1_file(sha1
);
1514 if (!fstat(fd
, &st
)) {
1515 *size
= xsize_t(st
.st_size
);
1517 /* mmap() is forbidden on empty files */
1518 error("object file %s is empty", sha1_file_name(sha1
));
1521 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1528 unsigned long unpack_object_header_buffer(const unsigned char *buf
,
1529 unsigned long len
, enum object_type
*type
, unsigned long *sizep
)
1532 unsigned long size
, c
;
1533 unsigned long used
= 0;
1536 *type
= (c
>> 4) & 7;
1540 if (len
<= used
|| bitsizeof(long) <= shift
) {
1541 error("bad object header");
1546 size
+= (c
& 0x7f) << shift
;
1553 int unpack_sha1_header(git_zstream
*stream
, unsigned char *map
, unsigned long mapsize
, void *buffer
, unsigned long bufsiz
)
1555 /* Get the data stream */
1556 memset(stream
, 0, sizeof(*stream
));
1557 stream
->next_in
= map
;
1558 stream
->avail_in
= mapsize
;
1559 stream
->next_out
= buffer
;
1560 stream
->avail_out
= bufsiz
;
1562 git_inflate_init(stream
);
1563 return git_inflate(stream
, 0);
1566 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1568 int bytes
= strlen(buffer
) + 1;
1569 unsigned char *buf
= xmallocz(size
);
1573 n
= stream
->total_out
- bytes
;
1576 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1578 if (bytes
<= size
) {
1580 * The above condition must be (bytes <= size), not
1581 * (bytes < size). In other words, even though we
1582 * expect no more output and set avail_out to zero,
1583 * the input zlib stream may have bytes that express
1584 * "this concludes the stream", and we *do* want to
1587 * Otherwise we would not be able to test that we
1588 * consumed all the input to reach the expected size;
1589 * we also want to check that zlib tells us that all
1590 * went well with status == Z_STREAM_END at the end.
1592 stream
->next_out
= buf
+ bytes
;
1593 stream
->avail_out
= size
- bytes
;
1594 while (status
== Z_OK
)
1595 status
= git_inflate(stream
, Z_FINISH
);
1597 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1598 git_inflate_end(stream
);
1603 error("corrupt loose object '%s'", sha1_to_hex(sha1
));
1604 else if (stream
->avail_in
)
1605 error("garbage at end of loose object '%s'",
1612 * We used to just use "sscanf()", but that's actually way
1613 * too permissive for what we want to check. So do an anal
1614 * object header parse by hand.
1616 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1623 * The type can be at most ten bytes (including the
1624 * terminating '\0' that we add), and is followed by
1633 if (i
>= sizeof(type
))
1639 * The length must follow immediately, and be in canonical
1640 * decimal format (ie "010" is not valid).
1642 size
= *hdr
++ - '0';
1647 unsigned long c
= *hdr
- '0';
1651 size
= size
* 10 + c
;
1657 * The length must be followed by a zero byte
1659 return *hdr
? -1 : type_from_string(type
);
1662 static void *unpack_sha1_file(void *map
, unsigned long mapsize
, enum object_type
*type
, unsigned long *size
, const unsigned char *sha1
)
1668 ret
= unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
));
1669 if (ret
< Z_OK
|| (*type
= parse_sha1_header(hdr
, size
)) < 0)
1672 return unpack_sha1_rest(&stream
, hdr
, *size
, sha1
);
1675 unsigned long get_size_from_delta(struct packed_git
*p
,
1676 struct pack_window
**w_curs
,
1679 const unsigned char *data
;
1680 unsigned char delta_head
[20], *in
;
1684 memset(&stream
, 0, sizeof(stream
));
1685 stream
.next_out
= delta_head
;
1686 stream
.avail_out
= sizeof(delta_head
);
1688 git_inflate_init(&stream
);
1690 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1691 stream
.next_in
= in
;
1692 st
= git_inflate(&stream
, Z_FINISH
);
1693 curpos
+= stream
.next_in
- in
;
1694 } while ((st
== Z_OK
|| st
== Z_BUF_ERROR
) &&
1695 stream
.total_out
< sizeof(delta_head
));
1696 git_inflate_end(&stream
);
1697 if ((st
!= Z_STREAM_END
) && stream
.total_out
!= sizeof(delta_head
)) {
1698 error("delta data unpack-initial failed");
1702 /* Examine the initial part of the delta to figure out
1707 /* ignore base size */
1708 get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1710 /* Read the result size */
1711 return get_delta_hdr_size(&data
, delta_head
+sizeof(delta_head
));
1714 static off_t
get_delta_base(struct packed_git
*p
,
1715 struct pack_window
**w_curs
,
1717 enum object_type type
,
1718 off_t delta_obj_offset
)
1720 unsigned char *base_info
= use_pack(p
, w_curs
, *curpos
, NULL
);
1723 /* use_pack() assured us we have [base_info, base_info + 20)
1724 * as a range that we can look at without walking off the
1725 * end of the mapped window. Its actually the hash size
1726 * that is assured. An OFS_DELTA longer than the hash size
1727 * is stupid, as then a REF_DELTA would be smaller to store.
1729 if (type
== OBJ_OFS_DELTA
) {
1731 unsigned char c
= base_info
[used
++];
1732 base_offset
= c
& 127;
1735 if (!base_offset
|| MSB(base_offset
, 7))
1736 return 0; /* overflow */
1737 c
= base_info
[used
++];
1738 base_offset
= (base_offset
<< 7) + (c
& 127);
1740 base_offset
= delta_obj_offset
- base_offset
;
1741 if (base_offset
<= 0 || base_offset
>= delta_obj_offset
)
1742 return 0; /* out of bound */
1744 } else if (type
== OBJ_REF_DELTA
) {
1745 /* The base entry _must_ be in the same pack */
1746 base_offset
= find_pack_entry_one(base_info
, p
);
1749 die("I am totally screwed");
1754 * Like get_delta_base above, but we return the sha1 instead of the pack
1755 * offset. This means it is cheaper for REF deltas (we do not have to do
1756 * the final object lookup), but more expensive for OFS deltas (we
1757 * have to load the revidx to convert the offset back into a sha1).
1759 static const unsigned char *get_delta_base_sha1(struct packed_git
*p
,
1760 struct pack_window
**w_curs
,
1762 enum object_type type
,
1763 off_t delta_obj_offset
)
1765 if (type
== OBJ_REF_DELTA
) {
1766 unsigned char *base
= use_pack(p
, w_curs
, curpos
, NULL
);
1768 } else if (type
== OBJ_OFS_DELTA
) {
1769 struct revindex_entry
*revidx
;
1770 off_t base_offset
= get_delta_base(p
, w_curs
, &curpos
,
1771 type
, delta_obj_offset
);
1776 revidx
= find_pack_revindex(p
, base_offset
);
1780 return nth_packed_object_sha1(p
, revidx
->nr
);
1785 int unpack_object_header(struct packed_git
*p
,
1786 struct pack_window
**w_curs
,
1788 unsigned long *sizep
)
1790 unsigned char *base
;
1793 enum object_type type
;
1795 /* use_pack() assures us we have [base, base + 20) available
1796 * as a range that we can look at. (Its actually the hash
1797 * size that is assured.) With our object header encoding
1798 * the maximum deflated object size is 2^137, which is just
1799 * insane, so we know won't exceed what we have been given.
1801 base
= use_pack(p
, w_curs
, *curpos
, &left
);
1802 used
= unpack_object_header_buffer(base
, left
, &type
, sizep
);
1811 static int retry_bad_packed_offset(struct packed_git
*p
, off_t obj_offset
)
1814 struct revindex_entry
*revidx
;
1815 const unsigned char *sha1
;
1816 revidx
= find_pack_revindex(p
, obj_offset
);
1819 sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
1820 mark_bad_packed_object(p
, sha1
);
1821 type
= sha1_object_info(sha1
, NULL
);
1822 if (type
<= OBJ_NONE
)
1827 #define POI_STACK_PREALLOC 64
1829 static enum object_type
packed_to_object_type(struct packed_git
*p
,
1831 enum object_type type
,
1832 struct pack_window
**w_curs
,
1835 off_t small_poi_stack
[POI_STACK_PREALLOC
];
1836 off_t
*poi_stack
= small_poi_stack
;
1837 int poi_stack_nr
= 0, poi_stack_alloc
= POI_STACK_PREALLOC
;
1839 while (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1842 /* Push the object we're going to leave behind */
1843 if (poi_stack_nr
>= poi_stack_alloc
&& poi_stack
== small_poi_stack
) {
1844 poi_stack_alloc
= alloc_nr(poi_stack_nr
);
1845 poi_stack
= xmalloc(sizeof(off_t
)*poi_stack_alloc
);
1846 memcpy(poi_stack
, small_poi_stack
, sizeof(off_t
)*poi_stack_nr
);
1848 ALLOC_GROW(poi_stack
, poi_stack_nr
+1, poi_stack_alloc
);
1850 poi_stack
[poi_stack_nr
++] = obj_offset
;
1851 /* If parsing the base offset fails, just unwind */
1852 base_offset
= get_delta_base(p
, w_curs
, &curpos
, type
, obj_offset
);
1855 curpos
= obj_offset
= base_offset
;
1856 type
= unpack_object_header(p
, w_curs
, &curpos
, &size
);
1857 if (type
<= OBJ_NONE
) {
1858 /* If getting the base itself fails, we first
1859 * retry the base, otherwise unwind */
1860 type
= retry_bad_packed_offset(p
, base_offset
);
1861 if (type
> OBJ_NONE
)
1875 error("unknown object type %i at offset %"PRIuMAX
" in %s",
1876 type
, (uintmax_t)obj_offset
, p
->pack_name
);
1881 if (poi_stack
!= small_poi_stack
)
1886 while (poi_stack_nr
) {
1887 obj_offset
= poi_stack
[--poi_stack_nr
];
1888 type
= retry_bad_packed_offset(p
, obj_offset
);
1889 if (type
> OBJ_NONE
)
1896 static int packed_object_info(struct packed_git
*p
, off_t obj_offset
,
1897 struct object_info
*oi
)
1899 struct pack_window
*w_curs
= NULL
;
1901 off_t curpos
= obj_offset
;
1902 enum object_type type
;
1905 * We always get the representation type, but only convert it to
1906 * a "real" type later if the caller is interested.
1908 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
1911 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1912 off_t tmp_pos
= curpos
;
1913 off_t base_offset
= get_delta_base(p
, &w_curs
, &tmp_pos
,
1919 *oi
->sizep
= get_size_from_delta(p
, &w_curs
, tmp_pos
);
1920 if (*oi
->sizep
== 0) {
1929 if (oi
->disk_sizep
) {
1930 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
1931 *oi
->disk_sizep
= revidx
[1].offset
- obj_offset
;
1935 *oi
->typep
= packed_to_object_type(p
, obj_offset
, type
, &w_curs
, curpos
);
1936 if (*oi
->typep
< 0) {
1942 if (oi
->delta_base_sha1
) {
1943 if (type
== OBJ_OFS_DELTA
|| type
== OBJ_REF_DELTA
) {
1944 const unsigned char *base
;
1946 base
= get_delta_base_sha1(p
, &w_curs
, curpos
,
1953 hashcpy(oi
->delta_base_sha1
, base
);
1955 hashclr(oi
->delta_base_sha1
);
1959 unuse_pack(&w_curs
);
1963 static void *unpack_compressed_entry(struct packed_git
*p
,
1964 struct pack_window
**w_curs
,
1970 unsigned char *buffer
, *in
;
1972 buffer
= xmallocz_gently(size
);
1975 memset(&stream
, 0, sizeof(stream
));
1976 stream
.next_out
= buffer
;
1977 stream
.avail_out
= size
+ 1;
1979 git_inflate_init(&stream
);
1981 in
= use_pack(p
, w_curs
, curpos
, &stream
.avail_in
);
1982 stream
.next_in
= in
;
1983 st
= git_inflate(&stream
, Z_FINISH
);
1984 if (!stream
.avail_out
)
1985 break; /* the payload is larger than it should be */
1986 curpos
+= stream
.next_in
- in
;
1987 } while (st
== Z_OK
|| st
== Z_BUF_ERROR
);
1988 git_inflate_end(&stream
);
1989 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= size
) {
1997 #define MAX_DELTA_CACHE (256)
1999 static size_t delta_base_cached
;
2001 static struct delta_base_cache_lru_list
{
2002 struct delta_base_cache_lru_list
*prev
;
2003 struct delta_base_cache_lru_list
*next
;
2004 } delta_base_cache_lru
= { &delta_base_cache_lru
, &delta_base_cache_lru
};
2006 static struct delta_base_cache_entry
{
2007 struct delta_base_cache_lru_list lru
;
2009 struct packed_git
*p
;
2012 enum object_type type
;
2013 } delta_base_cache
[MAX_DELTA_CACHE
];
2015 static unsigned long pack_entry_hash(struct packed_git
*p
, off_t base_offset
)
2019 hash
= (unsigned long)p
+ (unsigned long)base_offset
;
2020 hash
+= (hash
>> 8) + (hash
>> 16);
2021 return hash
% MAX_DELTA_CACHE
;
2024 static struct delta_base_cache_entry
*
2025 get_delta_base_cache_entry(struct packed_git
*p
, off_t base_offset
)
2027 unsigned long hash
= pack_entry_hash(p
, base_offset
);
2028 return delta_base_cache
+ hash
;
2031 static int eq_delta_base_cache_entry(struct delta_base_cache_entry
*ent
,
2032 struct packed_git
*p
, off_t base_offset
)
2034 return (ent
->data
&& ent
->p
== p
&& ent
->base_offset
== base_offset
);
2037 static int in_delta_base_cache(struct packed_git
*p
, off_t base_offset
)
2039 struct delta_base_cache_entry
*ent
;
2040 ent
= get_delta_base_cache_entry(p
, base_offset
);
2041 return eq_delta_base_cache_entry(ent
, p
, base_offset
);
2044 static void clear_delta_base_cache_entry(struct delta_base_cache_entry
*ent
)
2047 ent
->lru
.next
->prev
= ent
->lru
.prev
;
2048 ent
->lru
.prev
->next
= ent
->lru
.next
;
2049 delta_base_cached
-= ent
->size
;
2052 static void *cache_or_unpack_entry(struct packed_git
*p
, off_t base_offset
,
2053 unsigned long *base_size
, enum object_type
*type
, int keep_cache
)
2055 struct delta_base_cache_entry
*ent
;
2058 ent
= get_delta_base_cache_entry(p
, base_offset
);
2060 if (!eq_delta_base_cache_entry(ent
, p
, base_offset
))
2061 return unpack_entry(p
, base_offset
, type
, base_size
);
2066 clear_delta_base_cache_entry(ent
);
2068 ret
= xmemdupz(ent
->data
, ent
->size
);
2070 *base_size
= ent
->size
;
2074 static inline void release_delta_base_cache(struct delta_base_cache_entry
*ent
)
2079 ent
->lru
.next
->prev
= ent
->lru
.prev
;
2080 ent
->lru
.prev
->next
= ent
->lru
.next
;
2081 delta_base_cached
-= ent
->size
;
2085 void clear_delta_base_cache(void)
2088 for (p
= 0; p
< MAX_DELTA_CACHE
; p
++)
2089 release_delta_base_cache(&delta_base_cache
[p
]);
2092 static void add_delta_base_cache(struct packed_git
*p
, off_t base_offset
,
2093 void *base
, unsigned long base_size
, enum object_type type
)
2095 unsigned long hash
= pack_entry_hash(p
, base_offset
);
2096 struct delta_base_cache_entry
*ent
= delta_base_cache
+ hash
;
2097 struct delta_base_cache_lru_list
*lru
;
2099 release_delta_base_cache(ent
);
2100 delta_base_cached
+= base_size
;
2102 for (lru
= delta_base_cache_lru
.next
;
2103 delta_base_cached
> delta_base_cache_limit
2104 && lru
!= &delta_base_cache_lru
;
2106 struct delta_base_cache_entry
*f
= (void *)lru
;
2107 if (f
->type
== OBJ_BLOB
)
2108 release_delta_base_cache(f
);
2110 for (lru
= delta_base_cache_lru
.next
;
2111 delta_base_cached
> delta_base_cache_limit
2112 && lru
!= &delta_base_cache_lru
;
2114 struct delta_base_cache_entry
*f
= (void *)lru
;
2115 release_delta_base_cache(f
);
2119 ent
->base_offset
= base_offset
;
2122 ent
->size
= base_size
;
2123 ent
->lru
.next
= &delta_base_cache_lru
;
2124 ent
->lru
.prev
= delta_base_cache_lru
.prev
;
2125 delta_base_cache_lru
.prev
->next
= &ent
->lru
;
2126 delta_base_cache_lru
.prev
= &ent
->lru
;
2129 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2130 unsigned long *size
);
2132 static void write_pack_access_log(struct packed_git
*p
, off_t obj_offset
)
2134 static struct trace_key pack_access
= TRACE_KEY_INIT(PACK_ACCESS
);
2135 trace_printf_key(&pack_access
, "%s %"PRIuMAX
"\n",
2136 p
->pack_name
, (uintmax_t)obj_offset
);
2139 int do_check_packed_object_crc
;
2141 #define UNPACK_ENTRY_STACK_PREALLOC 64
2142 struct unpack_entry_stack_ent
{
2148 void *unpack_entry(struct packed_git
*p
, off_t obj_offset
,
2149 enum object_type
*final_type
, unsigned long *final_size
)
2151 struct pack_window
*w_curs
= NULL
;
2152 off_t curpos
= obj_offset
;
2155 enum object_type type
;
2156 struct unpack_entry_stack_ent small_delta_stack
[UNPACK_ENTRY_STACK_PREALLOC
];
2157 struct unpack_entry_stack_ent
*delta_stack
= small_delta_stack
;
2158 int delta_stack_nr
= 0, delta_stack_alloc
= UNPACK_ENTRY_STACK_PREALLOC
;
2159 int base_from_cache
= 0;
2161 write_pack_access_log(p
, obj_offset
);
2163 /* PHASE 1: drill down to the innermost base object */
2167 struct delta_base_cache_entry
*ent
;
2169 ent
= get_delta_base_cache_entry(p
, curpos
);
2170 if (eq_delta_base_cache_entry(ent
, p
, curpos
)) {
2174 clear_delta_base_cache_entry(ent
);
2175 base_from_cache
= 1;
2179 if (do_check_packed_object_crc
&& p
->index_version
> 1) {
2180 struct revindex_entry
*revidx
= find_pack_revindex(p
, obj_offset
);
2181 unsigned long len
= revidx
[1].offset
- obj_offset
;
2182 if (check_pack_crc(p
, &w_curs
, obj_offset
, len
, revidx
->nr
)) {
2183 const unsigned char *sha1
=
2184 nth_packed_object_sha1(p
, revidx
->nr
);
2185 error("bad packed object CRC for %s",
2187 mark_bad_packed_object(p
, sha1
);
2188 unuse_pack(&w_curs
);
2193 type
= unpack_object_header(p
, &w_curs
, &curpos
, &size
);
2194 if (type
!= OBJ_OFS_DELTA
&& type
!= OBJ_REF_DELTA
)
2197 base_offset
= get_delta_base(p
, &w_curs
, &curpos
, type
, obj_offset
);
2199 error("failed to validate delta base reference "
2200 "at offset %"PRIuMAX
" from %s",
2201 (uintmax_t)curpos
, p
->pack_name
);
2202 /* bail to phase 2, in hopes of recovery */
2207 /* push object, proceed to base */
2208 if (delta_stack_nr
>= delta_stack_alloc
2209 && delta_stack
== small_delta_stack
) {
2210 delta_stack_alloc
= alloc_nr(delta_stack_nr
);
2211 delta_stack
= xmalloc(sizeof(*delta_stack
)*delta_stack_alloc
);
2212 memcpy(delta_stack
, small_delta_stack
,
2213 sizeof(*delta_stack
)*delta_stack_nr
);
2215 ALLOC_GROW(delta_stack
, delta_stack_nr
+1, delta_stack_alloc
);
2217 i
= delta_stack_nr
++;
2218 delta_stack
[i
].obj_offset
= obj_offset
;
2219 delta_stack
[i
].curpos
= curpos
;
2220 delta_stack
[i
].size
= size
;
2222 curpos
= obj_offset
= base_offset
;
2225 /* PHASE 2: handle the base */
2230 die("BUG in unpack_entry: left loop at a valid delta");
2236 if (!base_from_cache
)
2237 data
= unpack_compressed_entry(p
, &w_curs
, curpos
, size
);
2241 error("unknown object type %i at offset %"PRIuMAX
" in %s",
2242 type
, (uintmax_t)obj_offset
, p
->pack_name
);
2245 /* PHASE 3: apply deltas in order */
2248 * 'data' holds the base data, or NULL if there was corruption
2250 while (delta_stack_nr
) {
2253 unsigned long delta_size
, base_size
= size
;
2259 add_delta_base_cache(p
, obj_offset
, base
, base_size
, type
);
2263 * We're probably in deep shit, but let's try to fetch
2264 * the required base anyway from another pack or loose.
2265 * This is costly but should happen only in the presence
2266 * of a corrupted pack, and is better than failing outright.
2268 struct revindex_entry
*revidx
;
2269 const unsigned char *base_sha1
;
2270 revidx
= find_pack_revindex(p
, obj_offset
);
2272 base_sha1
= nth_packed_object_sha1(p
, revidx
->nr
);
2273 error("failed to read delta base object %s"
2274 " at offset %"PRIuMAX
" from %s",
2275 sha1_to_hex(base_sha1
), (uintmax_t)obj_offset
,
2277 mark_bad_packed_object(p
, base_sha1
);
2278 base
= read_object(base_sha1
, &type
, &base_size
);
2282 i
= --delta_stack_nr
;
2283 obj_offset
= delta_stack
[i
].obj_offset
;
2284 curpos
= delta_stack
[i
].curpos
;
2285 delta_size
= delta_stack
[i
].size
;
2290 delta_data
= unpack_compressed_entry(p
, &w_curs
, curpos
, delta_size
);
2293 error("failed to unpack compressed delta "
2294 "at offset %"PRIuMAX
" from %s",
2295 (uintmax_t)curpos
, p
->pack_name
);
2300 data
= patch_delta(base
, base_size
,
2301 delta_data
, delta_size
,
2305 * We could not apply the delta; warn the user, but keep going.
2306 * Our failure will be noticed either in the next iteration of
2307 * the loop, or if this is the final delta, in the caller when
2308 * we return NULL. Those code paths will take care of making
2309 * a more explicit warning and retrying with another copy of
2313 error("failed to apply delta");
2321 unuse_pack(&w_curs
);
2323 if (delta_stack
!= small_delta_stack
)
2329 const unsigned char *nth_packed_object_sha1(struct packed_git
*p
,
2332 const unsigned char *index
= p
->index_data
;
2334 if (open_pack_index(p
))
2336 index
= p
->index_data
;
2338 if (n
>= p
->num_objects
)
2341 if (p
->index_version
== 1) {
2342 return index
+ 24 * n
+ 4;
2345 return index
+ 20 * n
;
2349 off_t
nth_packed_object_offset(const struct packed_git
*p
, uint32_t n
)
2351 const unsigned char *index
= p
->index_data
;
2353 if (p
->index_version
== 1) {
2354 return ntohl(*((uint32_t *)(index
+ 24 * n
)));
2357 index
+= 8 + p
->num_objects
* (20 + 4);
2358 off
= ntohl(*((uint32_t *)(index
+ 4 * n
)));
2359 if (!(off
& 0x80000000))
2361 index
+= p
->num_objects
* 4 + (off
& 0x7fffffff) * 8;
2362 return (((uint64_t)ntohl(*((uint32_t *)(index
+ 0)))) << 32) |
2363 ntohl(*((uint32_t *)(index
+ 4)));
2367 off_t
find_pack_entry_one(const unsigned char *sha1
,
2368 struct packed_git
*p
)
2370 const uint32_t *level1_ofs
= p
->index_data
;
2371 const unsigned char *index
= p
->index_data
;
2372 unsigned hi
, lo
, stride
;
2373 static int use_lookup
= -1;
2374 static int debug_lookup
= -1;
2376 if (debug_lookup
< 0)
2377 debug_lookup
= !!getenv("GIT_DEBUG_LOOKUP");
2380 if (open_pack_index(p
))
2382 level1_ofs
= p
->index_data
;
2383 index
= p
->index_data
;
2385 if (p
->index_version
> 1) {
2390 hi
= ntohl(level1_ofs
[*sha1
]);
2391 lo
= ((*sha1
== 0x0) ? 0 : ntohl(level1_ofs
[*sha1
- 1]));
2392 if (p
->index_version
> 1) {
2400 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32
"\n",
2401 sha1
[0], sha1
[1], sha1
[2], lo
, hi
, p
->num_objects
);
2404 use_lookup
= !!getenv("GIT_USE_LOOKUP");
2406 int pos
= sha1_entry_pos(index
, stride
, 0,
2407 lo
, hi
, p
->num_objects
, sha1
);
2410 return nth_packed_object_offset(p
, pos
);
2414 unsigned mi
= (lo
+ hi
) / 2;
2415 int cmp
= hashcmp(index
+ mi
* stride
, sha1
);
2418 printf("lo %u hi %u rg %u mi %u\n",
2419 lo
, hi
, hi
- lo
, mi
);
2421 return nth_packed_object_offset(p
, mi
);
2430 int is_pack_valid(struct packed_git
*p
)
2432 /* An already open pack is known to be valid. */
2433 if (p
->pack_fd
!= -1)
2436 /* If the pack has one window completely covering the
2437 * file size, the pack is known to be valid even if
2438 * the descriptor is not currently open.
2441 struct pack_window
*w
= p
->windows
;
2443 if (!w
->offset
&& w
->len
== p
->pack_size
)
2447 /* Force the pack to open to prove its valid. */
2448 return !open_packed_git(p
);
2451 static int fill_pack_entry(const unsigned char *sha1
,
2452 struct pack_entry
*e
,
2453 struct packed_git
*p
)
2457 if (p
->num_bad_objects
) {
2459 for (i
= 0; i
< p
->num_bad_objects
; i
++)
2460 if (!hashcmp(sha1
, p
->bad_object_sha1
+ 20 * i
))
2464 offset
= find_pack_entry_one(sha1
, p
);
2469 * We are about to tell the caller where they can locate the
2470 * requested object. We better make sure the packfile is
2471 * still here and can be accessed before supplying that
2472 * answer, as it may have been deleted since the index was
2475 if (!is_pack_valid(p
)) {
2476 warning("packfile %s cannot be accessed", p
->pack_name
);
2481 hashcpy(e
->sha1
, sha1
);
2486 * Iff a pack file contains the object named by sha1, return true and
2487 * store its location to e.
2489 static int find_pack_entry(const unsigned char *sha1
, struct pack_entry
*e
)
2491 struct packed_git
*p
;
2493 prepare_packed_git();
2497 if (last_found_pack
&& fill_pack_entry(sha1
, e
, last_found_pack
))
2500 for (p
= packed_git
; p
; p
= p
->next
) {
2501 if (p
== last_found_pack
)
2502 continue; /* we already checked this one */
2504 if (fill_pack_entry(sha1
, e
, p
)) {
2505 last_found_pack
= p
;
2512 struct packed_git
*find_sha1_pack(const unsigned char *sha1
,
2513 struct packed_git
*packs
)
2515 struct packed_git
*p
;
2517 for (p
= packs
; p
; p
= p
->next
) {
2518 if (find_pack_entry_one(sha1
, p
))
2525 static int sha1_loose_object_info(const unsigned char *sha1
,
2526 struct object_info
*oi
)
2529 unsigned long mapsize
, size
;
2534 if (oi
->delta_base_sha1
)
2535 hashclr(oi
->delta_base_sha1
);
2538 * If we don't care about type or size, then we don't
2539 * need to look inside the object at all. Note that we
2540 * do not optimize out the stat call, even if the
2541 * caller doesn't care about the disk-size, since our
2542 * return value implicitly indicates whether the
2543 * object even exists.
2545 if (!oi
->typep
&& !oi
->sizep
) {
2547 if (stat_sha1_file(sha1
, &st
) < 0)
2550 *oi
->disk_sizep
= st
.st_size
;
2554 map
= map_sha1_file(sha1
, &mapsize
);
2558 *oi
->disk_sizep
= mapsize
;
2559 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
2560 status
= error("unable to unpack %s header",
2562 else if ((status
= parse_sha1_header(hdr
, &size
)) < 0)
2563 status
= error("unable to parse %s header", sha1_to_hex(sha1
));
2566 git_inflate_end(&stream
);
2567 munmap(map
, mapsize
);
2569 *oi
->typep
= status
;
2573 int sha1_object_info_extended(const unsigned char *sha1
, struct object_info
*oi
, unsigned flags
)
2575 struct cached_object
*co
;
2576 struct pack_entry e
;
2578 const unsigned char *real
= lookup_replace_object_extended(sha1
, flags
);
2580 co
= find_cached_object(real
);
2583 *(oi
->typep
) = co
->type
;
2585 *(oi
->sizep
) = co
->size
;
2587 *(oi
->disk_sizep
) = 0;
2588 if (oi
->delta_base_sha1
)
2589 hashclr(oi
->delta_base_sha1
);
2590 oi
->whence
= OI_CACHED
;
2594 if (!find_pack_entry(real
, &e
)) {
2595 /* Most likely it's a loose object. */
2596 if (!sha1_loose_object_info(real
, oi
)) {
2597 oi
->whence
= OI_LOOSE
;
2601 /* Not a loose object; someone else may have just packed it. */
2602 reprepare_packed_git();
2603 if (!find_pack_entry(real
, &e
))
2607 rtype
= packed_object_info(e
.p
, e
.offset
, oi
);
2609 mark_bad_packed_object(e
.p
, real
);
2610 return sha1_object_info_extended(real
, oi
, 0);
2611 } else if (in_delta_base_cache(e
.p
, e
.offset
)) {
2612 oi
->whence
= OI_DBCACHED
;
2614 oi
->whence
= OI_PACKED
;
2615 oi
->u
.packed
.offset
= e
.offset
;
2616 oi
->u
.packed
.pack
= e
.p
;
2617 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
2618 rtype
== OBJ_OFS_DELTA
);
2624 /* returns enum object_type or negative */
2625 int sha1_object_info(const unsigned char *sha1
, unsigned long *sizep
)
2627 enum object_type type
;
2628 struct object_info oi
= {NULL
};
2632 if (sha1_object_info_extended(sha1
, &oi
, LOOKUP_REPLACE_OBJECT
) < 0)
2637 static void *read_packed_sha1(const unsigned char *sha1
,
2638 enum object_type
*type
, unsigned long *size
)
2640 struct pack_entry e
;
2643 if (!find_pack_entry(sha1
, &e
))
2645 data
= cache_or_unpack_entry(e
.p
, e
.offset
, size
, type
, 1);
2648 * We're probably in deep shit, but let's try to fetch
2649 * the required object anyway from another pack or loose.
2650 * This should happen only in the presence of a corrupted
2651 * pack, and is better than failing outright.
2653 error("failed to read object %s at offset %"PRIuMAX
" from %s",
2654 sha1_to_hex(sha1
), (uintmax_t)e
.offset
, e
.p
->pack_name
);
2655 mark_bad_packed_object(e
.p
, sha1
);
2656 data
= read_object(sha1
, type
, size
);
2661 int pretend_sha1_file(void *buf
, unsigned long len
, enum object_type type
,
2662 unsigned char *sha1
)
2664 struct cached_object
*co
;
2666 hash_sha1_file(buf
, len
, typename(type
), sha1
);
2667 if (has_sha1_file(sha1
) || find_cached_object(sha1
))
2669 ALLOC_GROW(cached_objects
, cached_object_nr
+ 1, cached_object_alloc
);
2670 co
= &cached_objects
[cached_object_nr
++];
2673 co
->buf
= xmalloc(len
);
2674 memcpy(co
->buf
, buf
, len
);
2675 hashcpy(co
->sha1
, sha1
);
2679 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
2680 unsigned long *size
)
2682 unsigned long mapsize
;
2684 struct cached_object
*co
;
2686 co
= find_cached_object(sha1
);
2690 return xmemdupz(co
->buf
, co
->size
);
2693 buf
= read_packed_sha1(sha1
, type
, size
);
2696 map
= map_sha1_file(sha1
, &mapsize
);
2698 buf
= unpack_sha1_file(map
, mapsize
, type
, size
, sha1
);
2699 munmap(map
, mapsize
);
2702 reprepare_packed_git();
2703 return read_packed_sha1(sha1
, type
, size
);
2707 * This function dies on corrupt objects; the callers who want to
2708 * deal with them should arrange to call read_object() and give error
2709 * messages themselves.
2711 void *read_sha1_file_extended(const unsigned char *sha1
,
2712 enum object_type
*type
,
2713 unsigned long *size
,
2717 const struct packed_git
*p
;
2718 const unsigned char *repl
= lookup_replace_object_extended(sha1
, flag
);
2721 data
= read_object(repl
, type
, size
);
2725 if (errno
&& errno
!= ENOENT
)
2726 die_errno("failed to read object %s", sha1_to_hex(sha1
));
2728 /* die if we replaced an object with one that does not exist */
2730 die("replacement %s not found for %s",
2731 sha1_to_hex(repl
), sha1_to_hex(sha1
));
2733 if (has_loose_object(repl
)) {
2734 const char *path
= sha1_file_name(sha1
);
2736 die("loose object %s (stored in %s) is corrupt",
2737 sha1_to_hex(repl
), path
);
2740 if ((p
= has_packed_and_bad(repl
)) != NULL
)
2741 die("packed object %s (stored in %s) is corrupt",
2742 sha1_to_hex(repl
), p
->pack_name
);
2747 void *read_object_with_reference(const unsigned char *sha1
,
2748 const char *required_type_name
,
2749 unsigned long *size
,
2750 unsigned char *actual_sha1_return
)
2752 enum object_type type
, required_type
;
2754 unsigned long isize
;
2755 unsigned char actual_sha1
[20];
2757 required_type
= type_from_string(required_type_name
);
2758 hashcpy(actual_sha1
, sha1
);
2760 int ref_length
= -1;
2761 const char *ref_type
= NULL
;
2763 buffer
= read_sha1_file(actual_sha1
, &type
, &isize
);
2766 if (type
== required_type
) {
2768 if (actual_sha1_return
)
2769 hashcpy(actual_sha1_return
, actual_sha1
);
2772 /* Handle references */
2773 else if (type
== OBJ_COMMIT
)
2775 else if (type
== OBJ_TAG
)
2776 ref_type
= "object ";
2781 ref_length
= strlen(ref_type
);
2783 if (ref_length
+ 40 > isize
||
2784 memcmp(buffer
, ref_type
, ref_length
) ||
2785 get_sha1_hex((char *) buffer
+ ref_length
, actual_sha1
)) {
2790 /* Now we have the ID of the referred-to object in
2791 * actual_sha1. Check again. */
2795 static void write_sha1_file_prepare(const void *buf
, unsigned long len
,
2796 const char *type
, unsigned char *sha1
,
2797 char *hdr
, int *hdrlen
)
2801 /* Generate the header */
2802 *hdrlen
= sprintf(hdr
, "%s %lu", type
, len
)+1;
2806 git_SHA1_Update(&c
, hdr
, *hdrlen
);
2807 git_SHA1_Update(&c
, buf
, len
);
2808 git_SHA1_Final(sha1
, &c
);
2812 * Move the just written object into its final resting place.
2813 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2814 * "moving" is only a part of what it does, when no patch between
2815 * master to pu changes the call sites of this function.
2817 int move_temp_to_file(const char *tmpfile
, const char *filename
)
2821 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
2823 else if (link(tmpfile
, filename
))
2827 * Coda hack - coda doesn't like cross-directory links,
2828 * so we fall back to a rename, which will mean that it
2829 * won't be able to check collisions, but that's not a
2832 * The same holds for FAT formatted media.
2834 * When this succeeds, we just return. We have nothing
2837 if (ret
&& ret
!= EEXIST
) {
2839 if (!rename(tmpfile
, filename
))
2843 unlink_or_warn(tmpfile
);
2845 if (ret
!= EEXIST
) {
2846 return error("unable to write sha1 filename %s: %s", filename
, strerror(ret
));
2848 /* FIXME!!! Collision check here ? */
2852 if (adjust_shared_perm(filename
))
2853 return error("unable to set permission to '%s'", filename
);
2857 static int write_buffer(int fd
, const void *buf
, size_t len
)
2859 if (write_in_full(fd
, buf
, len
) < 0)
2860 return error("file write error (%s)", strerror(errno
));
2864 int hash_sha1_file(const void *buf
, unsigned long len
, const char *type
,
2865 unsigned char *sha1
)
2869 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
2873 /* Finalize a file on disk, and close it. */
2874 static void close_sha1_file(int fd
)
2876 if (fsync_object_files
)
2877 fsync_or_die(fd
, "sha1 file");
2879 die_errno("error when closing sha1 file");
2882 /* Size of directory component, including the ending '/' */
2883 static inline int directory_size(const char *filename
)
2885 const char *s
= strrchr(filename
, '/');
2888 return s
- filename
+ 1;
2892 * This creates a temporary file in the same directory as the final
2895 * We want to avoid cross-directory filename renames, because those
2896 * can have problems on various filesystems (FAT, NFS, Coda).
2898 static int create_tmpfile(char *buffer
, size_t bufsiz
, const char *filename
)
2900 int fd
, dirlen
= directory_size(filename
);
2902 if (dirlen
+ 20 > bufsiz
) {
2903 errno
= ENAMETOOLONG
;
2906 memcpy(buffer
, filename
, dirlen
);
2907 strcpy(buffer
+ dirlen
, "tmp_obj_XXXXXX");
2908 fd
= git_mkstemp_mode(buffer
, 0444);
2909 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
2910 /* Make sure the directory exists */
2911 memcpy(buffer
, filename
, dirlen
);
2912 buffer
[dirlen
-1] = 0;
2913 if (mkdir(buffer
, 0777) && errno
!= EEXIST
)
2915 if (adjust_shared_perm(buffer
))
2919 strcpy(buffer
+ dirlen
- 1, "/tmp_obj_XXXXXX");
2920 fd
= git_mkstemp_mode(buffer
, 0444);
2925 static int write_loose_object(const unsigned char *sha1
, char *hdr
, int hdrlen
,
2926 const void *buf
, unsigned long len
, time_t mtime
)
2929 unsigned char compressed
[4096];
2932 unsigned char parano_sha1
[20];
2933 static char tmp_file
[PATH_MAX
];
2934 const char *filename
= sha1_file_name(sha1
);
2936 fd
= create_tmpfile(tmp_file
, sizeof(tmp_file
), filename
);
2938 if (errno
== EACCES
)
2939 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2941 return error("unable to create temporary file: %s", strerror(errno
));
2945 memset(&stream
, 0, sizeof(stream
));
2946 git_deflate_init(&stream
, zlib_compression_level
);
2947 stream
.next_out
= compressed
;
2948 stream
.avail_out
= sizeof(compressed
);
2951 /* First header.. */
2952 stream
.next_in
= (unsigned char *)hdr
;
2953 stream
.avail_in
= hdrlen
;
2954 while (git_deflate(&stream
, 0) == Z_OK
)
2956 git_SHA1_Update(&c
, hdr
, hdrlen
);
2958 /* Then the data itself.. */
2959 stream
.next_in
= (void *)buf
;
2960 stream
.avail_in
= len
;
2962 unsigned char *in0
= stream
.next_in
;
2963 ret
= git_deflate(&stream
, Z_FINISH
);
2964 git_SHA1_Update(&c
, in0
, stream
.next_in
- in0
);
2965 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
2966 die("unable to write sha1 file");
2967 stream
.next_out
= compressed
;
2968 stream
.avail_out
= sizeof(compressed
);
2969 } while (ret
== Z_OK
);
2971 if (ret
!= Z_STREAM_END
)
2972 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1
), ret
);
2973 ret
= git_deflate_end_gently(&stream
);
2975 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1
), ret
);
2976 git_SHA1_Final(parano_sha1
, &c
);
2977 if (hashcmp(sha1
, parano_sha1
) != 0)
2978 die("confused by unstable object source data for %s", sha1_to_hex(sha1
));
2980 close_sha1_file(fd
);
2985 utb
.modtime
= mtime
;
2986 if (utime(tmp_file
, &utb
) < 0)
2987 warning("failed utime() on %s: %s",
2988 tmp_file
, strerror(errno
));
2991 return move_temp_to_file(tmp_file
, filename
);
2994 static int freshen_loose_object(const unsigned char *sha1
)
2996 return check_and_freshen(sha1
, 1);
2999 static int freshen_packed_object(const unsigned char *sha1
)
3001 struct pack_entry e
;
3002 return find_pack_entry(sha1
, &e
) && freshen_file(e
.p
->pack_name
);
3005 int write_sha1_file(const void *buf
, unsigned long len
, const char *type
, unsigned char *returnsha1
)
3007 unsigned char sha1
[20];
3011 /* Normally if we have it in the pack then we do not bother writing
3012 * it out into .git/objects/??/?{38} file.
3014 write_sha1_file_prepare(buf
, len
, type
, sha1
, hdr
, &hdrlen
);
3016 hashcpy(returnsha1
, sha1
);
3017 if (freshen_loose_object(sha1
) || freshen_packed_object(sha1
))
3019 return write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, 0);
3022 int force_object_loose(const unsigned char *sha1
, time_t mtime
)
3026 enum object_type type
;
3031 if (has_loose_object(sha1
))
3033 buf
= read_packed_sha1(sha1
, &type
, &len
);
3035 return error("cannot read sha1_file for %s", sha1_to_hex(sha1
));
3036 hdrlen
= sprintf(hdr
, "%s %lu", typename(type
), len
) + 1;
3037 ret
= write_loose_object(sha1
, hdr
, hdrlen
, buf
, len
, mtime
);
3043 int has_pack_index(const unsigned char *sha1
)
3046 if (stat(sha1_pack_index_name(sha1
), &st
))
3051 int has_sha1_pack(const unsigned char *sha1
)
3053 struct pack_entry e
;
3054 return find_pack_entry(sha1
, &e
);
3057 int has_sha1_file(const unsigned char *sha1
)
3059 struct pack_entry e
;
3061 if (find_pack_entry(sha1
, &e
))
3063 if (has_loose_object(sha1
))
3065 reprepare_packed_git();
3066 return find_pack_entry(sha1
, &e
);
3069 static void check_tree(const void *buf
, size_t size
)
3071 struct tree_desc desc
;
3072 struct name_entry entry
;
3074 init_tree_desc(&desc
, buf
, size
);
3075 while (tree_entry(&desc
, &entry
))
3077 * tree_entry() will die() on malformed entries */
3081 static void check_commit(const void *buf
, size_t size
)
3084 memset(&c
, 0, sizeof(c
));
3085 if (parse_commit_buffer(&c
, buf
, size
))
3086 die("corrupt commit");
3089 static void check_tag(const void *buf
, size_t size
)
3092 memset(&t
, 0, sizeof(t
));
3093 if (parse_tag_buffer(&t
, buf
, size
))
3097 static int index_mem(unsigned char *sha1
, void *buf
, size_t size
,
3098 enum object_type type
,
3099 const char *path
, unsigned flags
)
3101 int ret
, re_allocated
= 0;
3102 int write_object
= flags
& HASH_WRITE_OBJECT
;
3108 * Convert blobs to git internal format
3110 if ((type
== OBJ_BLOB
) && path
) {
3111 struct strbuf nbuf
= STRBUF_INIT
;
3112 if (convert_to_git(path
, buf
, size
, &nbuf
,
3113 write_object
? safe_crlf
: SAFE_CRLF_FALSE
)) {
3114 buf
= strbuf_detach(&nbuf
, &size
);
3118 if (flags
& HASH_FORMAT_CHECK
) {
3119 if (type
== OBJ_TREE
)
3120 check_tree(buf
, size
);
3121 if (type
== OBJ_COMMIT
)
3122 check_commit(buf
, size
);
3123 if (type
== OBJ_TAG
)
3124 check_tag(buf
, size
);
3128 ret
= write_sha1_file(buf
, size
, typename(type
), sha1
);
3130 ret
= hash_sha1_file(buf
, size
, typename(type
), sha1
);
3136 static int index_stream_convert_blob(unsigned char *sha1
, int fd
,
3137 const char *path
, unsigned flags
)
3140 const int write_object
= flags
& HASH_WRITE_OBJECT
;
3141 struct strbuf sbuf
= STRBUF_INIT
;
3144 assert(would_convert_to_git_filter_fd(path
));
3146 convert_to_git_filter_fd(path
, fd
, &sbuf
,
3147 write_object
? safe_crlf
: SAFE_CRLF_FALSE
);
3150 ret
= write_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3153 ret
= hash_sha1_file(sbuf
.buf
, sbuf
.len
, typename(OBJ_BLOB
),
3155 strbuf_release(&sbuf
);
3159 static int index_pipe(unsigned char *sha1
, int fd
, enum object_type type
,
3160 const char *path
, unsigned flags
)
3162 struct strbuf sbuf
= STRBUF_INIT
;
3165 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
3166 ret
= index_mem(sha1
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
3169 strbuf_release(&sbuf
);
3173 #define SMALL_FILE_SIZE (32*1024)
3175 static int index_core(unsigned char *sha1
, int fd
, size_t size
,
3176 enum object_type type
, const char *path
,
3182 ret
= index_mem(sha1
, NULL
, size
, type
, path
, flags
);
3183 } else if (size
<= SMALL_FILE_SIZE
) {
3184 char *buf
= xmalloc(size
);
3185 if (size
== read_in_full(fd
, buf
, size
))
3186 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3188 ret
= error("short read %s", strerror(errno
));
3191 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
3192 ret
= index_mem(sha1
, buf
, size
, type
, path
, flags
);
3199 * This creates one packfile per large blob unless bulk-checkin
3200 * machinery is "plugged".
3202 * This also bypasses the usual "convert-to-git" dance, and that is on
3203 * purpose. We could write a streaming version of the converting
3204 * functions and insert that before feeding the data to fast-import
3205 * (or equivalent in-core API described above). However, that is
3206 * somewhat complicated, as we do not know the size of the filter
3207 * result, which we need to know beforehand when writing a git object.
3208 * Since the primary motivation for trying to stream from the working
3209 * tree file and to avoid mmaping it in core is to deal with large
3210 * binary blobs, they generally do not want to get any conversion, and
3211 * callers should avoid this code path when filters are requested.
3213 static int index_stream(unsigned char *sha1
, int fd
, size_t size
,
3214 enum object_type type
, const char *path
,
3217 return index_bulk_checkin(sha1
, fd
, size
, type
, path
, flags
);
3220 int index_fd(unsigned char *sha1
, int fd
, struct stat
*st
,
3221 enum object_type type
, const char *path
, unsigned flags
)
3226 * Call xsize_t() only when needed to avoid potentially unnecessary
3227 * die() for large files.
3229 if (type
== OBJ_BLOB
&& path
&& would_convert_to_git_filter_fd(path
))
3230 ret
= index_stream_convert_blob(sha1
, fd
, path
, flags
);
3231 else if (!S_ISREG(st
->st_mode
))
3232 ret
= index_pipe(sha1
, fd
, type
, path
, flags
);
3233 else if (st
->st_size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
3234 (path
&& would_convert_to_git(path
)))
3235 ret
= index_core(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3238 ret
= index_stream(sha1
, fd
, xsize_t(st
->st_size
), type
, path
,
3244 int index_path(unsigned char *sha1
, const char *path
, struct stat
*st
, unsigned flags
)
3247 struct strbuf sb
= STRBUF_INIT
;
3249 switch (st
->st_mode
& S_IFMT
) {
3251 fd
= open(path
, O_RDONLY
);
3253 return error("open(\"%s\"): %s", path
,
3255 if (index_fd(sha1
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
3256 return error("%s: failed to insert into database",
3260 if (strbuf_readlink(&sb
, path
, st
->st_size
)) {
3261 char *errstr
= strerror(errno
);
3262 return error("readlink(\"%s\"): %s", path
,
3265 if (!(flags
& HASH_WRITE_OBJECT
))
3266 hash_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
);
3267 else if (write_sha1_file(sb
.buf
, sb
.len
, blob_type
, sha1
))
3268 return error("%s: failed to insert into database",
3270 strbuf_release(&sb
);
3273 return resolve_gitlink_ref(path
, "HEAD", sha1
);
3275 return error("%s: unsupported file type", path
);
3280 int read_pack_header(int fd
, struct pack_header
*header
)
3282 if (read_in_full(fd
, header
, sizeof(*header
)) < sizeof(*header
))
3283 /* "eof before pack header was fully read" */
3284 return PH_ERROR_EOF
;
3286 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
3287 /* "protocol error (pack signature mismatch detected)" */
3288 return PH_ERROR_PACK_SIGNATURE
;
3289 if (!pack_version_ok(header
->hdr_version
))
3290 /* "protocol error (pack version unsupported)" */
3291 return PH_ERROR_PROTOCOL
;
3295 void assert_sha1_type(const unsigned char *sha1
, enum object_type expect
)
3297 enum object_type type
= sha1_object_info(sha1
, NULL
);
3299 die("%s is not a valid object", sha1_to_hex(sha1
));
3301 die("%s is not a valid '%s' object", sha1_to_hex(sha1
),
3305 static int for_each_file_in_obj_subdir(int subdir_nr
,
3306 struct strbuf
*path
,
3307 each_loose_object_fn obj_cb
,
3308 each_loose_cruft_fn cruft_cb
,
3309 each_loose_subdir_fn subdir_cb
,
3312 size_t baselen
= path
->len
;
3313 DIR *dir
= opendir(path
->buf
);
3318 if (errno
== ENOENT
)
3320 return error("unable to open %s: %s", path
->buf
, strerror(errno
));
3323 while ((de
= readdir(dir
))) {
3324 if (is_dot_or_dotdot(de
->d_name
))
3327 strbuf_setlen(path
, baselen
);
3328 strbuf_addf(path
, "/%s", de
->d_name
);
3330 if (strlen(de
->d_name
) == 38) {
3332 unsigned char sha1
[20];
3334 snprintf(hex
, sizeof(hex
), "%02x%s",
3335 subdir_nr
, de
->d_name
);
3336 if (!get_sha1_hex(hex
, sha1
)) {
3338 r
= obj_cb(sha1
, path
->buf
, data
);
3347 r
= cruft_cb(de
->d_name
, path
->buf
, data
);
3352 strbuf_setlen(path
, baselen
);
3354 if (!r
&& subdir_cb
)
3355 r
= subdir_cb(subdir_nr
, path
->buf
, data
);
3361 int for_each_loose_file_in_objdir(const char *path
,
3362 each_loose_object_fn obj_cb
,
3363 each_loose_cruft_fn cruft_cb
,
3364 each_loose_subdir_fn subdir_cb
,
3367 struct strbuf buf
= STRBUF_INIT
;
3372 strbuf_addstr(&buf
, path
);
3373 strbuf_addch(&buf
, '/');
3376 for (i
= 0; i
< 256; i
++) {
3377 strbuf_addf(&buf
, "%02x", i
);
3378 r
= for_each_file_in_obj_subdir(i
, &buf
, obj_cb
, cruft_cb
,
3380 strbuf_setlen(&buf
, baselen
);
3385 strbuf_release(&buf
);
3389 struct loose_alt_odb_data
{
3390 each_loose_object_fn
*cb
;
3394 static int loose_from_alt_odb(struct alternate_object_database
*alt
,
3397 struct loose_alt_odb_data
*data
= vdata
;
3398 return for_each_loose_file_in_objdir(alt
->base
,
3399 data
->cb
, NULL
, NULL
,
3403 int for_each_loose_object(each_loose_object_fn cb
, void *data
)
3405 struct loose_alt_odb_data alt
;
3408 r
= for_each_loose_file_in_objdir(get_object_directory(),
3409 cb
, NULL
, NULL
, data
);
3415 return foreach_alt_odb(loose_from_alt_odb
, &alt
);
3418 static int for_each_object_in_pack(struct packed_git
*p
, each_packed_object_fn cb
, void *data
)
3423 for (i
= 0; i
< p
->num_objects
; i
++) {
3424 const unsigned char *sha1
= nth_packed_object_sha1(p
, i
);
3427 return error("unable to get sha1 of object %u in %s",
3430 r
= cb(sha1
, p
, i
, data
);
3437 int for_each_packed_object(each_packed_object_fn cb
, void *data
)
3439 struct packed_git
*p
;
3442 prepare_packed_git();
3443 for (p
= packed_git
; p
; p
= p
->next
) {
3444 r
= for_each_object_in_pack(p
, cb
, data
);