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