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