38ff03a5cdab4eb6107b471daa156dfd57753be7
   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
 518static void *get_base_data(struct base_data *c)
 519{
 520        if (!c->data) {
 521                struct object_entry *obj = c->obj;
 522
 523                if (is_delta_type(obj->type)) {
 524                        void *base = get_base_data(c->base);
 525                        void *raw = get_data_from_pack(obj);
 526                        c->data = patch_delta(
 527                                base, c->base->size,
 528                                raw, obj->size,
 529                                &c->size);
 530                        free(raw);
 531                        if (!c->data)
 532                                bad_object(obj->idx.offset, "failed to apply delta");
 533                } else {
 534                        c->data = get_data_from_pack(obj);
 535                        c->size = obj->size;
 536                }
 537
 538                base_cache_used += c->size;
 539                prune_base_data(c);
 540        }
 541        return c->data;
 542}
 543
 544static void resolve_delta(struct object_entry *delta_obj,
 545                          struct base_data *base, struct base_data *result)
 546{
 547        void *base_data, *delta_data;
 548
 549        delta_obj->real_type = base->obj->real_type;
 550        delta_obj->delta_depth = base->obj->delta_depth + 1;
 551        if (deepest_delta < delta_obj->delta_depth)
 552                deepest_delta = delta_obj->delta_depth;
 553        delta_obj->base_object_no = base->obj - objects;
 554        delta_data = get_data_from_pack(delta_obj);
 555        base_data = get_base_data(base);
 556        result->obj = delta_obj;
 557        result->data = patch_delta(base_data, base->size,
 558                                   delta_data, delta_obj->size, &result->size);
 559        free(delta_data);
 560        if (!result->data)
 561                bad_object(delta_obj->idx.offset, "failed to apply delta");
 562        sha1_object(result->data, result->size, delta_obj->real_type,
 563                    delta_obj->idx.sha1);
 564        nr_resolved_deltas++;
 565}
 566
 567static struct base_data *find_unresolved_deltas_1(struct base_data *base,
 568                                                  struct base_data *prev_base)
 569{
 570        if (base->ref_last == -1 && base->ofs_last == -1) {
 571                union delta_base base_spec;
 572
 573                hashcpy(base_spec.sha1, base->obj->idx.sha1);
 574                find_delta_children(&base_spec,
 575                                    &base->ref_first, &base->ref_last, OBJ_REF_DELTA);
 576
 577                memset(&base_spec, 0, sizeof(base_spec));
 578                base_spec.offset = base->obj->idx.offset;
 579                find_delta_children(&base_spec,
 580                                    &base->ofs_first, &base->ofs_last, OBJ_OFS_DELTA);
 581
 582                if (base->ref_last == -1 && base->ofs_last == -1) {
 583                        free(base->data);
 584                        return NULL;
 585                }
 586
 587                link_base_data(prev_base, base);
 588        }
 589
 590        if (base->ref_first <= base->ref_last) {
 591                struct object_entry *child = objects + deltas[base->ref_first].obj_no;
 592                struct base_data *result = alloc_base_data();
 593
 594                assert(child->real_type == OBJ_REF_DELTA);
 595                resolve_delta(child, base, result);
 596                if (base->ref_first == base->ref_last && base->ofs_last == -1)
 597                        free_base_data(base);
 598
 599                base->ref_first++;
 600                return result;
 601        }
 602
 603        if (base->ofs_first <= base->ofs_last) {
 604                struct object_entry *child = objects + deltas[base->ofs_first].obj_no;
 605                struct base_data *result = alloc_base_data();
 606
 607                assert(child->real_type == OBJ_OFS_DELTA);
 608                resolve_delta(child, base, result);
 609                if (base->ofs_first == base->ofs_last)
 610                        free_base_data(base);
 611
 612                base->ofs_first++;
 613                return result;
 614        }
 615
 616        unlink_base_data(base);
 617        return NULL;
 618}
 619
 620static void find_unresolved_deltas(struct base_data *base)
 621{
 622        struct base_data *new_base, *prev_base = NULL;
 623        for (;;) {
 624                new_base = find_unresolved_deltas_1(base, prev_base);
 625
 626                if (new_base) {
 627                        prev_base = base;
 628                        base = new_base;
 629                } else {
 630                        free(base);
 631                        base = prev_base;
 632                        if (!base)
 633                                return;
 634                        prev_base = base->base;
 635                }
 636        }
 637}
 638
 639static int compare_delta_entry(const void *a, const void *b)
 640{
 641        const struct delta_entry *delta_a = a;
 642        const struct delta_entry *delta_b = b;
 643
 644        /* group by type (ref vs ofs) and then by value (sha-1 or offset) */
 645        return compare_delta_bases(&delta_a->base, &delta_b->base,
 646                                   objects[delta_a->obj_no].type,
 647                                   objects[delta_b->obj_no].type);
 648}
 649
 650/* Parse all objects and return the pack content SHA1 hash */
 651static void parse_pack_objects(unsigned char *sha1)
 652{
 653        int i;
 654        struct delta_entry *delta = deltas;
 655        struct stat st;
 656
 657        /*
 658         * First pass:
 659         * - find locations of all objects;
 660         * - calculate SHA1 of all non-delta objects;
 661         * - remember base (SHA1 or offset) for all deltas.
 662         */
 663        if (verbose)
 664                progress = start_progress(
 665                                from_stdin ? "Receiving objects" : "Indexing objects",
 666                                nr_objects);
 667        for (i = 0; i < nr_objects; i++) {
 668                struct object_entry *obj = &objects[i];
 669                void *data = unpack_raw_entry(obj, &delta->base);
 670                obj->real_type = obj->type;
 671                if (is_delta_type(obj->type)) {
 672                        nr_deltas++;
 673                        delta->obj_no = i;
 674                        delta++;
 675                } else
 676                        sha1_object(data, obj->size, obj->type, obj->idx.sha1);
 677                free(data);
 678                display_progress(progress, i+1);
 679        }
 680        objects[i].idx.offset = consumed_bytes;
 681        stop_progress(&progress);
 682
 683        /* Check pack integrity */
 684        flush();
 685        git_SHA1_Final(sha1, &input_ctx);
 686        if (hashcmp(fill(20), sha1))
 687                die("pack is corrupted (SHA1 mismatch)");
 688        use(20);
 689
 690        /* If input_fd is a file, we should have reached its end now. */
 691        if (fstat(input_fd, &st))
 692                die_errno("cannot fstat packfile");
 693        if (S_ISREG(st.st_mode) &&
 694                        lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
 695                die("pack has junk at the end");
 696
 697        if (!nr_deltas)
 698                return;
 699
 700        /* Sort deltas by base SHA1/offset for fast searching */
 701        qsort(deltas, nr_deltas, sizeof(struct delta_entry),
 702              compare_delta_entry);
 703
 704        /*
 705         * Second pass:
 706         * - for all non-delta objects, look if it is used as a base for
 707         *   deltas;
 708         * - if used as a base, uncompress the object and apply all deltas,
 709         *   recursively checking if the resulting object is used as a base
 710         *   for some more deltas.
 711         */
 712        if (verbose)
 713                progress = start_progress("Resolving deltas", nr_deltas);
 714        for (i = 0; i < nr_objects; i++) {
 715                struct object_entry *obj = &objects[i];
 716                struct base_data *base_obj = alloc_base_data();
 717
 718                if (is_delta_type(obj->type))
 719                        continue;
 720                base_obj->obj = obj;
 721                base_obj->data = NULL;
 722                find_unresolved_deltas(base_obj);
 723                display_progress(progress, nr_resolved_deltas);
 724        }
 725}
 726
 727static int write_compressed(struct sha1file *f, void *in, unsigned int size)
 728{
 729        git_zstream stream;
 730        int status;
 731        unsigned char outbuf[4096];
 732
 733        memset(&stream, 0, sizeof(stream));
 734        git_deflate_init(&stream, zlib_compression_level);
 735        stream.next_in = in;
 736        stream.avail_in = size;
 737
 738        do {
 739                stream.next_out = outbuf;
 740                stream.avail_out = sizeof(outbuf);
 741                status = git_deflate(&stream, Z_FINISH);
 742                sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
 743        } while (status == Z_OK);
 744
 745        if (status != Z_STREAM_END)
 746                die("unable to deflate appended object (%d)", status);
 747        size = stream.total_out;
 748        git_deflate_end(&stream);
 749        return size;
 750}
 751
 752static struct object_entry *append_obj_to_pack(struct sha1file *f,
 753                               const unsigned char *sha1, void *buf,
 754                               unsigned long size, enum object_type type)
 755{
 756        struct object_entry *obj = &objects[nr_objects++];
 757        unsigned char header[10];
 758        unsigned long s = size;
 759        int n = 0;
 760        unsigned char c = (type << 4) | (s & 15);
 761        s >>= 4;
 762        while (s) {
 763                header[n++] = c | 0x80;
 764                c = s & 0x7f;
 765                s >>= 7;
 766        }
 767        header[n++] = c;
 768        crc32_begin(f);
 769        sha1write(f, header, n);
 770        obj[0].size = size;
 771        obj[0].hdr_size = n;
 772        obj[0].type = type;
 773        obj[0].real_type = type;
 774        obj[1].idx.offset = obj[0].idx.offset + n;
 775        obj[1].idx.offset += write_compressed(f, buf, size);
 776        obj[0].idx.crc32 = crc32_end(f);
 777        sha1flush(f);
 778        hashcpy(obj->idx.sha1, sha1);
 779        return obj;
 780}
 781
 782static int delta_pos_compare(const void *_a, const void *_b)
 783{
 784        struct delta_entry *a = *(struct delta_entry **)_a;
 785        struct delta_entry *b = *(struct delta_entry **)_b;
 786        return a->obj_no - b->obj_no;
 787}
 788
 789static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
 790{
 791        struct delta_entry **sorted_by_pos;
 792        int i, n = 0;
 793
 794        /*
 795         * Since many unresolved deltas may well be themselves base objects
 796         * for more unresolved deltas, we really want to include the
 797         * smallest number of base objects that would cover as much delta
 798         * as possible by picking the
 799         * trunc deltas first, allowing for other deltas to resolve without
 800         * additional base objects.  Since most base objects are to be found
 801         * before deltas depending on them, a good heuristic is to start
 802         * resolving deltas in the same order as their position in the pack.
 803         */
 804        sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
 805        for (i = 0; i < nr_deltas; i++) {
 806                if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
 807                        continue;
 808                sorted_by_pos[n++] = &deltas[i];
 809        }
 810        qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
 811
 812        for (i = 0; i < n; i++) {
 813                struct delta_entry *d = sorted_by_pos[i];
 814                enum object_type type;
 815                struct base_data *base_obj = alloc_base_data();
 816
 817                if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
 818                        continue;
 819                base_obj->data = read_sha1_file(d->base.sha1, &type, &base_obj->size);
 820                if (!base_obj->data)
 821                        continue;
 822
 823                if (check_sha1_signature(d->base.sha1, base_obj->data,
 824                                base_obj->size, typename(type)))
 825                        die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
 826                base_obj->obj = append_obj_to_pack(f, d->base.sha1,
 827                                        base_obj->data, base_obj->size, type);
 828                find_unresolved_deltas(base_obj);
 829                display_progress(progress, nr_resolved_deltas);
 830        }
 831        free(sorted_by_pos);
 832}
 833
 834static void final(const char *final_pack_name, const char *curr_pack_name,
 835                  const char *final_index_name, const char *curr_index_name,
 836                  const char *keep_name, const char *keep_msg,
 837                  unsigned char *sha1)
 838{
 839        const char *report = "pack";
 840        char name[PATH_MAX];
 841        int err;
 842
 843        if (!from_stdin) {
 844                close(input_fd);
 845        } else {
 846                fsync_or_die(output_fd, curr_pack_name);
 847                err = close(output_fd);
 848                if (err)
 849                        die_errno("error while closing pack file");
 850        }
 851
 852        if (keep_msg) {
 853                int keep_fd, keep_msg_len = strlen(keep_msg);
 854
 855                if (!keep_name)
 856                        keep_fd = odb_pack_keep(name, sizeof(name), sha1);
 857                else
 858                        keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
 859
 860                if (keep_fd < 0) {
 861                        if (errno != EEXIST)
 862                                die_errno("cannot write keep file '%s'",
 863                                          keep_name);
 864                } else {
 865                        if (keep_msg_len > 0) {
 866                                write_or_die(keep_fd, keep_msg, keep_msg_len);
 867                                write_or_die(keep_fd, "\n", 1);
 868                        }
 869                        if (close(keep_fd) != 0)
 870                                die_errno("cannot close written keep file '%s'",
 871                                    keep_name);
 872                        report = "keep";
 873                }
 874        }
 875
 876        if (final_pack_name != curr_pack_name) {
 877                if (!final_pack_name) {
 878                        snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
 879                                 get_object_directory(), sha1_to_hex(sha1));
 880                        final_pack_name = name;
 881                }
 882                if (move_temp_to_file(curr_pack_name, final_pack_name))
 883                        die("cannot store pack file");
 884        } else if (from_stdin)
 885                chmod(final_pack_name, 0444);
 886
 887        if (final_index_name != curr_index_name) {
 888                if (!final_index_name) {
 889                        snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
 890                                 get_object_directory(), sha1_to_hex(sha1));
 891                        final_index_name = name;
 892                }
 893                if (move_temp_to_file(curr_index_name, final_index_name))
 894                        die("cannot store index file");
 895        } else
 896                chmod(final_index_name, 0444);
 897
 898        if (!from_stdin) {
 899                printf("%s\n", sha1_to_hex(sha1));
 900        } else {
 901                char buf[48];
 902                int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
 903                                   report, sha1_to_hex(sha1));
 904                write_or_die(1, buf, len);
 905
 906                /*
 907                 * Let's just mimic git-unpack-objects here and write
 908                 * the last part of the input buffer to stdout.
 909                 */
 910                while (input_len) {
 911                        err = xwrite(1, input_buffer + input_offset, input_len);
 912                        if (err <= 0)
 913                                break;
 914                        input_len -= err;
 915                        input_offset += err;
 916                }
 917        }
 918}
 919
 920static int git_index_pack_config(const char *k, const char *v, void *cb)
 921{
 922        struct pack_idx_option *opts = cb;
 923
 924        if (!strcmp(k, "pack.indexversion")) {
 925                opts->version = git_config_int(k, v);
 926                if (opts->version > 2)
 927                        die("bad pack.indexversion=%"PRIu32, opts->version);
 928                return 0;
 929        }
 930        return git_default_config(k, v, cb);
 931}
 932
 933static int cmp_uint32(const void *a_, const void *b_)
 934{
 935        uint32_t a = *((uint32_t *)a_);
 936        uint32_t b = *((uint32_t *)b_);
 937
 938        return (a < b) ? -1 : (a != b);
 939}
 940
 941static void read_v2_anomalous_offsets(struct packed_git *p,
 942                                      struct pack_idx_option *opts)
 943{
 944        const uint32_t *idx1, *idx2;
 945        uint32_t i;
 946
 947        /* The address of the 4-byte offset table */
 948        idx1 = (((const uint32_t *)p->index_data)
 949                + 2 /* 8-byte header */
 950                + 256 /* fan out */
 951                + 5 * p->num_objects /* 20-byte SHA-1 table */
 952                + p->num_objects /* CRC32 table */
 953                );
 954
 955        /* The address of the 8-byte offset table */
 956        idx2 = idx1 + p->num_objects;
 957
 958        for (i = 0; i < p->num_objects; i++) {
 959                uint32_t off = ntohl(idx1[i]);
 960                if (!(off & 0x80000000))
 961                        continue;
 962                off = off & 0x7fffffff;
 963                if (idx2[off * 2])
 964                        continue;
 965                /*
 966                 * The real offset is ntohl(idx2[off * 2]) in high 4
 967                 * octets, and ntohl(idx2[off * 2 + 1]) in low 4
 968                 * octets.  But idx2[off * 2] is Zero!!!
 969                 */
 970                ALLOC_GROW(opts->anomaly, opts->anomaly_nr + 1, opts->anomaly_alloc);
 971                opts->anomaly[opts->anomaly_nr++] = ntohl(idx2[off * 2 + 1]);
 972        }
 973
 974        if (1 < opts->anomaly_nr)
 975                qsort(opts->anomaly, opts->anomaly_nr, sizeof(uint32_t), cmp_uint32);
 976}
 977
 978static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
 979{
 980        struct packed_git *p = add_packed_git(pack_name, strlen(pack_name), 1);
 981
 982        if (!p)
 983                die("Cannot open existing pack file '%s'", pack_name);
 984        if (open_pack_index(p))
 985                die("Cannot open existing pack idx file for '%s'", pack_name);
 986
 987        /* Read the attributes from the existing idx file */
 988        opts->version = p->index_version;
 989
 990        if (opts->version == 2)
 991                read_v2_anomalous_offsets(p, opts);
 992
 993        /*
 994         * Get rid of the idx file as we do not need it anymore.
 995         * NEEDSWORK: extract this bit from free_pack_by_name() in
 996         * sha1_file.c, perhaps?  It shouldn't matter very much as we
 997         * know we haven't installed this pack (hence we never have
 998         * read anything from it).
 999         */
1000        close_pack_index(p);
1001        free(p);
1002}
1003
1004static void show_pack_info(int stat_only)
1005{
1006        int i, baseobjects = nr_objects - nr_deltas;
1007        unsigned long *chain_histogram = NULL;
1008
1009        if (deepest_delta)
1010                chain_histogram = xcalloc(deepest_delta, sizeof(unsigned long));
1011
1012        for (i = 0; i < nr_objects; i++) {
1013                struct object_entry *obj = &objects[i];
1014
1015                if (is_delta_type(obj->type))
1016                        chain_histogram[obj->delta_depth - 1]++;
1017                if (stat_only)
1018                        continue;
1019                printf("%s %-6s %lu %lu %"PRIuMAX,
1020                       sha1_to_hex(obj->idx.sha1),
1021                       typename(obj->real_type), obj->size,
1022                       (unsigned long)(obj[1].idx.offset - obj->idx.offset),
1023                       (uintmax_t)obj->idx.offset);
1024                if (is_delta_type(obj->type)) {
1025                        struct object_entry *bobj = &objects[obj->base_object_no];
1026                        printf(" %u %s", obj->delta_depth, sha1_to_hex(bobj->idx.sha1));
1027                }
1028                putchar('\n');
1029        }
1030
1031        if (baseobjects)
1032                printf("non delta: %d object%s\n",
1033                       baseobjects, baseobjects > 1 ? "s" : "");
1034        for (i = 0; i < deepest_delta; i++) {
1035                if (!chain_histogram[i])
1036                        continue;
1037                printf("chain length = %d: %lu object%s\n",
1038                       i + 1,
1039                       chain_histogram[i],
1040                       chain_histogram[i] > 1 ? "s" : "");
1041        }
1042}
1043
1044int cmd_index_pack(int argc, const char **argv, const char *prefix)
1045{
1046        int i, fix_thin_pack = 0, verify = 0, stat_only = 0, stat = 0;
1047        const char *curr_pack, *curr_index;
1048        const char *index_name = NULL, *pack_name = NULL;
1049        const char *keep_name = NULL, *keep_msg = NULL;
1050        char *index_name_buf = NULL, *keep_name_buf = NULL;
1051        struct pack_idx_entry **idx_objects;
1052        struct pack_idx_option opts;
1053        unsigned char pack_sha1[20];
1054
1055        if (argc == 2 && !strcmp(argv[1], "-h"))
1056                usage(index_pack_usage);
1057
1058        read_replace_refs = 0;
1059
1060        reset_pack_idx_option(&opts);
1061        git_config(git_index_pack_config, &opts);
1062        if (prefix && chdir(prefix))
1063                die("Cannot come back to cwd");
1064
1065        for (i = 1; i < argc; i++) {
1066                const char *arg = argv[i];
1067
1068                if (*arg == '-') {
1069                        if (!strcmp(arg, "--stdin")) {
1070                                from_stdin = 1;
1071                        } else if (!strcmp(arg, "--fix-thin")) {
1072                                fix_thin_pack = 1;
1073                        } else if (!strcmp(arg, "--strict")) {
1074                                strict = 1;
1075                        } else if (!strcmp(arg, "--verify")) {
1076                                verify = 1;
1077                        } else if (!strcmp(arg, "--verify-stat")) {
1078                                verify = 1;
1079                                stat = 1;
1080                        } else if (!strcmp(arg, "--verify-stat-only")) {
1081                                verify = 1;
1082                                stat = 1;
1083                                stat_only = 1;
1084                        } else if (!strcmp(arg, "--keep")) {
1085                                keep_msg = "";
1086                        } else if (!prefixcmp(arg, "--keep=")) {
1087                                keep_msg = arg + 7;
1088                        } else if (!prefixcmp(arg, "--pack_header=")) {
1089                                struct pack_header *hdr;
1090                                char *c;
1091
1092                                hdr = (struct pack_header *)input_buffer;
1093                                hdr->hdr_signature = htonl(PACK_SIGNATURE);
1094                                hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
1095                                if (*c != ',')
1096                                        die("bad %s", arg);
1097                                hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
1098                                if (*c)
1099                                        die("bad %s", arg);
1100                                input_len = sizeof(*hdr);
1101                        } else if (!strcmp(arg, "-v")) {
1102                                verbose = 1;
1103                        } else if (!strcmp(arg, "-o")) {
1104                                if (index_name || (i+1) >= argc)
1105                                        usage(index_pack_usage);
1106                                index_name = argv[++i];
1107                        } else if (!prefixcmp(arg, "--index-version=")) {
1108                                char *c;
1109                                opts.version = strtoul(arg + 16, &c, 10);
1110                                if (opts.version > 2)
1111                                        die("bad %s", arg);
1112                                if (*c == ',')
1113                                        opts.off32_limit = strtoul(c+1, &c, 0);
1114                                if (*c || opts.off32_limit & 0x80000000)
1115                                        die("bad %s", arg);
1116                        } else
1117                                usage(index_pack_usage);
1118                        continue;
1119                }
1120
1121                if (pack_name)
1122                        usage(index_pack_usage);
1123                pack_name = arg;
1124        }
1125
1126        if (!pack_name && !from_stdin)
1127                usage(index_pack_usage);
1128        if (fix_thin_pack && !from_stdin)
1129                die("--fix-thin cannot be used without --stdin");
1130        if (!index_name && pack_name) {
1131                int len = strlen(pack_name);
1132                if (!has_extension(pack_name, ".pack"))
1133                        die("packfile name '%s' does not end with '.pack'",
1134                            pack_name);
1135                index_name_buf = xmalloc(len);
1136                memcpy(index_name_buf, pack_name, len - 5);
1137                strcpy(index_name_buf + len - 5, ".idx");
1138                index_name = index_name_buf;
1139        }
1140        if (keep_msg && !keep_name && pack_name) {
1141                int len = strlen(pack_name);
1142                if (!has_extension(pack_name, ".pack"))
1143                        die("packfile name '%s' does not end with '.pack'",
1144                            pack_name);
1145                keep_name_buf = xmalloc(len);
1146                memcpy(keep_name_buf, pack_name, len - 5);
1147                strcpy(keep_name_buf + len - 5, ".keep");
1148                keep_name = keep_name_buf;
1149        }
1150        if (verify) {
1151                if (!index_name)
1152                        die("--verify with no packfile name given");
1153                read_idx_option(&opts, index_name);
1154                opts.flags |= WRITE_IDX_VERIFY | WRITE_IDX_STRICT;
1155        }
1156        if (strict)
1157                opts.flags |= WRITE_IDX_STRICT;
1158
1159        curr_pack = open_pack_file(pack_name);
1160        parse_pack_header();
1161        objects = xcalloc(nr_objects + 1, sizeof(struct object_entry));
1162        deltas = xcalloc(nr_objects, sizeof(struct delta_entry));
1163        parse_pack_objects(pack_sha1);
1164        if (nr_deltas == nr_resolved_deltas) {
1165                stop_progress(&progress);
1166                /* Flush remaining pack final 20-byte SHA1. */
1167                flush();
1168        } else {
1169                if (fix_thin_pack) {
1170                        struct sha1file *f;
1171                        unsigned char read_sha1[20], tail_sha1[20];
1172                        char msg[48];
1173                        int nr_unresolved = nr_deltas - nr_resolved_deltas;
1174                        int nr_objects_initial = nr_objects;
1175                        if (nr_unresolved <= 0)
1176                                die("confusion beyond insanity");
1177                        objects = xrealloc(objects,
1178                                           (nr_objects + nr_unresolved + 1)
1179                                           * sizeof(*objects));
1180                        f = sha1fd(output_fd, curr_pack);
1181                        fix_unresolved_deltas(f, nr_unresolved);
1182                        sprintf(msg, "completed with %d local objects",
1183                                nr_objects - nr_objects_initial);
1184                        stop_progress_msg(&progress, msg);
1185                        sha1close(f, tail_sha1, 0);
1186                        hashcpy(read_sha1, pack_sha1);
1187                        fixup_pack_header_footer(output_fd, pack_sha1,
1188                                                 curr_pack, nr_objects,
1189                                                 read_sha1, consumed_bytes-20);
1190                        if (hashcmp(read_sha1, tail_sha1) != 0)
1191                                die("Unexpected tail checksum for %s "
1192                                    "(disk corruption?)", curr_pack);
1193                }
1194                if (nr_deltas != nr_resolved_deltas)
1195                        die("pack has %d unresolved deltas",
1196                            nr_deltas - nr_resolved_deltas);
1197        }
1198        free(deltas);
1199        if (strict)
1200                check_objects();
1201
1202        if (stat)
1203                show_pack_info(stat_only);
1204
1205        idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1206        for (i = 0; i < nr_objects; i++)
1207                idx_objects[i] = &objects[i].idx;
1208        curr_index = write_idx_file(index_name, idx_objects, nr_objects, &opts, pack_sha1);
1209        free(idx_objects);
1210
1211        if (!verify)
1212                final(pack_name, curr_pack,
1213                      index_name, curr_index,
1214                      keep_name, keep_msg,
1215                      pack_sha1);
1216        else
1217                close(input_fd);
1218        free(objects);
1219        free(index_name_buf);
1220        free(keep_name_buf);
1221        if (pack_name == NULL)
1222                free((void *) curr_pack);
1223        if (index_name == NULL)
1224                free((void *) curr_index);
1225
1226        return 0;
1227}