interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / packfile.c

2232 lines · 59260 bytes Raw Blame History
1#define DISABLE_SIGN_COMPARE_WARNINGS
2
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 "packfile.h"
12#include "delta.h"
13#include "hash-lookup.h"
14#include "commit.h"
15#include "object.h"
16#include "tag.h"
17#include "trace.h"
18#include "tree-walk.h"
19#include "tree.h"
20#include "object-file.h"
21#include "odb.h"
22#include "odb/streaming.h"
23#include "midx.h"
24#include "commit-graph.h"
25#include "pack-revindex.h"
26#include "promisor-remote.h"
27#include "pack-mtimes.h"
28
29char *odb_pack_name(struct repository *r, struct strbuf *buf,
30 const unsigned char *hash, const char *ext)
31{
32 strbuf_reset(buf);
33 strbuf_addf(buf, "%s/pack/pack-%s.%s", repo_get_object_directory(r),
34 hash_to_hex_algop(hash, r->hash_algo), ext);
35 return buf->buf;
36}
37
38static unsigned int pack_used_ctr;
39static unsigned int pack_mmap_calls;
40static unsigned int peak_pack_open_windows;
41static unsigned int pack_open_windows;
42static unsigned int pack_open_fds;
43static unsigned int pack_max_fds;
44static size_t peak_pack_mapped;
45static size_t pack_mapped;
46
47#define SZ_FMT PRIuMAX
48static inline uintmax_t sz_fmt(size_t s) { return s; }
49
50void pack_report(struct repository *repo)
51{
52 fprintf(stderr,
53 "pack_report: getpagesize() = %10" SZ_FMT "\n"
54 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
55 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
56 sz_fmt(getpagesize()),
57 sz_fmt(repo->settings.packed_git_window_size),
58 sz_fmt(repo->settings.packed_git_limit));
59 fprintf(stderr,
60 "pack_report: pack_used_ctr = %10u\n"
61 "pack_report: pack_mmap_calls = %10u\n"
62 "pack_report: pack_open_windows = %10u / %10u\n"
63 "pack_report: pack_mapped = "
64 "%10" SZ_FMT " / %10" SZ_FMT "\n",
65 pack_used_ctr,
66 pack_mmap_calls,
67 pack_open_windows, peak_pack_open_windows,
68 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
69}
70
71/*
72 * Open and mmap the index file at path, perform a couple of
73 * consistency checks, then record its information to p. Return 0 on
74 * success.
75 */
76static int check_packed_git_idx(const char *path, struct packed_git *p)
77{
78 void *idx_map;
79 size_t idx_size;
80 int fd = git_open(path), ret;
81 struct stat st;
82 const unsigned int hashsz = p->repo->hash_algo->rawsz;
83
84 if (fd < 0)
85 return -1;
86 if (fstat(fd, &st)) {
87 close(fd);
88 return -1;
89 }
90 idx_size = xsize_t(st.st_size);
91 if (idx_size < 4 * 256 + hashsz + hashsz) {
92 close(fd);
93 return error("index file %s is too small", path);
94 }
95 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
96 close(fd);
97
98 ret = load_idx(path, hashsz, idx_map, idx_size, p);
99
100 if (ret)
101 munmap(idx_map, idx_size);
102
103 return ret;
104}
105
106int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
107 size_t idx_size, struct packed_git *p)
108{
109 struct pack_idx_header *hdr = idx_map;
110 uint32_t version, nr, i, *index;
111
112 if (idx_size < 4 * 256 + hashsz + hashsz)
113 return error("index file %s is too small", path);
114 if (!idx_map)
115 return error("empty data");
116
117 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
118 version = ntohl(hdr->idx_version);
119 if (version < 2 || version > 2)
120 return error("index file %s is version %"PRIu32
121 " and is not supported by this binary"
122 " (try upgrading GIT to a newer version)",
123 path, version);
124 } else
125 version = 1;
126
127 nr = 0;
128 index = idx_map;
129 if (version > 1)
130 index += 2; /* skip index header */
131 for (i = 0; i < 256; i++) {
132 uint32_t n = ntohl(index[i]);
133 if (n < nr)
134 return error("non-monotonic index %s", path);
135 nr = n;
136 }
137
138 if (version == 1) {
139 /*
140 * Total size:
141 * - 256 index entries 4 bytes each
142 * - 24-byte entries * nr (object ID + 4-byte offset)
143 * - hash of the packfile
144 * - file checksum
145 */
146 if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
147 return error("wrong index v1 file size in %s", path);
148 } else if (version == 2) {
149 /*
150 * Minimum size:
151 * - 8 bytes of header
152 * - 256 index entries 4 bytes each
153 * - object ID entry * nr
154 * - 4-byte crc entry * nr
155 * - 4-byte offset entry * nr
156 * - hash of the packfile
157 * - file checksum
158 * And after the 4-byte offset table might be a
159 * variable sized table containing 8-byte entries
160 * for offsets larger than 2^31.
161 */
162 size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
163 size_t max_size = min_size;
164 if (nr)
165 max_size = st_add(max_size, st_mult(nr - 1, 8));
166 if (idx_size < min_size || idx_size > max_size)
167 return error("wrong index v2 file size in %s", path);
168 if (idx_size != min_size &&
169 /*
170 * make sure we can deal with large pack offsets.
171 * 31-bit signed offset won't be enough, neither
172 * 32-bit unsigned one will be.
173 */
174 (sizeof(off_t) <= 4))
175 return error("pack too large for current definition of off_t in %s", path);
176 p->crc_offset = st_add(8 + 4 * 256, st_mult(nr, hashsz));
177 }
178
179 p->index_version = version;
180 p->index_data = idx_map;
181 p->index_size = idx_size;
182 p->num_objects = nr;
183 return 0;
184}
185
186int open_pack_index(struct packed_git *p)
187{
188 char *idx_name;
189 size_t len;
190 int ret;
191
192 if (p->index_data)
193 return 0;
194
195 if (!strip_suffix(p->pack_name, ".pack", &len))
196 BUG("pack_name does not end in .pack");
197 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
198 ret = check_packed_git_idx(idx_name, p);
199 free(idx_name);
200 return ret;
201}
202
203uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
204{
205 const uint32_t *level1_ofs = p->index_data;
206
207 if (!level1_ofs) {
208 if (open_pack_index(p))
209 return 0;
210 level1_ofs = p->index_data;
211 }
212
213 if (p->index_version > 1) {
214 level1_ofs += 2;
215 }
216
217 return ntohl(level1_ofs[value]);
218}
219
220static struct packed_git *alloc_packed_git(struct repository *r, int extra)
221{
222 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
223 memset(p, 0, sizeof(*p));
224 p->pack_fd = -1;
225 p->repo = r;
226 return p;
227}
228
229static char *pack_path_from_idx(const char *idx_path)
230{
231 size_t len;
232 if (!strip_suffix(idx_path, ".idx", &len))
233 BUG("idx path does not end in .idx: %s", idx_path);
234 return xstrfmt("%.*s.pack", (int)len, idx_path);
235}
236
237struct packed_git *parse_pack_index(struct repository *r, unsigned char *sha1,
238 const char *idx_path)
239{
240 char *path = pack_path_from_idx(idx_path);
241 size_t alloc = st_add(strlen(path), 1);
242 struct packed_git *p = alloc_packed_git(r, alloc);
243
244 memcpy(p->pack_name, path, alloc); /* includes NUL */
245 free(path);
246 hashcpy(p->hash, sha1, p->repo->hash_algo);
247 if (check_packed_git_idx(idx_path, p)) {
248 free(p);
249 return NULL;
250 }
251
252 return p;
253}
254
255static void scan_windows(struct packed_git *p,
256 struct packed_git **lru_p,
257 struct pack_window **lru_w,
258 struct pack_window **lru_l)
259{
260 struct pack_window *w, *w_l;
261
262 for (w_l = NULL, w = p->windows; w; w = w->next) {
263 if (!w->inuse_cnt) {
264 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
265 *lru_p = p;
266 *lru_w = w;
267 *lru_l = w_l;
268 }
269 }
270 w_l = w;
271 }
272}
273
274static int unuse_one_window(struct object_database *odb)
275{
276 struct odb_source_files *files = odb_source_files_downcast(odb->source);
277 struct packfile_list_entry *e;
278 struct packed_git *lru_p = NULL;
279 struct pack_window *lru_w = NULL, *lru_l = NULL;
280
281 for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
282 for (e = dir->packed->packs.head; e; e = e->next)
283 scan_windows(e->pack, &lru_p, &lru_w, &lru_l);
284 }
285
286 if (lru_p) {
287 munmap(lru_w->base, lru_w->len);
288 pack_mapped -= lru_w->len;
289 if (lru_l)
290 lru_l->next = lru_w->next;
291 else
292 lru_p->windows = lru_w->next;
293 free(lru_w);
294 pack_open_windows--;
295 return 1;
296 }
297 return 0;
298}
299
300void close_pack_windows(struct packed_git *p)
301{
302 while (p->windows) {
303 struct pack_window *w = p->windows;
304
305 if (w->inuse_cnt)
306 die("pack '%s' still has open windows to it",
307 p->pack_name);
308 munmap(w->base, w->len);
309 pack_mapped -= w->len;
310 pack_open_windows--;
311 p->windows = w->next;
312 free(w);
313 }
314}
315
316int close_pack_fd(struct packed_git *p)
317{
318 if (p->pack_fd < 0)
319 return 0;
320
321 close(p->pack_fd);
322 pack_open_fds--;
323 p->pack_fd = -1;
324
325 return 1;
326}
327
328void close_pack_index(struct packed_git *p)
329{
330 if (p->index_data) {
331 munmap((void *)p->index_data, p->index_size);
332 p->index_data = NULL;
333 }
334}
335
336static void close_pack_revindex(struct packed_git *p)
337{
338 FREE_AND_NULL(p->revindex);
339
340 if (!p->revindex_map)
341 return;
342
343 munmap((void *)p->revindex_map, p->revindex_size);
344 p->revindex_map = NULL;
345 p->revindex_data = NULL;
346}
347
348static void close_pack_mtimes(struct packed_git *p)
349{
350 if (!p->mtimes_map)
351 return;
352
353 munmap((void *)p->mtimes_map, p->mtimes_size);
354 p->mtimes_map = NULL;
355}
356
357void unlink_pack_path(const char *pack_name, int force_delete)
358{
359 static const char *exts[] = {".idx", ".pack", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
360 int i;
361 struct strbuf buf = STRBUF_INIT;
362 size_t plen;
363
364 strbuf_addstr(&buf, pack_name);
365 strip_suffix_mem(buf.buf, &buf.len, ".pack");
366 plen = buf.len;
367
368 if (!force_delete) {
369 strbuf_addstr(&buf, ".keep");
370 if (!access(buf.buf, F_OK)) {
371 strbuf_release(&buf);
372 return;
373 }
374 }
375
376 for (i = 0; i < ARRAY_SIZE(exts); i++) {
377 strbuf_setlen(&buf, plen);
378 strbuf_addstr(&buf, exts[i]);
379 unlink(buf.buf);
380 }
381
382 strbuf_release(&buf);
383}
384
385/*
386 * The LRU pack is the one with the oldest MRU window, preferring packs
387 * with no used windows, or the oldest mtime if it has no windows allocated.
388 */
389static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
390{
391 struct pack_window *w, *this_mru_w;
392 int has_windows_inuse = 0;
393
394 /*
395 * Reject this pack if it has windows and the previously selected
396 * one does not. If this pack does not have windows, reject
397 * it if the pack file is newer than the previously selected one.
398 */
399 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
400 return;
401
402 for (w = this_mru_w = p->windows; w; w = w->next) {
403 /*
404 * Reject this pack if any of its windows are in use,
405 * but the previously selected pack did not have any
406 * inuse windows. Otherwise, record that this pack
407 * has windows in use.
408 */
409 if (w->inuse_cnt) {
410 if (*accept_windows_inuse)
411 has_windows_inuse = 1;
412 else
413 return;
414 }
415
416 if (w->last_used > this_mru_w->last_used)
417 this_mru_w = w;
418
419 /*
420 * Reject this pack if it has windows that have been
421 * used more recently than the previously selected pack.
422 * If the previously selected pack had windows inuse and
423 * we have not encountered a window in this pack that is
424 * inuse, skip this check since we prefer a pack with no
425 * inuse windows to one that has inuse windows.
426 */
427 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
428 this_mru_w->last_used > (*mru_w)->last_used)
429 return;
430 }
431
432 /*
433 * Select this pack.
434 */
435 *mru_w = this_mru_w;
436 *lru_p = p;
437 *accept_windows_inuse = has_windows_inuse;
438}
439
440static int close_one_pack(struct repository *r)
441{
442 struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
443 struct packfile_list_entry *e;
444 struct packed_git *lru_p = NULL;
445 struct pack_window *mru_w = NULL;
446 int accept_windows_inuse = 1;
447
448 for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
449 for (e = dir->packed->packs.head; e; e = e->next) {
450 if (e->pack->pack_fd == -1)
451 continue;
452 find_lru_pack(e->pack, &lru_p, &mru_w, &accept_windows_inuse);
453 }
454 }
455
456 if (lru_p)
457 return close_pack_fd(lru_p);
458
459 return 0;
460}
461
462static unsigned int get_max_fd_limit(void)
463{
464#ifdef RLIMIT_NOFILE
465 {
466 struct rlimit lim;
467
468 if (!getrlimit(RLIMIT_NOFILE, &lim))
469 return lim.rlim_cur;
470 }
471#endif
472
473#ifdef _SC_OPEN_MAX
474 {
475 long open_max = sysconf(_SC_OPEN_MAX);
476 if (0 < open_max)
477 return open_max;
478 /*
479 * Otherwise, we got -1 for one of the two
480 * reasons:
481 *
482 * (1) sysconf() did not understand _SC_OPEN_MAX
483 * and signaled an error with -1; or
484 * (2) sysconf() said there is no limit.
485 *
486 * We _could_ clear errno before calling sysconf() to
487 * tell these two cases apart and return a huge number
488 * in the latter case to let the caller cap it to a
489 * value that is not so selfish, but letting the
490 * fallback OPEN_MAX codepath take care of these cases
491 * is a lot simpler.
492 */
493 }
494#endif
495
496#ifdef OPEN_MAX
497 return OPEN_MAX;
498#else
499 return 1; /* see the caller ;-) */
500#endif
501}
502
503const char *pack_basename(struct packed_git *p)
504{
505 const char *ret = strrchr(p->pack_name, '/');
506 if (ret)
507 ret = ret + 1; /* skip past slash */
508 else
509 ret = p->pack_name; /* we only have a base */
510 return ret;
511}
512
513/*
514 * Do not call this directly as this leaks p->pack_fd on error return;
515 * call open_packed_git() instead.
516 */
517static int open_packed_git_1(struct packed_git *p)
518{
519 struct stat st;
520 struct pack_header hdr;
521 unsigned char hash[GIT_MAX_RAWSZ];
522 unsigned char *idx_hash;
523 ssize_t read_result;
524 const unsigned hashsz = p->repo->hash_algo->rawsz;
525
526 if (open_pack_index(p))
527 return error("packfile %s index unavailable", p->pack_name);
528
529 if (!pack_max_fds) {
530 unsigned int max_fds = get_max_fd_limit();
531
532 /* Save 3 for stdin/stdout/stderr, 22 for work */
533 if (25 < max_fds)
534 pack_max_fds = max_fds - 25;
535 else
536 pack_max_fds = 1;
537 }
538
539 while (pack_max_fds <= pack_open_fds && close_one_pack(p->repo))
540 ; /* nothing */
541
542 p->pack_fd = git_open(p->pack_name);
543 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
544 return -1;
545 pack_open_fds++;
546
547 /* If we created the struct before we had the pack we lack size. */
548 if (!p->pack_size) {
549 if (!S_ISREG(st.st_mode))
550 return error("packfile %s not a regular file", p->pack_name);
551 p->pack_size = st.st_size;
552 } else if (p->pack_size != st.st_size)
553 return error("packfile %s size changed", p->pack_name);
554
555 /* Verify we recognize this pack file format. */
556 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
557 if (read_result < 0)
558 return error_errno("error reading from %s", p->pack_name);
559 if (read_result != sizeof(hdr))
560 return error("file %s is far too short to be a packfile", p->pack_name);
561 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
562 return error("file %s is not a GIT packfile", p->pack_name);
563 if (!pack_version_ok(hdr.hdr_version))
564 return error("packfile %s is version %"PRIu32" and not"
565 " supported (try upgrading GIT to a newer version)",
566 p->pack_name, ntohl(hdr.hdr_version));
567
568 /* Verify the pack matches its index. */
569 if (p->num_objects != ntohl(hdr.hdr_entries))
570 return error("packfile %s claims to have %"PRIu32" objects"
571 " while index indicates %"PRIu32" objects",
572 p->pack_name, ntohl(hdr.hdr_entries),
573 p->num_objects);
574 read_result = pread_in_full(p->pack_fd, hash, hashsz,
575 p->pack_size - hashsz);
576 if (read_result < 0)
577 return error_errno("error reading from %s", p->pack_name);
578 if (read_result != hashsz)
579 return error("packfile %s signature is unavailable", p->pack_name);
580 idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
581 if (!hasheq(hash, idx_hash, p->repo->hash_algo))
582 return error("packfile %s does not match index", p->pack_name);
583 return 0;
584}
585
586static int open_packed_git(struct packed_git *p)
587{
588 if (!open_packed_git_1(p))
589 return 0;
590 close_pack_fd(p);
591 return -1;
592}
593
594static int in_window(struct repository *r, struct pack_window *win,
595 off_t offset)
596{
597 /* We must promise at least one full hash after the
598 * offset is available from this window, otherwise the offset
599 * is not actually in this window and a different window (which
600 * has that one hash excess) must be used. This is to support
601 * the object header and delta base parsing routines below.
602 */
603 off_t win_off = win->offset;
604 return win_off <= offset
605 && (offset + r->hash_algo->rawsz) <= (win_off + win->len);
606}
607
608unsigned char *use_pack(struct packed_git *p,
609 struct pack_window **w_cursor,
610 off_t offset,
611 size_t *left)
612{
613 struct pack_window *win = *w_cursor;
614
615 /* Since packfiles end in a hash of their content and it's
616 * pointless to ask for an offset into the middle of that
617 * hash, and the in_window function above wouldn't match
618 * don't allow an offset too close to the end of the file.
619 */
620 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
621 die("packfile %s cannot be accessed", p->pack_name);
622 if (offset > (p->pack_size - p->repo->hash_algo->rawsz))
623 die("offset beyond end of packfile (truncated pack?)");
624 if (offset < 0)
625 die(_("offset before end of packfile (broken .idx?)"));
626
627 if (!win || !in_window(p->repo, win, offset)) {
628 if (win)
629 win->inuse_cnt--;
630 for (win = p->windows; win; win = win->next) {
631 if (in_window(p->repo, win, offset))
632 break;
633 }
634 if (!win) {
635 size_t window_align;
636 off_t len;
637 struct repo_settings *settings;
638
639 /* lazy load the settings in case it hasn't been setup */
640 prepare_repo_settings(p->repo);
641 settings = &p->repo->settings;
642
643 window_align = settings->packed_git_window_size / 2;
644
645 if (p->pack_fd == -1 && open_packed_git(p))
646 die("packfile %s cannot be accessed", p->pack_name);
647
648 CALLOC_ARRAY(win, 1);
649 win->offset = (offset / window_align) * window_align;
650 len = p->pack_size - win->offset;
651 if (len > settings->packed_git_window_size)
652 len = settings->packed_git_window_size;
653 win->len = (size_t)len;
654 pack_mapped += win->len;
655
656 while (settings->packed_git_limit < pack_mapped &&
657 unuse_one_window(p->repo->objects))
658 ; /* nothing */
659 win->base = xmmap_gently(NULL, win->len,
660 PROT_READ, MAP_PRIVATE,
661 p->pack_fd, win->offset);
662 if (win->base == MAP_FAILED)
663 die_errno(_("packfile %s cannot be mapped%s"),
664 p->pack_name, mmap_os_err());
665 if (!win->offset && win->len == p->pack_size
666 && !p->do_not_close)
667 close_pack_fd(p);
668 pack_mmap_calls++;
669 pack_open_windows++;
670 if (pack_mapped > peak_pack_mapped)
671 peak_pack_mapped = pack_mapped;
672 if (pack_open_windows > peak_pack_open_windows)
673 peak_pack_open_windows = pack_open_windows;
674 win->next = p->windows;
675 p->windows = win;
676 }
677 }
678 if (win != *w_cursor) {
679 win->last_used = pack_used_ctr++;
680 win->inuse_cnt++;
681 *w_cursor = win;
682 }
683 offset -= win->offset;
684 if (left)
685 *left = win->len - xsize_t(offset);
686 return win->base + offset;
687}
688
689void unuse_pack(struct pack_window **w_cursor)
690{
691 struct pack_window *w = *w_cursor;
692 if (w) {
693 w->inuse_cnt--;
694 *w_cursor = NULL;
695 }
696}
697
698struct packed_git *add_packed_git(struct repository *r, const char *path,
699 size_t path_len, int local)
700{
701 struct stat st;
702 size_t alloc;
703 struct packed_git *p;
704 struct object_id oid;
705
706 /*
707 * Make sure a corresponding .pack file exists and that
708 * the index looks sane.
709 */
710 if (!strip_suffix_mem(path, &path_len, ".idx"))
711 return NULL;
712
713 /*
714 * ".promisor" is long enough to hold any suffix we're adding (and
715 * the use xsnprintf double-checks that)
716 */
717 alloc = st_add3(path_len, strlen(".promisor"), 1);
718 p = alloc_packed_git(r, alloc);
719 memcpy(p->pack_name, path, path_len);
720
721 /*
722 * Note that we have to check auxiliary data structures before we check
723 * for the ".pack" file to exist to avoid races with a packfile that is
724 * in the process of being deleted. The ".pack" file is unlinked before
725 * its auxiliary data structures, so we know that we either get a
726 * consistent snapshot of all data structures or that we'll fail to
727 * stat(3p) the packfile itself and thus return `NULL`.
728 *
729 * As such, we cannot bail out before the access(3p) calls in case the
730 * packfile doesn't exist without doing two stat(3p) calls for it.
731 */
732 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
733 if (!access(p->pack_name, F_OK))
734 p->pack_keep = 1;
735
736 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
737 if (!access(p->pack_name, F_OK))
738 p->pack_promisor = 1;
739
740 xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
741 if (!access(p->pack_name, F_OK))
742 p->is_cruft = 1;
743
744 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
745 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
746 free(p);
747 return NULL;
748 }
749
750 /* ok, it looks sane as far as we can check without
751 * actually mapping the pack file.
752 */
753 p->pack_size = st.st_size;
754 p->pack_local = local;
755 p->mtime = st.st_mtime;
756 if (path_len < r->hash_algo->hexsz ||
757 get_oid_hex_algop(path + path_len - r->hash_algo->hexsz, &oid,
758 r->hash_algo))
759 hashclr(p->hash, r->hash_algo);
760 else
761 hashcpy(p->hash, oid.hash, r->hash_algo);
762
763 return p;
764}
765
766void packfile_store_add_pack(struct odb_source_packed *store,
767 struct packed_git *pack)
768{
769 if (pack->pack_fd != -1)
770 pack_open_fds++;
771
772 packfile_list_append(&store->packs, pack, 1);
773 strmap_put(&store->packs_by_path, pack->pack_name, pack);
774}
775
776struct packed_git *packfile_store_load_pack(struct odb_source_packed *store,
777 const char *idx_path, int local)
778{
779 struct strbuf key = STRBUF_INIT;
780 struct packed_git *p;
781
782 /*
783 * We're being called with the path to the index file, but `pack_map`
784 * holds the path to the packfile itself.
785 */
786 strbuf_addstr(&key, idx_path);
787 strbuf_strip_suffix(&key, ".idx");
788 strbuf_addstr(&key, ".pack");
789
790 p = strmap_get(&store->packs_by_path, key.buf);
791 if (!p) {
792 p = add_packed_git(store->base.odb->repo, idx_path,
793 strlen(idx_path), local);
794 if (p)
795 packfile_store_add_pack(store, p);
796 }
797
798 strbuf_release(&key);
799 return p;
800}
801
802void for_each_file_in_pack_subdir(const char *objdir,
803 const char *subdir,
804 each_file_in_pack_dir_fn fn,
805 void *data)
806{
807 struct strbuf path = STRBUF_INIT;
808 size_t dirnamelen;
809 DIR *dir;
810 struct dirent *de;
811
812 strbuf_addstr(&path, objdir);
813 strbuf_addstr(&path, "/pack");
814 if (subdir)
815 strbuf_addf(&path, "/%s", subdir);
816 dir = opendir(path.buf);
817 if (!dir) {
818 if (errno != ENOENT)
819 error_errno("unable to open object pack directory: %s",
820 path.buf);
821 strbuf_release(&path);
822 return;
823 }
824 strbuf_addch(&path, '/');
825 dirnamelen = path.len;
826 while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
827 strbuf_setlen(&path, dirnamelen);
828 strbuf_addstr(&path, de->d_name);
829
830 fn(path.buf, path.len, de->d_name, data);
831 }
832
833 closedir(dir);
834 strbuf_release(&path);
835}
836
837void for_each_file_in_pack_dir(const char *objdir,
838 each_file_in_pack_dir_fn fn,
839 void *data)
840{
841 for_each_file_in_pack_subdir(objdir, NULL, fn, data);
842}
843
844struct packfile_list_entry *packfile_store_get_packs(struct odb_source_packed *store)
845{
846 odb_source_prepare(&store->base, 0);
847
848 if (store->midx) {
849 struct multi_pack_index *m = store->midx;
850 for (uint32_t i = 0; i < m->num_packs + m->num_packs_in_base; i++)
851 prepare_midx_pack(m, i);
852 }
853
854 return store->packs.head;
855}
856
857size_t unpack_object_header_buffer(const unsigned char *buf, size_t len,
858 enum object_type *type, size_t *sizep)
859{
860 unsigned shift;
861 size_t size, c, used = 0;
862
863 c = buf[used++];
864 *type = (c >> 4) & 7;
865 size = c & 15;
866 shift = 4;
867 while (c & 0x80) {
868 /*
869 * Each continuation byte adds 7 bits. Ensure shift won't
870 * overflow size_t (use size_t not long for 64-bit on Windows).
871 */
872 if (len <= used || (bitsizeof(size_t) - 7) < shift) {
873 error("bad object header");
874 size = used = 0;
875 break;
876 }
877 c = buf[used++];
878 size = st_add(size, st_left_shift(c & 0x7f, shift));
879 shift += 7;
880 }
881 *sizep = size;
882 return used;
883}
884
885/*
886 * Read a delta object's header at curpos in p (already inflated as needed)
887 * and return the size of the result object (the post-application target).
888 */
889size_t get_size_from_delta(struct packed_git *p,
890 struct pack_window **w_curs,
891 off_t curpos)
892{
893 const unsigned char *data;
894 unsigned char delta_head[20], *in;
895 git_zstream stream;
896 int st;
897
898 memset(&stream, 0, sizeof(stream));
899 stream.next_out = delta_head;
900 stream.avail_out = sizeof(delta_head);
901
902 git_inflate_init(&stream);
903 do {
904 in = use_pack(p, w_curs, curpos, &stream.avail_in);
905 stream.next_in = in;
906 /*
907 * Note: the window section returned by use_pack() must be
908 * available throughout git_inflate()'s unlocked execution. To
909 * ensure no other thread will modify the window in the
910 * meantime, we rely on the packed_window.inuse_cnt. This
911 * counter is incremented before window reading and checked
912 * before window disposal.
913 *
914 * Other worrying sections could be the call to close_pack_fd(),
915 * which can close packs even with in-use windows, and to
916 * odb_reprepare(). Regarding the former, mmap doc says:
917 * "closing the file descriptor does not unmap the region". And
918 * for the latter, it won't re-open already available packs.
919 */
920 obj_read_unlock();
921 st = git_inflate(&stream, Z_FINISH);
922 obj_read_lock();
923 curpos += stream.next_in - in;
924 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
925 stream.total_out < sizeof(delta_head));
926 git_inflate_end(&stream);
927 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
928 error("delta data unpack-initial failed");
929 return 0;
930 }
931
932 /* Examine the initial part of the delta to figure out
933 * the result size.
934 */
935 data = delta_head;
936
937 /* ignore base size */
938 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
939
940 /* Read the result size */
941 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
942}
943
944int unpack_object_header(struct packed_git *p,
945 struct pack_window **w_curs,
946 off_t *curpos,
947 size_t *sizep)
948{
949 unsigned char *base;
950 size_t left, used;
951 enum object_type type;
952
953 /* use_pack() assures us we have [base, base + 20) available
954 * as a range that we can look at. (Its actually the hash
955 * size that is assured.) With our object header encoding
956 * the maximum deflated object size is 2^137, which is just
957 * insane, so we know won't exceed what we have been given.
958 */
959 base = use_pack(p, w_curs, *curpos, &left);
960 used = unpack_object_header_buffer(base, left, &type, sizep);
961 if (!used) {
962 type = OBJ_BAD;
963 } else
964 *curpos += used;
965
966 return type;
967}
968
969void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
970{
971 oidset_insert(&p->bad_objects, oid);
972}
973
974off_t get_delta_base(struct packed_git *p,
975 struct pack_window **w_curs,
976 off_t *curpos,
977 enum object_type type,
978 off_t delta_obj_offset)
979{
980 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
981 off_t base_offset;
982
983 /* use_pack() assured us we have [base_info, base_info + 20)
984 * as a range that we can look at without walking off the
985 * end of the mapped window. Its actually the hash size
986 * that is assured. An OFS_DELTA longer than the hash size
987 * is stupid, as then a REF_DELTA would be smaller to store.
988 */
989 if (type == OBJ_OFS_DELTA) {
990 unsigned used = 0;
991 unsigned char c = base_info[used++];
992 base_offset = c & 127;
993 while (c & 128) {
994 base_offset += 1;
995 if (!base_offset || MSB(base_offset, 7))
996 return 0; /* overflow */
997 c = base_info[used++];
998 base_offset = (base_offset << 7) + (c & 127);
999 }
1000 base_offset = delta_obj_offset - base_offset;
1001 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1002 return 0; /* out of bound */
1003 *curpos += used;
1004 } else if (type == OBJ_REF_DELTA) {
1005 /* The base entry _must_ be in the same pack */
1006 struct object_id oid;
1007 oidread(&oid, base_info, p->repo->hash_algo);
1008 base_offset = find_pack_entry_one(&oid, p);
1009 *curpos += p->repo->hash_algo->rawsz;
1010 } else
1011 die("I am totally screwed");
1012 return base_offset;
1013}
1014
1015/*
1016 * Like get_delta_base above, but we return the sha1 instead of the pack
1017 * offset. This means it is cheaper for REF deltas (we do not have to do
1018 * the final object lookup), but more expensive for OFS deltas (we
1019 * have to load the revidx to convert the offset back into a sha1).
1020 */
1021static int get_delta_base_oid(struct packed_git *p,
1022 struct pack_window **w_curs,
1023 off_t curpos,
1024 struct object_id *oid,
1025 enum object_type type,
1026 off_t delta_obj_offset)
1027{
1028 if (type == OBJ_REF_DELTA) {
1029 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1030 oidread(oid, base, p->repo->hash_algo);
1031 return 0;
1032 } else if (type == OBJ_OFS_DELTA) {
1033 uint32_t base_pos;
1034 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1035 type, delta_obj_offset);
1036
1037 if (!base_offset)
1038 return -1;
1039
1040 if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1041 return -1;
1042
1043 return nth_packed_object_id(oid, p,
1044 pack_pos_to_index(p, base_pos));
1045 } else
1046 return -1;
1047}
1048
1049static int retry_bad_packed_offset(struct repository *r,
1050 struct packed_git *p,
1051 off_t obj_offset)
1052{
1053 int type;
1054 uint32_t pos;
1055 struct object_id oid;
1056 if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1057 return OBJ_BAD;
1058 nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1059 mark_bad_packed_object(p, &oid);
1060 type = odb_read_object_info(r->objects, &oid, NULL);
1061 if (type <= OBJ_NONE)
1062 return OBJ_BAD;
1063 return type;
1064}
1065
1066#define POI_STACK_PREALLOC 64
1067
1068static enum object_type packed_to_object_type(struct repository *r,
1069 struct packed_git *p,
1070 off_t obj_offset,
1071 enum object_type type,
1072 struct pack_window **w_curs,
1073 off_t curpos)
1074{
1075 off_t small_poi_stack[POI_STACK_PREALLOC];
1076 off_t *poi_stack = small_poi_stack;
1077 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1078
1079 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1080 off_t base_offset;
1081 size_t size;
1082 /* Push the object we're going to leave behind */
1083 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1084 poi_stack_alloc = alloc_nr(poi_stack_nr);
1085 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1086 COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1087 } else {
1088 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1089 }
1090 poi_stack[poi_stack_nr++] = obj_offset;
1091 /* If parsing the base offset fails, just unwind */
1092 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1093 if (!base_offset)
1094 goto unwind;
1095 curpos = obj_offset = base_offset;
1096 type = unpack_object_header(p, w_curs, &curpos, &size);
1097 if (type <= OBJ_NONE) {
1098 /* If getting the base itself fails, we first
1099 * retry the base, otherwise unwind */
1100 type = retry_bad_packed_offset(r, p, base_offset);
1101 if (type > OBJ_NONE)
1102 goto out;
1103 goto unwind;
1104 }
1105 }
1106
1107 switch (type) {
1108 case OBJ_BAD:
1109 case OBJ_COMMIT:
1110 case OBJ_TREE:
1111 case OBJ_BLOB:
1112 case OBJ_TAG:
1113 break;
1114 default:
1115 error("unknown object type %i at offset %"PRIuMAX" in %s",
1116 type, (uintmax_t)obj_offset, p->pack_name);
1117 type = OBJ_BAD;
1118 }
1119
1120out:
1121 if (poi_stack != small_poi_stack)
1122 free(poi_stack);
1123 return type;
1124
1125unwind:
1126 while (poi_stack_nr) {
1127 obj_offset = poi_stack[--poi_stack_nr];
1128 type = retry_bad_packed_offset(r, p, obj_offset);
1129 if (type > OBJ_NONE)
1130 goto out;
1131 }
1132 type = OBJ_BAD;
1133 goto out;
1134}
1135
1136static struct hashmap delta_base_cache;
1137static size_t delta_base_cached;
1138
1139static LIST_HEAD(delta_base_cache_lru);
1140
1141struct delta_base_cache_key {
1142 struct packed_git *p;
1143 off_t base_offset;
1144};
1145
1146struct delta_base_cache_entry {
1147 struct hashmap_entry ent;
1148 struct delta_base_cache_key key;
1149 struct list_head lru;
1150 void *data;
1151 size_t size;
1152 enum object_type type;
1153};
1154
1155static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1156{
1157 unsigned int hash;
1158
1159 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1160 hash += (hash >> 8) + (hash >> 16);
1161 return hash;
1162}
1163
1164static struct delta_base_cache_entry *
1165get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1166{
1167 struct hashmap_entry entry, *e;
1168 struct delta_base_cache_key key;
1169
1170 if (!delta_base_cache.cmpfn)
1171 return NULL;
1172
1173 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1174 key.p = p;
1175 key.base_offset = base_offset;
1176 e = hashmap_get(&delta_base_cache, &entry, &key);
1177 return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1178}
1179
1180static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1181 const struct delta_base_cache_key *b)
1182{
1183 return a->p == b->p && a->base_offset == b->base_offset;
1184}
1185
1186static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1187 const struct hashmap_entry *va,
1188 const struct hashmap_entry *vb,
1189 const void *vkey)
1190{
1191 const struct delta_base_cache_entry *a, *b;
1192 const struct delta_base_cache_key *key = vkey;
1193
1194 a = container_of(va, const struct delta_base_cache_entry, ent);
1195 b = container_of(vb, const struct delta_base_cache_entry, ent);
1196
1197 if (key)
1198 return !delta_base_cache_key_eq(&a->key, key);
1199 else
1200 return !delta_base_cache_key_eq(&a->key, &b->key);
1201}
1202
1203static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1204{
1205 return !!get_delta_base_cache_entry(p, base_offset);
1206}
1207
1208/*
1209 * Remove the entry from the cache, but do _not_ free the associated
1210 * entry data. The caller takes ownership of the "data" buffer, and
1211 * should copy out any fields it wants before detaching.
1212 */
1213static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1214{
1215 hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1216 list_del(&ent->lru);
1217 delta_base_cached -= ent->size;
1218 free(ent);
1219}
1220
1221static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1222 off_t base_offset, size_t *base_size,
1223 enum object_type *type)
1224{
1225 struct delta_base_cache_entry *ent;
1226
1227 ent = get_delta_base_cache_entry(p, base_offset);
1228 if (!ent)
1229 return unpack_entry(r, p, base_offset, type, base_size);
1230
1231 if (type)
1232 *type = ent->type;
1233 if (base_size)
1234 *base_size = ent->size;
1235 return xmemdupz(ent->data, ent->size);
1236}
1237
1238static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1239{
1240 free(ent->data);
1241 detach_delta_base_cache_entry(ent);
1242}
1243
1244void clear_delta_base_cache(void)
1245{
1246 struct list_head *lru, *tmp;
1247 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1248 struct delta_base_cache_entry *entry =
1249 list_entry(lru, struct delta_base_cache_entry, lru);
1250 release_delta_base_cache(entry);
1251 }
1252}
1253
1254static void delta_base_cache_evict_entry(struct packed_git *p)
1255{
1256 struct list_head *lru, *tmp;
1257
1258 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1259 struct delta_base_cache_entry *entry =
1260 list_entry(lru, struct delta_base_cache_entry, lru);
1261 if (entry->key.p == p)
1262 release_delta_base_cache(entry);
1263 }
1264}
1265
1266void close_pack(struct packed_git *p)
1267{
1268 close_pack_windows(p);
1269 close_pack_fd(p);
1270 close_pack_index(p);
1271 close_pack_revindex(p);
1272 close_pack_mtimes(p);
1273 oidset_clear(&p->bad_objects);
1274 delta_base_cache_evict_entry(p);
1275}
1276
1277static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1278 void *base, size_t base_size,
1279 size_t delta_base_cache_limit,
1280 enum object_type type)
1281{
1282 struct delta_base_cache_entry *ent;
1283 struct list_head *lru, *tmp;
1284
1285 /*
1286 * Check required to avoid redundant entries when more than one thread
1287 * is unpacking the same object, in unpack_entry() (since its phases I
1288 * and III might run concurrently across multiple threads).
1289 */
1290 if (in_delta_base_cache(p, base_offset)) {
1291 free(base);
1292 return;
1293 }
1294
1295 delta_base_cached += base_size;
1296
1297 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1298 struct delta_base_cache_entry *f =
1299 list_entry(lru, struct delta_base_cache_entry, lru);
1300 if (delta_base_cached <= delta_base_cache_limit)
1301 break;
1302 release_delta_base_cache(f);
1303 }
1304
1305 ent = xmalloc(sizeof(*ent));
1306 ent->key.p = p;
1307 ent->key.base_offset = base_offset;
1308 ent->type = type;
1309 ent->data = base;
1310 ent->size = base_size;
1311 list_add_tail(&ent->lru, &delta_base_cache_lru);
1312
1313 if (!delta_base_cache.cmpfn)
1314 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1315 hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1316 hashmap_add(&delta_base_cache, &ent->ent);
1317}
1318
1319int packed_object_info_with_index_pos(struct odb_source_packed *source,
1320 struct packed_git *p, off_t obj_offset,
1321 uint32_t *maybe_index_pos, struct object_info *oi)
1322{
1323 struct pack_window *w_curs = NULL;
1324 size_t size;
1325 off_t curpos = obj_offset;
1326 enum object_type type = OBJ_NONE;
1327 uint32_t pack_pos;
1328 int ret;
1329
1330 /*
1331 * We always get the representation type, but only convert it to
1332 * a "real" type later if the caller is interested.
1333 */
1334 if (oi->contentp) {
1335 *oi->contentp = cache_or_unpack_entry(p->repo, p, obj_offset,
1336 oi->sizep, &type);
1337 if (!*oi->contentp)
1338 type = OBJ_BAD;
1339 } else if (oi->sizep || oi->typep || oi->delta_base_oid) {
1340 type = unpack_object_header(p, &w_curs, &curpos, &size);
1341 }
1342
1343 if (!oi->contentp && oi->sizep) {
1344 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1345 off_t tmp_pos = curpos;
1346 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1347 type, obj_offset);
1348 if (!base_offset) {
1349 ret = -1;
1350 goto out;
1351 }
1352 size = get_size_from_delta(p, &w_curs, tmp_pos);
1353 if (size == 0) {
1354 ret = -1;
1355 goto out;
1356 }
1357 }
1358 *oi->sizep = size;
1359 }
1360
1361 if (oi->disk_sizep || (oi->mtimep && p->is_cruft)) {
1362 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1363 error("could not find object at offset %"PRIuMAX" "
1364 "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1365 ret = -1;
1366 goto out;
1367 }
1368 }
1369
1370 if (oi->disk_sizep)
1371 *oi->disk_sizep = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1372
1373 if (oi->mtimep) {
1374 if (p->is_cruft) {
1375 uint32_t index_pos;
1376
1377 if (load_pack_mtimes(p) < 0)
1378 die(_("could not load .mtimes for cruft pack '%s'"),
1379 pack_basename(p));
1380
1381 if (maybe_index_pos)
1382 index_pos = *maybe_index_pos;
1383 else
1384 index_pos = pack_pos_to_index(p, pack_pos);
1385
1386 *oi->mtimep = nth_packed_mtime(p, index_pos);
1387 } else {
1388 *oi->mtimep = p->mtime;
1389 }
1390 }
1391
1392 if (oi->typep) {
1393 enum object_type ptot;
1394 ptot = packed_to_object_type(p->repo, p, obj_offset,
1395 type, &w_curs, curpos);
1396 if (oi->typep)
1397 *oi->typep = ptot;
1398 if (ptot < 0) {
1399 ret = -1;
1400 goto out;
1401 }
1402 }
1403
1404 if (oi->delta_base_oid) {
1405 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1406 if (get_delta_base_oid(p, &w_curs, curpos,
1407 oi->delta_base_oid,
1408 type, obj_offset) < 0) {
1409 ret = -1;
1410 goto out;
1411 }
1412 } else
1413 oidclr(oi->delta_base_oid, p->repo->hash_algo);
1414 }
1415
1416 if (oi->source_infop) {
1417 if (!source)
1418 BUG("cannot request source without an owning source");
1419 oi->source_infop->source = &source->base;
1420
1421 oi->source_infop->u.packed.offset = obj_offset;
1422 oi->source_infop->u.packed.pack = p;
1423
1424 switch (type) {
1425 case OBJ_NONE:
1426 oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_UNKNOWN;
1427 break;
1428 case OBJ_REF_DELTA:
1429 oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_REF_DELTA;
1430 break;
1431 case OBJ_OFS_DELTA:
1432 oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_OFS_DELTA;
1433 break;
1434 default:
1435 oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_FULL;
1436 break;
1437 }
1438 }
1439
1440 ret = 0;
1441
1442out:
1443 unuse_pack(&w_curs);
1444 return ret;
1445}
1446
1447int packed_object_info(struct odb_source_packed *source,
1448 struct packed_git *p, off_t obj_offset,
1449 struct object_info *oi)
1450{
1451 return packed_object_info_with_index_pos(source, p, obj_offset, NULL, oi);
1452}
1453
1454static void *unpack_compressed_entry(struct packed_git *p,
1455 struct pack_window **w_curs,
1456 off_t curpos,
1457 size_t size)
1458{
1459 int st;
1460 git_zstream stream;
1461 unsigned char *buffer, *in;
1462
1463 buffer = xmallocz_gently(size);
1464 if (!buffer)
1465 return NULL;
1466 memset(&stream, 0, sizeof(stream));
1467 stream.next_out = buffer;
1468 stream.avail_out = size + 1;
1469
1470 git_inflate_init(&stream);
1471 do {
1472 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1473 stream.next_in = in;
1474 /*
1475 * Note: we must ensure the window section returned by
1476 * use_pack() will be available throughout git_inflate()'s
1477 * unlocked execution. Please refer to the comment at
1478 * get_size_from_delta() to see how this is done.
1479 */
1480 obj_read_unlock();
1481 st = git_inflate(&stream, Z_FINISH);
1482 obj_read_lock();
1483 if (!stream.avail_out)
1484 break; /* the payload is larger than it should be */
1485 curpos += stream.next_in - in;
1486 } while (st == Z_OK || st == Z_BUF_ERROR);
1487 git_inflate_end(&stream);
1488 if ((st != Z_STREAM_END) || stream.total_out != size) {
1489 free(buffer);
1490 return NULL;
1491 }
1492
1493 /* versions of zlib can clobber unconsumed portion of outbuf */
1494 buffer[size] = '\0';
1495
1496 return buffer;
1497}
1498
1499static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1500{
1501 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1502 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1503 p->pack_name, (uintmax_t)obj_offset);
1504}
1505
1506int do_check_packed_object_crc;
1507
1508#define UNPACK_ENTRY_STACK_PREALLOC 64
1509struct unpack_entry_stack_ent {
1510 off_t obj_offset;
1511 off_t curpos;
1512 size_t size;
1513};
1514
1515void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1516 enum object_type *final_type, size_t *final_size)
1517{
1518 struct pack_window *w_curs = NULL;
1519 off_t curpos = obj_offset;
1520 void *data = NULL;
1521 size_t size;
1522 enum object_type type;
1523 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1524 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1525 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1526 int base_from_cache = 0;
1527
1528 prepare_repo_settings(p->repo);
1529
1530 write_pack_access_log(p, obj_offset);
1531
1532 /* PHASE 1: drill down to the innermost base object */
1533 for (;;) {
1534 off_t base_offset;
1535 int i;
1536 struct delta_base_cache_entry *ent;
1537
1538 ent = get_delta_base_cache_entry(p, curpos);
1539 if (ent) {
1540 type = ent->type;
1541 data = ent->data;
1542 size = ent->size;
1543 detach_delta_base_cache_entry(ent);
1544 base_from_cache = 1;
1545 break;
1546 }
1547
1548 if (do_check_packed_object_crc && p->index_version > 1) {
1549 uint32_t pack_pos, index_pos;
1550 off_t len;
1551
1552 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1553 error("could not find object at offset %"PRIuMAX" in pack %s",
1554 (uintmax_t)obj_offset, p->pack_name);
1555 data = NULL;
1556 goto out;
1557 }
1558
1559 len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1560 index_pos = pack_pos_to_index(p, pack_pos);
1561 if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1562 struct object_id oid;
1563 nth_packed_object_id(&oid, p, index_pos);
1564 error("bad packed object CRC for %s",
1565 oid_to_hex(&oid));
1566 mark_bad_packed_object(p, &oid);
1567 data = NULL;
1568 goto out;
1569 }
1570 }
1571
1572 type = unpack_object_header(p, &w_curs, &curpos, &size);
1573 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1574 break;
1575
1576 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1577 if (!base_offset) {
1578 error("failed to validate delta base reference "
1579 "at offset %"PRIuMAX" from %s",
1580 (uintmax_t)curpos, p->pack_name);
1581 /* bail to phase 2, in hopes of recovery */
1582 data = NULL;
1583 break;
1584 }
1585
1586 /* push object, proceed to base */
1587 if (delta_stack_nr >= delta_stack_alloc
1588 && delta_stack == small_delta_stack) {
1589 delta_stack_alloc = alloc_nr(delta_stack_nr);
1590 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1591 COPY_ARRAY(delta_stack, small_delta_stack,
1592 delta_stack_nr);
1593 } else {
1594 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1595 }
1596 i = delta_stack_nr++;
1597 delta_stack[i].obj_offset = obj_offset;
1598 delta_stack[i].curpos = curpos;
1599 delta_stack[i].size = size;
1600
1601 curpos = obj_offset = base_offset;
1602 }
1603
1604 /* PHASE 2: handle the base */
1605 switch (type) {
1606 case OBJ_OFS_DELTA:
1607 case OBJ_REF_DELTA:
1608 if (data)
1609 BUG("unpack_entry: left loop at a valid delta");
1610 break;
1611 case OBJ_COMMIT:
1612 case OBJ_TREE:
1613 case OBJ_BLOB:
1614 case OBJ_TAG:
1615 if (!base_from_cache)
1616 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1617 break;
1618 default:
1619 data = NULL;
1620 error("unknown object type %i at offset %"PRIuMAX" in %s",
1621 type, (uintmax_t)obj_offset, p->pack_name);
1622 }
1623
1624 /* PHASE 3: apply deltas in order */
1625
1626 /* invariants:
1627 * 'data' holds the base data, or NULL if there was corruption
1628 */
1629 while (delta_stack_nr) {
1630 void *delta_data;
1631 void *base = data;
1632 void *external_base = NULL;
1633 size_t delta_size, base_size = size;
1634 int i;
1635 off_t base_obj_offset = obj_offset;
1636
1637 data = NULL;
1638
1639 if (!base) {
1640 /*
1641 * We're probably in deep shit, but let's try to fetch
1642 * the required base anyway from another pack or loose.
1643 * This is costly but should happen only in the presence
1644 * of a corrupted pack, and is better than failing outright.
1645 */
1646 uint32_t pos;
1647 struct object_id base_oid;
1648 if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1649 struct object_info oi = OBJECT_INFO_INIT;
1650
1651 nth_packed_object_id(&base_oid, p,
1652 pack_pos_to_index(p, pos));
1653 error("failed to read delta base object %s"
1654 " at offset %"PRIuMAX" from %s",
1655 oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1656 p->pack_name);
1657 mark_bad_packed_object(p, &base_oid);
1658
1659 oi.typep = &type;
1660 oi.sizep = &base_size;
1661 oi.contentp = &base;
1662 if (odb_read_object_info_extended(r->objects, &base_oid,
1663 &oi, 0) < 0)
1664 base = NULL;
1665
1666 external_base = base;
1667 }
1668 }
1669
1670 i = --delta_stack_nr;
1671 obj_offset = delta_stack[i].obj_offset;
1672 curpos = delta_stack[i].curpos;
1673 delta_size = delta_stack[i].size;
1674
1675 if (!base)
1676 continue;
1677
1678 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1679
1680 if (!delta_data) {
1681 error("failed to unpack compressed delta "
1682 "at offset %"PRIuMAX" from %s",
1683 (uintmax_t)curpos, p->pack_name);
1684 data = NULL;
1685 } else {
1686 data = patch_delta(base, base_size, delta_data,
1687 delta_size, &size);
1688
1689 /*
1690 * We could not apply the delta; warn the user, but
1691 * keep going. Our failure will be noticed either in
1692 * the next iteration of the loop, or if this is the
1693 * final delta, in the caller when we return NULL.
1694 * Those code paths will take care of making a more
1695 * explicit warning and retrying with another copy of
1696 * the object.
1697 */
1698 if (!data)
1699 error("failed to apply delta");
1700 }
1701
1702 /*
1703 * We delay adding `base` to the cache until the end of the loop
1704 * because unpack_compressed_entry() momentarily releases the
1705 * obj_read_mutex, giving another thread the chance to access
1706 * the cache. Therefore, if `base` was already there, this other
1707 * thread could free() it (e.g. to make space for another entry)
1708 * before we are done using it.
1709 */
1710 if (!external_base)
1711 add_delta_base_cache(p, base_obj_offset, base, base_size,
1712 p->repo->settings.delta_base_cache_limit,
1713 type);
1714
1715 free(delta_data);
1716 free(external_base);
1717 }
1718
1719 if (final_type)
1720 *final_type = type;
1721 if (final_size)
1722 *final_size = size;
1723
1724out:
1725 unuse_pack(&w_curs);
1726
1727 if (delta_stack != small_delta_stack)
1728 free(delta_stack);
1729
1730 return data;
1731}
1732
1733int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1734{
1735 const unsigned char *index_fanout = p->index_data;
1736 const unsigned char *index_lookup;
1737 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1738 int index_lookup_width;
1739
1740 if (!index_fanout)
1741 BUG("bsearch_pack called without a valid pack-index");
1742
1743 index_lookup = index_fanout + 4 * 256;
1744 if (p->index_version == 1) {
1745 index_lookup_width = hashsz + 4;
1746 index_lookup += 4;
1747 } else {
1748 index_lookup_width = hashsz;
1749 index_fanout += 8;
1750 index_lookup += 8;
1751 }
1752
1753 return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1754 index_lookup, index_lookup_width, result);
1755}
1756
1757int nth_packed_object_id(struct object_id *oid,
1758 struct packed_git *p,
1759 uint32_t n)
1760{
1761 const unsigned char *index = p->index_data;
1762 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1763 if (!index) {
1764 if (open_pack_index(p))
1765 return -1;
1766 index = p->index_data;
1767 }
1768 if (n >= p->num_objects)
1769 return -1;
1770 index += 4 * 256;
1771 if (p->index_version == 1) {
1772 oidread(oid, index + st_add(st_mult(hashsz + 4, n), 4),
1773 p->repo->hash_algo);
1774 } else {
1775 index += 8;
1776 oidread(oid, index + st_mult(hashsz, n), p->repo->hash_algo);
1777 }
1778 return 0;
1779}
1780
1781void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1782{
1783 const unsigned char *ptr = vptr;
1784 const unsigned char *start = p->index_data;
1785 const unsigned char *end = start + p->index_size;
1786 if (ptr < start)
1787 die(_("offset before start of pack index for %s (corrupt index?)"),
1788 p->pack_name);
1789 /* No need to check for underflow; .idx files must be at least 8 bytes */
1790 if (ptr >= end - 8)
1791 die(_("offset beyond end of pack index for %s (truncated index?)"),
1792 p->pack_name);
1793}
1794
1795off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1796{
1797 const unsigned char *index = p->index_data;
1798 const unsigned int hashsz = p->repo->hash_algo->rawsz;
1799 index += 4 * 256;
1800 if (p->index_version == 1) {
1801 return ntohl(*((uint32_t *)(index + st_mult(hashsz + 4, n))));
1802 } else {
1803 uint32_t off;
1804 index += st_add(8, st_mult(p->num_objects, hashsz + 4));
1805 off = ntohl(*((uint32_t *)(index + st_mult(4, n))));
1806 if (!(off & 0x80000000))
1807 return off;
1808 index += st_add(st_mult(p->num_objects, 4),
1809 st_mult(off & 0x7fffffff, 8));
1810 check_pack_index_ptr(p, index);
1811 return get_be64(index);
1812 }
1813}
1814
1815off_t find_pack_entry_one(const struct object_id *oid,
1816 struct packed_git *p)
1817{
1818 const unsigned char *index = p->index_data;
1819 uint32_t result;
1820
1821 if (!index) {
1822 if (open_pack_index(p))
1823 return 0;
1824 }
1825
1826 if (bsearch_pack(oid, p, &result))
1827 return nth_packed_object_offset(p, result);
1828 return 0;
1829}
1830
1831int is_pack_valid(struct packed_git *p)
1832{
1833 /* An already open pack is known to be valid. */
1834 if (p->pack_fd != -1)
1835 return 1;
1836
1837 /* If the pack has one window completely covering the
1838 * file size, the pack is known to be valid even if
1839 * the descriptor is not currently open.
1840 */
1841 if (p->windows) {
1842 struct pack_window *w = p->windows;
1843
1844 if (!w->offset && w->len == p->pack_size)
1845 return 1;
1846 }
1847
1848 /* Force the pack to open to prove its valid. */
1849 return !open_packed_git(p);
1850}
1851
1852int packfile_fill_entry(struct packed_git *p,
1853 const struct object_id *oid,
1854 struct pack_entry *e,
1855 struct packed_git **bad_pack)
1856{
1857 off_t offset;
1858
1859 if (oidset_size(&p->bad_objects) &&
1860 oidset_contains(&p->bad_objects, oid)) {
1861 if (bad_pack && !*bad_pack)
1862 *bad_pack = p;
1863 return 0;
1864 }
1865
1866 offset = find_pack_entry_one(oid, p);
1867 if (!offset)
1868 return 0;
1869
1870 /*
1871 * We are about to tell the caller where they can locate the
1872 * requested object. We better make sure the packfile is
1873 * still here and can be accessed before supplying that
1874 * answer, as it may have been deleted since the index was
1875 * loaded!
1876 */
1877 if (!is_pack_valid(p))
1878 return 0;
1879 e->offset = offset;
1880 e->p = p;
1881 return 1;
1882}
1883
1884static void maybe_invalidate_kept_pack_cache(struct odb_source_packed *store,
1885 unsigned flags)
1886{
1887 if (!store->kept_cache.packs)
1888 return;
1889 if (store->kept_cache.flags == flags)
1890 return;
1891 FREE_AND_NULL(store->kept_cache.packs);
1892 store->kept_cache.flags = 0;
1893}
1894
1895struct packed_git **packfile_store_get_kept_pack_cache(struct odb_source_packed *store,
1896 unsigned flags)
1897{
1898 maybe_invalidate_kept_pack_cache(store, flags);
1899
1900 if (!store->kept_cache.packs) {
1901 struct packed_git **packs = NULL;
1902 struct packfile_list_entry *e;
1903 size_t nr = 0, alloc = 0;
1904
1905 /*
1906 * We want "all" packs here, because we need to cover ones that
1907 * are used by a midx, as well. We need to look in every one of
1908 * them (instead of the midx itself) to cover duplicates. It's
1909 * possible that an object is found in two packs that the midx
1910 * covers, one kept and one not kept, but the midx returns only
1911 * the non-kept version.
1912 */
1913 for (e = packfile_store_get_packs(store); e; e = e->next) {
1914 struct packed_git *p = e->pack;
1915
1916 if ((p->pack_keep && (flags & KEPT_PACK_ON_DISK)) ||
1917 (p->pack_keep_in_core && (flags & KEPT_PACK_IN_CORE)) ||
1918 (p->pack_keep_in_core_open && (flags & KEPT_PACK_IN_CORE_OPEN))) {
1919 ALLOC_GROW(packs, nr + 1, alloc);
1920 packs[nr++] = p;
1921 }
1922 }
1923 ALLOC_GROW(packs, nr + 1, alloc);
1924 packs[nr] = NULL;
1925
1926 store->kept_cache.packs = packs;
1927 store->kept_cache.flags = flags;
1928 }
1929
1930 return store->kept_cache.packs;
1931}
1932
1933int has_object_pack(struct repository *r, const struct object_id *oid)
1934{
1935 struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
1936
1937 for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
1938 if (!odb_source_read_object_info(&dir->packed->base, oid, NULL, 0, NULL))
1939 return 1;
1940 }
1941
1942 return 0;
1943}
1944
1945int has_object_kept_pack(struct repository *r, const struct object_id *oid,
1946 unsigned flags)
1947{
1948 struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
1949 struct pack_entry e;
1950
1951 for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
1952 struct packed_git **cache;
1953
1954 cache = packfile_store_get_kept_pack_cache(dir->packed, flags);
1955
1956 for (; *cache; cache++) {
1957 struct packed_git *p = *cache;
1958 if (packfile_fill_entry(p, oid, &e, NULL))
1959 return 1;
1960 }
1961 }
1962
1963 return 0;
1964}
1965
1966int for_each_object_in_pack(struct packed_git *p,
1967 each_packed_object_fn cb, void *data,
1968 enum odb_for_each_object_flags flags)
1969{
1970 uint32_t i;
1971 int r = 0;
1972
1973 if (flags & ODB_FOR_EACH_OBJECT_PACK_ORDER) {
1974 if (load_pack_revindex(p->repo, p))
1975 return -1;
1976 }
1977
1978 for (i = 0; i < p->num_objects; i++) {
1979 uint32_t index_pos;
1980 struct object_id oid;
1981
1982 /*
1983 * We are iterating "i" from 0 up to num_objects, but its
1984 * meaning may be different, depending on the requested output
1985 * order:
1986 *
1987 * - in object-name order, it is the same as the index order
1988 * used by nth_packed_object_id(), so we can pass it
1989 * directly
1990 *
1991 * - in pack-order, it is pack position, which we must
1992 * convert to an index position in order to get the oid.
1993 */
1994 if (flags & ODB_FOR_EACH_OBJECT_PACK_ORDER)
1995 index_pos = pack_pos_to_index(p, i);
1996 else
1997 index_pos = i;
1998
1999 if (nth_packed_object_id(&oid, p, index_pos) < 0)
2000 return error("unable to get sha1 of object %u in %s",
2001 index_pos, p->pack_name);
2002
2003 r = cb(&oid, p, index_pos, data);
2004 if (r)
2005 break;
2006 }
2007 return r;
2008}
2009
2010struct add_promisor_object_data {
2011 struct repository *repo;
2012 struct oidset *set;
2013};
2014
2015static int add_promisor_object(const struct object_id *oid,
2016 struct object_info *oi UNUSED,
2017 void *cb_data)
2018{
2019 struct add_promisor_object_data *data = cb_data;
2020 struct object *obj;
2021 int we_parsed_object;
2022
2023 obj = lookup_object(data->repo, oid);
2024 if (obj && obj->parsed) {
2025 we_parsed_object = 0;
2026 } else {
2027 we_parsed_object = 1;
2028 obj = parse_object_with_flags(data->repo, oid,
2029 PARSE_OBJECT_SKIP_HASH_CHECK);
2030 }
2031
2032 if (!obj)
2033 return 1;
2034
2035 oidset_insert(data->set, oid);
2036
2037 /*
2038 * If this is a tree, commit, or tag, the objects it refers
2039 * to are also promisor objects. (Blobs refer to no objects->)
2040 */
2041 if (obj->type == OBJ_TREE) {
2042 struct tree *tree = (struct tree *)obj;
2043 struct tree_desc desc;
2044 struct name_entry entry;
2045 if (init_tree_desc_gently(&desc, &tree->object.oid,
2046 tree->buffer, tree->size, 0))
2047 /*
2048 * Error messages are given when packs are
2049 * verified, so do not print any here.
2050 */
2051 return 0;
2052 while (tree_entry_gently(&desc, &entry))
2053 oidset_insert(data->set, &entry.oid);
2054 if (we_parsed_object)
2055 free_tree_buffer(tree);
2056 } else if (obj->type == OBJ_COMMIT) {
2057 struct commit *commit = (struct commit *) obj;
2058 struct commit_list *parents = commit->parents;
2059
2060 oidset_insert(data->set, get_commit_tree_oid(commit));
2061 for (; parents; parents = parents->next)
2062 oidset_insert(data->set, &parents->item->object.oid);
2063 } else if (obj->type == OBJ_TAG) {
2064 struct tag *tag = (struct tag *) obj;
2065 oidset_insert(data->set, get_tagged_oid(tag));
2066 }
2067 return 0;
2068}
2069
2070int is_promisor_object(struct repository *r, const struct object_id *oid)
2071{
2072 static struct oidset promisor_objects;
2073 static int promisor_objects_prepared;
2074
2075 if (!promisor_objects_prepared) {
2076 if (repo_has_promisor_remote(r)) {
2077 struct add_promisor_object_data data = {
2078 .repo = r,
2079 .set = &promisor_objects,
2080 };
2081
2082 odb_for_each_object(r->objects, NULL, add_promisor_object, &data,
2083 ODB_FOR_EACH_OBJECT_PROMISOR_ONLY | ODB_FOR_EACH_OBJECT_PACK_ORDER);
2084 }
2085 promisor_objects_prepared = 1;
2086 }
2087 return oidset_contains(&promisor_objects, oid);
2088}
2089
2090int parse_pack_header_option(const char *in, unsigned char *out, unsigned int *len)
2091{
2092 unsigned char *hdr;
2093 char *c;
2094
2095 hdr = out;
2096 put_be32(hdr, PACK_SIGNATURE);
2097 hdr += 4;
2098 put_be32(hdr, strtoul(in, &c, 10));
2099 hdr += 4;
2100 if (*c != ',')
2101 return -1;
2102 put_be32(hdr, strtoul(c + 1, &c, 10));
2103 hdr += 4;
2104 if (*c)
2105 return -1;
2106 *len = hdr - out;
2107 return 0;
2108}
2109
2110struct odb_packed_read_stream {
2111 struct odb_stream base;
2112 struct packed_git *pack;
2113 git_zstream z;
2114 enum {
2115 ODB_PACKED_READ_STREAM_UNINITIALIZED,
2116 ODB_PACKED_READ_STREAM_INUSE,
2117 ODB_PACKED_READ_STREAM_DONE,
2118 ODB_PACKED_READ_STREAM_ERROR,
2119 } z_state;
2120 off_t pos;
2121};
2122
2123static ssize_t read_istream_pack_non_delta(struct odb_stream *_st, char *buf,
2124 size_t sz)
2125{
2126 struct odb_packed_read_stream *st = (struct odb_packed_read_stream *)_st;
2127 size_t total_read = 0;
2128
2129 switch (st->z_state) {
2130 case ODB_PACKED_READ_STREAM_UNINITIALIZED:
2131 memset(&st->z, 0, sizeof(st->z));
2132 git_inflate_init(&st->z);
2133 st->z_state = ODB_PACKED_READ_STREAM_INUSE;
2134 break;
2135 case ODB_PACKED_READ_STREAM_DONE:
2136 return 0;
2137 case ODB_PACKED_READ_STREAM_ERROR:
2138 return -1;
2139 case ODB_PACKED_READ_STREAM_INUSE:
2140 break;
2141 }
2142
2143 while (total_read < sz) {
2144 int status;
2145 struct pack_window *window = NULL;
2146 unsigned char *mapped;
2147
2148 mapped = use_pack(st->pack, &window,
2149 st->pos, &st->z.avail_in);
2150
2151 st->z.next_out = (unsigned char *)buf + total_read;
2152 st->z.avail_out = sz - total_read;
2153 st->z.next_in = mapped;
2154 status = git_inflate(&st->z, Z_FINISH);
2155
2156 st->pos += st->z.next_in - mapped;
2157 total_read = st->z.next_out - (unsigned char *)buf;
2158 unuse_pack(&window);
2159
2160 if (status == Z_STREAM_END) {
2161 git_inflate_end(&st->z);
2162 st->z_state = ODB_PACKED_READ_STREAM_DONE;
2163 break;
2164 }
2165
2166 /*
2167 * Unlike the loose object case, we do not have to worry here
2168 * about running out of input bytes and spinning infinitely. If
2169 * we get Z_BUF_ERROR due to too few input bytes, then we'll
2170 * replenish them in the next use_pack() call when we loop. If
2171 * we truly hit the end of the pack (i.e., because it's corrupt
2172 * or truncated), then use_pack() catches that and will die().
2173 */
2174 if (status != Z_OK && status != Z_BUF_ERROR) {
2175 git_inflate_end(&st->z);
2176 st->z_state = ODB_PACKED_READ_STREAM_ERROR;
2177 return -1;
2178 }
2179 }
2180 return total_read;
2181}
2182
2183static int close_istream_pack_non_delta(struct odb_stream *_st)
2184{
2185 struct odb_packed_read_stream *st = (struct odb_packed_read_stream *)_st;
2186 if (st->z_state == ODB_PACKED_READ_STREAM_INUSE)
2187 git_inflate_end(&st->z);
2188 return 0;
2189}
2190
2191int packfile_read_object_stream(struct odb_stream **out,
2192 const struct object_id *oid,
2193 struct packed_git *pack,
2194 off_t offset)
2195{
2196 struct odb_packed_read_stream *stream;
2197 struct pack_window *window = NULL;
2198 enum object_type in_pack_type;
2199 size_t size;
2200
2201 in_pack_type = unpack_object_header(pack, &window, &offset, &size);
2202 unuse_pack(&window);
2203
2204 if (repo_settings_get_big_file_threshold(pack->repo) >= size)
2205 return -1;
2206
2207 switch (in_pack_type) {
2208 default:
2209 return -1; /* we do not do deltas for now */
2210 case OBJ_BAD:
2211 mark_bad_packed_object(pack, oid);
2212 return -1;
2213 case OBJ_COMMIT:
2214 case OBJ_TREE:
2215 case OBJ_BLOB:
2216 case OBJ_TAG:
2217 break;
2218 }
2219
2220 CALLOC_ARRAY(stream, 1);
2221 stream->base.close = close_istream_pack_non_delta;
2222 stream->base.read = read_istream_pack_non_delta;
2223 stream->base.type = in_pack_type;
2224 stream->base.size = size;
2225 stream->z_state = ODB_PACKED_READ_STREAM_UNINITIALIZED;
2226 stream->pack = pack;
2227 stream->pos = offset;
2228
2229 *out = &stream->base;
2230
2231 return 0;
2232}