Merge branch 'hn/reftable-coverity-fixes'
[git/debian.git] / builtin / index-pack.c
blob3c2e6aee3cc67be5df9bc1b4b62f5cd8a5c26b86
1 #include "builtin.h"
2 #include "config.h"
3 #include "delta.h"
4 #include "pack.h"
5 #include "csum-file.h"
6 #include "blob.h"
7 #include "commit.h"
8 #include "tag.h"
9 #include "tree.h"
10 #include "progress.h"
11 #include "fsck.h"
12 #include "exec-cmd.h"
13 #include "streaming.h"
14 #include "thread-utils.h"
15 #include "packfile.h"
16 #include "object-store.h"
17 #include "promisor-remote.h"
19 static const char index_pack_usage[] =
20 "git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--[no-]rev-index] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
22 struct object_entry {
23 struct pack_idx_entry idx;
24 unsigned long size;
25 unsigned char hdr_size;
26 signed char type;
27 signed char real_type;
30 struct object_stat {
31 unsigned delta_depth;
32 int base_object_no;
35 struct base_data {
36 /* Initialized by make_base(). */
37 struct base_data *base;
38 struct object_entry *obj;
39 int ref_first, ref_last;
40 int ofs_first, ofs_last;
42 * Threads should increment retain_data if they are about to call
43 * patch_delta() using this struct's data as a base, and decrement this
44 * when they are done. While retain_data is nonzero, this struct's data
45 * will not be freed even if the delta base cache limit is exceeded.
47 int retain_data;
49 * The number of direct children that have not been fully processed
50 * (entered work_head, entered done_head, left done_head). When this
51 * number reaches zero, this struct base_data can be freed.
53 int children_remaining;
55 /* Not initialized by make_base(). */
56 struct list_head list;
57 void *data;
58 unsigned long size;
62 * Stack of struct base_data that have unprocessed children.
63 * threaded_second_pass() uses this as a source of work (the other being the
64 * objects array).
66 * Guarded by work_mutex.
68 static LIST_HEAD(work_head);
71 * Stack of struct base_data that have children, all of whom have been
72 * processed or are being processed, and at least one child is being processed.
73 * These struct base_data must be kept around until the last child is
74 * processed.
76 * Guarded by work_mutex.
78 static LIST_HEAD(done_head);
81 * All threads share one delta base cache.
83 * base_cache_used is guarded by work_mutex, and base_cache_limit is read-only
84 * in a thread.
86 static size_t base_cache_used;
87 static size_t base_cache_limit;
89 struct thread_local {
90 pthread_t thread;
91 int pack_fd;
94 /* Remember to update object flag allocation in object.h */
95 #define FLAG_LINK (1u<<20)
96 #define FLAG_CHECKED (1u<<21)
98 struct ofs_delta_entry {
99 off_t offset;
100 int obj_no;
103 struct ref_delta_entry {
104 struct object_id oid;
105 int obj_no;
108 static struct object_entry *objects;
109 static struct object_stat *obj_stat;
110 static struct ofs_delta_entry *ofs_deltas;
111 static struct ref_delta_entry *ref_deltas;
112 static struct thread_local nothread_data;
113 static int nr_objects;
114 static int nr_ofs_deltas;
115 static int nr_ref_deltas;
116 static int ref_deltas_alloc;
117 static int nr_resolved_deltas;
118 static int nr_threads;
120 static int from_stdin;
121 static int strict;
122 static int do_fsck_object;
123 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
124 static int verbose;
125 static const char *progress_title;
126 static int show_resolving_progress;
127 static int show_stat;
128 static int check_self_contained_and_connected;
130 static struct progress *progress;
132 /* We always read in 4kB chunks. */
133 static unsigned char input_buffer[4096];
134 static unsigned int input_offset, input_len;
135 static off_t consumed_bytes;
136 static off_t max_input_size;
137 static unsigned deepest_delta;
138 static git_hash_ctx input_ctx;
139 static uint32_t input_crc32;
140 static int input_fd, output_fd;
141 static const char *curr_pack;
143 static struct thread_local *thread_data;
144 static int nr_dispatched;
145 static int threads_active;
147 static pthread_mutex_t read_mutex;
148 #define read_lock() lock_mutex(&read_mutex)
149 #define read_unlock() unlock_mutex(&read_mutex)
151 static pthread_mutex_t counter_mutex;
152 #define counter_lock() lock_mutex(&counter_mutex)
153 #define counter_unlock() unlock_mutex(&counter_mutex)
155 static pthread_mutex_t work_mutex;
156 #define work_lock() lock_mutex(&work_mutex)
157 #define work_unlock() unlock_mutex(&work_mutex)
159 static pthread_mutex_t deepest_delta_mutex;
160 #define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
161 #define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
163 static pthread_key_t key;
165 static inline void lock_mutex(pthread_mutex_t *mutex)
167 if (threads_active)
168 pthread_mutex_lock(mutex);
171 static inline void unlock_mutex(pthread_mutex_t *mutex)
173 if (threads_active)
174 pthread_mutex_unlock(mutex);
178 * Mutex and conditional variable can't be statically-initialized on Windows.
180 static void init_thread(void)
182 int i;
183 init_recursive_mutex(&read_mutex);
184 pthread_mutex_init(&counter_mutex, NULL);
185 pthread_mutex_init(&work_mutex, NULL);
186 if (show_stat)
187 pthread_mutex_init(&deepest_delta_mutex, NULL);
188 pthread_key_create(&key, NULL);
189 CALLOC_ARRAY(thread_data, nr_threads);
190 for (i = 0; i < nr_threads; i++) {
191 thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
194 threads_active = 1;
197 static void cleanup_thread(void)
199 int i;
200 if (!threads_active)
201 return;
202 threads_active = 0;
203 pthread_mutex_destroy(&read_mutex);
204 pthread_mutex_destroy(&counter_mutex);
205 pthread_mutex_destroy(&work_mutex);
206 if (show_stat)
207 pthread_mutex_destroy(&deepest_delta_mutex);
208 for (i = 0; i < nr_threads; i++)
209 close(thread_data[i].pack_fd);
210 pthread_key_delete(key);
211 free(thread_data);
214 static int mark_link(struct object *obj, enum object_type type,
215 void *data, struct fsck_options *options)
217 if (!obj)
218 return -1;
220 if (type != OBJ_ANY && obj->type != type)
221 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
223 obj->flags |= FLAG_LINK;
224 return 0;
227 /* The content of each linked object must have been checked
228 or it must be already present in the object database */
229 static unsigned check_object(struct object *obj)
231 if (!obj)
232 return 0;
234 if (!(obj->flags & FLAG_LINK))
235 return 0;
237 if (!(obj->flags & FLAG_CHECKED)) {
238 unsigned long size;
239 int type = oid_object_info(the_repository, &obj->oid, &size);
240 if (type <= 0)
241 die(_("did not receive expected object %s"),
242 oid_to_hex(&obj->oid));
243 if (type != obj->type)
244 die(_("object %s: expected type %s, found %s"),
245 oid_to_hex(&obj->oid),
246 type_name(obj->type), type_name(type));
247 obj->flags |= FLAG_CHECKED;
248 return 1;
251 return 0;
254 static unsigned check_objects(void)
256 unsigned i, max, foreign_nr = 0;
258 max = get_max_object_index();
260 if (verbose)
261 progress = start_delayed_progress(_("Checking objects"), max);
263 for (i = 0; i < max; i++) {
264 foreign_nr += check_object(get_indexed_object(i));
265 display_progress(progress, i + 1);
268 stop_progress(&progress);
269 return foreign_nr;
273 /* Discard current buffer used content. */
274 static void flush(void)
276 if (input_offset) {
277 if (output_fd >= 0)
278 write_or_die(output_fd, input_buffer, input_offset);
279 the_hash_algo->update_fn(&input_ctx, input_buffer, input_offset);
280 memmove(input_buffer, input_buffer + input_offset, input_len);
281 input_offset = 0;
286 * Make sure at least "min" bytes are available in the buffer, and
287 * return the pointer to the buffer.
289 static void *fill(int min)
291 if (min <= input_len)
292 return input_buffer + input_offset;
293 if (min > sizeof(input_buffer))
294 die(Q_("cannot fill %d byte",
295 "cannot fill %d bytes",
296 min),
297 min);
298 flush();
299 do {
300 ssize_t ret = xread(input_fd, input_buffer + input_len,
301 sizeof(input_buffer) - input_len);
302 if (ret <= 0) {
303 if (!ret)
304 die(_("early EOF"));
305 die_errno(_("read error on input"));
307 input_len += ret;
308 if (from_stdin)
309 display_throughput(progress, consumed_bytes + input_len);
310 } while (input_len < min);
311 return input_buffer;
314 static void use(int bytes)
316 if (bytes > input_len)
317 die(_("used more bytes than were available"));
318 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
319 input_len -= bytes;
320 input_offset += bytes;
322 /* make sure off_t is sufficiently large not to wrap */
323 if (signed_add_overflows(consumed_bytes, bytes))
324 die(_("pack too large for current definition of off_t"));
325 consumed_bytes += bytes;
326 if (max_input_size && consumed_bytes > max_input_size)
327 die(_("pack exceeds maximum allowed size"));
330 static const char *open_pack_file(const char *pack_name)
332 if (from_stdin) {
333 input_fd = 0;
334 if (!pack_name) {
335 struct strbuf tmp_file = STRBUF_INIT;
336 output_fd = odb_mkstemp(&tmp_file,
337 "pack/tmp_pack_XXXXXX");
338 pack_name = strbuf_detach(&tmp_file, NULL);
339 } else {
340 output_fd = xopen(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
342 nothread_data.pack_fd = output_fd;
343 } else {
344 input_fd = xopen(pack_name, O_RDONLY);
345 output_fd = -1;
346 nothread_data.pack_fd = input_fd;
348 the_hash_algo->init_fn(&input_ctx);
349 return pack_name;
352 static void parse_pack_header(void)
354 struct pack_header *hdr = fill(sizeof(struct pack_header));
356 /* Header consistency check */
357 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
358 die(_("pack signature mismatch"));
359 if (!pack_version_ok(hdr->hdr_version))
360 die(_("pack version %"PRIu32" unsupported"),
361 ntohl(hdr->hdr_version));
363 nr_objects = ntohl(hdr->hdr_entries);
364 use(sizeof(struct pack_header));
367 __attribute__((format (printf, 2, 3)))
368 static NORETURN void bad_object(off_t offset, const char *format, ...)
370 va_list params;
371 char buf[1024];
373 va_start(params, format);
374 vsnprintf(buf, sizeof(buf), format, params);
375 va_end(params);
376 die(_("pack has bad object at offset %"PRIuMAX": %s"),
377 (uintmax_t)offset, buf);
380 static inline struct thread_local *get_thread_data(void)
382 if (HAVE_THREADS) {
383 if (threads_active)
384 return pthread_getspecific(key);
385 assert(!threads_active &&
386 "This should only be reached when all threads are gone");
388 return &nothread_data;
391 static void set_thread_data(struct thread_local *data)
393 if (threads_active)
394 pthread_setspecific(key, data);
397 static void free_base_data(struct base_data *c)
399 if (c->data) {
400 FREE_AND_NULL(c->data);
401 base_cache_used -= c->size;
405 static void prune_base_data(struct base_data *retain)
407 struct list_head *pos;
409 if (base_cache_used <= base_cache_limit)
410 return;
412 list_for_each_prev(pos, &done_head) {
413 struct base_data *b = list_entry(pos, struct base_data, list);
414 if (b->retain_data || b == retain)
415 continue;
416 if (b->data) {
417 free_base_data(b);
418 if (base_cache_used <= base_cache_limit)
419 return;
423 list_for_each_prev(pos, &work_head) {
424 struct base_data *b = list_entry(pos, struct base_data, list);
425 if (b->retain_data || b == retain)
426 continue;
427 if (b->data) {
428 free_base_data(b);
429 if (base_cache_used <= base_cache_limit)
430 return;
435 static int is_delta_type(enum object_type type)
437 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
440 static void *unpack_entry_data(off_t offset, unsigned long size,
441 enum object_type type, struct object_id *oid)
443 static char fixed_buf[8192];
444 int status;
445 git_zstream stream;
446 void *buf;
447 git_hash_ctx c;
448 char hdr[32];
449 int hdrlen;
451 if (!is_delta_type(type)) {
452 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX,
453 type_name(type),(uintmax_t)size) + 1;
454 the_hash_algo->init_fn(&c);
455 the_hash_algo->update_fn(&c, hdr, hdrlen);
456 } else
457 oid = NULL;
458 if (type == OBJ_BLOB && size > big_file_threshold)
459 buf = fixed_buf;
460 else
461 buf = xmallocz(size);
463 memset(&stream, 0, sizeof(stream));
464 git_inflate_init(&stream);
465 stream.next_out = buf;
466 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
468 do {
469 unsigned char *last_out = stream.next_out;
470 stream.next_in = fill(1);
471 stream.avail_in = input_len;
472 status = git_inflate(&stream, 0);
473 use(input_len - stream.avail_in);
474 if (oid)
475 the_hash_algo->update_fn(&c, last_out, stream.next_out - last_out);
476 if (buf == fixed_buf) {
477 stream.next_out = buf;
478 stream.avail_out = sizeof(fixed_buf);
480 } while (status == Z_OK);
481 if (stream.total_out != size || status != Z_STREAM_END)
482 bad_object(offset, _("inflate returned %d"), status);
483 git_inflate_end(&stream);
484 if (oid)
485 the_hash_algo->final_oid_fn(oid, &c);
486 return buf == fixed_buf ? NULL : buf;
489 static void *unpack_raw_entry(struct object_entry *obj,
490 off_t *ofs_offset,
491 struct object_id *ref_oid,
492 struct object_id *oid)
494 unsigned char *p;
495 unsigned long size, c;
496 off_t base_offset;
497 unsigned shift;
498 void *data;
500 obj->idx.offset = consumed_bytes;
501 input_crc32 = crc32(0, NULL, 0);
503 p = fill(1);
504 c = *p;
505 use(1);
506 obj->type = (c >> 4) & 7;
507 size = (c & 15);
508 shift = 4;
509 while (c & 0x80) {
510 p = fill(1);
511 c = *p;
512 use(1);
513 size += (c & 0x7f) << shift;
514 shift += 7;
516 obj->size = size;
518 switch (obj->type) {
519 case OBJ_REF_DELTA:
520 oidread(ref_oid, fill(the_hash_algo->rawsz));
521 use(the_hash_algo->rawsz);
522 break;
523 case OBJ_OFS_DELTA:
524 p = fill(1);
525 c = *p;
526 use(1);
527 base_offset = c & 127;
528 while (c & 128) {
529 base_offset += 1;
530 if (!base_offset || MSB(base_offset, 7))
531 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
532 p = fill(1);
533 c = *p;
534 use(1);
535 base_offset = (base_offset << 7) + (c & 127);
537 *ofs_offset = obj->idx.offset - base_offset;
538 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
539 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
540 break;
541 case OBJ_COMMIT:
542 case OBJ_TREE:
543 case OBJ_BLOB:
544 case OBJ_TAG:
545 break;
546 default:
547 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
549 obj->hdr_size = consumed_bytes - obj->idx.offset;
551 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, oid);
552 obj->idx.crc32 = input_crc32;
553 return data;
556 static void *unpack_data(struct object_entry *obj,
557 int (*consume)(const unsigned char *, unsigned long, void *),
558 void *cb_data)
560 off_t from = obj[0].idx.offset + obj[0].hdr_size;
561 off_t len = obj[1].idx.offset - from;
562 unsigned char *data, *inbuf;
563 git_zstream stream;
564 int status;
566 data = xmallocz(consume ? 64*1024 : obj->size);
567 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
569 memset(&stream, 0, sizeof(stream));
570 git_inflate_init(&stream);
571 stream.next_out = data;
572 stream.avail_out = consume ? 64*1024 : obj->size;
574 do {
575 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
576 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
577 if (n < 0)
578 die_errno(_("cannot pread pack file"));
579 if (!n)
580 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
581 "premature end of pack file, %"PRIuMAX" bytes missing",
582 (unsigned int)len),
583 (uintmax_t)len);
584 from += n;
585 len -= n;
586 stream.next_in = inbuf;
587 stream.avail_in = n;
588 if (!consume)
589 status = git_inflate(&stream, 0);
590 else {
591 do {
592 status = git_inflate(&stream, 0);
593 if (consume(data, stream.next_out - data, cb_data)) {
594 free(inbuf);
595 free(data);
596 return NULL;
598 stream.next_out = data;
599 stream.avail_out = 64*1024;
600 } while (status == Z_OK && stream.avail_in);
602 } while (len && status == Z_OK && !stream.avail_in);
604 /* This has been inflated OK when first encountered, so... */
605 if (status != Z_STREAM_END || stream.total_out != obj->size)
606 die(_("serious inflate inconsistency"));
608 git_inflate_end(&stream);
609 free(inbuf);
610 if (consume) {
611 FREE_AND_NULL(data);
613 return data;
616 static void *get_data_from_pack(struct object_entry *obj)
618 return unpack_data(obj, NULL, NULL);
621 static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
622 enum object_type type1,
623 enum object_type type2)
625 int cmp = type1 - type2;
626 if (cmp)
627 return cmp;
628 return offset1 < offset2 ? -1 :
629 offset1 > offset2 ? 1 :
633 static int find_ofs_delta(const off_t offset)
635 int first = 0, last = nr_ofs_deltas;
637 while (first < last) {
638 int next = first + (last - first) / 2;
639 struct ofs_delta_entry *delta = &ofs_deltas[next];
640 int cmp;
642 cmp = compare_ofs_delta_bases(offset, delta->offset,
643 OBJ_OFS_DELTA,
644 objects[delta->obj_no].type);
645 if (!cmp)
646 return next;
647 if (cmp < 0) {
648 last = next;
649 continue;
651 first = next+1;
653 return -first-1;
656 static void find_ofs_delta_children(off_t offset,
657 int *first_index, int *last_index)
659 int first = find_ofs_delta(offset);
660 int last = first;
661 int end = nr_ofs_deltas - 1;
663 if (first < 0) {
664 *first_index = 0;
665 *last_index = -1;
666 return;
668 while (first > 0 && ofs_deltas[first - 1].offset == offset)
669 --first;
670 while (last < end && ofs_deltas[last + 1].offset == offset)
671 ++last;
672 *first_index = first;
673 *last_index = last;
676 static int compare_ref_delta_bases(const struct object_id *oid1,
677 const struct object_id *oid2,
678 enum object_type type1,
679 enum object_type type2)
681 int cmp = type1 - type2;
682 if (cmp)
683 return cmp;
684 return oidcmp(oid1, oid2);
687 static int find_ref_delta(const struct object_id *oid)
689 int first = 0, last = nr_ref_deltas;
691 while (first < last) {
692 int next = first + (last - first) / 2;
693 struct ref_delta_entry *delta = &ref_deltas[next];
694 int cmp;
696 cmp = compare_ref_delta_bases(oid, &delta->oid,
697 OBJ_REF_DELTA,
698 objects[delta->obj_no].type);
699 if (!cmp)
700 return next;
701 if (cmp < 0) {
702 last = next;
703 continue;
705 first = next+1;
707 return -first-1;
710 static void find_ref_delta_children(const struct object_id *oid,
711 int *first_index, int *last_index)
713 int first = find_ref_delta(oid);
714 int last = first;
715 int end = nr_ref_deltas - 1;
717 if (first < 0) {
718 *first_index = 0;
719 *last_index = -1;
720 return;
722 while (first > 0 && oideq(&ref_deltas[first - 1].oid, oid))
723 --first;
724 while (last < end && oideq(&ref_deltas[last + 1].oid, oid))
725 ++last;
726 *first_index = first;
727 *last_index = last;
730 struct compare_data {
731 struct object_entry *entry;
732 struct git_istream *st;
733 unsigned char *buf;
734 unsigned long buf_size;
737 static int compare_objects(const unsigned char *buf, unsigned long size,
738 void *cb_data)
740 struct compare_data *data = cb_data;
742 if (data->buf_size < size) {
743 free(data->buf);
744 data->buf = xmalloc(size);
745 data->buf_size = size;
748 while (size) {
749 ssize_t len = read_istream(data->st, data->buf, size);
750 if (len == 0)
751 die(_("SHA1 COLLISION FOUND WITH %s !"),
752 oid_to_hex(&data->entry->idx.oid));
753 if (len < 0)
754 die(_("unable to read %s"),
755 oid_to_hex(&data->entry->idx.oid));
756 if (memcmp(buf, data->buf, len))
757 die(_("SHA1 COLLISION FOUND WITH %s !"),
758 oid_to_hex(&data->entry->idx.oid));
759 size -= len;
760 buf += len;
762 return 0;
765 static int check_collison(struct object_entry *entry)
767 struct compare_data data;
768 enum object_type type;
769 unsigned long size;
771 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
772 return -1;
774 memset(&data, 0, sizeof(data));
775 data.entry = entry;
776 data.st = open_istream(the_repository, &entry->idx.oid, &type, &size,
777 NULL);
778 if (!data.st)
779 return -1;
780 if (size != entry->size || type != entry->type)
781 die(_("SHA1 COLLISION FOUND WITH %s !"),
782 oid_to_hex(&entry->idx.oid));
783 unpack_data(entry, compare_objects, &data);
784 close_istream(data.st);
785 free(data.buf);
786 return 0;
789 static void sha1_object(const void *data, struct object_entry *obj_entry,
790 unsigned long size, enum object_type type,
791 const struct object_id *oid)
793 void *new_data = NULL;
794 int collision_test_needed = 0;
796 assert(data || obj_entry);
798 if (startup_info->have_repository) {
799 read_lock();
800 collision_test_needed =
801 has_object_file_with_flags(oid, OBJECT_INFO_QUICK);
802 read_unlock();
805 if (collision_test_needed && !data) {
806 read_lock();
807 if (!check_collison(obj_entry))
808 collision_test_needed = 0;
809 read_unlock();
811 if (collision_test_needed) {
812 void *has_data;
813 enum object_type has_type;
814 unsigned long has_size;
815 read_lock();
816 has_type = oid_object_info(the_repository, oid, &has_size);
817 if (has_type < 0)
818 die(_("cannot read existing object info %s"), oid_to_hex(oid));
819 if (has_type != type || has_size != size)
820 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
821 has_data = read_object_file(oid, &has_type, &has_size);
822 read_unlock();
823 if (!data)
824 data = new_data = get_data_from_pack(obj_entry);
825 if (!has_data)
826 die(_("cannot read existing object %s"), oid_to_hex(oid));
827 if (size != has_size || type != has_type ||
828 memcmp(data, has_data, size) != 0)
829 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
830 free(has_data);
833 if (strict || do_fsck_object) {
834 read_lock();
835 if (type == OBJ_BLOB) {
836 struct blob *blob = lookup_blob(the_repository, oid);
837 if (blob)
838 blob->object.flags |= FLAG_CHECKED;
839 else
840 die(_("invalid blob object %s"), oid_to_hex(oid));
841 if (do_fsck_object &&
842 fsck_object(&blob->object, (void *)data, size, &fsck_options))
843 die(_("fsck error in packed object"));
844 } else {
845 struct object *obj;
846 int eaten;
847 void *buf = (void *) data;
849 assert(data && "data can only be NULL for large _blobs_");
852 * we do not need to free the memory here, as the
853 * buf is deleted by the caller.
855 obj = parse_object_buffer(the_repository, oid, type,
856 size, buf,
857 &eaten);
858 if (!obj)
859 die(_("invalid %s"), type_name(type));
860 if (do_fsck_object &&
861 fsck_object(obj, buf, size, &fsck_options))
862 die(_("fsck error in packed object"));
863 if (strict && fsck_walk(obj, NULL, &fsck_options))
864 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
866 if (obj->type == OBJ_TREE) {
867 struct tree *item = (struct tree *) obj;
868 item->buffer = NULL;
869 obj->parsed = 0;
871 if (obj->type == OBJ_COMMIT) {
872 struct commit *commit = (struct commit *) obj;
873 if (detach_commit_buffer(commit, NULL) != data)
874 BUG("parse_object_buffer transmogrified our buffer");
876 obj->flags |= FLAG_CHECKED;
878 read_unlock();
881 free(new_data);
885 * Ensure that this node has been reconstructed and return its contents.
887 * In the typical and best case, this node would already be reconstructed
888 * (through the invocation to resolve_delta() in threaded_second_pass()) and it
889 * would not be pruned. However, if pruning of this node was necessary due to
890 * reaching delta_base_cache_limit, this function will find the closest
891 * ancestor with reconstructed data that has not been pruned (or if there is
892 * none, the ultimate base object), and reconstruct each node in the delta
893 * chain in order to generate the reconstructed data for this node.
895 static void *get_base_data(struct base_data *c)
897 if (!c->data) {
898 struct object_entry *obj = c->obj;
899 struct base_data **delta = NULL;
900 int delta_nr = 0, delta_alloc = 0;
902 while (is_delta_type(c->obj->type) && !c->data) {
903 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
904 delta[delta_nr++] = c;
905 c = c->base;
907 if (!delta_nr) {
908 c->data = get_data_from_pack(obj);
909 c->size = obj->size;
910 base_cache_used += c->size;
911 prune_base_data(c);
913 for (; delta_nr > 0; delta_nr--) {
914 void *base, *raw;
915 c = delta[delta_nr - 1];
916 obj = c->obj;
917 base = get_base_data(c->base);
918 raw = get_data_from_pack(obj);
919 c->data = patch_delta(
920 base, c->base->size,
921 raw, obj->size,
922 &c->size);
923 free(raw);
924 if (!c->data)
925 bad_object(obj->idx.offset, _("failed to apply delta"));
926 base_cache_used += c->size;
927 prune_base_data(c);
929 free(delta);
931 return c->data;
934 static struct base_data *make_base(struct object_entry *obj,
935 struct base_data *parent)
937 struct base_data *base = xcalloc(1, sizeof(struct base_data));
938 base->base = parent;
939 base->obj = obj;
940 find_ref_delta_children(&obj->idx.oid,
941 &base->ref_first, &base->ref_last);
942 find_ofs_delta_children(obj->idx.offset,
943 &base->ofs_first, &base->ofs_last);
944 base->children_remaining = base->ref_last - base->ref_first +
945 base->ofs_last - base->ofs_first + 2;
946 return base;
949 static struct base_data *resolve_delta(struct object_entry *delta_obj,
950 struct base_data *base)
952 void *delta_data, *result_data;
953 struct base_data *result;
954 unsigned long result_size;
956 if (show_stat) {
957 int i = delta_obj - objects;
958 int j = base->obj - objects;
959 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
960 deepest_delta_lock();
961 if (deepest_delta < obj_stat[i].delta_depth)
962 deepest_delta = obj_stat[i].delta_depth;
963 deepest_delta_unlock();
964 obj_stat[i].base_object_no = j;
966 delta_data = get_data_from_pack(delta_obj);
967 assert(base->data);
968 result_data = patch_delta(base->data, base->size,
969 delta_data, delta_obj->size, &result_size);
970 free(delta_data);
971 if (!result_data)
972 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
973 hash_object_file(the_hash_algo, result_data, result_size,
974 type_name(delta_obj->real_type), &delta_obj->idx.oid);
975 sha1_object(result_data, NULL, result_size, delta_obj->real_type,
976 &delta_obj->idx.oid);
978 result = make_base(delta_obj, base);
979 result->data = result_data;
980 result->size = result_size;
982 counter_lock();
983 nr_resolved_deltas++;
984 counter_unlock();
986 return result;
989 static int compare_ofs_delta_entry(const void *a, const void *b)
991 const struct ofs_delta_entry *delta_a = a;
992 const struct ofs_delta_entry *delta_b = b;
994 return delta_a->offset < delta_b->offset ? -1 :
995 delta_a->offset > delta_b->offset ? 1 :
999 static int compare_ref_delta_entry(const void *a, const void *b)
1001 const struct ref_delta_entry *delta_a = a;
1002 const struct ref_delta_entry *delta_b = b;
1004 return oidcmp(&delta_a->oid, &delta_b->oid);
1007 static void *threaded_second_pass(void *data)
1009 if (data)
1010 set_thread_data(data);
1011 for (;;) {
1012 struct base_data *parent = NULL;
1013 struct object_entry *child_obj;
1014 struct base_data *child;
1016 counter_lock();
1017 display_progress(progress, nr_resolved_deltas);
1018 counter_unlock();
1020 work_lock();
1021 if (list_empty(&work_head)) {
1023 * Take an object from the object array.
1025 while (nr_dispatched < nr_objects &&
1026 is_delta_type(objects[nr_dispatched].type))
1027 nr_dispatched++;
1028 if (nr_dispatched >= nr_objects) {
1029 work_unlock();
1030 break;
1032 child_obj = &objects[nr_dispatched++];
1033 } else {
1035 * Peek at the top of the stack, and take a child from
1036 * it.
1038 parent = list_first_entry(&work_head, struct base_data,
1039 list);
1041 if (parent->ref_first <= parent->ref_last) {
1042 int offset = ref_deltas[parent->ref_first++].obj_no;
1043 child_obj = objects + offset;
1044 if (child_obj->real_type != OBJ_REF_DELTA)
1045 die("REF_DELTA at offset %"PRIuMAX" already resolved (duplicate base %s?)",
1046 (uintmax_t) child_obj->idx.offset,
1047 oid_to_hex(&parent->obj->idx.oid));
1048 child_obj->real_type = parent->obj->real_type;
1049 } else {
1050 child_obj = objects +
1051 ofs_deltas[parent->ofs_first++].obj_no;
1052 assert(child_obj->real_type == OBJ_OFS_DELTA);
1053 child_obj->real_type = parent->obj->real_type;
1056 if (parent->ref_first > parent->ref_last &&
1057 parent->ofs_first > parent->ofs_last) {
1059 * This parent has run out of children, so move
1060 * it to done_head.
1062 list_del(&parent->list);
1063 list_add(&parent->list, &done_head);
1067 * Ensure that the parent has data, since we will need
1068 * it later.
1070 * NEEDSWORK: If parent data needs to be reloaded, this
1071 * prolongs the time that the current thread spends in
1072 * the mutex. A mitigating factor is that parent data
1073 * needs to be reloaded only if the delta base cache
1074 * limit is exceeded, so in the typical case, this does
1075 * not happen.
1077 get_base_data(parent);
1078 parent->retain_data++;
1080 work_unlock();
1082 if (parent) {
1083 child = resolve_delta(child_obj, parent);
1084 if (!child->children_remaining)
1085 FREE_AND_NULL(child->data);
1086 } else {
1087 child = make_base(child_obj, NULL);
1088 if (child->children_remaining) {
1090 * Since this child has its own delta children,
1091 * we will need this data in the future.
1092 * Inflate now so that future iterations will
1093 * have access to this object's data while
1094 * outside the work mutex.
1096 child->data = get_data_from_pack(child_obj);
1097 child->size = child_obj->size;
1101 work_lock();
1102 if (parent)
1103 parent->retain_data--;
1104 if (child->data) {
1106 * This child has its own children, so add it to
1107 * work_head.
1109 list_add(&child->list, &work_head);
1110 base_cache_used += child->size;
1111 prune_base_data(NULL);
1112 } else {
1114 * This child does not have its own children. It may be
1115 * the last descendant of its ancestors; free those
1116 * that we can.
1118 struct base_data *p = parent;
1120 while (p) {
1121 struct base_data *next_p;
1123 p->children_remaining--;
1124 if (p->children_remaining)
1125 break;
1127 next_p = p->base;
1128 free_base_data(p);
1129 list_del(&p->list);
1130 free(p);
1132 p = next_p;
1135 work_unlock();
1137 return NULL;
1141 * First pass:
1142 * - find locations of all objects;
1143 * - calculate SHA1 of all non-delta objects;
1144 * - remember base (SHA1 or offset) for all deltas.
1146 static void parse_pack_objects(unsigned char *hash)
1148 int i, nr_delays = 0;
1149 struct ofs_delta_entry *ofs_delta = ofs_deltas;
1150 struct object_id ref_delta_oid;
1151 struct stat st;
1153 if (verbose)
1154 progress = start_progress(
1155 progress_title ? progress_title :
1156 from_stdin ? _("Receiving objects") : _("Indexing objects"),
1157 nr_objects);
1158 for (i = 0; i < nr_objects; i++) {
1159 struct object_entry *obj = &objects[i];
1160 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
1161 &ref_delta_oid,
1162 &obj->idx.oid);
1163 obj->real_type = obj->type;
1164 if (obj->type == OBJ_OFS_DELTA) {
1165 nr_ofs_deltas++;
1166 ofs_delta->obj_no = i;
1167 ofs_delta++;
1168 } else if (obj->type == OBJ_REF_DELTA) {
1169 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
1170 oidcpy(&ref_deltas[nr_ref_deltas].oid, &ref_delta_oid);
1171 ref_deltas[nr_ref_deltas].obj_no = i;
1172 nr_ref_deltas++;
1173 } else if (!data) {
1174 /* large blobs, check later */
1175 obj->real_type = OBJ_BAD;
1176 nr_delays++;
1177 } else
1178 sha1_object(data, NULL, obj->size, obj->type,
1179 &obj->idx.oid);
1180 free(data);
1181 display_progress(progress, i+1);
1183 objects[i].idx.offset = consumed_bytes;
1184 stop_progress(&progress);
1186 /* Check pack integrity */
1187 flush();
1188 the_hash_algo->final_fn(hash, &input_ctx);
1189 if (!hasheq(fill(the_hash_algo->rawsz), hash))
1190 die(_("pack is corrupted (SHA1 mismatch)"));
1191 use(the_hash_algo->rawsz);
1193 /* If input_fd is a file, we should have reached its end now. */
1194 if (fstat(input_fd, &st))
1195 die_errno(_("cannot fstat packfile"));
1196 if (S_ISREG(st.st_mode) &&
1197 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
1198 die(_("pack has junk at the end"));
1200 for (i = 0; i < nr_objects; i++) {
1201 struct object_entry *obj = &objects[i];
1202 if (obj->real_type != OBJ_BAD)
1203 continue;
1204 obj->real_type = obj->type;
1205 sha1_object(NULL, obj, obj->size, obj->type,
1206 &obj->idx.oid);
1207 nr_delays--;
1209 if (nr_delays)
1210 die(_("confusion beyond insanity in parse_pack_objects()"));
1214 * Second pass:
1215 * - for all non-delta objects, look if it is used as a base for
1216 * deltas;
1217 * - if used as a base, uncompress the object and apply all deltas,
1218 * recursively checking if the resulting object is used as a base
1219 * for some more deltas.
1221 static void resolve_deltas(void)
1223 int i;
1225 if (!nr_ofs_deltas && !nr_ref_deltas)
1226 return;
1228 /* Sort deltas by base SHA1/offset for fast searching */
1229 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1230 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
1232 if (verbose || show_resolving_progress)
1233 progress = start_progress(_("Resolving deltas"),
1234 nr_ref_deltas + nr_ofs_deltas);
1236 nr_dispatched = 0;
1237 base_cache_limit = delta_base_cache_limit * nr_threads;
1238 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1239 init_thread();
1240 for (i = 0; i < nr_threads; i++) {
1241 int ret = pthread_create(&thread_data[i].thread, NULL,
1242 threaded_second_pass, thread_data + i);
1243 if (ret)
1244 die(_("unable to create thread: %s"),
1245 strerror(ret));
1247 for (i = 0; i < nr_threads; i++)
1248 pthread_join(thread_data[i].thread, NULL);
1249 cleanup_thread();
1250 return;
1252 threaded_second_pass(&nothread_data);
1256 * Third pass:
1257 * - append objects to convert thin pack to full pack if required
1258 * - write the final pack hash
1260 static void fix_unresolved_deltas(struct hashfile *f);
1261 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_hash)
1263 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
1264 stop_progress(&progress);
1265 /* Flush remaining pack final hash. */
1266 flush();
1267 return;
1270 if (fix_thin_pack) {
1271 struct hashfile *f;
1272 unsigned char read_hash[GIT_MAX_RAWSZ], tail_hash[GIT_MAX_RAWSZ];
1273 struct strbuf msg = STRBUF_INIT;
1274 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
1275 int nr_objects_initial = nr_objects;
1276 if (nr_unresolved <= 0)
1277 die(_("confusion beyond insanity"));
1278 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
1279 memset(objects + nr_objects + 1, 0,
1280 nr_unresolved * sizeof(*objects));
1281 f = hashfd(output_fd, curr_pack);
1282 fix_unresolved_deltas(f);
1283 strbuf_addf(&msg, Q_("completed with %d local object",
1284 "completed with %d local objects",
1285 nr_objects - nr_objects_initial),
1286 nr_objects - nr_objects_initial);
1287 stop_progress_msg(&progress, msg.buf);
1288 strbuf_release(&msg);
1289 finalize_hashfile(f, tail_hash, 0);
1290 hashcpy(read_hash, pack_hash);
1291 fixup_pack_header_footer(output_fd, pack_hash,
1292 curr_pack, nr_objects,
1293 read_hash, consumed_bytes-the_hash_algo->rawsz);
1294 if (!hasheq(read_hash, tail_hash))
1295 die(_("Unexpected tail checksum for %s "
1296 "(disk corruption?)"), curr_pack);
1298 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
1299 die(Q_("pack has %d unresolved delta",
1300 "pack has %d unresolved deltas",
1301 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1302 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
1305 static int write_compressed(struct hashfile *f, void *in, unsigned int size)
1307 git_zstream stream;
1308 int status;
1309 unsigned char outbuf[4096];
1311 git_deflate_init(&stream, zlib_compression_level);
1312 stream.next_in = in;
1313 stream.avail_in = size;
1315 do {
1316 stream.next_out = outbuf;
1317 stream.avail_out = sizeof(outbuf);
1318 status = git_deflate(&stream, Z_FINISH);
1319 hashwrite(f, outbuf, sizeof(outbuf) - stream.avail_out);
1320 } while (status == Z_OK);
1322 if (status != Z_STREAM_END)
1323 die(_("unable to deflate appended object (%d)"), status);
1324 size = stream.total_out;
1325 git_deflate_end(&stream);
1326 return size;
1329 static struct object_entry *append_obj_to_pack(struct hashfile *f,
1330 const unsigned char *sha1, void *buf,
1331 unsigned long size, enum object_type type)
1333 struct object_entry *obj = &objects[nr_objects++];
1334 unsigned char header[10];
1335 unsigned long s = size;
1336 int n = 0;
1337 unsigned char c = (type << 4) | (s & 15);
1338 s >>= 4;
1339 while (s) {
1340 header[n++] = c | 0x80;
1341 c = s & 0x7f;
1342 s >>= 7;
1344 header[n++] = c;
1345 crc32_begin(f);
1346 hashwrite(f, header, n);
1347 obj[0].size = size;
1348 obj[0].hdr_size = n;
1349 obj[0].type = type;
1350 obj[0].real_type = type;
1351 obj[1].idx.offset = obj[0].idx.offset + n;
1352 obj[1].idx.offset += write_compressed(f, buf, size);
1353 obj[0].idx.crc32 = crc32_end(f);
1354 hashflush(f);
1355 oidread(&obj->idx.oid, sha1);
1356 return obj;
1359 static int delta_pos_compare(const void *_a, const void *_b)
1361 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1362 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
1363 return a->obj_no - b->obj_no;
1366 static void fix_unresolved_deltas(struct hashfile *f)
1368 struct ref_delta_entry **sorted_by_pos;
1369 int i;
1372 * Since many unresolved deltas may well be themselves base objects
1373 * for more unresolved deltas, we really want to include the
1374 * smallest number of base objects that would cover as much delta
1375 * as possible by picking the
1376 * trunc deltas first, allowing for other deltas to resolve without
1377 * additional base objects. Since most base objects are to be found
1378 * before deltas depending on them, a good heuristic is to start
1379 * resolving deltas in the same order as their position in the pack.
1381 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
1382 for (i = 0; i < nr_ref_deltas; i++)
1383 sorted_by_pos[i] = &ref_deltas[i];
1384 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
1386 if (has_promisor_remote()) {
1388 * Prefetch the delta bases.
1390 struct oid_array to_fetch = OID_ARRAY_INIT;
1391 for (i = 0; i < nr_ref_deltas; i++) {
1392 struct ref_delta_entry *d = sorted_by_pos[i];
1393 if (!oid_object_info_extended(the_repository, &d->oid,
1394 NULL,
1395 OBJECT_INFO_FOR_PREFETCH))
1396 continue;
1397 oid_array_append(&to_fetch, &d->oid);
1399 promisor_remote_get_direct(the_repository,
1400 to_fetch.oid, to_fetch.nr);
1401 oid_array_clear(&to_fetch);
1404 for (i = 0; i < nr_ref_deltas; i++) {
1405 struct ref_delta_entry *d = sorted_by_pos[i];
1406 enum object_type type;
1407 void *data;
1408 unsigned long size;
1410 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1411 continue;
1412 data = read_object_file(&d->oid, &type, &size);
1413 if (!data)
1414 continue;
1416 if (check_object_signature(the_repository, &d->oid,
1417 data, size,
1418 type_name(type), NULL))
1419 die(_("local object %s is corrupt"), oid_to_hex(&d->oid));
1422 * Add this as an object to the objects array and call
1423 * threaded_second_pass() (which will pick up the added
1424 * object).
1426 append_obj_to_pack(f, d->oid.hash, data, size, type);
1427 threaded_second_pass(NULL);
1429 display_progress(progress, nr_resolved_deltas);
1431 free(sorted_by_pos);
1434 static const char *derive_filename(const char *pack_name, const char *strip,
1435 const char *suffix, struct strbuf *buf)
1437 size_t len;
1438 if (!strip_suffix(pack_name, strip, &len) || !len ||
1439 pack_name[len - 1] != '.')
1440 die(_("packfile name '%s' does not end with '.%s'"),
1441 pack_name, strip);
1442 strbuf_add(buf, pack_name, len);
1443 strbuf_addstr(buf, suffix);
1444 return buf->buf;
1447 static void write_special_file(const char *suffix, const char *msg,
1448 const char *pack_name, const unsigned char *hash,
1449 const char **report)
1451 struct strbuf name_buf = STRBUF_INIT;
1452 const char *filename;
1453 int fd;
1454 int msg_len = strlen(msg);
1456 if (pack_name)
1457 filename = derive_filename(pack_name, "pack", suffix, &name_buf);
1458 else
1459 filename = odb_pack_name(&name_buf, hash, suffix);
1461 fd = odb_pack_keep(filename);
1462 if (fd < 0) {
1463 if (errno != EEXIST)
1464 die_errno(_("cannot write %s file '%s'"),
1465 suffix, filename);
1466 } else {
1467 if (msg_len > 0) {
1468 write_or_die(fd, msg, msg_len);
1469 write_or_die(fd, "\n", 1);
1471 if (close(fd) != 0)
1472 die_errno(_("cannot close written %s file '%s'"),
1473 suffix, filename);
1474 if (report)
1475 *report = suffix;
1477 strbuf_release(&name_buf);
1480 static void rename_tmp_packfile(const char **final_name,
1481 const char *curr_name,
1482 struct strbuf *name, unsigned char *hash,
1483 const char *ext, int make_read_only_if_same)
1485 if (*final_name != curr_name) {
1486 if (!*final_name)
1487 *final_name = odb_pack_name(name, hash, ext);
1488 if (finalize_object_file(curr_name, *final_name))
1489 die(_("unable to rename temporary '*.%s' file to '%s'"),
1490 ext, *final_name);
1491 } else if (make_read_only_if_same) {
1492 chmod(*final_name, 0444);
1496 static void final(const char *final_pack_name, const char *curr_pack_name,
1497 const char *final_index_name, const char *curr_index_name,
1498 const char *final_rev_index_name, const char *curr_rev_index_name,
1499 const char *keep_msg, const char *promisor_msg,
1500 unsigned char *hash)
1502 const char *report = "pack";
1503 struct strbuf pack_name = STRBUF_INIT;
1504 struct strbuf index_name = STRBUF_INIT;
1505 struct strbuf rev_index_name = STRBUF_INIT;
1506 int err;
1508 if (!from_stdin) {
1509 close(input_fd);
1510 } else {
1511 fsync_or_die(output_fd, curr_pack_name);
1512 err = close(output_fd);
1513 if (err)
1514 die_errno(_("error while closing pack file"));
1517 if (keep_msg)
1518 write_special_file("keep", keep_msg, final_pack_name, hash,
1519 &report);
1520 if (promisor_msg)
1521 write_special_file("promisor", promisor_msg, final_pack_name,
1522 hash, NULL);
1524 rename_tmp_packfile(&final_pack_name, curr_pack_name, &pack_name,
1525 hash, "pack", from_stdin);
1526 if (curr_rev_index_name)
1527 rename_tmp_packfile(&final_rev_index_name, curr_rev_index_name,
1528 &rev_index_name, hash, "rev", 1);
1529 rename_tmp_packfile(&final_index_name, curr_index_name, &index_name,
1530 hash, "idx", 1);
1532 if (do_fsck_object) {
1533 struct packed_git *p;
1534 p = add_packed_git(final_index_name, strlen(final_index_name), 0);
1535 if (p)
1536 install_packed_git(the_repository, p);
1539 if (!from_stdin) {
1540 printf("%s\n", hash_to_hex(hash));
1541 } else {
1542 struct strbuf buf = STRBUF_INIT;
1544 strbuf_addf(&buf, "%s\t%s\n", report, hash_to_hex(hash));
1545 write_or_die(1, buf.buf, buf.len);
1546 strbuf_release(&buf);
1549 * Let's just mimic git-unpack-objects here and write
1550 * the last part of the input buffer to stdout.
1552 while (input_len) {
1553 err = xwrite(1, input_buffer + input_offset, input_len);
1554 if (err <= 0)
1555 break;
1556 input_len -= err;
1557 input_offset += err;
1561 strbuf_release(&rev_index_name);
1562 strbuf_release(&index_name);
1563 strbuf_release(&pack_name);
1566 static int git_index_pack_config(const char *k, const char *v, void *cb)
1568 struct pack_idx_option *opts = cb;
1570 if (!strcmp(k, "pack.indexversion")) {
1571 opts->version = git_config_int(k, v);
1572 if (opts->version > 2)
1573 die(_("bad pack.indexversion=%"PRIu32), opts->version);
1574 return 0;
1576 if (!strcmp(k, "pack.threads")) {
1577 nr_threads = git_config_int(k, v);
1578 if (nr_threads < 0)
1579 die(_("invalid number of threads specified (%d)"),
1580 nr_threads);
1581 if (!HAVE_THREADS && nr_threads != 1) {
1582 warning(_("no threads support, ignoring %s"), k);
1583 nr_threads = 1;
1585 return 0;
1587 if (!strcmp(k, "pack.writereverseindex")) {
1588 if (git_config_bool(k, v))
1589 opts->flags |= WRITE_REV;
1590 else
1591 opts->flags &= ~WRITE_REV;
1593 return git_default_config(k, v, cb);
1596 static int cmp_uint32(const void *a_, const void *b_)
1598 uint32_t a = *((uint32_t *)a_);
1599 uint32_t b = *((uint32_t *)b_);
1601 return (a < b) ? -1 : (a != b);
1604 static void read_v2_anomalous_offsets(struct packed_git *p,
1605 struct pack_idx_option *opts)
1607 const uint32_t *idx1, *idx2;
1608 uint32_t i;
1610 /* The address of the 4-byte offset table */
1611 idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
1612 + (size_t)p->num_objects /* CRC32 table */
1615 /* The address of the 8-byte offset table */
1616 idx2 = idx1 + p->num_objects;
1618 for (i = 0; i < p->num_objects; i++) {
1619 uint32_t off = ntohl(idx1[i]);
1620 if (!(off & 0x80000000))
1621 continue;
1622 off = off & 0x7fffffff;
1623 check_pack_index_ptr(p, &idx2[off * 2]);
1624 if (idx2[off * 2])
1625 continue;
1627 * The real offset is ntohl(idx2[off * 2]) in high 4
1628 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1629 * octets. But idx2[off * 2] is Zero!!!
1631 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1632 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1635 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
1638 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1640 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1642 if (!p)
1643 die(_("Cannot open existing pack file '%s'"), pack_name);
1644 if (open_pack_index(p))
1645 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1647 /* Read the attributes from the existing idx file */
1648 opts->version = p->index_version;
1650 if (opts->version == 2)
1651 read_v2_anomalous_offsets(p, opts);
1654 * Get rid of the idx file as we do not need it anymore.
1655 * NEEDSWORK: extract this bit from free_pack_by_name() in
1656 * object-file.c, perhaps? It shouldn't matter very much as we
1657 * know we haven't installed this pack (hence we never have
1658 * read anything from it).
1660 close_pack_index(p);
1661 free(p);
1664 static void show_pack_info(int stat_only)
1666 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
1667 unsigned long *chain_histogram = NULL;
1669 if (deepest_delta)
1670 CALLOC_ARRAY(chain_histogram, deepest_delta);
1672 for (i = 0; i < nr_objects; i++) {
1673 struct object_entry *obj = &objects[i];
1675 if (is_delta_type(obj->type))
1676 chain_histogram[obj_stat[i].delta_depth - 1]++;
1677 if (stat_only)
1678 continue;
1679 printf("%s %-6s %"PRIuMAX" %"PRIuMAX" %"PRIuMAX,
1680 oid_to_hex(&obj->idx.oid),
1681 type_name(obj->real_type), (uintmax_t)obj->size,
1682 (uintmax_t)(obj[1].idx.offset - obj->idx.offset),
1683 (uintmax_t)obj->idx.offset);
1684 if (is_delta_type(obj->type)) {
1685 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
1686 printf(" %u %s", obj_stat[i].delta_depth,
1687 oid_to_hex(&bobj->idx.oid));
1689 putchar('\n');
1692 if (baseobjects)
1693 printf_ln(Q_("non delta: %d object",
1694 "non delta: %d objects",
1695 baseobjects),
1696 baseobjects);
1697 for (i = 0; i < deepest_delta; i++) {
1698 if (!chain_histogram[i])
1699 continue;
1700 printf_ln(Q_("chain length = %d: %lu object",
1701 "chain length = %d: %lu objects",
1702 chain_histogram[i]),
1703 i + 1,
1704 chain_histogram[i]);
1708 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1710 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, rev_index;
1711 const char *curr_index;
1712 const char *curr_rev_index = NULL;
1713 const char *index_name = NULL, *pack_name = NULL, *rev_index_name = NULL;
1714 const char *keep_msg = NULL;
1715 const char *promisor_msg = NULL;
1716 struct strbuf index_name_buf = STRBUF_INIT;
1717 struct strbuf rev_index_name_buf = STRBUF_INIT;
1718 struct pack_idx_entry **idx_objects;
1719 struct pack_idx_option opts;
1720 unsigned char pack_hash[GIT_MAX_RAWSZ];
1721 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
1722 int report_end_of_input = 0;
1723 int hash_algo = 0;
1726 * index-pack never needs to fetch missing objects except when
1727 * REF_DELTA bases are missing (which are explicitly handled). It only
1728 * accesses the repo to do hash collision checks and to check which
1729 * REF_DELTA bases need to be fetched.
1731 fetch_if_missing = 0;
1733 if (argc == 2 && !strcmp(argv[1], "-h"))
1734 usage(index_pack_usage);
1736 read_replace_refs = 0;
1737 fsck_options.walk = mark_link;
1739 reset_pack_idx_option(&opts);
1740 git_config(git_index_pack_config, &opts);
1741 if (prefix && chdir(prefix))
1742 die(_("Cannot come back to cwd"));
1744 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
1745 rev_index = 1;
1746 else
1747 rev_index = !!(opts.flags & (WRITE_REV_VERIFY | WRITE_REV));
1749 for (i = 1; i < argc; i++) {
1750 const char *arg = argv[i];
1752 if (*arg == '-') {
1753 if (!strcmp(arg, "--stdin")) {
1754 from_stdin = 1;
1755 } else if (!strcmp(arg, "--fix-thin")) {
1756 fix_thin_pack = 1;
1757 } else if (skip_to_optional_arg(arg, "--strict", &arg)) {
1758 strict = 1;
1759 do_fsck_object = 1;
1760 fsck_set_msg_types(&fsck_options, arg);
1761 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1762 strict = 1;
1763 check_self_contained_and_connected = 1;
1764 } else if (!strcmp(arg, "--fsck-objects")) {
1765 do_fsck_object = 1;
1766 } else if (!strcmp(arg, "--verify")) {
1767 verify = 1;
1768 } else if (!strcmp(arg, "--verify-stat")) {
1769 verify = 1;
1770 show_stat = 1;
1771 } else if (!strcmp(arg, "--verify-stat-only")) {
1772 verify = 1;
1773 show_stat = 1;
1774 stat_only = 1;
1775 } else if (skip_to_optional_arg(arg, "--keep", &keep_msg)) {
1776 ; /* nothing to do */
1777 } else if (skip_to_optional_arg(arg, "--promisor", &promisor_msg)) {
1778 ; /* already parsed */
1779 } else if (starts_with(arg, "--threads=")) {
1780 char *end;
1781 nr_threads = strtoul(arg+10, &end, 0);
1782 if (!arg[10] || *end || nr_threads < 0)
1783 usage(index_pack_usage);
1784 if (!HAVE_THREADS && nr_threads != 1) {
1785 warning(_("no threads support, ignoring %s"), arg);
1786 nr_threads = 1;
1788 } else if (starts_with(arg, "--pack_header=")) {
1789 struct pack_header *hdr;
1790 char *c;
1792 hdr = (struct pack_header *)input_buffer;
1793 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1794 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1795 if (*c != ',')
1796 die(_("bad %s"), arg);
1797 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1798 if (*c)
1799 die(_("bad %s"), arg);
1800 input_len = sizeof(*hdr);
1801 } else if (!strcmp(arg, "-v")) {
1802 verbose = 1;
1803 } else if (!strcmp(arg, "--progress-title")) {
1804 if (progress_title || (i+1) >= argc)
1805 usage(index_pack_usage);
1806 progress_title = argv[++i];
1807 } else if (!strcmp(arg, "--show-resolving-progress")) {
1808 show_resolving_progress = 1;
1809 } else if (!strcmp(arg, "--report-end-of-input")) {
1810 report_end_of_input = 1;
1811 } else if (!strcmp(arg, "-o")) {
1812 if (index_name || (i+1) >= argc)
1813 usage(index_pack_usage);
1814 index_name = argv[++i];
1815 } else if (starts_with(arg, "--index-version=")) {
1816 char *c;
1817 opts.version = strtoul(arg + 16, &c, 10);
1818 if (opts.version > 2)
1819 die(_("bad %s"), arg);
1820 if (*c == ',')
1821 opts.off32_limit = strtoul(c+1, &c, 0);
1822 if (*c || opts.off32_limit & 0x80000000)
1823 die(_("bad %s"), arg);
1824 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1825 max_input_size = strtoumax(arg, NULL, 10);
1826 } else if (skip_prefix(arg, "--object-format=", &arg)) {
1827 hash_algo = hash_algo_by_name(arg);
1828 if (hash_algo == GIT_HASH_UNKNOWN)
1829 die(_("unknown hash algorithm '%s'"), arg);
1830 repo_set_hash_algo(the_repository, hash_algo);
1831 } else if (!strcmp(arg, "--rev-index")) {
1832 rev_index = 1;
1833 } else if (!strcmp(arg, "--no-rev-index")) {
1834 rev_index = 0;
1835 } else
1836 usage(index_pack_usage);
1837 continue;
1840 if (pack_name)
1841 usage(index_pack_usage);
1842 pack_name = arg;
1845 if (!pack_name && !from_stdin)
1846 usage(index_pack_usage);
1847 if (fix_thin_pack && !from_stdin)
1848 die(_("the option '%s' requires '%s'"), "--fix-thin", "--stdin");
1849 if (from_stdin && !startup_info->have_repository)
1850 die(_("--stdin requires a git repository"));
1851 if (from_stdin && hash_algo)
1852 die(_("options '%s' and '%s' cannot be used together"), "--object-format", "--stdin");
1853 if (!index_name && pack_name)
1854 index_name = derive_filename(pack_name, "pack", "idx", &index_name_buf);
1856 opts.flags &= ~(WRITE_REV | WRITE_REV_VERIFY);
1857 if (rev_index) {
1858 opts.flags |= verify ? WRITE_REV_VERIFY : WRITE_REV;
1859 if (index_name)
1860 rev_index_name = derive_filename(index_name,
1861 "idx", "rev",
1862 &rev_index_name_buf);
1865 if (verify) {
1866 if (!index_name)
1867 die(_("--verify with no packfile name given"));
1868 read_idx_option(&opts, index_name);
1869 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1871 if (strict)
1872 opts.flags |= WRITE_IDX_STRICT;
1874 if (HAVE_THREADS && !nr_threads) {
1875 nr_threads = online_cpus();
1877 * Experiments show that going above 20 threads doesn't help,
1878 * no matter how many cores you have. Below that, we tend to
1879 * max at half the number of online_cpus(), presumably because
1880 * half of those are hyperthreads rather than full cores. We'll
1881 * never reduce the level below "3", though, to match a
1882 * historical value that nobody complained about.
1884 if (nr_threads < 4)
1885 ; /* too few cores to consider capping */
1886 else if (nr_threads < 6)
1887 nr_threads = 3; /* historic cap */
1888 else if (nr_threads < 40)
1889 nr_threads /= 2;
1890 else
1891 nr_threads = 20; /* hard cap */
1894 curr_pack = open_pack_file(pack_name);
1895 parse_pack_header();
1896 CALLOC_ARRAY(objects, st_add(nr_objects, 1));
1897 if (show_stat)
1898 CALLOC_ARRAY(obj_stat, st_add(nr_objects, 1));
1899 CALLOC_ARRAY(ofs_deltas, nr_objects);
1900 parse_pack_objects(pack_hash);
1901 if (report_end_of_input)
1902 write_in_full(2, "\0", 1);
1903 resolve_deltas();
1904 conclude_pack(fix_thin_pack, curr_pack, pack_hash);
1905 free(ofs_deltas);
1906 free(ref_deltas);
1907 if (strict)
1908 foreign_nr = check_objects();
1910 if (show_stat)
1911 show_pack_info(stat_only);
1913 ALLOC_ARRAY(idx_objects, nr_objects);
1914 for (i = 0; i < nr_objects; i++)
1915 idx_objects[i] = &objects[i].idx;
1916 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_hash);
1917 if (rev_index)
1918 curr_rev_index = write_rev_file(rev_index_name, idx_objects,
1919 nr_objects, pack_hash,
1920 opts.flags);
1921 free(idx_objects);
1923 if (!verify)
1924 final(pack_name, curr_pack,
1925 index_name, curr_index,
1926 rev_index_name, curr_rev_index,
1927 keep_msg, promisor_msg,
1928 pack_hash);
1929 else
1930 close(input_fd);
1932 if (do_fsck_object && fsck_finish(&fsck_options))
1933 die(_("fsck error in pack objects"));
1935 free(objects);
1936 strbuf_release(&index_name_buf);
1937 strbuf_release(&rev_index_name_buf);
1938 if (pack_name == NULL)
1939 free((void *) curr_pack);
1940 if (index_name == NULL)
1941 free((void *) curr_index);
1942 if (rev_index_name == NULL)
1943 free((void *) curr_rev_index);
1946 * Let the caller know this pack is not self contained
1948 if (check_self_contained_and_connected && foreign_nr)
1949 return 1;
1951 return 0;