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