sha1_file.con commit diff: teach diff to display submodule difference with an inline diff (fd47ae6)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 *
   6 * This handles basic git sha1 object files - packing, unpacking,
   7 * creation etc.
   8 */
   9#include "cache.h"
  10#include "string-list.h"
  11#include "lockfile.h"
  12#include "delta.h"
  13#include "pack.h"
  14#include "blob.h"
  15#include "commit.h"
  16#include "run-command.h"
  17#include "tag.h"
  18#include "tree.h"
  19#include "tree-walk.h"
  20#include "refs.h"
  21#include "pack-revindex.h"
  22#include "sha1-lookup.h"
  23#include "bulk-checkin.h"
  24#include "streaming.h"
  25#include "dir.h"
  26#include "mru.h"
  27
  28#ifndef O_NOATIME
  29#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  30#define O_NOATIME 01000000
  31#else
  32#define O_NOATIME 0
  33#endif
  34#endif
  35
  36#define SZ_FMT PRIuMAX
  37static inline uintmax_t sz_fmt(size_t s) { return s; }
  38
  39const unsigned char null_sha1[20];
  40const struct object_id null_oid;
  41const struct object_id empty_tree_oid = {
  42        EMPTY_TREE_SHA1_BIN_LITERAL
  43};
  44const struct object_id empty_blob_oid = {
  45        EMPTY_BLOB_SHA1_BIN_LITERAL
  46};
  47
  48/*
  49 * This is meant to hold a *small* number of objects that you would
  50 * want read_sha1_file() to be able to return, but yet you do not want
  51 * to write them into the object store (e.g. a browse-only
  52 * application).
  53 */
  54static struct cached_object {
  55        unsigned char sha1[20];
  56        enum object_type type;
  57        void *buf;
  58        unsigned long size;
  59} *cached_objects;
  60static int cached_object_nr, cached_object_alloc;
  61
  62static struct cached_object empty_tree = {
  63        EMPTY_TREE_SHA1_BIN_LITERAL,
  64        OBJ_TREE,
  65        "",
  66        0
  67};
  68
  69static struct cached_object *find_cached_object(const unsigned char *sha1)
  70{
  71        int i;
  72        struct cached_object *co = cached_objects;
  73
  74        for (i = 0; i < cached_object_nr; i++, co++) {
  75                if (!hashcmp(co->sha1, sha1))
  76                        return co;
  77        }
  78        if (!hashcmp(sha1, empty_tree.sha1))
  79                return &empty_tree;
  80        return NULL;
  81}
  82
  83int mkdir_in_gitdir(const char *path)
  84{
  85        if (mkdir(path, 0777)) {
  86                int saved_errno = errno;
  87                struct stat st;
  88                struct strbuf sb = STRBUF_INIT;
  89
  90                if (errno != EEXIST)
  91                        return -1;
  92                /*
  93                 * Are we looking at a path in a symlinked worktree
  94                 * whose original repository does not yet have it?
  95                 * e.g. .git/rr-cache pointing at its original
  96                 * repository in which the user hasn't performed any
  97                 * conflict resolution yet?
  98                 */
  99                if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
 100                    strbuf_readlink(&sb, path, st.st_size) ||
 101                    !is_absolute_path(sb.buf) ||
 102                    mkdir(sb.buf, 0777)) {
 103                        strbuf_release(&sb);
 104                        errno = saved_errno;
 105                        return -1;
 106                }
 107                strbuf_release(&sb);
 108        }
 109        return adjust_shared_perm(path);
 110}
 111
 112enum scld_error safe_create_leading_directories(char *path)
 113{
 114        char *next_component = path + offset_1st_component(path);
 115        enum scld_error ret = SCLD_OK;
 116
 117        while (ret == SCLD_OK && next_component) {
 118                struct stat st;
 119                char *slash = next_component, slash_character;
 120
 121                while (*slash && !is_dir_sep(*slash))
 122                        slash++;
 123
 124                if (!*slash)
 125                        break;
 126
 127                next_component = slash + 1;
 128                while (is_dir_sep(*next_component))
 129                        next_component++;
 130                if (!*next_component)
 131                        break;
 132
 133                slash_character = *slash;
 134                *slash = '\0';
 135                if (!stat(path, &st)) {
 136                        /* path exists */
 137                        if (!S_ISDIR(st.st_mode))
 138                                ret = SCLD_EXISTS;
 139                } else if (mkdir(path, 0777)) {
 140                        if (errno == EEXIST &&
 141                            !stat(path, &st) && S_ISDIR(st.st_mode))
 142                                ; /* somebody created it since we checked */
 143                        else if (errno == ENOENT)
 144                                /*
 145                                 * Either mkdir() failed because
 146                                 * somebody just pruned the containing
 147                                 * directory, or stat() failed because
 148                                 * the file that was in our way was
 149                                 * just removed.  Either way, inform
 150                                 * the caller that it might be worth
 151                                 * trying again:
 152                                 */
 153                                ret = SCLD_VANISHED;
 154                        else
 155                                ret = SCLD_FAILED;
 156                } else if (adjust_shared_perm(path)) {
 157                        ret = SCLD_PERMS;
 158                }
 159                *slash = slash_character;
 160        }
 161        return ret;
 162}
 163
 164enum scld_error safe_create_leading_directories_const(const char *path)
 165{
 166        /* path points to cache entries, so xstrdup before messing with it */
 167        char *buf = xstrdup(path);
 168        enum scld_error result = safe_create_leading_directories(buf);
 169        free(buf);
 170        return result;
 171}
 172
 173static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 174{
 175        int i;
 176        for (i = 0; i < 20; i++) {
 177                static char hex[] = "0123456789abcdef";
 178                unsigned int val = sha1[i];
 179                char *pos = pathbuf + i*2 + (i > 0);
 180                *pos++ = hex[val >> 4];
 181                *pos = hex[val & 0xf];
 182        }
 183}
 184
 185const char *sha1_file_name(const unsigned char *sha1)
 186{
 187        static char buf[PATH_MAX];
 188        const char *objdir;
 189        int len;
 190
 191        objdir = get_object_directory();
 192        len = strlen(objdir);
 193
 194        /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
 195        if (len + 43 > PATH_MAX)
 196                die("insanely long object directory %s", objdir);
 197        memcpy(buf, objdir, len);
 198        buf[len] = '/';
 199        buf[len+3] = '/';
 200        buf[len+42] = '\0';
 201        fill_sha1_path(buf + len + 1, sha1);
 202        return buf;
 203}
 204
 205/*
 206 * Return the name of the pack or index file with the specified sha1
 207 * in its filename.  *base and *name are scratch space that must be
 208 * provided by the caller.  which should be "pack" or "idx".
 209 */
 210static char *sha1_get_pack_name(const unsigned char *sha1,
 211                                struct strbuf *buf,
 212                                const char *which)
 213{
 214        strbuf_reset(buf);
 215        strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
 216                    sha1_to_hex(sha1), which);
 217        return buf->buf;
 218}
 219
 220char *sha1_pack_name(const unsigned char *sha1)
 221{
 222        static struct strbuf buf = STRBUF_INIT;
 223        return sha1_get_pack_name(sha1, &buf, "pack");
 224}
 225
 226char *sha1_pack_index_name(const unsigned char *sha1)
 227{
 228        static struct strbuf buf = STRBUF_INIT;
 229        return sha1_get_pack_name(sha1, &buf, "idx");
 230}
 231
 232struct alternate_object_database *alt_odb_list;
 233static struct alternate_object_database **alt_odb_tail;
 234
 235/*
 236 * Prepare alternate object database registry.
 237 *
 238 * The variable alt_odb_list points at the list of struct
 239 * alternate_object_database.  The elements on this list come from
 240 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 241 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 242 * whose contents is similar to that environment variable but can be
 243 * LF separated.  Its base points at a statically allocated buffer that
 244 * contains "/the/directory/corresponding/to/.git/objects/...", while
 245 * its name points just after the slash at the end of ".git/objects/"
 246 * in the example above, and has enough space to hold 40-byte hex
 247 * SHA1, an extra slash for the first level indirection, and the
 248 * terminating NUL.
 249 */
 250static int link_alt_odb_entry(const char *entry, const char *relative_base,
 251        int depth, const char *normalized_objdir)
 252{
 253        struct alternate_object_database *ent;
 254        struct alternate_object_database *alt;
 255        size_t pfxlen, entlen;
 256        struct strbuf pathbuf = STRBUF_INIT;
 257
 258        if (!is_absolute_path(entry) && relative_base) {
 259                strbuf_addstr(&pathbuf, real_path(relative_base));
 260                strbuf_addch(&pathbuf, '/');
 261        }
 262        strbuf_addstr(&pathbuf, entry);
 263
 264        normalize_path_copy(pathbuf.buf, pathbuf.buf);
 265
 266        pfxlen = strlen(pathbuf.buf);
 267
 268        /*
 269         * The trailing slash after the directory name is given by
 270         * this function at the end. Remove duplicates.
 271         */
 272        while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
 273                pfxlen -= 1;
 274
 275        entlen = st_add(pfxlen, 43); /* '/' + 2 hex + '/' + 38 hex + NUL */
 276        ent = xmalloc(st_add(sizeof(*ent), entlen));
 277        memcpy(ent->base, pathbuf.buf, pfxlen);
 278        strbuf_release(&pathbuf);
 279
 280        ent->name = ent->base + pfxlen + 1;
 281        ent->base[pfxlen + 3] = '/';
 282        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 283
 284        /* Detect cases where alternate disappeared */
 285        if (!is_directory(ent->base)) {
 286                error("object directory %s does not exist; "
 287                      "check .git/objects/info/alternates.",
 288                      ent->base);
 289                free(ent);
 290                return -1;
 291        }
 292
 293        /* Prevent the common mistake of listing the same
 294         * thing twice, or object directory itself.
 295         */
 296        for (alt = alt_odb_list; alt; alt = alt->next) {
 297                if (pfxlen == alt->name - alt->base - 1 &&
 298                    !memcmp(ent->base, alt->base, pfxlen)) {
 299                        free(ent);
 300                        return -1;
 301                }
 302        }
 303        if (!fspathcmp(ent->base, normalized_objdir)) {
 304                free(ent);
 305                return -1;
 306        }
 307
 308        /* add the alternate entry */
 309        *alt_odb_tail = ent;
 310        alt_odb_tail = &(ent->next);
 311        ent->next = NULL;
 312
 313        /* recursively add alternates */
 314        read_info_alternates(ent->base, depth + 1);
 315
 316        ent->base[pfxlen] = '/';
 317
 318        return 0;
 319}
 320
 321static void link_alt_odb_entries(const char *alt, int len, int sep,
 322                                 const char *relative_base, int depth)
 323{
 324        struct string_list entries = STRING_LIST_INIT_NODUP;
 325        char *alt_copy;
 326        int i;
 327        struct strbuf objdirbuf = STRBUF_INIT;
 328
 329        if (depth > 5) {
 330                error("%s: ignoring alternate object stores, nesting too deep.",
 331                                relative_base);
 332                return;
 333        }
 334
 335        strbuf_add_absolute_path(&objdirbuf, get_object_directory());
 336        normalize_path_copy(objdirbuf.buf, objdirbuf.buf);
 337
 338        alt_copy = xmemdupz(alt, len);
 339        string_list_split_in_place(&entries, alt_copy, sep, -1);
 340        for (i = 0; i < entries.nr; i++) {
 341                const char *entry = entries.items[i].string;
 342                if (entry[0] == '\0' || entry[0] == '#')
 343                        continue;
 344                if (!is_absolute_path(entry) && depth) {
 345                        error("%s: ignoring relative alternate object store %s",
 346                                        relative_base, entry);
 347                } else {
 348                        link_alt_odb_entry(entry, relative_base, depth, objdirbuf.buf);
 349                }
 350        }
 351        string_list_clear(&entries, 0);
 352        free(alt_copy);
 353        strbuf_release(&objdirbuf);
 354}
 355
 356void read_info_alternates(const char * relative_base, int depth)
 357{
 358        char *map;
 359        size_t mapsz;
 360        struct stat st;
 361        char *path;
 362        int fd;
 363
 364        path = xstrfmt("%s/info/alternates", relative_base);
 365        fd = git_open_noatime(path);
 366        free(path);
 367        if (fd < 0)
 368                return;
 369        if (fstat(fd, &st) || (st.st_size == 0)) {
 370                close(fd);
 371                return;
 372        }
 373        mapsz = xsize_t(st.st_size);
 374        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 375        close(fd);
 376
 377        link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
 378
 379        munmap(map, mapsz);
 380}
 381
 382void add_to_alternates_file(const char *reference)
 383{
 384        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 385        char *alts = git_pathdup("objects/info/alternates");
 386        FILE *in, *out;
 387
 388        hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
 389        out = fdopen_lock_file(lock, "w");
 390        if (!out)
 391                die_errno("unable to fdopen alternates lockfile");
 392
 393        in = fopen(alts, "r");
 394        if (in) {
 395                struct strbuf line = STRBUF_INIT;
 396                int found = 0;
 397
 398                while (strbuf_getline(&line, in) != EOF) {
 399                        if (!strcmp(reference, line.buf)) {
 400                                found = 1;
 401                                break;
 402                        }
 403                        fprintf_or_die(out, "%s\n", line.buf);
 404                }
 405
 406                strbuf_release(&line);
 407                fclose(in);
 408
 409                if (found) {
 410                        rollback_lock_file(lock);
 411                        lock = NULL;
 412                }
 413        }
 414        else if (errno != ENOENT)
 415                die_errno("unable to read alternates file");
 416
 417        if (lock) {
 418                fprintf_or_die(out, "%s\n", reference);
 419                if (commit_lock_file(lock))
 420                        die_errno("unable to move new alternates file into place");
 421                if (alt_odb_tail)
 422                        link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
 423        }
 424        free(alts);
 425}
 426
 427int foreach_alt_odb(alt_odb_fn fn, void *cb)
 428{
 429        struct alternate_object_database *ent;
 430        int r = 0;
 431
 432        prepare_alt_odb();
 433        for (ent = alt_odb_list; ent; ent = ent->next) {
 434                r = fn(ent, cb);
 435                if (r)
 436                        break;
 437        }
 438        return r;
 439}
 440
 441void prepare_alt_odb(void)
 442{
 443        const char *alt;
 444
 445        if (alt_odb_tail)
 446                return;
 447
 448        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 449        if (!alt) alt = "";
 450
 451        alt_odb_tail = &alt_odb_list;
 452        link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
 453
 454        read_info_alternates(get_object_directory(), 0);
 455}
 456
 457/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
 458static int freshen_file(const char *fn)
 459{
 460        struct utimbuf t;
 461        t.actime = t.modtime = time(NULL);
 462        return !utime(fn, &t);
 463}
 464
 465/*
 466 * All of the check_and_freshen functions return 1 if the file exists and was
 467 * freshened (if freshening was requested), 0 otherwise. If they return
 468 * 0, you should not assume that it is safe to skip a write of the object (it
 469 * either does not exist on disk, or has a stale mtime and may be subject to
 470 * pruning).
 471 */
 472static int check_and_freshen_file(const char *fn, int freshen)
 473{
 474        if (access(fn, F_OK))
 475                return 0;
 476        if (freshen && !freshen_file(fn))
 477                return 0;
 478        return 1;
 479}
 480
 481static int check_and_freshen_local(const unsigned char *sha1, int freshen)
 482{
 483        return check_and_freshen_file(sha1_file_name(sha1), freshen);
 484}
 485
 486static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
 487{
 488        struct alternate_object_database *alt;
 489        prepare_alt_odb();
 490        for (alt = alt_odb_list; alt; alt = alt->next) {
 491                fill_sha1_path(alt->name, sha1);
 492                if (check_and_freshen_file(alt->base, freshen))
 493                        return 1;
 494        }
 495        return 0;
 496}
 497
 498static int check_and_freshen(const unsigned char *sha1, int freshen)
 499{
 500        return check_and_freshen_local(sha1, freshen) ||
 501               check_and_freshen_nonlocal(sha1, freshen);
 502}
 503
 504int has_loose_object_nonlocal(const unsigned char *sha1)
 505{
 506        return check_and_freshen_nonlocal(sha1, 0);
 507}
 508
 509static int has_loose_object(const unsigned char *sha1)
 510{
 511        return check_and_freshen(sha1, 0);
 512}
 513
 514static unsigned int pack_used_ctr;
 515static unsigned int pack_mmap_calls;
 516static unsigned int peak_pack_open_windows;
 517static unsigned int pack_open_windows;
 518static unsigned int pack_open_fds;
 519static unsigned int pack_max_fds;
 520static size_t peak_pack_mapped;
 521static size_t pack_mapped;
 522struct packed_git *packed_git;
 523
 524static struct mru packed_git_mru_storage;
 525struct mru *packed_git_mru = &packed_git_mru_storage;
 526
 527void pack_report(void)
 528{
 529        fprintf(stderr,
 530                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
 531                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
 532                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
 533                sz_fmt(getpagesize()),
 534                sz_fmt(packed_git_window_size),
 535                sz_fmt(packed_git_limit));
 536        fprintf(stderr,
 537                "pack_report: pack_used_ctr            = %10u\n"
 538                "pack_report: pack_mmap_calls          = %10u\n"
 539                "pack_report: pack_open_windows        = %10u / %10u\n"
 540                "pack_report: pack_mapped              = "
 541                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
 542                pack_used_ctr,
 543                pack_mmap_calls,
 544                pack_open_windows, peak_pack_open_windows,
 545                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
 546}
 547
 548/*
 549 * Open and mmap the index file at path, perform a couple of
 550 * consistency checks, then record its information to p.  Return 0 on
 551 * success.
 552 */
 553static int check_packed_git_idx(const char *path, struct packed_git *p)
 554{
 555        void *idx_map;
 556        struct pack_idx_header *hdr;
 557        size_t idx_size;
 558        uint32_t version, nr, i, *index;
 559        int fd = git_open_noatime(path);
 560        struct stat st;
 561
 562        if (fd < 0)
 563                return -1;
 564        if (fstat(fd, &st)) {
 565                close(fd);
 566                return -1;
 567        }
 568        idx_size = xsize_t(st.st_size);
 569        if (idx_size < 4 * 256 + 20 + 20) {
 570                close(fd);
 571                return error("index file %s is too small", path);
 572        }
 573        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 574        close(fd);
 575
 576        hdr = idx_map;
 577        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
 578                version = ntohl(hdr->idx_version);
 579                if (version < 2 || version > 2) {
 580                        munmap(idx_map, idx_size);
 581                        return error("index file %s is version %"PRIu32
 582                                     " and is not supported by this binary"
 583                                     " (try upgrading GIT to a newer version)",
 584                                     path, version);
 585                }
 586        } else
 587                version = 1;
 588
 589        nr = 0;
 590        index = idx_map;
 591        if (version > 1)
 592                index += 2;  /* skip index header */
 593        for (i = 0; i < 256; i++) {
 594                uint32_t n = ntohl(index[i]);
 595                if (n < nr) {
 596                        munmap(idx_map, idx_size);
 597                        return error("non-monotonic index %s", path);
 598                }
 599                nr = n;
 600        }
 601
 602        if (version == 1) {
 603                /*
 604                 * Total size:
 605                 *  - 256 index entries 4 bytes each
 606                 *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 607                 *  - 20-byte SHA1 of the packfile
 608                 *  - 20-byte SHA1 file checksum
 609                 */
 610                if (idx_size != 4*256 + nr * 24 + 20 + 20) {
 611                        munmap(idx_map, idx_size);
 612                        return error("wrong index v1 file size in %s", path);
 613                }
 614        } else if (version == 2) {
 615                /*
 616                 * Minimum size:
 617                 *  - 8 bytes of header
 618                 *  - 256 index entries 4 bytes each
 619                 *  - 20-byte sha1 entry * nr
 620                 *  - 4-byte crc entry * nr
 621                 *  - 4-byte offset entry * nr
 622                 *  - 20-byte SHA1 of the packfile
 623                 *  - 20-byte SHA1 file checksum
 624                 * And after the 4-byte offset table might be a
 625                 * variable sized table containing 8-byte entries
 626                 * for offsets larger than 2^31.
 627                 */
 628                unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
 629                unsigned long max_size = min_size;
 630                if (nr)
 631                        max_size += (nr - 1)*8;
 632                if (idx_size < min_size || idx_size > max_size) {
 633                        munmap(idx_map, idx_size);
 634                        return error("wrong index v2 file size in %s", path);
 635                }
 636                if (idx_size != min_size &&
 637                    /*
 638                     * make sure we can deal with large pack offsets.
 639                     * 31-bit signed offset won't be enough, neither
 640                     * 32-bit unsigned one will be.
 641                     */
 642                    (sizeof(off_t) <= 4)) {
 643                        munmap(idx_map, idx_size);
 644                        return error("pack too large for current definition of off_t in %s", path);
 645                }
 646        }
 647
 648        p->index_version = version;
 649        p->index_data = idx_map;
 650        p->index_size = idx_size;
 651        p->num_objects = nr;
 652        return 0;
 653}
 654
 655int open_pack_index(struct packed_git *p)
 656{
 657        char *idx_name;
 658        size_t len;
 659        int ret;
 660
 661        if (p->index_data)
 662                return 0;
 663
 664        if (!strip_suffix(p->pack_name, ".pack", &len))
 665                die("BUG: pack_name does not end in .pack");
 666        idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
 667        ret = check_packed_git_idx(idx_name, p);
 668        free(idx_name);
 669        return ret;
 670}
 671
 672static void scan_windows(struct packed_git *p,
 673        struct packed_git **lru_p,
 674        struct pack_window **lru_w,
 675        struct pack_window **lru_l)
 676{
 677        struct pack_window *w, *w_l;
 678
 679        for (w_l = NULL, w = p->windows; w; w = w->next) {
 680                if (!w->inuse_cnt) {
 681                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 682                                *lru_p = p;
 683                                *lru_w = w;
 684                                *lru_l = w_l;
 685                        }
 686                }
 687                w_l = w;
 688        }
 689}
 690
 691static int unuse_one_window(struct packed_git *current)
 692{
 693        struct packed_git *p, *lru_p = NULL;
 694        struct pack_window *lru_w = NULL, *lru_l = NULL;
 695
 696        if (current)
 697                scan_windows(current, &lru_p, &lru_w, &lru_l);
 698        for (p = packed_git; p; p = p->next)
 699                scan_windows(p, &lru_p, &lru_w, &lru_l);
 700        if (lru_p) {
 701                munmap(lru_w->base, lru_w->len);
 702                pack_mapped -= lru_w->len;
 703                if (lru_l)
 704                        lru_l->next = lru_w->next;
 705                else
 706                        lru_p->windows = lru_w->next;
 707                free(lru_w);
 708                pack_open_windows--;
 709                return 1;
 710        }
 711        return 0;
 712}
 713
 714void release_pack_memory(size_t need)
 715{
 716        size_t cur = pack_mapped;
 717        while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
 718                ; /* nothing */
 719}
 720
 721static void mmap_limit_check(size_t length)
 722{
 723        static size_t limit = 0;
 724        if (!limit) {
 725                limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
 726                if (!limit)
 727                        limit = SIZE_MAX;
 728        }
 729        if (length > limit)
 730                die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
 731                    (uintmax_t)length, (uintmax_t)limit);
 732}
 733
 734void *xmmap_gently(void *start, size_t length,
 735                  int prot, int flags, int fd, off_t offset)
 736{
 737        void *ret;
 738
 739        mmap_limit_check(length);
 740        ret = mmap(start, length, prot, flags, fd, offset);
 741        if (ret == MAP_FAILED) {
 742                if (!length)
 743                        return NULL;
 744                release_pack_memory(length);
 745                ret = mmap(start, length, prot, flags, fd, offset);
 746        }
 747        return ret;
 748}
 749
 750void *xmmap(void *start, size_t length,
 751        int prot, int flags, int fd, off_t offset)
 752{
 753        void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
 754        if (ret == MAP_FAILED)
 755                die_errno("mmap failed");
 756        return ret;
 757}
 758
 759void close_pack_windows(struct packed_git *p)
 760{
 761        while (p->windows) {
 762                struct pack_window *w = p->windows;
 763
 764                if (w->inuse_cnt)
 765                        die("pack '%s' still has open windows to it",
 766                            p->pack_name);
 767                munmap(w->base, w->len);
 768                pack_mapped -= w->len;
 769                pack_open_windows--;
 770                p->windows = w->next;
 771                free(w);
 772        }
 773}
 774
 775static int close_pack_fd(struct packed_git *p)
 776{
 777        if (p->pack_fd < 0)
 778                return 0;
 779
 780        close(p->pack_fd);
 781        pack_open_fds--;
 782        p->pack_fd = -1;
 783
 784        return 1;
 785}
 786
 787static void close_pack(struct packed_git *p)
 788{
 789        close_pack_windows(p);
 790        close_pack_fd(p);
 791        close_pack_index(p);
 792}
 793
 794void close_all_packs(void)
 795{
 796        struct packed_git *p;
 797
 798        for (p = packed_git; p; p = p->next)
 799                if (p->do_not_close)
 800                        die("BUG: want to close pack marked 'do-not-close'");
 801                else
 802                        close_pack(p);
 803}
 804
 805
 806/*
 807 * The LRU pack is the one with the oldest MRU window, preferring packs
 808 * with no used windows, or the oldest mtime if it has no windows allocated.
 809 */
 810static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
 811{
 812        struct pack_window *w, *this_mru_w;
 813        int has_windows_inuse = 0;
 814
 815        /*
 816         * Reject this pack if it has windows and the previously selected
 817         * one does not.  If this pack does not have windows, reject
 818         * it if the pack file is newer than the previously selected one.
 819         */
 820        if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
 821                return;
 822
 823        for (w = this_mru_w = p->windows; w; w = w->next) {
 824                /*
 825                 * Reject this pack if any of its windows are in use,
 826                 * but the previously selected pack did not have any
 827                 * inuse windows.  Otherwise, record that this pack
 828                 * has windows in use.
 829                 */
 830                if (w->inuse_cnt) {
 831                        if (*accept_windows_inuse)
 832                                has_windows_inuse = 1;
 833                        else
 834                                return;
 835                }
 836
 837                if (w->last_used > this_mru_w->last_used)
 838                        this_mru_w = w;
 839
 840                /*
 841                 * Reject this pack if it has windows that have been
 842                 * used more recently than the previously selected pack.
 843                 * If the previously selected pack had windows inuse and
 844                 * we have not encountered a window in this pack that is
 845                 * inuse, skip this check since we prefer a pack with no
 846                 * inuse windows to one that has inuse windows.
 847                 */
 848                if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
 849                    this_mru_w->last_used > (*mru_w)->last_used)
 850                        return;
 851        }
 852
 853        /*
 854         * Select this pack.
 855         */
 856        *mru_w = this_mru_w;
 857        *lru_p = p;
 858        *accept_windows_inuse = has_windows_inuse;
 859}
 860
 861static int close_one_pack(void)
 862{
 863        struct packed_git *p, *lru_p = NULL;
 864        struct pack_window *mru_w = NULL;
 865        int accept_windows_inuse = 1;
 866
 867        for (p = packed_git; p; p = p->next) {
 868                if (p->pack_fd == -1)
 869                        continue;
 870                find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
 871        }
 872
 873        if (lru_p)
 874                return close_pack_fd(lru_p);
 875
 876        return 0;
 877}
 878
 879void unuse_pack(struct pack_window **w_cursor)
 880{
 881        struct pack_window *w = *w_cursor;
 882        if (w) {
 883                w->inuse_cnt--;
 884                *w_cursor = NULL;
 885        }
 886}
 887
 888void close_pack_index(struct packed_git *p)
 889{
 890        if (p->index_data) {
 891                munmap((void *)p->index_data, p->index_size);
 892                p->index_data = NULL;
 893        }
 894}
 895
 896static unsigned int get_max_fd_limit(void)
 897{
 898#ifdef RLIMIT_NOFILE
 899        {
 900                struct rlimit lim;
 901
 902                if (!getrlimit(RLIMIT_NOFILE, &lim))
 903                        return lim.rlim_cur;
 904        }
 905#endif
 906
 907#ifdef _SC_OPEN_MAX
 908        {
 909                long open_max = sysconf(_SC_OPEN_MAX);
 910                if (0 < open_max)
 911                        return open_max;
 912                /*
 913                 * Otherwise, we got -1 for one of the two
 914                 * reasons:
 915                 *
 916                 * (1) sysconf() did not understand _SC_OPEN_MAX
 917                 *     and signaled an error with -1; or
 918                 * (2) sysconf() said there is no limit.
 919                 *
 920                 * We _could_ clear errno before calling sysconf() to
 921                 * tell these two cases apart and return a huge number
 922                 * in the latter case to let the caller cap it to a
 923                 * value that is not so selfish, but letting the
 924                 * fallback OPEN_MAX codepath take care of these cases
 925                 * is a lot simpler.
 926                 */
 927        }
 928#endif
 929
 930#ifdef OPEN_MAX
 931        return OPEN_MAX;
 932#else
 933        return 1; /* see the caller ;-) */
 934#endif
 935}
 936
 937/*
 938 * Do not call this directly as this leaks p->pack_fd on error return;
 939 * call open_packed_git() instead.
 940 */
 941static int open_packed_git_1(struct packed_git *p)
 942{
 943        struct stat st;
 944        struct pack_header hdr;
 945        unsigned char sha1[20];
 946        unsigned char *idx_sha1;
 947        long fd_flag;
 948
 949        if (!p->index_data && open_pack_index(p))
 950                return error("packfile %s index unavailable", p->pack_name);
 951
 952        if (!pack_max_fds) {
 953                unsigned int max_fds = get_max_fd_limit();
 954
 955                /* Save 3 for stdin/stdout/stderr, 22 for work */
 956                if (25 < max_fds)
 957                        pack_max_fds = max_fds - 25;
 958                else
 959                        pack_max_fds = 1;
 960        }
 961
 962        while (pack_max_fds <= pack_open_fds && close_one_pack())
 963                ; /* nothing */
 964
 965        p->pack_fd = git_open_noatime(p->pack_name);
 966        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 967                return -1;
 968        pack_open_fds++;
 969
 970        /* If we created the struct before we had the pack we lack size. */
 971        if (!p->pack_size) {
 972                if (!S_ISREG(st.st_mode))
 973                        return error("packfile %s not a regular file", p->pack_name);
 974                p->pack_size = st.st_size;
 975        } else if (p->pack_size != st.st_size)
 976                return error("packfile %s size changed", p->pack_name);
 977
 978        /* We leave these file descriptors open with sliding mmap;
 979         * there is no point keeping them open across exec(), though.
 980         */
 981        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 982        if (fd_flag < 0)
 983                return error("cannot determine file descriptor flags");
 984        fd_flag |= FD_CLOEXEC;
 985        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 986                return error("cannot set FD_CLOEXEC");
 987
 988        /* Verify we recognize this pack file format. */
 989        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 990                return error("file %s is far too short to be a packfile", p->pack_name);
 991        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 992                return error("file %s is not a GIT packfile", p->pack_name);
 993        if (!pack_version_ok(hdr.hdr_version))
 994                return error("packfile %s is version %"PRIu32" and not"
 995                        " supported (try upgrading GIT to a newer version)",
 996                        p->pack_name, ntohl(hdr.hdr_version));
 997
 998        /* Verify the pack matches its index. */
 999        if (p->num_objects != ntohl(hdr.hdr_entries))
1000                return error("packfile %s claims to have %"PRIu32" objects"
1001                             " while index indicates %"PRIu32" objects",
1002                             p->pack_name, ntohl(hdr.hdr_entries),
1003                             p->num_objects);
1004        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
1005                return error("end of packfile %s is unavailable", p->pack_name);
1006        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
1007                return error("packfile %s signature is unavailable", p->pack_name);
1008        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
1009        if (hashcmp(sha1, idx_sha1))
1010                return error("packfile %s does not match index", p->pack_name);
1011        return 0;
1012}
1013
1014static int open_packed_git(struct packed_git *p)
1015{
1016        if (!open_packed_git_1(p))
1017                return 0;
1018        close_pack_fd(p);
1019        return -1;
1020}
1021
1022static int in_window(struct pack_window *win, off_t offset)
1023{
1024        /* We must promise at least 20 bytes (one hash) after the
1025         * offset is available from this window, otherwise the offset
1026         * is not actually in this window and a different window (which
1027         * has that one hash excess) must be used.  This is to support
1028         * the object header and delta base parsing routines below.
1029         */
1030        off_t win_off = win->offset;
1031        return win_off <= offset
1032                && (offset + 20) <= (win_off + win->len);
1033}
1034
1035unsigned char *use_pack(struct packed_git *p,
1036                struct pack_window **w_cursor,
1037                off_t offset,
1038                unsigned long *left)
1039{
1040        struct pack_window *win = *w_cursor;
1041
1042        /* Since packfiles end in a hash of their content and it's
1043         * pointless to ask for an offset into the middle of that
1044         * hash, and the in_window function above wouldn't match
1045         * don't allow an offset too close to the end of the file.
1046         */
1047        if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1048                die("packfile %s cannot be accessed", p->pack_name);
1049        if (offset > (p->pack_size - 20))
1050                die("offset beyond end of packfile (truncated pack?)");
1051        if (offset < 0)
1052                die(_("offset before end of packfile (broken .idx?)"));
1053
1054        if (!win || !in_window(win, offset)) {
1055                if (win)
1056                        win->inuse_cnt--;
1057                for (win = p->windows; win; win = win->next) {
1058                        if (in_window(win, offset))
1059                                break;
1060                }
1061                if (!win) {
1062                        size_t window_align = packed_git_window_size / 2;
1063                        off_t len;
1064
1065                        if (p->pack_fd == -1 && open_packed_git(p))
1066                                die("packfile %s cannot be accessed", p->pack_name);
1067
1068                        win = xcalloc(1, sizeof(*win));
1069                        win->offset = (offset / window_align) * window_align;
1070                        len = p->pack_size - win->offset;
1071                        if (len > packed_git_window_size)
1072                                len = packed_git_window_size;
1073                        win->len = (size_t)len;
1074                        pack_mapped += win->len;
1075                        while (packed_git_limit < pack_mapped
1076                                && unuse_one_window(p))
1077                                ; /* nothing */
1078                        win->base = xmmap(NULL, win->len,
1079                                PROT_READ, MAP_PRIVATE,
1080                                p->pack_fd, win->offset);
1081                        if (win->base == MAP_FAILED)
1082                                die_errno("packfile %s cannot be mapped",
1083                                          p->pack_name);
1084                        if (!win->offset && win->len == p->pack_size
1085                                && !p->do_not_close)
1086                                close_pack_fd(p);
1087                        pack_mmap_calls++;
1088                        pack_open_windows++;
1089                        if (pack_mapped > peak_pack_mapped)
1090                                peak_pack_mapped = pack_mapped;
1091                        if (pack_open_windows > peak_pack_open_windows)
1092                                peak_pack_open_windows = pack_open_windows;
1093                        win->next = p->windows;
1094                        p->windows = win;
1095                }
1096        }
1097        if (win != *w_cursor) {
1098                win->last_used = pack_used_ctr++;
1099                win->inuse_cnt++;
1100                *w_cursor = win;
1101        }
1102        offset -= win->offset;
1103        if (left)
1104                *left = win->len - xsize_t(offset);
1105        return win->base + offset;
1106}
1107
1108static struct packed_git *alloc_packed_git(int extra)
1109{
1110        struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
1111        memset(p, 0, sizeof(*p));
1112        p->pack_fd = -1;
1113        return p;
1114}
1115
1116static void try_to_free_pack_memory(size_t size)
1117{
1118        release_pack_memory(size);
1119}
1120
1121struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
1122{
1123        static int have_set_try_to_free_routine;
1124        struct stat st;
1125        size_t alloc;
1126        struct packed_git *p;
1127
1128        if (!have_set_try_to_free_routine) {
1129                have_set_try_to_free_routine = 1;
1130                set_try_to_free_routine(try_to_free_pack_memory);
1131        }
1132
1133        /*
1134         * Make sure a corresponding .pack file exists and that
1135         * the index looks sane.
1136         */
1137        if (!strip_suffix_mem(path, &path_len, ".idx"))
1138                return NULL;
1139
1140        /*
1141         * ".pack" is long enough to hold any suffix we're adding (and
1142         * the use xsnprintf double-checks that)
1143         */
1144        alloc = st_add3(path_len, strlen(".pack"), 1);
1145        p = alloc_packed_git(alloc);
1146        memcpy(p->pack_name, path, path_len);
1147
1148        xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
1149        if (!access(p->pack_name, F_OK))
1150                p->pack_keep = 1;
1151
1152        xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
1153        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1154                free(p);
1155                return NULL;
1156        }
1157
1158        /* ok, it looks sane as far as we can check without
1159         * actually mapping the pack file.
1160         */
1161        p->pack_size = st.st_size;
1162        p->pack_local = local;
1163        p->mtime = st.st_mtime;
1164        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1165                hashclr(p->sha1);
1166        return p;
1167}
1168
1169struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1170{
1171        const char *path = sha1_pack_name(sha1);
1172        size_t alloc = st_add(strlen(path), 1);
1173        struct packed_git *p = alloc_packed_git(alloc);
1174
1175        memcpy(p->pack_name, path, alloc); /* includes NUL */
1176        hashcpy(p->sha1, sha1);
1177        if (check_packed_git_idx(idx_path, p)) {
1178                free(p);
1179                return NULL;
1180        }
1181
1182        return p;
1183}
1184
1185void install_packed_git(struct packed_git *pack)
1186{
1187        if (pack->pack_fd != -1)
1188                pack_open_fds++;
1189
1190        pack->next = packed_git;
1191        packed_git = pack;
1192}
1193
1194void (*report_garbage)(unsigned seen_bits, const char *path);
1195
1196static void report_helper(const struct string_list *list,
1197                          int seen_bits, int first, int last)
1198{
1199        if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
1200                return;
1201
1202        for (; first < last; first++)
1203                report_garbage(seen_bits, list->items[first].string);
1204}
1205
1206static void report_pack_garbage(struct string_list *list)
1207{
1208        int i, baselen = -1, first = 0, seen_bits = 0;
1209
1210        if (!report_garbage)
1211                return;
1212
1213        string_list_sort(list);
1214
1215        for (i = 0; i < list->nr; i++) {
1216                const char *path = list->items[i].string;
1217                if (baselen != -1 &&
1218                    strncmp(path, list->items[first].string, baselen)) {
1219                        report_helper(list, seen_bits, first, i);
1220                        baselen = -1;
1221                        seen_bits = 0;
1222                }
1223                if (baselen == -1) {
1224                        const char *dot = strrchr(path, '.');
1225                        if (!dot) {
1226                                report_garbage(PACKDIR_FILE_GARBAGE, path);
1227                                continue;
1228                        }
1229                        baselen = dot - path + 1;
1230                        first = i;
1231                }
1232                if (!strcmp(path + baselen, "pack"))
1233                        seen_bits |= 1;
1234                else if (!strcmp(path + baselen, "idx"))
1235                        seen_bits |= 2;
1236        }
1237        report_helper(list, seen_bits, first, list->nr);
1238}
1239
1240static void prepare_packed_git_one(char *objdir, int local)
1241{
1242        struct strbuf path = STRBUF_INIT;
1243        size_t dirnamelen;
1244        DIR *dir;
1245        struct dirent *de;
1246        struct string_list garbage = STRING_LIST_INIT_DUP;
1247
1248        strbuf_addstr(&path, objdir);
1249        strbuf_addstr(&path, "/pack");
1250        dir = opendir(path.buf);
1251        if (!dir) {
1252                if (errno != ENOENT)
1253                        error_errno("unable to open object pack directory: %s",
1254                                    path.buf);
1255                strbuf_release(&path);
1256                return;
1257        }
1258        strbuf_addch(&path, '/');
1259        dirnamelen = path.len;
1260        while ((de = readdir(dir)) != NULL) {
1261                struct packed_git *p;
1262                size_t base_len;
1263
1264                if (is_dot_or_dotdot(de->d_name))
1265                        continue;
1266
1267                strbuf_setlen(&path, dirnamelen);
1268                strbuf_addstr(&path, de->d_name);
1269
1270                base_len = path.len;
1271                if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1272                        /* Don't reopen a pack we already have. */
1273                        for (p = packed_git; p; p = p->next) {
1274                                size_t len;
1275                                if (strip_suffix(p->pack_name, ".pack", &len) &&
1276                                    len == base_len &&
1277                                    !memcmp(p->pack_name, path.buf, len))
1278                                        break;
1279                        }
1280                        if (p == NULL &&
1281                            /*
1282                             * See if it really is a valid .idx file with
1283                             * corresponding .pack file that we can map.
1284                             */
1285                            (p = add_packed_git(path.buf, path.len, local)) != NULL)
1286                                install_packed_git(p);
1287                }
1288
1289                if (!report_garbage)
1290                        continue;
1291
1292                if (ends_with(de->d_name, ".idx") ||
1293                    ends_with(de->d_name, ".pack") ||
1294                    ends_with(de->d_name, ".bitmap") ||
1295                    ends_with(de->d_name, ".keep"))
1296                        string_list_append(&garbage, path.buf);
1297                else
1298                        report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
1299        }
1300        closedir(dir);
1301        report_pack_garbage(&garbage);
1302        string_list_clear(&garbage, 0);
1303        strbuf_release(&path);
1304}
1305
1306static int sort_pack(const void *a_, const void *b_)
1307{
1308        struct packed_git *a = *((struct packed_git **)a_);
1309        struct packed_git *b = *((struct packed_git **)b_);
1310        int st;
1311
1312        /*
1313         * Local packs tend to contain objects specific to our
1314         * variant of the project than remote ones.  In addition,
1315         * remote ones could be on a network mounted filesystem.
1316         * Favor local ones for these reasons.
1317         */
1318        st = a->pack_local - b->pack_local;
1319        if (st)
1320                return -st;
1321
1322        /*
1323         * Younger packs tend to contain more recent objects,
1324         * and more recent objects tend to get accessed more
1325         * often.
1326         */
1327        if (a->mtime < b->mtime)
1328                return 1;
1329        else if (a->mtime == b->mtime)
1330                return 0;
1331        return -1;
1332}
1333
1334static void rearrange_packed_git(void)
1335{
1336        struct packed_git **ary, *p;
1337        int i, n;
1338
1339        for (n = 0, p = packed_git; p; p = p->next)
1340                n++;
1341        if (n < 2)
1342                return;
1343
1344        /* prepare an array of packed_git for easier sorting */
1345        ary = xcalloc(n, sizeof(struct packed_git *));
1346        for (n = 0, p = packed_git; p; p = p->next)
1347                ary[n++] = p;
1348
1349        qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1350
1351        /* link them back again */
1352        for (i = 0; i < n - 1; i++)
1353                ary[i]->next = ary[i + 1];
1354        ary[n - 1]->next = NULL;
1355        packed_git = ary[0];
1356
1357        free(ary);
1358}
1359
1360static void prepare_packed_git_mru(void)
1361{
1362        struct packed_git *p;
1363
1364        mru_clear(packed_git_mru);
1365        for (p = packed_git; p; p = p->next)
1366                mru_append(packed_git_mru, p);
1367}
1368
1369static int prepare_packed_git_run_once = 0;
1370void prepare_packed_git(void)
1371{
1372        struct alternate_object_database *alt;
1373
1374        if (prepare_packed_git_run_once)
1375                return;
1376        prepare_packed_git_one(get_object_directory(), 1);
1377        prepare_alt_odb();
1378        for (alt = alt_odb_list; alt; alt = alt->next) {
1379                alt->name[-1] = 0;
1380                prepare_packed_git_one(alt->base, 0);
1381                alt->name[-1] = '/';
1382        }
1383        rearrange_packed_git();
1384        prepare_packed_git_mru();
1385        prepare_packed_git_run_once = 1;
1386}
1387
1388void reprepare_packed_git(void)
1389{
1390        prepare_packed_git_run_once = 0;
1391        prepare_packed_git();
1392}
1393
1394static void mark_bad_packed_object(struct packed_git *p,
1395                                   const unsigned char *sha1)
1396{
1397        unsigned i;
1398        for (i = 0; i < p->num_bad_objects; i++)
1399                if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1400                        return;
1401        p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1402                                      st_mult(GIT_SHA1_RAWSZ,
1403                                              st_add(p->num_bad_objects, 1)));
1404        hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1405        p->num_bad_objects++;
1406}
1407
1408static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1409{
1410        struct packed_git *p;
1411        unsigned i;
1412
1413        for (p = packed_git; p; p = p->next)
1414                for (i = 0; i < p->num_bad_objects; i++)
1415                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1416                                return p;
1417        return NULL;
1418}
1419
1420/*
1421 * With an in-core object data in "map", rehash it to make sure the
1422 * object name actually matches "sha1" to detect object corruption.
1423 * With "map" == NULL, try reading the object named with "sha1" using
1424 * the streaming interface and rehash it to do the same.
1425 */
1426int check_sha1_signature(const unsigned char *sha1, void *map,
1427                         unsigned long size, const char *type)
1428{
1429        unsigned char real_sha1[20];
1430        enum object_type obj_type;
1431        struct git_istream *st;
1432        git_SHA_CTX c;
1433        char hdr[32];
1434        int hdrlen;
1435
1436        if (map) {
1437                hash_sha1_file(map, size, type, real_sha1);
1438                return hashcmp(sha1, real_sha1) ? -1 : 0;
1439        }
1440
1441        st = open_istream(sha1, &obj_type, &size, NULL);
1442        if (!st)
1443                return -1;
1444
1445        /* Generate the header */
1446        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1447
1448        /* Sha1.. */
1449        git_SHA1_Init(&c);
1450        git_SHA1_Update(&c, hdr, hdrlen);
1451        for (;;) {
1452                char buf[1024 * 16];
1453                ssize_t readlen = read_istream(st, buf, sizeof(buf));
1454
1455                if (readlen < 0) {
1456                        close_istream(st);
1457                        return -1;
1458                }
1459                if (!readlen)
1460                        break;
1461                git_SHA1_Update(&c, buf, readlen);
1462        }
1463        git_SHA1_Final(real_sha1, &c);
1464        close_istream(st);
1465        return hashcmp(sha1, real_sha1) ? -1 : 0;
1466}
1467
1468int git_open_noatime(const char *name)
1469{
1470        static int sha1_file_open_flag = O_NOATIME;
1471
1472        for (;;) {
1473                int fd;
1474
1475                errno = 0;
1476                fd = open(name, O_RDONLY | sha1_file_open_flag);
1477                if (fd >= 0)
1478                        return fd;
1479
1480                /* Might the failure be due to O_NOATIME? */
1481                if (errno != ENOENT && sha1_file_open_flag) {
1482                        sha1_file_open_flag = 0;
1483                        continue;
1484                }
1485
1486                return -1;
1487        }
1488}
1489
1490static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1491{
1492        struct alternate_object_database *alt;
1493
1494        if (!lstat(sha1_file_name(sha1), st))
1495                return 0;
1496
1497        prepare_alt_odb();
1498        errno = ENOENT;
1499        for (alt = alt_odb_list; alt; alt = alt->next) {
1500                fill_sha1_path(alt->name, sha1);
1501                if (!lstat(alt->base, st))
1502                        return 0;
1503        }
1504
1505        return -1;
1506}
1507
1508static int open_sha1_file(const unsigned char *sha1)
1509{
1510        int fd;
1511        struct alternate_object_database *alt;
1512        int most_interesting_errno;
1513
1514        fd = git_open_noatime(sha1_file_name(sha1));
1515        if (fd >= 0)
1516                return fd;
1517        most_interesting_errno = errno;
1518
1519        prepare_alt_odb();
1520        for (alt = alt_odb_list; alt; alt = alt->next) {
1521                fill_sha1_path(alt->name, sha1);
1522                fd = git_open_noatime(alt->base);
1523                if (fd >= 0)
1524                        return fd;
1525                if (most_interesting_errno == ENOENT)
1526                        most_interesting_errno = errno;
1527        }
1528        errno = most_interesting_errno;
1529        return -1;
1530}
1531
1532void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1533{
1534        void *map;
1535        int fd;
1536
1537        fd = open_sha1_file(sha1);
1538        map = NULL;
1539        if (fd >= 0) {
1540                struct stat st;
1541
1542                if (!fstat(fd, &st)) {
1543                        *size = xsize_t(st.st_size);
1544                        if (!*size) {
1545                                /* mmap() is forbidden on empty files */
1546                                error("object file %s is empty", sha1_file_name(sha1));
1547                                return NULL;
1548                        }
1549                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1550                }
1551                close(fd);
1552        }
1553        return map;
1554}
1555
1556unsigned long unpack_object_header_buffer(const unsigned char *buf,
1557                unsigned long len, enum object_type *type, unsigned long *sizep)
1558{
1559        unsigned shift;
1560        unsigned long size, c;
1561        unsigned long used = 0;
1562
1563        c = buf[used++];
1564        *type = (c >> 4) & 7;
1565        size = c & 15;
1566        shift = 4;
1567        while (c & 0x80) {
1568                if (len <= used || bitsizeof(long) <= shift) {
1569                        error("bad object header");
1570                        size = used = 0;
1571                        break;
1572                }
1573                c = buf[used++];
1574                size += (c & 0x7f) << shift;
1575                shift += 7;
1576        }
1577        *sizep = size;
1578        return used;
1579}
1580
1581int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1582{
1583        /* Get the data stream */
1584        memset(stream, 0, sizeof(*stream));
1585        stream->next_in = map;
1586        stream->avail_in = mapsize;
1587        stream->next_out = buffer;
1588        stream->avail_out = bufsiz;
1589
1590        git_inflate_init(stream);
1591        return git_inflate(stream, 0);
1592}
1593
1594static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1595                                        unsigned long mapsize, void *buffer,
1596                                        unsigned long bufsiz, struct strbuf *header)
1597{
1598        int status;
1599
1600        status = unpack_sha1_header(stream, map, mapsize, buffer, bufsiz);
1601
1602        /*
1603         * Check if entire header is unpacked in the first iteration.
1604         */
1605        if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1606                return 0;
1607
1608        /*
1609         * buffer[0..bufsiz] was not large enough.  Copy the partial
1610         * result out to header, and then append the result of further
1611         * reading the stream.
1612         */
1613        strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1614        stream->next_out = buffer;
1615        stream->avail_out = bufsiz;
1616
1617        do {
1618                status = git_inflate(stream, 0);
1619                strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1620                if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1621                        return 0;
1622                stream->next_out = buffer;
1623                stream->avail_out = bufsiz;
1624        } while (status != Z_STREAM_END);
1625        return -1;
1626}
1627
1628static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1629{
1630        int bytes = strlen(buffer) + 1;
1631        unsigned char *buf = xmallocz(size);
1632        unsigned long n;
1633        int status = Z_OK;
1634
1635        n = stream->total_out - bytes;
1636        if (n > size)
1637                n = size;
1638        memcpy(buf, (char *) buffer + bytes, n);
1639        bytes = n;
1640        if (bytes <= size) {
1641                /*
1642                 * The above condition must be (bytes <= size), not
1643                 * (bytes < size).  In other words, even though we
1644                 * expect no more output and set avail_out to zero,
1645                 * the input zlib stream may have bytes that express
1646                 * "this concludes the stream", and we *do* want to
1647                 * eat that input.
1648                 *
1649                 * Otherwise we would not be able to test that we
1650                 * consumed all the input to reach the expected size;
1651                 * we also want to check that zlib tells us that all
1652                 * went well with status == Z_STREAM_END at the end.
1653                 */
1654                stream->next_out = buf + bytes;
1655                stream->avail_out = size - bytes;
1656                while (status == Z_OK)
1657                        status = git_inflate(stream, Z_FINISH);
1658        }
1659        if (status == Z_STREAM_END && !stream->avail_in) {
1660                git_inflate_end(stream);
1661                return buf;
1662        }
1663
1664        if (status < 0)
1665                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1666        else if (stream->avail_in)
1667                error("garbage at end of loose object '%s'",
1668                      sha1_to_hex(sha1));
1669        free(buf);
1670        return NULL;
1671}
1672
1673/*
1674 * We used to just use "sscanf()", but that's actually way
1675 * too permissive for what we want to check. So do an anal
1676 * object header parse by hand.
1677 */
1678static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1679                               unsigned int flags)
1680{
1681        const char *type_buf = hdr;
1682        unsigned long size;
1683        int type, type_len = 0;
1684
1685        /*
1686         * The type can be of any size but is followed by
1687         * a space.
1688         */
1689        for (;;) {
1690                char c = *hdr++;
1691                if (c == ' ')
1692                        break;
1693                type_len++;
1694        }
1695
1696        type = type_from_string_gently(type_buf, type_len, 1);
1697        if (oi->typename)
1698                strbuf_add(oi->typename, type_buf, type_len);
1699        /*
1700         * Set type to 0 if its an unknown object and
1701         * we're obtaining the type using '--allow-unkown-type'
1702         * option.
1703         */
1704        if ((flags & LOOKUP_UNKNOWN_OBJECT) && (type < 0))
1705                type = 0;
1706        else if (type < 0)
1707                die("invalid object type");
1708        if (oi->typep)
1709                *oi->typep = type;
1710
1711        /*
1712         * The length must follow immediately, and be in canonical
1713         * decimal format (ie "010" is not valid).
1714         */
1715        size = *hdr++ - '0';
1716        if (size > 9)
1717                return -1;
1718        if (size) {
1719                for (;;) {
1720                        unsigned long c = *hdr - '0';
1721                        if (c > 9)
1722                                break;
1723                        hdr++;
1724                        size = size * 10 + c;
1725                }
1726        }
1727
1728        if (oi->sizep)
1729                *oi->sizep = size;
1730
1731        /*
1732         * The length must be followed by a zero byte
1733         */
1734        return *hdr ? -1 : type;
1735}
1736
1737int parse_sha1_header(const char *hdr, unsigned long *sizep)
1738{
1739        struct object_info oi;
1740
1741        oi.sizep = sizep;
1742        oi.typename = NULL;
1743        oi.typep = NULL;
1744        return parse_sha1_header_extended(hdr, &oi, LOOKUP_REPLACE_OBJECT);
1745}
1746
1747static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1748{
1749        int ret;
1750        git_zstream stream;
1751        char hdr[8192];
1752
1753        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1754        if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1755                return NULL;
1756
1757        return unpack_sha1_rest(&stream, hdr, *size, sha1);
1758}
1759
1760unsigned long get_size_from_delta(struct packed_git *p,
1761                                  struct pack_window **w_curs,
1762                                  off_t curpos)
1763{
1764        const unsigned char *data;
1765        unsigned char delta_head[20], *in;
1766        git_zstream stream;
1767        int st;
1768
1769        memset(&stream, 0, sizeof(stream));
1770        stream.next_out = delta_head;
1771        stream.avail_out = sizeof(delta_head);
1772
1773        git_inflate_init(&stream);
1774        do {
1775                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1776                stream.next_in = in;
1777                st = git_inflate(&stream, Z_FINISH);
1778                curpos += stream.next_in - in;
1779        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1780                 stream.total_out < sizeof(delta_head));
1781        git_inflate_end(&stream);
1782        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1783                error("delta data unpack-initial failed");
1784                return 0;
1785        }
1786
1787        /* Examine the initial part of the delta to figure out
1788         * the result size.
1789         */
1790        data = delta_head;
1791
1792        /* ignore base size */
1793        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1794
1795        /* Read the result size */
1796        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1797}
1798
1799static off_t get_delta_base(struct packed_git *p,
1800                                    struct pack_window **w_curs,
1801                                    off_t *curpos,
1802                                    enum object_type type,
1803                                    off_t delta_obj_offset)
1804{
1805        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1806        off_t base_offset;
1807
1808        /* use_pack() assured us we have [base_info, base_info + 20)
1809         * as a range that we can look at without walking off the
1810         * end of the mapped window.  Its actually the hash size
1811         * that is assured.  An OFS_DELTA longer than the hash size
1812         * is stupid, as then a REF_DELTA would be smaller to store.
1813         */
1814        if (type == OBJ_OFS_DELTA) {
1815                unsigned used = 0;
1816                unsigned char c = base_info[used++];
1817                base_offset = c & 127;
1818                while (c & 128) {
1819                        base_offset += 1;
1820                        if (!base_offset || MSB(base_offset, 7))
1821                                return 0;  /* overflow */
1822                        c = base_info[used++];
1823                        base_offset = (base_offset << 7) + (c & 127);
1824                }
1825                base_offset = delta_obj_offset - base_offset;
1826                if (base_offset <= 0 || base_offset >= delta_obj_offset)
1827                        return 0;  /* out of bound */
1828                *curpos += used;
1829        } else if (type == OBJ_REF_DELTA) {
1830                /* The base entry _must_ be in the same pack */
1831                base_offset = find_pack_entry_one(base_info, p);
1832                *curpos += 20;
1833        } else
1834                die("I am totally screwed");
1835        return base_offset;
1836}
1837
1838/*
1839 * Like get_delta_base above, but we return the sha1 instead of the pack
1840 * offset. This means it is cheaper for REF deltas (we do not have to do
1841 * the final object lookup), but more expensive for OFS deltas (we
1842 * have to load the revidx to convert the offset back into a sha1).
1843 */
1844static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1845                                                struct pack_window **w_curs,
1846                                                off_t curpos,
1847                                                enum object_type type,
1848                                                off_t delta_obj_offset)
1849{
1850        if (type == OBJ_REF_DELTA) {
1851                unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1852                return base;
1853        } else if (type == OBJ_OFS_DELTA) {
1854                struct revindex_entry *revidx;
1855                off_t base_offset = get_delta_base(p, w_curs, &curpos,
1856                                                   type, delta_obj_offset);
1857
1858                if (!base_offset)
1859                        return NULL;
1860
1861                revidx = find_pack_revindex(p, base_offset);
1862                if (!revidx)
1863                        return NULL;
1864
1865                return nth_packed_object_sha1(p, revidx->nr);
1866        } else
1867                return NULL;
1868}
1869
1870int unpack_object_header(struct packed_git *p,
1871                         struct pack_window **w_curs,
1872                         off_t *curpos,
1873                         unsigned long *sizep)
1874{
1875        unsigned char *base;
1876        unsigned long left;
1877        unsigned long used;
1878        enum object_type type;
1879
1880        /* use_pack() assures us we have [base, base + 20) available
1881         * as a range that we can look at.  (Its actually the hash
1882         * size that is assured.)  With our object header encoding
1883         * the maximum deflated object size is 2^137, which is just
1884         * insane, so we know won't exceed what we have been given.
1885         */
1886        base = use_pack(p, w_curs, *curpos, &left);
1887        used = unpack_object_header_buffer(base, left, &type, sizep);
1888        if (!used) {
1889                type = OBJ_BAD;
1890        } else
1891                *curpos += used;
1892
1893        return type;
1894}
1895
1896static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1897{
1898        int type;
1899        struct revindex_entry *revidx;
1900        const unsigned char *sha1;
1901        revidx = find_pack_revindex(p, obj_offset);
1902        if (!revidx)
1903                return OBJ_BAD;
1904        sha1 = nth_packed_object_sha1(p, revidx->nr);
1905        mark_bad_packed_object(p, sha1);
1906        type = sha1_object_info(sha1, NULL);
1907        if (type <= OBJ_NONE)
1908                return OBJ_BAD;
1909        return type;
1910}
1911
1912#define POI_STACK_PREALLOC 64
1913
1914static enum object_type packed_to_object_type(struct packed_git *p,
1915                                              off_t obj_offset,
1916                                              enum object_type type,
1917                                              struct pack_window **w_curs,
1918                                              off_t curpos)
1919{
1920        off_t small_poi_stack[POI_STACK_PREALLOC];
1921        off_t *poi_stack = small_poi_stack;
1922        int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1923
1924        while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1925                off_t base_offset;
1926                unsigned long size;
1927                /* Push the object we're going to leave behind */
1928                if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1929                        poi_stack_alloc = alloc_nr(poi_stack_nr);
1930                        ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1931                        memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1932                } else {
1933                        ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1934                }
1935                poi_stack[poi_stack_nr++] = obj_offset;
1936                /* If parsing the base offset fails, just unwind */
1937                base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1938                if (!base_offset)
1939                        goto unwind;
1940                curpos = obj_offset = base_offset;
1941                type = unpack_object_header(p, w_curs, &curpos, &size);
1942                if (type <= OBJ_NONE) {
1943                        /* If getting the base itself fails, we first
1944                         * retry the base, otherwise unwind */
1945                        type = retry_bad_packed_offset(p, base_offset);
1946                        if (type > OBJ_NONE)
1947                                goto out;
1948                        goto unwind;
1949                }
1950        }
1951
1952        switch (type) {
1953        case OBJ_BAD:
1954        case OBJ_COMMIT:
1955        case OBJ_TREE:
1956        case OBJ_BLOB:
1957        case OBJ_TAG:
1958                break;
1959        default:
1960                error("unknown object type %i at offset %"PRIuMAX" in %s",
1961                      type, (uintmax_t)obj_offset, p->pack_name);
1962                type = OBJ_BAD;
1963        }
1964
1965out:
1966        if (poi_stack != small_poi_stack)
1967                free(poi_stack);
1968        return type;
1969
1970unwind:
1971        while (poi_stack_nr) {
1972                obj_offset = poi_stack[--poi_stack_nr];
1973                type = retry_bad_packed_offset(p, obj_offset);
1974                if (type > OBJ_NONE)
1975                        goto out;
1976        }
1977        type = OBJ_BAD;
1978        goto out;
1979}
1980
1981static int packed_object_info(struct packed_git *p, off_t obj_offset,
1982                              struct object_info *oi)
1983{
1984        struct pack_window *w_curs = NULL;
1985        unsigned long size;
1986        off_t curpos = obj_offset;
1987        enum object_type type;
1988
1989        /*
1990         * We always get the representation type, but only convert it to
1991         * a "real" type later if the caller is interested.
1992         */
1993        type = unpack_object_header(p, &w_curs, &curpos, &size);
1994
1995        if (oi->sizep) {
1996                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1997                        off_t tmp_pos = curpos;
1998                        off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1999                                                           type, obj_offset);
2000                        if (!base_offset) {
2001                                type = OBJ_BAD;
2002                                goto out;
2003                        }
2004                        *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
2005                        if (*oi->sizep == 0) {
2006                                type = OBJ_BAD;
2007                                goto out;
2008                        }
2009                } else {
2010                        *oi->sizep = size;
2011                }
2012        }
2013
2014        if (oi->disk_sizep) {
2015                struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2016                *oi->disk_sizep = revidx[1].offset - obj_offset;
2017        }
2018
2019        if (oi->typep) {
2020                *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
2021                if (*oi->typep < 0) {
2022                        type = OBJ_BAD;
2023                        goto out;
2024                }
2025        }
2026
2027        if (oi->delta_base_sha1) {
2028                if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2029                        const unsigned char *base;
2030
2031                        base = get_delta_base_sha1(p, &w_curs, curpos,
2032                                                   type, obj_offset);
2033                        if (!base) {
2034                                type = OBJ_BAD;
2035                                goto out;
2036                        }
2037
2038                        hashcpy(oi->delta_base_sha1, base);
2039                } else
2040                        hashclr(oi->delta_base_sha1);
2041        }
2042
2043out:
2044        unuse_pack(&w_curs);
2045        return type;
2046}
2047
2048static void *unpack_compressed_entry(struct packed_git *p,
2049                                    struct pack_window **w_curs,
2050                                    off_t curpos,
2051                                    unsigned long size)
2052{
2053        int st;
2054        git_zstream stream;
2055        unsigned char *buffer, *in;
2056
2057        buffer = xmallocz_gently(size);
2058        if (!buffer)
2059                return NULL;
2060        memset(&stream, 0, sizeof(stream));
2061        stream.next_out = buffer;
2062        stream.avail_out = size + 1;
2063
2064        git_inflate_init(&stream);
2065        do {
2066                in = use_pack(p, w_curs, curpos, &stream.avail_in);
2067                stream.next_in = in;
2068                st = git_inflate(&stream, Z_FINISH);
2069                if (!stream.avail_out)
2070                        break; /* the payload is larger than it should be */
2071                curpos += stream.next_in - in;
2072        } while (st == Z_OK || st == Z_BUF_ERROR);
2073        git_inflate_end(&stream);
2074        if ((st != Z_STREAM_END) || stream.total_out != size) {
2075                free(buffer);
2076                return NULL;
2077        }
2078
2079        return buffer;
2080}
2081
2082#define MAX_DELTA_CACHE (256)
2083
2084static size_t delta_base_cached;
2085
2086static struct delta_base_cache_lru_list {
2087        struct delta_base_cache_lru_list *prev;
2088        struct delta_base_cache_lru_list *next;
2089} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
2090
2091static struct delta_base_cache_entry {
2092        struct delta_base_cache_lru_list lru;
2093        void *data;
2094        struct packed_git *p;
2095        off_t base_offset;
2096        unsigned long size;
2097        enum object_type type;
2098} delta_base_cache[MAX_DELTA_CACHE];
2099
2100static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
2101{
2102        unsigned long hash;
2103
2104        hash = (unsigned long)(intptr_t)p + (unsigned long)base_offset;
2105        hash += (hash >> 8) + (hash >> 16);
2106        return hash % MAX_DELTA_CACHE;
2107}
2108
2109static struct delta_base_cache_entry *
2110get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2111{
2112        unsigned long hash = pack_entry_hash(p, base_offset);
2113        return delta_base_cache + hash;
2114}
2115
2116static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
2117                                     struct packed_git *p, off_t base_offset)
2118{
2119        return (ent->data && ent->p == p && ent->base_offset == base_offset);
2120}
2121
2122static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2123{
2124        struct delta_base_cache_entry *ent;
2125        ent = get_delta_base_cache_entry(p, base_offset);
2126        return eq_delta_base_cache_entry(ent, p, base_offset);
2127}
2128
2129static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2130{
2131        ent->data = NULL;
2132        ent->lru.next->prev = ent->lru.prev;
2133        ent->lru.prev->next = ent->lru.next;
2134        delta_base_cached -= ent->size;
2135}
2136
2137static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2138        unsigned long *base_size, enum object_type *type, int keep_cache)
2139{
2140        struct delta_base_cache_entry *ent;
2141        void *ret;
2142
2143        ent = get_delta_base_cache_entry(p, base_offset);
2144
2145        if (!eq_delta_base_cache_entry(ent, p, base_offset))
2146                return unpack_entry(p, base_offset, type, base_size);
2147
2148        ret = ent->data;
2149
2150        if (!keep_cache)
2151                clear_delta_base_cache_entry(ent);
2152        else
2153                ret = xmemdupz(ent->data, ent->size);
2154        *type = ent->type;
2155        *base_size = ent->size;
2156        return ret;
2157}
2158
2159static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2160{
2161        if (ent->data) {
2162                free(ent->data);
2163                ent->data = NULL;
2164                ent->lru.next->prev = ent->lru.prev;
2165                ent->lru.prev->next = ent->lru.next;
2166                delta_base_cached -= ent->size;
2167        }
2168}
2169
2170void clear_delta_base_cache(void)
2171{
2172        unsigned long p;
2173        for (p = 0; p < MAX_DELTA_CACHE; p++)
2174                release_delta_base_cache(&delta_base_cache[p]);
2175}
2176
2177static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2178        void *base, unsigned long base_size, enum object_type type)
2179{
2180        unsigned long hash = pack_entry_hash(p, base_offset);
2181        struct delta_base_cache_entry *ent = delta_base_cache + hash;
2182        struct delta_base_cache_lru_list *lru;
2183
2184        release_delta_base_cache(ent);
2185        delta_base_cached += base_size;
2186
2187        for (lru = delta_base_cache_lru.next;
2188             delta_base_cached > delta_base_cache_limit
2189             && lru != &delta_base_cache_lru;
2190             lru = lru->next) {
2191                struct delta_base_cache_entry *f = (void *)lru;
2192                if (f->type == OBJ_BLOB)
2193                        release_delta_base_cache(f);
2194        }
2195        for (lru = delta_base_cache_lru.next;
2196             delta_base_cached > delta_base_cache_limit
2197             && lru != &delta_base_cache_lru;
2198             lru = lru->next) {
2199                struct delta_base_cache_entry *f = (void *)lru;
2200                release_delta_base_cache(f);
2201        }
2202
2203        ent->p = p;
2204        ent->base_offset = base_offset;
2205        ent->type = type;
2206        ent->data = base;
2207        ent->size = base_size;
2208        ent->lru.next = &delta_base_cache_lru;
2209        ent->lru.prev = delta_base_cache_lru.prev;
2210        delta_base_cache_lru.prev->next = &ent->lru;
2211        delta_base_cache_lru.prev = &ent->lru;
2212}
2213
2214static void *read_object(const unsigned char *sha1, enum object_type *type,
2215                         unsigned long *size);
2216
2217static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2218{
2219        static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2220        trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2221                         p->pack_name, (uintmax_t)obj_offset);
2222}
2223
2224int do_check_packed_object_crc;
2225
2226#define UNPACK_ENTRY_STACK_PREALLOC 64
2227struct unpack_entry_stack_ent {
2228        off_t obj_offset;
2229        off_t curpos;
2230        unsigned long size;
2231};
2232
2233void *unpack_entry(struct packed_git *p, off_t obj_offset,
2234                   enum object_type *final_type, unsigned long *final_size)
2235{
2236        struct pack_window *w_curs = NULL;
2237        off_t curpos = obj_offset;
2238        void *data = NULL;
2239        unsigned long size;
2240        enum object_type type;
2241        struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2242        struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2243        int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2244        int base_from_cache = 0;
2245
2246        write_pack_access_log(p, obj_offset);
2247
2248        /* PHASE 1: drill down to the innermost base object */
2249        for (;;) {
2250                off_t base_offset;
2251                int i;
2252                struct delta_base_cache_entry *ent;
2253
2254                ent = get_delta_base_cache_entry(p, curpos);
2255                if (eq_delta_base_cache_entry(ent, p, curpos)) {
2256                        type = ent->type;
2257                        data = ent->data;
2258                        size = ent->size;
2259                        clear_delta_base_cache_entry(ent);
2260                        base_from_cache = 1;
2261                        break;
2262                }
2263
2264                if (do_check_packed_object_crc && p->index_version > 1) {
2265                        struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2266                        off_t len = revidx[1].offset - obj_offset;
2267                        if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2268                                const unsigned char *sha1 =
2269                                        nth_packed_object_sha1(p, revidx->nr);
2270                                error("bad packed object CRC for %s",
2271                                      sha1_to_hex(sha1));
2272                                mark_bad_packed_object(p, sha1);
2273                                unuse_pack(&w_curs);
2274                                return NULL;
2275                        }
2276                }
2277
2278                type = unpack_object_header(p, &w_curs, &curpos, &size);
2279                if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2280                        break;
2281
2282                base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2283                if (!base_offset) {
2284                        error("failed to validate delta base reference "
2285                              "at offset %"PRIuMAX" from %s",
2286                              (uintmax_t)curpos, p->pack_name);
2287                        /* bail to phase 2, in hopes of recovery */
2288                        data = NULL;
2289                        break;
2290                }
2291
2292                /* push object, proceed to base */
2293                if (delta_stack_nr >= delta_stack_alloc
2294                    && delta_stack == small_delta_stack) {
2295                        delta_stack_alloc = alloc_nr(delta_stack_nr);
2296                        ALLOC_ARRAY(delta_stack, delta_stack_alloc);
2297                        memcpy(delta_stack, small_delta_stack,
2298                               sizeof(*delta_stack)*delta_stack_nr);
2299                } else {
2300                        ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2301                }
2302                i = delta_stack_nr++;
2303                delta_stack[i].obj_offset = obj_offset;
2304                delta_stack[i].curpos = curpos;
2305                delta_stack[i].size = size;
2306
2307                curpos = obj_offset = base_offset;
2308        }
2309
2310        /* PHASE 2: handle the base */
2311        switch (type) {
2312        case OBJ_OFS_DELTA:
2313        case OBJ_REF_DELTA:
2314                if (data)
2315                        die("BUG: unpack_entry: left loop at a valid delta");
2316                break;
2317        case OBJ_COMMIT:
2318        case OBJ_TREE:
2319        case OBJ_BLOB:
2320        case OBJ_TAG:
2321                if (!base_from_cache)
2322                        data = unpack_compressed_entry(p, &w_curs, curpos, size);
2323                break;
2324        default:
2325                data = NULL;
2326                error("unknown object type %i at offset %"PRIuMAX" in %s",
2327                      type, (uintmax_t)obj_offset, p->pack_name);
2328        }
2329
2330        /* PHASE 3: apply deltas in order */
2331
2332        /* invariants:
2333         *   'data' holds the base data, or NULL if there was corruption
2334         */
2335        while (delta_stack_nr) {
2336                void *delta_data;
2337                void *base = data;
2338                unsigned long delta_size, base_size = size;
2339                int i;
2340
2341                data = NULL;
2342
2343                if (base)
2344                        add_delta_base_cache(p, obj_offset, base, base_size, type);
2345
2346                if (!base) {
2347                        /*
2348                         * We're probably in deep shit, but let's try to fetch
2349                         * the required base anyway from another pack or loose.
2350                         * This is costly but should happen only in the presence
2351                         * of a corrupted pack, and is better than failing outright.
2352                         */
2353                        struct revindex_entry *revidx;
2354                        const unsigned char *base_sha1;
2355                        revidx = find_pack_revindex(p, obj_offset);
2356                        if (revidx) {
2357                                base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2358                                error("failed to read delta base object %s"
2359                                      " at offset %"PRIuMAX" from %s",
2360                                      sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2361                                      p->pack_name);
2362                                mark_bad_packed_object(p, base_sha1);
2363                                base = read_object(base_sha1, &type, &base_size);
2364                        }
2365                }
2366
2367                i = --delta_stack_nr;
2368                obj_offset = delta_stack[i].obj_offset;
2369                curpos = delta_stack[i].curpos;
2370                delta_size = delta_stack[i].size;
2371
2372                if (!base)
2373                        continue;
2374
2375                delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2376
2377                if (!delta_data) {
2378                        error("failed to unpack compressed delta "
2379                              "at offset %"PRIuMAX" from %s",
2380                              (uintmax_t)curpos, p->pack_name);
2381                        data = NULL;
2382                        continue;
2383                }
2384
2385                data = patch_delta(base, base_size,
2386                                   delta_data, delta_size,
2387                                   &size);
2388
2389                /*
2390                 * We could not apply the delta; warn the user, but keep going.
2391                 * Our failure will be noticed either in the next iteration of
2392                 * the loop, or if this is the final delta, in the caller when
2393                 * we return NULL. Those code paths will take care of making
2394                 * a more explicit warning and retrying with another copy of
2395                 * the object.
2396                 */
2397                if (!data)
2398                        error("failed to apply delta");
2399
2400                free(delta_data);
2401        }
2402
2403        *final_type = type;
2404        *final_size = size;
2405
2406        unuse_pack(&w_curs);
2407
2408        if (delta_stack != small_delta_stack)
2409                free(delta_stack);
2410
2411        return data;
2412}
2413
2414const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2415                                            uint32_t n)
2416{
2417        const unsigned char *index = p->index_data;
2418        if (!index) {
2419                if (open_pack_index(p))
2420                        return NULL;
2421                index = p->index_data;
2422        }
2423        if (n >= p->num_objects)
2424                return NULL;
2425        index += 4 * 256;
2426        if (p->index_version == 1) {
2427                return index + 24 * n + 4;
2428        } else {
2429                index += 8;
2430                return index + 20 * n;
2431        }
2432}
2433
2434void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2435{
2436        const unsigned char *ptr = vptr;
2437        const unsigned char *start = p->index_data;
2438        const unsigned char *end = start + p->index_size;
2439        if (ptr < start)
2440                die(_("offset before start of pack index for %s (corrupt index?)"),
2441                    p->pack_name);
2442        /* No need to check for underflow; .idx files must be at least 8 bytes */
2443        if (ptr >= end - 8)
2444                die(_("offset beyond end of pack index for %s (truncated index?)"),
2445                    p->pack_name);
2446}
2447
2448off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2449{
2450        const unsigned char *index = p->index_data;
2451        index += 4 * 256;
2452        if (p->index_version == 1) {
2453                return ntohl(*((uint32_t *)(index + 24 * n)));
2454        } else {
2455                uint32_t off;
2456                index += 8 + p->num_objects * (20 + 4);
2457                off = ntohl(*((uint32_t *)(index + 4 * n)));
2458                if (!(off & 0x80000000))
2459                        return off;
2460                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2461                check_pack_index_ptr(p, index);
2462                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2463                                   ntohl(*((uint32_t *)(index + 4)));
2464        }
2465}
2466
2467off_t find_pack_entry_one(const unsigned char *sha1,
2468                                  struct packed_git *p)
2469{
2470        const uint32_t *level1_ofs = p->index_data;
2471        const unsigned char *index = p->index_data;
2472        unsigned hi, lo, stride;
2473        static int use_lookup = -1;
2474        static int debug_lookup = -1;
2475
2476        if (debug_lookup < 0)
2477                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2478
2479        if (!index) {
2480                if (open_pack_index(p))
2481                        return 0;
2482                level1_ofs = p->index_data;
2483                index = p->index_data;
2484        }
2485        if (p->index_version > 1) {
2486                level1_ofs += 2;
2487                index += 8;
2488        }
2489        index += 4 * 256;
2490        hi = ntohl(level1_ofs[*sha1]);
2491        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2492        if (p->index_version > 1) {
2493                stride = 20;
2494        } else {
2495                stride = 24;
2496                index += 4;
2497        }
2498
2499        if (debug_lookup)
2500                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2501                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2502
2503        if (use_lookup < 0)
2504                use_lookup = !!getenv("GIT_USE_LOOKUP");
2505        if (use_lookup) {
2506                int pos = sha1_entry_pos(index, stride, 0,
2507                                         lo, hi, p->num_objects, sha1);
2508                if (pos < 0)
2509                        return 0;
2510                return nth_packed_object_offset(p, pos);
2511        }
2512
2513        do {
2514                unsigned mi = (lo + hi) / 2;
2515                int cmp = hashcmp(index + mi * stride, sha1);
2516
2517                if (debug_lookup)
2518                        printf("lo %u hi %u rg %u mi %u\n",
2519                               lo, hi, hi - lo, mi);
2520                if (!cmp)
2521                        return nth_packed_object_offset(p, mi);
2522                if (cmp > 0)
2523                        hi = mi;
2524                else
2525                        lo = mi+1;
2526        } while (lo < hi);
2527        return 0;
2528}
2529
2530int is_pack_valid(struct packed_git *p)
2531{
2532        /* An already open pack is known to be valid. */
2533        if (p->pack_fd != -1)
2534                return 1;
2535
2536        /* If the pack has one window completely covering the
2537         * file size, the pack is known to be valid even if
2538         * the descriptor is not currently open.
2539         */
2540        if (p->windows) {
2541                struct pack_window *w = p->windows;
2542
2543                if (!w->offset && w->len == p->pack_size)
2544                        return 1;
2545        }
2546
2547        /* Force the pack to open to prove its valid. */
2548        return !open_packed_git(p);
2549}
2550
2551static int fill_pack_entry(const unsigned char *sha1,
2552                           struct pack_entry *e,
2553                           struct packed_git *p)
2554{
2555        off_t offset;
2556
2557        if (p->num_bad_objects) {
2558                unsigned i;
2559                for (i = 0; i < p->num_bad_objects; i++)
2560                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2561                                return 0;
2562        }
2563
2564        offset = find_pack_entry_one(sha1, p);
2565        if (!offset)
2566                return 0;
2567
2568        /*
2569         * We are about to tell the caller where they can locate the
2570         * requested object.  We better make sure the packfile is
2571         * still here and can be accessed before supplying that
2572         * answer, as it may have been deleted since the index was
2573         * loaded!
2574         */
2575        if (!is_pack_valid(p))
2576                return 0;
2577        e->offset = offset;
2578        e->p = p;
2579        hashcpy(e->sha1, sha1);
2580        return 1;
2581}
2582
2583/*
2584 * Iff a pack file contains the object named by sha1, return true and
2585 * store its location to e.
2586 */
2587static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2588{
2589        struct mru_entry *p;
2590
2591        prepare_packed_git();
2592        if (!packed_git)
2593                return 0;
2594
2595        for (p = packed_git_mru->head; p; p = p->next) {
2596                if (fill_pack_entry(sha1, e, p->item)) {
2597                        mru_mark(packed_git_mru, p);
2598                        return 1;
2599                }
2600        }
2601        return 0;
2602}
2603
2604struct packed_git *find_sha1_pack(const unsigned char *sha1,
2605                                  struct packed_git *packs)
2606{
2607        struct packed_git *p;
2608
2609        for (p = packs; p; p = p->next) {
2610                if (find_pack_entry_one(sha1, p))
2611                        return p;
2612        }
2613        return NULL;
2614
2615}
2616
2617static int sha1_loose_object_info(const unsigned char *sha1,
2618                                  struct object_info *oi,
2619                                  int flags)
2620{
2621        int status = 0;
2622        unsigned long mapsize;
2623        void *map;
2624        git_zstream stream;
2625        char hdr[32];
2626        struct strbuf hdrbuf = STRBUF_INIT;
2627
2628        if (oi->delta_base_sha1)
2629                hashclr(oi->delta_base_sha1);
2630
2631        /*
2632         * If we don't care about type or size, then we don't
2633         * need to look inside the object at all. Note that we
2634         * do not optimize out the stat call, even if the
2635         * caller doesn't care about the disk-size, since our
2636         * return value implicitly indicates whether the
2637         * object even exists.
2638         */
2639        if (!oi->typep && !oi->typename && !oi->sizep) {
2640                struct stat st;
2641                if (stat_sha1_file(sha1, &st) < 0)
2642                        return -1;
2643                if (oi->disk_sizep)
2644                        *oi->disk_sizep = st.st_size;
2645                return 0;
2646        }
2647
2648        map = map_sha1_file(sha1, &mapsize);
2649        if (!map)
2650                return -1;
2651        if (oi->disk_sizep)
2652                *oi->disk_sizep = mapsize;
2653        if ((flags & LOOKUP_UNKNOWN_OBJECT)) {
2654                if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2655                        status = error("unable to unpack %s header with --allow-unknown-type",
2656                                       sha1_to_hex(sha1));
2657        } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2658                status = error("unable to unpack %s header",
2659                               sha1_to_hex(sha1));
2660        if (status < 0)
2661                ; /* Do nothing */
2662        else if (hdrbuf.len) {
2663                if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2664                        status = error("unable to parse %s header with --allow-unknown-type",
2665                                       sha1_to_hex(sha1));
2666        } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2667                status = error("unable to parse %s header", sha1_to_hex(sha1));
2668        git_inflate_end(&stream);
2669        munmap(map, mapsize);
2670        if (status && oi->typep)
2671                *oi->typep = status;
2672        strbuf_release(&hdrbuf);
2673        return 0;
2674}
2675
2676int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2677{
2678        struct cached_object *co;
2679        struct pack_entry e;
2680        int rtype;
2681        enum object_type real_type;
2682        const unsigned char *real = lookup_replace_object_extended(sha1, flags);
2683
2684        co = find_cached_object(real);
2685        if (co) {
2686                if (oi->typep)
2687                        *(oi->typep) = co->type;
2688                if (oi->sizep)
2689                        *(oi->sizep) = co->size;
2690                if (oi->disk_sizep)
2691                        *(oi->disk_sizep) = 0;
2692                if (oi->delta_base_sha1)
2693                        hashclr(oi->delta_base_sha1);
2694                if (oi->typename)
2695                        strbuf_addstr(oi->typename, typename(co->type));
2696                oi->whence = OI_CACHED;
2697                return 0;
2698        }
2699
2700        if (!find_pack_entry(real, &e)) {
2701                /* Most likely it's a loose object. */
2702                if (!sha1_loose_object_info(real, oi, flags)) {
2703                        oi->whence = OI_LOOSE;
2704                        return 0;
2705                }
2706
2707                /* Not a loose object; someone else may have just packed it. */
2708                reprepare_packed_git();
2709                if (!find_pack_entry(real, &e))
2710                        return -1;
2711        }
2712
2713        /*
2714         * packed_object_info() does not follow the delta chain to
2715         * find out the real type, unless it is given oi->typep.
2716         */
2717        if (oi->typename && !oi->typep)
2718                oi->typep = &real_type;
2719
2720        rtype = packed_object_info(e.p, e.offset, oi);
2721        if (rtype < 0) {
2722                mark_bad_packed_object(e.p, real);
2723                if (oi->typep == &real_type)
2724                        oi->typep = NULL;
2725                return sha1_object_info_extended(real, oi, 0);
2726        } else if (in_delta_base_cache(e.p, e.offset)) {
2727                oi->whence = OI_DBCACHED;
2728        } else {
2729                oi->whence = OI_PACKED;
2730                oi->u.packed.offset = e.offset;
2731                oi->u.packed.pack = e.p;
2732                oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2733                                         rtype == OBJ_OFS_DELTA);
2734        }
2735        if (oi->typename)
2736                strbuf_addstr(oi->typename, typename(*oi->typep));
2737        if (oi->typep == &real_type)
2738                oi->typep = NULL;
2739
2740        return 0;
2741}
2742
2743/* returns enum object_type or negative */
2744int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2745{
2746        enum object_type type;
2747        struct object_info oi = {NULL};
2748
2749        oi.typep = &type;
2750        oi.sizep = sizep;
2751        if (sha1_object_info_extended(sha1, &oi, LOOKUP_REPLACE_OBJECT) < 0)
2752                return -1;
2753        return type;
2754}
2755
2756static void *read_packed_sha1(const unsigned char *sha1,
2757                              enum object_type *type, unsigned long *size)
2758{
2759        struct pack_entry e;
2760        void *data;
2761
2762        if (!find_pack_entry(sha1, &e))
2763                return NULL;
2764        data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2765        if (!data) {
2766                /*
2767                 * We're probably in deep shit, but let's try to fetch
2768                 * the required object anyway from another pack or loose.
2769                 * This should happen only in the presence of a corrupted
2770                 * pack, and is better than failing outright.
2771                 */
2772                error("failed to read object %s at offset %"PRIuMAX" from %s",
2773                      sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2774                mark_bad_packed_object(e.p, sha1);
2775                data = read_object(sha1, type, size);
2776        }
2777        return data;
2778}
2779
2780int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2781                      unsigned char *sha1)
2782{
2783        struct cached_object *co;
2784
2785        hash_sha1_file(buf, len, typename(type), sha1);
2786        if (has_sha1_file(sha1) || find_cached_object(sha1))
2787                return 0;
2788        ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2789        co = &cached_objects[cached_object_nr++];
2790        co->size = len;
2791        co->type = type;
2792        co->buf = xmalloc(len);
2793        memcpy(co->buf, buf, len);
2794        hashcpy(co->sha1, sha1);
2795        return 0;
2796}
2797
2798static void *read_object(const unsigned char *sha1, enum object_type *type,
2799                         unsigned long *size)
2800{
2801        unsigned long mapsize;
2802        void *map, *buf;
2803        struct cached_object *co;
2804
2805        co = find_cached_object(sha1);
2806        if (co) {
2807                *type = co->type;
2808                *size = co->size;
2809                return xmemdupz(co->buf, co->size);
2810        }
2811
2812        buf = read_packed_sha1(sha1, type, size);
2813        if (buf)
2814                return buf;
2815        map = map_sha1_file(sha1, &mapsize);
2816        if (map) {
2817                buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2818                munmap(map, mapsize);
2819                return buf;
2820        }
2821        reprepare_packed_git();
2822        return read_packed_sha1(sha1, type, size);
2823}
2824
2825/*
2826 * This function dies on corrupt objects; the callers who want to
2827 * deal with them should arrange to call read_object() and give error
2828 * messages themselves.
2829 */
2830void *read_sha1_file_extended(const unsigned char *sha1,
2831                              enum object_type *type,
2832                              unsigned long *size,
2833                              unsigned flag)
2834{
2835        void *data;
2836        const struct packed_git *p;
2837        const unsigned char *repl = lookup_replace_object_extended(sha1, flag);
2838
2839        errno = 0;
2840        data = read_object(repl, type, size);
2841        if (data)
2842                return data;
2843
2844        if (errno && errno != ENOENT)
2845                die_errno("failed to read object %s", sha1_to_hex(sha1));
2846
2847        /* die if we replaced an object with one that does not exist */
2848        if (repl != sha1)
2849                die("replacement %s not found for %s",
2850                    sha1_to_hex(repl), sha1_to_hex(sha1));
2851
2852        if (has_loose_object(repl)) {
2853                const char *path = sha1_file_name(sha1);
2854
2855                die("loose object %s (stored in %s) is corrupt",
2856                    sha1_to_hex(repl), path);
2857        }
2858
2859        if ((p = has_packed_and_bad(repl)) != NULL)
2860                die("packed object %s (stored in %s) is corrupt",
2861                    sha1_to_hex(repl), p->pack_name);
2862
2863        return NULL;
2864}
2865
2866void *read_object_with_reference(const unsigned char *sha1,
2867                                 const char *required_type_name,
2868                                 unsigned long *size,
2869                                 unsigned char *actual_sha1_return)
2870{
2871        enum object_type type, required_type;
2872        void *buffer;
2873        unsigned long isize;
2874        unsigned char actual_sha1[20];
2875
2876        required_type = type_from_string(required_type_name);
2877        hashcpy(actual_sha1, sha1);
2878        while (1) {
2879                int ref_length = -1;
2880                const char *ref_type = NULL;
2881
2882                buffer = read_sha1_file(actual_sha1, &type, &isize);
2883                if (!buffer)
2884                        return NULL;
2885                if (type == required_type) {
2886                        *size = isize;
2887                        if (actual_sha1_return)
2888                                hashcpy(actual_sha1_return, actual_sha1);
2889                        return buffer;
2890                }
2891                /* Handle references */
2892                else if (type == OBJ_COMMIT)
2893                        ref_type = "tree ";
2894                else if (type == OBJ_TAG)
2895                        ref_type = "object ";
2896                else {
2897                        free(buffer);
2898                        return NULL;
2899                }
2900                ref_length = strlen(ref_type);
2901
2902                if (ref_length + 40 > isize ||
2903                    memcmp(buffer, ref_type, ref_length) ||
2904                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2905                        free(buffer);
2906                        return NULL;
2907                }
2908                free(buffer);
2909                /* Now we have the ID of the referred-to object in
2910                 * actual_sha1.  Check again. */
2911        }
2912}
2913
2914static void write_sha1_file_prepare(const void *buf, unsigned long len,
2915                                    const char *type, unsigned char *sha1,
2916                                    char *hdr, int *hdrlen)
2917{
2918        git_SHA_CTX c;
2919
2920        /* Generate the header */
2921        *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
2922
2923        /* Sha1.. */
2924        git_SHA1_Init(&c);
2925        git_SHA1_Update(&c, hdr, *hdrlen);
2926        git_SHA1_Update(&c, buf, len);
2927        git_SHA1_Final(sha1, &c);
2928}
2929
2930/*
2931 * Move the just written object into its final resting place.
2932 */
2933int finalize_object_file(const char *tmpfile, const char *filename)
2934{
2935        int ret = 0;
2936
2937        if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2938                goto try_rename;
2939        else if (link(tmpfile, filename))
2940                ret = errno;
2941
2942        /*
2943         * Coda hack - coda doesn't like cross-directory links,
2944         * so we fall back to a rename, which will mean that it
2945         * won't be able to check collisions, but that's not a
2946         * big deal.
2947         *
2948         * The same holds for FAT formatted media.
2949         *
2950         * When this succeeds, we just return.  We have nothing
2951         * left to unlink.
2952         */
2953        if (ret && ret != EEXIST) {
2954        try_rename:
2955                if (!rename(tmpfile, filename))
2956                        goto out;
2957                ret = errno;
2958        }
2959        unlink_or_warn(tmpfile);
2960        if (ret) {
2961                if (ret != EEXIST) {
2962                        return error_errno("unable to write sha1 filename %s", filename);
2963                }
2964                /* FIXME!!! Collision check here ? */
2965        }
2966
2967out:
2968        if (adjust_shared_perm(filename))
2969                return error("unable to set permission to '%s'", filename);
2970        return 0;
2971}
2972
2973static int write_buffer(int fd, const void *buf, size_t len)
2974{
2975        if (write_in_full(fd, buf, len) < 0)
2976                return error_errno("file write error");
2977        return 0;
2978}
2979
2980int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2981                   unsigned char *sha1)
2982{
2983        char hdr[32];
2984        int hdrlen = sizeof(hdr);
2985        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2986        return 0;
2987}
2988
2989/* Finalize a file on disk, and close it. */
2990static void close_sha1_file(int fd)
2991{
2992        if (fsync_object_files)
2993                fsync_or_die(fd, "sha1 file");
2994        if (close(fd) != 0)
2995                die_errno("error when closing sha1 file");
2996}
2997
2998/* Size of directory component, including the ending '/' */
2999static inline int directory_size(const char *filename)
3000{
3001        const char *s = strrchr(filename, '/');
3002        if (!s)
3003                return 0;
3004        return s - filename + 1;
3005}
3006
3007/*
3008 * This creates a temporary file in the same directory as the final
3009 * 'filename'
3010 *
3011 * We want to avoid cross-directory filename renames, because those
3012 * can have problems on various filesystems (FAT, NFS, Coda).
3013 */
3014static int create_tmpfile(struct strbuf *tmp, const char *filename)
3015{
3016        int fd, dirlen = directory_size(filename);
3017
3018        strbuf_reset(tmp);
3019        strbuf_add(tmp, filename, dirlen);
3020        strbuf_addstr(tmp, "tmp_obj_XXXXXX");
3021        fd = git_mkstemp_mode(tmp->buf, 0444);
3022        if (fd < 0 && dirlen && errno == ENOENT) {
3023                /*
3024                 * Make sure the directory exists; note that the contents
3025                 * of the buffer are undefined after mkstemp returns an
3026                 * error, so we have to rewrite the whole buffer from
3027                 * scratch.
3028                 */
3029                strbuf_reset(tmp);
3030                strbuf_add(tmp, filename, dirlen - 1);
3031                if (mkdir(tmp->buf, 0777) && errno != EEXIST)
3032                        return -1;
3033                if (adjust_shared_perm(tmp->buf))
3034                        return -1;
3035
3036                /* Try again */
3037                strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
3038                fd = git_mkstemp_mode(tmp->buf, 0444);
3039        }
3040        return fd;
3041}
3042
3043static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
3044                              const void *buf, unsigned long len, time_t mtime)
3045{
3046        int fd, ret;
3047        unsigned char compressed[4096];
3048        git_zstream stream;
3049        git_SHA_CTX c;
3050        unsigned char parano_sha1[20];
3051        static struct strbuf tmp_file = STRBUF_INIT;
3052        const char *filename = sha1_file_name(sha1);
3053
3054        fd = create_tmpfile(&tmp_file, filename);
3055        if (fd < 0) {
3056                if (errno == EACCES)
3057                        return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3058                else
3059                        return error_errno("unable to create temporary file");
3060        }
3061
3062        /* Set it up */
3063        git_deflate_init(&stream, zlib_compression_level);
3064        stream.next_out = compressed;
3065        stream.avail_out = sizeof(compressed);
3066        git_SHA1_Init(&c);
3067
3068        /* First header.. */
3069        stream.next_in = (unsigned char *)hdr;
3070        stream.avail_in = hdrlen;
3071        while (git_deflate(&stream, 0) == Z_OK)
3072                ; /* nothing */
3073        git_SHA1_Update(&c, hdr, hdrlen);
3074
3075        /* Then the data itself.. */
3076        stream.next_in = (void *)buf;
3077        stream.avail_in = len;
3078        do {
3079                unsigned char *in0 = stream.next_in;
3080                ret = git_deflate(&stream, Z_FINISH);
3081                git_SHA1_Update(&c, in0, stream.next_in - in0);
3082                if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
3083                        die("unable to write sha1 file");
3084                stream.next_out = compressed;
3085                stream.avail_out = sizeof(compressed);
3086        } while (ret == Z_OK);
3087
3088        if (ret != Z_STREAM_END)
3089                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
3090        ret = git_deflate_end_gently(&stream);
3091        if (ret != Z_OK)
3092                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
3093        git_SHA1_Final(parano_sha1, &c);
3094        if (hashcmp(sha1, parano_sha1) != 0)
3095                die("confused by unstable object source data for %s", sha1_to_hex(sha1));
3096
3097        close_sha1_file(fd);
3098
3099        if (mtime) {
3100                struct utimbuf utb;
3101                utb.actime = mtime;
3102                utb.modtime = mtime;
3103                if (utime(tmp_file.buf, &utb) < 0)
3104                        warning_errno("failed utime() on %s", tmp_file.buf);
3105        }
3106
3107        return finalize_object_file(tmp_file.buf, filename);
3108}
3109
3110static int freshen_loose_object(const unsigned char *sha1)
3111{
3112        return check_and_freshen(sha1, 1);
3113}
3114
3115static int freshen_packed_object(const unsigned char *sha1)
3116{
3117        struct pack_entry e;
3118        if (!find_pack_entry(sha1, &e))
3119                return 0;
3120        if (e.p->freshened)
3121                return 1;
3122        if (!freshen_file(e.p->pack_name))
3123                return 0;
3124        e.p->freshened = 1;
3125        return 1;
3126}
3127
3128int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
3129{
3130        char hdr[32];
3131        int hdrlen = sizeof(hdr);
3132
3133        /* Normally if we have it in the pack then we do not bother writing
3134         * it out into .git/objects/??/?{38} file.
3135         */
3136        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3137        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3138                return 0;
3139        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3140}
3141
3142int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
3143                             unsigned char *sha1, unsigned flags)
3144{
3145        char *header;
3146        int hdrlen, status = 0;
3147
3148        /* type string, SP, %lu of the length plus NUL must fit this */
3149        hdrlen = strlen(type) + 32;
3150        header = xmalloc(hdrlen);
3151        write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
3152
3153        if (!(flags & HASH_WRITE_OBJECT))
3154                goto cleanup;
3155        if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3156                goto cleanup;
3157        status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
3158
3159cleanup:
3160        free(header);
3161        return status;
3162}
3163
3164int force_object_loose(const unsigned char *sha1, time_t mtime)
3165{
3166        void *buf;
3167        unsigned long len;
3168        enum object_type type;
3169        char hdr[32];
3170        int hdrlen;
3171        int ret;
3172
3173        if (has_loose_object(sha1))
3174                return 0;
3175        buf = read_packed_sha1(sha1, &type, &len);
3176        if (!buf)
3177                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3178        hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
3179        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3180        free(buf);
3181
3182        return ret;
3183}
3184
3185int has_pack_index(const unsigned char *sha1)
3186{
3187        struct stat st;
3188        if (stat(sha1_pack_index_name(sha1), &st))
3189                return 0;
3190        return 1;
3191}
3192
3193int has_sha1_pack(const unsigned char *sha1)
3194{
3195        struct pack_entry e;
3196        return find_pack_entry(sha1, &e);
3197}
3198
3199int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
3200{
3201        struct pack_entry e;
3202
3203        if (find_pack_entry(sha1, &e))
3204                return 1;
3205        if (has_loose_object(sha1))
3206                return 1;
3207        if (flags & HAS_SHA1_QUICK)
3208                return 0;
3209        reprepare_packed_git();
3210        return find_pack_entry(sha1, &e);
3211}
3212
3213int has_object_file(const struct object_id *oid)
3214{
3215        return has_sha1_file(oid->hash);
3216}
3217
3218static void check_tree(const void *buf, size_t size)
3219{
3220        struct tree_desc desc;
3221        struct name_entry entry;
3222
3223        init_tree_desc(&desc, buf, size);
3224        while (tree_entry(&desc, &entry))
3225                /* do nothing
3226                 * tree_entry() will die() on malformed entries */
3227                ;
3228}
3229
3230static void check_commit(const void *buf, size_t size)
3231{
3232        struct commit c;
3233        memset(&c, 0, sizeof(c));
3234        if (parse_commit_buffer(&c, buf, size))
3235                die("corrupt commit");
3236}
3237
3238static void check_tag(const void *buf, size_t size)
3239{
3240        struct tag t;
3241        memset(&t, 0, sizeof(t));
3242        if (parse_tag_buffer(&t, buf, size))
3243                die("corrupt tag");
3244}
3245
3246static int index_mem(unsigned char *sha1, void *buf, size_t size,
3247                     enum object_type type,
3248                     const char *path, unsigned flags)
3249{
3250        int ret, re_allocated = 0;
3251        int write_object = flags & HASH_WRITE_OBJECT;
3252
3253        if (!type)
3254                type = OBJ_BLOB;
3255
3256        /*
3257         * Convert blobs to git internal format
3258         */
3259        if ((type == OBJ_BLOB) && path) {
3260                struct strbuf nbuf = STRBUF_INIT;
3261                if (convert_to_git(path, buf, size, &nbuf,
3262                                   write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3263                        buf = strbuf_detach(&nbuf, &size);
3264                        re_allocated = 1;
3265                }
3266        }
3267        if (flags & HASH_FORMAT_CHECK) {
3268                if (type == OBJ_TREE)
3269                        check_tree(buf, size);
3270                if (type == OBJ_COMMIT)
3271                        check_commit(buf, size);
3272                if (type == OBJ_TAG)
3273                        check_tag(buf, size);
3274        }
3275
3276        if (write_object)
3277                ret = write_sha1_file(buf, size, typename(type), sha1);
3278        else
3279                ret = hash_sha1_file(buf, size, typename(type), sha1);
3280        if (re_allocated)
3281                free(buf);
3282        return ret;
3283}
3284
3285static int index_stream_convert_blob(unsigned char *sha1, int fd,
3286                                     const char *path, unsigned flags)
3287{
3288        int ret;
3289        const int write_object = flags & HASH_WRITE_OBJECT;
3290        struct strbuf sbuf = STRBUF_INIT;
3291
3292        assert(path);
3293        assert(would_convert_to_git_filter_fd(path));
3294
3295        convert_to_git_filter_fd(path, fd, &sbuf,
3296                                 write_object ? safe_crlf : SAFE_CRLF_FALSE);
3297
3298        if (write_object)
3299                ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3300                                      sha1);
3301        else
3302                ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3303                                     sha1);
3304        strbuf_release(&sbuf);
3305        return ret;
3306}
3307
3308static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3309                      const char *path, unsigned flags)
3310{
3311        struct strbuf sbuf = STRBUF_INIT;
3312        int ret;
3313
3314        if (strbuf_read(&sbuf, fd, 4096) >= 0)
3315                ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3316        else
3317                ret = -1;
3318        strbuf_release(&sbuf);
3319        return ret;
3320}
3321
3322#define SMALL_FILE_SIZE (32*1024)
3323
3324static int index_core(unsigned char *sha1, int fd, size_t size,
3325                      enum object_type type, const char *path,
3326                      unsigned flags)
3327{
3328        int ret;
3329
3330        if (!size) {
3331                ret = index_mem(sha1, "", size, type, path, flags);
3332        } else if (size <= SMALL_FILE_SIZE) {
3333                char *buf = xmalloc(size);
3334                if (size == read_in_full(fd, buf, size))
3335                        ret = index_mem(sha1, buf, size, type, path, flags);
3336                else
3337                        ret = error_errno("short read");
3338                free(buf);
3339        } else {
3340                void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3341                ret = index_mem(sha1, buf, size, type, path, flags);
3342                munmap(buf, size);
3343        }
3344        return ret;
3345}
3346
3347/*
3348 * This creates one packfile per large blob unless bulk-checkin
3349 * machinery is "plugged".
3350 *
3351 * This also bypasses the usual "convert-to-git" dance, and that is on
3352 * purpose. We could write a streaming version of the converting
3353 * functions and insert that before feeding the data to fast-import
3354 * (or equivalent in-core API described above). However, that is
3355 * somewhat complicated, as we do not know the size of the filter
3356 * result, which we need to know beforehand when writing a git object.
3357 * Since the primary motivation for trying to stream from the working
3358 * tree file and to avoid mmaping it in core is to deal with large
3359 * binary blobs, they generally do not want to get any conversion, and
3360 * callers should avoid this code path when filters are requested.
3361 */
3362static int index_stream(unsigned char *sha1, int fd, size_t size,
3363                        enum object_type type, const char *path,
3364                        unsigned flags)
3365{
3366        return index_bulk_checkin(sha1, fd, size, type, path, flags);
3367}
3368
3369int index_fd(unsigned char *sha1, int fd, struct stat *st,
3370             enum object_type type, const char *path, unsigned flags)
3371{
3372        int ret;
3373
3374        /*
3375         * Call xsize_t() only when needed to avoid potentially unnecessary
3376         * die() for large files.
3377         */
3378        if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3379                ret = index_stream_convert_blob(sha1, fd, path, flags);
3380        else if (!S_ISREG(st->st_mode))
3381                ret = index_pipe(sha1, fd, type, path, flags);
3382        else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3383                 (path && would_convert_to_git(path)))
3384                ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3385                                 flags);
3386        else
3387                ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3388                                   flags);
3389        close(fd);
3390        return ret;
3391}
3392
3393int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3394{
3395        int fd;
3396        struct strbuf sb = STRBUF_INIT;
3397
3398        switch (st->st_mode & S_IFMT) {
3399        case S_IFREG:
3400                fd = open(path, O_RDONLY);
3401                if (fd < 0)
3402                        return error_errno("open(\"%s\")", path);
3403                if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3404                        return error("%s: failed to insert into database",
3405                                     path);
3406                break;
3407        case S_IFLNK:
3408                if (strbuf_readlink(&sb, path, st->st_size))
3409                        return error_errno("readlink(\"%s\")", path);
3410                if (!(flags & HASH_WRITE_OBJECT))
3411                        hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3412                else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3413                        return error("%s: failed to insert into database",
3414                                     path);
3415                strbuf_release(&sb);
3416                break;
3417        case S_IFDIR:
3418                return resolve_gitlink_ref(path, "HEAD", sha1);
3419        default:
3420                return error("%s: unsupported file type", path);
3421        }
3422        return 0;
3423}
3424
3425int read_pack_header(int fd, struct pack_header *header)
3426{
3427        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3428                /* "eof before pack header was fully read" */
3429                return PH_ERROR_EOF;
3430
3431        if (header->hdr_signature != htonl(PACK_SIGNATURE))
3432                /* "protocol error (pack signature mismatch detected)" */
3433                return PH_ERROR_PACK_SIGNATURE;
3434        if (!pack_version_ok(header->hdr_version))
3435                /* "protocol error (pack version unsupported)" */
3436                return PH_ERROR_PROTOCOL;
3437        return 0;
3438}
3439
3440void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3441{
3442        enum object_type type = sha1_object_info(sha1, NULL);
3443        if (type < 0)
3444                die("%s is not a valid object", sha1_to_hex(sha1));
3445        if (type != expect)
3446                die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3447                    typename(expect));
3448}
3449
3450static int for_each_file_in_obj_subdir(int subdir_nr,
3451                                       struct strbuf *path,
3452                                       each_loose_object_fn obj_cb,
3453                                       each_loose_cruft_fn cruft_cb,
3454                                       each_loose_subdir_fn subdir_cb,
3455                                       void *data)
3456{
3457        size_t baselen = path->len;
3458        DIR *dir = opendir(path->buf);
3459        struct dirent *de;
3460        int r = 0;
3461
3462        if (!dir) {
3463                if (errno == ENOENT)
3464                        return 0;
3465                return error_errno("unable to open %s", path->buf);
3466        }
3467
3468        while ((de = readdir(dir))) {
3469                if (is_dot_or_dotdot(de->d_name))
3470                        continue;
3471
3472                strbuf_setlen(path, baselen);
3473                strbuf_addf(path, "/%s", de->d_name);
3474
3475                if (strlen(de->d_name) == 38)  {
3476                        char hex[41];
3477                        unsigned char sha1[20];
3478
3479                        snprintf(hex, sizeof(hex), "%02x%s",
3480                                 subdir_nr, de->d_name);
3481                        if (!get_sha1_hex(hex, sha1)) {
3482                                if (obj_cb) {
3483                                        r = obj_cb(sha1, path->buf, data);
3484                                        if (r)
3485                                                break;
3486                                }
3487                                continue;
3488                        }
3489                }
3490
3491                if (cruft_cb) {
3492                        r = cruft_cb(de->d_name, path->buf, data);
3493                        if (r)
3494                                break;
3495                }
3496        }
3497        closedir(dir);
3498
3499        strbuf_setlen(path, baselen);
3500        if (!r && subdir_cb)
3501                r = subdir_cb(subdir_nr, path->buf, data);
3502
3503        return r;
3504}
3505
3506int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3507                            each_loose_object_fn obj_cb,
3508                            each_loose_cruft_fn cruft_cb,
3509                            each_loose_subdir_fn subdir_cb,
3510                            void *data)
3511{
3512        size_t baselen = path->len;
3513        int r = 0;
3514        int i;
3515
3516        for (i = 0; i < 256; i++) {
3517                strbuf_addf(path, "/%02x", i);
3518                r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3519                                                subdir_cb, data);
3520                strbuf_setlen(path, baselen);
3521                if (r)
3522                        break;
3523        }
3524
3525        return r;
3526}
3527
3528int for_each_loose_file_in_objdir(const char *path,
3529                                  each_loose_object_fn obj_cb,
3530                                  each_loose_cruft_fn cruft_cb,
3531                                  each_loose_subdir_fn subdir_cb,
3532                                  void *data)
3533{
3534        struct strbuf buf = STRBUF_INIT;
3535        int r;
3536
3537        strbuf_addstr(&buf, path);
3538        r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3539                                              subdir_cb, data);
3540        strbuf_release(&buf);
3541
3542        return r;
3543}
3544
3545struct loose_alt_odb_data {
3546        each_loose_object_fn *cb;
3547        void *data;
3548};
3549
3550static int loose_from_alt_odb(struct alternate_object_database *alt,
3551                              void *vdata)
3552{
3553        struct loose_alt_odb_data *data = vdata;
3554        struct strbuf buf = STRBUF_INIT;
3555        int r;
3556
3557        /* copy base not including trailing '/' */
3558        strbuf_add(&buf, alt->base, alt->name - alt->base - 1);
3559        r = for_each_loose_file_in_objdir_buf(&buf,
3560                                              data->cb, NULL, NULL,
3561                                              data->data);
3562        strbuf_release(&buf);
3563        return r;
3564}
3565
3566int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3567{
3568        struct loose_alt_odb_data alt;
3569        int r;
3570
3571        r = for_each_loose_file_in_objdir(get_object_directory(),
3572                                          cb, NULL, NULL, data);
3573        if (r)
3574                return r;
3575
3576        if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3577                return 0;
3578
3579        alt.cb = cb;
3580        alt.data = data;
3581        return foreach_alt_odb(loose_from_alt_odb, &alt);
3582}
3583
3584static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3585{
3586        uint32_t i;
3587        int r = 0;
3588
3589        for (i = 0; i < p->num_objects; i++) {
3590                const unsigned char *sha1 = nth_packed_object_sha1(p, i);
3591
3592                if (!sha1)
3593                        return error("unable to get sha1 of object %u in %s",
3594                                     i, p->pack_name);
3595
3596                r = cb(sha1, p, i, data);
3597                if (r)
3598                        break;
3599        }
3600        return r;
3601}
3602
3603int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3604{
3605        struct packed_git *p;
3606        int r = 0;
3607        int pack_errors = 0;
3608
3609        prepare_packed_git();
3610        for (p = packed_git; p; p = p->next) {
3611                if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3612                        continue;
3613                if (open_pack_index(p)) {
3614                        pack_errors = 1;
3615                        continue;
3616                }
3617                r = for_each_object_in_pack(p, cb, data);
3618                if (r)
3619                        break;
3620        }
3621        return r ? r : pack_errors;
3622}