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