1#include "builtin.h"
2#include "config.h"
3#include "delta.h"
4#include "pack.h"
5#include "csum-file.h"
6#include "blob.h"
7#include "commit.h"
8#include "tag.h"
9#include "tree.h"
10#include "progress.h"
11#include "fsck.h"
12#include "exec_cmd.h"
13#include "streaming.h"
14#include "thread-utils.h"
15
16static const char index_pack_usage[] =
17"git index-pack [-v] [-o <index-file>] [--keep | --keep=<msg>] [--verify] [--strict] (<pack-file> | --stdin [--fix-thin] [<pack-file>])";
18
19struct object_entry {
20 struct pack_idx_entry idx;
21 unsigned long size;
22 unsigned char hdr_size;
23 signed char type;
24 signed char real_type;
25};
26
27struct object_stat {
28 unsigned delta_depth;
29 int base_object_no;
30};
31
32struct 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;
40};
41
42struct thread_local {
43#ifndef NO_PTHREADS
44 pthread_t thread;
45#endif
46 struct base_data *base_cache;
47 size_t base_cache_used;
48 int pack_fd;
49};
50
51#define FLAG_LINK (1u<<20)
52#define FLAG_CHECKED (1u<<21)
53
54struct ofs_delta_entry {
55 off_t offset;
56 int obj_no;
57};
58
59struct ref_delta_entry {
60 unsigned char sha1[20];
61 int obj_no;
62};
63
64static struct object_entry *objects;
65static struct object_stat *obj_stat;
66static struct ofs_delta_entry *ofs_deltas;
67static struct ref_delta_entry *ref_deltas;
68static struct thread_local nothread_data;
69static int nr_objects;
70static int nr_ofs_deltas;
71static int nr_ref_deltas;
72static int ref_deltas_alloc;
73static int nr_resolved_deltas;
74static int nr_threads;
75
76static int from_stdin;
77static int strict;
78static int do_fsck_object;
79static struct fsck_options fsck_options = FSCK_OPTIONS_STRICT;
80static int verbose;
81static int show_resolving_progress;
82static int show_stat;
83static int check_self_contained_and_connected;
84
85static struct progress *progress;
86
87/* We always read in 4kB chunks. */
88static unsigned char input_buffer[4096];
89static unsigned int input_offset, input_len;
90static off_t consumed_bytes;
91static off_t max_input_size;
92static unsigned deepest_delta;
93static git_SHA_CTX input_ctx;
94static uint32_t input_crc32;
95static int input_fd, output_fd;
96static const char *curr_pack;
97
98#ifndef NO_PTHREADS
99
100static struct thread_local *thread_data;
101static int nr_dispatched;
102static int threads_active;
103
104static pthread_mutex_t read_mutex;
105#define read_lock() lock_mutex(&read_mutex)
106#define read_unlock() unlock_mutex(&read_mutex)
107
108static pthread_mutex_t counter_mutex;
109#define counter_lock() lock_mutex(&counter_mutex)
110#define counter_unlock() unlock_mutex(&counter_mutex)
111
112static pthread_mutex_t work_mutex;
113#define work_lock() lock_mutex(&work_mutex)
114#define work_unlock() unlock_mutex(&work_mutex)
115
116static pthread_mutex_t deepest_delta_mutex;
117#define deepest_delta_lock() lock_mutex(&deepest_delta_mutex)
118#define deepest_delta_unlock() unlock_mutex(&deepest_delta_mutex)
119
120static pthread_mutex_t type_cas_mutex;
121#define type_cas_lock() lock_mutex(&type_cas_mutex)
122#define type_cas_unlock() unlock_mutex(&type_cas_mutex)
123
124static pthread_key_t key;
125
126static inline void lock_mutex(pthread_mutex_t *mutex)
127{
128 if (threads_active)
129 pthread_mutex_lock(mutex);
130}
131
132static inline void unlock_mutex(pthread_mutex_t *mutex)
133{
134 if (threads_active)
135 pthread_mutex_unlock(mutex);
136}
137
138/*
139 * Mutex and conditional variable can't be statically-initialized on Windows.
140 */
141static void init_thread(void)
142{
143 int i;
144 init_recursive_mutex(&read_mutex);
145 pthread_mutex_init(&counter_mutex, NULL);
146 pthread_mutex_init(&work_mutex, NULL);
147 pthread_mutex_init(&type_cas_mutex, NULL);
148 if (show_stat)
149 pthread_mutex_init(&deepest_delta_mutex, NULL);
150 pthread_key_create(&key, NULL);
151 thread_data = xcalloc(nr_threads, sizeof(*thread_data));
152 for (i = 0; i < nr_threads; i++) {
153 thread_data[i].pack_fd = open(curr_pack, O_RDONLY);
154 if (thread_data[i].pack_fd == -1)
155 die_errno(_("unable to open %s"), curr_pack);
156 }
157
158 threads_active = 1;
159}
160
161static void cleanup_thread(void)
162{
163 int i;
164 if (!threads_active)
165 return;
166 threads_active = 0;
167 pthread_mutex_destroy(&read_mutex);
168 pthread_mutex_destroy(&counter_mutex);
169 pthread_mutex_destroy(&work_mutex);
170 pthread_mutex_destroy(&type_cas_mutex);
171 if (show_stat)
172 pthread_mutex_destroy(&deepest_delta_mutex);
173 for (i = 0; i < nr_threads; i++)
174 close(thread_data[i].pack_fd);
175 pthread_key_delete(key);
176 free(thread_data);
177}
178
179#else
180
181#define read_lock()
182#define read_unlock()
183
184#define counter_lock()
185#define counter_unlock()
186
187#define work_lock()
188#define work_unlock()
189
190#define deepest_delta_lock()
191#define deepest_delta_unlock()
192
193#define type_cas_lock()
194#define type_cas_unlock()
195
196#endif
197
198
199static int mark_link(struct object *obj, int type, void *data, struct fsck_options *options)
200{
201 if (!obj)
202 return -1;
203
204 if (type != OBJ_ANY && obj->type != type)
205 die(_("object type mismatch at %s"), oid_to_hex(&obj->oid));
206
207 obj->flags |= FLAG_LINK;
208 return 0;
209}
210
211/* The content of each linked object must have been checked
212 or it must be already present in the object database */
213static unsigned check_object(struct object *obj)
214{
215 if (!obj)
216 return 0;
217
218 if (!(obj->flags & FLAG_LINK))
219 return 0;
220
221 if (!(obj->flags & FLAG_CHECKED)) {
222 unsigned long size;
223 int type = sha1_object_info(obj->oid.hash, &size);
224 if (type <= 0)
225 die(_("did not receive expected object %s"),
226 oid_to_hex(&obj->oid));
227 if (type != obj->type)
228 die(_("object %s: expected type %s, found %s"),
229 oid_to_hex(&obj->oid),
230 typename(obj->type), typename(type));
231 obj->flags |= FLAG_CHECKED;
232 return 1;
233 }
234
235 return 0;
236}
237
238static unsigned check_objects(void)
239{
240 unsigned i, max, foreign_nr = 0;
241
242 max = get_max_object_index();
243 for (i = 0; i < max; i++)
244 foreign_nr += check_object(get_indexed_object(i));
245 return foreign_nr;
246}
247
248
249/* Discard current buffer used content. */
250static void flush(void)
251{
252 if (input_offset) {
253 if (output_fd >= 0)
254 write_or_die(output_fd, input_buffer, input_offset);
255 git_SHA1_Update(&input_ctx, input_buffer, input_offset);
256 memmove(input_buffer, input_buffer + input_offset, input_len);
257 input_offset = 0;
258 }
259}
260
261/*
262 * Make sure at least "min" bytes are available in the buffer, and
263 * return the pointer to the buffer.
264 */
265static void *fill(int min)
266{
267 if (min <= input_len)
268 return input_buffer + input_offset;
269 if (min > sizeof(input_buffer))
270 die(Q_("cannot fill %d byte",
271 "cannot fill %d bytes",
272 min),
273 min);
274 flush();
275 do {
276 ssize_t ret = xread(input_fd, input_buffer + input_len,
277 sizeof(input_buffer) - input_len);
278 if (ret <= 0) {
279 if (!ret)
280 die(_("early EOF"));
281 die_errno(_("read error on input"));
282 }
283 input_len += ret;
284 if (from_stdin)
285 display_throughput(progress, consumed_bytes + input_len);
286 } while (input_len < min);
287 return input_buffer;
288}
289
290static void use(int bytes)
291{
292 if (bytes > input_len)
293 die(_("used more bytes than were available"));
294 input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
295 input_len -= bytes;
296 input_offset += bytes;
297
298 /* make sure off_t is sufficiently large not to wrap */
299 if (signed_add_overflows(consumed_bytes, bytes))
300 die(_("pack too large for current definition of off_t"));
301 consumed_bytes += bytes;
302 if (max_input_size && consumed_bytes > max_input_size)
303 die(_("pack exceeds maximum allowed size"));
304}
305
306static const char *open_pack_file(const char *pack_name)
307{
308 if (from_stdin) {
309 input_fd = 0;
310 if (!pack_name) {
311 struct strbuf tmp_file = STRBUF_INIT;
312 output_fd = odb_mkstemp(&tmp_file,
313 "pack/tmp_pack_XXXXXX");
314 pack_name = strbuf_detach(&tmp_file, NULL);
315 } else {
316 output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
317 if (output_fd < 0)
318 die_errno(_("unable to create '%s'"), pack_name);
319 }
320 nothread_data.pack_fd = output_fd;
321 } else {
322 input_fd = open(pack_name, O_RDONLY);
323 if (input_fd < 0)
324 die_errno(_("cannot open packfile '%s'"), pack_name);
325 output_fd = -1;
326 nothread_data.pack_fd = input_fd;
327 }
328 git_SHA1_Init(&input_ctx);
329 return pack_name;
330}
331
332static void parse_pack_header(void)
333{
334 struct pack_header *hdr = fill(sizeof(struct pack_header));
335
336 /* Header consistency check */
337 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
338 die(_("pack signature mismatch"));
339 if (!pack_version_ok(hdr->hdr_version))
340 die(_("pack version %"PRIu32" unsupported"),
341 ntohl(hdr->hdr_version));
342
343 nr_objects = ntohl(hdr->hdr_entries);
344 use(sizeof(struct pack_header));
345}
346
347static NORETURN void bad_object(off_t offset, const char *format,
348 ...) __attribute__((format (printf, 2, 3)));
349
350static NORETURN void bad_object(off_t offset, const char *format, ...)
351{
352 va_list params;
353 char buf[1024];
354
355 va_start(params, format);
356 vsnprintf(buf, sizeof(buf), format, params);
357 va_end(params);
358 die(_("pack has bad object at offset %"PRIuMAX": %s"),
359 (uintmax_t)offset, buf);
360}
361
362static inline struct thread_local *get_thread_data(void)
363{
364#ifndef NO_PTHREADS
365 if (threads_active)
366 return pthread_getspecific(key);
367 assert(!threads_active &&
368 "This should only be reached when all threads are gone");
369#endif
370 return ¬hread_data;
371}
372
373#ifndef NO_PTHREADS
374static void set_thread_data(struct thread_local *data)
375{
376 if (threads_active)
377 pthread_setspecific(key, data);
378}
379#endif
380
381static struct base_data *alloc_base_data(void)
382{
383 struct base_data *base = xcalloc(1, sizeof(struct base_data));
384 base->ref_last = -1;
385 base->ofs_last = -1;
386 return base;
387}
388
389static void free_base_data(struct base_data *c)
390{
391 if (c->data) {
392 free(c->data);
393 c->data = NULL;
394 get_thread_data()->base_cache_used -= c->size;
395 }
396}
397
398static void prune_base_data(struct base_data *retain)
399{
400 struct base_data *b;
401 struct thread_local *data = get_thread_data();
402 for (b = data->base_cache;
403 data->base_cache_used > delta_base_cache_limit && b;
404 b = b->child) {
405 if (b->data && b != retain)
406 free_base_data(b);
407 }
408}
409
410static void link_base_data(struct base_data *base, struct base_data *c)
411{
412 if (base)
413 base->child = c;
414 else
415 get_thread_data()->base_cache = c;
416
417 c->base = base;
418 c->child = NULL;
419 if (c->data)
420 get_thread_data()->base_cache_used += c->size;
421 prune_base_data(c);
422}
423
424static void unlink_base_data(struct base_data *c)
425{
426 struct base_data *base = c->base;
427 if (base)
428 base->child = NULL;
429 else
430 get_thread_data()->base_cache = NULL;
431 free_base_data(c);
432}
433
434static int is_delta_type(enum object_type type)
435{
436 return (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA);
437}
438
439static void *unpack_entry_data(off_t offset, unsigned long size,
440 enum object_type type, unsigned char *sha1)
441{
442 static char fixed_buf[8192];
443 int status;
444 git_zstream stream;
445 void *buf;
446 git_SHA_CTX c;
447 char hdr[32];
448 int hdrlen;
449
450 if (!is_delta_type(type)) {
451 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), size) + 1;
452 git_SHA1_Init(&c);
453 git_SHA1_Update(&c, hdr, hdrlen);
454 } else
455 sha1 = NULL;
456 if (type == OBJ_BLOB && size > big_file_threshold)
457 buf = fixed_buf;
458 else
459 buf = xmallocz(size);
460
461 memset(&stream, 0, sizeof(stream));
462 git_inflate_init(&stream);
463 stream.next_out = buf;
464 stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
465
466 do {
467 unsigned char *last_out = stream.next_out;
468 stream.next_in = fill(1);
469 stream.avail_in = input_len;
470 status = git_inflate(&stream, 0);
471 use(input_len - stream.avail_in);
472 if (sha1)
473 git_SHA1_Update(&c, last_out, stream.next_out - last_out);
474 if (buf == fixed_buf) {
475 stream.next_out = buf;
476 stream.avail_out = sizeof(fixed_buf);
477 }
478 } while (status == Z_OK);
479 if (stream.total_out != size || status != Z_STREAM_END)
480 bad_object(offset, _("inflate returned %d"), status);
481 git_inflate_end(&stream);
482 if (sha1)
483 git_SHA1_Final(sha1, &c);
484 return buf == fixed_buf ? NULL : buf;
485}
486
487static void *unpack_raw_entry(struct object_entry *obj,
488 off_t *ofs_offset,
489 unsigned char *ref_sha1,
490 unsigned char *sha1)
491{
492 unsigned char *p;
493 unsigned long size, c;
494 off_t base_offset;
495 unsigned shift;
496 void *data;
497
498 obj->idx.offset = consumed_bytes;
499 input_crc32 = crc32(0, NULL, 0);
500
501 p = fill(1);
502 c = *p;
503 use(1);
504 obj->type = (c >> 4) & 7;
505 size = (c & 15);
506 shift = 4;
507 while (c & 0x80) {
508 p = fill(1);
509 c = *p;
510 use(1);
511 size += (c & 0x7f) << shift;
512 shift += 7;
513 }
514 obj->size = size;
515
516 switch (obj->type) {
517 case OBJ_REF_DELTA:
518 hashcpy(ref_sha1, fill(20));
519 use(20);
520 break;
521 case OBJ_OFS_DELTA:
522 p = fill(1);
523 c = *p;
524 use(1);
525 base_offset = c & 127;
526 while (c & 128) {
527 base_offset += 1;
528 if (!base_offset || MSB(base_offset, 7))
529 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
530 p = fill(1);
531 c = *p;
532 use(1);
533 base_offset = (base_offset << 7) + (c & 127);
534 }
535 *ofs_offset = obj->idx.offset - base_offset;
536 if (*ofs_offset <= 0 || *ofs_offset >= obj->idx.offset)
537 bad_object(obj->idx.offset, _("delta base offset is out of bound"));
538 break;
539 case OBJ_COMMIT:
540 case OBJ_TREE:
541 case OBJ_BLOB:
542 case OBJ_TAG:
543 break;
544 default:
545 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
546 }
547 obj->hdr_size = consumed_bytes - obj->idx.offset;
548
549 data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, sha1);
550 obj->idx.crc32 = input_crc32;
551 return data;
552}
553
554static void *unpack_data(struct object_entry *obj,
555 int (*consume)(const unsigned char *, unsigned long, void *),
556 void *cb_data)
557{
558 off_t from = obj[0].idx.offset + obj[0].hdr_size;
559 off_t len = obj[1].idx.offset - from;
560 unsigned char *data, *inbuf;
561 git_zstream stream;
562 int status;
563
564 data = xmallocz(consume ? 64*1024 : obj->size);
565 inbuf = xmalloc((len < 64*1024) ? (int)len : 64*1024);
566
567 memset(&stream, 0, sizeof(stream));
568 git_inflate_init(&stream);
569 stream.next_out = data;
570 stream.avail_out = consume ? 64*1024 : obj->size;
571
572 do {
573 ssize_t n = (len < 64*1024) ? (ssize_t)len : 64*1024;
574 n = xpread(get_thread_data()->pack_fd, inbuf, n, from);
575 if (n < 0)
576 die_errno(_("cannot pread pack file"));
577 if (!n)
578 die(Q_("premature end of pack file, %"PRIuMAX" byte missing",
579 "premature end of pack file, %"PRIuMAX" bytes missing",
580 (unsigned int)len),
581 (uintmax_t)len);
582 from += n;
583 len -= n;
584 stream.next_in = inbuf;
585 stream.avail_in = n;
586 if (!consume)
587 status = git_inflate(&stream, 0);
588 else {
589 do {
590 status = git_inflate(&stream, 0);
591 if (consume(data, stream.next_out - data, cb_data)) {
592 free(inbuf);
593 free(data);
594 return NULL;
595 }
596 stream.next_out = data;
597 stream.avail_out = 64*1024;
598 } while (status == Z_OK && stream.avail_in);
599 }
600 } while (len && status == Z_OK && !stream.avail_in);
601
602 /* This has been inflated OK when first encountered, so... */
603 if (status != Z_STREAM_END || stream.total_out != obj->size)
604 die(_("serious inflate inconsistency"));
605
606 git_inflate_end(&stream);
607 free(inbuf);
608 if (consume) {
609 free(data);
610 data = NULL;
611 }
612 return data;
613}
614
615static void *get_data_from_pack(struct object_entry *obj)
616{
617 return unpack_data(obj, NULL, NULL);
618}
619
620static int compare_ofs_delta_bases(off_t offset1, off_t offset2,
621 enum object_type type1,
622 enum object_type type2)
623{
624 int cmp = type1 - type2;
625 if (cmp)
626 return cmp;
627 return offset1 < offset2 ? -1 :
628 offset1 > offset2 ? 1 :
629 0;
630}
631
632static int find_ofs_delta(const off_t offset, enum object_type type)
633{
634 int first = 0, last = nr_ofs_deltas;
635
636 while (first < last) {
637 int next = (first + last) / 2;
638 struct ofs_delta_entry *delta = &ofs_deltas[next];
639 int cmp;
640
641 cmp = compare_ofs_delta_bases(offset, delta->offset,
642 type, objects[delta->obj_no].type);
643 if (!cmp)
644 return next;
645 if (cmp < 0) {
646 last = next;
647 continue;
648 }
649 first = next+1;
650 }
651 return -first-1;
652}
653
654static void find_ofs_delta_children(off_t offset,
655 int *first_index, int *last_index,
656 enum object_type type)
657{
658 int first = find_ofs_delta(offset, type);
659 int last = first;
660 int end = nr_ofs_deltas - 1;
661
662 if (first < 0) {
663 *first_index = 0;
664 *last_index = -1;
665 return;
666 }
667 while (first > 0 && ofs_deltas[first - 1].offset == offset)
668 --first;
669 while (last < end && ofs_deltas[last + 1].offset == offset)
670 ++last;
671 *first_index = first;
672 *last_index = last;
673}
674
675static int compare_ref_delta_bases(const unsigned char *sha1,
676 const unsigned char *sha2,
677 enum object_type type1,
678 enum object_type type2)
679{
680 int cmp = type1 - type2;
681 if (cmp)
682 return cmp;
683 return hashcmp(sha1, sha2);
684}
685
686static int find_ref_delta(const unsigned char *sha1, enum object_type type)
687{
688 int first = 0, last = nr_ref_deltas;
689
690 while (first < last) {
691 int next = (first + last) / 2;
692 struct ref_delta_entry *delta = &ref_deltas[next];
693 int cmp;
694
695 cmp = compare_ref_delta_bases(sha1, delta->sha1,
696 type, objects[delta->obj_no].type);
697 if (!cmp)
698 return next;
699 if (cmp < 0) {
700 last = next;
701 continue;
702 }
703 first = next+1;
704 }
705 return -first-1;
706}
707
708static void find_ref_delta_children(const unsigned char *sha1,
709 int *first_index, int *last_index,
710 enum object_type type)
711{
712 int first = find_ref_delta(sha1, type);
713 int last = first;
714 int end = nr_ref_deltas - 1;
715
716 if (first < 0) {
717 *first_index = 0;
718 *last_index = -1;
719 return;
720 }
721 while (first > 0 && !hashcmp(ref_deltas[first - 1].sha1, sha1))
722 --first;
723 while (last < end && !hashcmp(ref_deltas[last + 1].sha1, sha1))
724 ++last;
725 *first_index = first;
726 *last_index = last;
727}
728
729struct compare_data {
730 struct object_entry *entry;
731 struct git_istream *st;
732 unsigned char *buf;
733 unsigned long buf_size;
734};
735
736static int compare_objects(const unsigned char *buf, unsigned long size,
737 void *cb_data)
738{
739 struct compare_data *data = cb_data;
740
741 if (data->buf_size < size) {
742 free(data->buf);
743 data->buf = xmalloc(size);
744 data->buf_size = size;
745 }
746
747 while (size) {
748 ssize_t len = read_istream(data->st, data->buf, size);
749 if (len == 0)
750 die(_("SHA1 COLLISION FOUND WITH %s !"),
751 sha1_to_hex(data->entry->idx.sha1));
752 if (len < 0)
753 die(_("unable to read %s"),
754 sha1_to_hex(data->entry->idx.sha1));
755 if (memcmp(buf, data->buf, len))
756 die(_("SHA1 COLLISION FOUND WITH %s !"),
757 sha1_to_hex(data->entry->idx.sha1));
758 size -= len;
759 buf += len;
760 }
761 return 0;
762}
763
764static int check_collison(struct object_entry *entry)
765{
766 struct compare_data data;
767 enum object_type type;
768 unsigned long size;
769
770 if (entry->size <= big_file_threshold || entry->type != OBJ_BLOB)
771 return -1;
772
773 memset(&data, 0, sizeof(data));
774 data.entry = entry;
775 data.st = open_istream(entry->idx.sha1, &type, &size, NULL);
776 if (!data.st)
777 return -1;
778 if (size != entry->size || type != entry->type)
779 die(_("SHA1 COLLISION FOUND WITH %s !"),
780 sha1_to_hex(entry->idx.sha1));
781 unpack_data(entry, compare_objects, &data);
782 close_istream(data.st);
783 free(data.buf);
784 return 0;
785}
786
787static void sha1_object(const void *data, struct object_entry *obj_entry,
788 unsigned long size, enum object_type type,
789 const unsigned char *sha1)
790{
791 void *new_data = NULL;
792 int collision_test_needed = 0;
793
794 assert(data || obj_entry);
795
796 if (startup_info->have_repository) {
797 read_lock();
798 collision_test_needed = has_sha1_file_with_flags(sha1, HAS_SHA1_QUICK);
799 read_unlock();
800 }
801
802 if (collision_test_needed && !data) {
803 read_lock();
804 if (!check_collison(obj_entry))
805 collision_test_needed = 0;
806 read_unlock();
807 }
808 if (collision_test_needed) {
809 void *has_data;
810 enum object_type has_type;
811 unsigned long has_size;
812 read_lock();
813 has_type = sha1_object_info(sha1, &has_size);
814 if (has_type < 0)
815 die(_("cannot read existing object info %s"), sha1_to_hex(sha1));
816 if (has_type != type || has_size != size)
817 die(_("SHA1 COLLISION FOUND WITH %s !"), sha1_to_hex(sha1));
818 has_data = read_sha1_file(sha1, &has_type, &has_size);
819 read_unlock();
820 if (!data)
821 data = new_data = get_data_from_pack(obj_entry);
822 if (!has_data)
823 die(_("cannot read existing object %s"), sha1_to_hex(sha1));
824 if (size != has_size || type != has_type ||
825 memcmp(data, has_data, size) != 0)
826 die(_("SHA1 COLLISION FOUND WITH %s !"), sha1_to_hex(sha1));
827 free(has_data);
828 }
829
830 if (strict) {
831 read_lock();
832 if (type == OBJ_BLOB) {
833 struct blob *blob = lookup_blob(sha1);
834 if (blob)
835 blob->object.flags |= FLAG_CHECKED;
836 else
837 die(_("invalid blob object %s"), sha1_to_hex(sha1));
838 } else {
839 struct object *obj;
840 int eaten;
841 void *buf = (void *) data;
842
843 assert(data && "data can only be NULL for large _blobs_");
844
845 /*
846 * we do not need to free the memory here, as the
847 * buf is deleted by the caller.
848 */
849 obj = parse_object_buffer(sha1, type, size, buf, &eaten);
850 if (!obj)
851 die(_("invalid %s"), typename(type));
852 if (do_fsck_object &&
853 fsck_object(obj, buf, size, &fsck_options))
854 die(_("Error in object"));
855 if (fsck_walk(obj, NULL, &fsck_options))
856 die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
857
858 if (obj->type == OBJ_TREE) {
859 struct tree *item = (struct tree *) obj;
860 item->buffer = NULL;
861 obj->parsed = 0;
862 }
863 if (obj->type == OBJ_COMMIT) {
864 struct commit *commit = (struct commit *) obj;
865 if (detach_commit_buffer(commit, NULL) != data)
866 die("BUG: parse_object_buffer transmogrified our buffer");
867 }
868 obj->flags |= FLAG_CHECKED;
869 }
870 read_unlock();
871 }
872
873 free(new_data);
874}
875
876/*
877 * This function is part of find_unresolved_deltas(). There are two
878 * walkers going in the opposite ways.
879 *
880 * The first one in find_unresolved_deltas() traverses down from
881 * parent node to children, deflating nodes along the way. However,
882 * memory for deflated nodes is limited by delta_base_cache_limit, so
883 * at some point parent node's deflated content may be freed.
884 *
885 * The second walker is this function, which goes from current node up
886 * to top parent if necessary to deflate the node. In normal
887 * situation, its parent node would be already deflated, so it just
888 * needs to apply delta.
889 *
890 * In the worst case scenario, parent node is no longer deflated because
891 * we're running out of delta_base_cache_limit; we need to re-deflate
892 * parents, possibly up to the top base.
893 *
894 * All deflated objects here are subject to be freed if we exceed
895 * delta_base_cache_limit, just like in find_unresolved_deltas(), we
896 * just need to make sure the last node is not freed.
897 */
898static void *get_base_data(struct base_data *c)
899{
900 if (!c->data) {
901 struct object_entry *obj = c->obj;
902 struct base_data **delta = NULL;
903 int delta_nr = 0, delta_alloc = 0;
904
905 while (is_delta_type(c->obj->type) && !c->data) {
906 ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
907 delta[delta_nr++] = c;
908 c = c->base;
909 }
910 if (!delta_nr) {
911 c->data = get_data_from_pack(obj);
912 c->size = obj->size;
913 get_thread_data()->base_cache_used += c->size;
914 prune_base_data(c);
915 }
916 for (; delta_nr > 0; delta_nr--) {
917 void *base, *raw;
918 c = delta[delta_nr - 1];
919 obj = c->obj;
920 base = get_base_data(c->base);
921 raw = get_data_from_pack(obj);
922 c->data = patch_delta(
923 base, c->base->size,
924 raw, obj->size,
925 &c->size);
926 free(raw);
927 if (!c->data)
928 bad_object(obj->idx.offset, _("failed to apply delta"));
929 get_thread_data()->base_cache_used += c->size;
930 prune_base_data(c);
931 }
932 free(delta);
933 }
934 return c->data;
935}
936
937static void resolve_delta(struct object_entry *delta_obj,
938 struct base_data *base, struct base_data *result)
939{
940 void *base_data, *delta_data;
941
942 if (show_stat) {
943 int i = delta_obj - objects;
944 int j = base->obj - objects;
945 obj_stat[i].delta_depth = obj_stat[j].delta_depth + 1;
946 deepest_delta_lock();
947 if (deepest_delta < obj_stat[i].delta_depth)
948 deepest_delta = obj_stat[i].delta_depth;
949 deepest_delta_unlock();
950 obj_stat[i].base_object_no = j;
951 }
952 delta_data = get_data_from_pack(delta_obj);
953 base_data = get_base_data(base);
954 result->obj = delta_obj;
955 result->data = patch_delta(base_data, base->size,
956 delta_data, delta_obj->size, &result->size);
957 free(delta_data);
958 if (!result->data)
959 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
960 hash_sha1_file(result->data, result->size,
961 typename(delta_obj->real_type), delta_obj->idx.sha1);
962 sha1_object(result->data, NULL, result->size, delta_obj->real_type,
963 delta_obj->idx.sha1);
964 counter_lock();
965 nr_resolved_deltas++;
966 counter_unlock();
967}
968
969/*
970 * Standard boolean compare-and-swap: atomically check whether "*type" is
971 * "want"; if so, swap in "set" and return true. Otherwise, leave it untouched
972 * and return false.
973 */
974static int compare_and_swap_type(signed char *type,
975 enum object_type want,
976 enum object_type set)
977{
978 enum object_type old;
979
980 type_cas_lock();
981 old = *type;
982 if (old == want)
983 *type = set;
984 type_cas_unlock();
985
986 return old == want;
987}
988
989static struct base_data *find_unresolved_deltas_1(struct base_data *base,
990 struct base_data *prev_base)
991{
992 if (base->ref_last == -1 && base->ofs_last == -1) {
993 find_ref_delta_children(base->obj->idx.sha1,
994 &base->ref_first, &base->ref_last,
995 OBJ_REF_DELTA);
996
997 find_ofs_delta_children(base->obj->idx.offset,
998 &base->ofs_first, &base->ofs_last,
999 OBJ_OFS_DELTA);
1000
1001 if (base->ref_last == -1 && base->ofs_last == -1) {
1002 free(base->data);
1003 return NULL;
1004 }
1005
1006 link_base_data(prev_base, base);
1007 }
1008
1009 if (base->ref_first <= base->ref_last) {
1010 struct object_entry *child = objects + ref_deltas[base->ref_first].obj_no;
1011 struct base_data *result = alloc_base_data();
1012
1013 if (!compare_and_swap_type(&child->real_type, OBJ_REF_DELTA,
1014 base->obj->real_type))
1015 die("BUG: child->real_type != OBJ_REF_DELTA");
1016
1017 resolve_delta(child, base, result);
1018 if (base->ref_first == base->ref_last && base->ofs_last == -1)
1019 free_base_data(base);
1020
1021 base->ref_first++;
1022 return result;
1023 }
1024
1025 if (base->ofs_first <= base->ofs_last) {
1026 struct object_entry *child = objects + ofs_deltas[base->ofs_first].obj_no;
1027 struct base_data *result = alloc_base_data();
1028
1029 assert(child->real_type == OBJ_OFS_DELTA);
1030 child->real_type = base->obj->real_type;
1031 resolve_delta(child, base, result);
1032 if (base->ofs_first == base->ofs_last)
1033 free_base_data(base);
1034
1035 base->ofs_first++;
1036 return result;
1037 }
1038
1039 unlink_base_data(base);
1040 return NULL;
1041}
1042
1043static void find_unresolved_deltas(struct base_data *base)
1044{
1045 struct base_data *new_base, *prev_base = NULL;
1046 for (;;) {
1047 new_base = find_unresolved_deltas_1(base, prev_base);
1048
1049 if (new_base) {
1050 prev_base = base;
1051 base = new_base;
1052 } else {
1053 free(base);
1054 base = prev_base;
1055 if (!base)
1056 return;
1057 prev_base = base->base;
1058 }
1059 }
1060}
1061
1062static int compare_ofs_delta_entry(const void *a, const void *b)
1063{
1064 const struct ofs_delta_entry *delta_a = a;
1065 const struct ofs_delta_entry *delta_b = b;
1066
1067 return delta_a->offset < delta_b->offset ? -1 :
1068 delta_a->offset > delta_b->offset ? 1 :
1069 0;
1070}
1071
1072static int compare_ref_delta_entry(const void *a, const void *b)
1073{
1074 const struct ref_delta_entry *delta_a = a;
1075 const struct ref_delta_entry *delta_b = b;
1076
1077 return hashcmp(delta_a->sha1, delta_b->sha1);
1078}
1079
1080static void resolve_base(struct object_entry *obj)
1081{
1082 struct base_data *base_obj = alloc_base_data();
1083 base_obj->obj = obj;
1084 base_obj->data = NULL;
1085 find_unresolved_deltas(base_obj);
1086}
1087
1088#ifndef NO_PTHREADS
1089static void *threaded_second_pass(void *data)
1090{
1091 set_thread_data(data);
1092 for (;;) {
1093 int i;
1094 counter_lock();
1095 display_progress(progress, nr_resolved_deltas);
1096 counter_unlock();
1097 work_lock();
1098 while (nr_dispatched < nr_objects &&
1099 is_delta_type(objects[nr_dispatched].type))
1100 nr_dispatched++;
1101 if (nr_dispatched >= nr_objects) {
1102 work_unlock();
1103 break;
1104 }
1105 i = nr_dispatched++;
1106 work_unlock();
1107
1108 resolve_base(&objects[i]);
1109 }
1110 return NULL;
1111}
1112#endif
1113
1114/*
1115 * First pass:
1116 * - find locations of all objects;
1117 * - calculate SHA1 of all non-delta objects;
1118 * - remember base (SHA1 or offset) for all deltas.
1119 */
1120static void parse_pack_objects(unsigned char *sha1)
1121{
1122 int i, nr_delays = 0;
1123 struct ofs_delta_entry *ofs_delta = ofs_deltas;
1124 unsigned char ref_delta_sha1[20];
1125 struct stat st;
1126
1127 if (verbose)
1128 progress = start_progress(
1129 from_stdin ? _("Receiving objects") : _("Indexing objects"),
1130 nr_objects);
1131 for (i = 0; i < nr_objects; i++) {
1132 struct object_entry *obj = &objects[i];
1133 void *data = unpack_raw_entry(obj, &ofs_delta->offset,
1134 ref_delta_sha1, obj->idx.sha1);
1135 obj->real_type = obj->type;
1136 if (obj->type == OBJ_OFS_DELTA) {
1137 nr_ofs_deltas++;
1138 ofs_delta->obj_no = i;
1139 ofs_delta++;
1140 } else if (obj->type == OBJ_REF_DELTA) {
1141 ALLOC_GROW(ref_deltas, nr_ref_deltas + 1, ref_deltas_alloc);
1142 hashcpy(ref_deltas[nr_ref_deltas].sha1, ref_delta_sha1);
1143 ref_deltas[nr_ref_deltas].obj_no = i;
1144 nr_ref_deltas++;
1145 } else if (!data) {
1146 /* large blobs, check later */
1147 obj->real_type = OBJ_BAD;
1148 nr_delays++;
1149 } else
1150 sha1_object(data, NULL, obj->size, obj->type, obj->idx.sha1);
1151 free(data);
1152 display_progress(progress, i+1);
1153 }
1154 objects[i].idx.offset = consumed_bytes;
1155 stop_progress(&progress);
1156
1157 /* Check pack integrity */
1158 flush();
1159 git_SHA1_Final(sha1, &input_ctx);
1160 if (hashcmp(fill(20), sha1))
1161 die(_("pack is corrupted (SHA1 mismatch)"));
1162 use(20);
1163
1164 /* If input_fd is a file, we should have reached its end now. */
1165 if (fstat(input_fd, &st))
1166 die_errno(_("cannot fstat packfile"));
1167 if (S_ISREG(st.st_mode) &&
1168 lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
1169 die(_("pack has junk at the end"));
1170
1171 for (i = 0; i < nr_objects; i++) {
1172 struct object_entry *obj = &objects[i];
1173 if (obj->real_type != OBJ_BAD)
1174 continue;
1175 obj->real_type = obj->type;
1176 sha1_object(NULL, obj, obj->size, obj->type, obj->idx.sha1);
1177 nr_delays--;
1178 }
1179 if (nr_delays)
1180 die(_("confusion beyond insanity in parse_pack_objects()"));
1181}
1182
1183/*
1184 * Second pass:
1185 * - for all non-delta objects, look if it is used as a base for
1186 * deltas;
1187 * - if used as a base, uncompress the object and apply all deltas,
1188 * recursively checking if the resulting object is used as a base
1189 * for some more deltas.
1190 */
1191static void resolve_deltas(void)
1192{
1193 int i;
1194
1195 if (!nr_ofs_deltas && !nr_ref_deltas)
1196 return;
1197
1198 /* Sort deltas by base SHA1/offset for fast searching */
1199 QSORT(ofs_deltas, nr_ofs_deltas, compare_ofs_delta_entry);
1200 QSORT(ref_deltas, nr_ref_deltas, compare_ref_delta_entry);
1201
1202 if (verbose || show_resolving_progress)
1203 progress = start_progress(_("Resolving deltas"),
1204 nr_ref_deltas + nr_ofs_deltas);
1205
1206#ifndef NO_PTHREADS
1207 nr_dispatched = 0;
1208 if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
1209 init_thread();
1210 for (i = 0; i < nr_threads; i++) {
1211 int ret = pthread_create(&thread_data[i].thread, NULL,
1212 threaded_second_pass, thread_data + i);
1213 if (ret)
1214 die(_("unable to create thread: %s"),
1215 strerror(ret));
1216 }
1217 for (i = 0; i < nr_threads; i++)
1218 pthread_join(thread_data[i].thread, NULL);
1219 cleanup_thread();
1220 return;
1221 }
1222#endif
1223
1224 for (i = 0; i < nr_objects; i++) {
1225 struct object_entry *obj = &objects[i];
1226
1227 if (is_delta_type(obj->type))
1228 continue;
1229 resolve_base(obj);
1230 display_progress(progress, nr_resolved_deltas);
1231 }
1232}
1233
1234/*
1235 * Third pass:
1236 * - append objects to convert thin pack to full pack if required
1237 * - write the final 20-byte SHA-1
1238 */
1239static void fix_unresolved_deltas(struct sha1file *f);
1240static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
1241{
1242 if (nr_ref_deltas + nr_ofs_deltas == nr_resolved_deltas) {
1243 stop_progress(&progress);
1244 /* Flush remaining pack final 20-byte SHA1. */
1245 flush();
1246 return;
1247 }
1248
1249 if (fix_thin_pack) {
1250 struct sha1file *f;
1251 unsigned char read_sha1[20], tail_sha1[20];
1252 struct strbuf msg = STRBUF_INIT;
1253 int nr_unresolved = nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas;
1254 int nr_objects_initial = nr_objects;
1255 if (nr_unresolved <= 0)
1256 die(_("confusion beyond insanity"));
1257 REALLOC_ARRAY(objects, nr_objects + nr_unresolved + 1);
1258 memset(objects + nr_objects + 1, 0,
1259 nr_unresolved * sizeof(*objects));
1260 f = sha1fd(output_fd, curr_pack);
1261 fix_unresolved_deltas(f);
1262 strbuf_addf(&msg, Q_("completed with %d local object",
1263 "completed with %d local objects",
1264 nr_objects - nr_objects_initial),
1265 nr_objects - nr_objects_initial);
1266 stop_progress_msg(&progress, msg.buf);
1267 strbuf_release(&msg);
1268 sha1close(f, tail_sha1, 0);
1269 hashcpy(read_sha1, pack_sha1);
1270 fixup_pack_header_footer(output_fd, pack_sha1,
1271 curr_pack, nr_objects,
1272 read_sha1, consumed_bytes-20);
1273 if (hashcmp(read_sha1, tail_sha1) != 0)
1274 die(_("Unexpected tail checksum for %s "
1275 "(disk corruption?)"), curr_pack);
1276 }
1277 if (nr_ofs_deltas + nr_ref_deltas != nr_resolved_deltas)
1278 die(Q_("pack has %d unresolved delta",
1279 "pack has %d unresolved deltas",
1280 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas),
1281 nr_ofs_deltas + nr_ref_deltas - nr_resolved_deltas);
1282}
1283
1284static int write_compressed(struct sha1file *f, void *in, unsigned int size)
1285{
1286 git_zstream stream;
1287 int status;
1288 unsigned char outbuf[4096];
1289
1290 git_deflate_init(&stream, zlib_compression_level);
1291 stream.next_in = in;
1292 stream.avail_in = size;
1293
1294 do {
1295 stream.next_out = outbuf;
1296 stream.avail_out = sizeof(outbuf);
1297 status = git_deflate(&stream, Z_FINISH);
1298 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
1299 } while (status == Z_OK);
1300
1301 if (status != Z_STREAM_END)
1302 die(_("unable to deflate appended object (%d)"), status);
1303 size = stream.total_out;
1304 git_deflate_end(&stream);
1305 return size;
1306}
1307
1308static struct object_entry *append_obj_to_pack(struct sha1file *f,
1309 const unsigned char *sha1, void *buf,
1310 unsigned long size, enum object_type type)
1311{
1312 struct object_entry *obj = &objects[nr_objects++];
1313 unsigned char header[10];
1314 unsigned long s = size;
1315 int n = 0;
1316 unsigned char c = (type << 4) | (s & 15);
1317 s >>= 4;
1318 while (s) {
1319 header[n++] = c | 0x80;
1320 c = s & 0x7f;
1321 s >>= 7;
1322 }
1323 header[n++] = c;
1324 crc32_begin(f);
1325 sha1write(f, header, n);
1326 obj[0].size = size;
1327 obj[0].hdr_size = n;
1328 obj[0].type = type;
1329 obj[0].real_type = type;
1330 obj[1].idx.offset = obj[0].idx.offset + n;
1331 obj[1].idx.offset += write_compressed(f, buf, size);
1332 obj[0].idx.crc32 = crc32_end(f);
1333 sha1flush(f);
1334 hashcpy(obj->idx.sha1, sha1);
1335 return obj;
1336}
1337
1338static int delta_pos_compare(const void *_a, const void *_b)
1339{
1340 struct ref_delta_entry *a = *(struct ref_delta_entry **)_a;
1341 struct ref_delta_entry *b = *(struct ref_delta_entry **)_b;
1342 return a->obj_no - b->obj_no;
1343}
1344
1345static void fix_unresolved_deltas(struct sha1file *f)
1346{
1347 struct ref_delta_entry **sorted_by_pos;
1348 int i;
1349
1350 /*
1351 * Since many unresolved deltas may well be themselves base objects
1352 * for more unresolved deltas, we really want to include the
1353 * smallest number of base objects that would cover as much delta
1354 * as possible by picking the
1355 * trunc deltas first, allowing for other deltas to resolve without
1356 * additional base objects. Since most base objects are to be found
1357 * before deltas depending on them, a good heuristic is to start
1358 * resolving deltas in the same order as their position in the pack.
1359 */
1360 ALLOC_ARRAY(sorted_by_pos, nr_ref_deltas);
1361 for (i = 0; i < nr_ref_deltas; i++)
1362 sorted_by_pos[i] = &ref_deltas[i];
1363 QSORT(sorted_by_pos, nr_ref_deltas, delta_pos_compare);
1364
1365 for (i = 0; i < nr_ref_deltas; i++) {
1366 struct ref_delta_entry *d = sorted_by_pos[i];
1367 enum object_type type;
1368 struct base_data *base_obj = alloc_base_data();
1369
1370 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1371 continue;
1372 base_obj->data = read_sha1_file(d->sha1, &type, &base_obj->size);
1373 if (!base_obj->data)
1374 continue;
1375
1376 if (check_sha1_signature(d->sha1, base_obj->data,
1377 base_obj->size, typename(type)))
1378 die(_("local object %s is corrupt"), sha1_to_hex(d->sha1));
1379 base_obj->obj = append_obj_to_pack(f, d->sha1,
1380 base_obj->data, base_obj->size, type);
1381 find_unresolved_deltas(base_obj);
1382 display_progress(progress, nr_resolved_deltas);
1383 }
1384 free(sorted_by_pos);
1385}
1386
1387static void final(const char *final_pack_name, const char *curr_pack_name,
1388 const char *final_index_name, const char *curr_index_name,
1389 const char *keep_name, const char *keep_msg,
1390 unsigned char *sha1)
1391{
1392 const char *report = "pack";
1393 struct strbuf pack_name = STRBUF_INIT;
1394 struct strbuf index_name = STRBUF_INIT;
1395 struct strbuf keep_name_buf = STRBUF_INIT;
1396 int err;
1397
1398 if (!from_stdin) {
1399 close(input_fd);
1400 } else {
1401 fsync_or_die(output_fd, curr_pack_name);
1402 err = close(output_fd);
1403 if (err)
1404 die_errno(_("error while closing pack file"));
1405 }
1406
1407 if (keep_msg) {
1408 int keep_fd, keep_msg_len = strlen(keep_msg);
1409
1410 if (!keep_name)
1411 keep_name = odb_pack_name(&keep_name_buf, sha1, "keep");
1412
1413 keep_fd = odb_pack_keep(keep_name);
1414 if (keep_fd < 0) {
1415 if (errno != EEXIST)
1416 die_errno(_("cannot write keep file '%s'"),
1417 keep_name);
1418 } else {
1419 if (keep_msg_len > 0) {
1420 write_or_die(keep_fd, keep_msg, keep_msg_len);
1421 write_or_die(keep_fd, "\n", 1);
1422 }
1423 if (close(keep_fd) != 0)
1424 die_errno(_("cannot close written keep file '%s'"),
1425 keep_name);
1426 report = "keep";
1427 }
1428 }
1429
1430 if (final_pack_name != curr_pack_name) {
1431 if (!final_pack_name)
1432 final_pack_name = odb_pack_name(&pack_name, sha1, "pack");
1433 if (finalize_object_file(curr_pack_name, final_pack_name))
1434 die(_("cannot store pack file"));
1435 } else if (from_stdin)
1436 chmod(final_pack_name, 0444);
1437
1438 if (final_index_name != curr_index_name) {
1439 if (!final_index_name)
1440 final_index_name = odb_pack_name(&index_name, sha1, "idx");
1441 if (finalize_object_file(curr_index_name, final_index_name))
1442 die(_("cannot store index file"));
1443 } else
1444 chmod(final_index_name, 0444);
1445
1446 if (!from_stdin) {
1447 printf("%s\n", sha1_to_hex(sha1));
1448 } else {
1449 struct strbuf buf = STRBUF_INIT;
1450
1451 strbuf_addf(&buf, "%s\t%s\n", report, sha1_to_hex(sha1));
1452 write_or_die(1, buf.buf, buf.len);
1453 strbuf_release(&buf);
1454
1455 /*
1456 * Let's just mimic git-unpack-objects here and write
1457 * the last part of the input buffer to stdout.
1458 */
1459 while (input_len) {
1460 err = xwrite(1, input_buffer + input_offset, input_len);
1461 if (err <= 0)
1462 break;
1463 input_len -= err;
1464 input_offset += err;
1465 }
1466 }
1467
1468 strbuf_release(&index_name);
1469 strbuf_release(&pack_name);
1470 strbuf_release(&keep_name_buf);
1471}
1472
1473static int git_index_pack_config(const char *k, const char *v, void *cb)
1474{
1475 struct pack_idx_option *opts = cb;
1476
1477 if (!strcmp(k, "pack.indexversion")) {
1478 opts->version = git_config_int(k, v);
1479 if (opts->version > 2)
1480 die(_("bad pack.indexversion=%"PRIu32), opts->version);
1481 return 0;
1482 }
1483 if (!strcmp(k, "pack.threads")) {
1484 nr_threads = git_config_int(k, v);
1485 if (nr_threads < 0)
1486 die(_("invalid number of threads specified (%d)"),
1487 nr_threads);
1488#ifdef NO_PTHREADS
1489 if (nr_threads != 1)
1490 warning(_("no threads support, ignoring %s"), k);
1491 nr_threads = 1;
1492#endif
1493 return 0;
1494 }
1495 return git_default_config(k, v, cb);
1496}
1497
1498static int cmp_uint32(const void *a_, const void *b_)
1499{
1500 uint32_t a = *((uint32_t *)a_);
1501 uint32_t b = *((uint32_t *)b_);
1502
1503 return (a < b) ? -1 : (a != b);
1504}
1505
1506static void read_v2_anomalous_offsets(struct packed_git *p,
1507 struct pack_idx_option *opts)
1508{
1509 const uint32_t *idx1, *idx2;
1510 uint32_t i;
1511
1512 /* The address of the 4-byte offset table */
1513 idx1 = (((const uint32_t *)p->index_data)
1514 + 2 /* 8-byte header */
1515 + 256 /* fan out */
1516 + 5 * p->num_objects /* 20-byte SHA-1 table */
1517 + p->num_objects /* CRC32 table */
1518 );
1519
1520 /* The address of the 8-byte offset table */
1521 idx2 = idx1 + p->num_objects;
1522
1523 for (i = 0; i < p->num_objects; i++) {
1524 uint32_t off = ntohl(idx1[i]);
1525 if (!(off & 0x80000000))
1526 continue;
1527 off = off & 0x7fffffff;
1528 check_pack_index_ptr(p, &idx2[off * 2]);
1529 if (idx2[off * 2])
1530 continue;
1531 /*
1532 * The real offset is ntohl(idx2[off * 2]) in high 4
1533 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1534 * octets. But idx2[off * 2] is Zero!!!
1535 */
1536 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1537 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1538 }
1539
1540 QSORT(opts->anomaly, opts->anomaly_nr, cmp_uint32);
1541}
1542
1543static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1544{
1545 struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1546
1547 if (!p)
1548 die(_("Cannot open existing pack file '%s'"), pack_name);
1549 if (open_pack_index(p))
1550 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1551
1552 /* Read the attributes from the existing idx file */
1553 opts->version = p->index_version;
1554
1555 if (opts->version == 2)
1556 read_v2_anomalous_offsets(p, opts);
1557
1558 /*
1559 * Get rid of the idx file as we do not need it anymore.
1560 * NEEDSWORK: extract this bit from free_pack_by_name() in
1561 * sha1_file.c, perhaps? It shouldn't matter very much as we
1562 * know we haven't installed this pack (hence we never have
1563 * read anything from it).
1564 */
1565 close_pack_index(p);
1566 free(p);
1567}
1568
1569static void show_pack_info(int stat_only)
1570{
1571 int i, baseobjects = nr_objects - nr_ref_deltas - nr_ofs_deltas;
1572 unsigned long *chain_histogram = NULL;
1573
1574 if (deepest_delta)
1575 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1576
1577 for (i = 0; i < nr_objects; i++) {
1578 struct object_entry *obj = &objects[i];
1579
1580 if (is_delta_type(obj->type))
1581 chain_histogram[obj_stat[i].delta_depth - 1]++;
1582 if (stat_only)
1583 continue;
1584 printf("%s %-6s %lu %lu %"PRIuMAX,
1585 sha1_to_hex(obj->idx.sha1),
1586 typename(obj->real_type), obj->size,
1587 (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1588 (uintmax_t)obj->idx.offset);
1589 if (is_delta_type(obj->type)) {
1590 struct object_entry *bobj = &objects[obj_stat[i].base_object_no];
1591 printf(" %u %s", obj_stat[i].delta_depth, sha1_to_hex(bobj->idx.sha1));
1592 }
1593 putchar('\n');
1594 }
1595
1596 if (baseobjects)
1597 printf_ln(Q_("non delta: %d object",
1598 "non delta: %d objects",
1599 baseobjects),
1600 baseobjects);
1601 for (i = 0; i < deepest_delta; i++) {
1602 if (!chain_histogram[i])
1603 continue;
1604 printf_ln(Q_("chain length = %d: %lu object",
1605 "chain length = %d: %lu objects",
1606 chain_histogram[i]),
1607 i + 1,
1608 chain_histogram[i]);
1609 }
1610}
1611
1612static const char *derive_filename(const char *pack_name, const char *suffix,
1613 struct strbuf *buf)
1614{
1615 size_t len;
1616 if (!strip_suffix(pack_name, ".pack", &len))
1617 die(_("packfile name '%s' does not end with '.pack'"),
1618 pack_name);
1619 strbuf_add(buf, pack_name, len);
1620 strbuf_addstr(buf, suffix);
1621 return buf->buf;
1622}
1623
1624int cmd_index_pack(int argc, const char **argv, const char *prefix)
1625{
1626 int i, fix_thin_pack = 0, verify = 0, stat_only = 0;
1627 const char *curr_index;
1628 const char *index_name = NULL, *pack_name = NULL;
1629 const char *keep_name = NULL, *keep_msg = NULL;
1630 struct strbuf index_name_buf = STRBUF_INIT,
1631 keep_name_buf = STRBUF_INIT;
1632 struct pack_idx_entry **idx_objects;
1633 struct pack_idx_option opts;
1634 unsigned char pack_sha1[20];
1635 unsigned foreign_nr = 1; /* zero is a "good" value, assume bad */
1636 int report_end_of_input = 0;
1637
1638 if (argc == 2 && !strcmp(argv[1], "-h"))
1639 usage(index_pack_usage);
1640
1641 check_replace_refs = 0;
1642 fsck_options.walk = mark_link;
1643
1644 reset_pack_idx_option(&opts);
1645 git_config(git_index_pack_config, &opts);
1646 if (prefix && chdir(prefix))
1647 die(_("Cannot come back to cwd"));
1648
1649 for (i = 1; i < argc; i++) {
1650 const char *arg = argv[i];
1651
1652 if (*arg == '-') {
1653 if (!strcmp(arg, "--stdin")) {
1654 from_stdin = 1;
1655 } else if (!strcmp(arg, "--fix-thin")) {
1656 fix_thin_pack = 1;
1657 } else if (!strcmp(arg, "--strict")) {
1658 strict = 1;
1659 do_fsck_object = 1;
1660 } else if (skip_prefix(arg, "--strict=", &arg)) {
1661 strict = 1;
1662 do_fsck_object = 1;
1663 fsck_set_msg_types(&fsck_options, arg);
1664 } else if (!strcmp(arg, "--check-self-contained-and-connected")) {
1665 strict = 1;
1666 check_self_contained_and_connected = 1;
1667 } else if (!strcmp(arg, "--verify")) {
1668 verify = 1;
1669 } else if (!strcmp(arg, "--verify-stat")) {
1670 verify = 1;
1671 show_stat = 1;
1672 } else if (!strcmp(arg, "--verify-stat-only")) {
1673 verify = 1;
1674 show_stat = 1;
1675 stat_only = 1;
1676 } else if (!strcmp(arg, "--keep")) {
1677 keep_msg = "";
1678 } else if (starts_with(arg, "--keep=")) {
1679 keep_msg = arg + 7;
1680 } else if (starts_with(arg, "--threads=")) {
1681 char *end;
1682 nr_threads = strtoul(arg+10, &end, 0);
1683 if (!arg[10] || *end || nr_threads < 0)
1684 usage(index_pack_usage);
1685#ifdef NO_PTHREADS
1686 if (nr_threads != 1)
1687 warning(_("no threads support, "
1688 "ignoring %s"), arg);
1689 nr_threads = 1;
1690#endif
1691 } else if (starts_with(arg, "--pack_header=")) {
1692 struct pack_header *hdr;
1693 char *c;
1694
1695 hdr = (struct pack_header *)input_buffer;
1696 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1697 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1698 if (*c != ',')
1699 die(_("bad %s"), arg);
1700 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1701 if (*c)
1702 die(_("bad %s"), arg);
1703 input_len = sizeof(*hdr);
1704 } else if (!strcmp(arg, "-v")) {
1705 verbose = 1;
1706 } else if (!strcmp(arg, "--show-resolving-progress")) {
1707 show_resolving_progress = 1;
1708 } else if (!strcmp(arg, "--report-end-of-input")) {
1709 report_end_of_input = 1;
1710 } else if (!strcmp(arg, "-o")) {
1711 if (index_name || (i+1) >= argc)
1712 usage(index_pack_usage);
1713 index_name = argv[++i];
1714 } else if (starts_with(arg, "--index-version=")) {
1715 char *c;
1716 opts.version = strtoul(arg + 16, &c, 10);
1717 if (opts.version > 2)
1718 die(_("bad %s"), arg);
1719 if (*c == ',')
1720 opts.off32_limit = strtoul(c+1, &c, 0);
1721 if (*c || opts.off32_limit & 0x80000000)
1722 die(_("bad %s"), arg);
1723 } else if (skip_prefix(arg, "--max-input-size=", &arg)) {
1724 max_input_size = strtoumax(arg, NULL, 10);
1725 } else
1726 usage(index_pack_usage);
1727 continue;
1728 }
1729
1730 if (pack_name)
1731 usage(index_pack_usage);
1732 pack_name = arg;
1733 }
1734
1735 if (!pack_name && !from_stdin)
1736 usage(index_pack_usage);
1737 if (fix_thin_pack && !from_stdin)
1738 die(_("--fix-thin cannot be used without --stdin"));
1739 if (from_stdin && !startup_info->have_repository)
1740 die(_("--stdin requires a git repository"));
1741 if (!index_name && pack_name)
1742 index_name = derive_filename(pack_name, ".idx", &index_name_buf);
1743 if (keep_msg && !keep_name && pack_name)
1744 keep_name = derive_filename(pack_name, ".keep", &keep_name_buf);
1745
1746 if (verify) {
1747 if (!index_name)
1748 die(_("--verify with no packfile name given"));
1749 read_idx_option(&opts, index_name);
1750 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1751 }
1752 if (strict)
1753 opts.flags |= WRITE_IDX_STRICT;
1754
1755#ifndef NO_PTHREADS
1756 if (!nr_threads) {
1757 nr_threads = online_cpus();
1758 /* An experiment showed that more threads does not mean faster */
1759 if (nr_threads > 3)
1760 nr_threads = 3;
1761 }
1762#endif
1763
1764 curr_pack = open_pack_file(pack_name);
1765 parse_pack_header();
1766 objects = xcalloc(st_add(nr_objects, 1), sizeof(struct object_entry));
1767 if (show_stat)
1768 obj_stat = xcalloc(st_add(nr_objects, 1), sizeof(struct object_stat));
1769 ofs_deltas = xcalloc(nr_objects, sizeof(struct ofs_delta_entry));
1770 parse_pack_objects(pack_sha1);
1771 if (report_end_of_input)
1772 write_in_full(2, "\0", 1);
1773 resolve_deltas();
1774 conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
1775 free(ofs_deltas);
1776 free(ref_deltas);
1777 if (strict)
1778 foreign_nr = check_objects();
1779
1780 if (show_stat)
1781 show_pack_info(stat_only);
1782
1783 ALLOC_ARRAY(idx_objects, nr_objects);
1784 for (i = 0; i < nr_objects; i++)
1785 idx_objects[i] = &objects[i].idx;
1786 curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1787 free(idx_objects);
1788
1789 if (!verify)
1790 final(pack_name, curr_pack,
1791 index_name, curr_index,
1792 keep_name, keep_msg,
1793 pack_sha1);
1794 else
1795 close(input_fd);
1796 free(objects);
1797 strbuf_release(&index_name_buf);
1798 strbuf_release(&keep_name_buf);
1799 if (pack_name == NULL)
1800 free((void *) curr_pack);
1801 if (index_name == NULL)
1802 free((void *) curr_index);
1803
1804 /*
1805 * Let the caller know this pack is not self contained
1806 */
1807 if (check_self_contained_and_connected && foreign_nr)
1808 return 1;
1809
1810 return 0;
1811}