sha1_file.con commit Consolidate ignore_packed logic more (386cb77)
   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 "delta.h"
  11#include "pack.h"
  12#include "blob.h"
  13#include "commit.h"
  14#include "tag.h"
  15#include "tree.h"
  16#include "refs.h"
  17#include "pack-revindex.h"
  18#include "sha1-lookup.h"
  19#include "diff.h"
  20#include "revision.h"
  21
  22#ifndef O_NOATIME
  23#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
  24#define O_NOATIME 01000000
  25#else
  26#define O_NOATIME 0
  27#endif
  28#endif
  29
  30#ifdef NO_C99_FORMAT
  31#define SZ_FMT "lu"
  32static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
  33#else
  34#define SZ_FMT "zu"
  35static size_t sz_fmt(size_t s) { return s; }
  36#endif
  37
  38const unsigned char null_sha1[20];
  39
  40const signed char hexval_table[256] = {
  41         -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
  42         -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
  43         -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
  44         -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
  45         -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
  46         -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
  47          0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
  48          8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
  49         -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
  50         -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
  51         -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
  52         -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
  53         -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
  54         -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
  55         -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
  56         -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
  57         -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
  58         -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
  59         -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
  60         -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
  61         -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
  62         -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
  63         -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
  64         -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
  65         -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
  66         -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
  67         -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
  68         -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
  69         -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
  70         -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
  71         -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
  72         -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
  73};
  74
  75int get_sha1_hex(const char *hex, unsigned char *sha1)
  76{
  77        int i;
  78        for (i = 0; i < 20; i++) {
  79                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
  80                if (val & ~0xff)
  81                        return -1;
  82                *sha1++ = val;
  83                hex += 2;
  84        }
  85        return 0;
  86}
  87
  88static inline int offset_1st_component(const char *path)
  89{
  90        if (has_dos_drive_prefix(path))
  91                return 2 + (path[2] == '/');
  92        return *path == '/';
  93}
  94
  95int safe_create_leading_directories(char *path)
  96{
  97        char *pos = path + offset_1st_component(path);
  98        struct stat st;
  99
 100        while (pos) {
 101                pos = strchr(pos, '/');
 102                if (!pos)
 103                        break;
 104                *pos = 0;
 105                if (!stat(path, &st)) {
 106                        /* path exists */
 107                        if (!S_ISDIR(st.st_mode)) {
 108                                *pos = '/';
 109                                return -3;
 110                        }
 111                }
 112                else if (mkdir(path, 0777)) {
 113                        *pos = '/';
 114                        return -1;
 115                }
 116                else if (adjust_shared_perm(path)) {
 117                        *pos = '/';
 118                        return -2;
 119                }
 120                *pos++ = '/';
 121        }
 122        return 0;
 123}
 124
 125int safe_create_leading_directories_const(const char *path)
 126{
 127        /* path points to cache entries, so xstrdup before messing with it */
 128        char *buf = xstrdup(path);
 129        int result = safe_create_leading_directories(buf);
 130        free(buf);
 131        return result;
 132}
 133
 134char *sha1_to_hex(const unsigned char *sha1)
 135{
 136        static int bufno;
 137        static char hexbuffer[4][50];
 138        static const char hex[] = "0123456789abcdef";
 139        char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
 140        int i;
 141
 142        for (i = 0; i < 20; i++) {
 143                unsigned int val = *sha1++;
 144                *buf++ = hex[val >> 4];
 145                *buf++ = hex[val & 0xf];
 146        }
 147        *buf = '\0';
 148
 149        return buffer;
 150}
 151
 152static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
 153{
 154        int i;
 155        for (i = 0; i < 20; i++) {
 156                static char hex[] = "0123456789abcdef";
 157                unsigned int val = sha1[i];
 158                char *pos = pathbuf + i*2 + (i > 0);
 159                *pos++ = hex[val >> 4];
 160                *pos = hex[val & 0xf];
 161        }
 162}
 163
 164/*
 165 * NOTE! This returns a statically allocated buffer, so you have to be
 166 * careful about using it. Do an "xstrdup()" if you need to save the
 167 * filename.
 168 *
 169 * Also note that this returns the location for creating.  Reading
 170 * SHA1 file can happen from any alternate directory listed in the
 171 * DB_ENVIRONMENT environment variable if it is not found in
 172 * the primary object database.
 173 */
 174char *sha1_file_name(const unsigned char *sha1)
 175{
 176        static char *name, *base;
 177
 178        if (!base) {
 179                const char *sha1_file_directory = get_object_directory();
 180                int len = strlen(sha1_file_directory);
 181                base = xmalloc(len + 60);
 182                memcpy(base, sha1_file_directory, len);
 183                memset(base+len, 0, 60);
 184                base[len] = '/';
 185                base[len+3] = '/';
 186                name = base + len + 1;
 187        }
 188        fill_sha1_path(name, sha1);
 189        return base;
 190}
 191
 192static char *sha1_get_pack_name(const unsigned char *sha1,
 193                                char **name, char **base, const char *which)
 194{
 195        static const char hex[] = "0123456789abcdef";
 196        char *buf;
 197        int i;
 198
 199        if (!*base) {
 200                const char *sha1_file_directory = get_object_directory();
 201                int len = strlen(sha1_file_directory);
 202                *base = xmalloc(len + 60);
 203                sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
 204                        sha1_file_directory, which);
 205                *name = *base + len + 11;
 206        }
 207
 208        buf = *name;
 209
 210        for (i = 0; i < 20; i++) {
 211                unsigned int val = *sha1++;
 212                *buf++ = hex[val >> 4];
 213                *buf++ = hex[val & 0xf];
 214        }
 215
 216        return *base;
 217}
 218
 219char *sha1_pack_name(const unsigned char *sha1)
 220{
 221        static char *name, *base;
 222
 223        return sha1_get_pack_name(sha1, &name, &base, "pack");
 224}
 225
 226char *sha1_pack_index_name(const unsigned char *sha1)
 227{
 228        static char *name, *base;
 229
 230        return sha1_get_pack_name(sha1, &name, &base, "idx");
 231}
 232
 233struct alternate_object_database *alt_odb_list;
 234static struct alternate_object_database **alt_odb_tail;
 235
 236static void read_info_alternates(const char * alternates, int depth);
 237
 238/*
 239 * Prepare alternate object database registry.
 240 *
 241 * The variable alt_odb_list points at the list of struct
 242 * alternate_object_database.  The elements on this list come from
 243 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
 244 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
 245 * whose contents is similar to that environment variable but can be
 246 * LF separated.  Its base points at a statically allocated buffer that
 247 * contains "/the/directory/corresponding/to/.git/objects/...", while
 248 * its name points just after the slash at the end of ".git/objects/"
 249 * in the example above, and has enough space to hold 40-byte hex
 250 * SHA1, an extra slash for the first level indirection, and the
 251 * terminating NUL.
 252 */
 253static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
 254{
 255        struct stat st;
 256        const char *objdir = get_object_directory();
 257        struct alternate_object_database *ent;
 258        struct alternate_object_database *alt;
 259        /* 43 = 40-byte + 2 '/' + terminating NUL */
 260        int pfxlen = len;
 261        int entlen = pfxlen + 43;
 262        int base_len = -1;
 263
 264        if (!is_absolute_path(entry) && relative_base) {
 265                /* Relative alt-odb */
 266                if (base_len < 0)
 267                        base_len = strlen(relative_base) + 1;
 268                entlen += base_len;
 269                pfxlen += base_len;
 270        }
 271        ent = xmalloc(sizeof(*ent) + entlen);
 272
 273        if (!is_absolute_path(entry) && relative_base) {
 274                memcpy(ent->base, relative_base, base_len - 1);
 275                ent->base[base_len - 1] = '/';
 276                memcpy(ent->base + base_len, entry, len);
 277        }
 278        else
 279                memcpy(ent->base, entry, pfxlen);
 280
 281        ent->name = ent->base + pfxlen + 1;
 282        ent->base[pfxlen + 3] = '/';
 283        ent->base[pfxlen] = ent->base[entlen-1] = 0;
 284
 285        /* Detect cases where alternate disappeared */
 286        if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
 287                error("object directory %s does not exist; "
 288                      "check .git/objects/info/alternates.",
 289                      ent->base);
 290                free(ent);
 291                return -1;
 292        }
 293
 294        /* Prevent the common mistake of listing the same
 295         * thing twice, or object directory itself.
 296         */
 297        for (alt = alt_odb_list; alt; alt = alt->next) {
 298                if (!memcmp(ent->base, alt->base, pfxlen)) {
 299                        free(ent);
 300                        return -1;
 301                }
 302        }
 303        if (!memcmp(ent->base, objdir, pfxlen)) {
 304                free(ent);
 305                return -1;
 306        }
 307
 308        /* add the alternate entry */
 309        *alt_odb_tail = ent;
 310        alt_odb_tail = &(ent->next);
 311        ent->next = NULL;
 312
 313        /* recursively add alternates */
 314        read_info_alternates(ent->base, depth + 1);
 315
 316        ent->base[pfxlen] = '/';
 317
 318        return 0;
 319}
 320
 321static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
 322                                 const char *relative_base, int depth)
 323{
 324        const char *cp, *last;
 325
 326        if (depth > 5) {
 327                error("%s: ignoring alternate object stores, nesting too deep.",
 328                                relative_base);
 329                return;
 330        }
 331
 332        last = alt;
 333        while (last < ep) {
 334                cp = last;
 335                if (cp < ep && *cp == '#') {
 336                        while (cp < ep && *cp != sep)
 337                                cp++;
 338                        last = cp + 1;
 339                        continue;
 340                }
 341                while (cp < ep && *cp != sep)
 342                        cp++;
 343                if (last != cp) {
 344                        if (!is_absolute_path(last) && depth) {
 345                                error("%s: ignoring relative alternate object store %s",
 346                                                relative_base, last);
 347                        } else {
 348                                link_alt_odb_entry(last, cp - last,
 349                                                relative_base, depth);
 350                        }
 351                }
 352                while (cp < ep && *cp == sep)
 353                        cp++;
 354                last = cp;
 355        }
 356}
 357
 358static void read_info_alternates(const char * relative_base, int depth)
 359{
 360        char *map;
 361        size_t mapsz;
 362        struct stat st;
 363        const char alt_file_name[] = "info/alternates";
 364        /* Given that relative_base is no longer than PATH_MAX,
 365           ensure that "path" has enough space to append "/", the
 366           file name, "info/alternates", and a trailing NUL.  */
 367        char path[PATH_MAX + 1 + sizeof alt_file_name];
 368        int fd;
 369
 370        sprintf(path, "%s/%s", relative_base, alt_file_name);
 371        fd = open(path, O_RDONLY);
 372        if (fd < 0)
 373                return;
 374        if (fstat(fd, &st) || (st.st_size == 0)) {
 375                close(fd);
 376                return;
 377        }
 378        mapsz = xsize_t(st.st_size);
 379        map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
 380        close(fd);
 381
 382        link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
 383
 384        munmap(map, mapsz);
 385}
 386
 387void add_to_alternates_file(const char *reference)
 388{
 389        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 390        int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
 391        char *alt = mkpath("%s/objects\n", reference);
 392        write_or_die(fd, alt, strlen(alt));
 393        if (commit_lock_file(lock))
 394                die("could not close alternates file");
 395        if (alt_odb_tail)
 396                link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
 397}
 398
 399void prepare_alt_odb(void)
 400{
 401        const char *alt;
 402
 403        if (alt_odb_tail)
 404                return;
 405
 406        alt = getenv(ALTERNATE_DB_ENVIRONMENT);
 407        if (!alt) alt = "";
 408
 409        alt_odb_tail = &alt_odb_list;
 410        link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
 411
 412        read_info_alternates(get_object_directory(), 0);
 413}
 414
 415static int has_loose_object_local(const unsigned char *sha1)
 416{
 417        char *name = sha1_file_name(sha1);
 418        return !access(name, F_OK);
 419}
 420
 421int has_loose_object_nonlocal(const unsigned char *sha1)
 422{
 423        struct alternate_object_database *alt;
 424        prepare_alt_odb();
 425        for (alt = alt_odb_list; alt; alt = alt->next) {
 426                fill_sha1_path(alt->name, sha1);
 427                if (!access(alt->base, F_OK))
 428                        return 1;
 429        }
 430        return 0;
 431}
 432
 433static int has_loose_object(const unsigned char *sha1)
 434{
 435        return has_loose_object_local(sha1) ||
 436               has_loose_object_nonlocal(sha1);
 437}
 438
 439static unsigned int pack_used_ctr;
 440static unsigned int pack_mmap_calls;
 441static unsigned int peak_pack_open_windows;
 442static unsigned int pack_open_windows;
 443static size_t peak_pack_mapped;
 444static size_t pack_mapped;
 445struct packed_git *packed_git;
 446
 447void pack_report(void)
 448{
 449        fprintf(stderr,
 450                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
 451                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
 452                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
 453                sz_fmt(getpagesize()),
 454                sz_fmt(packed_git_window_size),
 455                sz_fmt(packed_git_limit));
 456        fprintf(stderr,
 457                "pack_report: pack_used_ctr            = %10u\n"
 458                "pack_report: pack_mmap_calls          = %10u\n"
 459                "pack_report: pack_open_windows        = %10u / %10u\n"
 460                "pack_report: pack_mapped              = "
 461                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
 462                pack_used_ctr,
 463                pack_mmap_calls,
 464                pack_open_windows, peak_pack_open_windows,
 465                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
 466}
 467
 468static int check_packed_git_idx(const char *path,  struct packed_git *p)
 469{
 470        void *idx_map;
 471        struct pack_idx_header *hdr;
 472        size_t idx_size;
 473        uint32_t version, nr, i, *index;
 474        int fd = open(path, O_RDONLY);
 475        struct stat st;
 476
 477        if (fd < 0)
 478                return -1;
 479        if (fstat(fd, &st)) {
 480                close(fd);
 481                return -1;
 482        }
 483        idx_size = xsize_t(st.st_size);
 484        if (idx_size < 4 * 256 + 20 + 20) {
 485                close(fd);
 486                return error("index file %s is too small", path);
 487        }
 488        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
 489        close(fd);
 490
 491        hdr = idx_map;
 492        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
 493                version = ntohl(hdr->idx_version);
 494                if (version < 2 || version > 2) {
 495                        munmap(idx_map, idx_size);
 496                        return error("index file %s is version %"PRIu32
 497                                     " and is not supported by this binary"
 498                                     " (try upgrading GIT to a newer version)",
 499                                     path, version);
 500                }
 501        } else
 502                version = 1;
 503
 504        nr = 0;
 505        index = idx_map;
 506        if (version > 1)
 507                index += 2;  /* skip index header */
 508        for (i = 0; i < 256; i++) {
 509                uint32_t n = ntohl(index[i]);
 510                if (n < nr) {
 511                        munmap(idx_map, idx_size);
 512                        return error("non-monotonic index %s", path);
 513                }
 514                nr = n;
 515        }
 516
 517        if (version == 1) {
 518                /*
 519                 * Total size:
 520                 *  - 256 index entries 4 bytes each
 521                 *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 522                 *  - 20-byte SHA1 of the packfile
 523                 *  - 20-byte SHA1 file checksum
 524                 */
 525                if (idx_size != 4*256 + nr * 24 + 20 + 20) {
 526                        munmap(idx_map, idx_size);
 527                        return error("wrong index v1 file size in %s", path);
 528                }
 529        } else if (version == 2) {
 530                /*
 531                 * Minimum size:
 532                 *  - 8 bytes of header
 533                 *  - 256 index entries 4 bytes each
 534                 *  - 20-byte sha1 entry * nr
 535                 *  - 4-byte crc entry * nr
 536                 *  - 4-byte offset entry * nr
 537                 *  - 20-byte SHA1 of the packfile
 538                 *  - 20-byte SHA1 file checksum
 539                 * And after the 4-byte offset table might be a
 540                 * variable sized table containing 8-byte entries
 541                 * for offsets larger than 2^31.
 542                 */
 543                unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
 544                unsigned long max_size = min_size;
 545                if (nr)
 546                        max_size += (nr - 1)*8;
 547                if (idx_size < min_size || idx_size > max_size) {
 548                        munmap(idx_map, idx_size);
 549                        return error("wrong index v2 file size in %s", path);
 550                }
 551                if (idx_size != min_size &&
 552                    /*
 553                     * make sure we can deal with large pack offsets.
 554                     * 31-bit signed offset won't be enough, neither
 555                     * 32-bit unsigned one will be.
 556                     */
 557                    (sizeof(off_t) <= 4)) {
 558                        munmap(idx_map, idx_size);
 559                        return error("pack too large for current definition of off_t in %s", path);
 560                }
 561        }
 562
 563        p->index_version = version;
 564        p->index_data = idx_map;
 565        p->index_size = idx_size;
 566        p->num_objects = nr;
 567        return 0;
 568}
 569
 570int open_pack_index(struct packed_git *p)
 571{
 572        char *idx_name;
 573        int ret;
 574
 575        if (p->index_data)
 576                return 0;
 577
 578        idx_name = xstrdup(p->pack_name);
 579        strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
 580        ret = check_packed_git_idx(idx_name, p);
 581        free(idx_name);
 582        return ret;
 583}
 584
 585static void scan_windows(struct packed_git *p,
 586        struct packed_git **lru_p,
 587        struct pack_window **lru_w,
 588        struct pack_window **lru_l)
 589{
 590        struct pack_window *w, *w_l;
 591
 592        for (w_l = NULL, w = p->windows; w; w = w->next) {
 593                if (!w->inuse_cnt) {
 594                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 595                                *lru_p = p;
 596                                *lru_w = w;
 597                                *lru_l = w_l;
 598                        }
 599                }
 600                w_l = w;
 601        }
 602}
 603
 604static int unuse_one_window(struct packed_git *current, int keep_fd)
 605{
 606        struct packed_git *p, *lru_p = NULL;
 607        struct pack_window *lru_w = NULL, *lru_l = NULL;
 608
 609        if (current)
 610                scan_windows(current, &lru_p, &lru_w, &lru_l);
 611        for (p = packed_git; p; p = p->next)
 612                scan_windows(p, &lru_p, &lru_w, &lru_l);
 613        if (lru_p) {
 614                munmap(lru_w->base, lru_w->len);
 615                pack_mapped -= lru_w->len;
 616                if (lru_l)
 617                        lru_l->next = lru_w->next;
 618                else {
 619                        lru_p->windows = lru_w->next;
 620                        if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
 621                                close(lru_p->pack_fd);
 622                                lru_p->pack_fd = -1;
 623                        }
 624                }
 625                free(lru_w);
 626                pack_open_windows--;
 627                return 1;
 628        }
 629        return 0;
 630}
 631
 632void release_pack_memory(size_t need, int fd)
 633{
 634        size_t cur = pack_mapped;
 635        while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
 636                ; /* nothing */
 637}
 638
 639void close_pack_windows(struct packed_git *p)
 640{
 641        while (p->windows) {
 642                struct pack_window *w = p->windows;
 643
 644                if (w->inuse_cnt)
 645                        die("pack '%s' still has open windows to it",
 646                            p->pack_name);
 647                munmap(w->base, w->len);
 648                pack_mapped -= w->len;
 649                pack_open_windows--;
 650                p->windows = w->next;
 651                free(w);
 652        }
 653}
 654
 655void unuse_pack(struct pack_window **w_cursor)
 656{
 657        struct pack_window *w = *w_cursor;
 658        if (w) {
 659                w->inuse_cnt--;
 660                *w_cursor = NULL;
 661        }
 662}
 663
 664/*
 665 * This is used by git-repack in case a newly created pack happens to
 666 * contain the same set of objects as an existing one.  In that case
 667 * the resulting file might be different even if its name would be the
 668 * same.  It is best to close any reference to the old pack before it is
 669 * replaced on disk.  Of course no index pointers nor windows for given pack
 670 * must subsist at this point.  If ever objects from this pack are requested
 671 * again, the new version of the pack will be reinitialized through
 672 * reprepare_packed_git().
 673 */
 674void free_pack_by_name(const char *pack_name)
 675{
 676        struct packed_git *p, **pp = &packed_git;
 677
 678        while (*pp) {
 679                p = *pp;
 680                if (strcmp(pack_name, p->pack_name) == 0) {
 681                        close_pack_windows(p);
 682                        if (p->pack_fd != -1)
 683                                close(p->pack_fd);
 684                        if (p->index_data)
 685                                munmap((void *)p->index_data, p->index_size);
 686                        free(p->bad_object_sha1);
 687                        *pp = p->next;
 688                        free(p);
 689                        return;
 690                }
 691                pp = &p->next;
 692        }
 693}
 694
 695/*
 696 * Do not call this directly as this leaks p->pack_fd on error return;
 697 * call open_packed_git() instead.
 698 */
 699static int open_packed_git_1(struct packed_git *p)
 700{
 701        struct stat st;
 702        struct pack_header hdr;
 703        unsigned char sha1[20];
 704        unsigned char *idx_sha1;
 705        long fd_flag;
 706
 707        if (!p->index_data && open_pack_index(p))
 708                return error("packfile %s index unavailable", p->pack_name);
 709
 710        p->pack_fd = open(p->pack_name, O_RDONLY);
 711        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 712                return -1;
 713
 714        /* If we created the struct before we had the pack we lack size. */
 715        if (!p->pack_size) {
 716                if (!S_ISREG(st.st_mode))
 717                        return error("packfile %s not a regular file", p->pack_name);
 718                p->pack_size = st.st_size;
 719        } else if (p->pack_size != st.st_size)
 720                return error("packfile %s size changed", p->pack_name);
 721
 722        /* We leave these file descriptors open with sliding mmap;
 723         * there is no point keeping them open across exec(), though.
 724         */
 725        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 726        if (fd_flag < 0)
 727                return error("cannot determine file descriptor flags");
 728        fd_flag |= FD_CLOEXEC;
 729        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 730                return error("cannot set FD_CLOEXEC");
 731
 732        /* Verify we recognize this pack file format. */
 733        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 734                return error("file %s is far too short to be a packfile", p->pack_name);
 735        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 736                return error("file %s is not a GIT packfile", p->pack_name);
 737        if (!pack_version_ok(hdr.hdr_version))
 738                return error("packfile %s is version %"PRIu32" and not"
 739                        " supported (try upgrading GIT to a newer version)",
 740                        p->pack_name, ntohl(hdr.hdr_version));
 741
 742        /* Verify the pack matches its index. */
 743        if (p->num_objects != ntohl(hdr.hdr_entries))
 744                return error("packfile %s claims to have %"PRIu32" objects"
 745                             " while index indicates %"PRIu32" objects",
 746                             p->pack_name, ntohl(hdr.hdr_entries),
 747                             p->num_objects);
 748        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
 749                return error("end of packfile %s is unavailable", p->pack_name);
 750        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
 751                return error("packfile %s signature is unavailable", p->pack_name);
 752        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
 753        if (hashcmp(sha1, idx_sha1))
 754                return error("packfile %s does not match index", p->pack_name);
 755        return 0;
 756}
 757
 758static int open_packed_git(struct packed_git *p)
 759{
 760        if (!open_packed_git_1(p))
 761                return 0;
 762        if (p->pack_fd != -1) {
 763                close(p->pack_fd);
 764                p->pack_fd = -1;
 765        }
 766        return -1;
 767}
 768
 769static int in_window(struct pack_window *win, off_t offset)
 770{
 771        /* We must promise at least 20 bytes (one hash) after the
 772         * offset is available from this window, otherwise the offset
 773         * is not actually in this window and a different window (which
 774         * has that one hash excess) must be used.  This is to support
 775         * the object header and delta base parsing routines below.
 776         */
 777        off_t win_off = win->offset;
 778        return win_off <= offset
 779                && (offset + 20) <= (win_off + win->len);
 780}
 781
 782unsigned char* use_pack(struct packed_git *p,
 783                struct pack_window **w_cursor,
 784                off_t offset,
 785                unsigned int *left)
 786{
 787        struct pack_window *win = *w_cursor;
 788
 789        if (p->pack_fd == -1 && open_packed_git(p))
 790                die("packfile %s cannot be accessed", p->pack_name);
 791
 792        /* Since packfiles end in a hash of their content and its
 793         * pointless to ask for an offset into the middle of that
 794         * hash, and the in_window function above wouldn't match
 795         * don't allow an offset too close to the end of the file.
 796         */
 797        if (offset > (p->pack_size - 20))
 798                die("offset beyond end of packfile (truncated pack?)");
 799
 800        if (!win || !in_window(win, offset)) {
 801                if (win)
 802                        win->inuse_cnt--;
 803                for (win = p->windows; win; win = win->next) {
 804                        if (in_window(win, offset))
 805                                break;
 806                }
 807                if (!win) {
 808                        size_t window_align = packed_git_window_size / 2;
 809                        off_t len;
 810                        win = xcalloc(1, sizeof(*win));
 811                        win->offset = (offset / window_align) * window_align;
 812                        len = p->pack_size - win->offset;
 813                        if (len > packed_git_window_size)
 814                                len = packed_git_window_size;
 815                        win->len = (size_t)len;
 816                        pack_mapped += win->len;
 817                        while (packed_git_limit < pack_mapped
 818                                && unuse_one_window(p, p->pack_fd))
 819                                ; /* nothing */
 820                        win->base = xmmap(NULL, win->len,
 821                                PROT_READ, MAP_PRIVATE,
 822                                p->pack_fd, win->offset);
 823                        if (win->base == MAP_FAILED)
 824                                die("packfile %s cannot be mapped: %s",
 825                                        p->pack_name,
 826                                        strerror(errno));
 827                        pack_mmap_calls++;
 828                        pack_open_windows++;
 829                        if (pack_mapped > peak_pack_mapped)
 830                                peak_pack_mapped = pack_mapped;
 831                        if (pack_open_windows > peak_pack_open_windows)
 832                                peak_pack_open_windows = pack_open_windows;
 833                        win->next = p->windows;
 834                        p->windows = win;
 835                }
 836        }
 837        if (win != *w_cursor) {
 838                win->last_used = pack_used_ctr++;
 839                win->inuse_cnt++;
 840                *w_cursor = win;
 841        }
 842        offset -= win->offset;
 843        if (left)
 844                *left = win->len - xsize_t(offset);
 845        return win->base + offset;
 846}
 847
 848static struct packed_git *alloc_packed_git(int extra)
 849{
 850        struct packed_git *p = xmalloc(sizeof(*p) + extra);
 851        memset(p, 0, sizeof(*p));
 852        p->pack_fd = -1;
 853        return p;
 854}
 855
 856struct packed_git *add_packed_git(const char *path, int path_len, int local)
 857{
 858        struct stat st;
 859        struct packed_git *p = alloc_packed_git(path_len + 2);
 860
 861        /*
 862         * Make sure a corresponding .pack file exists and that
 863         * the index looks sane.
 864         */
 865        path_len -= strlen(".idx");
 866        if (path_len < 1) {
 867                free(p);
 868                return NULL;
 869        }
 870        memcpy(p->pack_name, path, path_len);
 871
 872        strcpy(p->pack_name + path_len, ".keep");
 873        if (!access(p->pack_name, F_OK))
 874                p->pack_keep = 1;
 875
 876        strcpy(p->pack_name + path_len, ".pack");
 877        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 878                free(p);
 879                return NULL;
 880        }
 881
 882        /* ok, it looks sane as far as we can check without
 883         * actually mapping the pack file.
 884         */
 885        p->pack_size = st.st_size;
 886        p->pack_local = local;
 887        p->mtime = st.st_mtime;
 888        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
 889                hashclr(p->sha1);
 890        return p;
 891}
 892
 893struct packed_git *parse_pack_index(unsigned char *sha1)
 894{
 895        const char *idx_path = sha1_pack_index_name(sha1);
 896        const char *path = sha1_pack_name(sha1);
 897        struct packed_git *p = alloc_packed_git(strlen(path) + 1);
 898
 899        strcpy(p->pack_name, path);
 900        hashcpy(p->sha1, sha1);
 901        if (check_packed_git_idx(idx_path, p)) {
 902                free(p);
 903                return NULL;
 904        }
 905
 906        return p;
 907}
 908
 909void install_packed_git(struct packed_git *pack)
 910{
 911        pack->next = packed_git;
 912        packed_git = pack;
 913}
 914
 915static void prepare_packed_git_one(char *objdir, int local)
 916{
 917        /* Ensure that this buffer is large enough so that we can
 918           append "/pack/" without clobbering the stack even if
 919           strlen(objdir) were PATH_MAX.  */
 920        char path[PATH_MAX + 1 + 4 + 1 + 1];
 921        int len;
 922        DIR *dir;
 923        struct dirent *de;
 924
 925        sprintf(path, "%s/pack", objdir);
 926        len = strlen(path);
 927        dir = opendir(path);
 928        if (!dir) {
 929                if (errno != ENOENT)
 930                        error("unable to open object pack directory: %s: %s",
 931                              path, strerror(errno));
 932                return;
 933        }
 934        path[len++] = '/';
 935        while ((de = readdir(dir)) != NULL) {
 936                int namelen = strlen(de->d_name);
 937                struct packed_git *p;
 938
 939                if (!has_extension(de->d_name, ".idx"))
 940                        continue;
 941
 942                if (len + namelen + 1 > sizeof(path))
 943                        continue;
 944
 945                /* Don't reopen a pack we already have. */
 946                strcpy(path + len, de->d_name);
 947                for (p = packed_git; p; p = p->next) {
 948                        if (!memcmp(path, p->pack_name, len + namelen - 4))
 949                                break;
 950                }
 951                if (p)
 952                        continue;
 953                /* See if it really is a valid .idx file with corresponding
 954                 * .pack file that we can map.
 955                 */
 956                p = add_packed_git(path, len + namelen, local);
 957                if (!p)
 958                        continue;
 959                install_packed_git(p);
 960        }
 961        closedir(dir);
 962}
 963
 964static int sort_pack(const void *a_, const void *b_)
 965{
 966        struct packed_git *a = *((struct packed_git **)a_);
 967        struct packed_git *b = *((struct packed_git **)b_);
 968        int st;
 969
 970        /*
 971         * Local packs tend to contain objects specific to our
 972         * variant of the project than remote ones.  In addition,
 973         * remote ones could be on a network mounted filesystem.
 974         * Favor local ones for these reasons.
 975         */
 976        st = a->pack_local - b->pack_local;
 977        if (st)
 978                return -st;
 979
 980        /*
 981         * Younger packs tend to contain more recent objects,
 982         * and more recent objects tend to get accessed more
 983         * often.
 984         */
 985        if (a->mtime < b->mtime)
 986                return 1;
 987        else if (a->mtime == b->mtime)
 988                return 0;
 989        return -1;
 990}
 991
 992static void rearrange_packed_git(void)
 993{
 994        struct packed_git **ary, *p;
 995        int i, n;
 996
 997        for (n = 0, p = packed_git; p; p = p->next)
 998                n++;
 999        if (n < 2)
1000                return;
1001
1002        /* prepare an array of packed_git for easier sorting */
1003        ary = xcalloc(n, sizeof(struct packed_git *));
1004        for (n = 0, p = packed_git; p; p = p->next)
1005                ary[n++] = p;
1006
1007        qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1008
1009        /* link them back again */
1010        for (i = 0; i < n - 1; i++)
1011                ary[i]->next = ary[i + 1];
1012        ary[n - 1]->next = NULL;
1013        packed_git = ary[0];
1014
1015        free(ary);
1016}
1017
1018static int prepare_packed_git_run_once = 0;
1019void prepare_packed_git(void)
1020{
1021        struct alternate_object_database *alt;
1022
1023        if (prepare_packed_git_run_once)
1024                return;
1025        prepare_packed_git_one(get_object_directory(), 1);
1026        prepare_alt_odb();
1027        for (alt = alt_odb_list; alt; alt = alt->next) {
1028                alt->name[-1] = 0;
1029                prepare_packed_git_one(alt->base, 0);
1030                alt->name[-1] = '/';
1031        }
1032        rearrange_packed_git();
1033        prepare_packed_git_run_once = 1;
1034}
1035
1036void reprepare_packed_git(void)
1037{
1038        discard_revindex();
1039        prepare_packed_git_run_once = 0;
1040        prepare_packed_git();
1041}
1042
1043static void mark_bad_packed_object(struct packed_git *p,
1044                                   const unsigned char *sha1)
1045{
1046        unsigned i;
1047        for (i = 0; i < p->num_bad_objects; i++)
1048                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1049                        return;
1050        p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1051        hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1052        p->num_bad_objects++;
1053}
1054
1055static int has_packed_and_bad(const unsigned char *sha1)
1056{
1057        struct packed_git *p;
1058        unsigned i;
1059
1060        for (p = packed_git; p; p = p->next)
1061                for (i = 0; i < p->num_bad_objects; i++)
1062                        if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1063                                return 1;
1064        return 0;
1065}
1066
1067int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1068{
1069        unsigned char real_sha1[20];
1070        hash_sha1_file(map, size, type, real_sha1);
1071        return hashcmp(sha1, real_sha1) ? -1 : 0;
1072}
1073
1074static int git_open_noatime(const char *name)
1075{
1076        static int sha1_file_open_flag = O_NOATIME;
1077        int fd = open(name, O_RDONLY | sha1_file_open_flag);
1078
1079        /* Might the failure be due to O_NOATIME? */
1080        if (fd < 0 && errno != ENOENT && sha1_file_open_flag) {
1081                fd = open(name, O_RDONLY);
1082                if (fd >= 0)
1083                        sha1_file_open_flag = 0;
1084        }
1085        return fd;
1086}
1087
1088static int open_sha1_file(const unsigned char *sha1)
1089{
1090        int fd;
1091        char *name = sha1_file_name(sha1);
1092        struct alternate_object_database *alt;
1093
1094        fd = git_open_noatime(name);
1095        if (fd >= 0)
1096                return fd;
1097
1098        prepare_alt_odb();
1099        errno = ENOENT;
1100        for (alt = alt_odb_list; alt; alt = alt->next) {
1101                name = alt->name;
1102                fill_sha1_path(name, sha1);
1103                fd = git_open_noatime(alt->base);
1104                if (fd >= 0)
1105                        return fd;
1106        }
1107        return -1;
1108}
1109
1110static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1111{
1112        void *map;
1113        int fd;
1114
1115        fd = open_sha1_file(sha1);
1116        map = NULL;
1117        if (fd >= 0) {
1118                struct stat st;
1119
1120                if (!fstat(fd, &st)) {
1121                        *size = xsize_t(st.st_size);
1122                        map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1123                }
1124                close(fd);
1125        }
1126        return map;
1127}
1128
1129static int legacy_loose_object(unsigned char *map)
1130{
1131        unsigned int word;
1132
1133        /*
1134         * Is it a zlib-compressed buffer? If so, the first byte
1135         * must be 0x78 (15-bit window size, deflated), and the
1136         * first 16-bit word is evenly divisible by 31
1137         */
1138        word = (map[0] << 8) + map[1];
1139        if (map[0] == 0x78 && !(word % 31))
1140                return 1;
1141        else
1142                return 0;
1143}
1144
1145unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1146{
1147        unsigned shift;
1148        unsigned char c;
1149        unsigned long size;
1150        unsigned long used = 0;
1151
1152        c = buf[used++];
1153        *type = (c >> 4) & 7;
1154        size = c & 15;
1155        shift = 4;
1156        while (c & 0x80) {
1157                if (len <= used)
1158                        return 0;
1159                if (sizeof(long) * 8 <= shift)
1160                        return 0;
1161                c = buf[used++];
1162                size += (c & 0x7f) << shift;
1163                shift += 7;
1164        }
1165        *sizep = size;
1166        return used;
1167}
1168
1169static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1170{
1171        unsigned long size, used;
1172        static const char valid_loose_object_type[8] = {
1173                0, /* OBJ_EXT */
1174                1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1175                0, /* "delta" and others are invalid in a loose object */
1176        };
1177        enum object_type type;
1178
1179        /* Get the data stream */
1180        memset(stream, 0, sizeof(*stream));
1181        stream->next_in = map;
1182        stream->avail_in = mapsize;
1183        stream->next_out = buffer;
1184        stream->avail_out = bufsiz;
1185
1186        if (legacy_loose_object(map)) {
1187                inflateInit(stream);
1188                return inflate(stream, 0);
1189        }
1190
1191
1192        /*
1193         * There used to be a second loose object header format which
1194         * was meant to mimic the in-pack format, allowing for direct
1195         * copy of the object data.  This format turned up not to be
1196         * really worth it and we don't write it any longer.  But we
1197         * can still read it.
1198         */
1199        used = unpack_object_header_gently(map, mapsize, &type, &size);
1200        if (!used || !valid_loose_object_type[type])
1201                return -1;
1202        map += used;
1203        mapsize -= used;
1204
1205        /* Set up the stream for the rest.. */
1206        stream->next_in = map;
1207        stream->avail_in = mapsize;
1208        inflateInit(stream);
1209
1210        /* And generate the fake traditional header */
1211        stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1212                                         typename(type), size);
1213        return 0;
1214}
1215
1216static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1217{
1218        int bytes = strlen(buffer) + 1;
1219        unsigned char *buf = xmalloc(1+size);
1220        unsigned long n;
1221        int status = Z_OK;
1222
1223        n = stream->total_out - bytes;
1224        if (n > size)
1225                n = size;
1226        memcpy(buf, (char *) buffer + bytes, n);
1227        bytes = n;
1228        if (bytes <= size) {
1229                /*
1230                 * The above condition must be (bytes <= size), not
1231                 * (bytes < size).  In other words, even though we
1232                 * expect no more output and set avail_out to zer0,
1233                 * the input zlib stream may have bytes that express
1234                 * "this concludes the stream", and we *do* want to
1235                 * eat that input.
1236                 *
1237                 * Otherwise we would not be able to test that we
1238                 * consumed all the input to reach the expected size;
1239                 * we also want to check that zlib tells us that all
1240                 * went well with status == Z_STREAM_END at the end.
1241                 */
1242                stream->next_out = buf + bytes;
1243                stream->avail_out = size - bytes;
1244                while (status == Z_OK)
1245                        status = inflate(stream, Z_FINISH);
1246        }
1247        buf[size] = 0;
1248        if (status == Z_STREAM_END && !stream->avail_in) {
1249                inflateEnd(stream);
1250                return buf;
1251        }
1252
1253        if (status < 0)
1254                error("corrupt loose object '%s'", sha1_to_hex(sha1));
1255        else if (stream->avail_in)
1256                error("garbage at end of loose object '%s'",
1257                      sha1_to_hex(sha1));
1258        free(buf);
1259        return NULL;
1260}
1261
1262/*
1263 * We used to just use "sscanf()", but that's actually way
1264 * too permissive for what we want to check. So do an anal
1265 * object header parse by hand.
1266 */
1267static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1268{
1269        char type[10];
1270        int i;
1271        unsigned long size;
1272
1273        /*
1274         * The type can be at most ten bytes (including the
1275         * terminating '\0' that we add), and is followed by
1276         * a space.
1277         */
1278        i = 0;
1279        for (;;) {
1280                char c = *hdr++;
1281                if (c == ' ')
1282                        break;
1283                type[i++] = c;
1284                if (i >= sizeof(type))
1285                        return -1;
1286        }
1287        type[i] = 0;
1288
1289        /*
1290         * The length must follow immediately, and be in canonical
1291         * decimal format (ie "010" is not valid).
1292         */
1293        size = *hdr++ - '0';
1294        if (size > 9)
1295                return -1;
1296        if (size) {
1297                for (;;) {
1298                        unsigned long c = *hdr - '0';
1299                        if (c > 9)
1300                                break;
1301                        hdr++;
1302                        size = size * 10 + c;
1303                }
1304        }
1305        *sizep = size;
1306
1307        /*
1308         * The length must be followed by a zero byte
1309         */
1310        return *hdr ? -1 : type_from_string(type);
1311}
1312
1313static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1314{
1315        int ret;
1316        z_stream stream;
1317        char hdr[8192];
1318
1319        ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1320        if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1321                return NULL;
1322
1323        return unpack_sha1_rest(&stream, hdr, *size, sha1);
1324}
1325
1326unsigned long get_size_from_delta(struct packed_git *p,
1327                                  struct pack_window **w_curs,
1328                                  off_t curpos)
1329{
1330        const unsigned char *data;
1331        unsigned char delta_head[20], *in;
1332        z_stream stream;
1333        int st;
1334
1335        memset(&stream, 0, sizeof(stream));
1336        stream.next_out = delta_head;
1337        stream.avail_out = sizeof(delta_head);
1338
1339        inflateInit(&stream);
1340        do {
1341                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1342                stream.next_in = in;
1343                st = inflate(&stream, Z_FINISH);
1344                curpos += stream.next_in - in;
1345        } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1346                 stream.total_out < sizeof(delta_head));
1347        inflateEnd(&stream);
1348        if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1349                die("delta data unpack-initial failed");
1350
1351        /* Examine the initial part of the delta to figure out
1352         * the result size.
1353         */
1354        data = delta_head;
1355
1356        /* ignore base size */
1357        get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1358
1359        /* Read the result size */
1360        return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1361}
1362
1363static off_t get_delta_base(struct packed_git *p,
1364                                    struct pack_window **w_curs,
1365                                    off_t *curpos,
1366                                    enum object_type type,
1367                                    off_t delta_obj_offset)
1368{
1369        unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1370        off_t base_offset;
1371
1372        /* use_pack() assured us we have [base_info, base_info + 20)
1373         * as a range that we can look at without walking off the
1374         * end of the mapped window.  Its actually the hash size
1375         * that is assured.  An OFS_DELTA longer than the hash size
1376         * is stupid, as then a REF_DELTA would be smaller to store.
1377         */
1378        if (type == OBJ_OFS_DELTA) {
1379                unsigned used = 0;
1380                unsigned char c = base_info[used++];
1381                base_offset = c & 127;
1382                while (c & 128) {
1383                        base_offset += 1;
1384                        if (!base_offset || MSB(base_offset, 7))
1385                                return 0;  /* overflow */
1386                        c = base_info[used++];
1387                        base_offset = (base_offset << 7) + (c & 127);
1388                }
1389                base_offset = delta_obj_offset - base_offset;
1390                if (base_offset >= delta_obj_offset)
1391                        return 0;  /* out of bound */
1392                *curpos += used;
1393        } else if (type == OBJ_REF_DELTA) {
1394                /* The base entry _must_ be in the same pack */
1395                base_offset = find_pack_entry_one(base_info, p);
1396                *curpos += 20;
1397        } else
1398                die("I am totally screwed");
1399        return base_offset;
1400}
1401
1402/* forward declaration for a mutually recursive function */
1403static int packed_object_info(struct packed_git *p, off_t offset,
1404                              unsigned long *sizep);
1405
1406static int packed_delta_info(struct packed_git *p,
1407                             struct pack_window **w_curs,
1408                             off_t curpos,
1409                             enum object_type type,
1410                             off_t obj_offset,
1411                             unsigned long *sizep)
1412{
1413        off_t base_offset;
1414
1415        base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1416        type = packed_object_info(p, base_offset, NULL);
1417
1418        /* We choose to only get the type of the base object and
1419         * ignore potentially corrupt pack file that expects the delta
1420         * based on a base with a wrong size.  This saves tons of
1421         * inflate() calls.
1422         */
1423        if (sizep)
1424                *sizep = get_size_from_delta(p, w_curs, curpos);
1425
1426        return type;
1427}
1428
1429static int unpack_object_header(struct packed_git *p,
1430                                struct pack_window **w_curs,
1431                                off_t *curpos,
1432                                unsigned long *sizep)
1433{
1434        unsigned char *base;
1435        unsigned int left;
1436        unsigned long used;
1437        enum object_type type;
1438
1439        /* use_pack() assures us we have [base, base + 20) available
1440         * as a range that we can look at at.  (Its actually the hash
1441         * size that is assured.)  With our object header encoding
1442         * the maximum deflated object size is 2^137, which is just
1443         * insane, so we know won't exceed what we have been given.
1444         */
1445        base = use_pack(p, w_curs, *curpos, &left);
1446        used = unpack_object_header_gently(base, left, &type, sizep);
1447        if (!used)
1448                die("object offset outside of pack file");
1449        *curpos += used;
1450
1451        return type;
1452}
1453
1454const char *packed_object_info_detail(struct packed_git *p,
1455                                      off_t obj_offset,
1456                                      unsigned long *size,
1457                                      unsigned long *store_size,
1458                                      unsigned int *delta_chain_length,
1459                                      unsigned char *base_sha1)
1460{
1461        struct pack_window *w_curs = NULL;
1462        off_t curpos;
1463        unsigned long dummy;
1464        unsigned char *next_sha1;
1465        enum object_type type;
1466        struct revindex_entry *revidx;
1467
1468        *delta_chain_length = 0;
1469        curpos = obj_offset;
1470        type = unpack_object_header(p, &w_curs, &curpos, size);
1471
1472        revidx = find_pack_revindex(p, obj_offset);
1473        *store_size = revidx[1].offset - obj_offset;
1474
1475        for (;;) {
1476                switch (type) {
1477                default:
1478                        die("pack %s contains unknown object type %d",
1479                            p->pack_name, type);
1480                case OBJ_COMMIT:
1481                case OBJ_TREE:
1482                case OBJ_BLOB:
1483                case OBJ_TAG:
1484                        unuse_pack(&w_curs);
1485                        return typename(type);
1486                case OBJ_OFS_DELTA:
1487                        obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1488                        if (!obj_offset)
1489                                die("pack %s contains bad delta base reference of type %s",
1490                                    p->pack_name, typename(type));
1491                        if (*delta_chain_length == 0) {
1492                                revidx = find_pack_revindex(p, obj_offset);
1493                                hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1494                        }
1495                        break;
1496                case OBJ_REF_DELTA:
1497                        next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1498                        if (*delta_chain_length == 0)
1499                                hashcpy(base_sha1, next_sha1);
1500                        obj_offset = find_pack_entry_one(next_sha1, p);
1501                        break;
1502                }
1503                (*delta_chain_length)++;
1504                curpos = obj_offset;
1505                type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1506        }
1507}
1508
1509static int packed_object_info(struct packed_git *p, off_t obj_offset,
1510                              unsigned long *sizep)
1511{
1512        struct pack_window *w_curs = NULL;
1513        unsigned long size;
1514        off_t curpos = obj_offset;
1515        enum object_type type;
1516
1517        type = unpack_object_header(p, &w_curs, &curpos, &size);
1518
1519        switch (type) {
1520        case OBJ_OFS_DELTA:
1521        case OBJ_REF_DELTA:
1522                type = packed_delta_info(p, &w_curs, curpos,
1523                                         type, obj_offset, sizep);
1524                break;
1525        case OBJ_COMMIT:
1526        case OBJ_TREE:
1527        case OBJ_BLOB:
1528        case OBJ_TAG:
1529                if (sizep)
1530                        *sizep = size;
1531                break;
1532        default:
1533                die("pack %s contains unknown object type %d",
1534                    p->pack_name, type);
1535        }
1536        unuse_pack(&w_curs);
1537        return type;
1538}
1539
1540static void *unpack_compressed_entry(struct packed_git *p,
1541                                    struct pack_window **w_curs,
1542                                    off_t curpos,
1543                                    unsigned long size)
1544{
1545        int st;
1546        z_stream stream;
1547        unsigned char *buffer, *in;
1548
1549        buffer = xmalloc(size + 1);
1550        buffer[size] = 0;
1551        memset(&stream, 0, sizeof(stream));
1552        stream.next_out = buffer;
1553        stream.avail_out = size;
1554
1555        inflateInit(&stream);
1556        do {
1557                in = use_pack(p, w_curs, curpos, &stream.avail_in);
1558                stream.next_in = in;
1559                st = inflate(&stream, Z_FINISH);
1560                curpos += stream.next_in - in;
1561        } while (st == Z_OK || st == Z_BUF_ERROR);
1562        inflateEnd(&stream);
1563        if ((st != Z_STREAM_END) || stream.total_out != size) {
1564                free(buffer);
1565                return NULL;
1566        }
1567
1568        return buffer;
1569}
1570
1571#define MAX_DELTA_CACHE (256)
1572
1573static size_t delta_base_cached;
1574
1575static struct delta_base_cache_lru_list {
1576        struct delta_base_cache_lru_list *prev;
1577        struct delta_base_cache_lru_list *next;
1578} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1579
1580static struct delta_base_cache_entry {
1581        struct delta_base_cache_lru_list lru;
1582        void *data;
1583        struct packed_git *p;
1584        off_t base_offset;
1585        unsigned long size;
1586        enum object_type type;
1587} delta_base_cache[MAX_DELTA_CACHE];
1588
1589static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1590{
1591        unsigned long hash;
1592
1593        hash = (unsigned long)p + (unsigned long)base_offset;
1594        hash += (hash >> 8) + (hash >> 16);
1595        return hash % MAX_DELTA_CACHE;
1596}
1597
1598static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1599        unsigned long *base_size, enum object_type *type, int keep_cache)
1600{
1601        void *ret;
1602        unsigned long hash = pack_entry_hash(p, base_offset);
1603        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1604
1605        ret = ent->data;
1606        if (ret && ent->p == p && ent->base_offset == base_offset)
1607                goto found_cache_entry;
1608        return unpack_entry(p, base_offset, type, base_size);
1609
1610found_cache_entry:
1611        if (!keep_cache) {
1612                ent->data = NULL;
1613                ent->lru.next->prev = ent->lru.prev;
1614                ent->lru.prev->next = ent->lru.next;
1615                delta_base_cached -= ent->size;
1616        } else {
1617                ret = xmemdupz(ent->data, ent->size);
1618        }
1619        *type = ent->type;
1620        *base_size = ent->size;
1621        return ret;
1622}
1623
1624static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1625{
1626        if (ent->data) {
1627                free(ent->data);
1628                ent->data = NULL;
1629                ent->lru.next->prev = ent->lru.prev;
1630                ent->lru.prev->next = ent->lru.next;
1631                delta_base_cached -= ent->size;
1632        }
1633}
1634
1635static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1636        void *base, unsigned long base_size, enum object_type type)
1637{
1638        unsigned long hash = pack_entry_hash(p, base_offset);
1639        struct delta_base_cache_entry *ent = delta_base_cache + hash;
1640        struct delta_base_cache_lru_list *lru;
1641
1642        release_delta_base_cache(ent);
1643        delta_base_cached += base_size;
1644
1645        for (lru = delta_base_cache_lru.next;
1646             delta_base_cached > delta_base_cache_limit
1647             && lru != &delta_base_cache_lru;
1648             lru = lru->next) {
1649                struct delta_base_cache_entry *f = (void *)lru;
1650                if (f->type == OBJ_BLOB)
1651                        release_delta_base_cache(f);
1652        }
1653        for (lru = delta_base_cache_lru.next;
1654             delta_base_cached > delta_base_cache_limit
1655             && lru != &delta_base_cache_lru;
1656             lru = lru->next) {
1657                struct delta_base_cache_entry *f = (void *)lru;
1658                release_delta_base_cache(f);
1659        }
1660
1661        ent->p = p;
1662        ent->base_offset = base_offset;
1663        ent->type = type;
1664        ent->data = base;
1665        ent->size = base_size;
1666        ent->lru.next = &delta_base_cache_lru;
1667        ent->lru.prev = delta_base_cache_lru.prev;
1668        delta_base_cache_lru.prev->next = &ent->lru;
1669        delta_base_cache_lru.prev = &ent->lru;
1670}
1671
1672static void *unpack_delta_entry(struct packed_git *p,
1673                                struct pack_window **w_curs,
1674                                off_t curpos,
1675                                unsigned long delta_size,
1676                                off_t obj_offset,
1677                                enum object_type *type,
1678                                unsigned long *sizep)
1679{
1680        void *delta_data, *result, *base;
1681        unsigned long base_size;
1682        off_t base_offset;
1683
1684        base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1685        if (!base_offset) {
1686                error("failed to validate delta base reference "
1687                      "at offset %"PRIuMAX" from %s",
1688                      (uintmax_t)curpos, p->pack_name);
1689                return NULL;
1690        }
1691        unuse_pack(w_curs);
1692        base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1693        if (!base) {
1694                /*
1695                 * We're probably in deep shit, but let's try to fetch
1696                 * the required base anyway from another pack or loose.
1697                 * This is costly but should happen only in the presence
1698                 * of a corrupted pack, and is better than failing outright.
1699                 */
1700                struct revindex_entry *revidx = find_pack_revindex(p, base_offset);
1701                const unsigned char *base_sha1 =
1702                                        nth_packed_object_sha1(p, revidx->nr);
1703                error("failed to read delta base object %s"
1704                      " at offset %"PRIuMAX" from %s",
1705                      sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1706                      p->pack_name);
1707                mark_bad_packed_object(p, base_sha1);
1708                base = read_object(base_sha1, type, &base_size);
1709                if (!base)
1710                        return NULL;
1711        }
1712
1713        delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1714        if (!delta_data) {
1715                error("failed to unpack compressed delta "
1716                      "at offset %"PRIuMAX" from %s",
1717                      (uintmax_t)curpos, p->pack_name);
1718                free(base);
1719                return NULL;
1720        }
1721        result = patch_delta(base, base_size,
1722                             delta_data, delta_size,
1723                             sizep);
1724        if (!result)
1725                die("failed to apply delta");
1726        free(delta_data);
1727        add_delta_base_cache(p, base_offset, base, base_size, *type);
1728        return result;
1729}
1730
1731void *unpack_entry(struct packed_git *p, off_t obj_offset,
1732                   enum object_type *type, unsigned long *sizep)
1733{
1734        struct pack_window *w_curs = NULL;
1735        off_t curpos = obj_offset;
1736        void *data;
1737
1738        *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1739        switch (*type) {
1740        case OBJ_OFS_DELTA:
1741        case OBJ_REF_DELTA:
1742                data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1743                                          obj_offset, type, sizep);
1744                break;
1745        case OBJ_COMMIT:
1746        case OBJ_TREE:
1747        case OBJ_BLOB:
1748        case OBJ_TAG:
1749                data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1750                break;
1751        default:
1752                data = NULL;
1753                error("unknown object type %i at offset %"PRIuMAX" in %s",
1754                      *type, (uintmax_t)obj_offset, p->pack_name);
1755        }
1756        unuse_pack(&w_curs);
1757        return data;
1758}
1759
1760const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1761                                            uint32_t n)
1762{
1763        const unsigned char *index = p->index_data;
1764        if (!index) {
1765                if (open_pack_index(p))
1766                        return NULL;
1767                index = p->index_data;
1768        }
1769        if (n >= p->num_objects)
1770                return NULL;
1771        index += 4 * 256;
1772        if (p->index_version == 1) {
1773                return index + 24 * n + 4;
1774        } else {
1775                index += 8;
1776                return index + 20 * n;
1777        }
1778}
1779
1780off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1781{
1782        const unsigned char *index = p->index_data;
1783        index += 4 * 256;
1784        if (p->index_version == 1) {
1785                return ntohl(*((uint32_t *)(index + 24 * n)));
1786        } else {
1787                uint32_t off;
1788                index += 8 + p->num_objects * (20 + 4);
1789                off = ntohl(*((uint32_t *)(index + 4 * n)));
1790                if (!(off & 0x80000000))
1791                        return off;
1792                index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1793                return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1794                                   ntohl(*((uint32_t *)(index + 4)));
1795        }
1796}
1797
1798off_t find_pack_entry_one(const unsigned char *sha1,
1799                                  struct packed_git *p)
1800{
1801        const uint32_t *level1_ofs = p->index_data;
1802        const unsigned char *index = p->index_data;
1803        unsigned hi, lo, stride;
1804        static int use_lookup = -1;
1805        static int debug_lookup = -1;
1806
1807        if (debug_lookup < 0)
1808                debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1809
1810        if (!index) {
1811                if (open_pack_index(p))
1812                        return 0;
1813                level1_ofs = p->index_data;
1814                index = p->index_data;
1815        }
1816        if (p->index_version > 1) {
1817                level1_ofs += 2;
1818                index += 8;
1819        }
1820        index += 4 * 256;
1821        hi = ntohl(level1_ofs[*sha1]);
1822        lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1823        if (p->index_version > 1) {
1824                stride = 20;
1825        } else {
1826                stride = 24;
1827                index += 4;
1828        }
1829
1830        if (debug_lookup)
1831                printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1832                       sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1833
1834        if (use_lookup < 0)
1835                use_lookup = !!getenv("GIT_USE_LOOKUP");
1836        if (use_lookup) {
1837                int pos = sha1_entry_pos(index, stride, 0,
1838                                         lo, hi, p->num_objects, sha1);
1839                if (pos < 0)
1840                        return 0;
1841                return nth_packed_object_offset(p, pos);
1842        }
1843
1844        do {
1845                unsigned mi = (lo + hi) / 2;
1846                int cmp = hashcmp(index + mi * stride, sha1);
1847
1848                if (debug_lookup)
1849                        printf("lo %u hi %u rg %u mi %u\n",
1850                               lo, hi, hi - lo, mi);
1851                if (!cmp)
1852                        return nth_packed_object_offset(p, mi);
1853                if (cmp > 0)
1854                        hi = mi;
1855                else
1856                        lo = mi+1;
1857        } while (lo < hi);
1858        return 0;
1859}
1860
1861static int matches_pack_name(const struct packed_git *p, const char *name)
1862{
1863        const char *last_c, *c;
1864
1865        if (!strcmp(p->pack_name, name))
1866                return 1;
1867
1868        for (c = p->pack_name, last_c = c; *c;)
1869                if (*c == '/')
1870                        last_c = ++c;
1871                else
1872                        ++c;
1873        if (!strcmp(last_c, name))
1874                return 1;
1875
1876        return 0;
1877}
1878
1879int is_kept_pack(const struct packed_git *p, const struct rev_info *revs)
1880{
1881        int i;
1882
1883        for (i = 0; i < revs->num_ignore_packed; i++) {
1884                if (matches_pack_name(p, revs->ignore_packed[i]))
1885                        return 0;
1886        }
1887        return 1;
1888}
1889
1890static int find_pack_ent(const unsigned char *sha1, struct pack_entry *e,
1891                         const struct rev_info *revs)
1892{
1893        static struct packed_git *last_found = (void *)1;
1894        struct packed_git *p;
1895        off_t offset;
1896
1897        prepare_packed_git();
1898        if (!packed_git)
1899                return 0;
1900        p = (last_found == (void *)1) ? packed_git : last_found;
1901
1902        do {
1903                if (revs->ignore_packed && !is_kept_pack(p, revs))
1904                        goto next;
1905                if (p->num_bad_objects) {
1906                        unsigned i;
1907                        for (i = 0; i < p->num_bad_objects; i++)
1908                                if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1909                                        goto next;
1910                }
1911
1912                offset = find_pack_entry_one(sha1, p);
1913                if (offset) {
1914                        /*
1915                         * We are about to tell the caller where they can
1916                         * locate the requested object.  We better make
1917                         * sure the packfile is still here and can be
1918                         * accessed before supplying that answer, as
1919                         * it may have been deleted since the index
1920                         * was loaded!
1921                         */
1922                        if (p->pack_fd == -1 && open_packed_git(p)) {
1923                                error("packfile %s cannot be accessed", p->pack_name);
1924                                goto next;
1925                        }
1926                        e->offset = offset;
1927                        e->p = p;
1928                        hashcpy(e->sha1, sha1);
1929                        last_found = p;
1930                        return 1;
1931                }
1932
1933                next:
1934                if (p == last_found)
1935                        p = packed_git;
1936                else
1937                        p = p->next;
1938                if (p == last_found)
1939                        p = p->next;
1940        } while (p);
1941        return 0;
1942}
1943
1944static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1945{
1946        return find_pack_ent(sha1, e, NULL);
1947}
1948
1949static int find_kept_pack_entry(const unsigned char *sha1, struct pack_entry *e,
1950                                const struct rev_info *revs)
1951{
1952        return find_pack_ent(sha1, e, revs);
1953}
1954
1955struct packed_git *find_sha1_pack(const unsigned char *sha1,
1956                                  struct packed_git *packs)
1957{
1958        struct packed_git *p;
1959
1960        for (p = packs; p; p = p->next) {
1961                if (find_pack_entry_one(sha1, p))
1962                        return p;
1963        }
1964        return NULL;
1965
1966}
1967
1968static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1969{
1970        int status;
1971        unsigned long mapsize, size;
1972        void *map;
1973        z_stream stream;
1974        char hdr[32];
1975
1976        map = map_sha1_file(sha1, &mapsize);
1977        if (!map)
1978                return error("unable to find %s", sha1_to_hex(sha1));
1979        if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1980                status = error("unable to unpack %s header",
1981                               sha1_to_hex(sha1));
1982        else if ((status = parse_sha1_header(hdr, &size)) < 0)
1983                status = error("unable to parse %s header", sha1_to_hex(sha1));
1984        else if (sizep)
1985                *sizep = size;
1986        inflateEnd(&stream);
1987        munmap(map, mapsize);
1988        return status;
1989}
1990
1991int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1992{
1993        struct pack_entry e;
1994        int status;
1995
1996        if (!find_pack_entry(sha1, &e)) {
1997                /* Most likely it's a loose object. */
1998                status = sha1_loose_object_info(sha1, sizep);
1999                if (status >= 0)
2000                        return status;
2001
2002                /* Not a loose object; someone else may have just packed it. */
2003                reprepare_packed_git();
2004                if (!find_pack_entry(sha1, &e))
2005                        return status;
2006        }
2007        return packed_object_info(e.p, e.offset, sizep);
2008}
2009
2010static void *read_packed_sha1(const unsigned char *sha1,
2011                              enum object_type *type, unsigned long *size)
2012{
2013        struct pack_entry e;
2014        void *data;
2015
2016        if (!find_pack_entry(sha1, &e))
2017                return NULL;
2018        data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2019        if (!data) {
2020                /*
2021                 * We're probably in deep shit, but let's try to fetch
2022                 * the required object anyway from another pack or loose.
2023                 * This should happen only in the presence of a corrupted
2024                 * pack, and is better than failing outright.
2025                 */
2026                error("failed to read object %s at offset %"PRIuMAX" from %s",
2027                      sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2028                mark_bad_packed_object(e.p, sha1);
2029                data = read_object(sha1, type, size);
2030        }
2031        return data;
2032}
2033
2034/*
2035 * This is meant to hold a *small* number of objects that you would
2036 * want read_sha1_file() to be able to return, but yet you do not want
2037 * to write them into the object store (e.g. a browse-only
2038 * application).
2039 */
2040static struct cached_object {
2041        unsigned char sha1[20];
2042        enum object_type type;
2043        void *buf;
2044        unsigned long size;
2045} *cached_objects;
2046static int cached_object_nr, cached_object_alloc;
2047
2048static struct cached_object empty_tree = {
2049        /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
2050        "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
2051        "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
2052        OBJ_TREE,
2053        "",
2054        0
2055};
2056
2057static struct cached_object *find_cached_object(const unsigned char *sha1)
2058{
2059        int i;
2060        struct cached_object *co = cached_objects;
2061
2062        for (i = 0; i < cached_object_nr; i++, co++) {
2063                if (!hashcmp(co->sha1, sha1))
2064                        return co;
2065        }
2066        if (!hashcmp(sha1, empty_tree.sha1))
2067                return &empty_tree;
2068        return NULL;
2069}
2070
2071int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2072                      unsigned char *sha1)
2073{
2074        struct cached_object *co;
2075
2076        hash_sha1_file(buf, len, typename(type), sha1);
2077        if (has_sha1_file(sha1) || find_cached_object(sha1))
2078                return 0;
2079        if (cached_object_alloc <= cached_object_nr) {
2080                cached_object_alloc = alloc_nr(cached_object_alloc);
2081                cached_objects = xrealloc(cached_objects,
2082                                          sizeof(*cached_objects) *
2083                                          cached_object_alloc);
2084        }
2085        co = &cached_objects[cached_object_nr++];
2086        co->size = len;
2087        co->type = type;
2088        co->buf = xmalloc(len);
2089        memcpy(co->buf, buf, len);
2090        hashcpy(co->sha1, sha1);
2091        return 0;
2092}
2093
2094void *read_object(const unsigned char *sha1, enum object_type *type,
2095                  unsigned long *size)
2096{
2097        unsigned long mapsize;
2098        void *map, *buf;
2099        struct cached_object *co;
2100
2101        co = find_cached_object(sha1);
2102        if (co) {
2103                *type = co->type;
2104                *size = co->size;
2105                return xmemdupz(co->buf, co->size);
2106        }
2107
2108        buf = read_packed_sha1(sha1, type, size);
2109        if (buf)
2110                return buf;
2111        map = map_sha1_file(sha1, &mapsize);
2112        if (map) {
2113                buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2114                munmap(map, mapsize);
2115                return buf;
2116        }
2117        reprepare_packed_git();
2118        return read_packed_sha1(sha1, type, size);
2119}
2120
2121void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
2122                     unsigned long *size)
2123{
2124        void *data = read_object(sha1, type, size);
2125        /* legacy behavior is to die on corrupted objects */
2126        if (!data && (has_loose_object(sha1) || has_packed_and_bad(sha1)))
2127                die("object %s is corrupted", sha1_to_hex(sha1));
2128        return data;
2129}
2130
2131void *read_object_with_reference(const unsigned char *sha1,
2132                                 const char *required_type_name,
2133                                 unsigned long *size,
2134                                 unsigned char *actual_sha1_return)
2135{
2136        enum object_type type, required_type;
2137        void *buffer;
2138        unsigned long isize;
2139        unsigned char actual_sha1[20];
2140
2141        required_type = type_from_string(required_type_name);
2142        hashcpy(actual_sha1, sha1);
2143        while (1) {
2144                int ref_length = -1;
2145                const char *ref_type = NULL;
2146
2147                buffer = read_sha1_file(actual_sha1, &type, &isize);
2148                if (!buffer)
2149                        return NULL;
2150                if (type == required_type) {
2151                        *size = isize;
2152                        if (actual_sha1_return)
2153                                hashcpy(actual_sha1_return, actual_sha1);
2154                        return buffer;
2155                }
2156                /* Handle references */
2157                else if (type == OBJ_COMMIT)
2158                        ref_type = "tree ";
2159                else if (type == OBJ_TAG)
2160                        ref_type = "object ";
2161                else {
2162                        free(buffer);
2163                        return NULL;
2164                }
2165                ref_length = strlen(ref_type);
2166
2167                if (ref_length + 40 > isize ||
2168                    memcmp(buffer, ref_type, ref_length) ||
2169                    get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2170                        free(buffer);
2171                        return NULL;
2172                }
2173                free(buffer);
2174                /* Now we have the ID of the referred-to object in
2175                 * actual_sha1.  Check again. */
2176        }
2177}
2178
2179static void write_sha1_file_prepare(const void *buf, unsigned long len,
2180                                    const char *type, unsigned char *sha1,
2181                                    char *hdr, int *hdrlen)
2182{
2183        SHA_CTX c;
2184
2185        /* Generate the header */
2186        *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2187
2188        /* Sha1.. */
2189        SHA1_Init(&c);
2190        SHA1_Update(&c, hdr, *hdrlen);
2191        SHA1_Update(&c, buf, len);
2192        SHA1_Final(sha1, &c);
2193}
2194
2195/*
2196 * Move the just written object into its final resting place
2197 */
2198int move_temp_to_file(const char *tmpfile, const char *filename)
2199{
2200        int ret = 0;
2201        if (link(tmpfile, filename))
2202                ret = errno;
2203
2204        /*
2205         * Coda hack - coda doesn't like cross-directory links,
2206         * so we fall back to a rename, which will mean that it
2207         * won't be able to check collisions, but that's not a
2208         * big deal.
2209         *
2210         * The same holds for FAT formatted media.
2211         *
2212         * When this succeeds, we just return 0. We have nothing
2213         * left to unlink.
2214         */
2215        if (ret && ret != EEXIST) {
2216                if (!rename(tmpfile, filename))
2217                        return 0;
2218                ret = errno;
2219        }
2220        unlink(tmpfile);
2221        if (ret) {
2222                if (ret != EEXIST) {
2223                        return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2224                }
2225                /* FIXME!!! Collision check here ? */
2226        }
2227
2228        return 0;
2229}
2230
2231static int write_buffer(int fd, const void *buf, size_t len)
2232{
2233        if (write_in_full(fd, buf, len) < 0)
2234                return error("file write error (%s)", strerror(errno));
2235        return 0;
2236}
2237
2238int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2239                   unsigned char *sha1)
2240{
2241        char hdr[32];
2242        int hdrlen;
2243        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2244        return 0;
2245}
2246
2247/* Finalize a file on disk, and close it. */
2248static void close_sha1_file(int fd)
2249{
2250        if (fsync_object_files)
2251                fsync_or_die(fd, "sha1 file");
2252        fchmod(fd, 0444);
2253        if (close(fd) != 0)
2254                die("unable to write sha1 file");
2255}
2256
2257/* Size of directory component, including the ending '/' */
2258static inline int directory_size(const char *filename)
2259{
2260        const char *s = strrchr(filename, '/');
2261        if (!s)
2262                return 0;
2263        return s - filename + 1;
2264}
2265
2266/*
2267 * This creates a temporary file in the same directory as the final
2268 * 'filename'
2269 *
2270 * We want to avoid cross-directory filename renames, because those
2271 * can have problems on various filesystems (FAT, NFS, Coda).
2272 */
2273static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2274{
2275        int fd, dirlen = directory_size(filename);
2276
2277        if (dirlen + 20 > bufsiz) {
2278                errno = ENAMETOOLONG;
2279                return -1;
2280        }
2281        memcpy(buffer, filename, dirlen);
2282        strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2283        fd = mkstemp(buffer);
2284        if (fd < 0 && dirlen && errno == ENOENT) {
2285                /* Make sure the directory exists */
2286                memcpy(buffer, filename, dirlen);
2287                buffer[dirlen-1] = 0;
2288                if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2289                        return -1;
2290
2291                /* Try again */
2292                strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2293                fd = mkstemp(buffer);
2294        }
2295        return fd;
2296}
2297
2298static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2299                              void *buf, unsigned long len, time_t mtime)
2300{
2301        int fd, size, ret;
2302        unsigned char *compressed;
2303        z_stream stream;
2304        char *filename;
2305        static char tmpfile[PATH_MAX];
2306
2307        filename = sha1_file_name(sha1);
2308        fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2309        if (fd < 0) {
2310                if (errno == EACCES)
2311                        return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2312                else
2313                        return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2314        }
2315
2316        /* Set it up */
2317        memset(&stream, 0, sizeof(stream));
2318        deflateInit(&stream, zlib_compression_level);
2319        size = 8 + deflateBound(&stream, len+hdrlen);
2320        compressed = xmalloc(size);
2321
2322        /* Compress it */
2323        stream.next_out = compressed;
2324        stream.avail_out = size;
2325
2326        /* First header.. */
2327        stream.next_in = (unsigned char *)hdr;
2328        stream.avail_in = hdrlen;
2329        while (deflate(&stream, 0) == Z_OK)
2330                /* nothing */;
2331
2332        /* Then the data itself.. */
2333        stream.next_in = buf;
2334        stream.avail_in = len;
2335        ret = deflate(&stream, Z_FINISH);
2336        if (ret != Z_STREAM_END)
2337                die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2338
2339        ret = deflateEnd(&stream);
2340        if (ret != Z_OK)
2341                die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2342
2343        size = stream.total_out;
2344
2345        if (write_buffer(fd, compressed, size) < 0)
2346                die("unable to write sha1 file");
2347        close_sha1_file(fd);
2348        free(compressed);
2349
2350        if (mtime) {
2351                struct utimbuf utb;
2352                utb.actime = mtime;
2353                utb.modtime = mtime;
2354                if (utime(tmpfile, &utb) < 0)
2355                        warning("failed utime() on %s: %s",
2356                                tmpfile, strerror(errno));
2357        }
2358
2359        return move_temp_to_file(tmpfile, filename);
2360}
2361
2362int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2363{
2364        unsigned char sha1[20];
2365        char hdr[32];
2366        int hdrlen;
2367
2368        /* Normally if we have it in the pack then we do not bother writing
2369         * it out into .git/objects/??/?{38} file.
2370         */
2371        write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2372        if (returnsha1)
2373                hashcpy(returnsha1, sha1);
2374        if (has_sha1_file(sha1))
2375                return 0;
2376        return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2377}
2378
2379int force_object_loose(const unsigned char *sha1, time_t mtime)
2380{
2381        void *buf;
2382        unsigned long len;
2383        enum object_type type;
2384        char hdr[32];
2385        int hdrlen;
2386        int ret;
2387
2388        if (has_loose_object(sha1))
2389                return 0;
2390        buf = read_packed_sha1(sha1, &type, &len);
2391        if (!buf)
2392                return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2393        hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2394        ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2395        free(buf);
2396
2397        return ret;
2398}
2399
2400int has_pack_index(const unsigned char *sha1)
2401{
2402        struct stat st;
2403        if (stat(sha1_pack_index_name(sha1), &st))
2404                return 0;
2405        return 1;
2406}
2407
2408int has_pack_file(const unsigned char *sha1)
2409{
2410        struct stat st;
2411        if (stat(sha1_pack_name(sha1), &st))
2412                return 0;
2413        return 1;
2414}
2415
2416int has_sha1_pack(const unsigned char *sha1)
2417{
2418        struct pack_entry e;
2419        return find_pack_entry(sha1, &e);
2420}
2421
2422int has_sha1_kept_pack(const unsigned char *sha1, const struct rev_info *revs)
2423{
2424        struct pack_entry e;
2425        return find_kept_pack_entry(sha1, &e, revs);
2426}
2427
2428int has_sha1_file(const unsigned char *sha1)
2429{
2430        struct pack_entry e;
2431
2432        if (find_pack_entry(sha1, &e))
2433                return 1;
2434        return has_loose_object(sha1);
2435}
2436
2437int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2438{
2439        struct strbuf buf;
2440        int ret;
2441
2442        strbuf_init(&buf, 0);
2443        if (strbuf_read(&buf, fd, 4096) < 0) {
2444                strbuf_release(&buf);
2445                return -1;
2446        }
2447
2448        if (!type)
2449                type = blob_type;
2450        if (write_object)
2451                ret = write_sha1_file(buf.buf, buf.len, type, sha1);
2452        else
2453                ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2454        strbuf_release(&buf);
2455
2456        return ret;
2457}
2458
2459int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2460             enum object_type type, const char *path)
2461{
2462        size_t size = xsize_t(st->st_size);
2463        void *buf = NULL;
2464        int ret, re_allocated = 0;
2465
2466        if (size)
2467                buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2468        close(fd);
2469
2470        if (!type)
2471                type = OBJ_BLOB;
2472
2473        /*
2474         * Convert blobs to git internal format
2475         */
2476        if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2477                struct strbuf nbuf;
2478                strbuf_init(&nbuf, 0);
2479                if (convert_to_git(path, buf, size, &nbuf,
2480                                   write_object ? safe_crlf : 0)) {
2481                        munmap(buf, size);
2482                        buf = strbuf_detach(&nbuf, &size);
2483                        re_allocated = 1;
2484                }
2485        }
2486
2487        if (write_object)
2488                ret = write_sha1_file(buf, size, typename(type), sha1);
2489        else
2490                ret = hash_sha1_file(buf, size, typename(type), sha1);
2491        if (re_allocated) {
2492                free(buf);
2493                return ret;
2494        }
2495        if (size)
2496                munmap(buf, size);
2497        return ret;
2498}
2499
2500int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2501{
2502        int fd;
2503        char *target;
2504        size_t len;
2505
2506        switch (st->st_mode & S_IFMT) {
2507        case S_IFREG:
2508                fd = open(path, O_RDONLY);
2509                if (fd < 0)
2510                        return error("open(\"%s\"): %s", path,
2511                                     strerror(errno));
2512                if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2513                        return error("%s: failed to insert into database",
2514                                     path);
2515                break;
2516        case S_IFLNK:
2517                len = xsize_t(st->st_size);
2518                target = xmalloc(len + 1);
2519                if (readlink(path, target, len + 1) != st->st_size) {
2520                        char *errstr = strerror(errno);
2521                        free(target);
2522                        return error("readlink(\"%s\"): %s", path,
2523                                     errstr);
2524                }
2525                if (!write_object)
2526                        hash_sha1_file(target, len, blob_type, sha1);
2527                else if (write_sha1_file(target, len, blob_type, sha1))
2528                        return error("%s: failed to insert into database",
2529                                     path);
2530                free(target);
2531                break;
2532        case S_IFDIR:
2533                return resolve_gitlink_ref(path, "HEAD", sha1);
2534        default:
2535                return error("%s: unsupported file type", path);
2536        }
2537        return 0;
2538}
2539
2540int read_pack_header(int fd, struct pack_header *header)
2541{
2542        if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2543                /* "eof before pack header was fully read" */
2544                return PH_ERROR_EOF;
2545
2546        if (header->hdr_signature != htonl(PACK_SIGNATURE))
2547                /* "protocol error (pack signature mismatch detected)" */
2548                return PH_ERROR_PACK_SIGNATURE;
2549        if (!pack_version_ok(header->hdr_version))
2550                /* "protocol error (pack version unsupported)" */
2551                return PH_ERROR_PROTOCOL;
2552        return 0;
2553}