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