sha1_file.con commit pull: do not clobber untracked files on initial pull (4b3ffe5)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 *
   6 * This handles basic git sha1 object files - packing, unpacking,
   7 * creation etc.
   8 */
   9#include "cache.h"
  10#include "delta.h"
  11#include "pack.h"
  12#include "blob.h"
  13#include "commit.h"
  14#include "tag.h"
  15#include "tree.h"
  16#include "tree-walk.h"
  17#include "refs.h"
  18#include "pack-revindex.h"
  19#include "sha1-lookup.h"
  20
  21#ifndef O_NOATIME
  22#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  23#define O_NOATIME 01000000
  24#else
  25#define O_NOATIME 0
  26#endif
  27#endif
  28
  29#define SZ_FMT PRIuMAX
  30static inline uintmax_t sz_fmt(size_t s) { return s; }
  31
  32const unsigned char null_sha1[20];
  33
  34static int git_open_noatime(const char *name, struct packed_git *p);
  35
  36/*
  37 * This is meant to hold a *small* number of objects that you would
  38 * want read_sha1_file() to be able to return, but yet you do not want
  39 * to write them into the object store (e.g. a browse-only
  40 * application).
  41 */
  42static struct cached_object {
  43        unsigned char sha1[20];
  44        enum object_type type;
  45        void *buf;
  46        unsigned long size;
  47} *cached_objects;
  48static int cached_object_nr, cached_object_alloc;
  49
  50static struct cached_object empty_tree = {
  51        EMPTY_TREE_SHA1_BIN_LITERAL,
  52        OBJ_TREE,
  53        "",
  54        0
  55};
  56
  57static struct cached_object *find_cached_object(const unsigned char *sha1)
  58{
  59        int i;
  60        struct cached_object *co = cached_objects;
  61
  62        for (i = 0; i < cached_object_nr; i++, co++) {
  63                if (!hashcmp(co->sha1, sha1))
  64                        return co;
  65        }
  66        if (!hashcmp(sha1, empty_tree.sha1))
  67                return &empty_tree;
  68        return NULL;
  69}
  70
  71int safe_create_leading_directories(char *path)
  72{
  73        char *pos = path + offset_1st_component(path);
  74        struct stat st;
  75
  76        while (pos) {
  77                pos = strchr(pos, '/');
  78                if (!pos)
  79                        break;
  80                while (*++pos == '/')
  81                        ;
  82                if (!*pos)
  83                        break;
  84                *--pos = '\0';
  85                if (!stat(path, &st)) {
  86                        /* path exists */
  87                        if (!S_ISDIR(st.st_mode)) {
  88                                *pos = '/';
  89                                return -3;
  90                        }
  91                }
  92                else if (mkdir(path, 0777)) {
  93                        *pos = '/';
  94                        return -1;
  95                }
  96                else if (adjust_shared_perm(path)) {
  97                        *pos = '/';
  98                        return -2;
  99                }
 100                *pos++ = '/';
 101        }
 102        return 0;
 103}
 104
 105int safe_create_leading_directories_const(const char *path)
 106{
 107        /* path points to cache entries, so xstrdup before messing with it */
 108        char *buf = xstrdup(path);
 109        int result = safe_create_leading_directories(buf);
 110        free(buf);
 111        return result;
 112}
 113
 114static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 115{
 116        int i;
 117        for (i = 0; i < 20; i++) {
 118                static char hex[] = "0123456789abcdef";
 119                unsigned int val = sha1[i];
 120                char *pos = pathbuf + i*2 + (i > 0);
 121                *pos++ = hex[val >> 4];
 122                *pos = hex[val & 0xf];
 123        }
 124}
 125
 126/*
 127 * NOTE! This returns a statically allocated buffer, so you have to be
 128 * careful about using it. Do an "xstrdup()" if you need to save the
 129 * filename.
 130 *
 131 * Also note that this returns the location for creating.  Reading
 132 * SHA1 file can happen from any alternate directory listed in the
 133 * DB_ENVIRONMENT environment variable if it is not found in
 134 * the primary object database.
 135 */
 136char *sha1_file_name(const unsigned char *sha1)
 137{
 138        static char buf[PATH_MAX];
 139        const char *objdir;
 140        int len;
 141
 142        objdir = get_object_directory();
 143        len = strlen(objdir);
 144
 145        /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
 146        if (len + 43 > PATH_MAX)
 147                die("insanely long object directory %s", objdir);
 148        memcpy(buf, objdir, len);
 149        buf[len] = '/';
 150        buf[len+3] = '/';
 151        buf[len+42] = '\0';
 152        fill_sha1_path(buf + len + 1, sha1);
 153        return buf;
 154}
 155
 156static char *sha1_get_pack_name(const unsigned char *sha1,
 157                                char **name, char **base, const char *which)
 158{
 159        static const char hex[] = "0123456789abcdef";
 160        char *buf;
 161        int i;
 162
 163        if (!*base) {
 164                const char *sha1_file_directory = get_object_directory();
 165                int len = strlen(sha1_file_directory);
 166                *base = xmalloc(len + 60);
 167                sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
 168                        sha1_file_directory, which);
 169                *name = *base + len + 11;
 170        }
 171
 172        buf = *name;
 173
 174        for (i = 0; i < 20; i++) {
 175                unsigned int val = *sha1++;
 176                *buf++ = hex[val >> 4];
 177                *buf++ = hex[val & 0xf];
 178        }
 179
 180        return *base;
 181}
 182
 183char *sha1_pack_name(const unsigned char *sha1)
 184{
 185        static char *name, *base;
 186
 187        return sha1_get_pack_name(sha1, &name, &base, "pack");
 188}
 189
 190char *sha1_pack_index_name(const unsigned char *sha1)
 191{
 192        static char *name, *base;
 193
 194        return sha1_get_pack_name(sha1, &name, &base, "idx");
 195}
 196
 197struct alternate_object_database *alt_odb_list;
 198static struct alternate_object_database **alt_odb_tail;
 199
 200static void read_info_alternates(const char * alternates, int depth);
 201
 202/*
 203 * Prepare alternate object database registry.
 204 *
 205 * The variable alt_odb_list points at the list of struct
 206 * alternate_object_database.  The elements on this list come from
 207 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 208 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 209 * whose contents is similar to that environment variable but can be
 210 * LF separated.  Its base points at a statically allocated buffer that
 211 * contains "/the/directory/corresponding/to/.git/objects/...", while
 212 * its name points just after the slash at the end of ".git/objects/"
 213 * in the example above, and has enough space to hold 40-byte hex
 214 * SHA1, an extra slash for the first level indirection, and the
 215 * terminating NUL.
 216 */
 217static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
 218{
 219        const char *objdir = get_object_directory();
 220        struct alternate_object_database *ent;
 221        struct alternate_object_database *alt;
 222        /* 43 = 40-byte + 2 '/' + terminating NUL */
 223        int pfxlen = len;
 224        int entlen = pfxlen + 43;
 225        int base_len = -1;
 226
 227        if (!is_absolute_path(entry) && relative_base) {
 228                /* Relative alt-odb */
 229                if (base_len < 0)
 230                        base_len = strlen(relative_base) + 1;
 231                entlen += base_len;
 232                pfxlen += base_len;
 233        }
 234        ent = xmalloc(sizeof(*ent) + entlen);
 235
 236        if (!is_absolute_path(entry) && relative_base) {
 237                memcpy(ent->base, relative_base, base_len - 1);
 238                ent->base[base_len - 1] = '/';
 239                memcpy(ent->base + base_len, entry, len);
 240        }
 241        else
 242                memcpy(ent->base, entry, pfxlen);
 243
 244        ent->name = ent->base + pfxlen + 1;
 245        ent->base[pfxlen + 3] = '/';
 246        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 247
 248        /* Detect cases where alternate disappeared */
 249        if (!is_directory(ent->base)) {
 250                error("object directory %s does not exist; "
 251                      "check .git/objects/info/alternates.",
 252                      ent->base);
 253                free(ent);
 254                return -1;
 255        }
 256
 257        /* Prevent the common mistake of listing the same
 258         * thing twice, or object directory itself.
 259         */
 260        for (alt = alt_odb_list; alt; alt = alt->next) {
 261                if (!memcmp(ent->base, alt->base, pfxlen)) {
 262                        free(ent);
 263                        return -1;
 264                }
 265        }
 266        if (!memcmp(ent->base, objdir, pfxlen)) {
 267                free(ent);
 268                return -1;
 269        }
 270
 271        /* add the alternate entry */
 272        *alt_odb_tail = ent;
 273        alt_odb_tail = &(ent->next);
 274        ent->next = NULL;
 275
 276        /* recursively add alternates */
 277        read_info_alternates(ent->base, depth + 1);
 278
 279        ent->base[pfxlen] = '/';
 280
 281        return 0;
 282}
 283
 284static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
 285                                 const char *relative_base, int depth)
 286{
 287        const char *cp, *last;
 288
 289        if (depth > 5) {
 290                error("%s: ignoring alternate object stores, nesting too deep.",
 291                                relative_base);
 292                return;
 293        }
 294
 295        last = alt;
 296        while (last < ep) {
 297                cp = last;
 298                if (cp < ep && *cp == '#') {
 299                        while (cp < ep && *cp != sep)
 300                                cp++;
 301                        last = cp + 1;
 302                        continue;
 303                }
 304                while (cp < ep && *cp != sep)
 305                        cp++;
 306                if (last != cp) {
 307                        if (!is_absolute_path(last) && depth) {
 308                                error("%s: ignoring relative alternate object store %s",
 309                                                relative_base, last);
 310                        } else {
 311                                link_alt_odb_entry(last, cp - last,
 312                                                relative_base, depth);
 313                        }
 314                }
 315                while (cp < ep && *cp == sep)
 316                        cp++;
 317                last = cp;
 318        }
 319}
 320
 321static void read_info_alternates(const char * relative_base, int depth)
 322{
 323        char *map;
 324        size_t mapsz;
 325        struct stat st;
 326        const char alt_file_name[] = "info/alternates";
 327        /* Given that relative_base is no longer than PATH_MAX,
 328           ensure that "path" has enough space to append "/", the
 329           file name, "info/alternates", and a trailing NUL.  */
 330        char path[PATH_MAX + 1 + sizeof alt_file_name];
 331        int fd;
 332
 333        sprintf(path, "%s/%s", relative_base, alt_file_name);
 334        fd = git_open_noatime(path, NULL);
 335        if (fd < 0)
 336                return;
 337        if (fstat(fd, &st) || (st.st_size == 0)) {
 338                close(fd);
 339                return;
 340        }
 341        mapsz = xsize_t(st.st_size);
 342        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 343        close(fd);
 344
 345        link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
 346
 347        munmap(map, mapsz);
 348}
 349
 350void add_to_alternates_file(const char *reference)
 351{
 352        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 353        int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
 354        char *alt = mkpath("%s/objects\n", reference);
 355        write_or_die(fd, alt, strlen(alt));
 356        if (commit_lock_file(lock))
 357                die("could not close alternates file");
 358        if (alt_odb_tail)
 359                link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
 360}
 361
 362void foreach_alt_odb(alt_odb_fn fn, void *cb)
 363{
 364        struct alternate_object_database *ent;
 365
 366        prepare_alt_odb();
 367        for (ent = alt_odb_list; ent; ent = ent->next)
 368                if (fn(ent, cb))
 369                        return;
 370}
 371
 372void prepare_alt_odb(void)
 373{
 374        const char *alt;
 375
 376        if (alt_odb_tail)
 377                return;
 378
 379        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 380        if (!alt) alt = "";
 381
 382        alt_odb_tail = &alt_odb_list;
 383        link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
 384
 385        read_info_alternates(get_object_directory(), 0);
 386}
 387
 388static int has_loose_object_local(const unsigned char *sha1)
 389{
 390        char *name = sha1_file_name(sha1);
 391        return !access(name, F_OK);
 392}
 393
 394int has_loose_object_nonlocal(const unsigned char *sha1)
 395{
 396        struct alternate_object_database *alt;
 397        prepare_alt_odb();
 398        for (alt = alt_odb_list; alt; alt = alt->next) {
 399                fill_sha1_path(alt->name, sha1);
 400                if (!access(alt->base, F_OK))
 401                        return 1;
 402        }
 403        return 0;
 404}
 405
 406static int has_loose_object(const unsigned char *sha1)
 407{
 408        return has_loose_object_local(sha1) ||
 409               has_loose_object_nonlocal(sha1);
 410}
 411
 412static unsigned int pack_used_ctr;
 413static unsigned int pack_mmap_calls;
 414static unsigned int peak_pack_open_windows;
 415static unsigned int pack_open_windows;
 416static unsigned int pack_open_fds;
 417static unsigned int pack_max_fds;
 418static size_t peak_pack_mapped;
 419static size_t pack_mapped;
 420struct packed_git *packed_git;
 421
 422void pack_report(void)
 423{
 424        fprintf(stderr,
 425                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
 426                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
 427                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
 428                sz_fmt(getpagesize()),
 429                sz_fmt(packed_git_window_size),
 430                sz_fmt(packed_git_limit));
 431        fprintf(stderr,
 432                "pack_report: pack_used_ctr            = %10u\n"
 433                "pack_report: pack_mmap_calls          = %10u\n"
 434                "pack_report: pack_open_windows        = %10u / %10u\n"
 435                "pack_report: pack_mapped              = "
 436                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
 437                pack_used_ctr,
 438                pack_mmap_calls,
 439                pack_open_windows, peak_pack_open_windows,
 440                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
 441}
 442
 443static int check_packed_git_idx(const char *path,  struct packed_git *p)
 444{
 445        void *idx_map;
 446        struct pack_idx_header *hdr;
 447        size_t idx_size;
 448        uint32_t version, nr, i, *index;
 449        int fd = git_open_noatime(path, p);
 450        struct stat st;
 451
 452        if (fd < 0)
 453                return -1;
 454        if (fstat(fd, &st)) {
 455                close(fd);
 456                return -1;
 457        }
 458        idx_size = xsize_t(st.st_size);
 459        if (idx_size < 4 * 256 + 20 + 20) {
 460                close(fd);
 461                return error("index file %s is too small", path);
 462        }
 463        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 464        close(fd);
 465
 466        hdr = idx_map;
 467        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
 468                version = ntohl(hdr->idx_version);
 469                if (version < 2 || version > 2) {
 470                        munmap(idx_map, idx_size);
 471                        return error("index file %s is version %"PRIu32
 472                                     " and is not supported by this binary"
 473                                     " (try upgrading GIT to a newer version)",
 474                                     path, version);
 475                }
 476        } else
 477                version = 1;
 478
 479        nr = 0;
 480        index = idx_map;
 481        if (version > 1)
 482                index += 2;  /* skip index header */
 483        for (i = 0; i < 256; i++) {
 484                uint32_t n = ntohl(index[i]);
 485                if (n < nr) {
 486                        munmap(idx_map, idx_size);
 487                        return error("non-monotonic index %s", path);
 488                }
 489                nr = n;
 490        }
 491
 492        if (version == 1) {
 493                /*
 494                 * Total size:
 495                 *  - 256 index entries 4 bytes each
 496                 *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 497                 *  - 20-byte SHA1 of the packfile
 498                 *  - 20-byte SHA1 file checksum
 499                 */
 500                if (idx_size != 4*256 + nr * 24 + 20 + 20) {
 501                        munmap(idx_map, idx_size);
 502                        return error("wrong index v1 file size in %s", path);
 503                }
 504        } else if (version == 2) {
 505                /*
 506                 * Minimum size:
 507                 *  - 8 bytes of header
 508                 *  - 256 index entries 4 bytes each
 509                 *  - 20-byte sha1 entry * nr
 510                 *  - 4-byte crc entry * nr
 511                 *  - 4-byte offset entry * nr
 512                 *  - 20-byte SHA1 of the packfile
 513                 *  - 20-byte SHA1 file checksum
 514                 * And after the 4-byte offset table might be a
 515                 * variable sized table containing 8-byte entries
 516                 * for offsets larger than 2^31.
 517                 */
 518                unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
 519                unsigned long max_size = min_size;
 520                if (nr)
 521                        max_size += (nr - 1)*8;
 522                if (idx_size < min_size || idx_size > max_size) {
 523                        munmap(idx_map, idx_size);
 524                        return error("wrong index v2 file size in %s", path);
 525                }
 526                if (idx_size != min_size &&
 527                    /*
 528                     * make sure we can deal with large pack offsets.
 529                     * 31-bit signed offset won't be enough, neither
 530                     * 32-bit unsigned one will be.
 531                     */
 532                    (sizeof(off_t) <= 4)) {
 533                        munmap(idx_map, idx_size);
 534                        return error("pack too large for current definition of off_t in %s", path);
 535                }
 536        }
 537
 538        p->index_version = version;
 539        p->index_data = idx_map;
 540        p->index_size = idx_size;
 541        p->num_objects = nr;
 542        return 0;
 543}
 544
 545int open_pack_index(struct packed_git *p)
 546{
 547        char *idx_name;
 548        int ret;
 549
 550        if (p->index_data)
 551                return 0;
 552
 553        idx_name = xstrdup(p->pack_name);
 554        strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
 555        ret = check_packed_git_idx(idx_name, p);
 556        free(idx_name);
 557        return ret;
 558}
 559
 560static void scan_windows(struct packed_git *p,
 561        struct packed_git **lru_p,
 562        struct pack_window **lru_w,
 563        struct pack_window **lru_l)
 564{
 565        struct pack_window *w, *w_l;
 566
 567        for (w_l = NULL, w = p->windows; w; w = w->next) {
 568                if (!w->inuse_cnt) {
 569                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 570                                *lru_p = p;
 571                                *lru_w = w;
 572                                *lru_l = w_l;
 573                        }
 574                }
 575                w_l = w;
 576        }
 577}
 578
 579static int unuse_one_window(struct packed_git *current, int keep_fd)
 580{
 581        struct packed_git *p, *lru_p = NULL;
 582        struct pack_window *lru_w = NULL, *lru_l = NULL;
 583
 584        if (current)
 585                scan_windows(current, &lru_p, &lru_w, &lru_l);
 586        for (p = packed_git; p; p = p->next)
 587                scan_windows(p, &lru_p, &lru_w, &lru_l);
 588        if (lru_p) {
 589                munmap(lru_w->base, lru_w->len);
 590                pack_mapped -= lru_w->len;
 591                if (lru_l)
 592                        lru_l->next = lru_w->next;
 593                else {
 594                        lru_p->windows = lru_w->next;
 595                        if (!lru_p->windows && lru_p->pack_fd != -1
 596                                && lru_p->pack_fd != keep_fd) {
 597                                close(lru_p->pack_fd);
 598                                pack_open_fds--;
 599                                lru_p->pack_fd = -1;
 600                        }
 601                }
 602                free(lru_w);
 603                pack_open_windows--;
 604                return 1;
 605        }
 606        return 0;
 607}
 608
 609void release_pack_memory(size_t need, int fd)
 610{
 611        size_t cur = pack_mapped;
 612        while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
 613                ; /* nothing */
 614}
 615
 616void *xmmap(void *start, size_t length,
 617        int prot, int flags, int fd, off_t offset)
 618{
 619        void *ret = mmap(start, length, prot, flags, fd, offset);
 620        if (ret == MAP_FAILED) {
 621                if (!length)
 622                        return NULL;
 623                release_pack_memory(length, fd);
 624                ret = mmap(start, length, prot, flags, fd, offset);
 625                if (ret == MAP_FAILED)
 626                        die_errno("Out of memory? mmap failed");
 627        }
 628        return ret;
 629}
 630
 631void close_pack_windows(struct packed_git *p)
 632{
 633        while (p->windows) {
 634                struct pack_window *w = p->windows;
 635
 636                if (w->inuse_cnt)
 637                        die("pack '%s' still has open windows to it",
 638                            p->pack_name);
 639                munmap(w->base, w->len);
 640                pack_mapped -= w->len;
 641                pack_open_windows--;
 642                p->windows = w->next;
 643                free(w);
 644        }
 645}
 646
 647void unuse_pack(struct pack_window **w_cursor)
 648{
 649        struct pack_window *w = *w_cursor;
 650        if (w) {
 651                w->inuse_cnt--;
 652                *w_cursor = NULL;
 653        }
 654}
 655
 656void close_pack_index(struct packed_git *p)
 657{
 658        if (p->index_data) {
 659                munmap((void *)p->index_data, p->index_size);
 660                p->index_data = NULL;
 661        }
 662}
 663
 664/*
 665 * This is used by git-repack in case a newly created pack happens to
 666 * contain the same set of objects as an existing one.  In that case
 667 * the resulting file might be different even if its name would be the
 668 * same.  It is best to close any reference to the old pack before it is
 669 * replaced on disk.  Of course no index pointers nor windows for given pack
 670 * must subsist at this point.  If ever objects from this pack are requested
 671 * again, the new version of the pack will be reinitialized through
 672 * reprepare_packed_git().
 673 */
 674void free_pack_by_name(const char *pack_name)
 675{
 676        struct packed_git *p, **pp = &packed_git;
 677
 678        while (*pp) {
 679                p = *pp;
 680                if (strcmp(pack_name, p->pack_name) == 0) {
 681                        clear_delta_base_cache();
 682                        close_pack_windows(p);
 683                        if (p->pack_fd != -1) {
 684                                close(p->pack_fd);
 685                                pack_open_fds--;
 686                        }
 687                        close_pack_index(p);
 688                        free(p->bad_object_sha1);
 689                        *pp = p->next;
 690                        free(p);
 691                        return;
 692                }
 693                pp = &p->next;
 694        }
 695}
 696
 697/*
 698 * Do not call this directly as this leaks p->pack_fd on error return;
 699 * call open_packed_git() instead.
 700 */
 701static int open_packed_git_1(struct packed_git *p)
 702{
 703        struct stat st;
 704        struct pack_header hdr;
 705        unsigned char sha1[20];
 706        unsigned char *idx_sha1;
 707        long fd_flag;
 708
 709        if (!p->index_data && open_pack_index(p))
 710                return error("packfile %s index unavailable", p->pack_name);
 711
 712        if (!pack_max_fds) {
 713                struct rlimit lim;
 714                unsigned int max_fds;
 715
 716                if (getrlimit(RLIMIT_NOFILE, &lim))
 717                        die_errno("cannot get RLIMIT_NOFILE");
 718
 719                max_fds = lim.rlim_cur;
 720
 721                /* Save 3 for stdin/stdout/stderr, 22 for work */
 722                if (25 < max_fds)
 723                        pack_max_fds = max_fds - 25;
 724                else
 725                        pack_max_fds = 1;
 726        }
 727
 728        while (pack_max_fds <= pack_open_fds && unuse_one_window(NULL, -1))
 729                ; /* nothing */
 730
 731        p->pack_fd = git_open_noatime(p->pack_name, p);
 732        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 733                return -1;
 734        pack_open_fds++;
 735
 736        /* If we created the struct before we had the pack we lack size. */
 737        if (!p->pack_size) {
 738                if (!S_ISREG(st.st_mode))
 739                        return error("packfile %s not a regular file", p->pack_name);
 740                p->pack_size = st.st_size;
 741        } else if (p->pack_size != st.st_size)
 742                return error("packfile %s size changed", p->pack_name);
 743
 744        /* We leave these file descriptors open with sliding mmap;
 745         * there is no point keeping them open across exec(), though.
 746         */
 747        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 748        if (fd_flag < 0)
 749                return error("cannot determine file descriptor flags");
 750        fd_flag |= FD_CLOEXEC;
 751        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 752                return error("cannot set FD_CLOEXEC");
 753
 754        /* Verify we recognize this pack file format. */
 755        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 756                return error("file %s is far too short to be a packfile", p->pack_name);
 757        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 758                return error("file %s is not a GIT packfile", p->pack_name);
 759        if (!pack_version_ok(hdr.hdr_version))
 760                return error("packfile %s is version %"PRIu32" and not"
 761                        " supported (try upgrading GIT to a newer version)",
 762                        p->pack_name, ntohl(hdr.hdr_version));
 763
 764        /* Verify the pack matches its index. */
 765        if (p->num_objects != ntohl(hdr.hdr_entries))
 766                return error("packfile %s claims to have %"PRIu32" objects"
 767                             " while index indicates %"PRIu32" objects",
 768                             p->pack_name, ntohl(hdr.hdr_entries),
 769                             p->num_objects);
 770        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
 771                return error("end of packfile %s is unavailable", p->pack_name);
 772        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
 773                return error("packfile %s signature is unavailable", p->pack_name);
 774        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
 775        if (hashcmp(sha1, idx_sha1))
 776                return error("packfile %s does not match index", p->pack_name);
 777        return 0;
 778}
 779
 780static int open_packed_git(struct packed_git *p)
 781{
 782        if (!open_packed_git_1(p))
 783                return 0;
 784        if (p->pack_fd != -1) {
 785                close(p->pack_fd);
 786                pack_open_fds--;
 787                p->pack_fd = -1;
 788        }
 789        return -1;
 790}
 791
 792static int in_window(struct pack_window *win, off_t offset)
 793{
 794        /* We must promise at least 20 bytes (one hash) after the
 795         * offset is available from this window, otherwise the offset
 796         * is not actually in this window and a different window (which
 797         * has that one hash excess) must be used.  This is to support
 798         * the object header and delta base parsing routines below.
 799         */
 800        off_t win_off = win->offset;
 801        return win_off <= offset
 802                && (offset + 20) <= (win_off + win->len);
 803}
 804
 805unsigned char *use_pack(struct packed_git *p,
 806                struct pack_window **w_cursor,
 807                off_t offset,
 808                unsigned int *left)
 809{
 810        struct pack_window *win = *w_cursor;
 811
 812        /* Since packfiles end in a hash of their content and it's
 813         * pointless to ask for an offset into the middle of that
 814         * hash, and the in_window function above wouldn't match
 815         * don't allow an offset too close to the end of the file.
 816         */
 817        if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
 818                die("packfile %s cannot be accessed", p->pack_name);
 819        if (offset > (p->pack_size - 20))
 820                die("offset beyond end of packfile (truncated pack?)");
 821
 822        if (!win || !in_window(win, offset)) {
 823                if (win)
 824                        win->inuse_cnt--;
 825                for (win = p->windows; win; win = win->next) {
 826                        if (in_window(win, offset))
 827                                break;
 828                }
 829                if (!win) {
 830                        size_t window_align = packed_git_window_size / 2;
 831                        off_t len;
 832
 833                        if (p->pack_fd == -1 && open_packed_git(p))
 834                                die("packfile %s cannot be accessed", p->pack_name);
 835
 836                        win = xcalloc(1, sizeof(*win));
 837                        win->offset = (offset / window_align) * window_align;
 838                        len = p->pack_size - win->offset;
 839                        if (len > packed_git_window_size)
 840                                len = packed_git_window_size;
 841                        win->len = (size_t)len;
 842                        pack_mapped += win->len;
 843                        while (packed_git_limit < pack_mapped
 844                                && unuse_one_window(p, p->pack_fd))
 845                                ; /* nothing */
 846                        win->base = xmmap(NULL, win->len,
 847                                PROT_READ, MAP_PRIVATE,
 848                                p->pack_fd, win->offset);
 849                        if (win->base == MAP_FAILED)
 850                                die("packfile %s cannot be mapped: %s",
 851                                        p->pack_name,
 852                                        strerror(errno));
 853                        if (!win->offset && win->len == p->pack_size
 854                                && !p->do_not_close) {
 855                                close(p->pack_fd);
 856                                pack_open_fds--;
 857                                p->pack_fd = -1;
 858                        }
 859                        pack_mmap_calls++;
 860                        pack_open_windows++;
 861                        if (pack_mapped > peak_pack_mapped)
 862                                peak_pack_mapped = pack_mapped;
 863                        if (pack_open_windows > peak_pack_open_windows)
 864                                peak_pack_open_windows = pack_open_windows;
 865                        win->next = p->windows;
 866                        p->windows = win;
 867                }
 868        }
 869        if (win != *w_cursor) {
 870                win->last_used = pack_used_ctr++;
 871                win->inuse_cnt++;
 872                *w_cursor = win;
 873        }
 874        offset -= win->offset;
 875        if (left)
 876                *left = win->len - xsize_t(offset);
 877        return win->base + offset;
 878}
 879
 880static struct packed_git *alloc_packed_git(int extra)
 881{
 882        struct packed_git *p = xmalloc(sizeof(*p) + extra);
 883        memset(p, 0, sizeof(*p));
 884        p->pack_fd = -1;
 885        return p;
 886}
 887
 888static void try_to_free_pack_memory(size_t size)
 889{
 890        release_pack_memory(size, -1);
 891}
 892
 893struct packed_git *add_packed_git(const char *path, int path_len, int local)
 894{
 895        static int have_set_try_to_free_routine;
 896        struct stat st;
 897        struct packed_git *p = alloc_packed_git(path_len + 2);
 898
 899        if (!have_set_try_to_free_routine) {
 900                have_set_try_to_free_routine = 1;
 901                set_try_to_free_routine(try_to_free_pack_memory);
 902        }
 903
 904        /*
 905         * Make sure a corresponding .pack file exists and that
 906         * the index looks sane.
 907         */
 908        path_len -= strlen(".idx");
 909        if (path_len < 1) {
 910                free(p);
 911                return NULL;
 912        }
 913        memcpy(p->pack_name, path, path_len);
 914
 915        strcpy(p->pack_name + path_len, ".keep");
 916        if (!access(p->pack_name, F_OK))
 917                p->pack_keep = 1;
 918
 919        strcpy(p->pack_name + path_len, ".pack");
 920        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 921                free(p);
 922                return NULL;
 923        }
 924
 925        /* ok, it looks sane as far as we can check without
 926         * actually mapping the pack file.
 927         */
 928        p->pack_size = st.st_size;
 929        p->pack_local = local;
 930        p->mtime = st.st_mtime;
 931        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
 932                hashclr(p->sha1);
 933        return p;
 934}
 935
 936struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
 937{
 938        const char *path = sha1_pack_name(sha1);
 939        struct packed_git *p = alloc_packed_git(strlen(path) + 1);
 940
 941        strcpy(p->pack_name, path);
 942        hashcpy(p->sha1, sha1);
 943        if (check_packed_git_idx(idx_path, p)) {
 944                free(p);
 945                return NULL;
 946        }
 947
 948        return p;
 949}
 950
 951void install_packed_git(struct packed_git *pack)
 952{
 953        if (pack->pack_fd != -1)
 954                pack_open_fds++;
 955
 956        pack->next = packed_git;
 957        packed_git = pack;
 958}
 959
 960static void prepare_packed_git_one(char *objdir, int local)
 961{
 962        /* Ensure that this buffer is large enough so that we can
 963           append "/pack/" without clobbering the stack even if
 964           strlen(objdir) were PATH_MAX.  */
 965        char path[PATH_MAX + 1 + 4 + 1 + 1];
 966        int len;
 967        DIR *dir;
 968        struct dirent *de;
 969
 970        sprintf(path, "%s/pack", objdir);
 971        len = strlen(path);
 972        dir = opendir(path);
 973        if (!dir) {
 974                if (errno != ENOENT)
 975                        error("unable to open object pack directory: %s: %s",
 976                              path, strerror(errno));
 977                return;
 978        }
 979        path[len++] = '/';
 980        while ((de = readdir(dir)) != NULL) {
 981                int namelen = strlen(de->d_name);
 982                struct packed_git *p;
 983
 984                if (!has_extension(de->d_name, ".idx"))
 985                        continue;
 986
 987                if (len + namelen + 1 > sizeof(path))
 988                        continue;
 989
 990                /* Don't reopen a pack we already have. */
 991                strcpy(path + len, de->d_name);
 992                for (p = packed_git; p; p = p->next) {
 993                        if (!memcmp(path, p->pack_name, len + namelen - 4))
 994                                break;
 995                }
 996                if (p)
 997                        continue;
 998                /* See if it really is a valid .idx file with corresponding
 999                 * .pack file that we can map.
1000                 */
1001                p = add_packed_git(path, len + namelen, local);
1002                if (!p)
1003                        continue;
1004                install_packed_git(p);
1005        }
1006        closedir(dir);
1007}
1008
1009static int sort_pack(const void *a_, const void *b_)
1010{
1011        struct packed_git *a = *((struct packed_git **)a_);
1012        struct packed_git *b = *((struct packed_git **)b_);
1013        int st;
1014
1015        /*
1016         * Local packs tend to contain objects specific to our
1017         * variant of the project than remote ones.  In addition,
1018         * remote ones could be on a network mounted filesystem.
1019         * Favor local ones for these reasons.
1020         */
1021        st = a->pack_local - b->pack_local;
1022        if (st)
1023                return -st;
1024
1025        /*
1026         * Younger packs tend to contain more recent objects,
1027         * and more recent objects tend to get accessed more
1028         * often.
1029         */
1030        if (a->mtime < b->mtime)
1031                return 1;
1032        else if (a->mtime == b->mtime)
1033                return 0;
1034        return -1;
1035}
1036
1037static void rearrange_packed_git(void)
1038{
1039        struct packed_git **ary, *p;
1040        int i, n;
1041
1042        for (n = 0, p = packed_git; p; p = p->next)
1043                n++;
1044        if (n < 2)
1045                return;
1046
1047        /* prepare an array of packed_git for easier sorting */
1048        ary = xcalloc(n, sizeof(struct packed_git *));
1049        for (n = 0, p = packed_git; p; p = p->next)
1050                ary[n++] = p;
1051
1052        qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1053
1054        /* link them back again */
1055        for (i = 0; i < n - 1; i++)
1056                ary[i]->next = ary[i + 1];
1057        ary[n - 1]->next = NULL;
1058        packed_git = ary[0];
1059
1060        free(ary);
1061}
1062
1063static int prepare_packed_git_run_once = 0;
1064void prepare_packed_git(void)
1065{
1066        struct alternate_object_database *alt;
1067
1068        if (prepare_packed_git_run_once)
1069                return;
1070        prepare_packed_git_one(get_object_directory(), 1);
1071        prepare_alt_odb();
1072        for (alt = alt_odb_list; alt; alt = alt->next) {
1073                alt->name[-1] = 0;
1074                prepare_packed_git_one(alt->base, 0);
1075                alt->name[-1] = '/';
1076        }
1077        rearrange_packed_git();
1078        prepare_packed_git_run_once = 1;
1079}
1080
1081void reprepare_packed_git(void)
1082{
1083        discard_revindex();
1084        prepare_packed_git_run_once = 0;
1085        prepare_packed_git();
1086}
1087
1088static void mark_bad_packed_object(struct packed_git *p,
1089                                   const unsigned char *sha1)
1090{
1091        unsigned i;
1092        for (i = 0; i < p->num_bad_objects; i++)
1093                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1094                        return;
1095        p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1096        hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1097        p->num_bad_objects++;
1098}
1099
1100static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1101{
1102        struct packed_git *p;
1103        unsigned i;
1104
1105        for (p = packed_git; p; p = p->next)
1106                for (i = 0; i < p->num_bad_objects; i++)
1107                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1108                                return p;
1109        return NULL;
1110}
1111
1112int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1113{
1114        unsigned char real_sha1[20];
1115        hash_sha1_file(map, size, type, real_sha1);
1116        return hashcmp(sha1, real_sha1) ? -1 : 0;
1117}
1118
1119static int git_open_noatime(const char *name, struct packed_git *p)
1120{
1121        static int sha1_file_open_flag = O_NOATIME;
1122
1123        for (;;) {
1124                int fd = open(name, O_RDONLY | sha1_file_open_flag);
1125                if (fd >= 0)
1126                        return fd;
1127
1128                /* Might the failure be due to O_NOATIME? */
1129                if (errno != ENOENT && sha1_file_open_flag) {
1130                        sha1_file_open_flag = 0;
1131                        continue;
1132                }
1133
1134                return -1;
1135        }
1136}
1137
1138static int open_sha1_file(const unsigned char *sha1)
1139{
1140        int fd;
1141        char *name = sha1_file_name(sha1);
1142        struct alternate_object_database *alt;
1143
1144        fd = git_open_noatime(name, NULL);
1145        if (fd >= 0)
1146                return fd;
1147
1148        prepare_alt_odb();
1149        errno = ENOENT;
1150        for (alt = alt_odb_list; alt; alt = alt->next) {
1151                name = alt->name;
1152                fill_sha1_path(name, sha1);
1153                fd = git_open_noatime(alt->base, NULL);
1154                if (fd >= 0)
1155                        return fd;
1156        }
1157        return -1;
1158}
1159
1160static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1161{
1162        void *map;
1163        int fd;
1164
1165        fd = open_sha1_file(sha1);
1166        map = NULL;
1167        if (fd >= 0) {
1168                struct stat st;
1169
1170                if (!fstat(fd, &st)) {
1171                        *size = xsize_t(st.st_size);
1172                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1173                }
1174                close(fd);
1175        }
1176        return map;
1177}
1178
1179static int legacy_loose_object(unsigned char *map)
1180{
1181        unsigned int word;
1182
1183        /*
1184         * Is it a zlib-compressed buffer? If so, the first byte
1185         * must be 0x78 (15-bit window size, deflated), and the
1186         * first 16-bit word is evenly divisible by 31
1187         */
1188        word = (map[0] << 8) + map[1];
1189        if (map[0] == 0x78 && !(word % 31))
1190                return 1;
1191        else
1192                return 0;
1193}
1194
1195unsigned long unpack_object_header_buffer(const unsigned char *buf,
1196                unsigned long len, enum object_type *type, unsigned long *sizep)
1197{
1198        unsigned shift;
1199        unsigned long size, c;
1200        unsigned long used = 0;
1201
1202        c = buf[used++];
1203        *type = (c >> 4) & 7;
1204        size = c & 15;
1205        shift = 4;
1206        while (c & 0x80) {
1207                if (len <= used || bitsizeof(long) <= shift) {
1208                        error("bad object header");
1209                        return 0;
1210                }
1211                c = buf[used++];
1212                size += (c & 0x7f) << shift;
1213                shift += 7;
1214        }
1215        *sizep = size;
1216        return used;
1217}
1218
1219static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1220{
1221        unsigned long size, used;
1222        static const char valid_loose_object_type[8] = {
1223                0, /* OBJ_EXT */
1224                1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1225                0, /* "delta" and others are invalid in a loose object */
1226        };
1227        enum object_type type;
1228
1229        /* Get the data stream */
1230        memset(stream, 0, sizeof(*stream));
1231        stream->next_in = map;
1232        stream->avail_in = mapsize;
1233        stream->next_out = buffer;
1234        stream->avail_out = bufsiz;
1235
1236        if (legacy_loose_object(map)) {
1237                git_inflate_init(stream);
1238                return git_inflate(stream, 0);
1239        }
1240
1241
1242        /*
1243         * There used to be a second loose object header format which
1244         * was meant to mimic the in-pack format, allowing for direct
1245         * copy of the object data.  This format turned up not to be
1246         * really worth it and we don't write it any longer.  But we
1247         * can still read it.
1248         */
1249        used = unpack_object_header_buffer(map, mapsize, &type, &size);
1250        if (!used || !valid_loose_object_type[type])
1251                return -1;
1252        map += used;
1253        mapsize -= used;
1254
1255        /* Set up the stream for the rest.. */
1256        stream->next_in = map;
1257        stream->avail_in = mapsize;
1258        git_inflate_init(stream);
1259
1260        /* And generate the fake traditional header */
1261        stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1262                                         typename(type), size);
1263        return 0;
1264}
1265
1266static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1267{
1268        int bytes = strlen(buffer) + 1;
1269        unsigned char *buf = xmallocz(size);
1270        unsigned long n;
1271        int status = Z_OK;
1272
1273        n = stream->total_out - bytes;
1274        if (n > size)
1275                n = size;
1276        memcpy(buf, (char *) buffer + bytes, n);
1277        bytes = n;
1278        if (bytes <= size) {
1279                /*
1280                 * The above condition must be (bytes <= size), not
1281                 * (bytes < size).  In other words, even though we
1282                 * expect no more output and set avail_out to zer0,
1283                 * the input zlib stream may have bytes that express
1284                 * "this concludes the stream", and we *do* want to
1285                 * eat that input.
1286                 *
1287                 * Otherwise we would not be able to test that we
1288                 * consumed all the input to reach the expected size;
1289                 * we also want to check that zlib tells us that all
1290                 * went well with status == Z_STREAM_END at the end.
1291                 */
1292                stream->next_out = buf + bytes;
1293                stream->avail_out = size - bytes;
1294                while (status == Z_OK)
1295                        status = git_inflate(stream, Z_FINISH);
1296        }
1297        if (status == Z_STREAM_END && !stream->avail_in) {
1298                git_inflate_end(stream);
1299                return buf;
1300        }
1301
1302        if (status < 0)
1303                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1304        else if (stream->avail_in)
1305                error("garbage at end of loose object '%s'",
1306                      sha1_to_hex(sha1));
1307        free(buf);
1308        return NULL;
1309}
1310
1311/*
1312 * We used to just use "sscanf()", but that's actually way
1313 * too permissive for what we want to check. So do an anal
1314 * object header parse by hand.
1315 */
1316static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1317{
1318        char type[10];
1319        int i;
1320        unsigned long size;
1321
1322        /*
1323         * The type can be at most ten bytes (including the
1324         * terminating '\0' that we add), and is followed by
1325         * a space.
1326         */
1327        i = 0;
1328        for (;;) {
1329                char c = *hdr++;
1330                if (c == ' ')
1331                        break;
1332                type[i++] = c;
1333                if (i >= sizeof(type))
1334                        return -1;
1335        }
1336        type[i] = 0;
1337
1338        /*
1339         * The length must follow immediately, and be in canonical
1340         * decimal format (ie "010" is not valid).
1341         */
1342        size = *hdr++ - '0';
1343        if (size > 9)
1344                return -1;
1345        if (size) {
1346                for (;;) {
1347                        unsigned long c = *hdr - '0';
1348                        if (c > 9)
1349                                break;
1350                        hdr++;
1351                        size = size * 10 + c;
1352                }
1353        }
1354        *sizep = size;
1355
1356        /*
1357         * The length must be followed by a zero byte
1358         */
1359        return *hdr ? -1 : type_from_string(type);
1360}
1361
1362static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1363{
1364        int ret;
1365        z_stream stream;
1366        char hdr[8192];
1367
1368        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1369        if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1370                return NULL;
1371
1372        return unpack_sha1_rest(&stream, hdr, *size, sha1);
1373}
1374
1375unsigned long get_size_from_delta(struct packed_git *p,
1376                                  struct pack_window **w_curs,
1377                                  off_t curpos)
1378{
1379        const unsigned char *data;
1380        unsigned char delta_head[20], *in;
1381        z_stream stream;
1382        int st;
1383
1384        memset(&stream, 0, sizeof(stream));
1385        stream.next_out = delta_head;
1386        stream.avail_out = sizeof(delta_head);
1387
1388        git_inflate_init(&stream);
1389        do {
1390                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1391                stream.next_in = in;
1392                st = git_inflate(&stream, Z_FINISH);
1393                curpos += stream.next_in - in;
1394        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1395                 stream.total_out < sizeof(delta_head));
1396        git_inflate_end(&stream);
1397        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1398                error("delta data unpack-initial failed");
1399                return 0;
1400        }
1401
1402        /* Examine the initial part of the delta to figure out
1403         * the result size.
1404         */
1405        data = delta_head;
1406
1407        /* ignore base size */
1408        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1409
1410        /* Read the result size */
1411        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1412}
1413
1414static off_t get_delta_base(struct packed_git *p,
1415                                    struct pack_window **w_curs,
1416                                    off_t *curpos,
1417                                    enum object_type type,
1418                                    off_t delta_obj_offset)
1419{
1420        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1421        off_t base_offset;
1422
1423        /* use_pack() assured us we have [base_info, base_info + 20)
1424         * as a range that we can look at without walking off the
1425         * end of the mapped window.  Its actually the hash size
1426         * that is assured.  An OFS_DELTA longer than the hash size
1427         * is stupid, as then a REF_DELTA would be smaller to store.
1428         */
1429        if (type == OBJ_OFS_DELTA) {
1430                unsigned used = 0;
1431                unsigned char c = base_info[used++];
1432                base_offset = c & 127;
1433                while (c & 128) {
1434                        base_offset += 1;
1435                        if (!base_offset || MSB(base_offset, 7))
1436                                return 0;  /* overflow */
1437                        c = base_info[used++];
1438                        base_offset = (base_offset << 7) + (c & 127);
1439                }
1440                base_offset = delta_obj_offset - base_offset;
1441                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1442                        return 0;  /* out of bound */
1443                *curpos += used;
1444        } else if (type == OBJ_REF_DELTA) {
1445                /* The base entry _must_ be in the same pack */
1446                base_offset = find_pack_entry_one(base_info, p);
1447                *curpos += 20;
1448        } else
1449                die("I am totally screwed");
1450        return base_offset;
1451}
1452
1453/* forward declaration for a mutually recursive function */
1454static int packed_object_info(struct packed_git *p, off_t offset,
1455                              unsigned long *sizep);
1456
1457static int packed_delta_info(struct packed_git *p,
1458                             struct pack_window **w_curs,
1459                             off_t curpos,
1460                             enum object_type type,
1461                             off_t obj_offset,
1462                             unsigned long *sizep)
1463{
1464        off_t base_offset;
1465
1466        base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1467        if (!base_offset)
1468                return OBJ_BAD;
1469        type = packed_object_info(p, base_offset, NULL);
1470        if (type <= OBJ_NONE) {
1471                struct revindex_entry *revidx;
1472                const unsigned char *base_sha1;
1473                revidx = find_pack_revindex(p, base_offset);
1474                if (!revidx)
1475                        return OBJ_BAD;
1476                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1477                mark_bad_packed_object(p, base_sha1);
1478                type = sha1_object_info(base_sha1, NULL);
1479                if (type <= OBJ_NONE)
1480                        return OBJ_BAD;
1481        }
1482
1483        /* We choose to only get the type of the base object and
1484         * ignore potentially corrupt pack file that expects the delta
1485         * based on a base with a wrong size.  This saves tons of
1486         * inflate() calls.
1487         */
1488        if (sizep) {
1489                *sizep = get_size_from_delta(p, w_curs, curpos);
1490                if (*sizep == 0)
1491                        type = OBJ_BAD;
1492        }
1493
1494        return type;
1495}
1496
1497static int unpack_object_header(struct packed_git *p,
1498                                struct pack_window **w_curs,
1499                                off_t *curpos,
1500                                unsigned long *sizep)
1501{
1502        unsigned char *base;
1503        unsigned int left;
1504        unsigned long used;
1505        enum object_type type;
1506
1507        /* use_pack() assures us we have [base, base + 20) available
1508         * as a range that we can look at at.  (Its actually the hash
1509         * size that is assured.)  With our object header encoding
1510         * the maximum deflated object size is 2^137, which is just
1511         * insane, so we know won't exceed what we have been given.
1512         */
1513        base = use_pack(p, w_curs, *curpos, &left);
1514        used = unpack_object_header_buffer(base, left, &type, sizep);
1515        if (!used) {
1516                type = OBJ_BAD;
1517        } else
1518                *curpos += used;
1519
1520        return type;
1521}
1522
1523const char *packed_object_info_detail(struct packed_git *p,
1524                                      off_t obj_offset,
1525                                      unsigned long *size,
1526                                      unsigned long *store_size,
1527                                      unsigned int *delta_chain_length,
1528                                      unsigned char *base_sha1)
1529{
1530        struct pack_window *w_curs = NULL;
1531        off_t curpos;
1532        unsigned long dummy;
1533        unsigned char *next_sha1;
1534        enum object_type type;
1535        struct revindex_entry *revidx;
1536
1537        *delta_chain_length = 0;
1538        curpos = obj_offset;
1539        type = unpack_object_header(p, &w_curs, &curpos, size);
1540
1541        revidx = find_pack_revindex(p, obj_offset);
1542        *store_size = revidx[1].offset - obj_offset;
1543
1544        for (;;) {
1545                switch (type) {
1546                default:
1547                        die("pack %s contains unknown object type %d",
1548                            p->pack_name, type);
1549                case OBJ_COMMIT:
1550                case OBJ_TREE:
1551                case OBJ_BLOB:
1552                case OBJ_TAG:
1553                        unuse_pack(&w_curs);
1554                        return typename(type);
1555                case OBJ_OFS_DELTA:
1556                        obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1557                        if (!obj_offset)
1558                                die("pack %s contains bad delta base reference of type %s",
1559                                    p->pack_name, typename(type));
1560                        if (*delta_chain_length == 0) {
1561                                revidx = find_pack_revindex(p, obj_offset);
1562                                hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1563                        }
1564                        break;
1565                case OBJ_REF_DELTA:
1566                        next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1567                        if (*delta_chain_length == 0)
1568                                hashcpy(base_sha1, next_sha1);
1569                        obj_offset = find_pack_entry_one(next_sha1, p);
1570                        break;
1571                }
1572                (*delta_chain_length)++;
1573                curpos = obj_offset;
1574                type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1575        }
1576}
1577
1578static int packed_object_info(struct packed_git *p, off_t obj_offset,
1579                              unsigned long *sizep)
1580{
1581        struct pack_window *w_curs = NULL;
1582        unsigned long size;
1583        off_t curpos = obj_offset;
1584        enum object_type type;
1585
1586        type = unpack_object_header(p, &w_curs, &curpos, &size);
1587
1588        switch (type) {
1589        case OBJ_OFS_DELTA:
1590        case OBJ_REF_DELTA:
1591                type = packed_delta_info(p, &w_curs, curpos,
1592                                         type, obj_offset, sizep);
1593                break;
1594        case OBJ_COMMIT:
1595        case OBJ_TREE:
1596        case OBJ_BLOB:
1597        case OBJ_TAG:
1598                if (sizep)
1599                        *sizep = size;
1600                break;
1601        default:
1602                error("unknown object type %i at offset %"PRIuMAX" in %s",
1603                      type, (uintmax_t)obj_offset, p->pack_name);
1604                type = OBJ_BAD;
1605        }
1606        unuse_pack(&w_curs);
1607        return type;
1608}
1609
1610static void *unpack_compressed_entry(struct packed_git *p,
1611                                    struct pack_window **w_curs,
1612                                    off_t curpos,
1613                                    unsigned long size)
1614{
1615        int st;
1616        z_stream stream;
1617        unsigned char *buffer, *in;
1618
1619        buffer = xmallocz(size);
1620        memset(&stream, 0, sizeof(stream));
1621        stream.next_out = buffer;
1622        stream.avail_out = size + 1;
1623
1624        git_inflate_init(&stream);
1625        do {
1626                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1627                stream.next_in = in;
1628                st = git_inflate(&stream, Z_FINISH);
1629                if (!stream.avail_out)
1630                        break; /* the payload is larger than it should be */
1631                curpos += stream.next_in - in;
1632        } while (st == Z_OK || st == Z_BUF_ERROR);
1633        git_inflate_end(&stream);
1634        if ((st != Z_STREAM_END) || stream.total_out != size) {
1635                free(buffer);
1636                return NULL;
1637        }
1638
1639        return buffer;
1640}
1641
1642#define MAX_DELTA_CACHE (256)
1643
1644static size_t delta_base_cached;
1645
1646static struct delta_base_cache_lru_list {
1647        struct delta_base_cache_lru_list *prev;
1648        struct delta_base_cache_lru_list *next;
1649} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1650
1651static struct delta_base_cache_entry {
1652        struct delta_base_cache_lru_list lru;
1653        void *data;
1654        struct packed_git *p;
1655        off_t base_offset;
1656        unsigned long size;
1657        enum object_type type;
1658} delta_base_cache[MAX_DELTA_CACHE];
1659
1660static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1661{
1662        unsigned long hash;
1663
1664        hash = (unsigned long)p + (unsigned long)base_offset;
1665        hash += (hash >> 8) + (hash >> 16);
1666        return hash % MAX_DELTA_CACHE;
1667}
1668
1669static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1670        unsigned long *base_size, enum object_type *type, int keep_cache)
1671{
1672        void *ret;
1673        unsigned long hash = pack_entry_hash(p, base_offset);
1674        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1675
1676        ret = ent->data;
1677        if (!ret || ent->p != p || ent->base_offset != base_offset)
1678                return unpack_entry(p, base_offset, type, base_size);
1679
1680        if (!keep_cache) {
1681                ent->data = NULL;
1682                ent->lru.next->prev = ent->lru.prev;
1683                ent->lru.prev->next = ent->lru.next;
1684                delta_base_cached -= ent->size;
1685        } else {
1686                ret = xmemdupz(ent->data, ent->size);
1687        }
1688        *type = ent->type;
1689        *base_size = ent->size;
1690        return ret;
1691}
1692
1693static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1694{
1695        if (ent->data) {
1696                free(ent->data);
1697                ent->data = NULL;
1698                ent->lru.next->prev = ent->lru.prev;
1699                ent->lru.prev->next = ent->lru.next;
1700                delta_base_cached -= ent->size;
1701        }
1702}
1703
1704void clear_delta_base_cache(void)
1705{
1706        unsigned long p;
1707        for (p = 0; p < MAX_DELTA_CACHE; p++)
1708                release_delta_base_cache(&delta_base_cache[p]);
1709}
1710
1711static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1712        void *base, unsigned long base_size, enum object_type type)
1713{
1714        unsigned long hash = pack_entry_hash(p, base_offset);
1715        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1716        struct delta_base_cache_lru_list *lru;
1717
1718        release_delta_base_cache(ent);
1719        delta_base_cached += base_size;
1720
1721        for (lru = delta_base_cache_lru.next;
1722             delta_base_cached > delta_base_cache_limit
1723             && lru != &delta_base_cache_lru;
1724             lru = lru->next) {
1725                struct delta_base_cache_entry *f = (void *)lru;
1726                if (f->type == OBJ_BLOB)
1727                        release_delta_base_cache(f);
1728        }
1729        for (lru = delta_base_cache_lru.next;
1730             delta_base_cached > delta_base_cache_limit
1731             && lru != &delta_base_cache_lru;
1732             lru = lru->next) {
1733                struct delta_base_cache_entry *f = (void *)lru;
1734                release_delta_base_cache(f);
1735        }
1736
1737        ent->p = p;
1738        ent->base_offset = base_offset;
1739        ent->type = type;
1740        ent->data = base;
1741        ent->size = base_size;
1742        ent->lru.next = &delta_base_cache_lru;
1743        ent->lru.prev = delta_base_cache_lru.prev;
1744        delta_base_cache_lru.prev->next = &ent->lru;
1745        delta_base_cache_lru.prev = &ent->lru;
1746}
1747
1748static void *read_object(const unsigned char *sha1, enum object_type *type,
1749                         unsigned long *size);
1750
1751static void *unpack_delta_entry(struct packed_git *p,
1752                                struct pack_window **w_curs,
1753                                off_t curpos,
1754                                unsigned long delta_size,
1755                                off_t obj_offset,
1756                                enum object_type *type,
1757                                unsigned long *sizep)
1758{
1759        void *delta_data, *result, *base;
1760        unsigned long base_size;
1761        off_t base_offset;
1762
1763        base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1764        if (!base_offset) {
1765                error("failed to validate delta base reference "
1766                      "at offset %"PRIuMAX" from %s",
1767                      (uintmax_t)curpos, p->pack_name);
1768                return NULL;
1769        }
1770        unuse_pack(w_curs);
1771        base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1772        if (!base) {
1773                /*
1774                 * We're probably in deep shit, but let's try to fetch
1775                 * the required base anyway from another pack or loose.
1776                 * This is costly but should happen only in the presence
1777                 * of a corrupted pack, and is better than failing outright.
1778                 */
1779                struct revindex_entry *revidx;
1780                const unsigned char *base_sha1;
1781                revidx = find_pack_revindex(p, base_offset);
1782                if (!revidx)
1783                        return NULL;
1784                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1785                error("failed to read delta base object %s"
1786                      " at offset %"PRIuMAX" from %s",
1787                      sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1788                      p->pack_name);
1789                mark_bad_packed_object(p, base_sha1);
1790                base = read_object(base_sha1, type, &base_size);
1791                if (!base)
1792                        return NULL;
1793        }
1794
1795        delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1796        if (!delta_data) {
1797                error("failed to unpack compressed delta "
1798                      "at offset %"PRIuMAX" from %s",
1799                      (uintmax_t)curpos, p->pack_name);
1800                free(base);
1801                return NULL;
1802        }
1803        result = patch_delta(base, base_size,
1804                             delta_data, delta_size,
1805                             sizep);
1806        if (!result)
1807                die("failed to apply delta");
1808        free(delta_data);
1809        add_delta_base_cache(p, base_offset, base, base_size, *type);
1810        return result;
1811}
1812
1813int do_check_packed_object_crc;
1814
1815void *unpack_entry(struct packed_git *p, off_t obj_offset,
1816                   enum object_type *type, unsigned long *sizep)
1817{
1818        struct pack_window *w_curs = NULL;
1819        off_t curpos = obj_offset;
1820        void *data;
1821
1822        if (do_check_packed_object_crc && p->index_version > 1) {
1823                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1824                unsigned long len = revidx[1].offset - obj_offset;
1825                if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1826                        const unsigned char *sha1 =
1827                                nth_packed_object_sha1(p, revidx->nr);
1828                        error("bad packed object CRC for %s",
1829                              sha1_to_hex(sha1));
1830                        mark_bad_packed_object(p, sha1);
1831                        unuse_pack(&w_curs);
1832                        return NULL;
1833                }
1834        }
1835
1836        *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1837        switch (*type) {
1838        case OBJ_OFS_DELTA:
1839        case OBJ_REF_DELTA:
1840                data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1841                                          obj_offset, type, sizep);
1842                break;
1843        case OBJ_COMMIT:
1844        case OBJ_TREE:
1845        case OBJ_BLOB:
1846        case OBJ_TAG:
1847                data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1848                break;
1849        default:
1850                data = NULL;
1851                error("unknown object type %i at offset %"PRIuMAX" in %s",
1852                      *type, (uintmax_t)obj_offset, p->pack_name);
1853        }
1854        unuse_pack(&w_curs);
1855        return data;
1856}
1857
1858const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1859                                            uint32_t n)
1860{
1861        const unsigned char *index = p->index_data;
1862        if (!index) {
1863                if (open_pack_index(p))
1864                        return NULL;
1865                index = p->index_data;
1866        }
1867        if (n >= p->num_objects)
1868                return NULL;
1869        index += 4 * 256;
1870        if (p->index_version == 1) {
1871                return index + 24 * n + 4;
1872        } else {
1873                index += 8;
1874                return index + 20 * n;
1875        }
1876}
1877
1878off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1879{
1880        const unsigned char *index = p->index_data;
1881        index += 4 * 256;
1882        if (p->index_version == 1) {
1883                return ntohl(*((uint32_t *)(index + 24 * n)));
1884        } else {
1885                uint32_t off;
1886                index += 8 + p->num_objects * (20 + 4);
1887                off = ntohl(*((uint32_t *)(index + 4 * n)));
1888                if (!(off & 0x80000000))
1889                        return off;
1890                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1891                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1892                                   ntohl(*((uint32_t *)(index + 4)));
1893        }
1894}
1895
1896off_t find_pack_entry_one(const unsigned char *sha1,
1897                                  struct packed_git *p)
1898{
1899        const uint32_t *level1_ofs = p->index_data;
1900        const unsigned char *index = p->index_data;
1901        unsigned hi, lo, stride;
1902        static int use_lookup = -1;
1903        static int debug_lookup = -1;
1904
1905        if (debug_lookup < 0)
1906                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1907
1908        if (!index) {
1909                if (open_pack_index(p))
1910                        return 0;
1911                level1_ofs = p->index_data;
1912                index = p->index_data;
1913        }
1914        if (p->index_version > 1) {
1915                level1_ofs += 2;
1916                index += 8;
1917        }
1918        index += 4 * 256;
1919        hi = ntohl(level1_ofs[*sha1]);
1920        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1921        if (p->index_version > 1) {
1922                stride = 20;
1923        } else {
1924                stride = 24;
1925                index += 4;
1926        }
1927
1928        if (debug_lookup)
1929                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1930                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1931
1932        if (use_lookup < 0)
1933                use_lookup = !!getenv("GIT_USE_LOOKUP");
1934        if (use_lookup) {
1935                int pos = sha1_entry_pos(index, stride, 0,
1936                                         lo, hi, p->num_objects, sha1);
1937                if (pos < 0)
1938                        return 0;
1939                return nth_packed_object_offset(p, pos);
1940        }
1941
1942        do {
1943                unsigned mi = (lo + hi) / 2;
1944                int cmp = hashcmp(index + mi * stride, sha1);
1945
1946                if (debug_lookup)
1947                        printf("lo %u hi %u rg %u mi %u\n",
1948                               lo, hi, hi - lo, mi);
1949                if (!cmp)
1950                        return nth_packed_object_offset(p, mi);
1951                if (cmp > 0)
1952                        hi = mi;
1953                else
1954                        lo = mi+1;
1955        } while (lo < hi);
1956        return 0;
1957}
1958
1959static int is_pack_valid(struct packed_git *p)
1960{
1961        /* An already open pack is known to be valid. */
1962        if (p->pack_fd != -1)
1963                return 1;
1964
1965        /* If the pack has one window completely covering the
1966         * file size, the pack is known to be valid even if
1967         * the descriptor is not currently open.
1968         */
1969        if (p->windows) {
1970                struct pack_window *w = p->windows;
1971
1972                if (!w->offset && w->len == p->pack_size)
1973                        return 1;
1974        }
1975
1976        /* Force the pack to open to prove its valid. */
1977        return !open_packed_git(p);
1978}
1979
1980static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1981{
1982        static struct packed_git *last_found = (void *)1;
1983        struct packed_git *p;
1984        off_t offset;
1985
1986        prepare_packed_git();
1987        if (!packed_git)
1988                return 0;
1989        p = (last_found == (void *)1) ? packed_git : last_found;
1990
1991        do {
1992                if (p->num_bad_objects) {
1993                        unsigned i;
1994                        for (i = 0; i < p->num_bad_objects; i++)
1995                                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1996                                        goto next;
1997                }
1998
1999                offset = find_pack_entry_one(sha1, p);
2000                if (offset) {
2001                        /*
2002                         * We are about to tell the caller where they can
2003                         * locate the requested object.  We better make
2004                         * sure the packfile is still here and can be
2005                         * accessed before supplying that answer, as
2006                         * it may have been deleted since the index
2007                         * was loaded!
2008                         */
2009                        if (!is_pack_valid(p)) {
2010                                error("packfile %s cannot be accessed", p->pack_name);
2011                                goto next;
2012                        }
2013                        e->offset = offset;
2014                        e->p = p;
2015                        hashcpy(e->sha1, sha1);
2016                        last_found = p;
2017                        return 1;
2018                }
2019
2020                next:
2021                if (p == last_found)
2022                        p = packed_git;
2023                else
2024                        p = p->next;
2025                if (p == last_found)
2026                        p = p->next;
2027        } while (p);
2028        return 0;
2029}
2030
2031struct packed_git *find_sha1_pack(const unsigned char *sha1,
2032                                  struct packed_git *packs)
2033{
2034        struct packed_git *p;
2035
2036        for (p = packs; p; p = p->next) {
2037                if (find_pack_entry_one(sha1, p))
2038                        return p;
2039        }
2040        return NULL;
2041
2042}
2043
2044static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
2045{
2046        int status;
2047        unsigned long mapsize, size;
2048        void *map;
2049        z_stream stream;
2050        char hdr[32];
2051
2052        map = map_sha1_file(sha1, &mapsize);
2053        if (!map)
2054                return error("unable to find %s", sha1_to_hex(sha1));
2055        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2056                status = error("unable to unpack %s header",
2057                               sha1_to_hex(sha1));
2058        else if ((status = parse_sha1_header(hdr, &size)) < 0)
2059                status = error("unable to parse %s header", sha1_to_hex(sha1));
2060        else if (sizep)
2061                *sizep = size;
2062        git_inflate_end(&stream);
2063        munmap(map, mapsize);
2064        return status;
2065}
2066
2067int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2068{
2069        struct cached_object *co;
2070        struct pack_entry e;
2071        int status;
2072
2073        co = find_cached_object(sha1);
2074        if (co) {
2075                if (sizep)
2076                        *sizep = co->size;
2077                return co->type;
2078        }
2079
2080        if (!find_pack_entry(sha1, &e)) {
2081                /* Most likely it's a loose object. */
2082                status = sha1_loose_object_info(sha1, sizep);
2083                if (status >= 0)
2084                        return status;
2085
2086                /* Not a loose object; someone else may have just packed it. */
2087                reprepare_packed_git();
2088                if (!find_pack_entry(sha1, &e))
2089                        return status;
2090        }
2091
2092        status = packed_object_info(e.p, e.offset, sizep);
2093        if (status < 0) {
2094                mark_bad_packed_object(e.p, sha1);
2095                status = sha1_object_info(sha1, sizep);
2096        }
2097
2098        return status;
2099}
2100
2101static void *read_packed_sha1(const unsigned char *sha1,
2102                              enum object_type *type, unsigned long *size)
2103{
2104        struct pack_entry e;
2105        void *data;
2106
2107        if (!find_pack_entry(sha1, &e))
2108                return NULL;
2109        data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2110        if (!data) {
2111                /*
2112                 * We're probably in deep shit, but let's try to fetch
2113                 * the required object anyway from another pack or loose.
2114                 * This should happen only in the presence of a corrupted
2115                 * pack, and is better than failing outright.
2116                 */
2117                error("failed to read object %s at offset %"PRIuMAX" from %s",
2118                      sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2119                mark_bad_packed_object(e.p, sha1);
2120                data = read_object(sha1, type, size);
2121        }
2122        return data;
2123}
2124
2125int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2126                      unsigned char *sha1)
2127{
2128        struct cached_object *co;
2129
2130        hash_sha1_file(buf, len, typename(type), sha1);
2131        if (has_sha1_file(sha1) || find_cached_object(sha1))
2132                return 0;
2133        if (cached_object_alloc <= cached_object_nr) {
2134                cached_object_alloc = alloc_nr(cached_object_alloc);
2135                cached_objects = xrealloc(cached_objects,
2136                                          sizeof(*cached_objects) *
2137                                          cached_object_alloc);
2138        }
2139        co = &cached_objects[cached_object_nr++];
2140        co->size = len;
2141        co->type = type;
2142        co->buf = xmalloc(len);
2143        memcpy(co->buf, buf, len);
2144        hashcpy(co->sha1, sha1);
2145        return 0;
2146}
2147
2148static void *read_object(const unsigned char *sha1, enum object_type *type,
2149                         unsigned long *size)
2150{
2151        unsigned long mapsize;
2152        void *map, *buf;
2153        struct cached_object *co;
2154
2155        co = find_cached_object(sha1);
2156        if (co) {
2157                *type = co->type;
2158                *size = co->size;
2159                return xmemdupz(co->buf, co->size);
2160        }
2161
2162        buf = read_packed_sha1(sha1, type, size);
2163        if (buf)
2164                return buf;
2165        map = map_sha1_file(sha1, &mapsize);
2166        if (map) {
2167                buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2168                munmap(map, mapsize);
2169                return buf;
2170        }
2171        reprepare_packed_git();
2172        return read_packed_sha1(sha1, type, size);
2173}
2174
2175/*
2176 * This function dies on corrupt objects; the callers who want to
2177 * deal with them should arrange to call read_object() and give error
2178 * messages themselves.
2179 */
2180void *read_sha1_file_repl(const unsigned char *sha1,
2181                          enum object_type *type,
2182                          unsigned long *size,
2183                          const unsigned char **replacement)
2184{
2185        const unsigned char *repl = lookup_replace_object(sha1);
2186        void *data;
2187        char *path;
2188        const struct packed_git *p;
2189
2190        errno = 0;
2191        data = read_object(repl, type, size);
2192        if (data) {
2193                if (replacement)
2194                        *replacement = repl;
2195                return data;
2196        }
2197
2198        if (errno && errno != ENOENT)
2199                die_errno("failed to read object %s", sha1_to_hex(sha1));
2200
2201        /* die if we replaced an object with one that does not exist */
2202        if (repl != sha1)
2203                die("replacement %s not found for %s",
2204                    sha1_to_hex(repl), sha1_to_hex(sha1));
2205
2206        if (has_loose_object(repl)) {
2207                path = sha1_file_name(sha1);
2208                die("loose object %s (stored in %s) is corrupt",
2209                    sha1_to_hex(repl), path);
2210        }
2211
2212        if ((p = has_packed_and_bad(repl)) != NULL)
2213                die("packed object %s (stored in %s) is corrupt",
2214                    sha1_to_hex(repl), p->pack_name);
2215
2216        return NULL;
2217}
2218
2219void *read_object_with_reference(const unsigned char *sha1,
2220                                 const char *required_type_name,
2221                                 unsigned long *size,
2222                                 unsigned char *actual_sha1_return)
2223{
2224        enum object_type type, required_type;
2225        void *buffer;
2226        unsigned long isize;
2227        unsigned char actual_sha1[20];
2228
2229        required_type = type_from_string(required_type_name);
2230        hashcpy(actual_sha1, sha1);
2231        while (1) {
2232                int ref_length = -1;
2233                const char *ref_type = NULL;
2234
2235                buffer = read_sha1_file(actual_sha1, &type, &isize);
2236                if (!buffer)
2237                        return NULL;
2238                if (type == required_type) {
2239                        *size = isize;
2240                        if (actual_sha1_return)
2241                                hashcpy(actual_sha1_return, actual_sha1);
2242                        return buffer;
2243                }
2244                /* Handle references */
2245                else if (type == OBJ_COMMIT)
2246                        ref_type = "tree ";
2247                else if (type == OBJ_TAG)
2248                        ref_type = "object ";
2249                else {
2250                        free(buffer);
2251                        return NULL;
2252                }
2253                ref_length = strlen(ref_type);
2254
2255                if (ref_length + 40 > isize ||
2256                    memcmp(buffer, ref_type, ref_length) ||
2257                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2258                        free(buffer);
2259                        return NULL;
2260                }
2261                free(buffer);
2262                /* Now we have the ID of the referred-to object in
2263                 * actual_sha1.  Check again. */
2264        }
2265}
2266
2267static void write_sha1_file_prepare(const void *buf, unsigned long len,
2268                                    const char *type, unsigned char *sha1,
2269                                    char *hdr, int *hdrlen)
2270{
2271        git_SHA_CTX c;
2272
2273        /* Generate the header */
2274        *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2275
2276        /* Sha1.. */
2277        git_SHA1_Init(&c);
2278        git_SHA1_Update(&c, hdr, *hdrlen);
2279        git_SHA1_Update(&c, buf, len);
2280        git_SHA1_Final(sha1, &c);
2281}
2282
2283/*
2284 * Move the just written object into its final resting place.
2285 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2286 * "moving" is only a part of what it does, when no patch between
2287 * master to pu changes the call sites of this function.
2288 */
2289int move_temp_to_file(const char *tmpfile, const char *filename)
2290{
2291        int ret = 0;
2292
2293        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2294                goto try_rename;
2295        else if (link(tmpfile, filename))
2296                ret = errno;
2297
2298        /*
2299         * Coda hack - coda doesn't like cross-directory links,
2300         * so we fall back to a rename, which will mean that it
2301         * won't be able to check collisions, but that's not a
2302         * big deal.
2303         *
2304         * The same holds for FAT formatted media.
2305         *
2306         * When this succeeds, we just return.  We have nothing
2307         * left to unlink.
2308         */
2309        if (ret && ret != EEXIST) {
2310        try_rename:
2311                if (!rename(tmpfile, filename))
2312                        goto out;
2313                ret = errno;
2314        }
2315        unlink_or_warn(tmpfile);
2316        if (ret) {
2317                if (ret != EEXIST) {
2318                        return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2319                }
2320                /* FIXME!!! Collision check here ? */
2321        }
2322
2323out:
2324        if (adjust_shared_perm(filename))
2325                return error("unable to set permission to '%s'", filename);
2326        return 0;
2327}
2328
2329static int write_buffer(int fd, const void *buf, size_t len)
2330{
2331        if (write_in_full(fd, buf, len) < 0)
2332                return error("file write error (%s)", strerror(errno));
2333        return 0;
2334}
2335
2336int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2337                   unsigned char *sha1)
2338{
2339        char hdr[32];
2340        int hdrlen;
2341        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2342        return 0;
2343}
2344
2345/* Finalize a file on disk, and close it. */
2346static void close_sha1_file(int fd)
2347{
2348        if (fsync_object_files)
2349                fsync_or_die(fd, "sha1 file");
2350        if (close(fd) != 0)
2351                die_errno("error when closing sha1 file");
2352}
2353
2354/* Size of directory component, including the ending '/' */
2355static inline int directory_size(const char *filename)
2356{
2357        const char *s = strrchr(filename, '/');
2358        if (!s)
2359                return 0;
2360        return s - filename + 1;
2361}
2362
2363/*
2364 * This creates a temporary file in the same directory as the final
2365 * 'filename'
2366 *
2367 * We want to avoid cross-directory filename renames, because those
2368 * can have problems on various filesystems (FAT, NFS, Coda).
2369 */
2370static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2371{
2372        int fd, dirlen = directory_size(filename);
2373
2374        if (dirlen + 20 > bufsiz) {
2375                errno = ENAMETOOLONG;
2376                return -1;
2377        }
2378        memcpy(buffer, filename, dirlen);
2379        strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2380        fd = git_mkstemp_mode(buffer, 0444);
2381        if (fd < 0 && dirlen && errno == ENOENT) {
2382                /* Make sure the directory exists */
2383                memcpy(buffer, filename, dirlen);
2384                buffer[dirlen-1] = 0;
2385                if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2386                        return -1;
2387
2388                /* Try again */
2389                strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2390                fd = git_mkstemp_mode(buffer, 0444);
2391        }
2392        return fd;
2393}
2394
2395static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2396                              const void *buf, unsigned long len, time_t mtime)
2397{
2398        int fd, ret;
2399        unsigned char compressed[4096];
2400        z_stream stream;
2401        git_SHA_CTX c;
2402        unsigned char parano_sha1[20];
2403        char *filename;
2404        static char tmpfile[PATH_MAX];
2405
2406        filename = sha1_file_name(sha1);
2407        fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2408        if (fd < 0) {
2409                if (errno == EACCES)
2410                        return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2411                else
2412                        return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2413        }
2414
2415        /* Set it up */
2416        memset(&stream, 0, sizeof(stream));
2417        deflateInit(&stream, zlib_compression_level);
2418        stream.next_out = compressed;
2419        stream.avail_out = sizeof(compressed);
2420        git_SHA1_Init(&c);
2421
2422        /* First header.. */
2423        stream.next_in = (unsigned char *)hdr;
2424        stream.avail_in = hdrlen;
2425        while (deflate(&stream, 0) == Z_OK)
2426                /* nothing */;
2427        git_SHA1_Update(&c, hdr, hdrlen);
2428
2429        /* Then the data itself.. */
2430        stream.next_in = (void *)buf;
2431        stream.avail_in = len;
2432        do {
2433                unsigned char *in0 = stream.next_in;
2434                ret = deflate(&stream, Z_FINISH);
2435                git_SHA1_Update(&c, in0, stream.next_in - in0);
2436                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2437                        die("unable to write sha1 file");
2438                stream.next_out = compressed;
2439                stream.avail_out = sizeof(compressed);
2440        } while (ret == Z_OK);
2441
2442        if (ret != Z_STREAM_END)
2443                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2444        ret = deflateEnd(&stream);
2445        if (ret != Z_OK)
2446                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2447        git_SHA1_Final(parano_sha1, &c);
2448        if (hashcmp(sha1, parano_sha1) != 0)
2449                die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2450
2451        close_sha1_file(fd);
2452
2453        if (mtime) {
2454                struct utimbuf utb;
2455                utb.actime = mtime;
2456                utb.modtime = mtime;
2457                if (utime(tmpfile, &utb) < 0)
2458                        warning("failed utime() on %s: %s",
2459                                tmpfile, strerror(errno));
2460        }
2461
2462        return move_temp_to_file(tmpfile, filename);
2463}
2464
2465int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2466{
2467        unsigned char sha1[20];
2468        char hdr[32];
2469        int hdrlen;
2470
2471        /* Normally if we have it in the pack then we do not bother writing
2472         * it out into .git/objects/??/?{38} file.
2473         */
2474        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2475        if (returnsha1)
2476                hashcpy(returnsha1, sha1);
2477        if (has_sha1_file(sha1))
2478                return 0;
2479        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2480}
2481
2482int force_object_loose(const unsigned char *sha1, time_t mtime)
2483{
2484        void *buf;
2485        unsigned long len;
2486        enum object_type type;
2487        char hdr[32];
2488        int hdrlen;
2489        int ret;
2490
2491        if (has_loose_object(sha1))
2492                return 0;
2493        buf = read_packed_sha1(sha1, &type, &len);
2494        if (!buf)
2495                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2496        hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2497        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2498        free(buf);
2499
2500        return ret;
2501}
2502
2503int has_pack_index(const unsigned char *sha1)
2504{
2505        struct stat st;
2506        if (stat(sha1_pack_index_name(sha1), &st))
2507                return 0;
2508        return 1;
2509}
2510
2511int has_sha1_pack(const unsigned char *sha1)
2512{
2513        struct pack_entry e;
2514        return find_pack_entry(sha1, &e);
2515}
2516
2517int has_sha1_file(const unsigned char *sha1)
2518{
2519        struct pack_entry e;
2520
2521        if (find_pack_entry(sha1, &e))
2522                return 1;
2523        return has_loose_object(sha1);
2524}
2525
2526static void check_tree(const void *buf, size_t size)
2527{
2528        struct tree_desc desc;
2529        struct name_entry entry;
2530
2531        init_tree_desc(&desc, buf, size);
2532        while (tree_entry(&desc, &entry))
2533                /* do nothing
2534                 * tree_entry() will die() on malformed entries */
2535                ;
2536}
2537
2538static void check_commit(const void *buf, size_t size)
2539{
2540        struct commit c;
2541        memset(&c, 0, sizeof(c));
2542        if (parse_commit_buffer(&c, buf, size))
2543                die("corrupt commit");
2544}
2545
2546static void check_tag(const void *buf, size_t size)
2547{
2548        struct tag t;
2549        memset(&t, 0, sizeof(t));
2550        if (parse_tag_buffer(&t, buf, size))
2551                die("corrupt tag");
2552}
2553
2554static int index_mem(unsigned char *sha1, void *buf, size_t size,
2555                     int write_object, enum object_type type,
2556                     const char *path, int format_check)
2557{
2558        int ret, re_allocated = 0;
2559
2560        if (!type)
2561                type = OBJ_BLOB;
2562
2563        /*
2564         * Convert blobs to git internal format
2565         */
2566        if ((type == OBJ_BLOB) && path) {
2567                struct strbuf nbuf = STRBUF_INIT;
2568                if (convert_to_git(path, buf, size, &nbuf,
2569                                   write_object ? safe_crlf : 0)) {
2570                        buf = strbuf_detach(&nbuf, &size);
2571                        re_allocated = 1;
2572                }
2573        }
2574        if (format_check) {
2575                if (type == OBJ_TREE)
2576                        check_tree(buf, size);
2577                if (type == OBJ_COMMIT)
2578                        check_commit(buf, size);
2579                if (type == OBJ_TAG)
2580                        check_tag(buf, size);
2581        }
2582
2583        if (write_object)
2584                ret = write_sha1_file(buf, size, typename(type), sha1);
2585        else
2586                ret = hash_sha1_file(buf, size, typename(type), sha1);
2587        if (re_allocated)
2588                free(buf);
2589        return ret;
2590}
2591
2592#define SMALL_FILE_SIZE (32*1024)
2593
2594int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2595             enum object_type type, const char *path, int format_check)
2596{
2597        int ret;
2598        size_t size = xsize_t(st->st_size);
2599
2600        if (!S_ISREG(st->st_mode)) {
2601                struct strbuf sbuf = STRBUF_INIT;
2602                if (strbuf_read(&sbuf, fd, 4096) >= 0)
2603                        ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object,
2604                                        type, path, format_check);
2605                else
2606                        ret = -1;
2607                strbuf_release(&sbuf);
2608        } else if (!size) {
2609                ret = index_mem(sha1, NULL, size, write_object, type, path,
2610                                format_check);
2611        } else if (size <= SMALL_FILE_SIZE) {
2612                char *buf = xmalloc(size);
2613                if (size == read_in_full(fd, buf, size))
2614                        ret = index_mem(sha1, buf, size, write_object, type,
2615                                        path, format_check);
2616                else
2617                        ret = error("short read %s", strerror(errno));
2618                free(buf);
2619        } else {
2620                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2621                ret = index_mem(sha1, buf, size, write_object, type, path,
2622                                format_check);
2623                munmap(buf, size);
2624        }
2625        close(fd);
2626        return ret;
2627}
2628
2629int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2630{
2631        int fd;
2632        struct strbuf sb = STRBUF_INIT;
2633
2634        switch (st->st_mode & S_IFMT) {
2635        case S_IFREG:
2636                fd = open(path, O_RDONLY);
2637                if (fd < 0)
2638                        return error("open(\"%s\"): %s", path,
2639                                     strerror(errno));
2640                if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path, 0) < 0)
2641                        return error("%s: failed to insert into database",
2642                                     path);
2643                break;
2644        case S_IFLNK:
2645                if (strbuf_readlink(&sb, path, st->st_size)) {
2646                        char *errstr = strerror(errno);
2647                        return error("readlink(\"%s\"): %s", path,
2648                                     errstr);
2649                }
2650                if (!write_object)
2651                        hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2652                else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2653                        return error("%s: failed to insert into database",
2654                                     path);
2655                strbuf_release(&sb);
2656                break;
2657        case S_IFDIR:
2658                return resolve_gitlink_ref(path, "HEAD", sha1);
2659        default:
2660                return error("%s: unsupported file type", path);
2661        }
2662        return 0;
2663}
2664
2665int read_pack_header(int fd, struct pack_header *header)
2666{
2667        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2668                /* "eof before pack header was fully read" */
2669                return PH_ERROR_EOF;
2670
2671        if (header->hdr_signature != htonl(PACK_SIGNATURE))
2672                /* "protocol error (pack signature mismatch detected)" */
2673                return PH_ERROR_PACK_SIGNATURE;
2674        if (!pack_version_ok(header->hdr_version))
2675                /* "protocol error (pack version unsupported)" */
2676                return PH_ERROR_PROTOCOL;
2677        return 0;
2678}
2679
2680void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2681{
2682        enum object_type type = sha1_object_info(sha1, NULL);
2683        if (type < 0)
2684                die("%s is not a valid object", sha1_to_hex(sha1));
2685        if (type != expect)
2686                die("%s is not a valid '%s' object", sha1_to_hex(sha1),
2687                    typename(expect));
2688}