index-pack: support multithreaded delta resolving
[git/jrn.git] / builtin / index-pack.c
blobd4685c50d7b4a4fec0c210725689d4d72029bda5
1 #include "builtin.h"
2 #include "delta.h"
3 #include "pack.h"
4 #include "csum-file.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "progress.h"
10 #include "fsck.h"
11 #include "exec_cmd.h"
12 #include "thread-utils.h"
14 static const char index_pack_usage[] =
15 "git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
17 struct object_entry {
18 struct pack_idx_entry idx;
19 unsigned long size;
20 unsigned int hdr_size;
21 enum object_type type;
22 enum object_type real_type;
23 unsigned delta_depth;
24 int base_object_no;
27 union delta_base {
28 unsigned char sha1[20];
29 off_t offset;
32 struct base_data {
33 struct base_data *base;
34 struct base_data *child;
35 struct object_entry *obj;
36 void *data;
37 unsigned long size;
38 int ref_first, ref_last;
39 int ofs_first, ofs_last;
42 struct thread_local {
43 #ifndef NO_PTHREADS
44 pthread_t thread;
45 #endif
46 struct base_data *base_cache;
47 size_t base_cache_used;
51 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
52 * to memcmp() only the first 20 bytes.
54 #define UNION_BASE_SZ 20
56 #define FLAG_LINK (1u<<20)
57 #define FLAG_CHECKED (1u<<21)
59 struct delta_entry {
60 union delta_base base;
61 int obj_no;
64 static struct object_entry *objects;
65 static struct delta_entry *deltas;
66 static struct thread_local nothread_data;
67 static int nr_objects;
68 static int nr_deltas;
69 static int nr_resolved_deltas;
70 static int nr_threads;
72 static int from_stdin;
73 static int strict;
74 static int verbose;
76 static struct progress *progress;
78 /* We always read in 4kB chunks. */
79 static unsigned char input_buffer[4096];
80 static unsigned int input_offset, input_len;
81 static off_t consumed_bytes;
82 static unsigned deepest_delta;
83 static git_SHA_CTX input_ctx;
84 static uint32_t input_crc32;
85 static int input_fd, output_fd, pack_fd;
87 #ifndef NO_PTHREADS
89 static struct thread_local *thread_data;
90 static int nr_dispatched;
91 static int threads_active;
93 static pthread_mutex_t read_mutex;
94 #define read_lock() lock_mutex(&read_mutex)
95 #define read_unlock() unlock_mutex(&read_mutex)
97 static pthread_mutex_t counter_mutex;
98 #define counter_lock() lock_mutex(&counter_mutex)
99 #define counter_unlock() unlock_mutex(&counter_mutex)
101 static pthread_mutex_t work_mutex;
102 #define work_lock() lock_mutex(&work_mutex)
103 #define work_unlock() unlock_mutex(&work_mutex)
105 static pthread_key_t key;
107 static inline void lock_mutex(pthread_mutex_t *mutex)
109 if (threads_active)
110 pthread_mutex_lock(mutex);
113 static inline void unlock_mutex(pthread_mutex_t *mutex)
115 if (threads_active)
116 pthread_mutex_unlock(mutex);
120 * Mutex and conditional variable can't be statically-initialized on Windows.
122 static void init_thread(void)
124 init_recursive_mutex(&read_mutex);
125 pthread_mutex_init(&counter_mutex, NULL);
126 pthread_mutex_init(&work_mutex, NULL);
127 pthread_key_create(&key, NULL);
128 thread_data = xcalloc(nr_threads, sizeof(*thread_data));
129 threads_active = 1;
132 static void cleanup_thread(void)
134 if (!threads_active)
135 return;
136 threads_active = 0;
137 pthread_mutex_destroy(&read_mutex);
138 pthread_mutex_destroy(&counter_mutex);
139 pthread_mutex_destroy(&work_mutex);
140 pthread_key_delete(key);
141 free(thread_data);
144 #else
146 #define read_lock()
147 #define read_unlock()
149 #define counter_lock()
150 #define counter_unlock()
152 #define work_lock()
153 #define work_unlock()
155 #endif
158 static int mark_link(struct object *obj, int type, void *data)
160 if (!obj)
161 return -1;
163 if (type != OBJ_ANY && obj->type != type)
164 die("object type mismatch at %s", sha1_to_hex(obj->sha1));
166 obj->flags |= FLAG_LINK;
167 return 0;
170 /* The content of each linked object must have been checked
171 or it must be already present in the object database */
172 static void check_object(struct object *obj)
174 if (!obj)
175 return;
177 if (!(obj->flags & FLAG_LINK))
178 return;
180 if (!(obj->flags & FLAG_CHECKED)) {
181 unsigned long size;
182 int type = sha1_object_info(obj->sha1, &size);
183 if (type != obj->type || type <= 0)
184 die("object of unexpected type");
185 obj->flags |= FLAG_CHECKED;
186 return;
190 static void check_objects(void)
192 unsigned i, max;
194 max = get_max_object_index();
195 for (i = 0; i < max; i++)
196 check_object(get_indexed_object(i));
200 /* Discard current buffer used content. */
201 static void flush(void)
203 if (input_offset) {
204 if (output_fd >= 0)
205 write_or_die(output_fd, input_buffer, input_offset);
206 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
207 memmove(input_buffer, input_buffer + input_offset, input_len);
208 input_offset = 0;
213 * Make sure at least "min" bytes are available in the buffer, and
214 * return the pointer to the buffer.
216 static void *fill(int min)
218 if (min <= input_len)
219 return input_buffer + input_offset;
220 if (min > sizeof(input_buffer))
221 die("cannot fill %d bytes", min);
222 flush();
223 do {
224 ssize_t ret = xread(input_fd, input_buffer + input_len,
225 sizeof(input_buffer) - input_len);
226 if (ret <= 0) {
227 if (!ret)
228 die("early EOF");
229 die_errno("read error on input");
231 input_len += ret;
232 if (from_stdin)
233 display_throughput(progress, consumed_bytes + input_len);
234 } while (input_len < min);
235 return input_buffer;
238 static void use(int bytes)
240 if (bytes > input_len)
241 die("used more bytes than were available");
242 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
243 input_len -= bytes;
244 input_offset += bytes;
246 /* make sure off_t is sufficiently large not to wrap */
247 if (signed_add_overflows(consumed_bytes, bytes))
248 die("pack too large for current definition of off_t");
249 consumed_bytes += bytes;
252 static const char *open_pack_file(const char *pack_name)
254 if (from_stdin) {
255 input_fd = 0;
256 if (!pack_name) {
257 static char tmp_file[PATH_MAX];
258 output_fd = odb_mkstemp(tmp_file, sizeof(tmp_file),
259 "pack/tmp_pack_XXXXXX");
260 pack_name = xstrdup(tmp_file);
261 } else
262 output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
263 if (output_fd < 0)
264 die_errno("unable to create '%s'", pack_name);
265 pack_fd = output_fd;
266 } else {
267 input_fd = open(pack_name, O_RDONLY);
268 if (input_fd < 0)
269 die_errno("cannot open packfile '%s'", pack_name);
270 output_fd = -1;
271 pack_fd = input_fd;
273 git_SHA1_Init(&input_ctx);
274 return pack_name;
277 static void parse_pack_header(void)
279 struct pack_header *hdr = fill(sizeof(struct pack_header));
281 /* Header consistency check */
282 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
283 die("pack signature mismatch");
284 if (!pack_version_ok(hdr->hdr_version))
285 die("pack version %"PRIu32" unsupported",
286 ntohl(hdr->hdr_version));
288 nr_objects = ntohl(hdr->hdr_entries);
289 use(sizeof(struct pack_header));
292 static NORETURN void bad_object(unsigned long offset, const char *format,
293 ...) __attribute__((format (printf, 2, 3)));
295 static NORETURN void bad_object(unsigned long offset, const char *format, ...)
297 va_list params;
298 char buf[1024];
300 va_start(params, format);
301 vsnprintf(buf, sizeof(buf), format, params);
302 va_end(params);
303 die("pack has bad object at offset %lu: %s", offset, buf);
306 static inline struct thread_local *get_thread_data(void)
308 #ifndef NO_PTHREADS
309 if (threads_active)
310 return pthread_getspecific(key);
311 assert(!threads_active &&
312 "This should only be reached when all threads are gone");
313 #endif
314 return &nothread_data;
317 #ifndef NO_PTHREADS
318 static void set_thread_data(struct thread_local *data)
320 if (threads_active)
321 pthread_setspecific(key, data);
323 #endif
325 static struct base_data *alloc_base_data(void)
327 struct base_data *base = xmalloc(sizeof(struct base_data));
328 memset(base, 0, sizeof(*base));
329 base->ref_last = -1;
330 base->ofs_last = -1;
331 return base;
334 static void free_base_data(struct base_data *c)
336 if (c->data) {
337 free(c->data);
338 c->data = NULL;
339 get_thread_data()->base_cache_used -= c->size;
343 static void prune_base_data(struct base_data *retain)
345 struct base_data *b;
346 struct thread_local *data = get_thread_data();
347 for (b = data->base_cache;
348 data->base_cache_used > delta_base_cache_limit && b;
349 b = b->child) {
350 if (b->data && b != retain)
351 free_base_data(b);
355 static void link_base_data(struct base_data *base, struct base_data *c)
357 if (base)
358 base->child = c;
359 else
360 get_thread_data()->base_cache = c;
362 c->base = base;
363 c->child = NULL;
364 if (c->data)
365 get_thread_data()->base_cache_used += c->size;
366 prune_base_data(c);
369 static void unlink_base_data(struct base_data *c)
371 struct base_data *base = c->base;
372 if (base)
373 base->child = NULL;
374 else
375 get_thread_data()->base_cache = NULL;
376 free_base_data(c);
379 static void *unpack_entry_data(unsigned long offset, unsigned long size)
381 int status;
382 git_zstream stream;
383 void *buf = xmalloc(size);
385 memset(&stream, 0, sizeof(stream));
386 git_inflate_init(&stream);
387 stream.next_out = buf;
388 stream.avail_out = size;
390 do {
391 stream.next_in = fill(1);
392 stream.avail_in = input_len;
393 status = git_inflate(&stream, 0);
394 use(input_len - stream.avail_in);
395 } while (status == Z_OK);
396 if (stream.total_out != size || status != Z_STREAM_END)
397 bad_object(offset, "inflate returned %d", status);
398 git_inflate_end(&stream);
399 return buf;
402 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
404 unsigned char *p;
405 unsigned long size, c;
406 off_t base_offset;
407 unsigned shift;
408 void *data;
410 obj->idx.offset = consumed_bytes;
411 input_crc32 = crc32(0, NULL, 0);
413 p = fill(1);
414 c = *p;
415 use(1);
416 obj->type = (c >> 4) & 7;
417 size = (c & 15);
418 shift = 4;
419 while (c & 0x80) {
420 p = fill(1);
421 c = *p;
422 use(1);
423 size += (c & 0x7f) << shift;
424 shift += 7;
426 obj->size = size;
428 switch (obj->type) {
429 case OBJ_REF_DELTA:
430 hashcpy(delta_base->sha1, fill(20));
431 use(20);
432 break;
433 case OBJ_OFS_DELTA:
434 memset(delta_base, 0, sizeof(*delta_base));
435 p = fill(1);
436 c = *p;
437 use(1);
438 base_offset = c & 127;
439 while (c & 128) {
440 base_offset += 1;
441 if (!base_offset || MSB(base_offset, 7))
442 bad_object(obj->idx.offset, "offset value overflow for delta base object");
443 p = fill(1);
444 c = *p;
445 use(1);
446 base_offset = (base_offset << 7) + (c & 127);
448 delta_base->offset = obj->idx.offset - base_offset;
449 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
450 bad_object(obj->idx.offset, "delta base offset is out of bound");
451 break;
452 case OBJ_COMMIT:
453 case OBJ_TREE:
454 case OBJ_BLOB:
455 case OBJ_TAG:
456 break;
457 default:
458 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
460 obj->hdr_size = consumed_bytes - obj->idx.offset;
462 data = unpack_entry_data(obj->idx.offset, obj->size);
463 obj->idx.crc32 = input_crc32;
464 return data;
467 static void *get_data_from_pack(struct object_entry *obj)
469 off_t from = obj[0].idx.offset + obj[0].hdr_size;
470 unsigned long len = obj[1].idx.offset - from;
471 unsigned char *data, *inbuf;
472 git_zstream stream;
473 int status;
475 data = xmalloc(obj->size);
476 inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
478 memset(&stream, 0, sizeof(stream));
479 git_inflate_init(&stream);
480 stream.next_out = data;
481 stream.avail_out = obj->size;
483 do {
484 ssize_t n = (len < 64*1024) ? len : 64*1024;
485 n = pread(pack_fd, inbuf, n, from);
486 if (n < 0)
487 die_errno("cannot pread pack file");
488 if (!n)
489 die("premature end of pack file, %lu bytes missing", len);
490 from += n;
491 len -= n;
492 stream.next_in = inbuf;
493 stream.avail_in = n;
494 status = git_inflate(&stream, 0);
495 } while (len && status == Z_OK && !stream.avail_in);
497 /* This has been inflated OK when first encountered, so... */
498 if (status != Z_STREAM_END || stream.total_out != obj->size)
499 die("serious inflate inconsistency");
501 git_inflate_end(&stream);
502 free(inbuf);
503 return data;
506 static int compare_delta_bases(const union delta_base *base1,
507 const union delta_base *base2,
508 enum object_type type1,
509 enum object_type type2)
511 int cmp = type1 - type2;
512 if (cmp)
513 return cmp;
514 return memcmp(base1, base2, UNION_BASE_SZ);
517 static int find_delta(const union delta_base *base, enum object_type type)
519 int first = 0, last = nr_deltas;
521 while (first < last) {
522 int next = (first + last) / 2;
523 struct delta_entry *delta = &deltas[next];
524 int cmp;
526 cmp = compare_delta_bases(base, &delta->base,
527 type, objects[delta->obj_no].type);
528 if (!cmp)
529 return next;
530 if (cmp < 0) {
531 last = next;
532 continue;
534 first = next+1;
536 return -first-1;
539 static void find_delta_children(const union delta_base *base,
540 int *first_index, int *last_index,
541 enum object_type type)
543 int first = find_delta(base, type);
544 int last = first;
545 int end = nr_deltas - 1;
547 if (first < 0) {
548 *first_index = 0;
549 *last_index = -1;
550 return;
552 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
553 --first;
554 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
555 ++last;
556 *first_index = first;
557 *last_index = last;
560 static void sha1_object(const void *data, unsigned long size,
561 enum object_type type, unsigned char *sha1)
563 hash_sha1_file(data, size, typename(type), sha1);
564 read_lock();
565 if (has_sha1_file(sha1)) {
566 void *has_data;
567 enum object_type has_type;
568 unsigned long has_size;
569 has_data = read_sha1_file(sha1, &has_type, &has_size);
570 read_unlock();
571 if (!has_data)
572 die("cannot read existing object %s", sha1_to_hex(sha1));
573 if (size != has_size || type != has_type ||
574 memcmp(data, has_data, size) != 0)
575 die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
576 free(has_data);
577 } else
578 read_unlock();
580 if (strict) {
581 read_lock();
582 if (type == OBJ_BLOB) {
583 struct blob *blob = lookup_blob(sha1);
584 if (blob)
585 blob->object.flags |= FLAG_CHECKED;
586 else
587 die("invalid blob object %s", sha1_to_hex(sha1));
588 } else {
589 struct object *obj;
590 int eaten;
591 void *buf = (void *) data;
594 * we do not need to free the memory here, as the
595 * buf is deleted by the caller.
597 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
598 if (!obj)
599 die("invalid %s", typename(type));
600 if (fsck_object(obj, 1, fsck_error_function))
601 die("Error in object");
602 if (fsck_walk(obj, mark_link, NULL))
603 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
605 if (obj->type == OBJ_TREE) {
606 struct tree *item = (struct tree *) obj;
607 item->buffer = NULL;
609 if (obj->type == OBJ_COMMIT) {
610 struct commit *commit = (struct commit *) obj;
611 commit->buffer = NULL;
613 obj->flags |= FLAG_CHECKED;
615 read_unlock();
619 static int is_delta_type(enum object_type type)
621 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
625 * This function is part of find_unresolved_deltas(). There are two
626 * walkers going in the opposite ways.
628 * The first one in find_unresolved_deltas() traverses down from
629 * parent node to children, deflating nodes along the way. However,
630 * memory for deflated nodes is limited by delta_base_cache_limit, so
631 * at some point parent node's deflated content may be freed.
633 * The second walker is this function, which goes from current node up
634 * to top parent if necessary to deflate the node. In normal
635 * situation, its parent node would be already deflated, so it just
636 * needs to apply delta.
638 * In the worst case scenario, parent node is no longer deflated because
639 * we're running out of delta_base_cache_limit; we need to re-deflate
640 * parents, possibly up to the top base.
642 * All deflated objects here are subject to be freed if we exceed
643 * delta_base_cache_limit, just like in find_unresolved_deltas(), we
644 * just need to make sure the last node is not freed.
646 static void *get_base_data(struct base_data *c)
648 if (!c->data) {
649 struct object_entry *obj = c->obj;
650 struct base_data **delta = NULL;
651 int delta_nr = 0, delta_alloc = 0;
653 while (is_delta_type(c->obj->type) && !c->data) {
654 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
655 delta[delta_nr++] = c;
656 c = c->base;
658 if (!delta_nr) {
659 c->data = get_data_from_pack(obj);
660 c->size = obj->size;
661 get_thread_data()->base_cache_used += c->size;
662 prune_base_data(c);
664 for (; delta_nr > 0; delta_nr--) {
665 void *base, *raw;
666 c = delta[delta_nr - 1];
667 obj = c->obj;
668 base = get_base_data(c->base);
669 raw = get_data_from_pack(obj);
670 c->data = patch_delta(
671 base, c->base->size,
672 raw, obj->size,
673 &c->size);
674 free(raw);
675 if (!c->data)
676 bad_object(obj->idx.offset, "failed to apply delta");
677 get_thread_data()->base_cache_used += c->size;
678 prune_base_data(c);
680 free(delta);
682 return c->data;
685 static void resolve_delta(struct object_entry *delta_obj,
686 struct base_data *base, struct base_data *result)
688 void *base_data, *delta_data;
690 delta_obj->real_type = base->obj->real_type;
691 delta_obj->delta_depth = base->obj->delta_depth + 1;
692 if (deepest_delta < delta_obj->delta_depth)
693 deepest_delta = delta_obj->delta_depth;
694 delta_obj->base_object_no = base->obj - objects;
695 delta_data = get_data_from_pack(delta_obj);
696 base_data = get_base_data(base);
697 result->obj = delta_obj;
698 result->data = patch_delta(base_data, base->size,
699 delta_data, delta_obj->size, &result->size);
700 free(delta_data);
701 if (!result->data)
702 bad_object(delta_obj->idx.offset, "failed to apply delta");
703 sha1_object(result->data, result->size, delta_obj->real_type,
704 delta_obj->idx.sha1);
705 counter_lock();
706 nr_resolved_deltas++;
707 counter_unlock();
710 static struct base_data *find_unresolved_deltas_1(struct base_data *base,
711 struct base_data *prev_base)
713 if (base->ref_last == -1 && base->ofs_last == -1) {
714 union delta_base base_spec;
716 hashcpy(base_spec.sha1, base->obj->idx.sha1);
717 find_delta_children(&base_spec,
718 &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
720 memset(&base_spec, 0, sizeof(base_spec));
721 base_spec.offset = base->obj->idx.offset;
722 find_delta_children(&base_spec,
723 &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
725 if (base->ref_last == -1 && base->ofs_last == -1) {
726 free(base->data);
727 return NULL;
730 link_base_data(prev_base, base);
733 if (base->ref_first <= base->ref_last) {
734 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
735 struct base_data *result = alloc_base_data();
737 assert(child->real_type == OBJ_REF_DELTA);
738 resolve_delta(child, base, result);
739 if (base->ref_first == base->ref_last && base->ofs_last == -1)
740 free_base_data(base);
742 base->ref_first++;
743 return result;
746 if (base->ofs_first <= base->ofs_last) {
747 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
748 struct base_data *result = alloc_base_data();
750 assert(child->real_type == OBJ_OFS_DELTA);
751 resolve_delta(child, base, result);
752 if (base->ofs_first == base->ofs_last)
753 free_base_data(base);
755 base->ofs_first++;
756 return result;
759 unlink_base_data(base);
760 return NULL;
763 static void find_unresolved_deltas(struct base_data *base)
765 struct base_data *new_base, *prev_base = NULL;
766 for (;;) {
767 new_base = find_unresolved_deltas_1(base, prev_base);
769 if (new_base) {
770 prev_base = base;
771 base = new_base;
772 } else {
773 free(base);
774 base = prev_base;
775 if (!base)
776 return;
777 prev_base = base->base;
782 static int compare_delta_entry(const void *a, const void *b)
784 const struct delta_entry *delta_a = a;
785 const struct delta_entry *delta_b = b;
787 /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
788 return compare_delta_bases(&delta_a->base, &delta_b->base,
789 objects[delta_a->obj_no].type,
790 objects[delta_b->obj_no].type);
793 static void resolve_base(struct object_entry *obj)
795 struct base_data *base_obj = alloc_base_data();
796 base_obj->obj = obj;
797 base_obj->data = NULL;
798 find_unresolved_deltas(base_obj);
801 #ifndef NO_PTHREADS
802 static void *threaded_second_pass(void *data)
804 set_thread_data(data);
805 for (;;) {
806 int i;
807 work_lock();
808 display_progress(progress, nr_resolved_deltas);
809 while (nr_dispatched < nr_objects &&
810 is_delta_type(objects[nr_dispatched].type))
811 nr_dispatched++;
812 if (nr_dispatched >= nr_objects) {
813 work_unlock();
814 break;
816 i = nr_dispatched++;
817 work_unlock();
819 resolve_base(&objects[i]);
821 return NULL;
823 #endif
826 * First pass:
827 * - find locations of all objects;
828 * - calculate SHA1 of all non-delta objects;
829 * - remember base (SHA1 or offset) for all deltas.
831 static void parse_pack_objects(unsigned char *sha1)
833 int i;
834 struct delta_entry *delta = deltas;
835 struct stat st;
837 if (verbose)
838 progress = start_progress(
839 from_stdin ? "Receiving objects" : "Indexing objects",
840 nr_objects);
841 for (i = 0; i < nr_objects; i++) {
842 struct object_entry *obj = &objects[i];
843 void *data = unpack_raw_entry(obj, &delta->base);
844 obj->real_type = obj->type;
845 if (is_delta_type(obj->type)) {
846 nr_deltas++;
847 delta->obj_no = i;
848 delta++;
849 } else
850 sha1_object(data, obj->size, obj->type, obj->idx.sha1);
851 free(data);
852 display_progress(progress, i+1);
854 objects[i].idx.offset = consumed_bytes;
855 stop_progress(&progress);
857 /* Check pack integrity */
858 flush();
859 git_SHA1_Final(sha1, &input_ctx);
860 if (hashcmp(fill(20), sha1))
861 die("pack is corrupted (SHA1 mismatch)");
862 use(20);
864 /* If input_fd is a file, we should have reached its end now. */
865 if (fstat(input_fd, &st))
866 die_errno("cannot fstat packfile");
867 if (S_ISREG(st.st_mode) &&
868 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
869 die("pack has junk at the end");
873 * Second pass:
874 * - for all non-delta objects, look if it is used as a base for
875 * deltas;
876 * - if used as a base, uncompress the object and apply all deltas,
877 * recursively checking if the resulting object is used as a base
878 * for some more deltas.
880 static void resolve_deltas(void)
882 int i;
884 if (!nr_deltas)
885 return;
887 /* Sort deltas by base SHA1/offset for fast searching */
888 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
889 compare_delta_entry);
891 if (verbose)
892 progress = start_progress("Resolving deltas", nr_deltas);
894 #ifndef NO_PTHREADS
895 nr_dispatched = 0;
896 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
897 init_thread();
898 for (i = 0; i < nr_threads; i++) {
899 int ret = pthread_create(&thread_data[i].thread, NULL,
900 threaded_second_pass, thread_data + i);
901 if (ret)
902 die("unable to create thread: %s", strerror(ret));
904 for (i = 0; i < nr_threads; i++)
905 pthread_join(thread_data[i].thread, NULL);
906 cleanup_thread();
907 return;
909 #endif
911 for (i = 0; i < nr_objects; i++) {
912 struct object_entry *obj = &objects[i];
914 if (is_delta_type(obj->type))
915 continue;
916 resolve_base(obj);
917 display_progress(progress, nr_resolved_deltas);
922 * Third pass:
923 * - append objects to convert thin pack to full pack if required
924 * - write the final 20-byte SHA-1
926 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
927 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
929 if (nr_deltas == nr_resolved_deltas) {
930 stop_progress(&progress);
931 /* Flush remaining pack final 20-byte SHA1. */
932 flush();
933 return;
936 if (fix_thin_pack) {
937 struct sha1file *f;
938 unsigned char read_sha1[20], tail_sha1[20];
939 char msg[48];
940 int nr_unresolved = nr_deltas - nr_resolved_deltas;
941 int nr_objects_initial = nr_objects;
942 if (nr_unresolved <= 0)
943 die("confusion beyond insanity");
944 objects = xrealloc(objects,
945 (nr_objects + nr_unresolved + 1)
946 * sizeof(*objects));
947 f = sha1fd(output_fd, curr_pack);
948 fix_unresolved_deltas(f, nr_unresolved);
949 sprintf(msg, "completed with %d local objects",
950 nr_objects - nr_objects_initial);
951 stop_progress_msg(&progress, msg);
952 sha1close(f, tail_sha1, 0);
953 hashcpy(read_sha1, pack_sha1);
954 fixup_pack_header_footer(output_fd, pack_sha1,
955 curr_pack, nr_objects,
956 read_sha1, consumed_bytes-20);
957 if (hashcmp(read_sha1, tail_sha1) != 0)
958 die("Unexpected tail checksum for %s "
959 "(disk corruption?)", curr_pack);
961 if (nr_deltas != nr_resolved_deltas)
962 die("pack has %d unresolved deltas",
963 nr_deltas - nr_resolved_deltas);
966 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
968 git_zstream stream;
969 int status;
970 unsigned char outbuf[4096];
972 memset(&stream, 0, sizeof(stream));
973 git_deflate_init(&stream, zlib_compression_level);
974 stream.next_in = in;
975 stream.avail_in = size;
977 do {
978 stream.next_out = outbuf;
979 stream.avail_out = sizeof(outbuf);
980 status = git_deflate(&stream, Z_FINISH);
981 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
982 } while (status == Z_OK);
984 if (status != Z_STREAM_END)
985 die("unable to deflate appended object (%d)", status);
986 size = stream.total_out;
987 git_deflate_end(&stream);
988 return size;
991 static struct object_entry *append_obj_to_pack(struct sha1file *f,
992 const unsigned char *sha1, void *buf,
993 unsigned long size, enum object_type type)
995 struct object_entry *obj = &objects[nr_objects++];
996 unsigned char header[10];
997 unsigned long s = size;
998 int n = 0;
999 unsigned char c = (type << 4) | (s & 15);
1000 s >>= 4;
1001 while (s) {
1002 header[n++] = c | 0x80;
1003 c = s & 0x7f;
1004 s >>= 7;
1006 header[n++] = c;
1007 crc32_begin(f);
1008 sha1write(f, header, n);
1009 obj[0].size = size;
1010 obj[0].hdr_size = n;
1011 obj[0].type = type;
1012 obj[0].real_type = type;
1013 obj[1].idx.offset = obj[0].idx.offset + n;
1014 obj[1].idx.offset += write_compressed(f, buf, size);
1015 obj[0].idx.crc32 = crc32_end(f);
1016 sha1flush(f);
1017 hashcpy(obj->idx.sha1, sha1);
1018 return obj;
1021 static int delta_pos_compare(const void *_a, const void *_b)
1023 struct delta_entry *a = *(struct delta_entry **)_a;
1024 struct delta_entry *b = *(struct delta_entry **)_b;
1025 return a->obj_no - b->obj_no;
1028 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
1030 struct delta_entry **sorted_by_pos;
1031 int i, n = 0;
1034 * Since many unresolved deltas may well be themselves base objects
1035 * for more unresolved deltas, we really want to include the
1036 * smallest number of base objects that would cover as much delta
1037 * as possible by picking the
1038 * trunc deltas first, allowing for other deltas to resolve without
1039 * additional base objects. Since most base objects are to be found
1040 * before deltas depending on them, a good heuristic is to start
1041 * resolving deltas in the same order as their position in the pack.
1043 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
1044 for (i = 0; i < nr_deltas; i++) {
1045 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
1046 continue;
1047 sorted_by_pos[n++] = &deltas[i];
1049 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
1051 for (i = 0; i < n; i++) {
1052 struct delta_entry *d = sorted_by_pos[i];
1053 enum object_type type;
1054 struct base_data *base_obj = alloc_base_data();
1056 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1057 continue;
1058 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
1059 if (!base_obj->data)
1060 continue;
1062 if (check_sha1_signature(d->base.sha1, base_obj->data,
1063 base_obj->size, typename(type)))
1064 die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
1065 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
1066 base_obj->data, base_obj->size, type);
1067 find_unresolved_deltas(base_obj);
1068 display_progress(progress, nr_resolved_deltas);
1070 free(sorted_by_pos);
1073 static void final(const char *final_pack_name, const char *curr_pack_name,
1074 const char *final_index_name, const char *curr_index_name,
1075 const char *keep_name, const char *keep_msg,
1076 unsigned char *sha1)
1078 const char *report = "pack";
1079 char name[PATH_MAX];
1080 int err;
1082 if (!from_stdin) {
1083 close(input_fd);
1084 } else {
1085 fsync_or_die(output_fd, curr_pack_name);
1086 err = close(output_fd);
1087 if (err)
1088 die_errno("error while closing pack file");
1091 if (keep_msg) {
1092 int keep_fd, keep_msg_len = strlen(keep_msg);
1094 if (!keep_name)
1095 keep_fd = odb_pack_keep(name, sizeof(name), sha1);
1096 else
1097 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
1099 if (keep_fd < 0) {
1100 if (errno != EEXIST)
1101 die_errno("cannot write keep file '%s'",
1102 keep_name);
1103 } else {
1104 if (keep_msg_len > 0) {
1105 write_or_die(keep_fd, keep_msg, keep_msg_len);
1106 write_or_die(keep_fd, "\n", 1);
1108 if (close(keep_fd) != 0)
1109 die_errno("cannot close written keep file '%s'",
1110 keep_name);
1111 report = "keep";
1115 if (final_pack_name != curr_pack_name) {
1116 if (!final_pack_name) {
1117 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
1118 get_object_directory(), sha1_to_hex(sha1));
1119 final_pack_name = name;
1121 if (move_temp_to_file(curr_pack_name, final_pack_name))
1122 die("cannot store pack file");
1123 } else if (from_stdin)
1124 chmod(final_pack_name, 0444);
1126 if (final_index_name != curr_index_name) {
1127 if (!final_index_name) {
1128 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
1129 get_object_directory(), sha1_to_hex(sha1));
1130 final_index_name = name;
1132 if (move_temp_to_file(curr_index_name, final_index_name))
1133 die("cannot store index file");
1134 } else
1135 chmod(final_index_name, 0444);
1137 if (!from_stdin) {
1138 printf("%s\n", sha1_to_hex(sha1));
1139 } else {
1140 char buf[48];
1141 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
1142 report, sha1_to_hex(sha1));
1143 write_or_die(1, buf, len);
1146 * Let's just mimic git-unpack-objects here and write
1147 * the last part of the input buffer to stdout.
1149 while (input_len) {
1150 err = xwrite(1, input_buffer + input_offset, input_len);
1151 if (err <= 0)
1152 break;
1153 input_len -= err;
1154 input_offset += err;
1159 static int git_index_pack_config(const char *k, const char *v, void *cb)
1161 struct pack_idx_option *opts = cb;
1163 if (!strcmp(k, "pack.indexversion")) {
1164 opts->version = git_config_int(k, v);
1165 if (opts->version > 2)
1166 die("bad pack.indexversion=%"PRIu32, opts->version);
1167 return 0;
1169 if (!strcmp(k, "pack.threads")) {
1170 nr_threads = git_config_int(k, v);
1171 if (nr_threads < 0)
1172 die("invalid number of threads specified (%d)",
1173 nr_threads);
1174 #ifdef NO_PTHREADS
1175 if (nr_threads != 1)
1176 warning("no threads support, ignoring %s", k);
1177 nr_threads = 1;
1178 #endif
1179 return 0;
1181 return git_default_config(k, v, cb);
1184 static int cmp_uint32(const void *a_, const void *b_)
1186 uint32_t a = *((uint32_t *)a_);
1187 uint32_t b = *((uint32_t *)b_);
1189 return (a < b) ? -1 : (a != b);
1192 static void read_v2_anomalous_offsets(struct packed_git *p,
1193 struct pack_idx_option *opts)
1195 const uint32_t *idx1, *idx2;
1196 uint32_t i;
1198 /* The address of the 4-byte offset table */
1199 idx1 = (((const uint32_t *)p->index_data)
1200 + 2 /* 8-byte header */
1201 + 256 /* fan out */
1202 + 5 * p->num_objects /* 20-byte SHA-1 table */
1203 + p->num_objects /* CRC32 table */
1206 /* The address of the 8-byte offset table */
1207 idx2 = idx1 + p->num_objects;
1209 for (i = 0; i < p->num_objects; i++) {
1210 uint32_t off = ntohl(idx1[i]);
1211 if (!(off & 0x80000000))
1212 continue;
1213 off = off & 0x7fffffff;
1214 if (idx2[off * 2])
1215 continue;
1217 * The real offset is ntohl(idx2[off * 2]) in high 4
1218 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1219 * octets. But idx2[off * 2] is Zero!!!
1221 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1222 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1225 if (1 < opts->anomaly_nr)
1226 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1229 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1231 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1233 if (!p)
1234 die("Cannot open existing pack file '%s'", pack_name);
1235 if (open_pack_index(p))
1236 die("Cannot open existing pack idx file for '%s'", pack_name);
1238 /* Read the attributes from the existing idx file */
1239 opts->version = p->index_version;
1241 if (opts->version == 2)
1242 read_v2_anomalous_offsets(p, opts);
1245 * Get rid of the idx file as we do not need it anymore.
1246 * NEEDSWORK: extract this bit from free_pack_by_name() in
1247 * sha1_file.c, perhaps? It shouldn't matter very much as we
1248 * know we haven't installed this pack (hence we never have
1249 * read anything from it).
1251 close_pack_index(p);
1252 free(p);
1255 static void show_pack_info(int stat_only)
1257 int i, baseobjects = nr_objects - nr_deltas;
1258 unsigned long *chain_histogram = NULL;
1260 if (deepest_delta)
1261 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1263 for (i = 0; i < nr_objects; i++) {
1264 struct object_entry *obj = &objects[i];
1266 if (is_delta_type(obj->type))
1267 chain_histogram[obj->delta_depth - 1]++;
1268 if (stat_only)
1269 continue;
1270 printf("%s %-6s %lu %lu %"PRIuMAX,
1271 sha1_to_hex(obj->idx.sha1),
1272 typename(obj->real_type), obj->size,
1273 (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1274 (uintmax_t)obj->idx.offset);
1275 if (is_delta_type(obj->type)) {
1276 struct object_entry *bobj = &objects[obj->base_object_no];
1277 printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1279 putchar('\n');
1282 if (baseobjects)
1283 printf("non delta: %d object%s\n",
1284 baseobjects, baseobjects > 1 ? "s" : "");
1285 for (i = 0; i < deepest_delta; i++) {
1286 if (!chain_histogram[i])
1287 continue;
1288 printf("chain length = %d: %lu object%s\n",
1289 i + 1,
1290 chain_histogram[i],
1291 chain_histogram[i] > 1 ? "s" : "");
1295 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1297 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
1298 const char *curr_pack, *curr_index;
1299 const char *index_name = NULL, *pack_name = NULL;
1300 const char *keep_name = NULL, *keep_msg = NULL;
1301 char *index_name_buf = NULL, *keep_name_buf = NULL;
1302 struct pack_idx_entry **idx_objects;
1303 struct pack_idx_option opts;
1304 unsigned char pack_sha1[20];
1306 if (argc == 2 && !strcmp(argv[1], "-h"))
1307 usage(index_pack_usage);
1309 read_replace_refs = 0;
1311 reset_pack_idx_option(&opts);
1312 git_config(git_index_pack_config, &opts);
1313 if (prefix && chdir(prefix))
1314 die("Cannot come back to cwd");
1316 for (i = 1; i < argc; i++) {
1317 const char *arg = argv[i];
1319 if (*arg == '-') {
1320 if (!strcmp(arg, "--stdin")) {
1321 from_stdin = 1;
1322 } else if (!strcmp(arg, "--fix-thin")) {
1323 fix_thin_pack = 1;
1324 } else if (!strcmp(arg, "--strict")) {
1325 strict = 1;
1326 } else if (!strcmp(arg, "--verify")) {
1327 verify = 1;
1328 } else if (!strcmp(arg, "--verify-stat")) {
1329 verify = 1;
1330 stat = 1;
1331 } else if (!strcmp(arg, "--verify-stat-only")) {
1332 verify = 1;
1333 stat = 1;
1334 stat_only = 1;
1335 } else if (!strcmp(arg, "--keep")) {
1336 keep_msg = "";
1337 } else if (!prefixcmp(arg, "--keep=")) {
1338 keep_msg = arg + 7;
1339 } else if (!prefixcmp(arg, "--threads=")) {
1340 char *end;
1341 nr_threads = strtoul(arg+10, &end, 0);
1342 if (!arg[10] || *end || nr_threads < 0)
1343 usage(index_pack_usage);
1344 #ifdef NO_PTHREADS
1345 if (nr_threads != 1)
1346 warning("no threads support, "
1347 "ignoring %s", arg);
1348 nr_threads = 1;
1349 #endif
1350 } else if (!prefixcmp(arg, "--pack_header=")) {
1351 struct pack_header *hdr;
1352 char *c;
1354 hdr = (struct pack_header *)input_buffer;
1355 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1356 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1357 if (*c != ',')
1358 die("bad %s", arg);
1359 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1360 if (*c)
1361 die("bad %s", arg);
1362 input_len = sizeof(*hdr);
1363 } else if (!strcmp(arg, "-v")) {
1364 verbose = 1;
1365 } else if (!strcmp(arg, "-o")) {
1366 if (index_name || (i+1) >= argc)
1367 usage(index_pack_usage);
1368 index_name = argv[++i];
1369 } else if (!prefixcmp(arg, "--index-version=")) {
1370 char *c;
1371 opts.version = strtoul(arg + 16, &c, 10);
1372 if (opts.version > 2)
1373 die("bad %s", arg);
1374 if (*c == ',')
1375 opts.off32_limit = strtoul(c+1, &c, 0);
1376 if (*c || opts.off32_limit & 0x80000000)
1377 die("bad %s", arg);
1378 } else
1379 usage(index_pack_usage);
1380 continue;
1383 if (pack_name)
1384 usage(index_pack_usage);
1385 pack_name = arg;
1388 if (!pack_name && !from_stdin)
1389 usage(index_pack_usage);
1390 if (fix_thin_pack && !from_stdin)
1391 die("--fix-thin cannot be used without --stdin");
1392 if (!index_name && pack_name) {
1393 int len = strlen(pack_name);
1394 if (!has_extension(pack_name, ".pack"))
1395 die("packfile name '%s' does not end with '.pack'",
1396 pack_name);
1397 index_name_buf = xmalloc(len);
1398 memcpy(index_name_buf, pack_name, len - 5);
1399 strcpy(index_name_buf + len - 5, ".idx");
1400 index_name = index_name_buf;
1402 if (keep_msg && !keep_name && pack_name) {
1403 int len = strlen(pack_name);
1404 if (!has_extension(pack_name, ".pack"))
1405 die("packfile name '%s' does not end with '.pack'",
1406 pack_name);
1407 keep_name_buf = xmalloc(len);
1408 memcpy(keep_name_buf, pack_name, len - 5);
1409 strcpy(keep_name_buf + len - 5, ".keep");
1410 keep_name = keep_name_buf;
1412 if (verify) {
1413 if (!index_name)
1414 die("--verify with no packfile name given");
1415 read_idx_option(&opts, index_name);
1416 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1418 if (strict)
1419 opts.flags |= WRITE_IDX_STRICT;
1421 #ifndef NO_PTHREADS
1422 if (!nr_threads) {
1423 nr_threads = online_cpus();
1424 /* An experiment showed that more threads does not mean faster */
1425 if (nr_threads > 3)
1426 nr_threads = 3;
1428 #endif
1430 curr_pack = open_pack_file(pack_name);
1431 parse_pack_header();
1432 objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1433 deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
1434 parse_pack_objects(pack_sha1);
1435 resolve_deltas();
1436 conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
1437 free(deltas);
1438 if (strict)
1439 check_objects();
1441 if (stat)
1442 show_pack_info(stat_only);
1444 idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1445 for (i = 0; i < nr_objects; i++)
1446 idx_objects[i] = &objects[i].idx;
1447 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1448 free(idx_objects);
1450 if (!verify)
1451 final(pack_name, curr_pack,
1452 index_name, curr_index,
1453 keep_name, keep_msg,
1454 pack_sha1);
1455 else
1456 close(input_fd);
1457 free(objects);
1458 free(index_name_buf);
1459 free(keep_name_buf);
1460 if (pack_name == NULL)
1461 free((void *) curr_pack);
1462 if (index_name == NULL)
1463 free((void *) curr_index);
1465 return 0;