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