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