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