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