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