]> git.proxmox.com Git - libgit2.git/blame - src/pack.c
New upstream version 0.28.4+dfsg.1
[libgit2.git] / src / pack.c
CommitLineData
7d0cdf82 1/*
359fc2d2 2 * Copyright (C) the libgit2 contributors. All rights reserved.
7d0cdf82 3 *
bb742ede
VM
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
7d0cdf82
CMN
6 */
7
7d0cdf82 8#include "pack.h"
eae0bfdc
PP
9
10#include "odb.h"
6a2d2f8a 11#include "delta.h"
a070f152 12#include "sha1_lookup.h"
a15c550d
VM
13#include "mwindow.h"
14#include "fileops.h"
b7f167da 15#include "oid.h"
7d0cdf82 16
0c3bae62 17#include <zlib.h>
7d0cdf82 18
a070f152 19static int packfile_open(struct git_pack_file *p);
e1de726c 20static git_off_t nth_packed_object_offset(const struct git_pack_file *p, uint32_t n);
b644e223 21static int packfile_unpack_compressed(
a070f152
CMN
22 git_rawobj *obj,
23 struct git_pack_file *p,
24 git_mwindow **w_curs,
e1de726c 25 git_off_t *curpos,
a070f152 26 size_t size,
ac3d33df 27 git_object_t type);
a070f152
CMN
28
29/* Can find the offset of an object given
30 * a prefix of an identifier.
904b67e6 31 * Throws GIT_EAMBIGUOUSOIDPREFIX if short oid
a070f152
CMN
32 * is ambiguous within the pack.
33 * This method assumes that len is between
34 * GIT_OID_MINPREFIXLEN and GIT_OID_HEXSZ.
35 */
36static int pack_entry_find_offset(
e1de726c 37 git_off_t *offset_out,
a070f152
CMN
38 git_oid *found_oid,
39 struct git_pack_file *p,
40 const git_oid *short_oid,
b8457baa 41 size_t len);
a070f152 42
e1de726c
RB
43static int packfile_error(const char *message)
44{
ac3d33df 45 git_error_set(GIT_ERROR_ODB, "invalid pack file - %s", message);
e1de726c
RB
46 return -1;
47}
48
c8f79c2b
CMN
49/********************
50 * Delta base cache
51 ********************/
c0f4a011 52
525d961c 53static git_pack_cache_entry *new_cache_object(git_rawobj *source)
c0f4a011 54{
c8f79c2b 55 git_pack_cache_entry *e = git__calloc(1, sizeof(git_pack_cache_entry));
c0f4a011
CMN
56 if (!e)
57 return NULL;
58
8588cb0c 59 git_atomic_inc(&e->refcount);
c0f4a011
CMN
60 memcpy(&e->raw, source, sizeof(git_rawobj));
61
62 return e;
63}
64
65static void free_cache_object(void *o)
66{
67 git_pack_cache_entry *e = (git_pack_cache_entry *)o;
68
69 if (e != NULL) {
0ed75620 70 assert(e->refcount.val == 0);
c0f4a011
CMN
71 git__free(e->raw.data);
72 git__free(e);
73 }
74}
75
c8f79c2b
CMN
76static void cache_free(git_pack_cache *cache)
77{
9694d9ba 78 git_pack_cache_entry *entry;
c8f79c2b
CMN
79
80 if (cache->entries) {
9694d9ba
PS
81 git_offmap_foreach_value(cache->entries, entry, {
82 free_cache_object(entry);
83 });
c8f79c2b
CMN
84
85 git_offmap_free(cache->entries);
649214be 86 cache->entries = NULL;
c8f79c2b
CMN
87 }
88}
89
90static int cache_init(git_pack_cache *cache)
91{
c8f79c2b 92 cache->entries = git_offmap_alloc();
ac3d33df 93 GIT_ERROR_CHECK_ALLOC(cache->entries);
f658dc43 94
c8f79c2b 95 cache->memory_limit = GIT_PACK_CACHE_MEMORY_LIMIT;
1a42dd17
RB
96
97 if (git_mutex_init(&cache->lock)) {
ac3d33df 98 git_error_set(GIT_ERROR_OS, "failed to initialize pack cache mutex");
1a42dd17
RB
99
100 git__free(cache->entries);
101 cache->entries = NULL;
102
103 return -1;
104 }
c8f79c2b
CMN
105
106 return 0;
107}
108
09e29e47 109static git_pack_cache_entry *cache_get(git_pack_cache *cache, git_off_t offset)
c8f79c2b 110{
c8f79c2b 111 git_pack_cache_entry *entry = NULL;
ac3d33df 112 size_t k;
c8f79c2b 113
09e29e47
CMN
114 if (git_mutex_lock(&cache->lock) < 0)
115 return NULL;
116
a853c527 117 k = git_offmap_lookup_index(cache->entries, offset);
64e46dc3 118 if (git_offmap_valid_index(cache->entries, k)) { /* found it */
cb18386f 119 entry = git_offmap_value_at(cache->entries, k);
c8f79c2b 120 git_atomic_inc(&entry->refcount);
0ed75620 121 entry->last_usage = cache->use_ctr++;
c8f79c2b
CMN
122 }
123 git_mutex_unlock(&cache->lock);
124
125 return entry;
126}
127
0ed75620
CMN
128/* Run with the cache lock held */
129static void free_lowest_entry(git_pack_cache *cache)
130{
685f2251 131 git_off_t offset;
ed6648ba 132 git_pack_cache_entry *entry;
ed6648ba 133
685f2251 134 git_offmap_foreach(cache->entries, offset, entry, {
9c62aaab
CMN
135 if (entry && entry->refcount.val == 0) {
136 cache->memory_used -= entry->raw.len;
685f2251 137 git_offmap_delete(cache->entries, offset);
9c62aaab 138 free_cache_object(entry);
ed6648ba 139 }
9694d9ba 140 });
0ed75620
CMN
141}
142
8588cb0c
JH
143static int cache_add(
144 git_pack_cache_entry **cached_out,
145 git_pack_cache *cache,
146 git_rawobj *base,
147 git_off_t offset)
c8f79c2b
CMN
148{
149 git_pack_cache_entry *entry;
150 int error, exists = 0;
ac3d33df 151 size_t k;
c8f79c2b 152
0ed75620
CMN
153 if (base->len > GIT_PACK_CACHE_SIZE_LIMIT)
154 return -1;
155
c8f79c2b
CMN
156 entry = new_cache_object(base);
157 if (entry) {
09e29e47 158 if (git_mutex_lock(&cache->lock) < 0) {
ac3d33df 159 git_error_set(GIT_ERROR_OS, "failed to lock cache");
6f73e026 160 git__free(entry);
09e29e47
CMN
161 return -1;
162 }
c8f79c2b 163 /* Add it to the cache if nobody else has */
036daa59 164 exists = git_offmap_exists(cache->entries, offset);
c8f79c2b 165 if (!exists) {
0ed75620
CMN
166 while (cache->memory_used + base->len > cache->memory_limit)
167 free_lowest_entry(cache);
168
f31cb45a 169 k = git_offmap_put(cache->entries, offset, &error);
c8f79c2b 170 assert(error != 0);
85d2748c 171 git_offmap_set_value_at(cache->entries, k, entry);
0ed75620 172 cache->memory_used += entry->raw.len;
8588cb0c
JH
173
174 *cached_out = entry;
c8f79c2b
CMN
175 }
176 git_mutex_unlock(&cache->lock);
177 /* Somebody beat us to adding it into the cache */
178 if (exists) {
179 git__free(entry);
180 return -1;
181 }
182 }
183
184 return 0;
185}
186
a070f152
CMN
187/***********************************************************
188 *
189 * PACK INDEX METHODS
190 *
191 ***********************************************************/
192
193static void pack_index_free(struct git_pack_file *p)
194{
60ecdf59
DMB
195 if (p->oids) {
196 git__free(p->oids);
197 p->oids = NULL;
198 }
a070f152
CMN
199 if (p->index_map.data) {
200 git_futils_mmap_free(&p->index_map);
201 p->index_map.data = NULL;
202 }
203}
204
87d9869f 205static int pack_index_check(const char *path, struct git_pack_file *p)
a070f152
CMN
206{
207 struct git_pack_idx_header *hdr;
208 uint32_t version, nr, i, *index;
a070f152
CMN
209 void *idx_map;
210 size_t idx_size;
a070f152 211 struct stat st;
a070f152 212 int error;
e1de726c
RB
213 /* TODO: properly open the file without access time using O_NOATIME */
214 git_file fd = git_futils_open_ro(path);
a070f152 215 if (fd < 0)
e1de726c 216 return fd;
a070f152 217
9d2f841a
RB
218 if (p_fstat(fd, &st) < 0) {
219 p_close(fd);
ac3d33df 220 git_error_set(GIT_ERROR_OS, "unable to stat pack index '%s'", path);
9d2f841a
RB
221 return -1;
222 }
223
224 if (!S_ISREG(st.st_mode) ||
e1de726c
RB
225 !git__is_sizet(st.st_size) ||
226 (idx_size = (size_t)st.st_size) < 4 * 256 + 20 + 20)
227 {
a070f152 228 p_close(fd);
ac3d33df 229 git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path);
e1de726c 230 return -1;
a070f152
CMN
231 }
232
233 error = git_futils_mmap_ro(&p->index_map, fd, 0, idx_size);
e1de726c 234
a070f152
CMN
235 p_close(fd);
236
e1de726c
RB
237 if (error < 0)
238 return error;
a070f152
CMN
239
240 hdr = idx_map = p->index_map.data;
241
242 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
243 version = ntohl(hdr->idx_version);
244
245 if (version < 2 || version > 2) {
246 git_futils_mmap_free(&p->index_map);
e1de726c 247 return packfile_error("unsupported index version");
a070f152
CMN
248 }
249
250 } else
251 version = 1;
252
253 nr = 0;
254 index = idx_map;
255
256 if (version > 1)
87d9869f 257 index += 2; /* skip index header */
a070f152
CMN
258
259 for (i = 0; i < 256; i++) {
260 uint32_t n = ntohl(index[i]);
261 if (n < nr) {
262 git_futils_mmap_free(&p->index_map);
e1de726c 263 return packfile_error("index is non-monotonic");
a070f152
CMN
264 }
265 nr = n;
266 }
267
268 if (version == 1) {
269 /*
270 * Total size:
87d9869f
VM
271 * - 256 index entries 4 bytes each
272 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
273 * - 20-byte SHA1 of the packfile
274 * - 20-byte SHA1 file checksum
a070f152
CMN
275 */
276 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
277 git_futils_mmap_free(&p->index_map);
e1de726c 278 return packfile_error("index is corrupted");
a070f152
CMN
279 }
280 } else if (version == 2) {
281 /*
282 * Minimum size:
87d9869f
VM
283 * - 8 bytes of header
284 * - 256 index entries 4 bytes each
285 * - 20-byte sha1 entry * nr
286 * - 4-byte crc entry * nr
287 * - 4-byte offset entry * nr
288 * - 20-byte SHA1 of the packfile
289 * - 20-byte SHA1 file checksum
a070f152
CMN
290 * And after the 4-byte offset table might be a
291 * variable sized table containing 8-byte entries
292 * for offsets larger than 2^31.
293 */
294 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
295 unsigned long max_size = min_size;
296
297 if (nr)
298 max_size += (nr - 1)*8;
299
300 if (idx_size < min_size || idx_size > max_size) {
301 git_futils_mmap_free(&p->index_map);
e1de726c 302 return packfile_error("wrong index size");
a070f152 303 }
a070f152
CMN
304 }
305
a070f152 306 p->num_objects = nr;
0ddfcb40 307 p->index_version = version;
e1de726c 308 return 0;
a070f152
CMN
309}
310
311static int pack_index_open(struct git_pack_file *p)
312{
24c70804 313 int error = 0;
878293f7 314 size_t name_len;
a693b873 315 git_buf idx_name;
24c70804 316
0ddfcb40 317 if (p->index_version > -1)
53607868 318 return 0;
a070f152 319
24c70804
RB
320 name_len = strlen(p->pack_name);
321 assert(name_len > strlen(".pack")); /* checked by git_pack_file alloc */
e1de726c 322
a693b873
PS
323 if (git_buf_init(&idx_name, name_len) < 0)
324 return -1;
325
878293f7
CMN
326 git_buf_put(&idx_name, p->pack_name, name_len - strlen(".pack"));
327 git_buf_puts(&idx_name, ".idx");
328 if (git_buf_oom(&idx_name)) {
ac3d33df 329 git_buf_dispose(&idx_name);
53607868 330 return -1;
878293f7 331 }
a070f152 332
050af8bb 333 if ((error = git_mutex_lock(&p->lock)) < 0) {
ac3d33df 334 git_buf_dispose(&idx_name);
53607868 335 return error;
050af8bb 336 }
53607868 337
0ddfcb40 338 if (p->index_version == -1)
878293f7 339 error = pack_index_check(idx_name.ptr, p);
24c70804 340
ac3d33df 341 git_buf_dispose(&idx_name);
a070f152 342
24c70804
RB
343 git_mutex_unlock(&p->lock);
344
e1de726c 345 return error;
a070f152
CMN
346}
347
348static unsigned char *pack_window_open(
349 struct git_pack_file *p,
7d0cdf82 350 git_mwindow **w_cursor,
e1de726c 351 git_off_t offset,
7d0cdf82
CMN
352 unsigned int *left)
353{
e1de726c 354 if (p->mwf.fd == -1 && packfile_open(p) < 0)
7d0cdf82
CMN
355 return NULL;
356
357 /* Since packfiles end in a hash of their content and it's
358 * pointless to ask for an offset into the middle of that
359 * hash, and the pack_window_contains function above wouldn't match
360 * don't allow an offset too close to the end of the file.
6d97beb9
CMN
361 *
362 * Don't allow a negative offset, as that means we've wrapped
363 * around.
7d0cdf82
CMN
364 */
365 if (offset > (p->mwf.size - 20))
366 return NULL;
6d97beb9
CMN
367 if (offset < 0)
368 return NULL;
7d0cdf82
CMN
369
370 return git_mwindow_open(&p->mwf, w_cursor, offset, 20, left);
371 }
372
51e82492
CMN
373/*
374 * The per-object header is a pretty dense thing, which is
375 * - first byte: low four bits are "size",
376 * then three bits of "type",
377 * with the high bit being "size continues".
378 * - each byte afterwards: low seven bits are size continuation,
379 * with the high bit being "size continues"
380 */
ac3d33df 381size_t git_packfile__object_header(unsigned char *hdr, size_t size, git_object_t type)
51e82492
CMN
382{
383 unsigned char *hdr_base;
384 unsigned char c;
385
ac3d33df 386 assert(type >= GIT_OBJECT_COMMIT && type <= GIT_OBJECT_REF_DELTA);
51e82492
CMN
387
388 /* TODO: add support for chunked objects; see git.git 6c0d19b1 */
389
390 c = (unsigned char)((type << 4) | (size & 15));
391 size >>= 4;
392 hdr_base = hdr;
393
394 while (size) {
395 *hdr++ = c | 0x80;
396 c = size & 0x7f;
397 size >>= 7;
398 }
399 *hdr++ = c;
400
51a3dfb5 401 return (hdr - hdr_base);
51e82492
CMN
402}
403
404
45d773ef
CMN
405static int packfile_unpack_header1(
406 unsigned long *usedp,
7d0cdf82 407 size_t *sizep,
ac3d33df 408 git_object_t *type,
7d0cdf82
CMN
409 const unsigned char *buf,
410 unsigned long len)
411{
412 unsigned shift;
413 unsigned long size, c;
414 unsigned long used = 0;
2aeadb9c 415
7d0cdf82
CMN
416 c = buf[used++];
417 *type = (c >> 4) & 7;
418 size = c & 15;
419 shift = 4;
420 while (c & 0x80) {
ec7e680c 421 if (len <= used) {
ac3d33df 422 git_error_set(GIT_ERROR_ODB, "buffer too small");
904b67e6 423 return GIT_EBUFS;
ec7e680c 424 }
45d773ef
CMN
425
426 if (bitsizeof(long) <= shift) {
427 *usedp = 0;
ac3d33df 428 git_error_set(GIT_ERROR_ODB, "packfile corrupted");
45d773ef
CMN
429 return -1;
430 }
7d0cdf82
CMN
431
432 c = buf[used++];
433 size += (c & 0x7f) << shift;
434 shift += 7;
435 }
436
437 *sizep = (size_t)size;
45d773ef
CMN
438 *usedp = used;
439 return 0;
7d0cdf82
CMN
440}
441
442int git_packfile_unpack_header(
443 size_t *size_p,
ac3d33df 444 git_object_t *type_p,
7d0cdf82
CMN
445 git_mwindow_file *mwf,
446 git_mwindow **w_curs,
e1de726c 447 git_off_t *curpos)
7d0cdf82
CMN
448{
449 unsigned char *base;
450 unsigned int left;
451 unsigned long used;
45d773ef 452 int ret;
7d0cdf82
CMN
453
454 /* pack_window_open() assures us we have [base, base + 20) available
87d9869f
VM
455 * as a range that we can look at at. (Its actually the hash
456 * size that is assured.) With our object header encoding
7d0cdf82
CMN
457 * the maximum deflated object size is 2^137, which is just
458 * insane, so we know won't exceed what we have been given.
459 */
24c70804 460/* base = pack_window_open(p, w_curs, *curpos, &left); */
7d0cdf82
CMN
461 base = git_mwindow_open(mwf, w_curs, *curpos, 20, &left);
462 if (base == NULL)
904b67e6 463 return GIT_EBUFS;
2aeadb9c 464
9d2f841a 465 ret = packfile_unpack_header1(&used, size_p, type_p, base, left);
45d773ef 466 git_mwindow_close(w_curs);
904b67e6 467 if (ret == GIT_EBUFS)
45d773ef
CMN
468 return ret;
469 else if (ret < 0)
e1de726c 470 return packfile_error("header length is zero");
7d0cdf82
CMN
471
472 *curpos += used;
e1de726c 473 return 0;
7d0cdf82
CMN
474}
475
44f9f547
DMB
476int git_packfile_resolve_header(
477 size_t *size_p,
ac3d33df 478 git_object_t *type_p,
44f9f547
DMB
479 struct git_pack_file *p,
480 git_off_t offset)
481{
482 git_mwindow *w_curs = NULL;
483 git_off_t curpos = offset;
484 size_t size;
ac3d33df 485 git_object_t type;
44f9f547
DMB
486 git_off_t base_offset;
487 int error;
488
489 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
44f9f547
DMB
490 if (error < 0)
491 return error;
492
ac3d33df 493 if (type == GIT_OBJECT_OFS_DELTA || type == GIT_OBJECT_REF_DELTA) {
44f9f547 494 size_t base_size;
a97b769a
CMN
495 git_packfile_stream stream;
496
44f9f547
DMB
497 base_offset = get_delta_base(p, &w_curs, &curpos, type, offset);
498 git_mwindow_close(&w_curs);
a97b769a 499 if ((error = git_packfile_stream_open(&stream, p, curpos)) < 0)
44f9f547 500 return error;
6a2d2f8a 501 error = git_delta_read_header_fromstream(&base_size, size_p, &stream);
ac3d33df 502 git_packfile_stream_dispose(&stream);
44f9f547
DMB
503 if (error < 0)
504 return error;
34b32053 505 } else {
44f9f547 506 *size_p = size;
34b32053
PS
507 base_offset = 0;
508 }
44f9f547 509
ac3d33df 510 while (type == GIT_OBJECT_OFS_DELTA || type == GIT_OBJECT_REF_DELTA) {
44f9f547
DMB
511 curpos = base_offset;
512 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
44f9f547
DMB
513 if (error < 0)
514 return error;
ac3d33df 515 if (type != GIT_OBJECT_OFS_DELTA && type != GIT_OBJECT_REF_DELTA)
44f9f547
DMB
516 break;
517 base_offset = get_delta_base(p, &w_curs, &curpos, type, base_offset);
518 git_mwindow_close(&w_curs);
519 }
520 *type_p = type;
521
522 return error;
523}
524
15bcced2
CMN
525#define SMALL_STACK_SIZE 64
526
a3ffbf23
CMN
527/**
528 * Generate the chain of dependencies which we need to get to the
529 * object at `off`. `chain` is used a stack, popping gives the right
530 * order to apply deltas on. If an object is found in the pack's base
531 * cache, we stop calculating there.
532 */
15bcced2
CMN
533static int pack_dependency_chain(git_dependency_chain *chain_out,
534 git_pack_cache_entry **cached_out, git_off_t *cached_off,
535 struct pack_chain_elem *small_stack, size_t *stack_sz,
536 struct git_pack_file *p, git_off_t obj_offset)
a3ffbf23
CMN
537{
538 git_dependency_chain chain = GIT_ARRAY_INIT;
539 git_mwindow *w_curs = NULL;
540 git_off_t curpos = obj_offset, base_offset;
15bcced2
CMN
541 int error = 0, use_heap = 0;
542 size_t size, elem_pos;
ac3d33df 543 git_object_t type;
a3ffbf23 544
15bcced2 545 elem_pos = 0;
a3ffbf23
CMN
546 while (true) {
547 struct pack_chain_elem *elem;
548 git_pack_cache_entry *cached = NULL;
549
550 /* if we have a base cached, we can stop here instead */
551 if ((cached = cache_get(&p->bases, obj_offset)) != NULL) {
552 *cached_out = cached;
553 *cached_off = obj_offset;
554 break;
555 }
556
15bcced2
CMN
557 /* if we run out of space on the small stack, use the array */
558 if (elem_pos == SMALL_STACK_SIZE) {
559 git_array_init_to_size(chain, elem_pos);
ac3d33df 560 GIT_ERROR_CHECK_ARRAY(chain);
15bcced2
CMN
561 memcpy(chain.ptr, small_stack, elem_pos * sizeof(struct pack_chain_elem));
562 chain.size = elem_pos;
563 use_heap = 1;
564 }
565
a3ffbf23 566 curpos = obj_offset;
15bcced2
CMN
567 if (!use_heap) {
568 elem = &small_stack[elem_pos];
569 } else {
570 elem = git_array_alloc(chain);
571 if (!elem) {
572 error = -1;
573 goto on_error;
574 }
a3ffbf23
CMN
575 }
576
577 elem->base_key = obj_offset;
578
579 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
a3ffbf23
CMN
580
581 if (error < 0)
582 goto on_error;
583
584 elem->offset = curpos;
585 elem->size = size;
586 elem->type = type;
587 elem->base_key = obj_offset;
588
ac3d33df 589 if (type != GIT_OBJECT_OFS_DELTA && type != GIT_OBJECT_REF_DELTA)
a3ffbf23
CMN
590 break;
591
592 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
593 git_mwindow_close(&w_curs);
594
595 if (base_offset == 0) {
596 error = packfile_error("delta offset is zero");
597 goto on_error;
598 }
599 if (base_offset < 0) { /* must actually be an error code */
600 error = (int)base_offset;
601 goto on_error;
602 }
603
604 /* we need to pass the pos *after* the delta-base bit */
605 elem->offset = curpos;
606
607 /* go through the loop again, but with the new object */
608 obj_offset = base_offset;
15bcced2 609 elem_pos++;
a3ffbf23
CMN
610 }
611
ac3d33df 612
15bcced2 613 *stack_sz = elem_pos + 1;
a3ffbf23
CMN
614 *chain_out = chain;
615 return error;
616
617on_error:
618 git_array_clear(chain);
619 return error;
620}
621
a070f152 622int git_packfile_unpack(
e1de726c
RB
623 git_rawobj *obj,
624 struct git_pack_file *p,
625 git_off_t *obj_offset)
7d0cdf82
CMN
626{
627 git_mwindow *w_curs = NULL;
e1de726c 628 git_off_t curpos = *obj_offset;
a332e91c
CMN
629 int error, free_base = 0;
630 git_dependency_chain chain = GIT_ARRAY_INIT;
15bcced2 631 struct pack_chain_elem *elem = NULL, *stack;
a332e91c 632 git_pack_cache_entry *cached = NULL;
15bcced2 633 struct pack_chain_elem small_stack[SMALL_STACK_SIZE];
f1453c59 634 size_t stack_size = 0, elem_pos, alloclen;
ac3d33df 635 git_object_t base_type;
7d0cdf82
CMN
636
637 /*
638 * TODO: optionally check the CRC on the packfile
639 */
640
15bcced2 641 error = pack_dependency_chain(&chain, &cached, obj_offset, small_stack, &stack_size, p, *obj_offset);
2acdf4b8
CMN
642 if (error < 0)
643 return error;
644
7d0cdf82
CMN
645 obj->data = NULL;
646 obj->len = 0;
ac3d33df 647 obj->type = GIT_OBJECT_INVALID;
7d0cdf82 648
15bcced2
CMN
649 /* let's point to the right stack */
650 stack = chain.ptr ? chain.ptr : small_stack;
651
652 elem_pos = stack_size;
a3ffbf23 653 if (cached) {
a332e91c 654 memcpy(obj, &cached->raw, sizeof(git_rawobj));
a3ffbf23 655 base_type = obj->type;
15bcced2 656 elem_pos--; /* stack_size includes the base, which isn't actually there */
a3ffbf23 657 } else {
15bcced2 658 elem = &stack[--elem_pos];
a3ffbf23 659 base_type = elem->type;
a332e91c 660 }
45d773ef 661
9dbd150f 662 switch (base_type) {
ac3d33df
JK
663 case GIT_OBJECT_COMMIT:
664 case GIT_OBJECT_TREE:
665 case GIT_OBJECT_BLOB:
666 case GIT_OBJECT_TAG:
a3ffbf23 667 if (!cached) {
9dbd150f
CMN
668 curpos = elem->offset;
669 error = packfile_unpack_compressed(obj, p, &w_curs, &curpos, elem->size, elem->type);
670 git_mwindow_close(&w_curs);
a3ffbf23 671 base_type = elem->type;
9dbd150f
CMN
672 }
673 if (error < 0)
674 goto cleanup;
675 break;
ac3d33df
JK
676 case GIT_OBJECT_OFS_DELTA:
677 case GIT_OBJECT_REF_DELTA:
9dbd150f
CMN
678 error = packfile_error("dependency chain ends in a delta");
679 goto cleanup;
680 default:
681 error = packfile_error("invalid packfile type in header");
682 goto cleanup;
683 }
684
a332e91c 685 /*
c968ce2c 686 * Finding the object we want a cached base element is
a332e91c
CMN
687 * problematic, as we need to make sure we don't accidentally
688 * give the caller the cached object, which it would then feel
689 * free to free, so we need to copy the data.
690 */
15bcced2 691 if (cached && stack_size == 1) {
a332e91c 692 void *data = obj->data;
392702ee 693
ac3d33df 694 GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, obj->len, 1);
f1453c59 695 obj->data = git__malloc(alloclen);
ac3d33df 696 GIT_ERROR_CHECK_ALLOC(obj->data);
392702ee 697
a332e91c
CMN
698 memcpy(obj->data, data, obj->len + 1);
699 git_atomic_dec(&cached->refcount);
700 goto cleanup;
701 }
702
2acdf4b8 703 /* we now apply each consecutive delta until we run out */
15bcced2 704 while (elem_pos > 0 && !error) {
2acdf4b8
CMN
705 git_rawobj base, delta;
706
c968ce2c
CMN
707 /*
708 * We can now try to add the base to the cache, as
709 * long as it's not already the cached one.
710 */
711 if (!cached)
8588cb0c 712 free_base = !!cache_add(&cached, &p->bases, obj, elem->base_key);
c968ce2c 713
15bcced2 714 elem = &stack[elem_pos - 1];
2acdf4b8
CMN
715 curpos = elem->offset;
716 error = packfile_unpack_compressed(&delta, p, &w_curs, &curpos, elem->size, elem->type);
717 git_mwindow_close(&w_curs);
718
eae0bfdc
PP
719 if (error < 0) {
720 /* We have transferred ownership of the data to the cache. */
721 obj->data = NULL;
2acdf4b8 722 break;
eae0bfdc 723 }
2acdf4b8
CMN
724
725 /* the current object becomes the new base, on which we apply the delta */
726 base = *obj;
727 obj->data = NULL;
728 obj->len = 0;
ac3d33df 729 obj->type = GIT_OBJECT_INVALID;
2acdf4b8 730
6a2d2f8a 731 error = git_delta_apply(&obj->data, &obj->len, base.data, base.len, delta.data, delta.len);
a332e91c 732 obj->type = base_type;
6a2d2f8a 733
a332e91c
CMN
734 /*
735 * We usually don't want to free the base at this
736 * point, as we put it into the cache in the previous
737 * iteration. free_base lets us know that we got the
738 * base object directly from the packfile, so we can free it.
739 */
2acdf4b8 740 git__free(delta.data);
a332e91c
CMN
741 if (free_base) {
742 free_base = 0;
743 git__free(base.data);
744 }
745
746 if (cached) {
747 git_atomic_dec(&cached->refcount);
748 cached = NULL;
749 }
2acdf4b8
CMN
750
751 if (error < 0)
752 break;
7d0cdf82 753
15bcced2 754 elem_pos--;
7d0cdf82
CMN
755 }
756
2acdf4b8 757cleanup:
ff5eea06 758 if (error < 0) {
a332e91c 759 git__free(obj->data);
ff5eea06
PS
760 if (cached)
761 git_atomic_dec(&cached->refcount);
762 }
a332e91c 763
a3ffbf23 764 if (elem)
b3d3459f 765 *obj_offset = curpos;
a332e91c 766
2acdf4b8 767 git_array_clear(chain);
e1de726c 768 return error;
7d0cdf82
CMN
769}
770
282283ac
RB
771static void *use_git_alloc(void *opaq, unsigned int count, unsigned int size)
772{
773 GIT_UNUSED(opaq);
774 return git__calloc(count, size);
775}
776
777static void use_git_free(void *opaq, void *ptr)
778{
779 GIT_UNUSED(opaq);
780 git__free(ptr);
781}
782
46635339
CMN
783int git_packfile_stream_open(git_packfile_stream *obj, struct git_pack_file *p, git_off_t curpos)
784{
785 int st;
786
787 memset(obj, 0, sizeof(git_packfile_stream));
788 obj->curpos = curpos;
789 obj->p = p;
790 obj->zstream.zalloc = use_git_alloc;
791 obj->zstream.zfree = use_git_free;
792 obj->zstream.next_in = Z_NULL;
793 obj->zstream.next_out = Z_NULL;
794 st = inflateInit(&obj->zstream);
795 if (st != Z_OK) {
ac3d33df 796 git_error_set(GIT_ERROR_ZLIB, "failed to init packfile stream");
46635339
CMN
797 return -1;
798 }
799
800 return 0;
801}
802
803ssize_t git_packfile_stream_read(git_packfile_stream *obj, void *buffer, size_t len)
804{
805 unsigned char *in;
806 size_t written;
807 int st;
808
809 if (obj->done)
810 return 0;
811
812 in = pack_window_open(obj->p, &obj->mw, obj->curpos, &obj->zstream.avail_in);
813 if (in == NULL)
814 return GIT_EBUFS;
815
816 obj->zstream.next_out = buffer;
090d5e1f 817 obj->zstream.avail_out = (unsigned int)len;
46635339
CMN
818 obj->zstream.next_in = in;
819
820 st = inflate(&obj->zstream, Z_SYNC_FLUSH);
821 git_mwindow_close(&obj->mw);
822
823 obj->curpos += obj->zstream.next_in - in;
824 written = len - obj->zstream.avail_out;
825
826 if (st != Z_OK && st != Z_STREAM_END) {
ac3d33df 827 git_error_set(GIT_ERROR_ZLIB, "error reading from the zlib stream");
46635339
CMN
828 return -1;
829 }
830
831 if (st == Z_STREAM_END)
832 obj->done = 1;
833
834
835 /* If we didn't write anything out but we're not done, we need more data */
836 if (!written && st != Z_STREAM_END)
837 return GIT_EBUFS;
838
839 return written;
840
841}
842
ac3d33df 843void git_packfile_stream_dispose(git_packfile_stream *obj)
46635339
CMN
844{
845 inflateEnd(&obj->zstream);
846}
847
b644e223 848static int packfile_unpack_compressed(
e1de726c
RB
849 git_rawobj *obj,
850 struct git_pack_file *p,
851 git_mwindow **w_curs,
852 git_off_t *curpos,
853 size_t size,
ac3d33df 854 git_object_t type)
7d0cdf82 855{
f1453c59 856 size_t buf_size;
7d0cdf82
CMN
857 int st;
858 z_stream stream;
859 unsigned char *buffer, *in;
860
ac3d33df 861 GIT_ERROR_CHECK_ALLOC_ADD(&buf_size, size, 1);
f1453c59 862 buffer = git__calloc(1, buf_size);
ac3d33df 863 GIT_ERROR_CHECK_ALLOC(buffer);
7d0cdf82
CMN
864
865 memset(&stream, 0, sizeof(stream));
866 stream.next_out = buffer;
f1453c59 867 stream.avail_out = (uInt)buf_size;
282283ac
RB
868 stream.zalloc = use_git_alloc;
869 stream.zfree = use_git_free;
7d0cdf82
CMN
870
871 st = inflateInit(&stream);
872 if (st != Z_OK) {
3286c408 873 git__free(buffer);
ac3d33df 874 git_error_set(GIT_ERROR_ZLIB, "failed to init zlib stream on unpack");
45d773ef 875
e1de726c 876 return -1;
7d0cdf82
CMN
877 }
878
879 do {
b5b474dd 880 in = pack_window_open(p, w_curs, *curpos, &stream.avail_in);
7d0cdf82
CMN
881 stream.next_in = in;
882 st = inflate(&stream, Z_FINISH);
45d773ef 883 git_mwindow_close(w_curs);
7d0cdf82
CMN
884
885 if (!stream.avail_out)
886 break; /* the payload is larger than it should be */
887
45d773ef
CMN
888 if (st == Z_BUF_ERROR && in == NULL) {
889 inflateEnd(&stream);
890 git__free(buffer);
904b67e6 891 return GIT_EBUFS;
45d773ef
CMN
892 }
893
b5b474dd 894 *curpos += stream.next_in - in;
7d0cdf82
CMN
895 } while (st == Z_OK || st == Z_BUF_ERROR);
896
897 inflateEnd(&stream);
898
899 if ((st != Z_STREAM_END) || stream.total_out != size) {
3286c408 900 git__free(buffer);
ac3d33df 901 git_error_set(GIT_ERROR_ZLIB, "error inflating zlib stream");
e1de726c 902 return -1;
7d0cdf82
CMN
903 }
904
905 obj->type = type;
906 obj->len = size;
907 obj->data = buffer;
e1de726c 908 return 0;
7d0cdf82
CMN
909}
910
b5b474dd
CMN
911/*
912 * curpos is where the data starts, delta_obj_offset is the where the
913 * header starts
914 */
e1de726c
RB
915git_off_t get_delta_base(
916 struct git_pack_file *p,
917 git_mwindow **w_curs,
918 git_off_t *curpos,
ac3d33df 919 git_object_t type,
e1de726c 920 git_off_t delta_obj_offset)
7d0cdf82 921{
45d773ef
CMN
922 unsigned int left = 0;
923 unsigned char *base_info;
e1de726c 924 git_off_t base_offset;
7d0cdf82
CMN
925 git_oid unused;
926
45d773ef
CMN
927 base_info = pack_window_open(p, w_curs, *curpos, &left);
928 /* Assumption: the only reason this would fail is because the file is too small */
929 if (base_info == NULL)
904b67e6 930 return GIT_EBUFS;
7d0cdf82
CMN
931 /* pack_window_open() assured us we have [base_info, base_info + 20)
932 * as a range that we can look at without walking off the
87d9869f
VM
933 * end of the mapped window. Its actually the hash size
934 * that is assured. An OFS_DELTA longer than the hash size
7d0cdf82
CMN
935 * is stupid, as then a REF_DELTA would be smaller to store.
936 */
ac3d33df 937 if (type == GIT_OBJECT_OFS_DELTA) {
7d0cdf82
CMN
938 unsigned used = 0;
939 unsigned char c = base_info[used++];
eae0bfdc 940 size_t unsigned_base_offset = c & 127;
7d0cdf82 941 while (c & 128) {
45d773ef 942 if (left <= used)
904b67e6 943 return GIT_EBUFS;
eae0bfdc
PP
944 unsigned_base_offset += 1;
945 if (!unsigned_base_offset || MSB(unsigned_base_offset, 7))
87d9869f 946 return 0; /* overflow */
7d0cdf82 947 c = base_info[used++];
eae0bfdc 948 unsigned_base_offset = (unsigned_base_offset << 7) + (c & 127);
7d0cdf82 949 }
eae0bfdc 950 if (unsigned_base_offset == 0 || (size_t)delta_obj_offset <= unsigned_base_offset)
87d9869f 951 return 0; /* out of bound */
eae0bfdc 952 base_offset = delta_obj_offset - unsigned_base_offset;
7d0cdf82 953 *curpos += used;
ac3d33df 954 } else if (type == GIT_OBJECT_REF_DELTA) {
c1af5a39
CMN
955 /* If we have the cooperative cache, search in it first */
956 if (p->has_cache) {
0e040c03 957 git_oid oid;
ac3d33df 958 size_t k;
c1af5a39 959
0e040c03 960 git_oid_fromraw(&oid, base_info);
a853c527 961 k = git_oidmap_lookup_index(p->idx_cache, &oid);
64e46dc3 962 if (git_oidmap_valid_index(p->idx_cache, k)) {
c1af5a39 963 *curpos += 20;
cb18386f 964 return ((struct git_pack_entry *)git_oidmap_value_at(p->idx_cache, k))->offset;
38c10ecd
ET
965 } else {
966 /* If we're building an index, don't try to find the pack
967 * entry; we just haven't seen it yet. We'll make
968 * progress again in the next loop.
969 */
970 return GIT_PASSTHROUGH;
c1af5a39
CMN
971 }
972 }
38c10ecd 973
7d0cdf82 974 /* The base entry _must_ be in the same pack */
e1de726c
RB
975 if (pack_entry_find_offset(&base_offset, &unused, p, (git_oid *)base_info, GIT_OID_HEXSZ) < 0)
976 return packfile_error("base entry delta is not in the same pack");
7d0cdf82
CMN
977 *curpos += 20;
978 } else
979 return 0;
980
981 return base_offset;
982}
a070f152
CMN
983
984/***********************************************************
985 *
986 * PACKFILE METHODS
987 *
988 ***********************************************************/
989
bf339ab0
ET
990void git_packfile_close(struct git_pack_file *p, bool unlink_packfile)
991{
992 if (p->mwf.fd >= 0) {
993 git_mwindow_free_all_locked(&p->mwf);
994 p_close(p->mwf.fd);
995 p->mwf.fd = -1;
996 }
997
998 if (unlink_packfile)
999 p_unlink(p->pack_name);
1000}
1001
96c9b9f0 1002void git_packfile_free(struct git_pack_file *p)
a070f152 1003{
24c70804
RB
1004 if (!p)
1005 return;
1006
c8f79c2b 1007 cache_free(&p->bases);
c0f4a011 1008
bf339ab0 1009 git_packfile_close(p, false);
a070f152
CMN
1010
1011 pack_index_free(p);
1012
3286c408 1013 git__free(p->bad_object_sha1);
24c70804 1014
24c70804 1015 git_mutex_free(&p->lock);
649214be 1016 git_mutex_free(&p->bases.lock);
3286c408 1017 git__free(p);
a070f152
CMN
1018}
1019
1020static int packfile_open(struct git_pack_file *p)
1021{
1022 struct stat st;
1023 struct git_pack_header hdr;
1024 git_oid sha1;
1025 unsigned char *idx_sha1;
1026
0ddfcb40 1027 if (p->index_version == -1 && pack_index_open(p) < 0)
e10144ae 1028 return git_odb__error_notfound("failed to open packfile", NULL, 0);
a070f152 1029
9d2f841a
RB
1030 /* if mwf opened by another thread, return now */
1031 if (git_mutex_lock(&p->lock) < 0)
1032 return packfile_error("failed to get lock for open");
1033
1034 if (p->mwf.fd >= 0) {
1035 git_mutex_unlock(&p->lock);
1036 return 0;
1037 }
1038
a070f152 1039 /* TODO: open with noatime */
e1de726c 1040 p->mwf.fd = git_futils_open_ro(p->pack_name);
9d2f841a
RB
1041 if (p->mwf.fd < 0)
1042 goto cleanup;
a070f152 1043
e1de726c
RB
1044 if (p_fstat(p->mwf.fd, &st) < 0 ||
1045 git_mwindow_file_register(&p->mwf) < 0)
1046 goto cleanup;
a070f152
CMN
1047
1048 /* If we created the struct before we had the pack we lack size. */
1049 if (!p->mwf.size) {
1050 if (!S_ISREG(st.st_mode))
1051 goto cleanup;
e1de726c 1052 p->mwf.size = (git_off_t)st.st_size;
a070f152
CMN
1053 } else if (p->mwf.size != st.st_size)
1054 goto cleanup;
1055
1056#if 0
1057 /* We leave these file descriptors open with sliding mmap;
1058 * there is no point keeping them open across exec(), though.
1059 */
1060 fd_flag = fcntl(p->mwf.fd, F_GETFD, 0);
1061 if (fd_flag < 0)
e1de726c 1062 goto cleanup;
a070f152
CMN
1063
1064 fd_flag |= FD_CLOEXEC;
1065 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
e1de726c 1066 goto cleanup;
a070f152
CMN
1067#endif
1068
1069 /* Verify we recognize this pack file format. */
e1de726c
RB
1070 if (p_read(p->mwf.fd, &hdr, sizeof(hdr)) < 0 ||
1071 hdr.hdr_signature != htonl(PACK_SIGNATURE) ||
1072 !pack_version_ok(hdr.hdr_version))
a070f152
CMN
1073 goto cleanup;
1074
1075 /* Verify the pack matches its index. */
e1de726c
RB
1076 if (p->num_objects != ntohl(hdr.hdr_entries) ||
1077 p_lseek(p->mwf.fd, p->mwf.size - GIT_OID_RAWSZ, SEEK_SET) == -1 ||
1078 p_read(p->mwf.fd, sha1.id, GIT_OID_RAWSZ) < 0)
a070f152
CMN
1079 goto cleanup;
1080
1081 idx_sha1 = ((unsigned char *)p->index_map.data) + p->index_map.len - 40;
1082
9d2f841a
RB
1083 if (git_oid__cmp(&sha1, (git_oid *)idx_sha1) != 0)
1084 goto cleanup;
1085
1086 git_mutex_unlock(&p->lock);
1087 return 0;
a070f152
CMN
1088
1089cleanup:
ac3d33df 1090 git_error_set(GIT_ERROR_OS, "invalid packfile '%s'", p->pack_name);
9d2f841a 1091
3a2d48d5
SS
1092 if (p->mwf.fd >= 0)
1093 p_close(p->mwf.fd);
a070f152 1094 p->mwf.fd = -1;
9d2f841a
RB
1095
1096 git_mutex_unlock(&p->lock);
1097
e1de726c 1098 return -1;
a070f152
CMN
1099}
1100
b3b66c57
CMN
1101int git_packfile__name(char **out, const char *path)
1102{
1103 size_t path_len;
1104 git_buf buf = GIT_BUF_INIT;
1105
1106 path_len = strlen(path);
1107
1108 if (path_len < strlen(".idx"))
e10144ae 1109 return git_odb__error_notfound("invalid packfile path", NULL, 0);
b3b66c57
CMN
1110
1111 if (git_buf_printf(&buf, "%.*s.pack", (int)(path_len - strlen(".idx")), path) < 0)
1112 return -1;
1113
1114 *out = git_buf_detach(&buf);
1115 return 0;
1116}
1117
5d2d21e5 1118int git_packfile_alloc(struct git_pack_file **pack_out, const char *path)
a070f152
CMN
1119{
1120 struct stat st;
1121 struct git_pack_file *p;
f1453c59 1122 size_t path_len = path ? strlen(path) : 0, alloc_len;
a070f152
CMN
1123
1124 *pack_out = NULL;
24c70804 1125
38eef611 1126 if (path_len < strlen(".idx"))
e10144ae 1127 return git_odb__error_notfound("invalid packfile path", NULL, 0);
24c70804 1128
ac3d33df
JK
1129 GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, sizeof(*p), path_len);
1130 GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 2);
392702ee 1131
f1453c59 1132 p = git__calloc(1, alloc_len);
ac3d33df 1133 GIT_ERROR_CHECK_ALLOC(p);
a070f152 1134
38eef611
RB
1135 memcpy(p->pack_name, path, path_len + 1);
1136
a070f152
CMN
1137 /*
1138 * Make sure a corresponding .pack file exists and that
1139 * the index looks sane.
1140 */
38eef611
RB
1141 if (git__suffixcmp(path, ".idx") == 0) {
1142 size_t root_len = path_len - strlen(".idx");
1143
1144 memcpy(p->pack_name + root_len, ".keep", sizeof(".keep"));
1145 if (git_path_exists(p->pack_name) == true)
1146 p->pack_keep = 1;
a070f152 1147
38eef611 1148 memcpy(p->pack_name + root_len, ".pack", sizeof(".pack"));
38eef611 1149 }
a070f152 1150
e1de726c 1151 if (p_stat(p->pack_name, &st) < 0 || !S_ISREG(st.st_mode)) {
3286c408 1152 git__free(p);
e10144ae 1153 return git_odb__error_notfound("packfile not found", NULL, 0);
a070f152
CMN
1154 }
1155
1156 /* ok, it looks sane as far as we can check without
1157 * actually mapping the pack file.
1158 */
38eef611 1159 p->mwf.fd = -1;
1af56d7d 1160 p->mwf.size = st.st_size;
a070f152
CMN
1161 p->pack_local = 1;
1162 p->mtime = (git_time_t)st.st_mtime;
0ddfcb40 1163 p->index_version = -1;
a070f152 1164
1a42dd17 1165 if (git_mutex_init(&p->lock)) {
ac3d33df 1166 git_error_set(GIT_ERROR_OS, "failed to initialize packfile mutex");
1a42dd17
RB
1167 git__free(p);
1168 return -1;
1169 }
38eef611 1170
649214be
CMN
1171 if (cache_init(&p->bases) < 0) {
1172 git__free(p);
1173 return -1;
1174 }
1175
a070f152 1176 *pack_out = p;
e1de726c
RB
1177
1178 return 0;
a070f152
CMN
1179}
1180
1181/***********************************************************
1182 *
1183 * PACKFILE ENTRY SEARCH INTERNALS
1184 *
1185 ***********************************************************/
1186
e1de726c 1187static git_off_t nth_packed_object_offset(const struct git_pack_file *p, uint32_t n)
a070f152
CMN
1188{
1189 const unsigned char *index = p->index_map.data;
ea9e00cb 1190 const unsigned char *end = index + p->index_map.len;
a070f152
CMN
1191 index += 4 * 256;
1192 if (p->index_version == 1) {
1193 return ntohl(*((uint32_t *)(index + 24 * n)));
1194 } else {
1195 uint32_t off;
1196 index += 8 + p->num_objects * (20 + 4);
1197 off = ntohl(*((uint32_t *)(index + 4 * n)));
1198 if (!(off & 0x80000000))
1199 return off;
1200 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
ea9e00cb
CMN
1201
1202 /* Make sure we're not being sent out of bounds */
1203 if (index >= end - 8)
1204 return -1;
1205
a070f152 1206 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
87d9869f 1207 ntohl(*((uint32_t *)(index + 4)));
a070f152
CMN
1208 }
1209}
1210
60ecdf59
DMB
1211static int git__memcmp4(const void *a, const void *b) {
1212 return memcmp(a, b, 4);
1213}
1214
521aedad 1215int git_pack_foreach_entry(
5dca2010 1216 struct git_pack_file *p,
c3fb7d04 1217 git_odb_foreach_cb cb,
5dca2010 1218 void *data)
521aedad
CMN
1219{
1220 const unsigned char *index = p->index_map.data, *current;
521aedad 1221 uint32_t i;
dab89f9b 1222 int error = 0;
521aedad
CMN
1223
1224 if (index == NULL) {
521aedad
CMN
1225 if ((error = pack_index_open(p)) < 0)
1226 return error;
1227
1228 assert(p->index_map.data);
1229
1230 index = p->index_map.data;
1231 }
1232
1233 if (p->index_version > 1) {
1234 index += 8;
1235 }
1236
1237 index += 4 * 256;
1238
60ecdf59
DMB
1239 if (p->oids == NULL) {
1240 git_vector offsets, oids;
521aedad 1241
60ecdf59
DMB
1242 if ((error = git_vector_init(&oids, p->num_objects, NULL)))
1243 return error;
1244
1245 if ((error = git_vector_init(&offsets, p->num_objects, git__memcmp4)))
1246 return error;
5dca2010 1247
60ecdf59
DMB
1248 if (p->index_version > 1) {
1249 const unsigned char *off = index + 24 * p->num_objects;
1250 for (i = 0; i < p->num_objects; i++)
1251 git_vector_insert(&offsets, (void*)&off[4 * i]);
1252 git_vector_sort(&offsets);
1253 git_vector_foreach(&offsets, i, current)
1254 git_vector_insert(&oids, (void*)&index[5 * (current - off)]);
1255 } else {
1256 for (i = 0; i < p->num_objects; i++)
1257 git_vector_insert(&offsets, (void*)&index[24 * i]);
1258 git_vector_sort(&offsets);
1259 git_vector_foreach(&offsets, i, current)
1260 git_vector_insert(&oids, (void*)&current[4]);
1261 }
25e0b157 1262
60ecdf59 1263 git_vector_free(&offsets);
25e0b157 1264 p->oids = (git_oid **)git_vector_detach(NULL, NULL, &oids);
521aedad
CMN
1265 }
1266
60ecdf59 1267 for (i = 0; i < p->num_objects; i++)
26c1cb91 1268 if ((error = cb(p->oids[i], data)) != 0)
ac3d33df 1269 return git_error_set_after_callback(error);
60ecdf59 1270
25e0b157 1271 return error;
521aedad
CMN
1272}
1273
a070f152 1274static int pack_entry_find_offset(
e1de726c
RB
1275 git_off_t *offset_out,
1276 git_oid *found_oid,
1277 struct git_pack_file *p,
1278 const git_oid *short_oid,
b8457baa 1279 size_t len)
a070f152 1280{
0cf15e39
PS
1281 const uint32_t *level1_ofs;
1282 const unsigned char *index;
a070f152
CMN
1283 unsigned hi, lo, stride;
1284 int pos, found = 0;
ea9e00cb 1285 git_off_t offset;
a070f152
CMN
1286 const unsigned char *current = 0;
1287
1288 *offset_out = 0;
1289
0ddfcb40 1290 if (p->index_version == -1) {
34bd5999 1291 int error;
a070f152 1292
34bd5999
CMN
1293 if ((error = pack_index_open(p)) < 0)
1294 return error;
1295 assert(p->index_map.data);
34bd5999 1296 }
a070f152 1297
0cf15e39
PS
1298 index = p->index_map.data;
1299 level1_ofs = p->index_map.data;
1300
a070f152
CMN
1301 if (p->index_version > 1) {
1302 level1_ofs += 2;
1303 index += 8;
1304 }
1305
1306 index += 4 * 256;
1307 hi = ntohl(level1_ofs[(int)short_oid->id[0]]);
1308 lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(level1_ofs[(int)short_oid->id[0] - 1]));
1309
1310 if (p->index_version > 1) {
1311 stride = 20;
1312 } else {
1313 stride = 24;
1314 index += 4;
1315 }
1316
1317#ifdef INDEX_DEBUG_LOOKUP
1318 printf("%02x%02x%02x... lo %u hi %u nr %d\n",
1319 short_oid->id[0], short_oid->id[1], short_oid->id[2], lo, hi, p->num_objects);
1320#endif
1321
67591c8c 1322 pos = sha1_position(index, stride, lo, hi, short_oid->id);
a070f152
CMN
1323
1324 if (pos >= 0) {
1325 /* An object matching exactly the oid was found */
1326 found = 1;
1327 current = index + pos * stride;
1328 } else {
1329 /* No object was found */
1330 /* pos refers to the object with the "closest" oid to short_oid */
1331 pos = - 1 - pos;
1332 if (pos < (int)p->num_objects) {
1333 current = index + pos * stride;
1334
282283ac 1335 if (!git_oid_ncmp(short_oid, (const git_oid *)current, len))
a070f152 1336 found = 1;
a070f152
CMN
1337 }
1338 }
1339
b2a2702d 1340 if (found && len != GIT_OID_HEXSZ && pos + 1 < (int)p->num_objects) {
a070f152
CMN
1341 /* Check for ambiguousity */
1342 const unsigned char *next = current + stride;
1343
1344 if (!git_oid_ncmp(short_oid, (const git_oid *)next, len)) {
1345 found = 2;
1346 }
1347 }
1348
e1de726c 1349 if (!found)
e10144ae 1350 return git_odb__error_notfound("failed to find offset for pack entry", short_oid, len);
e1de726c
RB
1351 if (found > 1)
1352 return git_odb__error_ambiguous("found multiple offsets for pack entry");
24c70804 1353
ea9e00cb 1354 if ((offset = nth_packed_object_offset(p, pos)) < 0) {
ac3d33df 1355 git_error_set(GIT_ERROR_ODB, "packfile index is corrupt");
ea9e00cb
CMN
1356 return -1;
1357 }
1358
1359 *offset_out = offset;
e1de726c 1360 git_oid_fromraw(found_oid, current);
a070f152
CMN
1361
1362#ifdef INDEX_DEBUG_LOOKUP
e1de726c 1363 {
a070f152
CMN
1364 unsigned char hex_sha1[GIT_OID_HEXSZ + 1];
1365 git_oid_fmt(hex_sha1, found_oid);
1366 hex_sha1[GIT_OID_HEXSZ] = '\0';
1367 printf("found lo=%d %s\n", lo, hex_sha1);
a070f152 1368 }
e1de726c 1369#endif
24c70804 1370
e1de726c 1371 return 0;
a070f152
CMN
1372}
1373
1374int git_pack_entry_find(
1375 struct git_pack_entry *e,
1376 struct git_pack_file *p,
1377 const git_oid *short_oid,
b8457baa 1378 size_t len)
a070f152 1379{
e1de726c 1380 git_off_t offset;
a070f152
CMN
1381 git_oid found_oid;
1382 int error;
1383
1384 assert(p);
1385
1386 if (len == GIT_OID_HEXSZ && p->num_bad_objects) {
1387 unsigned i;
1388 for (i = 0; i < p->num_bad_objects; i++)
b7f167da 1389 if (git_oid__cmp(short_oid, &p->bad_object_sha1[i]) == 0)
e1de726c 1390 return packfile_error("bad object found in packfile");
a070f152
CMN
1391 }
1392
1393 error = pack_entry_find_offset(&offset, &found_oid, p, short_oid, len);
e1de726c
RB
1394 if (error < 0)
1395 return error;
a070f152
CMN
1396
1397 /* we found a unique entry in the index;
1398 * make sure the packfile backing the index
1399 * still exists on disk */
e1de726c
RB
1400 if (p->mwf.fd == -1 && (error = packfile_open(p)) < 0)
1401 return error;
a070f152
CMN
1402
1403 e->offset = offset;
1404 e->p = p;
1405
1406 git_oid_cpy(&e->sha1, &found_oid);
e1de726c 1407 return 0;
a070f152 1408}