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>])";
18 struct pack_idx_entry idx;
20 unsigned int hdr_size;
21 enum object_type type;
22 enum object_type real_type;
28 unsigned char sha1[20];
33 struct base_data *base;
34 struct base_data *child;
35 struct object_entry *obj;
38 int ref_first, ref_last;
39 int ofs_first, ofs_last;
42 #if !defined(NO_PTHREADS) && defined(NO_PREAD)
43 /* NO_PREAD uses compat/pread.c, which is not thread-safe. Disable threading. */
51 struct base_data *base_cache;
52 size_t base_cache_used;
56 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
57 * to memcmp() only the first 20 bytes.
59 #define UNION_BASE_SZ 20
61 #define FLAG_LINK (1u<<20)
62 #define FLAG_CHECKED (1u<<21)
65 union delta_base base;
69 static struct object_entry *objects;
70 static struct delta_entry *deltas;
71 static struct thread_local nothread_data;
72 static int nr_objects;
74 static int nr_resolved_deltas;
75 static int nr_threads;
77 static int from_stdin;
81 static struct progress *progress;
83 /* We always read in 4kB chunks. */
84 static unsigned char input_buffer[4096];
85 static unsigned int input_offset, input_len;
86 static off_t consumed_bytes;
87 static unsigned deepest_delta;
88 static git_SHA_CTX input_ctx;
89 static uint32_t input_crc32;
90 static int input_fd, output_fd, pack_fd;
94 static struct thread_local *thread_data;
95 static int nr_dispatched;
96 static int threads_active;
98 static pthread_mutex_t read_mutex;
99 #define read_lock() lock_mutex(&read_mutex)
100 #define read_unlock() unlock_mutex(&read_mutex)
102 static pthread_mutex_t counter_mutex;
103 #define counter_lock() lock_mutex(&counter_mutex)
104 #define counter_unlock() unlock_mutex(&counter_mutex)
106 static pthread_mutex_t work_mutex;
107 #define work_lock() lock_mutex(&work_mutex)
108 #define work_unlock() unlock_mutex(&work_mutex)
110 static pthread_key_t key;
112 static inline void lock_mutex(pthread_mutex_t *mutex)
115 pthread_mutex_lock(mutex);
118 static inline void unlock_mutex(pthread_mutex_t *mutex)
121 pthread_mutex_unlock(mutex);
125 * Mutex and conditional variable can't be statically-initialized on Windows.
127 static void init_thread(void)
129 init_recursive_mutex(&read_mutex);
130 pthread_mutex_init(&counter_mutex, NULL);
131 pthread_mutex_init(&work_mutex, NULL);
132 pthread_key_create(&key, NULL);
133 thread_data = xcalloc(nr_threads, sizeof(*thread_data));
137 static void cleanup_thread(void)
142 pthread_mutex_destroy(&read_mutex);
143 pthread_mutex_destroy(&counter_mutex);
144 pthread_mutex_destroy(&work_mutex);
145 pthread_key_delete(key);
152 #define read_unlock()
154 #define counter_lock()
155 #define counter_unlock()
158 #define work_unlock()
163 static int mark_link(struct object *obj, int type, void *data)
168 if (type != OBJ_ANY && obj->type != type)
169 die("object type mismatch at %s", sha1_to_hex(obj->sha1));
171 obj->flags |= FLAG_LINK;
175 /* The content of each linked object must have been checked
176 or it must be already present in the object database */
177 static void check_object(struct object *obj)
182 if (!(obj->flags & FLAG_LINK))
185 if (!(obj->flags & FLAG_CHECKED)) {
187 int type = sha1_object_info(obj->sha1, &size);
188 if (type != obj->type || type <= 0)
189 die("object of unexpected type");
190 obj->flags |= FLAG_CHECKED;
195 static void check_objects(void)
199 max = get_max_object_index();
200 for (i = 0; i < max; i++)
201 check_object(get_indexed_object(i));
205 /* Discard current buffer used content. */
206 static void flush(void)
210 write_or_die(output_fd, input_buffer, input_offset);
211 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
212 memmove(input_buffer, input_buffer + input_offset, input_len);
218 * Make sure at least "min" bytes are available in the buffer, and
219 * return the pointer to the buffer.
221 static void *fill(int min)
223 if (min <= input_len)
224 return input_buffer + input_offset;
225 if (min > sizeof(input_buffer))
226 die("cannot fill %d bytes", min);
229 ssize_t ret = xread(input_fd, input_buffer + input_len,
230 sizeof(input_buffer) - input_len);
234 die_errno("read error on input");
238 display_throughput(progress, consumed_bytes + input_len);
239 } while (input_len < min);
243 static void use(int bytes)
245 if (bytes > input_len)
246 die("used more bytes than were available");
247 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
249 input_offset += bytes;
251 /* make sure off_t is sufficiently large not to wrap */
252 if (signed_add_overflows(consumed_bytes, bytes))
253 die("pack too large for current definition of off_t");
254 consumed_bytes += bytes;
257 static const char *open_pack_file(const char *pack_name)
262 static char tmp_file[PATH_MAX];
263 output_fd = odb_mkstemp(tmp_file, sizeof(tmp_file),
264 "pack/tmp_pack_XXXXXX");
265 pack_name = xstrdup(tmp_file);
267 output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
269 die_errno("unable to create '%s'", pack_name);
272 input_fd = open(pack_name, O_RDONLY);
274 die_errno("cannot open packfile '%s'", pack_name);
278 git_SHA1_Init(&input_ctx);
282 static void parse_pack_header(void)
284 struct pack_header *hdr = fill(sizeof(struct pack_header));
286 /* Header consistency check */
287 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
288 die("pack signature mismatch");
289 if (!pack_version_ok(hdr->hdr_version))
290 die("pack version %"PRIu32" unsupported",
291 ntohl(hdr->hdr_version));
293 nr_objects = ntohl(hdr->hdr_entries);
294 use(sizeof(struct pack_header));
297 static NORETURN void bad_object(unsigned long offset, const char *format,
298 ...) __attribute__((format (printf, 2, 3)));
300 static NORETURN void bad_object(unsigned long offset, const char *format, ...)
305 va_start(params, format);
306 vsnprintf(buf, sizeof(buf), format, params);
308 die("pack has bad object at offset %lu: %s", offset, buf);
311 static inline struct thread_local *get_thread_data(void)
315 return pthread_getspecific(key);
316 assert(!threads_active &&
317 "This should only be reached when all threads are gone");
319 return ¬hread_data;
323 static void set_thread_data(struct thread_local *data)
326 pthread_setspecific(key, data);
330 static struct base_data *alloc_base_data(void)
332 struct base_data *base = xmalloc(sizeof(struct base_data));
333 memset(base, 0, sizeof(*base));
339 static void free_base_data(struct base_data *c)
344 get_thread_data()->base_cache_used -= c->size;
348 static void prune_base_data(struct base_data *retain)
351 struct thread_local *data = get_thread_data();
352 for (b = data->base_cache;
353 data->base_cache_used > delta_base_cache_limit && b;
355 if (b->data && b != retain)
360 static void link_base_data(struct base_data *base, struct base_data *c)
365 get_thread_data()->base_cache = c;
370 get_thread_data()->base_cache_used += c->size;
374 static void unlink_base_data(struct base_data *c)
376 struct base_data *base = c->base;
380 get_thread_data()->base_cache = NULL;
384 static void *unpack_entry_data(unsigned long offset, unsigned long size)
388 void *buf = xmalloc(size);
390 memset(&stream, 0, sizeof(stream));
391 git_inflate_init(&stream);
392 stream.next_out = buf;
393 stream.avail_out = size;
396 stream.next_in = fill(1);
397 stream.avail_in = input_len;
398 status = git_inflate(&stream, 0);
399 use(input_len - stream.avail_in);
400 } while (status == Z_OK);
401 if (stream.total_out != size || status != Z_STREAM_END)
402 bad_object(offset, "inflate returned %d", status);
403 git_inflate_end(&stream);
407 static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
410 unsigned long size, c;
415 obj->idx.offset = consumed_bytes;
416 input_crc32 = crc32(0, NULL, 0);
421 obj->type = (c >> 4) & 7;
428 size += (c & 0x7f) << shift;
435 hashcpy(delta_base->sha1, fill(20));
439 memset(delta_base, 0, sizeof(*delta_base));
443 base_offset = c & 127;
446 if (!base_offset || MSB(base_offset, 7))
447 bad_object(obj->idx.offset, "offset value overflow for delta base object");
451 base_offset = (base_offset << 7) + (c & 127);
453 delta_base->offset = obj->idx.offset - base_offset;
454 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
455 bad_object(obj->idx.offset, "delta base offset is out of bound");
463 bad_object(obj->idx.offset, "unknown object type %d", obj->type);
465 obj->hdr_size = consumed_bytes - obj->idx.offset;
467 data = unpack_entry_data(obj->idx.offset, obj->size);
468 obj->idx.crc32 = input_crc32;
472 static void *get_data_from_pack(struct object_entry *obj)
474 off_t from = obj[0].idx.offset + obj[0].hdr_size;
475 unsigned long len = obj[1].idx.offset - from;
476 unsigned char *data, *inbuf;
480 data = xmalloc(obj->size);
481 inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
483 memset(&stream, 0, sizeof(stream));
484 git_inflate_init(&stream);
485 stream.next_out = data;
486 stream.avail_out = obj->size;
489 ssize_t n = (len < 64*1024) ? len : 64*1024;
490 n = pread(pack_fd, inbuf, n, from);
492 die_errno("cannot pread pack file");
494 die("premature end of pack file, %lu bytes missing", len);
497 stream.next_in = inbuf;
499 status = git_inflate(&stream, 0);
500 } while (len && status == Z_OK && !stream.avail_in);
502 /* This has been inflated OK when first encountered, so... */
503 if (status != Z_STREAM_END || stream.total_out != obj->size)
504 die("serious inflate inconsistency");
506 git_inflate_end(&stream);
511 static int compare_delta_bases(const union delta_base *base1,
512 const union delta_base *base2,
513 enum object_type type1,
514 enum object_type type2)
516 int cmp = type1 - type2;
519 return memcmp(base1, base2, UNION_BASE_SZ);
522 static int find_delta(const union delta_base *base, enum object_type type)
524 int first = 0, last = nr_deltas;
526 while (first < last) {
527 int next = (first + last) / 2;
528 struct delta_entry *delta = &deltas[next];
531 cmp = compare_delta_bases(base, &delta->base,
532 type, objects[delta->obj_no].type);
544 static void find_delta_children(const union delta_base *base,
545 int *first_index, int *last_index,
546 enum object_type type)
548 int first = find_delta(base, type);
550 int end = nr_deltas - 1;
557 while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
559 while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
561 *first_index = first;
565 static void sha1_object(const void *data, unsigned long size,
566 enum object_type type, unsigned char *sha1)
568 hash_sha1_file(data, size, typename(type), sha1);
570 if (has_sha1_file(sha1)) {
572 enum object_type has_type;
573 unsigned long has_size;
574 has_data = read_sha1_file(sha1, &has_type, &has_size);
577 die("cannot read existing object %s", sha1_to_hex(sha1));
578 if (size != has_size || type != has_type ||
579 memcmp(data, has_data, size) != 0)
580 die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
587 if (type == OBJ_BLOB) {
588 struct blob *blob = lookup_blob(sha1);
590 blob->object.flags |= FLAG_CHECKED;
592 die("invalid blob object %s", sha1_to_hex(sha1));
596 void *buf = (void *) data;
599 * we do not need to free the memory here, as the
600 * buf is deleted by the caller.
602 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
604 die("invalid %s", typename(type));
605 if (fsck_object(obj, 1, fsck_error_function))
606 die("Error in object");
607 if (fsck_walk(obj, mark_link, NULL))
608 die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
610 if (obj->type == OBJ_TREE) {
611 struct tree *item = (struct tree *) obj;
614 if (obj->type == OBJ_COMMIT) {
615 struct commit *commit = (struct commit *) obj;
616 commit->buffer = NULL;
618 obj->flags |= FLAG_CHECKED;
624 static int is_delta_type(enum object_type type)
626 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
630 * This function is part of find_unresolved_deltas(). There are two
631 * walkers going in the opposite ways.
633 * The first one in find_unresolved_deltas() traverses down from
634 * parent node to children, deflating nodes along the way. However,
635 * memory for deflated nodes is limited by delta_base_cache_limit, so
636 * at some point parent node's deflated content may be freed.
638 * The second walker is this function, which goes from current node up
639 * to top parent if necessary to deflate the node. In normal
640 * situation, its parent node would be already deflated, so it just
641 * needs to apply delta.
643 * In the worst case scenario, parent node is no longer deflated because
644 * we're running out of delta_base_cache_limit; we need to re-deflate
645 * parents, possibly up to the top base.
647 * All deflated objects here are subject to be freed if we exceed
648 * delta_base_cache_limit, just like in find_unresolved_deltas(), we
649 * just need to make sure the last node is not freed.
651 static void *get_base_data(struct base_data *c)
654 struct object_entry *obj = c->obj;
655 struct base_data **delta = NULL;
656 int delta_nr = 0, delta_alloc = 0;
658 while (is_delta_type(c->obj->type) && !c->data) {
659 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
660 delta[delta_nr++] = c;
664 c->data = get_data_from_pack(obj);
666 get_thread_data()->base_cache_used += c->size;
669 for (; delta_nr > 0; delta_nr--) {
671 c = delta[delta_nr - 1];
673 base = get_base_data(c->base);
674 raw = get_data_from_pack(obj);
675 c->data = patch_delta(
681 bad_object(obj->idx.offset, "failed to apply delta");
682 get_thread_data()->base_cache_used += c->size;
690 static void resolve_delta(struct object_entry *delta_obj,
691 struct base_data *base, struct base_data *result)
693 void *base_data, *delta_data;
695 delta_obj->real_type = base->obj->real_type;
696 delta_obj->delta_depth = base->obj->delta_depth + 1;
697 if (deepest_delta < delta_obj->delta_depth)
698 deepest_delta = delta_obj->delta_depth;
699 delta_obj->base_object_no = base->obj - objects;
700 delta_data = get_data_from_pack(delta_obj);
701 base_data = get_base_data(base);
702 result->obj = delta_obj;
703 result->data = patch_delta(base_data, base->size,
704 delta_data, delta_obj->size, &result->size);
707 bad_object(delta_obj->idx.offset, "failed to apply delta");
708 sha1_object(result->data, result->size, delta_obj->real_type,
709 delta_obj->idx.sha1);
711 nr_resolved_deltas++;
715 static struct base_data *find_unresolved_deltas_1(struct base_data *base,
716 struct base_data *prev_base)
718 if (base->ref_last == -1 && base->ofs_last == -1) {
719 union delta_base base_spec;
721 hashcpy(base_spec.sha1, base->obj->idx.sha1);
722 find_delta_children(&base_spec,
723 &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
725 memset(&base_spec, 0, sizeof(base_spec));
726 base_spec.offset = base->obj->idx.offset;
727 find_delta_children(&base_spec,
728 &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
730 if (base->ref_last == -1 && base->ofs_last == -1) {
735 link_base_data(prev_base, base);
738 if (base->ref_first <= base->ref_last) {
739 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
740 struct base_data *result = alloc_base_data();
742 assert(child->real_type == OBJ_REF_DELTA);
743 resolve_delta(child, base, result);
744 if (base->ref_first == base->ref_last && base->ofs_last == -1)
745 free_base_data(base);
751 if (base->ofs_first <= base->ofs_last) {
752 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
753 struct base_data *result = alloc_base_data();
755 assert(child->real_type == OBJ_OFS_DELTA);
756 resolve_delta(child, base, result);
757 if (base->ofs_first == base->ofs_last)
758 free_base_data(base);
764 unlink_base_data(base);
768 static void find_unresolved_deltas(struct base_data *base)
770 struct base_data *new_base, *prev_base = NULL;
772 new_base = find_unresolved_deltas_1(base, prev_base);
782 prev_base = base->base;
787 static int compare_delta_entry(const void *a, const void *b)
789 const struct delta_entry *delta_a = a;
790 const struct delta_entry *delta_b = b;
792 /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
793 return compare_delta_bases(&delta_a->base, &delta_b->base,
794 objects[delta_a->obj_no].type,
795 objects[delta_b->obj_no].type);
798 static void resolve_base(struct object_entry *obj)
800 struct base_data *base_obj = alloc_base_data();
802 base_obj->data = NULL;
803 find_unresolved_deltas(base_obj);
807 static void *threaded_second_pass(void *data)
809 set_thread_data(data);
813 display_progress(progress, nr_resolved_deltas);
814 while (nr_dispatched < nr_objects &&
815 is_delta_type(objects[nr_dispatched].type))
817 if (nr_dispatched >= nr_objects) {
824 resolve_base(&objects[i]);
832 * - find locations of all objects;
833 * - calculate SHA1 of all non-delta objects;
834 * - remember base (SHA1 or offset) for all deltas.
836 static void parse_pack_objects(unsigned char *sha1)
839 struct delta_entry *delta = deltas;
843 progress = start_progress(
844 from_stdin ? "Receiving objects" : "Indexing objects",
846 for (i = 0; i < nr_objects; i++) {
847 struct object_entry *obj = &objects[i];
848 void *data = unpack_raw_entry(obj, &delta->base);
849 obj->real_type = obj->type;
850 if (is_delta_type(obj->type)) {
855 sha1_object(data, obj->size, obj->type, obj->idx.sha1);
857 display_progress(progress, i+1);
859 objects[i].idx.offset = consumed_bytes;
860 stop_progress(&progress);
862 /* Check pack integrity */
864 git_SHA1_Final(sha1, &input_ctx);
865 if (hashcmp(fill(20), sha1))
866 die("pack is corrupted (SHA1 mismatch)");
869 /* If input_fd is a file, we should have reached its end now. */
870 if (fstat(input_fd, &st))
871 die_errno("cannot fstat packfile");
872 if (S_ISREG(st.st_mode) &&
873 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
874 die("pack has junk at the end");
879 * - for all non-delta objects, look if it is used as a base for
881 * - if used as a base, uncompress the object and apply all deltas,
882 * recursively checking if the resulting object is used as a base
883 * for some more deltas.
885 static void resolve_deltas(void)
892 /* Sort deltas by base SHA1/offset for fast searching */
893 qsort(deltas, nr_deltas, sizeof(struct delta_entry),
894 compare_delta_entry);
897 progress = start_progress("Resolving deltas", nr_deltas);
901 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
903 for (i = 0; i < nr_threads; i++) {
904 int ret = pthread_create(&thread_data[i].thread, NULL,
905 threaded_second_pass, thread_data + i);
907 die("unable to create thread: %s", strerror(ret));
909 for (i = 0; i < nr_threads; i++)
910 pthread_join(thread_data[i].thread, NULL);
916 for (i = 0; i < nr_objects; i++) {
917 struct object_entry *obj = &objects[i];
919 if (is_delta_type(obj->type))
922 display_progress(progress, nr_resolved_deltas);
928 * - append objects to convert thin pack to full pack if required
929 * - write the final 20-byte SHA-1
931 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
932 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
934 if (nr_deltas == nr_resolved_deltas) {
935 stop_progress(&progress);
936 /* Flush remaining pack final 20-byte SHA1. */
943 unsigned char read_sha1[20], tail_sha1[20];
945 int nr_unresolved = nr_deltas - nr_resolved_deltas;
946 int nr_objects_initial = nr_objects;
947 if (nr_unresolved <= 0)
948 die("confusion beyond insanity");
949 objects = xrealloc(objects,
950 (nr_objects + nr_unresolved + 1)
952 f = sha1fd(output_fd, curr_pack);
953 fix_unresolved_deltas(f, nr_unresolved);
954 sprintf(msg, "completed with %d local objects",
955 nr_objects - nr_objects_initial);
956 stop_progress_msg(&progress, msg);
957 sha1close(f, tail_sha1, 0);
958 hashcpy(read_sha1, pack_sha1);
959 fixup_pack_header_footer(output_fd, pack_sha1,
960 curr_pack, nr_objects,
961 read_sha1, consumed_bytes-20);
962 if (hashcmp(read_sha1, tail_sha1) != 0)
963 die("Unexpected tail checksum for %s "
964 "(disk corruption?)", curr_pack);
966 if (nr_deltas != nr_resolved_deltas)
967 die("pack has %d unresolved deltas",
968 nr_deltas - nr_resolved_deltas);
971 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
975 unsigned char outbuf[4096];
977 memset(&stream, 0, sizeof(stream));
978 git_deflate_init(&stream, zlib_compression_level);
980 stream.avail_in = size;
983 stream.next_out = outbuf;
984 stream.avail_out = sizeof(outbuf);
985 status = git_deflate(&stream, Z_FINISH);
986 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
987 } while (status == Z_OK);
989 if (status != Z_STREAM_END)
990 die("unable to deflate appended object (%d)", status);
991 size = stream.total_out;
992 git_deflate_end(&stream);
996 static struct object_entry *append_obj_to_pack(struct sha1file *f,
997 const unsigned char *sha1, void *buf,
998 unsigned long size, enum object_type type)
1000 struct object_entry *obj = &objects[nr_objects++];
1001 unsigned char header[10];
1002 unsigned long s = size;
1004 unsigned char c = (type << 4) | (s & 15);
1007 header[n++] = c | 0x80;
1013 sha1write(f, header, n);
1015 obj[0].hdr_size = n;
1017 obj[0].real_type = type;
1018 obj[1].idx.offset = obj[0].idx.offset + n;
1019 obj[1].idx.offset += write_compressed(f, buf, size);
1020 obj[0].idx.crc32 = crc32_end(f);
1022 hashcpy(obj->idx.sha1, sha1);
1026 static int delta_pos_compare(const void *_a, const void *_b)
1028 struct delta_entry *a = *(struct delta_entry **)_a;
1029 struct delta_entry *b = *(struct delta_entry **)_b;
1030 return a->obj_no - b->obj_no;
1033 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
1035 struct delta_entry **sorted_by_pos;
1039 * Since many unresolved deltas may well be themselves base objects
1040 * for more unresolved deltas, we really want to include the
1041 * smallest number of base objects that would cover as much delta
1042 * as possible by picking the
1043 * trunc deltas first, allowing for other deltas to resolve without
1044 * additional base objects. Since most base objects are to be found
1045 * before deltas depending on them, a good heuristic is to start
1046 * resolving deltas in the same order as their position in the pack.
1048 sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
1049 for (i = 0; i < nr_deltas; i++) {
1050 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
1052 sorted_by_pos[n++] = &deltas[i];
1054 qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
1056 for (i = 0; i < n; i++) {
1057 struct delta_entry *d = sorted_by_pos[i];
1058 enum object_type type;
1059 struct base_data *base_obj = alloc_base_data();
1061 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1063 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
1064 if (!base_obj->data)
1067 if (check_sha1_signature(d->base.sha1, base_obj->data,
1068 base_obj->size, typename(type)))
1069 die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
1070 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
1071 base_obj->data, base_obj->size, type);
1072 find_unresolved_deltas(base_obj);
1073 display_progress(progress, nr_resolved_deltas);
1075 free(sorted_by_pos);
1078 static void final(const char *final_pack_name, const char *curr_pack_name,
1079 const char *final_index_name, const char *curr_index_name,
1080 const char *keep_name, const char *keep_msg,
1081 unsigned char *sha1)
1083 const char *report = "pack";
1084 char name[PATH_MAX];
1090 fsync_or_die(output_fd, curr_pack_name);
1091 err = close(output_fd);
1093 die_errno("error while closing pack file");
1097 int keep_fd, keep_msg_len = strlen(keep_msg);
1100 keep_fd = odb_pack_keep(name, sizeof(name), sha1);
1102 keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
1105 if (errno != EEXIST)
1106 die_errno("cannot write keep file '%s'",
1109 if (keep_msg_len > 0) {
1110 write_or_die(keep_fd, keep_msg, keep_msg_len);
1111 write_or_die(keep_fd, "\n", 1);
1113 if (close(keep_fd) != 0)
1114 die_errno("cannot close written keep file '%s'",
1120 if (final_pack_name != curr_pack_name) {
1121 if (!final_pack_name) {
1122 snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
1123 get_object_directory(), sha1_to_hex(sha1));
1124 final_pack_name = name;
1126 if (move_temp_to_file(curr_pack_name, final_pack_name))
1127 die("cannot store pack file");
1128 } else if (from_stdin)
1129 chmod(final_pack_name, 0444);
1131 if (final_index_name != curr_index_name) {
1132 if (!final_index_name) {
1133 snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
1134 get_object_directory(), sha1_to_hex(sha1));
1135 final_index_name = name;
1137 if (move_temp_to_file(curr_index_name, final_index_name))
1138 die("cannot store index file");
1140 chmod(final_index_name, 0444);
1143 printf("%s\n", sha1_to_hex(sha1));
1146 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
1147 report, sha1_to_hex(sha1));
1148 write_or_die(1, buf, len);
1151 * Let's just mimic git-unpack-objects here and write
1152 * the last part of the input buffer to stdout.
1155 err = xwrite(1, input_buffer + input_offset, input_len);
1159 input_offset += err;
1164 static int git_index_pack_config(const char *k, const char *v, void *cb)
1166 struct pack_idx_option *opts = cb;
1168 if (!strcmp(k, "pack.indexversion")) {
1169 opts->version = git_config_int(k, v);
1170 if (opts->version > 2)
1171 die("bad pack.indexversion=%"PRIu32, opts->version);
1174 if (!strcmp(k, "pack.threads")) {
1175 nr_threads = git_config_int(k, v);
1177 die("invalid number of threads specified (%d)",
1180 if (nr_threads != 1)
1181 warning("no threads support, ignoring %s", k);
1186 return git_default_config(k, v, cb);
1189 static int cmp_uint32(const void *a_, const void *b_)
1191 uint32_t a = *((uint32_t *)a_);
1192 uint32_t b = *((uint32_t *)b_);
1194 return (a < b) ? -1 : (a != b);
1197 static void read_v2_anomalous_offsets(struct packed_git *p,
1198 struct pack_idx_option *opts)
1200 const uint32_t *idx1, *idx2;
1203 /* The address of the 4-byte offset table */
1204 idx1 = (((const uint32_t *)p->index_data)
1205 + 2 /* 8-byte header */
1207 + 5 * p->num_objects /* 20-byte SHA-1 table */
1208 + p->num_objects /* CRC32 table */
1211 /* The address of the 8-byte offset table */
1212 idx2 = idx1 + p->num_objects;
1214 for (i = 0; i < p->num_objects; i++) {
1215 uint32_t off = ntohl(idx1[i]);
1216 if (!(off & 0x80000000))
1218 off = off & 0x7fffffff;
1222 * The real offset is ntohl(idx2[off * 2]) in high 4
1223 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1224 * octets. But idx2[off * 2] is Zero!!!
1226 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1227 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1230 if (1 < opts->anomaly_nr)
1231 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1234 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1236 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1239 die("Cannot open existing pack file '%s'", pack_name);
1240 if (open_pack_index(p))
1241 die("Cannot open existing pack idx file for '%s'", pack_name);
1243 /* Read the attributes from the existing idx file */
1244 opts->version = p->index_version;
1246 if (opts->version == 2)
1247 read_v2_anomalous_offsets(p, opts);
1250 * Get rid of the idx file as we do not need it anymore.
1251 * NEEDSWORK: extract this bit from free_pack_by_name() in
1252 * sha1_file.c, perhaps? It shouldn't matter very much as we
1253 * know we haven't installed this pack (hence we never have
1254 * read anything from it).
1256 close_pack_index(p);
1260 static void show_pack_info(int stat_only)
1262 int i, baseobjects = nr_objects - nr_deltas;
1263 unsigned long *chain_histogram = NULL;
1266 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1268 for (i = 0; i < nr_objects; i++) {
1269 struct object_entry *obj = &objects[i];
1271 if (is_delta_type(obj->type))
1272 chain_histogram[obj->delta_depth - 1]++;
1275 printf("%s %-6s %lu %lu %"PRIuMAX,
1276 sha1_to_hex(obj->idx.sha1),
1277 typename(obj->real_type), obj->size,
1278 (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1279 (uintmax_t)obj->idx.offset);
1280 if (is_delta_type(obj->type)) {
1281 struct object_entry *bobj = &objects[obj->base_object_no];
1282 printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1288 printf("non delta: %d object%s\n",
1289 baseobjects, baseobjects > 1 ? "s" : "");
1290 for (i = 0; i < deepest_delta; i++) {
1291 if (!chain_histogram[i])
1293 printf("chain length = %d: %lu object%s\n",
1296 chain_histogram[i] > 1 ? "s" : "");
1300 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1302 int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
1303 const char *curr_pack, *curr_index;
1304 const char *index_name = NULL, *pack_name = NULL;
1305 const char *keep_name = NULL, *keep_msg = NULL;
1306 char *index_name_buf = NULL, *keep_name_buf = NULL;
1307 struct pack_idx_entry **idx_objects;
1308 struct pack_idx_option opts;
1309 unsigned char pack_sha1[20];
1311 if (argc == 2 && !strcmp(argv[1], "-h"))
1312 usage(index_pack_usage);
1314 read_replace_refs = 0;
1316 reset_pack_idx_option(&opts);
1317 git_config(git_index_pack_config, &opts);
1318 if (prefix && chdir(prefix))
1319 die("Cannot come back to cwd");
1321 for (i = 1; i < argc; i++) {
1322 const char *arg = argv[i];
1325 if (!strcmp(arg, "--stdin")) {
1327 } else if (!strcmp(arg, "--fix-thin")) {
1329 } else if (!strcmp(arg, "--strict")) {
1331 } else if (!strcmp(arg, "--verify")) {
1333 } else if (!strcmp(arg, "--verify-stat")) {
1336 } else if (!strcmp(arg, "--verify-stat-only")) {
1340 } else if (!strcmp(arg, "--keep")) {
1342 } else if (!prefixcmp(arg, "--keep=")) {
1344 } else if (!prefixcmp(arg, "--threads=")) {
1346 nr_threads = strtoul(arg+10, &end, 0);
1347 if (!arg[10] || *end || nr_threads < 0)
1348 usage(index_pack_usage);
1350 if (nr_threads != 1)
1351 warning("no threads support, "
1352 "ignoring %s", arg);
1355 } else if (!prefixcmp(arg, "--pack_header=")) {
1356 struct pack_header *hdr;
1359 hdr = (struct pack_header *)input_buffer;
1360 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1361 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1364 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1367 input_len = sizeof(*hdr);
1368 } else if (!strcmp(arg, "-v")) {
1370 } else if (!strcmp(arg, "-o")) {
1371 if (index_name || (i+1) >= argc)
1372 usage(index_pack_usage);
1373 index_name = argv[++i];
1374 } else if (!prefixcmp(arg, "--index-version=")) {
1376 opts.version = strtoul(arg + 16, &c, 10);
1377 if (opts.version > 2)
1380 opts.off32_limit = strtoul(c+1, &c, 0);
1381 if (*c || opts.off32_limit & 0x80000000)
1384 usage(index_pack_usage);
1389 usage(index_pack_usage);
1393 if (!pack_name && !from_stdin)
1394 usage(index_pack_usage);
1395 if (fix_thin_pack && !from_stdin)
1396 die("--fix-thin cannot be used without --stdin");
1397 if (!index_name && pack_name) {
1398 int len = strlen(pack_name);
1399 if (!has_extension(pack_name, ".pack"))
1400 die("packfile name '%s' does not end with '.pack'",
1402 index_name_buf = xmalloc(len);
1403 memcpy(index_name_buf, pack_name, len - 5);
1404 strcpy(index_name_buf + len - 5, ".idx");
1405 index_name = index_name_buf;
1407 if (keep_msg && !keep_name && pack_name) {
1408 int len = strlen(pack_name);
1409 if (!has_extension(pack_name, ".pack"))
1410 die("packfile name '%s' does not end with '.pack'",
1412 keep_name_buf = xmalloc(len);
1413 memcpy(keep_name_buf, pack_name, len - 5);
1414 strcpy(keep_name_buf + len - 5, ".keep");
1415 keep_name = keep_name_buf;
1419 die("--verify with no packfile name given");
1420 read_idx_option(&opts, index_name);
1421 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1424 opts.flags |= WRITE_IDX_STRICT;
1428 nr_threads = online_cpus();
1429 /* An experiment showed that more threads does not mean faster */
1435 curr_pack = open_pack_file(pack_name);
1436 parse_pack_header();
1437 objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1438 deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
1439 parse_pack_objects(pack_sha1);
1441 conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
1447 show_pack_info(stat_only);
1449 idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1450 for (i = 0; i < nr_objects; i++)
1451 idx_objects[i] = &objects[i].idx;
1452 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1456 final(pack_name, curr_pack,
1457 index_name, curr_index,
1458 keep_name, keep_msg,
1463 free(index_name_buf);
1464 free(keep_name_buf);
1465 if (pack_name == NULL)
1466 free((void *) curr_pack);
1467 if (index_name == NULL)
1468 free((void *) curr_index);