687b4b5a9944ace5fde99e6275adc2bd3ca7ef9a
   1#include "builtin.h"
   2#include "cache.h"
   3#include "object.h"
   4#include "blob.h"
   5#include "commit.h"
   6#include "tag.h"
   7#include "tree.h"
   8#include "delta.h"
   9#include "pack.h"
  10#include "csum-file.h"
  11#include "tree-walk.h"
  12#include "diff.h"
  13#include "revision.h"
  14#include "list-objects.h"
  15
  16static const char pack_usage[] = "\
  17git-pack-objects [{ -q | --progress | --all-progress }] \n\
  18        [--local] [--incremental] [--window=N] [--depth=N] \n\
  19        [--no-reuse-delta] [--delta-base-offset] [--non-empty] \n\
  20        [--revs [--unpacked | --all]*] [--reflog] [--stdout | base-name] \n\
  21        [<ref-list | <object-list]";
  22
  23struct object_entry {
  24        unsigned char sha1[20];
  25        unsigned long size;     /* uncompressed size */
  26        off_t offset;   /* offset into the final pack file;
  27                                 * nonzero if already written.
  28                                 */
  29        unsigned int depth;     /* delta depth */
  30        unsigned int delta_limit;       /* base adjustment for in-pack delta */
  31        unsigned int hash;      /* name hint hash */
  32        enum object_type type;
  33        enum object_type in_pack_type;  /* could be delta */
  34        unsigned long delta_size;       /* delta data size (uncompressed) */
  35#define in_pack_header_size delta_size  /* only when reusing pack data */
  36        struct object_entry *delta;     /* delta base object */
  37        struct packed_git *in_pack;     /* already in pack */
  38        off_t in_pack_offset;
  39        struct object_entry *delta_child; /* deltified objects who bases me */
  40        struct object_entry *delta_sibling; /* other deltified objects who
  41                                             * uses the same base as me
  42                                             */
  43        int preferred_base;     /* we do not pack this, but is encouraged to
  44                                 * be used as the base objectto delta huge
  45                                 * objects against.
  46                                 */
  47        uint32_t crc32;         /* crc of raw pack data for this object */
  48};
  49
  50/*
  51 * Objects we are going to pack are collected in objects array (dynamically
  52 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  53 * in the order we see -- typically rev-list --objects order that gives us
  54 * nice "minimum seek" order.
  55 *
  56 * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
  57 * elements in the objects array.  The former is used to build the pack
  58 * index (lists object names in the ascending order to help offset lookup),
  59 * and the latter is used to group similar things together by try_delta()
  60 * heuristics.
  61 */
  62
  63static unsigned char object_list_sha1[20];
  64static int non_empty;
  65static int no_reuse_delta;
  66static int local;
  67static int incremental;
  68static int allow_ofs_delta;
  69
  70static struct object_entry **sorted_by_sha, **sorted_by_type;
  71static struct object_entry *objects;
  72static uint32_t nr_objects, nr_alloc, nr_result;
  73static const char *base_name;
  74static unsigned char pack_file_sha1[20];
  75static int progress = 1;
  76static volatile sig_atomic_t progress_update;
  77static int window = 10;
  78static int pack_to_stdout;
  79static int num_preferred_base;
  80
  81/*
  82 * The object names in objects array are hashed with this hashtable,
  83 * to help looking up the entry by object name.  Binary search from
  84 * sorted_by_sha is also possible but this was easier to code and faster.
  85 * This hashtable is built after all the objects are seen.
  86 */
  87static int *object_ix;
  88static int object_ix_hashsz;
  89
  90/*
  91 * Pack index for existing packs give us easy access to the offsets into
  92 * corresponding pack file where each object's data starts, but the entries
  93 * do not store the size of the compressed representation (uncompressed
  94 * size is easily available by examining the pack entry header).  It is
  95 * also rather expensive to find the sha1 for an object given its offset.
  96 *
  97 * We build a hashtable of existing packs (pack_revindex), and keep reverse
  98 * index here -- pack index file is sorted by object name mapping to offset;
  99 * this pack_revindex[].revindex array is a list of offset/index_nr pairs
 100 * ordered by offset, so if you know the offset of an object, next offset
 101 * is where its packed representation ends and the index_nr can be used to
 102 * get the object sha1 from the main index.
 103 */
 104struct revindex_entry {
 105        off_t offset;
 106        unsigned int nr;
 107};
 108struct pack_revindex {
 109        struct packed_git *p;
 110        struct revindex_entry *revindex;
 111};
 112static struct  pack_revindex *pack_revindex;
 113static int pack_revindex_hashsz;
 114
 115/*
 116 * stats
 117 */
 118static uint32_t written, written_delta;
 119static uint32_t reused, reused_delta;
 120
 121static int pack_revindex_ix(struct packed_git *p)
 122{
 123        unsigned long ui = (unsigned long)p;
 124        int i;
 125
 126        ui = ui ^ (ui >> 16); /* defeat structure alignment */
 127        i = (int)(ui % pack_revindex_hashsz);
 128        while (pack_revindex[i].p) {
 129                if (pack_revindex[i].p == p)
 130                        return i;
 131                if (++i == pack_revindex_hashsz)
 132                        i = 0;
 133        }
 134        return -1 - i;
 135}
 136
 137static void prepare_pack_ix(void)
 138{
 139        int num;
 140        struct packed_git *p;
 141        for (num = 0, p = packed_git; p; p = p->next)
 142                num++;
 143        if (!num)
 144                return;
 145        pack_revindex_hashsz = num * 11;
 146        pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
 147        for (p = packed_git; p; p = p->next) {
 148                num = pack_revindex_ix(p);
 149                num = - 1 - num;
 150                pack_revindex[num].p = p;
 151        }
 152        /* revindex elements are lazily initialized */
 153}
 154
 155static int cmp_offset(const void *a_, const void *b_)
 156{
 157        const struct revindex_entry *a = a_;
 158        const struct revindex_entry *b = b_;
 159        return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
 160}
 161
 162/*
 163 * Ordered list of offsets of objects in the pack.
 164 */
 165static void prepare_pack_revindex(struct pack_revindex *rix)
 166{
 167        struct packed_git *p = rix->p;
 168        int num_ent = p->num_objects;
 169        int i;
 170        const char *index = p->index_data;
 171
 172        rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
 173        index += 4 * 256;
 174
 175        if (p->index_version > 1) {
 176                const uint32_t *off_32 =
 177                        (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
 178                const uint32_t *off_64 = off_32 + p->num_objects;
 179                for (i = 0; i < num_ent; i++) {
 180                        uint32_t off = ntohl(*off_32++);
 181                        if (!(off & 0x80000000)) {
 182                                rix->revindex[i].offset = off;
 183                        } else {
 184                                rix->revindex[i].offset =
 185                                        ((uint64_t)ntohl(*off_64++)) << 32;
 186                                rix->revindex[i].offset |=
 187                                        ntohl(*off_64++);
 188                        }
 189                        rix->revindex[i].nr = i;
 190                }
 191        } else {
 192                for (i = 0; i < num_ent; i++) {
 193                        uint32_t hl = *((uint32_t *)(index + 24 * i));
 194                        rix->revindex[i].offset = ntohl(hl);
 195                        rix->revindex[i].nr = i;
 196                }
 197        }
 198
 199        /* This knows the pack format -- the 20-byte trailer
 200         * follows immediately after the last object data.
 201         */
 202        rix->revindex[num_ent].offset = p->pack_size - 20;
 203        rix->revindex[num_ent].nr = -1;
 204        qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
 205}
 206
 207static struct revindex_entry * find_packed_object(struct packed_git *p,
 208                                                  off_t ofs)
 209{
 210        int num;
 211        int lo, hi;
 212        struct pack_revindex *rix;
 213        struct revindex_entry *revindex;
 214        num = pack_revindex_ix(p);
 215        if (num < 0)
 216                die("internal error: pack revindex uninitialized");
 217        rix = &pack_revindex[num];
 218        if (!rix->revindex)
 219                prepare_pack_revindex(rix);
 220        revindex = rix->revindex;
 221        lo = 0;
 222        hi = p->num_objects + 1;
 223        do {
 224                int mi = (lo + hi) / 2;
 225                if (revindex[mi].offset == ofs) {
 226                        return revindex + mi;
 227                }
 228                else if (ofs < revindex[mi].offset)
 229                        hi = mi;
 230                else
 231                        lo = mi + 1;
 232        } while (lo < hi);
 233        die("internal error: pack revindex corrupt");
 234}
 235
 236static const unsigned char *find_packed_object_name(struct packed_git *p,
 237                                                    off_t ofs)
 238{
 239        struct revindex_entry *entry = find_packed_object(p, ofs);
 240        return nth_packed_object_sha1(p, entry->nr);
 241}
 242
 243static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
 244{
 245        unsigned long othersize, delta_size;
 246        enum object_type type;
 247        void *otherbuf = read_sha1_file(entry->delta->sha1, &type, &othersize);
 248        void *delta_buf;
 249
 250        if (!otherbuf)
 251                die("unable to read %s", sha1_to_hex(entry->delta->sha1));
 252        delta_buf = diff_delta(otherbuf, othersize,
 253                               buf, size, &delta_size, 0);
 254        if (!delta_buf || delta_size != entry->delta_size)
 255                die("delta size changed");
 256        free(buf);
 257        free(otherbuf);
 258        return delta_buf;
 259}
 260
 261/*
 262 * The per-object header is a pretty dense thing, which is
 263 *  - first byte: low four bits are "size", then three bits of "type",
 264 *    and the high bit is "size continues".
 265 *  - each byte afterwards: low seven bits are size continuation,
 266 *    with the high bit being "size continues"
 267 */
 268static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
 269{
 270        int n = 1;
 271        unsigned char c;
 272
 273        if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
 274                die("bad type %d", type);
 275
 276        c = (type << 4) | (size & 15);
 277        size >>= 4;
 278        while (size) {
 279                *hdr++ = c | 0x80;
 280                c = size & 0x7f;
 281                size >>= 7;
 282                n++;
 283        }
 284        *hdr = c;
 285        return n;
 286}
 287
 288/*
 289 * we are going to reuse the existing object data as is.  make
 290 * sure it is not corrupt.
 291 */
 292static int check_pack_inflate(struct packed_git *p,
 293                struct pack_window **w_curs,
 294                off_t offset,
 295                off_t len,
 296                unsigned long expect)
 297{
 298        z_stream stream;
 299        unsigned char fakebuf[4096], *in;
 300        int st;
 301
 302        memset(&stream, 0, sizeof(stream));
 303        inflateInit(&stream);
 304        do {
 305                in = use_pack(p, w_curs, offset, &stream.avail_in);
 306                stream.next_in = in;
 307                stream.next_out = fakebuf;
 308                stream.avail_out = sizeof(fakebuf);
 309                st = inflate(&stream, Z_FINISH);
 310                offset += stream.next_in - in;
 311        } while (st == Z_OK || st == Z_BUF_ERROR);
 312        inflateEnd(&stream);
 313        return (st == Z_STREAM_END &&
 314                stream.total_out == expect &&
 315                stream.total_in == len) ? 0 : -1;
 316}
 317
 318static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
 319                          off_t offset, off_t len, unsigned int nr)
 320{
 321        const uint32_t *index_crc;
 322        uint32_t data_crc = crc32(0, Z_NULL, 0);
 323
 324        do {
 325                unsigned int avail;
 326                void *data = use_pack(p, w_curs, offset, &avail);
 327                if (avail > len)
 328                        avail = len;
 329                data_crc = crc32(data_crc, data, avail);
 330                offset += avail;
 331                len -= avail;
 332        } while (len);
 333
 334        index_crc = p->index_data;
 335        index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
 336
 337        return data_crc != ntohl(*index_crc);
 338}
 339
 340static void copy_pack_data(struct sha1file *f,
 341                struct packed_git *p,
 342                struct pack_window **w_curs,
 343                off_t offset,
 344                off_t len)
 345{
 346        unsigned char *in;
 347        unsigned int avail;
 348
 349        while (len) {
 350                in = use_pack(p, w_curs, offset, &avail);
 351                if (avail > len)
 352                        avail = (unsigned int)len;
 353                sha1write(f, in, avail);
 354                offset += avail;
 355                len -= avail;
 356        }
 357}
 358
 359static int check_loose_inflate(unsigned char *data, unsigned long len, unsigned long expect)
 360{
 361        z_stream stream;
 362        unsigned char fakebuf[4096];
 363        int st;
 364
 365        memset(&stream, 0, sizeof(stream));
 366        stream.next_in = data;
 367        stream.avail_in = len;
 368        stream.next_out = fakebuf;
 369        stream.avail_out = sizeof(fakebuf);
 370        inflateInit(&stream);
 371
 372        while (1) {
 373                st = inflate(&stream, Z_FINISH);
 374                if (st == Z_STREAM_END || st == Z_OK) {
 375                        st = (stream.total_out == expect &&
 376                              stream.total_in == len) ? 0 : -1;
 377                        break;
 378                }
 379                if (st != Z_BUF_ERROR) {
 380                        st = -1;
 381                        break;
 382                }
 383                stream.next_out = fakebuf;
 384                stream.avail_out = sizeof(fakebuf);
 385        }
 386        inflateEnd(&stream);
 387        return st;
 388}
 389
 390static int revalidate_loose_object(struct object_entry *entry,
 391                                   unsigned char *map,
 392                                   unsigned long mapsize)
 393{
 394        /* we already know this is a loose object with new type header. */
 395        enum object_type type;
 396        unsigned long size, used;
 397
 398        if (pack_to_stdout)
 399                return 0;
 400
 401        used = unpack_object_header_gently(map, mapsize, &type, &size);
 402        if (!used)
 403                return -1;
 404        map += used;
 405        mapsize -= used;
 406        return check_loose_inflate(map, mapsize, size);
 407}
 408
 409static unsigned long write_object(struct sha1file *f,
 410                                  struct object_entry *entry)
 411{
 412        unsigned long size;
 413        enum object_type type;
 414        void *buf;
 415        unsigned char header[10];
 416        unsigned hdrlen;
 417        off_t datalen;
 418        enum object_type obj_type;
 419        int to_reuse = 0;
 420
 421        if (!pack_to_stdout)
 422                crc32_begin(f);
 423
 424        obj_type = entry->type;
 425        if (! entry->in_pack)
 426                to_reuse = 0;   /* can't reuse what we don't have */
 427        else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
 428                to_reuse = 1;   /* check_object() decided it for us */
 429        else if (obj_type != entry->in_pack_type)
 430                to_reuse = 0;   /* pack has delta which is unusable */
 431        else if (entry->delta)
 432                to_reuse = 0;   /* we want to pack afresh */
 433        else
 434                to_reuse = 1;   /* we have it in-pack undeltified,
 435                                 * and we do not need to deltify it.
 436                                 */
 437
 438        if (!entry->in_pack && !entry->delta) {
 439                unsigned char *map;
 440                unsigned long mapsize;
 441                map = map_sha1_file(entry->sha1, &mapsize);
 442                if (map && !legacy_loose_object(map)) {
 443                        /* We can copy straight into the pack file */
 444                        if (revalidate_loose_object(entry, map, mapsize))
 445                                die("corrupt loose object %s",
 446                                    sha1_to_hex(entry->sha1));
 447                        sha1write(f, map, mapsize);
 448                        munmap(map, mapsize);
 449                        written++;
 450                        reused++;
 451                        return mapsize;
 452                }
 453                if (map)
 454                        munmap(map, mapsize);
 455        }
 456
 457        if (!to_reuse) {
 458                buf = read_sha1_file(entry->sha1, &type, &size);
 459                if (!buf)
 460                        die("unable to read %s", sha1_to_hex(entry->sha1));
 461                if (size != entry->size)
 462                        die("object %s size inconsistency (%lu vs %lu)",
 463                            sha1_to_hex(entry->sha1), size, entry->size);
 464                if (entry->delta) {
 465                        buf = delta_against(buf, size, entry);
 466                        size = entry->delta_size;
 467                        obj_type = (allow_ofs_delta && entry->delta->offset) ?
 468                                OBJ_OFS_DELTA : OBJ_REF_DELTA;
 469                }
 470                /*
 471                 * The object header is a byte of 'type' followed by zero or
 472                 * more bytes of length.
 473                 */
 474                hdrlen = encode_header(obj_type, size, header);
 475                sha1write(f, header, hdrlen);
 476
 477                if (obj_type == OBJ_OFS_DELTA) {
 478                        /*
 479                         * Deltas with relative base contain an additional
 480                         * encoding of the relative offset for the delta
 481                         * base from this object's position in the pack.
 482                         */
 483                        off_t ofs = entry->offset - entry->delta->offset;
 484                        unsigned pos = sizeof(header) - 1;
 485                        header[pos] = ofs & 127;
 486                        while (ofs >>= 7)
 487                                header[--pos] = 128 | (--ofs & 127);
 488                        sha1write(f, header + pos, sizeof(header) - pos);
 489                        hdrlen += sizeof(header) - pos;
 490                } else if (obj_type == OBJ_REF_DELTA) {
 491                        /*
 492                         * Deltas with a base reference contain
 493                         * an additional 20 bytes for the base sha1.
 494                         */
 495                        sha1write(f, entry->delta->sha1, 20);
 496                        hdrlen += 20;
 497                }
 498                datalen = sha1write_compressed(f, buf, size);
 499                free(buf);
 500        }
 501        else {
 502                struct packed_git *p = entry->in_pack;
 503                struct pack_window *w_curs = NULL;
 504                struct revindex_entry *revidx;
 505                off_t offset;
 506
 507                if (entry->delta) {
 508                        obj_type = (allow_ofs_delta && entry->delta->offset) ?
 509                                OBJ_OFS_DELTA : OBJ_REF_DELTA;
 510                        reused_delta++;
 511                }
 512                hdrlen = encode_header(obj_type, entry->size, header);
 513                sha1write(f, header, hdrlen);
 514                if (obj_type == OBJ_OFS_DELTA) {
 515                        off_t ofs = entry->offset - entry->delta->offset;
 516                        unsigned pos = sizeof(header) - 1;
 517                        header[pos] = ofs & 127;
 518                        while (ofs >>= 7)
 519                                header[--pos] = 128 | (--ofs & 127);
 520                        sha1write(f, header + pos, sizeof(header) - pos);
 521                        hdrlen += sizeof(header) - pos;
 522                } else if (obj_type == OBJ_REF_DELTA) {
 523                        sha1write(f, entry->delta->sha1, 20);
 524                        hdrlen += 20;
 525                }
 526
 527                offset = entry->in_pack_offset;
 528                revidx = find_packed_object(p, offset);
 529                datalen = revidx[1].offset - offset;
 530                if (!pack_to_stdout && p->index_version > 1 &&
 531                    check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
 532                        die("bad packed object CRC for %s", sha1_to_hex(entry->sha1));
 533                offset += entry->in_pack_header_size;
 534                datalen -= entry->in_pack_header_size;
 535                if (!pack_to_stdout && p->index_version == 1 &&
 536                    check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
 537                        die("corrupt packed object for %s", sha1_to_hex(entry->sha1));
 538                copy_pack_data(f, p, &w_curs, offset, datalen);
 539                unuse_pack(&w_curs);
 540                reused++;
 541        }
 542        if (entry->delta)
 543                written_delta++;
 544        written++;
 545        if (!pack_to_stdout)
 546                entry->crc32 = crc32_end(f);
 547        return hdrlen + datalen;
 548}
 549
 550static off_t write_one(struct sha1file *f,
 551                               struct object_entry *e,
 552                               off_t offset)
 553{
 554        unsigned long size;
 555
 556        /* offset is non zero if object is written already. */
 557        if (e->offset || e->preferred_base)
 558                return offset;
 559
 560        /* if we are deltified, write out base object first. */
 561        if (e->delta)
 562                offset = write_one(f, e->delta, offset);
 563
 564        e->offset = offset;
 565        size = write_object(f, e);
 566
 567        /* make sure off_t is sufficiently large not to wrap */
 568        if (offset > offset + size)
 569                die("pack too large for current definition of off_t");
 570        return offset + size;
 571}
 572
 573static off_t write_pack_file(void)
 574{
 575        uint32_t i;
 576        struct sha1file *f;
 577        off_t offset, last_obj_offset = 0;
 578        struct pack_header hdr;
 579        unsigned last_percent = 999;
 580        int do_progress = progress;
 581
 582        if (!base_name) {
 583                f = sha1fd(1, "<stdout>");
 584                do_progress >>= 1;
 585        }
 586        else
 587                f = sha1create("%s-%s.%s", base_name,
 588                               sha1_to_hex(object_list_sha1), "pack");
 589        if (do_progress)
 590                fprintf(stderr, "Writing %u objects.\n", nr_result);
 591
 592        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 593        hdr.hdr_version = htonl(PACK_VERSION);
 594        hdr.hdr_entries = htonl(nr_result);
 595        sha1write(f, &hdr, sizeof(hdr));
 596        offset = sizeof(hdr);
 597        if (!nr_result)
 598                goto done;
 599        for (i = 0; i < nr_objects; i++) {
 600                last_obj_offset = offset;
 601                offset = write_one(f, objects + i, offset);
 602                if (do_progress) {
 603                        unsigned percent = written * 100 / nr_result;
 604                        if (progress_update || percent != last_percent) {
 605                                fprintf(stderr, "%4u%% (%u/%u) done\r",
 606                                        percent, written, nr_result);
 607                                progress_update = 0;
 608                                last_percent = percent;
 609                        }
 610                }
 611        }
 612        if (do_progress)
 613                fputc('\n', stderr);
 614 done:
 615        if (written != nr_result)
 616                die("wrote %u objects while expecting %u", written, nr_result);
 617        sha1close(f, pack_file_sha1, 1);
 618
 619        return last_obj_offset;
 620}
 621
 622static uint32_t index_default_version = 1;
 623static uint32_t index_off32_limit = 0x7fffffff;
 624
 625static void write_index_file(off_t last_obj_offset)
 626{
 627        uint32_t i;
 628        struct sha1file *f = sha1create("%s-%s.%s", base_name,
 629                                        sha1_to_hex(object_list_sha1), "idx");
 630        struct object_entry **list = sorted_by_sha;
 631        struct object_entry **last = list + nr_result;
 632        uint32_t array[256];
 633        uint32_t index_version;
 634
 635        /* if last object's offset is >= 2^31 we should use index V2 */
 636        index_version = (last_obj_offset >> 31) ? 2 : index_default_version;
 637
 638        /* index versions 2 and above need a header */
 639        if (index_version >= 2) {
 640                struct pack_idx_header hdr;
 641                hdr.idx_signature = htonl(PACK_IDX_SIGNATURE);
 642                hdr.idx_version = htonl(index_version);
 643                sha1write(f, &hdr, sizeof(hdr));
 644        }
 645
 646        /*
 647         * Write the first-level table (the list is sorted,
 648         * but we use a 256-entry lookup to be able to avoid
 649         * having to do eight extra binary search iterations).
 650         */
 651        for (i = 0; i < 256; i++) {
 652                struct object_entry **next = list;
 653                while (next < last) {
 654                        struct object_entry *entry = *next;
 655                        if (entry->sha1[0] != i)
 656                                break;
 657                        next++;
 658                }
 659                array[i] = htonl(next - sorted_by_sha);
 660                list = next;
 661        }
 662        sha1write(f, array, 256 * 4);
 663
 664        /*
 665         * Write the actual SHA1 entries..
 666         */
 667        list = sorted_by_sha;
 668        for (i = 0; i < nr_result; i++) {
 669                struct object_entry *entry = *list++;
 670                if (index_version < 2) {
 671                        uint32_t offset = htonl(entry->offset);
 672                        sha1write(f, &offset, 4);
 673                }
 674                sha1write(f, entry->sha1, 20);
 675        }
 676
 677        if (index_version >= 2) {
 678                unsigned int nr_large_offset = 0;
 679
 680                /* write the crc32 table */
 681                list = sorted_by_sha;
 682                for (i = 0; i < nr_objects; i++) {
 683                        struct object_entry *entry = *list++;
 684                        uint32_t crc32_val = htonl(entry->crc32);
 685                        sha1write(f, &crc32_val, 4);
 686                }
 687
 688                /* write the 32-bit offset table */
 689                list = sorted_by_sha;
 690                for (i = 0; i < nr_objects; i++) {
 691                        struct object_entry *entry = *list++;
 692                        uint32_t offset = (entry->offset <= index_off32_limit) ?
 693                                entry->offset : (0x80000000 | nr_large_offset++);
 694                        offset = htonl(offset);
 695                        sha1write(f, &offset, 4);
 696                }
 697
 698                /* write the large offset table */
 699                list = sorted_by_sha;
 700                while (nr_large_offset) {
 701                        struct object_entry *entry = *list++;
 702                        uint64_t offset = entry->offset;
 703                        if (offset > index_off32_limit) {
 704                                uint32_t split[2];
 705                                split[0]        = htonl(offset >> 32);
 706                                split[1] = htonl(offset & 0xffffffff);
 707                                sha1write(f, split, 8);
 708                                nr_large_offset--;
 709                        }
 710                }
 711        }
 712
 713        sha1write(f, pack_file_sha1, 20);
 714        sha1close(f, NULL, 1);
 715}
 716
 717static int locate_object_entry_hash(const unsigned char *sha1)
 718{
 719        int i;
 720        unsigned int ui;
 721        memcpy(&ui, sha1, sizeof(unsigned int));
 722        i = ui % object_ix_hashsz;
 723        while (0 < object_ix[i]) {
 724                if (!hashcmp(sha1, objects[object_ix[i] - 1].sha1))
 725                        return i;
 726                if (++i == object_ix_hashsz)
 727                        i = 0;
 728        }
 729        return -1 - i;
 730}
 731
 732static struct object_entry *locate_object_entry(const unsigned char *sha1)
 733{
 734        int i;
 735
 736        if (!object_ix_hashsz)
 737                return NULL;
 738
 739        i = locate_object_entry_hash(sha1);
 740        if (0 <= i)
 741                return &objects[object_ix[i]-1];
 742        return NULL;
 743}
 744
 745static void rehash_objects(void)
 746{
 747        uint32_t i;
 748        struct object_entry *oe;
 749
 750        object_ix_hashsz = nr_objects * 3;
 751        if (object_ix_hashsz < 1024)
 752                object_ix_hashsz = 1024;
 753        object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
 754        memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
 755        for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
 756                int ix = locate_object_entry_hash(oe->sha1);
 757                if (0 <= ix)
 758                        continue;
 759                ix = -1 - ix;
 760                object_ix[ix] = i + 1;
 761        }
 762}
 763
 764static unsigned name_hash(const char *name)
 765{
 766        unsigned char c;
 767        unsigned hash = 0;
 768
 769        /*
 770         * This effectively just creates a sortable number from the
 771         * last sixteen non-whitespace characters. Last characters
 772         * count "most", so things that end in ".c" sort together.
 773         */
 774        while ((c = *name++) != 0) {
 775                if (isspace(c))
 776                        continue;
 777                hash = (hash >> 2) + (c << 24);
 778        }
 779        return hash;
 780}
 781
 782static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
 783{
 784        uint32_t idx = nr_objects;
 785        struct object_entry *entry;
 786        struct packed_git *p;
 787        off_t found_offset = 0;
 788        struct packed_git *found_pack = NULL;
 789        int ix, status = 0;
 790
 791        if (!exclude) {
 792                for (p = packed_git; p; p = p->next) {
 793                        off_t offset = find_pack_entry_one(sha1, p);
 794                        if (offset) {
 795                                if (incremental)
 796                                        return 0;
 797                                if (local && !p->pack_local)
 798                                        return 0;
 799                                if (!found_pack) {
 800                                        found_offset = offset;
 801                                        found_pack = p;
 802                                }
 803                        }
 804                }
 805        }
 806        if ((entry = locate_object_entry(sha1)) != NULL)
 807                goto already_added;
 808
 809        if (idx >= nr_alloc) {
 810                nr_alloc = (idx + 1024) * 3 / 2;
 811                objects = xrealloc(objects, nr_alloc * sizeof(*entry));
 812        }
 813        entry = objects + idx;
 814        nr_objects = idx + 1;
 815        memset(entry, 0, sizeof(*entry));
 816        hashcpy(entry->sha1, sha1);
 817        entry->hash = hash;
 818
 819        if (object_ix_hashsz * 3 <= nr_objects * 4)
 820                rehash_objects();
 821        else {
 822                ix = locate_object_entry_hash(entry->sha1);
 823                if (0 <= ix)
 824                        die("internal error in object hashing.");
 825                object_ix[-1 - ix] = idx + 1;
 826        }
 827        status = 1;
 828
 829 already_added:
 830        if (progress_update) {
 831                fprintf(stderr, "Counting objects...%u\r", nr_objects);
 832                progress_update = 0;
 833        }
 834        if (exclude)
 835                entry->preferred_base = 1;
 836        else {
 837                if (found_pack) {
 838                        entry->in_pack = found_pack;
 839                        entry->in_pack_offset = found_offset;
 840                }
 841        }
 842        return status;
 843}
 844
 845struct pbase_tree_cache {
 846        unsigned char sha1[20];
 847        int ref;
 848        int temporary;
 849        void *tree_data;
 850        unsigned long tree_size;
 851};
 852
 853static struct pbase_tree_cache *(pbase_tree_cache[256]);
 854static int pbase_tree_cache_ix(const unsigned char *sha1)
 855{
 856        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
 857}
 858static int pbase_tree_cache_ix_incr(int ix)
 859{
 860        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
 861}
 862
 863static struct pbase_tree {
 864        struct pbase_tree *next;
 865        /* This is a phony "cache" entry; we are not
 866         * going to evict it nor find it through _get()
 867         * mechanism -- this is for the toplevel node that
 868         * would almost always change with any commit.
 869         */
 870        struct pbase_tree_cache pcache;
 871} *pbase_tree;
 872
 873static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
 874{
 875        struct pbase_tree_cache *ent, *nent;
 876        void *data;
 877        unsigned long size;
 878        enum object_type type;
 879        int neigh;
 880        int my_ix = pbase_tree_cache_ix(sha1);
 881        int available_ix = -1;
 882
 883        /* pbase-tree-cache acts as a limited hashtable.
 884         * your object will be found at your index or within a few
 885         * slots after that slot if it is cached.
 886         */
 887        for (neigh = 0; neigh < 8; neigh++) {
 888                ent = pbase_tree_cache[my_ix];
 889                if (ent && !hashcmp(ent->sha1, sha1)) {
 890                        ent->ref++;
 891                        return ent;
 892                }
 893                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
 894                         ((0 <= available_ix) &&
 895                          (!ent && pbase_tree_cache[available_ix])))
 896                        available_ix = my_ix;
 897                if (!ent)
 898                        break;
 899                my_ix = pbase_tree_cache_ix_incr(my_ix);
 900        }
 901
 902        /* Did not find one.  Either we got a bogus request or
 903         * we need to read and perhaps cache.
 904         */
 905        data = read_sha1_file(sha1, &type, &size);
 906        if (!data)
 907                return NULL;
 908        if (type != OBJ_TREE) {
 909                free(data);
 910                return NULL;
 911        }
 912
 913        /* We need to either cache or return a throwaway copy */
 914
 915        if (available_ix < 0)
 916                ent = NULL;
 917        else {
 918                ent = pbase_tree_cache[available_ix];
 919                my_ix = available_ix;
 920        }
 921
 922        if (!ent) {
 923                nent = xmalloc(sizeof(*nent));
 924                nent->temporary = (available_ix < 0);
 925        }
 926        else {
 927                /* evict and reuse */
 928                free(ent->tree_data);
 929                nent = ent;
 930        }
 931        hashcpy(nent->sha1, sha1);
 932        nent->tree_data = data;
 933        nent->tree_size = size;
 934        nent->ref = 1;
 935        if (!nent->temporary)
 936                pbase_tree_cache[my_ix] = nent;
 937        return nent;
 938}
 939
 940static void pbase_tree_put(struct pbase_tree_cache *cache)
 941{
 942        if (!cache->temporary) {
 943                cache->ref--;
 944                return;
 945        }
 946        free(cache->tree_data);
 947        free(cache);
 948}
 949
 950static int name_cmp_len(const char *name)
 951{
 952        int i;
 953        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
 954                ;
 955        return i;
 956}
 957
 958static void add_pbase_object(struct tree_desc *tree,
 959                             const char *name,
 960                             int cmplen,
 961                             const char *fullname)
 962{
 963        struct name_entry entry;
 964
 965        while (tree_entry(tree,&entry)) {
 966                unsigned long size;
 967                enum object_type type;
 968
 969                if (tree_entry_len(entry.path, entry.sha1) != cmplen ||
 970                    memcmp(entry.path, name, cmplen) ||
 971                    !has_sha1_file(entry.sha1) ||
 972                    (type = sha1_object_info(entry.sha1, &size)) < 0)
 973                        continue;
 974                if (name[cmplen] != '/') {
 975                        unsigned hash = name_hash(fullname);
 976                        add_object_entry(entry.sha1, hash, 1);
 977                        return;
 978                }
 979                if (type == OBJ_TREE) {
 980                        struct tree_desc sub;
 981                        struct pbase_tree_cache *tree;
 982                        const char *down = name+cmplen+1;
 983                        int downlen = name_cmp_len(down);
 984
 985                        tree = pbase_tree_get(entry.sha1);
 986                        if (!tree)
 987                                return;
 988                        init_tree_desc(&sub, tree->tree_data, tree->tree_size);
 989
 990                        add_pbase_object(&sub, down, downlen, fullname);
 991                        pbase_tree_put(tree);
 992                }
 993        }
 994}
 995
 996static unsigned *done_pbase_paths;
 997static int done_pbase_paths_num;
 998static int done_pbase_paths_alloc;
 999static int done_pbase_path_pos(unsigned hash)
1000{
1001        int lo = 0;
1002        int hi = done_pbase_paths_num;
1003        while (lo < hi) {
1004                int mi = (hi + lo) / 2;
1005                if (done_pbase_paths[mi] == hash)
1006                        return mi;
1007                if (done_pbase_paths[mi] < hash)
1008                        hi = mi;
1009                else
1010                        lo = mi + 1;
1011        }
1012        return -lo-1;
1013}
1014
1015static int check_pbase_path(unsigned hash)
1016{
1017        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1018        if (0 <= pos)
1019                return 1;
1020        pos = -pos - 1;
1021        if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1022                done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1023                done_pbase_paths = xrealloc(done_pbase_paths,
1024                                            done_pbase_paths_alloc *
1025                                            sizeof(unsigned));
1026        }
1027        done_pbase_paths_num++;
1028        if (pos < done_pbase_paths_num)
1029                memmove(done_pbase_paths + pos + 1,
1030                        done_pbase_paths + pos,
1031                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1032        done_pbase_paths[pos] = hash;
1033        return 0;
1034}
1035
1036static void add_preferred_base_object(const char *name, unsigned hash)
1037{
1038        struct pbase_tree *it;
1039        int cmplen = name_cmp_len(name);
1040
1041        if (check_pbase_path(hash))
1042                return;
1043
1044        for (it = pbase_tree; it; it = it->next) {
1045                if (cmplen == 0) {
1046                        hash = name_hash("");
1047                        add_object_entry(it->pcache.sha1, hash, 1);
1048                }
1049                else {
1050                        struct tree_desc tree;
1051                        init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1052                        add_pbase_object(&tree, name, cmplen, name);
1053                }
1054        }
1055}
1056
1057static void add_preferred_base(unsigned char *sha1)
1058{
1059        struct pbase_tree *it;
1060        void *data;
1061        unsigned long size;
1062        unsigned char tree_sha1[20];
1063
1064        if (window <= num_preferred_base++)
1065                return;
1066
1067        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1068        if (!data)
1069                return;
1070
1071        for (it = pbase_tree; it; it = it->next) {
1072                if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1073                        free(data);
1074                        return;
1075                }
1076        }
1077
1078        it = xcalloc(1, sizeof(*it));
1079        it->next = pbase_tree;
1080        pbase_tree = it;
1081
1082        hashcpy(it->pcache.sha1, tree_sha1);
1083        it->pcache.tree_data = data;
1084        it->pcache.tree_size = size;
1085}
1086
1087static void check_object(struct object_entry *entry)
1088{
1089        if (entry->in_pack && !entry->preferred_base) {
1090                struct packed_git *p = entry->in_pack;
1091                struct pack_window *w_curs = NULL;
1092                unsigned long size, used;
1093                unsigned int avail;
1094                unsigned char *buf;
1095                struct object_entry *base_entry = NULL;
1096
1097                buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1098
1099                /* We want in_pack_type even if we do not reuse delta.
1100                 * There is no point not reusing non-delta representations.
1101                 */
1102                used = unpack_object_header_gently(buf, avail,
1103                                                   &entry->in_pack_type, &size);
1104
1105                /* Check if it is delta, and the base is also an object
1106                 * we are going to pack.  If so we will reuse the existing
1107                 * delta.
1108                 */
1109                if (!no_reuse_delta) {
1110                        unsigned char c;
1111                        const unsigned char *base_name;
1112                        off_t ofs;
1113                        unsigned long used_0;
1114                        /* there is at least 20 bytes left in the pack */
1115                        switch (entry->in_pack_type) {
1116                        case OBJ_REF_DELTA:
1117                                base_name = use_pack(p, &w_curs,
1118                                        entry->in_pack_offset + used, NULL);
1119                                used += 20;
1120                                break;
1121                        case OBJ_OFS_DELTA:
1122                                buf = use_pack(p, &w_curs,
1123                                        entry->in_pack_offset + used, NULL);
1124                                used_0 = 0;
1125                                c = buf[used_0++];
1126                                ofs = c & 127;
1127                                while (c & 128) {
1128                                        ofs += 1;
1129                                        if (!ofs || MSB(ofs, 7))
1130                                                die("delta base offset overflow in pack for %s",
1131                                                    sha1_to_hex(entry->sha1));
1132                                        c = buf[used_0++];
1133                                        ofs = (ofs << 7) + (c & 127);
1134                                }
1135                                if (ofs >= entry->in_pack_offset)
1136                                        die("delta base offset out of bound for %s",
1137                                            sha1_to_hex(entry->sha1));
1138                                ofs = entry->in_pack_offset - ofs;
1139                                base_name = find_packed_object_name(p, ofs);
1140                                used += used_0;
1141                                break;
1142                        default:
1143                                base_name = NULL;
1144                        }
1145                        if (base_name)
1146                                base_entry = locate_object_entry(base_name);
1147                }
1148                unuse_pack(&w_curs);
1149                entry->in_pack_header_size = used;
1150
1151                if (base_entry) {
1152
1153                        /* Depth value does not matter - find_deltas()
1154                         * will never consider reused delta as the
1155                         * base object to deltify other objects
1156                         * against, in order to avoid circular deltas.
1157                         */
1158
1159                        /* uncompressed size of the delta data */
1160                        entry->size = size;
1161                        entry->delta = base_entry;
1162                        entry->type = entry->in_pack_type;
1163
1164                        entry->delta_sibling = base_entry->delta_child;
1165                        base_entry->delta_child = entry;
1166
1167                        return;
1168                }
1169                /* Otherwise we would do the usual */
1170        }
1171
1172        entry->type = sha1_object_info(entry->sha1, &entry->size);
1173        if (entry->type < 0)
1174                die("unable to get type of object %s",
1175                    sha1_to_hex(entry->sha1));
1176}
1177
1178static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1179{
1180        struct object_entry *child = me->delta_child;
1181        unsigned int m = n;
1182        while (child) {
1183                unsigned int c = check_delta_limit(child, n + 1);
1184                if (m < c)
1185                        m = c;
1186                child = child->delta_sibling;
1187        }
1188        return m;
1189}
1190
1191static void get_object_details(void)
1192{
1193        uint32_t i;
1194        struct object_entry *entry;
1195
1196        prepare_pack_ix();
1197        for (i = 0, entry = objects; i < nr_objects; i++, entry++)
1198                check_object(entry);
1199
1200        if (nr_objects == nr_result) {
1201                /*
1202                 * Depth of objects that depend on the entry -- this
1203                 * is subtracted from depth-max to break too deep
1204                 * delta chain because of delta data reusing.
1205                 * However, we loosen this restriction when we know we
1206                 * are creating a thin pack -- it will have to be
1207                 * expanded on the other end anyway, so do not
1208                 * artificially cut the delta chain and let it go as
1209                 * deep as it wants.
1210                 */
1211                for (i = 0, entry = objects; i < nr_objects; i++, entry++)
1212                        if (!entry->delta && entry->delta_child)
1213                                entry->delta_limit =
1214                                        check_delta_limit(entry, 1);
1215        }
1216}
1217
1218typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
1219
1220static entry_sort_t current_sort;
1221
1222static int sort_comparator(const void *_a, const void *_b)
1223{
1224        struct object_entry *a = *(struct object_entry **)_a;
1225        struct object_entry *b = *(struct object_entry **)_b;
1226        return current_sort(a,b);
1227}
1228
1229static struct object_entry **create_sorted_list(entry_sort_t sort)
1230{
1231        struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
1232        uint32_t i;
1233
1234        for (i = 0; i < nr_objects; i++)
1235                list[i] = objects + i;
1236        current_sort = sort;
1237        qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
1238        return list;
1239}
1240
1241static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
1242{
1243        return hashcmp(a->sha1, b->sha1);
1244}
1245
1246static struct object_entry **create_final_object_list(void)
1247{
1248        struct object_entry **list;
1249        uint32_t i, j;
1250
1251        for (i = nr_result = 0; i < nr_objects; i++)
1252                if (!objects[i].preferred_base)
1253                        nr_result++;
1254        list = xmalloc(nr_result * sizeof(struct object_entry *));
1255        for (i = j = 0; i < nr_objects; i++) {
1256                if (!objects[i].preferred_base)
1257                        list[j++] = objects + i;
1258        }
1259        current_sort = sha1_sort;
1260        qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
1261        return list;
1262}
1263
1264static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
1265{
1266        if (a->type < b->type)
1267                return -1;
1268        if (a->type > b->type)
1269                return 1;
1270        if (a->hash < b->hash)
1271                return -1;
1272        if (a->hash > b->hash)
1273                return 1;
1274        if (a->preferred_base < b->preferred_base)
1275                return -1;
1276        if (a->preferred_base > b->preferred_base)
1277                return 1;
1278        if (a->size < b->size)
1279                return -1;
1280        if (a->size > b->size)
1281                return 1;
1282        return a < b ? -1 : (a > b);
1283}
1284
1285struct unpacked {
1286        struct object_entry *entry;
1287        void *data;
1288        struct delta_index *index;
1289};
1290
1291/*
1292 * We search for deltas _backwards_ in a list sorted by type and
1293 * by size, so that we see progressively smaller and smaller files.
1294 * That's because we prefer deltas to be from the bigger file
1295 * to the smaller - deletes are potentially cheaper, but perhaps
1296 * more importantly, the bigger file is likely the more recent
1297 * one.
1298 */
1299static int try_delta(struct unpacked *trg, struct unpacked *src,
1300                     unsigned max_depth)
1301{
1302        struct object_entry *trg_entry = trg->entry;
1303        struct object_entry *src_entry = src->entry;
1304        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1305        enum object_type type;
1306        void *delta_buf;
1307
1308        /* Don't bother doing diffs between different types */
1309        if (trg_entry->type != src_entry->type)
1310                return -1;
1311
1312        /* We do not compute delta to *create* objects we are not
1313         * going to pack.
1314         */
1315        if (trg_entry->preferred_base)
1316                return -1;
1317
1318        /*
1319         * We do not bother to try a delta that we discarded
1320         * on an earlier try, but only when reusing delta data.
1321         */
1322        if (!no_reuse_delta && trg_entry->in_pack &&
1323            trg_entry->in_pack == src_entry->in_pack &&
1324            trg_entry->in_pack_type != OBJ_REF_DELTA &&
1325            trg_entry->in_pack_type != OBJ_OFS_DELTA)
1326                return 0;
1327
1328        /*
1329         * If the current object is at pack edge, take the depth the
1330         * objects that depend on the current object into account --
1331         * otherwise they would become too deep.
1332         */
1333        if (trg_entry->delta_child) {
1334                if (max_depth <= trg_entry->delta_limit)
1335                        return 0;
1336                max_depth -= trg_entry->delta_limit;
1337        }
1338        if (src_entry->depth >= max_depth)
1339                return 0;
1340
1341        /* Now some size filtering heuristics. */
1342        trg_size = trg_entry->size;
1343        max_size = trg_size/2 - 20;
1344        max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1345        if (max_size == 0)
1346                return 0;
1347        if (trg_entry->delta && trg_entry->delta_size <= max_size)
1348                max_size = trg_entry->delta_size-1;
1349        src_size = src_entry->size;
1350        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1351        if (sizediff >= max_size)
1352                return 0;
1353
1354        /* Load data if not already done */
1355        if (!trg->data) {
1356                trg->data = read_sha1_file(trg_entry->sha1, &type, &sz);
1357                if (sz != trg_size)
1358                        die("object %s inconsistent object length (%lu vs %lu)",
1359                            sha1_to_hex(trg_entry->sha1), sz, trg_size);
1360        }
1361        if (!src->data) {
1362                src->data = read_sha1_file(src_entry->sha1, &type, &sz);
1363                if (sz != src_size)
1364                        die("object %s inconsistent object length (%lu vs %lu)",
1365                            sha1_to_hex(src_entry->sha1), sz, src_size);
1366        }
1367        if (!src->index) {
1368                src->index = create_delta_index(src->data, src_size);
1369                if (!src->index)
1370                        die("out of memory");
1371        }
1372
1373        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1374        if (!delta_buf)
1375                return 0;
1376
1377        trg_entry->delta = src_entry;
1378        trg_entry->delta_size = delta_size;
1379        trg_entry->depth = src_entry->depth + 1;
1380        free(delta_buf);
1381        return 1;
1382}
1383
1384static void progress_interval(int signum)
1385{
1386        progress_update = 1;
1387}
1388
1389static void find_deltas(struct object_entry **list, int window, int depth)
1390{
1391        uint32_t i = nr_objects, idx = 0, processed = 0;
1392        unsigned int array_size = window * sizeof(struct unpacked);
1393        struct unpacked *array;
1394        unsigned last_percent = 999;
1395
1396        if (!nr_objects)
1397                return;
1398        array = xmalloc(array_size);
1399        memset(array, 0, array_size);
1400        if (progress)
1401                fprintf(stderr, "Deltifying %u objects.\n", nr_result);
1402
1403        do {
1404                struct object_entry *entry = list[--i];
1405                struct unpacked *n = array + idx;
1406                int j;
1407
1408                if (!entry->preferred_base)
1409                        processed++;
1410
1411                if (progress) {
1412                        unsigned percent = processed * 100 / nr_result;
1413                        if (percent != last_percent || progress_update) {
1414                                fprintf(stderr, "%4u%% (%u/%u) done\r",
1415                                        percent, processed, nr_result);
1416                                progress_update = 0;
1417                                last_percent = percent;
1418                        }
1419                }
1420
1421                if (entry->delta)
1422                        /* This happens if we decided to reuse existing
1423                         * delta from a pack.  "!no_reuse_delta &&" is implied.
1424                         */
1425                        continue;
1426
1427                if (entry->size < 50)
1428                        continue;
1429                free_delta_index(n->index);
1430                n->index = NULL;
1431                free(n->data);
1432                n->data = NULL;
1433                n->entry = entry;
1434
1435                j = window;
1436                while (--j > 0) {
1437                        uint32_t other_idx = idx + j;
1438                        struct unpacked *m;
1439                        if (other_idx >= window)
1440                                other_idx -= window;
1441                        m = array + other_idx;
1442                        if (!m->entry)
1443                                break;
1444                        if (try_delta(n, m, depth) < 0)
1445                                break;
1446                }
1447                /* if we made n a delta, and if n is already at max
1448                 * depth, leaving it in the window is pointless.  we
1449                 * should evict it first.
1450                 */
1451                if (entry->delta && depth <= entry->depth)
1452                        continue;
1453
1454                idx++;
1455                if (idx >= window)
1456                        idx = 0;
1457        } while (i > 0);
1458
1459        if (progress)
1460                fputc('\n', stderr);
1461
1462        for (i = 0; i < window; ++i) {
1463                free_delta_index(array[i].index);
1464                free(array[i].data);
1465        }
1466        free(array);
1467}
1468
1469static void prepare_pack(int window, int depth)
1470{
1471        get_object_details();
1472        sorted_by_type = create_sorted_list(type_size_sort);
1473        if (window && depth)
1474                find_deltas(sorted_by_type, window+1, depth);
1475}
1476
1477static int reuse_cached_pack(unsigned char *sha1)
1478{
1479        static const char cache[] = "pack-cache/pack-%s.%s";
1480        char *cached_pack, *cached_idx;
1481        int ifd, ofd, ifd_ix = -1;
1482
1483        cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1484        ifd = open(cached_pack, O_RDONLY);
1485        if (ifd < 0)
1486                return 0;
1487
1488        if (!pack_to_stdout) {
1489                cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1490                ifd_ix = open(cached_idx, O_RDONLY);
1491                if (ifd_ix < 0) {
1492                        close(ifd);
1493                        return 0;
1494                }
1495        }
1496
1497        if (progress)
1498                fprintf(stderr, "Reusing %u objects pack %s\n", nr_objects,
1499                        sha1_to_hex(sha1));
1500
1501        if (pack_to_stdout) {
1502                if (copy_fd(ifd, 1))
1503                        exit(1);
1504                close(ifd);
1505        }
1506        else {
1507                char name[PATH_MAX];
1508                snprintf(name, sizeof(name),
1509                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1510                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1511                if (ofd < 0)
1512                        die("unable to open %s (%s)", name, strerror(errno));
1513                if (copy_fd(ifd, ofd))
1514                        exit(1);
1515                close(ifd);
1516
1517                snprintf(name, sizeof(name),
1518                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1519                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1520                if (ofd < 0)
1521                        die("unable to open %s (%s)", name, strerror(errno));
1522                if (copy_fd(ifd_ix, ofd))
1523                        exit(1);
1524                close(ifd_ix);
1525                puts(sha1_to_hex(sha1));
1526        }
1527
1528        return 1;
1529}
1530
1531static void setup_progress_signal(void)
1532{
1533        struct sigaction sa;
1534        struct itimerval v;
1535
1536        memset(&sa, 0, sizeof(sa));
1537        sa.sa_handler = progress_interval;
1538        sigemptyset(&sa.sa_mask);
1539        sa.sa_flags = SA_RESTART;
1540        sigaction(SIGALRM, &sa, NULL);
1541
1542        v.it_interval.tv_sec = 1;
1543        v.it_interval.tv_usec = 0;
1544        v.it_value = v.it_interval;
1545        setitimer(ITIMER_REAL, &v, NULL);
1546}
1547
1548static int git_pack_config(const char *k, const char *v)
1549{
1550        if(!strcmp(k, "pack.window")) {
1551                window = git_config_int(k, v);
1552                return 0;
1553        }
1554        return git_default_config(k, v);
1555}
1556
1557static void read_object_list_from_stdin(void)
1558{
1559        char line[40 + 1 + PATH_MAX + 2];
1560        unsigned char sha1[20];
1561        unsigned hash;
1562
1563        for (;;) {
1564                if (!fgets(line, sizeof(line), stdin)) {
1565                        if (feof(stdin))
1566                                break;
1567                        if (!ferror(stdin))
1568                                die("fgets returned NULL, not EOF, not error!");
1569                        if (errno != EINTR)
1570                                die("fgets: %s", strerror(errno));
1571                        clearerr(stdin);
1572                        continue;
1573                }
1574                if (line[0] == '-') {
1575                        if (get_sha1_hex(line+1, sha1))
1576                                die("expected edge sha1, got garbage:\n %s",
1577                                    line);
1578                        add_preferred_base(sha1);
1579                        continue;
1580                }
1581                if (get_sha1_hex(line, sha1))
1582                        die("expected sha1, got garbage:\n %s", line);
1583
1584                hash = name_hash(line+41);
1585                add_preferred_base_object(line+41, hash);
1586                add_object_entry(sha1, hash, 0);
1587        }
1588}
1589
1590static void show_commit(struct commit *commit)
1591{
1592        unsigned hash = name_hash("");
1593        add_preferred_base_object("", hash);
1594        add_object_entry(commit->object.sha1, hash, 0);
1595}
1596
1597static void show_object(struct object_array_entry *p)
1598{
1599        unsigned hash = name_hash(p->name);
1600        add_preferred_base_object(p->name, hash);
1601        add_object_entry(p->item->sha1, hash, 0);
1602}
1603
1604static void show_edge(struct commit *commit)
1605{
1606        add_preferred_base(commit->object.sha1);
1607}
1608
1609static void get_object_list(int ac, const char **av)
1610{
1611        struct rev_info revs;
1612        char line[1000];
1613        int flags = 0;
1614
1615        init_revisions(&revs, NULL);
1616        save_commit_buffer = 0;
1617        track_object_refs = 0;
1618        setup_revisions(ac, av, &revs, NULL);
1619
1620        while (fgets(line, sizeof(line), stdin) != NULL) {
1621                int len = strlen(line);
1622                if (line[len - 1] == '\n')
1623                        line[--len] = 0;
1624                if (!len)
1625                        break;
1626                if (*line == '-') {
1627                        if (!strcmp(line, "--not")) {
1628                                flags ^= UNINTERESTING;
1629                                continue;
1630                        }
1631                        die("not a rev '%s'", line);
1632                }
1633                if (handle_revision_arg(line, &revs, flags, 1))
1634                        die("bad revision '%s'", line);
1635        }
1636
1637        prepare_revision_walk(&revs);
1638        mark_edges_uninteresting(revs.commits, &revs, show_edge);
1639        traverse_commit_list(&revs, show_commit, show_object);
1640}
1641
1642int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1643{
1644        SHA_CTX ctx;
1645        int depth = 10;
1646        struct object_entry **list;
1647        int use_internal_rev_list = 0;
1648        int thin = 0;
1649        uint32_t i;
1650        const char **rp_av;
1651        int rp_ac_alloc = 64;
1652        int rp_ac;
1653
1654        rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
1655
1656        rp_av[0] = "pack-objects";
1657        rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
1658        rp_ac = 2;
1659
1660        git_config(git_pack_config);
1661
1662        progress = isatty(2);
1663        for (i = 1; i < argc; i++) {
1664                const char *arg = argv[i];
1665
1666                if (*arg != '-')
1667                        break;
1668
1669                if (!strcmp("--non-empty", arg)) {
1670                        non_empty = 1;
1671                        continue;
1672                }
1673                if (!strcmp("--local", arg)) {
1674                        local = 1;
1675                        continue;
1676                }
1677                if (!strcmp("--incremental", arg)) {
1678                        incremental = 1;
1679                        continue;
1680                }
1681                if (!prefixcmp(arg, "--window=")) {
1682                        char *end;
1683                        window = strtoul(arg+9, &end, 0);
1684                        if (!arg[9] || *end)
1685                                usage(pack_usage);
1686                        continue;
1687                }
1688                if (!prefixcmp(arg, "--depth=")) {
1689                        char *end;
1690                        depth = strtoul(arg+8, &end, 0);
1691                        if (!arg[8] || *end)
1692                                usage(pack_usage);
1693                        continue;
1694                }
1695                if (!strcmp("--progress", arg)) {
1696                        progress = 1;
1697                        continue;
1698                }
1699                if (!strcmp("--all-progress", arg)) {
1700                        progress = 2;
1701                        continue;
1702                }
1703                if (!strcmp("-q", arg)) {
1704                        progress = 0;
1705                        continue;
1706                }
1707                if (!strcmp("--no-reuse-delta", arg)) {
1708                        no_reuse_delta = 1;
1709                        continue;
1710                }
1711                if (!strcmp("--delta-base-offset", arg)) {
1712                        allow_ofs_delta = 1;
1713                        continue;
1714                }
1715                if (!strcmp("--stdout", arg)) {
1716                        pack_to_stdout = 1;
1717                        continue;
1718                }
1719                if (!strcmp("--revs", arg)) {
1720                        use_internal_rev_list = 1;
1721                        continue;
1722                }
1723                if (!strcmp("--unpacked", arg) ||
1724                    !prefixcmp(arg, "--unpacked=") ||
1725                    !strcmp("--reflog", arg) ||
1726                    !strcmp("--all", arg)) {
1727                        use_internal_rev_list = 1;
1728                        if (rp_ac >= rp_ac_alloc - 1) {
1729                                rp_ac_alloc = alloc_nr(rp_ac_alloc);
1730                                rp_av = xrealloc(rp_av,
1731                                                 rp_ac_alloc * sizeof(*rp_av));
1732                        }
1733                        rp_av[rp_ac++] = arg;
1734                        continue;
1735                }
1736                if (!strcmp("--thin", arg)) {
1737                        use_internal_rev_list = 1;
1738                        thin = 1;
1739                        rp_av[1] = "--objects-edge";
1740                        continue;
1741                }
1742                if (!prefixcmp(arg, "--index-version=")) {
1743                        char *c;
1744                        index_default_version = strtoul(arg + 16, &c, 10);
1745                        if (index_default_version > 2)
1746                                die("bad %s", arg);
1747                        if (*c == ',')
1748                                index_off32_limit = strtoul(c+1, &c, 0);
1749                        if (*c || index_off32_limit & 0x80000000)
1750                                die("bad %s", arg);
1751                        continue;
1752                }
1753                usage(pack_usage);
1754        }
1755
1756        /* Traditionally "pack-objects [options] base extra" failed;
1757         * we would however want to take refs parameter that would
1758         * have been given to upstream rev-list ourselves, which means
1759         * we somehow want to say what the base name is.  So the
1760         * syntax would be:
1761         *
1762         * pack-objects [options] base <refs...>
1763         *
1764         * in other words, we would treat the first non-option as the
1765         * base_name and send everything else to the internal revision
1766         * walker.
1767         */
1768
1769        if (!pack_to_stdout)
1770                base_name = argv[i++];
1771
1772        if (pack_to_stdout != !base_name)
1773                usage(pack_usage);
1774
1775        if (!pack_to_stdout && thin)
1776                die("--thin cannot be used to build an indexable pack.");
1777
1778        prepare_packed_git();
1779
1780        if (progress) {
1781                fprintf(stderr, "Generating pack...\n");
1782                setup_progress_signal();
1783        }
1784
1785        if (!use_internal_rev_list)
1786                read_object_list_from_stdin();
1787        else {
1788                rp_av[rp_ac] = NULL;
1789                get_object_list(rp_ac, rp_av);
1790        }
1791
1792        if (progress)
1793                fprintf(stderr, "Done counting %u objects.\n", nr_objects);
1794        sorted_by_sha = create_final_object_list();
1795        if (non_empty && !nr_result)
1796                return 0;
1797
1798        SHA1_Init(&ctx);
1799        list = sorted_by_sha;
1800        for (i = 0; i < nr_result; i++) {
1801                struct object_entry *entry = *list++;
1802                SHA1_Update(&ctx, entry->sha1, 20);
1803        }
1804        SHA1_Final(object_list_sha1, &ctx);
1805        if (progress && (nr_objects != nr_result))
1806                fprintf(stderr, "Result has %u objects.\n", nr_result);
1807
1808        if (reuse_cached_pack(object_list_sha1))
1809                ;
1810        else {
1811                off_t last_obj_offset;
1812                if (nr_result)
1813                        prepare_pack(window, depth);
1814                if (progress == 1 && pack_to_stdout) {
1815                        /* the other end usually displays progress itself */
1816                        struct itimerval v = {{0,},};
1817                        setitimer(ITIMER_REAL, &v, NULL);
1818                        signal(SIGALRM, SIG_IGN );
1819                        progress_update = 0;
1820                }
1821                last_obj_offset = write_pack_file();
1822                if (!pack_to_stdout) {
1823                        write_index_file(last_obj_offset);
1824                        puts(sha1_to_hex(object_list_sha1));
1825                }
1826        }
1827        if (progress)
1828                fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
1829                        written, written_delta, reused, reused_delta);
1830        return 0;
1831}