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