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