Revert "grep/pcre2: fix an edge case concerning ascii patterns and UTF-8 data"
[alt-git.git] / object-file.c
blobc1f7ece0550c8df1f18c42fcbfa93c84f867ac90
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "hash-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "replace-object.h"
27 #include "streaming.h"
28 #include "dir.h"
29 #include "list.h"
30 #include "mergesort.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "promisor-remote.h"
35 #include "submodule.h"
37 /* The maximum size for an object header. */
38 #define MAX_HEADER_LEN 32
41 #define EMPTY_TREE_SHA1_BIN_LITERAL \
42 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
43 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
44 #define EMPTY_TREE_SHA256_BIN_LITERAL \
45 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
46 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
47 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
48 "\x53\x21"
50 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
51 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
52 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
53 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
54 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
55 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
56 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
57 "\x18\x13"
59 static const struct object_id empty_tree_oid = {
60 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
61 .algo = GIT_HASH_SHA1,
63 static const struct object_id empty_blob_oid = {
64 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
65 .algo = GIT_HASH_SHA1,
67 static const struct object_id null_oid_sha1 = {
68 .hash = {0},
69 .algo = GIT_HASH_SHA1,
71 static const struct object_id empty_tree_oid_sha256 = {
72 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
73 .algo = GIT_HASH_SHA256,
75 static const struct object_id empty_blob_oid_sha256 = {
76 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
77 .algo = GIT_HASH_SHA256,
79 static const struct object_id null_oid_sha256 = {
80 .hash = {0},
81 .algo = GIT_HASH_SHA256,
84 static void git_hash_sha1_init(git_hash_ctx *ctx)
86 git_SHA1_Init(&ctx->sha1);
89 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
91 git_SHA1_Clone(&dst->sha1, &src->sha1);
94 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
96 git_SHA1_Update(&ctx->sha1, data, len);
99 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
101 git_SHA1_Final(hash, &ctx->sha1);
104 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
106 git_SHA1_Final(oid->hash, &ctx->sha1);
107 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
108 oid->algo = GIT_HASH_SHA1;
112 static void git_hash_sha256_init(git_hash_ctx *ctx)
114 git_SHA256_Init(&ctx->sha256);
117 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
119 git_SHA256_Clone(&dst->sha256, &src->sha256);
122 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
124 git_SHA256_Update(&ctx->sha256, data, len);
127 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
129 git_SHA256_Final(hash, &ctx->sha256);
132 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
134 git_SHA256_Final(oid->hash, &ctx->sha256);
136 * This currently does nothing, so the compiler should optimize it out,
137 * but keep it in case we extend the hash size again.
139 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
140 oid->algo = GIT_HASH_SHA256;
143 static void git_hash_unknown_init(git_hash_ctx *ctx)
145 BUG("trying to init unknown hash");
148 static void git_hash_unknown_clone(git_hash_ctx *dst, const git_hash_ctx *src)
150 BUG("trying to clone unknown hash");
153 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
155 BUG("trying to update unknown hash");
158 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
160 BUG("trying to finalize unknown hash");
163 static void git_hash_unknown_final_oid(struct object_id *oid, git_hash_ctx *ctx)
165 BUG("trying to finalize unknown hash");
169 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
171 NULL,
172 0x00000000,
176 git_hash_unknown_init,
177 git_hash_unknown_clone,
178 git_hash_unknown_update,
179 git_hash_unknown_final,
180 git_hash_unknown_final_oid,
181 NULL,
182 NULL,
183 NULL,
186 "sha1",
187 /* "sha1", big-endian */
188 0x73686131,
189 GIT_SHA1_RAWSZ,
190 GIT_SHA1_HEXSZ,
191 GIT_SHA1_BLKSZ,
192 git_hash_sha1_init,
193 git_hash_sha1_clone,
194 git_hash_sha1_update,
195 git_hash_sha1_final,
196 git_hash_sha1_final_oid,
197 &empty_tree_oid,
198 &empty_blob_oid,
199 &null_oid_sha1,
202 "sha256",
203 /* "s256", big-endian */
204 0x73323536,
205 GIT_SHA256_RAWSZ,
206 GIT_SHA256_HEXSZ,
207 GIT_SHA256_BLKSZ,
208 git_hash_sha256_init,
209 git_hash_sha256_clone,
210 git_hash_sha256_update,
211 git_hash_sha256_final,
212 git_hash_sha256_final_oid,
213 &empty_tree_oid_sha256,
214 &empty_blob_oid_sha256,
215 &null_oid_sha256,
219 const struct object_id *null_oid(void)
221 return the_hash_algo->null_oid;
224 const char *empty_tree_oid_hex(void)
226 static char buf[GIT_MAX_HEXSZ + 1];
227 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
230 const char *empty_blob_oid_hex(void)
232 static char buf[GIT_MAX_HEXSZ + 1];
233 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
236 int hash_algo_by_name(const char *name)
238 int i;
239 if (!name)
240 return GIT_HASH_UNKNOWN;
241 for (i = 1; i < GIT_HASH_NALGOS; i++)
242 if (!strcmp(name, hash_algos[i].name))
243 return i;
244 return GIT_HASH_UNKNOWN;
247 int hash_algo_by_id(uint32_t format_id)
249 int i;
250 for (i = 1; i < GIT_HASH_NALGOS; i++)
251 if (format_id == hash_algos[i].format_id)
252 return i;
253 return GIT_HASH_UNKNOWN;
256 int hash_algo_by_length(int len)
258 int i;
259 for (i = 1; i < GIT_HASH_NALGOS; i++)
260 if (len == hash_algos[i].rawsz)
261 return i;
262 return GIT_HASH_UNKNOWN;
266 * This is meant to hold a *small* number of objects that you would
267 * want read_object_file() to be able to return, but yet you do not want
268 * to write them into the object store (e.g. a browse-only
269 * application).
271 static struct cached_object {
272 struct object_id oid;
273 enum object_type type;
274 void *buf;
275 unsigned long size;
276 } *cached_objects;
277 static int cached_object_nr, cached_object_alloc;
279 static struct cached_object empty_tree = {
280 { EMPTY_TREE_SHA1_BIN_LITERAL },
281 OBJ_TREE,
286 static struct cached_object *find_cached_object(const struct object_id *oid)
288 int i;
289 struct cached_object *co = cached_objects;
291 for (i = 0; i < cached_object_nr; i++, co++) {
292 if (oideq(&co->oid, oid))
293 return co;
295 if (oideq(oid, the_hash_algo->empty_tree))
296 return &empty_tree;
297 return NULL;
301 static int get_conv_flags(unsigned flags)
303 if (flags & HASH_RENORMALIZE)
304 return CONV_EOL_RENORMALIZE;
305 else if (flags & HASH_WRITE_OBJECT)
306 return global_conv_flags_eol | CONV_WRITE_OBJECT;
307 else
308 return 0;
312 int mkdir_in_gitdir(const char *path)
314 if (mkdir(path, 0777)) {
315 int saved_errno = errno;
316 struct stat st;
317 struct strbuf sb = STRBUF_INIT;
319 if (errno != EEXIST)
320 return -1;
322 * Are we looking at a path in a symlinked worktree
323 * whose original repository does not yet have it?
324 * e.g. .git/rr-cache pointing at its original
325 * repository in which the user hasn't performed any
326 * conflict resolution yet?
328 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
329 strbuf_readlink(&sb, path, st.st_size) ||
330 !is_absolute_path(sb.buf) ||
331 mkdir(sb.buf, 0777)) {
332 strbuf_release(&sb);
333 errno = saved_errno;
334 return -1;
336 strbuf_release(&sb);
338 return adjust_shared_perm(path);
341 static enum scld_error safe_create_leading_directories_1(char *path, int share)
343 char *next_component = path + offset_1st_component(path);
344 enum scld_error ret = SCLD_OK;
346 while (ret == SCLD_OK && next_component) {
347 struct stat st;
348 char *slash = next_component, slash_character;
350 while (*slash && !is_dir_sep(*slash))
351 slash++;
353 if (!*slash)
354 break;
356 next_component = slash + 1;
357 while (is_dir_sep(*next_component))
358 next_component++;
359 if (!*next_component)
360 break;
362 slash_character = *slash;
363 *slash = '\0';
364 if (!stat(path, &st)) {
365 /* path exists */
366 if (!S_ISDIR(st.st_mode)) {
367 errno = ENOTDIR;
368 ret = SCLD_EXISTS;
370 } else if (mkdir(path, 0777)) {
371 if (errno == EEXIST &&
372 !stat(path, &st) && S_ISDIR(st.st_mode))
373 ; /* somebody created it since we checked */
374 else if (errno == ENOENT)
376 * Either mkdir() failed because
377 * somebody just pruned the containing
378 * directory, or stat() failed because
379 * the file that was in our way was
380 * just removed. Either way, inform
381 * the caller that it might be worth
382 * trying again:
384 ret = SCLD_VANISHED;
385 else
386 ret = SCLD_FAILED;
387 } else if (share && adjust_shared_perm(path)) {
388 ret = SCLD_PERMS;
390 *slash = slash_character;
392 return ret;
395 enum scld_error safe_create_leading_directories(char *path)
397 return safe_create_leading_directories_1(path, 1);
400 enum scld_error safe_create_leading_directories_no_share(char *path)
402 return safe_create_leading_directories_1(path, 0);
405 enum scld_error safe_create_leading_directories_const(const char *path)
407 int save_errno;
408 /* path points to cache entries, so xstrdup before messing with it */
409 char *buf = xstrdup(path);
410 enum scld_error result = safe_create_leading_directories(buf);
412 save_errno = errno;
413 free(buf);
414 errno = save_errno;
415 return result;
418 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
421 * The number of times we will try to remove empty directories
422 * in the way of path. This is only 1 because if another
423 * process is racily creating directories that conflict with
424 * us, we don't want to fight against them.
426 int remove_directories_remaining = 1;
429 * The number of times that we will try to create the
430 * directories containing path. We are willing to attempt this
431 * more than once, because another process could be trying to
432 * clean up empty directories at the same time as we are
433 * trying to create them.
435 int create_directories_remaining = 3;
437 /* A scratch copy of path, filled lazily if we need it: */
438 struct strbuf path_copy = STRBUF_INIT;
440 int ret, save_errno;
442 /* Sanity check: */
443 assert(*path);
445 retry_fn:
446 ret = fn(path, cb);
447 save_errno = errno;
448 if (!ret)
449 goto out;
451 if (errno == EISDIR && remove_directories_remaining-- > 0) {
453 * A directory is in the way. Maybe it is empty; try
454 * to remove it:
456 if (!path_copy.len)
457 strbuf_addstr(&path_copy, path);
459 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
460 goto retry_fn;
461 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
463 * Maybe the containing directory didn't exist, or
464 * maybe it was just deleted by a process that is
465 * racing with us to clean up empty directories. Try
466 * to create it:
468 enum scld_error scld_result;
470 if (!path_copy.len)
471 strbuf_addstr(&path_copy, path);
473 do {
474 scld_result = safe_create_leading_directories(path_copy.buf);
475 if (scld_result == SCLD_OK)
476 goto retry_fn;
477 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
480 out:
481 strbuf_release(&path_copy);
482 errno = save_errno;
483 return ret;
486 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
488 int i;
489 for (i = 0; i < the_hash_algo->rawsz; i++) {
490 static char hex[] = "0123456789abcdef";
491 unsigned int val = oid->hash[i];
492 strbuf_addch(buf, hex[val >> 4]);
493 strbuf_addch(buf, hex[val & 0xf]);
494 if (!i)
495 strbuf_addch(buf, '/');
499 static const char *odb_loose_path(struct object_directory *odb,
500 struct strbuf *buf,
501 const struct object_id *oid)
503 strbuf_reset(buf);
504 strbuf_addstr(buf, odb->path);
505 strbuf_addch(buf, '/');
506 fill_loose_path(buf, oid);
507 return buf->buf;
510 const char *loose_object_path(struct repository *r, struct strbuf *buf,
511 const struct object_id *oid)
513 return odb_loose_path(r->objects->odb, buf, oid);
517 * Return non-zero iff the path is usable as an alternate object database.
519 static int alt_odb_usable(struct raw_object_store *o,
520 struct strbuf *path,
521 const char *normalized_objdir, khiter_t *pos)
523 int r;
525 /* Detect cases where alternate disappeared */
526 if (!is_directory(path->buf)) {
527 error(_("object directory %s does not exist; "
528 "check .git/objects/info/alternates"),
529 path->buf);
530 return 0;
534 * Prevent the common mistake of listing the same
535 * thing twice, or object directory itself.
537 if (!o->odb_by_path) {
538 khiter_t p;
540 o->odb_by_path = kh_init_odb_path_map();
541 assert(!o->odb->next);
542 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
543 assert(r == 1); /* never used */
544 kh_value(o->odb_by_path, p) = o->odb;
546 if (fspatheq(path->buf, normalized_objdir))
547 return 0;
548 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
549 /* r: 0 = exists, 1 = never used, 2 = deleted */
550 return r == 0 ? 0 : 1;
554 * Prepare alternate object database registry.
556 * The variable alt_odb_list points at the list of struct
557 * object_directory. The elements on this list come from
558 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
559 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
560 * whose contents is similar to that environment variable but can be
561 * LF separated. Its base points at a statically allocated buffer that
562 * contains "/the/directory/corresponding/to/.git/objects/...", while
563 * its name points just after the slash at the end of ".git/objects/"
564 * in the example above, and has enough space to hold all hex characters
565 * of the object ID, an extra slash for the first level indirection, and
566 * the terminating NUL.
568 static void read_info_alternates(struct repository *r,
569 const char *relative_base,
570 int depth);
571 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
572 const char *relative_base, int depth, const char *normalized_objdir)
574 struct object_directory *ent;
575 struct strbuf pathbuf = STRBUF_INIT;
576 khiter_t pos;
578 if (!is_absolute_path(entry->buf) && relative_base) {
579 strbuf_realpath(&pathbuf, relative_base, 1);
580 strbuf_addch(&pathbuf, '/');
582 strbuf_addbuf(&pathbuf, entry);
584 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
585 error(_("unable to normalize alternate object path: %s"),
586 pathbuf.buf);
587 strbuf_release(&pathbuf);
588 return -1;
592 * The trailing slash after the directory name is given by
593 * this function at the end. Remove duplicates.
595 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
596 strbuf_setlen(&pathbuf, pathbuf.len - 1);
598 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos)) {
599 strbuf_release(&pathbuf);
600 return -1;
603 CALLOC_ARRAY(ent, 1);
604 /* pathbuf.buf is already in r->objects->odb_by_path */
605 ent->path = strbuf_detach(&pathbuf, NULL);
607 /* add the alternate entry */
608 *r->objects->odb_tail = ent;
609 r->objects->odb_tail = &(ent->next);
610 ent->next = NULL;
611 assert(r->objects->odb_by_path);
612 kh_value(r->objects->odb_by_path, pos) = ent;
614 /* recursively add alternates */
615 read_info_alternates(r, ent->path, depth + 1);
617 return 0;
620 static const char *parse_alt_odb_entry(const char *string,
621 int sep,
622 struct strbuf *out)
624 const char *end;
626 strbuf_reset(out);
628 if (*string == '#') {
629 /* comment; consume up to next separator */
630 end = strchrnul(string, sep);
631 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
633 * quoted path; unquote_c_style has copied the
634 * data for us and set "end". Broken quoting (e.g.,
635 * an entry that doesn't end with a quote) falls
636 * back to the unquoted case below.
638 } else {
639 /* normal, unquoted path */
640 end = strchrnul(string, sep);
641 strbuf_add(out, string, end - string);
644 if (*end)
645 end++;
646 return end;
649 static void link_alt_odb_entries(struct repository *r, const char *alt,
650 int sep, const char *relative_base, int depth)
652 struct strbuf objdirbuf = STRBUF_INIT;
653 struct strbuf entry = STRBUF_INIT;
655 if (!alt || !*alt)
656 return;
658 if (depth > 5) {
659 error(_("%s: ignoring alternate object stores, nesting too deep"),
660 relative_base);
661 return;
664 strbuf_add_absolute_path(&objdirbuf, r->objects->odb->path);
665 if (strbuf_normalize_path(&objdirbuf) < 0)
666 die(_("unable to normalize object directory: %s"),
667 objdirbuf.buf);
669 while (*alt) {
670 alt = parse_alt_odb_entry(alt, sep, &entry);
671 if (!entry.len)
672 continue;
673 link_alt_odb_entry(r, &entry,
674 relative_base, depth, objdirbuf.buf);
676 strbuf_release(&entry);
677 strbuf_release(&objdirbuf);
680 static void read_info_alternates(struct repository *r,
681 const char *relative_base,
682 int depth)
684 char *path;
685 struct strbuf buf = STRBUF_INIT;
687 path = xstrfmt("%s/info/alternates", relative_base);
688 if (strbuf_read_file(&buf, path, 1024) < 0) {
689 warn_on_fopen_errors(path);
690 free(path);
691 return;
694 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
695 strbuf_release(&buf);
696 free(path);
699 void add_to_alternates_file(const char *reference)
701 struct lock_file lock = LOCK_INIT;
702 char *alts = git_pathdup("objects/info/alternates");
703 FILE *in, *out;
704 int found = 0;
706 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
707 out = fdopen_lock_file(&lock, "w");
708 if (!out)
709 die_errno(_("unable to fdopen alternates lockfile"));
711 in = fopen(alts, "r");
712 if (in) {
713 struct strbuf line = STRBUF_INIT;
715 while (strbuf_getline(&line, in) != EOF) {
716 if (!strcmp(reference, line.buf)) {
717 found = 1;
718 break;
720 fprintf_or_die(out, "%s\n", line.buf);
723 strbuf_release(&line);
724 fclose(in);
726 else if (errno != ENOENT)
727 die_errno(_("unable to read alternates file"));
729 if (found) {
730 rollback_lock_file(&lock);
731 } else {
732 fprintf_or_die(out, "%s\n", reference);
733 if (commit_lock_file(&lock))
734 die_errno(_("unable to move new alternates file into place"));
735 if (the_repository->objects->loaded_alternates)
736 link_alt_odb_entries(the_repository, reference,
737 '\n', NULL, 0);
739 free(alts);
742 void add_to_alternates_memory(const char *reference)
745 * Make sure alternates are initialized, or else our entry may be
746 * overwritten when they are.
748 prepare_alt_odb(the_repository);
750 link_alt_odb_entries(the_repository, reference,
751 '\n', NULL, 0);
755 * Compute the exact path an alternate is at and returns it. In case of
756 * error NULL is returned and the human readable error is added to `err`
757 * `path` may be relative and should point to $GIT_DIR.
758 * `err` must not be null.
760 char *compute_alternate_path(const char *path, struct strbuf *err)
762 char *ref_git = NULL;
763 const char *repo;
764 int seen_error = 0;
766 ref_git = real_pathdup(path, 0);
767 if (!ref_git) {
768 seen_error = 1;
769 strbuf_addf(err, _("path '%s' does not exist"), path);
770 goto out;
773 repo = read_gitfile(ref_git);
774 if (!repo)
775 repo = read_gitfile(mkpath("%s/.git", ref_git));
776 if (repo) {
777 free(ref_git);
778 ref_git = xstrdup(repo);
781 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
782 char *ref_git_git = mkpathdup("%s/.git", ref_git);
783 free(ref_git);
784 ref_git = ref_git_git;
785 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
786 struct strbuf sb = STRBUF_INIT;
787 seen_error = 1;
788 if (get_common_dir(&sb, ref_git)) {
789 strbuf_addf(err,
790 _("reference repository '%s' as a linked "
791 "checkout is not supported yet."),
792 path);
793 goto out;
796 strbuf_addf(err, _("reference repository '%s' is not a "
797 "local repository."), path);
798 goto out;
801 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
802 strbuf_addf(err, _("reference repository '%s' is shallow"),
803 path);
804 seen_error = 1;
805 goto out;
808 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
809 strbuf_addf(err,
810 _("reference repository '%s' is grafted"),
811 path);
812 seen_error = 1;
813 goto out;
816 out:
817 if (seen_error) {
818 FREE_AND_NULL(ref_git);
821 return ref_git;
824 struct object_directory *find_odb(struct repository *r, const char *obj_dir)
826 struct object_directory *odb;
827 char *obj_dir_real = real_pathdup(obj_dir, 1);
828 struct strbuf odb_path_real = STRBUF_INIT;
830 prepare_alt_odb(r);
831 for (odb = r->objects->odb; odb; odb = odb->next) {
832 strbuf_realpath(&odb_path_real, odb->path, 1);
833 if (!strcmp(obj_dir_real, odb_path_real.buf))
834 break;
837 free(obj_dir_real);
838 strbuf_release(&odb_path_real);
840 if (!odb)
841 die(_("could not find object directory matching %s"), obj_dir);
842 return odb;
845 static void fill_alternate_refs_command(struct child_process *cmd,
846 const char *repo_path)
848 const char *value;
850 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
851 cmd->use_shell = 1;
853 strvec_push(&cmd->args, value);
854 strvec_push(&cmd->args, repo_path);
855 } else {
856 cmd->git_cmd = 1;
858 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
859 strvec_push(&cmd->args, "for-each-ref");
860 strvec_push(&cmd->args, "--format=%(objectname)");
862 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
863 strvec_push(&cmd->args, "--");
864 strvec_split(&cmd->args, value);
868 cmd->env = local_repo_env;
869 cmd->out = -1;
872 static void read_alternate_refs(const char *path,
873 alternate_ref_fn *cb,
874 void *data)
876 struct child_process cmd = CHILD_PROCESS_INIT;
877 struct strbuf line = STRBUF_INIT;
878 FILE *fh;
880 fill_alternate_refs_command(&cmd, path);
882 if (start_command(&cmd))
883 return;
885 fh = xfdopen(cmd.out, "r");
886 while (strbuf_getline_lf(&line, fh) != EOF) {
887 struct object_id oid;
888 const char *p;
890 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
891 warning(_("invalid line while parsing alternate refs: %s"),
892 line.buf);
893 break;
896 cb(&oid, data);
899 fclose(fh);
900 finish_command(&cmd);
901 strbuf_release(&line);
904 struct alternate_refs_data {
905 alternate_ref_fn *fn;
906 void *data;
909 static int refs_from_alternate_cb(struct object_directory *e,
910 void *data)
912 struct strbuf path = STRBUF_INIT;
913 size_t base_len;
914 struct alternate_refs_data *cb = data;
916 if (!strbuf_realpath(&path, e->path, 0))
917 goto out;
918 if (!strbuf_strip_suffix(&path, "/objects"))
919 goto out;
920 base_len = path.len;
922 /* Is this a git repository with refs? */
923 strbuf_addstr(&path, "/refs");
924 if (!is_directory(path.buf))
925 goto out;
926 strbuf_setlen(&path, base_len);
928 read_alternate_refs(path.buf, cb->fn, cb->data);
930 out:
931 strbuf_release(&path);
932 return 0;
935 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
937 struct alternate_refs_data cb;
938 cb.fn = fn;
939 cb.data = data;
940 foreach_alt_odb(refs_from_alternate_cb, &cb);
943 int foreach_alt_odb(alt_odb_fn fn, void *cb)
945 struct object_directory *ent;
946 int r = 0;
948 prepare_alt_odb(the_repository);
949 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
950 r = fn(ent, cb);
951 if (r)
952 break;
954 return r;
957 void prepare_alt_odb(struct repository *r)
959 if (r->objects->loaded_alternates)
960 return;
962 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
964 read_info_alternates(r, r->objects->odb->path, 0);
965 r->objects->loaded_alternates = 1;
968 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
969 static int freshen_file(const char *fn)
971 return !utime(fn, NULL);
975 * All of the check_and_freshen functions return 1 if the file exists and was
976 * freshened (if freshening was requested), 0 otherwise. If they return
977 * 0, you should not assume that it is safe to skip a write of the object (it
978 * either does not exist on disk, or has a stale mtime and may be subject to
979 * pruning).
981 int check_and_freshen_file(const char *fn, int freshen)
983 if (access(fn, F_OK))
984 return 0;
985 if (freshen && !freshen_file(fn))
986 return 0;
987 return 1;
990 static int check_and_freshen_odb(struct object_directory *odb,
991 const struct object_id *oid,
992 int freshen)
994 static struct strbuf path = STRBUF_INIT;
995 odb_loose_path(odb, &path, oid);
996 return check_and_freshen_file(path.buf, freshen);
999 static int check_and_freshen_local(const struct object_id *oid, int freshen)
1001 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
1004 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
1006 struct object_directory *odb;
1008 prepare_alt_odb(the_repository);
1009 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
1010 if (check_and_freshen_odb(odb, oid, freshen))
1011 return 1;
1013 return 0;
1016 static int check_and_freshen(const struct object_id *oid, int freshen)
1018 return check_and_freshen_local(oid, freshen) ||
1019 check_and_freshen_nonlocal(oid, freshen);
1022 int has_loose_object_nonlocal(const struct object_id *oid)
1024 return check_and_freshen_nonlocal(oid, 0);
1027 static int has_loose_object(const struct object_id *oid)
1029 return check_and_freshen(oid, 0);
1032 static void mmap_limit_check(size_t length)
1034 static size_t limit = 0;
1035 if (!limit) {
1036 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1037 if (!limit)
1038 limit = SIZE_MAX;
1040 if (length > limit)
1041 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1042 (uintmax_t)length, (uintmax_t)limit);
1045 void *xmmap_gently(void *start, size_t length,
1046 int prot, int flags, int fd, off_t offset)
1048 void *ret;
1050 mmap_limit_check(length);
1051 ret = mmap(start, length, prot, flags, fd, offset);
1052 if (ret == MAP_FAILED && !length)
1053 ret = NULL;
1054 return ret;
1057 const char *mmap_os_err(void)
1059 static const char blank[] = "";
1060 #if defined(__linux__)
1061 if (errno == ENOMEM) {
1062 /* this continues an existing error message: */
1063 static const char enomem[] =
1064 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1065 return enomem;
1067 #endif /* OS-specific bits */
1068 return blank;
1071 void *xmmap(void *start, size_t length,
1072 int prot, int flags, int fd, off_t offset)
1074 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1075 if (ret == MAP_FAILED)
1076 die_errno(_("mmap failed%s"), mmap_os_err());
1077 return ret;
1081 * With an in-core object data in "map", rehash it to make sure the
1082 * object name actually matches "oid" to detect object corruption.
1083 * With "map" == NULL, try reading the object named with "oid" using
1084 * the streaming interface and rehash it to do the same.
1086 int check_object_signature(struct repository *r, const struct object_id *oid,
1087 void *map, unsigned long size, const char *type)
1089 struct object_id real_oid;
1090 enum object_type obj_type;
1091 struct git_istream *st;
1092 git_hash_ctx c;
1093 char hdr[MAX_HEADER_LEN];
1094 int hdrlen;
1096 if (map) {
1097 hash_object_file(r->hash_algo, map, size, type, &real_oid);
1098 return !oideq(oid, &real_oid) ? -1 : 0;
1101 st = open_istream(r, oid, &obj_type, &size, NULL);
1102 if (!st)
1103 return -1;
1105 /* Generate the header */
1106 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(obj_type), (uintmax_t)size) + 1;
1108 /* Sha1.. */
1109 r->hash_algo->init_fn(&c);
1110 r->hash_algo->update_fn(&c, hdr, hdrlen);
1111 for (;;) {
1112 char buf[1024 * 16];
1113 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1115 if (readlen < 0) {
1116 close_istream(st);
1117 return -1;
1119 if (!readlen)
1120 break;
1121 r->hash_algo->update_fn(&c, buf, readlen);
1123 r->hash_algo->final_oid_fn(&real_oid, &c);
1124 close_istream(st);
1125 return !oideq(oid, &real_oid) ? -1 : 0;
1128 int git_open_cloexec(const char *name, int flags)
1130 int fd;
1131 static int o_cloexec = O_CLOEXEC;
1133 fd = open(name, flags | o_cloexec);
1134 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1135 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1136 o_cloexec &= ~O_CLOEXEC;
1137 fd = open(name, flags | o_cloexec);
1140 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1142 static int fd_cloexec = FD_CLOEXEC;
1144 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1145 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1146 int flags = fcntl(fd, F_GETFD);
1147 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1148 fd_cloexec = 0;
1151 #endif
1152 return fd;
1156 * Find "oid" as a loose object in the local repository or in an alternate.
1157 * Returns 0 on success, negative on failure.
1159 * The "path" out-parameter will give the path of the object we found (if any).
1160 * Note that it may point to static storage and is only valid until another
1161 * call to stat_loose_object().
1163 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1164 struct stat *st, const char **path)
1166 struct object_directory *odb;
1167 static struct strbuf buf = STRBUF_INIT;
1169 prepare_alt_odb(r);
1170 for (odb = r->objects->odb; odb; odb = odb->next) {
1171 *path = odb_loose_path(odb, &buf, oid);
1172 if (!lstat(*path, st))
1173 return 0;
1176 return -1;
1180 * Like stat_loose_object(), but actually open the object and return the
1181 * descriptor. See the caveats on the "path" parameter above.
1183 static int open_loose_object(struct repository *r,
1184 const struct object_id *oid, const char **path)
1186 int fd;
1187 struct object_directory *odb;
1188 int most_interesting_errno = ENOENT;
1189 static struct strbuf buf = STRBUF_INIT;
1191 prepare_alt_odb(r);
1192 for (odb = r->objects->odb; odb; odb = odb->next) {
1193 *path = odb_loose_path(odb, &buf, oid);
1194 fd = git_open(*path);
1195 if (fd >= 0)
1196 return fd;
1198 if (most_interesting_errno == ENOENT)
1199 most_interesting_errno = errno;
1201 errno = most_interesting_errno;
1202 return -1;
1205 static int quick_has_loose(struct repository *r,
1206 const struct object_id *oid)
1208 struct object_directory *odb;
1210 prepare_alt_odb(r);
1211 for (odb = r->objects->odb; odb; odb = odb->next) {
1212 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1213 return 1;
1215 return 0;
1219 * Map the loose object at "path" if it is not NULL, or the path found by
1220 * searching for a loose object named "oid".
1222 static void *map_loose_object_1(struct repository *r, const char *path,
1223 const struct object_id *oid, unsigned long *size)
1225 void *map;
1226 int fd;
1228 if (path)
1229 fd = git_open(path);
1230 else
1231 fd = open_loose_object(r, oid, &path);
1232 map = NULL;
1233 if (fd >= 0) {
1234 struct stat st;
1236 if (!fstat(fd, &st)) {
1237 *size = xsize_t(st.st_size);
1238 if (!*size) {
1239 /* mmap() is forbidden on empty files */
1240 error(_("object file %s is empty"), path);
1241 close(fd);
1242 return NULL;
1244 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1246 close(fd);
1248 return map;
1251 void *map_loose_object(struct repository *r,
1252 const struct object_id *oid,
1253 unsigned long *size)
1255 return map_loose_object_1(r, NULL, oid, size);
1258 static int unpack_loose_short_header(git_zstream *stream,
1259 unsigned char *map, unsigned long mapsize,
1260 void *buffer, unsigned long bufsiz)
1262 int ret;
1264 /* Get the data stream */
1265 memset(stream, 0, sizeof(*stream));
1266 stream->next_in = map;
1267 stream->avail_in = mapsize;
1268 stream->next_out = buffer;
1269 stream->avail_out = bufsiz;
1271 git_inflate_init(stream);
1272 obj_read_unlock();
1273 ret = git_inflate(stream, 0);
1274 obj_read_lock();
1276 return ret;
1279 int unpack_loose_header(git_zstream *stream,
1280 unsigned char *map, unsigned long mapsize,
1281 void *buffer, unsigned long bufsiz)
1283 int status = unpack_loose_short_header(stream, map, mapsize,
1284 buffer, bufsiz);
1286 if (status < Z_OK)
1287 return status;
1289 /* Make sure we have the terminating NUL */
1290 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1291 return -1;
1292 return 0;
1295 static int unpack_loose_header_to_strbuf(git_zstream *stream, unsigned char *map,
1296 unsigned long mapsize, void *buffer,
1297 unsigned long bufsiz, struct strbuf *header)
1299 int status;
1301 status = unpack_loose_short_header(stream, map, mapsize, buffer, bufsiz);
1302 if (status < Z_OK)
1303 return -1;
1306 * Check if entire header is unpacked in the first iteration.
1308 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1309 return 0;
1312 * buffer[0..bufsiz] was not large enough. Copy the partial
1313 * result out to header, and then append the result of further
1314 * reading the stream.
1316 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1317 stream->next_out = buffer;
1318 stream->avail_out = bufsiz;
1320 do {
1321 obj_read_unlock();
1322 status = git_inflate(stream, 0);
1323 obj_read_lock();
1324 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1325 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1326 return 0;
1327 stream->next_out = buffer;
1328 stream->avail_out = bufsiz;
1329 } while (status != Z_STREAM_END);
1330 return -1;
1333 static void *unpack_loose_rest(git_zstream *stream,
1334 void *buffer, unsigned long size,
1335 const struct object_id *oid)
1337 int bytes = strlen(buffer) + 1;
1338 unsigned char *buf = xmallocz(size);
1339 unsigned long n;
1340 int status = Z_OK;
1342 n = stream->total_out - bytes;
1343 if (n > size)
1344 n = size;
1345 memcpy(buf, (char *) buffer + bytes, n);
1346 bytes = n;
1347 if (bytes <= size) {
1349 * The above condition must be (bytes <= size), not
1350 * (bytes < size). In other words, even though we
1351 * expect no more output and set avail_out to zero,
1352 * the input zlib stream may have bytes that express
1353 * "this concludes the stream", and we *do* want to
1354 * eat that input.
1356 * Otherwise we would not be able to test that we
1357 * consumed all the input to reach the expected size;
1358 * we also want to check that zlib tells us that all
1359 * went well with status == Z_STREAM_END at the end.
1361 stream->next_out = buf + bytes;
1362 stream->avail_out = size - bytes;
1363 while (status == Z_OK) {
1364 obj_read_unlock();
1365 status = git_inflate(stream, Z_FINISH);
1366 obj_read_lock();
1369 if (status == Z_STREAM_END && !stream->avail_in) {
1370 git_inflate_end(stream);
1371 return buf;
1374 if (status < 0)
1375 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1376 else if (stream->avail_in)
1377 error(_("garbage at end of loose object '%s'"),
1378 oid_to_hex(oid));
1379 free(buf);
1380 return NULL;
1384 * We used to just use "sscanf()", but that's actually way
1385 * too permissive for what we want to check. So do an anal
1386 * object header parse by hand.
1388 static int parse_loose_header_extended(const char *hdr, struct object_info *oi,
1389 unsigned int flags)
1391 const char *type_buf = hdr;
1392 unsigned long size;
1393 int type, type_len = 0;
1396 * The type can be of any size but is followed by
1397 * a space.
1399 for (;;) {
1400 char c = *hdr++;
1401 if (!c)
1402 return -1;
1403 if (c == ' ')
1404 break;
1405 type_len++;
1408 type = type_from_string_gently(type_buf, type_len, 1);
1409 if (oi->type_name)
1410 strbuf_add(oi->type_name, type_buf, type_len);
1412 * Set type to 0 if its an unknown object and
1413 * we're obtaining the type using '--allow-unknown-type'
1414 * option.
1416 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1417 type = 0;
1418 else if (type < 0)
1419 die(_("invalid object type"));
1420 if (oi->typep)
1421 *oi->typep = type;
1424 * The length must follow immediately, and be in canonical
1425 * decimal format (ie "010" is not valid).
1427 size = *hdr++ - '0';
1428 if (size > 9)
1429 return -1;
1430 if (size) {
1431 for (;;) {
1432 unsigned long c = *hdr - '0';
1433 if (c > 9)
1434 break;
1435 hdr++;
1436 size = size * 10 + c;
1440 if (oi->sizep)
1441 *oi->sizep = size;
1444 * The length must be followed by a zero byte
1446 return *hdr ? -1 : type;
1449 int parse_loose_header(const char *hdr, unsigned long *sizep)
1451 struct object_info oi = OBJECT_INFO_INIT;
1453 oi.sizep = sizep;
1454 return parse_loose_header_extended(hdr, &oi, 0);
1457 static int loose_object_info(struct repository *r,
1458 const struct object_id *oid,
1459 struct object_info *oi, int flags)
1461 int status = 0;
1462 unsigned long mapsize;
1463 void *map;
1464 git_zstream stream;
1465 char hdr[MAX_HEADER_LEN];
1466 struct strbuf hdrbuf = STRBUF_INIT;
1467 unsigned long size_scratch;
1469 if (oi->delta_base_oid)
1470 oidclr(oi->delta_base_oid);
1473 * If we don't care about type or size, then we don't
1474 * need to look inside the object at all. Note that we
1475 * do not optimize out the stat call, even if the
1476 * caller doesn't care about the disk-size, since our
1477 * return value implicitly indicates whether the
1478 * object even exists.
1480 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1481 const char *path;
1482 struct stat st;
1483 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1484 return quick_has_loose(r, oid) ? 0 : -1;
1485 if (stat_loose_object(r, oid, &st, &path) < 0)
1486 return -1;
1487 if (oi->disk_sizep)
1488 *oi->disk_sizep = st.st_size;
1489 return 0;
1492 map = map_loose_object(r, oid, &mapsize);
1493 if (!map)
1494 return -1;
1496 if (!oi->sizep)
1497 oi->sizep = &size_scratch;
1499 if (oi->disk_sizep)
1500 *oi->disk_sizep = mapsize;
1501 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1502 if (unpack_loose_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1503 status = error(_("unable to unpack %s header with --allow-unknown-type"),
1504 oid_to_hex(oid));
1505 } else if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1506 status = error(_("unable to unpack %s header"),
1507 oid_to_hex(oid));
1508 if (status < 0)
1509 ; /* Do nothing */
1510 else if (hdrbuf.len) {
1511 if ((status = parse_loose_header_extended(hdrbuf.buf, oi, flags)) < 0)
1512 status = error(_("unable to parse %s header with --allow-unknown-type"),
1513 oid_to_hex(oid));
1514 } else if ((status = parse_loose_header_extended(hdr, oi, flags)) < 0)
1515 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1517 if (status >= 0 && oi->contentp) {
1518 *oi->contentp = unpack_loose_rest(&stream, hdr,
1519 *oi->sizep, oid);
1520 if (!*oi->contentp) {
1521 git_inflate_end(&stream);
1522 status = -1;
1524 } else
1525 git_inflate_end(&stream);
1527 munmap(map, mapsize);
1528 if (status && oi->typep)
1529 *oi->typep = status;
1530 if (oi->sizep == &size_scratch)
1531 oi->sizep = NULL;
1532 strbuf_release(&hdrbuf);
1533 oi->whence = OI_LOOSE;
1534 return (status < 0) ? status : 0;
1537 int obj_read_use_lock = 0;
1538 pthread_mutex_t obj_read_mutex;
1540 void enable_obj_read_lock(void)
1542 if (obj_read_use_lock)
1543 return;
1545 obj_read_use_lock = 1;
1546 init_recursive_mutex(&obj_read_mutex);
1549 void disable_obj_read_lock(void)
1551 if (!obj_read_use_lock)
1552 return;
1554 obj_read_use_lock = 0;
1555 pthread_mutex_destroy(&obj_read_mutex);
1558 int fetch_if_missing = 1;
1560 static int do_oid_object_info_extended(struct repository *r,
1561 const struct object_id *oid,
1562 struct object_info *oi, unsigned flags)
1564 static struct object_info blank_oi = OBJECT_INFO_INIT;
1565 struct cached_object *co;
1566 struct pack_entry e;
1567 int rtype;
1568 const struct object_id *real = oid;
1569 int already_retried = 0;
1572 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1573 real = lookup_replace_object(r, oid);
1575 if (is_null_oid(real))
1576 return -1;
1578 if (!oi)
1579 oi = &blank_oi;
1581 co = find_cached_object(real);
1582 if (co) {
1583 if (oi->typep)
1584 *(oi->typep) = co->type;
1585 if (oi->sizep)
1586 *(oi->sizep) = co->size;
1587 if (oi->disk_sizep)
1588 *(oi->disk_sizep) = 0;
1589 if (oi->delta_base_oid)
1590 oidclr(oi->delta_base_oid);
1591 if (oi->type_name)
1592 strbuf_addstr(oi->type_name, type_name(co->type));
1593 if (oi->contentp)
1594 *oi->contentp = xmemdupz(co->buf, co->size);
1595 oi->whence = OI_CACHED;
1596 return 0;
1599 while (1) {
1600 if (find_pack_entry(r, real, &e))
1601 break;
1603 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1604 return -1;
1606 /* Most likely it's a loose object. */
1607 if (!loose_object_info(r, real, oi, flags))
1608 return 0;
1610 /* Not a loose object; someone else may have just packed it. */
1611 if (!(flags & OBJECT_INFO_QUICK)) {
1612 reprepare_packed_git(r);
1613 if (find_pack_entry(r, real, &e))
1614 break;
1617 if (register_all_submodule_odb_as_alternates())
1618 /* We added some alternates; retry */
1619 continue;
1621 /* Check if it is a missing object */
1622 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1623 !already_retried &&
1624 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1626 * TODO Investigate checking promisor_remote_get_direct()
1627 * TODO return value and stopping on error here.
1629 promisor_remote_get_direct(r, real, 1);
1630 already_retried = 1;
1631 continue;
1634 return -1;
1637 if (oi == &blank_oi)
1639 * We know that the caller doesn't actually need the
1640 * information below, so return early.
1642 return 0;
1643 rtype = packed_object_info(r, e.p, e.offset, oi);
1644 if (rtype < 0) {
1645 mark_bad_packed_object(e.p, real->hash);
1646 return do_oid_object_info_extended(r, real, oi, 0);
1647 } else if (oi->whence == OI_PACKED) {
1648 oi->u.packed.offset = e.offset;
1649 oi->u.packed.pack = e.p;
1650 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1651 rtype == OBJ_OFS_DELTA);
1654 return 0;
1657 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1658 struct object_info *oi, unsigned flags)
1660 int ret;
1661 obj_read_lock();
1662 ret = do_oid_object_info_extended(r, oid, oi, flags);
1663 obj_read_unlock();
1664 return ret;
1668 /* returns enum object_type or negative */
1669 int oid_object_info(struct repository *r,
1670 const struct object_id *oid,
1671 unsigned long *sizep)
1673 enum object_type type;
1674 struct object_info oi = OBJECT_INFO_INIT;
1676 oi.typep = &type;
1677 oi.sizep = sizep;
1678 if (oid_object_info_extended(r, oid, &oi,
1679 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1680 return -1;
1681 return type;
1684 static void *read_object(struct repository *r,
1685 const struct object_id *oid, enum object_type *type,
1686 unsigned long *size)
1688 struct object_info oi = OBJECT_INFO_INIT;
1689 void *content;
1690 oi.typep = type;
1691 oi.sizep = size;
1692 oi.contentp = &content;
1694 if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1695 return NULL;
1696 return content;
1699 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1700 struct object_id *oid)
1702 struct cached_object *co;
1704 hash_object_file(the_hash_algo, buf, len, type_name(type), oid);
1705 if (has_object_file_with_flags(oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1706 find_cached_object(oid))
1707 return 0;
1708 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1709 co = &cached_objects[cached_object_nr++];
1710 co->size = len;
1711 co->type = type;
1712 co->buf = xmalloc(len);
1713 memcpy(co->buf, buf, len);
1714 oidcpy(&co->oid, oid);
1715 return 0;
1719 * This function dies on corrupt objects; the callers who want to
1720 * deal with them should arrange to call read_object() and give error
1721 * messages themselves.
1723 void *read_object_file_extended(struct repository *r,
1724 const struct object_id *oid,
1725 enum object_type *type,
1726 unsigned long *size,
1727 int lookup_replace)
1729 void *data;
1730 const struct packed_git *p;
1731 const char *path;
1732 struct stat st;
1733 const struct object_id *repl = lookup_replace ?
1734 lookup_replace_object(r, oid) : oid;
1736 errno = 0;
1737 data = read_object(r, repl, type, size);
1738 if (data)
1739 return data;
1741 obj_read_lock();
1742 if (errno && errno != ENOENT)
1743 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1745 /* die if we replaced an object with one that does not exist */
1746 if (repl != oid)
1747 die(_("replacement %s not found for %s"),
1748 oid_to_hex(repl), oid_to_hex(oid));
1750 if (!stat_loose_object(r, repl, &st, &path))
1751 die(_("loose object %s (stored in %s) is corrupt"),
1752 oid_to_hex(repl), path);
1754 if ((p = has_packed_and_bad(r, repl->hash)) != NULL)
1755 die(_("packed object %s (stored in %s) is corrupt"),
1756 oid_to_hex(repl), p->pack_name);
1757 obj_read_unlock();
1759 return NULL;
1762 void *read_object_with_reference(struct repository *r,
1763 const struct object_id *oid,
1764 const char *required_type_name,
1765 unsigned long *size,
1766 struct object_id *actual_oid_return)
1768 enum object_type type, required_type;
1769 void *buffer;
1770 unsigned long isize;
1771 struct object_id actual_oid;
1773 required_type = type_from_string(required_type_name);
1774 oidcpy(&actual_oid, oid);
1775 while (1) {
1776 int ref_length = -1;
1777 const char *ref_type = NULL;
1779 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1780 if (!buffer)
1781 return NULL;
1782 if (type == required_type) {
1783 *size = isize;
1784 if (actual_oid_return)
1785 oidcpy(actual_oid_return, &actual_oid);
1786 return buffer;
1788 /* Handle references */
1789 else if (type == OBJ_COMMIT)
1790 ref_type = "tree ";
1791 else if (type == OBJ_TAG)
1792 ref_type = "object ";
1793 else {
1794 free(buffer);
1795 return NULL;
1797 ref_length = strlen(ref_type);
1799 if (ref_length + the_hash_algo->hexsz > isize ||
1800 memcmp(buffer, ref_type, ref_length) ||
1801 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1802 free(buffer);
1803 return NULL;
1805 free(buffer);
1806 /* Now we have the ID of the referred-to object in
1807 * actual_oid. Check again. */
1811 static void write_object_file_prepare(const struct git_hash_algo *algo,
1812 const void *buf, unsigned long len,
1813 const char *type, struct object_id *oid,
1814 char *hdr, int *hdrlen)
1816 git_hash_ctx c;
1818 /* Generate the header */
1819 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %"PRIuMAX , type, (uintmax_t)len)+1;
1821 /* Sha1.. */
1822 algo->init_fn(&c);
1823 algo->update_fn(&c, hdr, *hdrlen);
1824 algo->update_fn(&c, buf, len);
1825 algo->final_oid_fn(oid, &c);
1829 * Move the just written object into its final resting place.
1831 int finalize_object_file(const char *tmpfile, const char *filename)
1833 int ret = 0;
1835 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1836 goto try_rename;
1837 else if (link(tmpfile, filename))
1838 ret = errno;
1841 * Coda hack - coda doesn't like cross-directory links,
1842 * so we fall back to a rename, which will mean that it
1843 * won't be able to check collisions, but that's not a
1844 * big deal.
1846 * The same holds for FAT formatted media.
1848 * When this succeeds, we just return. We have nothing
1849 * left to unlink.
1851 if (ret && ret != EEXIST) {
1852 try_rename:
1853 if (!rename(tmpfile, filename))
1854 goto out;
1855 ret = errno;
1857 unlink_or_warn(tmpfile);
1858 if (ret) {
1859 if (ret != EEXIST) {
1860 return error_errno(_("unable to write file %s"), filename);
1862 /* FIXME!!! Collision check here ? */
1865 out:
1866 if (adjust_shared_perm(filename))
1867 return error(_("unable to set permission to '%s'"), filename);
1868 return 0;
1871 static int write_buffer(int fd, const void *buf, size_t len)
1873 if (write_in_full(fd, buf, len) < 0)
1874 return error_errno(_("file write error"));
1875 return 0;
1878 int hash_object_file(const struct git_hash_algo *algo, const void *buf,
1879 unsigned long len, const char *type,
1880 struct object_id *oid)
1882 char hdr[MAX_HEADER_LEN];
1883 int hdrlen = sizeof(hdr);
1884 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
1885 return 0;
1888 /* Finalize a file on disk, and close it. */
1889 static void close_loose_object(int fd)
1891 if (fsync_object_files)
1892 fsync_or_die(fd, "loose object file");
1893 if (close(fd) != 0)
1894 die_errno(_("error when closing loose object file"));
1897 /* Size of directory component, including the ending '/' */
1898 static inline int directory_size(const char *filename)
1900 const char *s = strrchr(filename, '/');
1901 if (!s)
1902 return 0;
1903 return s - filename + 1;
1907 * This creates a temporary file in the same directory as the final
1908 * 'filename'
1910 * We want to avoid cross-directory filename renames, because those
1911 * can have problems on various filesystems (FAT, NFS, Coda).
1913 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1915 int fd, dirlen = directory_size(filename);
1917 strbuf_reset(tmp);
1918 strbuf_add(tmp, filename, dirlen);
1919 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1920 fd = git_mkstemp_mode(tmp->buf, 0444);
1921 if (fd < 0 && dirlen && errno == ENOENT) {
1923 * Make sure the directory exists; note that the contents
1924 * of the buffer are undefined after mkstemp returns an
1925 * error, so we have to rewrite the whole buffer from
1926 * scratch.
1928 strbuf_reset(tmp);
1929 strbuf_add(tmp, filename, dirlen - 1);
1930 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1931 return -1;
1932 if (adjust_shared_perm(tmp->buf))
1933 return -1;
1935 /* Try again */
1936 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1937 fd = git_mkstemp_mode(tmp->buf, 0444);
1939 return fd;
1942 static int write_loose_object(const struct object_id *oid, char *hdr,
1943 int hdrlen, const void *buf, unsigned long len,
1944 time_t mtime)
1946 int fd, ret;
1947 unsigned char compressed[4096];
1948 git_zstream stream;
1949 git_hash_ctx c;
1950 struct object_id parano_oid;
1951 static struct strbuf tmp_file = STRBUF_INIT;
1952 static struct strbuf filename = STRBUF_INIT;
1954 loose_object_path(the_repository, &filename, oid);
1956 fd = create_tmpfile(&tmp_file, filename.buf);
1957 if (fd < 0) {
1958 if (errno == EACCES)
1959 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1960 else
1961 return error_errno(_("unable to create temporary file"));
1964 /* Set it up */
1965 git_deflate_init(&stream, zlib_compression_level);
1966 stream.next_out = compressed;
1967 stream.avail_out = sizeof(compressed);
1968 the_hash_algo->init_fn(&c);
1970 /* First header.. */
1971 stream.next_in = (unsigned char *)hdr;
1972 stream.avail_in = hdrlen;
1973 while (git_deflate(&stream, 0) == Z_OK)
1974 ; /* nothing */
1975 the_hash_algo->update_fn(&c, hdr, hdrlen);
1977 /* Then the data itself.. */
1978 stream.next_in = (void *)buf;
1979 stream.avail_in = len;
1980 do {
1981 unsigned char *in0 = stream.next_in;
1982 ret = git_deflate(&stream, Z_FINISH);
1983 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1984 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1985 die(_("unable to write loose object file"));
1986 stream.next_out = compressed;
1987 stream.avail_out = sizeof(compressed);
1988 } while (ret == Z_OK);
1990 if (ret != Z_STREAM_END)
1991 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1992 ret);
1993 ret = git_deflate_end_gently(&stream);
1994 if (ret != Z_OK)
1995 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1996 ret);
1997 the_hash_algo->final_oid_fn(&parano_oid, &c);
1998 if (!oideq(oid, &parano_oid))
1999 die(_("confused by unstable object source data for %s"),
2000 oid_to_hex(oid));
2002 close_loose_object(fd);
2004 if (mtime) {
2005 struct utimbuf utb;
2006 utb.actime = mtime;
2007 utb.modtime = mtime;
2008 if (utime(tmp_file.buf, &utb) < 0)
2009 warning_errno(_("failed utime() on %s"), tmp_file.buf);
2012 return finalize_object_file(tmp_file.buf, filename.buf);
2015 static int freshen_loose_object(const struct object_id *oid)
2017 return check_and_freshen(oid, 1);
2020 static int freshen_packed_object(const struct object_id *oid)
2022 struct pack_entry e;
2023 if (!find_pack_entry(the_repository, oid, &e))
2024 return 0;
2025 if (e.p->freshened)
2026 return 1;
2027 if (!freshen_file(e.p->pack_name))
2028 return 0;
2029 e.p->freshened = 1;
2030 return 1;
2033 int write_object_file(const void *buf, unsigned long len, const char *type,
2034 struct object_id *oid)
2036 char hdr[MAX_HEADER_LEN];
2037 int hdrlen = sizeof(hdr);
2039 /* Normally if we have it in the pack then we do not bother writing
2040 * it out into .git/objects/??/?{38} file.
2042 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
2043 &hdrlen);
2044 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2045 return 0;
2046 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
2049 int hash_object_file_literally(const void *buf, unsigned long len,
2050 const char *type, struct object_id *oid,
2051 unsigned flags)
2053 char *header;
2054 int hdrlen, status = 0;
2056 /* type string, SP, %lu of the length plus NUL must fit this */
2057 hdrlen = strlen(type) + MAX_HEADER_LEN;
2058 header = xmalloc(hdrlen);
2059 write_object_file_prepare(the_hash_algo, buf, len, type, oid, header,
2060 &hdrlen);
2062 if (!(flags & HASH_WRITE_OBJECT))
2063 goto cleanup;
2064 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2065 goto cleanup;
2066 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
2068 cleanup:
2069 free(header);
2070 return status;
2073 int force_object_loose(const struct object_id *oid, time_t mtime)
2075 void *buf;
2076 unsigned long len;
2077 enum object_type type;
2078 char hdr[MAX_HEADER_LEN];
2079 int hdrlen;
2080 int ret;
2082 if (has_loose_object(oid))
2083 return 0;
2084 buf = read_object(the_repository, oid, &type, &len);
2085 if (!buf)
2086 return error(_("cannot read object for %s"), oid_to_hex(oid));
2087 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(type), (uintmax_t)len) + 1;
2088 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
2089 free(buf);
2091 return ret;
2094 int has_object(struct repository *r, const struct object_id *oid,
2095 unsigned flags)
2097 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2098 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2099 (quick ? OBJECT_INFO_QUICK : 0);
2101 if (!startup_info->have_repository)
2102 return 0;
2103 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2106 int repo_has_object_file_with_flags(struct repository *r,
2107 const struct object_id *oid, int flags)
2109 if (!startup_info->have_repository)
2110 return 0;
2111 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2114 int repo_has_object_file(struct repository *r,
2115 const struct object_id *oid)
2117 return repo_has_object_file_with_flags(r, oid, 0);
2120 static void check_tree(const void *buf, size_t size)
2122 struct tree_desc desc;
2123 struct name_entry entry;
2125 init_tree_desc(&desc, buf, size);
2126 while (tree_entry(&desc, &entry))
2127 /* do nothing
2128 * tree_entry() will die() on malformed entries */
2132 static void check_commit(const void *buf, size_t size)
2134 struct commit c;
2135 memset(&c, 0, sizeof(c));
2136 if (parse_commit_buffer(the_repository, &c, buf, size, 0))
2137 die(_("corrupt commit"));
2140 static void check_tag(const void *buf, size_t size)
2142 struct tag t;
2143 memset(&t, 0, sizeof(t));
2144 if (parse_tag_buffer(the_repository, &t, buf, size))
2145 die(_("corrupt tag"));
2148 static int index_mem(struct index_state *istate,
2149 struct object_id *oid, void *buf, size_t size,
2150 enum object_type type,
2151 const char *path, unsigned flags)
2153 int ret, re_allocated = 0;
2154 int write_object = flags & HASH_WRITE_OBJECT;
2156 if (!type)
2157 type = OBJ_BLOB;
2160 * Convert blobs to git internal format
2162 if ((type == OBJ_BLOB) && path) {
2163 struct strbuf nbuf = STRBUF_INIT;
2164 if (convert_to_git(istate, path, buf, size, &nbuf,
2165 get_conv_flags(flags))) {
2166 buf = strbuf_detach(&nbuf, &size);
2167 re_allocated = 1;
2170 if (flags & HASH_FORMAT_CHECK) {
2171 if (type == OBJ_TREE)
2172 check_tree(buf, size);
2173 if (type == OBJ_COMMIT)
2174 check_commit(buf, size);
2175 if (type == OBJ_TAG)
2176 check_tag(buf, size);
2179 if (write_object)
2180 ret = write_object_file(buf, size, type_name(type), oid);
2181 else
2182 ret = hash_object_file(the_hash_algo, buf, size,
2183 type_name(type), oid);
2184 if (re_allocated)
2185 free(buf);
2186 return ret;
2189 static int index_stream_convert_blob(struct index_state *istate,
2190 struct object_id *oid,
2191 int fd,
2192 const char *path,
2193 unsigned flags)
2195 int ret;
2196 const int write_object = flags & HASH_WRITE_OBJECT;
2197 struct strbuf sbuf = STRBUF_INIT;
2199 assert(path);
2200 assert(would_convert_to_git_filter_fd(istate, path));
2202 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2203 get_conv_flags(flags));
2205 if (write_object)
2206 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
2207 oid);
2208 else
2209 ret = hash_object_file(the_hash_algo, sbuf.buf, sbuf.len,
2210 type_name(OBJ_BLOB), oid);
2211 strbuf_release(&sbuf);
2212 return ret;
2215 static int index_pipe(struct index_state *istate, struct object_id *oid,
2216 int fd, enum object_type type,
2217 const char *path, unsigned flags)
2219 struct strbuf sbuf = STRBUF_INIT;
2220 int ret;
2222 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2223 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2224 else
2225 ret = -1;
2226 strbuf_release(&sbuf);
2227 return ret;
2230 #define SMALL_FILE_SIZE (32*1024)
2232 static int index_core(struct index_state *istate,
2233 struct object_id *oid, int fd, size_t size,
2234 enum object_type type, const char *path,
2235 unsigned flags)
2237 int ret;
2239 if (!size) {
2240 ret = index_mem(istate, oid, "", size, type, path, flags);
2241 } else if (size <= SMALL_FILE_SIZE) {
2242 char *buf = xmalloc(size);
2243 ssize_t read_result = read_in_full(fd, buf, size);
2244 if (read_result < 0)
2245 ret = error_errno(_("read error while indexing %s"),
2246 path ? path : "<unknown>");
2247 else if (read_result != size)
2248 ret = error(_("short read while indexing %s"),
2249 path ? path : "<unknown>");
2250 else
2251 ret = index_mem(istate, oid, buf, size, type, path, flags);
2252 free(buf);
2253 } else {
2254 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2255 ret = index_mem(istate, oid, buf, size, type, path, flags);
2256 munmap(buf, size);
2258 return ret;
2262 * This creates one packfile per large blob unless bulk-checkin
2263 * machinery is "plugged".
2265 * This also bypasses the usual "convert-to-git" dance, and that is on
2266 * purpose. We could write a streaming version of the converting
2267 * functions and insert that before feeding the data to fast-import
2268 * (or equivalent in-core API described above). However, that is
2269 * somewhat complicated, as we do not know the size of the filter
2270 * result, which we need to know beforehand when writing a git object.
2271 * Since the primary motivation for trying to stream from the working
2272 * tree file and to avoid mmaping it in core is to deal with large
2273 * binary blobs, they generally do not want to get any conversion, and
2274 * callers should avoid this code path when filters are requested.
2276 static int index_stream(struct object_id *oid, int fd, size_t size,
2277 enum object_type type, const char *path,
2278 unsigned flags)
2280 return index_bulk_checkin(oid, fd, size, type, path, flags);
2283 int index_fd(struct index_state *istate, struct object_id *oid,
2284 int fd, struct stat *st,
2285 enum object_type type, const char *path, unsigned flags)
2287 int ret;
2290 * Call xsize_t() only when needed to avoid potentially unnecessary
2291 * die() for large files.
2293 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2294 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2295 else if (!S_ISREG(st->st_mode))
2296 ret = index_pipe(istate, oid, fd, type, path, flags);
2297 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2298 (path && would_convert_to_git(istate, path)))
2299 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2300 type, path, flags);
2301 else
2302 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2303 flags);
2304 close(fd);
2305 return ret;
2308 int index_path(struct index_state *istate, struct object_id *oid,
2309 const char *path, struct stat *st, unsigned flags)
2311 int fd;
2312 struct strbuf sb = STRBUF_INIT;
2313 int rc = 0;
2315 switch (st->st_mode & S_IFMT) {
2316 case S_IFREG:
2317 fd = open(path, O_RDONLY);
2318 if (fd < 0)
2319 return error_errno("open(\"%s\")", path);
2320 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2321 return error(_("%s: failed to insert into database"),
2322 path);
2323 break;
2324 case S_IFLNK:
2325 if (strbuf_readlink(&sb, path, st->st_size))
2326 return error_errno("readlink(\"%s\")", path);
2327 if (!(flags & HASH_WRITE_OBJECT))
2328 hash_object_file(the_hash_algo, sb.buf, sb.len,
2329 blob_type, oid);
2330 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
2331 rc = error(_("%s: failed to insert into database"), path);
2332 strbuf_release(&sb);
2333 break;
2334 case S_IFDIR:
2335 return resolve_gitlink_ref(path, "HEAD", oid);
2336 default:
2337 return error(_("%s: unsupported file type"), path);
2339 return rc;
2342 int read_pack_header(int fd, struct pack_header *header)
2344 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2345 /* "eof before pack header was fully read" */
2346 return PH_ERROR_EOF;
2348 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2349 /* "protocol error (pack signature mismatch detected)" */
2350 return PH_ERROR_PACK_SIGNATURE;
2351 if (!pack_version_ok(header->hdr_version))
2352 /* "protocol error (pack version unsupported)" */
2353 return PH_ERROR_PROTOCOL;
2354 return 0;
2357 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2359 enum object_type type = oid_object_info(the_repository, oid, NULL);
2360 if (type < 0)
2361 die(_("%s is not a valid object"), oid_to_hex(oid));
2362 if (type != expect)
2363 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2364 type_name(expect));
2367 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2368 struct strbuf *path,
2369 each_loose_object_fn obj_cb,
2370 each_loose_cruft_fn cruft_cb,
2371 each_loose_subdir_fn subdir_cb,
2372 void *data)
2374 size_t origlen, baselen;
2375 DIR *dir;
2376 struct dirent *de;
2377 int r = 0;
2378 struct object_id oid;
2380 if (subdir_nr > 0xff)
2381 BUG("invalid loose object subdirectory: %x", subdir_nr);
2383 origlen = path->len;
2384 strbuf_complete(path, '/');
2385 strbuf_addf(path, "%02x", subdir_nr);
2387 dir = opendir(path->buf);
2388 if (!dir) {
2389 if (errno != ENOENT)
2390 r = error_errno(_("unable to open %s"), path->buf);
2391 strbuf_setlen(path, origlen);
2392 return r;
2395 oid.hash[0] = subdir_nr;
2396 strbuf_addch(path, '/');
2397 baselen = path->len;
2399 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2400 size_t namelen;
2402 namelen = strlen(de->d_name);
2403 strbuf_setlen(path, baselen);
2404 strbuf_add(path, de->d_name, namelen);
2405 if (namelen == the_hash_algo->hexsz - 2 &&
2406 !hex_to_bytes(oid.hash + 1, de->d_name,
2407 the_hash_algo->rawsz - 1)) {
2408 oid_set_algo(&oid, the_hash_algo);
2409 if (obj_cb) {
2410 r = obj_cb(&oid, path->buf, data);
2411 if (r)
2412 break;
2414 continue;
2417 if (cruft_cb) {
2418 r = cruft_cb(de->d_name, path->buf, data);
2419 if (r)
2420 break;
2423 closedir(dir);
2425 strbuf_setlen(path, baselen - 1);
2426 if (!r && subdir_cb)
2427 r = subdir_cb(subdir_nr, path->buf, data);
2429 strbuf_setlen(path, origlen);
2431 return r;
2434 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2435 each_loose_object_fn obj_cb,
2436 each_loose_cruft_fn cruft_cb,
2437 each_loose_subdir_fn subdir_cb,
2438 void *data)
2440 int r = 0;
2441 int i;
2443 for (i = 0; i < 256; i++) {
2444 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2445 subdir_cb, data);
2446 if (r)
2447 break;
2450 return r;
2453 int for_each_loose_file_in_objdir(const char *path,
2454 each_loose_object_fn obj_cb,
2455 each_loose_cruft_fn cruft_cb,
2456 each_loose_subdir_fn subdir_cb,
2457 void *data)
2459 struct strbuf buf = STRBUF_INIT;
2460 int r;
2462 strbuf_addstr(&buf, path);
2463 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2464 subdir_cb, data);
2465 strbuf_release(&buf);
2467 return r;
2470 int for_each_loose_object(each_loose_object_fn cb, void *data,
2471 enum for_each_object_flags flags)
2473 struct object_directory *odb;
2475 prepare_alt_odb(the_repository);
2476 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2477 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2478 NULL, data);
2479 if (r)
2480 return r;
2482 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2483 break;
2486 return 0;
2489 static int append_loose_object(const struct object_id *oid, const char *path,
2490 void *data)
2492 oidtree_insert(data, oid);
2493 return 0;
2496 struct oidtree *odb_loose_cache(struct object_directory *odb,
2497 const struct object_id *oid)
2499 int subdir_nr = oid->hash[0];
2500 struct strbuf buf = STRBUF_INIT;
2501 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2502 size_t word_index = subdir_nr / word_bits;
2503 size_t mask = 1u << (subdir_nr % word_bits);
2504 uint32_t *bitmap;
2506 if (subdir_nr < 0 ||
2507 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2508 BUG("subdir_nr out of range");
2510 bitmap = &odb->loose_objects_subdir_seen[word_index];
2511 if (*bitmap & mask)
2512 return odb->loose_objects_cache;
2513 if (!odb->loose_objects_cache) {
2514 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2515 oidtree_init(odb->loose_objects_cache);
2517 strbuf_addstr(&buf, odb->path);
2518 for_each_file_in_obj_subdir(subdir_nr, &buf,
2519 append_loose_object,
2520 NULL, NULL,
2521 odb->loose_objects_cache);
2522 *bitmap |= mask;
2523 strbuf_release(&buf);
2524 return odb->loose_objects_cache;
2527 void odb_clear_loose_cache(struct object_directory *odb)
2529 oidtree_clear(odb->loose_objects_cache);
2530 FREE_AND_NULL(odb->loose_objects_cache);
2531 memset(&odb->loose_objects_subdir_seen, 0,
2532 sizeof(odb->loose_objects_subdir_seen));
2535 static int check_stream_oid(git_zstream *stream,
2536 const char *hdr,
2537 unsigned long size,
2538 const char *path,
2539 const struct object_id *expected_oid)
2541 git_hash_ctx c;
2542 struct object_id real_oid;
2543 unsigned char buf[4096];
2544 unsigned long total_read;
2545 int status = Z_OK;
2547 the_hash_algo->init_fn(&c);
2548 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2551 * We already read some bytes into hdr, but the ones up to the NUL
2552 * do not count against the object's content size.
2554 total_read = stream->total_out - strlen(hdr) - 1;
2557 * This size comparison must be "<=" to read the final zlib packets;
2558 * see the comment in unpack_loose_rest for details.
2560 while (total_read <= size &&
2561 (status == Z_OK ||
2562 (status == Z_BUF_ERROR && !stream->avail_out))) {
2563 stream->next_out = buf;
2564 stream->avail_out = sizeof(buf);
2565 if (size - total_read < stream->avail_out)
2566 stream->avail_out = size - total_read;
2567 status = git_inflate(stream, Z_FINISH);
2568 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2569 total_read += stream->next_out - buf;
2571 git_inflate_end(stream);
2573 if (status != Z_STREAM_END) {
2574 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2575 return -1;
2577 if (stream->avail_in) {
2578 error(_("garbage at end of loose object '%s'"),
2579 oid_to_hex(expected_oid));
2580 return -1;
2583 the_hash_algo->final_oid_fn(&real_oid, &c);
2584 if (!oideq(expected_oid, &real_oid)) {
2585 error(_("hash mismatch for %s (expected %s)"), path,
2586 oid_to_hex(expected_oid));
2587 return -1;
2590 return 0;
2593 int read_loose_object(const char *path,
2594 const struct object_id *expected_oid,
2595 enum object_type *type,
2596 unsigned long *size,
2597 void **contents)
2599 int ret = -1;
2600 void *map = NULL;
2601 unsigned long mapsize;
2602 git_zstream stream;
2603 char hdr[MAX_HEADER_LEN];
2605 *contents = NULL;
2607 map = map_loose_object_1(the_repository, path, NULL, &mapsize);
2608 if (!map) {
2609 error_errno(_("unable to mmap %s"), path);
2610 goto out;
2613 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2614 error(_("unable to unpack header of %s"), path);
2615 goto out;
2618 *type = parse_loose_header(hdr, size);
2619 if (*type < 0) {
2620 error(_("unable to parse header of %s"), path);
2621 git_inflate_end(&stream);
2622 goto out;
2625 if (*type == OBJ_BLOB && *size > big_file_threshold) {
2626 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2627 goto out;
2628 } else {
2629 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2630 if (!*contents) {
2631 error(_("unable to unpack contents of %s"), path);
2632 git_inflate_end(&stream);
2633 goto out;
2635 if (check_object_signature(the_repository, expected_oid,
2636 *contents, *size,
2637 type_name(*type))) {
2638 error(_("hash mismatch for %s (expected %s)"), path,
2639 oid_to_hex(expected_oid));
2640 free(*contents);
2641 goto out;
2645 ret = 0; /* everything checks out */
2647 out:
2648 if (map)
2649 munmap(map, mapsize);
2650 return ret;