allow do_submodule_path to work even if submodule isn't checked out
[git.git] / sha1_file.c
blob5b8553d69e06ff37a37573a5ef1a040b90de812f
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "string-list.h"
11 #include "lockfile.h"
12 #include "delta.h"
13 #include "pack.h"
14 #include "blob.h"
15 #include "commit.h"
16 #include "run-command.h"
17 #include "tag.h"
18 #include "tree.h"
19 #include "tree-walk.h"
20 #include "refs.h"
21 #include "pack-revindex.h"
22 #include "sha1-lookup.h"
23 #include "bulk-checkin.h"
24 #include "streaming.h"
25 #include "dir.h"
26 #include "mru.h"
28 #ifndef O_NOATIME
29 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
30 #define O_NOATIME 01000000
31 #else
32 #define O_NOATIME 0
33 #endif
34 #endif
36 #define SZ_FMT PRIuMAX
37 static inline uintmax_t sz_fmt(size_t s) { return s; }
39 const unsigned char null_sha1[20];
40 const struct object_id null_oid;
41 const struct object_id empty_tree_oid = {
42 EMPTY_TREE_SHA1_BIN_LITERAL
44 const struct object_id empty_blob_oid = {
45 EMPTY_BLOB_SHA1_BIN_LITERAL
49 * This is meant to hold a *small* number of objects that you would
50 * want read_sha1_file() to be able to return, but yet you do not want
51 * to write them into the object store (e.g. a browse-only
52 * application).
54 static struct cached_object {
55 unsigned char sha1[20];
56 enum object_type type;
57 void *buf;
58 unsigned long size;
59 } *cached_objects;
60 static int cached_object_nr, cached_object_alloc;
62 static struct cached_object empty_tree = {
63 EMPTY_TREE_SHA1_BIN_LITERAL,
64 OBJ_TREE,
65 "",
69 static struct cached_object *find_cached_object(const unsigned char *sha1)
71 int i;
72 struct cached_object *co = cached_objects;
74 for (i = 0; i < cached_object_nr; i++, co++) {
75 if (!hashcmp(co->sha1, sha1))
76 return co;
78 if (!hashcmp(sha1, empty_tree.sha1))
79 return &empty_tree;
80 return NULL;
83 int mkdir_in_gitdir(const char *path)
85 if (mkdir(path, 0777)) {
86 int saved_errno = errno;
87 struct stat st;
88 struct strbuf sb = STRBUF_INIT;
90 if (errno != EEXIST)
91 return -1;
93 * Are we looking at a path in a symlinked worktree
94 * whose original repository does not yet have it?
95 * e.g. .git/rr-cache pointing at its original
96 * repository in which the user hasn't performed any
97 * conflict resolution yet?
99 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
100 strbuf_readlink(&sb, path, st.st_size) ||
101 !is_absolute_path(sb.buf) ||
102 mkdir(sb.buf, 0777)) {
103 strbuf_release(&sb);
104 errno = saved_errno;
105 return -1;
107 strbuf_release(&sb);
109 return adjust_shared_perm(path);
112 enum scld_error safe_create_leading_directories(char *path)
114 char *next_component = path + offset_1st_component(path);
115 enum scld_error ret = SCLD_OK;
117 while (ret == SCLD_OK && next_component) {
118 struct stat st;
119 char *slash = next_component, slash_character;
121 while (*slash && !is_dir_sep(*slash))
122 slash++;
124 if (!*slash)
125 break;
127 next_component = slash + 1;
128 while (is_dir_sep(*next_component))
129 next_component++;
130 if (!*next_component)
131 break;
133 slash_character = *slash;
134 *slash = '\0';
135 if (!stat(path, &st)) {
136 /* path exists */
137 if (!S_ISDIR(st.st_mode))
138 ret = SCLD_EXISTS;
139 } else if (mkdir(path, 0777)) {
140 if (errno == EEXIST &&
141 !stat(path, &st) && S_ISDIR(st.st_mode))
142 ; /* somebody created it since we checked */
143 else if (errno == ENOENT)
145 * Either mkdir() failed because
146 * somebody just pruned the containing
147 * directory, or stat() failed because
148 * the file that was in our way was
149 * just removed. Either way, inform
150 * the caller that it might be worth
151 * trying again:
153 ret = SCLD_VANISHED;
154 else
155 ret = SCLD_FAILED;
156 } else if (adjust_shared_perm(path)) {
157 ret = SCLD_PERMS;
159 *slash = slash_character;
161 return ret;
164 enum scld_error safe_create_leading_directories_const(const char *path)
166 /* path points to cache entries, so xstrdup before messing with it */
167 char *buf = xstrdup(path);
168 enum scld_error result = safe_create_leading_directories(buf);
169 free(buf);
170 return result;
173 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
175 int i;
176 for (i = 0; i < 20; i++) {
177 static char hex[] = "0123456789abcdef";
178 unsigned int val = sha1[i];
179 char *pos = pathbuf + i*2 + (i > 0);
180 *pos++ = hex[val >> 4];
181 *pos = hex[val & 0xf];
185 const char *sha1_file_name(const unsigned char *sha1)
187 static char buf[PATH_MAX];
188 const char *objdir;
189 int len;
191 objdir = get_object_directory();
192 len = strlen(objdir);
194 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
195 if (len + 43 > PATH_MAX)
196 die("insanely long object directory %s", objdir);
197 memcpy(buf, objdir, len);
198 buf[len] = '/';
199 buf[len+3] = '/';
200 buf[len+42] = '\0';
201 fill_sha1_path(buf + len + 1, sha1);
202 return buf;
206 * Return the name of the pack or index file with the specified sha1
207 * in its filename. *base and *name are scratch space that must be
208 * provided by the caller. which should be "pack" or "idx".
210 static char *sha1_get_pack_name(const unsigned char *sha1,
211 struct strbuf *buf,
212 const char *which)
214 strbuf_reset(buf);
215 strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
216 sha1_to_hex(sha1), which);
217 return buf->buf;
220 char *sha1_pack_name(const unsigned char *sha1)
222 static struct strbuf buf = STRBUF_INIT;
223 return sha1_get_pack_name(sha1, &buf, "pack");
226 char *sha1_pack_index_name(const unsigned char *sha1)
228 static struct strbuf buf = STRBUF_INIT;
229 return sha1_get_pack_name(sha1, &buf, "idx");
232 struct alternate_object_database *alt_odb_list;
233 static struct alternate_object_database **alt_odb_tail;
236 * Prepare alternate object database registry.
238 * The variable alt_odb_list points at the list of struct
239 * alternate_object_database. The elements on this list come from
240 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
241 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
242 * whose contents is similar to that environment variable but can be
243 * LF separated. Its base points at a statically allocated buffer that
244 * contains "/the/directory/corresponding/to/.git/objects/...", while
245 * its name points just after the slash at the end of ".git/objects/"
246 * in the example above, and has enough space to hold 40-byte hex
247 * SHA1, an extra slash for the first level indirection, and the
248 * terminating NUL.
250 static int link_alt_odb_entry(const char *entry, const char *relative_base,
251 int depth, const char *normalized_objdir)
253 struct alternate_object_database *ent;
254 struct alternate_object_database *alt;
255 size_t pfxlen, entlen;
256 struct strbuf pathbuf = STRBUF_INIT;
258 if (!is_absolute_path(entry) && relative_base) {
259 strbuf_addstr(&pathbuf, real_path(relative_base));
260 strbuf_addch(&pathbuf, '/');
262 strbuf_addstr(&pathbuf, entry);
264 normalize_path_copy(pathbuf.buf, pathbuf.buf);
266 pfxlen = strlen(pathbuf.buf);
269 * The trailing slash after the directory name is given by
270 * this function at the end. Remove duplicates.
272 while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
273 pfxlen -= 1;
275 entlen = st_add(pfxlen, 43); /* '/' + 2 hex + '/' + 38 hex + NUL */
276 ent = xmalloc(st_add(sizeof(*ent), entlen));
277 memcpy(ent->base, pathbuf.buf, pfxlen);
278 strbuf_release(&pathbuf);
280 ent->name = ent->base + pfxlen + 1;
281 ent->base[pfxlen + 3] = '/';
282 ent->base[pfxlen] = ent->base[entlen-1] = 0;
284 /* Detect cases where alternate disappeared */
285 if (!is_directory(ent->base)) {
286 error("object directory %s does not exist; "
287 "check .git/objects/info/alternates.",
288 ent->base);
289 free(ent);
290 return -1;
293 /* Prevent the common mistake of listing the same
294 * thing twice, or object directory itself.
296 for (alt = alt_odb_list; alt; alt = alt->next) {
297 if (pfxlen == alt->name - alt->base - 1 &&
298 !memcmp(ent->base, alt->base, pfxlen)) {
299 free(ent);
300 return -1;
303 if (!fspathcmp(ent->base, normalized_objdir)) {
304 free(ent);
305 return -1;
308 /* add the alternate entry */
309 *alt_odb_tail = ent;
310 alt_odb_tail = &(ent->next);
311 ent->next = NULL;
313 /* recursively add alternates */
314 read_info_alternates(ent->base, depth + 1);
316 ent->base[pfxlen] = '/';
318 return 0;
321 static void link_alt_odb_entries(const char *alt, int len, int sep,
322 const char *relative_base, int depth)
324 struct string_list entries = STRING_LIST_INIT_NODUP;
325 char *alt_copy;
326 int i;
327 struct strbuf objdirbuf = STRBUF_INIT;
329 if (depth > 5) {
330 error("%s: ignoring alternate object stores, nesting too deep.",
331 relative_base);
332 return;
335 strbuf_add_absolute_path(&objdirbuf, get_object_directory());
336 normalize_path_copy(objdirbuf.buf, objdirbuf.buf);
338 alt_copy = xmemdupz(alt, len);
339 string_list_split_in_place(&entries, alt_copy, sep, -1);
340 for (i = 0; i < entries.nr; i++) {
341 const char *entry = entries.items[i].string;
342 if (entry[0] == '\0' || entry[0] == '#')
343 continue;
344 if (!is_absolute_path(entry) && depth) {
345 error("%s: ignoring relative alternate object store %s",
346 relative_base, entry);
347 } else {
348 link_alt_odb_entry(entry, relative_base, depth, objdirbuf.buf);
351 string_list_clear(&entries, 0);
352 free(alt_copy);
353 strbuf_release(&objdirbuf);
356 void read_info_alternates(const char * relative_base, int depth)
358 char *map;
359 size_t mapsz;
360 struct stat st;
361 char *path;
362 int fd;
364 path = xstrfmt("%s/info/alternates", relative_base);
365 fd = git_open_noatime(path);
366 free(path);
367 if (fd < 0)
368 return;
369 if (fstat(fd, &st) || (st.st_size == 0)) {
370 close(fd);
371 return;
373 mapsz = xsize_t(st.st_size);
374 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
375 close(fd);
377 link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
379 munmap(map, mapsz);
382 void add_to_alternates_file(const char *reference)
384 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
385 char *alts = git_pathdup("objects/info/alternates");
386 FILE *in, *out;
388 hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
389 out = fdopen_lock_file(lock, "w");
390 if (!out)
391 die_errno("unable to fdopen alternates lockfile");
393 in = fopen(alts, "r");
394 if (in) {
395 struct strbuf line = STRBUF_INIT;
396 int found = 0;
398 while (strbuf_getline(&line, in) != EOF) {
399 if (!strcmp(reference, line.buf)) {
400 found = 1;
401 break;
403 fprintf_or_die(out, "%s\n", line.buf);
406 strbuf_release(&line);
407 fclose(in);
409 if (found) {
410 rollback_lock_file(lock);
411 lock = NULL;
414 else if (errno != ENOENT)
415 die_errno("unable to read alternates file");
417 if (lock) {
418 fprintf_or_die(out, "%s\n", reference);
419 if (commit_lock_file(lock))
420 die_errno("unable to move new alternates file into place");
421 if (alt_odb_tail)
422 link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
424 free(alts);
427 int foreach_alt_odb(alt_odb_fn fn, void *cb)
429 struct alternate_object_database *ent;
430 int r = 0;
432 prepare_alt_odb();
433 for (ent = alt_odb_list; ent; ent = ent->next) {
434 r = fn(ent, cb);
435 if (r)
436 break;
438 return r;
441 void prepare_alt_odb(void)
443 const char *alt;
445 if (alt_odb_tail)
446 return;
448 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
449 if (!alt) alt = "";
451 alt_odb_tail = &alt_odb_list;
452 link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
454 read_info_alternates(get_object_directory(), 0);
457 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
458 static int freshen_file(const char *fn)
460 struct utimbuf t;
461 t.actime = t.modtime = time(NULL);
462 return !utime(fn, &t);
466 * All of the check_and_freshen functions return 1 if the file exists and was
467 * freshened (if freshening was requested), 0 otherwise. If they return
468 * 0, you should not assume that it is safe to skip a write of the object (it
469 * either does not exist on disk, or has a stale mtime and may be subject to
470 * pruning).
472 static int check_and_freshen_file(const char *fn, int freshen)
474 if (access(fn, F_OK))
475 return 0;
476 if (freshen && !freshen_file(fn))
477 return 0;
478 return 1;
481 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
483 return check_and_freshen_file(sha1_file_name(sha1), freshen);
486 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
488 struct alternate_object_database *alt;
489 prepare_alt_odb();
490 for (alt = alt_odb_list; alt; alt = alt->next) {
491 fill_sha1_path(alt->name, sha1);
492 if (check_and_freshen_file(alt->base, freshen))
493 return 1;
495 return 0;
498 static int check_and_freshen(const unsigned char *sha1, int freshen)
500 return check_and_freshen_local(sha1, freshen) ||
501 check_and_freshen_nonlocal(sha1, freshen);
504 int has_loose_object_nonlocal(const unsigned char *sha1)
506 return check_and_freshen_nonlocal(sha1, 0);
509 static int has_loose_object(const unsigned char *sha1)
511 return check_and_freshen(sha1, 0);
514 static unsigned int pack_used_ctr;
515 static unsigned int pack_mmap_calls;
516 static unsigned int peak_pack_open_windows;
517 static unsigned int pack_open_windows;
518 static unsigned int pack_open_fds;
519 static unsigned int pack_max_fds;
520 static size_t peak_pack_mapped;
521 static size_t pack_mapped;
522 struct packed_git *packed_git;
524 static struct mru packed_git_mru_storage;
525 struct mru *packed_git_mru = &packed_git_mru_storage;
527 void pack_report(void)
529 fprintf(stderr,
530 "pack_report: getpagesize() = %10" SZ_FMT "\n"
531 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
532 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
533 sz_fmt(getpagesize()),
534 sz_fmt(packed_git_window_size),
535 sz_fmt(packed_git_limit));
536 fprintf(stderr,
537 "pack_report: pack_used_ctr = %10u\n"
538 "pack_report: pack_mmap_calls = %10u\n"
539 "pack_report: pack_open_windows = %10u / %10u\n"
540 "pack_report: pack_mapped = "
541 "%10" SZ_FMT " / %10" SZ_FMT "\n",
542 pack_used_ctr,
543 pack_mmap_calls,
544 pack_open_windows, peak_pack_open_windows,
545 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
549 * Open and mmap the index file at path, perform a couple of
550 * consistency checks, then record its information to p. Return 0 on
551 * success.
553 static int check_packed_git_idx(const char *path, struct packed_git *p)
555 void *idx_map;
556 struct pack_idx_header *hdr;
557 size_t idx_size;
558 uint32_t version, nr, i, *index;
559 int fd = git_open_noatime(path);
560 struct stat st;
562 if (fd < 0)
563 return -1;
564 if (fstat(fd, &st)) {
565 close(fd);
566 return -1;
568 idx_size = xsize_t(st.st_size);
569 if (idx_size < 4 * 256 + 20 + 20) {
570 close(fd);
571 return error("index file %s is too small", path);
573 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
574 close(fd);
576 hdr = idx_map;
577 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
578 version = ntohl(hdr->idx_version);
579 if (version < 2 || version > 2) {
580 munmap(idx_map, idx_size);
581 return error("index file %s is version %"PRIu32
582 " and is not supported by this binary"
583 " (try upgrading GIT to a newer version)",
584 path, version);
586 } else
587 version = 1;
589 nr = 0;
590 index = idx_map;
591 if (version > 1)
592 index += 2; /* skip index header */
593 for (i = 0; i < 256; i++) {
594 uint32_t n = ntohl(index[i]);
595 if (n < nr) {
596 munmap(idx_map, idx_size);
597 return error("non-monotonic index %s", path);
599 nr = n;
602 if (version == 1) {
604 * Total size:
605 * - 256 index entries 4 bytes each
606 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
607 * - 20-byte SHA1 of the packfile
608 * - 20-byte SHA1 file checksum
610 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
611 munmap(idx_map, idx_size);
612 return error("wrong index v1 file size in %s", path);
614 } else if (version == 2) {
616 * Minimum size:
617 * - 8 bytes of header
618 * - 256 index entries 4 bytes each
619 * - 20-byte sha1 entry * nr
620 * - 4-byte crc entry * nr
621 * - 4-byte offset entry * nr
622 * - 20-byte SHA1 of the packfile
623 * - 20-byte SHA1 file checksum
624 * And after the 4-byte offset table might be a
625 * variable sized table containing 8-byte entries
626 * for offsets larger than 2^31.
628 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
629 unsigned long max_size = min_size;
630 if (nr)
631 max_size += (nr - 1)*8;
632 if (idx_size < min_size || idx_size > max_size) {
633 munmap(idx_map, idx_size);
634 return error("wrong index v2 file size in %s", path);
636 if (idx_size != min_size &&
638 * make sure we can deal with large pack offsets.
639 * 31-bit signed offset won't be enough, neither
640 * 32-bit unsigned one will be.
642 (sizeof(off_t) <= 4)) {
643 munmap(idx_map, idx_size);
644 return error("pack too large for current definition of off_t in %s", path);
648 p->index_version = version;
649 p->index_data = idx_map;
650 p->index_size = idx_size;
651 p->num_objects = nr;
652 return 0;
655 int open_pack_index(struct packed_git *p)
657 char *idx_name;
658 size_t len;
659 int ret;
661 if (p->index_data)
662 return 0;
664 if (!strip_suffix(p->pack_name, ".pack", &len))
665 die("BUG: pack_name does not end in .pack");
666 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
667 ret = check_packed_git_idx(idx_name, p);
668 free(idx_name);
669 return ret;
672 static void scan_windows(struct packed_git *p,
673 struct packed_git **lru_p,
674 struct pack_window **lru_w,
675 struct pack_window **lru_l)
677 struct pack_window *w, *w_l;
679 for (w_l = NULL, w = p->windows; w; w = w->next) {
680 if (!w->inuse_cnt) {
681 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
682 *lru_p = p;
683 *lru_w = w;
684 *lru_l = w_l;
687 w_l = w;
691 static int unuse_one_window(struct packed_git *current)
693 struct packed_git *p, *lru_p = NULL;
694 struct pack_window *lru_w = NULL, *lru_l = NULL;
696 if (current)
697 scan_windows(current, &lru_p, &lru_w, &lru_l);
698 for (p = packed_git; p; p = p->next)
699 scan_windows(p, &lru_p, &lru_w, &lru_l);
700 if (lru_p) {
701 munmap(lru_w->base, lru_w->len);
702 pack_mapped -= lru_w->len;
703 if (lru_l)
704 lru_l->next = lru_w->next;
705 else
706 lru_p->windows = lru_w->next;
707 free(lru_w);
708 pack_open_windows--;
709 return 1;
711 return 0;
714 void release_pack_memory(size_t need)
716 size_t cur = pack_mapped;
717 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
718 ; /* nothing */
721 static void mmap_limit_check(size_t length)
723 static size_t limit = 0;
724 if (!limit) {
725 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
726 if (!limit)
727 limit = SIZE_MAX;
729 if (length > limit)
730 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
731 (uintmax_t)length, (uintmax_t)limit);
734 void *xmmap_gently(void *start, size_t length,
735 int prot, int flags, int fd, off_t offset)
737 void *ret;
739 mmap_limit_check(length);
740 ret = mmap(start, length, prot, flags, fd, offset);
741 if (ret == MAP_FAILED) {
742 if (!length)
743 return NULL;
744 release_pack_memory(length);
745 ret = mmap(start, length, prot, flags, fd, offset);
747 return ret;
750 void *xmmap(void *start, size_t length,
751 int prot, int flags, int fd, off_t offset)
753 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
754 if (ret == MAP_FAILED)
755 die_errno("mmap failed");
756 return ret;
759 void close_pack_windows(struct packed_git *p)
761 while (p->windows) {
762 struct pack_window *w = p->windows;
764 if (w->inuse_cnt)
765 die("pack '%s' still has open windows to it",
766 p->pack_name);
767 munmap(w->base, w->len);
768 pack_mapped -= w->len;
769 pack_open_windows--;
770 p->windows = w->next;
771 free(w);
775 static int close_pack_fd(struct packed_git *p)
777 if (p->pack_fd < 0)
778 return 0;
780 close(p->pack_fd);
781 pack_open_fds--;
782 p->pack_fd = -1;
784 return 1;
787 static void close_pack(struct packed_git *p)
789 close_pack_windows(p);
790 close_pack_fd(p);
791 close_pack_index(p);
794 void close_all_packs(void)
796 struct packed_git *p;
798 for (p = packed_git; p; p = p->next)
799 if (p->do_not_close)
800 die("BUG: want to close pack marked 'do-not-close'");
801 else
802 close_pack(p);
807 * The LRU pack is the one with the oldest MRU window, preferring packs
808 * with no used windows, or the oldest mtime if it has no windows allocated.
810 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
812 struct pack_window *w, *this_mru_w;
813 int has_windows_inuse = 0;
816 * Reject this pack if it has windows and the previously selected
817 * one does not. If this pack does not have windows, reject
818 * it if the pack file is newer than the previously selected one.
820 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
821 return;
823 for (w = this_mru_w = p->windows; w; w = w->next) {
825 * Reject this pack if any of its windows are in use,
826 * but the previously selected pack did not have any
827 * inuse windows. Otherwise, record that this pack
828 * has windows in use.
830 if (w->inuse_cnt) {
831 if (*accept_windows_inuse)
832 has_windows_inuse = 1;
833 else
834 return;
837 if (w->last_used > this_mru_w->last_used)
838 this_mru_w = w;
841 * Reject this pack if it has windows that have been
842 * used more recently than the previously selected pack.
843 * If the previously selected pack had windows inuse and
844 * we have not encountered a window in this pack that is
845 * inuse, skip this check since we prefer a pack with no
846 * inuse windows to one that has inuse windows.
848 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
849 this_mru_w->last_used > (*mru_w)->last_used)
850 return;
854 * Select this pack.
856 *mru_w = this_mru_w;
857 *lru_p = p;
858 *accept_windows_inuse = has_windows_inuse;
861 static int close_one_pack(void)
863 struct packed_git *p, *lru_p = NULL;
864 struct pack_window *mru_w = NULL;
865 int accept_windows_inuse = 1;
867 for (p = packed_git; p; p = p->next) {
868 if (p->pack_fd == -1)
869 continue;
870 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
873 if (lru_p)
874 return close_pack_fd(lru_p);
876 return 0;
879 void unuse_pack(struct pack_window **w_cursor)
881 struct pack_window *w = *w_cursor;
882 if (w) {
883 w->inuse_cnt--;
884 *w_cursor = NULL;
888 void close_pack_index(struct packed_git *p)
890 if (p->index_data) {
891 munmap((void *)p->index_data, p->index_size);
892 p->index_data = NULL;
896 static unsigned int get_max_fd_limit(void)
898 #ifdef RLIMIT_NOFILE
900 struct rlimit lim;
902 if (!getrlimit(RLIMIT_NOFILE, &lim))
903 return lim.rlim_cur;
905 #endif
907 #ifdef _SC_OPEN_MAX
909 long open_max = sysconf(_SC_OPEN_MAX);
910 if (0 < open_max)
911 return open_max;
913 * Otherwise, we got -1 for one of the two
914 * reasons:
916 * (1) sysconf() did not understand _SC_OPEN_MAX
917 * and signaled an error with -1; or
918 * (2) sysconf() said there is no limit.
920 * We _could_ clear errno before calling sysconf() to
921 * tell these two cases apart and return a huge number
922 * in the latter case to let the caller cap it to a
923 * value that is not so selfish, but letting the
924 * fallback OPEN_MAX codepath take care of these cases
925 * is a lot simpler.
928 #endif
930 #ifdef OPEN_MAX
931 return OPEN_MAX;
932 #else
933 return 1; /* see the caller ;-) */
934 #endif
938 * Do not call this directly as this leaks p->pack_fd on error return;
939 * call open_packed_git() instead.
941 static int open_packed_git_1(struct packed_git *p)
943 struct stat st;
944 struct pack_header hdr;
945 unsigned char sha1[20];
946 unsigned char *idx_sha1;
947 long fd_flag;
949 if (!p->index_data && open_pack_index(p))
950 return error("packfile %s index unavailable", p->pack_name);
952 if (!pack_max_fds) {
953 unsigned int max_fds = get_max_fd_limit();
955 /* Save 3 for stdin/stdout/stderr, 22 for work */
956 if (25 < max_fds)
957 pack_max_fds = max_fds - 25;
958 else
959 pack_max_fds = 1;
962 while (pack_max_fds <= pack_open_fds && close_one_pack())
963 ; /* nothing */
965 p->pack_fd = git_open_noatime(p->pack_name);
966 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
967 return -1;
968 pack_open_fds++;
970 /* If we created the struct before we had the pack we lack size. */
971 if (!p->pack_size) {
972 if (!S_ISREG(st.st_mode))
973 return error("packfile %s not a regular file", p->pack_name);
974 p->pack_size = st.st_size;
975 } else if (p->pack_size != st.st_size)
976 return error("packfile %s size changed", p->pack_name);
978 /* We leave these file descriptors open with sliding mmap;
979 * there is no point keeping them open across exec(), though.
981 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
982 if (fd_flag < 0)
983 return error("cannot determine file descriptor flags");
984 fd_flag |= FD_CLOEXEC;
985 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
986 return error("cannot set FD_CLOEXEC");
988 /* Verify we recognize this pack file format. */
989 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
990 return error("file %s is far too short to be a packfile", p->pack_name);
991 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
992 return error("file %s is not a GIT packfile", p->pack_name);
993 if (!pack_version_ok(hdr.hdr_version))
994 return error("packfile %s is version %"PRIu32" and not"
995 " supported (try upgrading GIT to a newer version)",
996 p->pack_name, ntohl(hdr.hdr_version));
998 /* Verify the pack matches its index. */
999 if (p->num_objects != ntohl(hdr.hdr_entries))
1000 return error("packfile %s claims to have %"PRIu32" objects"
1001 " while index indicates %"PRIu32" objects",
1002 p->pack_name, ntohl(hdr.hdr_entries),
1003 p->num_objects);
1004 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
1005 return error("end of packfile %s is unavailable", p->pack_name);
1006 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
1007 return error("packfile %s signature is unavailable", p->pack_name);
1008 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
1009 if (hashcmp(sha1, idx_sha1))
1010 return error("packfile %s does not match index", p->pack_name);
1011 return 0;
1014 static int open_packed_git(struct packed_git *p)
1016 if (!open_packed_git_1(p))
1017 return 0;
1018 close_pack_fd(p);
1019 return -1;
1022 static int in_window(struct pack_window *win, off_t offset)
1024 /* We must promise at least 20 bytes (one hash) after the
1025 * offset is available from this window, otherwise the offset
1026 * is not actually in this window and a different window (which
1027 * has that one hash excess) must be used. This is to support
1028 * the object header and delta base parsing routines below.
1030 off_t win_off = win->offset;
1031 return win_off <= offset
1032 && (offset + 20) <= (win_off + win->len);
1035 unsigned char *use_pack(struct packed_git *p,
1036 struct pack_window **w_cursor,
1037 off_t offset,
1038 unsigned long *left)
1040 struct pack_window *win = *w_cursor;
1042 /* Since packfiles end in a hash of their content and it's
1043 * pointless to ask for an offset into the middle of that
1044 * hash, and the in_window function above wouldn't match
1045 * don't allow an offset too close to the end of the file.
1047 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1048 die("packfile %s cannot be accessed", p->pack_name);
1049 if (offset > (p->pack_size - 20))
1050 die("offset beyond end of packfile (truncated pack?)");
1051 if (offset < 0)
1052 die(_("offset before end of packfile (broken .idx?)"));
1054 if (!win || !in_window(win, offset)) {
1055 if (win)
1056 win->inuse_cnt--;
1057 for (win = p->windows; win; win = win->next) {
1058 if (in_window(win, offset))
1059 break;
1061 if (!win) {
1062 size_t window_align = packed_git_window_size / 2;
1063 off_t len;
1065 if (p->pack_fd == -1 && open_packed_git(p))
1066 die("packfile %s cannot be accessed", p->pack_name);
1068 win = xcalloc(1, sizeof(*win));
1069 win->offset = (offset / window_align) * window_align;
1070 len = p->pack_size - win->offset;
1071 if (len > packed_git_window_size)
1072 len = packed_git_window_size;
1073 win->len = (size_t)len;
1074 pack_mapped += win->len;
1075 while (packed_git_limit < pack_mapped
1076 && unuse_one_window(p))
1077 ; /* nothing */
1078 win->base = xmmap(NULL, win->len,
1079 PROT_READ, MAP_PRIVATE,
1080 p->pack_fd, win->offset);
1081 if (win->base == MAP_FAILED)
1082 die_errno("packfile %s cannot be mapped",
1083 p->pack_name);
1084 if (!win->offset && win->len == p->pack_size
1085 && !p->do_not_close)
1086 close_pack_fd(p);
1087 pack_mmap_calls++;
1088 pack_open_windows++;
1089 if (pack_mapped > peak_pack_mapped)
1090 peak_pack_mapped = pack_mapped;
1091 if (pack_open_windows > peak_pack_open_windows)
1092 peak_pack_open_windows = pack_open_windows;
1093 win->next = p->windows;
1094 p->windows = win;
1097 if (win != *w_cursor) {
1098 win->last_used = pack_used_ctr++;
1099 win->inuse_cnt++;
1100 *w_cursor = win;
1102 offset -= win->offset;
1103 if (left)
1104 *left = win->len - xsize_t(offset);
1105 return win->base + offset;
1108 static struct packed_git *alloc_packed_git(int extra)
1110 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
1111 memset(p, 0, sizeof(*p));
1112 p->pack_fd = -1;
1113 return p;
1116 static void try_to_free_pack_memory(size_t size)
1118 release_pack_memory(size);
1121 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
1123 static int have_set_try_to_free_routine;
1124 struct stat st;
1125 size_t alloc;
1126 struct packed_git *p;
1128 if (!have_set_try_to_free_routine) {
1129 have_set_try_to_free_routine = 1;
1130 set_try_to_free_routine(try_to_free_pack_memory);
1134 * Make sure a corresponding .pack file exists and that
1135 * the index looks sane.
1137 if (!strip_suffix_mem(path, &path_len, ".idx"))
1138 return NULL;
1141 * ".pack" is long enough to hold any suffix we're adding (and
1142 * the use xsnprintf double-checks that)
1144 alloc = st_add3(path_len, strlen(".pack"), 1);
1145 p = alloc_packed_git(alloc);
1146 memcpy(p->pack_name, path, path_len);
1148 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
1149 if (!access(p->pack_name, F_OK))
1150 p->pack_keep = 1;
1152 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
1153 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1154 free(p);
1155 return NULL;
1158 /* ok, it looks sane as far as we can check without
1159 * actually mapping the pack file.
1161 p->pack_size = st.st_size;
1162 p->pack_local = local;
1163 p->mtime = st.st_mtime;
1164 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1165 hashclr(p->sha1);
1166 return p;
1169 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1171 const char *path = sha1_pack_name(sha1);
1172 size_t alloc = st_add(strlen(path), 1);
1173 struct packed_git *p = alloc_packed_git(alloc);
1175 memcpy(p->pack_name, path, alloc); /* includes NUL */
1176 hashcpy(p->sha1, sha1);
1177 if (check_packed_git_idx(idx_path, p)) {
1178 free(p);
1179 return NULL;
1182 return p;
1185 void install_packed_git(struct packed_git *pack)
1187 if (pack->pack_fd != -1)
1188 pack_open_fds++;
1190 pack->next = packed_git;
1191 packed_git = pack;
1194 void (*report_garbage)(unsigned seen_bits, const char *path);
1196 static void report_helper(const struct string_list *list,
1197 int seen_bits, int first, int last)
1199 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
1200 return;
1202 for (; first < last; first++)
1203 report_garbage(seen_bits, list->items[first].string);
1206 static void report_pack_garbage(struct string_list *list)
1208 int i, baselen = -1, first = 0, seen_bits = 0;
1210 if (!report_garbage)
1211 return;
1213 string_list_sort(list);
1215 for (i = 0; i < list->nr; i++) {
1216 const char *path = list->items[i].string;
1217 if (baselen != -1 &&
1218 strncmp(path, list->items[first].string, baselen)) {
1219 report_helper(list, seen_bits, first, i);
1220 baselen = -1;
1221 seen_bits = 0;
1223 if (baselen == -1) {
1224 const char *dot = strrchr(path, '.');
1225 if (!dot) {
1226 report_garbage(PACKDIR_FILE_GARBAGE, path);
1227 continue;
1229 baselen = dot - path + 1;
1230 first = i;
1232 if (!strcmp(path + baselen, "pack"))
1233 seen_bits |= 1;
1234 else if (!strcmp(path + baselen, "idx"))
1235 seen_bits |= 2;
1237 report_helper(list, seen_bits, first, list->nr);
1240 static void prepare_packed_git_one(char *objdir, int local)
1242 struct strbuf path = STRBUF_INIT;
1243 size_t dirnamelen;
1244 DIR *dir;
1245 struct dirent *de;
1246 struct string_list garbage = STRING_LIST_INIT_DUP;
1248 strbuf_addstr(&path, objdir);
1249 strbuf_addstr(&path, "/pack");
1250 dir = opendir(path.buf);
1251 if (!dir) {
1252 if (errno != ENOENT)
1253 error_errno("unable to open object pack directory: %s",
1254 path.buf);
1255 strbuf_release(&path);
1256 return;
1258 strbuf_addch(&path, '/');
1259 dirnamelen = path.len;
1260 while ((de = readdir(dir)) != NULL) {
1261 struct packed_git *p;
1262 size_t base_len;
1264 if (is_dot_or_dotdot(de->d_name))
1265 continue;
1267 strbuf_setlen(&path, dirnamelen);
1268 strbuf_addstr(&path, de->d_name);
1270 base_len = path.len;
1271 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1272 /* Don't reopen a pack we already have. */
1273 for (p = packed_git; p; p = p->next) {
1274 size_t len;
1275 if (strip_suffix(p->pack_name, ".pack", &len) &&
1276 len == base_len &&
1277 !memcmp(p->pack_name, path.buf, len))
1278 break;
1280 if (p == NULL &&
1282 * See if it really is a valid .idx file with
1283 * corresponding .pack file that we can map.
1285 (p = add_packed_git(path.buf, path.len, local)) != NULL)
1286 install_packed_git(p);
1289 if (!report_garbage)
1290 continue;
1292 if (ends_with(de->d_name, ".idx") ||
1293 ends_with(de->d_name, ".pack") ||
1294 ends_with(de->d_name, ".bitmap") ||
1295 ends_with(de->d_name, ".keep"))
1296 string_list_append(&garbage, path.buf);
1297 else
1298 report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
1300 closedir(dir);
1301 report_pack_garbage(&garbage);
1302 string_list_clear(&garbage, 0);
1303 strbuf_release(&path);
1306 static int sort_pack(const void *a_, const void *b_)
1308 struct packed_git *a = *((struct packed_git **)a_);
1309 struct packed_git *b = *((struct packed_git **)b_);
1310 int st;
1313 * Local packs tend to contain objects specific to our
1314 * variant of the project than remote ones. In addition,
1315 * remote ones could be on a network mounted filesystem.
1316 * Favor local ones for these reasons.
1318 st = a->pack_local - b->pack_local;
1319 if (st)
1320 return -st;
1323 * Younger packs tend to contain more recent objects,
1324 * and more recent objects tend to get accessed more
1325 * often.
1327 if (a->mtime < b->mtime)
1328 return 1;
1329 else if (a->mtime == b->mtime)
1330 return 0;
1331 return -1;
1334 static void rearrange_packed_git(void)
1336 struct packed_git **ary, *p;
1337 int i, n;
1339 for (n = 0, p = packed_git; p; p = p->next)
1340 n++;
1341 if (n < 2)
1342 return;
1344 /* prepare an array of packed_git for easier sorting */
1345 ary = xcalloc(n, sizeof(struct packed_git *));
1346 for (n = 0, p = packed_git; p; p = p->next)
1347 ary[n++] = p;
1349 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1351 /* link them back again */
1352 for (i = 0; i < n - 1; i++)
1353 ary[i]->next = ary[i + 1];
1354 ary[n - 1]->next = NULL;
1355 packed_git = ary[0];
1357 free(ary);
1360 static void prepare_packed_git_mru(void)
1362 struct packed_git *p;
1364 mru_clear(packed_git_mru);
1365 for (p = packed_git; p; p = p->next)
1366 mru_append(packed_git_mru, p);
1369 static int prepare_packed_git_run_once = 0;
1370 void prepare_packed_git(void)
1372 struct alternate_object_database *alt;
1374 if (prepare_packed_git_run_once)
1375 return;
1376 prepare_packed_git_one(get_object_directory(), 1);
1377 prepare_alt_odb();
1378 for (alt = alt_odb_list; alt; alt = alt->next) {
1379 alt->name[-1] = 0;
1380 prepare_packed_git_one(alt->base, 0);
1381 alt->name[-1] = '/';
1383 rearrange_packed_git();
1384 prepare_packed_git_mru();
1385 prepare_packed_git_run_once = 1;
1388 void reprepare_packed_git(void)
1390 prepare_packed_git_run_once = 0;
1391 prepare_packed_git();
1394 static void mark_bad_packed_object(struct packed_git *p,
1395 const unsigned char *sha1)
1397 unsigned i;
1398 for (i = 0; i < p->num_bad_objects; i++)
1399 if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1400 return;
1401 p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1402 st_mult(GIT_SHA1_RAWSZ,
1403 st_add(p->num_bad_objects, 1)));
1404 hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1405 p->num_bad_objects++;
1408 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1410 struct packed_git *p;
1411 unsigned i;
1413 for (p = packed_git; p; p = p->next)
1414 for (i = 0; i < p->num_bad_objects; i++)
1415 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1416 return p;
1417 return NULL;
1421 * With an in-core object data in "map", rehash it to make sure the
1422 * object name actually matches "sha1" to detect object corruption.
1423 * With "map" == NULL, try reading the object named with "sha1" using
1424 * the streaming interface and rehash it to do the same.
1426 int check_sha1_signature(const unsigned char *sha1, void *map,
1427 unsigned long size, const char *type)
1429 unsigned char real_sha1[20];
1430 enum object_type obj_type;
1431 struct git_istream *st;
1432 git_SHA_CTX c;
1433 char hdr[32];
1434 int hdrlen;
1436 if (map) {
1437 hash_sha1_file(map, size, type, real_sha1);
1438 return hashcmp(sha1, real_sha1) ? -1 : 0;
1441 st = open_istream(sha1, &obj_type, &size, NULL);
1442 if (!st)
1443 return -1;
1445 /* Generate the header */
1446 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1448 /* Sha1.. */
1449 git_SHA1_Init(&c);
1450 git_SHA1_Update(&c, hdr, hdrlen);
1451 for (;;) {
1452 char buf[1024 * 16];
1453 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1455 if (readlen < 0) {
1456 close_istream(st);
1457 return -1;
1459 if (!readlen)
1460 break;
1461 git_SHA1_Update(&c, buf, readlen);
1463 git_SHA1_Final(real_sha1, &c);
1464 close_istream(st);
1465 return hashcmp(sha1, real_sha1) ? -1 : 0;
1468 int git_open_noatime(const char *name)
1470 static int sha1_file_open_flag = O_NOATIME;
1472 for (;;) {
1473 int fd;
1475 errno = 0;
1476 fd = open(name, O_RDONLY | sha1_file_open_flag);
1477 if (fd >= 0)
1478 return fd;
1480 /* Might the failure be due to O_NOATIME? */
1481 if (errno != ENOENT && sha1_file_open_flag) {
1482 sha1_file_open_flag = 0;
1483 continue;
1486 return -1;
1490 static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1492 struct alternate_object_database *alt;
1494 if (!lstat(sha1_file_name(sha1), st))
1495 return 0;
1497 prepare_alt_odb();
1498 errno = ENOENT;
1499 for (alt = alt_odb_list; alt; alt = alt->next) {
1500 fill_sha1_path(alt->name, sha1);
1501 if (!lstat(alt->base, st))
1502 return 0;
1505 return -1;
1508 static int open_sha1_file(const unsigned char *sha1)
1510 int fd;
1511 struct alternate_object_database *alt;
1512 int most_interesting_errno;
1514 fd = git_open_noatime(sha1_file_name(sha1));
1515 if (fd >= 0)
1516 return fd;
1517 most_interesting_errno = errno;
1519 prepare_alt_odb();
1520 for (alt = alt_odb_list; alt; alt = alt->next) {
1521 fill_sha1_path(alt->name, sha1);
1522 fd = git_open_noatime(alt->base);
1523 if (fd >= 0)
1524 return fd;
1525 if (most_interesting_errno == ENOENT)
1526 most_interesting_errno = errno;
1528 errno = most_interesting_errno;
1529 return -1;
1532 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1534 void *map;
1535 int fd;
1537 fd = open_sha1_file(sha1);
1538 map = NULL;
1539 if (fd >= 0) {
1540 struct stat st;
1542 if (!fstat(fd, &st)) {
1543 *size = xsize_t(st.st_size);
1544 if (!*size) {
1545 /* mmap() is forbidden on empty files */
1546 error("object file %s is empty", sha1_file_name(sha1));
1547 return NULL;
1549 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1551 close(fd);
1553 return map;
1556 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1557 unsigned long len, enum object_type *type, unsigned long *sizep)
1559 unsigned shift;
1560 unsigned long size, c;
1561 unsigned long used = 0;
1563 c = buf[used++];
1564 *type = (c >> 4) & 7;
1565 size = c & 15;
1566 shift = 4;
1567 while (c & 0x80) {
1568 if (len <= used || bitsizeof(long) <= shift) {
1569 error("bad object header");
1570 size = used = 0;
1571 break;
1573 c = buf[used++];
1574 size += (c & 0x7f) << shift;
1575 shift += 7;
1577 *sizep = size;
1578 return used;
1581 int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1583 /* Get the data stream */
1584 memset(stream, 0, sizeof(*stream));
1585 stream->next_in = map;
1586 stream->avail_in = mapsize;
1587 stream->next_out = buffer;
1588 stream->avail_out = bufsiz;
1590 git_inflate_init(stream);
1591 return git_inflate(stream, 0);
1594 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1595 unsigned long mapsize, void *buffer,
1596 unsigned long bufsiz, struct strbuf *header)
1598 int status;
1600 status = unpack_sha1_header(stream, map, mapsize, buffer, bufsiz);
1603 * Check if entire header is unpacked in the first iteration.
1605 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1606 return 0;
1609 * buffer[0..bufsiz] was not large enough. Copy the partial
1610 * result out to header, and then append the result of further
1611 * reading the stream.
1613 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1614 stream->next_out = buffer;
1615 stream->avail_out = bufsiz;
1617 do {
1618 status = git_inflate(stream, 0);
1619 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1620 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1621 return 0;
1622 stream->next_out = buffer;
1623 stream->avail_out = bufsiz;
1624 } while (status != Z_STREAM_END);
1625 return -1;
1628 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1630 int bytes = strlen(buffer) + 1;
1631 unsigned char *buf = xmallocz(size);
1632 unsigned long n;
1633 int status = Z_OK;
1635 n = stream->total_out - bytes;
1636 if (n > size)
1637 n = size;
1638 memcpy(buf, (char *) buffer + bytes, n);
1639 bytes = n;
1640 if (bytes <= size) {
1642 * The above condition must be (bytes <= size), not
1643 * (bytes < size). In other words, even though we
1644 * expect no more output and set avail_out to zero,
1645 * the input zlib stream may have bytes that express
1646 * "this concludes the stream", and we *do* want to
1647 * eat that input.
1649 * Otherwise we would not be able to test that we
1650 * consumed all the input to reach the expected size;
1651 * we also want to check that zlib tells us that all
1652 * went well with status == Z_STREAM_END at the end.
1654 stream->next_out = buf + bytes;
1655 stream->avail_out = size - bytes;
1656 while (status == Z_OK)
1657 status = git_inflate(stream, Z_FINISH);
1659 if (status == Z_STREAM_END && !stream->avail_in) {
1660 git_inflate_end(stream);
1661 return buf;
1664 if (status < 0)
1665 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1666 else if (stream->avail_in)
1667 error("garbage at end of loose object '%s'",
1668 sha1_to_hex(sha1));
1669 free(buf);
1670 return NULL;
1674 * We used to just use "sscanf()", but that's actually way
1675 * too permissive for what we want to check. So do an anal
1676 * object header parse by hand.
1678 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1679 unsigned int flags)
1681 const char *type_buf = hdr;
1682 unsigned long size;
1683 int type, type_len = 0;
1686 * The type can be of any size but is followed by
1687 * a space.
1689 for (;;) {
1690 char c = *hdr++;
1691 if (c == ' ')
1692 break;
1693 type_len++;
1696 type = type_from_string_gently(type_buf, type_len, 1);
1697 if (oi->typename)
1698 strbuf_add(oi->typename, type_buf, type_len);
1700 * Set type to 0 if its an unknown object and
1701 * we're obtaining the type using '--allow-unkown-type'
1702 * option.
1704 if ((flags & LOOKUP_UNKNOWN_OBJECT) && (type < 0))
1705 type = 0;
1706 else if (type < 0)
1707 die("invalid object type");
1708 if (oi->typep)
1709 *oi->typep = type;
1712 * The length must follow immediately, and be in canonical
1713 * decimal format (ie "010" is not valid).
1715 size = *hdr++ - '0';
1716 if (size > 9)
1717 return -1;
1718 if (size) {
1719 for (;;) {
1720 unsigned long c = *hdr - '0';
1721 if (c > 9)
1722 break;
1723 hdr++;
1724 size = size * 10 + c;
1728 if (oi->sizep)
1729 *oi->sizep = size;
1732 * The length must be followed by a zero byte
1734 return *hdr ? -1 : type;
1737 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1739 struct object_info oi;
1741 oi.sizep = sizep;
1742 oi.typename = NULL;
1743 oi.typep = NULL;
1744 return parse_sha1_header_extended(hdr, &oi, LOOKUP_REPLACE_OBJECT);
1747 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1749 int ret;
1750 git_zstream stream;
1751 char hdr[8192];
1753 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1754 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1755 return NULL;
1757 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1760 unsigned long get_size_from_delta(struct packed_git *p,
1761 struct pack_window **w_curs,
1762 off_t curpos)
1764 const unsigned char *data;
1765 unsigned char delta_head[20], *in;
1766 git_zstream stream;
1767 int st;
1769 memset(&stream, 0, sizeof(stream));
1770 stream.next_out = delta_head;
1771 stream.avail_out = sizeof(delta_head);
1773 git_inflate_init(&stream);
1774 do {
1775 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1776 stream.next_in = in;
1777 st = git_inflate(&stream, Z_FINISH);
1778 curpos += stream.next_in - in;
1779 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1780 stream.total_out < sizeof(delta_head));
1781 git_inflate_end(&stream);
1782 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1783 error("delta data unpack-initial failed");
1784 return 0;
1787 /* Examine the initial part of the delta to figure out
1788 * the result size.
1790 data = delta_head;
1792 /* ignore base size */
1793 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1795 /* Read the result size */
1796 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1799 static off_t get_delta_base(struct packed_git *p,
1800 struct pack_window **w_curs,
1801 off_t *curpos,
1802 enum object_type type,
1803 off_t delta_obj_offset)
1805 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1806 off_t base_offset;
1808 /* use_pack() assured us we have [base_info, base_info + 20)
1809 * as a range that we can look at without walking off the
1810 * end of the mapped window. Its actually the hash size
1811 * that is assured. An OFS_DELTA longer than the hash size
1812 * is stupid, as then a REF_DELTA would be smaller to store.
1814 if (type == OBJ_OFS_DELTA) {
1815 unsigned used = 0;
1816 unsigned char c = base_info[used++];
1817 base_offset = c & 127;
1818 while (c & 128) {
1819 base_offset += 1;
1820 if (!base_offset || MSB(base_offset, 7))
1821 return 0; /* overflow */
1822 c = base_info[used++];
1823 base_offset = (base_offset << 7) + (c & 127);
1825 base_offset = delta_obj_offset - base_offset;
1826 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1827 return 0; /* out of bound */
1828 *curpos += used;
1829 } else if (type == OBJ_REF_DELTA) {
1830 /* The base entry _must_ be in the same pack */
1831 base_offset = find_pack_entry_one(base_info, p);
1832 *curpos += 20;
1833 } else
1834 die("I am totally screwed");
1835 return base_offset;
1839 * Like get_delta_base above, but we return the sha1 instead of the pack
1840 * offset. This means it is cheaper for REF deltas (we do not have to do
1841 * the final object lookup), but more expensive for OFS deltas (we
1842 * have to load the revidx to convert the offset back into a sha1).
1844 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1845 struct pack_window **w_curs,
1846 off_t curpos,
1847 enum object_type type,
1848 off_t delta_obj_offset)
1850 if (type == OBJ_REF_DELTA) {
1851 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1852 return base;
1853 } else if (type == OBJ_OFS_DELTA) {
1854 struct revindex_entry *revidx;
1855 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1856 type, delta_obj_offset);
1858 if (!base_offset)
1859 return NULL;
1861 revidx = find_pack_revindex(p, base_offset);
1862 if (!revidx)
1863 return NULL;
1865 return nth_packed_object_sha1(p, revidx->nr);
1866 } else
1867 return NULL;
1870 int unpack_object_header(struct packed_git *p,
1871 struct pack_window **w_curs,
1872 off_t *curpos,
1873 unsigned long *sizep)
1875 unsigned char *base;
1876 unsigned long left;
1877 unsigned long used;
1878 enum object_type type;
1880 /* use_pack() assures us we have [base, base + 20) available
1881 * as a range that we can look at. (Its actually the hash
1882 * size that is assured.) With our object header encoding
1883 * the maximum deflated object size is 2^137, which is just
1884 * insane, so we know won't exceed what we have been given.
1886 base = use_pack(p, w_curs, *curpos, &left);
1887 used = unpack_object_header_buffer(base, left, &type, sizep);
1888 if (!used) {
1889 type = OBJ_BAD;
1890 } else
1891 *curpos += used;
1893 return type;
1896 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1898 int type;
1899 struct revindex_entry *revidx;
1900 const unsigned char *sha1;
1901 revidx = find_pack_revindex(p, obj_offset);
1902 if (!revidx)
1903 return OBJ_BAD;
1904 sha1 = nth_packed_object_sha1(p, revidx->nr);
1905 mark_bad_packed_object(p, sha1);
1906 type = sha1_object_info(sha1, NULL);
1907 if (type <= OBJ_NONE)
1908 return OBJ_BAD;
1909 return type;
1912 #define POI_STACK_PREALLOC 64
1914 static enum object_type packed_to_object_type(struct packed_git *p,
1915 off_t obj_offset,
1916 enum object_type type,
1917 struct pack_window **w_curs,
1918 off_t curpos)
1920 off_t small_poi_stack[POI_STACK_PREALLOC];
1921 off_t *poi_stack = small_poi_stack;
1922 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1924 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1925 off_t base_offset;
1926 unsigned long size;
1927 /* Push the object we're going to leave behind */
1928 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1929 poi_stack_alloc = alloc_nr(poi_stack_nr);
1930 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1931 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1932 } else {
1933 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1935 poi_stack[poi_stack_nr++] = obj_offset;
1936 /* If parsing the base offset fails, just unwind */
1937 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1938 if (!base_offset)
1939 goto unwind;
1940 curpos = obj_offset = base_offset;
1941 type = unpack_object_header(p, w_curs, &curpos, &size);
1942 if (type <= OBJ_NONE) {
1943 /* If getting the base itself fails, we first
1944 * retry the base, otherwise unwind */
1945 type = retry_bad_packed_offset(p, base_offset);
1946 if (type > OBJ_NONE)
1947 goto out;
1948 goto unwind;
1952 switch (type) {
1953 case OBJ_BAD:
1954 case OBJ_COMMIT:
1955 case OBJ_TREE:
1956 case OBJ_BLOB:
1957 case OBJ_TAG:
1958 break;
1959 default:
1960 error("unknown object type %i at offset %"PRIuMAX" in %s",
1961 type, (uintmax_t)obj_offset, p->pack_name);
1962 type = OBJ_BAD;
1965 out:
1966 if (poi_stack != small_poi_stack)
1967 free(poi_stack);
1968 return type;
1970 unwind:
1971 while (poi_stack_nr) {
1972 obj_offset = poi_stack[--poi_stack_nr];
1973 type = retry_bad_packed_offset(p, obj_offset);
1974 if (type > OBJ_NONE)
1975 goto out;
1977 type = OBJ_BAD;
1978 goto out;
1981 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1982 struct object_info *oi)
1984 struct pack_window *w_curs = NULL;
1985 unsigned long size;
1986 off_t curpos = obj_offset;
1987 enum object_type type;
1990 * We always get the representation type, but only convert it to
1991 * a "real" type later if the caller is interested.
1993 type = unpack_object_header(p, &w_curs, &curpos, &size);
1995 if (oi->sizep) {
1996 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1997 off_t tmp_pos = curpos;
1998 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1999 type, obj_offset);
2000 if (!base_offset) {
2001 type = OBJ_BAD;
2002 goto out;
2004 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
2005 if (*oi->sizep == 0) {
2006 type = OBJ_BAD;
2007 goto out;
2009 } else {
2010 *oi->sizep = size;
2014 if (oi->disk_sizep) {
2015 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2016 *oi->disk_sizep = revidx[1].offset - obj_offset;
2019 if (oi->typep) {
2020 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
2021 if (*oi->typep < 0) {
2022 type = OBJ_BAD;
2023 goto out;
2027 if (oi->delta_base_sha1) {
2028 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2029 const unsigned char *base;
2031 base = get_delta_base_sha1(p, &w_curs, curpos,
2032 type, obj_offset);
2033 if (!base) {
2034 type = OBJ_BAD;
2035 goto out;
2038 hashcpy(oi->delta_base_sha1, base);
2039 } else
2040 hashclr(oi->delta_base_sha1);
2043 out:
2044 unuse_pack(&w_curs);
2045 return type;
2048 static void *unpack_compressed_entry(struct packed_git *p,
2049 struct pack_window **w_curs,
2050 off_t curpos,
2051 unsigned long size)
2053 int st;
2054 git_zstream stream;
2055 unsigned char *buffer, *in;
2057 buffer = xmallocz_gently(size);
2058 if (!buffer)
2059 return NULL;
2060 memset(&stream, 0, sizeof(stream));
2061 stream.next_out = buffer;
2062 stream.avail_out = size + 1;
2064 git_inflate_init(&stream);
2065 do {
2066 in = use_pack(p, w_curs, curpos, &stream.avail_in);
2067 stream.next_in = in;
2068 st = git_inflate(&stream, Z_FINISH);
2069 if (!stream.avail_out)
2070 break; /* the payload is larger than it should be */
2071 curpos += stream.next_in - in;
2072 } while (st == Z_OK || st == Z_BUF_ERROR);
2073 git_inflate_end(&stream);
2074 if ((st != Z_STREAM_END) || stream.total_out != size) {
2075 free(buffer);
2076 return NULL;
2079 return buffer;
2082 #define MAX_DELTA_CACHE (256)
2084 static size_t delta_base_cached;
2086 static struct delta_base_cache_lru_list {
2087 struct delta_base_cache_lru_list *prev;
2088 struct delta_base_cache_lru_list *next;
2089 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
2091 static struct delta_base_cache_entry {
2092 struct delta_base_cache_lru_list lru;
2093 void *data;
2094 struct packed_git *p;
2095 off_t base_offset;
2096 unsigned long size;
2097 enum object_type type;
2098 } delta_base_cache[MAX_DELTA_CACHE];
2100 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
2102 unsigned long hash;
2104 hash = (unsigned long)(intptr_t)p + (unsigned long)base_offset;
2105 hash += (hash >> 8) + (hash >> 16);
2106 return hash % MAX_DELTA_CACHE;
2109 static struct delta_base_cache_entry *
2110 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2112 unsigned long hash = pack_entry_hash(p, base_offset);
2113 return delta_base_cache + hash;
2116 static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
2117 struct packed_git *p, off_t base_offset)
2119 return (ent->data && ent->p == p && ent->base_offset == base_offset);
2122 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2124 struct delta_base_cache_entry *ent;
2125 ent = get_delta_base_cache_entry(p, base_offset);
2126 return eq_delta_base_cache_entry(ent, p, base_offset);
2129 static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2131 ent->data = NULL;
2132 ent->lru.next->prev = ent->lru.prev;
2133 ent->lru.prev->next = ent->lru.next;
2134 delta_base_cached -= ent->size;
2137 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2138 unsigned long *base_size, enum object_type *type, int keep_cache)
2140 struct delta_base_cache_entry *ent;
2141 void *ret;
2143 ent = get_delta_base_cache_entry(p, base_offset);
2145 if (!eq_delta_base_cache_entry(ent, p, base_offset))
2146 return unpack_entry(p, base_offset, type, base_size);
2148 ret = ent->data;
2150 if (!keep_cache)
2151 clear_delta_base_cache_entry(ent);
2152 else
2153 ret = xmemdupz(ent->data, ent->size);
2154 *type = ent->type;
2155 *base_size = ent->size;
2156 return ret;
2159 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2161 if (ent->data) {
2162 free(ent->data);
2163 ent->data = NULL;
2164 ent->lru.next->prev = ent->lru.prev;
2165 ent->lru.prev->next = ent->lru.next;
2166 delta_base_cached -= ent->size;
2170 void clear_delta_base_cache(void)
2172 unsigned long p;
2173 for (p = 0; p < MAX_DELTA_CACHE; p++)
2174 release_delta_base_cache(&delta_base_cache[p]);
2177 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2178 void *base, unsigned long base_size, enum object_type type)
2180 unsigned long hash = pack_entry_hash(p, base_offset);
2181 struct delta_base_cache_entry *ent = delta_base_cache + hash;
2182 struct delta_base_cache_lru_list *lru;
2184 release_delta_base_cache(ent);
2185 delta_base_cached += base_size;
2187 for (lru = delta_base_cache_lru.next;
2188 delta_base_cached > delta_base_cache_limit
2189 && lru != &delta_base_cache_lru;
2190 lru = lru->next) {
2191 struct delta_base_cache_entry *f = (void *)lru;
2192 if (f->type == OBJ_BLOB)
2193 release_delta_base_cache(f);
2195 for (lru = delta_base_cache_lru.next;
2196 delta_base_cached > delta_base_cache_limit
2197 && lru != &delta_base_cache_lru;
2198 lru = lru->next) {
2199 struct delta_base_cache_entry *f = (void *)lru;
2200 release_delta_base_cache(f);
2203 ent->p = p;
2204 ent->base_offset = base_offset;
2205 ent->type = type;
2206 ent->data = base;
2207 ent->size = base_size;
2208 ent->lru.next = &delta_base_cache_lru;
2209 ent->lru.prev = delta_base_cache_lru.prev;
2210 delta_base_cache_lru.prev->next = &ent->lru;
2211 delta_base_cache_lru.prev = &ent->lru;
2214 static void *read_object(const unsigned char *sha1, enum object_type *type,
2215 unsigned long *size);
2217 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2219 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2220 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2221 p->pack_name, (uintmax_t)obj_offset);
2224 int do_check_packed_object_crc;
2226 #define UNPACK_ENTRY_STACK_PREALLOC 64
2227 struct unpack_entry_stack_ent {
2228 off_t obj_offset;
2229 off_t curpos;
2230 unsigned long size;
2233 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2234 enum object_type *final_type, unsigned long *final_size)
2236 struct pack_window *w_curs = NULL;
2237 off_t curpos = obj_offset;
2238 void *data = NULL;
2239 unsigned long size;
2240 enum object_type type;
2241 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2242 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2243 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2244 int base_from_cache = 0;
2246 write_pack_access_log(p, obj_offset);
2248 /* PHASE 1: drill down to the innermost base object */
2249 for (;;) {
2250 off_t base_offset;
2251 int i;
2252 struct delta_base_cache_entry *ent;
2254 ent = get_delta_base_cache_entry(p, curpos);
2255 if (eq_delta_base_cache_entry(ent, p, curpos)) {
2256 type = ent->type;
2257 data = ent->data;
2258 size = ent->size;
2259 clear_delta_base_cache_entry(ent);
2260 base_from_cache = 1;
2261 break;
2264 if (do_check_packed_object_crc && p->index_version > 1) {
2265 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2266 off_t len = revidx[1].offset - obj_offset;
2267 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2268 const unsigned char *sha1 =
2269 nth_packed_object_sha1(p, revidx->nr);
2270 error("bad packed object CRC for %s",
2271 sha1_to_hex(sha1));
2272 mark_bad_packed_object(p, sha1);
2273 unuse_pack(&w_curs);
2274 return NULL;
2278 type = unpack_object_header(p, &w_curs, &curpos, &size);
2279 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2280 break;
2282 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2283 if (!base_offset) {
2284 error("failed to validate delta base reference "
2285 "at offset %"PRIuMAX" from %s",
2286 (uintmax_t)curpos, p->pack_name);
2287 /* bail to phase 2, in hopes of recovery */
2288 data = NULL;
2289 break;
2292 /* push object, proceed to base */
2293 if (delta_stack_nr >= delta_stack_alloc
2294 && delta_stack == small_delta_stack) {
2295 delta_stack_alloc = alloc_nr(delta_stack_nr);
2296 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
2297 memcpy(delta_stack, small_delta_stack,
2298 sizeof(*delta_stack)*delta_stack_nr);
2299 } else {
2300 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2302 i = delta_stack_nr++;
2303 delta_stack[i].obj_offset = obj_offset;
2304 delta_stack[i].curpos = curpos;
2305 delta_stack[i].size = size;
2307 curpos = obj_offset = base_offset;
2310 /* PHASE 2: handle the base */
2311 switch (type) {
2312 case OBJ_OFS_DELTA:
2313 case OBJ_REF_DELTA:
2314 if (data)
2315 die("BUG: unpack_entry: left loop at a valid delta");
2316 break;
2317 case OBJ_COMMIT:
2318 case OBJ_TREE:
2319 case OBJ_BLOB:
2320 case OBJ_TAG:
2321 if (!base_from_cache)
2322 data = unpack_compressed_entry(p, &w_curs, curpos, size);
2323 break;
2324 default:
2325 data = NULL;
2326 error("unknown object type %i at offset %"PRIuMAX" in %s",
2327 type, (uintmax_t)obj_offset, p->pack_name);
2330 /* PHASE 3: apply deltas in order */
2332 /* invariants:
2333 * 'data' holds the base data, or NULL if there was corruption
2335 while (delta_stack_nr) {
2336 void *delta_data;
2337 void *base = data;
2338 unsigned long delta_size, base_size = size;
2339 int i;
2341 data = NULL;
2343 if (base)
2344 add_delta_base_cache(p, obj_offset, base, base_size, type);
2346 if (!base) {
2348 * We're probably in deep shit, but let's try to fetch
2349 * the required base anyway from another pack or loose.
2350 * This is costly but should happen only in the presence
2351 * of a corrupted pack, and is better than failing outright.
2353 struct revindex_entry *revidx;
2354 const unsigned char *base_sha1;
2355 revidx = find_pack_revindex(p, obj_offset);
2356 if (revidx) {
2357 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2358 error("failed to read delta base object %s"
2359 " at offset %"PRIuMAX" from %s",
2360 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2361 p->pack_name);
2362 mark_bad_packed_object(p, base_sha1);
2363 base = read_object(base_sha1, &type, &base_size);
2367 i = --delta_stack_nr;
2368 obj_offset = delta_stack[i].obj_offset;
2369 curpos = delta_stack[i].curpos;
2370 delta_size = delta_stack[i].size;
2372 if (!base)
2373 continue;
2375 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2377 if (!delta_data) {
2378 error("failed to unpack compressed delta "
2379 "at offset %"PRIuMAX" from %s",
2380 (uintmax_t)curpos, p->pack_name);
2381 data = NULL;
2382 continue;
2385 data = patch_delta(base, base_size,
2386 delta_data, delta_size,
2387 &size);
2390 * We could not apply the delta; warn the user, but keep going.
2391 * Our failure will be noticed either in the next iteration of
2392 * the loop, or if this is the final delta, in the caller when
2393 * we return NULL. Those code paths will take care of making
2394 * a more explicit warning and retrying with another copy of
2395 * the object.
2397 if (!data)
2398 error("failed to apply delta");
2400 free(delta_data);
2403 *final_type = type;
2404 *final_size = size;
2406 unuse_pack(&w_curs);
2408 if (delta_stack != small_delta_stack)
2409 free(delta_stack);
2411 return data;
2414 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2415 uint32_t n)
2417 const unsigned char *index = p->index_data;
2418 if (!index) {
2419 if (open_pack_index(p))
2420 return NULL;
2421 index = p->index_data;
2423 if (n >= p->num_objects)
2424 return NULL;
2425 index += 4 * 256;
2426 if (p->index_version == 1) {
2427 return index + 24 * n + 4;
2428 } else {
2429 index += 8;
2430 return index + 20 * n;
2434 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2436 const unsigned char *ptr = vptr;
2437 const unsigned char *start = p->index_data;
2438 const unsigned char *end = start + p->index_size;
2439 if (ptr < start)
2440 die(_("offset before start of pack index for %s (corrupt index?)"),
2441 p->pack_name);
2442 /* No need to check for underflow; .idx files must be at least 8 bytes */
2443 if (ptr >= end - 8)
2444 die(_("offset beyond end of pack index for %s (truncated index?)"),
2445 p->pack_name);
2448 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2450 const unsigned char *index = p->index_data;
2451 index += 4 * 256;
2452 if (p->index_version == 1) {
2453 return ntohl(*((uint32_t *)(index + 24 * n)));
2454 } else {
2455 uint32_t off;
2456 index += 8 + p->num_objects * (20 + 4);
2457 off = ntohl(*((uint32_t *)(index + 4 * n)));
2458 if (!(off & 0x80000000))
2459 return off;
2460 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2461 check_pack_index_ptr(p, index);
2462 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2463 ntohl(*((uint32_t *)(index + 4)));
2467 off_t find_pack_entry_one(const unsigned char *sha1,
2468 struct packed_git *p)
2470 const uint32_t *level1_ofs = p->index_data;
2471 const unsigned char *index = p->index_data;
2472 unsigned hi, lo, stride;
2473 static int use_lookup = -1;
2474 static int debug_lookup = -1;
2476 if (debug_lookup < 0)
2477 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2479 if (!index) {
2480 if (open_pack_index(p))
2481 return 0;
2482 level1_ofs = p->index_data;
2483 index = p->index_data;
2485 if (p->index_version > 1) {
2486 level1_ofs += 2;
2487 index += 8;
2489 index += 4 * 256;
2490 hi = ntohl(level1_ofs[*sha1]);
2491 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2492 if (p->index_version > 1) {
2493 stride = 20;
2494 } else {
2495 stride = 24;
2496 index += 4;
2499 if (debug_lookup)
2500 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2501 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2503 if (use_lookup < 0)
2504 use_lookup = !!getenv("GIT_USE_LOOKUP");
2505 if (use_lookup) {
2506 int pos = sha1_entry_pos(index, stride, 0,
2507 lo, hi, p->num_objects, sha1);
2508 if (pos < 0)
2509 return 0;
2510 return nth_packed_object_offset(p, pos);
2513 do {
2514 unsigned mi = (lo + hi) / 2;
2515 int cmp = hashcmp(index + mi * stride, sha1);
2517 if (debug_lookup)
2518 printf("lo %u hi %u rg %u mi %u\n",
2519 lo, hi, hi - lo, mi);
2520 if (!cmp)
2521 return nth_packed_object_offset(p, mi);
2522 if (cmp > 0)
2523 hi = mi;
2524 else
2525 lo = mi+1;
2526 } while (lo < hi);
2527 return 0;
2530 int is_pack_valid(struct packed_git *p)
2532 /* An already open pack is known to be valid. */
2533 if (p->pack_fd != -1)
2534 return 1;
2536 /* If the pack has one window completely covering the
2537 * file size, the pack is known to be valid even if
2538 * the descriptor is not currently open.
2540 if (p->windows) {
2541 struct pack_window *w = p->windows;
2543 if (!w->offset && w->len == p->pack_size)
2544 return 1;
2547 /* Force the pack to open to prove its valid. */
2548 return !open_packed_git(p);
2551 static int fill_pack_entry(const unsigned char *sha1,
2552 struct pack_entry *e,
2553 struct packed_git *p)
2555 off_t offset;
2557 if (p->num_bad_objects) {
2558 unsigned i;
2559 for (i = 0; i < p->num_bad_objects; i++)
2560 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2561 return 0;
2564 offset = find_pack_entry_one(sha1, p);
2565 if (!offset)
2566 return 0;
2569 * We are about to tell the caller where they can locate the
2570 * requested object. We better make sure the packfile is
2571 * still here and can be accessed before supplying that
2572 * answer, as it may have been deleted since the index was
2573 * loaded!
2575 if (!is_pack_valid(p))
2576 return 0;
2577 e->offset = offset;
2578 e->p = p;
2579 hashcpy(e->sha1, sha1);
2580 return 1;
2584 * Iff a pack file contains the object named by sha1, return true and
2585 * store its location to e.
2587 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2589 struct mru_entry *p;
2591 prepare_packed_git();
2592 if (!packed_git)
2593 return 0;
2595 for (p = packed_git_mru->head; p; p = p->next) {
2596 if (fill_pack_entry(sha1, e, p->item)) {
2597 mru_mark(packed_git_mru, p);
2598 return 1;
2601 return 0;
2604 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2605 struct packed_git *packs)
2607 struct packed_git *p;
2609 for (p = packs; p; p = p->next) {
2610 if (find_pack_entry_one(sha1, p))
2611 return p;
2613 return NULL;
2617 static int sha1_loose_object_info(const unsigned char *sha1,
2618 struct object_info *oi,
2619 int flags)
2621 int status = 0;
2622 unsigned long mapsize;
2623 void *map;
2624 git_zstream stream;
2625 char hdr[32];
2626 struct strbuf hdrbuf = STRBUF_INIT;
2628 if (oi->delta_base_sha1)
2629 hashclr(oi->delta_base_sha1);
2632 * If we don't care about type or size, then we don't
2633 * need to look inside the object at all. Note that we
2634 * do not optimize out the stat call, even if the
2635 * caller doesn't care about the disk-size, since our
2636 * return value implicitly indicates whether the
2637 * object even exists.
2639 if (!oi->typep && !oi->typename && !oi->sizep) {
2640 struct stat st;
2641 if (stat_sha1_file(sha1, &st) < 0)
2642 return -1;
2643 if (oi->disk_sizep)
2644 *oi->disk_sizep = st.st_size;
2645 return 0;
2648 map = map_sha1_file(sha1, &mapsize);
2649 if (!map)
2650 return -1;
2651 if (oi->disk_sizep)
2652 *oi->disk_sizep = mapsize;
2653 if ((flags & LOOKUP_UNKNOWN_OBJECT)) {
2654 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2655 status = error("unable to unpack %s header with --allow-unknown-type",
2656 sha1_to_hex(sha1));
2657 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2658 status = error("unable to unpack %s header",
2659 sha1_to_hex(sha1));
2660 if (status < 0)
2661 ; /* Do nothing */
2662 else if (hdrbuf.len) {
2663 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2664 status = error("unable to parse %s header with --allow-unknown-type",
2665 sha1_to_hex(sha1));
2666 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2667 status = error("unable to parse %s header", sha1_to_hex(sha1));
2668 git_inflate_end(&stream);
2669 munmap(map, mapsize);
2670 if (status && oi->typep)
2671 *oi->typep = status;
2672 strbuf_release(&hdrbuf);
2673 return 0;
2676 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2678 struct cached_object *co;
2679 struct pack_entry e;
2680 int rtype;
2681 enum object_type real_type;
2682 const unsigned char *real = lookup_replace_object_extended(sha1, flags);
2684 co = find_cached_object(real);
2685 if (co) {
2686 if (oi->typep)
2687 *(oi->typep) = co->type;
2688 if (oi->sizep)
2689 *(oi->sizep) = co->size;
2690 if (oi->disk_sizep)
2691 *(oi->disk_sizep) = 0;
2692 if (oi->delta_base_sha1)
2693 hashclr(oi->delta_base_sha1);
2694 if (oi->typename)
2695 strbuf_addstr(oi->typename, typename(co->type));
2696 oi->whence = OI_CACHED;
2697 return 0;
2700 if (!find_pack_entry(real, &e)) {
2701 /* Most likely it's a loose object. */
2702 if (!sha1_loose_object_info(real, oi, flags)) {
2703 oi->whence = OI_LOOSE;
2704 return 0;
2707 /* Not a loose object; someone else may have just packed it. */
2708 reprepare_packed_git();
2709 if (!find_pack_entry(real, &e))
2710 return -1;
2714 * packed_object_info() does not follow the delta chain to
2715 * find out the real type, unless it is given oi->typep.
2717 if (oi->typename && !oi->typep)
2718 oi->typep = &real_type;
2720 rtype = packed_object_info(e.p, e.offset, oi);
2721 if (rtype < 0) {
2722 mark_bad_packed_object(e.p, real);
2723 if (oi->typep == &real_type)
2724 oi->typep = NULL;
2725 return sha1_object_info_extended(real, oi, 0);
2726 } else if (in_delta_base_cache(e.p, e.offset)) {
2727 oi->whence = OI_DBCACHED;
2728 } else {
2729 oi->whence = OI_PACKED;
2730 oi->u.packed.offset = e.offset;
2731 oi->u.packed.pack = e.p;
2732 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2733 rtype == OBJ_OFS_DELTA);
2735 if (oi->typename)
2736 strbuf_addstr(oi->typename, typename(*oi->typep));
2737 if (oi->typep == &real_type)
2738 oi->typep = NULL;
2740 return 0;
2743 /* returns enum object_type or negative */
2744 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2746 enum object_type type;
2747 struct object_info oi = {NULL};
2749 oi.typep = &type;
2750 oi.sizep = sizep;
2751 if (sha1_object_info_extended(sha1, &oi, LOOKUP_REPLACE_OBJECT) < 0)
2752 return -1;
2753 return type;
2756 static void *read_packed_sha1(const unsigned char *sha1,
2757 enum object_type *type, unsigned long *size)
2759 struct pack_entry e;
2760 void *data;
2762 if (!find_pack_entry(sha1, &e))
2763 return NULL;
2764 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2765 if (!data) {
2767 * We're probably in deep shit, but let's try to fetch
2768 * the required object anyway from another pack or loose.
2769 * This should happen only in the presence of a corrupted
2770 * pack, and is better than failing outright.
2772 error("failed to read object %s at offset %"PRIuMAX" from %s",
2773 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2774 mark_bad_packed_object(e.p, sha1);
2775 data = read_object(sha1, type, size);
2777 return data;
2780 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2781 unsigned char *sha1)
2783 struct cached_object *co;
2785 hash_sha1_file(buf, len, typename(type), sha1);
2786 if (has_sha1_file(sha1) || find_cached_object(sha1))
2787 return 0;
2788 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2789 co = &cached_objects[cached_object_nr++];
2790 co->size = len;
2791 co->type = type;
2792 co->buf = xmalloc(len);
2793 memcpy(co->buf, buf, len);
2794 hashcpy(co->sha1, sha1);
2795 return 0;
2798 static void *read_object(const unsigned char *sha1, enum object_type *type,
2799 unsigned long *size)
2801 unsigned long mapsize;
2802 void *map, *buf;
2803 struct cached_object *co;
2805 co = find_cached_object(sha1);
2806 if (co) {
2807 *type = co->type;
2808 *size = co->size;
2809 return xmemdupz(co->buf, co->size);
2812 buf = read_packed_sha1(sha1, type, size);
2813 if (buf)
2814 return buf;
2815 map = map_sha1_file(sha1, &mapsize);
2816 if (map) {
2817 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2818 munmap(map, mapsize);
2819 return buf;
2821 reprepare_packed_git();
2822 return read_packed_sha1(sha1, type, size);
2826 * This function dies on corrupt objects; the callers who want to
2827 * deal with them should arrange to call read_object() and give error
2828 * messages themselves.
2830 void *read_sha1_file_extended(const unsigned char *sha1,
2831 enum object_type *type,
2832 unsigned long *size,
2833 unsigned flag)
2835 void *data;
2836 const struct packed_git *p;
2837 const unsigned char *repl = lookup_replace_object_extended(sha1, flag);
2839 errno = 0;
2840 data = read_object(repl, type, size);
2841 if (data)
2842 return data;
2844 if (errno && errno != ENOENT)
2845 die_errno("failed to read object %s", sha1_to_hex(sha1));
2847 /* die if we replaced an object with one that does not exist */
2848 if (repl != sha1)
2849 die("replacement %s not found for %s",
2850 sha1_to_hex(repl), sha1_to_hex(sha1));
2852 if (has_loose_object(repl)) {
2853 const char *path = sha1_file_name(sha1);
2855 die("loose object %s (stored in %s) is corrupt",
2856 sha1_to_hex(repl), path);
2859 if ((p = has_packed_and_bad(repl)) != NULL)
2860 die("packed object %s (stored in %s) is corrupt",
2861 sha1_to_hex(repl), p->pack_name);
2863 return NULL;
2866 void *read_object_with_reference(const unsigned char *sha1,
2867 const char *required_type_name,
2868 unsigned long *size,
2869 unsigned char *actual_sha1_return)
2871 enum object_type type, required_type;
2872 void *buffer;
2873 unsigned long isize;
2874 unsigned char actual_sha1[20];
2876 required_type = type_from_string(required_type_name);
2877 hashcpy(actual_sha1, sha1);
2878 while (1) {
2879 int ref_length = -1;
2880 const char *ref_type = NULL;
2882 buffer = read_sha1_file(actual_sha1, &type, &isize);
2883 if (!buffer)
2884 return NULL;
2885 if (type == required_type) {
2886 *size = isize;
2887 if (actual_sha1_return)
2888 hashcpy(actual_sha1_return, actual_sha1);
2889 return buffer;
2891 /* Handle references */
2892 else if (type == OBJ_COMMIT)
2893 ref_type = "tree ";
2894 else if (type == OBJ_TAG)
2895 ref_type = "object ";
2896 else {
2897 free(buffer);
2898 return NULL;
2900 ref_length = strlen(ref_type);
2902 if (ref_length + 40 > isize ||
2903 memcmp(buffer, ref_type, ref_length) ||
2904 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2905 free(buffer);
2906 return NULL;
2908 free(buffer);
2909 /* Now we have the ID of the referred-to object in
2910 * actual_sha1. Check again. */
2914 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2915 const char *type, unsigned char *sha1,
2916 char *hdr, int *hdrlen)
2918 git_SHA_CTX c;
2920 /* Generate the header */
2921 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
2923 /* Sha1.. */
2924 git_SHA1_Init(&c);
2925 git_SHA1_Update(&c, hdr, *hdrlen);
2926 git_SHA1_Update(&c, buf, len);
2927 git_SHA1_Final(sha1, &c);
2931 * Move the just written object into its final resting place.
2933 int finalize_object_file(const char *tmpfile, const char *filename)
2935 int ret = 0;
2937 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2938 goto try_rename;
2939 else if (link(tmpfile, filename))
2940 ret = errno;
2943 * Coda hack - coda doesn't like cross-directory links,
2944 * so we fall back to a rename, which will mean that it
2945 * won't be able to check collisions, but that's not a
2946 * big deal.
2948 * The same holds for FAT formatted media.
2950 * When this succeeds, we just return. We have nothing
2951 * left to unlink.
2953 if (ret && ret != EEXIST) {
2954 try_rename:
2955 if (!rename(tmpfile, filename))
2956 goto out;
2957 ret = errno;
2959 unlink_or_warn(tmpfile);
2960 if (ret) {
2961 if (ret != EEXIST) {
2962 return error_errno("unable to write sha1 filename %s", filename);
2964 /* FIXME!!! Collision check here ? */
2967 out:
2968 if (adjust_shared_perm(filename))
2969 return error("unable to set permission to '%s'", filename);
2970 return 0;
2973 static int write_buffer(int fd, const void *buf, size_t len)
2975 if (write_in_full(fd, buf, len) < 0)
2976 return error_errno("file write error");
2977 return 0;
2980 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2981 unsigned char *sha1)
2983 char hdr[32];
2984 int hdrlen = sizeof(hdr);
2985 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2986 return 0;
2989 /* Finalize a file on disk, and close it. */
2990 static void close_sha1_file(int fd)
2992 if (fsync_object_files)
2993 fsync_or_die(fd, "sha1 file");
2994 if (close(fd) != 0)
2995 die_errno("error when closing sha1 file");
2998 /* Size of directory component, including the ending '/' */
2999 static inline int directory_size(const char *filename)
3001 const char *s = strrchr(filename, '/');
3002 if (!s)
3003 return 0;
3004 return s - filename + 1;
3008 * This creates a temporary file in the same directory as the final
3009 * 'filename'
3011 * We want to avoid cross-directory filename renames, because those
3012 * can have problems on various filesystems (FAT, NFS, Coda).
3014 static int create_tmpfile(struct strbuf *tmp, const char *filename)
3016 int fd, dirlen = directory_size(filename);
3018 strbuf_reset(tmp);
3019 strbuf_add(tmp, filename, dirlen);
3020 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
3021 fd = git_mkstemp_mode(tmp->buf, 0444);
3022 if (fd < 0 && dirlen && errno == ENOENT) {
3024 * Make sure the directory exists; note that the contents
3025 * of the buffer are undefined after mkstemp returns an
3026 * error, so we have to rewrite the whole buffer from
3027 * scratch.
3029 strbuf_reset(tmp);
3030 strbuf_add(tmp, filename, dirlen - 1);
3031 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
3032 return -1;
3033 if (adjust_shared_perm(tmp->buf))
3034 return -1;
3036 /* Try again */
3037 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
3038 fd = git_mkstemp_mode(tmp->buf, 0444);
3040 return fd;
3043 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
3044 const void *buf, unsigned long len, time_t mtime)
3046 int fd, ret;
3047 unsigned char compressed[4096];
3048 git_zstream stream;
3049 git_SHA_CTX c;
3050 unsigned char parano_sha1[20];
3051 static struct strbuf tmp_file = STRBUF_INIT;
3052 const char *filename = sha1_file_name(sha1);
3054 fd = create_tmpfile(&tmp_file, filename);
3055 if (fd < 0) {
3056 if (errno == EACCES)
3057 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3058 else
3059 return error_errno("unable to create temporary file");
3062 /* Set it up */
3063 git_deflate_init(&stream, zlib_compression_level);
3064 stream.next_out = compressed;
3065 stream.avail_out = sizeof(compressed);
3066 git_SHA1_Init(&c);
3068 /* First header.. */
3069 stream.next_in = (unsigned char *)hdr;
3070 stream.avail_in = hdrlen;
3071 while (git_deflate(&stream, 0) == Z_OK)
3072 ; /* nothing */
3073 git_SHA1_Update(&c, hdr, hdrlen);
3075 /* Then the data itself.. */
3076 stream.next_in = (void *)buf;
3077 stream.avail_in = len;
3078 do {
3079 unsigned char *in0 = stream.next_in;
3080 ret = git_deflate(&stream, Z_FINISH);
3081 git_SHA1_Update(&c, in0, stream.next_in - in0);
3082 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
3083 die("unable to write sha1 file");
3084 stream.next_out = compressed;
3085 stream.avail_out = sizeof(compressed);
3086 } while (ret == Z_OK);
3088 if (ret != Z_STREAM_END)
3089 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
3090 ret = git_deflate_end_gently(&stream);
3091 if (ret != Z_OK)
3092 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
3093 git_SHA1_Final(parano_sha1, &c);
3094 if (hashcmp(sha1, parano_sha1) != 0)
3095 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
3097 close_sha1_file(fd);
3099 if (mtime) {
3100 struct utimbuf utb;
3101 utb.actime = mtime;
3102 utb.modtime = mtime;
3103 if (utime(tmp_file.buf, &utb) < 0)
3104 warning_errno("failed utime() on %s", tmp_file.buf);
3107 return finalize_object_file(tmp_file.buf, filename);
3110 static int freshen_loose_object(const unsigned char *sha1)
3112 return check_and_freshen(sha1, 1);
3115 static int freshen_packed_object(const unsigned char *sha1)
3117 struct pack_entry e;
3118 if (!find_pack_entry(sha1, &e))
3119 return 0;
3120 if (e.p->freshened)
3121 return 1;
3122 if (!freshen_file(e.p->pack_name))
3123 return 0;
3124 e.p->freshened = 1;
3125 return 1;
3128 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
3130 char hdr[32];
3131 int hdrlen = sizeof(hdr);
3133 /* Normally if we have it in the pack then we do not bother writing
3134 * it out into .git/objects/??/?{38} file.
3136 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3137 if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3138 return 0;
3139 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3142 int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
3143 unsigned char *sha1, unsigned flags)
3145 char *header;
3146 int hdrlen, status = 0;
3148 /* type string, SP, %lu of the length plus NUL must fit this */
3149 hdrlen = strlen(type) + 32;
3150 header = xmalloc(hdrlen);
3151 write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
3153 if (!(flags & HASH_WRITE_OBJECT))
3154 goto cleanup;
3155 if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3156 goto cleanup;
3157 status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
3159 cleanup:
3160 free(header);
3161 return status;
3164 int force_object_loose(const unsigned char *sha1, time_t mtime)
3166 void *buf;
3167 unsigned long len;
3168 enum object_type type;
3169 char hdr[32];
3170 int hdrlen;
3171 int ret;
3173 if (has_loose_object(sha1))
3174 return 0;
3175 buf = read_packed_sha1(sha1, &type, &len);
3176 if (!buf)
3177 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3178 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
3179 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3180 free(buf);
3182 return ret;
3185 int has_pack_index(const unsigned char *sha1)
3187 struct stat st;
3188 if (stat(sha1_pack_index_name(sha1), &st))
3189 return 0;
3190 return 1;
3193 int has_sha1_pack(const unsigned char *sha1)
3195 struct pack_entry e;
3196 return find_pack_entry(sha1, &e);
3199 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
3201 struct pack_entry e;
3203 if (find_pack_entry(sha1, &e))
3204 return 1;
3205 if (has_loose_object(sha1))
3206 return 1;
3207 if (flags & HAS_SHA1_QUICK)
3208 return 0;
3209 reprepare_packed_git();
3210 return find_pack_entry(sha1, &e);
3213 int has_object_file(const struct object_id *oid)
3215 return has_sha1_file(oid->hash);
3218 static void check_tree(const void *buf, size_t size)
3220 struct tree_desc desc;
3221 struct name_entry entry;
3223 init_tree_desc(&desc, buf, size);
3224 while (tree_entry(&desc, &entry))
3225 /* do nothing
3226 * tree_entry() will die() on malformed entries */
3230 static void check_commit(const void *buf, size_t size)
3232 struct commit c;
3233 memset(&c, 0, sizeof(c));
3234 if (parse_commit_buffer(&c, buf, size))
3235 die("corrupt commit");
3238 static void check_tag(const void *buf, size_t size)
3240 struct tag t;
3241 memset(&t, 0, sizeof(t));
3242 if (parse_tag_buffer(&t, buf, size))
3243 die("corrupt tag");
3246 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3247 enum object_type type,
3248 const char *path, unsigned flags)
3250 int ret, re_allocated = 0;
3251 int write_object = flags & HASH_WRITE_OBJECT;
3253 if (!type)
3254 type = OBJ_BLOB;
3257 * Convert blobs to git internal format
3259 if ((type == OBJ_BLOB) && path) {
3260 struct strbuf nbuf = STRBUF_INIT;
3261 if (convert_to_git(path, buf, size, &nbuf,
3262 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3263 buf = strbuf_detach(&nbuf, &size);
3264 re_allocated = 1;
3267 if (flags & HASH_FORMAT_CHECK) {
3268 if (type == OBJ_TREE)
3269 check_tree(buf, size);
3270 if (type == OBJ_COMMIT)
3271 check_commit(buf, size);
3272 if (type == OBJ_TAG)
3273 check_tag(buf, size);
3276 if (write_object)
3277 ret = write_sha1_file(buf, size, typename(type), sha1);
3278 else
3279 ret = hash_sha1_file(buf, size, typename(type), sha1);
3280 if (re_allocated)
3281 free(buf);
3282 return ret;
3285 static int index_stream_convert_blob(unsigned char *sha1, int fd,
3286 const char *path, unsigned flags)
3288 int ret;
3289 const int write_object = flags & HASH_WRITE_OBJECT;
3290 struct strbuf sbuf = STRBUF_INIT;
3292 assert(path);
3293 assert(would_convert_to_git_filter_fd(path));
3295 convert_to_git_filter_fd(path, fd, &sbuf,
3296 write_object ? safe_crlf : SAFE_CRLF_FALSE);
3298 if (write_object)
3299 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3300 sha1);
3301 else
3302 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3303 sha1);
3304 strbuf_release(&sbuf);
3305 return ret;
3308 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3309 const char *path, unsigned flags)
3311 struct strbuf sbuf = STRBUF_INIT;
3312 int ret;
3314 if (strbuf_read(&sbuf, fd, 4096) >= 0)
3315 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3316 else
3317 ret = -1;
3318 strbuf_release(&sbuf);
3319 return ret;
3322 #define SMALL_FILE_SIZE (32*1024)
3324 static int index_core(unsigned char *sha1, int fd, size_t size,
3325 enum object_type type, const char *path,
3326 unsigned flags)
3328 int ret;
3330 if (!size) {
3331 ret = index_mem(sha1, "", size, type, path, flags);
3332 } else if (size <= SMALL_FILE_SIZE) {
3333 char *buf = xmalloc(size);
3334 if (size == read_in_full(fd, buf, size))
3335 ret = index_mem(sha1, buf, size, type, path, flags);
3336 else
3337 ret = error_errno("short read");
3338 free(buf);
3339 } else {
3340 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3341 ret = index_mem(sha1, buf, size, type, path, flags);
3342 munmap(buf, size);
3344 return ret;
3348 * This creates one packfile per large blob unless bulk-checkin
3349 * machinery is "plugged".
3351 * This also bypasses the usual "convert-to-git" dance, and that is on
3352 * purpose. We could write a streaming version of the converting
3353 * functions and insert that before feeding the data to fast-import
3354 * (or equivalent in-core API described above). However, that is
3355 * somewhat complicated, as we do not know the size of the filter
3356 * result, which we need to know beforehand when writing a git object.
3357 * Since the primary motivation for trying to stream from the working
3358 * tree file and to avoid mmaping it in core is to deal with large
3359 * binary blobs, they generally do not want to get any conversion, and
3360 * callers should avoid this code path when filters are requested.
3362 static int index_stream(unsigned char *sha1, int fd, size_t size,
3363 enum object_type type, const char *path,
3364 unsigned flags)
3366 return index_bulk_checkin(sha1, fd, size, type, path, flags);
3369 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3370 enum object_type type, const char *path, unsigned flags)
3372 int ret;
3375 * Call xsize_t() only when needed to avoid potentially unnecessary
3376 * die() for large files.
3378 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3379 ret = index_stream_convert_blob(sha1, fd, path, flags);
3380 else if (!S_ISREG(st->st_mode))
3381 ret = index_pipe(sha1, fd, type, path, flags);
3382 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3383 (path && would_convert_to_git(path)))
3384 ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3385 flags);
3386 else
3387 ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3388 flags);
3389 close(fd);
3390 return ret;
3393 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3395 int fd;
3396 struct strbuf sb = STRBUF_INIT;
3398 switch (st->st_mode & S_IFMT) {
3399 case S_IFREG:
3400 fd = open(path, O_RDONLY);
3401 if (fd < 0)
3402 return error_errno("open(\"%s\")", path);
3403 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3404 return error("%s: failed to insert into database",
3405 path);
3406 break;
3407 case S_IFLNK:
3408 if (strbuf_readlink(&sb, path, st->st_size))
3409 return error_errno("readlink(\"%s\")", path);
3410 if (!(flags & HASH_WRITE_OBJECT))
3411 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3412 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3413 return error("%s: failed to insert into database",
3414 path);
3415 strbuf_release(&sb);
3416 break;
3417 case S_IFDIR:
3418 return resolve_gitlink_ref(path, "HEAD", sha1);
3419 default:
3420 return error("%s: unsupported file type", path);
3422 return 0;
3425 int read_pack_header(int fd, struct pack_header *header)
3427 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3428 /* "eof before pack header was fully read" */
3429 return PH_ERROR_EOF;
3431 if (header->hdr_signature != htonl(PACK_SIGNATURE))
3432 /* "protocol error (pack signature mismatch detected)" */
3433 return PH_ERROR_PACK_SIGNATURE;
3434 if (!pack_version_ok(header->hdr_version))
3435 /* "protocol error (pack version unsupported)" */
3436 return PH_ERROR_PROTOCOL;
3437 return 0;
3440 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3442 enum object_type type = sha1_object_info(sha1, NULL);
3443 if (type < 0)
3444 die("%s is not a valid object", sha1_to_hex(sha1));
3445 if (type != expect)
3446 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3447 typename(expect));
3450 static int for_each_file_in_obj_subdir(int subdir_nr,
3451 struct strbuf *path,
3452 each_loose_object_fn obj_cb,
3453 each_loose_cruft_fn cruft_cb,
3454 each_loose_subdir_fn subdir_cb,
3455 void *data)
3457 size_t baselen = path->len;
3458 DIR *dir = opendir(path->buf);
3459 struct dirent *de;
3460 int r = 0;
3462 if (!dir) {
3463 if (errno == ENOENT)
3464 return 0;
3465 return error_errno("unable to open %s", path->buf);
3468 while ((de = readdir(dir))) {
3469 if (is_dot_or_dotdot(de->d_name))
3470 continue;
3472 strbuf_setlen(path, baselen);
3473 strbuf_addf(path, "/%s", de->d_name);
3475 if (strlen(de->d_name) == 38) {
3476 char hex[41];
3477 unsigned char sha1[20];
3479 snprintf(hex, sizeof(hex), "%02x%s",
3480 subdir_nr, de->d_name);
3481 if (!get_sha1_hex(hex, sha1)) {
3482 if (obj_cb) {
3483 r = obj_cb(sha1, path->buf, data);
3484 if (r)
3485 break;
3487 continue;
3491 if (cruft_cb) {
3492 r = cruft_cb(de->d_name, path->buf, data);
3493 if (r)
3494 break;
3497 closedir(dir);
3499 strbuf_setlen(path, baselen);
3500 if (!r && subdir_cb)
3501 r = subdir_cb(subdir_nr, path->buf, data);
3503 return r;
3506 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3507 each_loose_object_fn obj_cb,
3508 each_loose_cruft_fn cruft_cb,
3509 each_loose_subdir_fn subdir_cb,
3510 void *data)
3512 size_t baselen = path->len;
3513 int r = 0;
3514 int i;
3516 for (i = 0; i < 256; i++) {
3517 strbuf_addf(path, "/%02x", i);
3518 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3519 subdir_cb, data);
3520 strbuf_setlen(path, baselen);
3521 if (r)
3522 break;
3525 return r;
3528 int for_each_loose_file_in_objdir(const char *path,
3529 each_loose_object_fn obj_cb,
3530 each_loose_cruft_fn cruft_cb,
3531 each_loose_subdir_fn subdir_cb,
3532 void *data)
3534 struct strbuf buf = STRBUF_INIT;
3535 int r;
3537 strbuf_addstr(&buf, path);
3538 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3539 subdir_cb, data);
3540 strbuf_release(&buf);
3542 return r;
3545 struct loose_alt_odb_data {
3546 each_loose_object_fn *cb;
3547 void *data;
3550 static int loose_from_alt_odb(struct alternate_object_database *alt,
3551 void *vdata)
3553 struct loose_alt_odb_data *data = vdata;
3554 struct strbuf buf = STRBUF_INIT;
3555 int r;
3557 /* copy base not including trailing '/' */
3558 strbuf_add(&buf, alt->base, alt->name - alt->base - 1);
3559 r = for_each_loose_file_in_objdir_buf(&buf,
3560 data->cb, NULL, NULL,
3561 data->data);
3562 strbuf_release(&buf);
3563 return r;
3566 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3568 struct loose_alt_odb_data alt;
3569 int r;
3571 r = for_each_loose_file_in_objdir(get_object_directory(),
3572 cb, NULL, NULL, data);
3573 if (r)
3574 return r;
3576 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3577 return 0;
3579 alt.cb = cb;
3580 alt.data = data;
3581 return foreach_alt_odb(loose_from_alt_odb, &alt);
3584 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3586 uint32_t i;
3587 int r = 0;
3589 for (i = 0; i < p->num_objects; i++) {
3590 const unsigned char *sha1 = nth_packed_object_sha1(p, i);
3592 if (!sha1)
3593 return error("unable to get sha1 of object %u in %s",
3594 i, p->pack_name);
3596 r = cb(sha1, p, i, data);
3597 if (r)
3598 break;
3600 return r;
3603 int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3605 struct packed_git *p;
3606 int r = 0;
3607 int pack_errors = 0;
3609 prepare_packed_git();
3610 for (p = packed_git; p; p = p->next) {
3611 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3612 continue;
3613 if (open_pack_index(p)) {
3614 pack_errors = 1;
3615 continue;
3617 r = for_each_object_in_pack(p, cb, data);
3618 if (r)
3619 break;
3621 return r ? r : pack_errors;