notes.c: use designated initializers for clarity
[git/debian.git] / builtin / index-pack.c
blobb17e79cd40f797d53ee3dbe12440af0ed4787228
1 #include "builtin.h"
2 #include "alloc.h"
3 #include "config.h"
4 #include "delta.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "pack.h"
9 #include "csum-file.h"
10 #include "blob.h"
11 #include "commit.h"
12 #include "tag.h"
13 #include "tree.h"
14 #include "progress.h"
15 #include "fsck.h"
16 #include "exec-cmd.h"
17 #include "streaming.h"
18 #include "thread-utils.h"
19 #include "packfile.h"
20 #include "object-store.h"
21 #include "replace-object.h"
22 #include "promisor-remote.h"
23 #include "setup.h"
24 #include "wrapper.h"
26 static const char index_pack_usage[] =
27 "git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--[no-]rev-index] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
29 struct object_entry {
30 struct pack_idx_entry idx;
31 unsigned long size;
32 unsigned char hdr_size;
33 signed char type;
34 signed char real_type;
37 struct object_stat {
38 unsigned delta_depth;
39 int base_object_no;
42 struct base_data {
43 /* Initialized by make_base(). */
44 struct base_data *base;
45 struct object_entry *obj;
46 int ref_first, ref_last;
47 int ofs_first, ofs_last;
49 * Threads should increment retain_data if they are about to call
50 * patch_delta() using this struct's data as a base, and decrement this
51 * when they are done. While retain_data is nonzero, this struct's data
52 * will not be freed even if the delta base cache limit is exceeded.
54 int retain_data;
56 * The number of direct children that have not been fully processed
57 * (entered work_head, entered done_head, left done_head). When this
58 * number reaches zero, this struct base_data can be freed.
60 int children_remaining;
62 /* Not initialized by make_base(). */
63 struct list_head list;
64 void *data;
65 unsigned long size;
69 * Stack of struct base_data that have unprocessed children.
70 * threaded_second_pass() uses this as a source of work (the other being the
71 * objects array).
73 * Guarded by work_mutex.
75 static LIST_HEAD(work_head);
78 * Stack of struct base_data that have children, all of whom have been
79 * processed or are being processed, and at least one child is being processed.
80 * These struct base_data must be kept around until the last child is
81 * processed.
83 * Guarded by work_mutex.
85 static LIST_HEAD(done_head);
88 * All threads share one delta base cache.
90 * base_cache_used is guarded by work_mutex, and base_cache_limit is read-only
91 * in a thread.
93 static size_t base_cache_used;
94 static size_t base_cache_limit;
96 struct thread_local {
97 pthread_t thread;
98 int pack_fd;
101 /* Remember to update object flag allocation in object.h */
102 #define FLAG_LINK (1u<<20)
103 #define FLAG_CHECKED (1u<<21)
105 struct ofs_delta_entry {
106 off_t offset;
107 int obj_no;
110 struct ref_delta_entry {
111 struct object_id oid;
112 int obj_no;
115 static struct object_entry *objects;
116 static struct object_stat *obj_stat;
117 static struct ofs_delta_entry *ofs_deltas;
118 static struct ref_delta_entry *ref_deltas;
119 static struct thread_local nothread_data;
120 static int nr_objects;
121 static int nr_ofs_deltas;
122 static int nr_ref_deltas;
123 static int ref_deltas_alloc;
124 static int nr_resolved_deltas;
125 static int nr_threads;
127 static int from_stdin;
128 static int strict;
129 static int do_fsck_object;
130 static struct fsck_options fsck_options = FSCK_OPTIONS_MISSING_GITMODULES;
131 static int verbose;
132 static const char *progress_title;
133 static int show_resolving_progress;
134 static int show_stat;
135 static int check_self_contained_and_connected;
137 static struct progress *progress;
139 /* We always read in 4kB chunks. */
140 static unsigned char input_buffer[4096];
141 static unsigned int input_offset, input_len;
142 static off_t consumed_bytes;
143 static off_t max_input_size;
144 static unsigned deepest_delta;
145 static git_hash_ctx input_ctx;
146 static uint32_t input_crc32;
147 static int input_fd, output_fd;
148 static const char *curr_pack;
150 static struct thread_local *thread_data;
151 static int nr_dispatched;
152 static int threads_active;
154 static pthread_mutex_t read_mutex;
155 #define read_lock() lock_mutex(&read_mutex)
156 #define read_unlock() unlock_mutex(&read_mutex)
158 static pthread_mutex_t counter_mutex;
159 #define counter_lock() lock_mutex(&counter_mutex)
160 #define counter_unlock() unlock_mutex(&counter_mutex)
162 static pthread_mutex_t work_mutex;
163 #define work_lock() lock_mutex(&work_mutex)
164 #define work_unlock() unlock_mutex(&work_mutex)
166 static pthread_mutex_t deepest_delta_mutex;
167 #define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
168 #define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
170 static pthread_key_t key;
172 static inline void lock_mutex(pthread_mutex_t *mutex)
174 if (threads_active)
175 pthread_mutex_lock(mutex);
178 static inline void unlock_mutex(pthread_mutex_t *mutex)
180 if (threads_active)
181 pthread_mutex_unlock(mutex);
185 * Mutex and conditional variable can't be statically-initialized on Windows.
187 static void init_thread(void)
189 int i;
190 init_recursive_mutex(&read_mutex);
191 pthread_mutex_init(&counter_mutex, NULL);
192 pthread_mutex_init(&work_mutex, NULL);
193 if (show_stat)
194 pthread_mutex_init(&deepest_delta_mutex, NULL);
195 pthread_key_create(&key, NULL);
196 CALLOC_ARRAY(thread_data, nr_threads);
197 for (i = 0; i < nr_threads; i++) {
198 thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
201 threads_active = 1;
204 static void cleanup_thread(void)
206 int i;
207 if (!threads_active)
208 return;
209 threads_active = 0;
210 pthread_mutex_destroy(&read_mutex);
211 pthread_mutex_destroy(&counter_mutex);
212 pthread_mutex_destroy(&work_mutex);
213 if (show_stat)
214 pthread_mutex_destroy(&deepest_delta_mutex);
215 for (i = 0; i < nr_threads; i++)
216 close(thread_data[i].pack_fd);
217 pthread_key_delete(key);
218 free(thread_data);
221 static int mark_link(struct object *obj, enum object_type type,
222 void *data, struct fsck_options *options)
224 if (!obj)
225 return -1;
227 if (type != OBJ_ANY && obj->type != type)
228 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
230 obj->flags |= FLAG_LINK;
231 return 0;
234 /* The content of each linked object must have been checked
235 or it must be already present in the object database */
236 static unsigned check_object(struct object *obj)
238 if (!obj)
239 return 0;
241 if (!(obj->flags & FLAG_LINK))
242 return 0;
244 if (!(obj->flags & FLAG_CHECKED)) {
245 unsigned long size;
246 int type = oid_object_info(the_repository, &obj->oid, &size);
247 if (type <= 0)
248 die(_("did not receive expected object %s"),
249 oid_to_hex(&obj->oid));
250 if (type != obj->type)
251 die(_("object %s: expected type %s, found %s"),
252 oid_to_hex(&obj->oid),
253 type_name(obj->type), type_name(type));
254 obj->flags |= FLAG_CHECKED;
255 return 1;
258 return 0;
261 static unsigned check_objects(void)
263 unsigned i, max, foreign_nr = 0;
265 max = get_max_object_index();
267 if (verbose)
268 progress = start_delayed_progress(_("Checking objects"), max);
270 for (i = 0; i < max; i++) {
271 foreign_nr += check_object(get_indexed_object(i));
272 display_progress(progress, i + 1);
275 stop_progress(&progress);
276 return foreign_nr;
280 /* Discard current buffer used content. */
281 static void flush(void)
283 if (input_offset) {
284 if (output_fd >= 0)
285 write_or_die(output_fd, input_buffer, input_offset);
286 the_hash_algo->update_fn(&input_ctx, input_buffer, input_offset);
287 memmove(input_buffer, input_buffer + input_offset, input_len);
288 input_offset = 0;
293 * Make sure at least "min" bytes are available in the buffer, and
294 * return the pointer to the buffer.
296 static void *fill(int min)
298 if (min <= input_len)
299 return input_buffer + input_offset;
300 if (min > sizeof(input_buffer))
301 die(Q_("cannot fill %d byte",
302 "cannot fill %d bytes",
303 min),
304 min);
305 flush();
306 do {
307 ssize_t ret = xread(input_fd, input_buffer + input_len,
308 sizeof(input_buffer) - input_len);
309 if (ret <= 0) {
310 if (!ret)
311 die(_("early EOF"));
312 die_errno(_("read error on input"));
314 input_len += ret;
315 if (from_stdin)
316 display_throughput(progress, consumed_bytes + input_len);
317 } while (input_len < min);
318 return input_buffer;
321 static void use(int bytes)
323 if (bytes > input_len)
324 die(_("used more bytes than were available"));
325 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
326 input_len -= bytes;
327 input_offset += bytes;
329 /* make sure off_t is sufficiently large not to wrap */
330 if (signed_add_overflows(consumed_bytes, bytes))
331 die(_("pack too large for current definition of off_t"));
332 consumed_bytes += bytes;
333 if (max_input_size && consumed_bytes > max_input_size) {
334 struct strbuf size_limit = STRBUF_INIT;
335 strbuf_humanise_bytes(&size_limit, max_input_size);
336 die(_("pack exceeds maximum allowed size (%s)"),
337 size_limit.buf);
341 static const char *open_pack_file(const char *pack_name)
343 if (from_stdin) {
344 input_fd = 0;
345 if (!pack_name) {
346 struct strbuf tmp_file = STRBUF_INIT;
347 output_fd = odb_mkstemp(&tmp_file,
348 "pack/tmp_pack_XXXXXX");
349 pack_name = strbuf_detach(&tmp_file, NULL);
350 } else {
351 output_fd = xopen(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
353 nothread_data.pack_fd = output_fd;
354 } else {
355 input_fd = xopen(pack_name, O_RDONLY);
356 output_fd = -1;
357 nothread_data.pack_fd = input_fd;
359 the_hash_algo->init_fn(&input_ctx);
360 return pack_name;
363 static void parse_pack_header(void)
365 struct pack_header *hdr = fill(sizeof(struct pack_header));
367 /* Header consistency check */
368 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
369 die(_("pack signature mismatch"));
370 if (!pack_version_ok(hdr->hdr_version))
371 die(_("pack version %"PRIu32" unsupported"),
372 ntohl(hdr->hdr_version));
374 nr_objects = ntohl(hdr->hdr_entries);
375 use(sizeof(struct pack_header));
378 __attribute__((format (printf, 2, 3)))
379 static NORETURN void bad_object(off_t offset, const char *format, ...)
381 va_list params;
382 char buf[1024];
384 va_start(params, format);
385 vsnprintf(buf, sizeof(buf), format, params);
386 va_end(params);
387 die(_("pack has bad object at offset %"PRIuMAX": %s"),
388 (uintmax_t)offset, buf);
391 static inline struct thread_local *get_thread_data(void)
393 if (HAVE_THREADS) {
394 if (threads_active)
395 return pthread_getspecific(key);
396 assert(!threads_active &&
397 "This should only be reached when all threads are gone");
399 return &nothread_data;
402 static void set_thread_data(struct thread_local *data)
404 if (threads_active)
405 pthread_setspecific(key, data);
408 static void free_base_data(struct base_data *c)
410 if (c->data) {
411 FREE_AND_NULL(c->data);
412 base_cache_used -= c->size;
416 static void prune_base_data(struct base_data *retain)
418 struct list_head *pos;
420 if (base_cache_used <= base_cache_limit)
421 return;
423 list_for_each_prev(pos, &done_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;
434 list_for_each_prev(pos, &work_head) {
435 struct base_data *b = list_entry(pos, struct base_data, list);
436 if (b->retain_data || b == retain)
437 continue;
438 if (b->data) {
439 free_base_data(b);
440 if (base_cache_used <= base_cache_limit)
441 return;
446 static int is_delta_type(enum object_type type)
448 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
451 static void *unpack_entry_data(off_t offset, unsigned long size,
452 enum object_type type, struct object_id *oid)
454 static char fixed_buf[8192];
455 int status;
456 git_zstream stream;
457 void *buf;
458 git_hash_ctx c;
459 char hdr[32];
460 int hdrlen;
462 if (!is_delta_type(type)) {
463 hdrlen = format_object_header(hdr, sizeof(hdr), type, size);
464 the_hash_algo->init_fn(&c);
465 the_hash_algo->update_fn(&c, hdr, hdrlen);
466 } else
467 oid = NULL;
468 if (type == OBJ_BLOB && size > big_file_threshold)
469 buf = fixed_buf;
470 else
471 buf = xmallocz(size);
473 memset(&stream, 0, sizeof(stream));
474 git_inflate_init(&stream);
475 stream.next_out = buf;
476 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
478 do {
479 unsigned char *last_out = stream.next_out;
480 stream.next_in = fill(1);
481 stream.avail_in = input_len;
482 status = git_inflate(&stream, 0);
483 use(input_len - stream.avail_in);
484 if (oid)
485 the_hash_algo->update_fn(&c, last_out, stream.next_out - last_out);
486 if (buf == fixed_buf) {
487 stream.next_out = buf;
488 stream.avail_out = sizeof(fixed_buf);
490 } while (status == Z_OK);
491 if (stream.total_out != size || status != Z_STREAM_END)
492 bad_object(offset, _("inflate returned %d"), status);
493 git_inflate_end(&stream);
494 if (oid)
495 the_hash_algo->final_oid_fn(oid, &c);
496 return buf == fixed_buf ? NULL : buf;
499 static void *unpack_raw_entry(struct object_entry *obj,
500 off_t *ofs_offset,
501 struct object_id *ref_oid,
502 struct object_id *oid)
504 unsigned char *p;
505 unsigned long size, c;
506 off_t base_offset;
507 unsigned shift;
508 void *data;
510 obj->idx.offset = consumed_bytes;
511 input_crc32 = crc32(0, NULL, 0);
513 p = fill(1);
514 c = *p;
515 use(1);
516 obj->type = (c >> 4) & 7;
517 size = (c & 15);
518 shift = 4;
519 while (c & 0x80) {
520 p = fill(1);
521 c = *p;
522 use(1);
523 size += (c & 0x7f) << shift;
524 shift += 7;
526 obj->size = size;
528 switch (obj->type) {
529 case OBJ_REF_DELTA:
530 oidread(ref_oid, fill(the_hash_algo->rawsz));
531 use(the_hash_algo->rawsz);
532 break;
533 case OBJ_OFS_DELTA:
534 p = fill(1);
535 c = *p;
536 use(1);
537 base_offset = c & 127;
538 while (c & 128) {
539 base_offset += 1;
540 if (!base_offset || MSB(base_offset, 7))
541 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
542 p = fill(1);
543 c = *p;
544 use(1);
545 base_offset = (base_offset << 7) + (c & 127);
547 *ofs_offset = obj->idx.offset - base_offset;
548 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
549 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
550 break;
551 case OBJ_COMMIT:
552 case OBJ_TREE:
553 case OBJ_BLOB:
554 case OBJ_TAG:
555 break;
556 default:
557 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
559 obj->hdr_size = consumed_bytes - obj->idx.offset;
561 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, oid);
562 obj->idx.crc32 = input_crc32;
563 return data;
566 static void *unpack_data(struct object_entry *obj,
567 int (*consume)(const unsigned char *, unsigned long, void *),
568 void *cb_data)
570 off_t from = obj[0].idx.offset + obj[0].hdr_size;
571 off_t len = obj[1].idx.offset - from;
572 unsigned char *data, *inbuf;
573 git_zstream stream;
574 int status;
576 data = xmallocz(consume ? 64*1024 : obj->size);
577 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
579 memset(&stream, 0, sizeof(stream));
580 git_inflate_init(&stream);
581 stream.next_out = data;
582 stream.avail_out = consume ? 64*1024 : obj->size;
584 do {
585 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
586 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
587 if (n < 0)
588 die_errno(_("cannot pread pack file"));
589 if (!n)
590 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
591 "premature end of pack file, %"PRIuMAX" bytes missing",
592 len),
593 (uintmax_t)len);
594 from += n;
595 len -= n;
596 stream.next_in = inbuf;
597 stream.avail_in = n;
598 if (!consume)
599 status = git_inflate(&stream, 0);
600 else {
601 do {
602 status = git_inflate(&stream, 0);
603 if (consume(data, stream.next_out - data, cb_data)) {
604 free(inbuf);
605 free(data);
606 return NULL;
608 stream.next_out = data;
609 stream.avail_out = 64*1024;
610 } while (status == Z_OK && stream.avail_in);
612 } while (len && status == Z_OK && !stream.avail_in);
614 /* This has been inflated OK when first encountered, so... */
615 if (status != Z_STREAM_END || stream.total_out != obj->size)
616 die(_("serious inflate inconsistency"));
618 git_inflate_end(&stream);
619 free(inbuf);
620 if (consume) {
621 FREE_AND_NULL(data);
623 return data;
626 static void *get_data_from_pack(struct object_entry *obj)
628 return unpack_data(obj, NULL, NULL);
631 static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
632 enum object_type type1,
633 enum object_type type2)
635 int cmp = type1 - type2;
636 if (cmp)
637 return cmp;
638 return offset1 < offset2 ? -1 :
639 offset1 > offset2 ? 1 :
643 static int find_ofs_delta(const off_t offset)
645 int first = 0, last = nr_ofs_deltas;
647 while (first < last) {
648 int next = first + (last - first) / 2;
649 struct ofs_delta_entry *delta = &ofs_deltas[next];
650 int cmp;
652 cmp = compare_ofs_delta_bases(offset, delta->offset,
653 OBJ_OFS_DELTA,
654 objects[delta->obj_no].type);
655 if (!cmp)
656 return next;
657 if (cmp < 0) {
658 last = next;
659 continue;
661 first = next+1;
663 return -first-1;
666 static void find_ofs_delta_children(off_t offset,
667 int *first_index, int *last_index)
669 int first = find_ofs_delta(offset);
670 int last = first;
671 int end = nr_ofs_deltas - 1;
673 if (first < 0) {
674 *first_index = 0;
675 *last_index = -1;
676 return;
678 while (first > 0 && ofs_deltas[first - 1].offset == offset)
679 --first;
680 while (last < end && ofs_deltas[last + 1].offset == offset)
681 ++last;
682 *first_index = first;
683 *last_index = last;
686 static int compare_ref_delta_bases(const struct object_id *oid1,
687 const struct object_id *oid2,
688 enum object_type type1,
689 enum object_type type2)
691 int cmp = type1 - type2;
692 if (cmp)
693 return cmp;
694 return oidcmp(oid1, oid2);
697 static int find_ref_delta(const struct object_id *oid)
699 int first = 0, last = nr_ref_deltas;
701 while (first < last) {
702 int next = first + (last - first) / 2;
703 struct ref_delta_entry *delta = &ref_deltas[next];
704 int cmp;
706 cmp = compare_ref_delta_bases(oid, &delta->oid,
707 OBJ_REF_DELTA,
708 objects[delta->obj_no].type);
709 if (!cmp)
710 return next;
711 if (cmp < 0) {
712 last = next;
713 continue;
715 first = next+1;
717 return -first-1;
720 static void find_ref_delta_children(const struct object_id *oid,
721 int *first_index, int *last_index)
723 int first = find_ref_delta(oid);
724 int last = first;
725 int end = nr_ref_deltas - 1;
727 if (first < 0) {
728 *first_index = 0;
729 *last_index = -1;
730 return;
732 while (first > 0 && oideq(&ref_deltas[first - 1].oid, oid))
733 --first;
734 while (last < end && oideq(&ref_deltas[last + 1].oid, oid))
735 ++last;
736 *first_index = first;
737 *last_index = last;
740 struct compare_data {
741 struct object_entry *entry;
742 struct git_istream *st;
743 unsigned char *buf;
744 unsigned long buf_size;
747 static int compare_objects(const unsigned char *buf, unsigned long size,
748 void *cb_data)
750 struct compare_data *data = cb_data;
752 if (data->buf_size < size) {
753 free(data->buf);
754 data->buf = xmalloc(size);
755 data->buf_size = size;
758 while (size) {
759 ssize_t len = read_istream(data->st, data->buf, size);
760 if (len == 0)
761 die(_("SHA1 COLLISION FOUND WITH %s !"),
762 oid_to_hex(&data->entry->idx.oid));
763 if (len < 0)
764 die(_("unable to read %s"),
765 oid_to_hex(&data->entry->idx.oid));
766 if (memcmp(buf, data->buf, len))
767 die(_("SHA1 COLLISION FOUND WITH %s !"),
768 oid_to_hex(&data->entry->idx.oid));
769 size -= len;
770 buf += len;
772 return 0;
775 static int check_collison(struct object_entry *entry)
777 struct compare_data data;
778 enum object_type type;
779 unsigned long size;
781 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
782 return -1;
784 memset(&data, 0, sizeof(data));
785 data.entry = entry;
786 data.st = open_istream(the_repository, &entry->idx.oid, &type, &size,
787 NULL);
788 if (!data.st)
789 return -1;
790 if (size != entry->size || type != entry->type)
791 die(_("SHA1 COLLISION FOUND WITH %s !"),
792 oid_to_hex(&entry->idx.oid));
793 unpack_data(entry, compare_objects, &data);
794 close_istream(data.st);
795 free(data.buf);
796 return 0;
799 static void sha1_object(const void *data, struct object_entry *obj_entry,
800 unsigned long size, enum object_type type,
801 const struct object_id *oid)
803 void *new_data = NULL;
804 int collision_test_needed = 0;
806 assert(data || obj_entry);
808 if (startup_info->have_repository) {
809 read_lock();
810 collision_test_needed =
811 repo_has_object_file_with_flags(the_repository, oid,
812 OBJECT_INFO_QUICK);
813 read_unlock();
816 if (collision_test_needed && !data) {
817 read_lock();
818 if (!check_collison(obj_entry))
819 collision_test_needed = 0;
820 read_unlock();
822 if (collision_test_needed) {
823 void *has_data;
824 enum object_type has_type;
825 unsigned long has_size;
826 read_lock();
827 has_type = oid_object_info(the_repository, oid, &has_size);
828 if (has_type < 0)
829 die(_("cannot read existing object info %s"), oid_to_hex(oid));
830 if (has_type != type || has_size != size)
831 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
832 has_data = repo_read_object_file(the_repository, oid,
833 &has_type, &has_size);
834 read_unlock();
835 if (!data)
836 data = new_data = get_data_from_pack(obj_entry);
837 if (!has_data)
838 die(_("cannot read existing object %s"), oid_to_hex(oid));
839 if (size != has_size || type != has_type ||
840 memcmp(data, has_data, size) != 0)
841 die(_("SHA1 COLLISION FOUND WITH %s !"), oid_to_hex(oid));
842 free(has_data);
845 if (strict || do_fsck_object) {
846 read_lock();
847 if (type == OBJ_BLOB) {
848 struct blob *blob = lookup_blob(the_repository, oid);
849 if (blob)
850 blob->object.flags |= FLAG_CHECKED;
851 else
852 die(_("invalid blob object %s"), oid_to_hex(oid));
853 if (do_fsck_object &&
854 fsck_object(&blob->object, (void *)data, size, &fsck_options))
855 die(_("fsck error in packed object"));
856 } else {
857 struct object *obj;
858 int eaten;
859 void *buf = (void *) data;
861 assert(data && "data can only be NULL for large _blobs_");
864 * we do not need to free the memory here, as the
865 * buf is deleted by the caller.
867 obj = parse_object_buffer(the_repository, oid, type,
868 size, buf,
869 &eaten);
870 if (!obj)
871 die(_("invalid %s"), type_name(type));
872 if (do_fsck_object &&
873 fsck_object(obj, buf, size, &fsck_options))
874 die(_("fsck error in packed object"));
875 if (strict && fsck_walk(obj, NULL, &fsck_options))
876 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
878 if (obj->type == OBJ_TREE) {
879 struct tree *item = (struct tree *) obj;
880 item->buffer = NULL;
881 obj->parsed = 0;
883 if (obj->type == OBJ_COMMIT) {
884 struct commit *commit = (struct commit *) obj;
885 if (detach_commit_buffer(commit, NULL) != data)
886 BUG("parse_object_buffer transmogrified our buffer");
888 obj->flags |= FLAG_CHECKED;
890 read_unlock();
893 free(new_data);
897 * Ensure that this node has been reconstructed and return its contents.
899 * In the typical and best case, this node would already be reconstructed
900 * (through the invocation to resolve_delta() in threaded_second_pass()) and it
901 * would not be pruned. However, if pruning of this node was necessary due to
902 * reaching delta_base_cache_limit, this function will find the closest
903 * ancestor with reconstructed data that has not been pruned (or if there is
904 * none, the ultimate base object), and reconstruct each node in the delta
905 * chain in order to generate the reconstructed data for this node.
907 static void *get_base_data(struct base_data *c)
909 if (!c->data) {
910 struct object_entry *obj = c->obj;
911 struct base_data **delta = NULL;
912 int delta_nr = 0, delta_alloc = 0;
914 while (is_delta_type(c->obj->type) && !c->data) {
915 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
916 delta[delta_nr++] = c;
917 c = c->base;
919 if (!delta_nr) {
920 c->data = get_data_from_pack(obj);
921 c->size = obj->size;
922 base_cache_used += c->size;
923 prune_base_data(c);
925 for (; delta_nr > 0; delta_nr--) {
926 void *base, *raw;
927 c = delta[delta_nr - 1];
928 obj = c->obj;
929 base = get_base_data(c->base);
930 raw = get_data_from_pack(obj);
931 c->data = patch_delta(
932 base, c->base->size,
933 raw, obj->size,
934 &c->size);
935 free(raw);
936 if (!c->data)
937 bad_object(obj->idx.offset, _("failed to apply delta"));
938 base_cache_used += c->size;
939 prune_base_data(c);
941 free(delta);
943 return c->data;
946 static struct base_data *make_base(struct object_entry *obj,
947 struct base_data *parent)
949 struct base_data *base = xcalloc(1, sizeof(struct base_data));
950 base->base = parent;
951 base->obj = obj;
952 find_ref_delta_children(&obj->idx.oid,
953 &base->ref_first, &base->ref_last);
954 find_ofs_delta_children(obj->idx.offset,
955 &base->ofs_first, &base->ofs_last);
956 base->children_remaining = base->ref_last - base->ref_first +
957 base->ofs_last - base->ofs_first + 2;
958 return base;
961 static struct base_data *resolve_delta(struct object_entry *delta_obj,
962 struct base_data *base)
964 void *delta_data, *result_data;
965 struct base_data *result;
966 unsigned long result_size;
968 if (show_stat) {
969 int i = delta_obj - objects;
970 int j = base->obj - objects;
971 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
972 deepest_delta_lock();
973 if (deepest_delta < obj_stat[i].delta_depth)
974 deepest_delta = obj_stat[i].delta_depth;
975 deepest_delta_unlock();
976 obj_stat[i].base_object_no = j;
978 delta_data = get_data_from_pack(delta_obj);
979 assert(base->data);
980 result_data = patch_delta(base->data, base->size,
981 delta_data, delta_obj->size, &result_size);
982 free(delta_data);
983 if (!result_data)
984 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
985 hash_object_file(the_hash_algo, result_data, result_size,
986 delta_obj->real_type, &delta_obj->idx.oid);
987 sha1_object(result_data, NULL, result_size, delta_obj->real_type,
988 &delta_obj->idx.oid);
990 result = make_base(delta_obj, base);
991 result->data = result_data;
992 result->size = result_size;
994 counter_lock();
995 nr_resolved_deltas++;
996 counter_unlock();
998 return result;
1001 static int compare_ofs_delta_entry(const void *a, const void *b)
1003 const struct ofs_delta_entry *delta_a = a;
1004 const struct ofs_delta_entry *delta_b = b;
1006 return delta_a->offset < delta_b->offset ? -1 :
1007 delta_a->offset > delta_b->offset ? 1 :
1011 static int compare_ref_delta_entry(const void *a, const void *b)
1013 const struct ref_delta_entry *delta_a = a;
1014 const struct ref_delta_entry *delta_b = b;
1016 return oidcmp(&delta_a->oid, &delta_b->oid);
1019 static void *threaded_second_pass(void *data)
1021 if (data)
1022 set_thread_data(data);
1023 for (;;) {
1024 struct base_data *parent = NULL;
1025 struct object_entry *child_obj;
1026 struct base_data *child;
1028 counter_lock();
1029 display_progress(progress, nr_resolved_deltas);
1030 counter_unlock();
1032 work_lock();
1033 if (list_empty(&work_head)) {
1035 * Take an object from the object array.
1037 while (nr_dispatched < nr_objects &&
1038 is_delta_type(objects[nr_dispatched].type))
1039 nr_dispatched++;
1040 if (nr_dispatched >= nr_objects) {
1041 work_unlock();
1042 break;
1044 child_obj = &objects[nr_dispatched++];
1045 } else {
1047 * Peek at the top of the stack, and take a child from
1048 * it.
1050 parent = list_first_entry(&work_head, struct base_data,
1051 list);
1053 if (parent->ref_first <= parent->ref_last) {
1054 int offset = ref_deltas[parent->ref_first++].obj_no;
1055 child_obj = objects + offset;
1056 if (child_obj->real_type != OBJ_REF_DELTA)
1057 die("REF_DELTA at offset %"PRIuMAX" already resolved (duplicate base %s?)",
1058 (uintmax_t) child_obj->idx.offset,
1059 oid_to_hex(&parent->obj->idx.oid));
1060 child_obj->real_type = parent->obj->real_type;
1061 } else {
1062 child_obj = objects +
1063 ofs_deltas[parent->ofs_first++].obj_no;
1064 assert(child_obj->real_type == OBJ_OFS_DELTA);
1065 child_obj->real_type = parent->obj->real_type;
1068 if (parent->ref_first > parent->ref_last &&
1069 parent->ofs_first > parent->ofs_last) {
1071 * This parent has run out of children, so move
1072 * it to done_head.
1074 list_del(&parent->list);
1075 list_add(&parent->list, &done_head);
1079 * Ensure that the parent has data, since we will need
1080 * it later.
1082 * NEEDSWORK: If parent data needs to be reloaded, this
1083 * prolongs the time that the current thread spends in
1084 * the mutex. A mitigating factor is that parent data
1085 * needs to be reloaded only if the delta base cache
1086 * limit is exceeded, so in the typical case, this does
1087 * not happen.
1089 get_base_data(parent);
1090 parent->retain_data++;
1092 work_unlock();
1094 if (parent) {
1095 child = resolve_delta(child_obj, parent);
1096 if (!child->children_remaining)
1097 FREE_AND_NULL(child->data);
1098 } else {
1099 child = make_base(child_obj, NULL);
1100 if (child->children_remaining) {
1102 * Since this child has its own delta children,
1103 * we will need this data in the future.
1104 * Inflate now so that future iterations will
1105 * have access to this object's data while
1106 * outside the work mutex.
1108 child->data = get_data_from_pack(child_obj);
1109 child->size = child_obj->size;
1113 work_lock();
1114 if (parent)
1115 parent->retain_data--;
1116 if (child->data) {
1118 * This child has its own children, so add it to
1119 * work_head.
1121 list_add(&child->list, &work_head);
1122 base_cache_used += child->size;
1123 prune_base_data(NULL);
1124 free_base_data(child);
1125 } else {
1127 * This child does not have its own children. It may be
1128 * the last descendant of its ancestors; free those
1129 * that we can.
1131 struct base_data *p = parent;
1133 while (p) {
1134 struct base_data *next_p;
1136 p->children_remaining--;
1137 if (p->children_remaining)
1138 break;
1140 next_p = p->base;
1141 free_base_data(p);
1142 list_del(&p->list);
1143 free(p);
1145 p = next_p;
1147 FREE_AND_NULL(child);
1149 work_unlock();
1151 return NULL;
1155 * First pass:
1156 * - find locations of all objects;
1157 * - calculate SHA1 of all non-delta objects;
1158 * - remember base (SHA1 or offset) for all deltas.
1160 static void parse_pack_objects(unsigned char *hash)
1162 int i, nr_delays = 0;
1163 struct ofs_delta_entry *ofs_delta = ofs_deltas;
1164 struct object_id ref_delta_oid;
1165 struct stat st;
1167 if (verbose)
1168 progress = start_progress(
1169 progress_title ? progress_title :
1170 from_stdin ? _("Receiving objects") : _("Indexing objects"),
1171 nr_objects);
1172 for (i = 0; i < nr_objects; i++) {
1173 struct object_entry *obj = &objects[i];
1174 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
1175 &ref_delta_oid,
1176 &obj->idx.oid);
1177 obj->real_type = obj->type;
1178 if (obj->type == OBJ_OFS_DELTA) {
1179 nr_ofs_deltas++;
1180 ofs_delta->obj_no = i;
1181 ofs_delta++;
1182 } else if (obj->type == OBJ_REF_DELTA) {
1183 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
1184 oidcpy(&ref_deltas[nr_ref_deltas].oid, &ref_delta_oid);
1185 ref_deltas[nr_ref_deltas].obj_no = i;
1186 nr_ref_deltas++;
1187 } else if (!data) {
1188 /* large blobs, check later */
1189 obj->real_type = OBJ_BAD;
1190 nr_delays++;
1191 } else
1192 sha1_object(data, NULL, obj->size, obj->type,
1193 &obj->idx.oid);
1194 free(data);
1195 display_progress(progress, i+1);
1197 objects[i].idx.offset = consumed_bytes;
1198 stop_progress(&progress);
1200 /* Check pack integrity */
1201 flush();
1202 the_hash_algo->final_fn(hash, &input_ctx);
1203 if (!hasheq(fill(the_hash_algo->rawsz), hash))
1204 die(_("pack is corrupted (SHA1 mismatch)"));
1205 use(the_hash_algo->rawsz);
1207 /* If input_fd is a file, we should have reached its end now. */
1208 if (fstat(input_fd, &st))
1209 die_errno(_("cannot fstat packfile"));
1210 if (S_ISREG(st.st_mode) &&
1211 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
1212 die(_("pack has junk at the end"));
1214 for (i = 0; i < nr_objects; i++) {
1215 struct object_entry *obj = &objects[i];
1216 if (obj->real_type != OBJ_BAD)
1217 continue;
1218 obj->real_type = obj->type;
1219 sha1_object(NULL, obj, obj->size, obj->type,
1220 &obj->idx.oid);
1221 nr_delays--;
1223 if (nr_delays)
1224 die(_("confusion beyond insanity in parse_pack_objects()"));
1228 * Second pass:
1229 * - for all non-delta objects, look if it is used as a base for
1230 * deltas;
1231 * - if used as a base, uncompress the object and apply all deltas,
1232 * recursively checking if the resulting object is used as a base
1233 * for some more deltas.
1235 static void resolve_deltas(void)
1237 int i;
1239 if (!nr_ofs_deltas && !nr_ref_deltas)
1240 return;
1242 /* Sort deltas by base SHA1/offset for fast searching */
1243 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1244 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
1246 if (verbose || show_resolving_progress)
1247 progress = start_progress(_("Resolving deltas"),
1248 nr_ref_deltas + nr_ofs_deltas);
1250 nr_dispatched = 0;
1251 base_cache_limit = delta_base_cache_limit * nr_threads;
1252 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1253 init_thread();
1254 for (i = 0; i < nr_threads; i++) {
1255 int ret = pthread_create(&thread_data[i].thread, NULL,
1256 threaded_second_pass, thread_data + i);
1257 if (ret)
1258 die(_("unable to create thread: %s"),
1259 strerror(ret));
1261 for (i = 0; i < nr_threads; i++)
1262 pthread_join(thread_data[i].thread, NULL);
1263 cleanup_thread();
1264 return;
1266 threaded_second_pass(&nothread_data);
1270 * Third pass:
1271 * - append objects to convert thin pack to full pack if required
1272 * - write the final pack hash
1274 static void fix_unresolved_deltas(struct hashfile *f);
1275 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_hash)
1277 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
1278 stop_progress(&progress);
1279 /* Flush remaining pack final hash. */
1280 flush();
1281 return;
1284 if (fix_thin_pack) {
1285 struct hashfile *f;
1286 unsigned char read_hash[GIT_MAX_RAWSZ], tail_hash[GIT_MAX_RAWSZ];
1287 struct strbuf msg = STRBUF_INIT;
1288 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
1289 int nr_objects_initial = nr_objects;
1290 if (nr_unresolved <= 0)
1291 die(_("confusion beyond insanity"));
1292 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
1293 memset(objects + nr_objects + 1, 0,
1294 nr_unresolved * sizeof(*objects));
1295 f = hashfd(output_fd, curr_pack);
1296 fix_unresolved_deltas(f);
1297 strbuf_addf(&msg, Q_("completed with %d local object",
1298 "completed with %d local objects",
1299 nr_objects - nr_objects_initial),
1300 nr_objects - nr_objects_initial);
1301 stop_progress_msg(&progress, msg.buf);
1302 strbuf_release(&msg);
1303 finalize_hashfile(f, tail_hash, FSYNC_COMPONENT_PACK, 0);
1304 hashcpy(read_hash, pack_hash);
1305 fixup_pack_header_footer(output_fd, pack_hash,
1306 curr_pack, nr_objects,
1307 read_hash, consumed_bytes-the_hash_algo->rawsz);
1308 if (!hasheq(read_hash, tail_hash))
1309 die(_("Unexpected tail checksum for %s "
1310 "(disk corruption?)"), curr_pack);
1312 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
1313 die(Q_("pack has %d unresolved delta",
1314 "pack has %d unresolved deltas",
1315 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1316 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
1319 static int write_compressed(struct hashfile *f, void *in, unsigned int size)
1321 git_zstream stream;
1322 int status;
1323 unsigned char outbuf[4096];
1325 git_deflate_init(&stream, zlib_compression_level);
1326 stream.next_in = in;
1327 stream.avail_in = size;
1329 do {
1330 stream.next_out = outbuf;
1331 stream.avail_out = sizeof(outbuf);
1332 status = git_deflate(&stream, Z_FINISH);
1333 hashwrite(f, outbuf, sizeof(outbuf) - stream.avail_out);
1334 } while (status == Z_OK);
1336 if (status != Z_STREAM_END)
1337 die(_("unable to deflate appended object (%d)"), status);
1338 size = stream.total_out;
1339 git_deflate_end(&stream);
1340 return size;
1343 static struct object_entry *append_obj_to_pack(struct hashfile *f,
1344 const unsigned char *sha1, void *buf,
1345 unsigned long size, enum object_type type)
1347 struct object_entry *obj = &objects[nr_objects++];
1348 unsigned char header[10];
1349 unsigned long s = size;
1350 int n = 0;
1351 unsigned char c = (type << 4) | (s & 15);
1352 s >>= 4;
1353 while (s) {
1354 header[n++] = c | 0x80;
1355 c = s & 0x7f;
1356 s >>= 7;
1358 header[n++] = c;
1359 crc32_begin(f);
1360 hashwrite(f, header, n);
1361 obj[0].size = size;
1362 obj[0].hdr_size = n;
1363 obj[0].type = type;
1364 obj[0].real_type = type;
1365 obj[1].idx.offset = obj[0].idx.offset + n;
1366 obj[1].idx.offset += write_compressed(f, buf, size);
1367 obj[0].idx.crc32 = crc32_end(f);
1368 hashflush(f);
1369 oidread(&obj->idx.oid, sha1);
1370 return obj;
1373 static int delta_pos_compare(const void *_a, const void *_b)
1375 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1376 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
1377 return a->obj_no - b->obj_no;
1380 static void fix_unresolved_deltas(struct hashfile *f)
1382 struct ref_delta_entry **sorted_by_pos;
1383 int i;
1386 * Since many unresolved deltas may well be themselves base objects
1387 * for more unresolved deltas, we really want to include the
1388 * smallest number of base objects that would cover as much delta
1389 * as possible by picking the
1390 * trunc deltas first, allowing for other deltas to resolve without
1391 * additional base objects. Since most base objects are to be found
1392 * before deltas depending on them, a good heuristic is to start
1393 * resolving deltas in the same order as their position in the pack.
1395 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
1396 for (i = 0; i < nr_ref_deltas; i++)
1397 sorted_by_pos[i] = &ref_deltas[i];
1398 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
1400 if (repo_has_promisor_remote(the_repository)) {
1402 * Prefetch the delta bases.
1404 struct oid_array to_fetch = OID_ARRAY_INIT;
1405 for (i = 0; i < nr_ref_deltas; i++) {
1406 struct ref_delta_entry *d = sorted_by_pos[i];
1407 if (!oid_object_info_extended(the_repository, &d->oid,
1408 NULL,
1409 OBJECT_INFO_FOR_PREFETCH))
1410 continue;
1411 oid_array_append(&to_fetch, &d->oid);
1413 promisor_remote_get_direct(the_repository,
1414 to_fetch.oid, to_fetch.nr);
1415 oid_array_clear(&to_fetch);
1418 for (i = 0; i < nr_ref_deltas; i++) {
1419 struct ref_delta_entry *d = sorted_by_pos[i];
1420 enum object_type type;
1421 void *data;
1422 unsigned long size;
1424 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1425 continue;
1426 data = repo_read_object_file(the_repository, &d->oid, &type,
1427 &size);
1428 if (!data)
1429 continue;
1431 if (check_object_signature(the_repository, &d->oid, data, size,
1432 type) < 0)
1433 die(_("local object %s is corrupt"), oid_to_hex(&d->oid));
1436 * Add this as an object to the objects array and call
1437 * threaded_second_pass() (which will pick up the added
1438 * object).
1440 append_obj_to_pack(f, d->oid.hash, data, size, type);
1441 free(data);
1442 threaded_second_pass(NULL);
1444 display_progress(progress, nr_resolved_deltas);
1446 free(sorted_by_pos);
1449 static const char *derive_filename(const char *pack_name, const char *strip,
1450 const char *suffix, struct strbuf *buf)
1452 size_t len;
1453 if (!strip_suffix(pack_name, strip, &len) || !len ||
1454 pack_name[len - 1] != '.')
1455 die(_("packfile name '%s' does not end with '.%s'"),
1456 pack_name, strip);
1457 strbuf_add(buf, pack_name, len);
1458 strbuf_addstr(buf, suffix);
1459 return buf->buf;
1462 static void write_special_file(const char *suffix, const char *msg,
1463 const char *pack_name, const unsigned char *hash,
1464 const char **report)
1466 struct strbuf name_buf = STRBUF_INIT;
1467 const char *filename;
1468 int fd;
1469 int msg_len = strlen(msg);
1471 if (pack_name)
1472 filename = derive_filename(pack_name, "pack", suffix, &name_buf);
1473 else
1474 filename = odb_pack_name(&name_buf, hash, suffix);
1476 fd = odb_pack_keep(filename);
1477 if (fd < 0) {
1478 if (errno != EEXIST)
1479 die_errno(_("cannot write %s file '%s'"),
1480 suffix, filename);
1481 } else {
1482 if (msg_len > 0) {
1483 write_or_die(fd, msg, msg_len);
1484 write_or_die(fd, "\n", 1);
1486 if (close(fd) != 0)
1487 die_errno(_("cannot close written %s file '%s'"),
1488 suffix, filename);
1489 if (report)
1490 *report = suffix;
1492 strbuf_release(&name_buf);
1495 static void rename_tmp_packfile(const char **final_name,
1496 const char *curr_name,
1497 struct strbuf *name, unsigned char *hash,
1498 const char *ext, int make_read_only_if_same)
1500 if (*final_name != curr_name) {
1501 if (!*final_name)
1502 *final_name = odb_pack_name(name, hash, ext);
1503 if (finalize_object_file(curr_name, *final_name))
1504 die(_("unable to rename temporary '*.%s' file to '%s'"),
1505 ext, *final_name);
1506 } else if (make_read_only_if_same) {
1507 chmod(*final_name, 0444);
1511 static void final(const char *final_pack_name, const char *curr_pack_name,
1512 const char *final_index_name, const char *curr_index_name,
1513 const char *final_rev_index_name, const char *curr_rev_index_name,
1514 const char *keep_msg, const char *promisor_msg,
1515 unsigned char *hash)
1517 const char *report = "pack";
1518 struct strbuf pack_name = STRBUF_INIT;
1519 struct strbuf index_name = STRBUF_INIT;
1520 struct strbuf rev_index_name = STRBUF_INIT;
1521 int err;
1523 if (!from_stdin) {
1524 close(input_fd);
1525 } else {
1526 fsync_component_or_die(FSYNC_COMPONENT_PACK, output_fd, curr_pack_name);
1527 err = close(output_fd);
1528 if (err)
1529 die_errno(_("error while closing pack file"));
1532 if (keep_msg)
1533 write_special_file("keep", keep_msg, final_pack_name, hash,
1534 &report);
1535 if (promisor_msg)
1536 write_special_file("promisor", promisor_msg, final_pack_name,
1537 hash, NULL);
1539 rename_tmp_packfile(&final_pack_name, curr_pack_name, &pack_name,
1540 hash, "pack", from_stdin);
1541 if (curr_rev_index_name)
1542 rename_tmp_packfile(&final_rev_index_name, curr_rev_index_name,
1543 &rev_index_name, hash, "rev", 1);
1544 rename_tmp_packfile(&final_index_name, curr_index_name, &index_name,
1545 hash, "idx", 1);
1547 if (do_fsck_object) {
1548 struct packed_git *p;
1549 p = add_packed_git(final_index_name, strlen(final_index_name), 0);
1550 if (p)
1551 install_packed_git(the_repository, p);
1554 if (!from_stdin) {
1555 printf("%s\n", hash_to_hex(hash));
1556 } else {
1557 struct strbuf buf = STRBUF_INIT;
1559 strbuf_addf(&buf, "%s\t%s\n", report, hash_to_hex(hash));
1560 write_or_die(1, buf.buf, buf.len);
1561 strbuf_release(&buf);
1564 * Let's just mimic git-unpack-objects here and write
1565 * the last part of the input buffer to stdout.
1567 while (input_len) {
1568 err = xwrite(1, input_buffer + input_offset, input_len);
1569 if (err <= 0)
1570 break;
1571 input_len -= err;
1572 input_offset += err;
1576 strbuf_release(&rev_index_name);
1577 strbuf_release(&index_name);
1578 strbuf_release(&pack_name);
1581 static int git_index_pack_config(const char *k, const char *v, void *cb)
1583 struct pack_idx_option *opts = cb;
1585 if (!strcmp(k, "pack.indexversion")) {
1586 opts->version = git_config_int(k, v);
1587 if (opts->version > 2)
1588 die(_("bad pack.indexVersion=%"PRIu32), opts->version);
1589 return 0;
1591 if (!strcmp(k, "pack.threads")) {
1592 nr_threads = git_config_int(k, v);
1593 if (nr_threads < 0)
1594 die(_("invalid number of threads specified (%d)"),
1595 nr_threads);
1596 if (!HAVE_THREADS && nr_threads != 1) {
1597 warning(_("no threads support, ignoring %s"), k);
1598 nr_threads = 1;
1600 return 0;
1602 if (!strcmp(k, "pack.writereverseindex")) {
1603 if (git_config_bool(k, v))
1604 opts->flags |= WRITE_REV;
1605 else
1606 opts->flags &= ~WRITE_REV;
1608 return git_default_config(k, v, cb);
1611 static int cmp_uint32(const void *a_, const void *b_)
1613 uint32_t a = *((uint32_t *)a_);
1614 uint32_t b = *((uint32_t *)b_);
1616 return (a < b) ? -1 : (a != b);
1619 static void read_v2_anomalous_offsets(struct packed_git *p,
1620 struct pack_idx_option *opts)
1622 const uint32_t *idx1, *idx2;
1623 uint32_t i;
1625 /* The address of the 4-byte offset table */
1626 idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
1627 + (size_t)p->num_objects /* CRC32 table */
1630 /* The address of the 8-byte offset table */
1631 idx2 = idx1 + p->num_objects;
1633 for (i = 0; i < p->num_objects; i++) {
1634 uint32_t off = ntohl(idx1[i]);
1635 if (!(off & 0x80000000))
1636 continue;
1637 off = off & 0x7fffffff;
1638 check_pack_index_ptr(p, &idx2[off * 2]);
1639 if (idx2[off * 2])
1640 continue;
1642 * The real offset is ntohl(idx2[off * 2]) in high 4
1643 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1644 * octets. But idx2[off * 2] is Zero!!!
1646 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1647 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1650 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
1653 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1655 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1657 if (!p)
1658 die(_("Cannot open existing pack file '%s'"), pack_name);
1659 if (open_pack_index(p))
1660 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1662 /* Read the attributes from the existing idx file */
1663 opts->version = p->index_version;
1665 if (opts->version == 2)
1666 read_v2_anomalous_offsets(p, opts);
1669 * Get rid of the idx file as we do not need it anymore.
1670 * NEEDSWORK: extract this bit from free_pack_by_name() in
1671 * object-file.c, perhaps? It shouldn't matter very much as we
1672 * know we haven't installed this pack (hence we never have
1673 * read anything from it).
1675 close_pack_index(p);
1676 free(p);
1679 static void show_pack_info(int stat_only)
1681 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
1682 unsigned long *chain_histogram = NULL;
1684 if (deepest_delta)
1685 CALLOC_ARRAY(chain_histogram, deepest_delta);
1687 for (i = 0; i < nr_objects; i++) {
1688 struct object_entry *obj = &objects[i];
1690 if (is_delta_type(obj->type))
1691 chain_histogram[obj_stat[i].delta_depth - 1]++;
1692 if (stat_only)
1693 continue;
1694 printf("%s %-6s %"PRIuMAX" %"PRIuMAX" %"PRIuMAX,
1695 oid_to_hex(&obj->idx.oid),
1696 type_name(obj->real_type), (uintmax_t)obj->size,
1697 (uintmax_t)(obj[1].idx.offset - obj->idx.offset),
1698 (uintmax_t)obj->idx.offset);
1699 if (is_delta_type(obj->type)) {
1700 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
1701 printf(" %u %s", obj_stat[i].delta_depth,
1702 oid_to_hex(&bobj->idx.oid));
1704 putchar('\n');
1707 if (baseobjects)
1708 printf_ln(Q_("non delta: %d object",
1709 "non delta: %d objects",
1710 baseobjects),
1711 baseobjects);
1712 for (i = 0; i < deepest_delta; i++) {
1713 if (!chain_histogram[i])
1714 continue;
1715 printf_ln(Q_("chain length = %d: %lu object",
1716 "chain length = %d: %lu objects",
1717 chain_histogram[i]),
1718 i + 1,
1719 chain_histogram[i]);
1721 free(chain_histogram);
1724 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1726 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, rev_index;
1727 const char *curr_index;
1728 const char *curr_rev_index = NULL;
1729 const char *index_name = NULL, *pack_name = NULL, *rev_index_name = NULL;
1730 const char *keep_msg = NULL;
1731 const char *promisor_msg = NULL;
1732 struct strbuf index_name_buf = STRBUF_INIT;
1733 struct strbuf rev_index_name_buf = STRBUF_INIT;
1734 struct pack_idx_entry **idx_objects;
1735 struct pack_idx_option opts;
1736 unsigned char pack_hash[GIT_MAX_RAWSZ];
1737 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
1738 int report_end_of_input = 0;
1739 int hash_algo = 0;
1742 * index-pack never needs to fetch missing objects except when
1743 * REF_DELTA bases are missing (which are explicitly handled). It only
1744 * accesses the repo to do hash collision checks and to check which
1745 * REF_DELTA bases need to be fetched.
1747 fetch_if_missing = 0;
1749 if (argc == 2 && !strcmp(argv[1], "-h"))
1750 usage(index_pack_usage);
1752 read_replace_refs = 0;
1753 fsck_options.walk = mark_link;
1755 reset_pack_idx_option(&opts);
1756 git_config(git_index_pack_config, &opts);
1757 if (prefix && chdir(prefix))
1758 die(_("Cannot come back to cwd"));
1760 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
1761 rev_index = 1;
1762 else
1763 rev_index = !!(opts.flags & (WRITE_REV_VERIFY | WRITE_REV));
1765 for (i = 1; i < argc; i++) {
1766 const char *arg = argv[i];
1768 if (*arg == '-') {
1769 if (!strcmp(arg, "--stdin")) {
1770 from_stdin = 1;
1771 } else if (!strcmp(arg, "--fix-thin")) {
1772 fix_thin_pack = 1;
1773 } else if (skip_to_optional_arg(arg, "--strict", &arg)) {
1774 strict = 1;
1775 do_fsck_object = 1;
1776 fsck_set_msg_types(&fsck_options, arg);
1777 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1778 strict = 1;
1779 check_self_contained_and_connected = 1;
1780 } else if (!strcmp(arg, "--fsck-objects")) {
1781 do_fsck_object = 1;
1782 } else if (!strcmp(arg, "--verify")) {
1783 verify = 1;
1784 } else if (!strcmp(arg, "--verify-stat")) {
1785 verify = 1;
1786 show_stat = 1;
1787 } else if (!strcmp(arg, "--verify-stat-only")) {
1788 verify = 1;
1789 show_stat = 1;
1790 stat_only = 1;
1791 } else if (skip_to_optional_arg(arg, "--keep", &keep_msg)) {
1792 ; /* nothing to do */
1793 } else if (skip_to_optional_arg(arg, "--promisor", &promisor_msg)) {
1794 ; /* already parsed */
1795 } else if (starts_with(arg, "--threads=")) {
1796 char *end;
1797 nr_threads = strtoul(arg+10, &end, 0);
1798 if (!arg[10] || *end || nr_threads < 0)
1799 usage(index_pack_usage);
1800 if (!HAVE_THREADS && nr_threads != 1) {
1801 warning(_("no threads support, ignoring %s"), arg);
1802 nr_threads = 1;
1804 } else if (starts_with(arg, "--pack_header=")) {
1805 struct pack_header *hdr;
1806 char *c;
1808 hdr = (struct pack_header *)input_buffer;
1809 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1810 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1811 if (*c != ',')
1812 die(_("bad %s"), arg);
1813 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1814 if (*c)
1815 die(_("bad %s"), arg);
1816 input_len = sizeof(*hdr);
1817 } else if (!strcmp(arg, "-v")) {
1818 verbose = 1;
1819 } else if (!strcmp(arg, "--progress-title")) {
1820 if (progress_title || (i+1) >= argc)
1821 usage(index_pack_usage);
1822 progress_title = argv[++i];
1823 } else if (!strcmp(arg, "--show-resolving-progress")) {
1824 show_resolving_progress = 1;
1825 } else if (!strcmp(arg, "--report-end-of-input")) {
1826 report_end_of_input = 1;
1827 } else if (!strcmp(arg, "-o")) {
1828 if (index_name || (i+1) >= argc)
1829 usage(index_pack_usage);
1830 index_name = argv[++i];
1831 } else if (starts_with(arg, "--index-version=")) {
1832 char *c;
1833 opts.version = strtoul(arg + 16, &c, 10);
1834 if (opts.version > 2)
1835 die(_("bad %s"), arg);
1836 if (*c == ',')
1837 opts.off32_limit = strtoul(c+1, &c, 0);
1838 if (*c || opts.off32_limit & 0x80000000)
1839 die(_("bad %s"), arg);
1840 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1841 max_input_size = strtoumax(arg, NULL, 10);
1842 } else if (skip_prefix(arg, "--object-format=", &arg)) {
1843 hash_algo = hash_algo_by_name(arg);
1844 if (hash_algo == GIT_HASH_UNKNOWN)
1845 die(_("unknown hash algorithm '%s'"), arg);
1846 repo_set_hash_algo(the_repository, hash_algo);
1847 } else if (!strcmp(arg, "--rev-index")) {
1848 rev_index = 1;
1849 } else if (!strcmp(arg, "--no-rev-index")) {
1850 rev_index = 0;
1851 } else
1852 usage(index_pack_usage);
1853 continue;
1856 if (pack_name)
1857 usage(index_pack_usage);
1858 pack_name = arg;
1861 if (!pack_name && !from_stdin)
1862 usage(index_pack_usage);
1863 if (fix_thin_pack && !from_stdin)
1864 die(_("the option '%s' requires '%s'"), "--fix-thin", "--stdin");
1865 if (from_stdin && !startup_info->have_repository)
1866 die(_("--stdin requires a git repository"));
1867 if (from_stdin && hash_algo)
1868 die(_("options '%s' and '%s' cannot be used together"), "--object-format", "--stdin");
1869 if (!index_name && pack_name)
1870 index_name = derive_filename(pack_name, "pack", "idx", &index_name_buf);
1872 opts.flags &= ~(WRITE_REV | WRITE_REV_VERIFY);
1873 if (rev_index) {
1874 opts.flags |= verify ? WRITE_REV_VERIFY : WRITE_REV;
1875 if (index_name)
1876 rev_index_name = derive_filename(index_name,
1877 "idx", "rev",
1878 &rev_index_name_buf);
1881 if (verify) {
1882 if (!index_name)
1883 die(_("--verify with no packfile name given"));
1884 read_idx_option(&opts, index_name);
1885 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1887 if (strict)
1888 opts.flags |= WRITE_IDX_STRICT;
1890 if (HAVE_THREADS && !nr_threads) {
1891 nr_threads = online_cpus();
1893 * Experiments show that going above 20 threads doesn't help,
1894 * no matter how many cores you have. Below that, we tend to
1895 * max at half the number of online_cpus(), presumably because
1896 * half of those are hyperthreads rather than full cores. We'll
1897 * never reduce the level below "3", though, to match a
1898 * historical value that nobody complained about.
1900 if (nr_threads < 4)
1901 ; /* too few cores to consider capping */
1902 else if (nr_threads < 6)
1903 nr_threads = 3; /* historic cap */
1904 else if (nr_threads < 40)
1905 nr_threads /= 2;
1906 else
1907 nr_threads = 20; /* hard cap */
1910 curr_pack = open_pack_file(pack_name);
1911 parse_pack_header();
1912 CALLOC_ARRAY(objects, st_add(nr_objects, 1));
1913 if (show_stat)
1914 CALLOC_ARRAY(obj_stat, st_add(nr_objects, 1));
1915 CALLOC_ARRAY(ofs_deltas, nr_objects);
1916 parse_pack_objects(pack_hash);
1917 if (report_end_of_input)
1918 write_in_full(2, "\0", 1);
1919 resolve_deltas();
1920 conclude_pack(fix_thin_pack, curr_pack, pack_hash);
1921 free(ofs_deltas);
1922 free(ref_deltas);
1923 if (strict)
1924 foreign_nr = check_objects();
1926 if (show_stat)
1927 show_pack_info(stat_only);
1929 ALLOC_ARRAY(idx_objects, nr_objects);
1930 for (i = 0; i < nr_objects; i++)
1931 idx_objects[i] = &objects[i].idx;
1932 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_hash);
1933 if (rev_index)
1934 curr_rev_index = write_rev_file(rev_index_name, idx_objects,
1935 nr_objects, pack_hash,
1936 opts.flags);
1937 free(idx_objects);
1939 if (!verify)
1940 final(pack_name, curr_pack,
1941 index_name, curr_index,
1942 rev_index_name, curr_rev_index,
1943 keep_msg, promisor_msg,
1944 pack_hash);
1945 else
1946 close(input_fd);
1948 if (do_fsck_object && fsck_finish(&fsck_options))
1949 die(_("fsck error in pack objects"));
1951 free(opts.anomaly);
1952 free(objects);
1953 strbuf_release(&index_name_buf);
1954 strbuf_release(&rev_index_name_buf);
1955 if (!pack_name)
1956 free((void *) curr_pack);
1957 if (!index_name)
1958 free((void *) curr_index);
1959 if (!rev_index_name)
1960 free((void *) curr_rev_index);
1963 * Let the caller know this pack is not self contained
1965 if (check_self_contained_and_connected && foreign_nr)
1966 return 1;
1968 return 0;