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