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