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