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