]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/index-pack.c
index-pack: factor out unpack core from get_data_from_pack
[thirdparty/git.git] / builtin / index-pack.c
CommitLineData
2ad9d4cb 1#include "builtin.h"
9cf6d335
SV
2#include "delta.h"
3#include "pack.h"
4#include "csum-file.h"
8e440259
PE
5#include "blob.h"
6#include "commit.h"
7#include "tag.h"
8#include "tree.h"
96a02f8f 9#include "progress.h"
0153be05 10#include "fsck.h"
2fb3f6db 11#include "exec_cmd.h"
b8a2486f 12#include "thread-utils.h"
9cf6d335
SV
13
14static const char index_pack_usage[] =
e337a04d 15"git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
9cf6d335 16
9cba13ca 17struct object_entry {
aa7e44bf 18 struct pack_idx_entry idx;
2d477051
NP
19 unsigned long size;
20 unsigned int hdr_size;
9cf6d335
SV
21 enum object_type type;
22 enum object_type real_type;
38a45561
JH
23 unsigned delta_depth;
24 int base_object_no;
9cf6d335
SV
25};
26
53dda6ff
NP
27union delta_base {
28 unsigned char sha1[20];
d7dd0223 29 off_t offset;
53dda6ff
NP
30};
31
f41aebd4 32struct base_data {
4a438cab
SP
33 struct base_data *base;
34 struct base_data *child;
03993e13 35 struct object_entry *obj;
f41aebd4
SP
36 void *data;
37 unsigned long size;
2baad220
NTND
38 int ref_first, ref_last;
39 int ofs_first, ofs_last;
f41aebd4
SP
40};
41
b038a610
NTND
42#if !defined(NO_PTHREADS) && defined(NO_PREAD)
43/* NO_PREAD uses compat/pread.c, which is not thread-safe. Disable threading. */
44#define NO_PTHREADS
45#endif
46
b8a2486f
NTND
47struct thread_local {
48#ifndef NO_PTHREADS
49 pthread_t thread;
50#endif
51 struct base_data *base_cache;
52 size_t base_cache_used;
53};
54
3c552873
NP
55/*
56 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
57 * to memcmp() only the first 20 bytes.
58 */
59#define UNION_BASE_SZ 20
60
0153be05
MK
61#define FLAG_LINK (1u<<20)
62#define FLAG_CHECKED (1u<<21)
63
9cba13ca 64struct delta_entry {
53dda6ff 65 union delta_base base;
636171cb 66 int obj_no;
9cf6d335
SV
67};
68
9cf6d335
SV
69static struct object_entry *objects;
70static struct delta_entry *deltas;
b8a2486f 71static struct thread_local nothread_data;
9cf6d335
SV
72static int nr_objects;
73static int nr_deltas;
636171cb 74static int nr_resolved_deltas;
b8a2486f 75static int nr_threads;
9cf6d335 76
e42797f5 77static int from_stdin;
0153be05 78static int strict;
3c9af366
NP
79static int verbose;
80
dc6a0757 81static struct progress *progress;
e42797f5 82
2d477051
NP
83/* We always read in 4kB chunks. */
84static unsigned char input_buffer[4096];
d7dd0223
NP
85static unsigned int input_offset, input_len;
86static off_t consumed_bytes;
d1a0ed18 87static unsigned deepest_delta;
9126f009 88static git_SHA_CTX input_ctx;
ee5743ce 89static uint32_t input_crc32;
6d2fa7f1 90static int input_fd, output_fd, pack_fd;
2d477051 91
b8a2486f
NTND
92#ifndef NO_PTHREADS
93
94static struct thread_local *thread_data;
95static int nr_dispatched;
96static int threads_active;
97
98static pthread_mutex_t read_mutex;
99#define read_lock() lock_mutex(&read_mutex)
100#define read_unlock() unlock_mutex(&read_mutex)
101
102static pthread_mutex_t counter_mutex;
103#define counter_lock() lock_mutex(&counter_mutex)
104#define counter_unlock() unlock_mutex(&counter_mutex)
105
106static pthread_mutex_t work_mutex;
107#define work_lock() lock_mutex(&work_mutex)
108#define work_unlock() unlock_mutex(&work_mutex)
109
110static pthread_key_t key;
111
112static inline void lock_mutex(pthread_mutex_t *mutex)
113{
114 if (threads_active)
115 pthread_mutex_lock(mutex);
116}
117
118static inline void unlock_mutex(pthread_mutex_t *mutex)
119{
120 if (threads_active)
121 pthread_mutex_unlock(mutex);
122}
123
124/*
125 * Mutex and conditional variable can't be statically-initialized on Windows.
126 */
127static void init_thread(void)
128{
129 init_recursive_mutex(&read_mutex);
130 pthread_mutex_init(&counter_mutex, NULL);
131 pthread_mutex_init(&work_mutex, NULL);
132 pthread_key_create(&key, NULL);
133 thread_data = xcalloc(nr_threads, sizeof(*thread_data));
134 threads_active = 1;
135}
136
137static void cleanup_thread(void)
138{
139 if (!threads_active)
140 return;
141 threads_active = 0;
142 pthread_mutex_destroy(&read_mutex);
143 pthread_mutex_destroy(&counter_mutex);
144 pthread_mutex_destroy(&work_mutex);
145 pthread_key_delete(key);
146 free(thread_data);
147}
148
149#else
150
151#define read_lock()
152#define read_unlock()
153
154#define counter_lock()
155#define counter_unlock()
156
157#define work_lock()
158#define work_unlock()
159
160#endif
161
162
0153be05
MK
163static int mark_link(struct object *obj, int type, void *data)
164{
165 if (!obj)
166 return -1;
167
168 if (type != OBJ_ANY && obj->type != type)
c2b97ecf 169 die(_("object type mismatch at %s"), sha1_to_hex(obj->sha1));
0153be05
MK
170
171 obj->flags |= FLAG_LINK;
172 return 0;
173}
174
175/* The content of each linked object must have been checked
176 or it must be already present in the object database */
177static void check_object(struct object *obj)
178{
179 if (!obj)
180 return;
181
182 if (!(obj->flags & FLAG_LINK))
183 return;
184
185 if (!(obj->flags & FLAG_CHECKED)) {
186 unsigned long size;
187 int type = sha1_object_info(obj->sha1, &size);
188 if (type != obj->type || type <= 0)
c2b97ecf 189 die(_("object of unexpected type"));
0153be05
MK
190 obj->flags |= FLAG_CHECKED;
191 return;
192 }
193}
194
195static void check_objects(void)
196{
197 unsigned i, max;
198
199 max = get_max_object_index();
200 for (i = 0; i < max; i++)
201 check_object(get_indexed_object(i));
202}
203
204
636171cb 205/* Discard current buffer used content. */
a6e8a767 206static void flush(void)
636171cb
NP
207{
208 if (input_offset) {
209 if (output_fd >= 0)
210 write_or_die(output_fd, input_buffer, input_offset);
9126f009 211 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
554a2636 212 memmove(input_buffer, input_buffer + input_offset, input_len);
636171cb
NP
213 input_offset = 0;
214 }
215}
216
2d477051
NP
217/*
218 * Make sure at least "min" bytes are available in the buffer, and
219 * return the pointer to the buffer.
220 */
b89c4e93 221static void *fill(int min)
9cf6d335 222{
2d477051
NP
223 if (min <= input_len)
224 return input_buffer + input_offset;
225 if (min > sizeof(input_buffer))
c2b97ecf
NTND
226 die(Q_("cannot fill %d byte",
227 "cannot fill %d bytes",
228 min),
229 min);
636171cb 230 flush();
2d477051 231 do {
8a912bcb 232 ssize_t ret = xread(input_fd, input_buffer + input_len,
2d477051
NP
233 sizeof(input_buffer) - input_len);
234 if (ret <= 0) {
235 if (!ret)
c2b97ecf
NTND
236 die(_("early EOF"));
237 die_errno(_("read error on input"));
2d477051
NP
238 }
239 input_len += ret;
218558af
NP
240 if (from_stdin)
241 display_throughput(progress, consumed_bytes + input_len);
2d477051
NP
242 } while (input_len < min);
243 return input_buffer;
244}
245
246static void use(int bytes)
247{
248 if (bytes > input_len)
c2b97ecf 249 die(_("used more bytes than were available"));
ee5743ce 250 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
2d477051
NP
251 input_len -= bytes;
252 input_offset += bytes;
d7dd0223
NP
253
254 /* make sure off_t is sufficiently large not to wrap */
c03c8315 255 if (signed_add_overflows(consumed_bytes, bytes))
c2b97ecf 256 die(_("pack too large for current definition of off_t"));
2d477051
NP
257 consumed_bytes += bytes;
258}
9cf6d335 259
3bb72562 260static const char *open_pack_file(const char *pack_name)
2d477051 261{
e42797f5
NP
262 if (from_stdin) {
263 input_fd = 0;
264 if (!pack_name) {
ab1900a3
ÆAB
265 static char tmp_file[PATH_MAX];
266 output_fd = odb_mkstemp(tmp_file, sizeof(tmp_file),
6e180cdc 267 "pack/tmp_pack_XXXXXX");
ab1900a3 268 pack_name = xstrdup(tmp_file);
e42797f5
NP
269 } else
270 output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
271 if (output_fd < 0)
c2b97ecf 272 die_errno(_("unable to create '%s'"), pack_name);
6d2fa7f1 273 pack_fd = output_fd;
e42797f5
NP
274 } else {
275 input_fd = open(pack_name, O_RDONLY);
276 if (input_fd < 0)
c2b97ecf 277 die_errno(_("cannot open packfile '%s'"), pack_name);
e42797f5 278 output_fd = -1;
6d2fa7f1 279 pack_fd = input_fd;
e42797f5 280 }
9126f009 281 git_SHA1_Init(&input_ctx);
e42797f5 282 return pack_name;
9cf6d335
SV
283}
284
285static void parse_pack_header(void)
286{
2d477051 287 struct pack_header *hdr = fill(sizeof(struct pack_header));
9cf6d335
SV
288
289 /* Header consistency check */
9cf6d335 290 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
c2b97ecf 291 die(_("pack signature mismatch"));
d60fc1c8 292 if (!pack_version_ok(hdr->hdr_version))
6e1c2344
RJ
293 die("pack version %"PRIu32" unsupported",
294 ntohl(hdr->hdr_version));
9cf6d335
SV
295
296 nr_objects = ntohl(hdr->hdr_entries);
2d477051 297 use(sizeof(struct pack_header));
9cf6d335
SV
298}
299
a4f3131c
EFL
300static NORETURN void bad_object(unsigned long offset, const char *format,
301 ...) __attribute__((format (printf, 2, 3)));
9cf6d335 302
c2e86add 303static NORETURN void bad_object(unsigned long offset, const char *format, ...)
9cf6d335
SV
304{
305 va_list params;
306 char buf[1024];
307
308 va_start(params, format);
309 vsnprintf(buf, sizeof(buf), format, params);
310 va_end(params);
c2b97ecf 311 die(_("pack has bad object at offset %lu: %s"), offset, buf);
9cf6d335
SV
312}
313
b8a2486f
NTND
314static inline struct thread_local *get_thread_data(void)
315{
316#ifndef NO_PTHREADS
317 if (threads_active)
318 return pthread_getspecific(key);
319 assert(!threads_active &&
320 "This should only be reached when all threads are gone");
321#endif
322 return &nothread_data;
323}
324
325#ifndef NO_PTHREADS
326static void set_thread_data(struct thread_local *data)
327{
328 if (threads_active)
329 pthread_setspecific(key, data);
330}
331#endif
332
2baad220
NTND
333static struct base_data *alloc_base_data(void)
334{
335 struct base_data *base = xmalloc(sizeof(struct base_data));
336 memset(base, 0, sizeof(*base));
337 base->ref_last = -1;
338 base->ofs_last = -1;
339 return base;
340}
341
6a87ed97
NP
342static void free_base_data(struct base_data *c)
343{
344 if (c->data) {
345 free(c->data);
346 c->data = NULL;
b8a2486f 347 get_thread_data()->base_cache_used -= c->size;
6a87ed97
NP
348 }
349}
350
92392b4a
SP
351static void prune_base_data(struct base_data *retain)
352{
8e24cbae 353 struct base_data *b;
b8a2486f
NTND
354 struct thread_local *data = get_thread_data();
355 for (b = data->base_cache;
356 data->base_cache_used > delta_base_cache_limit && b;
92392b4a 357 b = b->child) {
6a87ed97
NP
358 if (b->data && b != retain)
359 free_base_data(b);
92392b4a
SP
360 }
361}
362
4a438cab
SP
363static void link_base_data(struct base_data *base, struct base_data *c)
364{
365 if (base)
366 base->child = c;
367 else
b8a2486f 368 get_thread_data()->base_cache = c;
4a438cab
SP
369
370 c->base = base;
371 c->child = NULL;
9441b61d 372 if (c->data)
b8a2486f 373 get_thread_data()->base_cache_used += c->size;
92392b4a 374 prune_base_data(c);
4a438cab
SP
375}
376
377static void unlink_base_data(struct base_data *c)
378{
379 struct base_data *base = c->base;
380 if (base)
381 base->child = NULL;
382 else
b8a2486f 383 get_thread_data()->base_cache = NULL;
6a87ed97 384 free_base_data(c);
4a438cab
SP
385}
386
681b07de
NTND
387static int is_delta_type(enum object_type type)
388{
389 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
390}
391
392static void *unpack_entry_data(unsigned long offset, unsigned long size,
393 enum object_type type, unsigned char *sha1)
9cf6d335 394{
9ec2dde9 395 static char fixed_buf[8192];
7ce4721a 396 int status;
ef49a7a0 397 git_zstream stream;
9ec2dde9 398 void *buf;
681b07de
NTND
399 git_SHA_CTX c;
400 char hdr[32];
401 int hdrlen;
402
403 if (!is_delta_type(type)) {
404 hdrlen = sprintf(hdr, "%s %lu", typename(type), size) + 1;
405 git_SHA1_Init(&c);
406 git_SHA1_Update(&c, hdr, hdrlen);
407 } else
408 sha1 = NULL;
9ec2dde9
NTND
409 if (type == OBJ_BLOB && size > big_file_threshold)
410 buf = fixed_buf;
411 else
412 buf = xmalloc(size);
9cf6d335
SV
413
414 memset(&stream, 0, sizeof(stream));
7ce4721a 415 git_inflate_init(&stream);
9cf6d335 416 stream.next_out = buf;
9ec2dde9 417 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
9cf6d335 418
7ce4721a 419 do {
681b07de 420 unsigned char *last_out = stream.next_out;
2d477051
NP
421 stream.next_in = fill(1);
422 stream.avail_in = input_len;
7ce4721a
NP
423 status = git_inflate(&stream, 0);
424 use(input_len - stream.avail_in);
681b07de
NTND
425 if (sha1)
426 git_SHA1_Update(&c, last_out, stream.next_out - last_out);
9ec2dde9
NTND
427 if (buf == fixed_buf) {
428 stream.next_out = buf;
429 stream.avail_out = sizeof(fixed_buf);
430 }
7ce4721a
NP
431 } while (status == Z_OK);
432 if (stream.total_out != size || status != Z_STREAM_END)
c2b97ecf 433 bad_object(offset, _("inflate returned %d"), status);
39c68542 434 git_inflate_end(&stream);
681b07de
NTND
435 if (sha1)
436 git_SHA1_Final(sha1, &c);
9ec2dde9 437 return buf == fixed_buf ? NULL : buf;
9cf6d335
SV
438}
439
681b07de
NTND
440static void *unpack_raw_entry(struct object_entry *obj,
441 union delta_base *delta_base,
442 unsigned char *sha1)
9cf6d335 443{
48fb7deb
LT
444 unsigned char *p;
445 unsigned long size, c;
d7dd0223 446 off_t base_offset;
9cf6d335 447 unsigned shift;
ee5743ce 448 void *data;
9cf6d335 449
aa7e44bf 450 obj->idx.offset = consumed_bytes;
1e4cd68c 451 input_crc32 = crc32(0, NULL, 0);
2d477051
NP
452
453 p = fill(1);
454 c = *p;
455 use(1);
456 obj->type = (c >> 4) & 7;
9cf6d335
SV
457 size = (c & 15);
458 shift = 4;
459 while (c & 0x80) {
2d477051
NP
460 p = fill(1);
461 c = *p;
462 use(1);
48fb7deb 463 size += (c & 0x7f) << shift;
9cf6d335
SV
464 shift += 7;
465 }
2d477051 466 obj->size = size;
9cf6d335 467
2d477051 468 switch (obj->type) {
eb32d236 469 case OBJ_REF_DELTA:
2d477051
NP
470 hashcpy(delta_base->sha1, fill(20));
471 use(20);
53dda6ff
NP
472 break;
473 case OBJ_OFS_DELTA:
474 memset(delta_base, 0, sizeof(*delta_base));
2d477051
NP
475 p = fill(1);
476 c = *p;
477 use(1);
53dda6ff
NP
478 base_offset = c & 127;
479 while (c & 128) {
480 base_offset += 1;
8723f216 481 if (!base_offset || MSB(base_offset, 7))
c2b97ecf 482 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
2d477051
NP
483 p = fill(1);
484 c = *p;
485 use(1);
53dda6ff
NP
486 base_offset = (base_offset << 7) + (c & 127);
487 }
aa7e44bf 488 delta_base->offset = obj->idx.offset - base_offset;
d8f32556 489 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
c2b97ecf 490 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
53dda6ff 491 break;
9cf6d335
SV
492 case OBJ_COMMIT:
493 case OBJ_TREE:
494 case OBJ_BLOB:
495 case OBJ_TAG:
9cf6d335
SV
496 break;
497 default:
c2b97ecf 498 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
9cf6d335 499 }
aa7e44bf 500 obj->hdr_size = consumed_bytes - obj->idx.offset;
2d477051 501
681b07de 502 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, sha1);
aa7e44bf 503 obj->idx.crc32 = input_crc32;
ee5743ce 504 return data;
2d477051
NP
505}
506
8a2e163c
NTND
507static void *unpack_data(struct object_entry *obj,
508 int (*consume)(const unsigned char *, unsigned long, void *),
509 void *cb_data)
2d477051 510{
a91ef6e7 511 off_t from = obj[0].idx.offset + obj[0].hdr_size;
aa7e44bf 512 unsigned long len = obj[1].idx.offset - from;
776ea370 513 unsigned char *data, *inbuf;
ef49a7a0 514 git_zstream stream;
776ea370 515 int status;
9cf6d335 516
8a2e163c 517 data = xmalloc(consume ? 64*1024 : obj->size);
776ea370
NP
518 inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
519
2d477051 520 memset(&stream, 0, sizeof(stream));
776ea370 521 git_inflate_init(&stream);
2d477051 522 stream.next_out = data;
8a2e163c 523 stream.avail_out = consume ? 64*1024 : obj->size;
776ea370
NP
524
525 do {
8a2e163c 526 unsigned char *last_out = stream.next_out;
776ea370
NP
527 ssize_t n = (len < 64*1024) ? len : 64*1024;
528 n = pread(pack_fd, inbuf, n, from);
529 if (n < 0)
c2b97ecf 530 die_errno(_("cannot pread pack file"));
776ea370 531 if (!n)
c2b97ecf
NTND
532 die(Q_("premature end of pack file, %lu byte missing",
533 "premature end of pack file, %lu bytes missing",
534 len),
535 len);
776ea370
NP
536 from += n;
537 len -= n;
538 stream.next_in = inbuf;
539 stream.avail_in = n;
540 status = git_inflate(&stream, 0);
8a2e163c
NTND
541 if (consume) {
542 if (consume(last_out, stream.next_out - last_out, cb_data)) {
543 free(inbuf);
544 free(data);
545 return NULL;
546 }
547 stream.next_out = data;
548 stream.avail_out = 64*1024;
549 }
776ea370
NP
550 } while (len && status == Z_OK && !stream.avail_in);
551
552 /* This has been inflated OK when first encountered, so... */
553 if (status != Z_STREAM_END || stream.total_out != obj->size)
c2b97ecf 554 die(_("serious inflate inconsistency"));
776ea370
NP
555
556 git_inflate_end(&stream);
557 free(inbuf);
8a2e163c
NTND
558 if (consume) {
559 free(data);
560 data = NULL;
561 }
9cf6d335
SV
562 return data;
563}
564
8a2e163c
NTND
565static void *get_data_from_pack(struct object_entry *obj)
566{
567 return unpack_data(obj, NULL, NULL);
568}
569
7218a215
JH
570static int compare_delta_bases(const union delta_base *base1,
571 const union delta_base *base2,
572 enum object_type type1,
573 enum object_type type2)
574{
575 int cmp = type1 - type2;
576 if (cmp)
577 return cmp;
578 return memcmp(base1, base2, UNION_BASE_SZ);
579}
580
581static int find_delta(const union delta_base *base, enum object_type type)
9cf6d335
SV
582{
583 int first = 0, last = nr_deltas;
584
585 while (first < last) {
586 int next = (first + last) / 2;
587 struct delta_entry *delta = &deltas[next];
588 int cmp;
589
7218a215
JH
590 cmp = compare_delta_bases(base, &delta->base,
591 type, objects[delta->obj_no].type);
9cf6d335
SV
592 if (!cmp)
593 return next;
594 if (cmp < 0) {
595 last = next;
596 continue;
597 }
598 first = next+1;
599 }
600 return -first-1;
601}
602
6a87ed97 603static void find_delta_children(const union delta_base *base,
7218a215
JH
604 int *first_index, int *last_index,
605 enum object_type type)
9cf6d335 606{
7218a215 607 int first = find_delta(base, type);
9cf6d335
SV
608 int last = first;
609 int end = nr_deltas - 1;
610
6a87ed97
NP
611 if (first < 0) {
612 *first_index = 0;
613 *last_index = -1;
614 return;
615 }
3c552873 616 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
9cf6d335 617 --first;
3c552873 618 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
9cf6d335
SV
619 ++last;
620 *first_index = first;
621 *last_index = last;
9cf6d335
SV
622}
623
9ec2dde9
NTND
624static void sha1_object(const void *data, struct object_entry *obj_entry,
625 unsigned long size, enum object_type type,
626 const unsigned char *sha1)
9cf6d335 627{
9ec2dde9
NTND
628 void *new_data = NULL;
629
630 assert(data || obj_entry);
631
b8a2486f 632 read_lock();
9096c660 633 if (has_sha1_file(sha1)) {
8685da42
NP
634 void *has_data;
635 enum object_type has_type;
636 unsigned long has_size;
9ec2dde9
NTND
637 if (!data)
638 data = new_data = get_data_from_pack(obj_entry);
8685da42 639 has_data = read_sha1_file(sha1, &has_type, &has_size);
b8a2486f 640 read_unlock();
8685da42 641 if (!has_data)
c2b97ecf 642 die(_("cannot read existing object %s"), sha1_to_hex(sha1));
8685da42
NP
643 if (size != has_size || type != has_type ||
644 memcmp(data, has_data, size) != 0)
c2b97ecf 645 die(_("SHA1 COLLISION FOUND WITH %s !"), sha1_to_hex(sha1));
bbf4b41b 646 free(has_data);
b8a2486f
NTND
647 } else
648 read_unlock();
649
0153be05 650 if (strict) {
b8a2486f 651 read_lock();
0153be05
MK
652 if (type == OBJ_BLOB) {
653 struct blob *blob = lookup_blob(sha1);
654 if (blob)
655 blob->object.flags |= FLAG_CHECKED;
656 else
c2b97ecf 657 die(_("invalid blob object %s"), sha1_to_hex(sha1));
0153be05
MK
658 } else {
659 struct object *obj;
660 int eaten;
661 void *buf = (void *) data;
662
9ec2dde9
NTND
663 if (!buf)
664 buf = new_data = get_data_from_pack(obj_entry);
665
0153be05
MK
666 /*
667 * we do not need to free the memory here, as the
668 * buf is deleted by the caller.
669 */
670 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
671 if (!obj)
c2b97ecf 672 die(_("invalid %s"), typename(type));
0153be05 673 if (fsck_object(obj, 1, fsck_error_function))
c2b97ecf 674 die(_("Error in object"));
2af202be 675 if (fsck_walk(obj, mark_link, NULL))
c2b97ecf 676 die(_("Not all child objects of %s are reachable"), sha1_to_hex(obj->sha1));
0153be05
MK
677
678 if (obj->type == OBJ_TREE) {
679 struct tree *item = (struct tree *) obj;
680 item->buffer = NULL;
681 }
682 if (obj->type == OBJ_COMMIT) {
683 struct commit *commit = (struct commit *) obj;
684 commit->buffer = NULL;
685 }
686 obj->flags |= FLAG_CHECKED;
687 }
b8a2486f 688 read_unlock();
0153be05 689 }
9ec2dde9
NTND
690
691 free(new_data);
9cf6d335
SV
692}
693
20e95d0a
NTND
694/*
695 * This function is part of find_unresolved_deltas(). There are two
696 * walkers going in the opposite ways.
697 *
698 * The first one in find_unresolved_deltas() traverses down from
699 * parent node to children, deflating nodes along the way. However,
700 * memory for deflated nodes is limited by delta_base_cache_limit, so
701 * at some point parent node's deflated content may be freed.
702 *
703 * The second walker is this function, which goes from current node up
704 * to top parent if necessary to deflate the node. In normal
705 * situation, its parent node would be already deflated, so it just
706 * needs to apply delta.
707 *
708 * In the worst case scenario, parent node is no longer deflated because
709 * we're running out of delta_base_cache_limit; we need to re-deflate
710 * parents, possibly up to the top base.
711 *
712 * All deflated objects here are subject to be freed if we exceed
713 * delta_base_cache_limit, just like in find_unresolved_deltas(), we
714 * just need to make sure the last node is not freed.
715 */
92392b4a
SP
716static void *get_base_data(struct base_data *c)
717{
718 if (!c->data) {
719 struct object_entry *obj = c->obj;
20e95d0a
NTND
720 struct base_data **delta = NULL;
721 int delta_nr = 0, delta_alloc = 0;
92392b4a 722
20e95d0a
NTND
723 while (is_delta_type(c->obj->type) && !c->data) {
724 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
725 delta[delta_nr++] = c;
726 c = c->base;
727 }
728 if (!delta_nr) {
729 c->data = get_data_from_pack(obj);
730 c->size = obj->size;
b8a2486f 731 get_thread_data()->base_cache_used += c->size;
20e95d0a
NTND
732 prune_base_data(c);
733 }
734 for (; delta_nr > 0; delta_nr--) {
735 void *base, *raw;
736 c = delta[delta_nr - 1];
737 obj = c->obj;
738 base = get_base_data(c->base);
739 raw = get_data_from_pack(obj);
92392b4a
SP
740 c->data = patch_delta(
741 base, c->base->size,
742 raw, obj->size,
743 &c->size);
744 free(raw);
745 if (!c->data)
c2b97ecf 746 bad_object(obj->idx.offset, _("failed to apply delta"));
b8a2486f 747 get_thread_data()->base_cache_used += c->size;
20e95d0a 748 prune_base_data(c);
9441b61d 749 }
20e95d0a 750 free(delta);
92392b4a
SP
751 }
752 return c->data;
753}
754
f41aebd4 755static void resolve_delta(struct object_entry *delta_obj,
9441b61d 756 struct base_data *base, struct base_data *result)
9cf6d335 757{
ce3f6dc6 758 void *base_data, *delta_data;
9cf6d335 759
ce3f6dc6 760 delta_obj->real_type = base->obj->real_type;
38a45561 761 delta_obj->delta_depth = base->obj->delta_depth + 1;
d1a0ed18
JH
762 if (deepest_delta < delta_obj->delta_depth)
763 deepest_delta = delta_obj->delta_depth;
38a45561 764 delta_obj->base_object_no = base->obj - objects;
636171cb 765 delta_data = get_data_from_pack(delta_obj);
ce3f6dc6 766 base_data = get_base_data(base);
9441b61d 767 result->obj = delta_obj;
ce3f6dc6
NP
768 result->data = patch_delta(base_data, base->size,
769 delta_data, delta_obj->size, &result->size);
9cf6d335 770 free(delta_data);
9441b61d 771 if (!result->data)
c2b97ecf 772 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
681b07de
NTND
773 hash_sha1_file(result->data, result->size,
774 typename(delta_obj->real_type), delta_obj->idx.sha1);
9ec2dde9 775 sha1_object(result->data, NULL, result->size, delta_obj->real_type,
9441b61d 776 delta_obj->idx.sha1);
b8a2486f 777 counter_lock();
636171cb 778 nr_resolved_deltas++;
b8a2486f 779 counter_unlock();
9441b61d
NP
780}
781
2baad220
NTND
782static struct base_data *find_unresolved_deltas_1(struct base_data *base,
783 struct base_data *prev_base)
9441b61d 784{
2baad220 785 if (base->ref_last == -1 && base->ofs_last == -1) {
9441b61d
NP
786 union delta_base base_spec;
787
788 hashcpy(base_spec.sha1, base->obj->idx.sha1);
7218a215 789 find_delta_children(&base_spec,
2baad220 790 &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
53dda6ff 791
9441b61d
NP
792 memset(&base_spec, 0, sizeof(base_spec));
793 base_spec.offset = base->obj->idx.offset;
7218a215 794 find_delta_children(&base_spec,
2baad220 795 &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
4a438cab 796
2baad220
NTND
797 if (base->ref_last == -1 && base->ofs_last == -1) {
798 free(base->data);
799 return NULL;
800 }
53dda6ff 801
2baad220
NTND
802 link_base_data(prev_base, base);
803 }
4a438cab 804
2baad220
NTND
805 if (base->ref_first <= base->ref_last) {
806 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
807 struct base_data *result = alloc_base_data();
7218a215
JH
808
809 assert(child->real_type == OBJ_REF_DELTA);
2baad220
NTND
810 resolve_delta(child, base, result);
811 if (base->ref_first == base->ref_last && base->ofs_last == -1)
7218a215 812 free_base_data(base);
2baad220
NTND
813
814 base->ref_first++;
815 return result;
53dda6ff
NP
816 }
817
2baad220
NTND
818 if (base->ofs_first <= base->ofs_last) {
819 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
820 struct base_data *result = alloc_base_data();
7218a215
JH
821
822 assert(child->real_type == OBJ_OFS_DELTA);
2baad220
NTND
823 resolve_delta(child, base, result);
824 if (base->ofs_first == base->ofs_last)
7218a215 825 free_base_data(base);
2baad220
NTND
826
827 base->ofs_first++;
828 return result;
9cf6d335 829 }
53dda6ff 830
9441b61d 831 unlink_base_data(base);
2baad220
NTND
832 return NULL;
833}
834
835static void find_unresolved_deltas(struct base_data *base)
836{
837 struct base_data *new_base, *prev_base = NULL;
838 for (;;) {
839 new_base = find_unresolved_deltas_1(base, prev_base);
840
841 if (new_base) {
842 prev_base = base;
843 base = new_base;
844 } else {
845 free(base);
846 base = prev_base;
847 if (!base)
848 return;
849 prev_base = base->base;
850 }
851 }
9cf6d335
SV
852}
853
854static int compare_delta_entry(const void *a, const void *b)
855{
856 const struct delta_entry *delta_a = a;
857 const struct delta_entry *delta_b = b;
7218a215
JH
858
859 /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
860 return compare_delta_bases(&delta_a->base, &delta_b->base,
861 objects[delta_a->obj_no].type,
862 objects[delta_b->obj_no].type);
9cf6d335
SV
863}
864
5272f755
NTND
865static void resolve_base(struct object_entry *obj)
866{
867 struct base_data *base_obj = alloc_base_data();
868 base_obj->obj = obj;
869 base_obj->data = NULL;
870 find_unresolved_deltas(base_obj);
871}
872
b8a2486f
NTND
873#ifndef NO_PTHREADS
874static void *threaded_second_pass(void *data)
875{
876 set_thread_data(data);
877 for (;;) {
878 int i;
879 work_lock();
880 display_progress(progress, nr_resolved_deltas);
881 while (nr_dispatched < nr_objects &&
882 is_delta_type(objects[nr_dispatched].type))
883 nr_dispatched++;
884 if (nr_dispatched >= nr_objects) {
885 work_unlock();
886 break;
887 }
888 i = nr_dispatched++;
889 work_unlock();
890
891 resolve_base(&objects[i]);
892 }
893 return NULL;
894}
895#endif
896
5272f755
NTND
897/*
898 * First pass:
899 * - find locations of all objects;
900 * - calculate SHA1 of all non-delta objects;
901 * - remember base (SHA1 or offset) for all deltas.
902 */
2d477051 903static void parse_pack_objects(unsigned char *sha1)
9cf6d335 904{
9ec2dde9 905 int i, nr_delays = 0;
53dda6ff 906 struct delta_entry *delta = deltas;
2d477051 907 struct stat st;
9cf6d335 908
13aaf148 909 if (verbose)
29e63ed3 910 progress = start_progress(
c2b97ecf 911 from_stdin ? _("Receiving objects") : _("Indexing objects"),
29e63ed3 912 nr_objects);
9cf6d335
SV
913 for (i = 0; i < nr_objects; i++) {
914 struct object_entry *obj = &objects[i];
681b07de 915 void *data = unpack_raw_entry(obj, &delta->base, obj->idx.sha1);
9cf6d335 916 obj->real_type = obj->type;
4f8ec74e 917 if (is_delta_type(obj->type)) {
53dda6ff 918 nr_deltas++;
636171cb 919 delta->obj_no = i;
53dda6ff 920 delta++;
9ec2dde9
NTND
921 } else if (!data) {
922 /* large blobs, check later */
923 obj->real_type = OBJ_BAD;
924 nr_delays++;
9cf6d335 925 } else
9ec2dde9 926 sha1_object(data, NULL, obj->size, obj->type, obj->idx.sha1);
9cf6d335 927 free(data);
4d4fcc54 928 display_progress(progress, i+1);
9cf6d335 929 }
aa7e44bf 930 objects[i].idx.offset = consumed_bytes;
4d4fcc54 931 stop_progress(&progress);
2d477051
NP
932
933 /* Check pack integrity */
636171cb 934 flush();
9126f009 935 git_SHA1_Final(sha1, &input_ctx);
2d477051 936 if (hashcmp(fill(20), sha1))
c2b97ecf 937 die(_("pack is corrupted (SHA1 mismatch)"));
9bee2478 938 use(20);
2d477051
NP
939
940 /* If input_fd is a file, we should have reached its end now. */
941 if (fstat(input_fd, &st))
c2b97ecf 942 die_errno(_("cannot fstat packfile"));
fa257b05
JS
943 if (S_ISREG(st.st_mode) &&
944 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
c2b97ecf 945 die(_("pack has junk at the end"));
9ec2dde9
NTND
946
947 for (i = 0; i < nr_objects; i++) {
948 struct object_entry *obj = &objects[i];
949 if (obj->real_type != OBJ_BAD)
950 continue;
951 obj->real_type = obj->type;
952 sha1_object(NULL, obj, obj->size, obj->type, obj->idx.sha1);
953 nr_delays--;
954 }
955 if (nr_delays)
956 die(_("confusion beyond insanity in parse_pack_objects()"));
5272f755
NTND
957}
958
959/*
960 * Second pass:
961 * - for all non-delta objects, look if it is used as a base for
962 * deltas;
963 * - if used as a base, uncompress the object and apply all deltas,
964 * recursively checking if the resulting object is used as a base
965 * for some more deltas.
966 */
967static void resolve_deltas(void)
968{
969 int i;
9cf6d335 970
3c9af366
NP
971 if (!nr_deltas)
972 return;
973
53dda6ff 974 /* Sort deltas by base SHA1/offset for fast searching */
9cf6d335
SV
975 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
976 compare_delta_entry);
977
13aaf148 978 if (verbose)
c2b97ecf 979 progress = start_progress(_("Resolving deltas"), nr_deltas);
b8a2486f
NTND
980
981#ifndef NO_PTHREADS
982 nr_dispatched = 0;
983 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
984 init_thread();
985 for (i = 0; i < nr_threads; i++) {
986 int ret = pthread_create(&thread_data[i].thread, NULL,
987 threaded_second_pass, thread_data + i);
988 if (ret)
989 die("unable to create thread: %s", strerror(ret));
990 }
991 for (i = 0; i < nr_threads; i++)
992 pthread_join(thread_data[i].thread, NULL);
993 cleanup_thread();
994 return;
995 }
996#endif
997
9cf6d335
SV
998 for (i = 0; i < nr_objects; i++) {
999 struct object_entry *obj = &objects[i];
9cf6d335 1000
4f8ec74e 1001 if (is_delta_type(obj->type))
9cf6d335 1002 continue;
5272f755 1003 resolve_base(obj);
4d4fcc54 1004 display_progress(progress, nr_resolved_deltas);
9cf6d335 1005 }
636171cb
NP
1006}
1007
5272f755
NTND
1008/*
1009 * Third pass:
1010 * - append objects to convert thin pack to full pack if required
1011 * - write the final 20-byte SHA-1
1012 */
1013static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
1014static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
1015{
1016 if (nr_deltas == nr_resolved_deltas) {
1017 stop_progress(&progress);
1018 /* Flush remaining pack final 20-byte SHA1. */
1019 flush();
1020 return;
1021 }
1022
1023 if (fix_thin_pack) {
1024 struct sha1file *f;
1025 unsigned char read_sha1[20], tail_sha1[20];
1026 char msg[48];
1027 int nr_unresolved = nr_deltas - nr_resolved_deltas;
1028 int nr_objects_initial = nr_objects;
1029 if (nr_unresolved <= 0)
cc13431a 1030 die(_("confusion beyond insanity"));
5272f755
NTND
1031 objects = xrealloc(objects,
1032 (nr_objects + nr_unresolved + 1)
1033 * sizeof(*objects));
1034 f = sha1fd(output_fd, curr_pack);
1035 fix_unresolved_deltas(f, nr_unresolved);
1036 sprintf(msg, "completed with %d local objects",
1037 nr_objects - nr_objects_initial);
1038 stop_progress_msg(&progress, msg);
1039 sha1close(f, tail_sha1, 0);
1040 hashcpy(read_sha1, pack_sha1);
1041 fixup_pack_header_footer(output_fd, pack_sha1,
1042 curr_pack, nr_objects,
1043 read_sha1, consumed_bytes-20);
1044 if (hashcmp(read_sha1, tail_sha1) != 0)
1045 die("Unexpected tail checksum for %s "
1046 "(disk corruption?)", curr_pack);
1047 }
1048 if (nr_deltas != nr_resolved_deltas)
cc13431a
JH
1049 die(Q_("pack has %d unresolved delta",
1050 "pack has %d unresolved deltas",
1051 nr_deltas - nr_resolved_deltas),
5272f755
NTND
1052 nr_deltas - nr_resolved_deltas);
1053}
1054
8522148f 1055static int write_compressed(struct sha1file *f, void *in, unsigned int size)
636171cb 1056{
ef49a7a0 1057 git_zstream stream;
7734d7f2
NP
1058 int status;
1059 unsigned char outbuf[4096];
636171cb
NP
1060
1061 memset(&stream, 0, sizeof(stream));
55bb5c91 1062 git_deflate_init(&stream, zlib_compression_level);
636171cb
NP
1063 stream.next_in = in;
1064 stream.avail_in = size;
636171cb 1065
7734d7f2
NP
1066 do {
1067 stream.next_out = outbuf;
1068 stream.avail_out = sizeof(outbuf);
55bb5c91 1069 status = git_deflate(&stream, Z_FINISH);
7734d7f2
NP
1070 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
1071 } while (status == Z_OK);
1072
1073 if (status != Z_STREAM_END)
c2b97ecf 1074 die(_("unable to deflate appended object (%d)"), status);
636171cb 1075 size = stream.total_out;
55bb5c91 1076 git_deflate_end(&stream);
636171cb
NP
1077 return size;
1078}
1079
8522148f 1080static struct object_entry *append_obj_to_pack(struct sha1file *f,
03993e13 1081 const unsigned char *sha1, void *buf,
636171cb
NP
1082 unsigned long size, enum object_type type)
1083{
1084 struct object_entry *obj = &objects[nr_objects++];
1085 unsigned char header[10];
1086 unsigned long s = size;
1087 int n = 0;
1088 unsigned char c = (type << 4) | (s & 15);
1089 s >>= 4;
1090 while (s) {
1091 header[n++] = c | 0x80;
1092 c = s & 0x7f;
1093 s >>= 7;
1094 }
1095 header[n++] = c;
8522148f
NP
1096 crc32_begin(f);
1097 sha1write(f, header, n);
72de2883
BS
1098 obj[0].size = size;
1099 obj[0].hdr_size = n;
1100 obj[0].type = type;
1101 obj[0].real_type = type;
aa7e44bf 1102 obj[1].idx.offset = obj[0].idx.offset + n;
8522148f
NP
1103 obj[1].idx.offset += write_compressed(f, buf, size);
1104 obj[0].idx.crc32 = crc32_end(f);
838cd346 1105 sha1flush(f);
aa7e44bf 1106 hashcpy(obj->idx.sha1, sha1);
03993e13 1107 return obj;
636171cb
NP
1108}
1109
1110static int delta_pos_compare(const void *_a, const void *_b)
1111{
1112 struct delta_entry *a = *(struct delta_entry **)_a;
1113 struct delta_entry *b = *(struct delta_entry **)_b;
1114 return a->obj_no - b->obj_no;
1115}
9cf6d335 1116
8522148f 1117static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
636171cb
NP
1118{
1119 struct delta_entry **sorted_by_pos;
96a02f8f 1120 int i, n = 0;
636171cb
NP
1121
1122 /*
1123 * Since many unresolved deltas may well be themselves base objects
1124 * for more unresolved deltas, we really want to include the
1125 * smallest number of base objects that would cover as much delta
1126 * as possible by picking the
1127 * trunc deltas first, allowing for other deltas to resolve without
1128 * additional base objects. Since most base objects are to be found
1129 * before deltas depending on them, a good heuristic is to start
1130 * resolving deltas in the same order as their position in the pack.
1131 */
1132 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
9cf6d335 1133 for (i = 0; i < nr_deltas; i++) {
636171cb
NP
1134 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
1135 continue;
1136 sorted_by_pos[n++] = &deltas[i];
9cf6d335 1137 }
636171cb
NP
1138 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
1139
1140 for (i = 0; i < n; i++) {
1141 struct delta_entry *d = sorted_by_pos[i];
21666f1a 1142 enum object_type type;
2baad220 1143 struct base_data *base_obj = alloc_base_data();
636171cb
NP
1144
1145 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1146 continue;
2baad220
NTND
1147 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
1148 if (!base_obj->data)
636171cb 1149 continue;
636171cb 1150
2baad220
NTND
1151 if (check_sha1_signature(d->base.sha1, base_obj->data,
1152 base_obj->size, typename(type)))
c2b97ecf 1153 die(_("local object %s is corrupt"), sha1_to_hex(d->base.sha1));
2baad220
NTND
1154 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
1155 base_obj->data, base_obj->size, type);
1156 find_unresolved_deltas(base_obj);
4d4fcc54 1157 display_progress(progress, nr_resolved_deltas);
636171cb
NP
1158 }
1159 free(sorted_by_pos);
1160}
1161
e42797f5
NP
1162static void final(const char *final_pack_name, const char *curr_pack_name,
1163 const char *final_index_name, const char *curr_index_name,
b8077709 1164 const char *keep_name, const char *keep_msg,
e42797f5
NP
1165 unsigned char *sha1)
1166{
3a55602e 1167 const char *report = "pack";
e42797f5
NP
1168 char name[PATH_MAX];
1169 int err;
1170
1171 if (!from_stdin) {
1172 close(input_fd);
1173 } else {
4c81b03e 1174 fsync_or_die(output_fd, curr_pack_name);
e42797f5
NP
1175 err = close(output_fd);
1176 if (err)
c2b97ecf 1177 die_errno(_("error while closing pack file"));
e42797f5
NP
1178 }
1179
b8077709
SP
1180 if (keep_msg) {
1181 int keep_fd, keep_msg_len = strlen(keep_msg);
6e180cdc
JH
1182
1183 if (!keep_name)
1184 keep_fd = odb_pack_keep(name, sizeof(name), sha1);
1185 else
1186 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
1187
9ca4a201
NP
1188 if (keep_fd < 0) {
1189 if (errno != EEXIST)
c2b97ecf 1190 die_errno(_("cannot write keep file '%s'"),
d824cbba 1191 keep_name);
9ca4a201
NP
1192 } else {
1193 if (keep_msg_len > 0) {
1194 write_or_die(keep_fd, keep_msg, keep_msg_len);
1195 write_or_die(keep_fd, "\n", 1);
1196 }
91c8d590 1197 if (close(keep_fd) != 0)
c2b97ecf 1198 die_errno(_("cannot close written keep file '%s'"),
d824cbba 1199 keep_name);
576162a4 1200 report = "keep";
b8077709 1201 }
b8077709
SP
1202 }
1203
e42797f5
NP
1204 if (final_pack_name != curr_pack_name) {
1205 if (!final_pack_name) {
1206 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
1207 get_object_directory(), sha1_to_hex(sha1));
1208 final_pack_name = name;
1209 }
1210 if (move_temp_to_file(curr_pack_name, final_pack_name))
c2b97ecf 1211 die(_("cannot store pack file"));
fb8b1936 1212 } else if (from_stdin)
33b65030 1213 chmod(final_pack_name, 0444);
e42797f5 1214
e42797f5
NP
1215 if (final_index_name != curr_index_name) {
1216 if (!final_index_name) {
1217 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
1218 get_object_directory(), sha1_to_hex(sha1));
1219 final_index_name = name;
1220 }
1221 if (move_temp_to_file(curr_index_name, final_index_name))
c2b97ecf 1222 die(_("cannot store index file"));
fb8b1936
JH
1223 } else
1224 chmod(final_index_name, 0444);
576162a4
NP
1225
1226 if (!from_stdin) {
1227 printf("%s\n", sha1_to_hex(sha1));
1228 } else {
1229 char buf[48];
1230 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
1231 report, sha1_to_hex(sha1));
d1b2ddc8 1232 write_or_die(1, buf, len);
576162a4
NP
1233
1234 /*
1235 * Let's just mimic git-unpack-objects here and write
1236 * the last part of the input buffer to stdout.
1237 */
1238 while (input_len) {
1239 err = xwrite(1, input_buffer + input_offset, input_len);
1240 if (err <= 0)
1241 break;
1242 input_len -= err;
1243 input_offset += err;
1244 }
1245 }
9cf6d335
SV
1246}
1247
ef90d6d4 1248static int git_index_pack_config(const char *k, const char *v, void *cb)
4d00bda2 1249{
ebcfb379
JH
1250 struct pack_idx_option *opts = cb;
1251
4d00bda2 1252 if (!strcmp(k, "pack.indexversion")) {
ebcfb379
JH
1253 opts->version = git_config_int(k, v);
1254 if (opts->version > 2)
1255 die("bad pack.indexversion=%"PRIu32, opts->version);
4d00bda2
NP
1256 return 0;
1257 }
b8a2486f
NTND
1258 if (!strcmp(k, "pack.threads")) {
1259 nr_threads = git_config_int(k, v);
1260 if (nr_threads < 0)
1261 die("invalid number of threads specified (%d)",
1262 nr_threads);
1263#ifdef NO_PTHREADS
1264 if (nr_threads != 1)
1265 warning("no threads support, ignoring %s", k);
1266 nr_threads = 1;
1267#endif
1268 return 0;
1269 }
ef90d6d4 1270 return git_default_config(k, v, cb);
4d00bda2
NP
1271}
1272
3c9fc074
JH
1273static int cmp_uint32(const void *a_, const void *b_)
1274{
1275 uint32_t a = *((uint32_t *)a_);
1276 uint32_t b = *((uint32_t *)b_);
1277
1278 return (a < b) ? -1 : (a != b);
1279}
1280
1281static void read_v2_anomalous_offsets(struct packed_git *p,
1282 struct pack_idx_option *opts)
1283{
1284 const uint32_t *idx1, *idx2;
1285 uint32_t i;
1286
1287 /* The address of the 4-byte offset table */
1288 idx1 = (((const uint32_t *)p->index_data)
1289 + 2 /* 8-byte header */
1290 + 256 /* fan out */
1291 + 5 * p->num_objects /* 20-byte SHA-1 table */
1292 + p->num_objects /* CRC32 table */
1293 );
1294
1295 /* The address of the 8-byte offset table */
1296 idx2 = idx1 + p->num_objects;
1297
1298 for (i = 0; i < p->num_objects; i++) {
1299 uint32_t off = ntohl(idx1[i]);
1300 if (!(off & 0x80000000))
1301 continue;
1302 off = off & 0x7fffffff;
1303 if (idx2[off * 2])
1304 continue;
1305 /*
1306 * The real offset is ntohl(idx2[off * 2]) in high 4
1307 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1308 * octets. But idx2[off * 2] is Zero!!!
1309 */
1310 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1311 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1312 }
1313
1314 if (1 < opts->anomaly_nr)
1315 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1316}
1317
e337a04d
JH
1318static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1319{
1320 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1321
1322 if (!p)
c2b97ecf 1323 die(_("Cannot open existing pack file '%s'"), pack_name);
e337a04d 1324 if (open_pack_index(p))
c2b97ecf 1325 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
e337a04d
JH
1326
1327 /* Read the attributes from the existing idx file */
1328 opts->version = p->index_version;
1329
3c9fc074
JH
1330 if (opts->version == 2)
1331 read_v2_anomalous_offsets(p, opts);
1332
e337a04d
JH
1333 /*
1334 * Get rid of the idx file as we do not need it anymore.
1335 * NEEDSWORK: extract this bit from free_pack_by_name() in
1336 * sha1_file.c, perhaps? It shouldn't matter very much as we
1337 * know we haven't installed this pack (hence we never have
1338 * read anything from it).
1339 */
1340 close_pack_index(p);
1341 free(p);
1342}
1343
38a45561
JH
1344static void show_pack_info(int stat_only)
1345{
d1a0ed18
JH
1346 int i, baseobjects = nr_objects - nr_deltas;
1347 unsigned long *chain_histogram = NULL;
1348
1349 if (deepest_delta)
1350 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1351
38a45561
JH
1352 for (i = 0; i < nr_objects; i++) {
1353 struct object_entry *obj = &objects[i];
1354
d1a0ed18
JH
1355 if (is_delta_type(obj->type))
1356 chain_histogram[obj->delta_depth - 1]++;
38a45561
JH
1357 if (stat_only)
1358 continue;
1359 printf("%s %-6s %lu %lu %"PRIuMAX,
1360 sha1_to_hex(obj->idx.sha1),
1361 typename(obj->real_type), obj->size,
1362 (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1363 (uintmax_t)obj->idx.offset);
1364 if (is_delta_type(obj->type)) {
1365 struct object_entry *bobj = &objects[obj->base_object_no];
1366 printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1367 }
1368 putchar('\n');
1369 }
d1a0ed18
JH
1370
1371 if (baseobjects)
c2b97ecf
NTND
1372 printf_ln(Q_("non delta: %d object",
1373 "non delta: %d objects",
1374 baseobjects),
1375 baseobjects);
d1a0ed18
JH
1376 for (i = 0; i < deepest_delta; i++) {
1377 if (!chain_histogram[i])
1378 continue;
c2b97ecf
NTND
1379 printf_ln(Q_("chain length = %d: %lu object",
1380 "chain length = %d: %lu objects",
1381 chain_histogram[i]),
1382 i + 1,
1383 chain_histogram[i]);
d1a0ed18 1384 }
38a45561
JH
1385}
1386
3bb72562 1387int cmd_index_pack(int argc, const char **argv, const char *prefix)
9cf6d335 1388{
38a45561 1389 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
3bb72562
LT
1390 const char *curr_pack, *curr_index;
1391 const char *index_name = NULL, *pack_name = NULL;
b8077709
SP
1392 const char *keep_name = NULL, *keep_msg = NULL;
1393 char *index_name_buf = NULL, *keep_name_buf = NULL;
aa7e44bf 1394 struct pack_idx_entry **idx_objects;
ebcfb379 1395 struct pack_idx_option opts;
8522148f 1396 unsigned char pack_sha1[20];
9cf6d335 1397
99caeed0
JN
1398 if (argc == 2 && !strcmp(argv[1], "-h"))
1399 usage(index_pack_usage);
1400
6e2a09d2
NE
1401 read_replace_refs = 0;
1402
ebcfb379
JH
1403 reset_pack_idx_option(&opts);
1404 git_config(git_index_pack_config, &opts);
3f8099fc 1405 if (prefix && chdir(prefix))
c2b97ecf 1406 die(_("Cannot come back to cwd"));
4d00bda2 1407
9cf6d335 1408 for (i = 1; i < argc; i++) {
3bb72562 1409 const char *arg = argv[i];
9cf6d335
SV
1410
1411 if (*arg == '-') {
e42797f5
NP
1412 if (!strcmp(arg, "--stdin")) {
1413 from_stdin = 1;
636171cb
NP
1414 } else if (!strcmp(arg, "--fix-thin")) {
1415 fix_thin_pack = 1;
0153be05
MK
1416 } else if (!strcmp(arg, "--strict")) {
1417 strict = 1;
e337a04d
JH
1418 } else if (!strcmp(arg, "--verify")) {
1419 verify = 1;
38a45561
JH
1420 } else if (!strcmp(arg, "--verify-stat")) {
1421 verify = 1;
1422 stat = 1;
1423 } else if (!strcmp(arg, "--verify-stat-only")) {
1424 verify = 1;
1425 stat = 1;
1426 stat_only = 1;
b8077709
SP
1427 } else if (!strcmp(arg, "--keep")) {
1428 keep_msg = "";
cc44c765 1429 } else if (!prefixcmp(arg, "--keep=")) {
b8077709 1430 keep_msg = arg + 7;
b8a2486f
NTND
1431 } else if (!prefixcmp(arg, "--threads=")) {
1432 char *end;
1433 nr_threads = strtoul(arg+10, &end, 0);
1434 if (!arg[10] || *end || nr_threads < 0)
1435 usage(index_pack_usage);
1436#ifdef NO_PTHREADS
1437 if (nr_threads != 1)
1438 warning("no threads support, "
1439 "ignoring %s", arg);
1440 nr_threads = 1;
1441#endif
cc44c765 1442 } else if (!prefixcmp(arg, "--pack_header=")) {
bed006fb
NP
1443 struct pack_header *hdr;
1444 char *c;
1445
1446 hdr = (struct pack_header *)input_buffer;
1447 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1448 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1449 if (*c != ',')
c2b97ecf 1450 die(_("bad %s"), arg);
bed006fb
NP
1451 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1452 if (*c)
c2b97ecf 1453 die(_("bad %s"), arg);
bed006fb 1454 input_len = sizeof(*hdr);
3c9af366
NP
1455 } else if (!strcmp(arg, "-v")) {
1456 verbose = 1;
e42797f5 1457 } else if (!strcmp(arg, "-o")) {
9cf6d335
SV
1458 if (index_name || (i+1) >= argc)
1459 usage(index_pack_usage);
1460 index_name = argv[++i];
4ba7d711
NP
1461 } else if (!prefixcmp(arg, "--index-version=")) {
1462 char *c;
ebcfb379
JH
1463 opts.version = strtoul(arg + 16, &c, 10);
1464 if (opts.version > 2)
c2b97ecf 1465 die(_("bad %s"), arg);
4ba7d711 1466 if (*c == ',')
ebcfb379
JH
1467 opts.off32_limit = strtoul(c+1, &c, 0);
1468 if (*c || opts.off32_limit & 0x80000000)
c2b97ecf 1469 die(_("bad %s"), arg);
9cf6d335
SV
1470 } else
1471 usage(index_pack_usage);
1472 continue;
1473 }
1474
1475 if (pack_name)
1476 usage(index_pack_usage);
1477 pack_name = arg;
1478 }
1479
e42797f5 1480 if (!pack_name && !from_stdin)
9cf6d335 1481 usage(index_pack_usage);
636171cb 1482 if (fix_thin_pack && !from_stdin)
c2b97ecf 1483 die(_("--fix-thin cannot be used without --stdin"));
e42797f5 1484 if (!index_name && pack_name) {
9cf6d335 1485 int len = strlen(pack_name);
5bb1cda5 1486 if (!has_extension(pack_name, ".pack"))
c2b97ecf 1487 die(_("packfile name '%s' does not end with '.pack'"),
9cf6d335 1488 pack_name);
6689f087 1489 index_name_buf = xmalloc(len);
9cf6d335
SV
1490 memcpy(index_name_buf, pack_name, len - 5);
1491 strcpy(index_name_buf + len - 5, ".idx");
1492 index_name = index_name_buf;
1493 }
b8077709
SP
1494 if (keep_msg && !keep_name && pack_name) {
1495 int len = strlen(pack_name);
1496 if (!has_extension(pack_name, ".pack"))
c2b97ecf 1497 die(_("packfile name '%s' does not end with '.pack'"),
b8077709
SP
1498 pack_name);
1499 keep_name_buf = xmalloc(len);
1500 memcpy(keep_name_buf, pack_name, len - 5);
1501 strcpy(keep_name_buf + len - 5, ".keep");
1502 keep_name = keep_name_buf;
1503 }
e337a04d
JH
1504 if (verify) {
1505 if (!index_name)
c2b97ecf 1506 die(_("--verify with no packfile name given"));
e337a04d 1507 read_idx_option(&opts, index_name);
68be2fea 1508 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
e337a04d 1509 }
68be2fea
JH
1510 if (strict)
1511 opts.flags |= WRITE_IDX_STRICT;
9cf6d335 1512
b8a2486f
NTND
1513#ifndef NO_PTHREADS
1514 if (!nr_threads) {
1515 nr_threads = online_cpus();
1516 /* An experiment showed that more threads does not mean faster */
1517 if (nr_threads > 3)
1518 nr_threads = 3;
1519 }
1520#endif
1521
e42797f5 1522 curr_pack = open_pack_file(pack_name);
9cf6d335 1523 parse_pack_header();
38a45561
JH
1524 objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1525 deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
8522148f 1526 parse_pack_objects(pack_sha1);
5272f755
NTND
1527 resolve_deltas();
1528 conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
9cf6d335 1529 free(deltas);
0153be05
MK
1530 if (strict)
1531 check_objects();
aa7e44bf 1532
38a45561
JH
1533 if (stat)
1534 show_pack_info(stat_only);
1535
aa7e44bf
GB
1536 idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1537 for (i = 0; i < nr_objects; i++)
1538 idx_objects[i] = &objects[i].idx;
ebcfb379 1539 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
aa7e44bf
GB
1540 free(idx_objects);
1541
e337a04d
JH
1542 if (!verify)
1543 final(pack_name, curr_pack,
1544 index_name, curr_index,
1545 keep_name, keep_msg,
1546 pack_sha1);
1547 else
1548 close(input_fd);
9cf6d335
SV
1549 free(objects);
1550 free(index_name_buf);
b8077709 1551 free(keep_name_buf);
c85228ed 1552 if (pack_name == NULL)
3bb72562 1553 free((void *) curr_pack);
c85228ed 1554 if (index_name == NULL)
3bb72562 1555 free((void *) curr_index);
9cf6d335
SV
1556
1557 return 0;
1558}