abspath.h: move absolute path functions from cache.h
[git/debian.git] / packfile.c
blob3290fde15a1a9ff81060d825585a37e24f8e4572
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "gettext.h"
4 #include "hex.h"
5 #include "list.h"
6 #include "pack.h"
7 #include "repository.h"
8 #include "dir.h"
9 #include "mergesort.h"
10 #include "packfile.h"
11 #include "delta.h"
12 #include "streaming.h"
13 #include "hash-lookup.h"
14 #include "commit.h"
15 #include "object.h"
16 #include "tag.h"
17 #include "tree-walk.h"
18 #include "tree.h"
19 #include "object-store.h"
20 #include "midx.h"
21 #include "commit-graph.h"
22 #include "promisor-remote.h"
24 char *odb_pack_name(struct strbuf *buf,
25 const unsigned char *hash,
26 const char *ext)
28 strbuf_reset(buf);
29 strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
30 hash_to_hex(hash), ext);
31 return buf->buf;
34 char *sha1_pack_name(const unsigned char *sha1)
36 static struct strbuf buf = STRBUF_INIT;
37 return odb_pack_name(&buf, sha1, "pack");
40 char *sha1_pack_index_name(const unsigned char *sha1)
42 static struct strbuf buf = STRBUF_INIT;
43 return odb_pack_name(&buf, sha1, "idx");
46 static unsigned int pack_used_ctr;
47 static unsigned int pack_mmap_calls;
48 static unsigned int peak_pack_open_windows;
49 static unsigned int pack_open_windows;
50 static unsigned int pack_open_fds;
51 static unsigned int pack_max_fds;
52 static size_t peak_pack_mapped;
53 static size_t pack_mapped;
55 #define SZ_FMT PRIuMAX
56 static inline uintmax_t sz_fmt(size_t s) { return s; }
58 void pack_report(void)
60 fprintf(stderr,
61 "pack_report: getpagesize() = %10" SZ_FMT "\n"
62 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
63 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
64 sz_fmt(getpagesize()),
65 sz_fmt(packed_git_window_size),
66 sz_fmt(packed_git_limit));
67 fprintf(stderr,
68 "pack_report: pack_used_ctr = %10u\n"
69 "pack_report: pack_mmap_calls = %10u\n"
70 "pack_report: pack_open_windows = %10u / %10u\n"
71 "pack_report: pack_mapped = "
72 "%10" SZ_FMT " / %10" SZ_FMT "\n",
73 pack_used_ctr,
74 pack_mmap_calls,
75 pack_open_windows, peak_pack_open_windows,
76 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
80 * Open and mmap the index file at path, perform a couple of
81 * consistency checks, then record its information to p. Return 0 on
82 * success.
84 static int check_packed_git_idx(const char *path, struct packed_git *p)
86 void *idx_map;
87 size_t idx_size;
88 int fd = git_open(path), ret;
89 struct stat st;
90 const unsigned int hashsz = the_hash_algo->rawsz;
92 if (fd < 0)
93 return -1;
94 if (fstat(fd, &st)) {
95 close(fd);
96 return -1;
98 idx_size = xsize_t(st.st_size);
99 if (idx_size < 4 * 256 + hashsz + hashsz) {
100 close(fd);
101 return error("index file %s is too small", path);
103 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
104 close(fd);
106 ret = load_idx(path, hashsz, idx_map, idx_size, p);
108 if (ret)
109 munmap(idx_map, idx_size);
111 return ret;
114 int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
115 size_t idx_size, struct packed_git *p)
117 struct pack_idx_header *hdr = idx_map;
118 uint32_t version, nr, i, *index;
120 if (idx_size < 4 * 256 + hashsz + hashsz)
121 return error("index file %s is too small", path);
122 if (!idx_map)
123 return error("empty data");
125 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
126 version = ntohl(hdr->idx_version);
127 if (version < 2 || version > 2)
128 return error("index file %s is version %"PRIu32
129 " and is not supported by this binary"
130 " (try upgrading GIT to a newer version)",
131 path, version);
132 } else
133 version = 1;
135 nr = 0;
136 index = idx_map;
137 if (version > 1)
138 index += 2; /* skip index header */
139 for (i = 0; i < 256; i++) {
140 uint32_t n = ntohl(index[i]);
141 if (n < nr)
142 return error("non-monotonic index %s", path);
143 nr = n;
146 if (version == 1) {
148 * Total size:
149 * - 256 index entries 4 bytes each
150 * - 24-byte entries * nr (object ID + 4-byte offset)
151 * - hash of the packfile
152 * - file checksum
154 if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
155 return error("wrong index v1 file size in %s", path);
156 } else if (version == 2) {
158 * Minimum size:
159 * - 8 bytes of header
160 * - 256 index entries 4 bytes each
161 * - object ID entry * nr
162 * - 4-byte crc entry * nr
163 * - 4-byte offset entry * nr
164 * - hash of the packfile
165 * - file checksum
166 * And after the 4-byte offset table might be a
167 * variable sized table containing 8-byte entries
168 * for offsets larger than 2^31.
170 size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
171 size_t max_size = min_size;
172 if (nr)
173 max_size = st_add(max_size, st_mult(nr - 1, 8));
174 if (idx_size < min_size || idx_size > max_size)
175 return error("wrong index v2 file size in %s", path);
176 if (idx_size != min_size &&
178 * make sure we can deal with large pack offsets.
179 * 31-bit signed offset won't be enough, neither
180 * 32-bit unsigned one will be.
182 (sizeof(off_t) <= 4))
183 return error("pack too large for current definition of off_t in %s", path);
184 p->crc_offset = 8 + 4 * 256 + nr * hashsz;
187 p->index_version = version;
188 p->index_data = idx_map;
189 p->index_size = idx_size;
190 p->num_objects = nr;
191 return 0;
194 int open_pack_index(struct packed_git *p)
196 char *idx_name;
197 size_t len;
198 int ret;
200 if (p->index_data)
201 return 0;
203 if (!strip_suffix(p->pack_name, ".pack", &len))
204 BUG("pack_name does not end in .pack");
205 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
206 ret = check_packed_git_idx(idx_name, p);
207 free(idx_name);
208 return ret;
211 uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
213 const uint32_t *level1_ofs = p->index_data;
215 if (!level1_ofs) {
216 if (open_pack_index(p))
217 return 0;
218 level1_ofs = p->index_data;
221 if (p->index_version > 1) {
222 level1_ofs += 2;
225 return ntohl(level1_ofs[value]);
228 static struct packed_git *alloc_packed_git(int extra)
230 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
231 memset(p, 0, sizeof(*p));
232 p->pack_fd = -1;
233 return p;
236 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
238 const char *path = sha1_pack_name(sha1);
239 size_t alloc = st_add(strlen(path), 1);
240 struct packed_git *p = alloc_packed_git(alloc);
242 memcpy(p->pack_name, path, alloc); /* includes NUL */
243 hashcpy(p->hash, sha1);
244 if (check_packed_git_idx(idx_path, p)) {
245 free(p);
246 return NULL;
249 return p;
252 static void scan_windows(struct packed_git *p,
253 struct packed_git **lru_p,
254 struct pack_window **lru_w,
255 struct pack_window **lru_l)
257 struct pack_window *w, *w_l;
259 for (w_l = NULL, w = p->windows; w; w = w->next) {
260 if (!w->inuse_cnt) {
261 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
262 *lru_p = p;
263 *lru_w = w;
264 *lru_l = w_l;
267 w_l = w;
271 static int unuse_one_window(struct packed_git *current)
273 struct packed_git *p, *lru_p = NULL;
274 struct pack_window *lru_w = NULL, *lru_l = NULL;
276 if (current)
277 scan_windows(current, &lru_p, &lru_w, &lru_l);
278 for (p = the_repository->objects->packed_git; p; p = p->next)
279 scan_windows(p, &lru_p, &lru_w, &lru_l);
280 if (lru_p) {
281 munmap(lru_w->base, lru_w->len);
282 pack_mapped -= lru_w->len;
283 if (lru_l)
284 lru_l->next = lru_w->next;
285 else
286 lru_p->windows = lru_w->next;
287 free(lru_w);
288 pack_open_windows--;
289 return 1;
291 return 0;
294 void close_pack_windows(struct packed_git *p)
296 while (p->windows) {
297 struct pack_window *w = p->windows;
299 if (w->inuse_cnt)
300 die("pack '%s' still has open windows to it",
301 p->pack_name);
302 munmap(w->base, w->len);
303 pack_mapped -= w->len;
304 pack_open_windows--;
305 p->windows = w->next;
306 free(w);
310 int close_pack_fd(struct packed_git *p)
312 if (p->pack_fd < 0)
313 return 0;
315 close(p->pack_fd);
316 pack_open_fds--;
317 p->pack_fd = -1;
319 return 1;
322 void close_pack_index(struct packed_git *p)
324 if (p->index_data) {
325 munmap((void *)p->index_data, p->index_size);
326 p->index_data = NULL;
330 static void close_pack_revindex(struct packed_git *p)
332 if (!p->revindex_map)
333 return;
335 munmap((void *)p->revindex_map, p->revindex_size);
336 p->revindex_map = NULL;
337 p->revindex_data = NULL;
340 static void close_pack_mtimes(struct packed_git *p)
342 if (!p->mtimes_map)
343 return;
345 munmap((void *)p->mtimes_map, p->mtimes_size);
346 p->mtimes_map = NULL;
349 void close_pack(struct packed_git *p)
351 close_pack_windows(p);
352 close_pack_fd(p);
353 close_pack_index(p);
354 close_pack_revindex(p);
355 close_pack_mtimes(p);
356 oidset_clear(&p->bad_objects);
359 void close_object_store(struct raw_object_store *o)
361 struct packed_git *p;
363 for (p = o->packed_git; p; p = p->next)
364 if (p->do_not_close)
365 BUG("want to close pack marked 'do-not-close'");
366 else
367 close_pack(p);
369 if (o->multi_pack_index) {
370 close_midx(o->multi_pack_index);
371 o->multi_pack_index = NULL;
374 close_commit_graph(o);
377 void unlink_pack_path(const char *pack_name, int force_delete)
379 static const char *exts[] = {".pack", ".idx", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
380 int i;
381 struct strbuf buf = STRBUF_INIT;
382 size_t plen;
384 strbuf_addstr(&buf, pack_name);
385 strip_suffix_mem(buf.buf, &buf.len, ".pack");
386 plen = buf.len;
388 if (!force_delete) {
389 strbuf_addstr(&buf, ".keep");
390 if (!access(buf.buf, F_OK)) {
391 strbuf_release(&buf);
392 return;
396 for (i = 0; i < ARRAY_SIZE(exts); i++) {
397 strbuf_setlen(&buf, plen);
398 strbuf_addstr(&buf, exts[i]);
399 unlink(buf.buf);
402 strbuf_release(&buf);
406 * The LRU pack is the one with the oldest MRU window, preferring packs
407 * with no used windows, or the oldest mtime if it has no windows allocated.
409 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
411 struct pack_window *w, *this_mru_w;
412 int has_windows_inuse = 0;
415 * Reject this pack if it has windows and the previously selected
416 * one does not. If this pack does not have windows, reject
417 * it if the pack file is newer than the previously selected one.
419 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
420 return;
422 for (w = this_mru_w = p->windows; w; w = w->next) {
424 * Reject this pack if any of its windows are in use,
425 * but the previously selected pack did not have any
426 * inuse windows. Otherwise, record that this pack
427 * has windows in use.
429 if (w->inuse_cnt) {
430 if (*accept_windows_inuse)
431 has_windows_inuse = 1;
432 else
433 return;
436 if (w->last_used > this_mru_w->last_used)
437 this_mru_w = w;
440 * Reject this pack if it has windows that have been
441 * used more recently than the previously selected pack.
442 * If the previously selected pack had windows inuse and
443 * we have not encountered a window in this pack that is
444 * inuse, skip this check since we prefer a pack with no
445 * inuse windows to one that has inuse windows.
447 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
448 this_mru_w->last_used > (*mru_w)->last_used)
449 return;
453 * Select this pack.
455 *mru_w = this_mru_w;
456 *lru_p = p;
457 *accept_windows_inuse = has_windows_inuse;
460 static int close_one_pack(void)
462 struct packed_git *p, *lru_p = NULL;
463 struct pack_window *mru_w = NULL;
464 int accept_windows_inuse = 1;
466 for (p = the_repository->objects->packed_git; p; p = p->next) {
467 if (p->pack_fd == -1)
468 continue;
469 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
472 if (lru_p)
473 return close_pack_fd(lru_p);
475 return 0;
478 static unsigned int get_max_fd_limit(void)
480 #ifdef RLIMIT_NOFILE
482 struct rlimit lim;
484 if (!getrlimit(RLIMIT_NOFILE, &lim))
485 return lim.rlim_cur;
487 #endif
489 #ifdef _SC_OPEN_MAX
491 long open_max = sysconf(_SC_OPEN_MAX);
492 if (0 < open_max)
493 return open_max;
495 * Otherwise, we got -1 for one of the two
496 * reasons:
498 * (1) sysconf() did not understand _SC_OPEN_MAX
499 * and signaled an error with -1; or
500 * (2) sysconf() said there is no limit.
502 * We _could_ clear errno before calling sysconf() to
503 * tell these two cases apart and return a huge number
504 * in the latter case to let the caller cap it to a
505 * value that is not so selfish, but letting the
506 * fallback OPEN_MAX codepath take care of these cases
507 * is a lot simpler.
510 #endif
512 #ifdef OPEN_MAX
513 return OPEN_MAX;
514 #else
515 return 1; /* see the caller ;-) */
516 #endif
519 const char *pack_basename(struct packed_git *p)
521 const char *ret = strrchr(p->pack_name, '/');
522 if (ret)
523 ret = ret + 1; /* skip past slash */
524 else
525 ret = p->pack_name; /* we only have a base */
526 return ret;
530 * Do not call this directly as this leaks p->pack_fd on error return;
531 * call open_packed_git() instead.
533 static int open_packed_git_1(struct packed_git *p)
535 struct stat st;
536 struct pack_header hdr;
537 unsigned char hash[GIT_MAX_RAWSZ];
538 unsigned char *idx_hash;
539 ssize_t read_result;
540 const unsigned hashsz = the_hash_algo->rawsz;
542 if (open_pack_index(p))
543 return error("packfile %s index unavailable", p->pack_name);
545 if (!pack_max_fds) {
546 unsigned int max_fds = get_max_fd_limit();
548 /* Save 3 for stdin/stdout/stderr, 22 for work */
549 if (25 < max_fds)
550 pack_max_fds = max_fds - 25;
551 else
552 pack_max_fds = 1;
555 while (pack_max_fds <= pack_open_fds && close_one_pack())
556 ; /* nothing */
558 p->pack_fd = git_open(p->pack_name);
559 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
560 return -1;
561 pack_open_fds++;
563 /* If we created the struct before we had the pack we lack size. */
564 if (!p->pack_size) {
565 if (!S_ISREG(st.st_mode))
566 return error("packfile %s not a regular file", p->pack_name);
567 p->pack_size = st.st_size;
568 } else if (p->pack_size != st.st_size)
569 return error("packfile %s size changed", p->pack_name);
571 /* Verify we recognize this pack file format. */
572 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
573 if (read_result < 0)
574 return error_errno("error reading from %s", p->pack_name);
575 if (read_result != sizeof(hdr))
576 return error("file %s is far too short to be a packfile", p->pack_name);
577 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
578 return error("file %s is not a GIT packfile", p->pack_name);
579 if (!pack_version_ok(hdr.hdr_version))
580 return error("packfile %s is version %"PRIu32" and not"
581 " supported (try upgrading GIT to a newer version)",
582 p->pack_name, ntohl(hdr.hdr_version));
584 /* Verify the pack matches its index. */
585 if (p->num_objects != ntohl(hdr.hdr_entries))
586 return error("packfile %s claims to have %"PRIu32" objects"
587 " while index indicates %"PRIu32" objects",
588 p->pack_name, ntohl(hdr.hdr_entries),
589 p->num_objects);
590 read_result = pread_in_full(p->pack_fd, hash, hashsz,
591 p->pack_size - hashsz);
592 if (read_result < 0)
593 return error_errno("error reading from %s", p->pack_name);
594 if (read_result != hashsz)
595 return error("packfile %s signature is unavailable", p->pack_name);
596 idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
597 if (!hasheq(hash, idx_hash))
598 return error("packfile %s does not match index", p->pack_name);
599 return 0;
602 static int open_packed_git(struct packed_git *p)
604 if (!open_packed_git_1(p))
605 return 0;
606 close_pack_fd(p);
607 return -1;
610 static int in_window(struct pack_window *win, off_t offset)
612 /* We must promise at least one full hash after the
613 * offset is available from this window, otherwise the offset
614 * is not actually in this window and a different window (which
615 * has that one hash excess) must be used. This is to support
616 * the object header and delta base parsing routines below.
618 off_t win_off = win->offset;
619 return win_off <= offset
620 && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
623 unsigned char *use_pack(struct packed_git *p,
624 struct pack_window **w_cursor,
625 off_t offset,
626 unsigned long *left)
628 struct pack_window *win = *w_cursor;
630 /* Since packfiles end in a hash of their content and it's
631 * pointless to ask for an offset into the middle of that
632 * hash, and the in_window function above wouldn't match
633 * don't allow an offset too close to the end of the file.
635 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
636 die("packfile %s cannot be accessed", p->pack_name);
637 if (offset > (p->pack_size - the_hash_algo->rawsz))
638 die("offset beyond end of packfile (truncated pack?)");
639 if (offset < 0)
640 die(_("offset before end of packfile (broken .idx?)"));
642 if (!win || !in_window(win, offset)) {
643 if (win)
644 win->inuse_cnt--;
645 for (win = p->windows; win; win = win->next) {
646 if (in_window(win, offset))
647 break;
649 if (!win) {
650 size_t window_align = packed_git_window_size / 2;
651 off_t len;
653 if (p->pack_fd == -1 && open_packed_git(p))
654 die("packfile %s cannot be accessed", p->pack_name);
656 CALLOC_ARRAY(win, 1);
657 win->offset = (offset / window_align) * window_align;
658 len = p->pack_size - win->offset;
659 if (len > packed_git_window_size)
660 len = packed_git_window_size;
661 win->len = (size_t)len;
662 pack_mapped += win->len;
663 while (packed_git_limit < pack_mapped
664 && unuse_one_window(p))
665 ; /* nothing */
666 win->base = xmmap_gently(NULL, win->len,
667 PROT_READ, MAP_PRIVATE,
668 p->pack_fd, win->offset);
669 if (win->base == MAP_FAILED)
670 die_errno(_("packfile %s cannot be mapped%s"),
671 p->pack_name, mmap_os_err());
672 if (!win->offset && win->len == p->pack_size
673 && !p->do_not_close)
674 close_pack_fd(p);
675 pack_mmap_calls++;
676 pack_open_windows++;
677 if (pack_mapped > peak_pack_mapped)
678 peak_pack_mapped = pack_mapped;
679 if (pack_open_windows > peak_pack_open_windows)
680 peak_pack_open_windows = pack_open_windows;
681 win->next = p->windows;
682 p->windows = win;
685 if (win != *w_cursor) {
686 win->last_used = pack_used_ctr++;
687 win->inuse_cnt++;
688 *w_cursor = win;
690 offset -= win->offset;
691 if (left)
692 *left = win->len - xsize_t(offset);
693 return win->base + offset;
696 void unuse_pack(struct pack_window **w_cursor)
698 struct pack_window *w = *w_cursor;
699 if (w) {
700 w->inuse_cnt--;
701 *w_cursor = NULL;
705 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
707 struct stat st;
708 size_t alloc;
709 struct packed_git *p;
712 * Make sure a corresponding .pack file exists and that
713 * the index looks sane.
715 if (!strip_suffix_mem(path, &path_len, ".idx"))
716 return NULL;
719 * ".promisor" is long enough to hold any suffix we're adding (and
720 * the use xsnprintf double-checks that)
722 alloc = st_add3(path_len, strlen(".promisor"), 1);
723 p = alloc_packed_git(alloc);
724 memcpy(p->pack_name, path, path_len);
726 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
727 if (!access(p->pack_name, F_OK))
728 p->pack_keep = 1;
730 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
731 if (!access(p->pack_name, F_OK))
732 p->pack_promisor = 1;
734 xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
735 if (!access(p->pack_name, F_OK))
736 p->is_cruft = 1;
738 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
739 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
740 free(p);
741 return NULL;
744 /* ok, it looks sane as far as we can check without
745 * actually mapping the pack file.
747 p->pack_size = st.st_size;
748 p->pack_local = local;
749 p->mtime = st.st_mtime;
750 if (path_len < the_hash_algo->hexsz ||
751 get_sha1_hex(path + path_len - the_hash_algo->hexsz, p->hash))
752 hashclr(p->hash);
753 return p;
756 void install_packed_git(struct repository *r, struct packed_git *pack)
758 if (pack->pack_fd != -1)
759 pack_open_fds++;
761 pack->next = r->objects->packed_git;
762 r->objects->packed_git = pack;
764 hashmap_entry_init(&pack->packmap_ent, strhash(pack->pack_name));
765 hashmap_add(&r->objects->pack_map, &pack->packmap_ent);
768 void (*report_garbage)(unsigned seen_bits, const char *path);
770 static void report_helper(const struct string_list *list,
771 int seen_bits, int first, int last)
773 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
774 return;
776 for (; first < last; first++)
777 report_garbage(seen_bits, list->items[first].string);
780 static void report_pack_garbage(struct string_list *list)
782 int i, baselen = -1, first = 0, seen_bits = 0;
784 if (!report_garbage)
785 return;
787 string_list_sort(list);
789 for (i = 0; i < list->nr; i++) {
790 const char *path = list->items[i].string;
791 if (baselen != -1 &&
792 strncmp(path, list->items[first].string, baselen)) {
793 report_helper(list, seen_bits, first, i);
794 baselen = -1;
795 seen_bits = 0;
797 if (baselen == -1) {
798 const char *dot = strrchr(path, '.');
799 if (!dot) {
800 report_garbage(PACKDIR_FILE_GARBAGE, path);
801 continue;
803 baselen = dot - path + 1;
804 first = i;
806 if (!strcmp(path + baselen, "pack"))
807 seen_bits |= 1;
808 else if (!strcmp(path + baselen, "idx"))
809 seen_bits |= 2;
811 report_helper(list, seen_bits, first, list->nr);
814 void for_each_file_in_pack_dir(const char *objdir,
815 each_file_in_pack_dir_fn fn,
816 void *data)
818 struct strbuf path = STRBUF_INIT;
819 size_t dirnamelen;
820 DIR *dir;
821 struct dirent *de;
823 strbuf_addstr(&path, objdir);
824 strbuf_addstr(&path, "/pack");
825 dir = opendir(path.buf);
826 if (!dir) {
827 if (errno != ENOENT)
828 error_errno("unable to open object pack directory: %s",
829 path.buf);
830 strbuf_release(&path);
831 return;
833 strbuf_addch(&path, '/');
834 dirnamelen = path.len;
835 while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
836 strbuf_setlen(&path, dirnamelen);
837 strbuf_addstr(&path, de->d_name);
839 fn(path.buf, path.len, de->d_name, data);
842 closedir(dir);
843 strbuf_release(&path);
846 struct prepare_pack_data {
847 struct repository *r;
848 struct string_list *garbage;
849 int local;
850 struct multi_pack_index *m;
853 static void prepare_pack(const char *full_name, size_t full_name_len,
854 const char *file_name, void *_data)
856 struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
857 struct packed_git *p;
858 size_t base_len = full_name_len;
860 if (strip_suffix_mem(full_name, &base_len, ".idx") &&
861 !(data->m && midx_contains_pack(data->m, file_name))) {
862 struct hashmap_entry hent;
863 char *pack_name = xstrfmt("%.*s.pack", (int)base_len, full_name);
864 unsigned int hash = strhash(pack_name);
865 hashmap_entry_init(&hent, hash);
867 /* Don't reopen a pack we already have. */
868 if (!hashmap_get(&data->r->objects->pack_map, &hent, pack_name)) {
869 p = add_packed_git(full_name, full_name_len, data->local);
870 if (p)
871 install_packed_git(data->r, p);
873 free(pack_name);
876 if (!report_garbage)
877 return;
879 if (!strcmp(file_name, "multi-pack-index"))
880 return;
881 if (starts_with(file_name, "multi-pack-index") &&
882 (ends_with(file_name, ".bitmap") || ends_with(file_name, ".rev")))
883 return;
884 if (ends_with(file_name, ".idx") ||
885 ends_with(file_name, ".rev") ||
886 ends_with(file_name, ".pack") ||
887 ends_with(file_name, ".bitmap") ||
888 ends_with(file_name, ".keep") ||
889 ends_with(file_name, ".promisor") ||
890 ends_with(file_name, ".mtimes"))
891 string_list_append(data->garbage, full_name);
892 else
893 report_garbage(PACKDIR_FILE_GARBAGE, full_name);
896 static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
898 struct prepare_pack_data data;
899 struct string_list garbage = STRING_LIST_INIT_DUP;
901 data.m = r->objects->multi_pack_index;
903 /* look for the multi-pack-index for this object directory */
904 while (data.m && strcmp(data.m->object_dir, objdir))
905 data.m = data.m->next;
907 data.r = r;
908 data.garbage = &garbage;
909 data.local = local;
911 for_each_file_in_pack_dir(objdir, prepare_pack, &data);
913 report_pack_garbage(data.garbage);
914 string_list_clear(data.garbage, 0);
917 static void prepare_packed_git(struct repository *r);
919 * Give a fast, rough count of the number of objects in the repository. This
920 * ignores loose objects completely. If you have a lot of them, then either
921 * you should repack because your performance will be awful, or they are
922 * all unreachable objects about to be pruned, in which case they're not really
923 * interesting as a measure of repo size in the first place.
925 unsigned long repo_approximate_object_count(struct repository *r)
927 if (!r->objects->approximate_object_count_valid) {
928 unsigned long count;
929 struct multi_pack_index *m;
930 struct packed_git *p;
932 prepare_packed_git(r);
933 count = 0;
934 for (m = get_multi_pack_index(r); m; m = m->next)
935 count += m->num_objects;
936 for (p = r->objects->packed_git; p; p = p->next) {
937 if (open_pack_index(p))
938 continue;
939 count += p->num_objects;
941 r->objects->approximate_object_count = count;
942 r->objects->approximate_object_count_valid = 1;
944 return r->objects->approximate_object_count;
947 DEFINE_LIST_SORT(static, sort_packs, struct packed_git, next);
949 static int sort_pack(const struct packed_git *a, const struct packed_git *b)
951 int st;
954 * Local packs tend to contain objects specific to our
955 * variant of the project than remote ones. In addition,
956 * remote ones could be on a network mounted filesystem.
957 * Favor local ones for these reasons.
959 st = a->pack_local - b->pack_local;
960 if (st)
961 return -st;
964 * Younger packs tend to contain more recent objects,
965 * and more recent objects tend to get accessed more
966 * often.
968 if (a->mtime < b->mtime)
969 return 1;
970 else if (a->mtime == b->mtime)
971 return 0;
972 return -1;
975 static void rearrange_packed_git(struct repository *r)
977 sort_packs(&r->objects->packed_git, sort_pack);
980 static void prepare_packed_git_mru(struct repository *r)
982 struct packed_git *p;
984 INIT_LIST_HEAD(&r->objects->packed_git_mru);
986 for (p = r->objects->packed_git; p; p = p->next)
987 list_add_tail(&p->mru, &r->objects->packed_git_mru);
990 static void prepare_packed_git(struct repository *r)
992 struct object_directory *odb;
994 if (r->objects->packed_git_initialized)
995 return;
997 prepare_alt_odb(r);
998 for (odb = r->objects->odb; odb; odb = odb->next) {
999 int local = (odb == r->objects->odb);
1000 prepare_multi_pack_index_one(r, odb->path, local);
1001 prepare_packed_git_one(r, odb->path, local);
1003 rearrange_packed_git(r);
1005 prepare_packed_git_mru(r);
1006 r->objects->packed_git_initialized = 1;
1009 void reprepare_packed_git(struct repository *r)
1011 struct object_directory *odb;
1013 obj_read_lock();
1016 * Reprepare alt odbs, in case the alternates file was modified
1017 * during the course of this process. This only _adds_ odbs to
1018 * the linked list, so existing odbs will continue to exist for
1019 * the lifetime of the process.
1021 r->objects->loaded_alternates = 0;
1022 prepare_alt_odb(r);
1024 for (odb = r->objects->odb; odb; odb = odb->next)
1025 odb_clear_loose_cache(odb);
1027 r->objects->approximate_object_count_valid = 0;
1028 r->objects->packed_git_initialized = 0;
1029 prepare_packed_git(r);
1030 obj_read_unlock();
1033 struct packed_git *get_packed_git(struct repository *r)
1035 prepare_packed_git(r);
1036 return r->objects->packed_git;
1039 struct multi_pack_index *get_multi_pack_index(struct repository *r)
1041 prepare_packed_git(r);
1042 return r->objects->multi_pack_index;
1045 struct multi_pack_index *get_local_multi_pack_index(struct repository *r)
1047 struct multi_pack_index *m = get_multi_pack_index(r);
1049 /* no need to iterate; we always put the local one first (if any) */
1050 if (m && m->local)
1051 return m;
1053 return NULL;
1056 struct packed_git *get_all_packs(struct repository *r)
1058 struct multi_pack_index *m;
1060 prepare_packed_git(r);
1061 for (m = r->objects->multi_pack_index; m; m = m->next) {
1062 uint32_t i;
1063 for (i = 0; i < m->num_packs; i++)
1064 prepare_midx_pack(r, m, i);
1067 return r->objects->packed_git;
1070 struct list_head *get_packed_git_mru(struct repository *r)
1072 prepare_packed_git(r);
1073 return &r->objects->packed_git_mru;
1076 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1077 unsigned long len, enum object_type *type, unsigned long *sizep)
1079 unsigned shift;
1080 size_t size, c;
1081 unsigned long used = 0;
1083 c = buf[used++];
1084 *type = (c >> 4) & 7;
1085 size = c & 15;
1086 shift = 4;
1087 while (c & 0x80) {
1088 if (len <= used || (bitsizeof(long) - 7) < shift) {
1089 error("bad object header");
1090 size = used = 0;
1091 break;
1093 c = buf[used++];
1094 size = st_add(size, st_left_shift(c & 0x7f, shift));
1095 shift += 7;
1097 *sizep = cast_size_t_to_ulong(size);
1098 return used;
1101 unsigned long get_size_from_delta(struct packed_git *p,
1102 struct pack_window **w_curs,
1103 off_t curpos)
1105 const unsigned char *data;
1106 unsigned char delta_head[20], *in;
1107 git_zstream stream;
1108 int st;
1110 memset(&stream, 0, sizeof(stream));
1111 stream.next_out = delta_head;
1112 stream.avail_out = sizeof(delta_head);
1114 git_inflate_init(&stream);
1115 do {
1116 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1117 stream.next_in = in;
1119 * Note: the window section returned by use_pack() must be
1120 * available throughout git_inflate()'s unlocked execution. To
1121 * ensure no other thread will modify the window in the
1122 * meantime, we rely on the packed_window.inuse_cnt. This
1123 * counter is incremented before window reading and checked
1124 * before window disposal.
1126 * Other worrying sections could be the call to close_pack_fd(),
1127 * which can close packs even with in-use windows, and to
1128 * reprepare_packed_git(). Regarding the former, mmap doc says:
1129 * "closing the file descriptor does not unmap the region". And
1130 * for the latter, it won't re-open already available packs.
1132 obj_read_unlock();
1133 st = git_inflate(&stream, Z_FINISH);
1134 obj_read_lock();
1135 curpos += stream.next_in - in;
1136 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1137 stream.total_out < sizeof(delta_head));
1138 git_inflate_end(&stream);
1139 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1140 error("delta data unpack-initial failed");
1141 return 0;
1144 /* Examine the initial part of the delta to figure out
1145 * the result size.
1147 data = delta_head;
1149 /* ignore base size */
1150 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1152 /* Read the result size */
1153 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1156 int unpack_object_header(struct packed_git *p,
1157 struct pack_window **w_curs,
1158 off_t *curpos,
1159 unsigned long *sizep)
1161 unsigned char *base;
1162 unsigned long left;
1163 unsigned long used;
1164 enum object_type type;
1166 /* use_pack() assures us we have [base, base + 20) available
1167 * as a range that we can look at. (Its actually the hash
1168 * size that is assured.) With our object header encoding
1169 * the maximum deflated object size is 2^137, which is just
1170 * insane, so we know won't exceed what we have been given.
1172 base = use_pack(p, w_curs, *curpos, &left);
1173 used = unpack_object_header_buffer(base, left, &type, sizep);
1174 if (!used) {
1175 type = OBJ_BAD;
1176 } else
1177 *curpos += used;
1179 return type;
1182 void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
1184 oidset_insert(&p->bad_objects, oid);
1187 const struct packed_git *has_packed_and_bad(struct repository *r,
1188 const struct object_id *oid)
1190 struct packed_git *p;
1192 for (p = r->objects->packed_git; p; p = p->next)
1193 if (oidset_contains(&p->bad_objects, oid))
1194 return p;
1195 return NULL;
1198 off_t get_delta_base(struct packed_git *p,
1199 struct pack_window **w_curs,
1200 off_t *curpos,
1201 enum object_type type,
1202 off_t delta_obj_offset)
1204 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1205 off_t base_offset;
1207 /* use_pack() assured us we have [base_info, base_info + 20)
1208 * as a range that we can look at without walking off the
1209 * end of the mapped window. Its actually the hash size
1210 * that is assured. An OFS_DELTA longer than the hash size
1211 * is stupid, as then a REF_DELTA would be smaller to store.
1213 if (type == OBJ_OFS_DELTA) {
1214 unsigned used = 0;
1215 unsigned char c = base_info[used++];
1216 base_offset = c & 127;
1217 while (c & 128) {
1218 base_offset += 1;
1219 if (!base_offset || MSB(base_offset, 7))
1220 return 0; /* overflow */
1221 c = base_info[used++];
1222 base_offset = (base_offset << 7) + (c & 127);
1224 base_offset = delta_obj_offset - base_offset;
1225 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1226 return 0; /* out of bound */
1227 *curpos += used;
1228 } else if (type == OBJ_REF_DELTA) {
1229 /* The base entry _must_ be in the same pack */
1230 base_offset = find_pack_entry_one(base_info, p);
1231 *curpos += the_hash_algo->rawsz;
1232 } else
1233 die("I am totally screwed");
1234 return base_offset;
1238 * Like get_delta_base above, but we return the sha1 instead of the pack
1239 * offset. This means it is cheaper for REF deltas (we do not have to do
1240 * the final object lookup), but more expensive for OFS deltas (we
1241 * have to load the revidx to convert the offset back into a sha1).
1243 static int get_delta_base_oid(struct packed_git *p,
1244 struct pack_window **w_curs,
1245 off_t curpos,
1246 struct object_id *oid,
1247 enum object_type type,
1248 off_t delta_obj_offset)
1250 if (type == OBJ_REF_DELTA) {
1251 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1252 oidread(oid, base);
1253 return 0;
1254 } else if (type == OBJ_OFS_DELTA) {
1255 uint32_t base_pos;
1256 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1257 type, delta_obj_offset);
1259 if (!base_offset)
1260 return -1;
1262 if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1263 return -1;
1265 return nth_packed_object_id(oid, p,
1266 pack_pos_to_index(p, base_pos));
1267 } else
1268 return -1;
1271 static int retry_bad_packed_offset(struct repository *r,
1272 struct packed_git *p,
1273 off_t obj_offset)
1275 int type;
1276 uint32_t pos;
1277 struct object_id oid;
1278 if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1279 return OBJ_BAD;
1280 nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1281 mark_bad_packed_object(p, &oid);
1282 type = oid_object_info(r, &oid, NULL);
1283 if (type <= OBJ_NONE)
1284 return OBJ_BAD;
1285 return type;
1288 #define POI_STACK_PREALLOC 64
1290 static enum object_type packed_to_object_type(struct repository *r,
1291 struct packed_git *p,
1292 off_t obj_offset,
1293 enum object_type type,
1294 struct pack_window **w_curs,
1295 off_t curpos)
1297 off_t small_poi_stack[POI_STACK_PREALLOC];
1298 off_t *poi_stack = small_poi_stack;
1299 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1301 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1302 off_t base_offset;
1303 unsigned long size;
1304 /* Push the object we're going to leave behind */
1305 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1306 poi_stack_alloc = alloc_nr(poi_stack_nr);
1307 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1308 COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1309 } else {
1310 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1312 poi_stack[poi_stack_nr++] = obj_offset;
1313 /* If parsing the base offset fails, just unwind */
1314 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1315 if (!base_offset)
1316 goto unwind;
1317 curpos = obj_offset = base_offset;
1318 type = unpack_object_header(p, w_curs, &curpos, &size);
1319 if (type <= OBJ_NONE) {
1320 /* If getting the base itself fails, we first
1321 * retry the base, otherwise unwind */
1322 type = retry_bad_packed_offset(r, p, base_offset);
1323 if (type > OBJ_NONE)
1324 goto out;
1325 goto unwind;
1329 switch (type) {
1330 case OBJ_BAD:
1331 case OBJ_COMMIT:
1332 case OBJ_TREE:
1333 case OBJ_BLOB:
1334 case OBJ_TAG:
1335 break;
1336 default:
1337 error("unknown object type %i at offset %"PRIuMAX" in %s",
1338 type, (uintmax_t)obj_offset, p->pack_name);
1339 type = OBJ_BAD;
1342 out:
1343 if (poi_stack != small_poi_stack)
1344 free(poi_stack);
1345 return type;
1347 unwind:
1348 while (poi_stack_nr) {
1349 obj_offset = poi_stack[--poi_stack_nr];
1350 type = retry_bad_packed_offset(r, p, obj_offset);
1351 if (type > OBJ_NONE)
1352 goto out;
1354 type = OBJ_BAD;
1355 goto out;
1358 static struct hashmap delta_base_cache;
1359 static size_t delta_base_cached;
1361 static LIST_HEAD(delta_base_cache_lru);
1363 struct delta_base_cache_key {
1364 struct packed_git *p;
1365 off_t base_offset;
1368 struct delta_base_cache_entry {
1369 struct hashmap_entry ent;
1370 struct delta_base_cache_key key;
1371 struct list_head lru;
1372 void *data;
1373 unsigned long size;
1374 enum object_type type;
1377 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1379 unsigned int hash;
1381 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1382 hash += (hash >> 8) + (hash >> 16);
1383 return hash;
1386 static struct delta_base_cache_entry *
1387 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1389 struct hashmap_entry entry, *e;
1390 struct delta_base_cache_key key;
1392 if (!delta_base_cache.cmpfn)
1393 return NULL;
1395 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1396 key.p = p;
1397 key.base_offset = base_offset;
1398 e = hashmap_get(&delta_base_cache, &entry, &key);
1399 return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1402 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1403 const struct delta_base_cache_key *b)
1405 return a->p == b->p && a->base_offset == b->base_offset;
1408 static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1409 const struct hashmap_entry *va,
1410 const struct hashmap_entry *vb,
1411 const void *vkey)
1413 const struct delta_base_cache_entry *a, *b;
1414 const struct delta_base_cache_key *key = vkey;
1416 a = container_of(va, const struct delta_base_cache_entry, ent);
1417 b = container_of(vb, const struct delta_base_cache_entry, ent);
1419 if (key)
1420 return !delta_base_cache_key_eq(&a->key, key);
1421 else
1422 return !delta_base_cache_key_eq(&a->key, &b->key);
1425 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1427 return !!get_delta_base_cache_entry(p, base_offset);
1431 * Remove the entry from the cache, but do _not_ free the associated
1432 * entry data. The caller takes ownership of the "data" buffer, and
1433 * should copy out any fields it wants before detaching.
1435 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1437 hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1438 list_del(&ent->lru);
1439 delta_base_cached -= ent->size;
1440 free(ent);
1443 static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1444 off_t base_offset, unsigned long *base_size,
1445 enum object_type *type)
1447 struct delta_base_cache_entry *ent;
1449 ent = get_delta_base_cache_entry(p, base_offset);
1450 if (!ent)
1451 return unpack_entry(r, p, base_offset, type, base_size);
1453 if (type)
1454 *type = ent->type;
1455 if (base_size)
1456 *base_size = ent->size;
1457 return xmemdupz(ent->data, ent->size);
1460 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1462 free(ent->data);
1463 detach_delta_base_cache_entry(ent);
1466 void clear_delta_base_cache(void)
1468 struct list_head *lru, *tmp;
1469 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1470 struct delta_base_cache_entry *entry =
1471 list_entry(lru, struct delta_base_cache_entry, lru);
1472 release_delta_base_cache(entry);
1476 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1477 void *base, unsigned long base_size, enum object_type type)
1479 struct delta_base_cache_entry *ent;
1480 struct list_head *lru, *tmp;
1483 * Check required to avoid redundant entries when more than one thread
1484 * is unpacking the same object, in unpack_entry() (since its phases I
1485 * and III might run concurrently across multiple threads).
1487 if (in_delta_base_cache(p, base_offset)) {
1488 free(base);
1489 return;
1492 delta_base_cached += base_size;
1494 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1495 struct delta_base_cache_entry *f =
1496 list_entry(lru, struct delta_base_cache_entry, lru);
1497 if (delta_base_cached <= delta_base_cache_limit)
1498 break;
1499 release_delta_base_cache(f);
1502 ent = xmalloc(sizeof(*ent));
1503 ent->key.p = p;
1504 ent->key.base_offset = base_offset;
1505 ent->type = type;
1506 ent->data = base;
1507 ent->size = base_size;
1508 list_add_tail(&ent->lru, &delta_base_cache_lru);
1510 if (!delta_base_cache.cmpfn)
1511 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1512 hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1513 hashmap_add(&delta_base_cache, &ent->ent);
1516 int packed_object_info(struct repository *r, struct packed_git *p,
1517 off_t obj_offset, struct object_info *oi)
1519 struct pack_window *w_curs = NULL;
1520 unsigned long size;
1521 off_t curpos = obj_offset;
1522 enum object_type type;
1525 * We always get the representation type, but only convert it to
1526 * a "real" type later if the caller is interested.
1528 if (oi->contentp) {
1529 *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1530 &type);
1531 if (!*oi->contentp)
1532 type = OBJ_BAD;
1533 } else {
1534 type = unpack_object_header(p, &w_curs, &curpos, &size);
1537 if (!oi->contentp && oi->sizep) {
1538 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1539 off_t tmp_pos = curpos;
1540 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1541 type, obj_offset);
1542 if (!base_offset) {
1543 type = OBJ_BAD;
1544 goto out;
1546 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1547 if (*oi->sizep == 0) {
1548 type = OBJ_BAD;
1549 goto out;
1551 } else {
1552 *oi->sizep = size;
1556 if (oi->disk_sizep) {
1557 uint32_t pos;
1558 if (offset_to_pack_pos(p, obj_offset, &pos) < 0) {
1559 error("could not find object at offset %"PRIuMAX" "
1560 "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1561 type = OBJ_BAD;
1562 goto out;
1565 *oi->disk_sizep = pack_pos_to_offset(p, pos + 1) - obj_offset;
1568 if (oi->typep || oi->type_name) {
1569 enum object_type ptot;
1570 ptot = packed_to_object_type(r, p, obj_offset,
1571 type, &w_curs, curpos);
1572 if (oi->typep)
1573 *oi->typep = ptot;
1574 if (oi->type_name) {
1575 const char *tn = type_name(ptot);
1576 if (tn)
1577 strbuf_addstr(oi->type_name, tn);
1579 if (ptot < 0) {
1580 type = OBJ_BAD;
1581 goto out;
1585 if (oi->delta_base_oid) {
1586 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1587 if (get_delta_base_oid(p, &w_curs, curpos,
1588 oi->delta_base_oid,
1589 type, obj_offset) < 0) {
1590 type = OBJ_BAD;
1591 goto out;
1593 } else
1594 oidclr(oi->delta_base_oid);
1597 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1598 OI_PACKED;
1600 out:
1601 unuse_pack(&w_curs);
1602 return type;
1605 static void *unpack_compressed_entry(struct packed_git *p,
1606 struct pack_window **w_curs,
1607 off_t curpos,
1608 unsigned long size)
1610 int st;
1611 git_zstream stream;
1612 unsigned char *buffer, *in;
1614 buffer = xmallocz_gently(size);
1615 if (!buffer)
1616 return NULL;
1617 memset(&stream, 0, sizeof(stream));
1618 stream.next_out = buffer;
1619 stream.avail_out = size + 1;
1621 git_inflate_init(&stream);
1622 do {
1623 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1624 stream.next_in = in;
1626 * Note: we must ensure the window section returned by
1627 * use_pack() will be available throughout git_inflate()'s
1628 * unlocked execution. Please refer to the comment at
1629 * get_size_from_delta() to see how this is done.
1631 obj_read_unlock();
1632 st = git_inflate(&stream, Z_FINISH);
1633 obj_read_lock();
1634 if (!stream.avail_out)
1635 break; /* the payload is larger than it should be */
1636 curpos += stream.next_in - in;
1637 } while (st == Z_OK || st == Z_BUF_ERROR);
1638 git_inflate_end(&stream);
1639 if ((st != Z_STREAM_END) || stream.total_out != size) {
1640 free(buffer);
1641 return NULL;
1644 /* versions of zlib can clobber unconsumed portion of outbuf */
1645 buffer[size] = '\0';
1647 return buffer;
1650 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1652 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1653 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1654 p->pack_name, (uintmax_t)obj_offset);
1657 int do_check_packed_object_crc;
1659 #define UNPACK_ENTRY_STACK_PREALLOC 64
1660 struct unpack_entry_stack_ent {
1661 off_t obj_offset;
1662 off_t curpos;
1663 unsigned long size;
1666 void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1667 enum object_type *final_type, unsigned long *final_size)
1669 struct pack_window *w_curs = NULL;
1670 off_t curpos = obj_offset;
1671 void *data = NULL;
1672 unsigned long size;
1673 enum object_type type;
1674 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1675 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1676 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1677 int base_from_cache = 0;
1679 write_pack_access_log(p, obj_offset);
1681 /* PHASE 1: drill down to the innermost base object */
1682 for (;;) {
1683 off_t base_offset;
1684 int i;
1685 struct delta_base_cache_entry *ent;
1687 ent = get_delta_base_cache_entry(p, curpos);
1688 if (ent) {
1689 type = ent->type;
1690 data = ent->data;
1691 size = ent->size;
1692 detach_delta_base_cache_entry(ent);
1693 base_from_cache = 1;
1694 break;
1697 if (do_check_packed_object_crc && p->index_version > 1) {
1698 uint32_t pack_pos, index_pos;
1699 off_t len;
1701 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1702 error("could not find object at offset %"PRIuMAX" in pack %s",
1703 (uintmax_t)obj_offset, p->pack_name);
1704 data = NULL;
1705 goto out;
1708 len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1709 index_pos = pack_pos_to_index(p, pack_pos);
1710 if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1711 struct object_id oid;
1712 nth_packed_object_id(&oid, p, index_pos);
1713 error("bad packed object CRC for %s",
1714 oid_to_hex(&oid));
1715 mark_bad_packed_object(p, &oid);
1716 data = NULL;
1717 goto out;
1721 type = unpack_object_header(p, &w_curs, &curpos, &size);
1722 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1723 break;
1725 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1726 if (!base_offset) {
1727 error("failed to validate delta base reference "
1728 "at offset %"PRIuMAX" from %s",
1729 (uintmax_t)curpos, p->pack_name);
1730 /* bail to phase 2, in hopes of recovery */
1731 data = NULL;
1732 break;
1735 /* push object, proceed to base */
1736 if (delta_stack_nr >= delta_stack_alloc
1737 && delta_stack == small_delta_stack) {
1738 delta_stack_alloc = alloc_nr(delta_stack_nr);
1739 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1740 COPY_ARRAY(delta_stack, small_delta_stack,
1741 delta_stack_nr);
1742 } else {
1743 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1745 i = delta_stack_nr++;
1746 delta_stack[i].obj_offset = obj_offset;
1747 delta_stack[i].curpos = curpos;
1748 delta_stack[i].size = size;
1750 curpos = obj_offset = base_offset;
1753 /* PHASE 2: handle the base */
1754 switch (type) {
1755 case OBJ_OFS_DELTA:
1756 case OBJ_REF_DELTA:
1757 if (data)
1758 BUG("unpack_entry: left loop at a valid delta");
1759 break;
1760 case OBJ_COMMIT:
1761 case OBJ_TREE:
1762 case OBJ_BLOB:
1763 case OBJ_TAG:
1764 if (!base_from_cache)
1765 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1766 break;
1767 default:
1768 data = NULL;
1769 error("unknown object type %i at offset %"PRIuMAX" in %s",
1770 type, (uintmax_t)obj_offset, p->pack_name);
1773 /* PHASE 3: apply deltas in order */
1775 /* invariants:
1776 * 'data' holds the base data, or NULL if there was corruption
1778 while (delta_stack_nr) {
1779 void *delta_data;
1780 void *base = data;
1781 void *external_base = NULL;
1782 unsigned long delta_size, base_size = size;
1783 int i;
1784 off_t base_obj_offset = obj_offset;
1786 data = NULL;
1788 if (!base) {
1790 * We're probably in deep shit, but let's try to fetch
1791 * the required base anyway from another pack or loose.
1792 * This is costly but should happen only in the presence
1793 * of a corrupted pack, and is better than failing outright.
1795 uint32_t pos;
1796 struct object_id base_oid;
1797 if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1798 struct object_info oi = OBJECT_INFO_INIT;
1800 nth_packed_object_id(&base_oid, p,
1801 pack_pos_to_index(p, pos));
1802 error("failed to read delta base object %s"
1803 " at offset %"PRIuMAX" from %s",
1804 oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1805 p->pack_name);
1806 mark_bad_packed_object(p, &base_oid);
1808 oi.typep = &type;
1809 oi.sizep = &base_size;
1810 oi.contentp = &base;
1811 if (oid_object_info_extended(r, &base_oid, &oi, 0) < 0)
1812 base = NULL;
1814 external_base = base;
1818 i = --delta_stack_nr;
1819 obj_offset = delta_stack[i].obj_offset;
1820 curpos = delta_stack[i].curpos;
1821 delta_size = delta_stack[i].size;
1823 if (!base)
1824 continue;
1826 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1828 if (!delta_data) {
1829 error("failed to unpack compressed delta "
1830 "at offset %"PRIuMAX" from %s",
1831 (uintmax_t)curpos, p->pack_name);
1832 data = NULL;
1833 } else {
1834 data = patch_delta(base, base_size, delta_data,
1835 delta_size, &size);
1838 * We could not apply the delta; warn the user, but
1839 * keep going. Our failure will be noticed either in
1840 * the next iteration of the loop, or if this is the
1841 * final delta, in the caller when we return NULL.
1842 * Those code paths will take care of making a more
1843 * explicit warning and retrying with another copy of
1844 * the object.
1846 if (!data)
1847 error("failed to apply delta");
1851 * We delay adding `base` to the cache until the end of the loop
1852 * because unpack_compressed_entry() momentarily releases the
1853 * obj_read_mutex, giving another thread the chance to access
1854 * the cache. Therefore, if `base` was already there, this other
1855 * thread could free() it (e.g. to make space for another entry)
1856 * before we are done using it.
1858 if (!external_base)
1859 add_delta_base_cache(p, base_obj_offset, base, base_size, type);
1861 free(delta_data);
1862 free(external_base);
1865 if (final_type)
1866 *final_type = type;
1867 if (final_size)
1868 *final_size = size;
1870 out:
1871 unuse_pack(&w_curs);
1873 if (delta_stack != small_delta_stack)
1874 free(delta_stack);
1876 return data;
1879 int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1881 const unsigned char *index_fanout = p->index_data;
1882 const unsigned char *index_lookup;
1883 const unsigned int hashsz = the_hash_algo->rawsz;
1884 int index_lookup_width;
1886 if (!index_fanout)
1887 BUG("bsearch_pack called without a valid pack-index");
1889 index_lookup = index_fanout + 4 * 256;
1890 if (p->index_version == 1) {
1891 index_lookup_width = hashsz + 4;
1892 index_lookup += 4;
1893 } else {
1894 index_lookup_width = hashsz;
1895 index_fanout += 8;
1896 index_lookup += 8;
1899 return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1900 index_lookup, index_lookup_width, result);
1903 int nth_packed_object_id(struct object_id *oid,
1904 struct packed_git *p,
1905 uint32_t n)
1907 const unsigned char *index = p->index_data;
1908 const unsigned int hashsz = the_hash_algo->rawsz;
1909 if (!index) {
1910 if (open_pack_index(p))
1911 return -1;
1912 index = p->index_data;
1914 if (n >= p->num_objects)
1915 return -1;
1916 index += 4 * 256;
1917 if (p->index_version == 1) {
1918 oidread(oid, index + (hashsz + 4) * n + 4);
1919 } else {
1920 index += 8;
1921 oidread(oid, index + hashsz * n);
1923 return 0;
1926 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1928 const unsigned char *ptr = vptr;
1929 const unsigned char *start = p->index_data;
1930 const unsigned char *end = start + p->index_size;
1931 if (ptr < start)
1932 die(_("offset before start of pack index for %s (corrupt index?)"),
1933 p->pack_name);
1934 /* No need to check for underflow; .idx files must be at least 8 bytes */
1935 if (ptr >= end - 8)
1936 die(_("offset beyond end of pack index for %s (truncated index?)"),
1937 p->pack_name);
1940 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1942 const unsigned char *index = p->index_data;
1943 const unsigned int hashsz = the_hash_algo->rawsz;
1944 index += 4 * 256;
1945 if (p->index_version == 1) {
1946 return ntohl(*((uint32_t *)(index + (hashsz + 4) * (size_t)n)));
1947 } else {
1948 uint32_t off;
1949 index += 8 + (size_t)p->num_objects * (hashsz + 4);
1950 off = ntohl(*((uint32_t *)(index + 4 * n)));
1951 if (!(off & 0x80000000))
1952 return off;
1953 index += (size_t)p->num_objects * 4 + (off & 0x7fffffff) * 8;
1954 check_pack_index_ptr(p, index);
1955 return get_be64(index);
1959 off_t find_pack_entry_one(const unsigned char *sha1,
1960 struct packed_git *p)
1962 const unsigned char *index = p->index_data;
1963 struct object_id oid;
1964 uint32_t result;
1966 if (!index) {
1967 if (open_pack_index(p))
1968 return 0;
1971 hashcpy(oid.hash, sha1);
1972 if (bsearch_pack(&oid, p, &result))
1973 return nth_packed_object_offset(p, result);
1974 return 0;
1977 int is_pack_valid(struct packed_git *p)
1979 /* An already open pack is known to be valid. */
1980 if (p->pack_fd != -1)
1981 return 1;
1983 /* If the pack has one window completely covering the
1984 * file size, the pack is known to be valid even if
1985 * the descriptor is not currently open.
1987 if (p->windows) {
1988 struct pack_window *w = p->windows;
1990 if (!w->offset && w->len == p->pack_size)
1991 return 1;
1994 /* Force the pack to open to prove its valid. */
1995 return !open_packed_git(p);
1998 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1999 struct packed_git *packs)
2001 struct packed_git *p;
2003 for (p = packs; p; p = p->next) {
2004 if (find_pack_entry_one(sha1, p))
2005 return p;
2007 return NULL;
2011 static int fill_pack_entry(const struct object_id *oid,
2012 struct pack_entry *e,
2013 struct packed_git *p)
2015 off_t offset;
2017 if (oidset_size(&p->bad_objects) &&
2018 oidset_contains(&p->bad_objects, oid))
2019 return 0;
2021 offset = find_pack_entry_one(oid->hash, p);
2022 if (!offset)
2023 return 0;
2026 * We are about to tell the caller where they can locate the
2027 * requested object. We better make sure the packfile is
2028 * still here and can be accessed before supplying that
2029 * answer, as it may have been deleted since the index was
2030 * loaded!
2032 if (!is_pack_valid(p))
2033 return 0;
2034 e->offset = offset;
2035 e->p = p;
2036 return 1;
2039 int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
2041 struct list_head *pos;
2042 struct multi_pack_index *m;
2044 prepare_packed_git(r);
2045 if (!r->objects->packed_git && !r->objects->multi_pack_index)
2046 return 0;
2048 for (m = r->objects->multi_pack_index; m; m = m->next) {
2049 if (fill_midx_entry(r, oid, e, m))
2050 return 1;
2053 list_for_each(pos, &r->objects->packed_git_mru) {
2054 struct packed_git *p = list_entry(pos, struct packed_git, mru);
2055 if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
2056 list_move(&p->mru, &r->objects->packed_git_mru);
2057 return 1;
2060 return 0;
2063 static void maybe_invalidate_kept_pack_cache(struct repository *r,
2064 unsigned flags)
2066 if (!r->objects->kept_pack_cache.packs)
2067 return;
2068 if (r->objects->kept_pack_cache.flags == flags)
2069 return;
2070 FREE_AND_NULL(r->objects->kept_pack_cache.packs);
2071 r->objects->kept_pack_cache.flags = 0;
2074 static struct packed_git **kept_pack_cache(struct repository *r, unsigned flags)
2076 maybe_invalidate_kept_pack_cache(r, flags);
2078 if (!r->objects->kept_pack_cache.packs) {
2079 struct packed_git **packs = NULL;
2080 size_t nr = 0, alloc = 0;
2081 struct packed_git *p;
2084 * We want "all" packs here, because we need to cover ones that
2085 * are used by a midx, as well. We need to look in every one of
2086 * them (instead of the midx itself) to cover duplicates. It's
2087 * possible that an object is found in two packs that the midx
2088 * covers, one kept and one not kept, but the midx returns only
2089 * the non-kept version.
2091 for (p = get_all_packs(r); p; p = p->next) {
2092 if ((p->pack_keep && (flags & ON_DISK_KEEP_PACKS)) ||
2093 (p->pack_keep_in_core && (flags & IN_CORE_KEEP_PACKS))) {
2094 ALLOC_GROW(packs, nr + 1, alloc);
2095 packs[nr++] = p;
2098 ALLOC_GROW(packs, nr + 1, alloc);
2099 packs[nr] = NULL;
2101 r->objects->kept_pack_cache.packs = packs;
2102 r->objects->kept_pack_cache.flags = flags;
2105 return r->objects->kept_pack_cache.packs;
2108 int find_kept_pack_entry(struct repository *r,
2109 const struct object_id *oid,
2110 unsigned flags,
2111 struct pack_entry *e)
2113 struct packed_git **cache;
2115 for (cache = kept_pack_cache(r, flags); *cache; cache++) {
2116 struct packed_git *p = *cache;
2117 if (fill_pack_entry(oid, e, p))
2118 return 1;
2121 return 0;
2124 int has_object_pack(const struct object_id *oid)
2126 struct pack_entry e;
2127 return find_pack_entry(the_repository, oid, &e);
2130 int has_object_kept_pack(const struct object_id *oid, unsigned flags)
2132 struct pack_entry e;
2133 return find_kept_pack_entry(the_repository, oid, flags, &e);
2136 int has_pack_index(const unsigned char *sha1)
2138 struct stat st;
2139 if (stat(sha1_pack_index_name(sha1), &st))
2140 return 0;
2141 return 1;
2144 int for_each_object_in_pack(struct packed_git *p,
2145 each_packed_object_fn cb, void *data,
2146 enum for_each_object_flags flags)
2148 uint32_t i;
2149 int r = 0;
2151 if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2152 if (load_pack_revindex(p))
2153 return -1;
2156 for (i = 0; i < p->num_objects; i++) {
2157 uint32_t index_pos;
2158 struct object_id oid;
2161 * We are iterating "i" from 0 up to num_objects, but its
2162 * meaning may be different, depending on the requested output
2163 * order:
2165 * - in object-name order, it is the same as the index order
2166 * used by nth_packed_object_id(), so we can pass it
2167 * directly
2169 * - in pack-order, it is pack position, which we must
2170 * convert to an index position in order to get the oid.
2172 if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2173 index_pos = pack_pos_to_index(p, i);
2174 else
2175 index_pos = i;
2177 if (nth_packed_object_id(&oid, p, index_pos) < 0)
2178 return error("unable to get sha1 of object %u in %s",
2179 index_pos, p->pack_name);
2181 r = cb(&oid, p, index_pos, data);
2182 if (r)
2183 break;
2185 return r;
2188 int for_each_packed_object(each_packed_object_fn cb, void *data,
2189 enum for_each_object_flags flags)
2191 struct packed_git *p;
2192 int r = 0;
2193 int pack_errors = 0;
2195 prepare_packed_git(the_repository);
2196 for (p = get_all_packs(the_repository); p; p = p->next) {
2197 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2198 continue;
2199 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2200 !p->pack_promisor)
2201 continue;
2202 if ((flags & FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS) &&
2203 p->pack_keep_in_core)
2204 continue;
2205 if ((flags & FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS) &&
2206 p->pack_keep)
2207 continue;
2208 if (open_pack_index(p)) {
2209 pack_errors = 1;
2210 continue;
2212 r = for_each_object_in_pack(p, cb, data, flags);
2213 if (r)
2214 break;
2216 return r ? r : pack_errors;
2219 static int add_promisor_object(const struct object_id *oid,
2220 struct packed_git *pack UNUSED,
2221 uint32_t pos UNUSED,
2222 void *set_)
2224 struct oidset *set = set_;
2225 struct object *obj;
2226 int we_parsed_object;
2228 obj = lookup_object(the_repository, oid);
2229 if (obj && obj->parsed) {
2230 we_parsed_object = 0;
2231 } else {
2232 we_parsed_object = 1;
2233 obj = parse_object(the_repository, oid);
2236 if (!obj)
2237 return 1;
2239 oidset_insert(set, oid);
2242 * If this is a tree, commit, or tag, the objects it refers
2243 * to are also promisor objects. (Blobs refer to no objects->)
2245 if (obj->type == OBJ_TREE) {
2246 struct tree *tree = (struct tree *)obj;
2247 struct tree_desc desc;
2248 struct name_entry entry;
2249 if (init_tree_desc_gently(&desc, tree->buffer, tree->size, 0))
2251 * Error messages are given when packs are
2252 * verified, so do not print any here.
2254 return 0;
2255 while (tree_entry_gently(&desc, &entry))
2256 oidset_insert(set, &entry.oid);
2257 if (we_parsed_object)
2258 free_tree_buffer(tree);
2259 } else if (obj->type == OBJ_COMMIT) {
2260 struct commit *commit = (struct commit *) obj;
2261 struct commit_list *parents = commit->parents;
2263 oidset_insert(set, get_commit_tree_oid(commit));
2264 for (; parents; parents = parents->next)
2265 oidset_insert(set, &parents->item->object.oid);
2266 } else if (obj->type == OBJ_TAG) {
2267 struct tag *tag = (struct tag *) obj;
2268 oidset_insert(set, get_tagged_oid(tag));
2270 return 0;
2273 int is_promisor_object(const struct object_id *oid)
2275 static struct oidset promisor_objects;
2276 static int promisor_objects_prepared;
2278 if (!promisor_objects_prepared) {
2279 if (has_promisor_remote()) {
2280 for_each_packed_object(add_promisor_object,
2281 &promisor_objects,
2282 FOR_EACH_OBJECT_PROMISOR_ONLY |
2283 FOR_EACH_OBJECT_PACK_ORDER);
2285 promisor_objects_prepared = 1;
2287 return oidset_contains(&promisor_objects, oid);