builtin-pack-objects.con commit pack-objects: fix thinko in revalidate code (7042dbf)
   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 <sys/time.h>
  13#include <signal.h>
  14
  15static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
  16
  17struct object_entry {
  18        unsigned char sha1[20];
  19        unsigned long size;     /* uncompressed size */
  20        unsigned long offset;   /* offset into the final pack file;
  21                                 * nonzero if already written.
  22                                 */
  23        unsigned int depth;     /* delta depth */
  24        unsigned int delta_limit;       /* base adjustment for in-pack delta */
  25        unsigned int hash;      /* name hint hash */
  26        enum object_type type;
  27        enum object_type in_pack_type;  /* could be delta */
  28        unsigned long delta_size;       /* delta data size (uncompressed) */
  29        struct object_entry *delta;     /* delta base object */
  30        struct packed_git *in_pack;     /* already in pack */
  31        unsigned int in_pack_offset;
  32        struct object_entry *delta_child; /* deltified objects who bases me */
  33        struct object_entry *delta_sibling; /* other deltified objects who
  34                                             * uses the same base as me
  35                                             */
  36        int preferred_base;     /* we do not pack this, but is encouraged to
  37                                 * be used as the base objectto delta huge
  38                                 * objects against.
  39                                 */
  40};
  41
  42/*
  43 * Objects we are going to pack are collected in objects array (dynamically
  44 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  45 * in the order we see -- typically rev-list --objects order that gives us
  46 * nice "minimum seek" order.
  47 *
  48 * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
  49 * elements in the objects array.  The former is used to build the pack
  50 * index (lists object names in the ascending order to help offset lookup),
  51 * and the latter is used to group similar things together by try_delta()
  52 * heuristics.
  53 */
  54
  55static unsigned char object_list_sha1[20];
  56static int non_empty;
  57static int no_reuse_delta;
  58static int local;
  59static int incremental;
  60static struct object_entry **sorted_by_sha, **sorted_by_type;
  61static struct object_entry *objects;
  62static int nr_objects, nr_alloc, nr_result;
  63static const char *base_name;
  64static unsigned char pack_file_sha1[20];
  65static int progress = 1;
  66static volatile sig_atomic_t progress_update;
  67static int window = 10;
  68static int pack_to_stdout;
  69
  70/*
  71 * The object names in objects array are hashed with this hashtable,
  72 * to help looking up the entry by object name.  Binary search from
  73 * sorted_by_sha is also possible but this was easier to code and faster.
  74 * This hashtable is built after all the objects are seen.
  75 */
  76static int *object_ix;
  77static int object_ix_hashsz;
  78
  79/*
  80 * Pack index for existing packs give us easy access to the offsets into
  81 * corresponding pack file where each object's data starts, but the entries
  82 * do not store the size of the compressed representation (uncompressed
  83 * size is easily available by examining the pack entry header).  We build
  84 * a hashtable of existing packs (pack_revindex), and keep reverse index
  85 * here -- pack index file is sorted by object name mapping to offset; this
  86 * pack_revindex[].revindex array is an ordered list of offsets, so if you
  87 * know the offset of an object, next offset is where its packed
  88 * representation ends.
  89 */
  90struct pack_revindex {
  91        struct packed_git *p;
  92        unsigned long *revindex;
  93} *pack_revindex = NULL;
  94static int pack_revindex_hashsz;
  95
  96/*
  97 * stats
  98 */
  99static int written;
 100static int written_delta;
 101static int reused;
 102static int reused_delta;
 103
 104static int pack_revindex_ix(struct packed_git *p)
 105{
 106        unsigned long ui = (unsigned long)p;
 107        int i;
 108
 109        ui = ui ^ (ui >> 16); /* defeat structure alignment */
 110        i = (int)(ui % pack_revindex_hashsz);
 111        while (pack_revindex[i].p) {
 112                if (pack_revindex[i].p == p)
 113                        return i;
 114                if (++i == pack_revindex_hashsz)
 115                        i = 0;
 116        }
 117        return -1 - i;
 118}
 119
 120static void prepare_pack_ix(void)
 121{
 122        int num;
 123        struct packed_git *p;
 124        for (num = 0, p = packed_git; p; p = p->next)
 125                num++;
 126        if (!num)
 127                return;
 128        pack_revindex_hashsz = num * 11;
 129        pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
 130        for (p = packed_git; p; p = p->next) {
 131                num = pack_revindex_ix(p);
 132                num = - 1 - num;
 133                pack_revindex[num].p = p;
 134        }
 135        /* revindex elements are lazily initialized */
 136}
 137
 138static int cmp_offset(const void *a_, const void *b_)
 139{
 140        unsigned long a = *(unsigned long *) a_;
 141        unsigned long b = *(unsigned long *) b_;
 142        if (a < b)
 143                return -1;
 144        else if (a == b)
 145                return 0;
 146        else
 147                return 1;
 148}
 149
 150/*
 151 * Ordered list of offsets of objects in the pack.
 152 */
 153static void prepare_pack_revindex(struct pack_revindex *rix)
 154{
 155        struct packed_git *p = rix->p;
 156        int num_ent = num_packed_objects(p);
 157        int i;
 158        void *index = p->index_base + 256;
 159
 160        rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
 161        for (i = 0; i < num_ent; i++) {
 162                unsigned int hl = *((unsigned int *)((char *) index + 24*i));
 163                rix->revindex[i] = ntohl(hl);
 164        }
 165        /* This knows the pack format -- the 20-byte trailer
 166         * follows immediately after the last object data.
 167         */
 168        rix->revindex[num_ent] = p->pack_size - 20;
 169        qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
 170}
 171
 172static unsigned long find_packed_object_size(struct packed_git *p,
 173                                             unsigned long ofs)
 174{
 175        int num;
 176        int lo, hi;
 177        struct pack_revindex *rix;
 178        unsigned long *revindex;
 179        num = pack_revindex_ix(p);
 180        if (num < 0)
 181                die("internal error: pack revindex uninitialized");
 182        rix = &pack_revindex[num];
 183        if (!rix->revindex)
 184                prepare_pack_revindex(rix);
 185        revindex = rix->revindex;
 186        lo = 0;
 187        hi = num_packed_objects(p) + 1;
 188        do {
 189                int mi = (lo + hi) / 2;
 190                if (revindex[mi] == ofs) {
 191                        return revindex[mi+1] - ofs;
 192                }
 193                else if (ofs < revindex[mi])
 194                        hi = mi;
 195                else
 196                        lo = mi + 1;
 197        } while (lo < hi);
 198        die("internal error: pack revindex corrupt");
 199}
 200
 201static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
 202{
 203        unsigned long othersize, delta_size;
 204        char type[10];
 205        void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
 206        void *delta_buf;
 207
 208        if (!otherbuf)
 209                die("unable to read %s", sha1_to_hex(entry->delta->sha1));
 210        delta_buf = diff_delta(otherbuf, othersize,
 211                               buf, size, &delta_size, 0);
 212        if (!delta_buf || delta_size != entry->delta_size)
 213                die("delta size changed");
 214        free(buf);
 215        free(otherbuf);
 216        return delta_buf;
 217}
 218
 219/*
 220 * The per-object header is a pretty dense thing, which is
 221 *  - first byte: low four bits are "size", then three bits of "type",
 222 *    and the high bit is "size continues".
 223 *  - each byte afterwards: low seven bits are size continuation,
 224 *    with the high bit being "size continues"
 225 */
 226static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
 227{
 228        int n = 1;
 229        unsigned char c;
 230
 231        if (type < OBJ_COMMIT || type > OBJ_DELTA)
 232                die("bad type %d", type);
 233
 234        c = (type << 4) | (size & 15);
 235        size >>= 4;
 236        while (size) {
 237                *hdr++ = c | 0x80;
 238                c = size & 0x7f;
 239                size >>= 7;
 240                n++;
 241        }
 242        *hdr = c;
 243        return n;
 244}
 245
 246static int revalidate_one(struct object_entry *entry,
 247                          void *data, char *type, unsigned long size)
 248{
 249        int err;
 250        if ((!data) ||
 251            ((entry->type != OBJ_DELTA) &&
 252             ( (size != entry->size) ||
 253               strcmp(type_names[entry->type], type))))
 254                err = -1;
 255        else
 256                err = check_sha1_signature(entry->sha1, data, size, type);
 257        free(data);
 258        return err;
 259}
 260
 261/*
 262 * we are going to reuse the existing pack entry data.  make
 263 * sure it is not corrupt.
 264 */
 265static int revalidate_pack_entry(struct object_entry *entry)
 266{
 267        void *data;
 268        char type[20];
 269        unsigned long size;
 270        struct pack_entry e;
 271
 272        if (pack_to_stdout)
 273                return 0;
 274
 275        e.p = entry->in_pack;
 276        e.offset = entry->in_pack_offset;
 277
 278        /* the caller has already called use_packed_git() for us */
 279        data = unpack_entry_gently(&e, type, &size);
 280        return revalidate_one(entry, data, type, size);
 281}
 282
 283static int revalidate_loose_object(struct object_entry *entry,
 284                                   unsigned char *map,
 285                                   unsigned long mapsize)
 286{
 287        /* we already know this is a loose object with new type header. */
 288        void *data;
 289        char type[20];
 290        unsigned long size;
 291
 292        if (pack_to_stdout)
 293                return 0;
 294
 295        data = unpack_sha1_file(map, mapsize, type, &size);
 296        return revalidate_one(entry, data, type, size);
 297}
 298
 299static unsigned long write_object(struct sha1file *f,
 300                                  struct object_entry *entry)
 301{
 302        unsigned long size;
 303        char type[10];
 304        void *buf;
 305        unsigned char header[10];
 306        unsigned hdrlen, datalen;
 307        enum object_type obj_type;
 308        int to_reuse = 0;
 309
 310        if (entry->preferred_base)
 311                return 0;
 312
 313        obj_type = entry->type;
 314        if (! entry->in_pack)
 315                to_reuse = 0;   /* can't reuse what we don't have */
 316        else if (obj_type == OBJ_DELTA)
 317                to_reuse = 1;   /* check_object() decided it for us */
 318        else if (obj_type != entry->in_pack_type)
 319                to_reuse = 0;   /* pack has delta which is unusable */
 320        else if (entry->delta)
 321                to_reuse = 0;   /* we want to pack afresh */
 322        else
 323                to_reuse = 1;   /* we have it in-pack undeltified,
 324                                 * and we do not need to deltify it.
 325                                 */
 326
 327        if (!entry->in_pack && !entry->delta) {
 328                unsigned char *map;
 329                unsigned long mapsize;
 330                map = map_sha1_file(entry->sha1, &mapsize);
 331                if (map && !legacy_loose_object(map)) {
 332                        /* We can copy straight into the pack file */
 333                        if (revalidate_loose_object(entry, map, mapsize))
 334                                die("corrupt loose object %s",
 335                                    sha1_to_hex(entry->sha1));
 336                        sha1write(f, map, mapsize);
 337                        munmap(map, mapsize);
 338                        written++;
 339                        reused++;
 340                        return mapsize;
 341                }
 342                if (map)
 343                        munmap(map, mapsize);
 344        }
 345
 346        if (!to_reuse) {
 347                buf = read_sha1_file(entry->sha1, type, &size);
 348                if (!buf)
 349                        die("unable to read %s", sha1_to_hex(entry->sha1));
 350                if (size != entry->size)
 351                        die("object %s size inconsistency (%lu vs %lu)",
 352                            sha1_to_hex(entry->sha1), size, entry->size);
 353                if (entry->delta) {
 354                        buf = delta_against(buf, size, entry);
 355                        size = entry->delta_size;
 356                        obj_type = OBJ_DELTA;
 357                }
 358                /*
 359                 * The object header is a byte of 'type' followed by zero or
 360                 * more bytes of length.  For deltas, the 20 bytes of delta
 361                 * sha1 follows that.
 362                 */
 363                hdrlen = encode_header(obj_type, size, header);
 364                sha1write(f, header, hdrlen);
 365
 366                if (entry->delta) {
 367                        sha1write(f, entry->delta, 20);
 368                        hdrlen += 20;
 369                }
 370                datalen = sha1write_compressed(f, buf, size);
 371                free(buf);
 372        }
 373        else {
 374                struct packed_git *p = entry->in_pack;
 375                use_packed_git(p);
 376
 377                datalen = find_packed_object_size(p, entry->in_pack_offset);
 378                buf = (char *) p->pack_base + entry->in_pack_offset;
 379
 380                if (revalidate_pack_entry(entry))
 381                        die("corrupt delta in pack %s", sha1_to_hex(entry->sha1));
 382                sha1write(f, buf, datalen);
 383                unuse_packed_git(p);
 384                hdrlen = 0; /* not really */
 385                if (obj_type == OBJ_DELTA)
 386                        reused_delta++;
 387                reused++;
 388        }
 389        if (obj_type == OBJ_DELTA)
 390                written_delta++;
 391        written++;
 392        return hdrlen + datalen;
 393}
 394
 395static unsigned long write_one(struct sha1file *f,
 396                               struct object_entry *e,
 397                               unsigned long offset)
 398{
 399        if (e->offset)
 400                /* offset starts from header size and cannot be zero
 401                 * if it is written already.
 402                 */
 403                return offset;
 404        e->offset = offset;
 405        offset += write_object(f, e);
 406        /* if we are deltified, write out its base object. */
 407        if (e->delta)
 408                offset = write_one(f, e->delta, offset);
 409        return offset;
 410}
 411
 412static void write_pack_file(void)
 413{
 414        int i;
 415        struct sha1file *f;
 416        unsigned long offset;
 417        struct pack_header hdr;
 418        unsigned last_percent = 999;
 419        int do_progress = 0;
 420
 421        if (!base_name)
 422                f = sha1fd(1, "<stdout>");
 423        else {
 424                f = sha1create("%s-%s.%s", base_name,
 425                               sha1_to_hex(object_list_sha1), "pack");
 426                do_progress = progress;
 427        }
 428        if (do_progress)
 429                fprintf(stderr, "Writing %d objects.\n", nr_result);
 430
 431        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 432        hdr.hdr_version = htonl(PACK_VERSION);
 433        hdr.hdr_entries = htonl(nr_result);
 434        sha1write(f, &hdr, sizeof(hdr));
 435        offset = sizeof(hdr);
 436        if (!nr_result)
 437                goto done;
 438        for (i = 0; i < nr_objects; i++) {
 439                offset = write_one(f, objects + i, offset);
 440                if (do_progress) {
 441                        unsigned percent = written * 100 / nr_result;
 442                        if (progress_update || percent != last_percent) {
 443                                fprintf(stderr, "%4u%% (%u/%u) done\r",
 444                                        percent, written, nr_result);
 445                                progress_update = 0;
 446                                last_percent = percent;
 447                        }
 448                }
 449        }
 450        if (do_progress)
 451                fputc('\n', stderr);
 452 done:
 453        sha1close(f, pack_file_sha1, 1);
 454}
 455
 456static void write_index_file(void)
 457{
 458        int i;
 459        struct sha1file *f = sha1create("%s-%s.%s", base_name,
 460                                        sha1_to_hex(object_list_sha1), "idx");
 461        struct object_entry **list = sorted_by_sha;
 462        struct object_entry **last = list + nr_result;
 463        unsigned int array[256];
 464
 465        /*
 466         * Write the first-level table (the list is sorted,
 467         * but we use a 256-entry lookup to be able to avoid
 468         * having to do eight extra binary search iterations).
 469         */
 470        for (i = 0; i < 256; i++) {
 471                struct object_entry **next = list;
 472                while (next < last) {
 473                        struct object_entry *entry = *next;
 474                        if (entry->sha1[0] != i)
 475                                break;
 476                        next++;
 477                }
 478                array[i] = htonl(next - sorted_by_sha);
 479                list = next;
 480        }
 481        sha1write(f, array, 256 * sizeof(int));
 482
 483        /*
 484         * Write the actual SHA1 entries..
 485         */
 486        list = sorted_by_sha;
 487        for (i = 0; i < nr_result; i++) {
 488                struct object_entry *entry = *list++;
 489                unsigned int offset = htonl(entry->offset);
 490                sha1write(f, &offset, 4);
 491                sha1write(f, entry->sha1, 20);
 492        }
 493        sha1write(f, pack_file_sha1, 20);
 494        sha1close(f, NULL, 1);
 495}
 496
 497static int locate_object_entry_hash(const unsigned char *sha1)
 498{
 499        int i;
 500        unsigned int ui;
 501        memcpy(&ui, sha1, sizeof(unsigned int));
 502        i = ui % object_ix_hashsz;
 503        while (0 < object_ix[i]) {
 504                if (!hashcmp(sha1, objects[object_ix[i] - 1].sha1))
 505                        return i;
 506                if (++i == object_ix_hashsz)
 507                        i = 0;
 508        }
 509        return -1 - i;
 510}
 511
 512static struct object_entry *locate_object_entry(const unsigned char *sha1)
 513{
 514        int i;
 515
 516        if (!object_ix_hashsz)
 517                return NULL;
 518
 519        i = locate_object_entry_hash(sha1);
 520        if (0 <= i)
 521                return &objects[object_ix[i]-1];
 522        return NULL;
 523}
 524
 525static void rehash_objects(void)
 526{
 527        int i;
 528        struct object_entry *oe;
 529
 530        object_ix_hashsz = nr_objects * 3;
 531        if (object_ix_hashsz < 1024)
 532                object_ix_hashsz = 1024;
 533        object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
 534        memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
 535        for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
 536                int ix = locate_object_entry_hash(oe->sha1);
 537                if (0 <= ix)
 538                        continue;
 539                ix = -1 - ix;
 540                object_ix[ix] = i + 1;
 541        }
 542}
 543
 544static unsigned name_hash(const char *name)
 545{
 546        unsigned char c;
 547        unsigned hash = 0;
 548
 549        /*
 550         * This effectively just creates a sortable number from the
 551         * last sixteen non-whitespace characters. Last characters
 552         * count "most", so things that end in ".c" sort together.
 553         */
 554        while ((c = *name++) != 0) {
 555                if (isspace(c))
 556                        continue;
 557                hash = (hash >> 2) + (c << 24);
 558        }
 559        return hash;
 560}
 561
 562static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
 563{
 564        unsigned int idx = nr_objects;
 565        struct object_entry *entry;
 566        struct packed_git *p;
 567        unsigned int found_offset = 0;
 568        struct packed_git *found_pack = NULL;
 569        int ix, status = 0;
 570
 571        if (!exclude) {
 572                for (p = packed_git; p; p = p->next) {
 573                        struct pack_entry e;
 574                        if (find_pack_entry_one(sha1, &e, p)) {
 575                                if (incremental)
 576                                        return 0;
 577                                if (local && !p->pack_local)
 578                                        return 0;
 579                                if (!found_pack) {
 580                                        found_offset = e.offset;
 581                                        found_pack = e.p;
 582                                }
 583                        }
 584                }
 585        }
 586        if ((entry = locate_object_entry(sha1)) != NULL)
 587                goto already_added;
 588
 589        if (idx >= nr_alloc) {
 590                unsigned int needed = (idx + 1024) * 3 / 2;
 591                objects = xrealloc(objects, needed * sizeof(*entry));
 592                nr_alloc = needed;
 593        }
 594        entry = objects + idx;
 595        nr_objects = idx + 1;
 596        memset(entry, 0, sizeof(*entry));
 597        hashcpy(entry->sha1, sha1);
 598        entry->hash = hash;
 599
 600        if (object_ix_hashsz * 3 <= nr_objects * 4)
 601                rehash_objects();
 602        else {
 603                ix = locate_object_entry_hash(entry->sha1);
 604                if (0 <= ix)
 605                        die("internal error in object hashing.");
 606                object_ix[-1 - ix] = idx + 1;
 607        }
 608        status = 1;
 609
 610 already_added:
 611        if (progress_update) {
 612                fprintf(stderr, "Counting objects...%d\r", nr_objects);
 613                progress_update = 0;
 614        }
 615        if (exclude)
 616                entry->preferred_base = 1;
 617        else {
 618                if (found_pack) {
 619                        entry->in_pack = found_pack;
 620                        entry->in_pack_offset = found_offset;
 621                }
 622        }
 623        return status;
 624}
 625
 626struct pbase_tree_cache {
 627        unsigned char sha1[20];
 628        int ref;
 629        int temporary;
 630        void *tree_data;
 631        unsigned long tree_size;
 632};
 633
 634static struct pbase_tree_cache *(pbase_tree_cache[256]);
 635static int pbase_tree_cache_ix(const unsigned char *sha1)
 636{
 637        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
 638}
 639static int pbase_tree_cache_ix_incr(int ix)
 640{
 641        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
 642}
 643
 644static struct pbase_tree {
 645        struct pbase_tree *next;
 646        /* This is a phony "cache" entry; we are not
 647         * going to evict it nor find it through _get()
 648         * mechanism -- this is for the toplevel node that
 649         * would almost always change with any commit.
 650         */
 651        struct pbase_tree_cache pcache;
 652} *pbase_tree;
 653
 654static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
 655{
 656        struct pbase_tree_cache *ent, *nent;
 657        void *data;
 658        unsigned long size;
 659        char type[20];
 660        int neigh;
 661        int my_ix = pbase_tree_cache_ix(sha1);
 662        int available_ix = -1;
 663
 664        /* pbase-tree-cache acts as a limited hashtable.
 665         * your object will be found at your index or within a few
 666         * slots after that slot if it is cached.
 667         */
 668        for (neigh = 0; neigh < 8; neigh++) {
 669                ent = pbase_tree_cache[my_ix];
 670                if (ent && !hashcmp(ent->sha1, sha1)) {
 671                        ent->ref++;
 672                        return ent;
 673                }
 674                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
 675                         ((0 <= available_ix) &&
 676                          (!ent && pbase_tree_cache[available_ix])))
 677                        available_ix = my_ix;
 678                if (!ent)
 679                        break;
 680                my_ix = pbase_tree_cache_ix_incr(my_ix);
 681        }
 682
 683        /* Did not find one.  Either we got a bogus request or
 684         * we need to read and perhaps cache.
 685         */
 686        data = read_sha1_file(sha1, type, &size);
 687        if (!data)
 688                return NULL;
 689        if (strcmp(type, tree_type)) {
 690                free(data);
 691                return NULL;
 692        }
 693
 694        /* We need to either cache or return a throwaway copy */
 695
 696        if (available_ix < 0)
 697                ent = NULL;
 698        else {
 699                ent = pbase_tree_cache[available_ix];
 700                my_ix = available_ix;
 701        }
 702
 703        if (!ent) {
 704                nent = xmalloc(sizeof(*nent));
 705                nent->temporary = (available_ix < 0);
 706        }
 707        else {
 708                /* evict and reuse */
 709                free(ent->tree_data);
 710                nent = ent;
 711        }
 712        hashcpy(nent->sha1, sha1);
 713        nent->tree_data = data;
 714        nent->tree_size = size;
 715        nent->ref = 1;
 716        if (!nent->temporary)
 717                pbase_tree_cache[my_ix] = nent;
 718        return nent;
 719}
 720
 721static void pbase_tree_put(struct pbase_tree_cache *cache)
 722{
 723        if (!cache->temporary) {
 724                cache->ref--;
 725                return;
 726        }
 727        free(cache->tree_data);
 728        free(cache);
 729}
 730
 731static int name_cmp_len(const char *name)
 732{
 733        int i;
 734        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
 735                ;
 736        return i;
 737}
 738
 739static void add_pbase_object(struct tree_desc *tree,
 740                             const char *name,
 741                             int cmplen,
 742                             const char *fullname)
 743{
 744        struct name_entry entry;
 745
 746        while (tree_entry(tree,&entry)) {
 747                unsigned long size;
 748                char type[20];
 749
 750                if (entry.pathlen != cmplen ||
 751                    memcmp(entry.path, name, cmplen) ||
 752                    !has_sha1_file(entry.sha1) ||
 753                    sha1_object_info(entry.sha1, type, &size))
 754                        continue;
 755                if (name[cmplen] != '/') {
 756                        unsigned hash = name_hash(fullname);
 757                        add_object_entry(entry.sha1, hash, 1);
 758                        return;
 759                }
 760                if (!strcmp(type, tree_type)) {
 761                        struct tree_desc sub;
 762                        struct pbase_tree_cache *tree;
 763                        const char *down = name+cmplen+1;
 764                        int downlen = name_cmp_len(down);
 765
 766                        tree = pbase_tree_get(entry.sha1);
 767                        if (!tree)
 768                                return;
 769                        sub.buf = tree->tree_data;
 770                        sub.size = tree->tree_size;
 771
 772                        add_pbase_object(&sub, down, downlen, fullname);
 773                        pbase_tree_put(tree);
 774                }
 775        }
 776}
 777
 778static unsigned *done_pbase_paths;
 779static int done_pbase_paths_num;
 780static int done_pbase_paths_alloc;
 781static int done_pbase_path_pos(unsigned hash)
 782{
 783        int lo = 0;
 784        int hi = done_pbase_paths_num;
 785        while (lo < hi) {
 786                int mi = (hi + lo) / 2;
 787                if (done_pbase_paths[mi] == hash)
 788                        return mi;
 789                if (done_pbase_paths[mi] < hash)
 790                        hi = mi;
 791                else
 792                        lo = mi + 1;
 793        }
 794        return -lo-1;
 795}
 796
 797static int check_pbase_path(unsigned hash)
 798{
 799        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
 800        if (0 <= pos)
 801                return 1;
 802        pos = -pos - 1;
 803        if (done_pbase_paths_alloc <= done_pbase_paths_num) {
 804                done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
 805                done_pbase_paths = xrealloc(done_pbase_paths,
 806                                            done_pbase_paths_alloc *
 807                                            sizeof(unsigned));
 808        }
 809        done_pbase_paths_num++;
 810        if (pos < done_pbase_paths_num)
 811                memmove(done_pbase_paths + pos + 1,
 812                        done_pbase_paths + pos,
 813                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
 814        done_pbase_paths[pos] = hash;
 815        return 0;
 816}
 817
 818static void add_preferred_base_object(char *name, unsigned hash)
 819{
 820        struct pbase_tree *it;
 821        int cmplen = name_cmp_len(name);
 822
 823        if (check_pbase_path(hash))
 824                return;
 825
 826        for (it = pbase_tree; it; it = it->next) {
 827                if (cmplen == 0) {
 828                        hash = name_hash("");
 829                        add_object_entry(it->pcache.sha1, hash, 1);
 830                }
 831                else {
 832                        struct tree_desc tree;
 833                        tree.buf = it->pcache.tree_data;
 834                        tree.size = it->pcache.tree_size;
 835                        add_pbase_object(&tree, name, cmplen, name);
 836                }
 837        }
 838}
 839
 840static void add_preferred_base(unsigned char *sha1)
 841{
 842        struct pbase_tree *it;
 843        void *data;
 844        unsigned long size;
 845        unsigned char tree_sha1[20];
 846
 847        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
 848        if (!data)
 849                return;
 850
 851        for (it = pbase_tree; it; it = it->next) {
 852                if (!hashcmp(it->pcache.sha1, tree_sha1)) {
 853                        free(data);
 854                        return;
 855                }
 856        }
 857
 858        it = xcalloc(1, sizeof(*it));
 859        it->next = pbase_tree;
 860        pbase_tree = it;
 861
 862        hashcpy(it->pcache.sha1, tree_sha1);
 863        it->pcache.tree_data = data;
 864        it->pcache.tree_size = size;
 865}
 866
 867static void check_object(struct object_entry *entry)
 868{
 869        char type[20];
 870
 871        if (entry->in_pack && !entry->preferred_base) {
 872                unsigned char base[20];
 873                unsigned long size;
 874                struct object_entry *base_entry;
 875
 876                /* We want in_pack_type even if we do not reuse delta.
 877                 * There is no point not reusing non-delta representations.
 878                 */
 879                check_reuse_pack_delta(entry->in_pack,
 880                                       entry->in_pack_offset,
 881                                       base, &size,
 882                                       &entry->in_pack_type);
 883
 884                /* Check if it is delta, and the base is also an object
 885                 * we are going to pack.  If so we will reuse the existing
 886                 * delta.
 887                 */
 888                if (!no_reuse_delta &&
 889                    entry->in_pack_type == OBJ_DELTA &&
 890                    (base_entry = locate_object_entry(base)) &&
 891                    (!base_entry->preferred_base)) {
 892
 893                        /* Depth value does not matter - find_deltas()
 894                         * will never consider reused delta as the
 895                         * base object to deltify other objects
 896                         * against, in order to avoid circular deltas.
 897                         */
 898
 899                        /* uncompressed size of the delta data */
 900                        entry->size = entry->delta_size = size;
 901                        entry->delta = base_entry;
 902                        entry->type = OBJ_DELTA;
 903
 904                        entry->delta_sibling = base_entry->delta_child;
 905                        base_entry->delta_child = entry;
 906
 907                        return;
 908                }
 909                /* Otherwise we would do the usual */
 910        }
 911
 912        if (sha1_object_info(entry->sha1, type, &entry->size))
 913                die("unable to get type of object %s",
 914                    sha1_to_hex(entry->sha1));
 915
 916        if (!strcmp(type, commit_type)) {
 917                entry->type = OBJ_COMMIT;
 918        } else if (!strcmp(type, tree_type)) {
 919                entry->type = OBJ_TREE;
 920        } else if (!strcmp(type, blob_type)) {
 921                entry->type = OBJ_BLOB;
 922        } else if (!strcmp(type, tag_type)) {
 923                entry->type = OBJ_TAG;
 924        } else
 925                die("unable to pack object %s of type %s",
 926                    sha1_to_hex(entry->sha1), type);
 927}
 928
 929static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
 930{
 931        struct object_entry *child = me->delta_child;
 932        unsigned int m = n;
 933        while (child) {
 934                unsigned int c = check_delta_limit(child, n + 1);
 935                if (m < c)
 936                        m = c;
 937                child = child->delta_sibling;
 938        }
 939        return m;
 940}
 941
 942static void get_object_details(void)
 943{
 944        int i;
 945        struct object_entry *entry;
 946
 947        prepare_pack_ix();
 948        for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 949                check_object(entry);
 950
 951        if (nr_objects == nr_result) {
 952                /*
 953                 * Depth of objects that depend on the entry -- this
 954                 * is subtracted from depth-max to break too deep
 955                 * delta chain because of delta data reusing.
 956                 * However, we loosen this restriction when we know we
 957                 * are creating a thin pack -- it will have to be
 958                 * expanded on the other end anyway, so do not
 959                 * artificially cut the delta chain and let it go as
 960                 * deep as it wants.
 961                 */
 962                for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 963                        if (!entry->delta && entry->delta_child)
 964                                entry->delta_limit =
 965                                        check_delta_limit(entry, 1);
 966        }
 967}
 968
 969typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
 970
 971static entry_sort_t current_sort;
 972
 973static int sort_comparator(const void *_a, const void *_b)
 974{
 975        struct object_entry *a = *(struct object_entry **)_a;
 976        struct object_entry *b = *(struct object_entry **)_b;
 977        return current_sort(a,b);
 978}
 979
 980static struct object_entry **create_sorted_list(entry_sort_t sort)
 981{
 982        struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
 983        int i;
 984
 985        for (i = 0; i < nr_objects; i++)
 986                list[i] = objects + i;
 987        current_sort = sort;
 988        qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
 989        return list;
 990}
 991
 992static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
 993{
 994        return hashcmp(a->sha1, b->sha1);
 995}
 996
 997static struct object_entry **create_final_object_list(void)
 998{
 999        struct object_entry **list;
1000        int i, j;
1001
1002        for (i = nr_result = 0; i < nr_objects; i++)
1003                if (!objects[i].preferred_base)
1004                        nr_result++;
1005        list = xmalloc(nr_result * sizeof(struct object_entry *));
1006        for (i = j = 0; i < nr_objects; i++) {
1007                if (!objects[i].preferred_base)
1008                        list[j++] = objects + i;
1009        }
1010        current_sort = sha1_sort;
1011        qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
1012        return list;
1013}
1014
1015static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
1016{
1017        if (a->type < b->type)
1018                return -1;
1019        if (a->type > b->type)
1020                return 1;
1021        if (a->hash < b->hash)
1022                return -1;
1023        if (a->hash > b->hash)
1024                return 1;
1025        if (a->preferred_base < b->preferred_base)
1026                return -1;
1027        if (a->preferred_base > b->preferred_base)
1028                return 1;
1029        if (a->size < b->size)
1030                return -1;
1031        if (a->size > b->size)
1032                return 1;
1033        return a < b ? -1 : (a > b);
1034}
1035
1036struct unpacked {
1037        struct object_entry *entry;
1038        void *data;
1039        struct delta_index *index;
1040};
1041
1042/*
1043 * We search for deltas _backwards_ in a list sorted by type and
1044 * by size, so that we see progressively smaller and smaller files.
1045 * That's because we prefer deltas to be from the bigger file
1046 * to the smaller - deletes are potentially cheaper, but perhaps
1047 * more importantly, the bigger file is likely the more recent
1048 * one.
1049 */
1050static int try_delta(struct unpacked *trg, struct unpacked *src,
1051                     unsigned max_depth)
1052{
1053        struct object_entry *trg_entry = trg->entry;
1054        struct object_entry *src_entry = src->entry;
1055        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1056        char type[10];
1057        void *delta_buf;
1058
1059        /* Don't bother doing diffs between different types */
1060        if (trg_entry->type != src_entry->type)
1061                return -1;
1062
1063        /* We do not compute delta to *create* objects we are not
1064         * going to pack.
1065         */
1066        if (trg_entry->preferred_base)
1067                return -1;
1068
1069        /*
1070         * We do not bother to try a delta that we discarded
1071         * on an earlier try, but only when reusing delta data.
1072         */
1073        if (!no_reuse_delta && trg_entry->in_pack &&
1074            trg_entry->in_pack == src_entry->in_pack)
1075                return 0;
1076
1077        /*
1078         * If the current object is at pack edge, take the depth the
1079         * objects that depend on the current object into account --
1080         * otherwise they would become too deep.
1081         */
1082        if (trg_entry->delta_child) {
1083                if (max_depth <= trg_entry->delta_limit)
1084                        return 0;
1085                max_depth -= trg_entry->delta_limit;
1086        }
1087        if (src_entry->depth >= max_depth)
1088                return 0;
1089
1090        /* Now some size filtering heuristics. */
1091        trg_size = trg_entry->size;
1092        max_size = trg_size/2 - 20;
1093        max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1094        if (max_size == 0)
1095                return 0;
1096        if (trg_entry->delta && trg_entry->delta_size <= max_size)
1097                max_size = trg_entry->delta_size-1;
1098        src_size = src_entry->size;
1099        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1100        if (sizediff >= max_size)
1101                return 0;
1102
1103        /* Load data if not already done */
1104        if (!trg->data) {
1105                trg->data = read_sha1_file(trg_entry->sha1, type, &sz);
1106                if (sz != trg_size)
1107                        die("object %s inconsistent object length (%lu vs %lu)",
1108                            sha1_to_hex(trg_entry->sha1), sz, trg_size);
1109        }
1110        if (!src->data) {
1111                src->data = read_sha1_file(src_entry->sha1, type, &sz);
1112                if (sz != src_size)
1113                        die("object %s inconsistent object length (%lu vs %lu)",
1114                            sha1_to_hex(src_entry->sha1), sz, src_size);
1115        }
1116        if (!src->index) {
1117                src->index = create_delta_index(src->data, src_size);
1118                if (!src->index)
1119                        die("out of memory");
1120        }
1121
1122        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1123        if (!delta_buf)
1124                return 0;
1125
1126        trg_entry->delta = src_entry;
1127        trg_entry->delta_size = delta_size;
1128        trg_entry->depth = src_entry->depth + 1;
1129        free(delta_buf);
1130        return 1;
1131}
1132
1133static void progress_interval(int signum)
1134{
1135        progress_update = 1;
1136}
1137
1138static void find_deltas(struct object_entry **list, int window, int depth)
1139{
1140        int i, idx;
1141        unsigned int array_size = window * sizeof(struct unpacked);
1142        struct unpacked *array = xmalloc(array_size);
1143        unsigned processed = 0;
1144        unsigned last_percent = 999;
1145
1146        memset(array, 0, array_size);
1147        i = nr_objects;
1148        idx = 0;
1149        if (progress)
1150                fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1151
1152        while (--i >= 0) {
1153                struct object_entry *entry = list[i];
1154                struct unpacked *n = array + idx;
1155                int j;
1156
1157                if (!entry->preferred_base)
1158                        processed++;
1159
1160                if (progress) {
1161                        unsigned percent = processed * 100 / nr_result;
1162                        if (percent != last_percent || progress_update) {
1163                                fprintf(stderr, "%4u%% (%u/%u) done\r",
1164                                        percent, processed, nr_result);
1165                                progress_update = 0;
1166                                last_percent = percent;
1167                        }
1168                }
1169
1170                if (entry->delta)
1171                        /* This happens if we decided to reuse existing
1172                         * delta from a pack.  "!no_reuse_delta &&" is implied.
1173                         */
1174                        continue;
1175
1176                if (entry->size < 50)
1177                        continue;
1178                free_delta_index(n->index);
1179                n->index = NULL;
1180                free(n->data);
1181                n->data = NULL;
1182                n->entry = entry;
1183
1184                j = window;
1185                while (--j > 0) {
1186                        unsigned int other_idx = idx + j;
1187                        struct unpacked *m;
1188                        if (other_idx >= window)
1189                                other_idx -= window;
1190                        m = array + other_idx;
1191                        if (!m->entry)
1192                                break;
1193                        if (try_delta(n, m, depth) < 0)
1194                                break;
1195                }
1196                /* if we made n a delta, and if n is already at max
1197                 * depth, leaving it in the window is pointless.  we
1198                 * should evict it first.
1199                 */
1200                if (entry->delta && depth <= entry->depth)
1201                        continue;
1202
1203                idx++;
1204                if (idx >= window)
1205                        idx = 0;
1206        }
1207
1208        if (progress)
1209                fputc('\n', stderr);
1210
1211        for (i = 0; i < window; ++i) {
1212                free_delta_index(array[i].index);
1213                free(array[i].data);
1214        }
1215        free(array);
1216}
1217
1218static void prepare_pack(int window, int depth)
1219{
1220        get_object_details();
1221        sorted_by_type = create_sorted_list(type_size_sort);
1222        if (window && depth)
1223                find_deltas(sorted_by_type, window+1, depth);
1224}
1225
1226static int reuse_cached_pack(unsigned char *sha1)
1227{
1228        static const char cache[] = "pack-cache/pack-%s.%s";
1229        char *cached_pack, *cached_idx;
1230        int ifd, ofd, ifd_ix = -1;
1231
1232        cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1233        ifd = open(cached_pack, O_RDONLY);
1234        if (ifd < 0)
1235                return 0;
1236
1237        if (!pack_to_stdout) {
1238                cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1239                ifd_ix = open(cached_idx, O_RDONLY);
1240                if (ifd_ix < 0) {
1241                        close(ifd);
1242                        return 0;
1243                }
1244        }
1245
1246        if (progress)
1247                fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1248                        sha1_to_hex(sha1));
1249
1250        if (pack_to_stdout) {
1251                if (copy_fd(ifd, 1))
1252                        exit(1);
1253                close(ifd);
1254        }
1255        else {
1256                char name[PATH_MAX];
1257                snprintf(name, sizeof(name),
1258                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1259                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1260                if (ofd < 0)
1261                        die("unable to open %s (%s)", name, strerror(errno));
1262                if (copy_fd(ifd, ofd))
1263                        exit(1);
1264                close(ifd);
1265
1266                snprintf(name, sizeof(name),
1267                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1268                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1269                if (ofd < 0)
1270                        die("unable to open %s (%s)", name, strerror(errno));
1271                if (copy_fd(ifd_ix, ofd))
1272                        exit(1);
1273                close(ifd_ix);
1274                puts(sha1_to_hex(sha1));
1275        }
1276
1277        return 1;
1278}
1279
1280static void setup_progress_signal(void)
1281{
1282        struct sigaction sa;
1283        struct itimerval v;
1284
1285        memset(&sa, 0, sizeof(sa));
1286        sa.sa_handler = progress_interval;
1287        sigemptyset(&sa.sa_mask);
1288        sa.sa_flags = SA_RESTART;
1289        sigaction(SIGALRM, &sa, NULL);
1290
1291        v.it_interval.tv_sec = 1;
1292        v.it_interval.tv_usec = 0;
1293        v.it_value = v.it_interval;
1294        setitimer(ITIMER_REAL, &v, NULL);
1295}
1296
1297static int git_pack_config(const char *k, const char *v)
1298{
1299        if(!strcmp(k, "pack.window")) {
1300                window = git_config_int(k, v);
1301                return 0;
1302        }
1303        return git_default_config(k, v);
1304}
1305
1306int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1307{
1308        SHA_CTX ctx;
1309        char line[40 + 1 + PATH_MAX + 2];
1310        int depth = 10;
1311        struct object_entry **list;
1312        int num_preferred_base = 0;
1313        int i;
1314
1315        git_config(git_pack_config);
1316
1317        progress = isatty(2);
1318        for (i = 1; i < argc; i++) {
1319                const char *arg = argv[i];
1320
1321                if (*arg == '-') {
1322                        if (!strcmp("--non-empty", arg)) {
1323                                non_empty = 1;
1324                                continue;
1325                        }
1326                        if (!strcmp("--local", arg)) {
1327                                local = 1;
1328                                continue;
1329                        }
1330                        if (!strcmp("--progress", arg)) {
1331                                progress = 1;
1332                                continue;
1333                        }
1334                        if (!strcmp("--incremental", arg)) {
1335                                incremental = 1;
1336                                continue;
1337                        }
1338                        if (!strncmp("--window=", arg, 9)) {
1339                                char *end;
1340                                window = strtoul(arg+9, &end, 0);
1341                                if (!arg[9] || *end)
1342                                        usage(pack_usage);
1343                                continue;
1344                        }
1345                        if (!strncmp("--depth=", arg, 8)) {
1346                                char *end;
1347                                depth = strtoul(arg+8, &end, 0);
1348                                if (!arg[8] || *end)
1349                                        usage(pack_usage);
1350                                continue;
1351                        }
1352                        if (!strcmp("--progress", arg)) {
1353                                progress = 1;
1354                                continue;
1355                        }
1356                        if (!strcmp("-q", arg)) {
1357                                progress = 0;
1358                                continue;
1359                        }
1360                        if (!strcmp("--no-reuse-delta", arg)) {
1361                                no_reuse_delta = 1;
1362                                continue;
1363                        }
1364                        if (!strcmp("--stdout", arg)) {
1365                                pack_to_stdout = 1;
1366                                continue;
1367                        }
1368                        usage(pack_usage);
1369                }
1370                if (base_name)
1371                        usage(pack_usage);
1372                base_name = arg;
1373        }
1374
1375        if (pack_to_stdout != !base_name)
1376                usage(pack_usage);
1377
1378        prepare_packed_git();
1379
1380        if (progress) {
1381                fprintf(stderr, "Generating pack...\n");
1382                setup_progress_signal();
1383        }
1384
1385        for (;;) {
1386                unsigned char sha1[20];
1387                unsigned hash;
1388
1389                if (!fgets(line, sizeof(line), stdin)) {
1390                        if (feof(stdin))
1391                                break;
1392                        if (!ferror(stdin))
1393                                die("fgets returned NULL, not EOF, not error!");
1394                        if (errno != EINTR)
1395                                die("fgets: %s", strerror(errno));
1396                        clearerr(stdin);
1397                        continue;
1398                }
1399
1400                if (line[0] == '-') {
1401                        if (get_sha1_hex(line+1, sha1))
1402                                die("expected edge sha1, got garbage:\n %s",
1403                                    line+1);
1404                        if (num_preferred_base++ < window)
1405                                add_preferred_base(sha1);
1406                        continue;
1407                }
1408                if (get_sha1_hex(line, sha1))
1409                        die("expected sha1, got garbage:\n %s", line);
1410                hash = name_hash(line+41);
1411                add_preferred_base_object(line+41, hash);
1412                add_object_entry(sha1, hash, 0);
1413        }
1414        if (progress)
1415                fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1416        sorted_by_sha = create_final_object_list();
1417        if (non_empty && !nr_result)
1418                return 0;
1419
1420        SHA1_Init(&ctx);
1421        list = sorted_by_sha;
1422        for (i = 0; i < nr_result; i++) {
1423                struct object_entry *entry = *list++;
1424                SHA1_Update(&ctx, entry->sha1, 20);
1425        }
1426        SHA1_Final(object_list_sha1, &ctx);
1427        if (progress && (nr_objects != nr_result))
1428                fprintf(stderr, "Result has %d objects.\n", nr_result);
1429
1430        if (reuse_cached_pack(object_list_sha1))
1431                ;
1432        else {
1433                if (nr_result)
1434                        prepare_pack(window, depth);
1435                if (progress && pack_to_stdout) {
1436                        /* the other end usually displays progress itself */
1437                        struct itimerval v = {{0,},};
1438                        setitimer(ITIMER_REAL, &v, NULL);
1439                        signal(SIGALRM, SIG_IGN );
1440                        progress_update = 0;
1441                }
1442                write_pack_file();
1443                if (!pack_to_stdout) {
1444                        write_index_file();
1445                        puts(sha1_to_hex(object_list_sha1));
1446                }
1447        }
1448        if (progress)
1449                fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1450                        nr_result, written, written_delta, reused, reused_delta);
1451        return 0;
1452}