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