The fifth batch
[alt-git.git] / packfile.c
blob2d80d80cb3838d5493081d3302f89ac3a5d3ac5a
1 #define DISABLE_SIGN_COMPARE_WARNINGS
3 #include "git-compat-util.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "list.h"
8 #include "pack.h"
9 #include "repository.h"
10 #include "dir.h"
11 #include "mergesort.h"
12 #include "packfile.h"
13 #include "delta.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-ll.h"
23 #include "midx.h"
24 #include "commit-graph.h"
25 #include "pack-revindex.h"
26 #include "promisor-remote.h"
28 char *odb_pack_name(struct repository *r, struct strbuf *buf,
29 const unsigned char *hash, const char *ext)
31 strbuf_reset(buf);
32 strbuf_addf(buf, "%s/pack/pack-%s.%s", repo_get_object_directory(r),
33 hash_to_hex_algop(hash, r->hash_algo), ext);
34 return buf->buf;
37 static unsigned int pack_used_ctr;
38 static unsigned int pack_mmap_calls;
39 static unsigned int peak_pack_open_windows;
40 static unsigned int pack_open_windows;
41 static unsigned int pack_open_fds;
42 static unsigned int pack_max_fds;
43 static size_t peak_pack_mapped;
44 static size_t pack_mapped;
46 #define SZ_FMT PRIuMAX
47 static inline uintmax_t sz_fmt(size_t s) { return s; }
49 void pack_report(struct repository *repo)
51 fprintf(stderr,
52 "pack_report: getpagesize() = %10" SZ_FMT "\n"
53 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
54 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
55 sz_fmt(getpagesize()),
56 sz_fmt(repo->settings.packed_git_window_size),
57 sz_fmt(repo->settings.packed_git_limit));
58 fprintf(stderr,
59 "pack_report: pack_used_ctr = %10u\n"
60 "pack_report: pack_mmap_calls = %10u\n"
61 "pack_report: pack_open_windows = %10u / %10u\n"
62 "pack_report: pack_mapped = "
63 "%10" SZ_FMT " / %10" SZ_FMT "\n",
64 pack_used_ctr,
65 pack_mmap_calls,
66 pack_open_windows, peak_pack_open_windows,
67 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
71 * Open and mmap the index file at path, perform a couple of
72 * consistency checks, then record its information to p. Return 0 on
73 * success.
75 static int check_packed_git_idx(const char *path, struct packed_git *p)
77 void *idx_map;
78 size_t idx_size;
79 int fd = git_open(path), ret;
80 struct stat st;
81 const unsigned int hashsz = p->repo->hash_algo->rawsz;
83 if (fd < 0)
84 return -1;
85 if (fstat(fd, &st)) {
86 close(fd);
87 return -1;
89 idx_size = xsize_t(st.st_size);
90 if (idx_size < 4 * 256 + hashsz + hashsz) {
91 close(fd);
92 return error("index file %s is too small", path);
94 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
95 close(fd);
97 ret = load_idx(path, hashsz, idx_map, idx_size, p);
99 if (ret)
100 munmap(idx_map, idx_size);
102 return ret;
105 int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
106 size_t idx_size, struct packed_git *p)
108 struct pack_idx_header *hdr = idx_map;
109 uint32_t version, nr, i, *index;
111 if (idx_size < 4 * 256 + hashsz + hashsz)
112 return error("index file %s is too small", path);
113 if (!idx_map)
114 return error("empty data");
116 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
117 version = ntohl(hdr->idx_version);
118 if (version < 2 || version > 2)
119 return error("index file %s is version %"PRIu32
120 " and is not supported by this binary"
121 " (try upgrading GIT to a newer version)",
122 path, version);
123 } else
124 version = 1;
126 nr = 0;
127 index = idx_map;
128 if (version > 1)
129 index += 2; /* skip index header */
130 for (i = 0; i < 256; i++) {
131 uint32_t n = ntohl(index[i]);
132 if (n < nr)
133 return error("non-monotonic index %s", path);
134 nr = n;
137 if (version == 1) {
139 * Total size:
140 * - 256 index entries 4 bytes each
141 * - 24-byte entries * nr (object ID + 4-byte offset)
142 * - hash of the packfile
143 * - file checksum
145 if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
146 return error("wrong index v1 file size in %s", path);
147 } else if (version == 2) {
149 * Minimum size:
150 * - 8 bytes of header
151 * - 256 index entries 4 bytes each
152 * - object ID entry * nr
153 * - 4-byte crc entry * nr
154 * - 4-byte offset entry * nr
155 * - hash of the packfile
156 * - file checksum
157 * And after the 4-byte offset table might be a
158 * variable sized table containing 8-byte entries
159 * for offsets larger than 2^31.
161 size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
162 size_t max_size = min_size;
163 if (nr)
164 max_size = st_add(max_size, st_mult(nr - 1, 8));
165 if (idx_size < min_size || idx_size > max_size)
166 return error("wrong index v2 file size in %s", path);
167 if (idx_size != min_size &&
169 * make sure we can deal with large pack offsets.
170 * 31-bit signed offset won't be enough, neither
171 * 32-bit unsigned one will be.
173 (sizeof(off_t) <= 4))
174 return error("pack too large for current definition of off_t in %s", path);
175 p->crc_offset = st_add(8 + 4 * 256, st_mult(nr, hashsz));
178 p->index_version = version;
179 p->index_data = idx_map;
180 p->index_size = idx_size;
181 p->num_objects = nr;
182 return 0;
185 int open_pack_index(struct packed_git *p)
187 char *idx_name;
188 size_t len;
189 int ret;
191 if (p->index_data)
192 return 0;
194 if (!strip_suffix(p->pack_name, ".pack", &len))
195 BUG("pack_name does not end in .pack");
196 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
197 ret = check_packed_git_idx(idx_name, p);
198 free(idx_name);
199 return ret;
202 uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
204 const uint32_t *level1_ofs = p->index_data;
206 if (!level1_ofs) {
207 if (open_pack_index(p))
208 return 0;
209 level1_ofs = p->index_data;
212 if (p->index_version > 1) {
213 level1_ofs += 2;
216 return ntohl(level1_ofs[value]);
219 static struct packed_git *alloc_packed_git(struct repository *r, int extra)
221 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
222 memset(p, 0, sizeof(*p));
223 p->pack_fd = -1;
224 p->repo = r;
225 return p;
228 static char *pack_path_from_idx(const char *idx_path)
230 size_t len;
231 if (!strip_suffix(idx_path, ".idx", &len))
232 BUG("idx path does not end in .idx: %s", idx_path);
233 return xstrfmt("%.*s.pack", (int)len, idx_path);
236 struct packed_git *parse_pack_index(struct repository *r, unsigned char *sha1,
237 const char *idx_path)
239 char *path = pack_path_from_idx(idx_path);
240 size_t alloc = st_add(strlen(path), 1);
241 struct packed_git *p = alloc_packed_git(r, alloc);
243 memcpy(p->pack_name, path, alloc); /* includes NUL */
244 free(path);
245 hashcpy(p->hash, sha1, p->repo->hash_algo);
246 if (check_packed_git_idx(idx_path, p)) {
247 free(p);
248 return NULL;
251 return p;
254 static void scan_windows(struct packed_git *p,
255 struct packed_git **lru_p,
256 struct pack_window **lru_w,
257 struct pack_window **lru_l)
259 struct pack_window *w, *w_l;
261 for (w_l = NULL, w = p->windows; w; w = w->next) {
262 if (!w->inuse_cnt) {
263 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
264 *lru_p = p;
265 *lru_w = w;
266 *lru_l = w_l;
269 w_l = w;
273 static int unuse_one_window(struct packed_git *current)
275 struct packed_git *p, *lru_p = NULL;
276 struct pack_window *lru_w = NULL, *lru_l = NULL;
278 if (current)
279 scan_windows(current, &lru_p, &lru_w, &lru_l);
280 for (p = current->repo->objects->packed_git; p; p = p->next)
281 scan_windows(p, &lru_p, &lru_w, &lru_l);
282 if (lru_p) {
283 munmap(lru_w->base, lru_w->len);
284 pack_mapped -= lru_w->len;
285 if (lru_l)
286 lru_l->next = lru_w->next;
287 else
288 lru_p->windows = lru_w->next;
289 free(lru_w);
290 pack_open_windows--;
291 return 1;
293 return 0;
296 void close_pack_windows(struct packed_git *p)
298 while (p->windows) {
299 struct pack_window *w = p->windows;
301 if (w->inuse_cnt)
302 die("pack '%s' still has open windows to it",
303 p->pack_name);
304 munmap(w->base, w->len);
305 pack_mapped -= w->len;
306 pack_open_windows--;
307 p->windows = w->next;
308 free(w);
312 int close_pack_fd(struct packed_git *p)
314 if (p->pack_fd < 0)
315 return 0;
317 close(p->pack_fd);
318 pack_open_fds--;
319 p->pack_fd = -1;
321 return 1;
324 void close_pack_index(struct packed_git *p)
326 if (p->index_data) {
327 munmap((void *)p->index_data, p->index_size);
328 p->index_data = NULL;
332 static void close_pack_revindex(struct packed_git *p)
334 if (!p->revindex_map)
335 return;
337 munmap((void *)p->revindex_map, p->revindex_size);
338 p->revindex_map = NULL;
339 p->revindex_data = NULL;
342 static void close_pack_mtimes(struct packed_git *p)
344 if (!p->mtimes_map)
345 return;
347 munmap((void *)p->mtimes_map, p->mtimes_size);
348 p->mtimes_map = NULL;
351 void close_pack(struct packed_git *p)
353 close_pack_windows(p);
354 close_pack_fd(p);
355 close_pack_index(p);
356 close_pack_revindex(p);
357 close_pack_mtimes(p);
358 oidset_clear(&p->bad_objects);
361 void close_object_store(struct raw_object_store *o)
363 struct packed_git *p;
365 for (p = o->packed_git; p; p = p->next)
366 if (p->do_not_close)
367 BUG("want to close pack marked 'do-not-close'");
368 else
369 close_pack(p);
371 if (o->multi_pack_index) {
372 close_midx(o->multi_pack_index);
373 o->multi_pack_index = NULL;
376 close_commit_graph(o);
379 void unlink_pack_path(const char *pack_name, int force_delete)
381 static const char *exts[] = {".idx", ".pack", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
382 int i;
383 struct strbuf buf = STRBUF_INIT;
384 size_t plen;
386 strbuf_addstr(&buf, pack_name);
387 strip_suffix_mem(buf.buf, &buf.len, ".pack");
388 plen = buf.len;
390 if (!force_delete) {
391 strbuf_addstr(&buf, ".keep");
392 if (!access(buf.buf, F_OK)) {
393 strbuf_release(&buf);
394 return;
398 for (i = 0; i < ARRAY_SIZE(exts); i++) {
399 strbuf_setlen(&buf, plen);
400 strbuf_addstr(&buf, exts[i]);
401 unlink(buf.buf);
404 strbuf_release(&buf);
408 * The LRU pack is the one with the oldest MRU window, preferring packs
409 * with no used windows, or the oldest mtime if it has no windows allocated.
411 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
413 struct pack_window *w, *this_mru_w;
414 int has_windows_inuse = 0;
417 * Reject this pack if it has windows and the previously selected
418 * one does not. If this pack does not have windows, reject
419 * it if the pack file is newer than the previously selected one.
421 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
422 return;
424 for (w = this_mru_w = p->windows; w; w = w->next) {
426 * Reject this pack if any of its windows are in use,
427 * but the previously selected pack did not have any
428 * inuse windows. Otherwise, record that this pack
429 * has windows in use.
431 if (w->inuse_cnt) {
432 if (*accept_windows_inuse)
433 has_windows_inuse = 1;
434 else
435 return;
438 if (w->last_used > this_mru_w->last_used)
439 this_mru_w = w;
442 * Reject this pack if it has windows that have been
443 * used more recently than the previously selected pack.
444 * If the previously selected pack had windows inuse and
445 * we have not encountered a window in this pack that is
446 * inuse, skip this check since we prefer a pack with no
447 * inuse windows to one that has inuse windows.
449 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
450 this_mru_w->last_used > (*mru_w)->last_used)
451 return;
455 * Select this pack.
457 *mru_w = this_mru_w;
458 *lru_p = p;
459 *accept_windows_inuse = has_windows_inuse;
462 static int close_one_pack(struct repository *r)
464 struct packed_git *p, *lru_p = NULL;
465 struct pack_window *mru_w = NULL;
466 int accept_windows_inuse = 1;
468 for (p = r->objects->packed_git; p; p = p->next) {
469 if (p->pack_fd == -1)
470 continue;
471 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
474 if (lru_p)
475 return close_pack_fd(lru_p);
477 return 0;
480 static unsigned int get_max_fd_limit(void)
482 #ifdef RLIMIT_NOFILE
484 struct rlimit lim;
486 if (!getrlimit(RLIMIT_NOFILE, &lim))
487 return lim.rlim_cur;
489 #endif
491 #ifdef _SC_OPEN_MAX
493 long open_max = sysconf(_SC_OPEN_MAX);
494 if (0 < open_max)
495 return open_max;
497 * Otherwise, we got -1 for one of the two
498 * reasons:
500 * (1) sysconf() did not understand _SC_OPEN_MAX
501 * and signaled an error with -1; or
502 * (2) sysconf() said there is no limit.
504 * We _could_ clear errno before calling sysconf() to
505 * tell these two cases apart and return a huge number
506 * in the latter case to let the caller cap it to a
507 * value that is not so selfish, but letting the
508 * fallback OPEN_MAX codepath take care of these cases
509 * is a lot simpler.
512 #endif
514 #ifdef OPEN_MAX
515 return OPEN_MAX;
516 #else
517 return 1; /* see the caller ;-) */
518 #endif
521 const char *pack_basename(struct packed_git *p)
523 const char *ret = strrchr(p->pack_name, '/');
524 if (ret)
525 ret = ret + 1; /* skip past slash */
526 else
527 ret = p->pack_name; /* we only have a base */
528 return ret;
532 * Do not call this directly as this leaks p->pack_fd on error return;
533 * call open_packed_git() instead.
535 static int open_packed_git_1(struct packed_git *p)
537 struct stat st;
538 struct pack_header hdr;
539 unsigned char hash[GIT_MAX_RAWSZ];
540 unsigned char *idx_hash;
541 ssize_t read_result;
542 const unsigned hashsz = p->repo->hash_algo->rawsz;
544 if (open_pack_index(p))
545 return error("packfile %s index unavailable", p->pack_name);
547 if (!pack_max_fds) {
548 unsigned int max_fds = get_max_fd_limit();
550 /* Save 3 for stdin/stdout/stderr, 22 for work */
551 if (25 < max_fds)
552 pack_max_fds = max_fds - 25;
553 else
554 pack_max_fds = 1;
557 while (pack_max_fds <= pack_open_fds && close_one_pack(p->repo))
558 ; /* nothing */
560 p->pack_fd = git_open(p->pack_name);
561 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
562 return -1;
563 pack_open_fds++;
565 /* If we created the struct before we had the pack we lack size. */
566 if (!p->pack_size) {
567 if (!S_ISREG(st.st_mode))
568 return error("packfile %s not a regular file", p->pack_name);
569 p->pack_size = st.st_size;
570 } else if (p->pack_size != st.st_size)
571 return error("packfile %s size changed", p->pack_name);
573 /* Verify we recognize this pack file format. */
574 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
575 if (read_result < 0)
576 return error_errno("error reading from %s", p->pack_name);
577 if (read_result != sizeof(hdr))
578 return error("file %s is far too short to be a packfile", p->pack_name);
579 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
580 return error("file %s is not a GIT packfile", p->pack_name);
581 if (!pack_version_ok(hdr.hdr_version))
582 return error("packfile %s is version %"PRIu32" and not"
583 " supported (try upgrading GIT to a newer version)",
584 p->pack_name, ntohl(hdr.hdr_version));
586 /* Verify the pack matches its index. */
587 if (p->num_objects != ntohl(hdr.hdr_entries))
588 return error("packfile %s claims to have %"PRIu32" objects"
589 " while index indicates %"PRIu32" objects",
590 p->pack_name, ntohl(hdr.hdr_entries),
591 p->num_objects);
592 read_result = pread_in_full(p->pack_fd, hash, hashsz,
593 p->pack_size - hashsz);
594 if (read_result < 0)
595 return error_errno("error reading from %s", p->pack_name);
596 if (read_result != hashsz)
597 return error("packfile %s signature is unavailable", p->pack_name);
598 idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
599 if (!hasheq(hash, idx_hash, p->repo->hash_algo))
600 return error("packfile %s does not match index", p->pack_name);
601 return 0;
604 static int open_packed_git(struct packed_git *p)
606 if (!open_packed_git_1(p))
607 return 0;
608 close_pack_fd(p);
609 return -1;
612 static int in_window(struct repository *r, struct pack_window *win,
613 off_t offset)
615 /* We must promise at least one full hash after the
616 * offset is available from this window, otherwise the offset
617 * is not actually in this window and a different window (which
618 * has that one hash excess) must be used. This is to support
619 * the object header and delta base parsing routines below.
621 off_t win_off = win->offset;
622 return win_off <= offset
623 && (offset + r->hash_algo->rawsz) <= (win_off + win->len);
626 unsigned char *use_pack(struct packed_git *p,
627 struct pack_window **w_cursor,
628 off_t offset,
629 unsigned long *left)
631 struct pack_window *win = *w_cursor;
633 /* Since packfiles end in a hash of their content and it's
634 * pointless to ask for an offset into the middle of that
635 * hash, and the in_window function above wouldn't match
636 * don't allow an offset too close to the end of the file.
638 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
639 die("packfile %s cannot be accessed", p->pack_name);
640 if (offset > (p->pack_size - p->repo->hash_algo->rawsz))
641 die("offset beyond end of packfile (truncated pack?)");
642 if (offset < 0)
643 die(_("offset before end of packfile (broken .idx?)"));
645 if (!win || !in_window(p->repo, win, offset)) {
646 if (win)
647 win->inuse_cnt--;
648 for (win = p->windows; win; win = win->next) {
649 if (in_window(p->repo, win, offset))
650 break;
652 if (!win) {
653 size_t window_align;
654 off_t len;
655 struct repo_settings *settings;
657 /* lazy load the settings in case it hasn't been setup */
658 prepare_repo_settings(p->repo);
659 settings = &p->repo->settings;
661 window_align = settings->packed_git_window_size / 2;
663 if (p->pack_fd == -1 && open_packed_git(p))
664 die("packfile %s cannot be accessed", p->pack_name);
666 CALLOC_ARRAY(win, 1);
667 win->offset = (offset / window_align) * window_align;
668 len = p->pack_size - win->offset;
669 if (len > settings->packed_git_window_size)
670 len = settings->packed_git_window_size;
671 win->len = (size_t)len;
672 pack_mapped += win->len;
674 while (settings->packed_git_limit < pack_mapped
675 && unuse_one_window(p))
676 ; /* nothing */
677 win->base = xmmap_gently(NULL, win->len,
678 PROT_READ, MAP_PRIVATE,
679 p->pack_fd, win->offset);
680 if (win->base == MAP_FAILED)
681 die_errno(_("packfile %s cannot be mapped%s"),
682 p->pack_name, mmap_os_err());
683 if (!win->offset && win->len == p->pack_size
684 && !p->do_not_close)
685 close_pack_fd(p);
686 pack_mmap_calls++;
687 pack_open_windows++;
688 if (pack_mapped > peak_pack_mapped)
689 peak_pack_mapped = pack_mapped;
690 if (pack_open_windows > peak_pack_open_windows)
691 peak_pack_open_windows = pack_open_windows;
692 win->next = p->windows;
693 p->windows = win;
696 if (win != *w_cursor) {
697 win->last_used = pack_used_ctr++;
698 win->inuse_cnt++;
699 *w_cursor = win;
701 offset -= win->offset;
702 if (left)
703 *left = win->len - xsize_t(offset);
704 return win->base + offset;
707 void unuse_pack(struct pack_window **w_cursor)
709 struct pack_window *w = *w_cursor;
710 if (w) {
711 w->inuse_cnt--;
712 *w_cursor = NULL;
716 struct packed_git *add_packed_git(struct repository *r, const char *path,
717 size_t path_len, int local)
719 struct stat st;
720 size_t alloc;
721 struct packed_git *p;
722 struct object_id oid;
725 * Make sure a corresponding .pack file exists and that
726 * the index looks sane.
728 if (!strip_suffix_mem(path, &path_len, ".idx"))
729 return NULL;
732 * ".promisor" is long enough to hold any suffix we're adding (and
733 * the use xsnprintf double-checks that)
735 alloc = st_add3(path_len, strlen(".promisor"), 1);
736 p = alloc_packed_git(r, alloc);
737 memcpy(p->pack_name, path, path_len);
739 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
740 if (!access(p->pack_name, F_OK))
741 p->pack_keep = 1;
743 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
744 if (!access(p->pack_name, F_OK))
745 p->pack_promisor = 1;
747 xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
748 if (!access(p->pack_name, F_OK))
749 p->is_cruft = 1;
751 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
752 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
753 free(p);
754 return NULL;
757 /* ok, it looks sane as far as we can check without
758 * actually mapping the pack file.
760 p->pack_size = st.st_size;
761 p->pack_local = local;
762 p->mtime = st.st_mtime;
763 if (path_len < r->hash_algo->hexsz ||
764 get_oid_hex_algop(path + path_len - r->hash_algo->hexsz, &oid,
765 r->hash_algo))
766 hashclr(p->hash, r->hash_algo);
767 else
768 hashcpy(p->hash, oid.hash, r->hash_algo);
770 return p;
773 void install_packed_git(struct repository *r, struct packed_git *pack)
775 if (pack->pack_fd != -1)
776 pack_open_fds++;
778 pack->next = r->objects->packed_git;
779 r->objects->packed_git = pack;
781 hashmap_entry_init(&pack->packmap_ent, strhash(pack->pack_name));
782 hashmap_add(&r->objects->pack_map, &pack->packmap_ent);
785 void (*report_garbage)(unsigned seen_bits, const char *path);
787 static void report_helper(const struct string_list *list,
788 int seen_bits, int first, int last)
790 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
791 return;
793 for (; first < last; first++)
794 report_garbage(seen_bits, list->items[first].string);
797 static void report_pack_garbage(struct string_list *list)
799 int i, baselen = -1, first = 0, seen_bits = 0;
801 if (!report_garbage)
802 return;
804 string_list_sort(list);
806 for (i = 0; i < list->nr; i++) {
807 const char *path = list->items[i].string;
808 if (baselen != -1 &&
809 strncmp(path, list->items[first].string, baselen)) {
810 report_helper(list, seen_bits, first, i);
811 baselen = -1;
812 seen_bits = 0;
814 if (baselen == -1) {
815 const char *dot = strrchr(path, '.');
816 if (!dot) {
817 report_garbage(PACKDIR_FILE_GARBAGE, path);
818 continue;
820 baselen = dot - path + 1;
821 first = i;
823 if (!strcmp(path + baselen, "pack"))
824 seen_bits |= 1;
825 else if (!strcmp(path + baselen, "idx"))
826 seen_bits |= 2;
828 report_helper(list, seen_bits, first, list->nr);
831 void for_each_file_in_pack_subdir(const char *objdir,
832 const char *subdir,
833 each_file_in_pack_dir_fn fn,
834 void *data)
836 struct strbuf path = STRBUF_INIT;
837 size_t dirnamelen;
838 DIR *dir;
839 struct dirent *de;
841 strbuf_addstr(&path, objdir);
842 strbuf_addstr(&path, "/pack");
843 if (subdir)
844 strbuf_addf(&path, "/%s", subdir);
845 dir = opendir(path.buf);
846 if (!dir) {
847 if (errno != ENOENT)
848 error_errno("unable to open object pack directory: %s",
849 path.buf);
850 strbuf_release(&path);
851 return;
853 strbuf_addch(&path, '/');
854 dirnamelen = path.len;
855 while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
856 strbuf_setlen(&path, dirnamelen);
857 strbuf_addstr(&path, de->d_name);
859 fn(path.buf, path.len, de->d_name, data);
862 closedir(dir);
863 strbuf_release(&path);
866 void for_each_file_in_pack_dir(const char *objdir,
867 each_file_in_pack_dir_fn fn,
868 void *data)
870 for_each_file_in_pack_subdir(objdir, NULL, fn, data);
873 struct prepare_pack_data {
874 struct repository *r;
875 struct string_list *garbage;
876 int local;
877 struct multi_pack_index *m;
880 static void prepare_pack(const char *full_name, size_t full_name_len,
881 const char *file_name, void *_data)
883 struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
884 struct packed_git *p;
885 size_t base_len = full_name_len;
887 if (strip_suffix_mem(full_name, &base_len, ".idx") &&
888 !(data->m && midx_contains_pack(data->m, file_name))) {
889 struct hashmap_entry hent;
890 char *pack_name = xstrfmt("%.*s.pack", (int)base_len, full_name);
891 unsigned int hash = strhash(pack_name);
892 hashmap_entry_init(&hent, hash);
894 /* Don't reopen a pack we already have. */
895 if (!hashmap_get(&data->r->objects->pack_map, &hent, pack_name)) {
896 p = add_packed_git(data->r, full_name, full_name_len, data->local);
897 if (p)
898 install_packed_git(data->r, p);
900 free(pack_name);
903 if (!report_garbage)
904 return;
906 if (!strcmp(file_name, "multi-pack-index") ||
907 !strcmp(file_name, "multi-pack-index.d"))
908 return;
909 if (starts_with(file_name, "multi-pack-index") &&
910 (ends_with(file_name, ".bitmap") || ends_with(file_name, ".rev")))
911 return;
912 if (ends_with(file_name, ".idx") ||
913 ends_with(file_name, ".rev") ||
914 ends_with(file_name, ".pack") ||
915 ends_with(file_name, ".bitmap") ||
916 ends_with(file_name, ".keep") ||
917 ends_with(file_name, ".promisor") ||
918 ends_with(file_name, ".mtimes"))
919 string_list_append(data->garbage, full_name);
920 else
921 report_garbage(PACKDIR_FILE_GARBAGE, full_name);
924 static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
926 struct prepare_pack_data data;
927 struct string_list garbage = STRING_LIST_INIT_DUP;
929 data.m = r->objects->multi_pack_index;
931 /* look for the multi-pack-index for this object directory */
932 while (data.m && strcmp(data.m->object_dir, objdir))
933 data.m = data.m->next;
935 data.r = r;
936 data.garbage = &garbage;
937 data.local = local;
939 for_each_file_in_pack_dir(objdir, prepare_pack, &data);
941 report_pack_garbage(data.garbage);
942 string_list_clear(data.garbage, 0);
945 static void prepare_packed_git(struct repository *r);
947 * Give a fast, rough count of the number of objects in the repository. This
948 * ignores loose objects completely. If you have a lot of them, then either
949 * you should repack because your performance will be awful, or they are
950 * all unreachable objects about to be pruned, in which case they're not really
951 * interesting as a measure of repo size in the first place.
953 unsigned long repo_approximate_object_count(struct repository *r)
955 if (!r->objects->approximate_object_count_valid) {
956 unsigned long count;
957 struct multi_pack_index *m;
958 struct packed_git *p;
960 prepare_packed_git(r);
961 count = 0;
962 for (m = get_multi_pack_index(r); m; m = m->next)
963 count += m->num_objects;
964 for (p = r->objects->packed_git; p; p = p->next) {
965 if (open_pack_index(p))
966 continue;
967 count += p->num_objects;
969 r->objects->approximate_object_count = count;
970 r->objects->approximate_object_count_valid = 1;
972 return r->objects->approximate_object_count;
975 DEFINE_LIST_SORT(static, sort_packs, struct packed_git, next);
977 static int sort_pack(const struct packed_git *a, const struct packed_git *b)
979 int st;
982 * Local packs tend to contain objects specific to our
983 * variant of the project than remote ones. In addition,
984 * remote ones could be on a network mounted filesystem.
985 * Favor local ones for these reasons.
987 st = a->pack_local - b->pack_local;
988 if (st)
989 return -st;
992 * Younger packs tend to contain more recent objects,
993 * and more recent objects tend to get accessed more
994 * often.
996 if (a->mtime < b->mtime)
997 return 1;
998 else if (a->mtime == b->mtime)
999 return 0;
1000 return -1;
1003 static void rearrange_packed_git(struct repository *r)
1005 sort_packs(&r->objects->packed_git, sort_pack);
1008 static void prepare_packed_git_mru(struct repository *r)
1010 struct packed_git *p;
1012 INIT_LIST_HEAD(&r->objects->packed_git_mru);
1014 for (p = r->objects->packed_git; p; p = p->next)
1015 list_add_tail(&p->mru, &r->objects->packed_git_mru);
1018 static void prepare_packed_git(struct repository *r)
1020 struct object_directory *odb;
1022 if (r->objects->packed_git_initialized)
1023 return;
1025 prepare_alt_odb(r);
1026 for (odb = r->objects->odb; odb; odb = odb->next) {
1027 int local = (odb == r->objects->odb);
1028 prepare_multi_pack_index_one(r, odb->path, local);
1029 prepare_packed_git_one(r, odb->path, local);
1031 rearrange_packed_git(r);
1033 prepare_packed_git_mru(r);
1034 r->objects->packed_git_initialized = 1;
1037 void reprepare_packed_git(struct repository *r)
1039 struct object_directory *odb;
1041 obj_read_lock();
1044 * Reprepare alt odbs, in case the alternates file was modified
1045 * during the course of this process. This only _adds_ odbs to
1046 * the linked list, so existing odbs will continue to exist for
1047 * the lifetime of the process.
1049 r->objects->loaded_alternates = 0;
1050 prepare_alt_odb(r);
1052 for (odb = r->objects->odb; odb; odb = odb->next)
1053 odb_clear_loose_cache(odb);
1055 r->objects->approximate_object_count_valid = 0;
1056 r->objects->packed_git_initialized = 0;
1057 prepare_packed_git(r);
1058 obj_read_unlock();
1061 struct packed_git *get_packed_git(struct repository *r)
1063 prepare_packed_git(r);
1064 return r->objects->packed_git;
1067 struct multi_pack_index *get_multi_pack_index(struct repository *r)
1069 prepare_packed_git(r);
1070 return r->objects->multi_pack_index;
1073 struct multi_pack_index *get_local_multi_pack_index(struct repository *r)
1075 struct multi_pack_index *m = get_multi_pack_index(r);
1077 /* no need to iterate; we always put the local one first (if any) */
1078 if (m && m->local)
1079 return m;
1081 return NULL;
1084 struct packed_git *get_all_packs(struct repository *r)
1086 struct multi_pack_index *m;
1088 prepare_packed_git(r);
1089 for (m = r->objects->multi_pack_index; m; m = m->next) {
1090 uint32_t i;
1091 for (i = 0; i < m->num_packs + m->num_packs_in_base; i++)
1092 prepare_midx_pack(r, m, i);
1095 return r->objects->packed_git;
1098 struct list_head *get_packed_git_mru(struct repository *r)
1100 prepare_packed_git(r);
1101 return &r->objects->packed_git_mru;
1104 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1105 unsigned long len, enum object_type *type, unsigned long *sizep)
1107 unsigned shift;
1108 size_t size, c;
1109 unsigned long used = 0;
1111 c = buf[used++];
1112 *type = (c >> 4) & 7;
1113 size = c & 15;
1114 shift = 4;
1115 while (c & 0x80) {
1116 if (len <= used || (bitsizeof(long) - 7) < shift) {
1117 error("bad object header");
1118 size = used = 0;
1119 break;
1121 c = buf[used++];
1122 size = st_add(size, st_left_shift(c & 0x7f, shift));
1123 shift += 7;
1125 *sizep = cast_size_t_to_ulong(size);
1126 return used;
1129 unsigned long get_size_from_delta(struct packed_git *p,
1130 struct pack_window **w_curs,
1131 off_t curpos)
1133 const unsigned char *data;
1134 unsigned char delta_head[20], *in;
1135 git_zstream stream;
1136 int st;
1138 memset(&stream, 0, sizeof(stream));
1139 stream.next_out = delta_head;
1140 stream.avail_out = sizeof(delta_head);
1142 git_inflate_init(&stream);
1143 do {
1144 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1145 stream.next_in = in;
1147 * Note: the window section returned by use_pack() must be
1148 * available throughout git_inflate()'s unlocked execution. To
1149 * ensure no other thread will modify the window in the
1150 * meantime, we rely on the packed_window.inuse_cnt. This
1151 * counter is incremented before window reading and checked
1152 * before window disposal.
1154 * Other worrying sections could be the call to close_pack_fd(),
1155 * which can close packs even with in-use windows, and to
1156 * reprepare_packed_git(). Regarding the former, mmap doc says:
1157 * "closing the file descriptor does not unmap the region". And
1158 * for the latter, it won't re-open already available packs.
1160 obj_read_unlock();
1161 st = git_inflate(&stream, Z_FINISH);
1162 obj_read_lock();
1163 curpos += stream.next_in - in;
1164 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1165 stream.total_out < sizeof(delta_head));
1166 git_inflate_end(&stream);
1167 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1168 error("delta data unpack-initial failed");
1169 return 0;
1172 /* Examine the initial part of the delta to figure out
1173 * the result size.
1175 data = delta_head;
1177 /* ignore base size */
1178 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1180 /* Read the result size */
1181 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1184 int unpack_object_header(struct packed_git *p,
1185 struct pack_window **w_curs,
1186 off_t *curpos,
1187 unsigned long *sizep)
1189 unsigned char *base;
1190 unsigned long left;
1191 unsigned long used;
1192 enum object_type type;
1194 /* use_pack() assures us we have [base, base + 20) available
1195 * as a range that we can look at. (Its actually the hash
1196 * size that is assured.) With our object header encoding
1197 * the maximum deflated object size is 2^137, which is just
1198 * insane, so we know won't exceed what we have been given.
1200 base = use_pack(p, w_curs, *curpos, &left);
1201 used = unpack_object_header_buffer(base, left, &type, sizep);
1202 if (!used) {
1203 type = OBJ_BAD;
1204 } else
1205 *curpos += used;
1207 return type;
1210 void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
1212 oidset_insert(&p->bad_objects, oid);
1215 const struct packed_git *has_packed_and_bad(struct repository *r,
1216 const struct object_id *oid)
1218 struct packed_git *p;
1220 for (p = r->objects->packed_git; p; p = p->next)
1221 if (oidset_contains(&p->bad_objects, oid))
1222 return p;
1223 return NULL;
1226 off_t get_delta_base(struct packed_git *p,
1227 struct pack_window **w_curs,
1228 off_t *curpos,
1229 enum object_type type,
1230 off_t delta_obj_offset)
1232 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1233 off_t base_offset;
1235 /* use_pack() assured us we have [base_info, base_info + 20)
1236 * as a range that we can look at without walking off the
1237 * end of the mapped window. Its actually the hash size
1238 * that is assured. An OFS_DELTA longer than the hash size
1239 * is stupid, as then a REF_DELTA would be smaller to store.
1241 if (type == OBJ_OFS_DELTA) {
1242 unsigned used = 0;
1243 unsigned char c = base_info[used++];
1244 base_offset = c & 127;
1245 while (c & 128) {
1246 base_offset += 1;
1247 if (!base_offset || MSB(base_offset, 7))
1248 return 0; /* overflow */
1249 c = base_info[used++];
1250 base_offset = (base_offset << 7) + (c & 127);
1252 base_offset = delta_obj_offset - base_offset;
1253 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1254 return 0; /* out of bound */
1255 *curpos += used;
1256 } else if (type == OBJ_REF_DELTA) {
1257 /* The base entry _must_ be in the same pack */
1258 struct object_id oid;
1259 oidread(&oid, base_info, p->repo->hash_algo);
1260 base_offset = find_pack_entry_one(&oid, p);
1261 *curpos += p->repo->hash_algo->rawsz;
1262 } else
1263 die("I am totally screwed");
1264 return base_offset;
1268 * Like get_delta_base above, but we return the sha1 instead of the pack
1269 * offset. This means it is cheaper for REF deltas (we do not have to do
1270 * the final object lookup), but more expensive for OFS deltas (we
1271 * have to load the revidx to convert the offset back into a sha1).
1273 static int get_delta_base_oid(struct packed_git *p,
1274 struct pack_window **w_curs,
1275 off_t curpos,
1276 struct object_id *oid,
1277 enum object_type type,
1278 off_t delta_obj_offset)
1280 if (type == OBJ_REF_DELTA) {
1281 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1282 oidread(oid, base, p->repo->hash_algo);
1283 return 0;
1284 } else if (type == OBJ_OFS_DELTA) {
1285 uint32_t base_pos;
1286 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1287 type, delta_obj_offset);
1289 if (!base_offset)
1290 return -1;
1292 if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1293 return -1;
1295 return nth_packed_object_id(oid, p,
1296 pack_pos_to_index(p, base_pos));
1297 } else
1298 return -1;
1301 static int retry_bad_packed_offset(struct repository *r,
1302 struct packed_git *p,
1303 off_t obj_offset)
1305 int type;
1306 uint32_t pos;
1307 struct object_id oid;
1308 if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1309 return OBJ_BAD;
1310 nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1311 mark_bad_packed_object(p, &oid);
1312 type = oid_object_info(r, &oid, NULL);
1313 if (type <= OBJ_NONE)
1314 return OBJ_BAD;
1315 return type;
1318 #define POI_STACK_PREALLOC 64
1320 static enum object_type packed_to_object_type(struct repository *r,
1321 struct packed_git *p,
1322 off_t obj_offset,
1323 enum object_type type,
1324 struct pack_window **w_curs,
1325 off_t curpos)
1327 off_t small_poi_stack[POI_STACK_PREALLOC];
1328 off_t *poi_stack = small_poi_stack;
1329 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1331 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1332 off_t base_offset;
1333 unsigned long size;
1334 /* Push the object we're going to leave behind */
1335 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1336 poi_stack_alloc = alloc_nr(poi_stack_nr);
1337 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1338 COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1339 } else {
1340 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1342 poi_stack[poi_stack_nr++] = obj_offset;
1343 /* If parsing the base offset fails, just unwind */
1344 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1345 if (!base_offset)
1346 goto unwind;
1347 curpos = obj_offset = base_offset;
1348 type = unpack_object_header(p, w_curs, &curpos, &size);
1349 if (type <= OBJ_NONE) {
1350 /* If getting the base itself fails, we first
1351 * retry the base, otherwise unwind */
1352 type = retry_bad_packed_offset(r, p, base_offset);
1353 if (type > OBJ_NONE)
1354 goto out;
1355 goto unwind;
1359 switch (type) {
1360 case OBJ_BAD:
1361 case OBJ_COMMIT:
1362 case OBJ_TREE:
1363 case OBJ_BLOB:
1364 case OBJ_TAG:
1365 break;
1366 default:
1367 error("unknown object type %i at offset %"PRIuMAX" in %s",
1368 type, (uintmax_t)obj_offset, p->pack_name);
1369 type = OBJ_BAD;
1372 out:
1373 if (poi_stack != small_poi_stack)
1374 free(poi_stack);
1375 return type;
1377 unwind:
1378 while (poi_stack_nr) {
1379 obj_offset = poi_stack[--poi_stack_nr];
1380 type = retry_bad_packed_offset(r, p, obj_offset);
1381 if (type > OBJ_NONE)
1382 goto out;
1384 type = OBJ_BAD;
1385 goto out;
1388 static struct hashmap delta_base_cache;
1389 static size_t delta_base_cached;
1391 static LIST_HEAD(delta_base_cache_lru);
1393 struct delta_base_cache_key {
1394 struct packed_git *p;
1395 off_t base_offset;
1398 struct delta_base_cache_entry {
1399 struct hashmap_entry ent;
1400 struct delta_base_cache_key key;
1401 struct list_head lru;
1402 void *data;
1403 unsigned long size;
1404 enum object_type type;
1407 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1409 unsigned int hash;
1411 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1412 hash += (hash >> 8) + (hash >> 16);
1413 return hash;
1416 static struct delta_base_cache_entry *
1417 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1419 struct hashmap_entry entry, *e;
1420 struct delta_base_cache_key key;
1422 if (!delta_base_cache.cmpfn)
1423 return NULL;
1425 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1426 key.p = p;
1427 key.base_offset = base_offset;
1428 e = hashmap_get(&delta_base_cache, &entry, &key);
1429 return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1432 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1433 const struct delta_base_cache_key *b)
1435 return a->p == b->p && a->base_offset == b->base_offset;
1438 static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1439 const struct hashmap_entry *va,
1440 const struct hashmap_entry *vb,
1441 const void *vkey)
1443 const struct delta_base_cache_entry *a, *b;
1444 const struct delta_base_cache_key *key = vkey;
1446 a = container_of(va, const struct delta_base_cache_entry, ent);
1447 b = container_of(vb, const struct delta_base_cache_entry, ent);
1449 if (key)
1450 return !delta_base_cache_key_eq(&a->key, key);
1451 else
1452 return !delta_base_cache_key_eq(&a->key, &b->key);
1455 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1457 return !!get_delta_base_cache_entry(p, base_offset);
1461 * Remove the entry from the cache, but do _not_ free the associated
1462 * entry data. The caller takes ownership of the "data" buffer, and
1463 * should copy out any fields it wants before detaching.
1465 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1467 hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1468 list_del(&ent->lru);
1469 delta_base_cached -= ent->size;
1470 free(ent);
1473 static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1474 off_t base_offset, unsigned long *base_size,
1475 enum object_type *type)
1477 struct delta_base_cache_entry *ent;
1479 ent = get_delta_base_cache_entry(p, base_offset);
1480 if (!ent)
1481 return unpack_entry(r, p, base_offset, type, base_size);
1483 if (type)
1484 *type = ent->type;
1485 if (base_size)
1486 *base_size = ent->size;
1487 return xmemdupz(ent->data, ent->size);
1490 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1492 free(ent->data);
1493 detach_delta_base_cache_entry(ent);
1496 void clear_delta_base_cache(void)
1498 struct list_head *lru, *tmp;
1499 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1500 struct delta_base_cache_entry *entry =
1501 list_entry(lru, struct delta_base_cache_entry, lru);
1502 release_delta_base_cache(entry);
1506 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1507 void *base, unsigned long base_size,
1508 unsigned long delta_base_cache_limit,
1509 enum object_type type)
1511 struct delta_base_cache_entry *ent;
1512 struct list_head *lru, *tmp;
1515 * Check required to avoid redundant entries when more than one thread
1516 * is unpacking the same object, in unpack_entry() (since its phases I
1517 * and III might run concurrently across multiple threads).
1519 if (in_delta_base_cache(p, base_offset)) {
1520 free(base);
1521 return;
1524 delta_base_cached += base_size;
1526 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1527 struct delta_base_cache_entry *f =
1528 list_entry(lru, struct delta_base_cache_entry, lru);
1529 if (delta_base_cached <= delta_base_cache_limit)
1530 break;
1531 release_delta_base_cache(f);
1534 ent = xmalloc(sizeof(*ent));
1535 ent->key.p = p;
1536 ent->key.base_offset = base_offset;
1537 ent->type = type;
1538 ent->data = base;
1539 ent->size = base_size;
1540 list_add_tail(&ent->lru, &delta_base_cache_lru);
1542 if (!delta_base_cache.cmpfn)
1543 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1544 hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1545 hashmap_add(&delta_base_cache, &ent->ent);
1548 int packed_object_info(struct repository *r, struct packed_git *p,
1549 off_t obj_offset, struct object_info *oi)
1551 struct pack_window *w_curs = NULL;
1552 unsigned long size;
1553 off_t curpos = obj_offset;
1554 enum object_type type;
1557 * We always get the representation type, but only convert it to
1558 * a "real" type later if the caller is interested.
1560 if (oi->contentp) {
1561 *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1562 &type);
1563 if (!*oi->contentp)
1564 type = OBJ_BAD;
1565 } else {
1566 type = unpack_object_header(p, &w_curs, &curpos, &size);
1569 if (!oi->contentp && oi->sizep) {
1570 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1571 off_t tmp_pos = curpos;
1572 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1573 type, obj_offset);
1574 if (!base_offset) {
1575 type = OBJ_BAD;
1576 goto out;
1578 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1579 if (*oi->sizep == 0) {
1580 type = OBJ_BAD;
1581 goto out;
1583 } else {
1584 *oi->sizep = size;
1588 if (oi->disk_sizep) {
1589 uint32_t pos;
1590 if (offset_to_pack_pos(p, obj_offset, &pos) < 0) {
1591 error("could not find object at offset %"PRIuMAX" "
1592 "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1593 type = OBJ_BAD;
1594 goto out;
1597 *oi->disk_sizep = pack_pos_to_offset(p, pos + 1) - obj_offset;
1600 if (oi->typep || oi->type_name) {
1601 enum object_type ptot;
1602 ptot = packed_to_object_type(r, p, obj_offset,
1603 type, &w_curs, curpos);
1604 if (oi->typep)
1605 *oi->typep = ptot;
1606 if (oi->type_name) {
1607 const char *tn = type_name(ptot);
1608 if (tn)
1609 strbuf_addstr(oi->type_name, tn);
1611 if (ptot < 0) {
1612 type = OBJ_BAD;
1613 goto out;
1617 if (oi->delta_base_oid) {
1618 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1619 if (get_delta_base_oid(p, &w_curs, curpos,
1620 oi->delta_base_oid,
1621 type, obj_offset) < 0) {
1622 type = OBJ_BAD;
1623 goto out;
1625 } else
1626 oidclr(oi->delta_base_oid, p->repo->hash_algo);
1629 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1630 OI_PACKED;
1632 out:
1633 unuse_pack(&w_curs);
1634 return type;
1637 static void *unpack_compressed_entry(struct packed_git *p,
1638 struct pack_window **w_curs,
1639 off_t curpos,
1640 unsigned long size)
1642 int st;
1643 git_zstream stream;
1644 unsigned char *buffer, *in;
1646 buffer = xmallocz_gently(size);
1647 if (!buffer)
1648 return NULL;
1649 memset(&stream, 0, sizeof(stream));
1650 stream.next_out = buffer;
1651 stream.avail_out = size + 1;
1653 git_inflate_init(&stream);
1654 do {
1655 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1656 stream.next_in = in;
1658 * Note: we must ensure the window section returned by
1659 * use_pack() will be available throughout git_inflate()'s
1660 * unlocked execution. Please refer to the comment at
1661 * get_size_from_delta() to see how this is done.
1663 obj_read_unlock();
1664 st = git_inflate(&stream, Z_FINISH);
1665 obj_read_lock();
1666 if (!stream.avail_out)
1667 break; /* the payload is larger than it should be */
1668 curpos += stream.next_in - in;
1669 } while (st == Z_OK || st == Z_BUF_ERROR);
1670 git_inflate_end(&stream);
1671 if ((st != Z_STREAM_END) || stream.total_out != size) {
1672 free(buffer);
1673 return NULL;
1676 /* versions of zlib can clobber unconsumed portion of outbuf */
1677 buffer[size] = '\0';
1679 return buffer;
1682 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1684 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1685 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1686 p->pack_name, (uintmax_t)obj_offset);
1689 int do_check_packed_object_crc;
1691 #define UNPACK_ENTRY_STACK_PREALLOC 64
1692 struct unpack_entry_stack_ent {
1693 off_t obj_offset;
1694 off_t curpos;
1695 unsigned long size;
1698 void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1699 enum object_type *final_type, unsigned long *final_size)
1701 struct pack_window *w_curs = NULL;
1702 off_t curpos = obj_offset;
1703 void *data = NULL;
1704 unsigned long size;
1705 enum object_type type;
1706 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1707 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1708 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1709 int base_from_cache = 0;
1711 prepare_repo_settings(p->repo);
1713 write_pack_access_log(p, obj_offset);
1715 /* PHASE 1: drill down to the innermost base object */
1716 for (;;) {
1717 off_t base_offset;
1718 int i;
1719 struct delta_base_cache_entry *ent;
1721 ent = get_delta_base_cache_entry(p, curpos);
1722 if (ent) {
1723 type = ent->type;
1724 data = ent->data;
1725 size = ent->size;
1726 detach_delta_base_cache_entry(ent);
1727 base_from_cache = 1;
1728 break;
1731 if (do_check_packed_object_crc && p->index_version > 1) {
1732 uint32_t pack_pos, index_pos;
1733 off_t len;
1735 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1736 error("could not find object at offset %"PRIuMAX" in pack %s",
1737 (uintmax_t)obj_offset, p->pack_name);
1738 data = NULL;
1739 goto out;
1742 len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1743 index_pos = pack_pos_to_index(p, pack_pos);
1744 if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1745 struct object_id oid;
1746 nth_packed_object_id(&oid, p, index_pos);
1747 error("bad packed object CRC for %s",
1748 oid_to_hex(&oid));
1749 mark_bad_packed_object(p, &oid);
1750 data = NULL;
1751 goto out;
1755 type = unpack_object_header(p, &w_curs, &curpos, &size);
1756 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1757 break;
1759 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1760 if (!base_offset) {
1761 error("failed to validate delta base reference "
1762 "at offset %"PRIuMAX" from %s",
1763 (uintmax_t)curpos, p->pack_name);
1764 /* bail to phase 2, in hopes of recovery */
1765 data = NULL;
1766 break;
1769 /* push object, proceed to base */
1770 if (delta_stack_nr >= delta_stack_alloc
1771 && delta_stack == small_delta_stack) {
1772 delta_stack_alloc = alloc_nr(delta_stack_nr);
1773 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1774 COPY_ARRAY(delta_stack, small_delta_stack,
1775 delta_stack_nr);
1776 } else {
1777 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1779 i = delta_stack_nr++;
1780 delta_stack[i].obj_offset = obj_offset;
1781 delta_stack[i].curpos = curpos;
1782 delta_stack[i].size = size;
1784 curpos = obj_offset = base_offset;
1787 /* PHASE 2: handle the base */
1788 switch (type) {
1789 case OBJ_OFS_DELTA:
1790 case OBJ_REF_DELTA:
1791 if (data)
1792 BUG("unpack_entry: left loop at a valid delta");
1793 break;
1794 case OBJ_COMMIT:
1795 case OBJ_TREE:
1796 case OBJ_BLOB:
1797 case OBJ_TAG:
1798 if (!base_from_cache)
1799 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1800 break;
1801 default:
1802 data = NULL;
1803 error("unknown object type %i at offset %"PRIuMAX" in %s",
1804 type, (uintmax_t)obj_offset, p->pack_name);
1807 /* PHASE 3: apply deltas in order */
1809 /* invariants:
1810 * 'data' holds the base data, or NULL if there was corruption
1812 while (delta_stack_nr) {
1813 void *delta_data;
1814 void *base = data;
1815 void *external_base = NULL;
1816 unsigned long delta_size, base_size = size;
1817 int i;
1818 off_t base_obj_offset = obj_offset;
1820 data = NULL;
1822 if (!base) {
1824 * We're probably in deep shit, but let's try to fetch
1825 * the required base anyway from another pack or loose.
1826 * This is costly but should happen only in the presence
1827 * of a corrupted pack, and is better than failing outright.
1829 uint32_t pos;
1830 struct object_id base_oid;
1831 if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1832 struct object_info oi = OBJECT_INFO_INIT;
1834 nth_packed_object_id(&base_oid, p,
1835 pack_pos_to_index(p, pos));
1836 error("failed to read delta base object %s"
1837 " at offset %"PRIuMAX" from %s",
1838 oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1839 p->pack_name);
1840 mark_bad_packed_object(p, &base_oid);
1842 oi.typep = &type;
1843 oi.sizep = &base_size;
1844 oi.contentp = &base;
1845 if (oid_object_info_extended(r, &base_oid, &oi, 0) < 0)
1846 base = NULL;
1848 external_base = base;
1852 i = --delta_stack_nr;
1853 obj_offset = delta_stack[i].obj_offset;
1854 curpos = delta_stack[i].curpos;
1855 delta_size = delta_stack[i].size;
1857 if (!base)
1858 continue;
1860 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1862 if (!delta_data) {
1863 error("failed to unpack compressed delta "
1864 "at offset %"PRIuMAX" from %s",
1865 (uintmax_t)curpos, p->pack_name);
1866 data = NULL;
1867 } else {
1868 data = patch_delta(base, base_size, delta_data,
1869 delta_size, &size);
1872 * We could not apply the delta; warn the user, but
1873 * keep going. Our failure will be noticed either in
1874 * the next iteration of the loop, or if this is the
1875 * final delta, in the caller when we return NULL.
1876 * Those code paths will take care of making a more
1877 * explicit warning and retrying with another copy of
1878 * the object.
1880 if (!data)
1881 error("failed to apply delta");
1885 * We delay adding `base` to the cache until the end of the loop
1886 * because unpack_compressed_entry() momentarily releases the
1887 * obj_read_mutex, giving another thread the chance to access
1888 * the cache. Therefore, if `base` was already there, this other
1889 * thread could free() it (e.g. to make space for another entry)
1890 * before we are done using it.
1892 if (!external_base)
1893 add_delta_base_cache(p, base_obj_offset, base, base_size,
1894 p->repo->settings.delta_base_cache_limit,
1895 type);
1897 free(delta_data);
1898 free(external_base);
1901 if (final_type)
1902 *final_type = type;
1903 if (final_size)
1904 *final_size = size;
1906 out:
1907 unuse_pack(&w_curs);
1909 if (delta_stack != small_delta_stack)
1910 free(delta_stack);
1912 return data;
1915 int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1917 const unsigned char *index_fanout = p->index_data;
1918 const unsigned char *index_lookup;
1919 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1920 int index_lookup_width;
1922 if (!index_fanout)
1923 BUG("bsearch_pack called without a valid pack-index");
1925 index_lookup = index_fanout + 4 * 256;
1926 if (p->index_version == 1) {
1927 index_lookup_width = hashsz + 4;
1928 index_lookup += 4;
1929 } else {
1930 index_lookup_width = hashsz;
1931 index_fanout += 8;
1932 index_lookup += 8;
1935 return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1936 index_lookup, index_lookup_width, result);
1939 int nth_packed_object_id(struct object_id *oid,
1940 struct packed_git *p,
1941 uint32_t n)
1943 const unsigned char *index = p->index_data;
1944 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1945 if (!index) {
1946 if (open_pack_index(p))
1947 return -1;
1948 index = p->index_data;
1950 if (n >= p->num_objects)
1951 return -1;
1952 index += 4 * 256;
1953 if (p->index_version == 1) {
1954 oidread(oid, index + st_add(st_mult(hashsz + 4, n), 4),
1955 p->repo->hash_algo);
1956 } else {
1957 index += 8;
1958 oidread(oid, index + st_mult(hashsz, n), p->repo->hash_algo);
1960 return 0;
1963 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1965 const unsigned char *ptr = vptr;
1966 const unsigned char *start = p->index_data;
1967 const unsigned char *end = start + p->index_size;
1968 if (ptr < start)
1969 die(_("offset before start of pack index for %s (corrupt index?)"),
1970 p->pack_name);
1971 /* No need to check for underflow; .idx files must be at least 8 bytes */
1972 if (ptr >= end - 8)
1973 die(_("offset beyond end of pack index for %s (truncated index?)"),
1974 p->pack_name);
1977 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1979 const unsigned char *index = p->index_data;
1980 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1981 index += 4 * 256;
1982 if (p->index_version == 1) {
1983 return ntohl(*((uint32_t *)(index + st_mult(hashsz + 4, n))));
1984 } else {
1985 uint32_t off;
1986 index += st_add(8, st_mult(p->num_objects, hashsz + 4));
1987 off = ntohl(*((uint32_t *)(index + st_mult(4, n))));
1988 if (!(off & 0x80000000))
1989 return off;
1990 index += st_add(st_mult(p->num_objects, 4),
1991 st_mult(off & 0x7fffffff, 8));
1992 check_pack_index_ptr(p, index);
1993 return get_be64(index);
1997 off_t find_pack_entry_one(const struct object_id *oid,
1998 struct packed_git *p)
2000 const unsigned char *index = p->index_data;
2001 uint32_t result;
2003 if (!index) {
2004 if (open_pack_index(p))
2005 return 0;
2008 if (bsearch_pack(oid, p, &result))
2009 return nth_packed_object_offset(p, result);
2010 return 0;
2013 int is_pack_valid(struct packed_git *p)
2015 /* An already open pack is known to be valid. */
2016 if (p->pack_fd != -1)
2017 return 1;
2019 /* If the pack has one window completely covering the
2020 * file size, the pack is known to be valid even if
2021 * the descriptor is not currently open.
2023 if (p->windows) {
2024 struct pack_window *w = p->windows;
2026 if (!w->offset && w->len == p->pack_size)
2027 return 1;
2030 /* Force the pack to open to prove its valid. */
2031 return !open_packed_git(p);
2034 struct packed_git *find_oid_pack(const struct object_id *oid,
2035 struct packed_git *packs)
2037 struct packed_git *p;
2039 for (p = packs; p; p = p->next) {
2040 if (find_pack_entry_one(oid, p))
2041 return p;
2043 return NULL;
2047 static int fill_pack_entry(const struct object_id *oid,
2048 struct pack_entry *e,
2049 struct packed_git *p)
2051 off_t offset;
2053 if (oidset_size(&p->bad_objects) &&
2054 oidset_contains(&p->bad_objects, oid))
2055 return 0;
2057 offset = find_pack_entry_one(oid, p);
2058 if (!offset)
2059 return 0;
2062 * We are about to tell the caller where they can locate the
2063 * requested object. We better make sure the packfile is
2064 * still here and can be accessed before supplying that
2065 * answer, as it may have been deleted since the index was
2066 * loaded!
2068 if (!is_pack_valid(p))
2069 return 0;
2070 e->offset = offset;
2071 e->p = p;
2072 return 1;
2075 int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
2077 struct list_head *pos;
2078 struct multi_pack_index *m;
2080 prepare_packed_git(r);
2081 if (!r->objects->packed_git && !r->objects->multi_pack_index)
2082 return 0;
2084 for (m = r->objects->multi_pack_index; m; m = m->next) {
2085 if (fill_midx_entry(r, oid, e, m))
2086 return 1;
2089 list_for_each(pos, &r->objects->packed_git_mru) {
2090 struct packed_git *p = list_entry(pos, struct packed_git, mru);
2091 if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
2092 list_move(&p->mru, &r->objects->packed_git_mru);
2093 return 1;
2096 return 0;
2099 static void maybe_invalidate_kept_pack_cache(struct repository *r,
2100 unsigned flags)
2102 if (!r->objects->kept_pack_cache.packs)
2103 return;
2104 if (r->objects->kept_pack_cache.flags == flags)
2105 return;
2106 FREE_AND_NULL(r->objects->kept_pack_cache.packs);
2107 r->objects->kept_pack_cache.flags = 0;
2110 static struct packed_git **kept_pack_cache(struct repository *r, unsigned flags)
2112 maybe_invalidate_kept_pack_cache(r, flags);
2114 if (!r->objects->kept_pack_cache.packs) {
2115 struct packed_git **packs = NULL;
2116 size_t nr = 0, alloc = 0;
2117 struct packed_git *p;
2120 * We want "all" packs here, because we need to cover ones that
2121 * are used by a midx, as well. We need to look in every one of
2122 * them (instead of the midx itself) to cover duplicates. It's
2123 * possible that an object is found in two packs that the midx
2124 * covers, one kept and one not kept, but the midx returns only
2125 * the non-kept version.
2127 for (p = get_all_packs(r); p; p = p->next) {
2128 if ((p->pack_keep && (flags & ON_DISK_KEEP_PACKS)) ||
2129 (p->pack_keep_in_core && (flags & IN_CORE_KEEP_PACKS))) {
2130 ALLOC_GROW(packs, nr + 1, alloc);
2131 packs[nr++] = p;
2134 ALLOC_GROW(packs, nr + 1, alloc);
2135 packs[nr] = NULL;
2137 r->objects->kept_pack_cache.packs = packs;
2138 r->objects->kept_pack_cache.flags = flags;
2141 return r->objects->kept_pack_cache.packs;
2144 int find_kept_pack_entry(struct repository *r,
2145 const struct object_id *oid,
2146 unsigned flags,
2147 struct pack_entry *e)
2149 struct packed_git **cache;
2151 for (cache = kept_pack_cache(r, flags); *cache; cache++) {
2152 struct packed_git *p = *cache;
2153 if (fill_pack_entry(oid, e, p))
2154 return 1;
2157 return 0;
2160 int has_object_pack(struct repository *r, const struct object_id *oid)
2162 struct pack_entry e;
2163 return find_pack_entry(r, oid, &e);
2166 int has_object_kept_pack(struct repository *r, const struct object_id *oid,
2167 unsigned flags)
2169 struct pack_entry e;
2170 return find_kept_pack_entry(r, oid, flags, &e);
2173 int for_each_object_in_pack(struct packed_git *p,
2174 each_packed_object_fn cb, void *data,
2175 enum for_each_object_flags flags)
2177 uint32_t i;
2178 int r = 0;
2180 if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2181 if (load_pack_revindex(p->repo, p))
2182 return -1;
2185 for (i = 0; i < p->num_objects; i++) {
2186 uint32_t index_pos;
2187 struct object_id oid;
2190 * We are iterating "i" from 0 up to num_objects, but its
2191 * meaning may be different, depending on the requested output
2192 * order:
2194 * - in object-name order, it is the same as the index order
2195 * used by nth_packed_object_id(), so we can pass it
2196 * directly
2198 * - in pack-order, it is pack position, which we must
2199 * convert to an index position in order to get the oid.
2201 if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2202 index_pos = pack_pos_to_index(p, i);
2203 else
2204 index_pos = i;
2206 if (nth_packed_object_id(&oid, p, index_pos) < 0)
2207 return error("unable to get sha1 of object %u in %s",
2208 index_pos, p->pack_name);
2210 r = cb(&oid, p, index_pos, data);
2211 if (r)
2212 break;
2214 return r;
2217 int for_each_packed_object(struct repository *repo, each_packed_object_fn cb,
2218 void *data, enum for_each_object_flags flags)
2220 struct packed_git *p;
2221 int r = 0;
2222 int pack_errors = 0;
2224 for (p = get_all_packs(repo); p; p = p->next) {
2225 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2226 continue;
2227 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2228 !p->pack_promisor)
2229 continue;
2230 if ((flags & FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS) &&
2231 p->pack_keep_in_core)
2232 continue;
2233 if ((flags & FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS) &&
2234 p->pack_keep)
2235 continue;
2236 if (open_pack_index(p)) {
2237 pack_errors = 1;
2238 continue;
2240 r = for_each_object_in_pack(p, cb, data, flags);
2241 if (r)
2242 break;
2244 return r ? r : pack_errors;
2247 static int add_promisor_object(const struct object_id *oid,
2248 struct packed_git *pack,
2249 uint32_t pos UNUSED,
2250 void *set_)
2252 struct oidset *set = set_;
2253 struct object *obj;
2254 int we_parsed_object;
2256 obj = lookup_object(pack->repo, oid);
2257 if (obj && obj->parsed) {
2258 we_parsed_object = 0;
2259 } else {
2260 we_parsed_object = 1;
2261 obj = parse_object(pack->repo, oid);
2264 if (!obj)
2265 return 1;
2267 oidset_insert(set, oid);
2270 * If this is a tree, commit, or tag, the objects it refers
2271 * to are also promisor objects. (Blobs refer to no objects->)
2273 if (obj->type == OBJ_TREE) {
2274 struct tree *tree = (struct tree *)obj;
2275 struct tree_desc desc;
2276 struct name_entry entry;
2277 if (init_tree_desc_gently(&desc, &tree->object.oid,
2278 tree->buffer, tree->size, 0))
2280 * Error messages are given when packs are
2281 * verified, so do not print any here.
2283 return 0;
2284 while (tree_entry_gently(&desc, &entry))
2285 oidset_insert(set, &entry.oid);
2286 if (we_parsed_object)
2287 free_tree_buffer(tree);
2288 } else if (obj->type == OBJ_COMMIT) {
2289 struct commit *commit = (struct commit *) obj;
2290 struct commit_list *parents = commit->parents;
2292 oidset_insert(set, get_commit_tree_oid(commit));
2293 for (; parents; parents = parents->next)
2294 oidset_insert(set, &parents->item->object.oid);
2295 } else if (obj->type == OBJ_TAG) {
2296 struct tag *tag = (struct tag *) obj;
2297 oidset_insert(set, get_tagged_oid(tag));
2299 return 0;
2302 int is_promisor_object(struct repository *r, const struct object_id *oid)
2304 static struct oidset promisor_objects;
2305 static int promisor_objects_prepared;
2307 if (!promisor_objects_prepared) {
2308 if (repo_has_promisor_remote(r)) {
2309 for_each_packed_object(r, add_promisor_object,
2310 &promisor_objects,
2311 FOR_EACH_OBJECT_PROMISOR_ONLY |
2312 FOR_EACH_OBJECT_PACK_ORDER);
2314 promisor_objects_prepared = 1;
2316 return oidset_contains(&promisor_objects, oid);
2319 int parse_pack_header_option(const char *in, unsigned char *out, unsigned int *len)
2321 unsigned char *hdr;
2322 char *c;
2324 hdr = out;
2325 put_be32(hdr, PACK_SIGNATURE);
2326 hdr += 4;
2327 put_be32(hdr, strtoul(in, &c, 10));
2328 hdr += 4;
2329 if (*c != ',')
2330 return -1;
2331 put_be32(hdr, strtoul(c + 1, &c, 10));
2332 hdr += 4;
2333 if (*c)
2334 return -1;
2335 *len = hdr - out;
2336 return 0;