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