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