branch: reject "--no-all" and "--no-remotes" early
[git.git] / packfile.c
blobfd083c86e00c1dbb1de6ba994f2df50e15797002
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "hex.h"
6 #include "list.h"
7 #include "pack.h"
8 #include "repository.h"
9 #include "dir.h"
10 #include "mergesort.h"
11 #include "packfile.h"
12 #include "delta.h"
13 #include "streaming.h"
14 #include "hash-lookup.h"
15 #include "commit.h"
16 #include "object.h"
17 #include "tag.h"
18 #include "trace.h"
19 #include "tree-walk.h"
20 #include "tree.h"
21 #include "object-file.h"
22 #include "object-store.h"
23 #include "midx.h"
24 #include "commit-graph.h"
25 #include "pack-revindex.h"
26 #include "promisor-remote.h"
27 #include "wrapper.h"
29 char *odb_pack_name(struct strbuf *buf,
30 const unsigned char *hash,
31 const char *ext)
33 strbuf_reset(buf);
34 strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
35 hash_to_hex(hash), ext);
36 return buf->buf;
39 char *sha1_pack_name(const unsigned char *sha1)
41 static struct strbuf buf = STRBUF_INIT;
42 return odb_pack_name(&buf, sha1, "pack");
45 char *sha1_pack_index_name(const unsigned char *sha1)
47 static struct strbuf buf = STRBUF_INIT;
48 return odb_pack_name(&buf, sha1, "idx");
51 static unsigned int pack_used_ctr;
52 static unsigned int pack_mmap_calls;
53 static unsigned int peak_pack_open_windows;
54 static unsigned int pack_open_windows;
55 static unsigned int pack_open_fds;
56 static unsigned int pack_max_fds;
57 static size_t peak_pack_mapped;
58 static size_t pack_mapped;
60 #define SZ_FMT PRIuMAX
61 static inline uintmax_t sz_fmt(size_t s) { return s; }
63 void pack_report(void)
65 fprintf(stderr,
66 "pack_report: getpagesize() = %10" SZ_FMT "\n"
67 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
68 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
69 sz_fmt(getpagesize()),
70 sz_fmt(packed_git_window_size),
71 sz_fmt(packed_git_limit));
72 fprintf(stderr,
73 "pack_report: pack_used_ctr = %10u\n"
74 "pack_report: pack_mmap_calls = %10u\n"
75 "pack_report: pack_open_windows = %10u / %10u\n"
76 "pack_report: pack_mapped = "
77 "%10" SZ_FMT " / %10" SZ_FMT "\n",
78 pack_used_ctr,
79 pack_mmap_calls,
80 pack_open_windows, peak_pack_open_windows,
81 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
85 * Open and mmap the index file at path, perform a couple of
86 * consistency checks, then record its information to p. Return 0 on
87 * success.
89 static int check_packed_git_idx(const char *path, struct packed_git *p)
91 void *idx_map;
92 size_t idx_size;
93 int fd = git_open(path), ret;
94 struct stat st;
95 const unsigned int hashsz = the_hash_algo->rawsz;
97 if (fd < 0)
98 return -1;
99 if (fstat(fd, &st)) {
100 close(fd);
101 return -1;
103 idx_size = xsize_t(st.st_size);
104 if (idx_size < 4 * 256 + hashsz + hashsz) {
105 close(fd);
106 return error("index file %s is too small", path);
108 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
109 close(fd);
111 ret = load_idx(path, hashsz, idx_map, idx_size, p);
113 if (ret)
114 munmap(idx_map, idx_size);
116 return ret;
119 int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
120 size_t idx_size, struct packed_git *p)
122 struct pack_idx_header *hdr = idx_map;
123 uint32_t version, nr, i, *index;
125 if (idx_size < 4 * 256 + hashsz + hashsz)
126 return error("index file %s is too small", path);
127 if (!idx_map)
128 return error("empty data");
130 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
131 version = ntohl(hdr->idx_version);
132 if (version < 2 || version > 2)
133 return error("index file %s is version %"PRIu32
134 " and is not supported by this binary"
135 " (try upgrading GIT to a newer version)",
136 path, version);
137 } else
138 version = 1;
140 nr = 0;
141 index = idx_map;
142 if (version > 1)
143 index += 2; /* skip index header */
144 for (i = 0; i < 256; i++) {
145 uint32_t n = ntohl(index[i]);
146 if (n < nr)
147 return error("non-monotonic index %s", path);
148 nr = n;
151 if (version == 1) {
153 * Total size:
154 * - 256 index entries 4 bytes each
155 * - 24-byte entries * nr (object ID + 4-byte offset)
156 * - hash of the packfile
157 * - file checksum
159 if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
160 return error("wrong index v1 file size in %s", path);
161 } else if (version == 2) {
163 * Minimum size:
164 * - 8 bytes of header
165 * - 256 index entries 4 bytes each
166 * - object ID entry * nr
167 * - 4-byte crc entry * nr
168 * - 4-byte offset entry * nr
169 * - hash of the packfile
170 * - file checksum
171 * And after the 4-byte offset table might be a
172 * variable sized table containing 8-byte entries
173 * for offsets larger than 2^31.
175 size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
176 size_t max_size = min_size;
177 if (nr)
178 max_size = st_add(max_size, st_mult(nr - 1, 8));
179 if (idx_size < min_size || idx_size > max_size)
180 return error("wrong index v2 file size in %s", path);
181 if (idx_size != min_size &&
183 * make sure we can deal with large pack offsets.
184 * 31-bit signed offset won't be enough, neither
185 * 32-bit unsigned one will be.
187 (sizeof(off_t) <= 4))
188 return error("pack too large for current definition of off_t in %s", path);
189 p->crc_offset = 8 + 4 * 256 + nr * hashsz;
192 p->index_version = version;
193 p->index_data = idx_map;
194 p->index_size = idx_size;
195 p->num_objects = nr;
196 return 0;
199 int open_pack_index(struct packed_git *p)
201 char *idx_name;
202 size_t len;
203 int ret;
205 if (p->index_data)
206 return 0;
208 if (!strip_suffix(p->pack_name, ".pack", &len))
209 BUG("pack_name does not end in .pack");
210 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
211 ret = check_packed_git_idx(idx_name, p);
212 free(idx_name);
213 return ret;
216 uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
218 const uint32_t *level1_ofs = p->index_data;
220 if (!level1_ofs) {
221 if (open_pack_index(p))
222 return 0;
223 level1_ofs = p->index_data;
226 if (p->index_version > 1) {
227 level1_ofs += 2;
230 return ntohl(level1_ofs[value]);
233 static struct packed_git *alloc_packed_git(int extra)
235 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
236 memset(p, 0, sizeof(*p));
237 p->pack_fd = -1;
238 return p;
241 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
243 const char *path = sha1_pack_name(sha1);
244 size_t alloc = st_add(strlen(path), 1);
245 struct packed_git *p = alloc_packed_git(alloc);
247 memcpy(p->pack_name, path, alloc); /* includes NUL */
248 hashcpy(p->hash, sha1);
249 if (check_packed_git_idx(idx_path, p)) {
250 free(p);
251 return NULL;
254 return p;
257 static void scan_windows(struct packed_git *p,
258 struct packed_git **lru_p,
259 struct pack_window **lru_w,
260 struct pack_window **lru_l)
262 struct pack_window *w, *w_l;
264 for (w_l = NULL, w = p->windows; w; w = w->next) {
265 if (!w->inuse_cnt) {
266 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
267 *lru_p = p;
268 *lru_w = w;
269 *lru_l = w_l;
272 w_l = w;
276 static int unuse_one_window(struct packed_git *current)
278 struct packed_git *p, *lru_p = NULL;
279 struct pack_window *lru_w = NULL, *lru_l = NULL;
281 if (current)
282 scan_windows(current, &lru_p, &lru_w, &lru_l);
283 for (p = the_repository->objects->packed_git; p; p = p->next)
284 scan_windows(p, &lru_p, &lru_w, &lru_l);
285 if (lru_p) {
286 munmap(lru_w->base, lru_w->len);
287 pack_mapped -= lru_w->len;
288 if (lru_l)
289 lru_l->next = lru_w->next;
290 else
291 lru_p->windows = lru_w->next;
292 free(lru_w);
293 pack_open_windows--;
294 return 1;
296 return 0;
299 void close_pack_windows(struct packed_git *p)
301 while (p->windows) {
302 struct pack_window *w = p->windows;
304 if (w->inuse_cnt)
305 die("pack '%s' still has open windows to it",
306 p->pack_name);
307 munmap(w->base, w->len);
308 pack_mapped -= w->len;
309 pack_open_windows--;
310 p->windows = w->next;
311 free(w);
315 int close_pack_fd(struct packed_git *p)
317 if (p->pack_fd < 0)
318 return 0;
320 close(p->pack_fd);
321 pack_open_fds--;
322 p->pack_fd = -1;
324 return 1;
327 void close_pack_index(struct packed_git *p)
329 if (p->index_data) {
330 munmap((void *)p->index_data, p->index_size);
331 p->index_data = NULL;
335 static void close_pack_revindex(struct packed_git *p)
337 if (!p->revindex_map)
338 return;
340 munmap((void *)p->revindex_map, p->revindex_size);
341 p->revindex_map = NULL;
342 p->revindex_data = NULL;
345 static void close_pack_mtimes(struct packed_git *p)
347 if (!p->mtimes_map)
348 return;
350 munmap((void *)p->mtimes_map, p->mtimes_size);
351 p->mtimes_map = NULL;
354 void close_pack(struct packed_git *p)
356 close_pack_windows(p);
357 close_pack_fd(p);
358 close_pack_index(p);
359 close_pack_revindex(p);
360 close_pack_mtimes(p);
361 oidset_clear(&p->bad_objects);
364 void close_object_store(struct raw_object_store *o)
366 struct packed_git *p;
368 for (p = o->packed_git; p; p = p->next)
369 if (p->do_not_close)
370 BUG("want to close pack marked 'do-not-close'");
371 else
372 close_pack(p);
374 if (o->multi_pack_index) {
375 close_midx(o->multi_pack_index);
376 o->multi_pack_index = NULL;
379 close_commit_graph(o);
382 void unlink_pack_path(const char *pack_name, int force_delete)
384 static const char *exts[] = {".pack", ".idx", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
385 int i;
386 struct strbuf buf = STRBUF_INIT;
387 size_t plen;
389 strbuf_addstr(&buf, pack_name);
390 strip_suffix_mem(buf.buf, &buf.len, ".pack");
391 plen = buf.len;
393 if (!force_delete) {
394 strbuf_addstr(&buf, ".keep");
395 if (!access(buf.buf, F_OK)) {
396 strbuf_release(&buf);
397 return;
401 for (i = 0; i < ARRAY_SIZE(exts); i++) {
402 strbuf_setlen(&buf, plen);
403 strbuf_addstr(&buf, exts[i]);
404 unlink(buf.buf);
407 strbuf_release(&buf);
411 * The LRU pack is the one with the oldest MRU window, preferring packs
412 * with no used windows, or the oldest mtime if it has no windows allocated.
414 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
416 struct pack_window *w, *this_mru_w;
417 int has_windows_inuse = 0;
420 * Reject this pack if it has windows and the previously selected
421 * one does not. If this pack does not have windows, reject
422 * it if the pack file is newer than the previously selected one.
424 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
425 return;
427 for (w = this_mru_w = p->windows; w; w = w->next) {
429 * Reject this pack if any of its windows are in use,
430 * but the previously selected pack did not have any
431 * inuse windows. Otherwise, record that this pack
432 * has windows in use.
434 if (w->inuse_cnt) {
435 if (*accept_windows_inuse)
436 has_windows_inuse = 1;
437 else
438 return;
441 if (w->last_used > this_mru_w->last_used)
442 this_mru_w = w;
445 * Reject this pack if it has windows that have been
446 * used more recently than the previously selected pack.
447 * If the previously selected pack had windows inuse and
448 * we have not encountered a window in this pack that is
449 * inuse, skip this check since we prefer a pack with no
450 * inuse windows to one that has inuse windows.
452 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
453 this_mru_w->last_used > (*mru_w)->last_used)
454 return;
458 * Select this pack.
460 *mru_w = this_mru_w;
461 *lru_p = p;
462 *accept_windows_inuse = has_windows_inuse;
465 static int close_one_pack(void)
467 struct packed_git *p, *lru_p = NULL;
468 struct pack_window *mru_w = NULL;
469 int accept_windows_inuse = 1;
471 for (p = the_repository->objects->packed_git; p; p = p->next) {
472 if (p->pack_fd == -1)
473 continue;
474 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
477 if (lru_p)
478 return close_pack_fd(lru_p);
480 return 0;
483 static unsigned int get_max_fd_limit(void)
485 #ifdef RLIMIT_NOFILE
487 struct rlimit lim;
489 if (!getrlimit(RLIMIT_NOFILE, &lim))
490 return lim.rlim_cur;
492 #endif
494 #ifdef _SC_OPEN_MAX
496 long open_max = sysconf(_SC_OPEN_MAX);
497 if (0 < open_max)
498 return open_max;
500 * Otherwise, we got -1 for one of the two
501 * reasons:
503 * (1) sysconf() did not understand _SC_OPEN_MAX
504 * and signaled an error with -1; or
505 * (2) sysconf() said there is no limit.
507 * We _could_ clear errno before calling sysconf() to
508 * tell these two cases apart and return a huge number
509 * in the latter case to let the caller cap it to a
510 * value that is not so selfish, but letting the
511 * fallback OPEN_MAX codepath take care of these cases
512 * is a lot simpler.
515 #endif
517 #ifdef OPEN_MAX
518 return OPEN_MAX;
519 #else
520 return 1; /* see the caller ;-) */
521 #endif
524 const char *pack_basename(struct packed_git *p)
526 const char *ret = strrchr(p->pack_name, '/');
527 if (ret)
528 ret = ret + 1; /* skip past slash */
529 else
530 ret = p->pack_name; /* we only have a base */
531 return ret;
535 * Do not call this directly as this leaks p->pack_fd on error return;
536 * call open_packed_git() instead.
538 static int open_packed_git_1(struct packed_git *p)
540 struct stat st;
541 struct pack_header hdr;
542 unsigned char hash[GIT_MAX_RAWSZ];
543 unsigned char *idx_hash;
544 ssize_t read_result;
545 const unsigned hashsz = the_hash_algo->rawsz;
547 if (open_pack_index(p))
548 return error("packfile %s index unavailable", p->pack_name);
550 if (!pack_max_fds) {
551 unsigned int max_fds = get_max_fd_limit();
553 /* Save 3 for stdin/stdout/stderr, 22 for work */
554 if (25 < max_fds)
555 pack_max_fds = max_fds - 25;
556 else
557 pack_max_fds = 1;
560 while (pack_max_fds <= pack_open_fds && close_one_pack())
561 ; /* nothing */
563 p->pack_fd = git_open(p->pack_name);
564 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
565 return -1;
566 pack_open_fds++;
568 /* If we created the struct before we had the pack we lack size. */
569 if (!p->pack_size) {
570 if (!S_ISREG(st.st_mode))
571 return error("packfile %s not a regular file", p->pack_name);
572 p->pack_size = st.st_size;
573 } else if (p->pack_size != st.st_size)
574 return error("packfile %s size changed", p->pack_name);
576 /* Verify we recognize this pack file format. */
577 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
578 if (read_result < 0)
579 return error_errno("error reading from %s", p->pack_name);
580 if (read_result != sizeof(hdr))
581 return error("file %s is far too short to be a packfile", p->pack_name);
582 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
583 return error("file %s is not a GIT packfile", p->pack_name);
584 if (!pack_version_ok(hdr.hdr_version))
585 return error("packfile %s is version %"PRIu32" and not"
586 " supported (try upgrading GIT to a newer version)",
587 p->pack_name, ntohl(hdr.hdr_version));
589 /* Verify the pack matches its index. */
590 if (p->num_objects != ntohl(hdr.hdr_entries))
591 return error("packfile %s claims to have %"PRIu32" objects"
592 " while index indicates %"PRIu32" objects",
593 p->pack_name, ntohl(hdr.hdr_entries),
594 p->num_objects);
595 read_result = pread_in_full(p->pack_fd, hash, hashsz,
596 p->pack_size - hashsz);
597 if (read_result < 0)
598 return error_errno("error reading from %s", p->pack_name);
599 if (read_result != hashsz)
600 return error("packfile %s signature is unavailable", p->pack_name);
601 idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
602 if (!hasheq(hash, idx_hash))
603 return error("packfile %s does not match index", p->pack_name);
604 return 0;
607 static int open_packed_git(struct packed_git *p)
609 if (!open_packed_git_1(p))
610 return 0;
611 close_pack_fd(p);
612 return -1;
615 static int in_window(struct pack_window *win, off_t offset)
617 /* We must promise at least one full hash after the
618 * offset is available from this window, otherwise the offset
619 * is not actually in this window and a different window (which
620 * has that one hash excess) must be used. This is to support
621 * the object header and delta base parsing routines below.
623 off_t win_off = win->offset;
624 return win_off <= offset
625 && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
628 unsigned char *use_pack(struct packed_git *p,
629 struct pack_window **w_cursor,
630 off_t offset,
631 unsigned long *left)
633 struct pack_window *win = *w_cursor;
635 /* Since packfiles end in a hash of their content and it's
636 * pointless to ask for an offset into the middle of that
637 * hash, and the in_window function above wouldn't match
638 * don't allow an offset too close to the end of the file.
640 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
641 die("packfile %s cannot be accessed", p->pack_name);
642 if (offset > (p->pack_size - the_hash_algo->rawsz))
643 die("offset beyond end of packfile (truncated pack?)");
644 if (offset < 0)
645 die(_("offset before end of packfile (broken .idx?)"));
647 if (!win || !in_window(win, offset)) {
648 if (win)
649 win->inuse_cnt--;
650 for (win = p->windows; win; win = win->next) {
651 if (in_window(win, offset))
652 break;
654 if (!win) {
655 size_t window_align = packed_git_window_size / 2;
656 off_t len;
658 if (p->pack_fd == -1 && open_packed_git(p))
659 die("packfile %s cannot be accessed", p->pack_name);
661 CALLOC_ARRAY(win, 1);
662 win->offset = (offset / window_align) * window_align;
663 len = p->pack_size - win->offset;
664 if (len > packed_git_window_size)
665 len = packed_git_window_size;
666 win->len = (size_t)len;
667 pack_mapped += win->len;
668 while (packed_git_limit < pack_mapped
669 && unuse_one_window(p))
670 ; /* nothing */
671 win->base = xmmap_gently(NULL, win->len,
672 PROT_READ, MAP_PRIVATE,
673 p->pack_fd, win->offset);
674 if (win->base == MAP_FAILED)
675 die_errno(_("packfile %s cannot be mapped%s"),
676 p->pack_name, mmap_os_err());
677 if (!win->offset && win->len == p->pack_size
678 && !p->do_not_close)
679 close_pack_fd(p);
680 pack_mmap_calls++;
681 pack_open_windows++;
682 if (pack_mapped > peak_pack_mapped)
683 peak_pack_mapped = pack_mapped;
684 if (pack_open_windows > peak_pack_open_windows)
685 peak_pack_open_windows = pack_open_windows;
686 win->next = p->windows;
687 p->windows = win;
690 if (win != *w_cursor) {
691 win->last_used = pack_used_ctr++;
692 win->inuse_cnt++;
693 *w_cursor = win;
695 offset -= win->offset;
696 if (left)
697 *left = win->len - xsize_t(offset);
698 return win->base + offset;
701 void unuse_pack(struct pack_window **w_cursor)
703 struct pack_window *w = *w_cursor;
704 if (w) {
705 w->inuse_cnt--;
706 *w_cursor = NULL;
710 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
712 struct stat st;
713 size_t alloc;
714 struct packed_git *p;
717 * Make sure a corresponding .pack file exists and that
718 * the index looks sane.
720 if (!strip_suffix_mem(path, &path_len, ".idx"))
721 return NULL;
724 * ".promisor" is long enough to hold any suffix we're adding (and
725 * the use xsnprintf double-checks that)
727 alloc = st_add3(path_len, strlen(".promisor"), 1);
728 p = alloc_packed_git(alloc);
729 memcpy(p->pack_name, path, path_len);
731 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
732 if (!access(p->pack_name, F_OK))
733 p->pack_keep = 1;
735 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
736 if (!access(p->pack_name, F_OK))
737 p->pack_promisor = 1;
739 xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
740 if (!access(p->pack_name, F_OK))
741 p->is_cruft = 1;
743 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
744 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
745 free(p);
746 return NULL;
749 /* ok, it looks sane as far as we can check without
750 * actually mapping the pack file.
752 p->pack_size = st.st_size;
753 p->pack_local = local;
754 p->mtime = st.st_mtime;
755 if (path_len < the_hash_algo->hexsz ||
756 get_sha1_hex(path + path_len - the_hash_algo->hexsz, p->hash))
757 hashclr(p->hash);
758 return p;
761 void install_packed_git(struct repository *r, struct packed_git *pack)
763 if (pack->pack_fd != -1)
764 pack_open_fds++;
766 pack->next = r->objects->packed_git;
767 r->objects->packed_git = pack;
769 hashmap_entry_init(&pack->packmap_ent, strhash(pack->pack_name));
770 hashmap_add(&r->objects->pack_map, &pack->packmap_ent);
773 void (*report_garbage)(unsigned seen_bits, const char *path);
775 static void report_helper(const struct string_list *list,
776 int seen_bits, int first, int last)
778 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
779 return;
781 for (; first < last; first++)
782 report_garbage(seen_bits, list->items[first].string);
785 static void report_pack_garbage(struct string_list *list)
787 int i, baselen = -1, first = 0, seen_bits = 0;
789 if (!report_garbage)
790 return;
792 string_list_sort(list);
794 for (i = 0; i < list->nr; i++) {
795 const char *path = list->items[i].string;
796 if (baselen != -1 &&
797 strncmp(path, list->items[first].string, baselen)) {
798 report_helper(list, seen_bits, first, i);
799 baselen = -1;
800 seen_bits = 0;
802 if (baselen == -1) {
803 const char *dot = strrchr(path, '.');
804 if (!dot) {
805 report_garbage(PACKDIR_FILE_GARBAGE, path);
806 continue;
808 baselen = dot - path + 1;
809 first = i;
811 if (!strcmp(path + baselen, "pack"))
812 seen_bits |= 1;
813 else if (!strcmp(path + baselen, "idx"))
814 seen_bits |= 2;
816 report_helper(list, seen_bits, first, list->nr);
819 void for_each_file_in_pack_dir(const char *objdir,
820 each_file_in_pack_dir_fn fn,
821 void *data)
823 struct strbuf path = STRBUF_INIT;
824 size_t dirnamelen;
825 DIR *dir;
826 struct dirent *de;
828 strbuf_addstr(&path, objdir);
829 strbuf_addstr(&path, "/pack");
830 dir = opendir(path.buf);
831 if (!dir) {
832 if (errno != ENOENT)
833 error_errno("unable to open object pack directory: %s",
834 path.buf);
835 strbuf_release(&path);
836 return;
838 strbuf_addch(&path, '/');
839 dirnamelen = path.len;
840 while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
841 strbuf_setlen(&path, dirnamelen);
842 strbuf_addstr(&path, de->d_name);
844 fn(path.buf, path.len, de->d_name, data);
847 closedir(dir);
848 strbuf_release(&path);
851 struct prepare_pack_data {
852 struct repository *r;
853 struct string_list *garbage;
854 int local;
855 struct multi_pack_index *m;
858 static void prepare_pack(const char *full_name, size_t full_name_len,
859 const char *file_name, void *_data)
861 struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
862 struct packed_git *p;
863 size_t base_len = full_name_len;
865 if (strip_suffix_mem(full_name, &base_len, ".idx") &&
866 !(data->m && midx_contains_pack(data->m, file_name))) {
867 struct hashmap_entry hent;
868 char *pack_name = xstrfmt("%.*s.pack", (int)base_len, full_name);
869 unsigned int hash = strhash(pack_name);
870 hashmap_entry_init(&hent, hash);
872 /* Don't reopen a pack we already have. */
873 if (!hashmap_get(&data->r->objects->pack_map, &hent, pack_name)) {
874 p = add_packed_git(full_name, full_name_len, data->local);
875 if (p)
876 install_packed_git(data->r, p);
878 free(pack_name);
881 if (!report_garbage)
882 return;
884 if (!strcmp(file_name, "multi-pack-index"))
885 return;
886 if (starts_with(file_name, "multi-pack-index") &&
887 (ends_with(file_name, ".bitmap") || ends_with(file_name, ".rev")))
888 return;
889 if (ends_with(file_name, ".idx") ||
890 ends_with(file_name, ".rev") ||
891 ends_with(file_name, ".pack") ||
892 ends_with(file_name, ".bitmap") ||
893 ends_with(file_name, ".keep") ||
894 ends_with(file_name, ".promisor") ||
895 ends_with(file_name, ".mtimes"))
896 string_list_append(data->garbage, full_name);
897 else
898 report_garbage(PACKDIR_FILE_GARBAGE, full_name);
901 static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
903 struct prepare_pack_data data;
904 struct string_list garbage = STRING_LIST_INIT_DUP;
906 data.m = r->objects->multi_pack_index;
908 /* look for the multi-pack-index for this object directory */
909 while (data.m && strcmp(data.m->object_dir, objdir))
910 data.m = data.m->next;
912 data.r = r;
913 data.garbage = &garbage;
914 data.local = local;
916 for_each_file_in_pack_dir(objdir, prepare_pack, &data);
918 report_pack_garbage(data.garbage);
919 string_list_clear(data.garbage, 0);
922 static void prepare_packed_git(struct repository *r);
924 * Give a fast, rough count of the number of objects in the repository. This
925 * ignores loose objects completely. If you have a lot of them, then either
926 * you should repack because your performance will be awful, or they are
927 * all unreachable objects about to be pruned, in which case they're not really
928 * interesting as a measure of repo size in the first place.
930 unsigned long repo_approximate_object_count(struct repository *r)
932 if (!r->objects->approximate_object_count_valid) {
933 unsigned long count;
934 struct multi_pack_index *m;
935 struct packed_git *p;
937 prepare_packed_git(r);
938 count = 0;
939 for (m = get_multi_pack_index(r); m; m = m->next)
940 count += m->num_objects;
941 for (p = r->objects->packed_git; p; p = p->next) {
942 if (open_pack_index(p))
943 continue;
944 count += p->num_objects;
946 r->objects->approximate_object_count = count;
947 r->objects->approximate_object_count_valid = 1;
949 return r->objects->approximate_object_count;
952 DEFINE_LIST_SORT(static, sort_packs, struct packed_git, next);
954 static int sort_pack(const struct packed_git *a, const struct packed_git *b)
956 int st;
959 * Local packs tend to contain objects specific to our
960 * variant of the project than remote ones. In addition,
961 * remote ones could be on a network mounted filesystem.
962 * Favor local ones for these reasons.
964 st = a->pack_local - b->pack_local;
965 if (st)
966 return -st;
969 * Younger packs tend to contain more recent objects,
970 * and more recent objects tend to get accessed more
971 * often.
973 if (a->mtime < b->mtime)
974 return 1;
975 else if (a->mtime == b->mtime)
976 return 0;
977 return -1;
980 static void rearrange_packed_git(struct repository *r)
982 sort_packs(&r->objects->packed_git, sort_pack);
985 static void prepare_packed_git_mru(struct repository *r)
987 struct packed_git *p;
989 INIT_LIST_HEAD(&r->objects->packed_git_mru);
991 for (p = r->objects->packed_git; p; p = p->next)
992 list_add_tail(&p->mru, &r->objects->packed_git_mru);
995 static void prepare_packed_git(struct repository *r)
997 struct object_directory *odb;
999 if (r->objects->packed_git_initialized)
1000 return;
1002 prepare_alt_odb(r);
1003 for (odb = r->objects->odb; odb; odb = odb->next) {
1004 int local = (odb == r->objects->odb);
1005 prepare_multi_pack_index_one(r, odb->path, local);
1006 prepare_packed_git_one(r, odb->path, local);
1008 rearrange_packed_git(r);
1010 prepare_packed_git_mru(r);
1011 r->objects->packed_git_initialized = 1;
1014 void reprepare_packed_git(struct repository *r)
1016 struct object_directory *odb;
1018 obj_read_lock();
1021 * Reprepare alt odbs, in case the alternates file was modified
1022 * during the course of this process. This only _adds_ odbs to
1023 * the linked list, so existing odbs will continue to exist for
1024 * the lifetime of the process.
1026 r->objects->loaded_alternates = 0;
1027 prepare_alt_odb(r);
1029 for (odb = r->objects->odb; odb; odb = odb->next)
1030 odb_clear_loose_cache(odb);
1032 r->objects->approximate_object_count_valid = 0;
1033 r->objects->packed_git_initialized = 0;
1034 prepare_packed_git(r);
1035 obj_read_unlock();
1038 struct packed_git *get_packed_git(struct repository *r)
1040 prepare_packed_git(r);
1041 return r->objects->packed_git;
1044 struct multi_pack_index *get_multi_pack_index(struct repository *r)
1046 prepare_packed_git(r);
1047 return r->objects->multi_pack_index;
1050 struct multi_pack_index *get_local_multi_pack_index(struct repository *r)
1052 struct multi_pack_index *m = get_multi_pack_index(r);
1054 /* no need to iterate; we always put the local one first (if any) */
1055 if (m && m->local)
1056 return m;
1058 return NULL;
1061 struct packed_git *get_all_packs(struct repository *r)
1063 struct multi_pack_index *m;
1065 prepare_packed_git(r);
1066 for (m = r->objects->multi_pack_index; m; m = m->next) {
1067 uint32_t i;
1068 for (i = 0; i < m->num_packs; i++)
1069 prepare_midx_pack(r, m, i);
1072 return r->objects->packed_git;
1075 struct list_head *get_packed_git_mru(struct repository *r)
1077 prepare_packed_git(r);
1078 return &r->objects->packed_git_mru;
1081 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1082 unsigned long len, enum object_type *type, unsigned long *sizep)
1084 unsigned shift;
1085 size_t size, c;
1086 unsigned long used = 0;
1088 c = buf[used++];
1089 *type = (c >> 4) & 7;
1090 size = c & 15;
1091 shift = 4;
1092 while (c & 0x80) {
1093 if (len <= used || (bitsizeof(long) - 7) < shift) {
1094 error("bad object header");
1095 size = used = 0;
1096 break;
1098 c = buf[used++];
1099 size = st_add(size, st_left_shift(c & 0x7f, shift));
1100 shift += 7;
1102 *sizep = cast_size_t_to_ulong(size);
1103 return used;
1106 unsigned long get_size_from_delta(struct packed_git *p,
1107 struct pack_window **w_curs,
1108 off_t curpos)
1110 const unsigned char *data;
1111 unsigned char delta_head[20], *in;
1112 git_zstream stream;
1113 int st;
1115 memset(&stream, 0, sizeof(stream));
1116 stream.next_out = delta_head;
1117 stream.avail_out = sizeof(delta_head);
1119 git_inflate_init(&stream);
1120 do {
1121 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1122 stream.next_in = in;
1124 * Note: the window section returned by use_pack() must be
1125 * available throughout git_inflate()'s unlocked execution. To
1126 * ensure no other thread will modify the window in the
1127 * meantime, we rely on the packed_window.inuse_cnt. This
1128 * counter is incremented before window reading and checked
1129 * before window disposal.
1131 * Other worrying sections could be the call to close_pack_fd(),
1132 * which can close packs even with in-use windows, and to
1133 * reprepare_packed_git(). Regarding the former, mmap doc says:
1134 * "closing the file descriptor does not unmap the region". And
1135 * for the latter, it won't re-open already available packs.
1137 obj_read_unlock();
1138 st = git_inflate(&stream, Z_FINISH);
1139 obj_read_lock();
1140 curpos += stream.next_in - in;
1141 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1142 stream.total_out < sizeof(delta_head));
1143 git_inflate_end(&stream);
1144 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1145 error("delta data unpack-initial failed");
1146 return 0;
1149 /* Examine the initial part of the delta to figure out
1150 * the result size.
1152 data = delta_head;
1154 /* ignore base size */
1155 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1157 /* Read the result size */
1158 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1161 int unpack_object_header(struct packed_git *p,
1162 struct pack_window **w_curs,
1163 off_t *curpos,
1164 unsigned long *sizep)
1166 unsigned char *base;
1167 unsigned long left;
1168 unsigned long used;
1169 enum object_type type;
1171 /* use_pack() assures us we have [base, base + 20) available
1172 * as a range that we can look at. (Its actually the hash
1173 * size that is assured.) With our object header encoding
1174 * the maximum deflated object size is 2^137, which is just
1175 * insane, so we know won't exceed what we have been given.
1177 base = use_pack(p, w_curs, *curpos, &left);
1178 used = unpack_object_header_buffer(base, left, &type, sizep);
1179 if (!used) {
1180 type = OBJ_BAD;
1181 } else
1182 *curpos += used;
1184 return type;
1187 void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
1189 oidset_insert(&p->bad_objects, oid);
1192 const struct packed_git *has_packed_and_bad(struct repository *r,
1193 const struct object_id *oid)
1195 struct packed_git *p;
1197 for (p = r->objects->packed_git; p; p = p->next)
1198 if (oidset_contains(&p->bad_objects, oid))
1199 return p;
1200 return NULL;
1203 off_t get_delta_base(struct packed_git *p,
1204 struct pack_window **w_curs,
1205 off_t *curpos,
1206 enum object_type type,
1207 off_t delta_obj_offset)
1209 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1210 off_t base_offset;
1212 /* use_pack() assured us we have [base_info, base_info + 20)
1213 * as a range that we can look at without walking off the
1214 * end of the mapped window. Its actually the hash size
1215 * that is assured. An OFS_DELTA longer than the hash size
1216 * is stupid, as then a REF_DELTA would be smaller to store.
1218 if (type == OBJ_OFS_DELTA) {
1219 unsigned used = 0;
1220 unsigned char c = base_info[used++];
1221 base_offset = c & 127;
1222 while (c & 128) {
1223 base_offset += 1;
1224 if (!base_offset || MSB(base_offset, 7))
1225 return 0; /* overflow */
1226 c = base_info[used++];
1227 base_offset = (base_offset << 7) + (c & 127);
1229 base_offset = delta_obj_offset - base_offset;
1230 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1231 return 0; /* out of bound */
1232 *curpos += used;
1233 } else if (type == OBJ_REF_DELTA) {
1234 /* The base entry _must_ be in the same pack */
1235 base_offset = find_pack_entry_one(base_info, p);
1236 *curpos += the_hash_algo->rawsz;
1237 } else
1238 die("I am totally screwed");
1239 return base_offset;
1243 * Like get_delta_base above, but we return the sha1 instead of the pack
1244 * offset. This means it is cheaper for REF deltas (we do not have to do
1245 * the final object lookup), but more expensive for OFS deltas (we
1246 * have to load the revidx to convert the offset back into a sha1).
1248 static int get_delta_base_oid(struct packed_git *p,
1249 struct pack_window **w_curs,
1250 off_t curpos,
1251 struct object_id *oid,
1252 enum object_type type,
1253 off_t delta_obj_offset)
1255 if (type == OBJ_REF_DELTA) {
1256 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1257 oidread(oid, base);
1258 return 0;
1259 } else if (type == OBJ_OFS_DELTA) {
1260 uint32_t base_pos;
1261 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1262 type, delta_obj_offset);
1264 if (!base_offset)
1265 return -1;
1267 if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1268 return -1;
1270 return nth_packed_object_id(oid, p,
1271 pack_pos_to_index(p, base_pos));
1272 } else
1273 return -1;
1276 static int retry_bad_packed_offset(struct repository *r,
1277 struct packed_git *p,
1278 off_t obj_offset)
1280 int type;
1281 uint32_t pos;
1282 struct object_id oid;
1283 if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1284 return OBJ_BAD;
1285 nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1286 mark_bad_packed_object(p, &oid);
1287 type = oid_object_info(r, &oid, NULL);
1288 if (type <= OBJ_NONE)
1289 return OBJ_BAD;
1290 return type;
1293 #define POI_STACK_PREALLOC 64
1295 static enum object_type packed_to_object_type(struct repository *r,
1296 struct packed_git *p,
1297 off_t obj_offset,
1298 enum object_type type,
1299 struct pack_window **w_curs,
1300 off_t curpos)
1302 off_t small_poi_stack[POI_STACK_PREALLOC];
1303 off_t *poi_stack = small_poi_stack;
1304 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1306 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1307 off_t base_offset;
1308 unsigned long size;
1309 /* Push the object we're going to leave behind */
1310 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1311 poi_stack_alloc = alloc_nr(poi_stack_nr);
1312 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1313 COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1314 } else {
1315 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1317 poi_stack[poi_stack_nr++] = obj_offset;
1318 /* If parsing the base offset fails, just unwind */
1319 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1320 if (!base_offset)
1321 goto unwind;
1322 curpos = obj_offset = base_offset;
1323 type = unpack_object_header(p, w_curs, &curpos, &size);
1324 if (type <= OBJ_NONE) {
1325 /* If getting the base itself fails, we first
1326 * retry the base, otherwise unwind */
1327 type = retry_bad_packed_offset(r, p, base_offset);
1328 if (type > OBJ_NONE)
1329 goto out;
1330 goto unwind;
1334 switch (type) {
1335 case OBJ_BAD:
1336 case OBJ_COMMIT:
1337 case OBJ_TREE:
1338 case OBJ_BLOB:
1339 case OBJ_TAG:
1340 break;
1341 default:
1342 error("unknown object type %i at offset %"PRIuMAX" in %s",
1343 type, (uintmax_t)obj_offset, p->pack_name);
1344 type = OBJ_BAD;
1347 out:
1348 if (poi_stack != small_poi_stack)
1349 free(poi_stack);
1350 return type;
1352 unwind:
1353 while (poi_stack_nr) {
1354 obj_offset = poi_stack[--poi_stack_nr];
1355 type = retry_bad_packed_offset(r, p, obj_offset);
1356 if (type > OBJ_NONE)
1357 goto out;
1359 type = OBJ_BAD;
1360 goto out;
1363 static struct hashmap delta_base_cache;
1364 static size_t delta_base_cached;
1366 static LIST_HEAD(delta_base_cache_lru);
1368 struct delta_base_cache_key {
1369 struct packed_git *p;
1370 off_t base_offset;
1373 struct delta_base_cache_entry {
1374 struct hashmap_entry ent;
1375 struct delta_base_cache_key key;
1376 struct list_head lru;
1377 void *data;
1378 unsigned long size;
1379 enum object_type type;
1382 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1384 unsigned int hash;
1386 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1387 hash += (hash >> 8) + (hash >> 16);
1388 return hash;
1391 static struct delta_base_cache_entry *
1392 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1394 struct hashmap_entry entry, *e;
1395 struct delta_base_cache_key key;
1397 if (!delta_base_cache.cmpfn)
1398 return NULL;
1400 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1401 key.p = p;
1402 key.base_offset = base_offset;
1403 e = hashmap_get(&delta_base_cache, &entry, &key);
1404 return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1407 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1408 const struct delta_base_cache_key *b)
1410 return a->p == b->p && a->base_offset == b->base_offset;
1413 static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1414 const struct hashmap_entry *va,
1415 const struct hashmap_entry *vb,
1416 const void *vkey)
1418 const struct delta_base_cache_entry *a, *b;
1419 const struct delta_base_cache_key *key = vkey;
1421 a = container_of(va, const struct delta_base_cache_entry, ent);
1422 b = container_of(vb, const struct delta_base_cache_entry, ent);
1424 if (key)
1425 return !delta_base_cache_key_eq(&a->key, key);
1426 else
1427 return !delta_base_cache_key_eq(&a->key, &b->key);
1430 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1432 return !!get_delta_base_cache_entry(p, base_offset);
1436 * Remove the entry from the cache, but do _not_ free the associated
1437 * entry data. The caller takes ownership of the "data" buffer, and
1438 * should copy out any fields it wants before detaching.
1440 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1442 hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1443 list_del(&ent->lru);
1444 delta_base_cached -= ent->size;
1445 free(ent);
1448 static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1449 off_t base_offset, unsigned long *base_size,
1450 enum object_type *type)
1452 struct delta_base_cache_entry *ent;
1454 ent = get_delta_base_cache_entry(p, base_offset);
1455 if (!ent)
1456 return unpack_entry(r, p, base_offset, type, base_size);
1458 if (type)
1459 *type = ent->type;
1460 if (base_size)
1461 *base_size = ent->size;
1462 return xmemdupz(ent->data, ent->size);
1465 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1467 free(ent->data);
1468 detach_delta_base_cache_entry(ent);
1471 void clear_delta_base_cache(void)
1473 struct list_head *lru, *tmp;
1474 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1475 struct delta_base_cache_entry *entry =
1476 list_entry(lru, struct delta_base_cache_entry, lru);
1477 release_delta_base_cache(entry);
1481 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1482 void *base, unsigned long base_size, enum object_type type)
1484 struct delta_base_cache_entry *ent;
1485 struct list_head *lru, *tmp;
1488 * Check required to avoid redundant entries when more than one thread
1489 * is unpacking the same object, in unpack_entry() (since its phases I
1490 * and III might run concurrently across multiple threads).
1492 if (in_delta_base_cache(p, base_offset)) {
1493 free(base);
1494 return;
1497 delta_base_cached += base_size;
1499 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1500 struct delta_base_cache_entry *f =
1501 list_entry(lru, struct delta_base_cache_entry, lru);
1502 if (delta_base_cached <= delta_base_cache_limit)
1503 break;
1504 release_delta_base_cache(f);
1507 ent = xmalloc(sizeof(*ent));
1508 ent->key.p = p;
1509 ent->key.base_offset = base_offset;
1510 ent->type = type;
1511 ent->data = base;
1512 ent->size = base_size;
1513 list_add_tail(&ent->lru, &delta_base_cache_lru);
1515 if (!delta_base_cache.cmpfn)
1516 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1517 hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1518 hashmap_add(&delta_base_cache, &ent->ent);
1521 int packed_object_info(struct repository *r, struct packed_git *p,
1522 off_t obj_offset, struct object_info *oi)
1524 struct pack_window *w_curs = NULL;
1525 unsigned long size;
1526 off_t curpos = obj_offset;
1527 enum object_type type;
1530 * We always get the representation type, but only convert it to
1531 * a "real" type later if the caller is interested.
1533 if (oi->contentp) {
1534 *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1535 &type);
1536 if (!*oi->contentp)
1537 type = OBJ_BAD;
1538 } else {
1539 type = unpack_object_header(p, &w_curs, &curpos, &size);
1542 if (!oi->contentp && oi->sizep) {
1543 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1544 off_t tmp_pos = curpos;
1545 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1546 type, obj_offset);
1547 if (!base_offset) {
1548 type = OBJ_BAD;
1549 goto out;
1551 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1552 if (*oi->sizep == 0) {
1553 type = OBJ_BAD;
1554 goto out;
1556 } else {
1557 *oi->sizep = size;
1561 if (oi->disk_sizep) {
1562 uint32_t pos;
1563 if (offset_to_pack_pos(p, obj_offset, &pos) < 0) {
1564 error("could not find object at offset %"PRIuMAX" "
1565 "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1566 type = OBJ_BAD;
1567 goto out;
1570 *oi->disk_sizep = pack_pos_to_offset(p, pos + 1) - obj_offset;
1573 if (oi->typep || oi->type_name) {
1574 enum object_type ptot;
1575 ptot = packed_to_object_type(r, p, obj_offset,
1576 type, &w_curs, curpos);
1577 if (oi->typep)
1578 *oi->typep = ptot;
1579 if (oi->type_name) {
1580 const char *tn = type_name(ptot);
1581 if (tn)
1582 strbuf_addstr(oi->type_name, tn);
1584 if (ptot < 0) {
1585 type = OBJ_BAD;
1586 goto out;
1590 if (oi->delta_base_oid) {
1591 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1592 if (get_delta_base_oid(p, &w_curs, curpos,
1593 oi->delta_base_oid,
1594 type, obj_offset) < 0) {
1595 type = OBJ_BAD;
1596 goto out;
1598 } else
1599 oidclr(oi->delta_base_oid);
1602 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1603 OI_PACKED;
1605 out:
1606 unuse_pack(&w_curs);
1607 return type;
1610 static void *unpack_compressed_entry(struct packed_git *p,
1611 struct pack_window **w_curs,
1612 off_t curpos,
1613 unsigned long size)
1615 int st;
1616 git_zstream stream;
1617 unsigned char *buffer, *in;
1619 buffer = xmallocz_gently(size);
1620 if (!buffer)
1621 return NULL;
1622 memset(&stream, 0, sizeof(stream));
1623 stream.next_out = buffer;
1624 stream.avail_out = size + 1;
1626 git_inflate_init(&stream);
1627 do {
1628 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1629 stream.next_in = in;
1631 * Note: we must ensure the window section returned by
1632 * use_pack() will be available throughout git_inflate()'s
1633 * unlocked execution. Please refer to the comment at
1634 * get_size_from_delta() to see how this is done.
1636 obj_read_unlock();
1637 st = git_inflate(&stream, Z_FINISH);
1638 obj_read_lock();
1639 if (!stream.avail_out)
1640 break; /* the payload is larger than it should be */
1641 curpos += stream.next_in - in;
1642 } while (st == Z_OK || st == Z_BUF_ERROR);
1643 git_inflate_end(&stream);
1644 if ((st != Z_STREAM_END) || stream.total_out != size) {
1645 free(buffer);
1646 return NULL;
1649 /* versions of zlib can clobber unconsumed portion of outbuf */
1650 buffer[size] = '\0';
1652 return buffer;
1655 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1657 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1658 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1659 p->pack_name, (uintmax_t)obj_offset);
1662 int do_check_packed_object_crc;
1664 #define UNPACK_ENTRY_STACK_PREALLOC 64
1665 struct unpack_entry_stack_ent {
1666 off_t obj_offset;
1667 off_t curpos;
1668 unsigned long size;
1671 void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1672 enum object_type *final_type, unsigned long *final_size)
1674 struct pack_window *w_curs = NULL;
1675 off_t curpos = obj_offset;
1676 void *data = NULL;
1677 unsigned long size;
1678 enum object_type type;
1679 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1680 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1681 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1682 int base_from_cache = 0;
1684 write_pack_access_log(p, obj_offset);
1686 /* PHASE 1: drill down to the innermost base object */
1687 for (;;) {
1688 off_t base_offset;
1689 int i;
1690 struct delta_base_cache_entry *ent;
1692 ent = get_delta_base_cache_entry(p, curpos);
1693 if (ent) {
1694 type = ent->type;
1695 data = ent->data;
1696 size = ent->size;
1697 detach_delta_base_cache_entry(ent);
1698 base_from_cache = 1;
1699 break;
1702 if (do_check_packed_object_crc && p->index_version > 1) {
1703 uint32_t pack_pos, index_pos;
1704 off_t len;
1706 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1707 error("could not find object at offset %"PRIuMAX" in pack %s",
1708 (uintmax_t)obj_offset, p->pack_name);
1709 data = NULL;
1710 goto out;
1713 len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1714 index_pos = pack_pos_to_index(p, pack_pos);
1715 if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1716 struct object_id oid;
1717 nth_packed_object_id(&oid, p, index_pos);
1718 error("bad packed object CRC for %s",
1719 oid_to_hex(&oid));
1720 mark_bad_packed_object(p, &oid);
1721 data = NULL;
1722 goto out;
1726 type = unpack_object_header(p, &w_curs, &curpos, &size);
1727 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1728 break;
1730 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1731 if (!base_offset) {
1732 error("failed to validate delta base reference "
1733 "at offset %"PRIuMAX" from %s",
1734 (uintmax_t)curpos, p->pack_name);
1735 /* bail to phase 2, in hopes of recovery */
1736 data = NULL;
1737 break;
1740 /* push object, proceed to base */
1741 if (delta_stack_nr >= delta_stack_alloc
1742 && delta_stack == small_delta_stack) {
1743 delta_stack_alloc = alloc_nr(delta_stack_nr);
1744 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1745 COPY_ARRAY(delta_stack, small_delta_stack,
1746 delta_stack_nr);
1747 } else {
1748 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1750 i = delta_stack_nr++;
1751 delta_stack[i].obj_offset = obj_offset;
1752 delta_stack[i].curpos = curpos;
1753 delta_stack[i].size = size;
1755 curpos = obj_offset = base_offset;
1758 /* PHASE 2: handle the base */
1759 switch (type) {
1760 case OBJ_OFS_DELTA:
1761 case OBJ_REF_DELTA:
1762 if (data)
1763 BUG("unpack_entry: left loop at a valid delta");
1764 break;
1765 case OBJ_COMMIT:
1766 case OBJ_TREE:
1767 case OBJ_BLOB:
1768 case OBJ_TAG:
1769 if (!base_from_cache)
1770 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1771 break;
1772 default:
1773 data = NULL;
1774 error("unknown object type %i at offset %"PRIuMAX" in %s",
1775 type, (uintmax_t)obj_offset, p->pack_name);
1778 /* PHASE 3: apply deltas in order */
1780 /* invariants:
1781 * 'data' holds the base data, or NULL if there was corruption
1783 while (delta_stack_nr) {
1784 void *delta_data;
1785 void *base = data;
1786 void *external_base = NULL;
1787 unsigned long delta_size, base_size = size;
1788 int i;
1789 off_t base_obj_offset = obj_offset;
1791 data = NULL;
1793 if (!base) {
1795 * We're probably in deep shit, but let's try to fetch
1796 * the required base anyway from another pack or loose.
1797 * This is costly but should happen only in the presence
1798 * of a corrupted pack, and is better than failing outright.
1800 uint32_t pos;
1801 struct object_id base_oid;
1802 if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1803 struct object_info oi = OBJECT_INFO_INIT;
1805 nth_packed_object_id(&base_oid, p,
1806 pack_pos_to_index(p, pos));
1807 error("failed to read delta base object %s"
1808 " at offset %"PRIuMAX" from %s",
1809 oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1810 p->pack_name);
1811 mark_bad_packed_object(p, &base_oid);
1813 oi.typep = &type;
1814 oi.sizep = &base_size;
1815 oi.contentp = &base;
1816 if (oid_object_info_extended(r, &base_oid, &oi, 0) < 0)
1817 base = NULL;
1819 external_base = base;
1823 i = --delta_stack_nr;
1824 obj_offset = delta_stack[i].obj_offset;
1825 curpos = delta_stack[i].curpos;
1826 delta_size = delta_stack[i].size;
1828 if (!base)
1829 continue;
1831 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1833 if (!delta_data) {
1834 error("failed to unpack compressed delta "
1835 "at offset %"PRIuMAX" from %s",
1836 (uintmax_t)curpos, p->pack_name);
1837 data = NULL;
1838 } else {
1839 data = patch_delta(base, base_size, delta_data,
1840 delta_size, &size);
1843 * We could not apply the delta; warn the user, but
1844 * keep going. Our failure will be noticed either in
1845 * the next iteration of the loop, or if this is the
1846 * final delta, in the caller when we return NULL.
1847 * Those code paths will take care of making a more
1848 * explicit warning and retrying with another copy of
1849 * the object.
1851 if (!data)
1852 error("failed to apply delta");
1856 * We delay adding `base` to the cache until the end of the loop
1857 * because unpack_compressed_entry() momentarily releases the
1858 * obj_read_mutex, giving another thread the chance to access
1859 * the cache. Therefore, if `base` was already there, this other
1860 * thread could free() it (e.g. to make space for another entry)
1861 * before we are done using it.
1863 if (!external_base)
1864 add_delta_base_cache(p, base_obj_offset, base, base_size, type);
1866 free(delta_data);
1867 free(external_base);
1870 if (final_type)
1871 *final_type = type;
1872 if (final_size)
1873 *final_size = size;
1875 out:
1876 unuse_pack(&w_curs);
1878 if (delta_stack != small_delta_stack)
1879 free(delta_stack);
1881 return data;
1884 int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1886 const unsigned char *index_fanout = p->index_data;
1887 const unsigned char *index_lookup;
1888 const unsigned int hashsz = the_hash_algo->rawsz;
1889 int index_lookup_width;
1891 if (!index_fanout)
1892 BUG("bsearch_pack called without a valid pack-index");
1894 index_lookup = index_fanout + 4 * 256;
1895 if (p->index_version == 1) {
1896 index_lookup_width = hashsz + 4;
1897 index_lookup += 4;
1898 } else {
1899 index_lookup_width = hashsz;
1900 index_fanout += 8;
1901 index_lookup += 8;
1904 return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1905 index_lookup, index_lookup_width, result);
1908 int nth_packed_object_id(struct object_id *oid,
1909 struct packed_git *p,
1910 uint32_t n)
1912 const unsigned char *index = p->index_data;
1913 const unsigned int hashsz = the_hash_algo->rawsz;
1914 if (!index) {
1915 if (open_pack_index(p))
1916 return -1;
1917 index = p->index_data;
1919 if (n >= p->num_objects)
1920 return -1;
1921 index += 4 * 256;
1922 if (p->index_version == 1) {
1923 oidread(oid, index + (hashsz + 4) * n + 4);
1924 } else {
1925 index += 8;
1926 oidread(oid, index + hashsz * n);
1928 return 0;
1931 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1933 const unsigned char *ptr = vptr;
1934 const unsigned char *start = p->index_data;
1935 const unsigned char *end = start + p->index_size;
1936 if (ptr < start)
1937 die(_("offset before start of pack index for %s (corrupt index?)"),
1938 p->pack_name);
1939 /* No need to check for underflow; .idx files must be at least 8 bytes */
1940 if (ptr >= end - 8)
1941 die(_("offset beyond end of pack index for %s (truncated index?)"),
1942 p->pack_name);
1945 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1947 const unsigned char *index = p->index_data;
1948 const unsigned int hashsz = the_hash_algo->rawsz;
1949 index += 4 * 256;
1950 if (p->index_version == 1) {
1951 return ntohl(*((uint32_t *)(index + (hashsz + 4) * (size_t)n)));
1952 } else {
1953 uint32_t off;
1954 index += 8 + (size_t)p->num_objects * (hashsz + 4);
1955 off = ntohl(*((uint32_t *)(index + 4 * n)));
1956 if (!(off & 0x80000000))
1957 return off;
1958 index += (size_t)p->num_objects * 4 + (off & 0x7fffffff) * 8;
1959 check_pack_index_ptr(p, index);
1960 return get_be64(index);
1964 off_t find_pack_entry_one(const unsigned char *sha1,
1965 struct packed_git *p)
1967 const unsigned char *index = p->index_data;
1968 struct object_id oid;
1969 uint32_t result;
1971 if (!index) {
1972 if (open_pack_index(p))
1973 return 0;
1976 hashcpy(oid.hash, sha1);
1977 if (bsearch_pack(&oid, p, &result))
1978 return nth_packed_object_offset(p, result);
1979 return 0;
1982 int is_pack_valid(struct packed_git *p)
1984 /* An already open pack is known to be valid. */
1985 if (p->pack_fd != -1)
1986 return 1;
1988 /* If the pack has one window completely covering the
1989 * file size, the pack is known to be valid even if
1990 * the descriptor is not currently open.
1992 if (p->windows) {
1993 struct pack_window *w = p->windows;
1995 if (!w->offset && w->len == p->pack_size)
1996 return 1;
1999 /* Force the pack to open to prove its valid. */
2000 return !open_packed_git(p);
2003 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2004 struct packed_git *packs)
2006 struct packed_git *p;
2008 for (p = packs; p; p = p->next) {
2009 if (find_pack_entry_one(sha1, p))
2010 return p;
2012 return NULL;
2016 static int fill_pack_entry(const struct object_id *oid,
2017 struct pack_entry *e,
2018 struct packed_git *p)
2020 off_t offset;
2022 if (oidset_size(&p->bad_objects) &&
2023 oidset_contains(&p->bad_objects, oid))
2024 return 0;
2026 offset = find_pack_entry_one(oid->hash, p);
2027 if (!offset)
2028 return 0;
2031 * We are about to tell the caller where they can locate the
2032 * requested object. We better make sure the packfile is
2033 * still here and can be accessed before supplying that
2034 * answer, as it may have been deleted since the index was
2035 * loaded!
2037 if (!is_pack_valid(p))
2038 return 0;
2039 e->offset = offset;
2040 e->p = p;
2041 return 1;
2044 int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
2046 struct list_head *pos;
2047 struct multi_pack_index *m;
2049 prepare_packed_git(r);
2050 if (!r->objects->packed_git && !r->objects->multi_pack_index)
2051 return 0;
2053 for (m = r->objects->multi_pack_index; m; m = m->next) {
2054 if (fill_midx_entry(r, oid, e, m))
2055 return 1;
2058 list_for_each(pos, &r->objects->packed_git_mru) {
2059 struct packed_git *p = list_entry(pos, struct packed_git, mru);
2060 if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
2061 list_move(&p->mru, &r->objects->packed_git_mru);
2062 return 1;
2065 return 0;
2068 static void maybe_invalidate_kept_pack_cache(struct repository *r,
2069 unsigned flags)
2071 if (!r->objects->kept_pack_cache.packs)
2072 return;
2073 if (r->objects->kept_pack_cache.flags == flags)
2074 return;
2075 FREE_AND_NULL(r->objects->kept_pack_cache.packs);
2076 r->objects->kept_pack_cache.flags = 0;
2079 static struct packed_git **kept_pack_cache(struct repository *r, unsigned flags)
2081 maybe_invalidate_kept_pack_cache(r, flags);
2083 if (!r->objects->kept_pack_cache.packs) {
2084 struct packed_git **packs = NULL;
2085 size_t nr = 0, alloc = 0;
2086 struct packed_git *p;
2089 * We want "all" packs here, because we need to cover ones that
2090 * are used by a midx, as well. We need to look in every one of
2091 * them (instead of the midx itself) to cover duplicates. It's
2092 * possible that an object is found in two packs that the midx
2093 * covers, one kept and one not kept, but the midx returns only
2094 * the non-kept version.
2096 for (p = get_all_packs(r); p; p = p->next) {
2097 if ((p->pack_keep && (flags & ON_DISK_KEEP_PACKS)) ||
2098 (p->pack_keep_in_core && (flags & IN_CORE_KEEP_PACKS))) {
2099 ALLOC_GROW(packs, nr + 1, alloc);
2100 packs[nr++] = p;
2103 ALLOC_GROW(packs, nr + 1, alloc);
2104 packs[nr] = NULL;
2106 r->objects->kept_pack_cache.packs = packs;
2107 r->objects->kept_pack_cache.flags = flags;
2110 return r->objects->kept_pack_cache.packs;
2113 int find_kept_pack_entry(struct repository *r,
2114 const struct object_id *oid,
2115 unsigned flags,
2116 struct pack_entry *e)
2118 struct packed_git **cache;
2120 for (cache = kept_pack_cache(r, flags); *cache; cache++) {
2121 struct packed_git *p = *cache;
2122 if (fill_pack_entry(oid, e, p))
2123 return 1;
2126 return 0;
2129 int has_object_pack(const struct object_id *oid)
2131 struct pack_entry e;
2132 return find_pack_entry(the_repository, oid, &e);
2135 int has_object_kept_pack(const struct object_id *oid, unsigned flags)
2137 struct pack_entry e;
2138 return find_kept_pack_entry(the_repository, oid, flags, &e);
2141 int has_pack_index(const unsigned char *sha1)
2143 struct stat st;
2144 if (stat(sha1_pack_index_name(sha1), &st))
2145 return 0;
2146 return 1;
2149 int for_each_object_in_pack(struct packed_git *p,
2150 each_packed_object_fn cb, void *data,
2151 enum for_each_object_flags flags)
2153 uint32_t i;
2154 int r = 0;
2156 if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2157 if (load_pack_revindex(the_repository, p))
2158 return -1;
2161 for (i = 0; i < p->num_objects; i++) {
2162 uint32_t index_pos;
2163 struct object_id oid;
2166 * We are iterating "i" from 0 up to num_objects, but its
2167 * meaning may be different, depending on the requested output
2168 * order:
2170 * - in object-name order, it is the same as the index order
2171 * used by nth_packed_object_id(), so we can pass it
2172 * directly
2174 * - in pack-order, it is pack position, which we must
2175 * convert to an index position in order to get the oid.
2177 if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2178 index_pos = pack_pos_to_index(p, i);
2179 else
2180 index_pos = i;
2182 if (nth_packed_object_id(&oid, p, index_pos) < 0)
2183 return error("unable to get sha1 of object %u in %s",
2184 index_pos, p->pack_name);
2186 r = cb(&oid, p, index_pos, data);
2187 if (r)
2188 break;
2190 return r;
2193 int for_each_packed_object(each_packed_object_fn cb, void *data,
2194 enum for_each_object_flags flags)
2196 struct packed_git *p;
2197 int r = 0;
2198 int pack_errors = 0;
2200 prepare_packed_git(the_repository);
2201 for (p = get_all_packs(the_repository); p; p = p->next) {
2202 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2203 continue;
2204 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2205 !p->pack_promisor)
2206 continue;
2207 if ((flags & FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS) &&
2208 p->pack_keep_in_core)
2209 continue;
2210 if ((flags & FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS) &&
2211 p->pack_keep)
2212 continue;
2213 if (open_pack_index(p)) {
2214 pack_errors = 1;
2215 continue;
2217 r = for_each_object_in_pack(p, cb, data, flags);
2218 if (r)
2219 break;
2221 return r ? r : pack_errors;
2224 static int add_promisor_object(const struct object_id *oid,
2225 struct packed_git *pack UNUSED,
2226 uint32_t pos UNUSED,
2227 void *set_)
2229 struct oidset *set = set_;
2230 struct object *obj;
2231 int we_parsed_object;
2233 obj = lookup_object(the_repository, oid);
2234 if (obj && obj->parsed) {
2235 we_parsed_object = 0;
2236 } else {
2237 we_parsed_object = 1;
2238 obj = parse_object(the_repository, oid);
2241 if (!obj)
2242 return 1;
2244 oidset_insert(set, oid);
2247 * If this is a tree, commit, or tag, the objects it refers
2248 * to are also promisor objects. (Blobs refer to no objects->)
2250 if (obj->type == OBJ_TREE) {
2251 struct tree *tree = (struct tree *)obj;
2252 struct tree_desc desc;
2253 struct name_entry entry;
2254 if (init_tree_desc_gently(&desc, tree->buffer, tree->size, 0))
2256 * Error messages are given when packs are
2257 * verified, so do not print any here.
2259 return 0;
2260 while (tree_entry_gently(&desc, &entry))
2261 oidset_insert(set, &entry.oid);
2262 if (we_parsed_object)
2263 free_tree_buffer(tree);
2264 } else if (obj->type == OBJ_COMMIT) {
2265 struct commit *commit = (struct commit *) obj;
2266 struct commit_list *parents = commit->parents;
2268 oidset_insert(set, get_commit_tree_oid(commit));
2269 for (; parents; parents = parents->next)
2270 oidset_insert(set, &parents->item->object.oid);
2271 } else if (obj->type == OBJ_TAG) {
2272 struct tag *tag = (struct tag *) obj;
2273 oidset_insert(set, get_tagged_oid(tag));
2275 return 0;
2278 int is_promisor_object(const struct object_id *oid)
2280 static struct oidset promisor_objects;
2281 static int promisor_objects_prepared;
2283 if (!promisor_objects_prepared) {
2284 if (repo_has_promisor_remote(the_repository)) {
2285 for_each_packed_object(add_promisor_object,
2286 &promisor_objects,
2287 FOR_EACH_OBJECT_PROMISOR_ONLY |
2288 FOR_EACH_OBJECT_PACK_ORDER);
2290 promisor_objects_prepared = 1;
2292 return oidset_contains(&promisor_objects, oid);