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