git

Форк
0
/
packfile.c 
2307 строк · 59.1 Кб
1
#define USE_THE_REPOSITORY_VARIABLE
2

3
#include "git-compat-util.h"
4
#include "environment.h"
5
#include "gettext.h"
6
#include "hex.h"
7
#include "list.h"
8
#include "pack.h"
9
#include "repository.h"
10
#include "dir.h"
11
#include "mergesort.h"
12
#include "packfile.h"
13
#include "delta.h"
14
#include "hash-lookup.h"
15
#include "commit.h"
16
#include "object.h"
17
#include "tag.h"
18
#include "trace.h"
19
#include "tree-walk.h"
20
#include "tree.h"
21
#include "object-file.h"
22
#include "object-store-ll.h"
23
#include "midx.h"
24
#include "commit-graph.h"
25
#include "pack-revindex.h"
26
#include "promisor-remote.h"
27

28
char *odb_pack_name(struct strbuf *buf,
29
		    const unsigned char *hash,
30
		    const char *ext)
31
{
32
	strbuf_reset(buf);
33
	strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
34
		    hash_to_hex(hash), ext);
35
	return buf->buf;
36
}
37

38
char *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

44
char *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
}
49

50
static unsigned int pack_used_ctr;
51
static unsigned int pack_mmap_calls;
52
static unsigned int peak_pack_open_windows;
53
static unsigned int pack_open_windows;
54
static unsigned int pack_open_fds;
55
static unsigned int pack_max_fds;
56
static size_t peak_pack_mapped;
57
static size_t pack_mapped;
58

59
#define SZ_FMT PRIuMAX
60
static inline uintmax_t sz_fmt(size_t s) { return s; }
61

62
void 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
}
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
 */
88
static int check_packed_git_idx(const char *path, struct packed_git *p)
89
{
90
	void *idx_map;
91
	size_t idx_size;
92
	int fd = git_open(path), ret;
93
	struct stat st;
94
	const unsigned int hashsz = the_hash_algo->rawsz;
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);
103
	if (idx_size < 4 * 256 + hashsz + hashsz) {
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

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

118
int 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);
126
	if (!idx_map)
127
		return error("empty data");
128

129
	if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
130
		version = ntohl(hdr->idx_version);
131
		if (version < 2 || version > 2)
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);
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]);
145
		if (n < nr)
146
			return error("non-monotonic index %s", path);
147
		nr = n;
148
	}
149

150
	if (version == 1) {
151
		/*
152
		 * Total size:
153
		 *  - 256 index entries 4 bytes each
154
		 *  - 24-byte entries * nr (object ID + 4-byte offset)
155
		 *  - hash of the packfile
156
		 *  - file checksum
157
		 */
158
		if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
159
			return error("wrong index v1 file size in %s", path);
160
	} else if (version == 2) {
161
		/*
162
		 * Minimum size:
163
		 *  - 8 bytes of header
164
		 *  - 256 index entries 4 bytes each
165
		 *  - object ID entry * nr
166
		 *  - 4-byte crc entry * nr
167
		 *  - 4-byte offset entry * nr
168
		 *  - hash of the packfile
169
		 *  - file checksum
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
		 */
174
		size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
175
		size_t max_size = min_size;
176
		if (nr)
177
			max_size = st_add(max_size, st_mult(nr - 1, 8));
178
		if (idx_size < min_size || idx_size > max_size)
179
			return error("wrong index v2 file size in %s", path);
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
		     */
186
		    (sizeof(off_t) <= 4))
187
			return error("pack too large for current definition of off_t in %s", path);
188
		p->crc_offset = st_add(8 + 4 * 256, st_mult(nr, hashsz));
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

198
int 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))
208
		BUG("pack_name does not end in .pack");
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

215
uint32_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

232
static 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

240
struct 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 */
247
	hashcpy(p->hash, sha1, the_repository->hash_algo);
248
	if (check_packed_git_idx(idx_path, p)) {
249
		free(p);
250
		return NULL;
251
	}
252

253
	return p;
254
}
255

256
static 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

275
static int unuse_one_window(struct packed_git *current)
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);
282
	for (p = the_repository->objects->packed_git; p; p = p->next)
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

298
void 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

314
int close_pack_fd(struct packed_git *p)
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

326
void 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

334
static void close_pack_revindex(struct packed_git *p)
335
{
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

344
static 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

353
void close_pack(struct packed_git *p)
354
{
355
	close_pack_windows(p);
356
	close_pack_fd(p);
357
	close_pack_index(p);
358
	close_pack_revindex(p);
359
	close_pack_mtimes(p);
360
	oidset_clear(&p->bad_objects);
361
}
362

363
void close_object_store(struct raw_object_store *o)
364
{
365
	struct packed_git *p;
366

367
	for (p = o->packed_git; p; p = p->next)
368
		if (p->do_not_close)
369
			BUG("want to close pack marked 'do-not-close'");
370
		else
371
			close_pack(p);
372

373
	if (o->multi_pack_index) {
374
		close_midx(o->multi_pack_index);
375
		o->multi_pack_index = NULL;
376
	}
377

378
	close_commit_graph(o);
379
}
380

381
void unlink_pack_path(const char *pack_name, int force_delete)
382
{
383
	static const char *exts[] = {".idx", ".pack", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
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

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
 */
413
static 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

464
static 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

470
	for (p = the_repository->objects->packed_git; p; p = p->next) {
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

482
static 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

523
const 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

533
/*
534
 * Do not call this directly as this leaks p->pack_fd on error return;
535
 * call open_packed_git() instead.
536
 */
537
static int open_packed_git_1(struct packed_git *p)
538
{
539
	struct stat st;
540
	struct pack_header hdr;
541
	unsigned char hash[GIT_MAX_RAWSZ];
542
	unsigned char *idx_hash;
543
	ssize_t read_result;
544
	const unsigned hashsz = the_hash_algo->rawsz;
545

546
	if (open_pack_index(p))
547
		return error("packfile %s index unavailable", p->pack_name);
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

575
	/* Verify we recognize this pack file format. */
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))
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);
594
	read_result = pread_in_full(p->pack_fd, hash, hashsz,
595
					p->pack_size - hashsz);
596
	if (read_result < 0)
597
		return error_errno("error reading from %s", p->pack_name);
598
	if (read_result != hashsz)
599
		return error("packfile %s signature is unavailable", p->pack_name);
600
	idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
601
	if (!hasheq(hash, idx_hash, the_repository->hash_algo))
602
		return error("packfile %s does not match index", p->pack_name);
603
	return 0;
604
}
605

606
static int open_packed_git(struct packed_git *p)
607
{
608
	if (!open_packed_git_1(p))
609
		return 0;
610
	close_pack_fd(p);
611
	return -1;
612
}
613

614
static int in_window(struct pack_window *win, off_t offset)
615
{
616
	/* We must promise at least one full hash after the
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
624
		&& (offset + the_hash_algo->rawsz) <= (win_off + win->len);
625
}
626

627
unsigned 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);
641
	if (offset > (p->pack_size - the_hash_algo->rawsz))
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

660
			CALLOC_ARRAY(win, 1);
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 */
670
			win->base = xmmap_gently(NULL, win->len,
671
				PROT_READ, MAP_PRIVATE,
672
				p->pack_fd, win->offset);
673
			if (win->base == MAP_FAILED)
674
				die_errno(_("packfile %s cannot be mapped%s"),
675
					  p->pack_name, mmap_os_err());
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
}
699

700
void 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
}
708

709
struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
710
{
711
	struct stat st;
712
	size_t alloc;
713
	struct packed_git *p;
714

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
	/*
723
	 * ".promisor" is long enough to hold any suffix we're adding (and
724
	 * the use xsnprintf double-checks that)
725
	 */
726
	alloc = st_add3(path_len, strlen(".promisor"), 1);
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

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

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

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;
754
	if (path_len < the_hash_algo->hexsz ||
755
	    get_hash_hex(path + path_len - the_hash_algo->hexsz, p->hash))
756
		hashclr(p->hash, the_repository->hash_algo);
757
	return p;
758
}
759

760
void install_packed_git(struct repository *r, struct packed_git *pack)
761
{
762
	if (pack->pack_fd != -1)
763
		pack_open_fds++;
764

765
	pack->next = r->objects->packed_git;
766
	r->objects->packed_git = pack;
767

768
	hashmap_entry_init(&pack->packmap_ent, strhash(pack->pack_name));
769
	hashmap_add(&r->objects->pack_map, &pack->packmap_ent);
770
}
771

772
void (*report_garbage)(unsigned seen_bits, const char *path);
773

774
static 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

784
static 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

818
void for_each_file_in_pack_subdir(const char *objdir,
819
				  const char *subdir,
820
				  each_file_in_pack_dir_fn fn,
821
				  void *data)
822
{
823
	struct strbuf path = STRBUF_INIT;
824
	size_t dirnamelen;
825
	DIR *dir;
826
	struct dirent *de;
827

828
	strbuf_addstr(&path, objdir);
829
	strbuf_addstr(&path, "/pack");
830
	if (subdir)
831
		strbuf_addf(&path, "/%s", subdir);
832
	dir = opendir(path.buf);
833
	if (!dir) {
834
		if (errno != ENOENT)
835
			error_errno("unable to open object pack directory: %s",
836
				    path.buf);
837
		strbuf_release(&path);
838
		return;
839
	}
840
	strbuf_addch(&path, '/');
841
	dirnamelen = path.len;
842
	while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
843
		strbuf_setlen(&path, dirnamelen);
844
		strbuf_addstr(&path, de->d_name);
845

846
		fn(path.buf, path.len, de->d_name, data);
847
	}
848

849
	closedir(dir);
850
	strbuf_release(&path);
851
}
852

853
void for_each_file_in_pack_dir(const char *objdir,
854
			       each_file_in_pack_dir_fn fn,
855
			       void *data)
856
{
857
	for_each_file_in_pack_subdir(objdir, NULL, fn, data);
858
}
859

860
struct prepare_pack_data {
861
	struct repository *r;
862
	struct string_list *garbage;
863
	int local;
864
	struct multi_pack_index *m;
865
};
866

867
static void prepare_pack(const char *full_name, size_t full_name_len,
868
			 const char *file_name, void *_data)
869
{
870
	struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
871
	struct packed_git *p;
872
	size_t base_len = full_name_len;
873

874
	if (strip_suffix_mem(full_name, &base_len, ".idx") &&
875
	    !(data->m && midx_contains_pack(data->m, file_name))) {
876
		struct hashmap_entry hent;
877
		char *pack_name = xstrfmt("%.*s.pack", (int)base_len, full_name);
878
		unsigned int hash = strhash(pack_name);
879
		hashmap_entry_init(&hent, hash);
880

881
		/* Don't reopen a pack we already have. */
882
		if (!hashmap_get(&data->r->objects->pack_map, &hent, pack_name)) {
883
			p = add_packed_git(full_name, full_name_len, data->local);
884
			if (p)
885
				install_packed_git(data->r, p);
886
		}
887
		free(pack_name);
888
	}
889

890
	if (!report_garbage)
891
		return;
892

893
	if (!strcmp(file_name, "multi-pack-index") ||
894
	    !strcmp(file_name, "multi-pack-index.d"))
895
		return;
896
	if (starts_with(file_name, "multi-pack-index") &&
897
	    (ends_with(file_name, ".bitmap") || ends_with(file_name, ".rev")))
898
		return;
899
	if (ends_with(file_name, ".idx") ||
900
	    ends_with(file_name, ".rev") ||
901
	    ends_with(file_name, ".pack") ||
902
	    ends_with(file_name, ".bitmap") ||
903
	    ends_with(file_name, ".keep") ||
904
	    ends_with(file_name, ".promisor") ||
905
	    ends_with(file_name, ".mtimes"))
906
		string_list_append(data->garbage, full_name);
907
	else
908
		report_garbage(PACKDIR_FILE_GARBAGE, full_name);
909
}
910

911
static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
912
{
913
	struct prepare_pack_data data;
914
	struct string_list garbage = STRING_LIST_INIT_DUP;
915

916
	data.m = r->objects->multi_pack_index;
917

918
	/* look for the multi-pack-index for this object directory */
919
	while (data.m && strcmp(data.m->object_dir, objdir))
920
		data.m = data.m->next;
921

922
	data.r = r;
923
	data.garbage = &garbage;
924
	data.local = local;
925

926
	for_each_file_in_pack_dir(objdir, prepare_pack, &data);
927

928
	report_pack_garbage(data.garbage);
929
	string_list_clear(data.garbage, 0);
930
}
931

932
static void prepare_packed_git(struct repository *r);
933
/*
934
 * Give a fast, rough count of the number of objects in the repository. This
935
 * ignores loose objects completely. If you have a lot of them, then either
936
 * you should repack because your performance will be awful, or they are
937
 * all unreachable objects about to be pruned, in which case they're not really
938
 * interesting as a measure of repo size in the first place.
939
 */
940
unsigned long repo_approximate_object_count(struct repository *r)
941
{
942
	if (!r->objects->approximate_object_count_valid) {
943
		unsigned long count;
944
		struct multi_pack_index *m;
945
		struct packed_git *p;
946

947
		prepare_packed_git(r);
948
		count = 0;
949
		for (m = get_multi_pack_index(r); m; m = m->next)
950
			count += m->num_objects;
951
		for (p = r->objects->packed_git; p; p = p->next) {
952
			if (open_pack_index(p))
953
				continue;
954
			count += p->num_objects;
955
		}
956
		r->objects->approximate_object_count = count;
957
		r->objects->approximate_object_count_valid = 1;
958
	}
959
	return r->objects->approximate_object_count;
960
}
961

962
DEFINE_LIST_SORT(static, sort_packs, struct packed_git, next);
963

964
static int sort_pack(const struct packed_git *a, const struct packed_git *b)
965
{
966
	int st;
967

968
	/*
969
	 * Local packs tend to contain objects specific to our
970
	 * variant of the project than remote ones.  In addition,
971
	 * remote ones could be on a network mounted filesystem.
972
	 * Favor local ones for these reasons.
973
	 */
974
	st = a->pack_local - b->pack_local;
975
	if (st)
976
		return -st;
977

978
	/*
979
	 * Younger packs tend to contain more recent objects,
980
	 * and more recent objects tend to get accessed more
981
	 * often.
982
	 */
983
	if (a->mtime < b->mtime)
984
		return 1;
985
	else if (a->mtime == b->mtime)
986
		return 0;
987
	return -1;
988
}
989

990
static void rearrange_packed_git(struct repository *r)
991
{
992
	sort_packs(&r->objects->packed_git, sort_pack);
993
}
994

995
static void prepare_packed_git_mru(struct repository *r)
996
{
997
	struct packed_git *p;
998

999
	INIT_LIST_HEAD(&r->objects->packed_git_mru);
1000

1001
	for (p = r->objects->packed_git; p; p = p->next)
1002
		list_add_tail(&p->mru, &r->objects->packed_git_mru);
1003
}
1004

1005
static void prepare_packed_git(struct repository *r)
1006
{
1007
	struct object_directory *odb;
1008

1009
	if (r->objects->packed_git_initialized)
1010
		return;
1011

1012
	prepare_alt_odb(r);
1013
	for (odb = r->objects->odb; odb; odb = odb->next) {
1014
		int local = (odb == r->objects->odb);
1015
		prepare_multi_pack_index_one(r, odb->path, local);
1016
		prepare_packed_git_one(r, odb->path, local);
1017
	}
1018
	rearrange_packed_git(r);
1019

1020
	prepare_packed_git_mru(r);
1021
	r->objects->packed_git_initialized = 1;
1022
}
1023

1024
void reprepare_packed_git(struct repository *r)
1025
{
1026
	struct object_directory *odb;
1027

1028
	obj_read_lock();
1029

1030
	/*
1031
	 * Reprepare alt odbs, in case the alternates file was modified
1032
	 * during the course of this process. This only _adds_ odbs to
1033
	 * the linked list, so existing odbs will continue to exist for
1034
	 * the lifetime of the process.
1035
	 */
1036
	r->objects->loaded_alternates = 0;
1037
	prepare_alt_odb(r);
1038

1039
	for (odb = r->objects->odb; odb; odb = odb->next)
1040
		odb_clear_loose_cache(odb);
1041

1042
	r->objects->approximate_object_count_valid = 0;
1043
	r->objects->packed_git_initialized = 0;
1044
	prepare_packed_git(r);
1045
	obj_read_unlock();
1046
}
1047

1048
struct packed_git *get_packed_git(struct repository *r)
1049
{
1050
	prepare_packed_git(r);
1051
	return r->objects->packed_git;
1052
}
1053

1054
struct multi_pack_index *get_multi_pack_index(struct repository *r)
1055
{
1056
	prepare_packed_git(r);
1057
	return r->objects->multi_pack_index;
1058
}
1059

1060
struct multi_pack_index *get_local_multi_pack_index(struct repository *r)
1061
{
1062
	struct multi_pack_index *m = get_multi_pack_index(r);
1063

1064
	/* no need to iterate; we always put the local one first (if any) */
1065
	if (m && m->local)
1066
		return m;
1067

1068
	return NULL;
1069
}
1070

1071
struct packed_git *get_all_packs(struct repository *r)
1072
{
1073
	struct multi_pack_index *m;
1074

1075
	prepare_packed_git(r);
1076
	for (m = r->objects->multi_pack_index; m; m = m->next) {
1077
		uint32_t i;
1078
		for (i = 0; i < m->num_packs + m->num_packs_in_base; i++)
1079
			prepare_midx_pack(r, m, i);
1080
	}
1081

1082
	return r->objects->packed_git;
1083
}
1084

1085
struct list_head *get_packed_git_mru(struct repository *r)
1086
{
1087
	prepare_packed_git(r);
1088
	return &r->objects->packed_git_mru;
1089
}
1090

1091
unsigned long unpack_object_header_buffer(const unsigned char *buf,
1092
		unsigned long len, enum object_type *type, unsigned long *sizep)
1093
{
1094
	unsigned shift;
1095
	size_t size, c;
1096
	unsigned long used = 0;
1097

1098
	c = buf[used++];
1099
	*type = (c >> 4) & 7;
1100
	size = c & 15;
1101
	shift = 4;
1102
	while (c & 0x80) {
1103
		if (len <= used || (bitsizeof(long) - 7) < shift) {
1104
			error("bad object header");
1105
			size = used = 0;
1106
			break;
1107
		}
1108
		c = buf[used++];
1109
		size = st_add(size, st_left_shift(c & 0x7f, shift));
1110
		shift += 7;
1111
	}
1112
	*sizep = cast_size_t_to_ulong(size);
1113
	return used;
1114
}
1115

1116
unsigned long get_size_from_delta(struct packed_git *p,
1117
				  struct pack_window **w_curs,
1118
				  off_t curpos)
1119
{
1120
	const unsigned char *data;
1121
	unsigned char delta_head[20], *in;
1122
	git_zstream stream;
1123
	int st;
1124

1125
	memset(&stream, 0, sizeof(stream));
1126
	stream.next_out = delta_head;
1127
	stream.avail_out = sizeof(delta_head);
1128

1129
	git_inflate_init(&stream);
1130
	do {
1131
		in = use_pack(p, w_curs, curpos, &stream.avail_in);
1132
		stream.next_in = in;
1133
		/*
1134
		 * Note: the window section returned by use_pack() must be
1135
		 * available throughout git_inflate()'s unlocked execution. To
1136
		 * ensure no other thread will modify the window in the
1137
		 * meantime, we rely on the packed_window.inuse_cnt. This
1138
		 * counter is incremented before window reading and checked
1139
		 * before window disposal.
1140
		 *
1141
		 * Other worrying sections could be the call to close_pack_fd(),
1142
		 * which can close packs even with in-use windows, and to
1143
		 * reprepare_packed_git(). Regarding the former, mmap doc says:
1144
		 * "closing the file descriptor does not unmap the region". And
1145
		 * for the latter, it won't re-open already available packs.
1146
		 */
1147
		obj_read_unlock();
1148
		st = git_inflate(&stream, Z_FINISH);
1149
		obj_read_lock();
1150
		curpos += stream.next_in - in;
1151
	} while ((st == Z_OK || st == Z_BUF_ERROR) &&
1152
		 stream.total_out < sizeof(delta_head));
1153
	git_inflate_end(&stream);
1154
	if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1155
		error("delta data unpack-initial failed");
1156
		return 0;
1157
	}
1158

1159
	/* Examine the initial part of the delta to figure out
1160
	 * the result size.
1161
	 */
1162
	data = delta_head;
1163

1164
	/* ignore base size */
1165
	get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1166

1167
	/* Read the result size */
1168
	return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1169
}
1170

1171
int unpack_object_header(struct packed_git *p,
1172
			 struct pack_window **w_curs,
1173
			 off_t *curpos,
1174
			 unsigned long *sizep)
1175
{
1176
	unsigned char *base;
1177
	unsigned long left;
1178
	unsigned long used;
1179
	enum object_type type;
1180

1181
	/* use_pack() assures us we have [base, base + 20) available
1182
	 * as a range that we can look at.  (Its actually the hash
1183
	 * size that is assured.)  With our object header encoding
1184
	 * the maximum deflated object size is 2^137, which is just
1185
	 * insane, so we know won't exceed what we have been given.
1186
	 */
1187
	base = use_pack(p, w_curs, *curpos, &left);
1188
	used = unpack_object_header_buffer(base, left, &type, sizep);
1189
	if (!used) {
1190
		type = OBJ_BAD;
1191
	} else
1192
		*curpos += used;
1193

1194
	return type;
1195
}
1196

1197
void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
1198
{
1199
	oidset_insert(&p->bad_objects, oid);
1200
}
1201

1202
const struct packed_git *has_packed_and_bad(struct repository *r,
1203
					    const struct object_id *oid)
1204
{
1205
	struct packed_git *p;
1206

1207
	for (p = r->objects->packed_git; p; p = p->next)
1208
		if (oidset_contains(&p->bad_objects, oid))
1209
			return p;
1210
	return NULL;
1211
}
1212

1213
off_t get_delta_base(struct packed_git *p,
1214
		     struct pack_window **w_curs,
1215
		     off_t *curpos,
1216
		     enum object_type type,
1217
		     off_t delta_obj_offset)
1218
{
1219
	unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1220
	off_t base_offset;
1221

1222
	/* use_pack() assured us we have [base_info, base_info + 20)
1223
	 * as a range that we can look at without walking off the
1224
	 * end of the mapped window.  Its actually the hash size
1225
	 * that is assured.  An OFS_DELTA longer than the hash size
1226
	 * is stupid, as then a REF_DELTA would be smaller to store.
1227
	 */
1228
	if (type == OBJ_OFS_DELTA) {
1229
		unsigned used = 0;
1230
		unsigned char c = base_info[used++];
1231
		base_offset = c & 127;
1232
		while (c & 128) {
1233
			base_offset += 1;
1234
			if (!base_offset || MSB(base_offset, 7))
1235
				return 0;  /* overflow */
1236
			c = base_info[used++];
1237
			base_offset = (base_offset << 7) + (c & 127);
1238
		}
1239
		base_offset = delta_obj_offset - base_offset;
1240
		if (base_offset <= 0 || base_offset >= delta_obj_offset)
1241
			return 0;  /* out of bound */
1242
		*curpos += used;
1243
	} else if (type == OBJ_REF_DELTA) {
1244
		/* The base entry _must_ be in the same pack */
1245
		base_offset = find_pack_entry_one(base_info, p);
1246
		*curpos += the_hash_algo->rawsz;
1247
	} else
1248
		die("I am totally screwed");
1249
	return base_offset;
1250
}
1251

1252
/*
1253
 * Like get_delta_base above, but we return the sha1 instead of the pack
1254
 * offset. This means it is cheaper for REF deltas (we do not have to do
1255
 * the final object lookup), but more expensive for OFS deltas (we
1256
 * have to load the revidx to convert the offset back into a sha1).
1257
 */
1258
static int get_delta_base_oid(struct packed_git *p,
1259
			      struct pack_window **w_curs,
1260
			      off_t curpos,
1261
			      struct object_id *oid,
1262
			      enum object_type type,
1263
			      off_t delta_obj_offset)
1264
{
1265
	if (type == OBJ_REF_DELTA) {
1266
		unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1267
		oidread(oid, base, the_repository->hash_algo);
1268
		return 0;
1269
	} else if (type == OBJ_OFS_DELTA) {
1270
		uint32_t base_pos;
1271
		off_t base_offset = get_delta_base(p, w_curs, &curpos,
1272
						   type, delta_obj_offset);
1273

1274
		if (!base_offset)
1275
			return -1;
1276

1277
		if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1278
			return -1;
1279

1280
		return nth_packed_object_id(oid, p,
1281
					    pack_pos_to_index(p, base_pos));
1282
	} else
1283
		return -1;
1284
}
1285

1286
static int retry_bad_packed_offset(struct repository *r,
1287
				   struct packed_git *p,
1288
				   off_t obj_offset)
1289
{
1290
	int type;
1291
	uint32_t pos;
1292
	struct object_id oid;
1293
	if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1294
		return OBJ_BAD;
1295
	nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1296
	mark_bad_packed_object(p, &oid);
1297
	type = oid_object_info(r, &oid, NULL);
1298
	if (type <= OBJ_NONE)
1299
		return OBJ_BAD;
1300
	return type;
1301
}
1302

1303
#define POI_STACK_PREALLOC 64
1304

1305
static enum object_type packed_to_object_type(struct repository *r,
1306
					      struct packed_git *p,
1307
					      off_t obj_offset,
1308
					      enum object_type type,
1309
					      struct pack_window **w_curs,
1310
					      off_t curpos)
1311
{
1312
	off_t small_poi_stack[POI_STACK_PREALLOC];
1313
	off_t *poi_stack = small_poi_stack;
1314
	int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1315

1316
	while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1317
		off_t base_offset;
1318
		unsigned long size;
1319
		/* Push the object we're going to leave behind */
1320
		if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1321
			poi_stack_alloc = alloc_nr(poi_stack_nr);
1322
			ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1323
			COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1324
		} else {
1325
			ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1326
		}
1327
		poi_stack[poi_stack_nr++] = obj_offset;
1328
		/* If parsing the base offset fails, just unwind */
1329
		base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1330
		if (!base_offset)
1331
			goto unwind;
1332
		curpos = obj_offset = base_offset;
1333
		type = unpack_object_header(p, w_curs, &curpos, &size);
1334
		if (type <= OBJ_NONE) {
1335
			/* If getting the base itself fails, we first
1336
			 * retry the base, otherwise unwind */
1337
			type = retry_bad_packed_offset(r, p, base_offset);
1338
			if (type > OBJ_NONE)
1339
				goto out;
1340
			goto unwind;
1341
		}
1342
	}
1343

1344
	switch (type) {
1345
	case OBJ_BAD:
1346
	case OBJ_COMMIT:
1347
	case OBJ_TREE:
1348
	case OBJ_BLOB:
1349
	case OBJ_TAG:
1350
		break;
1351
	default:
1352
		error("unknown object type %i at offset %"PRIuMAX" in %s",
1353
		      type, (uintmax_t)obj_offset, p->pack_name);
1354
		type = OBJ_BAD;
1355
	}
1356

1357
out:
1358
	if (poi_stack != small_poi_stack)
1359
		free(poi_stack);
1360
	return type;
1361

1362
unwind:
1363
	while (poi_stack_nr) {
1364
		obj_offset = poi_stack[--poi_stack_nr];
1365
		type = retry_bad_packed_offset(r, p, obj_offset);
1366
		if (type > OBJ_NONE)
1367
			goto out;
1368
	}
1369
	type = OBJ_BAD;
1370
	goto out;
1371
}
1372

1373
static struct hashmap delta_base_cache;
1374
static size_t delta_base_cached;
1375

1376
static LIST_HEAD(delta_base_cache_lru);
1377

1378
struct delta_base_cache_key {
1379
	struct packed_git *p;
1380
	off_t base_offset;
1381
};
1382

1383
struct delta_base_cache_entry {
1384
	struct hashmap_entry ent;
1385
	struct delta_base_cache_key key;
1386
	struct list_head lru;
1387
	void *data;
1388
	unsigned long size;
1389
	enum object_type type;
1390
};
1391

1392
static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1393
{
1394
	unsigned int hash;
1395

1396
	hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1397
	hash += (hash >> 8) + (hash >> 16);
1398
	return hash;
1399
}
1400

1401
static struct delta_base_cache_entry *
1402
get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1403
{
1404
	struct hashmap_entry entry, *e;
1405
	struct delta_base_cache_key key;
1406

1407
	if (!delta_base_cache.cmpfn)
1408
		return NULL;
1409

1410
	hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1411
	key.p = p;
1412
	key.base_offset = base_offset;
1413
	e = hashmap_get(&delta_base_cache, &entry, &key);
1414
	return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1415
}
1416

1417
static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1418
				   const struct delta_base_cache_key *b)
1419
{
1420
	return a->p == b->p && a->base_offset == b->base_offset;
1421
}
1422

1423
static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1424
				     const struct hashmap_entry *va,
1425
				     const struct hashmap_entry *vb,
1426
				     const void *vkey)
1427
{
1428
	const struct delta_base_cache_entry *a, *b;
1429
	const struct delta_base_cache_key *key = vkey;
1430

1431
	a = container_of(va, const struct delta_base_cache_entry, ent);
1432
	b = container_of(vb, const struct delta_base_cache_entry, ent);
1433

1434
	if (key)
1435
		return !delta_base_cache_key_eq(&a->key, key);
1436
	else
1437
		return !delta_base_cache_key_eq(&a->key, &b->key);
1438
}
1439

1440
static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1441
{
1442
	return !!get_delta_base_cache_entry(p, base_offset);
1443
}
1444

1445
/*
1446
 * Remove the entry from the cache, but do _not_ free the associated
1447
 * entry data. The caller takes ownership of the "data" buffer, and
1448
 * should copy out any fields it wants before detaching.
1449
 */
1450
static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1451
{
1452
	hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1453
	list_del(&ent->lru);
1454
	delta_base_cached -= ent->size;
1455
	free(ent);
1456
}
1457

1458
static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1459
				   off_t base_offset, unsigned long *base_size,
1460
				   enum object_type *type)
1461
{
1462
	struct delta_base_cache_entry *ent;
1463

1464
	ent = get_delta_base_cache_entry(p, base_offset);
1465
	if (!ent)
1466
		return unpack_entry(r, p, base_offset, type, base_size);
1467

1468
	if (type)
1469
		*type = ent->type;
1470
	if (base_size)
1471
		*base_size = ent->size;
1472
	return xmemdupz(ent->data, ent->size);
1473
}
1474

1475
static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1476
{
1477
	free(ent->data);
1478
	detach_delta_base_cache_entry(ent);
1479
}
1480

1481
void clear_delta_base_cache(void)
1482
{
1483
	struct list_head *lru, *tmp;
1484
	list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1485
		struct delta_base_cache_entry *entry =
1486
			list_entry(lru, struct delta_base_cache_entry, lru);
1487
		release_delta_base_cache(entry);
1488
	}
1489
}
1490

1491
static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1492
	void *base, unsigned long base_size, enum object_type type)
1493
{
1494
	struct delta_base_cache_entry *ent;
1495
	struct list_head *lru, *tmp;
1496

1497
	/*
1498
	 * Check required to avoid redundant entries when more than one thread
1499
	 * is unpacking the same object, in unpack_entry() (since its phases I
1500
	 * and III might run concurrently across multiple threads).
1501
	 */
1502
	if (in_delta_base_cache(p, base_offset)) {
1503
		free(base);
1504
		return;
1505
	}
1506

1507
	delta_base_cached += base_size;
1508

1509
	list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1510
		struct delta_base_cache_entry *f =
1511
			list_entry(lru, struct delta_base_cache_entry, lru);
1512
		if (delta_base_cached <= delta_base_cache_limit)
1513
			break;
1514
		release_delta_base_cache(f);
1515
	}
1516

1517
	ent = xmalloc(sizeof(*ent));
1518
	ent->key.p = p;
1519
	ent->key.base_offset = base_offset;
1520
	ent->type = type;
1521
	ent->data = base;
1522
	ent->size = base_size;
1523
	list_add_tail(&ent->lru, &delta_base_cache_lru);
1524

1525
	if (!delta_base_cache.cmpfn)
1526
		hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1527
	hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1528
	hashmap_add(&delta_base_cache, &ent->ent);
1529
}
1530

1531
int packed_object_info(struct repository *r, struct packed_git *p,
1532
		       off_t obj_offset, struct object_info *oi)
1533
{
1534
	struct pack_window *w_curs = NULL;
1535
	unsigned long size;
1536
	off_t curpos = obj_offset;
1537
	enum object_type type;
1538

1539
	/*
1540
	 * We always get the representation type, but only convert it to
1541
	 * a "real" type later if the caller is interested.
1542
	 */
1543
	if (oi->contentp) {
1544
		*oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1545
						      &type);
1546
		if (!*oi->contentp)
1547
			type = OBJ_BAD;
1548
	} else {
1549
		type = unpack_object_header(p, &w_curs, &curpos, &size);
1550
	}
1551

1552
	if (!oi->contentp && oi->sizep) {
1553
		if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1554
			off_t tmp_pos = curpos;
1555
			off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1556
							   type, obj_offset);
1557
			if (!base_offset) {
1558
				type = OBJ_BAD;
1559
				goto out;
1560
			}
1561
			*oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1562
			if (*oi->sizep == 0) {
1563
				type = OBJ_BAD;
1564
				goto out;
1565
			}
1566
		} else {
1567
			*oi->sizep = size;
1568
		}
1569
	}
1570

1571
	if (oi->disk_sizep) {
1572
		uint32_t pos;
1573
		if (offset_to_pack_pos(p, obj_offset, &pos) < 0) {
1574
			error("could not find object at offset %"PRIuMAX" "
1575
			      "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1576
			type = OBJ_BAD;
1577
			goto out;
1578
		}
1579

1580
		*oi->disk_sizep = pack_pos_to_offset(p, pos + 1) - obj_offset;
1581
	}
1582

1583
	if (oi->typep || oi->type_name) {
1584
		enum object_type ptot;
1585
		ptot = packed_to_object_type(r, p, obj_offset,
1586
					     type, &w_curs, curpos);
1587
		if (oi->typep)
1588
			*oi->typep = ptot;
1589
		if (oi->type_name) {
1590
			const char *tn = type_name(ptot);
1591
			if (tn)
1592
				strbuf_addstr(oi->type_name, tn);
1593
		}
1594
		if (ptot < 0) {
1595
			type = OBJ_BAD;
1596
			goto out;
1597
		}
1598
	}
1599

1600
	if (oi->delta_base_oid) {
1601
		if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1602
			if (get_delta_base_oid(p, &w_curs, curpos,
1603
					       oi->delta_base_oid,
1604
					       type, obj_offset) < 0) {
1605
				type = OBJ_BAD;
1606
				goto out;
1607
			}
1608
		} else
1609
			oidclr(oi->delta_base_oid, the_repository->hash_algo);
1610
	}
1611

1612
	oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1613
							  OI_PACKED;
1614

1615
out:
1616
	unuse_pack(&w_curs);
1617
	return type;
1618
}
1619

1620
static void *unpack_compressed_entry(struct packed_git *p,
1621
				    struct pack_window **w_curs,
1622
				    off_t curpos,
1623
				    unsigned long size)
1624
{
1625
	int st;
1626
	git_zstream stream;
1627
	unsigned char *buffer, *in;
1628

1629
	buffer = xmallocz_gently(size);
1630
	if (!buffer)
1631
		return NULL;
1632
	memset(&stream, 0, sizeof(stream));
1633
	stream.next_out = buffer;
1634
	stream.avail_out = size + 1;
1635

1636
	git_inflate_init(&stream);
1637
	do {
1638
		in = use_pack(p, w_curs, curpos, &stream.avail_in);
1639
		stream.next_in = in;
1640
		/*
1641
		 * Note: we must ensure the window section returned by
1642
		 * use_pack() will be available throughout git_inflate()'s
1643
		 * unlocked execution. Please refer to the comment at
1644
		 * get_size_from_delta() to see how this is done.
1645
		 */
1646
		obj_read_unlock();
1647
		st = git_inflate(&stream, Z_FINISH);
1648
		obj_read_lock();
1649
		if (!stream.avail_out)
1650
			break; /* the payload is larger than it should be */
1651
		curpos += stream.next_in - in;
1652
	} while (st == Z_OK || st == Z_BUF_ERROR);
1653
	git_inflate_end(&stream);
1654
	if ((st != Z_STREAM_END) || stream.total_out != size) {
1655
		free(buffer);
1656
		return NULL;
1657
	}
1658

1659
	/* versions of zlib can clobber unconsumed portion of outbuf */
1660
	buffer[size] = '\0';
1661

1662
	return buffer;
1663
}
1664

1665
static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1666
{
1667
	static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1668
	trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1669
			 p->pack_name, (uintmax_t)obj_offset);
1670
}
1671

1672
int do_check_packed_object_crc;
1673

1674
#define UNPACK_ENTRY_STACK_PREALLOC 64
1675
struct unpack_entry_stack_ent {
1676
	off_t obj_offset;
1677
	off_t curpos;
1678
	unsigned long size;
1679
};
1680

1681
void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1682
		   enum object_type *final_type, unsigned long *final_size)
1683
{
1684
	struct pack_window *w_curs = NULL;
1685
	off_t curpos = obj_offset;
1686
	void *data = NULL;
1687
	unsigned long size;
1688
	enum object_type type;
1689
	struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1690
	struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1691
	int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1692
	int base_from_cache = 0;
1693

1694
	write_pack_access_log(p, obj_offset);
1695

1696
	/* PHASE 1: drill down to the innermost base object */
1697
	for (;;) {
1698
		off_t base_offset;
1699
		int i;
1700
		struct delta_base_cache_entry *ent;
1701

1702
		ent = get_delta_base_cache_entry(p, curpos);
1703
		if (ent) {
1704
			type = ent->type;
1705
			data = ent->data;
1706
			size = ent->size;
1707
			detach_delta_base_cache_entry(ent);
1708
			base_from_cache = 1;
1709
			break;
1710
		}
1711

1712
		if (do_check_packed_object_crc && p->index_version > 1) {
1713
			uint32_t pack_pos, index_pos;
1714
			off_t len;
1715

1716
			if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1717
				error("could not find object at offset %"PRIuMAX" in pack %s",
1718
				      (uintmax_t)obj_offset, p->pack_name);
1719
				data = NULL;
1720
				goto out;
1721
			}
1722

1723
			len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1724
			index_pos = pack_pos_to_index(p, pack_pos);
1725
			if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1726
				struct object_id oid;
1727
				nth_packed_object_id(&oid, p, index_pos);
1728
				error("bad packed object CRC for %s",
1729
				      oid_to_hex(&oid));
1730
				mark_bad_packed_object(p, &oid);
1731
				data = NULL;
1732
				goto out;
1733
			}
1734
		}
1735

1736
		type = unpack_object_header(p, &w_curs, &curpos, &size);
1737
		if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1738
			break;
1739

1740
		base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1741
		if (!base_offset) {
1742
			error("failed to validate delta base reference "
1743
			      "at offset %"PRIuMAX" from %s",
1744
			      (uintmax_t)curpos, p->pack_name);
1745
			/* bail to phase 2, in hopes of recovery */
1746
			data = NULL;
1747
			break;
1748
		}
1749

1750
		/* push object, proceed to base */
1751
		if (delta_stack_nr >= delta_stack_alloc
1752
		    && delta_stack == small_delta_stack) {
1753
			delta_stack_alloc = alloc_nr(delta_stack_nr);
1754
			ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1755
			COPY_ARRAY(delta_stack, small_delta_stack,
1756
				   delta_stack_nr);
1757
		} else {
1758
			ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1759
		}
1760
		i = delta_stack_nr++;
1761
		delta_stack[i].obj_offset = obj_offset;
1762
		delta_stack[i].curpos = curpos;
1763
		delta_stack[i].size = size;
1764

1765
		curpos = obj_offset = base_offset;
1766
	}
1767

1768
	/* PHASE 2: handle the base */
1769
	switch (type) {
1770
	case OBJ_OFS_DELTA:
1771
	case OBJ_REF_DELTA:
1772
		if (data)
1773
			BUG("unpack_entry: left loop at a valid delta");
1774
		break;
1775
	case OBJ_COMMIT:
1776
	case OBJ_TREE:
1777
	case OBJ_BLOB:
1778
	case OBJ_TAG:
1779
		if (!base_from_cache)
1780
			data = unpack_compressed_entry(p, &w_curs, curpos, size);
1781
		break;
1782
	default:
1783
		data = NULL;
1784
		error("unknown object type %i at offset %"PRIuMAX" in %s",
1785
		      type, (uintmax_t)obj_offset, p->pack_name);
1786
	}
1787

1788
	/* PHASE 3: apply deltas in order */
1789

1790
	/* invariants:
1791
	 *   'data' holds the base data, or NULL if there was corruption
1792
	 */
1793
	while (delta_stack_nr) {
1794
		void *delta_data;
1795
		void *base = data;
1796
		void *external_base = NULL;
1797
		unsigned long delta_size, base_size = size;
1798
		int i;
1799
		off_t base_obj_offset = obj_offset;
1800

1801
		data = NULL;
1802

1803
		if (!base) {
1804
			/*
1805
			 * We're probably in deep shit, but let's try to fetch
1806
			 * the required base anyway from another pack or loose.
1807
			 * This is costly but should happen only in the presence
1808
			 * of a corrupted pack, and is better than failing outright.
1809
			 */
1810
			uint32_t pos;
1811
			struct object_id base_oid;
1812
			if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1813
				struct object_info oi = OBJECT_INFO_INIT;
1814

1815
				nth_packed_object_id(&base_oid, p,
1816
						     pack_pos_to_index(p, pos));
1817
				error("failed to read delta base object %s"
1818
				      " at offset %"PRIuMAX" from %s",
1819
				      oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1820
				      p->pack_name);
1821
				mark_bad_packed_object(p, &base_oid);
1822

1823
				oi.typep = &type;
1824
				oi.sizep = &base_size;
1825
				oi.contentp = &base;
1826
				if (oid_object_info_extended(r, &base_oid, &oi, 0) < 0)
1827
					base = NULL;
1828

1829
				external_base = base;
1830
			}
1831
		}
1832

1833
		i = --delta_stack_nr;
1834
		obj_offset = delta_stack[i].obj_offset;
1835
		curpos = delta_stack[i].curpos;
1836
		delta_size = delta_stack[i].size;
1837

1838
		if (!base)
1839
			continue;
1840

1841
		delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1842

1843
		if (!delta_data) {
1844
			error("failed to unpack compressed delta "
1845
			      "at offset %"PRIuMAX" from %s",
1846
			      (uintmax_t)curpos, p->pack_name);
1847
			data = NULL;
1848
		} else {
1849
			data = patch_delta(base, base_size, delta_data,
1850
					   delta_size, &size);
1851

1852
			/*
1853
			 * We could not apply the delta; warn the user, but
1854
			 * keep going. Our failure will be noticed either in
1855
			 * the next iteration of the loop, or if this is the
1856
			 * final delta, in the caller when we return NULL.
1857
			 * Those code paths will take care of making a more
1858
			 * explicit warning and retrying with another copy of
1859
			 * the object.
1860
			 */
1861
			if (!data)
1862
				error("failed to apply delta");
1863
		}
1864

1865
		/*
1866
		 * We delay adding `base` to the cache until the end of the loop
1867
		 * because unpack_compressed_entry() momentarily releases the
1868
		 * obj_read_mutex, giving another thread the chance to access
1869
		 * the cache. Therefore, if `base` was already there, this other
1870
		 * thread could free() it (e.g. to make space for another entry)
1871
		 * before we are done using it.
1872
		 */
1873
		if (!external_base)
1874
			add_delta_base_cache(p, base_obj_offset, base, base_size, type);
1875

1876
		free(delta_data);
1877
		free(external_base);
1878
	}
1879

1880
	if (final_type)
1881
		*final_type = type;
1882
	if (final_size)
1883
		*final_size = size;
1884

1885
out:
1886
	unuse_pack(&w_curs);
1887

1888
	if (delta_stack != small_delta_stack)
1889
		free(delta_stack);
1890

1891
	return data;
1892
}
1893

1894
int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1895
{
1896
	const unsigned char *index_fanout = p->index_data;
1897
	const unsigned char *index_lookup;
1898
	const unsigned int hashsz = the_hash_algo->rawsz;
1899
	int index_lookup_width;
1900

1901
	if (!index_fanout)
1902
		BUG("bsearch_pack called without a valid pack-index");
1903

1904
	index_lookup = index_fanout + 4 * 256;
1905
	if (p->index_version == 1) {
1906
		index_lookup_width = hashsz + 4;
1907
		index_lookup += 4;
1908
	} else {
1909
		index_lookup_width = hashsz;
1910
		index_fanout += 8;
1911
		index_lookup += 8;
1912
	}
1913

1914
	return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1915
			    index_lookup, index_lookup_width, result);
1916
}
1917

1918
int nth_packed_object_id(struct object_id *oid,
1919
			 struct packed_git *p,
1920
			 uint32_t n)
1921
{
1922
	const unsigned char *index = p->index_data;
1923
	const unsigned int hashsz = the_hash_algo->rawsz;
1924
	if (!index) {
1925
		if (open_pack_index(p))
1926
			return -1;
1927
		index = p->index_data;
1928
	}
1929
	if (n >= p->num_objects)
1930
		return -1;
1931
	index += 4 * 256;
1932
	if (p->index_version == 1) {
1933
		oidread(oid, index + st_add(st_mult(hashsz + 4, n), 4),
1934
			the_repository->hash_algo);
1935
	} else {
1936
		index += 8;
1937
		oidread(oid, index + st_mult(hashsz, n),
1938
			the_repository->hash_algo);
1939
	}
1940
	return 0;
1941
}
1942

1943
void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1944
{
1945
	const unsigned char *ptr = vptr;
1946
	const unsigned char *start = p->index_data;
1947
	const unsigned char *end = start + p->index_size;
1948
	if (ptr < start)
1949
		die(_("offset before start of pack index for %s (corrupt index?)"),
1950
		    p->pack_name);
1951
	/* No need to check for underflow; .idx files must be at least 8 bytes */
1952
	if (ptr >= end - 8)
1953
		die(_("offset beyond end of pack index for %s (truncated index?)"),
1954
		    p->pack_name);
1955
}
1956

1957
off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1958
{
1959
	const unsigned char *index = p->index_data;
1960
	const unsigned int hashsz = the_hash_algo->rawsz;
1961
	index += 4 * 256;
1962
	if (p->index_version == 1) {
1963
		return ntohl(*((uint32_t *)(index + st_mult(hashsz + 4, n))));
1964
	} else {
1965
		uint32_t off;
1966
		index += st_add(8, st_mult(p->num_objects, hashsz + 4));
1967
		off = ntohl(*((uint32_t *)(index + st_mult(4, n))));
1968
		if (!(off & 0x80000000))
1969
			return off;
1970
		index += st_add(st_mult(p->num_objects, 4),
1971
				st_mult(off & 0x7fffffff, 8));
1972
		check_pack_index_ptr(p, index);
1973
		return get_be64(index);
1974
	}
1975
}
1976

1977
off_t find_pack_entry_one(const unsigned char *sha1,
1978
				  struct packed_git *p)
1979
{
1980
	const unsigned char *index = p->index_data;
1981
	struct object_id oid;
1982
	uint32_t result;
1983

1984
	if (!index) {
1985
		if (open_pack_index(p))
1986
			return 0;
1987
	}
1988

1989
	hashcpy(oid.hash, sha1, the_repository->hash_algo);
1990
	if (bsearch_pack(&oid, p, &result))
1991
		return nth_packed_object_offset(p, result);
1992
	return 0;
1993
}
1994

1995
int is_pack_valid(struct packed_git *p)
1996
{
1997
	/* An already open pack is known to be valid. */
1998
	if (p->pack_fd != -1)
1999
		return 1;
2000

2001
	/* If the pack has one window completely covering the
2002
	 * file size, the pack is known to be valid even if
2003
	 * the descriptor is not currently open.
2004
	 */
2005
	if (p->windows) {
2006
		struct pack_window *w = p->windows;
2007

2008
		if (!w->offset && w->len == p->pack_size)
2009
			return 1;
2010
	}
2011

2012
	/* Force the pack to open to prove its valid. */
2013
	return !open_packed_git(p);
2014
}
2015

2016
struct packed_git *find_sha1_pack(const unsigned char *sha1,
2017
				  struct packed_git *packs)
2018
{
2019
	struct packed_git *p;
2020

2021
	for (p = packs; p; p = p->next) {
2022
		if (find_pack_entry_one(sha1, p))
2023
			return p;
2024
	}
2025
	return NULL;
2026

2027
}
2028

2029
static int fill_pack_entry(const struct object_id *oid,
2030
			   struct pack_entry *e,
2031
			   struct packed_git *p)
2032
{
2033
	off_t offset;
2034

2035
	if (oidset_size(&p->bad_objects) &&
2036
	    oidset_contains(&p->bad_objects, oid))
2037
		return 0;
2038

2039
	offset = find_pack_entry_one(oid->hash, p);
2040
	if (!offset)
2041
		return 0;
2042

2043
	/*
2044
	 * We are about to tell the caller where they can locate the
2045
	 * requested object.  We better make sure the packfile is
2046
	 * still here and can be accessed before supplying that
2047
	 * answer, as it may have been deleted since the index was
2048
	 * loaded!
2049
	 */
2050
	if (!is_pack_valid(p))
2051
		return 0;
2052
	e->offset = offset;
2053
	e->p = p;
2054
	return 1;
2055
}
2056

2057
int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
2058
{
2059
	struct list_head *pos;
2060
	struct multi_pack_index *m;
2061

2062
	prepare_packed_git(r);
2063
	if (!r->objects->packed_git && !r->objects->multi_pack_index)
2064
		return 0;
2065

2066
	for (m = r->objects->multi_pack_index; m; m = m->next) {
2067
		if (fill_midx_entry(r, oid, e, m))
2068
			return 1;
2069
	}
2070

2071
	list_for_each(pos, &r->objects->packed_git_mru) {
2072
		struct packed_git *p = list_entry(pos, struct packed_git, mru);
2073
		if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
2074
			list_move(&p->mru, &r->objects->packed_git_mru);
2075
			return 1;
2076
		}
2077
	}
2078
	return 0;
2079
}
2080

2081
static void maybe_invalidate_kept_pack_cache(struct repository *r,
2082
					     unsigned flags)
2083
{
2084
	if (!r->objects->kept_pack_cache.packs)
2085
		return;
2086
	if (r->objects->kept_pack_cache.flags == flags)
2087
		return;
2088
	FREE_AND_NULL(r->objects->kept_pack_cache.packs);
2089
	r->objects->kept_pack_cache.flags = 0;
2090
}
2091

2092
static struct packed_git **kept_pack_cache(struct repository *r, unsigned flags)
2093
{
2094
	maybe_invalidate_kept_pack_cache(r, flags);
2095

2096
	if (!r->objects->kept_pack_cache.packs) {
2097
		struct packed_git **packs = NULL;
2098
		size_t nr = 0, alloc = 0;
2099
		struct packed_git *p;
2100

2101
		/*
2102
		 * We want "all" packs here, because we need to cover ones that
2103
		 * are used by a midx, as well. We need to look in every one of
2104
		 * them (instead of the midx itself) to cover duplicates. It's
2105
		 * possible that an object is found in two packs that the midx
2106
		 * covers, one kept and one not kept, but the midx returns only
2107
		 * the non-kept version.
2108
		 */
2109
		for (p = get_all_packs(r); p; p = p->next) {
2110
			if ((p->pack_keep && (flags & ON_DISK_KEEP_PACKS)) ||
2111
			    (p->pack_keep_in_core && (flags & IN_CORE_KEEP_PACKS))) {
2112
				ALLOC_GROW(packs, nr + 1, alloc);
2113
				packs[nr++] = p;
2114
			}
2115
		}
2116
		ALLOC_GROW(packs, nr + 1, alloc);
2117
		packs[nr] = NULL;
2118

2119
		r->objects->kept_pack_cache.packs = packs;
2120
		r->objects->kept_pack_cache.flags = flags;
2121
	}
2122

2123
	return r->objects->kept_pack_cache.packs;
2124
}
2125

2126
int find_kept_pack_entry(struct repository *r,
2127
			 const struct object_id *oid,
2128
			 unsigned flags,
2129
			 struct pack_entry *e)
2130
{
2131
	struct packed_git **cache;
2132

2133
	for (cache = kept_pack_cache(r, flags); *cache; cache++) {
2134
		struct packed_git *p = *cache;
2135
		if (fill_pack_entry(oid, e, p))
2136
			return 1;
2137
	}
2138

2139
	return 0;
2140
}
2141

2142
int has_object_pack(const struct object_id *oid)
2143
{
2144
	struct pack_entry e;
2145
	return find_pack_entry(the_repository, oid, &e);
2146
}
2147

2148
int has_object_kept_pack(const struct object_id *oid, unsigned flags)
2149
{
2150
	struct pack_entry e;
2151
	return find_kept_pack_entry(the_repository, oid, flags, &e);
2152
}
2153

2154
int has_pack_index(const unsigned char *sha1)
2155
{
2156
	struct stat st;
2157
	if (stat(sha1_pack_index_name(sha1), &st))
2158
		return 0;
2159
	return 1;
2160
}
2161

2162
int for_each_object_in_pack(struct packed_git *p,
2163
			    each_packed_object_fn cb, void *data,
2164
			    enum for_each_object_flags flags)
2165
{
2166
	uint32_t i;
2167
	int r = 0;
2168

2169
	if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2170
		if (load_pack_revindex(the_repository, p))
2171
			return -1;
2172
	}
2173

2174
	for (i = 0; i < p->num_objects; i++) {
2175
		uint32_t index_pos;
2176
		struct object_id oid;
2177

2178
		/*
2179
		 * We are iterating "i" from 0 up to num_objects, but its
2180
		 * meaning may be different, depending on the requested output
2181
		 * order:
2182
		 *
2183
		 *   - in object-name order, it is the same as the index order
2184
		 *     used by nth_packed_object_id(), so we can pass it
2185
		 *     directly
2186
		 *
2187
		 *   - in pack-order, it is pack position, which we must
2188
		 *     convert to an index position in order to get the oid.
2189
		 */
2190
		if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2191
			index_pos = pack_pos_to_index(p, i);
2192
		else
2193
			index_pos = i;
2194

2195
		if (nth_packed_object_id(&oid, p, index_pos) < 0)
2196
			return error("unable to get sha1 of object %u in %s",
2197
				     index_pos, p->pack_name);
2198

2199
		r = cb(&oid, p, index_pos, data);
2200
		if (r)
2201
			break;
2202
	}
2203
	return r;
2204
}
2205

2206
int for_each_packed_object(each_packed_object_fn cb, void *data,
2207
			   enum for_each_object_flags flags)
2208
{
2209
	struct packed_git *p;
2210
	int r = 0;
2211
	int pack_errors = 0;
2212

2213
	prepare_packed_git(the_repository);
2214
	for (p = get_all_packs(the_repository); p; p = p->next) {
2215
		if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2216
			continue;
2217
		if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2218
		    !p->pack_promisor)
2219
			continue;
2220
		if ((flags & FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS) &&
2221
		    p->pack_keep_in_core)
2222
			continue;
2223
		if ((flags & FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS) &&
2224
		    p->pack_keep)
2225
			continue;
2226
		if (open_pack_index(p)) {
2227
			pack_errors = 1;
2228
			continue;
2229
		}
2230
		r = for_each_object_in_pack(p, cb, data, flags);
2231
		if (r)
2232
			break;
2233
	}
2234
	return r ? r : pack_errors;
2235
}
2236

2237
static int add_promisor_object(const struct object_id *oid,
2238
			       struct packed_git *pack UNUSED,
2239
			       uint32_t pos UNUSED,
2240
			       void *set_)
2241
{
2242
	struct oidset *set = set_;
2243
	struct object *obj;
2244
	int we_parsed_object;
2245

2246
	obj = lookup_object(the_repository, oid);
2247
	if (obj && obj->parsed) {
2248
		we_parsed_object = 0;
2249
	} else {
2250
		we_parsed_object = 1;
2251
		obj = parse_object(the_repository, oid);
2252
	}
2253

2254
	if (!obj)
2255
		return 1;
2256

2257
	oidset_insert(set, oid);
2258

2259
	/*
2260
	 * If this is a tree, commit, or tag, the objects it refers
2261
	 * to are also promisor objects. (Blobs refer to no objects->)
2262
	 */
2263
	if (obj->type == OBJ_TREE) {
2264
		struct tree *tree = (struct tree *)obj;
2265
		struct tree_desc desc;
2266
		struct name_entry entry;
2267
		if (init_tree_desc_gently(&desc, &tree->object.oid,
2268
					  tree->buffer, tree->size, 0))
2269
			/*
2270
			 * Error messages are given when packs are
2271
			 * verified, so do not print any here.
2272
			 */
2273
			return 0;
2274
		while (tree_entry_gently(&desc, &entry))
2275
			oidset_insert(set, &entry.oid);
2276
		if (we_parsed_object)
2277
			free_tree_buffer(tree);
2278
	} else if (obj->type == OBJ_COMMIT) {
2279
		struct commit *commit = (struct commit *) obj;
2280
		struct commit_list *parents = commit->parents;
2281

2282
		oidset_insert(set, get_commit_tree_oid(commit));
2283
		for (; parents; parents = parents->next)
2284
			oidset_insert(set, &parents->item->object.oid);
2285
	} else if (obj->type == OBJ_TAG) {
2286
		struct tag *tag = (struct tag *) obj;
2287
		oidset_insert(set, get_tagged_oid(tag));
2288
	}
2289
	return 0;
2290
}
2291

2292
int is_promisor_object(const struct object_id *oid)
2293
{
2294
	static struct oidset promisor_objects;
2295
	static int promisor_objects_prepared;
2296

2297
	if (!promisor_objects_prepared) {
2298
		if (repo_has_promisor_remote(the_repository)) {
2299
			for_each_packed_object(add_promisor_object,
2300
					       &promisor_objects,
2301
					       FOR_EACH_OBJECT_PROMISOR_ONLY |
2302
					       FOR_EACH_OBJECT_PACK_ORDER);
2303
		}
2304
		promisor_objects_prepared = 1;
2305
	}
2306
	return oidset_contains(&promisor_objects, oid);
2307
}
2308

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.