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