object-store: free alt_odb_list
[alt-git.git] / packfile.c
blobfdbf240f8171cbd99df21f1546aee08f86e38b20
1 #include "cache.h"
2 #include "list.h"
3 #include "pack.h"
4 #include "repository.h"
5 #include "dir.h"
6 #include "mergesort.h"
7 #include "packfile.h"
8 #include "delta.h"
9 #include "list.h"
10 #include "streaming.h"
11 #include "sha1-lookup.h"
12 #include "commit.h"
13 #include "object.h"
14 #include "tag.h"
15 #include "tree-walk.h"
16 #include "tree.h"
17 #include "object-store.h"
19 char *odb_pack_name(struct strbuf *buf,
20 const unsigned char *sha1,
21 const char *ext)
23 strbuf_reset(buf);
24 strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
25 sha1_to_hex(sha1), ext);
26 return buf->buf;
29 char *sha1_pack_name(const unsigned char *sha1)
31 static struct strbuf buf = STRBUF_INIT;
32 return odb_pack_name(&buf, sha1, "pack");
35 char *sha1_pack_index_name(const unsigned char *sha1)
37 static struct strbuf buf = STRBUF_INIT;
38 return odb_pack_name(&buf, sha1, "idx");
41 static unsigned int pack_used_ctr;
42 static unsigned int pack_mmap_calls;
43 static unsigned int peak_pack_open_windows;
44 static unsigned int pack_open_windows;
45 static unsigned int pack_open_fds;
46 static unsigned int pack_max_fds;
47 static size_t peak_pack_mapped;
48 static size_t pack_mapped;
49 struct packed_git *packed_git;
50 LIST_HEAD(packed_git_mru);
52 #define SZ_FMT PRIuMAX
53 static inline uintmax_t sz_fmt(size_t s) { return s; }
55 void pack_report(void)
57 fprintf(stderr,
58 "pack_report: getpagesize() = %10" SZ_FMT "\n"
59 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
60 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
61 sz_fmt(getpagesize()),
62 sz_fmt(packed_git_window_size),
63 sz_fmt(packed_git_limit));
64 fprintf(stderr,
65 "pack_report: pack_used_ctr = %10u\n"
66 "pack_report: pack_mmap_calls = %10u\n"
67 "pack_report: pack_open_windows = %10u / %10u\n"
68 "pack_report: pack_mapped = "
69 "%10" SZ_FMT " / %10" SZ_FMT "\n",
70 pack_used_ctr,
71 pack_mmap_calls,
72 pack_open_windows, peak_pack_open_windows,
73 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
77 * Open and mmap the index file at path, perform a couple of
78 * consistency checks, then record its information to p. Return 0 on
79 * success.
81 static int check_packed_git_idx(const char *path, struct packed_git *p)
83 void *idx_map;
84 struct pack_idx_header *hdr;
85 size_t idx_size;
86 uint32_t version, nr, i, *index;
87 int fd = git_open(path);
88 struct stat st;
90 if (fd < 0)
91 return -1;
92 if (fstat(fd, &st)) {
93 close(fd);
94 return -1;
96 idx_size = xsize_t(st.st_size);
97 if (idx_size < 4 * 256 + 20 + 20) {
98 close(fd);
99 return error("index file %s is too small", path);
101 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
102 close(fd);
104 hdr = idx_map;
105 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
106 version = ntohl(hdr->idx_version);
107 if (version < 2 || version > 2) {
108 munmap(idx_map, idx_size);
109 return error("index file %s is version %"PRIu32
110 " and is not supported by this binary"
111 " (try upgrading GIT to a newer version)",
112 path, version);
114 } else
115 version = 1;
117 nr = 0;
118 index = idx_map;
119 if (version > 1)
120 index += 2; /* skip index header */
121 for (i = 0; i < 256; i++) {
122 uint32_t n = ntohl(index[i]);
123 if (n < nr) {
124 munmap(idx_map, idx_size);
125 return error("non-monotonic index %s", path);
127 nr = n;
130 if (version == 1) {
132 * Total size:
133 * - 256 index entries 4 bytes each
134 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
135 * - 20-byte SHA1 of the packfile
136 * - 20-byte SHA1 file checksum
138 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
139 munmap(idx_map, idx_size);
140 return error("wrong index v1 file size in %s", path);
142 } else if (version == 2) {
144 * Minimum size:
145 * - 8 bytes of header
146 * - 256 index entries 4 bytes each
147 * - 20-byte sha1 entry * nr
148 * - 4-byte crc entry * nr
149 * - 4-byte offset entry * nr
150 * - 20-byte SHA1 of the packfile
151 * - 20-byte SHA1 file checksum
152 * And after the 4-byte offset table might be a
153 * variable sized table containing 8-byte entries
154 * for offsets larger than 2^31.
156 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
157 unsigned long max_size = min_size;
158 if (nr)
159 max_size += (nr - 1)*8;
160 if (idx_size < min_size || idx_size > max_size) {
161 munmap(idx_map, idx_size);
162 return error("wrong index v2 file size in %s", path);
164 if (idx_size != min_size &&
166 * make sure we can deal with large pack offsets.
167 * 31-bit signed offset won't be enough, neither
168 * 32-bit unsigned one will be.
170 (sizeof(off_t) <= 4)) {
171 munmap(idx_map, idx_size);
172 return error("pack too large for current definition of off_t in %s", path);
176 p->index_version = version;
177 p->index_data = idx_map;
178 p->index_size = idx_size;
179 p->num_objects = nr;
180 return 0;
183 int open_pack_index(struct packed_git *p)
185 char *idx_name;
186 size_t len;
187 int ret;
189 if (p->index_data)
190 return 0;
192 if (!strip_suffix(p->pack_name, ".pack", &len))
193 die("BUG: pack_name does not end in .pack");
194 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
195 ret = check_packed_git_idx(idx_name, p);
196 free(idx_name);
197 return ret;
200 static struct packed_git *alloc_packed_git(int extra)
202 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
203 memset(p, 0, sizeof(*p));
204 p->pack_fd = -1;
205 return p;
208 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
210 const char *path = sha1_pack_name(sha1);
211 size_t alloc = st_add(strlen(path), 1);
212 struct packed_git *p = alloc_packed_git(alloc);
214 memcpy(p->pack_name, path, alloc); /* includes NUL */
215 hashcpy(p->sha1, sha1);
216 if (check_packed_git_idx(idx_path, p)) {
217 free(p);
218 return NULL;
221 return p;
224 static void scan_windows(struct packed_git *p,
225 struct packed_git **lru_p,
226 struct pack_window **lru_w,
227 struct pack_window **lru_l)
229 struct pack_window *w, *w_l;
231 for (w_l = NULL, w = p->windows; w; w = w->next) {
232 if (!w->inuse_cnt) {
233 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
234 *lru_p = p;
235 *lru_w = w;
236 *lru_l = w_l;
239 w_l = w;
243 static int unuse_one_window(struct packed_git *current)
245 struct packed_git *p, *lru_p = NULL;
246 struct pack_window *lru_w = NULL, *lru_l = NULL;
248 if (current)
249 scan_windows(current, &lru_p, &lru_w, &lru_l);
250 for (p = packed_git; p; p = p->next)
251 scan_windows(p, &lru_p, &lru_w, &lru_l);
252 if (lru_p) {
253 munmap(lru_w->base, lru_w->len);
254 pack_mapped -= lru_w->len;
255 if (lru_l)
256 lru_l->next = lru_w->next;
257 else
258 lru_p->windows = lru_w->next;
259 free(lru_w);
260 pack_open_windows--;
261 return 1;
263 return 0;
266 void release_pack_memory(size_t need)
268 size_t cur = pack_mapped;
269 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
270 ; /* nothing */
273 void close_pack_windows(struct packed_git *p)
275 while (p->windows) {
276 struct pack_window *w = p->windows;
278 if (w->inuse_cnt)
279 die("pack '%s' still has open windows to it",
280 p->pack_name);
281 munmap(w->base, w->len);
282 pack_mapped -= w->len;
283 pack_open_windows--;
284 p->windows = w->next;
285 free(w);
289 static int close_pack_fd(struct packed_git *p)
291 if (p->pack_fd < 0)
292 return 0;
294 close(p->pack_fd);
295 pack_open_fds--;
296 p->pack_fd = -1;
298 return 1;
301 void close_pack_index(struct packed_git *p)
303 if (p->index_data) {
304 munmap((void *)p->index_data, p->index_size);
305 p->index_data = NULL;
309 static void close_pack(struct packed_git *p)
311 close_pack_windows(p);
312 close_pack_fd(p);
313 close_pack_index(p);
316 void close_all_packs(void)
318 struct packed_git *p;
320 for (p = packed_git; p; p = p->next)
321 if (p->do_not_close)
322 die("BUG: want to close pack marked 'do-not-close'");
323 else
324 close_pack(p);
328 * The LRU pack is the one with the oldest MRU window, preferring packs
329 * with no used windows, or the oldest mtime if it has no windows allocated.
331 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
333 struct pack_window *w, *this_mru_w;
334 int has_windows_inuse = 0;
337 * Reject this pack if it has windows and the previously selected
338 * one does not. If this pack does not have windows, reject
339 * it if the pack file is newer than the previously selected one.
341 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
342 return;
344 for (w = this_mru_w = p->windows; w; w = w->next) {
346 * Reject this pack if any of its windows are in use,
347 * but the previously selected pack did not have any
348 * inuse windows. Otherwise, record that this pack
349 * has windows in use.
351 if (w->inuse_cnt) {
352 if (*accept_windows_inuse)
353 has_windows_inuse = 1;
354 else
355 return;
358 if (w->last_used > this_mru_w->last_used)
359 this_mru_w = w;
362 * Reject this pack if it has windows that have been
363 * used more recently than the previously selected pack.
364 * If the previously selected pack had windows inuse and
365 * we have not encountered a window in this pack that is
366 * inuse, skip this check since we prefer a pack with no
367 * inuse windows to one that has inuse windows.
369 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
370 this_mru_w->last_used > (*mru_w)->last_used)
371 return;
375 * Select this pack.
377 *mru_w = this_mru_w;
378 *lru_p = p;
379 *accept_windows_inuse = has_windows_inuse;
382 static int close_one_pack(void)
384 struct packed_git *p, *lru_p = NULL;
385 struct pack_window *mru_w = NULL;
386 int accept_windows_inuse = 1;
388 for (p = packed_git; p; p = p->next) {
389 if (p->pack_fd == -1)
390 continue;
391 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
394 if (lru_p)
395 return close_pack_fd(lru_p);
397 return 0;
400 static unsigned int get_max_fd_limit(void)
402 #ifdef RLIMIT_NOFILE
404 struct rlimit lim;
406 if (!getrlimit(RLIMIT_NOFILE, &lim))
407 return lim.rlim_cur;
409 #endif
411 #ifdef _SC_OPEN_MAX
413 long open_max = sysconf(_SC_OPEN_MAX);
414 if (0 < open_max)
415 return open_max;
417 * Otherwise, we got -1 for one of the two
418 * reasons:
420 * (1) sysconf() did not understand _SC_OPEN_MAX
421 * and signaled an error with -1; or
422 * (2) sysconf() said there is no limit.
424 * We _could_ clear errno before calling sysconf() to
425 * tell these two cases apart and return a huge number
426 * in the latter case to let the caller cap it to a
427 * value that is not so selfish, but letting the
428 * fallback OPEN_MAX codepath take care of these cases
429 * is a lot simpler.
432 #endif
434 #ifdef OPEN_MAX
435 return OPEN_MAX;
436 #else
437 return 1; /* see the caller ;-) */
438 #endif
442 * Do not call this directly as this leaks p->pack_fd on error return;
443 * call open_packed_git() instead.
445 static int open_packed_git_1(struct packed_git *p)
447 struct stat st;
448 struct pack_header hdr;
449 unsigned char sha1[20];
450 unsigned char *idx_sha1;
451 long fd_flag;
452 ssize_t read_result;
454 if (!p->index_data && open_pack_index(p))
455 return error("packfile %s index unavailable", p->pack_name);
457 if (!pack_max_fds) {
458 unsigned int max_fds = get_max_fd_limit();
460 /* Save 3 for stdin/stdout/stderr, 22 for work */
461 if (25 < max_fds)
462 pack_max_fds = max_fds - 25;
463 else
464 pack_max_fds = 1;
467 while (pack_max_fds <= pack_open_fds && close_one_pack())
468 ; /* nothing */
470 p->pack_fd = git_open(p->pack_name);
471 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
472 return -1;
473 pack_open_fds++;
475 /* If we created the struct before we had the pack we lack size. */
476 if (!p->pack_size) {
477 if (!S_ISREG(st.st_mode))
478 return error("packfile %s not a regular file", p->pack_name);
479 p->pack_size = st.st_size;
480 } else if (p->pack_size != st.st_size)
481 return error("packfile %s size changed", p->pack_name);
483 /* We leave these file descriptors open with sliding mmap;
484 * there is no point keeping them open across exec(), though.
486 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
487 if (fd_flag < 0)
488 return error("cannot determine file descriptor flags");
489 fd_flag |= FD_CLOEXEC;
490 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
491 return error("cannot set FD_CLOEXEC");
493 /* Verify we recognize this pack file format. */
494 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
495 if (read_result < 0)
496 return error_errno("error reading from %s", p->pack_name);
497 if (read_result != sizeof(hdr))
498 return error("file %s is far too short to be a packfile", p->pack_name);
499 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
500 return error("file %s is not a GIT packfile", p->pack_name);
501 if (!pack_version_ok(hdr.hdr_version))
502 return error("packfile %s is version %"PRIu32" and not"
503 " supported (try upgrading GIT to a newer version)",
504 p->pack_name, ntohl(hdr.hdr_version));
506 /* Verify the pack matches its index. */
507 if (p->num_objects != ntohl(hdr.hdr_entries))
508 return error("packfile %s claims to have %"PRIu32" objects"
509 " while index indicates %"PRIu32" objects",
510 p->pack_name, ntohl(hdr.hdr_entries),
511 p->num_objects);
512 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
513 return error("end of packfile %s is unavailable", p->pack_name);
514 read_result = read_in_full(p->pack_fd, sha1, sizeof(sha1));
515 if (read_result < 0)
516 return error_errno("error reading from %s", p->pack_name);
517 if (read_result != sizeof(sha1))
518 return error("packfile %s signature is unavailable", p->pack_name);
519 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
520 if (hashcmp(sha1, idx_sha1))
521 return error("packfile %s does not match index", p->pack_name);
522 return 0;
525 static int open_packed_git(struct packed_git *p)
527 if (!open_packed_git_1(p))
528 return 0;
529 close_pack_fd(p);
530 return -1;
533 static int in_window(struct pack_window *win, off_t offset)
535 /* We must promise at least 20 bytes (one hash) after the
536 * offset is available from this window, otherwise the offset
537 * is not actually in this window and a different window (which
538 * has that one hash excess) must be used. This is to support
539 * the object header and delta base parsing routines below.
541 off_t win_off = win->offset;
542 return win_off <= offset
543 && (offset + 20) <= (win_off + win->len);
546 unsigned char *use_pack(struct packed_git *p,
547 struct pack_window **w_cursor,
548 off_t offset,
549 unsigned long *left)
551 struct pack_window *win = *w_cursor;
553 /* Since packfiles end in a hash of their content and it's
554 * pointless to ask for an offset into the middle of that
555 * hash, and the in_window function above wouldn't match
556 * don't allow an offset too close to the end of the file.
558 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
559 die("packfile %s cannot be accessed", p->pack_name);
560 if (offset > (p->pack_size - 20))
561 die("offset beyond end of packfile (truncated pack?)");
562 if (offset < 0)
563 die(_("offset before end of packfile (broken .idx?)"));
565 if (!win || !in_window(win, offset)) {
566 if (win)
567 win->inuse_cnt--;
568 for (win = p->windows; win; win = win->next) {
569 if (in_window(win, offset))
570 break;
572 if (!win) {
573 size_t window_align = packed_git_window_size / 2;
574 off_t len;
576 if (p->pack_fd == -1 && open_packed_git(p))
577 die("packfile %s cannot be accessed", p->pack_name);
579 win = xcalloc(1, sizeof(*win));
580 win->offset = (offset / window_align) * window_align;
581 len = p->pack_size - win->offset;
582 if (len > packed_git_window_size)
583 len = packed_git_window_size;
584 win->len = (size_t)len;
585 pack_mapped += win->len;
586 while (packed_git_limit < pack_mapped
587 && unuse_one_window(p))
588 ; /* nothing */
589 win->base = xmmap(NULL, win->len,
590 PROT_READ, MAP_PRIVATE,
591 p->pack_fd, win->offset);
592 if (win->base == MAP_FAILED)
593 die_errno("packfile %s cannot be mapped",
594 p->pack_name);
595 if (!win->offset && win->len == p->pack_size
596 && !p->do_not_close)
597 close_pack_fd(p);
598 pack_mmap_calls++;
599 pack_open_windows++;
600 if (pack_mapped > peak_pack_mapped)
601 peak_pack_mapped = pack_mapped;
602 if (pack_open_windows > peak_pack_open_windows)
603 peak_pack_open_windows = pack_open_windows;
604 win->next = p->windows;
605 p->windows = win;
608 if (win != *w_cursor) {
609 win->last_used = pack_used_ctr++;
610 win->inuse_cnt++;
611 *w_cursor = win;
613 offset -= win->offset;
614 if (left)
615 *left = win->len - xsize_t(offset);
616 return win->base + offset;
619 void unuse_pack(struct pack_window **w_cursor)
621 struct pack_window *w = *w_cursor;
622 if (w) {
623 w->inuse_cnt--;
624 *w_cursor = NULL;
628 static void try_to_free_pack_memory(size_t size)
630 release_pack_memory(size);
633 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
635 static int have_set_try_to_free_routine;
636 struct stat st;
637 size_t alloc;
638 struct packed_git *p;
640 if (!have_set_try_to_free_routine) {
641 have_set_try_to_free_routine = 1;
642 set_try_to_free_routine(try_to_free_pack_memory);
646 * Make sure a corresponding .pack file exists and that
647 * the index looks sane.
649 if (!strip_suffix_mem(path, &path_len, ".idx"))
650 return NULL;
653 * ".promisor" is long enough to hold any suffix we're adding (and
654 * the use xsnprintf double-checks that)
656 alloc = st_add3(path_len, strlen(".promisor"), 1);
657 p = alloc_packed_git(alloc);
658 memcpy(p->pack_name, path, path_len);
660 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
661 if (!access(p->pack_name, F_OK))
662 p->pack_keep = 1;
664 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
665 if (!access(p->pack_name, F_OK))
666 p->pack_promisor = 1;
668 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
669 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
670 free(p);
671 return NULL;
674 /* ok, it looks sane as far as we can check without
675 * actually mapping the pack file.
677 p->pack_size = st.st_size;
678 p->pack_local = local;
679 p->mtime = st.st_mtime;
680 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
681 hashclr(p->sha1);
682 return p;
685 void install_packed_git(struct packed_git *pack)
687 if (pack->pack_fd != -1)
688 pack_open_fds++;
690 pack->next = packed_git;
691 packed_git = pack;
694 void (*report_garbage)(unsigned seen_bits, const char *path);
696 static void report_helper(const struct string_list *list,
697 int seen_bits, int first, int last)
699 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
700 return;
702 for (; first < last; first++)
703 report_garbage(seen_bits, list->items[first].string);
706 static void report_pack_garbage(struct string_list *list)
708 int i, baselen = -1, first = 0, seen_bits = 0;
710 if (!report_garbage)
711 return;
713 string_list_sort(list);
715 for (i = 0; i < list->nr; i++) {
716 const char *path = list->items[i].string;
717 if (baselen != -1 &&
718 strncmp(path, list->items[first].string, baselen)) {
719 report_helper(list, seen_bits, first, i);
720 baselen = -1;
721 seen_bits = 0;
723 if (baselen == -1) {
724 const char *dot = strrchr(path, '.');
725 if (!dot) {
726 report_garbage(PACKDIR_FILE_GARBAGE, path);
727 continue;
729 baselen = dot - path + 1;
730 first = i;
732 if (!strcmp(path + baselen, "pack"))
733 seen_bits |= 1;
734 else if (!strcmp(path + baselen, "idx"))
735 seen_bits |= 2;
737 report_helper(list, seen_bits, first, list->nr);
740 static void prepare_packed_git_one(char *objdir, int local)
742 struct strbuf path = STRBUF_INIT;
743 size_t dirnamelen;
744 DIR *dir;
745 struct dirent *de;
746 struct string_list garbage = STRING_LIST_INIT_DUP;
748 strbuf_addstr(&path, objdir);
749 strbuf_addstr(&path, "/pack");
750 dir = opendir(path.buf);
751 if (!dir) {
752 if (errno != ENOENT)
753 error_errno("unable to open object pack directory: %s",
754 path.buf);
755 strbuf_release(&path);
756 return;
758 strbuf_addch(&path, '/');
759 dirnamelen = path.len;
760 while ((de = readdir(dir)) != NULL) {
761 struct packed_git *p;
762 size_t base_len;
764 if (is_dot_or_dotdot(de->d_name))
765 continue;
767 strbuf_setlen(&path, dirnamelen);
768 strbuf_addstr(&path, de->d_name);
770 base_len = path.len;
771 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
772 /* Don't reopen a pack we already have. */
773 for (p = packed_git; p; p = p->next) {
774 size_t len;
775 if (strip_suffix(p->pack_name, ".pack", &len) &&
776 len == base_len &&
777 !memcmp(p->pack_name, path.buf, len))
778 break;
780 if (p == NULL &&
782 * See if it really is a valid .idx file with
783 * corresponding .pack file that we can map.
785 (p = add_packed_git(path.buf, path.len, local)) != NULL)
786 install_packed_git(p);
789 if (!report_garbage)
790 continue;
792 if (ends_with(de->d_name, ".idx") ||
793 ends_with(de->d_name, ".pack") ||
794 ends_with(de->d_name, ".bitmap") ||
795 ends_with(de->d_name, ".keep") ||
796 ends_with(de->d_name, ".promisor"))
797 string_list_append(&garbage, path.buf);
798 else
799 report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
801 closedir(dir);
802 report_pack_garbage(&garbage);
803 string_list_clear(&garbage, 0);
804 strbuf_release(&path);
807 static int approximate_object_count_valid;
810 * Give a fast, rough count of the number of objects in the repository. This
811 * ignores loose objects completely. If you have a lot of them, then either
812 * you should repack because your performance will be awful, or they are
813 * all unreachable objects about to be pruned, in which case they're not really
814 * interesting as a measure of repo size in the first place.
816 unsigned long approximate_object_count(void)
818 static unsigned long count;
819 if (!approximate_object_count_valid) {
820 struct packed_git *p;
822 prepare_packed_git();
823 count = 0;
824 for (p = packed_git; p; p = p->next) {
825 if (open_pack_index(p))
826 continue;
827 count += p->num_objects;
830 return count;
833 static void *get_next_packed_git(const void *p)
835 return ((const struct packed_git *)p)->next;
838 static void set_next_packed_git(void *p, void *next)
840 ((struct packed_git *)p)->next = next;
843 static int sort_pack(const void *a_, const void *b_)
845 const struct packed_git *a = a_;
846 const struct packed_git *b = b_;
847 int st;
850 * Local packs tend to contain objects specific to our
851 * variant of the project than remote ones. In addition,
852 * remote ones could be on a network mounted filesystem.
853 * Favor local ones for these reasons.
855 st = a->pack_local - b->pack_local;
856 if (st)
857 return -st;
860 * Younger packs tend to contain more recent objects,
861 * and more recent objects tend to get accessed more
862 * often.
864 if (a->mtime < b->mtime)
865 return 1;
866 else if (a->mtime == b->mtime)
867 return 0;
868 return -1;
871 static void rearrange_packed_git(void)
873 packed_git = llist_mergesort(packed_git, get_next_packed_git,
874 set_next_packed_git, sort_pack);
877 static void prepare_packed_git_mru(void)
879 struct packed_git *p;
881 INIT_LIST_HEAD(&packed_git_mru);
883 for (p = packed_git; p; p = p->next)
884 list_add_tail(&p->mru, &packed_git_mru);
887 static int prepare_packed_git_run_once = 0;
888 void prepare_packed_git(void)
890 struct alternate_object_database *alt;
892 if (prepare_packed_git_run_once)
893 return;
894 prepare_packed_git_one(get_object_directory(), 1);
895 prepare_alt_odb();
896 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next)
897 prepare_packed_git_one(alt->path, 0);
898 rearrange_packed_git();
899 prepare_packed_git_mru();
900 prepare_packed_git_run_once = 1;
903 void reprepare_packed_git(void)
905 approximate_object_count_valid = 0;
906 prepare_packed_git_run_once = 0;
907 prepare_packed_git();
910 unsigned long unpack_object_header_buffer(const unsigned char *buf,
911 unsigned long len, enum object_type *type, unsigned long *sizep)
913 unsigned shift;
914 unsigned long size, c;
915 unsigned long used = 0;
917 c = buf[used++];
918 *type = (c >> 4) & 7;
919 size = c & 15;
920 shift = 4;
921 while (c & 0x80) {
922 if (len <= used || bitsizeof(long) <= shift) {
923 error("bad object header");
924 size = used = 0;
925 break;
927 c = buf[used++];
928 size += (c & 0x7f) << shift;
929 shift += 7;
931 *sizep = size;
932 return used;
935 unsigned long get_size_from_delta(struct packed_git *p,
936 struct pack_window **w_curs,
937 off_t curpos)
939 const unsigned char *data;
940 unsigned char delta_head[20], *in;
941 git_zstream stream;
942 int st;
944 memset(&stream, 0, sizeof(stream));
945 stream.next_out = delta_head;
946 stream.avail_out = sizeof(delta_head);
948 git_inflate_init(&stream);
949 do {
950 in = use_pack(p, w_curs, curpos, &stream.avail_in);
951 stream.next_in = in;
952 st = git_inflate(&stream, Z_FINISH);
953 curpos += stream.next_in - in;
954 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
955 stream.total_out < sizeof(delta_head));
956 git_inflate_end(&stream);
957 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
958 error("delta data unpack-initial failed");
959 return 0;
962 /* Examine the initial part of the delta to figure out
963 * the result size.
965 data = delta_head;
967 /* ignore base size */
968 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
970 /* Read the result size */
971 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
974 int unpack_object_header(struct packed_git *p,
975 struct pack_window **w_curs,
976 off_t *curpos,
977 unsigned long *sizep)
979 unsigned char *base;
980 unsigned long left;
981 unsigned long used;
982 enum object_type type;
984 /* use_pack() assures us we have [base, base + 20) available
985 * as a range that we can look at. (Its actually the hash
986 * size that is assured.) With our object header encoding
987 * the maximum deflated object size is 2^137, which is just
988 * insane, so we know won't exceed what we have been given.
990 base = use_pack(p, w_curs, *curpos, &left);
991 used = unpack_object_header_buffer(base, left, &type, sizep);
992 if (!used) {
993 type = OBJ_BAD;
994 } else
995 *curpos += used;
997 return type;
1000 void mark_bad_packed_object(struct packed_git *p, const unsigned char *sha1)
1002 unsigned i;
1003 for (i = 0; i < p->num_bad_objects; i++)
1004 if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1005 return;
1006 p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1007 st_mult(GIT_MAX_RAWSZ,
1008 st_add(p->num_bad_objects, 1)));
1009 hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1010 p->num_bad_objects++;
1013 const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1015 struct packed_git *p;
1016 unsigned i;
1018 for (p = packed_git; p; p = p->next)
1019 for (i = 0; i < p->num_bad_objects; i++)
1020 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1021 return p;
1022 return NULL;
1025 static off_t get_delta_base(struct packed_git *p,
1026 struct pack_window **w_curs,
1027 off_t *curpos,
1028 enum object_type type,
1029 off_t delta_obj_offset)
1031 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1032 off_t base_offset;
1034 /* use_pack() assured us we have [base_info, base_info + 20)
1035 * as a range that we can look at without walking off the
1036 * end of the mapped window. Its actually the hash size
1037 * that is assured. An OFS_DELTA longer than the hash size
1038 * is stupid, as then a REF_DELTA would be smaller to store.
1040 if (type == OBJ_OFS_DELTA) {
1041 unsigned used = 0;
1042 unsigned char c = base_info[used++];
1043 base_offset = c & 127;
1044 while (c & 128) {
1045 base_offset += 1;
1046 if (!base_offset || MSB(base_offset, 7))
1047 return 0; /* overflow */
1048 c = base_info[used++];
1049 base_offset = (base_offset << 7) + (c & 127);
1051 base_offset = delta_obj_offset - base_offset;
1052 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1053 return 0; /* out of bound */
1054 *curpos += used;
1055 } else if (type == OBJ_REF_DELTA) {
1056 /* The base entry _must_ be in the same pack */
1057 base_offset = find_pack_entry_one(base_info, p);
1058 *curpos += 20;
1059 } else
1060 die("I am totally screwed");
1061 return base_offset;
1065 * Like get_delta_base above, but we return the sha1 instead of the pack
1066 * offset. This means it is cheaper for REF deltas (we do not have to do
1067 * the final object lookup), but more expensive for OFS deltas (we
1068 * have to load the revidx to convert the offset back into a sha1).
1070 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1071 struct pack_window **w_curs,
1072 off_t curpos,
1073 enum object_type type,
1074 off_t delta_obj_offset)
1076 if (type == OBJ_REF_DELTA) {
1077 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1078 return base;
1079 } else if (type == OBJ_OFS_DELTA) {
1080 struct revindex_entry *revidx;
1081 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1082 type, delta_obj_offset);
1084 if (!base_offset)
1085 return NULL;
1087 revidx = find_pack_revindex(p, base_offset);
1088 if (!revidx)
1089 return NULL;
1091 return nth_packed_object_sha1(p, revidx->nr);
1092 } else
1093 return NULL;
1096 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1098 int type;
1099 struct revindex_entry *revidx;
1100 const unsigned char *sha1;
1101 revidx = find_pack_revindex(p, obj_offset);
1102 if (!revidx)
1103 return OBJ_BAD;
1104 sha1 = nth_packed_object_sha1(p, revidx->nr);
1105 mark_bad_packed_object(p, sha1);
1106 type = sha1_object_info(sha1, NULL);
1107 if (type <= OBJ_NONE)
1108 return OBJ_BAD;
1109 return type;
1112 #define POI_STACK_PREALLOC 64
1114 static enum object_type packed_to_object_type(struct packed_git *p,
1115 off_t obj_offset,
1116 enum object_type type,
1117 struct pack_window **w_curs,
1118 off_t curpos)
1120 off_t small_poi_stack[POI_STACK_PREALLOC];
1121 off_t *poi_stack = small_poi_stack;
1122 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1124 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1125 off_t base_offset;
1126 unsigned long size;
1127 /* Push the object we're going to leave behind */
1128 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1129 poi_stack_alloc = alloc_nr(poi_stack_nr);
1130 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1131 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1132 } else {
1133 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1135 poi_stack[poi_stack_nr++] = obj_offset;
1136 /* If parsing the base offset fails, just unwind */
1137 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1138 if (!base_offset)
1139 goto unwind;
1140 curpos = obj_offset = base_offset;
1141 type = unpack_object_header(p, w_curs, &curpos, &size);
1142 if (type <= OBJ_NONE) {
1143 /* If getting the base itself fails, we first
1144 * retry the base, otherwise unwind */
1145 type = retry_bad_packed_offset(p, base_offset);
1146 if (type > OBJ_NONE)
1147 goto out;
1148 goto unwind;
1152 switch (type) {
1153 case OBJ_BAD:
1154 case OBJ_COMMIT:
1155 case OBJ_TREE:
1156 case OBJ_BLOB:
1157 case OBJ_TAG:
1158 break;
1159 default:
1160 error("unknown object type %i at offset %"PRIuMAX" in %s",
1161 type, (uintmax_t)obj_offset, p->pack_name);
1162 type = OBJ_BAD;
1165 out:
1166 if (poi_stack != small_poi_stack)
1167 free(poi_stack);
1168 return type;
1170 unwind:
1171 while (poi_stack_nr) {
1172 obj_offset = poi_stack[--poi_stack_nr];
1173 type = retry_bad_packed_offset(p, obj_offset);
1174 if (type > OBJ_NONE)
1175 goto out;
1177 type = OBJ_BAD;
1178 goto out;
1181 static struct hashmap delta_base_cache;
1182 static size_t delta_base_cached;
1184 static LIST_HEAD(delta_base_cache_lru);
1186 struct delta_base_cache_key {
1187 struct packed_git *p;
1188 off_t base_offset;
1191 struct delta_base_cache_entry {
1192 struct hashmap hash;
1193 struct delta_base_cache_key key;
1194 struct list_head lru;
1195 void *data;
1196 unsigned long size;
1197 enum object_type type;
1200 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1202 unsigned int hash;
1204 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1205 hash += (hash >> 8) + (hash >> 16);
1206 return hash;
1209 static struct delta_base_cache_entry *
1210 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1212 struct hashmap_entry entry;
1213 struct delta_base_cache_key key;
1215 if (!delta_base_cache.cmpfn)
1216 return NULL;
1218 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1219 key.p = p;
1220 key.base_offset = base_offset;
1221 return hashmap_get(&delta_base_cache, &entry, &key);
1224 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1225 const struct delta_base_cache_key *b)
1227 return a->p == b->p && a->base_offset == b->base_offset;
1230 static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1231 const void *va, const void *vb,
1232 const void *vkey)
1234 const struct delta_base_cache_entry *a = va, *b = vb;
1235 const struct delta_base_cache_key *key = vkey;
1236 if (key)
1237 return !delta_base_cache_key_eq(&a->key, key);
1238 else
1239 return !delta_base_cache_key_eq(&a->key, &b->key);
1242 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1244 return !!get_delta_base_cache_entry(p, base_offset);
1248 * Remove the entry from the cache, but do _not_ free the associated
1249 * entry data. The caller takes ownership of the "data" buffer, and
1250 * should copy out any fields it wants before detaching.
1252 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1254 hashmap_remove(&delta_base_cache, ent, &ent->key);
1255 list_del(&ent->lru);
1256 delta_base_cached -= ent->size;
1257 free(ent);
1260 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1261 unsigned long *base_size, enum object_type *type)
1263 struct delta_base_cache_entry *ent;
1265 ent = get_delta_base_cache_entry(p, base_offset);
1266 if (!ent)
1267 return unpack_entry(p, base_offset, type, base_size);
1269 if (type)
1270 *type = ent->type;
1271 if (base_size)
1272 *base_size = ent->size;
1273 return xmemdupz(ent->data, ent->size);
1276 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1278 free(ent->data);
1279 detach_delta_base_cache_entry(ent);
1282 void clear_delta_base_cache(void)
1284 struct list_head *lru, *tmp;
1285 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1286 struct delta_base_cache_entry *entry =
1287 list_entry(lru, struct delta_base_cache_entry, lru);
1288 release_delta_base_cache(entry);
1292 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1293 void *base, unsigned long base_size, enum object_type type)
1295 struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
1296 struct list_head *lru, *tmp;
1298 delta_base_cached += base_size;
1300 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1301 struct delta_base_cache_entry *f =
1302 list_entry(lru, struct delta_base_cache_entry, lru);
1303 if (delta_base_cached <= delta_base_cache_limit)
1304 break;
1305 release_delta_base_cache(f);
1308 ent->key.p = p;
1309 ent->key.base_offset = base_offset;
1310 ent->type = type;
1311 ent->data = base;
1312 ent->size = base_size;
1313 list_add_tail(&ent->lru, &delta_base_cache_lru);
1315 if (!delta_base_cache.cmpfn)
1316 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1317 hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
1318 hashmap_add(&delta_base_cache, ent);
1321 int packed_object_info(struct packed_git *p, off_t obj_offset,
1322 struct object_info *oi)
1324 struct pack_window *w_curs = NULL;
1325 unsigned long size;
1326 off_t curpos = obj_offset;
1327 enum object_type type;
1330 * We always get the representation type, but only convert it to
1331 * a "real" type later if the caller is interested.
1333 if (oi->contentp) {
1334 *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
1335 &type);
1336 if (!*oi->contentp)
1337 type = OBJ_BAD;
1338 } else {
1339 type = unpack_object_header(p, &w_curs, &curpos, &size);
1342 if (!oi->contentp && oi->sizep) {
1343 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1344 off_t tmp_pos = curpos;
1345 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1346 type, obj_offset);
1347 if (!base_offset) {
1348 type = OBJ_BAD;
1349 goto out;
1351 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1352 if (*oi->sizep == 0) {
1353 type = OBJ_BAD;
1354 goto out;
1356 } else {
1357 *oi->sizep = size;
1361 if (oi->disk_sizep) {
1362 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1363 *oi->disk_sizep = revidx[1].offset - obj_offset;
1366 if (oi->typep || oi->typename) {
1367 enum object_type ptot;
1368 ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
1369 curpos);
1370 if (oi->typep)
1371 *oi->typep = ptot;
1372 if (oi->typename) {
1373 const char *tn = typename(ptot);
1374 if (tn)
1375 strbuf_addstr(oi->typename, tn);
1377 if (ptot < 0) {
1378 type = OBJ_BAD;
1379 goto out;
1383 if (oi->delta_base_sha1) {
1384 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1385 const unsigned char *base;
1387 base = get_delta_base_sha1(p, &w_curs, curpos,
1388 type, obj_offset);
1389 if (!base) {
1390 type = OBJ_BAD;
1391 goto out;
1394 hashcpy(oi->delta_base_sha1, base);
1395 } else
1396 hashclr(oi->delta_base_sha1);
1399 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1400 OI_PACKED;
1402 out:
1403 unuse_pack(&w_curs);
1404 return type;
1407 static void *unpack_compressed_entry(struct packed_git *p,
1408 struct pack_window **w_curs,
1409 off_t curpos,
1410 unsigned long size)
1412 int st;
1413 git_zstream stream;
1414 unsigned char *buffer, *in;
1416 buffer = xmallocz_gently(size);
1417 if (!buffer)
1418 return NULL;
1419 memset(&stream, 0, sizeof(stream));
1420 stream.next_out = buffer;
1421 stream.avail_out = size + 1;
1423 git_inflate_init(&stream);
1424 do {
1425 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1426 stream.next_in = in;
1427 st = git_inflate(&stream, Z_FINISH);
1428 if (!stream.avail_out)
1429 break; /* the payload is larger than it should be */
1430 curpos += stream.next_in - in;
1431 } while (st == Z_OK || st == Z_BUF_ERROR);
1432 git_inflate_end(&stream);
1433 if ((st != Z_STREAM_END) || stream.total_out != size) {
1434 free(buffer);
1435 return NULL;
1438 return buffer;
1441 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1443 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1444 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1445 p->pack_name, (uintmax_t)obj_offset);
1448 int do_check_packed_object_crc;
1450 #define UNPACK_ENTRY_STACK_PREALLOC 64
1451 struct unpack_entry_stack_ent {
1452 off_t obj_offset;
1453 off_t curpos;
1454 unsigned long size;
1457 static void *read_object(const unsigned char *sha1, enum object_type *type,
1458 unsigned long *size)
1460 struct object_info oi = OBJECT_INFO_INIT;
1461 void *content;
1462 oi.typep = type;
1463 oi.sizep = size;
1464 oi.contentp = &content;
1466 if (sha1_object_info_extended(sha1, &oi, 0) < 0)
1467 return NULL;
1468 return content;
1471 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1472 enum object_type *final_type, unsigned long *final_size)
1474 struct pack_window *w_curs = NULL;
1475 off_t curpos = obj_offset;
1476 void *data = NULL;
1477 unsigned long size;
1478 enum object_type type;
1479 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1480 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1481 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1482 int base_from_cache = 0;
1484 write_pack_access_log(p, obj_offset);
1486 /* PHASE 1: drill down to the innermost base object */
1487 for (;;) {
1488 off_t base_offset;
1489 int i;
1490 struct delta_base_cache_entry *ent;
1492 ent = get_delta_base_cache_entry(p, curpos);
1493 if (ent) {
1494 type = ent->type;
1495 data = ent->data;
1496 size = ent->size;
1497 detach_delta_base_cache_entry(ent);
1498 base_from_cache = 1;
1499 break;
1502 if (do_check_packed_object_crc && p->index_version > 1) {
1503 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1504 off_t len = revidx[1].offset - obj_offset;
1505 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1506 const unsigned char *sha1 =
1507 nth_packed_object_sha1(p, revidx->nr);
1508 error("bad packed object CRC for %s",
1509 sha1_to_hex(sha1));
1510 mark_bad_packed_object(p, sha1);
1511 data = NULL;
1512 goto out;
1516 type = unpack_object_header(p, &w_curs, &curpos, &size);
1517 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1518 break;
1520 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1521 if (!base_offset) {
1522 error("failed to validate delta base reference "
1523 "at offset %"PRIuMAX" from %s",
1524 (uintmax_t)curpos, p->pack_name);
1525 /* bail to phase 2, in hopes of recovery */
1526 data = NULL;
1527 break;
1530 /* push object, proceed to base */
1531 if (delta_stack_nr >= delta_stack_alloc
1532 && delta_stack == small_delta_stack) {
1533 delta_stack_alloc = alloc_nr(delta_stack_nr);
1534 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1535 memcpy(delta_stack, small_delta_stack,
1536 sizeof(*delta_stack)*delta_stack_nr);
1537 } else {
1538 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1540 i = delta_stack_nr++;
1541 delta_stack[i].obj_offset = obj_offset;
1542 delta_stack[i].curpos = curpos;
1543 delta_stack[i].size = size;
1545 curpos = obj_offset = base_offset;
1548 /* PHASE 2: handle the base */
1549 switch (type) {
1550 case OBJ_OFS_DELTA:
1551 case OBJ_REF_DELTA:
1552 if (data)
1553 die("BUG: unpack_entry: left loop at a valid delta");
1554 break;
1555 case OBJ_COMMIT:
1556 case OBJ_TREE:
1557 case OBJ_BLOB:
1558 case OBJ_TAG:
1559 if (!base_from_cache)
1560 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1561 break;
1562 default:
1563 data = NULL;
1564 error("unknown object type %i at offset %"PRIuMAX" in %s",
1565 type, (uintmax_t)obj_offset, p->pack_name);
1568 /* PHASE 3: apply deltas in order */
1570 /* invariants:
1571 * 'data' holds the base data, or NULL if there was corruption
1573 while (delta_stack_nr) {
1574 void *delta_data;
1575 void *base = data;
1576 void *external_base = NULL;
1577 unsigned long delta_size, base_size = size;
1578 int i;
1580 data = NULL;
1582 if (base)
1583 add_delta_base_cache(p, obj_offset, base, base_size, type);
1585 if (!base) {
1587 * We're probably in deep shit, but let's try to fetch
1588 * the required base anyway from another pack or loose.
1589 * This is costly but should happen only in the presence
1590 * of a corrupted pack, and is better than failing outright.
1592 struct revindex_entry *revidx;
1593 const unsigned char *base_sha1;
1594 revidx = find_pack_revindex(p, obj_offset);
1595 if (revidx) {
1596 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1597 error("failed to read delta base object %s"
1598 " at offset %"PRIuMAX" from %s",
1599 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
1600 p->pack_name);
1601 mark_bad_packed_object(p, base_sha1);
1602 base = read_object(base_sha1, &type, &base_size);
1603 external_base = base;
1607 i = --delta_stack_nr;
1608 obj_offset = delta_stack[i].obj_offset;
1609 curpos = delta_stack[i].curpos;
1610 delta_size = delta_stack[i].size;
1612 if (!base)
1613 continue;
1615 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1617 if (!delta_data) {
1618 error("failed to unpack compressed delta "
1619 "at offset %"PRIuMAX" from %s",
1620 (uintmax_t)curpos, p->pack_name);
1621 data = NULL;
1622 free(external_base);
1623 continue;
1626 data = patch_delta(base, base_size,
1627 delta_data, delta_size,
1628 &size);
1631 * We could not apply the delta; warn the user, but keep going.
1632 * Our failure will be noticed either in the next iteration of
1633 * the loop, or if this is the final delta, in the caller when
1634 * we return NULL. Those code paths will take care of making
1635 * a more explicit warning and retrying with another copy of
1636 * the object.
1638 if (!data)
1639 error("failed to apply delta");
1641 free(delta_data);
1642 free(external_base);
1645 if (final_type)
1646 *final_type = type;
1647 if (final_size)
1648 *final_size = size;
1650 out:
1651 unuse_pack(&w_curs);
1653 if (delta_stack != small_delta_stack)
1654 free(delta_stack);
1656 return data;
1659 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1660 uint32_t n)
1662 const unsigned char *index = p->index_data;
1663 if (!index) {
1664 if (open_pack_index(p))
1665 return NULL;
1666 index = p->index_data;
1668 if (n >= p->num_objects)
1669 return NULL;
1670 index += 4 * 256;
1671 if (p->index_version == 1) {
1672 return index + 24 * n + 4;
1673 } else {
1674 index += 8;
1675 return index + 20 * n;
1679 const struct object_id *nth_packed_object_oid(struct object_id *oid,
1680 struct packed_git *p,
1681 uint32_t n)
1683 const unsigned char *hash = nth_packed_object_sha1(p, n);
1684 if (!hash)
1685 return NULL;
1686 hashcpy(oid->hash, hash);
1687 return oid;
1690 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1692 const unsigned char *ptr = vptr;
1693 const unsigned char *start = p->index_data;
1694 const unsigned char *end = start + p->index_size;
1695 if (ptr < start)
1696 die(_("offset before start of pack index for %s (corrupt index?)"),
1697 p->pack_name);
1698 /* No need to check for underflow; .idx files must be at least 8 bytes */
1699 if (ptr >= end - 8)
1700 die(_("offset beyond end of pack index for %s (truncated index?)"),
1701 p->pack_name);
1704 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1706 const unsigned char *index = p->index_data;
1707 index += 4 * 256;
1708 if (p->index_version == 1) {
1709 return ntohl(*((uint32_t *)(index + 24 * n)));
1710 } else {
1711 uint32_t off;
1712 index += 8 + p->num_objects * (20 + 4);
1713 off = ntohl(*((uint32_t *)(index + 4 * n)));
1714 if (!(off & 0x80000000))
1715 return off;
1716 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1717 check_pack_index_ptr(p, index);
1718 return get_be64(index);
1722 off_t find_pack_entry_one(const unsigned char *sha1,
1723 struct packed_git *p)
1725 const uint32_t *level1_ofs = p->index_data;
1726 const unsigned char *index = p->index_data;
1727 unsigned hi, lo, stride;
1728 static int debug_lookup = -1;
1730 if (debug_lookup < 0)
1731 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1733 if (!index) {
1734 if (open_pack_index(p))
1735 return 0;
1736 level1_ofs = p->index_data;
1737 index = p->index_data;
1739 if (p->index_version > 1) {
1740 level1_ofs += 2;
1741 index += 8;
1743 index += 4 * 256;
1744 hi = ntohl(level1_ofs[*sha1]);
1745 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1746 if (p->index_version > 1) {
1747 stride = 20;
1748 } else {
1749 stride = 24;
1750 index += 4;
1753 if (debug_lookup)
1754 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1755 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1757 while (lo < hi) {
1758 unsigned mi = lo + (hi - lo) / 2;
1759 int cmp = hashcmp(index + mi * stride, sha1);
1761 if (debug_lookup)
1762 printf("lo %u hi %u rg %u mi %u\n",
1763 lo, hi, hi - lo, mi);
1764 if (!cmp)
1765 return nth_packed_object_offset(p, mi);
1766 if (cmp > 0)
1767 hi = mi;
1768 else
1769 lo = mi+1;
1771 return 0;
1774 int is_pack_valid(struct packed_git *p)
1776 /* An already open pack is known to be valid. */
1777 if (p->pack_fd != -1)
1778 return 1;
1780 /* If the pack has one window completely covering the
1781 * file size, the pack is known to be valid even if
1782 * the descriptor is not currently open.
1784 if (p->windows) {
1785 struct pack_window *w = p->windows;
1787 if (!w->offset && w->len == p->pack_size)
1788 return 1;
1791 /* Force the pack to open to prove its valid. */
1792 return !open_packed_git(p);
1795 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1796 struct packed_git *packs)
1798 struct packed_git *p;
1800 for (p = packs; p; p = p->next) {
1801 if (find_pack_entry_one(sha1, p))
1802 return p;
1804 return NULL;
1808 static int fill_pack_entry(const unsigned char *sha1,
1809 struct pack_entry *e,
1810 struct packed_git *p)
1812 off_t offset;
1814 if (p->num_bad_objects) {
1815 unsigned i;
1816 for (i = 0; i < p->num_bad_objects; i++)
1817 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1818 return 0;
1821 offset = find_pack_entry_one(sha1, p);
1822 if (!offset)
1823 return 0;
1826 * We are about to tell the caller where they can locate the
1827 * requested object. We better make sure the packfile is
1828 * still here and can be accessed before supplying that
1829 * answer, as it may have been deleted since the index was
1830 * loaded!
1832 if (!is_pack_valid(p))
1833 return 0;
1834 e->offset = offset;
1835 e->p = p;
1836 hashcpy(e->sha1, sha1);
1837 return 1;
1841 * Iff a pack file contains the object named by sha1, return true and
1842 * store its location to e.
1844 int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1846 struct list_head *pos;
1848 prepare_packed_git();
1849 if (!packed_git)
1850 return 0;
1852 list_for_each(pos, &packed_git_mru) {
1853 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1854 if (fill_pack_entry(sha1, e, p)) {
1855 list_move(&p->mru, &packed_git_mru);
1856 return 1;
1859 return 0;
1862 int has_sha1_pack(const unsigned char *sha1)
1864 struct pack_entry e;
1865 return find_pack_entry(sha1, &e);
1868 int has_pack_index(const unsigned char *sha1)
1870 struct stat st;
1871 if (stat(sha1_pack_index_name(sha1), &st))
1872 return 0;
1873 return 1;
1876 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
1878 uint32_t i;
1879 int r = 0;
1881 for (i = 0; i < p->num_objects; i++) {
1882 struct object_id oid;
1884 if (!nth_packed_object_oid(&oid, p, i))
1885 return error("unable to get sha1 of object %u in %s",
1886 i, p->pack_name);
1888 r = cb(&oid, p, i, data);
1889 if (r)
1890 break;
1892 return r;
1895 int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
1897 struct packed_git *p;
1898 int r = 0;
1899 int pack_errors = 0;
1901 prepare_packed_git();
1902 for (p = packed_git; p; p = p->next) {
1903 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
1904 continue;
1905 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
1906 !p->pack_promisor)
1907 continue;
1908 if (open_pack_index(p)) {
1909 pack_errors = 1;
1910 continue;
1912 r = for_each_object_in_pack(p, cb, data);
1913 if (r)
1914 break;
1916 return r ? r : pack_errors;
1919 static int add_promisor_object(const struct object_id *oid,
1920 struct packed_git *pack,
1921 uint32_t pos,
1922 void *set_)
1924 struct oidset *set = set_;
1925 struct object *obj = parse_object(oid);
1926 if (!obj)
1927 return 1;
1929 oidset_insert(set, oid);
1932 * If this is a tree, commit, or tag, the objects it refers
1933 * to are also promisor objects. (Blobs refer to no objects.)
1935 if (obj->type == OBJ_TREE) {
1936 struct tree *tree = (struct tree *)obj;
1937 struct tree_desc desc;
1938 struct name_entry entry;
1939 if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
1941 * Error messages are given when packs are
1942 * verified, so do not print any here.
1944 return 0;
1945 while (tree_entry_gently(&desc, &entry))
1946 oidset_insert(set, entry.oid);
1947 } else if (obj->type == OBJ_COMMIT) {
1948 struct commit *commit = (struct commit *) obj;
1949 struct commit_list *parents = commit->parents;
1951 oidset_insert(set, &commit->tree->object.oid);
1952 for (; parents; parents = parents->next)
1953 oidset_insert(set, &parents->item->object.oid);
1954 } else if (obj->type == OBJ_TAG) {
1955 struct tag *tag = (struct tag *) obj;
1956 oidset_insert(set, &tag->tagged->oid);
1958 return 0;
1961 int is_promisor_object(const struct object_id *oid)
1963 static struct oidset promisor_objects;
1964 static int promisor_objects_prepared;
1966 if (!promisor_objects_prepared) {
1967 if (repository_format_partial_clone) {
1968 for_each_packed_object(add_promisor_object,
1969 &promisor_objects,
1970 FOR_EACH_OBJECT_PROMISOR_ONLY);
1972 promisor_objects_prepared = 1;
1974 return oidset_contains(&promisor_objects, oid);