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