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