]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/index-pack.c
index-pack: use streaming interface on large blobs (most of the time)
[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
b89c4e93 507static void *get_data_from_pack(struct object_entry *obj)
2d477051 508{
a91ef6e7 509 off_t from = obj[0].idx.offset + obj[0].hdr_size;
aa7e44bf 510 unsigned long len = obj[1].idx.offset - from;
776ea370 511 unsigned char *data, *inbuf;
ef49a7a0 512 git_zstream stream;
776ea370 513 int status;
9cf6d335 514
2d477051 515 data = xmalloc(obj->size);
776ea370
NP
516 inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
517
2d477051 518 memset(&stream, 0, sizeof(stream));
776ea370 519 git_inflate_init(&stream);
2d477051
NP
520 stream.next_out = data;
521 stream.avail_out = obj->size;
776ea370
NP
522
523 do {
524 ssize_t n = (len < 64*1024) ? len : 64*1024;
525 n = pread(pack_fd, inbuf, n, from);
526 if (n < 0)
c2b97ecf 527 die_errno(_("cannot pread pack file"));
776ea370 528 if (!n)
c2b97ecf
NTND
529 die(Q_("premature end of pack file, %lu byte missing",
530 "premature end of pack file, %lu bytes missing",
531 len),
532 len);
776ea370
NP
533 from += n;
534 len -= n;
535 stream.next_in = inbuf;
536 stream.avail_in = n;
537 status = git_inflate(&stream, 0);
538 } while (len && status == Z_OK && !stream.avail_in);
539
540 /* This has been inflated OK when first encountered, so... */
541 if (status != Z_STREAM_END || stream.total_out != obj->size)
c2b97ecf 542 die(_("serious inflate inconsistency"));
776ea370
NP
543
544 git_inflate_end(&stream);
545 free(inbuf);
9cf6d335
SV
546 return data;
547}
548
7218a215
JH
549static int compare_delta_bases(const union delta_base *base1,
550 const union delta_base *base2,
551 enum object_type type1,
552 enum object_type type2)
553{
554 int cmp = type1 - type2;
555 if (cmp)
556 return cmp;
557 return memcmp(base1, base2, UNION_BASE_SZ);
558}
559
560static int find_delta(const union delta_base *base, enum object_type type)
9cf6d335
SV
561{
562 int first = 0, last = nr_deltas;
563
564 while (first < last) {
565 int next = (first + last) / 2;
566 struct delta_entry *delta = &deltas[next];
567 int cmp;
568
7218a215
JH
569 cmp = compare_delta_bases(base, &delta->base,
570 type, objects[delta->obj_no].type);
9cf6d335
SV
571 if (!cmp)
572 return next;
573 if (cmp < 0) {
574 last = next;
575 continue;
576 }
577 first = next+1;
578 }
579 return -first-1;
580}
581
6a87ed97 582static void find_delta_children(const union delta_base *base,
7218a215
JH
583 int *first_index, int *last_index,
584 enum object_type type)
9cf6d335 585{
7218a215 586 int first = find_delta(base, type);
9cf6d335
SV
587 int last = first;
588 int end = nr_deltas - 1;
589
6a87ed97
NP
590 if (first < 0) {
591 *first_index = 0;
592 *last_index = -1;
593 return;
594 }
3c552873 595 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
9cf6d335 596 --first;
3c552873 597 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
9cf6d335
SV
598 ++last;
599 *first_index = first;
600 *last_index = last;
9cf6d335
SV
601}
602
9ec2dde9
NTND
603static void sha1_object(const void *data, struct object_entry *obj_entry,
604 unsigned long size, enum object_type type,
605 const unsigned char *sha1)
9cf6d335 606{
9ec2dde9
NTND
607 void *new_data = NULL;
608
609 assert(data || obj_entry);
610
b8a2486f 611 read_lock();
9096c660 612 if (has_sha1_file(sha1)) {
8685da42
NP
613 void *has_data;
614 enum object_type has_type;
615 unsigned long has_size;
9ec2dde9
NTND
616 if (!data)
617 data = new_data = get_data_from_pack(obj_entry);
8685da42 618 has_data = read_sha1_file(sha1, &has_type, &has_size);
b8a2486f 619 read_unlock();
8685da42 620 if (!has_data)
c2b97ecf 621 die(_("cannot read existing object %s"), sha1_to_hex(sha1));
8685da42
NP
622 if (size != has_size || type != has_type ||
623 memcmp(data, has_data, size) != 0)
c2b97ecf 624 die(_("SHA1 COLLISION FOUND WITH %s !"), sha1_to_hex(sha1));
bbf4b41b 625 free(has_data);
b8a2486f
NTND
626 } else
627 read_unlock();
628
0153be05 629 if (strict) {
b8a2486f 630 read_lock();
0153be05
MK
631 if (type == OBJ_BLOB) {
632 struct blob *blob = lookup_blob(sha1);
633 if (blob)
634 blob->object.flags |= FLAG_CHECKED;
635 else
c2b97ecf 636 die(_("invalid blob object %s"), sha1_to_hex(sha1));
0153be05
MK
637 } else {
638 struct object *obj;
639 int eaten;
640 void *buf = (void *) data;
641
9ec2dde9
NTND
642 if (!buf)
643 buf = new_data = get_data_from_pack(obj_entry);
644
0153be05
MK
645 /*
646 * we do not need to free the memory here, as the
647 * buf is deleted by the caller.
648 */
649 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
650 if (!obj)
c2b97ecf 651 die(_("invalid %s"), typename(type));
0153be05 652 if (fsck_object(obj, 1, fsck_error_function))
c2b97ecf 653 die(_("Error in object"));
2af202be 654 if (fsck_walk(obj, mark_link, NULL))
c2b97ecf 655 die(_("Not all child objects of %s are reachable"), sha1_to_hex(obj->sha1));
0153be05
MK
656
657 if (obj->type == OBJ_TREE) {
658 struct tree *item = (struct tree *) obj;
659 item->buffer = NULL;
660 }
661 if (obj->type == OBJ_COMMIT) {
662 struct commit *commit = (struct commit *) obj;
663 commit->buffer = NULL;
664 }
665 obj->flags |= FLAG_CHECKED;
666 }
b8a2486f 667 read_unlock();
0153be05 668 }
9ec2dde9
NTND
669
670 free(new_data);
9cf6d335
SV
671}
672
20e95d0a
NTND
673/*
674 * This function is part of find_unresolved_deltas(). There are two
675 * walkers going in the opposite ways.
676 *
677 * The first one in find_unresolved_deltas() traverses down from
678 * parent node to children, deflating nodes along the way. However,
679 * memory for deflated nodes is limited by delta_base_cache_limit, so
680 * at some point parent node's deflated content may be freed.
681 *
682 * The second walker is this function, which goes from current node up
683 * to top parent if necessary to deflate the node. In normal
684 * situation, its parent node would be already deflated, so it just
685 * needs to apply delta.
686 *
687 * In the worst case scenario, parent node is no longer deflated because
688 * we're running out of delta_base_cache_limit; we need to re-deflate
689 * parents, possibly up to the top base.
690 *
691 * All deflated objects here are subject to be freed if we exceed
692 * delta_base_cache_limit, just like in find_unresolved_deltas(), we
693 * just need to make sure the last node is not freed.
694 */
92392b4a
SP
695static void *get_base_data(struct base_data *c)
696{
697 if (!c->data) {
698 struct object_entry *obj = c->obj;
20e95d0a
NTND
699 struct base_data **delta = NULL;
700 int delta_nr = 0, delta_alloc = 0;
92392b4a 701
20e95d0a
NTND
702 while (is_delta_type(c->obj->type) && !c->data) {
703 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
704 delta[delta_nr++] = c;
705 c = c->base;
706 }
707 if (!delta_nr) {
708 c->data = get_data_from_pack(obj);
709 c->size = obj->size;
b8a2486f 710 get_thread_data()->base_cache_used += c->size;
20e95d0a
NTND
711 prune_base_data(c);
712 }
713 for (; delta_nr > 0; delta_nr--) {
714 void *base, *raw;
715 c = delta[delta_nr - 1];
716 obj = c->obj;
717 base = get_base_data(c->base);
718 raw = get_data_from_pack(obj);
92392b4a
SP
719 c->data = patch_delta(
720 base, c->base->size,
721 raw, obj->size,
722 &c->size);
723 free(raw);
724 if (!c->data)
c2b97ecf 725 bad_object(obj->idx.offset, _("failed to apply delta"));
b8a2486f 726 get_thread_data()->base_cache_used += c->size;
20e95d0a 727 prune_base_data(c);
9441b61d 728 }
20e95d0a 729 free(delta);
92392b4a
SP
730 }
731 return c->data;
732}
733
f41aebd4 734static void resolve_delta(struct object_entry *delta_obj,
9441b61d 735 struct base_data *base, struct base_data *result)
9cf6d335 736{
ce3f6dc6 737 void *base_data, *delta_data;
9cf6d335 738
ce3f6dc6 739 delta_obj->real_type = base->obj->real_type;
38a45561 740 delta_obj->delta_depth = base->obj->delta_depth + 1;
d1a0ed18
JH
741 if (deepest_delta < delta_obj->delta_depth)
742 deepest_delta = delta_obj->delta_depth;
38a45561 743 delta_obj->base_object_no = base->obj - objects;
636171cb 744 delta_data = get_data_from_pack(delta_obj);
ce3f6dc6 745 base_data = get_base_data(base);
9441b61d 746 result->obj = delta_obj;
ce3f6dc6
NP
747 result->data = patch_delta(base_data, base->size,
748 delta_data, delta_obj->size, &result->size);
9cf6d335 749 free(delta_data);
9441b61d 750 if (!result->data)
c2b97ecf 751 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
681b07de
NTND
752 hash_sha1_file(result->data, result->size,
753 typename(delta_obj->real_type), delta_obj->idx.sha1);
9ec2dde9 754 sha1_object(result->data, NULL, result->size, delta_obj->real_type,
9441b61d 755 delta_obj->idx.sha1);
b8a2486f 756 counter_lock();
636171cb 757 nr_resolved_deltas++;
b8a2486f 758 counter_unlock();
9441b61d
NP
759}
760
2baad220
NTND
761static struct base_data *find_unresolved_deltas_1(struct base_data *base,
762 struct base_data *prev_base)
9441b61d 763{
2baad220 764 if (base->ref_last == -1 && base->ofs_last == -1) {
9441b61d
NP
765 union delta_base base_spec;
766
767 hashcpy(base_spec.sha1, base->obj->idx.sha1);
7218a215 768 find_delta_children(&base_spec,
2baad220 769 &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
53dda6ff 770
9441b61d
NP
771 memset(&base_spec, 0, sizeof(base_spec));
772 base_spec.offset = base->obj->idx.offset;
7218a215 773 find_delta_children(&base_spec,
2baad220 774 &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
4a438cab 775
2baad220
NTND
776 if (base->ref_last == -1 && base->ofs_last == -1) {
777 free(base->data);
778 return NULL;
779 }
53dda6ff 780
2baad220
NTND
781 link_base_data(prev_base, base);
782 }
4a438cab 783
2baad220
NTND
784 if (base->ref_first <= base->ref_last) {
785 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
786 struct base_data *result = alloc_base_data();
7218a215
JH
787
788 assert(child->real_type == OBJ_REF_DELTA);
2baad220
NTND
789 resolve_delta(child, base, result);
790 if (base->ref_first == base->ref_last && base->ofs_last == -1)
7218a215 791 free_base_data(base);
2baad220
NTND
792
793 base->ref_first++;
794 return result;
53dda6ff
NP
795 }
796
2baad220
NTND
797 if (base->ofs_first <= base->ofs_last) {
798 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
799 struct base_data *result = alloc_base_data();
7218a215
JH
800
801 assert(child->real_type == OBJ_OFS_DELTA);
2baad220
NTND
802 resolve_delta(child, base, result);
803 if (base->ofs_first == base->ofs_last)
7218a215 804 free_base_data(base);
2baad220
NTND
805
806 base->ofs_first++;
807 return result;
9cf6d335 808 }
53dda6ff 809
9441b61d 810 unlink_base_data(base);
2baad220
NTND
811 return NULL;
812}
813
814static void find_unresolved_deltas(struct base_data *base)
815{
816 struct base_data *new_base, *prev_base = NULL;
817 for (;;) {
818 new_base = find_unresolved_deltas_1(base, prev_base);
819
820 if (new_base) {
821 prev_base = base;
822 base = new_base;
823 } else {
824 free(base);
825 base = prev_base;
826 if (!base)
827 return;
828 prev_base = base->base;
829 }
830 }
9cf6d335
SV
831}
832
833static int compare_delta_entry(const void *a, const void *b)
834{
835 const struct delta_entry *delta_a = a;
836 const struct delta_entry *delta_b = b;
7218a215
JH
837
838 /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
839 return compare_delta_bases(&delta_a->base, &delta_b->base,
840 objects[delta_a->obj_no].type,
841 objects[delta_b->obj_no].type);
9cf6d335
SV
842}
843
5272f755
NTND
844static void resolve_base(struct object_entry *obj)
845{
846 struct base_data *base_obj = alloc_base_data();
847 base_obj->obj = obj;
848 base_obj->data = NULL;
849 find_unresolved_deltas(base_obj);
850}
851
b8a2486f
NTND
852#ifndef NO_PTHREADS
853static void *threaded_second_pass(void *data)
854{
855 set_thread_data(data);
856 for (;;) {
857 int i;
858 work_lock();
859 display_progress(progress, nr_resolved_deltas);
860 while (nr_dispatched < nr_objects &&
861 is_delta_type(objects[nr_dispatched].type))
862 nr_dispatched++;
863 if (nr_dispatched >= nr_objects) {
864 work_unlock();
865 break;
866 }
867 i = nr_dispatched++;
868 work_unlock();
869
870 resolve_base(&objects[i]);
871 }
872 return NULL;
873}
874#endif
875
5272f755
NTND
876/*
877 * First pass:
878 * - find locations of all objects;
879 * - calculate SHA1 of all non-delta objects;
880 * - remember base (SHA1 or offset) for all deltas.
881 */
2d477051 882static void parse_pack_objects(unsigned char *sha1)
9cf6d335 883{
9ec2dde9 884 int i, nr_delays = 0;
53dda6ff 885 struct delta_entry *delta = deltas;
2d477051 886 struct stat st;
9cf6d335 887
13aaf148 888 if (verbose)
29e63ed3 889 progress = start_progress(
c2b97ecf 890 from_stdin ? _("Receiving objects") : _("Indexing objects"),
29e63ed3 891 nr_objects);
9cf6d335
SV
892 for (i = 0; i < nr_objects; i++) {
893 struct object_entry *obj = &objects[i];
681b07de 894 void *data = unpack_raw_entry(obj, &delta->base, obj->idx.sha1);
9cf6d335 895 obj->real_type = obj->type;
4f8ec74e 896 if (is_delta_type(obj->type)) {
53dda6ff 897 nr_deltas++;
636171cb 898 delta->obj_no = i;
53dda6ff 899 delta++;
9ec2dde9
NTND
900 } else if (!data) {
901 /* large blobs, check later */
902 obj->real_type = OBJ_BAD;
903 nr_delays++;
9cf6d335 904 } else
9ec2dde9 905 sha1_object(data, NULL, obj->size, obj->type, obj->idx.sha1);
9cf6d335 906 free(data);
4d4fcc54 907 display_progress(progress, i+1);
9cf6d335 908 }
aa7e44bf 909 objects[i].idx.offset = consumed_bytes;
4d4fcc54 910 stop_progress(&progress);
2d477051
NP
911
912 /* Check pack integrity */
636171cb 913 flush();
9126f009 914 git_SHA1_Final(sha1, &input_ctx);
2d477051 915 if (hashcmp(fill(20), sha1))
c2b97ecf 916 die(_("pack is corrupted (SHA1 mismatch)"));
9bee2478 917 use(20);
2d477051
NP
918
919 /* If input_fd is a file, we should have reached its end now. */
920 if (fstat(input_fd, &st))
c2b97ecf 921 die_errno(_("cannot fstat packfile"));
fa257b05
JS
922 if (S_ISREG(st.st_mode) &&
923 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
c2b97ecf 924 die(_("pack has junk at the end"));
9ec2dde9
NTND
925
926 for (i = 0; i < nr_objects; i++) {
927 struct object_entry *obj = &objects[i];
928 if (obj->real_type != OBJ_BAD)
929 continue;
930 obj->real_type = obj->type;
931 sha1_object(NULL, obj, obj->size, obj->type, obj->idx.sha1);
932 nr_delays--;
933 }
934 if (nr_delays)
935 die(_("confusion beyond insanity in parse_pack_objects()"));
5272f755
NTND
936}
937
938/*
939 * Second pass:
940 * - for all non-delta objects, look if it is used as a base for
941 * deltas;
942 * - if used as a base, uncompress the object and apply all deltas,
943 * recursively checking if the resulting object is used as a base
944 * for some more deltas.
945 */
946static void resolve_deltas(void)
947{
948 int i;
9cf6d335 949
3c9af366
NP
950 if (!nr_deltas)
951 return;
952
53dda6ff 953 /* Sort deltas by base SHA1/offset for fast searching */
9cf6d335
SV
954 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
955 compare_delta_entry);
956
13aaf148 957 if (verbose)
c2b97ecf 958 progress = start_progress(_("Resolving deltas"), nr_deltas);
b8a2486f
NTND
959
960#ifndef NO_PTHREADS
961 nr_dispatched = 0;
962 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
963 init_thread();
964 for (i = 0; i < nr_threads; i++) {
965 int ret = pthread_create(&thread_data[i].thread, NULL,
966 threaded_second_pass, thread_data + i);
967 if (ret)
968 die("unable to create thread: %s", strerror(ret));
969 }
970 for (i = 0; i < nr_threads; i++)
971 pthread_join(thread_data[i].thread, NULL);
972 cleanup_thread();
973 return;
974 }
975#endif
976
9cf6d335
SV
977 for (i = 0; i < nr_objects; i++) {
978 struct object_entry *obj = &objects[i];
9cf6d335 979
4f8ec74e 980 if (is_delta_type(obj->type))
9cf6d335 981 continue;
5272f755 982 resolve_base(obj);
4d4fcc54 983 display_progress(progress, nr_resolved_deltas);
9cf6d335 984 }
636171cb
NP
985}
986
5272f755
NTND
987/*
988 * Third pass:
989 * - append objects to convert thin pack to full pack if required
990 * - write the final 20-byte SHA-1
991 */
992static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
993static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
994{
995 if (nr_deltas == nr_resolved_deltas) {
996 stop_progress(&progress);
997 /* Flush remaining pack final 20-byte SHA1. */
998 flush();
999 return;
1000 }
1001
1002 if (fix_thin_pack) {
1003 struct sha1file *f;
1004 unsigned char read_sha1[20], tail_sha1[20];
1005 char msg[48];
1006 int nr_unresolved = nr_deltas - nr_resolved_deltas;
1007 int nr_objects_initial = nr_objects;
1008 if (nr_unresolved <= 0)
cc13431a 1009 die(_("confusion beyond insanity"));
5272f755
NTND
1010 objects = xrealloc(objects,
1011 (nr_objects + nr_unresolved + 1)
1012 * sizeof(*objects));
1013 f = sha1fd(output_fd, curr_pack);
1014 fix_unresolved_deltas(f, nr_unresolved);
1015 sprintf(msg, "completed with %d local objects",
1016 nr_objects - nr_objects_initial);
1017 stop_progress_msg(&progress, msg);
1018 sha1close(f, tail_sha1, 0);
1019 hashcpy(read_sha1, pack_sha1);
1020 fixup_pack_header_footer(output_fd, pack_sha1,
1021 curr_pack, nr_objects,
1022 read_sha1, consumed_bytes-20);
1023 if (hashcmp(read_sha1, tail_sha1) != 0)
1024 die("Unexpected tail checksum for %s "
1025 "(disk corruption?)", curr_pack);
1026 }
1027 if (nr_deltas != nr_resolved_deltas)
cc13431a
JH
1028 die(Q_("pack has %d unresolved delta",
1029 "pack has %d unresolved deltas",
1030 nr_deltas - nr_resolved_deltas),
5272f755
NTND
1031 nr_deltas - nr_resolved_deltas);
1032}
1033
8522148f 1034static int write_compressed(struct sha1file *f, void *in, unsigned int size)
636171cb 1035{
ef49a7a0 1036 git_zstream stream;
7734d7f2
NP
1037 int status;
1038 unsigned char outbuf[4096];
636171cb
NP
1039
1040 memset(&stream, 0, sizeof(stream));
55bb5c91 1041 git_deflate_init(&stream, zlib_compression_level);
636171cb
NP
1042 stream.next_in = in;
1043 stream.avail_in = size;
636171cb 1044
7734d7f2
NP
1045 do {
1046 stream.next_out = outbuf;
1047 stream.avail_out = sizeof(outbuf);
55bb5c91 1048 status = git_deflate(&stream, Z_FINISH);
7734d7f2
NP
1049 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
1050 } while (status == Z_OK);
1051
1052 if (status != Z_STREAM_END)
c2b97ecf 1053 die(_("unable to deflate appended object (%d)"), status);
636171cb 1054 size = stream.total_out;
55bb5c91 1055 git_deflate_end(&stream);
636171cb
NP
1056 return size;
1057}
1058
8522148f 1059static struct object_entry *append_obj_to_pack(struct sha1file *f,
03993e13 1060 const unsigned char *sha1, void *buf,
636171cb
NP
1061 unsigned long size, enum object_type type)
1062{
1063 struct object_entry *obj = &objects[nr_objects++];
1064 unsigned char header[10];
1065 unsigned long s = size;
1066 int n = 0;
1067 unsigned char c = (type << 4) | (s & 15);
1068 s >>= 4;
1069 while (s) {
1070 header[n++] = c | 0x80;
1071 c = s & 0x7f;
1072 s >>= 7;
1073 }
1074 header[n++] = c;
8522148f
NP
1075 crc32_begin(f);
1076 sha1write(f, header, n);
72de2883
BS
1077 obj[0].size = size;
1078 obj[0].hdr_size = n;
1079 obj[0].type = type;
1080 obj[0].real_type = type;
aa7e44bf 1081 obj[1].idx.offset = obj[0].idx.offset + n;
8522148f
NP
1082 obj[1].idx.offset += write_compressed(f, buf, size);
1083 obj[0].idx.crc32 = crc32_end(f);
838cd346 1084 sha1flush(f);
aa7e44bf 1085 hashcpy(obj->idx.sha1, sha1);
03993e13 1086 return obj;
636171cb
NP
1087}
1088
1089static int delta_pos_compare(const void *_a, const void *_b)
1090{
1091 struct delta_entry *a = *(struct delta_entry **)_a;
1092 struct delta_entry *b = *(struct delta_entry **)_b;
1093 return a->obj_no - b->obj_no;
1094}
9cf6d335 1095
8522148f 1096static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
636171cb
NP
1097{
1098 struct delta_entry **sorted_by_pos;
96a02f8f 1099 int i, n = 0;
636171cb
NP
1100
1101 /*
1102 * Since many unresolved deltas may well be themselves base objects
1103 * for more unresolved deltas, we really want to include the
1104 * smallest number of base objects that would cover as much delta
1105 * as possible by picking the
1106 * trunc deltas first, allowing for other deltas to resolve without
1107 * additional base objects. Since most base objects are to be found
1108 * before deltas depending on them, a good heuristic is to start
1109 * resolving deltas in the same order as their position in the pack.
1110 */
1111 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
9cf6d335 1112 for (i = 0; i < nr_deltas; i++) {
636171cb
NP
1113 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
1114 continue;
1115 sorted_by_pos[n++] = &deltas[i];
9cf6d335 1116 }
636171cb
NP
1117 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
1118
1119 for (i = 0; i < n; i++) {
1120 struct delta_entry *d = sorted_by_pos[i];
21666f1a 1121 enum object_type type;
2baad220 1122 struct base_data *base_obj = alloc_base_data();
636171cb
NP
1123
1124 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1125 continue;
2baad220
NTND
1126 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
1127 if (!base_obj->data)
636171cb 1128 continue;
636171cb 1129
2baad220
NTND
1130 if (check_sha1_signature(d->base.sha1, base_obj->data,
1131 base_obj->size, typename(type)))
c2b97ecf 1132 die(_("local object %s is corrupt"), sha1_to_hex(d->base.sha1));
2baad220
NTND
1133 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
1134 base_obj->data, base_obj->size, type);
1135 find_unresolved_deltas(base_obj);
4d4fcc54 1136 display_progress(progress, nr_resolved_deltas);
636171cb
NP
1137 }
1138 free(sorted_by_pos);
1139}
1140
e42797f5
NP
1141static void final(const char *final_pack_name, const char *curr_pack_name,
1142 const char *final_index_name, const char *curr_index_name,
b8077709 1143 const char *keep_name, const char *keep_msg,
e42797f5
NP
1144 unsigned char *sha1)
1145{
3a55602e 1146 const char *report = "pack";
e42797f5
NP
1147 char name[PATH_MAX];
1148 int err;
1149
1150 if (!from_stdin) {
1151 close(input_fd);
1152 } else {
4c81b03e 1153 fsync_or_die(output_fd, curr_pack_name);
e42797f5
NP
1154 err = close(output_fd);
1155 if (err)
c2b97ecf 1156 die_errno(_("error while closing pack file"));
e42797f5
NP
1157 }
1158
b8077709
SP
1159 if (keep_msg) {
1160 int keep_fd, keep_msg_len = strlen(keep_msg);
6e180cdc
JH
1161
1162 if (!keep_name)
1163 keep_fd = odb_pack_keep(name, sizeof(name), sha1);
1164 else
1165 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
1166
9ca4a201
NP
1167 if (keep_fd < 0) {
1168 if (errno != EEXIST)
c2b97ecf 1169 die_errno(_("cannot write keep file '%s'"),
d824cbba 1170 keep_name);
9ca4a201
NP
1171 } else {
1172 if (keep_msg_len > 0) {
1173 write_or_die(keep_fd, keep_msg, keep_msg_len);
1174 write_or_die(keep_fd, "\n", 1);
1175 }
91c8d590 1176 if (close(keep_fd) != 0)
c2b97ecf 1177 die_errno(_("cannot close written keep file '%s'"),
d824cbba 1178 keep_name);
576162a4 1179 report = "keep";
b8077709 1180 }
b8077709
SP
1181 }
1182
e42797f5
NP
1183 if (final_pack_name != curr_pack_name) {
1184 if (!final_pack_name) {
1185 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
1186 get_object_directory(), sha1_to_hex(sha1));
1187 final_pack_name = name;
1188 }
1189 if (move_temp_to_file(curr_pack_name, final_pack_name))
c2b97ecf 1190 die(_("cannot store pack file"));
fb8b1936 1191 } else if (from_stdin)
33b65030 1192 chmod(final_pack_name, 0444);
e42797f5 1193
e42797f5
NP
1194 if (final_index_name != curr_index_name) {
1195 if (!final_index_name) {
1196 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
1197 get_object_directory(), sha1_to_hex(sha1));
1198 final_index_name = name;
1199 }
1200 if (move_temp_to_file(curr_index_name, final_index_name))
c2b97ecf 1201 die(_("cannot store index file"));
fb8b1936
JH
1202 } else
1203 chmod(final_index_name, 0444);
576162a4
NP
1204
1205 if (!from_stdin) {
1206 printf("%s\n", sha1_to_hex(sha1));
1207 } else {
1208 char buf[48];
1209 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
1210 report, sha1_to_hex(sha1));
d1b2ddc8 1211 write_or_die(1, buf, len);
576162a4
NP
1212
1213 /*
1214 * Let's just mimic git-unpack-objects here and write
1215 * the last part of the input buffer to stdout.
1216 */
1217 while (input_len) {
1218 err = xwrite(1, input_buffer + input_offset, input_len);
1219 if (err <= 0)
1220 break;
1221 input_len -= err;
1222 input_offset += err;
1223 }
1224 }
9cf6d335
SV
1225}
1226
ef90d6d4 1227static int git_index_pack_config(const char *k, const char *v, void *cb)
4d00bda2 1228{
ebcfb379
JH
1229 struct pack_idx_option *opts = cb;
1230
4d00bda2 1231 if (!strcmp(k, "pack.indexversion")) {
ebcfb379
JH
1232 opts->version = git_config_int(k, v);
1233 if (opts->version > 2)
1234 die("bad pack.indexversion=%"PRIu32, opts->version);
4d00bda2
NP
1235 return 0;
1236 }
b8a2486f
NTND
1237 if (!strcmp(k, "pack.threads")) {
1238 nr_threads = git_config_int(k, v);
1239 if (nr_threads < 0)
1240 die("invalid number of threads specified (%d)",
1241 nr_threads);
1242#ifdef NO_PTHREADS
1243 if (nr_threads != 1)
1244 warning("no threads support, ignoring %s", k);
1245 nr_threads = 1;
1246#endif
1247 return 0;
1248 }
ef90d6d4 1249 return git_default_config(k, v, cb);
4d00bda2
NP
1250}
1251
3c9fc074
JH
1252static int cmp_uint32(const void *a_, const void *b_)
1253{
1254 uint32_t a = *((uint32_t *)a_);
1255 uint32_t b = *((uint32_t *)b_);
1256
1257 return (a < b) ? -1 : (a != b);
1258}
1259
1260static void read_v2_anomalous_offsets(struct packed_git *p,
1261 struct pack_idx_option *opts)
1262{
1263 const uint32_t *idx1, *idx2;
1264 uint32_t i;
1265
1266 /* The address of the 4-byte offset table */
1267 idx1 = (((const uint32_t *)p->index_data)
1268 + 2 /* 8-byte header */
1269 + 256 /* fan out */
1270 + 5 * p->num_objects /* 20-byte SHA-1 table */
1271 + p->num_objects /* CRC32 table */
1272 );
1273
1274 /* The address of the 8-byte offset table */
1275 idx2 = idx1 + p->num_objects;
1276
1277 for (i = 0; i < p->num_objects; i++) {
1278 uint32_t off = ntohl(idx1[i]);
1279 if (!(off & 0x80000000))
1280 continue;
1281 off = off & 0x7fffffff;
1282 if (idx2[off * 2])
1283 continue;
1284 /*
1285 * The real offset is ntohl(idx2[off * 2]) in high 4
1286 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1287 * octets. But idx2[off * 2] is Zero!!!
1288 */
1289 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1290 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1291 }
1292
1293 if (1 < opts->anomaly_nr)
1294 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1295}
1296
e337a04d
JH
1297static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1298{
1299 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1300
1301 if (!p)
c2b97ecf 1302 die(_("Cannot open existing pack file '%s'"), pack_name);
e337a04d 1303 if (open_pack_index(p))
c2b97ecf 1304 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
e337a04d
JH
1305
1306 /* Read the attributes from the existing idx file */
1307 opts->version = p->index_version;
1308
3c9fc074
JH
1309 if (opts->version == 2)
1310 read_v2_anomalous_offsets(p, opts);
1311
e337a04d
JH
1312 /*
1313 * Get rid of the idx file as we do not need it anymore.
1314 * NEEDSWORK: extract this bit from free_pack_by_name() in
1315 * sha1_file.c, perhaps? It shouldn't matter very much as we
1316 * know we haven't installed this pack (hence we never have
1317 * read anything from it).
1318 */
1319 close_pack_index(p);
1320 free(p);
1321}
1322
38a45561
JH
1323static void show_pack_info(int stat_only)
1324{
d1a0ed18
JH
1325 int i, baseobjects = nr_objects - nr_deltas;
1326 unsigned long *chain_histogram = NULL;
1327
1328 if (deepest_delta)
1329 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1330
38a45561
JH
1331 for (i = 0; i < nr_objects; i++) {
1332 struct object_entry *obj = &objects[i];
1333
d1a0ed18
JH
1334 if (is_delta_type(obj->type))
1335 chain_histogram[obj->delta_depth - 1]++;
38a45561
JH
1336 if (stat_only)
1337 continue;
1338 printf("%s %-6s %lu %lu %"PRIuMAX,
1339 sha1_to_hex(obj->idx.sha1),
1340 typename(obj->real_type), obj->size,
1341 (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1342 (uintmax_t)obj->idx.offset);
1343 if (is_delta_type(obj->type)) {
1344 struct object_entry *bobj = &objects[obj->base_object_no];
1345 printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1346 }
1347 putchar('\n');
1348 }
d1a0ed18
JH
1349
1350 if (baseobjects)
c2b97ecf
NTND
1351 printf_ln(Q_("non delta: %d object",
1352 "non delta: %d objects",
1353 baseobjects),
1354 baseobjects);
d1a0ed18
JH
1355 for (i = 0; i < deepest_delta; i++) {
1356 if (!chain_histogram[i])
1357 continue;
c2b97ecf
NTND
1358 printf_ln(Q_("chain length = %d: %lu object",
1359 "chain length = %d: %lu objects",
1360 chain_histogram[i]),
1361 i + 1,
1362 chain_histogram[i]);
d1a0ed18 1363 }
38a45561
JH
1364}
1365
3bb72562 1366int cmd_index_pack(int argc, const char **argv, const char *prefix)
9cf6d335 1367{
38a45561 1368 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
3bb72562
LT
1369 const char *curr_pack, *curr_index;
1370 const char *index_name = NULL, *pack_name = NULL;
b8077709
SP
1371 const char *keep_name = NULL, *keep_msg = NULL;
1372 char *index_name_buf = NULL, *keep_name_buf = NULL;
aa7e44bf 1373 struct pack_idx_entry **idx_objects;
ebcfb379 1374 struct pack_idx_option opts;
8522148f 1375 unsigned char pack_sha1[20];
9cf6d335 1376
99caeed0
JN
1377 if (argc == 2 && !strcmp(argv[1], "-h"))
1378 usage(index_pack_usage);
1379
6e2a09d2
NE
1380 read_replace_refs = 0;
1381
ebcfb379
JH
1382 reset_pack_idx_option(&opts);
1383 git_config(git_index_pack_config, &opts);
3f8099fc 1384 if (prefix && chdir(prefix))
c2b97ecf 1385 die(_("Cannot come back to cwd"));
4d00bda2 1386
9cf6d335 1387 for (i = 1; i < argc; i++) {
3bb72562 1388 const char *arg = argv[i];
9cf6d335
SV
1389
1390 if (*arg == '-') {
e42797f5
NP
1391 if (!strcmp(arg, "--stdin")) {
1392 from_stdin = 1;
636171cb
NP
1393 } else if (!strcmp(arg, "--fix-thin")) {
1394 fix_thin_pack = 1;
0153be05
MK
1395 } else if (!strcmp(arg, "--strict")) {
1396 strict = 1;
e337a04d
JH
1397 } else if (!strcmp(arg, "--verify")) {
1398 verify = 1;
38a45561
JH
1399 } else if (!strcmp(arg, "--verify-stat")) {
1400 verify = 1;
1401 stat = 1;
1402 } else if (!strcmp(arg, "--verify-stat-only")) {
1403 verify = 1;
1404 stat = 1;
1405 stat_only = 1;
b8077709
SP
1406 } else if (!strcmp(arg, "--keep")) {
1407 keep_msg = "";
cc44c765 1408 } else if (!prefixcmp(arg, "--keep=")) {
b8077709 1409 keep_msg = arg + 7;
b8a2486f
NTND
1410 } else if (!prefixcmp(arg, "--threads=")) {
1411 char *end;
1412 nr_threads = strtoul(arg+10, &end, 0);
1413 if (!arg[10] || *end || nr_threads < 0)
1414 usage(index_pack_usage);
1415#ifdef NO_PTHREADS
1416 if (nr_threads != 1)
1417 warning("no threads support, "
1418 "ignoring %s", arg);
1419 nr_threads = 1;
1420#endif
cc44c765 1421 } else if (!prefixcmp(arg, "--pack_header=")) {
bed006fb
NP
1422 struct pack_header *hdr;
1423 char *c;
1424
1425 hdr = (struct pack_header *)input_buffer;
1426 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1427 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1428 if (*c != ',')
c2b97ecf 1429 die(_("bad %s"), arg);
bed006fb
NP
1430 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1431 if (*c)
c2b97ecf 1432 die(_("bad %s"), arg);
bed006fb 1433 input_len = sizeof(*hdr);
3c9af366
NP
1434 } else if (!strcmp(arg, "-v")) {
1435 verbose = 1;
e42797f5 1436 } else if (!strcmp(arg, "-o")) {
9cf6d335
SV
1437 if (index_name || (i+1) >= argc)
1438 usage(index_pack_usage);
1439 index_name = argv[++i];
4ba7d711
NP
1440 } else if (!prefixcmp(arg, "--index-version=")) {
1441 char *c;
ebcfb379
JH
1442 opts.version = strtoul(arg + 16, &c, 10);
1443 if (opts.version > 2)
c2b97ecf 1444 die(_("bad %s"), arg);
4ba7d711 1445 if (*c == ',')
ebcfb379
JH
1446 opts.off32_limit = strtoul(c+1, &c, 0);
1447 if (*c || opts.off32_limit & 0x80000000)
c2b97ecf 1448 die(_("bad %s"), arg);
9cf6d335
SV
1449 } else
1450 usage(index_pack_usage);
1451 continue;
1452 }
1453
1454 if (pack_name)
1455 usage(index_pack_usage);
1456 pack_name = arg;
1457 }
1458
e42797f5 1459 if (!pack_name && !from_stdin)
9cf6d335 1460 usage(index_pack_usage);
636171cb 1461 if (fix_thin_pack && !from_stdin)
c2b97ecf 1462 die(_("--fix-thin cannot be used without --stdin"));
e42797f5 1463 if (!index_name && pack_name) {
9cf6d335 1464 int len = strlen(pack_name);
5bb1cda5 1465 if (!has_extension(pack_name, ".pack"))
c2b97ecf 1466 die(_("packfile name '%s' does not end with '.pack'"),
9cf6d335 1467 pack_name);
6689f087 1468 index_name_buf = xmalloc(len);
9cf6d335
SV
1469 memcpy(index_name_buf, pack_name, len - 5);
1470 strcpy(index_name_buf + len - 5, ".idx");
1471 index_name = index_name_buf;
1472 }
b8077709
SP
1473 if (keep_msg && !keep_name && pack_name) {
1474 int len = strlen(pack_name);
1475 if (!has_extension(pack_name, ".pack"))
c2b97ecf 1476 die(_("packfile name '%s' does not end with '.pack'"),
b8077709
SP
1477 pack_name);
1478 keep_name_buf = xmalloc(len);
1479 memcpy(keep_name_buf, pack_name, len - 5);
1480 strcpy(keep_name_buf + len - 5, ".keep");
1481 keep_name = keep_name_buf;
1482 }
e337a04d
JH
1483 if (verify) {
1484 if (!index_name)
c2b97ecf 1485 die(_("--verify with no packfile name given"));
e337a04d 1486 read_idx_option(&opts, index_name);
68be2fea 1487 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
e337a04d 1488 }
68be2fea
JH
1489 if (strict)
1490 opts.flags |= WRITE_IDX_STRICT;
9cf6d335 1491
b8a2486f
NTND
1492#ifndef NO_PTHREADS
1493 if (!nr_threads) {
1494 nr_threads = online_cpus();
1495 /* An experiment showed that more threads does not mean faster */
1496 if (nr_threads > 3)
1497 nr_threads = 3;
1498 }
1499#endif
1500
e42797f5 1501 curr_pack = open_pack_file(pack_name);
9cf6d335 1502 parse_pack_header();
38a45561
JH
1503 objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1504 deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
8522148f 1505 parse_pack_objects(pack_sha1);
5272f755
NTND
1506 resolve_deltas();
1507 conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
9cf6d335 1508 free(deltas);
0153be05
MK
1509 if (strict)
1510 check_objects();
aa7e44bf 1511
38a45561
JH
1512 if (stat)
1513 show_pack_info(stat_only);
1514
aa7e44bf
GB
1515 idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1516 for (i = 0; i < nr_objects; i++)
1517 idx_objects[i] = &objects[i].idx;
ebcfb379 1518 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
aa7e44bf
GB
1519 free(idx_objects);
1520
e337a04d
JH
1521 if (!verify)
1522 final(pack_name, curr_pack,
1523 index_name, curr_index,
1524 keep_name, keep_msg,
1525 pack_sha1);
1526 else
1527 close(input_fd);
9cf6d335
SV
1528 free(objects);
1529 free(index_name_buf);
b8077709 1530 free(keep_name_buf);
c85228ed 1531 if (pack_name == NULL)
3bb72562 1532 free((void *) curr_pack);
c85228ed 1533 if (index_name == NULL)
3bb72562 1534 free((void *) curr_index);
9cf6d335
SV
1535
1536 return 0;
1537}