]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/index-pack.c
Merge branch 'rj/add-i-leak-fix'
[thirdparty/git.git] / builtin / index-pack.c
CommitLineData
2ad9d4cb 1#include "builtin.h"
b2141fc1 2#include "config.h"
9cf6d335 3#include "delta.h"
32a8f510 4#include "environment.h"
f394e093 5#include "gettext.h"
41771fa4 6#include "hex.h"
9cf6d335
SV
7#include "pack.h"
8#include "csum-file.h"
8e440259
PE
9#include "blob.h"
10#include "commit.h"
8e440259 11#include "tree.h"
96a02f8f 12#include "progress.h"
0153be05 13#include "fsck.h"
a034e910 14#include "strbuf.h"
4614043c 15#include "streaming.h"
b8a2486f 16#include "thread-utils.h"
4f39cd82 17#include "packfile.h"
75f273d9 18#include "pack-revindex.h"
87bed179 19#include "object-file.h"
a034e910 20#include "object-store-ll.h"
6f2d7430 21#include "oid-array.h"
cbeab747 22#include "replace-object.h"
b14ed5ad 23#include "promisor-remote.h"
e38da487 24#include "setup.h"
9cf6d335
SV
25
26static const char index_pack_usage[] =
0f8edf73 27"git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--[no-]rev-index] [--verify] [--strict[=<msg-id>=<severity>...]] [--fsck-objects[=<msg-id>=<severity>...]] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
9cf6d335 28
9cba13ca 29struct object_entry {
aa7e44bf 30 struct pack_idx_entry idx;
2d477051 31 unsigned long size;
41730576
NTND
32 unsigned char hdr_size;
33 signed char type;
34 signed char real_type;
9cf6d335
SV
35};
36
41730576 37struct object_stat {
38a45561
JH
38 unsigned delta_depth;
39 int base_object_no;
53dda6ff
NP
40};
41
f41aebd4 42struct base_data {
b4718cae 43 /* Initialized by make_base(). */
4a438cab 44 struct base_data *base;
03993e13 45 struct object_entry *obj;
2baad220
NTND
46 int ref_first, ref_last;
47 int ofs_first, ofs_last;
f08cbf60
JT
48 /*
49 * Threads should increment retain_data if they are about to call
50 * patch_delta() using this struct's data as a base, and decrement this
51 * when they are done. While retain_data is nonzero, this struct's data
52 * will not be freed even if the delta base cache limit is exceeded.
53 */
54 int retain_data;
55 /*
56 * The number of direct children that have not been fully processed
57 * (entered work_head, entered done_head, left done_head). When this
58 * number reaches zero, this struct base_data can be freed.
59 */
60 int children_remaining;
b4718cae
JT
61
62 /* Not initialized by make_base(). */
f08cbf60 63 struct list_head list;
b4718cae
JT
64 void *data;
65 unsigned long size;
f41aebd4
SP
66};
67
f08cbf60
JT
68/*
69 * Stack of struct base_data that have unprocessed children.
70 * threaded_second_pass() uses this as a source of work (the other being the
71 * objects array).
72 *
73 * Guarded by work_mutex.
74 */
75static LIST_HEAD(work_head);
76
77/*
78 * Stack of struct base_data that have children, all of whom have been
79 * processed or are being processed, and at least one child is being processed.
80 * These struct base_data must be kept around until the last child is
81 * processed.
82 *
83 * Guarded by work_mutex.
84 */
85static LIST_HEAD(done_head);
86
87/*
88 * All threads share one delta base cache.
89 *
90 * base_cache_used is guarded by work_mutex, and base_cache_limit is read-only
91 * in a thread.
92 */
93static size_t base_cache_used;
94static size_t base_cache_limit;
95
b8a2486f 96struct thread_local {
b8a2486f 97 pthread_t thread;
39539495 98 int pack_fd;
b8a2486f
NTND
99};
100
95308d64 101/* Remember to update object flag allocation in object.h */
0153be05
MK
102#define FLAG_LINK (1u<<20)
103#define FLAG_CHECKED (1u<<21)
104
c6458e60
NTND
105struct ofs_delta_entry {
106 off_t offset;
107 int obj_no;
108};
109
110struct ref_delta_entry {
af8caf33 111 struct object_id oid;
636171cb 112 int obj_no;
9cf6d335
SV
113};
114
9cf6d335 115static struct object_entry *objects;
41730576 116static struct object_stat *obj_stat;
c6458e60
NTND
117static struct ofs_delta_entry *ofs_deltas;
118static struct ref_delta_entry *ref_deltas;
b8a2486f 119static struct thread_local nothread_data;
9cf6d335 120static int nr_objects;
c6458e60
NTND
121static int nr_ofs_deltas;
122static int nr_ref_deltas;
123static int ref_deltas_alloc;
636171cb 124static int nr_resolved_deltas;
b8a2486f 125static int nr_threads;
9cf6d335 126
e42797f5 127static int from_stdin;
0153be05 128static int strict;
c6807a40 129static int do_fsck_object;
3745e269 130static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
3c9af366 131static int verbose;
f46c46e4 132static const char *progress_title;
e376f17f 133static int show_resolving_progress;
3aba2fdd 134static int show_stat;
c6807a40 135static int check_self_contained_and_connected;
3c9af366 136
dc6a0757 137static struct progress *progress;
e42797f5 138
2d477051
NP
139/* We always read in 4kB chunks. */
140static unsigned char input_buffer[4096];
d7dd0223
NP
141static unsigned int input_offset, input_len;
142static off_t consumed_bytes;
411481be 143static off_t max_input_size;
d1a0ed18 144static unsigned deepest_delta;
454253f0 145static git_hash_ctx input_ctx;
ee5743ce 146static uint32_t input_crc32;
39539495
NTND
147static int input_fd, output_fd;
148static const char *curr_pack;
2d477051 149
b8a2486f
NTND
150static struct thread_local *thread_data;
151static int nr_dispatched;
152static int threads_active;
153
154static pthread_mutex_t read_mutex;
155#define read_lock() lock_mutex(&read_mutex)
156#define read_unlock() unlock_mutex(&read_mutex)
157
158static pthread_mutex_t counter_mutex;
159#define counter_lock() lock_mutex(&counter_mutex)
160#define counter_unlock() unlock_mutex(&counter_mutex)
161
162static pthread_mutex_t work_mutex;
163#define work_lock() lock_mutex(&work_mutex)
164#define work_unlock() unlock_mutex(&work_mutex)
165
3aba2fdd
NTND
166static pthread_mutex_t deepest_delta_mutex;
167#define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
168#define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
169
b8a2486f
NTND
170static pthread_key_t key;
171
172static inline void lock_mutex(pthread_mutex_t *mutex)
173{
174 if (threads_active)
175 pthread_mutex_lock(mutex);
176}
177
178static inline void unlock_mutex(pthread_mutex_t *mutex)
179{
180 if (threads_active)
181 pthread_mutex_unlock(mutex);
182}
183
184/*
185 * Mutex and conditional variable can't be statically-initialized on Windows.
186 */
187static void init_thread(void)
188{
39539495 189 int i;
b8a2486f
NTND
190 init_recursive_mutex(&read_mutex);
191 pthread_mutex_init(&counter_mutex, NULL);
192 pthread_mutex_init(&work_mutex, NULL);
3aba2fdd
NTND
193 if (show_stat)
194 pthread_mutex_init(&deepest_delta_mutex, NULL);
b8a2486f 195 pthread_key_create(&key, NULL);
ca56dadb 196 CALLOC_ARRAY(thread_data, nr_threads);
39539495 197 for (i = 0; i < nr_threads; i++) {
6346f704 198 thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
39539495
NTND
199 }
200
b8a2486f
NTND
201 threads_active = 1;
202}
203
204static void cleanup_thread(void)
205{
39539495 206 int i;
b8a2486f
NTND
207 if (!threads_active)
208 return;
209 threads_active = 0;
210 pthread_mutex_destroy(&read_mutex);
211 pthread_mutex_destroy(&counter_mutex);
212 pthread_mutex_destroy(&work_mutex);
3aba2fdd
NTND
213 if (show_stat)
214 pthread_mutex_destroy(&deepest_delta_mutex);
39539495
NTND
215 for (i = 0; i < nr_threads; i++)
216 close(thread_data[i].pack_fd);
b8a2486f
NTND
217 pthread_key_delete(key);
218 free(thread_data);
219}
220
a1aad716 221static int mark_link(struct object *obj, enum object_type type,
0b4e9013
JK
222 void *data UNUSED,
223 struct fsck_options *options UNUSED)
0153be05
MK
224{
225 if (!obj)
226 return -1;
227
228 if (type != OBJ_ANY && obj->type != type)
f2fd0760 229 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
0153be05
MK
230
231 obj->flags |= FLAG_LINK;
232 return 0;
233}
234
235/* The content of each linked object must have been checked
236 or it must be already present in the object database */
c6807a40 237static unsigned check_object(struct object *obj)
0153be05
MK
238{
239 if (!obj)
c6807a40 240 return 0;
0153be05
MK
241
242 if (!(obj->flags & FLAG_LINK))
c6807a40 243 return 0;
0153be05
MK
244
245 if (!(obj->flags & FLAG_CHECKED)) {
246 unsigned long size;
0df8e965 247 int type = oid_object_info(the_repository, &obj->oid, &size);
77583e77
JK
248 if (type <= 0)
249 die(_("did not receive expected object %s"),
f2fd0760 250 oid_to_hex(&obj->oid));
77583e77
JK
251 if (type != obj->type)
252 die(_("object %s: expected type %s, found %s"),
f2fd0760 253 oid_to_hex(&obj->oid),
debca9d2 254 type_name(obj->type), type_name(type));
0153be05 255 obj->flags |= FLAG_CHECKED;
c6807a40 256 return 1;
0153be05 257 }
c6807a40
NTND
258
259 return 0;
0153be05
MK
260}
261
c6807a40 262static unsigned check_objects(void)
0153be05 263{
c6807a40 264 unsigned i, max, foreign_nr = 0;
0153be05
MK
265
266 max = get_max_object_index();
79e3aa66
SG
267
268 if (verbose)
269 progress = start_delayed_progress(_("Checking objects"), max);
270
271 for (i = 0; i < max; i++) {
c6807a40 272 foreign_nr += check_object(get_indexed_object(i));
79e3aa66
SG
273 display_progress(progress, i + 1);
274 }
275
276 stop_progress(&progress);
c6807a40 277 return foreign_nr;
0153be05
MK
278}
279
280
636171cb 281/* Discard current buffer used content. */
a6e8a767 282static void flush(void)
636171cb
NP
283{
284 if (input_offset) {
285 if (output_fd >= 0)
286 write_or_die(output_fd, input_buffer, input_offset);
454253f0 287 the_hash_algo->update_fn(&input_ctx, input_buffer, input_offset);
554a2636 288 memmove(input_buffer, input_buffer + input_offset, input_len);
636171cb
NP
289 input_offset = 0;
290 }
291}
292
2d477051
NP
293/*
294 * Make sure at least "min" bytes are available in the buffer, and
295 * return the pointer to the buffer.
296 */
b89c4e93 297static void *fill(int min)
9cf6d335 298{
2d477051
NP
299 if (min <= input_len)
300 return input_buffer + input_offset;
301 if (min > sizeof(input_buffer))
c2b97ecf
NTND
302 die(Q_("cannot fill %d byte",
303 "cannot fill %d bytes",
304 min),
305 min);
636171cb 306 flush();
2d477051 307 do {
8a912bcb 308 ssize_t ret = xread(input_fd, input_buffer + input_len,
2d477051
NP
309 sizeof(input_buffer) - input_len);
310 if (ret <= 0) {
311 if (!ret)
c2b97ecf
NTND
312 die(_("early EOF"));
313 die_errno(_("read error on input"));
2d477051
NP
314 }
315 input_len += ret;
218558af
NP
316 if (from_stdin)
317 display_throughput(progress, consumed_bytes + input_len);
2d477051
NP
318 } while (input_len < min);
319 return input_buffer;
320}
321
322static void use(int bytes)
323{
324 if (bytes > input_len)
c2b97ecf 325 die(_("used more bytes than were available"));
ee5743ce 326 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
2d477051
NP
327 input_len -= bytes;
328 input_offset += bytes;
d7dd0223
NP
329
330 /* make sure off_t is sufficiently large not to wrap */
c03c8315 331 if (signed_add_overflows(consumed_bytes, bytes))
c2b97ecf 332 die(_("pack too large for current definition of off_t"));
2d477051 333 consumed_bytes += bytes;
0cf5fbc2
MC
334 if (max_input_size && consumed_bytes > max_input_size) {
335 struct strbuf size_limit = STRBUF_INIT;
336 strbuf_humanise_bytes(&size_limit, max_input_size);
337 die(_("pack exceeds maximum allowed size (%s)"),
338 size_limit.buf);
339 }
2d477051 340}
9cf6d335 341
3bb72562 342static const char *open_pack_file(const char *pack_name)
2d477051 343{
e42797f5
NP
344 if (from_stdin) {
345 input_fd = 0;
346 if (!pack_name) {
594fa999
JK
347 struct strbuf tmp_file = STRBUF_INIT;
348 output_fd = odb_mkstemp(&tmp_file,
6e180cdc 349 "pack/tmp_pack_XXXXXX");
594fa999 350 pack_name = strbuf_detach(&tmp_file, NULL);
892e723a 351 } else {
66e905b7 352 output_fd = xopen(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
892e723a 353 }
39539495 354 nothread_data.pack_fd = output_fd;
e42797f5 355 } else {
66e905b7 356 input_fd = xopen(pack_name, O_RDONLY);
e42797f5 357 output_fd = -1;
39539495 358 nothread_data.pack_fd = input_fd;
e42797f5 359 }
454253f0 360 the_hash_algo->init_fn(&input_ctx);
e42797f5 361 return pack_name;
9cf6d335
SV
362}
363
364static void parse_pack_header(void)
365{
2d477051 366 struct pack_header *hdr = fill(sizeof(struct pack_header));
9cf6d335
SV
367
368 /* Header consistency check */
9cf6d335 369 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
c2b97ecf 370 die(_("pack signature mismatch"));
d60fc1c8 371 if (!pack_version_ok(hdr->hdr_version))
f350df42 372 die(_("pack version %"PRIu32" unsupported"),
6e1c2344 373 ntohl(hdr->hdr_version));
9cf6d335
SV
374
375 nr_objects = ntohl(hdr->hdr_entries);
2d477051 376 use(sizeof(struct pack_header));
9cf6d335
SV
377}
378
103e02c7 379__attribute__((format (printf, 2, 3)))
fd3e6747 380static NORETURN void bad_object(off_t offset, const char *format, ...)
9cf6d335
SV
381{
382 va_list params;
383 char buf[1024];
384
385 va_start(params, format);
386 vsnprintf(buf, sizeof(buf), format, params);
387 va_end(params);
fd3e6747
NTND
388 die(_("pack has bad object at offset %"PRIuMAX": %s"),
389 (uintmax_t)offset, buf);
9cf6d335
SV
390}
391
b8a2486f
NTND
392static inline struct thread_local *get_thread_data(void)
393{
2094c5e5
NTND
394 if (HAVE_THREADS) {
395 if (threads_active)
396 return pthread_getspecific(key);
397 assert(!threads_active &&
398 "This should only be reached when all threads are gone");
399 }
b8a2486f
NTND
400 return &nothread_data;
401}
402
b8a2486f
NTND
403static void set_thread_data(struct thread_local *data)
404{
405 if (threads_active)
406 pthread_setspecific(key, data);
407}
b8a2486f 408
6a87ed97
NP
409static void free_base_data(struct base_data *c)
410{
411 if (c->data) {
6a83d902 412 FREE_AND_NULL(c->data);
f08cbf60 413 base_cache_used -= c->size;
6a87ed97
NP
414 }
415}
416
92392b4a
SP
417static void prune_base_data(struct base_data *retain)
418{
f08cbf60 419 struct list_head *pos;
92392b4a 420
f08cbf60 421 if (base_cache_used <= base_cache_limit)
a7f7e84a 422 return;
4a438cab 423
f08cbf60
JT
424 list_for_each_prev(pos, &done_head) {
425 struct base_data *b = list_entry(pos, struct base_data, list);
426 if (b->retain_data || b == retain)
427 continue;
428 if (b->data) {
429 free_base_data(b);
430 if (base_cache_used <= base_cache_limit)
431 return;
432 }
92392b4a 433 }
4a438cab 434
f08cbf60
JT
435 list_for_each_prev(pos, &work_head) {
436 struct base_data *b = list_entry(pos, struct base_data, list);
437 if (b->retain_data || b == retain)
438 continue;
439 if (b->data) {
440 free_base_data(b);
441 if (base_cache_used <= base_cache_limit)
442 return;
443 }
a7f7e84a 444 }
4a438cab
SP
445}
446
681b07de
NTND
447static int is_delta_type(enum object_type type)
448{
449 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
450}
451
da49a7da 452static void *unpack_entry_data(off_t offset, unsigned long size,
454253f0 453 enum object_type type, struct object_id *oid)
9cf6d335 454{
9ec2dde9 455 static char fixed_buf[8192];
7ce4721a 456 int status;
ef49a7a0 457 git_zstream stream;
9ec2dde9 458 void *buf;
454253f0 459 git_hash_ctx c;
681b07de
NTND
460 char hdr[32];
461 int hdrlen;
462
463 if (!is_delta_type(type)) {
b04cdea4 464 hdrlen = format_object_header(hdr, sizeof(hdr), type, size);
454253f0 465 the_hash_algo->init_fn(&c);
466 the_hash_algo->update_fn(&c, hdr, hdrlen);
681b07de 467 } else
454253f0 468 oid = NULL;
9ec2dde9
NTND
469 if (type == OBJ_BLOB && size > big_file_threshold)
470 buf = fixed_buf;
471 else
a1e920a0 472 buf = xmallocz(size);
9cf6d335
SV
473
474 memset(&stream, 0, sizeof(stream));
7ce4721a 475 git_inflate_init(&stream);
9cf6d335 476 stream.next_out = buf;
9ec2dde9 477 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
9cf6d335 478
7ce4721a 479 do {
681b07de 480 unsigned char *last_out = stream.next_out;
2d477051
NP
481 stream.next_in = fill(1);
482 stream.avail_in = input_len;
7ce4721a
NP
483 status = git_inflate(&stream, 0);
484 use(input_len - stream.avail_in);
454253f0 485 if (oid)
486 the_hash_algo->update_fn(&c, last_out, stream.next_out - last_out);
9ec2dde9
NTND
487 if (buf == fixed_buf) {
488 stream.next_out = buf;
489 stream.avail_out = sizeof(fixed_buf);
490 }
7ce4721a
NP
491 } while (status == Z_OK);
492 if (stream.total_out != size || status != Z_STREAM_END)
c2b97ecf 493 bad_object(offset, _("inflate returned %d"), status);
39c68542 494 git_inflate_end(&stream);
454253f0 495 if (oid)
5951bf46 496 the_hash_algo->final_oid_fn(oid, &c);
9ec2dde9 497 return buf == fixed_buf ? NULL : buf;
9cf6d335
SV
498}
499
681b07de 500static void *unpack_raw_entry(struct object_entry *obj,
c6458e60 501 off_t *ofs_offset,
454253f0 502 struct object_id *ref_oid,
503 struct object_id *oid)
9cf6d335 504{
48fb7deb
LT
505 unsigned char *p;
506 unsigned long size, c;
d7dd0223 507 off_t base_offset;
9cf6d335 508 unsigned shift;
ee5743ce 509 void *data;
9cf6d335 510
aa7e44bf 511 obj->idx.offset = consumed_bytes;
1e4cd68c 512 input_crc32 = crc32(0, NULL, 0);
2d477051
NP
513
514 p = fill(1);
515 c = *p;
516 use(1);
517 obj->type = (c >> 4) & 7;
9cf6d335
SV
518 size = (c & 15);
519 shift = 4;
520 while (c & 0x80) {
2d477051
NP
521 p = fill(1);
522 c = *p;
523 use(1);
48fb7deb 524 size += (c & 0x7f) << shift;
9cf6d335
SV
525 shift += 7;
526 }
2d477051 527 obj->size = size;
9cf6d335 528
2d477051 529 switch (obj->type) {
eb32d236 530 case OBJ_REF_DELTA:
92e2cab9 531 oidread(ref_oid, fill(the_hash_algo->rawsz));
454253f0 532 use(the_hash_algo->rawsz);
53dda6ff
NP
533 break;
534 case OBJ_OFS_DELTA:
2d477051
NP
535 p = fill(1);
536 c = *p;
537 use(1);
53dda6ff
NP
538 base_offset = c & 127;
539 while (c & 128) {
540 base_offset += 1;
8723f216 541 if (!base_offset || MSB(base_offset, 7))
c2b97ecf 542 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
2d477051
NP
543 p = fill(1);
544 c = *p;
545 use(1);
53dda6ff
NP
546 base_offset = (base_offset << 7) + (c & 127);
547 }
c6458e60
NTND
548 *ofs_offset = obj->idx.offset - base_offset;
549 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
c2b97ecf 550 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
53dda6ff 551 break;
9cf6d335
SV
552 case OBJ_COMMIT:
553 case OBJ_TREE:
554 case OBJ_BLOB:
555 case OBJ_TAG:
9cf6d335
SV
556 break;
557 default:
c2b97ecf 558 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
9cf6d335 559 }
aa7e44bf 560 obj->hdr_size = consumed_bytes - obj->idx.offset;
2d477051 561
454253f0 562 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, oid);
aa7e44bf 563 obj->idx.crc32 = input_crc32;
ee5743ce 564 return data;
2d477051
NP
565}
566
8a2e163c
NTND
567static void *unpack_data(struct object_entry *obj,
568 int (*consume)(const unsigned char *, unsigned long, void *),
569 void *cb_data)
2d477051 570{
a91ef6e7 571 off_t from = obj[0].idx.offset + obj[0].hdr_size;
7171a0b0 572 off_t len = obj[1].idx.offset - from;
776ea370 573 unsigned char *data, *inbuf;
ef49a7a0 574 git_zstream stream;
776ea370 575 int status;
9cf6d335 576
a1e920a0 577 data = xmallocz(consume ? 64*1024 : obj->size);
7171a0b0 578 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
776ea370 579
2d477051 580 memset(&stream, 0, sizeof(stream));
776ea370 581 git_inflate_init(&stream);
2d477051 582 stream.next_out = data;
8a2e163c 583 stream.avail_out = consume ? 64*1024 : obj->size;
776ea370
NP
584
585 do {
7171a0b0 586 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
53f52cd9 587 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
776ea370 588 if (n < 0)
c2b97ecf 589 die_errno(_("cannot pread pack file"));
776ea370 590 if (!n)
7171a0b0
NTND
591 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
592 "premature end of pack file, %"PRIuMAX" bytes missing",
6f693252 593 len),
7171a0b0 594 (uintmax_t)len);
776ea370
NP
595 from += n;
596 len -= n;
597 stream.next_in = inbuf;
598 stream.avail_in = n;
f8b09038
JK
599 if (!consume)
600 status = git_inflate(&stream, 0);
601 else {
602 do {
603 status = git_inflate(&stream, 0);
604 if (consume(data, stream.next_out - data, cb_data)) {
605 free(inbuf);
606 free(data);
607 return NULL;
608 }
609 stream.next_out = data;
610 stream.avail_out = 64*1024;
611 } while (status == Z_OK && stream.avail_in);
8a2e163c 612 }
776ea370
NP
613 } while (len && status == Z_OK && !stream.avail_in);
614
615 /* This has been inflated OK when first encountered, so... */
616 if (status != Z_STREAM_END || stream.total_out != obj->size)
c2b97ecf 617 die(_("serious inflate inconsistency"));
776ea370
NP
618
619 git_inflate_end(&stream);
620 free(inbuf);
8a2e163c 621 if (consume) {
6a83d902 622 FREE_AND_NULL(data);
8a2e163c 623 }
9cf6d335
SV
624 return data;
625}
626
8a2e163c
NTND
627static void *get_data_from_pack(struct object_entry *obj)
628{
629 return unpack_data(obj, NULL, NULL);
630}
631
c6458e60
NTND
632static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
633 enum object_type type1,
634 enum object_type type2)
7218a215
JH
635{
636 int cmp = type1 - type2;
637 if (cmp)
638 return cmp;
f0e7f11d
JK
639 return offset1 < offset2 ? -1 :
640 offset1 > offset2 ? 1 :
641 0;
7218a215
JH
642}
643
fc968e26 644static int find_ofs_delta(const off_t offset)
9cf6d335 645{
c6458e60
NTND
646 int first = 0, last = nr_ofs_deltas;
647
648 while (first < last) {
19716b21 649 int next = first + (last - first) / 2;
c6458e60
NTND
650 struct ofs_delta_entry *delta = &ofs_deltas[next];
651 int cmp;
652
653 cmp = compare_ofs_delta_bases(offset, delta->offset,
fc968e26
JT
654 OBJ_OFS_DELTA,
655 objects[delta->obj_no].type);
c6458e60
NTND
656 if (!cmp)
657 return next;
658 if (cmp < 0) {
659 last = next;
660 continue;
661 }
662 first = next+1;
663 }
664 return -first-1;
9cf6d335
SV
665}
666
c6458e60 667static void find_ofs_delta_children(off_t offset,
fc968e26 668 int *first_index, int *last_index)
9cf6d335 669{
fc968e26 670 int first = find_ofs_delta(offset);
9cf6d335 671 int last = first;
c6458e60 672 int end = nr_ofs_deltas - 1;
9cf6d335 673
6a87ed97
NP
674 if (first < 0) {
675 *first_index = 0;
676 *last_index = -1;
677 return;
678 }
c6458e60 679 while (first > 0 && ofs_deltas[first - 1].offset == offset)
9cf6d335 680 --first;
c6458e60
NTND
681 while (last < end && ofs_deltas[last + 1].offset == offset)
682 ++last;
683 *first_index = first;
684 *last_index = last;
685}
686
af8caf33 687static int compare_ref_delta_bases(const struct object_id *oid1,
688 const struct object_id *oid2,
c6458e60
NTND
689 enum object_type type1,
690 enum object_type type2)
691{
692 int cmp = type1 - type2;
693 if (cmp)
694 return cmp;
af8caf33 695 return oidcmp(oid1, oid2);
c6458e60
NTND
696}
697
fc968e26 698static int find_ref_delta(const struct object_id *oid)
c6458e60
NTND
699{
700 int first = 0, last = nr_ref_deltas;
701
702 while (first < last) {
19716b21 703 int next = first + (last - first) / 2;
c6458e60
NTND
704 struct ref_delta_entry *delta = &ref_deltas[next];
705 int cmp;
706
af8caf33 707 cmp = compare_ref_delta_bases(oid, &delta->oid,
fc968e26
JT
708 OBJ_REF_DELTA,
709 objects[delta->obj_no].type);
c6458e60
NTND
710 if (!cmp)
711 return next;
712 if (cmp < 0) {
713 last = next;
714 continue;
715 }
716 first = next+1;
717 }
718 return -first-1;
719}
720
af8caf33 721static void find_ref_delta_children(const struct object_id *oid,
fc968e26 722 int *first_index, int *last_index)
c6458e60 723{
fc968e26 724 int first = find_ref_delta(oid);
c6458e60
NTND
725 int last = first;
726 int end = nr_ref_deltas - 1;
727
728 if (first < 0) {
729 *first_index = 0;
730 *last_index = -1;
731 return;
732 }
4a7e27e9 733 while (first > 0 && oideq(&ref_deltas[first - 1].oid, oid))
c6458e60 734 --first;
4a7e27e9 735 while (last < end && oideq(&ref_deltas[last + 1].oid, oid))
9cf6d335
SV
736 ++last;
737 *first_index = first;
738 *last_index = last;
9cf6d335
SV
739}
740
4614043c
NTND
741struct compare_data {
742 struct object_entry *entry;
743 struct git_istream *st;
744 unsigned char *buf;
745 unsigned long buf_size;
746};
747
748static int compare_objects(const unsigned char *buf, unsigned long size,
749 void *cb_data)
750{
751 struct compare_data *data = cb_data;
752
753 if (data->buf_size < size) {
754 free(data->buf);
755 data->buf = xmalloc(size);
756 data->buf_size = size;
757 }
758
759 while (size) {
760 ssize_t len = read_istream(data->st, data->buf, size);
761 if (len == 0)
762 die(_("SHA1 COLLISION FOUND WITH %s !"),
e6a492b7 763 oid_to_hex(&data->entry->idx.oid));
4614043c
NTND
764 if (len < 0)
765 die(_("unable to read %s"),
e6a492b7 766 oid_to_hex(&data->entry->idx.oid));
4614043c
NTND
767 if (memcmp(buf, data->buf, len))
768 die(_("SHA1 COLLISION FOUND WITH %s !"),
e6a492b7 769 oid_to_hex(&data->entry->idx.oid));
4614043c
NTND
770 size -= len;
771 buf += len;
772 }
773 return 0;
774}
775
776static int check_collison(struct object_entry *entry)
777{
778 struct compare_data data;
779 enum object_type type;
780 unsigned long size;
781
782 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
783 return -1;
784
785 memset(&data, 0, sizeof(data));
786 data.entry = entry;
c8123e72
MT
787 data.st = open_istream(the_repository, &entry->idx.oid, &type, &size,
788 NULL);
4614043c
NTND
789 if (!data.st)
790 return -1;
791 if (size != entry->size || type != entry->type)
792 die(_("SHA1 COLLISION FOUND WITH %s !"),
e6a492b7 793 oid_to_hex(&entry->idx.oid));
4614043c
NTND
794 unpack_data(entry, compare_objects, &data);
795 close_istream(data.st);
796 free(data.buf);
797 return 0;
798}
799
9ec2dde9
NTND
800static void sha1_object(const void *data, struct object_entry *obj_entry,
801 unsigned long size, enum object_type type,
3e930981 802 const struct object_id *oid)
9cf6d335 803{
9ec2dde9 804 void *new_data = NULL;
29401e15 805 int collision_test_needed = 0;
9ec2dde9
NTND
806
807 assert(data || obj_entry);
808
29401e15
JK
809 if (startup_info->have_repository) {
810 read_lock();
e83e71c5 811 collision_test_needed =
bc726bd0
ÆAB
812 repo_has_object_file_with_flags(the_repository, oid,
813 OBJECT_INFO_QUICK);
29401e15
JK
814 read_unlock();
815 }
4614043c
NTND
816
817 if (collision_test_needed && !data) {
818 read_lock();
819 if (!check_collison(obj_entry))
820 collision_test_needed = 0;
821 read_unlock();
822 }
823 if (collision_test_needed) {
8685da42
NP
824 void *has_data;
825 enum object_type has_type;
826 unsigned long has_size;
4614043c 827 read_lock();
0df8e965 828 has_type = oid_object_info(the_repository, oid, &has_size);
51054177 829 if (has_type < 0)
3e930981 830 die(_("cannot read existing object info %s"), oid_to_hex(oid));
4614043c 831 if (has_type != type || has_size != size)
3e930981 832 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
bc726bd0
ÆAB
833 has_data = repo_read_object_file(the_repository, oid,
834 &has_type, &has_size);
b8a2486f 835 read_unlock();
4614043c
NTND
836 if (!data)
837 data = new_data = get_data_from_pack(obj_entry);
8685da42 838 if (!has_data)
3e930981 839 die(_("cannot read existing object %s"), oid_to_hex(oid));
8685da42
NP
840 if (size != has_size || type != has_type ||
841 memcmp(data, has_data, size) != 0)
3e930981 842 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
bbf4b41b 843 free(has_data);
4614043c 844 }
b8a2486f 845
ffb2c0fe 846 if (strict || do_fsck_object) {
b8a2486f 847 read_lock();
0153be05 848 if (type == OBJ_BLOB) {
da14a7ff 849 struct blob *blob = lookup_blob(the_repository, oid);
0153be05
MK
850 if (blob)
851 blob->object.flags |= FLAG_CHECKED;
852 else
3e930981 853 die(_("invalid blob object %s"), oid_to_hex(oid));
73c3f0f7
JK
854 if (do_fsck_object &&
855 fsck_object(&blob->object, (void *)data, size, &fsck_options))
856 die(_("fsck error in packed object"));
0153be05
MK
857 } else {
858 struct object *obj;
859 int eaten;
860 void *buf = (void *) data;
861
920734b0 862 assert(data && "data can only be NULL for large _blobs_");
9ec2dde9 863
0153be05
MK
864 /*
865 * we do not need to free the memory here, as the
866 * buf is deleted by the caller.
867 */
1ec5bfd2
SB
868 obj = parse_object_buffer(the_repository, oid, type,
869 size, buf,
c251c83d 870 &eaten);
0153be05 871 if (!obj)
debca9d2 872 die(_("invalid %s"), type_name(type));
c6807a40 873 if (do_fsck_object &&
22410549 874 fsck_object(obj, buf, size, &fsck_options))
db5a58c1 875 die(_("fsck error in packed object"));
ffb2c0fe 876 if (strict && fsck_walk(obj, NULL, &fsck_options))
f2fd0760 877 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
0153be05
MK
878
879 if (obj->type == OBJ_TREE) {
880 struct tree *item = (struct tree *) obj;
881 item->buffer = NULL;
6e454b9a 882 obj->parsed = 0;
0153be05
MK
883 }
884 if (obj->type == OBJ_COMMIT) {
885 struct commit *commit = (struct commit *) obj;
8597ea3a 886 if (detach_commit_buffer(commit, NULL) != data)
033abf97 887 BUG("parse_object_buffer transmogrified our buffer");
0153be05
MK
888 }
889 obj->flags |= FLAG_CHECKED;
890 }
b8a2486f 891 read_unlock();
0153be05 892 }
9ec2dde9
NTND
893
894 free(new_data);
9cf6d335
SV
895}
896
20e95d0a 897/*
ec6a8f97 898 * Ensure that this node has been reconstructed and return its contents.
20e95d0a 899 *
ec6a8f97
JT
900 * In the typical and best case, this node would already be reconstructed
901 * (through the invocation to resolve_delta() in threaded_second_pass()) and it
902 * would not be pruned. However, if pruning of this node was necessary due to
903 * reaching delta_base_cache_limit, this function will find the closest
904 * ancestor with reconstructed data that has not been pruned (or if there is
905 * none, the ultimate base object), and reconstruct each node in the delta
906 * chain in order to generate the reconstructed data for this node.
20e95d0a 907 */
92392b4a
SP
908static void *get_base_data(struct base_data *c)
909{
910 if (!c->data) {
911 struct object_entry *obj = c->obj;
20e95d0a
NTND
912 struct base_data **delta = NULL;
913 int delta_nr = 0, delta_alloc = 0;
92392b4a 914
20e95d0a
NTND
915 while (is_delta_type(c->obj->type) && !c->data) {
916 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
917 delta[delta_nr++] = c;
918 c = c->base;
919 }
920 if (!delta_nr) {
921 c->data = get_data_from_pack(obj);
922 c->size = obj->size;
f08cbf60 923 base_cache_used += c->size;
20e95d0a
NTND
924 prune_base_data(c);
925 }
926 for (; delta_nr > 0; delta_nr--) {
927 void *base, *raw;
928 c = delta[delta_nr - 1];
929 obj = c->obj;
930 base = get_base_data(c->base);
931 raw = get_data_from_pack(obj);
92392b4a
SP
932 c->data = patch_delta(
933 base, c->base->size,
934 raw, obj->size,
935 &c->size);
936 free(raw);
937 if (!c->data)
c2b97ecf 938 bad_object(obj->idx.offset, _("failed to apply delta"));
f08cbf60 939 base_cache_used += c->size;
20e95d0a 940 prune_base_data(c);
9441b61d 941 }
20e95d0a 942 free(delta);
92392b4a
SP
943 }
944 return c->data;
945}
946
b4718cae
JT
947static struct base_data *make_base(struct object_entry *obj,
948 struct base_data *parent)
9cf6d335 949{
b4718cae
JT
950 struct base_data *base = xcalloc(1, sizeof(struct base_data));
951 base->base = parent;
952 base->obj = obj;
953 find_ref_delta_children(&obj->idx.oid,
954 &base->ref_first, &base->ref_last);
955 find_ofs_delta_children(obj->idx.offset,
956 &base->ofs_first, &base->ofs_last);
f08cbf60
JT
957 base->children_remaining = base->ref_last - base->ref_first +
958 base->ofs_last - base->ofs_first + 2;
b4718cae
JT
959 return base;
960}
961
962static struct base_data *resolve_delta(struct object_entry *delta_obj,
963 struct base_data *base)
964{
ee6f0583 965 void *delta_data, *result_data;
b4718cae
JT
966 struct base_data *result;
967 unsigned long result_size;
9cf6d335 968
3aba2fdd 969 if (show_stat) {
41730576
NTND
970 int i = delta_obj - objects;
971 int j = base->obj - objects;
972 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
3aba2fdd 973 deepest_delta_lock();
41730576
NTND
974 if (deepest_delta < obj_stat[i].delta_depth)
975 deepest_delta = obj_stat[i].delta_depth;
3aba2fdd 976 deepest_delta_unlock();
41730576 977 obj_stat[i].base_object_no = j;
3aba2fdd 978 }
636171cb 979 delta_data = get_data_from_pack(delta_obj);
ee6f0583
JT
980 assert(base->data);
981 result_data = patch_delta(base->data, base->size,
b4718cae 982 delta_data, delta_obj->size, &result_size);
9cf6d335 983 free(delta_data);
b4718cae 984 if (!result_data)
c2b97ecf 985 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
b4718cae 986 hash_object_file(the_hash_algo, result_data, result_size,
44439c1c 987 delta_obj->real_type, &delta_obj->idx.oid);
b4718cae 988 sha1_object(result_data, NULL, result_size, delta_obj->real_type,
3e930981 989 &delta_obj->idx.oid);
b4718cae
JT
990
991 result = make_base(delta_obj, base);
f08cbf60
JT
992 result->data = result_data;
993 result->size = result_size;
b4718cae 994
b8a2486f 995 counter_lock();
636171cb 996 nr_resolved_deltas++;
b8a2486f 997 counter_unlock();
ab791dd1 998
b4718cae 999 return result;
9cf6d335
SV
1000}
1001
c6458e60 1002static int compare_ofs_delta_entry(const void *a, const void *b)
9cf6d335 1003{
c6458e60
NTND
1004 const struct ofs_delta_entry *delta_a = a;
1005 const struct ofs_delta_entry *delta_b = b;
7218a215 1006
f0e7f11d
JK
1007 return delta_a->offset < delta_b->offset ? -1 :
1008 delta_a->offset > delta_b->offset ? 1 :
1009 0;
c6458e60
NTND
1010}
1011
1012static int compare_ref_delta_entry(const void *a, const void *b)
9cf6d335 1013{
c6458e60
NTND
1014 const struct ref_delta_entry *delta_a = a;
1015 const struct ref_delta_entry *delta_b = b;
7218a215 1016
af8caf33 1017 return oidcmp(&delta_a->oid, &delta_b->oid);
9cf6d335
SV
1018}
1019
b8a2486f
NTND
1020static void *threaded_second_pass(void *data)
1021{
f08cbf60
JT
1022 if (data)
1023 set_thread_data(data);
b8a2486f 1024 for (;;) {
f08cbf60
JT
1025 struct base_data *parent = NULL;
1026 struct object_entry *child_obj;
1027 struct base_data *child;
1028
cea69151
JK
1029 counter_lock();
1030 display_progress(progress, nr_resolved_deltas);
1031 counter_unlock();
1032
8f82aad4 1033 work_lock();
f08cbf60
JT
1034 if (list_empty(&work_head)) {
1035 /*
1036 * Take an object from the object array.
1037 */
1038 while (nr_dispatched < nr_objects &&
1039 is_delta_type(objects[nr_dispatched].type))
1040 nr_dispatched++;
1041 if (nr_dispatched >= nr_objects) {
1042 work_unlock();
1043 break;
1044 }
1045 child_obj = &objects[nr_dispatched++];
1046 } else {
1047 /*
1048 * Peek at the top of the stack, and take a child from
1049 * it.
1050 */
1051 parent = list_first_entry(&work_head, struct base_data,
1052 list);
1053
1054 if (parent->ref_first <= parent->ref_last) {
1055 int offset = ref_deltas[parent->ref_first++].obj_no;
1056 child_obj = objects + offset;
1057 if (child_obj->real_type != OBJ_REF_DELTA)
1058 die("REF_DELTA at offset %"PRIuMAX" already resolved (duplicate base %s?)",
1059 (uintmax_t) child_obj->idx.offset,
1060 oid_to_hex(&parent->obj->idx.oid));
1061 child_obj->real_type = parent->obj->real_type;
1062 } else {
1063 child_obj = objects +
1064 ofs_deltas[parent->ofs_first++].obj_no;
1065 assert(child_obj->real_type == OBJ_OFS_DELTA);
1066 child_obj->real_type = parent->obj->real_type;
1067 }
1068
1069 if (parent->ref_first > parent->ref_last &&
1070 parent->ofs_first > parent->ofs_last) {
1071 /*
1072 * This parent has run out of children, so move
1073 * it to done_head.
1074 */
1075 list_del(&parent->list);
1076 list_add(&parent->list, &done_head);
1077 }
1078
1079 /*
1080 * Ensure that the parent has data, since we will need
1081 * it later.
1082 *
1083 * NEEDSWORK: If parent data needs to be reloaded, this
1084 * prolongs the time that the current thread spends in
1085 * the mutex. A mitigating factor is that parent data
1086 * needs to be reloaded only if the delta base cache
1087 * limit is exceeded, so in the typical case, this does
1088 * not happen.
1089 */
1090 get_base_data(parent);
1091 parent->retain_data++;
b8a2486f 1092 }
b8a2486f
NTND
1093 work_unlock();
1094
f08cbf60
JT
1095 if (parent) {
1096 child = resolve_delta(child_obj, parent);
1097 if (!child->children_remaining)
1098 FREE_AND_NULL(child->data);
1099 } else {
1100 child = make_base(child_obj, NULL);
1101 if (child->children_remaining) {
1102 /*
1103 * Since this child has its own delta children,
1104 * we will need this data in the future.
1105 * Inflate now so that future iterations will
1106 * have access to this object's data while
1107 * outside the work mutex.
1108 */
1109 child->data = get_data_from_pack(child_obj);
1110 child->size = child_obj->size;
1111 }
1112 }
1113
1114 work_lock();
1115 if (parent)
1116 parent->retain_data--;
1117 if (child->data) {
1118 /*
1119 * This child has its own children, so add it to
1120 * work_head.
1121 */
1122 list_add(&child->list, &work_head);
1123 base_cache_used += child->size;
1124 prune_base_data(NULL);
f2bcc69e 1125 free_base_data(child);
f08cbf60
JT
1126 } else {
1127 /*
1128 * This child does not have its own children. It may be
1129 * the last descendant of its ancestors; free those
1130 * that we can.
1131 */
1132 struct base_data *p = parent;
1133
1134 while (p) {
1135 struct base_data *next_p;
1136
1137 p->children_remaining--;
1138 if (p->children_remaining)
1139 break;
1140
1141 next_p = p->base;
1142 free_base_data(p);
1143 list_del(&p->list);
1144 free(p);
1145
1146 p = next_p;
1147 }
f2bcc69e 1148 FREE_AND_NULL(child);
f08cbf60
JT
1149 }
1150 work_unlock();
b8a2486f
NTND
1151 }
1152 return NULL;
1153}
b8a2486f 1154
5272f755
NTND
1155/*
1156 * First pass:
1157 * - find locations of all objects;
1158 * - calculate SHA1 of all non-delta objects;
1159 * - remember base (SHA1 or offset) for all deltas.
1160 */
454253f0 1161static void parse_pack_objects(unsigned char *hash)
9cf6d335 1162{
9ec2dde9 1163 int i, nr_delays = 0;
c6458e60 1164 struct ofs_delta_entry *ofs_delta = ofs_deltas;
454253f0 1165 struct object_id ref_delta_oid;
2d477051 1166 struct stat st;
e0b8c842 1167 git_hash_ctx tmp_ctx;
9cf6d335 1168
13aaf148 1169 if (verbose)
29e63ed3 1170 progress = start_progress(
f46c46e4 1171 progress_title ? progress_title :
c2b97ecf 1172 from_stdin ? _("Receiving objects") : _("Indexing objects"),
29e63ed3 1173 nr_objects);
9cf6d335
SV
1174 for (i = 0; i < nr_objects; i++) {
1175 struct object_entry *obj = &objects[i];
c6458e60 1176 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
454253f0 1177 &ref_delta_oid,
1178 &obj->idx.oid);
9cf6d335 1179 obj->real_type = obj->type;
c6458e60
NTND
1180 if (obj->type == OBJ_OFS_DELTA) {
1181 nr_ofs_deltas++;
1182 ofs_delta->obj_no = i;
1183 ofs_delta++;
1184 } else if (obj->type == OBJ_REF_DELTA) {
1185 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
af8caf33 1186 oidcpy(&ref_deltas[nr_ref_deltas].oid, &ref_delta_oid);
c6458e60
NTND
1187 ref_deltas[nr_ref_deltas].obj_no = i;
1188 nr_ref_deltas++;
9ec2dde9
NTND
1189 } else if (!data) {
1190 /* large blobs, check later */
1191 obj->real_type = OBJ_BAD;
1192 nr_delays++;
9cf6d335 1193 } else
e6a492b7 1194 sha1_object(data, NULL, obj->size, obj->type,
3e930981 1195 &obj->idx.oid);
9cf6d335 1196 free(data);
4d4fcc54 1197 display_progress(progress, i+1);
9cf6d335 1198 }
aa7e44bf 1199 objects[i].idx.offset = consumed_bytes;
4d4fcc54 1200 stop_progress(&progress);
2d477051
NP
1201
1202 /* Check pack integrity */
636171cb 1203 flush();
e0b8c842
EW
1204 the_hash_algo->init_fn(&tmp_ctx);
1205 the_hash_algo->clone_fn(&tmp_ctx, &input_ctx);
1206 the_hash_algo->final_fn(hash, &tmp_ctx);
67947c34 1207 if (!hasheq(fill(the_hash_algo->rawsz), hash))
c2b97ecf 1208 die(_("pack is corrupted (SHA1 mismatch)"));
454253f0 1209 use(the_hash_algo->rawsz);
2d477051
NP
1210
1211 /* If input_fd is a file, we should have reached its end now. */
1212 if (fstat(input_fd, &st))
c2b97ecf 1213 die_errno(_("cannot fstat packfile"));
fa257b05
JS
1214 if (S_ISREG(st.st_mode) &&
1215 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
c2b97ecf 1216 die(_("pack has junk at the end"));
9ec2dde9
NTND
1217
1218 for (i = 0; i < nr_objects; i++) {
1219 struct object_entry *obj = &objects[i];
1220 if (obj->real_type != OBJ_BAD)
1221 continue;
1222 obj->real_type = obj->type;
e6a492b7 1223 sha1_object(NULL, obj, obj->size, obj->type,
3e930981 1224 &obj->idx.oid);
9ec2dde9
NTND
1225 nr_delays--;
1226 }
1227 if (nr_delays)
1228 die(_("confusion beyond insanity in parse_pack_objects()"));
5272f755
NTND
1229}
1230
1231/*
1232 * Second pass:
1233 * - for all non-delta objects, look if it is used as a base for
1234 * deltas;
1235 * - if used as a base, uncompress the object and apply all deltas,
1236 * recursively checking if the resulting object is used as a base
1237 * for some more deltas.
1238 */
1239static void resolve_deltas(void)
1240{
1241 int i;
9cf6d335 1242
c6458e60 1243 if (!nr_ofs_deltas && !nr_ref_deltas)
3c9af366
NP
1244 return;
1245
53dda6ff 1246 /* Sort deltas by base SHA1/offset for fast searching */
9ed0d8d6
RS
1247 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1248 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
9cf6d335 1249
e376f17f 1250 if (verbose || show_resolving_progress)
c6458e60
NTND
1251 progress = start_progress(_("Resolving deltas"),
1252 nr_ref_deltas + nr_ofs_deltas);
b8a2486f 1253
b8a2486f 1254 nr_dispatched = 0;
f08cbf60 1255 base_cache_limit = delta_base_cache_limit * nr_threads;
b8a2486f
NTND
1256 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1257 init_thread();
993d38a0 1258 work_lock();
b8a2486f
NTND
1259 for (i = 0; i < nr_threads; i++) {
1260 int ret = pthread_create(&thread_data[i].thread, NULL,
1261 threaded_second_pass, thread_data + i);
1262 if (ret)
f350df42
NTND
1263 die(_("unable to create thread: %s"),
1264 strerror(ret));
b8a2486f 1265 }
993d38a0 1266 work_unlock();
b8a2486f
NTND
1267 for (i = 0; i < nr_threads; i++)
1268 pthread_join(thread_data[i].thread, NULL);
1269 cleanup_thread();
1270 return;
1271 }
46e6fb1e 1272 threaded_second_pass(&nothread_data);
636171cb
NP
1273}
1274
5272f755
NTND
1275/*
1276 * Third pass:
1277 * - append objects to convert thin pack to full pack if required
454253f0 1278 * - write the final pack hash
5272f755 1279 */
98a3beab 1280static void fix_unresolved_deltas(struct hashfile *f);
454253f0 1281static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_hash)
5272f755 1282{
c6458e60 1283 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
5272f755 1284 stop_progress(&progress);
454253f0 1285 /* Flush remaining pack final hash. */
5272f755
NTND
1286 flush();
1287 return;
1288 }
1289
1290 if (fix_thin_pack) {
98a3beab 1291 struct hashfile *f;
454253f0 1292 unsigned char read_hash[GIT_MAX_RAWSZ], tail_hash[GIT_MAX_RAWSZ];
5c3459fc 1293 struct strbuf msg = STRBUF_INIT;
c6458e60 1294 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
5272f755
NTND
1295 int nr_objects_initial = nr_objects;
1296 if (nr_unresolved <= 0)
cc13431a 1297 die(_("confusion beyond insanity"));
2756ca43 1298 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
57165db0
JK
1299 memset(objects + nr_objects + 1, 0,
1300 nr_unresolved * sizeof(*objects));
98a3beab 1301 f = hashfd(output_fd, curr_pack);
781d9306 1302 fix_unresolved_deltas(f);
71d99b81
VA
1303 strbuf_addf(&msg, Q_("completed with %d local object",
1304 "completed with %d local objects",
1305 nr_objects - nr_objects_initial),
5c3459fc
NTND
1306 nr_objects - nr_objects_initial);
1307 stop_progress_msg(&progress, msg.buf);
1308 strbuf_release(&msg);
020406ea 1309 finalize_hashfile(f, tail_hash, FSYNC_COMPONENT_PACK, 0);
454253f0 1310 hashcpy(read_hash, pack_hash);
1311 fixup_pack_header_footer(output_fd, pack_hash,
5272f755 1312 curr_pack, nr_objects,
454253f0 1313 read_hash, consumed_bytes-the_hash_algo->rawsz);
67947c34 1314 if (!hasheq(read_hash, tail_hash))
f350df42
NTND
1315 die(_("Unexpected tail checksum for %s "
1316 "(disk corruption?)"), curr_pack);
5272f755 1317 }
c6458e60 1318 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
cc13431a
JH
1319 die(Q_("pack has %d unresolved delta",
1320 "pack has %d unresolved deltas",
c6458e60
NTND
1321 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1322 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
5272f755
NTND
1323}
1324
98a3beab 1325static int write_compressed(struct hashfile *f, void *in, unsigned int size)
636171cb 1326{
ef49a7a0 1327 git_zstream stream;
7734d7f2
NP
1328 int status;
1329 unsigned char outbuf[4096];
636171cb 1330
55bb5c91 1331 git_deflate_init(&stream, zlib_compression_level);
636171cb
NP
1332 stream.next_in = in;
1333 stream.avail_in = size;
636171cb 1334
7734d7f2
NP
1335 do {
1336 stream.next_out = outbuf;
1337 stream.avail_out = sizeof(outbuf);
55bb5c91 1338 status = git_deflate(&stream, Z_FINISH);
98a3beab 1339 hashwrite(f, outbuf, sizeof(outbuf) - stream.avail_out);
7734d7f2
NP
1340 } while (status == Z_OK);
1341
1342 if (status != Z_STREAM_END)
c2b97ecf 1343 die(_("unable to deflate appended object (%d)"), status);
636171cb 1344 size = stream.total_out;
55bb5c91 1345 git_deflate_end(&stream);
636171cb
NP
1346 return size;
1347}
1348
98a3beab 1349static struct object_entry *append_obj_to_pack(struct hashfile *f,
03993e13 1350 const unsigned char *sha1, void *buf,
636171cb
NP
1351 unsigned long size, enum object_type type)
1352{
1353 struct object_entry *obj = &objects[nr_objects++];
1354 unsigned char header[10];
1355 unsigned long s = size;
1356 int n = 0;
1357 unsigned char c = (type << 4) | (s & 15);
1358 s >>= 4;
1359 while (s) {
1360 header[n++] = c | 0x80;
1361 c = s & 0x7f;
1362 s >>= 7;
1363 }
1364 header[n++] = c;
8522148f 1365 crc32_begin(f);
98a3beab 1366 hashwrite(f, header, n);
72de2883
BS
1367 obj[0].size = size;
1368 obj[0].hdr_size = n;
1369 obj[0].type = type;
1370 obj[0].real_type = type;
aa7e44bf 1371 obj[1].idx.offset = obj[0].idx.offset + n;
8522148f
NP
1372 obj[1].idx.offset += write_compressed(f, buf, size);
1373 obj[0].idx.crc32 = crc32_end(f);
98a3beab 1374 hashflush(f);
92e2cab9 1375 oidread(&obj->idx.oid, sha1);
03993e13 1376 return obj;
636171cb
NP
1377}
1378
1379static int delta_pos_compare(const void *_a, const void *_b)
1380{
c6458e60
NTND
1381 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1382 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
636171cb
NP
1383 return a->obj_no - b->obj_no;
1384}
9cf6d335 1385
98a3beab 1386static void fix_unresolved_deltas(struct hashfile *f)
636171cb 1387{
c6458e60 1388 struct ref_delta_entry **sorted_by_pos;
781d9306 1389 int i;
636171cb
NP
1390
1391 /*
1392 * Since many unresolved deltas may well be themselves base objects
1393 * for more unresolved deltas, we really want to include the
1394 * smallest number of base objects that would cover as much delta
1395 * as possible by picking the
1396 * trunc deltas first, allowing for other deltas to resolve without
1397 * additional base objects. Since most base objects are to be found
1398 * before deltas depending on them, a good heuristic is to start
1399 * resolving deltas in the same order as their position in the pack.
1400 */
b32fa95f 1401 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
c6458e60 1402 for (i = 0; i < nr_ref_deltas; i++)
781d9306 1403 sorted_by_pos[i] = &ref_deltas[i];
9ed0d8d6 1404 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
636171cb 1405
a5183d76 1406 if (repo_has_promisor_remote(the_repository)) {
8a30a1ef
JT
1407 /*
1408 * Prefetch the delta bases.
1409 */
1410 struct oid_array to_fetch = OID_ARRAY_INIT;
1411 for (i = 0; i < nr_ref_deltas; i++) {
1412 struct ref_delta_entry *d = sorted_by_pos[i];
1413 if (!oid_object_info_extended(the_repository, &d->oid,
1414 NULL,
1415 OBJECT_INFO_FOR_PREFETCH))
1416 continue;
1417 oid_array_append(&to_fetch, &d->oid);
1418 }
db7ed741
JT
1419 promisor_remote_get_direct(the_repository,
1420 to_fetch.oid, to_fetch.nr);
8a30a1ef
JT
1421 oid_array_clear(&to_fetch);
1422 }
1423
781d9306 1424 for (i = 0; i < nr_ref_deltas; i++) {
c6458e60 1425 struct ref_delta_entry *d = sorted_by_pos[i];
21666f1a 1426 enum object_type type;
b4718cae
JT
1427 void *data;
1428 unsigned long size;
636171cb
NP
1429
1430 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1431 continue;
bc726bd0
ÆAB
1432 data = repo_read_object_file(the_repository, &d->oid, &type,
1433 &size);
b4718cae 1434 if (!data)
636171cb 1435 continue;
636171cb 1436
ee213de2 1437 if (check_object_signature(the_repository, &d->oid, data, size,
44439c1c 1438 type) < 0)
af8caf33 1439 die(_("local object %s is corrupt"), oid_to_hex(&d->oid));
f08cbf60
JT
1440
1441 /*
1442 * Add this as an object to the objects array and call
1443 * threaded_second_pass() (which will pick up the added
1444 * object).
1445 */
1446 append_obj_to_pack(f, d->oid.hash, data, size, type);
f2bcc69e 1447 free(data);
f08cbf60
JT
1448 threaded_second_pass(NULL);
1449
4d4fcc54 1450 display_progress(progress, nr_resolved_deltas);
636171cb
NP
1451 }
1452 free(sorted_by_pos);
1453}
1454
84d54494
TB
1455static const char *derive_filename(const char *pack_name, const char *strip,
1456 const char *suffix, struct strbuf *buf)
8e29c7c3
JT
1457{
1458 size_t len;
84d54494
TB
1459 if (!strip_suffix(pack_name, strip, &len) || !len ||
1460 pack_name[len - 1] != '.')
1461 die(_("packfile name '%s' does not end with '.%s'"),
1462 pack_name, strip);
8e29c7c3 1463 strbuf_add(buf, pack_name, len);
8e29c7c3
JT
1464 strbuf_addstr(buf, suffix);
1465 return buf->buf;
1466}
1467
1468static void write_special_file(const char *suffix, const char *msg,
0fd90dab 1469 const char *pack_name, const unsigned char *hash,
8e29c7c3
JT
1470 const char **report)
1471{
1472 struct strbuf name_buf = STRBUF_INIT;
1473 const char *filename;
1474 int fd;
1475 int msg_len = strlen(msg);
1476
1477 if (pack_name)
84d54494 1478 filename = derive_filename(pack_name, "pack", suffix, &name_buf);
8e29c7c3 1479 else
0fd90dab 1480 filename = odb_pack_name(&name_buf, hash, suffix);
8e29c7c3
JT
1481
1482 fd = odb_pack_keep(filename);
1483 if (fd < 0) {
1484 if (errno != EEXIST)
1485 die_errno(_("cannot write %s file '%s'"),
1486 suffix, filename);
1487 } else {
1488 if (msg_len > 0) {
1489 write_or_die(fd, msg, msg_len);
1490 write_or_die(fd, "\n", 1);
1491 }
1492 if (close(fd) != 0)
1493 die_errno(_("cannot close written %s file '%s'"),
1494 suffix, filename);
88e2f9ed
JT
1495 if (report)
1496 *report = suffix;
8e29c7c3
JT
1497 }
1498 strbuf_release(&name_buf);
1499}
1500
8737dab3
ÆAB
1501static void rename_tmp_packfile(const char **final_name,
1502 const char *curr_name,
1503 struct strbuf *name, unsigned char *hash,
1504 const char *ext, int make_read_only_if_same)
1505{
1506 if (*final_name != curr_name) {
1507 if (!*final_name)
1508 *final_name = odb_pack_name(name, hash, ext);
1509 if (finalize_object_file(curr_name, *final_name))
f7337193 1510 die(_("unable to rename temporary '*.%s' file to '%s'"),
8737dab3
ÆAB
1511 ext, *final_name);
1512 } else if (make_read_only_if_same) {
1513 chmod(*final_name, 0444);
1514 }
1515}
1516
e42797f5
NP
1517static void final(const char *final_pack_name, const char *curr_pack_name,
1518 const char *final_index_name, const char *curr_index_name,
e37d0b87 1519 const char *final_rev_index_name, const char *curr_rev_index_name,
88e2f9ed 1520 const char *keep_msg, const char *promisor_msg,
454253f0 1521 unsigned char *hash)
e42797f5 1522{
3a55602e 1523 const char *report = "pack";
f2075480
JK
1524 struct strbuf pack_name = STRBUF_INIT;
1525 struct strbuf index_name = STRBUF_INIT;
e37d0b87 1526 struct strbuf rev_index_name = STRBUF_INIT;
e42797f5
NP
1527
1528 if (!from_stdin) {
1529 close(input_fd);
1530 } else {
020406ea 1531 fsync_component_or_die(FSYNC_COMPONENT_PACK, output_fd, curr_pack_name);
fa6c3833 1532 if (close(output_fd))
c2b97ecf 1533 die_errno(_("error while closing pack file"));
e42797f5
NP
1534 }
1535
8e29c7c3 1536 if (keep_msg)
0fd90dab 1537 write_special_file("keep", keep_msg, final_pack_name, hash,
8e29c7c3 1538 &report);
88e2f9ed
JT
1539 if (promisor_msg)
1540 write_special_file("promisor", promisor_msg, final_pack_name,
0fd90dab 1541 hash, NULL);
b8077709 1542
8737dab3
ÆAB
1543 rename_tmp_packfile(&final_pack_name, curr_pack_name, &pack_name,
1544 hash, "pack", from_stdin);
8737dab3
ÆAB
1545 if (curr_rev_index_name)
1546 rename_tmp_packfile(&final_rev_index_name, curr_rev_index_name,
1547 &rev_index_name, hash, "rev", 1);
522a5c2c
TB
1548 rename_tmp_packfile(&final_index_name, curr_index_name, &index_name,
1549 hash, "idx", 1);
e37d0b87 1550
368b4e59
JK
1551 if (do_fsck_object) {
1552 struct packed_git *p;
1553 p = add_packed_git(final_index_name, strlen(final_index_name), 0);
1554 if (p)
549ca8aa 1555 install_packed_git(the_repository, p);
368b4e59 1556 }
73c3f0f7 1557
576162a4 1558 if (!from_stdin) {
69fa3370 1559 printf("%s\n", hash_to_hex(hash));
576162a4 1560 } else {
5b1ef2ce
JK
1561 struct strbuf buf = STRBUF_INIT;
1562
69fa3370 1563 strbuf_addf(&buf, "%s\t%s\n", report, hash_to_hex(hash));
5b1ef2ce
JK
1564 write_or_die(1, buf.buf, buf.len);
1565 strbuf_release(&buf);
576162a4 1566
fa6c3833
JH
1567 /* Write the last part of the buffer to stdout */
1568 write_in_full(1, input_buffer + input_offset, input_len);
576162a4 1569 }
ba47a308 1570
e37d0b87 1571 strbuf_release(&rev_index_name);
f2075480
JK
1572 strbuf_release(&index_name);
1573 strbuf_release(&pack_name);
9cf6d335
SV
1574}
1575
a4e7e317
GC
1576static int git_index_pack_config(const char *k, const char *v,
1577 const struct config_context *ctx, void *cb)
4d00bda2 1578{
ebcfb379
JH
1579 struct pack_idx_option *opts = cb;
1580
4d00bda2 1581 if (!strcmp(k, "pack.indexversion")) {
8868b1eb 1582 opts->version = git_config_int(k, v, ctx->kvi);
ebcfb379 1583 if (opts->version > 2)
b4eda05d 1584 die(_("bad pack.indexVersion=%"PRIu32), opts->version);
4d00bda2
NP
1585 return 0;
1586 }
b8a2486f 1587 if (!strcmp(k, "pack.threads")) {
8868b1eb 1588 nr_threads = git_config_int(k, v, ctx->kvi);
b8a2486f 1589 if (nr_threads < 0)
f350df42 1590 die(_("invalid number of threads specified (%d)"),
b8a2486f 1591 nr_threads);
2094c5e5 1592 if (!HAVE_THREADS && nr_threads != 1) {
f350df42 1593 warning(_("no threads support, ignoring %s"), k);
2094c5e5
NTND
1594 nr_threads = 1;
1595 }
b8a2486f
NTND
1596 return 0;
1597 }
e37d0b87
TB
1598 if (!strcmp(k, "pack.writereverseindex")) {
1599 if (git_config_bool(k, v))
1600 opts->flags |= WRITE_REV;
1601 else
1602 opts->flags &= ~WRITE_REV;
1603 }
a4e7e317 1604 return git_default_config(k, v, ctx, cb);
4d00bda2
NP
1605}
1606
3c9fc074
JH
1607static int cmp_uint32(const void *a_, const void *b_)
1608{
1609 uint32_t a = *((uint32_t *)a_);
1610 uint32_t b = *((uint32_t *)b_);
1611
1612 return (a < b) ? -1 : (a != b);
1613}
1614
1615static void read_v2_anomalous_offsets(struct packed_git *p,
1616 struct pack_idx_option *opts)
1617{
1618 const uint32_t *idx1, *idx2;
1619 uint32_t i;
1620
1621 /* The address of the 4-byte offset table */
629dffc4 1622 idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
f86f7695 1623 + (size_t)p->num_objects /* CRC32 table */
3c9fc074
JH
1624 );
1625
1626 /* The address of the 8-byte offset table */
1627 idx2 = idx1 + p->num_objects;
1628
1629 for (i = 0; i < p->num_objects; i++) {
1630 uint32_t off = ntohl(idx1[i]);
1631 if (!(off & 0x80000000))
1632 continue;
1633 off = off & 0x7fffffff;
47fe3f6e 1634 check_pack_index_ptr(p, &idx2[off * 2]);
3c9fc074
JH
1635 if (idx2[off * 2])
1636 continue;
1637 /*
1638 * The real offset is ntohl(idx2[off * 2]) in high 4
1639 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1640 * octets. But idx2[off * 2] is Zero!!!
1641 */
1642 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1643 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1644 }
1645
1b5294de 1646 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
3c9fc074
JH
1647}
1648
e337a04d
JH
1649static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1650{
1651 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1652
1653 if (!p)
c2b97ecf 1654 die(_("Cannot open existing pack file '%s'"), pack_name);
e337a04d 1655 if (open_pack_index(p))
c2b97ecf 1656 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
e337a04d
JH
1657
1658 /* Read the attributes from the existing idx file */
1659 opts->version = p->index_version;
1660
3c9fc074
JH
1661 if (opts->version == 2)
1662 read_v2_anomalous_offsets(p, opts);
1663
e337a04d
JH
1664 /*
1665 * Get rid of the idx file as we do not need it anymore.
1666 * NEEDSWORK: extract this bit from free_pack_by_name() in
e5afd444 1667 * object-file.c, perhaps? It shouldn't matter very much as we
e337a04d
JH
1668 * know we haven't installed this pack (hence we never have
1669 * read anything from it).
1670 */
1671 close_pack_index(p);
1672 free(p);
1673}
1674
38a45561
JH
1675static void show_pack_info(int stat_only)
1676{
c6458e60 1677 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
d1a0ed18
JH
1678 unsigned long *chain_histogram = NULL;
1679
1680 if (deepest_delta)
ca56dadb 1681 CALLOC_ARRAY(chain_histogram, deepest_delta);
d1a0ed18 1682
38a45561
JH
1683 for (i = 0; i < nr_objects; i++) {
1684 struct object_entry *obj = &objects[i];
1685
d1a0ed18 1686 if (is_delta_type(obj->type))
41730576 1687 chain_histogram[obj_stat[i].delta_depth - 1]++;
38a45561
JH
1688 if (stat_only)
1689 continue;
ca473cef 1690 printf("%s %-6s %"PRIuMAX" %"PRIuMAX" %"PRIuMAX,
e6a492b7 1691 oid_to_hex(&obj->idx.oid),
ca473cef
TB
1692 type_name(obj->real_type), (uintmax_t)obj->size,
1693 (uintmax_t)(obj[1].idx.offset - obj->idx.offset),
38a45561
JH
1694 (uintmax_t)obj->idx.offset);
1695 if (is_delta_type(obj->type)) {
41730576 1696 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
e6a492b7 1697 printf(" %u %s", obj_stat[i].delta_depth,
1698 oid_to_hex(&bobj->idx.oid));
38a45561
JH
1699 }
1700 putchar('\n');
1701 }
d1a0ed18
JH
1702
1703 if (baseobjects)
c2b97ecf
NTND
1704 printf_ln(Q_("non delta: %d object",
1705 "non delta: %d objects",
1706 baseobjects),
1707 baseobjects);
d1a0ed18
JH
1708 for (i = 0; i < deepest_delta; i++) {
1709 if (!chain_histogram[i])
1710 continue;
c2b97ecf
NTND
1711 printf_ln(Q_("chain length = %d: %lu object",
1712 "chain length = %d: %lu objects",
1713 chain_histogram[i]),
1714 i + 1,
1715 chain_histogram[i]);
d1a0ed18 1716 }
f2bcc69e 1717 free(chain_histogram);
38a45561
JH
1718}
1719
3bb72562 1720int cmd_index_pack(int argc, const char **argv, const char *prefix)
9cf6d335 1721{
e37d0b87 1722 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, rev_index;
39539495 1723 const char *curr_index;
e37d0b87
TB
1724 const char *curr_rev_index = NULL;
1725 const char *index_name = NULL, *pack_name = NULL, *rev_index_name = NULL;
8e29c7c3 1726 const char *keep_msg = NULL;
88e2f9ed 1727 const char *promisor_msg = NULL;
8e29c7c3 1728 struct strbuf index_name_buf = STRBUF_INIT;
e37d0b87 1729 struct strbuf rev_index_name_buf = STRBUF_INIT;
aa7e44bf 1730 struct pack_idx_entry **idx_objects;
ebcfb379 1731 struct pack_idx_option opts;
454253f0 1732 unsigned char pack_hash[GIT_MAX_RAWSZ];
c6807a40 1733 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
83558686 1734 int report_end_of_input = 0;
586740aa 1735 int hash_algo = 0;
9cf6d335 1736
8b4c0103 1737 /*
8a30a1ef
JT
1738 * index-pack never needs to fetch missing objects except when
1739 * REF_DELTA bases are missing (which are explicitly handled). It only
1740 * accesses the repo to do hash collision checks and to check which
1741 * REF_DELTA bases need to be fetched.
8b4c0103
JT
1742 */
1743 fetch_if_missing = 0;
1744
99caeed0
JN
1745 if (argc == 2 && !strcmp(argv[1], "-h"))
1746 usage(index_pack_usage);
1747
d24eda4e 1748 disable_replace_refs();
22410549 1749 fsck_options.walk = mark_link;
6e2a09d2 1750
ebcfb379 1751 reset_pack_idx_option(&opts);
a8dd7e05 1752 opts.flags |= WRITE_REV;
ebcfb379 1753 git_config(git_index_pack_config, &opts);
3f8099fc 1754 if (prefix && chdir(prefix))
c2b97ecf 1755 die(_("Cannot come back to cwd"));
4d00bda2 1756
9f7f10a2
TB
1757 if (git_env_bool(GIT_TEST_NO_WRITE_REV_INDEX, 0))
1758 rev_index = 0;
e8c58f89
TB
1759 else
1760 rev_index = !!(opts.flags & (WRITE_REV_VERIFY | WRITE_REV));
e37d0b87 1761
9cf6d335 1762 for (i = 1; i < argc; i++) {
3bb72562 1763 const char *arg = argv[i];
9cf6d335
SV
1764
1765 if (*arg == '-') {
e42797f5
NP
1766 if (!strcmp(arg, "--stdin")) {
1767 from_stdin = 1;
636171cb
NP
1768 } else if (!strcmp(arg, "--fix-thin")) {
1769 fix_thin_pack = 1;
72885a6d 1770 } else if (skip_to_optional_arg(arg, "--strict", &arg)) {
5d477a33
JS
1771 strict = 1;
1772 do_fsck_object = 1;
1773 fsck_set_msg_types(&fsck_options, arg);
c6807a40
NTND
1774 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1775 strict = 1;
1776 check_self_contained_and_connected = 1;
0f8edf73 1777 } else if (skip_to_optional_arg(arg, "--fsck-objects", &arg)) {
ffb2c0fe 1778 do_fsck_object = 1;
0f8edf73 1779 fsck_set_msg_types(&fsck_options, arg);
e337a04d
JH
1780 } else if (!strcmp(arg, "--verify")) {
1781 verify = 1;
38a45561
JH
1782 } else if (!strcmp(arg, "--verify-stat")) {
1783 verify = 1;
3aba2fdd 1784 show_stat = 1;
38a45561
JH
1785 } else if (!strcmp(arg, "--verify-stat-only")) {
1786 verify = 1;
3aba2fdd 1787 show_stat = 1;
38a45561 1788 stat_only = 1;
72885a6d
CC
1789 } else if (skip_to_optional_arg(arg, "--keep", &keep_msg)) {
1790 ; /* nothing to do */
f3d618d2
JH
1791 } else if (skip_to_optional_arg(arg, "--promisor", &promisor_msg)) {
1792 ; /* already parsed */
59556548 1793 } else if (starts_with(arg, "--threads=")) {
b8a2486f
NTND
1794 char *end;
1795 nr_threads = strtoul(arg+10, &end, 0);
1796 if (!arg[10] || *end || nr_threads < 0)
1797 usage(index_pack_usage);
2094c5e5
NTND
1798 if (!HAVE_THREADS && nr_threads != 1) {
1799 warning(_("no threads support, ignoring %s"), arg);
1800 nr_threads = 1;
1801 }
59556548 1802 } else if (starts_with(arg, "--pack_header=")) {
bed006fb
NP
1803 struct pack_header *hdr;
1804 char *c;
1805
1806 hdr = (struct pack_header *)input_buffer;
1807 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1808 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1809 if (*c != ',')
c2b97ecf 1810 die(_("bad %s"), arg);
bed006fb
NP
1811 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1812 if (*c)
c2b97ecf 1813 die(_("bad %s"), arg);
bed006fb 1814 input_len = sizeof(*hdr);
3c9af366
NP
1815 } else if (!strcmp(arg, "-v")) {
1816 verbose = 1;
f46c46e4
ÆAB
1817 } else if (!strcmp(arg, "--progress-title")) {
1818 if (progress_title || (i+1) >= argc)
1819 usage(index_pack_usage);
1820 progress_title = argv[++i];
e376f17f
JK
1821 } else if (!strcmp(arg, "--show-resolving-progress")) {
1822 show_resolving_progress = 1;
83558686
JK
1823 } else if (!strcmp(arg, "--report-end-of-input")) {
1824 report_end_of_input = 1;
e42797f5 1825 } else if (!strcmp(arg, "-o")) {
9cf6d335
SV
1826 if (index_name || (i+1) >= argc)
1827 usage(index_pack_usage);
1828 index_name = argv[++i];
59556548 1829 } else if (starts_with(arg, "--index-version=")) {
4ba7d711 1830 char *c;
ebcfb379
JH
1831 opts.version = strtoul(arg + 16, &c, 10);
1832 if (opts.version > 2)
c2b97ecf 1833 die(_("bad %s"), arg);
4ba7d711 1834 if (*c == ',')
ebcfb379
JH
1835 opts.off32_limit = strtoul(c+1, &c, 0);
1836 if (*c || opts.off32_limit & 0x80000000)
c2b97ecf 1837 die(_("bad %s"), arg);
411481be
JK
1838 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1839 max_input_size = strtoumax(arg, NULL, 10);
586740aa 1840 } else if (skip_prefix(arg, "--object-format=", &arg)) {
1841 hash_algo = hash_algo_by_name(arg);
1842 if (hash_algo == GIT_HASH_UNKNOWN)
1843 die(_("unknown hash algorithm '%s'"), arg);
1844 repo_set_hash_algo(the_repository, hash_algo);
e37d0b87
TB
1845 } else if (!strcmp(arg, "--rev-index")) {
1846 rev_index = 1;
1847 } else if (!strcmp(arg, "--no-rev-index")) {
1848 rev_index = 0;
9cf6d335
SV
1849 } else
1850 usage(index_pack_usage);
1851 continue;
1852 }
1853
1854 if (pack_name)
1855 usage(index_pack_usage);
1856 pack_name = arg;
1857 }
1858
e42797f5 1859 if (!pack_name && !from_stdin)
9cf6d335 1860 usage(index_pack_usage);
636171cb 1861 if (fix_thin_pack && !from_stdin)
6fa00ee8 1862 die(_("the option '%s' requires '%s'"), "--fix-thin", "--stdin");
7176a314
JK
1863 if (from_stdin && !startup_info->have_repository)
1864 die(_("--stdin requires a git repository"));
586740aa 1865 if (from_stdin && hash_algo)
12909b6b 1866 die(_("options '%s' and '%s' cannot be used together"), "--object-format", "--stdin");
bfee614a 1867 if (!index_name && pack_name)
84d54494 1868 index_name = derive_filename(pack_name, "pack", "idx", &index_name_buf);
bfee614a 1869
e37d0b87
TB
1870 opts.flags &= ~(WRITE_REV | WRITE_REV_VERIFY);
1871 if (rev_index) {
1872 opts.flags |= verify ? WRITE_REV_VERIFY : WRITE_REV;
1873 if (index_name)
1874 rev_index_name = derive_filename(index_name,
1875 "idx", "rev",
1876 &rev_index_name_buf);
1877 }
1878
e337a04d
JH
1879 if (verify) {
1880 if (!index_name)
c2b97ecf 1881 die(_("--verify with no packfile name given"));
e337a04d 1882 read_idx_option(&opts, index_name);
68be2fea 1883 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
e337a04d 1884 }
68be2fea
JH
1885 if (strict)
1886 opts.flags |= WRITE_IDX_STRICT;
9cf6d335 1887
2094c5e5 1888 if (HAVE_THREADS && !nr_threads) {
b8a2486f 1889 nr_threads = online_cpus();
fbff95b6
JK
1890 /*
1891 * Experiments show that going above 20 threads doesn't help,
1892 * no matter how many cores you have. Below that, we tend to
1893 * max at half the number of online_cpus(), presumably because
1894 * half of those are hyperthreads rather than full cores. We'll
1895 * never reduce the level below "3", though, to match a
1896 * historical value that nobody complained about.
1897 */
1898 if (nr_threads < 4)
1899 ; /* too few cores to consider capping */
1900 else if (nr_threads < 6)
1901 nr_threads = 3; /* historic cap */
1902 else if (nr_threads < 40)
1903 nr_threads /= 2;
1904 else
1905 nr_threads = 20; /* hard cap */
b8a2486f 1906 }
b8a2486f 1907
e42797f5 1908 curr_pack = open_pack_file(pack_name);
9cf6d335 1909 parse_pack_header();
ca56dadb 1910 CALLOC_ARRAY(objects, st_add(nr_objects, 1));
41730576 1911 if (show_stat)
ca56dadb
RS
1912 CALLOC_ARRAY(obj_stat, st_add(nr_objects, 1));
1913 CALLOC_ARRAY(ofs_deltas, nr_objects);
454253f0 1914 parse_pack_objects(pack_hash);
83558686
JK
1915 if (report_end_of_input)
1916 write_in_full(2, "\0", 1);
5272f755 1917 resolve_deltas();
454253f0 1918 conclude_pack(fix_thin_pack, curr_pack, pack_hash);
c6458e60
NTND
1919 free(ofs_deltas);
1920 free(ref_deltas);
0153be05 1921 if (strict)
c6807a40 1922 foreign_nr = check_objects();
aa7e44bf 1923
3aba2fdd 1924 if (show_stat)
38a45561
JH
1925 show_pack_info(stat_only);
1926
b32fa95f 1927 ALLOC_ARRAY(idx_objects, nr_objects);
aa7e44bf
GB
1928 for (i = 0; i < nr_objects; i++)
1929 idx_objects[i] = &objects[i].idx;
454253f0 1930 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_hash);
e37d0b87
TB
1931 if (rev_index)
1932 curr_rev_index = write_rev_file(rev_index_name, idx_objects,
1933 nr_objects, pack_hash,
1934 opts.flags);
aa7e44bf
GB
1935 free(idx_objects);
1936
e337a04d
JH
1937 if (!verify)
1938 final(pack_name, curr_pack,
1939 index_name, curr_index,
e37d0b87 1940 rev_index_name, curr_rev_index,
88e2f9ed 1941 keep_msg, promisor_msg,
454253f0 1942 pack_hash);
e337a04d
JH
1943 else
1944 close(input_fd);
73c3f0f7 1945
462f5cae
ÆAB
1946 if (do_fsck_object && fsck_finish(&fsck_options))
1947 die(_("fsck error in pack objects"));
73c3f0f7 1948
f2bcc69e 1949 free(opts.anomaly);
9cf6d335 1950 free(objects);
592ce208 1951 strbuf_release(&index_name_buf);
e37d0b87 1952 strbuf_release(&rev_index_name_buf);
afe8a907 1953 if (!pack_name)
3bb72562 1954 free((void *) curr_pack);
afe8a907 1955 if (!index_name)
3bb72562 1956 free((void *) curr_index);
afe8a907 1957 if (!rev_index_name)
e37d0b87 1958 free((void *) curr_rev_index);
9cf6d335 1959
c6807a40
NTND
1960 /*
1961 * Let the caller know this pack is not self contained
1962 */
1963 if (check_self_contained_and_connected && foreign_nr)
1964 return 1;
1965
9cf6d335
SV
1966 return 0;
1967}