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