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