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