packfile.con commit packfile: generalize pack directory list (9208e31)
   1#include "cache.h"
   2#include "list.h"
   3#include "pack.h"
   4#include "repository.h"
   5#include "dir.h"
   6#include "mergesort.h"
   7#include "packfile.h"
   8#include "delta.h"
   9#include "list.h"
  10#include "streaming.h"
  11#include "sha1-lookup.h"
  12#include "commit.h"
  13#include "object.h"
  14#include "tag.h"
  15#include "tree-walk.h"
  16#include "tree.h"
  17#include "object-store.h"
  18
  19char *odb_pack_name(struct strbuf *buf,
  20                    const unsigned char *sha1,
  21                    const char *ext)
  22{
  23        strbuf_reset(buf);
  24        strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
  25                    sha1_to_hex(sha1), ext);
  26        return buf->buf;
  27}
  28
  29char *sha1_pack_name(const unsigned char *sha1)
  30{
  31        static struct strbuf buf = STRBUF_INIT;
  32        return odb_pack_name(&buf, sha1, "pack");
  33}
  34
  35char *sha1_pack_index_name(const unsigned char *sha1)
  36{
  37        static struct strbuf buf = STRBUF_INIT;
  38        return odb_pack_name(&buf, sha1, "idx");
  39}
  40
  41static unsigned int pack_used_ctr;
  42static unsigned int pack_mmap_calls;
  43static unsigned int peak_pack_open_windows;
  44static unsigned int pack_open_windows;
  45static unsigned int pack_open_fds;
  46static unsigned int pack_max_fds;
  47static size_t peak_pack_mapped;
  48static size_t pack_mapped;
  49
  50#define SZ_FMT PRIuMAX
  51static inline uintmax_t sz_fmt(size_t s) { return s; }
  52
  53void pack_report(void)
  54{
  55        fprintf(stderr,
  56                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
  57                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
  58                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
  59                sz_fmt(getpagesize()),
  60                sz_fmt(packed_git_window_size),
  61                sz_fmt(packed_git_limit));
  62        fprintf(stderr,
  63                "pack_report: pack_used_ctr            = %10u\n"
  64                "pack_report: pack_mmap_calls          = %10u\n"
  65                "pack_report: pack_open_windows        = %10u / %10u\n"
  66                "pack_report: pack_mapped              = "
  67                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
  68                pack_used_ctr,
  69                pack_mmap_calls,
  70                pack_open_windows, peak_pack_open_windows,
  71                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
  72}
  73
  74/*
  75 * Open and mmap the index file at path, perform a couple of
  76 * consistency checks, then record its information to p.  Return 0 on
  77 * success.
  78 */
  79static int check_packed_git_idx(const char *path, struct packed_git *p)
  80{
  81        void *idx_map;
  82        struct pack_idx_header *hdr;
  83        size_t idx_size;
  84        uint32_t version, nr, i, *index;
  85        int fd = git_open(path);
  86        struct stat st;
  87        const unsigned int hashsz = the_hash_algo->rawsz;
  88
  89        if (fd < 0)
  90                return -1;
  91        if (fstat(fd, &st)) {
  92                close(fd);
  93                return -1;
  94        }
  95        idx_size = xsize_t(st.st_size);
  96        if (idx_size < 4 * 256 + hashsz + hashsz) {
  97                close(fd);
  98                return error("index file %s is too small", path);
  99        }
 100        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 101        close(fd);
 102
 103        hdr = idx_map;
 104        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
 105                version = ntohl(hdr->idx_version);
 106                if (version < 2 || version > 2) {
 107                        munmap(idx_map, idx_size);
 108                        return error("index file %s is version %"PRIu32
 109                                     " and is not supported by this binary"
 110                                     " (try upgrading GIT to a newer version)",
 111                                     path, version);
 112                }
 113        } else
 114                version = 1;
 115
 116        nr = 0;
 117        index = idx_map;
 118        if (version > 1)
 119                index += 2;  /* skip index header */
 120        for (i = 0; i < 256; i++) {
 121                uint32_t n = ntohl(index[i]);
 122                if (n < nr) {
 123                        munmap(idx_map, idx_size);
 124                        return error("non-monotonic index %s", path);
 125                }
 126                nr = n;
 127        }
 128
 129        if (version == 1) {
 130                /*
 131                 * Total size:
 132                 *  - 256 index entries 4 bytes each
 133                 *  - 24-byte entries * nr (object ID + 4-byte offset)
 134                 *  - hash of the packfile
 135                 *  - file checksum
 136                 */
 137                if (idx_size != 4*256 + nr * (hashsz + 4) + hashsz + hashsz) {
 138                        munmap(idx_map, idx_size);
 139                        return error("wrong index v1 file size in %s", path);
 140                }
 141        } else if (version == 2) {
 142                /*
 143                 * Minimum size:
 144                 *  - 8 bytes of header
 145                 *  - 256 index entries 4 bytes each
 146                 *  - object ID entry * nr
 147                 *  - 4-byte crc entry * nr
 148                 *  - 4-byte offset entry * nr
 149                 *  - hash of the packfile
 150                 *  - file checksum
 151                 * And after the 4-byte offset table might be a
 152                 * variable sized table containing 8-byte entries
 153                 * for offsets larger than 2^31.
 154                 */
 155                unsigned long min_size = 8 + 4*256 + nr*(hashsz + 4 + 4) + hashsz + hashsz;
 156                unsigned long max_size = min_size;
 157                if (nr)
 158                        max_size += (nr - 1)*8;
 159                if (idx_size < min_size || idx_size > max_size) {
 160                        munmap(idx_map, idx_size);
 161                        return error("wrong index v2 file size in %s", path);
 162                }
 163                if (idx_size != min_size &&
 164                    /*
 165                     * make sure we can deal with large pack offsets.
 166                     * 31-bit signed offset won't be enough, neither
 167                     * 32-bit unsigned one will be.
 168                     */
 169                    (sizeof(off_t) <= 4)) {
 170                        munmap(idx_map, idx_size);
 171                        return error("pack too large for current definition of off_t in %s", path);
 172                }
 173        }
 174
 175        p->index_version = version;
 176        p->index_data = idx_map;
 177        p->index_size = idx_size;
 178        p->num_objects = nr;
 179        return 0;
 180}
 181
 182int open_pack_index(struct packed_git *p)
 183{
 184        char *idx_name;
 185        size_t len;
 186        int ret;
 187
 188        if (p->index_data)
 189                return 0;
 190
 191        if (!strip_suffix(p->pack_name, ".pack", &len))
 192                BUG("pack_name does not end in .pack");
 193        idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
 194        ret = check_packed_git_idx(idx_name, p);
 195        free(idx_name);
 196        return ret;
 197}
 198
 199static struct packed_git *alloc_packed_git(int extra)
 200{
 201        struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
 202        memset(p, 0, sizeof(*p));
 203        p->pack_fd = -1;
 204        return p;
 205}
 206
 207struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
 208{
 209        const char *path = sha1_pack_name(sha1);
 210        size_t alloc = st_add(strlen(path), 1);
 211        struct packed_git *p = alloc_packed_git(alloc);
 212
 213        memcpy(p->pack_name, path, alloc); /* includes NUL */
 214        hashcpy(p->sha1, sha1);
 215        if (check_packed_git_idx(idx_path, p)) {
 216                free(p);
 217                return NULL;
 218        }
 219
 220        return p;
 221}
 222
 223static void scan_windows(struct packed_git *p,
 224        struct packed_git **lru_p,
 225        struct pack_window **lru_w,
 226        struct pack_window **lru_l)
 227{
 228        struct pack_window *w, *w_l;
 229
 230        for (w_l = NULL, w = p->windows; w; w = w->next) {
 231                if (!w->inuse_cnt) {
 232                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 233                                *lru_p = p;
 234                                *lru_w = w;
 235                                *lru_l = w_l;
 236                        }
 237                }
 238                w_l = w;
 239        }
 240}
 241
 242static int unuse_one_window(struct packed_git *current)
 243{
 244        struct packed_git *p, *lru_p = NULL;
 245        struct pack_window *lru_w = NULL, *lru_l = NULL;
 246
 247        if (current)
 248                scan_windows(current, &lru_p, &lru_w, &lru_l);
 249        for (p = the_repository->objects->packed_git; p; p = p->next)
 250                scan_windows(p, &lru_p, &lru_w, &lru_l);
 251        if (lru_p) {
 252                munmap(lru_w->base, lru_w->len);
 253                pack_mapped -= lru_w->len;
 254                if (lru_l)
 255                        lru_l->next = lru_w->next;
 256                else
 257                        lru_p->windows = lru_w->next;
 258                free(lru_w);
 259                pack_open_windows--;
 260                return 1;
 261        }
 262        return 0;
 263}
 264
 265void release_pack_memory(size_t need)
 266{
 267        size_t cur = pack_mapped;
 268        while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
 269                ; /* nothing */
 270}
 271
 272void close_pack_windows(struct packed_git *p)
 273{
 274        while (p->windows) {
 275                struct pack_window *w = p->windows;
 276
 277                if (w->inuse_cnt)
 278                        die("pack '%s' still has open windows to it",
 279                            p->pack_name);
 280                munmap(w->base, w->len);
 281                pack_mapped -= w->len;
 282                pack_open_windows--;
 283                p->windows = w->next;
 284                free(w);
 285        }
 286}
 287
 288static int close_pack_fd(struct packed_git *p)
 289{
 290        if (p->pack_fd < 0)
 291                return 0;
 292
 293        close(p->pack_fd);
 294        pack_open_fds--;
 295        p->pack_fd = -1;
 296
 297        return 1;
 298}
 299
 300void close_pack_index(struct packed_git *p)
 301{
 302        if (p->index_data) {
 303                munmap((void *)p->index_data, p->index_size);
 304                p->index_data = NULL;
 305        }
 306}
 307
 308void close_pack(struct packed_git *p)
 309{
 310        close_pack_windows(p);
 311        close_pack_fd(p);
 312        close_pack_index(p);
 313}
 314
 315void close_all_packs(struct raw_object_store *o)
 316{
 317        struct packed_git *p;
 318
 319        for (p = o->packed_git; p; p = p->next)
 320                if (p->do_not_close)
 321                        BUG("want to close pack marked 'do-not-close'");
 322                else
 323                        close_pack(p);
 324}
 325
 326/*
 327 * The LRU pack is the one with the oldest MRU window, preferring packs
 328 * with no used windows, or the oldest mtime if it has no windows allocated.
 329 */
 330static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
 331{
 332        struct pack_window *w, *this_mru_w;
 333        int has_windows_inuse = 0;
 334
 335        /*
 336         * Reject this pack if it has windows and the previously selected
 337         * one does not.  If this pack does not have windows, reject
 338         * it if the pack file is newer than the previously selected one.
 339         */
 340        if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
 341                return;
 342
 343        for (w = this_mru_w = p->windows; w; w = w->next) {
 344                /*
 345                 * Reject this pack if any of its windows are in use,
 346                 * but the previously selected pack did not have any
 347                 * inuse windows.  Otherwise, record that this pack
 348                 * has windows in use.
 349                 */
 350                if (w->inuse_cnt) {
 351                        if (*accept_windows_inuse)
 352                                has_windows_inuse = 1;
 353                        else
 354                                return;
 355                }
 356
 357                if (w->last_used > this_mru_w->last_used)
 358                        this_mru_w = w;
 359
 360                /*
 361                 * Reject this pack if it has windows that have been
 362                 * used more recently than the previously selected pack.
 363                 * If the previously selected pack had windows inuse and
 364                 * we have not encountered a window in this pack that is
 365                 * inuse, skip this check since we prefer a pack with no
 366                 * inuse windows to one that has inuse windows.
 367                 */
 368                if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
 369                    this_mru_w->last_used > (*mru_w)->last_used)
 370                        return;
 371        }
 372
 373        /*
 374         * Select this pack.
 375         */
 376        *mru_w = this_mru_w;
 377        *lru_p = p;
 378        *accept_windows_inuse = has_windows_inuse;
 379}
 380
 381static int close_one_pack(void)
 382{
 383        struct packed_git *p, *lru_p = NULL;
 384        struct pack_window *mru_w = NULL;
 385        int accept_windows_inuse = 1;
 386
 387        for (p = the_repository->objects->packed_git; p; p = p->next) {
 388                if (p->pack_fd == -1)
 389                        continue;
 390                find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
 391        }
 392
 393        if (lru_p)
 394                return close_pack_fd(lru_p);
 395
 396        return 0;
 397}
 398
 399static unsigned int get_max_fd_limit(void)
 400{
 401#ifdef RLIMIT_NOFILE
 402        {
 403                struct rlimit lim;
 404
 405                if (!getrlimit(RLIMIT_NOFILE, &lim))
 406                        return lim.rlim_cur;
 407        }
 408#endif
 409
 410#ifdef _SC_OPEN_MAX
 411        {
 412                long open_max = sysconf(_SC_OPEN_MAX);
 413                if (0 < open_max)
 414                        return open_max;
 415                /*
 416                 * Otherwise, we got -1 for one of the two
 417                 * reasons:
 418                 *
 419                 * (1) sysconf() did not understand _SC_OPEN_MAX
 420                 *     and signaled an error with -1; or
 421                 * (2) sysconf() said there is no limit.
 422                 *
 423                 * We _could_ clear errno before calling sysconf() to
 424                 * tell these two cases apart and return a huge number
 425                 * in the latter case to let the caller cap it to a
 426                 * value that is not so selfish, but letting the
 427                 * fallback OPEN_MAX codepath take care of these cases
 428                 * is a lot simpler.
 429                 */
 430        }
 431#endif
 432
 433#ifdef OPEN_MAX
 434        return OPEN_MAX;
 435#else
 436        return 1; /* see the caller ;-) */
 437#endif
 438}
 439
 440/*
 441 * Do not call this directly as this leaks p->pack_fd on error return;
 442 * call open_packed_git() instead.
 443 */
 444static int open_packed_git_1(struct packed_git *p)
 445{
 446        struct stat st;
 447        struct pack_header hdr;
 448        unsigned char hash[GIT_MAX_RAWSZ];
 449        unsigned char *idx_hash;
 450        long fd_flag;
 451        ssize_t read_result;
 452        const unsigned hashsz = the_hash_algo->rawsz;
 453
 454        if (!p->index_data && open_pack_index(p))
 455                return error("packfile %s index unavailable", p->pack_name);
 456
 457        if (!pack_max_fds) {
 458                unsigned int max_fds = get_max_fd_limit();
 459
 460                /* Save 3 for stdin/stdout/stderr, 22 for work */
 461                if (25 < max_fds)
 462                        pack_max_fds = max_fds - 25;
 463                else
 464                        pack_max_fds = 1;
 465        }
 466
 467        while (pack_max_fds <= pack_open_fds && close_one_pack())
 468                ; /* nothing */
 469
 470        p->pack_fd = git_open(p->pack_name);
 471        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 472                return -1;
 473        pack_open_fds++;
 474
 475        /* If we created the struct before we had the pack we lack size. */
 476        if (!p->pack_size) {
 477                if (!S_ISREG(st.st_mode))
 478                        return error("packfile %s not a regular file", p->pack_name);
 479                p->pack_size = st.st_size;
 480        } else if (p->pack_size != st.st_size)
 481                return error("packfile %s size changed", p->pack_name);
 482
 483        /* We leave these file descriptors open with sliding mmap;
 484         * there is no point keeping them open across exec(), though.
 485         */
 486        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 487        if (fd_flag < 0)
 488                return error("cannot determine file descriptor flags");
 489        fd_flag |= FD_CLOEXEC;
 490        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 491                return error("cannot set FD_CLOEXEC");
 492
 493        /* Verify we recognize this pack file format. */
 494        read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
 495        if (read_result < 0)
 496                return error_errno("error reading from %s", p->pack_name);
 497        if (read_result != sizeof(hdr))
 498                return error("file %s is far too short to be a packfile", p->pack_name);
 499        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 500                return error("file %s is not a GIT packfile", p->pack_name);
 501        if (!pack_version_ok(hdr.hdr_version))
 502                return error("packfile %s is version %"PRIu32" and not"
 503                        " supported (try upgrading GIT to a newer version)",
 504                        p->pack_name, ntohl(hdr.hdr_version));
 505
 506        /* Verify the pack matches its index. */
 507        if (p->num_objects != ntohl(hdr.hdr_entries))
 508                return error("packfile %s claims to have %"PRIu32" objects"
 509                             " while index indicates %"PRIu32" objects",
 510                             p->pack_name, ntohl(hdr.hdr_entries),
 511                             p->num_objects);
 512        if (lseek(p->pack_fd, p->pack_size - hashsz, SEEK_SET) == -1)
 513                return error("end of packfile %s is unavailable", p->pack_name);
 514        read_result = read_in_full(p->pack_fd, hash, hashsz);
 515        if (read_result < 0)
 516                return error_errno("error reading from %s", p->pack_name);
 517        if (read_result != hashsz)
 518                return error("packfile %s signature is unavailable", p->pack_name);
 519        idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
 520        if (hashcmp(hash, idx_hash))
 521                return error("packfile %s does not match index", p->pack_name);
 522        return 0;
 523}
 524
 525static int open_packed_git(struct packed_git *p)
 526{
 527        if (!open_packed_git_1(p))
 528                return 0;
 529        close_pack_fd(p);
 530        return -1;
 531}
 532
 533static int in_window(struct pack_window *win, off_t offset)
 534{
 535        /* We must promise at least one full hash after the
 536         * offset is available from this window, otherwise the offset
 537         * is not actually in this window and a different window (which
 538         * has that one hash excess) must be used.  This is to support
 539         * the object header and delta base parsing routines below.
 540         */
 541        off_t win_off = win->offset;
 542        return win_off <= offset
 543                && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
 544}
 545
 546unsigned char *use_pack(struct packed_git *p,
 547                struct pack_window **w_cursor,
 548                off_t offset,
 549                unsigned long *left)
 550{
 551        struct pack_window *win = *w_cursor;
 552
 553        /* Since packfiles end in a hash of their content and it's
 554         * pointless to ask for an offset into the middle of that
 555         * hash, and the in_window function above wouldn't match
 556         * don't allow an offset too close to the end of the file.
 557         */
 558        if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
 559                die("packfile %s cannot be accessed", p->pack_name);
 560        if (offset > (p->pack_size - the_hash_algo->rawsz))
 561                die("offset beyond end of packfile (truncated pack?)");
 562        if (offset < 0)
 563                die(_("offset before end of packfile (broken .idx?)"));
 564
 565        if (!win || !in_window(win, offset)) {
 566                if (win)
 567                        win->inuse_cnt--;
 568                for (win = p->windows; win; win = win->next) {
 569                        if (in_window(win, offset))
 570                                break;
 571                }
 572                if (!win) {
 573                        size_t window_align = packed_git_window_size / 2;
 574                        off_t len;
 575
 576                        if (p->pack_fd == -1 && open_packed_git(p))
 577                                die("packfile %s cannot be accessed", p->pack_name);
 578
 579                        win = xcalloc(1, sizeof(*win));
 580                        win->offset = (offset / window_align) * window_align;
 581                        len = p->pack_size - win->offset;
 582                        if (len > packed_git_window_size)
 583                                len = packed_git_window_size;
 584                        win->len = (size_t)len;
 585                        pack_mapped += win->len;
 586                        while (packed_git_limit < pack_mapped
 587                                && unuse_one_window(p))
 588                                ; /* nothing */
 589                        win->base = xmmap(NULL, win->len,
 590                                PROT_READ, MAP_PRIVATE,
 591                                p->pack_fd, win->offset);
 592                        if (win->base == MAP_FAILED)
 593                                die_errno("packfile %s cannot be mapped",
 594                                          p->pack_name);
 595                        if (!win->offset && win->len == p->pack_size
 596                                && !p->do_not_close)
 597                                close_pack_fd(p);
 598                        pack_mmap_calls++;
 599                        pack_open_windows++;
 600                        if (pack_mapped > peak_pack_mapped)
 601                                peak_pack_mapped = pack_mapped;
 602                        if (pack_open_windows > peak_pack_open_windows)
 603                                peak_pack_open_windows = pack_open_windows;
 604                        win->next = p->windows;
 605                        p->windows = win;
 606                }
 607        }
 608        if (win != *w_cursor) {
 609                win->last_used = pack_used_ctr++;
 610                win->inuse_cnt++;
 611                *w_cursor = win;
 612        }
 613        offset -= win->offset;
 614        if (left)
 615                *left = win->len - xsize_t(offset);
 616        return win->base + offset;
 617}
 618
 619void unuse_pack(struct pack_window **w_cursor)
 620{
 621        struct pack_window *w = *w_cursor;
 622        if (w) {
 623                w->inuse_cnt--;
 624                *w_cursor = NULL;
 625        }
 626}
 627
 628static void try_to_free_pack_memory(size_t size)
 629{
 630        release_pack_memory(size);
 631}
 632
 633struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
 634{
 635        static int have_set_try_to_free_routine;
 636        struct stat st;
 637        size_t alloc;
 638        struct packed_git *p;
 639
 640        if (!have_set_try_to_free_routine) {
 641                have_set_try_to_free_routine = 1;
 642                set_try_to_free_routine(try_to_free_pack_memory);
 643        }
 644
 645        /*
 646         * Make sure a corresponding .pack file exists and that
 647         * the index looks sane.
 648         */
 649        if (!strip_suffix_mem(path, &path_len, ".idx"))
 650                return NULL;
 651
 652        /*
 653         * ".promisor" is long enough to hold any suffix we're adding (and
 654         * the use xsnprintf double-checks that)
 655         */
 656        alloc = st_add3(path_len, strlen(".promisor"), 1);
 657        p = alloc_packed_git(alloc);
 658        memcpy(p->pack_name, path, path_len);
 659
 660        xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
 661        if (!access(p->pack_name, F_OK))
 662                p->pack_keep = 1;
 663
 664        xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
 665        if (!access(p->pack_name, F_OK))
 666                p->pack_promisor = 1;
 667
 668        xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
 669        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 670                free(p);
 671                return NULL;
 672        }
 673
 674        /* ok, it looks sane as far as we can check without
 675         * actually mapping the pack file.
 676         */
 677        p->pack_size = st.st_size;
 678        p->pack_local = local;
 679        p->mtime = st.st_mtime;
 680        if (path_len < the_hash_algo->hexsz ||
 681            get_sha1_hex(path + path_len - the_hash_algo->hexsz, p->sha1))
 682                hashclr(p->sha1);
 683        return p;
 684}
 685
 686void install_packed_git(struct repository *r, struct packed_git *pack)
 687{
 688        if (pack->pack_fd != -1)
 689                pack_open_fds++;
 690
 691        pack->next = r->objects->packed_git;
 692        r->objects->packed_git = pack;
 693}
 694
 695void (*report_garbage)(unsigned seen_bits, const char *path);
 696
 697static void report_helper(const struct string_list *list,
 698                          int seen_bits, int first, int last)
 699{
 700        if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
 701                return;
 702
 703        for (; first < last; first++)
 704                report_garbage(seen_bits, list->items[first].string);
 705}
 706
 707static void report_pack_garbage(struct string_list *list)
 708{
 709        int i, baselen = -1, first = 0, seen_bits = 0;
 710
 711        if (!report_garbage)
 712                return;
 713
 714        string_list_sort(list);
 715
 716        for (i = 0; i < list->nr; i++) {
 717                const char *path = list->items[i].string;
 718                if (baselen != -1 &&
 719                    strncmp(path, list->items[first].string, baselen)) {
 720                        report_helper(list, seen_bits, first, i);
 721                        baselen = -1;
 722                        seen_bits = 0;
 723                }
 724                if (baselen == -1) {
 725                        const char *dot = strrchr(path, '.');
 726                        if (!dot) {
 727                                report_garbage(PACKDIR_FILE_GARBAGE, path);
 728                                continue;
 729                        }
 730                        baselen = dot - path + 1;
 731                        first = i;
 732                }
 733                if (!strcmp(path + baselen, "pack"))
 734                        seen_bits |= 1;
 735                else if (!strcmp(path + baselen, "idx"))
 736                        seen_bits |= 2;
 737        }
 738        report_helper(list, seen_bits, first, list->nr);
 739}
 740
 741void for_each_file_in_pack_dir(const char *objdir,
 742                               each_file_in_pack_dir_fn fn,
 743                               void *data)
 744{
 745        struct strbuf path = STRBUF_INIT;
 746        size_t dirnamelen;
 747        DIR *dir;
 748        struct dirent *de;
 749
 750        strbuf_addstr(&path, objdir);
 751        strbuf_addstr(&path, "/pack");
 752        dir = opendir(path.buf);
 753        if (!dir) {
 754                if (errno != ENOENT)
 755                        error_errno("unable to open object pack directory: %s",
 756                                    path.buf);
 757                strbuf_release(&path);
 758                return;
 759        }
 760        strbuf_addch(&path, '/');
 761        dirnamelen = path.len;
 762        while ((de = readdir(dir)) != NULL) {
 763                if (is_dot_or_dotdot(de->d_name))
 764                        continue;
 765
 766                strbuf_setlen(&path, dirnamelen);
 767                strbuf_addstr(&path, de->d_name);
 768
 769                fn(path.buf, path.len, de->d_name, data);
 770        }
 771
 772        closedir(dir);
 773        strbuf_release(&path);
 774}
 775
 776struct prepare_pack_data {
 777        struct repository *r;
 778        struct string_list *garbage;
 779        int local;
 780};
 781
 782static void prepare_pack(const char *full_name, size_t full_name_len,
 783                         const char *file_name, void *_data)
 784{
 785        struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
 786        struct packed_git *p;
 787        size_t base_len = full_name_len;
 788
 789        if (strip_suffix_mem(full_name, &base_len, ".idx")) {
 790                /* Don't reopen a pack we already have. */
 791                for (p = data->r->objects->packed_git; p; p = p->next) {
 792                        size_t len;
 793                        if (strip_suffix(p->pack_name, ".pack", &len) &&
 794                            len == base_len &&
 795                            !memcmp(p->pack_name, full_name, len))
 796                                break;
 797                }
 798
 799                if (!p) {
 800                        p = add_packed_git(full_name, full_name_len, data->local);
 801                        if (p)
 802                                install_packed_git(data->r, p);
 803                }
 804        }
 805
 806        if (!report_garbage)
 807                return;
 808
 809        if (ends_with(file_name, ".idx") ||
 810            ends_with(file_name, ".pack") ||
 811            ends_with(file_name, ".bitmap") ||
 812            ends_with(file_name, ".keep") ||
 813            ends_with(file_name, ".promisor"))
 814                string_list_append(data->garbage, full_name);
 815        else
 816                report_garbage(PACKDIR_FILE_GARBAGE, full_name);
 817}
 818
 819static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
 820{
 821        struct prepare_pack_data data;
 822        struct string_list garbage = STRING_LIST_INIT_DUP;
 823
 824        data.r = r;
 825        data.garbage = &garbage;
 826        data.local = local;
 827
 828        for_each_file_in_pack_dir(objdir, prepare_pack, &data);
 829
 830        report_pack_garbage(data.garbage);
 831        string_list_clear(data.garbage, 0);
 832}
 833
 834static void prepare_packed_git(struct repository *r);
 835/*
 836 * Give a fast, rough count of the number of objects in the repository. This
 837 * ignores loose objects completely. If you have a lot of them, then either
 838 * you should repack because your performance will be awful, or they are
 839 * all unreachable objects about to be pruned, in which case they're not really
 840 * interesting as a measure of repo size in the first place.
 841 */
 842unsigned long approximate_object_count(void)
 843{
 844        if (!the_repository->objects->approximate_object_count_valid) {
 845                unsigned long count;
 846                struct packed_git *p;
 847
 848                prepare_packed_git(the_repository);
 849                count = 0;
 850                for (p = the_repository->objects->packed_git; p; p = p->next) {
 851                        if (open_pack_index(p))
 852                                continue;
 853                        count += p->num_objects;
 854                }
 855                the_repository->objects->approximate_object_count = count;
 856        }
 857        return the_repository->objects->approximate_object_count;
 858}
 859
 860static void *get_next_packed_git(const void *p)
 861{
 862        return ((const struct packed_git *)p)->next;
 863}
 864
 865static void set_next_packed_git(void *p, void *next)
 866{
 867        ((struct packed_git *)p)->next = next;
 868}
 869
 870static int sort_pack(const void *a_, const void *b_)
 871{
 872        const struct packed_git *a = a_;
 873        const struct packed_git *b = b_;
 874        int st;
 875
 876        /*
 877         * Local packs tend to contain objects specific to our
 878         * variant of the project than remote ones.  In addition,
 879         * remote ones could be on a network mounted filesystem.
 880         * Favor local ones for these reasons.
 881         */
 882        st = a->pack_local - b->pack_local;
 883        if (st)
 884                return -st;
 885
 886        /*
 887         * Younger packs tend to contain more recent objects,
 888         * and more recent objects tend to get accessed more
 889         * often.
 890         */
 891        if (a->mtime < b->mtime)
 892                return 1;
 893        else if (a->mtime == b->mtime)
 894                return 0;
 895        return -1;
 896}
 897
 898static void rearrange_packed_git(struct repository *r)
 899{
 900        r->objects->packed_git = llist_mergesort(
 901                r->objects->packed_git, get_next_packed_git,
 902                set_next_packed_git, sort_pack);
 903}
 904
 905static void prepare_packed_git_mru(struct repository *r)
 906{
 907        struct packed_git *p;
 908
 909        INIT_LIST_HEAD(&r->objects->packed_git_mru);
 910
 911        for (p = r->objects->packed_git; p; p = p->next)
 912                list_add_tail(&p->mru, &r->objects->packed_git_mru);
 913}
 914
 915static void prepare_packed_git(struct repository *r)
 916{
 917        struct alternate_object_database *alt;
 918
 919        if (r->objects->packed_git_initialized)
 920                return;
 921        prepare_packed_git_one(r, r->objects->objectdir, 1);
 922        prepare_alt_odb(r);
 923        for (alt = r->objects->alt_odb_list; alt; alt = alt->next)
 924                prepare_packed_git_one(r, alt->path, 0);
 925        rearrange_packed_git(r);
 926        prepare_packed_git_mru(r);
 927        r->objects->packed_git_initialized = 1;
 928}
 929
 930void reprepare_packed_git(struct repository *r)
 931{
 932        r->objects->approximate_object_count_valid = 0;
 933        r->objects->packed_git_initialized = 0;
 934        prepare_packed_git(r);
 935}
 936
 937struct packed_git *get_packed_git(struct repository *r)
 938{
 939        prepare_packed_git(r);
 940        return r->objects->packed_git;
 941}
 942
 943struct list_head *get_packed_git_mru(struct repository *r)
 944{
 945        prepare_packed_git(r);
 946        return &r->objects->packed_git_mru;
 947}
 948
 949unsigned long unpack_object_header_buffer(const unsigned char *buf,
 950                unsigned long len, enum object_type *type, unsigned long *sizep)
 951{
 952        unsigned shift;
 953        unsigned long size, c;
 954        unsigned long used = 0;
 955
 956        c = buf[used++];
 957        *type = (c >> 4) & 7;
 958        size = c & 15;
 959        shift = 4;
 960        while (c & 0x80) {
 961                if (len <= used || bitsizeof(long) <= shift) {
 962                        error("bad object header");
 963                        size = used = 0;
 964                        break;
 965                }
 966                c = buf[used++];
 967                size += (c & 0x7f) << shift;
 968                shift += 7;
 969        }
 970        *sizep = size;
 971        return used;
 972}
 973
 974unsigned long get_size_from_delta(struct packed_git *p,
 975                                  struct pack_window **w_curs,
 976                                  off_t curpos)
 977{
 978        const unsigned char *data;
 979        unsigned char delta_head[20], *in;
 980        git_zstream stream;
 981        int st;
 982
 983        memset(&stream, 0, sizeof(stream));
 984        stream.next_out = delta_head;
 985        stream.avail_out = sizeof(delta_head);
 986
 987        git_inflate_init(&stream);
 988        do {
 989                in = use_pack(p, w_curs, curpos, &stream.avail_in);
 990                stream.next_in = in;
 991                st = git_inflate(&stream, Z_FINISH);
 992                curpos += stream.next_in - in;
 993        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
 994                 stream.total_out < sizeof(delta_head));
 995        git_inflate_end(&stream);
 996        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
 997                error("delta data unpack-initial failed");
 998                return 0;
 999        }
1000
1001        /* Examine the initial part of the delta to figure out
1002         * the result size.
1003         */
1004        data = delta_head;
1005
1006        /* ignore base size */
1007        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1008
1009        /* Read the result size */
1010        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1011}
1012
1013int unpack_object_header(struct packed_git *p,
1014                         struct pack_window **w_curs,
1015                         off_t *curpos,
1016                         unsigned long *sizep)
1017{
1018        unsigned char *base;
1019        unsigned long left;
1020        unsigned long used;
1021        enum object_type type;
1022
1023        /* use_pack() assures us we have [base, base + 20) available
1024         * as a range that we can look at.  (Its actually the hash
1025         * size that is assured.)  With our object header encoding
1026         * the maximum deflated object size is 2^137, which is just
1027         * insane, so we know won't exceed what we have been given.
1028         */
1029        base = use_pack(p, w_curs, *curpos, &left);
1030        used = unpack_object_header_buffer(base, left, &type, sizep);
1031        if (!used) {
1032                type = OBJ_BAD;
1033        } else
1034                *curpos += used;
1035
1036        return type;
1037}
1038
1039void mark_bad_packed_object(struct packed_git *p, const unsigned char *sha1)
1040{
1041        unsigned i;
1042        for (i = 0; i < p->num_bad_objects; i++)
1043                if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1044                        return;
1045        p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1046                                      st_mult(GIT_MAX_RAWSZ,
1047                                              st_add(p->num_bad_objects, 1)));
1048        hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1049        p->num_bad_objects++;
1050}
1051
1052const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1053{
1054        struct packed_git *p;
1055        unsigned i;
1056
1057        for (p = the_repository->objects->packed_git; p; p = p->next)
1058                for (i = 0; i < p->num_bad_objects; i++)
1059                        if (!hashcmp(sha1,
1060                                     p->bad_object_sha1 + the_hash_algo->rawsz * i))
1061                                return p;
1062        return NULL;
1063}
1064
1065static off_t get_delta_base(struct packed_git *p,
1066                                    struct pack_window **w_curs,
1067                                    off_t *curpos,
1068                                    enum object_type type,
1069                                    off_t delta_obj_offset)
1070{
1071        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1072        off_t base_offset;
1073
1074        /* use_pack() assured us we have [base_info, base_info + 20)
1075         * as a range that we can look at without walking off the
1076         * end of the mapped window.  Its actually the hash size
1077         * that is assured.  An OFS_DELTA longer than the hash size
1078         * is stupid, as then a REF_DELTA would be smaller to store.
1079         */
1080        if (type == OBJ_OFS_DELTA) {
1081                unsigned used = 0;
1082                unsigned char c = base_info[used++];
1083                base_offset = c & 127;
1084                while (c & 128) {
1085                        base_offset += 1;
1086                        if (!base_offset || MSB(base_offset, 7))
1087                                return 0;  /* overflow */
1088                        c = base_info[used++];
1089                        base_offset = (base_offset << 7) + (c & 127);
1090                }
1091                base_offset = delta_obj_offset - base_offset;
1092                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1093                        return 0;  /* out of bound */
1094                *curpos += used;
1095        } else if (type == OBJ_REF_DELTA) {
1096                /* The base entry _must_ be in the same pack */
1097                base_offset = find_pack_entry_one(base_info, p);
1098                *curpos += the_hash_algo->rawsz;
1099        } else
1100                die("I am totally screwed");
1101        return base_offset;
1102}
1103
1104/*
1105 * Like get_delta_base above, but we return the sha1 instead of the pack
1106 * offset. This means it is cheaper for REF deltas (we do not have to do
1107 * the final object lookup), but more expensive for OFS deltas (we
1108 * have to load the revidx to convert the offset back into a sha1).
1109 */
1110static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1111                                                struct pack_window **w_curs,
1112                                                off_t curpos,
1113                                                enum object_type type,
1114                                                off_t delta_obj_offset)
1115{
1116        if (type == OBJ_REF_DELTA) {
1117                unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1118                return base;
1119        } else if (type == OBJ_OFS_DELTA) {
1120                struct revindex_entry *revidx;
1121                off_t base_offset = get_delta_base(p, w_curs, &curpos,
1122                                                   type, delta_obj_offset);
1123
1124                if (!base_offset)
1125                        return NULL;
1126
1127                revidx = find_pack_revindex(p, base_offset);
1128                if (!revidx)
1129                        return NULL;
1130
1131                return nth_packed_object_sha1(p, revidx->nr);
1132        } else
1133                return NULL;
1134}
1135
1136static int retry_bad_packed_offset(struct repository *r,
1137                                   struct packed_git *p,
1138                                   off_t obj_offset)
1139{
1140        int type;
1141        struct revindex_entry *revidx;
1142        struct object_id oid;
1143        revidx = find_pack_revindex(p, obj_offset);
1144        if (!revidx)
1145                return OBJ_BAD;
1146        nth_packed_object_oid(&oid, p, revidx->nr);
1147        mark_bad_packed_object(p, oid.hash);
1148        type = oid_object_info(r, &oid, NULL);
1149        if (type <= OBJ_NONE)
1150                return OBJ_BAD;
1151        return type;
1152}
1153
1154#define POI_STACK_PREALLOC 64
1155
1156static enum object_type packed_to_object_type(struct repository *r,
1157                                              struct packed_git *p,
1158                                              off_t obj_offset,
1159                                              enum object_type type,
1160                                              struct pack_window **w_curs,
1161                                              off_t curpos)
1162{
1163        off_t small_poi_stack[POI_STACK_PREALLOC];
1164        off_t *poi_stack = small_poi_stack;
1165        int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1166
1167        while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1168                off_t base_offset;
1169                unsigned long size;
1170                /* Push the object we're going to leave behind */
1171                if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1172                        poi_stack_alloc = alloc_nr(poi_stack_nr);
1173                        ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1174                        memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1175                } else {
1176                        ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1177                }
1178                poi_stack[poi_stack_nr++] = obj_offset;
1179                /* If parsing the base offset fails, just unwind */
1180                base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1181                if (!base_offset)
1182                        goto unwind;
1183                curpos = obj_offset = base_offset;
1184                type = unpack_object_header(p, w_curs, &curpos, &size);
1185                if (type <= OBJ_NONE) {
1186                        /* If getting the base itself fails, we first
1187                         * retry the base, otherwise unwind */
1188                        type = retry_bad_packed_offset(r, p, base_offset);
1189                        if (type > OBJ_NONE)
1190                                goto out;
1191                        goto unwind;
1192                }
1193        }
1194
1195        switch (type) {
1196        case OBJ_BAD:
1197        case OBJ_COMMIT:
1198        case OBJ_TREE:
1199        case OBJ_BLOB:
1200        case OBJ_TAG:
1201                break;
1202        default:
1203                error("unknown object type %i at offset %"PRIuMAX" in %s",
1204                      type, (uintmax_t)obj_offset, p->pack_name);
1205                type = OBJ_BAD;
1206        }
1207
1208out:
1209        if (poi_stack != small_poi_stack)
1210                free(poi_stack);
1211        return type;
1212
1213unwind:
1214        while (poi_stack_nr) {
1215                obj_offset = poi_stack[--poi_stack_nr];
1216                type = retry_bad_packed_offset(r, p, obj_offset);
1217                if (type > OBJ_NONE)
1218                        goto out;
1219        }
1220        type = OBJ_BAD;
1221        goto out;
1222}
1223
1224static struct hashmap delta_base_cache;
1225static size_t delta_base_cached;
1226
1227static LIST_HEAD(delta_base_cache_lru);
1228
1229struct delta_base_cache_key {
1230        struct packed_git *p;
1231        off_t base_offset;
1232};
1233
1234struct delta_base_cache_entry {
1235        struct hashmap hash;
1236        struct delta_base_cache_key key;
1237        struct list_head lru;
1238        void *data;
1239        unsigned long size;
1240        enum object_type type;
1241};
1242
1243static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1244{
1245        unsigned int hash;
1246
1247        hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1248        hash += (hash >> 8) + (hash >> 16);
1249        return hash;
1250}
1251
1252static struct delta_base_cache_entry *
1253get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1254{
1255        struct hashmap_entry entry;
1256        struct delta_base_cache_key key;
1257
1258        if (!delta_base_cache.cmpfn)
1259                return NULL;
1260
1261        hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1262        key.p = p;
1263        key.base_offset = base_offset;
1264        return hashmap_get(&delta_base_cache, &entry, &key);
1265}
1266
1267static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1268                                   const struct delta_base_cache_key *b)
1269{
1270        return a->p == b->p && a->base_offset == b->base_offset;
1271}
1272
1273static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1274                                     const void *va, const void *vb,
1275                                     const void *vkey)
1276{
1277        const struct delta_base_cache_entry *a = va, *b = vb;
1278        const struct delta_base_cache_key *key = vkey;
1279        if (key)
1280                return !delta_base_cache_key_eq(&a->key, key);
1281        else
1282                return !delta_base_cache_key_eq(&a->key, &b->key);
1283}
1284
1285static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1286{
1287        return !!get_delta_base_cache_entry(p, base_offset);
1288}
1289
1290/*
1291 * Remove the entry from the cache, but do _not_ free the associated
1292 * entry data. The caller takes ownership of the "data" buffer, and
1293 * should copy out any fields it wants before detaching.
1294 */
1295static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1296{
1297        hashmap_remove(&delta_base_cache, ent, &ent->key);
1298        list_del(&ent->lru);
1299        delta_base_cached -= ent->size;
1300        free(ent);
1301}
1302
1303static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1304                                   off_t base_offset, unsigned long *base_size,
1305                                   enum object_type *type)
1306{
1307        struct delta_base_cache_entry *ent;
1308
1309        ent = get_delta_base_cache_entry(p, base_offset);
1310        if (!ent)
1311                return unpack_entry(r, p, base_offset, type, base_size);
1312
1313        if (type)
1314                *type = ent->type;
1315        if (base_size)
1316                *base_size = ent->size;
1317        return xmemdupz(ent->data, ent->size);
1318}
1319
1320static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1321{
1322        free(ent->data);
1323        detach_delta_base_cache_entry(ent);
1324}
1325
1326void clear_delta_base_cache(void)
1327{
1328        struct list_head *lru, *tmp;
1329        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1330                struct delta_base_cache_entry *entry =
1331                        list_entry(lru, struct delta_base_cache_entry, lru);
1332                release_delta_base_cache(entry);
1333        }
1334}
1335
1336static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1337        void *base, unsigned long base_size, enum object_type type)
1338{
1339        struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
1340        struct list_head *lru, *tmp;
1341
1342        delta_base_cached += base_size;
1343
1344        list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1345                struct delta_base_cache_entry *f =
1346                        list_entry(lru, struct delta_base_cache_entry, lru);
1347                if (delta_base_cached <= delta_base_cache_limit)
1348                        break;
1349                release_delta_base_cache(f);
1350        }
1351
1352        ent->key.p = p;
1353        ent->key.base_offset = base_offset;
1354        ent->type = type;
1355        ent->data = base;
1356        ent->size = base_size;
1357        list_add_tail(&ent->lru, &delta_base_cache_lru);
1358
1359        if (!delta_base_cache.cmpfn)
1360                hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1361        hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
1362        hashmap_add(&delta_base_cache, ent);
1363}
1364
1365int packed_object_info(struct repository *r, struct packed_git *p,
1366                       off_t obj_offset, struct object_info *oi)
1367{
1368        struct pack_window *w_curs = NULL;
1369        unsigned long size;
1370        off_t curpos = obj_offset;
1371        enum object_type type;
1372
1373        /*
1374         * We always get the representation type, but only convert it to
1375         * a "real" type later if the caller is interested.
1376         */
1377        if (oi->contentp) {
1378                *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1379                                                      &type);
1380                if (!*oi->contentp)
1381                        type = OBJ_BAD;
1382        } else {
1383                type = unpack_object_header(p, &w_curs, &curpos, &size);
1384        }
1385
1386        if (!oi->contentp && oi->sizep) {
1387                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1388                        off_t tmp_pos = curpos;
1389                        off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1390                                                           type, obj_offset);
1391                        if (!base_offset) {
1392                                type = OBJ_BAD;
1393                                goto out;
1394                        }
1395                        *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1396                        if (*oi->sizep == 0) {
1397                                type = OBJ_BAD;
1398                                goto out;
1399                        }
1400                } else {
1401                        *oi->sizep = size;
1402                }
1403        }
1404
1405        if (oi->disk_sizep) {
1406                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1407                *oi->disk_sizep = revidx[1].offset - obj_offset;
1408        }
1409
1410        if (oi->typep || oi->type_name) {
1411                enum object_type ptot;
1412                ptot = packed_to_object_type(r, p, obj_offset,
1413                                             type, &w_curs, curpos);
1414                if (oi->typep)
1415                        *oi->typep = ptot;
1416                if (oi->type_name) {
1417                        const char *tn = type_name(ptot);
1418                        if (tn)
1419                                strbuf_addstr(oi->type_name, tn);
1420                }
1421                if (ptot < 0) {
1422                        type = OBJ_BAD;
1423                        goto out;
1424                }
1425        }
1426
1427        if (oi->delta_base_sha1) {
1428                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1429                        const unsigned char *base;
1430
1431                        base = get_delta_base_sha1(p, &w_curs, curpos,
1432                                                   type, obj_offset);
1433                        if (!base) {
1434                                type = OBJ_BAD;
1435                                goto out;
1436                        }
1437
1438                        hashcpy(oi->delta_base_sha1, base);
1439                } else
1440                        hashclr(oi->delta_base_sha1);
1441        }
1442
1443        oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1444                                                          OI_PACKED;
1445
1446out:
1447        unuse_pack(&w_curs);
1448        return type;
1449}
1450
1451static void *unpack_compressed_entry(struct packed_git *p,
1452                                    struct pack_window **w_curs,
1453                                    off_t curpos,
1454                                    unsigned long size)
1455{
1456        int st;
1457        git_zstream stream;
1458        unsigned char *buffer, *in;
1459
1460        buffer = xmallocz_gently(size);
1461        if (!buffer)
1462                return NULL;
1463        memset(&stream, 0, sizeof(stream));
1464        stream.next_out = buffer;
1465        stream.avail_out = size + 1;
1466
1467        git_inflate_init(&stream);
1468        do {
1469                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1470                stream.next_in = in;
1471                st = git_inflate(&stream, Z_FINISH);
1472                if (!stream.avail_out)
1473                        break; /* the payload is larger than it should be */
1474                curpos += stream.next_in - in;
1475        } while (st == Z_OK || st == Z_BUF_ERROR);
1476        git_inflate_end(&stream);
1477        if ((st != Z_STREAM_END) || stream.total_out != size) {
1478                free(buffer);
1479                return NULL;
1480        }
1481
1482        /* versions of zlib can clobber unconsumed portion of outbuf */
1483        buffer[size] = '\0';
1484
1485        return buffer;
1486}
1487
1488static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1489{
1490        static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1491        trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1492                         p->pack_name, (uintmax_t)obj_offset);
1493}
1494
1495int do_check_packed_object_crc;
1496
1497#define UNPACK_ENTRY_STACK_PREALLOC 64
1498struct unpack_entry_stack_ent {
1499        off_t obj_offset;
1500        off_t curpos;
1501        unsigned long size;
1502};
1503
1504static void *read_object(struct repository *r,
1505                         const struct object_id *oid,
1506                         enum object_type *type,
1507                         unsigned long *size)
1508{
1509        struct object_info oi = OBJECT_INFO_INIT;
1510        void *content;
1511        oi.typep = type;
1512        oi.sizep = size;
1513        oi.contentp = &content;
1514
1515        if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1516                return NULL;
1517        return content;
1518}
1519
1520void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1521                   enum object_type *final_type, unsigned long *final_size)
1522{
1523        struct pack_window *w_curs = NULL;
1524        off_t curpos = obj_offset;
1525        void *data = NULL;
1526        unsigned long size;
1527        enum object_type type;
1528        struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1529        struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1530        int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1531        int base_from_cache = 0;
1532
1533        write_pack_access_log(p, obj_offset);
1534
1535        /* PHASE 1: drill down to the innermost base object */
1536        for (;;) {
1537                off_t base_offset;
1538                int i;
1539                struct delta_base_cache_entry *ent;
1540
1541                ent = get_delta_base_cache_entry(p, curpos);
1542                if (ent) {
1543                        type = ent->type;
1544                        data = ent->data;
1545                        size = ent->size;
1546                        detach_delta_base_cache_entry(ent);
1547                        base_from_cache = 1;
1548                        break;
1549                }
1550
1551                if (do_check_packed_object_crc && p->index_version > 1) {
1552                        struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1553                        off_t len = revidx[1].offset - obj_offset;
1554                        if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1555                                struct object_id oid;
1556                                nth_packed_object_oid(&oid, p, revidx->nr);
1557                                error("bad packed object CRC for %s",
1558                                      oid_to_hex(&oid));
1559                                mark_bad_packed_object(p, oid.hash);
1560                                data = NULL;
1561                                goto out;
1562                        }
1563                }
1564
1565                type = unpack_object_header(p, &w_curs, &curpos, &size);
1566                if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1567                        break;
1568
1569                base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1570                if (!base_offset) {
1571                        error("failed to validate delta base reference "
1572                              "at offset %"PRIuMAX" from %s",
1573                              (uintmax_t)curpos, p->pack_name);
1574                        /* bail to phase 2, in hopes of recovery */
1575                        data = NULL;
1576                        break;
1577                }
1578
1579                /* push object, proceed to base */
1580                if (delta_stack_nr >= delta_stack_alloc
1581                    && delta_stack == small_delta_stack) {
1582                        delta_stack_alloc = alloc_nr(delta_stack_nr);
1583                        ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1584                        memcpy(delta_stack, small_delta_stack,
1585                               sizeof(*delta_stack)*delta_stack_nr);
1586                } else {
1587                        ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1588                }
1589                i = delta_stack_nr++;
1590                delta_stack[i].obj_offset = obj_offset;
1591                delta_stack[i].curpos = curpos;
1592                delta_stack[i].size = size;
1593
1594                curpos = obj_offset = base_offset;
1595        }
1596
1597        /* PHASE 2: handle the base */
1598        switch (type) {
1599        case OBJ_OFS_DELTA:
1600        case OBJ_REF_DELTA:
1601                if (data)
1602                        BUG("unpack_entry: left loop at a valid delta");
1603                break;
1604        case OBJ_COMMIT:
1605        case OBJ_TREE:
1606        case OBJ_BLOB:
1607        case OBJ_TAG:
1608                if (!base_from_cache)
1609                        data = unpack_compressed_entry(p, &w_curs, curpos, size);
1610                break;
1611        default:
1612                data = NULL;
1613                error("unknown object type %i at offset %"PRIuMAX" in %s",
1614                      type, (uintmax_t)obj_offset, p->pack_name);
1615        }
1616
1617        /* PHASE 3: apply deltas in order */
1618
1619        /* invariants:
1620         *   'data' holds the base data, or NULL if there was corruption
1621         */
1622        while (delta_stack_nr) {
1623                void *delta_data;
1624                void *base = data;
1625                void *external_base = NULL;
1626                unsigned long delta_size, base_size = size;
1627                int i;
1628
1629                data = NULL;
1630
1631                if (base)
1632                        add_delta_base_cache(p, obj_offset, base, base_size, type);
1633
1634                if (!base) {
1635                        /*
1636                         * We're probably in deep shit, but let's try to fetch
1637                         * the required base anyway from another pack or loose.
1638                         * This is costly but should happen only in the presence
1639                         * of a corrupted pack, and is better than failing outright.
1640                         */
1641                        struct revindex_entry *revidx;
1642                        struct object_id base_oid;
1643                        revidx = find_pack_revindex(p, obj_offset);
1644                        if (revidx) {
1645                                nth_packed_object_oid(&base_oid, p, revidx->nr);
1646                                error("failed to read delta base object %s"
1647                                      " at offset %"PRIuMAX" from %s",
1648                                      oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1649                                      p->pack_name);
1650                                mark_bad_packed_object(p, base_oid.hash);
1651                                base = read_object(r, &base_oid, &type, &base_size);
1652                                external_base = base;
1653                        }
1654                }
1655
1656                i = --delta_stack_nr;
1657                obj_offset = delta_stack[i].obj_offset;
1658                curpos = delta_stack[i].curpos;
1659                delta_size = delta_stack[i].size;
1660
1661                if (!base)
1662                        continue;
1663
1664                delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1665
1666                if (!delta_data) {
1667                        error("failed to unpack compressed delta "
1668                              "at offset %"PRIuMAX" from %s",
1669                              (uintmax_t)curpos, p->pack_name);
1670                        data = NULL;
1671                        free(external_base);
1672                        continue;
1673                }
1674
1675                data = patch_delta(base, base_size,
1676                                   delta_data, delta_size,
1677                                   &size);
1678
1679                /*
1680                 * We could not apply the delta; warn the user, but keep going.
1681                 * Our failure will be noticed either in the next iteration of
1682                 * the loop, or if this is the final delta, in the caller when
1683                 * we return NULL. Those code paths will take care of making
1684                 * a more explicit warning and retrying with another copy of
1685                 * the object.
1686                 */
1687                if (!data)
1688                        error("failed to apply delta");
1689
1690                free(delta_data);
1691                free(external_base);
1692        }
1693
1694        if (final_type)
1695                *final_type = type;
1696        if (final_size)
1697                *final_size = size;
1698
1699out:
1700        unuse_pack(&w_curs);
1701
1702        if (delta_stack != small_delta_stack)
1703                free(delta_stack);
1704
1705        return data;
1706}
1707
1708int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1709{
1710        const unsigned char *index_fanout = p->index_data;
1711        const unsigned char *index_lookup;
1712        const unsigned int hashsz = the_hash_algo->rawsz;
1713        int index_lookup_width;
1714
1715        if (!index_fanout)
1716                BUG("bsearch_pack called without a valid pack-index");
1717
1718        index_lookup = index_fanout + 4 * 256;
1719        if (p->index_version == 1) {
1720                index_lookup_width = hashsz + 4;
1721                index_lookup += 4;
1722        } else {
1723                index_lookup_width = hashsz;
1724                index_fanout += 8;
1725                index_lookup += 8;
1726        }
1727
1728        return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1729                            index_lookup, index_lookup_width, result);
1730}
1731
1732const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1733                                            uint32_t n)
1734{
1735        const unsigned char *index = p->index_data;
1736        const unsigned int hashsz = the_hash_algo->rawsz;
1737        if (!index) {
1738                if (open_pack_index(p))
1739                        return NULL;
1740                index = p->index_data;
1741        }
1742        if (n >= p->num_objects)
1743                return NULL;
1744        index += 4 * 256;
1745        if (p->index_version == 1) {
1746                return index + (hashsz + 4) * n + 4;
1747        } else {
1748                index += 8;
1749                return index + hashsz * n;
1750        }
1751}
1752
1753const struct object_id *nth_packed_object_oid(struct object_id *oid,
1754                                              struct packed_git *p,
1755                                              uint32_t n)
1756{
1757        const unsigned char *hash = nth_packed_object_sha1(p, n);
1758        if (!hash)
1759                return NULL;
1760        hashcpy(oid->hash, hash);
1761        return oid;
1762}
1763
1764void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1765{
1766        const unsigned char *ptr = vptr;
1767        const unsigned char *start = p->index_data;
1768        const unsigned char *end = start + p->index_size;
1769        if (ptr < start)
1770                die(_("offset before start of pack index for %s (corrupt index?)"),
1771                    p->pack_name);
1772        /* No need to check for underflow; .idx files must be at least 8 bytes */
1773        if (ptr >= end - 8)
1774                die(_("offset beyond end of pack index for %s (truncated index?)"),
1775                    p->pack_name);
1776}
1777
1778off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1779{
1780        const unsigned char *index = p->index_data;
1781        const unsigned int hashsz = the_hash_algo->rawsz;
1782        index += 4 * 256;
1783        if (p->index_version == 1) {
1784                return ntohl(*((uint32_t *)(index + (hashsz + 4) * n)));
1785        } else {
1786                uint32_t off;
1787                index += 8 + p->num_objects * (hashsz + 4);
1788                off = ntohl(*((uint32_t *)(index + 4 * n)));
1789                if (!(off & 0x80000000))
1790                        return off;
1791                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1792                check_pack_index_ptr(p, index);
1793                return get_be64(index);
1794        }
1795}
1796
1797off_t find_pack_entry_one(const unsigned char *sha1,
1798                                  struct packed_git *p)
1799{
1800        const unsigned char *index = p->index_data;
1801        struct object_id oid;
1802        uint32_t result;
1803
1804        if (!index) {
1805                if (open_pack_index(p))
1806                        return 0;
1807        }
1808
1809        hashcpy(oid.hash, sha1);
1810        if (bsearch_pack(&oid, p, &result))
1811                return nth_packed_object_offset(p, result);
1812        return 0;
1813}
1814
1815int is_pack_valid(struct packed_git *p)
1816{
1817        /* An already open pack is known to be valid. */
1818        if (p->pack_fd != -1)
1819                return 1;
1820
1821        /* If the pack has one window completely covering the
1822         * file size, the pack is known to be valid even if
1823         * the descriptor is not currently open.
1824         */
1825        if (p->windows) {
1826                struct pack_window *w = p->windows;
1827
1828                if (!w->offset && w->len == p->pack_size)
1829                        return 1;
1830        }
1831
1832        /* Force the pack to open to prove its valid. */
1833        return !open_packed_git(p);
1834}
1835
1836struct packed_git *find_sha1_pack(const unsigned char *sha1,
1837                                  struct packed_git *packs)
1838{
1839        struct packed_git *p;
1840
1841        for (p = packs; p; p = p->next) {
1842                if (find_pack_entry_one(sha1, p))
1843                        return p;
1844        }
1845        return NULL;
1846
1847}
1848
1849static int fill_pack_entry(const struct object_id *oid,
1850                           struct pack_entry *e,
1851                           struct packed_git *p)
1852{
1853        off_t offset;
1854
1855        if (p->num_bad_objects) {
1856                unsigned i;
1857                for (i = 0; i < p->num_bad_objects; i++)
1858                        if (!hashcmp(oid->hash,
1859                                     p->bad_object_sha1 + the_hash_algo->rawsz * i))
1860                                return 0;
1861        }
1862
1863        offset = find_pack_entry_one(oid->hash, p);
1864        if (!offset)
1865                return 0;
1866
1867        /*
1868         * We are about to tell the caller where they can locate the
1869         * requested object.  We better make sure the packfile is
1870         * still here and can be accessed before supplying that
1871         * answer, as it may have been deleted since the index was
1872         * loaded!
1873         */
1874        if (!is_pack_valid(p))
1875                return 0;
1876        e->offset = offset;
1877        e->p = p;
1878        return 1;
1879}
1880
1881int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
1882{
1883        struct list_head *pos;
1884
1885        prepare_packed_git(r);
1886        if (!r->objects->packed_git)
1887                return 0;
1888
1889        list_for_each(pos, &r->objects->packed_git_mru) {
1890                struct packed_git *p = list_entry(pos, struct packed_git, mru);
1891                if (fill_pack_entry(oid, e, p)) {
1892                        list_move(&p->mru, &r->objects->packed_git_mru);
1893                        return 1;
1894                }
1895        }
1896        return 0;
1897}
1898
1899int has_object_pack(const struct object_id *oid)
1900{
1901        struct pack_entry e;
1902        return find_pack_entry(the_repository, oid, &e);
1903}
1904
1905int has_pack_index(const unsigned char *sha1)
1906{
1907        struct stat st;
1908        if (stat(sha1_pack_index_name(sha1), &st))
1909                return 0;
1910        return 1;
1911}
1912
1913int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
1914{
1915        uint32_t i;
1916        int r = 0;
1917
1918        for (i = 0; i < p->num_objects; i++) {
1919                struct object_id oid;
1920
1921                if (!nth_packed_object_oid(&oid, p, i))
1922                        return error("unable to get sha1 of object %u in %s",
1923                                     i, p->pack_name);
1924
1925                r = cb(&oid, p, i, data);
1926                if (r)
1927                        break;
1928        }
1929        return r;
1930}
1931
1932int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
1933{
1934        struct packed_git *p;
1935        int r = 0;
1936        int pack_errors = 0;
1937
1938        prepare_packed_git(the_repository);
1939        for (p = the_repository->objects->packed_git; p; p = p->next) {
1940                if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
1941                        continue;
1942                if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
1943                    !p->pack_promisor)
1944                        continue;
1945                if (open_pack_index(p)) {
1946                        pack_errors = 1;
1947                        continue;
1948                }
1949                r = for_each_object_in_pack(p, cb, data);
1950                if (r)
1951                        break;
1952        }
1953        return r ? r : pack_errors;
1954}
1955
1956static int add_promisor_object(const struct object_id *oid,
1957                               struct packed_git *pack,
1958                               uint32_t pos,
1959                               void *set_)
1960{
1961        struct oidset *set = set_;
1962        struct object *obj = parse_object(oid);
1963        if (!obj)
1964                return 1;
1965
1966        oidset_insert(set, oid);
1967
1968        /*
1969         * If this is a tree, commit, or tag, the objects it refers
1970         * to are also promisor objects. (Blobs refer to no objects->)
1971         */
1972        if (obj->type == OBJ_TREE) {
1973                struct tree *tree = (struct tree *)obj;
1974                struct tree_desc desc;
1975                struct name_entry entry;
1976                if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
1977                        /*
1978                         * Error messages are given when packs are
1979                         * verified, so do not print any here.
1980                         */
1981                        return 0;
1982                while (tree_entry_gently(&desc, &entry))
1983                        oidset_insert(set, entry.oid);
1984        } else if (obj->type == OBJ_COMMIT) {
1985                struct commit *commit = (struct commit *) obj;
1986                struct commit_list *parents = commit->parents;
1987
1988                oidset_insert(set, get_commit_tree_oid(commit));
1989                for (; parents; parents = parents->next)
1990                        oidset_insert(set, &parents->item->object.oid);
1991        } else if (obj->type == OBJ_TAG) {
1992                struct tag *tag = (struct tag *) obj;
1993                oidset_insert(set, &tag->tagged->oid);
1994        }
1995        return 0;
1996}
1997
1998int is_promisor_object(const struct object_id *oid)
1999{
2000        static struct oidset promisor_objects;
2001        static int promisor_objects_prepared;
2002
2003        if (!promisor_objects_prepared) {
2004                if (repository_format_partial_clone) {
2005                        for_each_packed_object(add_promisor_object,
2006                                               &promisor_objects,
2007                                               FOR_EACH_OBJECT_PROMISOR_ONLY);
2008                }
2009                promisor_objects_prepared = 1;
2010        }
2011        return oidset_contains(&promisor_objects, oid);
2012}