builtin / index-pack.con commit Merge branch 'jn/maint-setup-fix' (early part) into jn/paginate-fix (fc196b6)
   1#include "cache.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> }] [--strict] { <pack-file> | --stdin [--fix-thin] [<pack-file>] }";
  15
  16struct object_entry
  17{
  18        struct pack_idx_entry idx;
  19        unsigned long size;
  20        unsigned int hdr_size;
  21        enum object_type type;
  22        enum object_type real_type;
  23};
  24
  25union delta_base {
  26        unsigned char sha1[20];
  27        off_t offset;
  28};
  29
  30struct base_data {
  31        struct base_data *base;
  32        struct base_data *child;
  33        struct object_entry *obj;
  34        void *data;
  35        unsigned long size;
  36};
  37
  38/*
  39 * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
  40 * to memcmp() only the first 20 bytes.
  41 */
  42#define UNION_BASE_SZ   20
  43
  44#define FLAG_LINK (1u<<20)
  45#define FLAG_CHECKED (1u<<21)
  46
  47struct delta_entry
  48{
  49        union delta_base base;
  50        int obj_no;
  51};
  52
  53static struct object_entry *objects;
  54static struct delta_entry *deltas;
  55static struct base_data *base_cache;
  56static size_t base_cache_used;
  57static int nr_objects;
  58static int nr_deltas;
  59static int nr_resolved_deltas;
  60
  61static int from_stdin;
  62static int strict;
  63static int verbose;
  64
  65static struct progress *progress;
  66
  67/* We always read in 4kB chunks. */
  68static unsigned char input_buffer[4096];
  69static unsigned int input_offset, input_len;
  70static off_t consumed_bytes;
  71static git_SHA_CTX input_ctx;
  72static uint32_t input_crc32;
  73static int input_fd, output_fd, pack_fd;
  74
  75static int mark_link(struct object *obj, int type, void *data)
  76{
  77        if (!obj)
  78                return -1;
  79
  80        if (type != OBJ_ANY && obj->type != type)
  81                die("object type mismatch at %s", sha1_to_hex(obj->sha1));
  82
  83        obj->flags |= FLAG_LINK;
  84        return 0;
  85}
  86
  87/* The content of each linked object must have been checked
  88   or it must be already present in the object database */
  89static void check_object(struct object *obj)
  90{
  91        if (!obj)
  92                return;
  93
  94        if (!(obj->flags & FLAG_LINK))
  95                return;
  96
  97        if (!(obj->flags & FLAG_CHECKED)) {
  98                unsigned long size;
  99                int type = sha1_object_info(obj->sha1, &size);
 100                if (type != obj->type || type <= 0)
 101                        die("object of unexpected type");
 102                obj->flags |= FLAG_CHECKED;
 103                return;
 104        }
 105}
 106
 107static void check_objects(void)
 108{
 109        unsigned i, max;
 110
 111        max = get_max_object_index();
 112        for (i = 0; i < max; i++)
 113                check_object(get_indexed_object(i));
 114}
 115
 116
 117/* Discard current buffer used content. */
 118static void flush(void)
 119{
 120        if (input_offset) {
 121                if (output_fd >= 0)
 122                        write_or_die(output_fd, input_buffer, input_offset);
 123                git_SHA1_Update(&input_ctx, input_buffer, input_offset);
 124                memmove(input_buffer, input_buffer + input_offset, input_len);
 125                input_offset = 0;
 126        }
 127}
 128
 129/*
 130 * Make sure at least "min" bytes are available in the buffer, and
 131 * return the pointer to the buffer.
 132 */
 133static void *fill(int min)
 134{
 135        if (min <= input_len)
 136                return input_buffer + input_offset;
 137        if (min > sizeof(input_buffer))
 138                die("cannot fill %d bytes", min);
 139        flush();
 140        do {
 141                ssize_t ret = xread(input_fd, input_buffer + input_len,
 142                                sizeof(input_buffer) - input_len);
 143                if (ret <= 0) {
 144                        if (!ret)
 145                                die("early EOF");
 146                        die_errno("read error on input");
 147                }
 148                input_len += ret;
 149                if (from_stdin)
 150                        display_throughput(progress, consumed_bytes + input_len);
 151        } while (input_len < min);
 152        return input_buffer;
 153}
 154
 155static void use(int bytes)
 156{
 157        if (bytes > input_len)
 158                die("used more bytes than were available");
 159        input_crc32 = crc32(input_crc32, input_buffer + input_offset, bytes);
 160        input_len -= bytes;
 161        input_offset += bytes;
 162
 163        /* make sure off_t is sufficiently large not to wrap */
 164        if (consumed_bytes > consumed_bytes + bytes)
 165                die("pack too large for current definition of off_t");
 166        consumed_bytes += bytes;
 167}
 168
 169static const char *open_pack_file(const char *pack_name)
 170{
 171        if (from_stdin) {
 172                input_fd = 0;
 173                if (!pack_name) {
 174                        static char tmpfile[PATH_MAX];
 175                        output_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
 176                                                "pack/tmp_pack_XXXXXX");
 177                        pack_name = xstrdup(tmpfile);
 178                } else
 179                        output_fd = open(pack_name, O_CREAT|O_EXCL|O_RDWR, 0600);
 180                if (output_fd < 0)
 181                        die_errno("unable to create '%s'", pack_name);
 182                pack_fd = output_fd;
 183        } else {
 184                input_fd = open(pack_name, O_RDONLY);
 185                if (input_fd < 0)
 186                        die_errno("cannot open packfile '%s'", pack_name);
 187                output_fd = -1;
 188                pack_fd = input_fd;
 189        }
 190        git_SHA1_Init(&input_ctx);
 191        return pack_name;
 192}
 193
 194static void parse_pack_header(void)
 195{
 196        struct pack_header *hdr = fill(sizeof(struct pack_header));
 197
 198        /* Header consistency check */
 199        if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
 200                die("pack signature mismatch");
 201        if (!pack_version_ok(hdr->hdr_version))
 202                die("pack version %"PRIu32" unsupported",
 203                        ntohl(hdr->hdr_version));
 204
 205        nr_objects = ntohl(hdr->hdr_entries);
 206        use(sizeof(struct pack_header));
 207}
 208
 209static NORETURN void bad_object(unsigned long offset, const char *format,
 210                       ...) __attribute__((format (printf, 2, 3)));
 211
 212static void bad_object(unsigned long offset, const char *format, ...)
 213{
 214        va_list params;
 215        char buf[1024];
 216
 217        va_start(params, format);
 218        vsnprintf(buf, sizeof(buf), format, params);
 219        va_end(params);
 220        die("pack has bad object at offset %lu: %s", offset, buf);
 221}
 222
 223static void free_base_data(struct base_data *c)
 224{
 225        if (c->data) {
 226                free(c->data);
 227                c->data = NULL;
 228                base_cache_used -= c->size;
 229        }
 230}
 231
 232static void prune_base_data(struct base_data *retain)
 233{
 234        struct base_data *b;
 235        for (b = base_cache;
 236             base_cache_used > delta_base_cache_limit && b;
 237             b = b->child) {
 238                if (b->data && b != retain)
 239                        free_base_data(b);
 240        }
 241}
 242
 243static void link_base_data(struct base_data *base, struct base_data *c)
 244{
 245        if (base)
 246                base->child = c;
 247        else
 248                base_cache = c;
 249
 250        c->base = base;
 251        c->child = NULL;
 252        if (c->data)
 253                base_cache_used += c->size;
 254        prune_base_data(c);
 255}
 256
 257static void unlink_base_data(struct base_data *c)
 258{
 259        struct base_data *base = c->base;
 260        if (base)
 261                base->child = NULL;
 262        else
 263                base_cache = NULL;
 264        free_base_data(c);
 265}
 266
 267static void *unpack_entry_data(unsigned long offset, unsigned long size)
 268{
 269        int status;
 270        z_stream stream;
 271        void *buf = xmalloc(size);
 272
 273        memset(&stream, 0, sizeof(stream));
 274        git_inflate_init(&stream);
 275        stream.next_out = buf;
 276        stream.avail_out = size;
 277
 278        do {
 279                stream.next_in = fill(1);
 280                stream.avail_in = input_len;
 281                status = git_inflate(&stream, 0);
 282                use(input_len - stream.avail_in);
 283        } while (status == Z_OK);
 284        if (stream.total_out != size || status != Z_STREAM_END)
 285                bad_object(offset, "inflate returned %d", status);
 286        git_inflate_end(&stream);
 287        return buf;
 288}
 289
 290static void *unpack_raw_entry(struct object_entry *obj, union delta_base *delta_base)
 291{
 292        unsigned char *p;
 293        unsigned long size, c;
 294        off_t base_offset;
 295        unsigned shift;
 296        void *data;
 297
 298        obj->idx.offset = consumed_bytes;
 299        input_crc32 = crc32(0, Z_NULL, 0);
 300
 301        p = fill(1);
 302        c = *p;
 303        use(1);
 304        obj->type = (c >> 4) & 7;
 305        size = (c & 15);
 306        shift = 4;
 307        while (c & 0x80) {
 308                p = fill(1);
 309                c = *p;
 310                use(1);
 311                size += (c & 0x7f) << shift;
 312                shift += 7;
 313        }
 314        obj->size = size;
 315
 316        switch (obj->type) {
 317        case OBJ_REF_DELTA:
 318                hashcpy(delta_base->sha1, fill(20));
 319                use(20);
 320                break;
 321        case OBJ_OFS_DELTA:
 322                memset(delta_base, 0, sizeof(*delta_base));
 323                p = fill(1);
 324                c = *p;
 325                use(1);
 326                base_offset = c & 127;
 327                while (c & 128) {
 328                        base_offset += 1;
 329                        if (!base_offset || MSB(base_offset, 7))
 330                                bad_object(obj->idx.offset, "offset value overflow for delta base object");
 331                        p = fill(1);
 332                        c = *p;
 333                        use(1);
 334                        base_offset = (base_offset << 7) + (c & 127);
 335                }
 336                delta_base->offset = obj->idx.offset - base_offset;
 337                if (delta_base->offset <= 0 || delta_base->offset >= obj->idx.offset)
 338                        bad_object(obj->idx.offset, "delta base offset is out of bound");
 339                break;
 340        case OBJ_COMMIT:
 341        case OBJ_TREE:
 342        case OBJ_BLOB:
 343        case OBJ_TAG:
 344                break;
 345        default:
 346                bad_object(obj->idx.offset, "unknown object type %d", obj->type);
 347        }
 348        obj->hdr_size = consumed_bytes - obj->idx.offset;
 349
 350        data = unpack_entry_data(obj->idx.offset, obj->size);
 351        obj->idx.crc32 = input_crc32;
 352        return data;
 353}
 354
 355static void *get_data_from_pack(struct object_entry *obj)
 356{
 357        off_t from = obj[0].idx.offset + obj[0].hdr_size;
 358        unsigned long len = obj[1].idx.offset - from;
 359        unsigned char *data, *inbuf;
 360        z_stream stream;
 361        int status;
 362
 363        data = xmalloc(obj->size);
 364        inbuf = xmalloc((len < 64*1024) ? len : 64*1024);
 365
 366        memset(&stream, 0, sizeof(stream));
 367        git_inflate_init(&stream);
 368        stream.next_out = data;
 369        stream.avail_out = obj->size;
 370
 371        do {
 372                ssize_t n = (len < 64*1024) ? len : 64*1024;
 373                n = pread(pack_fd, inbuf, n, from);
 374                if (n < 0)
 375                        die_errno("cannot pread pack file");
 376                if (!n)
 377                        die("premature end of pack file, %lu bytes missing", len);
 378                from += n;
 379                len -= n;
 380                stream.next_in = inbuf;
 381                stream.avail_in = n;
 382                status = git_inflate(&stream, 0);
 383        } while (len && status == Z_OK && !stream.avail_in);
 384
 385        /* This has been inflated OK when first encountered, so... */
 386        if (status != Z_STREAM_END || stream.total_out != obj->size)
 387                die("serious inflate inconsistency");
 388
 389        git_inflate_end(&stream);
 390        free(inbuf);
 391        return data;
 392}
 393
 394static int find_delta(const union delta_base *base)
 395{
 396        int first = 0, last = nr_deltas;
 397
 398        while (first < last) {
 399                int next = (first + last) / 2;
 400                struct delta_entry *delta = &deltas[next];
 401                int cmp;
 402
 403                cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
 404                if (!cmp)
 405                        return next;
 406                if (cmp < 0) {
 407                        last = next;
 408                        continue;
 409                }
 410                first = next+1;
 411        }
 412        return -first-1;
 413}
 414
 415static void find_delta_children(const union delta_base *base,
 416                                int *first_index, int *last_index)
 417{
 418        int first = find_delta(base);
 419        int last = first;
 420        int end = nr_deltas - 1;
 421
 422        if (first < 0) {
 423                *first_index = 0;
 424                *last_index = -1;
 425                return;
 426        }
 427        while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
 428                --first;
 429        while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
 430                ++last;
 431        *first_index = first;
 432        *last_index = last;
 433}
 434
 435static void sha1_object(const void *data, unsigned long size,
 436                        enum object_type type, unsigned char *sha1)
 437{
 438        hash_sha1_file(data, size, typename(type), sha1);
 439        if (has_sha1_file(sha1)) {
 440                void *has_data;
 441                enum object_type has_type;
 442                unsigned long has_size;
 443                has_data = read_sha1_file(sha1, &has_type, &has_size);
 444                if (!has_data)
 445                        die("cannot read existing object %s", sha1_to_hex(sha1));
 446                if (size != has_size || type != has_type ||
 447                    memcmp(data, has_data, size) != 0)
 448                        die("SHA1 COLLISION FOUND WITH %s !", sha1_to_hex(sha1));
 449                free(has_data);
 450        }
 451        if (strict) {
 452                if (type == OBJ_BLOB) {
 453                        struct blob *blob = lookup_blob(sha1);
 454                        if (blob)
 455                                blob->object.flags |= FLAG_CHECKED;
 456                        else
 457                                die("invalid blob object %s", sha1_to_hex(sha1));
 458                } else {
 459                        struct object *obj;
 460                        int eaten;
 461                        void *buf = (void *) data;
 462
 463                        /*
 464                         * we do not need to free the memory here, as the
 465                         * buf is deleted by the caller.
 466                         */
 467                        obj = parse_object_buffer(sha1, type, size, buf, &eaten);
 468                        if (!obj)
 469                                die("invalid %s", typename(type));
 470                        if (fsck_object(obj, 1, fsck_error_function))
 471                                die("Error in object");
 472                        if (fsck_walk(obj, mark_link, NULL))
 473                                die("Not all child objects of %s are reachable", sha1_to_hex(obj->sha1));
 474
 475                        if (obj->type == OBJ_TREE) {
 476                                struct tree *item = (struct tree *) obj;
 477                                item->buffer = NULL;
 478                        }
 479                        if (obj->type == OBJ_COMMIT) {
 480                                struct commit *commit = (struct commit *) obj;
 481                                commit->buffer = NULL;
 482                        }
 483                        obj->flags |= FLAG_CHECKED;
 484                }
 485        }
 486}
 487
 488static void *get_base_data(struct base_data *c)
 489{
 490        if (!c->data) {
 491                struct object_entry *obj = c->obj;
 492
 493                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
 494                        void *base = get_base_data(c->base);
 495                        void *raw = get_data_from_pack(obj);
 496                        c->data = patch_delta(
 497                                base, c->base->size,
 498                                raw, obj->size,
 499                                &c->size);
 500                        free(raw);
 501                        if (!c->data)
 502                                bad_object(obj->idx.offset, "failed to apply delta");
 503                } else {
 504                        c->data = get_data_from_pack(obj);
 505                        c->size = obj->size;
 506                }
 507
 508                base_cache_used += c->size;
 509                prune_base_data(c);
 510        }
 511        return c->data;
 512}
 513
 514static void resolve_delta(struct object_entry *delta_obj,
 515                          struct base_data *base, struct base_data *result)
 516{
 517        void *base_data, *delta_data;
 518
 519        delta_obj->real_type = base->obj->real_type;
 520        delta_data = get_data_from_pack(delta_obj);
 521        base_data = get_base_data(base);
 522        result->obj = delta_obj;
 523        result->data = patch_delta(base_data, base->size,
 524                                   delta_data, delta_obj->size, &result->size);
 525        free(delta_data);
 526        if (!result->data)
 527                bad_object(delta_obj->idx.offset, "failed to apply delta");
 528        sha1_object(result->data, result->size, delta_obj->real_type,
 529                    delta_obj->idx.sha1);
 530        nr_resolved_deltas++;
 531}
 532
 533static void find_unresolved_deltas(struct base_data *base,
 534                                   struct base_data *prev_base)
 535{
 536        int i, ref_first, ref_last, ofs_first, ofs_last;
 537
 538        /*
 539         * This is a recursive function. Those brackets should help reducing
 540         * stack usage by limiting the scope of the delta_base union.
 541         */
 542        {
 543                union delta_base base_spec;
 544
 545                hashcpy(base_spec.sha1, base->obj->idx.sha1);
 546                find_delta_children(&base_spec, &ref_first, &ref_last);
 547
 548                memset(&base_spec, 0, sizeof(base_spec));
 549                base_spec.offset = base->obj->idx.offset;
 550                find_delta_children(&base_spec, &ofs_first, &ofs_last);
 551        }
 552
 553        if (ref_last == -1 && ofs_last == -1) {
 554                free(base->data);
 555                return;
 556        }
 557
 558        link_base_data(prev_base, base);
 559
 560        for (i = ref_first; i <= ref_last; i++) {
 561                struct object_entry *child = objects + deltas[i].obj_no;
 562                if (child->real_type == OBJ_REF_DELTA) {
 563                        struct base_data result;
 564                        resolve_delta(child, base, &result);
 565                        if (i == ref_last && ofs_last == -1)
 566                                free_base_data(base);
 567                        find_unresolved_deltas(&result, base);
 568                }
 569        }
 570
 571        for (i = ofs_first; i <= ofs_last; i++) {
 572                struct object_entry *child = objects + deltas[i].obj_no;
 573                if (child->real_type == OBJ_OFS_DELTA) {
 574                        struct base_data result;
 575                        resolve_delta(child, base, &result);
 576                        if (i == ofs_last)
 577                                free_base_data(base);
 578                        find_unresolved_deltas(&result, base);
 579                }
 580        }
 581
 582        unlink_base_data(base);
 583}
 584
 585static int compare_delta_entry(const void *a, const void *b)
 586{
 587        const struct delta_entry *delta_a = a;
 588        const struct delta_entry *delta_b = b;
 589        return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
 590}
 591
 592/* Parse all objects and return the pack content SHA1 hash */
 593static void parse_pack_objects(unsigned char *sha1)
 594{
 595        int i;
 596        struct delta_entry *delta = deltas;
 597        struct stat st;
 598
 599        /*
 600         * First pass:
 601         * - find locations of all objects;
 602         * - calculate SHA1 of all non-delta objects;
 603         * - remember base (SHA1 or offset) for all deltas.
 604         */
 605        if (verbose)
 606                progress = start_progress(
 607                                from_stdin ? "Receiving objects" : "Indexing objects",
 608                                nr_objects);
 609        for (i = 0; i < nr_objects; i++) {
 610                struct object_entry *obj = &objects[i];
 611                void *data = unpack_raw_entry(obj, &delta->base);
 612                obj->real_type = obj->type;
 613                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA) {
 614                        nr_deltas++;
 615                        delta->obj_no = i;
 616                        delta++;
 617                } else
 618                        sha1_object(data, obj->size, obj->type, obj->idx.sha1);
 619                free(data);
 620                display_progress(progress, i+1);
 621        }
 622        objects[i].idx.offset = consumed_bytes;
 623        stop_progress(&progress);
 624
 625        /* Check pack integrity */
 626        flush();
 627        git_SHA1_Final(sha1, &input_ctx);
 628        if (hashcmp(fill(20), sha1))
 629                die("pack is corrupted (SHA1 mismatch)");
 630        use(20);
 631
 632        /* If input_fd is a file, we should have reached its end now. */
 633        if (fstat(input_fd, &st))
 634                die_errno("cannot fstat packfile");
 635        if (S_ISREG(st.st_mode) &&
 636                        lseek(input_fd, 0, SEEK_CUR) - input_len != st.st_size)
 637                die("pack has junk at the end");
 638
 639        if (!nr_deltas)
 640                return;
 641
 642        /* Sort deltas by base SHA1/offset for fast searching */
 643        qsort(deltas, nr_deltas, sizeof(struct delta_entry),
 644              compare_delta_entry);
 645
 646        /*
 647         * Second pass:
 648         * - for all non-delta objects, look if it is used as a base for
 649         *   deltas;
 650         * - if used as a base, uncompress the object and apply all deltas,
 651         *   recursively checking if the resulting object is used as a base
 652         *   for some more deltas.
 653         */
 654        if (verbose)
 655                progress = start_progress("Resolving deltas", nr_deltas);
 656        for (i = 0; i < nr_objects; i++) {
 657                struct object_entry *obj = &objects[i];
 658                struct base_data base_obj;
 659
 660                if (obj->type == OBJ_REF_DELTA || obj->type == OBJ_OFS_DELTA)
 661                        continue;
 662                base_obj.obj = obj;
 663                base_obj.data = NULL;
 664                find_unresolved_deltas(&base_obj, NULL);
 665                display_progress(progress, nr_resolved_deltas);
 666        }
 667}
 668
 669static int write_compressed(struct sha1file *f, void *in, unsigned int size)
 670{
 671        z_stream stream;
 672        int status;
 673        unsigned char outbuf[4096];
 674
 675        memset(&stream, 0, sizeof(stream));
 676        deflateInit(&stream, zlib_compression_level);
 677        stream.next_in = in;
 678        stream.avail_in = size;
 679
 680        do {
 681                stream.next_out = outbuf;
 682                stream.avail_out = sizeof(outbuf);
 683                status = deflate(&stream, Z_FINISH);
 684                sha1write(f, outbuf, sizeof(outbuf) - stream.avail_out);
 685        } while (status == Z_OK);
 686
 687        if (status != Z_STREAM_END)
 688                die("unable to deflate appended object (%d)", status);
 689        size = stream.total_out;
 690        deflateEnd(&stream);
 691        return size;
 692}
 693
 694static struct object_entry *append_obj_to_pack(struct sha1file *f,
 695                               const unsigned char *sha1, void *buf,
 696                               unsigned long size, enum object_type type)
 697{
 698        struct object_entry *obj = &objects[nr_objects++];
 699        unsigned char header[10];
 700        unsigned long s = size;
 701        int n = 0;
 702        unsigned char c = (type << 4) | (s & 15);
 703        s >>= 4;
 704        while (s) {
 705                header[n++] = c | 0x80;
 706                c = s & 0x7f;
 707                s >>= 7;
 708        }
 709        header[n++] = c;
 710        crc32_begin(f);
 711        sha1write(f, header, n);
 712        obj[0].size = size;
 713        obj[0].hdr_size = n;
 714        obj[0].type = type;
 715        obj[0].real_type = type;
 716        obj[1].idx.offset = obj[0].idx.offset + n;
 717        obj[1].idx.offset += write_compressed(f, buf, size);
 718        obj[0].idx.crc32 = crc32_end(f);
 719        sha1flush(f);
 720        hashcpy(obj->idx.sha1, sha1);
 721        return obj;
 722}
 723
 724static int delta_pos_compare(const void *_a, const void *_b)
 725{
 726        struct delta_entry *a = *(struct delta_entry **)_a;
 727        struct delta_entry *b = *(struct delta_entry **)_b;
 728        return a->obj_no - b->obj_no;
 729}
 730
 731static void fix_unresolved_deltas(struct sha1file *f, int nr_unresolved)
 732{
 733        struct delta_entry **sorted_by_pos;
 734        int i, n = 0;
 735
 736        /*
 737         * Since many unresolved deltas may well be themselves base objects
 738         * for more unresolved deltas, we really want to include the
 739         * smallest number of base objects that would cover as much delta
 740         * as possible by picking the
 741         * trunc deltas first, allowing for other deltas to resolve without
 742         * additional base objects.  Since most base objects are to be found
 743         * before deltas depending on them, a good heuristic is to start
 744         * resolving deltas in the same order as their position in the pack.
 745         */
 746        sorted_by_pos = xmalloc(nr_unresolved * sizeof(*sorted_by_pos));
 747        for (i = 0; i < nr_deltas; i++) {
 748                if (objects[deltas[i].obj_no].real_type != OBJ_REF_DELTA)
 749                        continue;
 750                sorted_by_pos[n++] = &deltas[i];
 751        }
 752        qsort(sorted_by_pos, n, sizeof(*sorted_by_pos), delta_pos_compare);
 753
 754        for (i = 0; i < n; i++) {
 755                struct delta_entry *d = sorted_by_pos[i];
 756                enum object_type type;
 757                struct base_data base_obj;
 758
 759                if (objects[d->obj_no].real_type != OBJ_REF_DELTA)
 760                        continue;
 761                base_obj.data = read_sha1_file(d->base.sha1, &type, &base_obj.size);
 762                if (!base_obj.data)
 763                        continue;
 764
 765                if (check_sha1_signature(d->base.sha1, base_obj.data,
 766                                base_obj.size, typename(type)))
 767                        die("local object %s is corrupt", sha1_to_hex(d->base.sha1));
 768                base_obj.obj = append_obj_to_pack(f, d->base.sha1,
 769                                        base_obj.data, base_obj.size, type);
 770                find_unresolved_deltas(&base_obj, NULL);
 771                display_progress(progress, nr_resolved_deltas);
 772        }
 773        free(sorted_by_pos);
 774}
 775
 776static void final(const char *final_pack_name, const char *curr_pack_name,
 777                  const char *final_index_name, const char *curr_index_name,
 778                  const char *keep_name, const char *keep_msg,
 779                  unsigned char *sha1)
 780{
 781        const char *report = "pack";
 782        char name[PATH_MAX];
 783        int err;
 784
 785        if (!from_stdin) {
 786                close(input_fd);
 787        } else {
 788                fsync_or_die(output_fd, curr_pack_name);
 789                err = close(output_fd);
 790                if (err)
 791                        die_errno("error while closing pack file");
 792        }
 793
 794        if (keep_msg) {
 795                int keep_fd, keep_msg_len = strlen(keep_msg);
 796
 797                if (!keep_name)
 798                        keep_fd = odb_pack_keep(name, sizeof(name), sha1);
 799                else
 800                        keep_fd = open(keep_name, O_RDWR|O_CREAT|O_EXCL, 0600);
 801
 802                if (keep_fd < 0) {
 803                        if (errno != EEXIST)
 804                                die_errno("cannot write keep file '%s'",
 805                                          keep_name);
 806                } else {
 807                        if (keep_msg_len > 0) {
 808                                write_or_die(keep_fd, keep_msg, keep_msg_len);
 809                                write_or_die(keep_fd, "\n", 1);
 810                        }
 811                        if (close(keep_fd) != 0)
 812                                die_errno("cannot close written keep file '%s'",
 813                                    keep_name);
 814                        report = "keep";
 815                }
 816        }
 817
 818        if (final_pack_name != curr_pack_name) {
 819                if (!final_pack_name) {
 820                        snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
 821                                 get_object_directory(), sha1_to_hex(sha1));
 822                        final_pack_name = name;
 823                }
 824                if (move_temp_to_file(curr_pack_name, final_pack_name))
 825                        die("cannot store pack file");
 826        } else if (from_stdin)
 827                chmod(final_pack_name, 0444);
 828
 829        if (final_index_name != curr_index_name) {
 830                if (!final_index_name) {
 831                        snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
 832                                 get_object_directory(), sha1_to_hex(sha1));
 833                        final_index_name = name;
 834                }
 835                if (move_temp_to_file(curr_index_name, final_index_name))
 836                        die("cannot store index file");
 837        } else
 838                chmod(final_index_name, 0444);
 839
 840        if (!from_stdin) {
 841                printf("%s\n", sha1_to_hex(sha1));
 842        } else {
 843                char buf[48];
 844                int len = snprintf(buf, sizeof(buf), "%s\t%s\n",
 845                                   report, sha1_to_hex(sha1));
 846                write_or_die(1, buf, len);
 847
 848                /*
 849                 * Let's just mimic git-unpack-objects here and write
 850                 * the last part of the input buffer to stdout.
 851                 */
 852                while (input_len) {
 853                        err = xwrite(1, input_buffer + input_offset, input_len);
 854                        if (err <= 0)
 855                                break;
 856                        input_len -= err;
 857                        input_offset += err;
 858                }
 859        }
 860}
 861
 862static int git_index_pack_config(const char *k, const char *v, void *cb)
 863{
 864        if (!strcmp(k, "pack.indexversion")) {
 865                pack_idx_default_version = git_config_int(k, v);
 866                if (pack_idx_default_version > 2)
 867                        die("bad pack.indexversion=%"PRIu32,
 868                                pack_idx_default_version);
 869                return 0;
 870        }
 871        return git_default_config(k, v, cb);
 872}
 873
 874int cmd_index_pack(int argc, const char **argv, const char *prefix)
 875{
 876        int i, fix_thin_pack = 0;
 877        const char *curr_pack, *curr_index;
 878        const char *index_name = NULL, *pack_name = NULL;
 879        const char *keep_name = NULL, *keep_msg = NULL;
 880        char *index_name_buf = NULL, *keep_name_buf = NULL;
 881        struct pack_idx_entry **idx_objects;
 882        unsigned char pack_sha1[20];
 883        int nongit;
 884
 885        if (argc == 2 && !strcmp(argv[1], "-h"))
 886                usage(index_pack_usage);
 887
 888        prefix = setup_git_directory_gently(&nongit);
 889        git_config(git_index_pack_config, NULL);
 890        if (prefix && chdir(prefix))
 891                die("Cannot come back to cwd");
 892
 893        for (i = 1; i < argc; i++) {
 894                const char *arg = argv[i];
 895
 896                if (*arg == '-') {
 897                        if (!strcmp(arg, "--stdin")) {
 898                                from_stdin = 1;
 899                        } else if (!strcmp(arg, "--fix-thin")) {
 900                                fix_thin_pack = 1;
 901                        } else if (!strcmp(arg, "--strict")) {
 902                                strict = 1;
 903                        } else if (!strcmp(arg, "--keep")) {
 904                                keep_msg = "";
 905                        } else if (!prefixcmp(arg, "--keep=")) {
 906                                keep_msg = arg + 7;
 907                        } else if (!prefixcmp(arg, "--pack_header=")) {
 908                                struct pack_header *hdr;
 909                                char *c;
 910
 911                                hdr = (struct pack_header *)input_buffer;
 912                                hdr->hdr_signature = htonl(PACK_SIGNATURE);
 913                                hdr->hdr_version = htonl(strtoul(arg + 14, &c, 10));
 914                                if (*c != ',')
 915                                        die("bad %s", arg);
 916                                hdr->hdr_entries = htonl(strtoul(c + 1, &c, 10));
 917                                if (*c)
 918                                        die("bad %s", arg);
 919                                input_len = sizeof(*hdr);
 920                        } else if (!strcmp(arg, "-v")) {
 921                                verbose = 1;
 922                        } else if (!strcmp(arg, "-o")) {
 923                                if (index_name || (i+1) >= argc)
 924                                        usage(index_pack_usage);
 925                                index_name = argv[++i];
 926                        } else if (!prefixcmp(arg, "--index-version=")) {
 927                                char *c;
 928                                pack_idx_default_version = strtoul(arg + 16, &c, 10);
 929                                if (pack_idx_default_version > 2)
 930                                        die("bad %s", arg);
 931                                if (*c == ',')
 932                                        pack_idx_off32_limit = strtoul(c+1, &c, 0);
 933                                if (*c || pack_idx_off32_limit & 0x80000000)
 934                                        die("bad %s", arg);
 935                        } else
 936                                usage(index_pack_usage);
 937                        continue;
 938                }
 939
 940                if (pack_name)
 941                        usage(index_pack_usage);
 942                pack_name = arg;
 943        }
 944
 945        if (!pack_name && !from_stdin)
 946                usage(index_pack_usage);
 947        if (fix_thin_pack && !from_stdin)
 948                die("--fix-thin cannot be used without --stdin");
 949        if (!index_name && pack_name) {
 950                int len = strlen(pack_name);
 951                if (!has_extension(pack_name, ".pack"))
 952                        die("packfile name '%s' does not end with '.pack'",
 953                            pack_name);
 954                index_name_buf = xmalloc(len);
 955                memcpy(index_name_buf, pack_name, len - 5);
 956                strcpy(index_name_buf + len - 5, ".idx");
 957                index_name = index_name_buf;
 958        }
 959        if (keep_msg && !keep_name && pack_name) {
 960                int len = strlen(pack_name);
 961                if (!has_extension(pack_name, ".pack"))
 962                        die("packfile name '%s' does not end with '.pack'",
 963                            pack_name);
 964                keep_name_buf = xmalloc(len);
 965                memcpy(keep_name_buf, pack_name, len - 5);
 966                strcpy(keep_name_buf + len - 5, ".keep");
 967                keep_name = keep_name_buf;
 968        }
 969
 970        curr_pack = open_pack_file(pack_name);
 971        parse_pack_header();
 972        objects = xmalloc((nr_objects + 1) * sizeof(struct object_entry));
 973        deltas = xmalloc(nr_objects * sizeof(struct delta_entry));
 974        parse_pack_objects(pack_sha1);
 975        if (nr_deltas == nr_resolved_deltas) {
 976                stop_progress(&progress);
 977                /* Flush remaining pack final 20-byte SHA1. */
 978                flush();
 979        } else {
 980                if (fix_thin_pack) {
 981                        struct sha1file *f;
 982                        unsigned char read_sha1[20], tail_sha1[20];
 983                        char msg[48];
 984                        int nr_unresolved = nr_deltas - nr_resolved_deltas;
 985                        int nr_objects_initial = nr_objects;
 986                        if (nr_unresolved <= 0)
 987                                die("confusion beyond insanity");
 988                        objects = xrealloc(objects,
 989                                           (nr_objects + nr_unresolved + 1)
 990                                           * sizeof(*objects));
 991                        f = sha1fd(output_fd, curr_pack);
 992                        fix_unresolved_deltas(f, nr_unresolved);
 993                        sprintf(msg, "completed with %d local objects",
 994                                nr_objects - nr_objects_initial);
 995                        stop_progress_msg(&progress, msg);
 996                        sha1close(f, tail_sha1, 0);
 997                        hashcpy(read_sha1, pack_sha1);
 998                        fixup_pack_header_footer(output_fd, pack_sha1,
 999                                                 curr_pack, nr_objects,
1000                                                 read_sha1, consumed_bytes-20);
1001                        if (hashcmp(read_sha1, tail_sha1) != 0)
1002                                die("Unexpected tail checksum for %s "
1003                                    "(disk corruption?)", curr_pack);
1004                }
1005                if (nr_deltas != nr_resolved_deltas)
1006                        die("pack has %d unresolved deltas",
1007                            nr_deltas - nr_resolved_deltas);
1008        }
1009        free(deltas);
1010        if (strict)
1011                check_objects();
1012
1013        idx_objects = xmalloc((nr_objects) * sizeof(struct pack_idx_entry *));
1014        for (i = 0; i < nr_objects; i++)
1015                idx_objects[i] = &objects[i].idx;
1016        curr_index = write_idx_file(index_name, idx_objects, nr_objects, pack_sha1);
1017        free(idx_objects);
1018
1019        final(pack_name, curr_pack,
1020                index_name, curr_index,
1021                keep_name, keep_msg,
1022                pack_sha1);
1023        free(objects);
1024        free(index_name_buf);
1025        free(keep_name_buf);
1026        if (pack_name == NULL)
1027                free((void *) curr_pack);
1028        if (index_name == NULL)
1029                free((void *) curr_index);
1030
1031        return 0;
1032}