index-pack: factor out unpack core from get_data_from_pack
[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         static char fixed_buf[8192];
396         int status;
397         git_zstream stream;
398         void *buf;
399         git_SHA_CTX c;
400         char hdr[32];
401         int hdrlen;
402
403         if (!is_delta_type(type)) {
404                 hdrlen = sprintf(hdr, "%s %lu", typename(type), size) + 1;
405                 git_SHA1_Init(&c);
406                 git_SHA1_Update(&c, hdr, hdrlen);
407         } else
408                 sha1 = NULL;
409         if (type == OBJ_BLOB && size > big_file_threshold)
410                 buf = fixed_buf;
411         else
412                 buf = xmalloc(size);
413
414         memset(&stream, 0, sizeof(stream));
415         git_inflate_init(&stream);
416         stream.next_out = buf;
417         stream.avail_out = buf == fixed_buf ? sizeof(fixed_buf) : size;
418
419         do {
420                 unsigned char *last_out = stream.next_out;
421                 stream.next_in = fill(1);
422                 stream.avail_in = input_len;
423                 status = git_inflate(&stream, 0);
424                 use(input_len - stream.avail_in);
425                 if (sha1)
426                         git_SHA1_Update(&c, last_out, stream.next_out - last_out);
427                 if (buf == fixed_buf) {
428                         stream.next_out = buf;
429                         stream.avail_out = sizeof(fixed_buf);
430                 }
431         } while (status == Z_OK);
432         if (stream.total_out != size || status != Z_STREAM_END)
433                 bad_object(offset, _("inflate returned %d"), status);
434         git_inflate_end(&stream);
435         if (sha1)
436                 git_SHA1_Final(sha1, &c);
437         return buf == fixed_buf ? NULL : buf;
438 }
439
440 static void *unpack_raw_entry(struct object_entry *obj,
441                               union delta_base *delta_base,
442                               unsigned char *sha1)
443 {
444         unsigned char *p;
445         unsigned long size, c;
446         off_t base_offset;
447         unsigned shift;
448         void *data;
449
450         obj->idx.offset = consumed_bytes;
451         input_crc32 = crc32(0, NULL, 0);
452
453         p = fill(1);
454         c = *p;
455         use(1);
456         obj->type = (c >> 4) & 7;
457         size = (c & 15);
458         shift = 4;
459         while (c & 0x80) {
460                 p = fill(1);
461                 c = *p;
462                 use(1);
463                 size += (c & 0x7f) << shift;
464                 shift += 7;
465         }
466         obj->size = size;
467
468         switch (obj->type) {
469         case OBJ_REF_DELTA:
470                 hashcpy(delta_base->sha1, fill(20));
471                 use(20);
472                 break;
473         case OBJ_OFS_DELTA:
474                 memset(delta_base, 0, sizeof(*delta_base));
475                 p = fill(1);
476                 c = *p;
477                 use(1);
478                 base_offset = c & 127;
479                 while (c & 128) {
480                         base_offset += 1;
481                         if (!base_offset || MSB(base_offset, 7))
482                                 bad_object(obj->idx.offset, _("offset value overflow for delta base object"));
483                         p = fill(1);
484                         c = *p;
485                         use(1);
486                         base_offset = (base_offset << 7) + (c & 127);
487                 }
488                 delta_base->offset = obj->idx.offset - base_offset;
489                 if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
490                         bad_object(obj->idx.offset, _("delta base offset is out of bound"));
491                 break;
492         case OBJ_COMMIT:
493         case OBJ_TREE:
494         case OBJ_BLOB:
495         case OBJ_TAG:
496                 break;
497         default:
498                 bad_object(obj->idx.offset, _("unknown object type %d"), obj->type);
499         }
500         obj->hdr_size = consumed_bytes - obj->idx.offset;
501
502         data = unpack_entry_data(obj->idx.offset, obj->size, obj->type, sha1);
503         obj->idx.crc32 = input_crc32;
504         return data;
505 }
506
507 static void *unpack_data(struct object_entry *obj,
508                          int (*consume)(const unsigned char *, unsigned long, void *),
509                          void *cb_data)
510 {
511         off_t from = obj[0].idx.offset + obj[0].hdr_size;
512         unsigned long len = obj[1].idx.offset - from;
513         unsigned char *data, *inbuf;
514         git_zstream stream;
515         int status;
516
517         data = xmalloc(consume ? 64*1024 : obj->size);
518         inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
519
520         memset(&stream, 0, sizeof(stream));
521         git_inflate_init(&stream);
522         stream.next_out = data;
523         stream.avail_out = consume ? 64*1024 : obj->size;
524
525         do {
526                 unsigned char *last_out = stream.next_out;
527                 ssize_t n = (len < 64*1024) ? len : 64*1024;
528                 n = pread(pack_fd, inbuf, n, from);
529                 if (n < 0)
530                         die_errno(_("cannot pread pack file"));
531                 if (!n)
532                         die(Q_("premature end of pack file, %lu byte missing",
533                                "premature end of pack file, %lu bytes missing",
534                                len),
535                             len);
536                 from += n;
537                 len -= n;
538                 stream.next_in = inbuf;
539                 stream.avail_in = n;
540                 status = git_inflate(&stream, 0);
541                 if (consume) {
542                         if (consume(last_out, stream.next_out - last_out, cb_data)) {
543                                 free(inbuf);
544                                 free(data);
545                                 return NULL;
546                         }
547                         stream.next_out = data;
548                         stream.avail_out = 64*1024;
549                 }
550         } while (len && status == Z_OK && !stream.avail_in);
551
552         /* This has been inflated OK when first encountered, so... */
553         if (status != Z_STREAM_END || stream.total_out != obj->size)
554                 die(_("serious inflate inconsistency"));
555
556         git_inflate_end(&stream);
557         free(inbuf);
558         if (consume) {
559                 free(data);
560                 data = NULL;
561         }
562         return data;
563 }
564
565 static void *get_data_from_pack(struct object_entry *obj)
566 {
567         return unpack_data(obj, NULL, NULL);
568 }
569
570 static int compare_delta_bases(const union delta_base *base1,
571                                const union delta_base *base2,
572                                enum object_type type1,
573                                enum object_type type2)
574 {
575         int cmp = type1 - type2;
576         if (cmp)
577                 return cmp;
578         return memcmp(base1, base2, UNION_BASE_SZ);
579 }
580
581 static int find_delta(const union delta_base *base, enum object_type type)
582 {
583         int first = 0, last = nr_deltas;
584
585         while (first < last) {
586                 int next = (first + last) / 2;
587                 struct delta_entry *delta = &deltas[next];
588                 int cmp;
589
590                 cmp = compare_delta_bases(base, &delta->base,
591                                           type, objects[delta->obj_no].type);
592                 if (!cmp)
593                         return next;
594                 if (cmp < 0) {
595                         last = next;
596                         continue;
597                 }
598                 first = next+1;
599         }
600         return -first-1;
601 }
602
603 static void find_delta_children(const union delta_base *base,
604                                 int *first_index, int *last_index,
605                                 enum object_type type)
606 {
607         int first = find_delta(base, type);
608         int last = first;
609         int end = nr_deltas - 1;
610
611         if (first < 0) {
612                 *first_index = 0;
613                 *last_index = -1;
614                 return;
615         }
616         while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
617                 --first;
618         while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
619                 ++last;
620         *first_index = first;
621         *last_index = last;
622 }
623
624 static void sha1_object(const void *data, struct object_entry *obj_entry,
625                         unsigned long size, enum object_type type,
626                         const unsigned char *sha1)
627 {
628         void *new_data = NULL;
629
630         assert(data || obj_entry);
631
632         read_lock();
633         if (has_sha1_file(sha1)) {
634                 void *has_data;
635                 enum object_type has_type;
636                 unsigned long has_size;
637                 if (!data)
638                         data = new_data = get_data_from_pack(obj_entry);
639                 has_data = read_sha1_file(sha1, &has_type, &has_size);
640                 read_unlock();
641                 if (!has_data)
642                         die(_("cannot read existing object %s"), sha1_to_hex(sha1));
643                 if (size != has_size || type != has_type ||
644                     memcmp(data, has_data, size) != 0)
645                         die(_("SHA1 COLLISION FOUND WITH %s !"), sha1_to_hex(sha1));
646                 free(has_data);
647         } else
648                 read_unlock();
649
650         if (strict) {
651                 read_lock();
652                 if (type == OBJ_BLOB) {
653                         struct blob *blob = lookup_blob(sha1);
654                         if (blob)
655                                 blob->object.flags |= FLAG_CHECKED;
656                         else
657                                 die(_("invalid blob object %s"), sha1_to_hex(sha1));
658                 } else {
659                         struct object *obj;
660                         int eaten;
661                         void *buf = (void *) data;
662
663                         if (!buf)
664                                 buf = new_data = get_data_from_pack(obj_entry);
665
666                         /*
667                          * we do not need to free the memory here, as the
668                          * buf is deleted by the caller.
669                          */
670                         obj = parse_object_buffer(sha1, type, size, buf, &eaten);
671                         if (!obj)
672                                 die(_("invalid %s"), typename(type));
673                         if (fsck_object(obj, 1, fsck_error_function))
674                                 die(_("Error in object"));
675                         if (fsck_walk(obj, mark_link, NULL))
676                                 die(_("Not all child objects of %s are reachable"), sha1_to_hex(obj->sha1));
677
678                         if (obj->type == OBJ_TREE) {
679                                 struct tree *item = (struct tree *) obj;
680                                 item->buffer = NULL;
681                         }
682                         if (obj->type == OBJ_COMMIT) {
683                                 struct commit *commit = (struct commit *) obj;
684                                 commit->buffer = NULL;
685                         }
686                         obj->flags |= FLAG_CHECKED;
687                 }
688                 read_unlock();
689         }
690
691         free(new_data);
692 }
693
694 /*
695  * This function is part of find_unresolved_deltas(). There are two
696  * walkers going in the opposite ways.
697  *
698  * The first one in find_unresolved_deltas() traverses down from
699  * parent node to children, deflating nodes along the way. However,
700  * memory for deflated nodes is limited by delta_base_cache_limit, so
701  * at some point parent node's deflated content may be freed.
702  *
703  * The second walker is this function, which goes from current node up
704  * to top parent if necessary to deflate the node. In normal
705  * situation, its parent node would be already deflated, so it just
706  * needs to apply delta.
707  *
708  * In the worst case scenario, parent node is no longer deflated because
709  * we're running out of delta_base_cache_limit; we need to re-deflate
710  * parents, possibly up to the top base.
711  *
712  * All deflated objects here are subject to be freed if we exceed
713  * delta_base_cache_limit, just like in find_unresolved_deltas(), we
714  * just need to make sure the last node is not freed.
715  */
716 static void *get_base_data(struct base_data *c)
717 {
718         if (!c->data) {
719                 struct object_entry *obj = c->obj;
720                 struct base_data **delta = NULL;
721                 int delta_nr = 0, delta_alloc = 0;
722
723                 while (is_delta_type(c->obj->type) && !c->data) {
724                         ALLOC_GROW(delta, delta_nr + 1, delta_alloc);
725                         delta[delta_nr++] = c;
726                         c = c->base;
727                 }
728                 if (!delta_nr) {
729                         c->data = get_data_from_pack(obj);
730                         c->size = obj->size;
731                         get_thread_data()->base_cache_used += c->size;
732                         prune_base_data(c);
733                 }
734                 for (; delta_nr > 0; delta_nr--) {
735                         void *base, *raw;
736                         c = delta[delta_nr - 1];
737                         obj = c->obj;
738                         base = get_base_data(c->base);
739                         raw = get_data_from_pack(obj);
740                         c->data = patch_delta(
741                                 base, c->base->size,
742                                 raw, obj->size,
743                                 &c->size);
744                         free(raw);
745                         if (!c->data)
746                                 bad_object(obj->idx.offset, _("failed to apply delta"));
747                         get_thread_data()->base_cache_used += c->size;
748                         prune_base_data(c);
749                 }
750                 free(delta);
751         }
752         return c->data;
753 }
754
755 static void resolve_delta(struct object_entry *delta_obj,
756                           struct base_data *base, struct base_data *result)
757 {
758         void *base_data, *delta_data;
759
760         delta_obj->real_type = base->obj->real_type;
761         delta_obj->delta_depth = base->obj->delta_depth + 1;
762         if (deepest_delta < delta_obj->delta_depth)
763                 deepest_delta = delta_obj->delta_depth;
764         delta_obj->base_object_no = base->obj - objects;
765         delta_data = get_data_from_pack(delta_obj);
766         base_data = get_base_data(base);
767         result->obj = delta_obj;
768         result->data = patch_delta(base_data, base->size,
769                                    delta_data, delta_obj->size, &result->size);
770         free(delta_data);
771         if (!result->data)
772                 bad_object(delta_obj->idx.offset, _("failed to apply delta"));
773         hash_sha1_file(result->data, result->size,
774                        typename(delta_obj->real_type), delta_obj->idx.sha1);
775         sha1_object(result->data, NULL, result->size, delta_obj->real_type,
776                     delta_obj->idx.sha1);
777         counter_lock();
778         nr_resolved_deltas++;
779         counter_unlock();
780 }
781
782 static struct base_data *find_unresolved_deltas_1(struct base_data *base,
783                                                   struct base_data *prev_base)
784 {
785         if (base->ref_last == -1 && base->ofs_last == -1) {
786                 union delta_base base_spec;
787
788                 hashcpy(base_spec.sha1, base->obj->idx.sha1);
789                 find_delta_children(&base_spec,
790                                     &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
791
792                 memset(&base_spec, 0, sizeof(base_spec));
793                 base_spec.offset = base->obj->idx.offset;
794                 find_delta_children(&base_spec,
795                                     &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
796
797                 if (base->ref_last == -1 && base->ofs_last == -1) {
798                         free(base->data);
799                         return NULL;
800                 }
801
802                 link_base_data(prev_base, base);
803         }
804
805         if (base->ref_first <= base->ref_last) {
806                 struct object_entry *child = objects + deltas[base->ref_first].obj_no;
807                 struct base_data *result = alloc_base_data();
808
809                 assert(child->real_type == OBJ_REF_DELTA);
810                 resolve_delta(child, base, result);
811                 if (base->ref_first == base->ref_last && base->ofs_last == -1)
812                         free_base_data(base);
813
814                 base->ref_first++;
815                 return result;
816         }
817
818         if (base->ofs_first <= base->ofs_last) {
819                 struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
820                 struct base_data *result = alloc_base_data();
821
822                 assert(child->real_type == OBJ_OFS_DELTA);
823                 resolve_delta(child, base, result);
824                 if (base->ofs_first == base->ofs_last)
825                         free_base_data(base);
826
827                 base->ofs_first++;
828                 return result;
829         }
830
831         unlink_base_data(base);
832         return NULL;
833 }
834
835 static void find_unresolved_deltas(struct base_data *base)
836 {
837         struct base_data *new_base, *prev_base = NULL;
838         for (;;) {
839                 new_base = find_unresolved_deltas_1(base, prev_base);
840
841                 if (new_base) {
842                         prev_base = base;
843                         base = new_base;
844                 } else {
845                         free(base);
846                         base = prev_base;
847                         if (!base)
848                                 return;
849                         prev_base = base->base;
850                 }
851         }
852 }
853
854 static int compare_delta_entry(const void *a, const void *b)
855 {
856         const struct delta_entry *delta_a = a;
857         const struct delta_entry *delta_b = b;
858
859         /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
860         return compare_delta_bases(&delta_a->base, &delta_b->base,
861                                    objects[delta_a->obj_no].type,
862                                    objects[delta_b->obj_no].type);
863 }
864
865 static void resolve_base(struct object_entry *obj)
866 {
867         struct base_data *base_obj = alloc_base_data();
868         base_obj->obj = obj;
869         base_obj->data = NULL;
870         find_unresolved_deltas(base_obj);
871 }
872
873 #ifndef NO_PTHREADS
874 static void *threaded_second_pass(void *data)
875 {
876         set_thread_data(data);
877         for (;;) {
878                 int i;
879                 work_lock();
880                 display_progress(progress, nr_resolved_deltas);
881                 while (nr_dispatched < nr_objects &&
882                        is_delta_type(objects[nr_dispatched].type))
883                         nr_dispatched++;
884                 if (nr_dispatched >= nr_objects) {
885                         work_unlock();
886                         break;
887                 }
888                 i = nr_dispatched++;
889                 work_unlock();
890
891                 resolve_base(&objects[i]);
892         }
893         return NULL;
894 }
895 #endif
896
897 /*
898  * First pass:
899  * - find locations of all objects;
900  * - calculate SHA1 of all non-delta objects;
901  * - remember base (SHA1 or offset) for all deltas.
902  */
903 static void parse_pack_objects(unsigned char *sha1)
904 {
905         int i, nr_delays = 0;
906         struct delta_entry *delta = deltas;
907         struct stat st;
908
909         if (verbose)
910                 progress = start_progress(
911                                 from_stdin ? _("Receiving objects") : _("Indexing objects"),
912                                 nr_objects);
913         for (i = 0; i < nr_objects; i++) {
914                 struct object_entry *obj = &objects[i];
915                 void *data = unpack_raw_entry(obj, &delta->base, obj->idx.sha1);
916                 obj->real_type = obj->type;
917                 if (is_delta_type(obj->type)) {
918                         nr_deltas++;
919                         delta->obj_no = i;
920                         delta++;
921                 } else if (!data) {
922                         /* large blobs, check later */
923                         obj->real_type = OBJ_BAD;
924                         nr_delays++;
925                 } else
926                         sha1_object(data, NULL, obj->size, obj->type, obj->idx.sha1);
927                 free(data);
928                 display_progress(progress, i+1);
929         }
930         objects[i].idx.offset = consumed_bytes;
931         stop_progress(&progress);
932
933         /* Check pack integrity */
934         flush();
935         git_SHA1_Final(sha1, &input_ctx);
936         if (hashcmp(fill(20), sha1))
937                 die(_("pack is corrupted (SHA1 mismatch)"));
938         use(20);
939
940         /* If input_fd is a file, we should have reached its end now. */
941         if (fstat(input_fd, &st))
942                 die_errno(_("cannot fstat packfile"));
943         if (S_ISREG(st.st_mode) &&
944                         lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
945                 die(_("pack has junk at the end"));
946
947         for (i = 0; i < nr_objects; i++) {
948                 struct object_entry *obj = &objects[i];
949                 if (obj->real_type != OBJ_BAD)
950                         continue;
951                 obj->real_type = obj->type;
952                 sha1_object(NULL, obj, obj->size, obj->type, obj->idx.sha1);
953                 nr_delays--;
954         }
955         if (nr_delays)
956                 die(_("confusion beyond insanity in parse_pack_objects()"));
957 }
958
959 /*
960  * Second pass:
961  * - for all non-delta objects, look if it is used as a base for
962  *   deltas;
963  * - if used as a base, uncompress the object and apply all deltas,
964  *   recursively checking if the resulting object is used as a base
965  *   for some more deltas.
966  */
967 static void resolve_deltas(void)
968 {
969         int i;
970
971         if (!nr_deltas)
972                 return;
973
974         /* Sort deltas by base SHA1/offset for fast searching */
975         qsort(deltas, nr_deltas, sizeof(struct delta_entry),
976               compare_delta_entry);
977
978         if (verbose)
979                 progress = start_progress(_("Resolving deltas"), nr_deltas);
980
981 #ifndef NO_PTHREADS
982         nr_dispatched = 0;
983         if (nr_threads > 1 || getenv("GIT_FORCE_THREADS")) {
984                 init_thread();
985                 for (i = 0; i < nr_threads; i++) {
986                         int ret = pthread_create(&thread_data[i].thread, NULL,
987                                                  threaded_second_pass, thread_data + i);
988                         if (ret)
989                                 die("unable to create thread: %s", strerror(ret));
990                 }
991                 for (i = 0; i < nr_threads; i++)
992                         pthread_join(thread_data[i].thread, NULL);
993                 cleanup_thread();
994                 return;
995         }
996 #endif
997
998         for (i = 0; i < nr_objects; i++) {
999                 struct object_entry *obj = &objects[i];
1000
1001                 if (is_delta_type(obj->type))
1002                         continue;
1003                 resolve_base(obj);
1004                 display_progress(progress, nr_resolved_deltas);
1005         }
1006 }
1007
1008 /*
1009  * Third pass:
1010  * - append objects to convert thin pack to full pack if required
1011  * - write the final 20-byte SHA-1
1012  */
1013 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved);
1014 static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned char *pack_sha1)
1015 {
1016         if (nr_deltas == nr_resolved_deltas) {
1017                 stop_progress(&progress);
1018                 /* Flush remaining pack final 20-byte SHA1. */
1019                 flush();
1020                 return;
1021         }
1022
1023         if (fix_thin_pack) {
1024                 struct sha1file *f;
1025                 unsigned char read_sha1[20], tail_sha1[20];
1026                 char msg[48];
1027                 int nr_unresolved = nr_deltas - nr_resolved_deltas;
1028                 int nr_objects_initial = nr_objects;
1029                 if (nr_unresolved <= 0)
1030                         die(_("confusion beyond insanity"));
1031                 objects = xrealloc(objects,
1032                                    (nr_objects + nr_unresolved + 1)
1033                                    * sizeof(*objects));
1034                 f = sha1fd(output_fd, curr_pack);
1035                 fix_unresolved_deltas(f, nr_unresolved);
1036                 sprintf(msg, "completed with %d local objects",
1037                         nr_objects - nr_objects_initial);
1038                 stop_progress_msg(&progress, msg);
1039                 sha1close(f, tail_sha1, 0);
1040                 hashcpy(read_sha1, pack_sha1);
1041                 fixup_pack_header_footer(output_fd, pack_sha1,
1042                                          curr_pack, nr_objects,
1043                                          read_sha1, consumed_bytes-20);
1044                 if (hashcmp(read_sha1, tail_sha1) != 0)
1045                         die("Unexpected tail checksum for %s "
1046                             "(disk corruption?)", curr_pack);
1047         }
1048         if (nr_deltas != nr_resolved_deltas)
1049                 die(Q_("pack has %d unresolved delta",
1050                        "pack has %d unresolved deltas",
1051                        nr_deltas - nr_resolved_deltas),
1052                     nr_deltas - nr_resolved_deltas);
1053 }
1054
1055 static int write_compressed(struct sha1file *f, void *in, unsigned int size)
1056 {
1057         git_zstream stream;
1058         int status;
1059         unsigned char outbuf[4096];
1060
1061         memset(&stream, 0, sizeof(stream));
1062         git_deflate_init(&stream, zlib_compression_level);
1063         stream.next_in = in;
1064         stream.avail_in = size;
1065
1066         do {
1067                 stream.next_out = outbuf;
1068                 stream.avail_out = sizeof(outbuf);
1069                 status = git_deflate(&stream, Z_FINISH);
1070                 sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
1071         } while (status == Z_OK);
1072
1073         if (status != Z_STREAM_END)
1074                 die(_("unable to deflate appended object (%d)"), status);
1075         size = stream.total_out;
1076         git_deflate_end(&stream);
1077         return size;
1078 }
1079
1080 static struct object_entry *append_obj_to_pack(struct sha1file *f,
1081                                const unsigned char *sha1, void *buf,
1082                                unsigned long size, enum object_type type)
1083 {
1084         struct object_entry *obj = &objects[nr_objects++];
1085         unsigned char header[10];
1086         unsigned long s = size;
1087         int n = 0;
1088         unsigned char c = (type << 4) | (s & 15);
1089         s >>= 4;
1090         while (s) {
1091                 header[n++] = c | 0x80;
1092                 c = s & 0x7f;
1093                 s >>= 7;
1094         }
1095         header[n++] = c;
1096         crc32_begin(f);
1097         sha1write(f, header, n);
1098         obj[0].size = size;
1099         obj[0].hdr_size = n;
1100         obj[0].type = type;
1101         obj[0].real_type = type;
1102         obj[1].idx.offset = obj[0].idx.offset + n;
1103         obj[1].idx.offset += write_compressed(f, buf, size);
1104         obj[0].idx.crc32 = crc32_end(f);
1105         sha1flush(f);
1106         hashcpy(obj->idx.sha1, sha1);
1107         return obj;
1108 }
1109
1110 static int delta_pos_compare(const void *_a, const void *_b)
1111 {
1112         struct delta_entry *a = *(struct delta_entry **)_a;
1113         struct delta_entry *b = *(struct delta_entry **)_b;
1114         return a->obj_no - b->obj_no;
1115 }
1116
1117 static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
1118 {
1119         struct delta_entry **sorted_by_pos;
1120         int i, n = 0;
1121
1122         /*
1123          * Since many unresolved deltas may well be themselves base objects
1124          * for more unresolved deltas, we really want to include the
1125          * smallest number of base objects that would cover as much delta
1126          * as possible by picking the
1127          * trunc deltas first, allowing for other deltas to resolve without
1128          * additional base objects.  Since most base objects are to be found
1129          * before deltas depending on them, a good heuristic is to start
1130          * resolving deltas in the same order as their position in the pack.
1131          */
1132         sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
1133         for (i = 0; i < nr_deltas; i++) {
1134                 if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
1135                         continue;
1136                 sorted_by_pos[n++] = &deltas[i];
1137         }
1138         qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
1139
1140         for (i = 0; i < n; i++) {
1141                 struct delta_entry *d = sorted_by_pos[i];
1142                 enum object_type type;
1143                 struct base_data *base_obj = alloc_base_data();
1144
1145                 if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
1146                         continue;
1147                 base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
1148                 if (!base_obj->data)
1149                         continue;
1150
1151                 if (check_sha1_signature(d->base.sha1, base_obj->data,
1152                                 base_obj->size, typename(type)))
1153                         die(_("local object %s is corrupt"), sha1_to_hex(d->base.sha1));
1154                 base_obj->obj = append_obj_to_pack(f, d->base.sha1,
1155                                         base_obj->data, base_obj->size, type);
1156                 find_unresolved_deltas(base_obj);
1157                 display_progress(progress, nr_resolved_deltas);
1158         }
1159         free(sorted_by_pos);
1160 }
1161
1162 static void final(const char *final_pack_name, const char *curr_pack_name,
1163                   const char *final_index_name, const char *curr_index_name,
1164                   const char *keep_name, const char *keep_msg,
1165                   unsigned char *sha1)
1166 {
1167         const char *report = "pack";
1168         char name[PATH_MAX];
1169         int err;
1170
1171         if (!from_stdin) {
1172                 close(input_fd);
1173         } else {
1174                 fsync_or_die(output_fd, curr_pack_name);
1175                 err = close(output_fd);
1176                 if (err)
1177                         die_errno(_("error while closing pack file"));
1178         }
1179
1180         if (keep_msg) {
1181                 int keep_fd, keep_msg_len = strlen(keep_msg);
1182
1183                 if (!keep_name)
1184                         keep_fd = odb_pack_keep(name, sizeof(name), sha1);
1185                 else
1186                         keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
1187
1188                 if (keep_fd < 0) {
1189                         if (errno != EEXIST)
1190                                 die_errno(_("cannot write keep file '%s'"),
1191                                           keep_name);
1192                 } else {
1193                         if (keep_msg_len > 0) {
1194                                 write_or_die(keep_fd, keep_msg, keep_msg_len);
1195                                 write_or_die(keep_fd, "\n", 1);
1196                         }
1197                         if (close(keep_fd) != 0)
1198                                 die_errno(_("cannot close written keep file '%s'"),
1199                                     keep_name);
1200                         report = "keep";
1201                 }
1202         }
1203
1204         if (final_pack_name != curr_pack_name) {
1205                 if (!final_pack_name) {
1206                         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
1207                                  get_object_directory(), sha1_to_hex(sha1));
1208                         final_pack_name = name;
1209                 }
1210                 if (move_temp_to_file(curr_pack_name, final_pack_name))
1211                         die(_("cannot store pack file"));
1212         } else if (from_stdin)
1213                 chmod(final_pack_name, 0444);
1214
1215         if (final_index_name != curr_index_name) {
1216                 if (!final_index_name) {
1217                         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
1218                                  get_object_directory(), sha1_to_hex(sha1));
1219                         final_index_name = name;
1220                 }
1221                 if (move_temp_to_file(curr_index_name, final_index_name))
1222                         die(_("cannot store index file"));
1223         } else
1224                 chmod(final_index_name, 0444);
1225
1226         if (!from_stdin) {
1227                 printf("%s\n", sha1_to_hex(sha1));
1228         } else {
1229                 char buf[48];
1230                 int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
1231                                    report, sha1_to_hex(sha1));
1232                 write_or_die(1, buf, len);
1233
1234                 /*
1235                  * Let's just mimic git-unpack-objects here and write
1236                  * the last part of the input buffer to stdout.
1237                  */
1238                 while (input_len) {
1239                         err = xwrite(1, input_buffer + input_offset, input_len);
1240                         if (err <= 0)
1241                                 break;
1242                         input_len -= err;
1243                         input_offset += err;
1244                 }
1245         }
1246 }
1247
1248 static int git_index_pack_config(const char *k, const char *v, void *cb)
1249 {
1250         struct pack_idx_option *opts = cb;
1251
1252         if (!strcmp(k, "pack.indexversion")) {
1253                 opts->version = git_config_int(k, v);
1254                 if (opts->version > 2)
1255                         die("bad pack.indexversion=%"PRIu32, opts->version);
1256                 return 0;
1257         }
1258         if (!strcmp(k, "pack.threads")) {
1259                 nr_threads = git_config_int(k, v);
1260                 if (nr_threads < 0)
1261                         die("invalid number of threads specified (%d)",
1262                             nr_threads);
1263 #ifdef NO_PTHREADS
1264                 if (nr_threads != 1)
1265                         warning("no threads support, ignoring %s", k);
1266                 nr_threads = 1;
1267 #endif
1268                 return 0;
1269         }
1270         return git_default_config(k, v, cb);
1271 }
1272
1273 static int cmp_uint32(const void *a_, const void *b_)
1274 {
1275         uint32_t a = *((uint32_t *)a_);
1276         uint32_t b = *((uint32_t *)b_);
1277
1278         return (a < b) ? -1 : (a != b);
1279 }
1280
1281 static void read_v2_anomalous_offsets(struct packed_git *p,
1282                                       struct pack_idx_option *opts)
1283 {
1284         const uint32_t *idx1, *idx2;
1285         uint32_t i;
1286
1287         /* The address of the 4-byte offset table */
1288         idx1 = (((const uint32_t *)p->index_data)
1289                 + 2 /* 8-byte header */
1290                 + 256 /* fan out */
1291                 + 5 * p->num_objects /* 20-byte SHA-1 table */
1292                 + p->num_objects /* CRC32 table */
1293                 );
1294
1295         /* The address of the 8-byte offset table */
1296         idx2 = idx1 + p->num_objects;
1297
1298         for (i = 0; i < p->num_objects; i++) {
1299                 uint32_t off = ntohl(idx1[i]);
1300                 if (!(off & 0x80000000))
1301                         continue;
1302                 off = off & 0x7fffffff;
1303                 if (idx2[off * 2])
1304                         continue;
1305                 /*
1306                  * The real offset is ntohl(idx2[off * 2]) in high 4
1307                  * octets, and ntohl(idx2[off * 2 + 1]) in low 4
1308                  * octets.  But idx2[off * 2] is Zero!!!
1309                  */
1310                 ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
1311                 opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
1312         }
1313
1314         if (1 < opts->anomaly_nr)
1315                 qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
1316 }
1317
1318 static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
1319 {
1320         struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
1321
1322         if (!p)
1323                 die(_("Cannot open existing pack file '%s'"), pack_name);
1324         if (open_pack_index(p))
1325                 die(_("Cannot open existing pack idx file for '%s'"), pack_name);
1326
1327         /* Read the attributes from the existing idx file */
1328         opts->version = p->index_version;
1329
1330         if (opts->version == 2)
1331                 read_v2_anomalous_offsets(p, opts);
1332
1333         /*
1334          * Get rid of the idx file as we do not need it anymore.
1335          * NEEDSWORK: extract this bit from free_pack_by_name() in
1336          * sha1_file.c, perhaps?  It shouldn't matter very much as we
1337          * know we haven't installed this pack (hence we never have
1338          * read anything from it).
1339          */
1340         close_pack_index(p);
1341         free(p);
1342 }
1343
1344 static void show_pack_info(int stat_only)
1345 {
1346         int i, baseobjects = nr_objects - nr_deltas;
1347         unsigned long *chain_histogram = NULL;
1348
1349         if (deepest_delta)
1350                 chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1351
1352         for (i = 0; i < nr_objects; i++) {
1353                 struct object_entry *obj = &objects[i];
1354
1355                 if (is_delta_type(obj->type))
1356                         chain_histogram[obj->delta_depth - 1]++;
1357                 if (stat_only)
1358                         continue;
1359                 printf("%s %-6s %lu %lu %"PRIuMAX,
1360                        sha1_to_hex(obj->idx.sha1),
1361                        typename(obj->real_type), obj->size,
1362                        (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1363                        (uintmax_t)obj->idx.offset);
1364                 if (is_delta_type(obj->type)) {
1365                         struct object_entry *bobj = &objects[obj->base_object_no];
1366                         printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1367                 }
1368                 putchar('\n');
1369         }
1370
1371         if (baseobjects)
1372                 printf_ln(Q_("non delta: %d object",
1373                              "non delta: %d objects",
1374                              baseobjects),
1375                           baseobjects);
1376         for (i = 0; i < deepest_delta; i++) {
1377                 if (!chain_histogram[i])
1378                         continue;
1379                 printf_ln(Q_("chain length = %d: %lu object",
1380                              "chain length = %d: %lu objects",
1381                              chain_histogram[i]),
1382                           i + 1,
1383                           chain_histogram[i]);
1384         }
1385 }
1386
1387 int cmd_index_pack(int argc, const char **argv, const char *prefix)
1388 {
1389         int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
1390         const char *curr_pack, *curr_index;
1391         const char *index_name = NULL, *pack_name = NULL;
1392         const char *keep_name = NULL, *keep_msg = NULL;
1393         char *index_name_buf = NULL, *keep_name_buf = NULL;
1394         struct pack_idx_entry **idx_objects;
1395         struct pack_idx_option opts;
1396         unsigned char pack_sha1[20];
1397
1398         if (argc == 2 && !strcmp(argv[1], "-h"))
1399                 usage(index_pack_usage);
1400
1401         read_replace_refs = 0;
1402
1403         reset_pack_idx_option(&opts);
1404         git_config(git_index_pack_config, &opts);
1405         if (prefix && chdir(prefix))
1406                 die(_("Cannot come back to cwd"));
1407
1408         for (i = 1; i < argc; i++) {
1409                 const char *arg = argv[i];
1410
1411                 if (*arg == '-') {
1412                         if (!strcmp(arg, "--stdin")) {
1413                                 from_stdin = 1;
1414                         } else if (!strcmp(arg, "--fix-thin")) {
1415                                 fix_thin_pack = 1;
1416                         } else if (!strcmp(arg, "--strict")) {
1417                                 strict = 1;
1418                         } else if (!strcmp(arg, "--verify")) {
1419                                 verify = 1;
1420                         } else if (!strcmp(arg, "--verify-stat")) {
1421                                 verify = 1;
1422                                 stat = 1;
1423                         } else if (!strcmp(arg, "--verify-stat-only")) {
1424                                 verify = 1;
1425                                 stat = 1;
1426                                 stat_only = 1;
1427                         } else if (!strcmp(arg, "--keep")) {
1428                                 keep_msg = "";
1429                         } else if (!prefixcmp(arg, "--keep=")) {
1430                                 keep_msg = arg + 7;
1431                         } else if (!prefixcmp(arg, "--threads=")) {
1432                                 char *end;
1433                                 nr_threads = strtoul(arg+10, &end, 0);
1434                                 if (!arg[10] || *end || nr_threads < 0)
1435                                         usage(index_pack_usage);
1436 #ifdef NO_PTHREADS
1437                                 if (nr_threads != 1)
1438                                         warning("no threads support, "
1439                                                 "ignoring %s", arg);
1440                                 nr_threads = 1;
1441 #endif
1442                         } else if (!prefixcmp(arg, "--pack_header=")) {
1443                                 struct pack_header *hdr;
1444                                 char *c;
1445
1446                                 hdr = (struct pack_header *)input_buffer;
1447                                 hdr->hdr_signature = htonl(PACK_SIGNATURE);
1448                                 hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1449                                 if (*c != ',')
1450                                         die(_("bad %s"), arg);
1451                                 hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1452                                 if (*c)
1453                                         die(_("bad %s"), arg);
1454                                 input_len = sizeof(*hdr);
1455                         } else if (!strcmp(arg, "-v")) {
1456                                 verbose = 1;
1457                         } else if (!strcmp(arg, "-o")) {
1458                                 if (index_name || (i+1) >= argc)
1459                                         usage(index_pack_usage);
1460                                 index_name = argv[++i];
1461                         } else if (!prefixcmp(arg, "--index-version=")) {
1462                                 char *c;
1463                                 opts.version = strtoul(arg + 16, &c, 10);
1464                                 if (opts.version > 2)
1465                                         die(_("bad %s"), arg);
1466                                 if (*c == ',')
1467                                         opts.off32_limit = strtoul(c+1, &c, 0);
1468                                 if (*c || opts.off32_limit & 0x80000000)
1469                                         die(_("bad %s"), arg);
1470                         } else
1471                                 usage(index_pack_usage);
1472                         continue;
1473                 }
1474
1475                 if (pack_name)
1476                         usage(index_pack_usage);
1477                 pack_name = arg;
1478         }
1479
1480         if (!pack_name && !from_stdin)
1481                 usage(index_pack_usage);
1482         if (fix_thin_pack && !from_stdin)
1483                 die(_("--fix-thin cannot be used without --stdin"));
1484         if (!index_name && pack_name) {
1485                 int len = strlen(pack_name);
1486                 if (!has_extension(pack_name, ".pack"))
1487                         die(_("packfile name '%s' does not end with '.pack'"),
1488                             pack_name);
1489                 index_name_buf = xmalloc(len);
1490                 memcpy(index_name_buf, pack_name, len - 5);
1491                 strcpy(index_name_buf + len - 5, ".idx");
1492                 index_name = index_name_buf;
1493         }
1494         if (keep_msg && !keep_name && pack_name) {
1495                 int len = strlen(pack_name);
1496                 if (!has_extension(pack_name, ".pack"))
1497                         die(_("packfile name '%s' does not end with '.pack'"),
1498                             pack_name);
1499                 keep_name_buf = xmalloc(len);
1500                 memcpy(keep_name_buf, pack_name, len - 5);
1501                 strcpy(keep_name_buf + len - 5, ".keep");
1502                 keep_name = keep_name_buf;
1503         }
1504         if (verify) {
1505                 if (!index_name)
1506                         die(_("--verify with no packfile name given"));
1507                 read_idx_option(&opts, index_name);
1508                 opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1509         }
1510         if (strict)
1511                 opts.flags |= WRITE_IDX_STRICT;
1512
1513 #ifndef NO_PTHREADS
1514         if (!nr_threads) {
1515                 nr_threads = online_cpus();
1516                 /* An experiment showed that more threads does not mean faster */
1517                 if (nr_threads > 3)
1518                         nr_threads = 3;
1519         }
1520 #endif
1521
1522         curr_pack = open_pack_file(pack_name);
1523         parse_pack_header();
1524         objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1525         deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
1526         parse_pack_objects(pack_sha1);
1527         resolve_deltas();
1528         conclude_pack(fix_thin_pack, curr_pack, pack_sha1);
1529         free(deltas);
1530         if (strict)
1531                 check_objects();
1532
1533         if (stat)
1534                 show_pack_info(stat_only);
1535
1536         idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1537         for (i = 0; i < nr_objects; i++)
1538                 idx_objects[i] = &objects[i].idx;
1539         curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1540         free(idx_objects);
1541
1542         if (!verify)
1543                 final(pack_name, curr_pack,
1544                       index_name, curr_index,
1545                       keep_name, keep_msg,
1546                       pack_sha1);
1547         else
1548                 close(input_fd);
1549         free(objects);
1550         free(index_name_buf);
1551         free(keep_name_buf);
1552         if (pack_name == NULL)
1553                 free((void *) curr_pack);
1554         if (index_name == NULL)
1555                 free((void *) curr_index);
1556
1557         return 0;
1558 }