2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git object files - packing, unpacking,
11 #include "string-list.h"
17 #include "run-command.h"
20 #include "tree-walk.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"
30 #include "mergesort.h"
33 #include "object-store.h"
34 #include "promisor-remote.h"
36 /* The maximum size for an object header. */
37 #define MAX_HEADER_LEN 32
40 #define EMPTY_TREE_SHA1_BIN_LITERAL \
41 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
42 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
43 #define EMPTY_TREE_SHA256_BIN_LITERAL \
44 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
45 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
46 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
49 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
50 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
51 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
52 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
53 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
54 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
55 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
58 const struct object_id null_oid;
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 empty_tree_oid_sha256 = {
68 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
69 .algo = GIT_HASH_SHA256,
71 static const struct object_id empty_blob_oid_sha256 = {
72 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
73 .algo = GIT_HASH_SHA256,
76 static void git_hash_sha1_init(git_hash_ctx *ctx)
78 git_SHA1_Init(&ctx->sha1);
81 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
83 git_SHA1_Clone(&dst->sha1, &src->sha1);
86 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
88 git_SHA1_Update(&ctx->sha1, data, len);
91 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
93 git_SHA1_Final(hash, &ctx->sha1);
96 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
98 git_SHA1_Final(oid->hash, &ctx->sha1);
99 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
100 oid->algo = GIT_HASH_SHA1;
104 static void git_hash_sha256_init(git_hash_ctx *ctx)
106 git_SHA256_Init(&ctx->sha256);
109 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
111 git_SHA256_Clone(&dst->sha256, &src->sha256);
114 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
116 git_SHA256_Update(&ctx->sha256, data, len);
119 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
121 git_SHA256_Final(hash, &ctx->sha256);
124 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
126 git_SHA256_Final(oid->hash, &ctx->sha256);
128 * This currently does nothing, so the compiler should optimize it out,
129 * but keep it in case we extend the hash size again.
131 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
132 oid->algo = GIT_HASH_SHA256;
135 static void git_hash_unknown_init(git_hash_ctx *ctx)
137 BUG("trying to init unknown hash");
140 static void git_hash_unknown_clone(git_hash_ctx *dst, const git_hash_ctx *src)
142 BUG("trying to clone unknown hash");
145 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
147 BUG("trying to update unknown hash");
150 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
152 BUG("trying to finalize unknown hash");
155 static void git_hash_unknown_final_oid(struct object_id *oid, git_hash_ctx *ctx)
157 BUG("trying to finalize unknown hash");
161 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
168 git_hash_unknown_init,
169 git_hash_unknown_clone,
170 git_hash_unknown_update,
171 git_hash_unknown_final,
172 git_hash_unknown_final_oid,
178 /* "sha1", big-endian */
185 git_hash_sha1_update,
187 git_hash_sha1_final_oid,
193 /* "s256", big-endian */
198 git_hash_sha256_init,
199 git_hash_sha256_clone,
200 git_hash_sha256_update,
201 git_hash_sha256_final,
202 git_hash_sha256_final_oid,
203 &empty_tree_oid_sha256,
204 &empty_blob_oid_sha256,
208 const char *empty_tree_oid_hex(void)
210 static char buf[GIT_MAX_HEXSZ + 1];
211 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
214 const char *empty_blob_oid_hex(void)
216 static char buf[GIT_MAX_HEXSZ + 1];
217 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
220 int hash_algo_by_name(const char *name)
224 return GIT_HASH_UNKNOWN;
225 for (i = 1; i < GIT_HASH_NALGOS; i++)
226 if (!strcmp(name, hash_algos[i].name))
228 return GIT_HASH_UNKNOWN;
231 int hash_algo_by_id(uint32_t format_id)
234 for (i = 1; i < GIT_HASH_NALGOS; i++)
235 if (format_id == hash_algos[i].format_id)
237 return GIT_HASH_UNKNOWN;
240 int hash_algo_by_length(int len)
243 for (i = 1; i < GIT_HASH_NALGOS; i++)
244 if (len == hash_algos[i].rawsz)
246 return GIT_HASH_UNKNOWN;
250 * This is meant to hold a *small* number of objects that you would
251 * want read_object_file() to be able to return, but yet you do not want
252 * to write them into the object store (e.g. a browse-only
255 static struct cached_object {
256 struct object_id oid;
257 enum object_type type;
261 static int cached_object_nr, cached_object_alloc;
263 static struct cached_object empty_tree = {
264 { EMPTY_TREE_SHA1_BIN_LITERAL },
270 static struct cached_object *find_cached_object(const struct object_id *oid)
273 struct cached_object *co = cached_objects;
275 for (i = 0; i < cached_object_nr; i++, co++) {
276 if (oideq(&co->oid, oid))
279 if (oideq(oid, the_hash_algo->empty_tree))
285 static int get_conv_flags(unsigned flags)
287 if (flags & HASH_RENORMALIZE)
288 return CONV_EOL_RENORMALIZE;
289 else if (flags & HASH_WRITE_OBJECT)
290 return global_conv_flags_eol | CONV_WRITE_OBJECT;
296 int mkdir_in_gitdir(const char *path)
298 if (mkdir(path, 0777)) {
299 int saved_errno = errno;
301 struct strbuf sb = STRBUF_INIT;
306 * Are we looking at a path in a symlinked worktree
307 * whose original repository does not yet have it?
308 * e.g. .git/rr-cache pointing at its original
309 * repository in which the user hasn't performed any
310 * conflict resolution yet?
312 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
313 strbuf_readlink(&sb, path, st.st_size) ||
314 !is_absolute_path(sb.buf) ||
315 mkdir(sb.buf, 0777)) {
322 return adjust_shared_perm(path);
325 static enum scld_error safe_create_leading_directories_1(char *path, int share)
327 char *next_component = path + offset_1st_component(path);
328 enum scld_error ret = SCLD_OK;
330 while (ret == SCLD_OK && next_component) {
332 char *slash = next_component, slash_character;
334 while (*slash && !is_dir_sep(*slash))
340 next_component = slash + 1;
341 while (is_dir_sep(*next_component))
343 if (!*next_component)
346 slash_character = *slash;
348 if (!stat(path, &st)) {
350 if (!S_ISDIR(st.st_mode)) {
354 } else if (mkdir(path, 0777)) {
355 if (errno == EEXIST &&
356 !stat(path, &st) && S_ISDIR(st.st_mode))
357 ; /* somebody created it since we checked */
358 else if (errno == ENOENT)
360 * Either mkdir() failed because
361 * somebody just pruned the containing
362 * directory, or stat() failed because
363 * the file that was in our way was
364 * just removed. Either way, inform
365 * the caller that it might be worth
371 } else if (share && adjust_shared_perm(path)) {
374 *slash = slash_character;
379 enum scld_error safe_create_leading_directories(char *path)
381 return safe_create_leading_directories_1(path, 1);
384 enum scld_error safe_create_leading_directories_no_share(char *path)
386 return safe_create_leading_directories_1(path, 0);
389 enum scld_error safe_create_leading_directories_const(const char *path)
392 /* path points to cache entries, so xstrdup before messing with it */
393 char *buf = xstrdup(path);
394 enum scld_error result = safe_create_leading_directories(buf);
402 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
405 * The number of times we will try to remove empty directories
406 * in the way of path. This is only 1 because if another
407 * process is racily creating directories that conflict with
408 * us, we don't want to fight against them.
410 int remove_directories_remaining = 1;
413 * The number of times that we will try to create the
414 * directories containing path. We are willing to attempt this
415 * more than once, because another process could be trying to
416 * clean up empty directories at the same time as we are
417 * trying to create them.
419 int create_directories_remaining = 3;
421 /* A scratch copy of path, filled lazily if we need it: */
422 struct strbuf path_copy = STRBUF_INIT;
435 if (errno == EISDIR && remove_directories_remaining-- > 0) {
437 * A directory is in the way. Maybe it is empty; try
441 strbuf_addstr(&path_copy, path);
443 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
445 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
447 * Maybe the containing directory didn't exist, or
448 * maybe it was just deleted by a process that is
449 * racing with us to clean up empty directories. Try
452 enum scld_error scld_result;
455 strbuf_addstr(&path_copy, path);
458 scld_result = safe_create_leading_directories(path_copy.buf);
459 if (scld_result == SCLD_OK)
461 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
465 strbuf_release(&path_copy);
470 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
473 for (i = 0; i < the_hash_algo->rawsz; i++) {
474 static char hex[] = "0123456789abcdef";
475 unsigned int val = oid->hash[i];
476 strbuf_addch(buf, hex[val >> 4]);
477 strbuf_addch(buf, hex[val & 0xf]);
479 strbuf_addch(buf, '/');
483 static const char *odb_loose_path(struct object_directory *odb,
485 const struct object_id *oid)
488 strbuf_addstr(buf, odb->path);
489 strbuf_addch(buf, '/');
490 fill_loose_path(buf, oid);
494 const char *loose_object_path(struct repository *r, struct strbuf *buf,
495 const struct object_id *oid)
497 return odb_loose_path(r->objects->odb, buf, oid);
501 * Return non-zero iff the path is usable as an alternate object database.
503 static int alt_odb_usable(struct raw_object_store *o,
505 const char *normalized_objdir)
507 struct object_directory *odb;
509 /* Detect cases where alternate disappeared */
510 if (!is_directory(path->buf)) {
511 error(_("object directory %s does not exist; "
512 "check .git/objects/info/alternates"),
518 * Prevent the common mistake of listing the same
519 * thing twice, or object directory itself.
521 for (odb = o->odb; odb; odb = odb->next) {
522 if (!fspathcmp(path->buf, odb->path))
525 if (!fspathcmp(path->buf, normalized_objdir))
532 * Prepare alternate object database registry.
534 * The variable alt_odb_list points at the list of struct
535 * object_directory. The elements on this list come from
536 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
537 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
538 * whose contents is similar to that environment variable but can be
539 * LF separated. Its base points at a statically allocated buffer that
540 * contains "/the/directory/corresponding/to/.git/objects/...", while
541 * its name points just after the slash at the end of ".git/objects/"
542 * in the example above, and has enough space to hold all hex characters
543 * of the object ID, an extra slash for the first level indirection, and
544 * the terminating NUL.
546 static void read_info_alternates(struct repository *r,
547 const char *relative_base,
549 static int link_alt_odb_entry(struct repository *r, const char *entry,
550 const char *relative_base, int depth, const char *normalized_objdir)
552 struct object_directory *ent;
553 struct strbuf pathbuf = STRBUF_INIT;
555 if (!is_absolute_path(entry) && relative_base) {
556 strbuf_realpath(&pathbuf, relative_base, 1);
557 strbuf_addch(&pathbuf, '/');
559 strbuf_addstr(&pathbuf, entry);
561 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
562 error(_("unable to normalize alternate object path: %s"),
564 strbuf_release(&pathbuf);
569 * The trailing slash after the directory name is given by
570 * this function at the end. Remove duplicates.
572 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
573 strbuf_setlen(&pathbuf, pathbuf.len - 1);
575 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
576 strbuf_release(&pathbuf);
580 CALLOC_ARRAY(ent, 1);
581 ent->path = xstrdup(pathbuf.buf);
583 /* add the alternate entry */
584 *r->objects->odb_tail = ent;
585 r->objects->odb_tail = &(ent->next);
588 /* recursively add alternates */
589 read_info_alternates(r, pathbuf.buf, depth + 1);
591 strbuf_release(&pathbuf);
595 static const char *parse_alt_odb_entry(const char *string,
603 if (*string == '#') {
604 /* comment; consume up to next separator */
605 end = strchrnul(string, sep);
606 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
608 * quoted path; unquote_c_style has copied the
609 * data for us and set "end". Broken quoting (e.g.,
610 * an entry that doesn't end with a quote) falls
611 * back to the unquoted case below.
614 /* normal, unquoted path */
615 end = strchrnul(string, sep);
616 strbuf_add(out, string, end - string);
624 static void link_alt_odb_entries(struct repository *r, const char *alt,
625 int sep, const char *relative_base, int depth)
627 struct strbuf objdirbuf = STRBUF_INIT;
628 struct strbuf entry = STRBUF_INIT;
634 error(_("%s: ignoring alternate object stores, nesting too deep"),
639 strbuf_add_absolute_path(&objdirbuf, r->objects->odb->path);
640 if (strbuf_normalize_path(&objdirbuf) < 0)
641 die(_("unable to normalize object directory: %s"),
645 alt = parse_alt_odb_entry(alt, sep, &entry);
648 link_alt_odb_entry(r, entry.buf,
649 relative_base, depth, objdirbuf.buf);
651 strbuf_release(&entry);
652 strbuf_release(&objdirbuf);
655 static void read_info_alternates(struct repository *r,
656 const char *relative_base,
660 struct strbuf buf = STRBUF_INIT;
662 path = xstrfmt("%s/info/alternates", relative_base);
663 if (strbuf_read_file(&buf, path, 1024) < 0) {
664 warn_on_fopen_errors(path);
669 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
670 strbuf_release(&buf);
674 void add_to_alternates_file(const char *reference)
676 struct lock_file lock = LOCK_INIT;
677 char *alts = git_pathdup("objects/info/alternates");
681 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
682 out = fdopen_lock_file(&lock, "w");
684 die_errno(_("unable to fdopen alternates lockfile"));
686 in = fopen(alts, "r");
688 struct strbuf line = STRBUF_INIT;
690 while (strbuf_getline(&line, in) != EOF) {
691 if (!strcmp(reference, line.buf)) {
695 fprintf_or_die(out, "%s\n", line.buf);
698 strbuf_release(&line);
701 else if (errno != ENOENT)
702 die_errno(_("unable to read alternates file"));
705 rollback_lock_file(&lock);
707 fprintf_or_die(out, "%s\n", reference);
708 if (commit_lock_file(&lock))
709 die_errno(_("unable to move new alternates file into place"));
710 if (the_repository->objects->loaded_alternates)
711 link_alt_odb_entries(the_repository, reference,
717 void add_to_alternates_memory(const char *reference)
720 * Make sure alternates are initialized, or else our entry may be
721 * overwritten when they are.
723 prepare_alt_odb(the_repository);
725 link_alt_odb_entries(the_repository, reference,
730 * Compute the exact path an alternate is at and returns it. In case of
731 * error NULL is returned and the human readable error is added to `err`
732 * `path` may be relative and should point to $GIT_DIR.
733 * `err` must not be null.
735 char *compute_alternate_path(const char *path, struct strbuf *err)
737 char *ref_git = NULL;
741 ref_git = real_pathdup(path, 0);
744 strbuf_addf(err, _("path '%s' does not exist"), path);
748 repo = read_gitfile(ref_git);
750 repo = read_gitfile(mkpath("%s/.git", ref_git));
753 ref_git = xstrdup(repo);
756 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
757 char *ref_git_git = mkpathdup("%s/.git", ref_git);
759 ref_git = ref_git_git;
760 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
761 struct strbuf sb = STRBUF_INIT;
763 if (get_common_dir(&sb, ref_git)) {
765 _("reference repository '%s' as a linked "
766 "checkout is not supported yet."),
771 strbuf_addf(err, _("reference repository '%s' is not a "
772 "local repository."), path);
776 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
777 strbuf_addf(err, _("reference repository '%s' is shallow"),
783 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
785 _("reference repository '%s' is grafted"),
793 FREE_AND_NULL(ref_git);
799 static void fill_alternate_refs_command(struct child_process *cmd,
800 const char *repo_path)
804 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
807 strvec_push(&cmd->args, value);
808 strvec_push(&cmd->args, repo_path);
812 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
813 strvec_push(&cmd->args, "for-each-ref");
814 strvec_push(&cmd->args, "--format=%(objectname)");
816 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
817 strvec_push(&cmd->args, "--");
818 strvec_split(&cmd->args, value);
822 cmd->env = local_repo_env;
826 static void read_alternate_refs(const char *path,
827 alternate_ref_fn *cb,
830 struct child_process cmd = CHILD_PROCESS_INIT;
831 struct strbuf line = STRBUF_INIT;
834 fill_alternate_refs_command(&cmd, path);
836 if (start_command(&cmd))
839 fh = xfdopen(cmd.out, "r");
840 while (strbuf_getline_lf(&line, fh) != EOF) {
841 struct object_id oid;
844 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
845 warning(_("invalid line while parsing alternate refs: %s"),
854 finish_command(&cmd);
855 strbuf_release(&line);
858 struct alternate_refs_data {
859 alternate_ref_fn *fn;
863 static int refs_from_alternate_cb(struct object_directory *e,
866 struct strbuf path = STRBUF_INIT;
868 struct alternate_refs_data *cb = data;
870 if (!strbuf_realpath(&path, e->path, 0))
872 if (!strbuf_strip_suffix(&path, "/objects"))
876 /* Is this a git repository with refs? */
877 strbuf_addstr(&path, "/refs");
878 if (!is_directory(path.buf))
880 strbuf_setlen(&path, base_len);
882 read_alternate_refs(path.buf, cb->fn, cb->data);
885 strbuf_release(&path);
889 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
891 struct alternate_refs_data cb;
894 foreach_alt_odb(refs_from_alternate_cb, &cb);
897 int foreach_alt_odb(alt_odb_fn fn, void *cb)
899 struct object_directory *ent;
902 prepare_alt_odb(the_repository);
903 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
911 void prepare_alt_odb(struct repository *r)
913 if (r->objects->loaded_alternates)
916 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
918 read_info_alternates(r, r->objects->odb->path, 0);
919 r->objects->loaded_alternates = 1;
922 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
923 static int freshen_file(const char *fn)
925 return !utime(fn, NULL);
929 * All of the check_and_freshen functions return 1 if the file exists and was
930 * freshened (if freshening was requested), 0 otherwise. If they return
931 * 0, you should not assume that it is safe to skip a write of the object (it
932 * either does not exist on disk, or has a stale mtime and may be subject to
935 int check_and_freshen_file(const char *fn, int freshen)
937 if (access(fn, F_OK))
939 if (freshen && !freshen_file(fn))
944 static int check_and_freshen_odb(struct object_directory *odb,
945 const struct object_id *oid,
948 static struct strbuf path = STRBUF_INIT;
949 odb_loose_path(odb, &path, oid);
950 return check_and_freshen_file(path.buf, freshen);
953 static int check_and_freshen_local(const struct object_id *oid, int freshen)
955 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
958 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
960 struct object_directory *odb;
962 prepare_alt_odb(the_repository);
963 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
964 if (check_and_freshen_odb(odb, oid, freshen))
970 static int check_and_freshen(const struct object_id *oid, int freshen)
972 return check_and_freshen_local(oid, freshen) ||
973 check_and_freshen_nonlocal(oid, freshen);
976 int has_loose_object_nonlocal(const struct object_id *oid)
978 return check_and_freshen_nonlocal(oid, 0);
981 static int has_loose_object(const struct object_id *oid)
983 return check_and_freshen(oid, 0);
986 static void mmap_limit_check(size_t length)
988 static size_t limit = 0;
990 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
995 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
996 (uintmax_t)length, (uintmax_t)limit);
999 void *xmmap_gently(void *start, size_t length,
1000 int prot, int flags, int fd, off_t offset)
1004 mmap_limit_check(length);
1005 ret = mmap(start, length, prot, flags, fd, offset);
1006 if (ret == MAP_FAILED && !length)
1011 void *xmmap(void *start, size_t length,
1012 int prot, int flags, int fd, off_t offset)
1014 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1015 if (ret == MAP_FAILED)
1016 die_errno(_("mmap failed"));
1021 * With an in-core object data in "map", rehash it to make sure the
1022 * object name actually matches "oid" to detect object corruption.
1023 * With "map" == NULL, try reading the object named with "oid" using
1024 * the streaming interface and rehash it to do the same.
1026 int check_object_signature(struct repository *r, const struct object_id *oid,
1027 void *map, unsigned long size, const char *type)
1029 struct object_id real_oid;
1030 enum object_type obj_type;
1031 struct git_istream *st;
1033 char hdr[MAX_HEADER_LEN];
1037 hash_object_file(r->hash_algo, map, size, type, &real_oid);
1038 return !oideq(oid, &real_oid) ? -1 : 0;
1041 st = open_istream(r, oid, &obj_type, &size, NULL);
1045 /* Generate the header */
1046 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(obj_type), (uintmax_t)size) + 1;
1049 r->hash_algo->init_fn(&c);
1050 r->hash_algo->update_fn(&c, hdr, hdrlen);
1052 char buf[1024 * 16];
1053 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1061 r->hash_algo->update_fn(&c, buf, readlen);
1063 r->hash_algo->final_oid_fn(&real_oid, &c);
1065 return !oideq(oid, &real_oid) ? -1 : 0;
1068 int git_open_cloexec(const char *name, int flags)
1071 static int o_cloexec = O_CLOEXEC;
1073 fd = open(name, flags | o_cloexec);
1074 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1075 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1076 o_cloexec &= ~O_CLOEXEC;
1077 fd = open(name, flags | o_cloexec);
1080 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1082 static int fd_cloexec = FD_CLOEXEC;
1084 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1085 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1086 int flags = fcntl(fd, F_GETFD);
1087 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1096 * Find "oid" as a loose object in the local repository or in an alternate.
1097 * Returns 0 on success, negative on failure.
1099 * The "path" out-parameter will give the path of the object we found (if any).
1100 * Note that it may point to static storage and is only valid until another
1101 * call to stat_loose_object().
1103 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1104 struct stat *st, const char **path)
1106 struct object_directory *odb;
1107 static struct strbuf buf = STRBUF_INIT;
1110 for (odb = r->objects->odb; odb; odb = odb->next) {
1111 *path = odb_loose_path(odb, &buf, oid);
1112 if (!lstat(*path, st))
1120 * Like stat_loose_object(), but actually open the object and return the
1121 * descriptor. See the caveats on the "path" parameter above.
1123 static int open_loose_object(struct repository *r,
1124 const struct object_id *oid, const char **path)
1127 struct object_directory *odb;
1128 int most_interesting_errno = ENOENT;
1129 static struct strbuf buf = STRBUF_INIT;
1132 for (odb = r->objects->odb; odb; odb = odb->next) {
1133 *path = odb_loose_path(odb, &buf, oid);
1134 fd = git_open(*path);
1138 if (most_interesting_errno == ENOENT)
1139 most_interesting_errno = errno;
1141 errno = most_interesting_errno;
1145 static int quick_has_loose(struct repository *r,
1146 const struct object_id *oid)
1148 struct object_directory *odb;
1151 for (odb = r->objects->odb; odb; odb = odb->next) {
1152 if (oid_array_lookup(odb_loose_cache(odb, oid), oid) >= 0)
1159 * Map the loose object at "path" if it is not NULL, or the path found by
1160 * searching for a loose object named "oid".
1162 static void *map_loose_object_1(struct repository *r, const char *path,
1163 const struct object_id *oid, unsigned long *size)
1169 fd = git_open(path);
1171 fd = open_loose_object(r, oid, &path);
1176 if (!fstat(fd, &st)) {
1177 *size = xsize_t(st.st_size);
1179 /* mmap() is forbidden on empty files */
1180 error(_("object file %s is empty"), path);
1184 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1191 void *map_loose_object(struct repository *r,
1192 const struct object_id *oid,
1193 unsigned long *size)
1195 return map_loose_object_1(r, NULL, oid, size);
1198 static int unpack_loose_short_header(git_zstream *stream,
1199 unsigned char *map, unsigned long mapsize,
1200 void *buffer, unsigned long bufsiz)
1204 /* Get the data stream */
1205 memset(stream, 0, sizeof(*stream));
1206 stream->next_in = map;
1207 stream->avail_in = mapsize;
1208 stream->next_out = buffer;
1209 stream->avail_out = bufsiz;
1211 git_inflate_init(stream);
1213 ret = git_inflate(stream, 0);
1219 int unpack_loose_header(git_zstream *stream,
1220 unsigned char *map, unsigned long mapsize,
1221 void *buffer, unsigned long bufsiz)
1223 int status = unpack_loose_short_header(stream, map, mapsize,
1229 /* Make sure we have the terminating NUL */
1230 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1235 static int unpack_loose_header_to_strbuf(git_zstream *stream, unsigned char *map,
1236 unsigned long mapsize, void *buffer,
1237 unsigned long bufsiz, struct strbuf *header)
1241 status = unpack_loose_short_header(stream, map, mapsize, buffer, bufsiz);
1246 * Check if entire header is unpacked in the first iteration.
1248 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1252 * buffer[0..bufsiz] was not large enough. Copy the partial
1253 * result out to header, and then append the result of further
1254 * reading the stream.
1256 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1257 stream->next_out = buffer;
1258 stream->avail_out = bufsiz;
1262 status = git_inflate(stream, 0);
1264 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1265 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1267 stream->next_out = buffer;
1268 stream->avail_out = bufsiz;
1269 } while (status != Z_STREAM_END);
1273 static void *unpack_loose_rest(git_zstream *stream,
1274 void *buffer, unsigned long size,
1275 const struct object_id *oid)
1277 int bytes = strlen(buffer) + 1;
1278 unsigned char *buf = xmallocz(size);
1282 n = stream->total_out - bytes;
1285 memcpy(buf, (char *) buffer + bytes, n);
1287 if (bytes <= size) {
1289 * The above condition must be (bytes <= size), not
1290 * (bytes < size). In other words, even though we
1291 * expect no more output and set avail_out to zero,
1292 * the input zlib stream may have bytes that express
1293 * "this concludes the stream", and we *do* want to
1296 * Otherwise we would not be able to test that we
1297 * consumed all the input to reach the expected size;
1298 * we also want to check that zlib tells us that all
1299 * went well with status == Z_STREAM_END at the end.
1301 stream->next_out = buf + bytes;
1302 stream->avail_out = size - bytes;
1303 while (status == Z_OK) {
1305 status = git_inflate(stream, Z_FINISH);
1309 if (status == Z_STREAM_END && !stream->avail_in) {
1310 git_inflate_end(stream);
1315 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1316 else if (stream->avail_in)
1317 error(_("garbage at end of loose object '%s'"),
1324 * We used to just use "sscanf()", but that's actually way
1325 * too permissive for what we want to check. So do an anal
1326 * object header parse by hand.
1328 static int parse_loose_header_extended(const char *hdr, struct object_info *oi,
1331 const char *type_buf = hdr;
1333 int type, type_len = 0;
1336 * The type can be of any size but is followed by
1348 type = type_from_string_gently(type_buf, type_len, 1);
1350 strbuf_add(oi->type_name, type_buf, type_len);
1352 * Set type to 0 if its an unknown object and
1353 * we're obtaining the type using '--allow-unknown-type'
1356 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1359 die(_("invalid object type"));
1364 * The length must follow immediately, and be in canonical
1365 * decimal format (ie "010" is not valid).
1367 size = *hdr++ - '0';
1372 unsigned long c = *hdr - '0';
1376 size = size * 10 + c;
1384 * The length must be followed by a zero byte
1386 return *hdr ? -1 : type;
1389 int parse_loose_header(const char *hdr, unsigned long *sizep)
1391 struct object_info oi = OBJECT_INFO_INIT;
1394 return parse_loose_header_extended(hdr, &oi, 0);
1397 static int loose_object_info(struct repository *r,
1398 const struct object_id *oid,
1399 struct object_info *oi, int flags)
1402 unsigned long mapsize;
1405 char hdr[MAX_HEADER_LEN];
1406 struct strbuf hdrbuf = STRBUF_INIT;
1407 unsigned long size_scratch;
1409 if (oi->delta_base_oid)
1410 oidclr(oi->delta_base_oid);
1413 * If we don't care about type or size, then we don't
1414 * need to look inside the object at all. Note that we
1415 * do not optimize out the stat call, even if the
1416 * caller doesn't care about the disk-size, since our
1417 * return value implicitly indicates whether the
1418 * object even exists.
1420 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1423 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1424 return quick_has_loose(r, oid) ? 0 : -1;
1425 if (stat_loose_object(r, oid, &st, &path) < 0)
1428 *oi->disk_sizep = st.st_size;
1432 map = map_loose_object(r, oid, &mapsize);
1437 oi->sizep = &size_scratch;
1440 *oi->disk_sizep = mapsize;
1441 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1442 if (unpack_loose_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1443 status = error(_("unable to unpack %s header with --allow-unknown-type"),
1445 } else if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1446 status = error(_("unable to unpack %s header"),
1450 else if (hdrbuf.len) {
1451 if ((status = parse_loose_header_extended(hdrbuf.buf, oi, flags)) < 0)
1452 status = error(_("unable to parse %s header with --allow-unknown-type"),
1454 } else if ((status = parse_loose_header_extended(hdr, oi, flags)) < 0)
1455 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1457 if (status >= 0 && oi->contentp) {
1458 *oi->contentp = unpack_loose_rest(&stream, hdr,
1460 if (!*oi->contentp) {
1461 git_inflate_end(&stream);
1465 git_inflate_end(&stream);
1467 munmap(map, mapsize);
1468 if (status && oi->typep)
1469 *oi->typep = status;
1470 if (oi->sizep == &size_scratch)
1472 strbuf_release(&hdrbuf);
1473 oi->whence = OI_LOOSE;
1474 return (status < 0) ? status : 0;
1477 int obj_read_use_lock = 0;
1478 pthread_mutex_t obj_read_mutex;
1480 void enable_obj_read_lock(void)
1482 if (obj_read_use_lock)
1485 obj_read_use_lock = 1;
1486 init_recursive_mutex(&obj_read_mutex);
1489 void disable_obj_read_lock(void)
1491 if (!obj_read_use_lock)
1494 obj_read_use_lock = 0;
1495 pthread_mutex_destroy(&obj_read_mutex);
1498 int fetch_if_missing = 1;
1500 static int do_oid_object_info_extended(struct repository *r,
1501 const struct object_id *oid,
1502 struct object_info *oi, unsigned flags)
1504 static struct object_info blank_oi = OBJECT_INFO_INIT;
1505 struct cached_object *co;
1506 struct pack_entry e;
1508 const struct object_id *real = oid;
1509 int already_retried = 0;
1512 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1513 real = lookup_replace_object(r, oid);
1515 if (is_null_oid(real))
1521 co = find_cached_object(real);
1524 *(oi->typep) = co->type;
1526 *(oi->sizep) = co->size;
1528 *(oi->disk_sizep) = 0;
1529 if (oi->delta_base_oid)
1530 oidclr(oi->delta_base_oid);
1532 strbuf_addstr(oi->type_name, type_name(co->type));
1534 *oi->contentp = xmemdupz(co->buf, co->size);
1535 oi->whence = OI_CACHED;
1540 if (find_pack_entry(r, real, &e))
1543 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1546 /* Most likely it's a loose object. */
1547 if (!loose_object_info(r, real, oi, flags))
1550 /* Not a loose object; someone else may have just packed it. */
1551 if (!(flags & OBJECT_INFO_QUICK)) {
1552 reprepare_packed_git(r);
1553 if (find_pack_entry(r, real, &e))
1557 /* Check if it is a missing object */
1558 if (fetch_if_missing && has_promisor_remote() &&
1559 !already_retried && r == the_repository &&
1560 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1562 * TODO Investigate checking promisor_remote_get_direct()
1563 * TODO return value and stopping on error here.
1564 * TODO Pass a repository struct through
1565 * promisor_remote_get_direct(), such that arbitrary
1566 * repositories work.
1568 promisor_remote_get_direct(r, real, 1);
1569 already_retried = 1;
1576 if (oi == &blank_oi)
1578 * We know that the caller doesn't actually need the
1579 * information below, so return early.
1582 rtype = packed_object_info(r, e.p, e.offset, oi);
1584 mark_bad_packed_object(e.p, real->hash);
1585 return do_oid_object_info_extended(r, real, oi, 0);
1586 } else if (oi->whence == OI_PACKED) {
1587 oi->u.packed.offset = e.offset;
1588 oi->u.packed.pack = e.p;
1589 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1590 rtype == OBJ_OFS_DELTA);
1596 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1597 struct object_info *oi, unsigned flags)
1601 ret = do_oid_object_info_extended(r, oid, oi, flags);
1607 /* returns enum object_type or negative */
1608 int oid_object_info(struct repository *r,
1609 const struct object_id *oid,
1610 unsigned long *sizep)
1612 enum object_type type;
1613 struct object_info oi = OBJECT_INFO_INIT;
1617 if (oid_object_info_extended(r, oid, &oi,
1618 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1623 static void *read_object(struct repository *r,
1624 const struct object_id *oid, enum object_type *type,
1625 unsigned long *size)
1627 struct object_info oi = OBJECT_INFO_INIT;
1631 oi.contentp = &content;
1633 if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1638 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1639 struct object_id *oid)
1641 struct cached_object *co;
1643 hash_object_file(the_hash_algo, buf, len, type_name(type), oid);
1644 if (has_object_file_with_flags(oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1645 find_cached_object(oid))
1647 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1648 co = &cached_objects[cached_object_nr++];
1651 co->buf = xmalloc(len);
1652 memcpy(co->buf, buf, len);
1653 oidcpy(&co->oid, oid);
1658 * This function dies on corrupt objects; the callers who want to
1659 * deal with them should arrange to call read_object() and give error
1660 * messages themselves.
1662 void *read_object_file_extended(struct repository *r,
1663 const struct object_id *oid,
1664 enum object_type *type,
1665 unsigned long *size,
1669 const struct packed_git *p;
1672 const struct object_id *repl = lookup_replace ?
1673 lookup_replace_object(r, oid) : oid;
1676 data = read_object(r, repl, type, size);
1681 if (errno && errno != ENOENT)
1682 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1684 /* die if we replaced an object with one that does not exist */
1686 die(_("replacement %s not found for %s"),
1687 oid_to_hex(repl), oid_to_hex(oid));
1689 if (!stat_loose_object(r, repl, &st, &path))
1690 die(_("loose object %s (stored in %s) is corrupt"),
1691 oid_to_hex(repl), path);
1693 if ((p = has_packed_and_bad(r, repl->hash)) != NULL)
1694 die(_("packed object %s (stored in %s) is corrupt"),
1695 oid_to_hex(repl), p->pack_name);
1701 void *read_object_with_reference(struct repository *r,
1702 const struct object_id *oid,
1703 const char *required_type_name,
1704 unsigned long *size,
1705 struct object_id *actual_oid_return)
1707 enum object_type type, required_type;
1709 unsigned long isize;
1710 struct object_id actual_oid;
1712 required_type = type_from_string(required_type_name);
1713 oidcpy(&actual_oid, oid);
1715 int ref_length = -1;
1716 const char *ref_type = NULL;
1718 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1721 if (type == required_type) {
1723 if (actual_oid_return)
1724 oidcpy(actual_oid_return, &actual_oid);
1727 /* Handle references */
1728 else if (type == OBJ_COMMIT)
1730 else if (type == OBJ_TAG)
1731 ref_type = "object ";
1736 ref_length = strlen(ref_type);
1738 if (ref_length + the_hash_algo->hexsz > isize ||
1739 memcmp(buffer, ref_type, ref_length) ||
1740 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1745 /* Now we have the ID of the referred-to object in
1746 * actual_oid. Check again. */
1750 static void write_object_file_prepare(const struct git_hash_algo *algo,
1751 const void *buf, unsigned long len,
1752 const char *type, struct object_id *oid,
1753 char *hdr, int *hdrlen)
1757 /* Generate the header */
1758 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %"PRIuMAX , type, (uintmax_t)len)+1;
1762 algo->update_fn(&c, hdr, *hdrlen);
1763 algo->update_fn(&c, buf, len);
1764 algo->final_oid_fn(oid, &c);
1768 * Move the just written object into its final resting place.
1770 int finalize_object_file(const char *tmpfile, const char *filename)
1774 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1776 else if (link(tmpfile, filename))
1780 * Coda hack - coda doesn't like cross-directory links,
1781 * so we fall back to a rename, which will mean that it
1782 * won't be able to check collisions, but that's not a
1785 * The same holds for FAT formatted media.
1787 * When this succeeds, we just return. We have nothing
1790 if (ret && ret != EEXIST) {
1792 if (!rename(tmpfile, filename))
1796 unlink_or_warn(tmpfile);
1798 if (ret != EEXIST) {
1799 return error_errno(_("unable to write file %s"), filename);
1801 /* FIXME!!! Collision check here ? */
1805 if (adjust_shared_perm(filename))
1806 return error(_("unable to set permission to '%s'"), filename);
1810 static int write_buffer(int fd, const void *buf, size_t len)
1812 if (write_in_full(fd, buf, len) < 0)
1813 return error_errno(_("file write error"));
1817 int hash_object_file(const struct git_hash_algo *algo, const void *buf,
1818 unsigned long len, const char *type,
1819 struct object_id *oid)
1821 char hdr[MAX_HEADER_LEN];
1822 int hdrlen = sizeof(hdr);
1823 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
1827 /* Finalize a file on disk, and close it. */
1828 static void close_loose_object(int fd)
1830 if (fsync_object_files)
1831 fsync_or_die(fd, "loose object file");
1833 die_errno(_("error when closing loose object file"));
1836 /* Size of directory component, including the ending '/' */
1837 static inline int directory_size(const char *filename)
1839 const char *s = strrchr(filename, '/');
1842 return s - filename + 1;
1846 * This creates a temporary file in the same directory as the final
1849 * We want to avoid cross-directory filename renames, because those
1850 * can have problems on various filesystems (FAT, NFS, Coda).
1852 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1854 int fd, dirlen = directory_size(filename);
1857 strbuf_add(tmp, filename, dirlen);
1858 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1859 fd = git_mkstemp_mode(tmp->buf, 0444);
1860 if (fd < 0 && dirlen && errno == ENOENT) {
1862 * Make sure the directory exists; note that the contents
1863 * of the buffer are undefined after mkstemp returns an
1864 * error, so we have to rewrite the whole buffer from
1868 strbuf_add(tmp, filename, dirlen - 1);
1869 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1871 if (adjust_shared_perm(tmp->buf))
1875 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1876 fd = git_mkstemp_mode(tmp->buf, 0444);
1881 static int write_loose_object(const struct object_id *oid, char *hdr,
1882 int hdrlen, const void *buf, unsigned long len,
1886 unsigned char compressed[4096];
1889 struct object_id parano_oid;
1890 static struct strbuf tmp_file = STRBUF_INIT;
1891 static struct strbuf filename = STRBUF_INIT;
1893 loose_object_path(the_repository, &filename, oid);
1895 fd = create_tmpfile(&tmp_file, filename.buf);
1897 if (errno == EACCES)
1898 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1900 return error_errno(_("unable to create temporary file"));
1904 git_deflate_init(&stream, zlib_compression_level);
1905 stream.next_out = compressed;
1906 stream.avail_out = sizeof(compressed);
1907 the_hash_algo->init_fn(&c);
1909 /* First header.. */
1910 stream.next_in = (unsigned char *)hdr;
1911 stream.avail_in = hdrlen;
1912 while (git_deflate(&stream, 0) == Z_OK)
1914 the_hash_algo->update_fn(&c, hdr, hdrlen);
1916 /* Then the data itself.. */
1917 stream.next_in = (void *)buf;
1918 stream.avail_in = len;
1920 unsigned char *in0 = stream.next_in;
1921 ret = git_deflate(&stream, Z_FINISH);
1922 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1923 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1924 die(_("unable to write loose object file"));
1925 stream.next_out = compressed;
1926 stream.avail_out = sizeof(compressed);
1927 } while (ret == Z_OK);
1929 if (ret != Z_STREAM_END)
1930 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1932 ret = git_deflate_end_gently(&stream);
1934 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1936 the_hash_algo->final_oid_fn(¶no_oid, &c);
1937 if (!oideq(oid, ¶no_oid))
1938 die(_("confused by unstable object source data for %s"),
1941 close_loose_object(fd);
1946 utb.modtime = mtime;
1947 if (utime(tmp_file.buf, &utb) < 0)
1948 warning_errno(_("failed utime() on %s"), tmp_file.buf);
1951 return finalize_object_file(tmp_file.buf, filename.buf);
1954 static int freshen_loose_object(const struct object_id *oid)
1956 return check_and_freshen(oid, 1);
1959 static int freshen_packed_object(const struct object_id *oid)
1961 struct pack_entry e;
1962 if (!find_pack_entry(the_repository, oid, &e))
1966 if (!freshen_file(e.p->pack_name))
1972 int write_object_file(const void *buf, unsigned long len, const char *type,
1973 struct object_id *oid)
1975 char hdr[MAX_HEADER_LEN];
1976 int hdrlen = sizeof(hdr);
1978 /* Normally if we have it in the pack then we do not bother writing
1979 * it out into .git/objects/??/?{38} file.
1981 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
1983 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1985 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1988 int hash_object_file_literally(const void *buf, unsigned long len,
1989 const char *type, struct object_id *oid,
1993 int hdrlen, status = 0;
1995 /* type string, SP, %lu of the length plus NUL must fit this */
1996 hdrlen = strlen(type) + MAX_HEADER_LEN;
1997 header = xmalloc(hdrlen);
1998 write_object_file_prepare(the_hash_algo, buf, len, type, oid, header,
2001 if (!(flags & HASH_WRITE_OBJECT))
2003 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2005 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
2012 int force_object_loose(const struct object_id *oid, time_t mtime)
2016 enum object_type type;
2017 char hdr[MAX_HEADER_LEN];
2021 if (has_loose_object(oid))
2023 buf = read_object(the_repository, oid, &type, &len);
2025 return error(_("cannot read object for %s"), oid_to_hex(oid));
2026 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(type), (uintmax_t)len) + 1;
2027 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
2033 int has_object(struct repository *r, const struct object_id *oid,
2036 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2037 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2038 (quick ? OBJECT_INFO_QUICK : 0);
2040 if (!startup_info->have_repository)
2042 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2045 int repo_has_object_file_with_flags(struct repository *r,
2046 const struct object_id *oid, int flags)
2048 if (!startup_info->have_repository)
2050 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2053 int repo_has_object_file(struct repository *r,
2054 const struct object_id *oid)
2056 return repo_has_object_file_with_flags(r, oid, 0);
2059 static void check_tree(const void *buf, size_t size)
2061 struct tree_desc desc;
2062 struct name_entry entry;
2064 init_tree_desc(&desc, buf, size);
2065 while (tree_entry(&desc, &entry))
2067 * tree_entry() will die() on malformed entries */
2071 static void check_commit(const void *buf, size_t size)
2074 memset(&c, 0, sizeof(c));
2075 if (parse_commit_buffer(the_repository, &c, buf, size, 0))
2076 die(_("corrupt commit"));
2079 static void check_tag(const void *buf, size_t size)
2082 memset(&t, 0, sizeof(t));
2083 if (parse_tag_buffer(the_repository, &t, buf, size))
2084 die(_("corrupt tag"));
2087 static int index_mem(struct index_state *istate,
2088 struct object_id *oid, void *buf, size_t size,
2089 enum object_type type,
2090 const char *path, unsigned flags)
2092 int ret, re_allocated = 0;
2093 int write_object = flags & HASH_WRITE_OBJECT;
2099 * Convert blobs to git internal format
2101 if ((type == OBJ_BLOB) && path) {
2102 struct strbuf nbuf = STRBUF_INIT;
2103 if (convert_to_git(istate, path, buf, size, &nbuf,
2104 get_conv_flags(flags))) {
2105 buf = strbuf_detach(&nbuf, &size);
2109 if (flags & HASH_FORMAT_CHECK) {
2110 if (type == OBJ_TREE)
2111 check_tree(buf, size);
2112 if (type == OBJ_COMMIT)
2113 check_commit(buf, size);
2114 if (type == OBJ_TAG)
2115 check_tag(buf, size);
2119 ret = write_object_file(buf, size, type_name(type), oid);
2121 ret = hash_object_file(the_hash_algo, buf, size,
2122 type_name(type), oid);
2128 static int index_stream_convert_blob(struct index_state *istate,
2129 struct object_id *oid,
2135 const int write_object = flags & HASH_WRITE_OBJECT;
2136 struct strbuf sbuf = STRBUF_INIT;
2139 assert(would_convert_to_git_filter_fd(istate, path));
2141 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2142 get_conv_flags(flags));
2145 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
2148 ret = hash_object_file(the_hash_algo, sbuf.buf, sbuf.len,
2149 type_name(OBJ_BLOB), oid);
2150 strbuf_release(&sbuf);
2154 static int index_pipe(struct index_state *istate, struct object_id *oid,
2155 int fd, enum object_type type,
2156 const char *path, unsigned flags)
2158 struct strbuf sbuf = STRBUF_INIT;
2161 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2162 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2165 strbuf_release(&sbuf);
2169 #define SMALL_FILE_SIZE (32*1024)
2171 static int index_core(struct index_state *istate,
2172 struct object_id *oid, int fd, size_t size,
2173 enum object_type type, const char *path,
2179 ret = index_mem(istate, oid, "", size, type, path, flags);
2180 } else if (size <= SMALL_FILE_SIZE) {
2181 char *buf = xmalloc(size);
2182 ssize_t read_result = read_in_full(fd, buf, size);
2183 if (read_result < 0)
2184 ret = error_errno(_("read error while indexing %s"),
2185 path ? path : "<unknown>");
2186 else if (read_result != size)
2187 ret = error(_("short read while indexing %s"),
2188 path ? path : "<unknown>");
2190 ret = index_mem(istate, oid, buf, size, type, path, flags);
2193 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2194 ret = index_mem(istate, oid, buf, size, type, path, flags);
2201 * This creates one packfile per large blob unless bulk-checkin
2202 * machinery is "plugged".
2204 * This also bypasses the usual "convert-to-git" dance, and that is on
2205 * purpose. We could write a streaming version of the converting
2206 * functions and insert that before feeding the data to fast-import
2207 * (or equivalent in-core API described above). However, that is
2208 * somewhat complicated, as we do not know the size of the filter
2209 * result, which we need to know beforehand when writing a git object.
2210 * Since the primary motivation for trying to stream from the working
2211 * tree file and to avoid mmaping it in core is to deal with large
2212 * binary blobs, they generally do not want to get any conversion, and
2213 * callers should avoid this code path when filters are requested.
2215 static int index_stream(struct object_id *oid, int fd, size_t size,
2216 enum object_type type, const char *path,
2219 return index_bulk_checkin(oid, fd, size, type, path, flags);
2222 int index_fd(struct index_state *istate, struct object_id *oid,
2223 int fd, struct stat *st,
2224 enum object_type type, const char *path, unsigned flags)
2229 * Call xsize_t() only when needed to avoid potentially unnecessary
2230 * die() for large files.
2232 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2233 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2234 else if (!S_ISREG(st->st_mode))
2235 ret = index_pipe(istate, oid, fd, type, path, flags);
2236 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2237 (path && would_convert_to_git(istate, path)))
2238 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2241 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2247 int index_path(struct index_state *istate, struct object_id *oid,
2248 const char *path, struct stat *st, unsigned flags)
2251 struct strbuf sb = STRBUF_INIT;
2254 switch (st->st_mode & S_IFMT) {
2256 fd = open(path, O_RDONLY);
2258 return error_errno("open(\"%s\")", path);
2259 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2260 return error(_("%s: failed to insert into database"),
2264 if (strbuf_readlink(&sb, path, st->st_size))
2265 return error_errno("readlink(\"%s\")", path);
2266 if (!(flags & HASH_WRITE_OBJECT))
2267 hash_object_file(the_hash_algo, sb.buf, sb.len,
2269 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
2270 rc = error(_("%s: failed to insert into database"), path);
2271 strbuf_release(&sb);
2274 return resolve_gitlink_ref(path, "HEAD", oid);
2276 return error(_("%s: unsupported file type"), path);
2281 int read_pack_header(int fd, struct pack_header *header)
2283 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2284 /* "eof before pack header was fully read" */
2285 return PH_ERROR_EOF;
2287 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2288 /* "protocol error (pack signature mismatch detected)" */
2289 return PH_ERROR_PACK_SIGNATURE;
2290 if (!pack_version_ok(header->hdr_version))
2291 /* "protocol error (pack version unsupported)" */
2292 return PH_ERROR_PROTOCOL;
2296 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2298 enum object_type type = oid_object_info(the_repository, oid, NULL);
2300 die(_("%s is not a valid object"), oid_to_hex(oid));
2302 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2306 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2307 struct strbuf *path,
2308 each_loose_object_fn obj_cb,
2309 each_loose_cruft_fn cruft_cb,
2310 each_loose_subdir_fn subdir_cb,
2313 size_t origlen, baselen;
2317 struct object_id oid;
2319 if (subdir_nr > 0xff)
2320 BUG("invalid loose object subdirectory: %x", subdir_nr);
2322 origlen = path->len;
2323 strbuf_complete(path, '/');
2324 strbuf_addf(path, "%02x", subdir_nr);
2326 dir = opendir(path->buf);
2328 if (errno != ENOENT)
2329 r = error_errno(_("unable to open %s"), path->buf);
2330 strbuf_setlen(path, origlen);
2334 oid.hash[0] = subdir_nr;
2335 strbuf_addch(path, '/');
2336 baselen = path->len;
2338 while ((de = readdir(dir))) {
2340 if (is_dot_or_dotdot(de->d_name))
2343 namelen = strlen(de->d_name);
2344 strbuf_setlen(path, baselen);
2345 strbuf_add(path, de->d_name, namelen);
2346 if (namelen == the_hash_algo->hexsz - 2 &&
2347 !hex_to_bytes(oid.hash + 1, de->d_name,
2348 the_hash_algo->rawsz - 1)) {
2349 oid_set_algo(&oid, the_hash_algo);
2351 r = obj_cb(&oid, path->buf, data);
2359 r = cruft_cb(de->d_name, path->buf, data);
2366 strbuf_setlen(path, baselen - 1);
2367 if (!r && subdir_cb)
2368 r = subdir_cb(subdir_nr, path->buf, data);
2370 strbuf_setlen(path, origlen);
2375 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2376 each_loose_object_fn obj_cb,
2377 each_loose_cruft_fn cruft_cb,
2378 each_loose_subdir_fn subdir_cb,
2384 for (i = 0; i < 256; i++) {
2385 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2394 int for_each_loose_file_in_objdir(const char *path,
2395 each_loose_object_fn obj_cb,
2396 each_loose_cruft_fn cruft_cb,
2397 each_loose_subdir_fn subdir_cb,
2400 struct strbuf buf = STRBUF_INIT;
2403 strbuf_addstr(&buf, path);
2404 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2406 strbuf_release(&buf);
2411 int for_each_loose_object(each_loose_object_fn cb, void *data,
2412 enum for_each_object_flags flags)
2414 struct object_directory *odb;
2416 prepare_alt_odb(the_repository);
2417 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2418 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2423 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2430 static int append_loose_object(const struct object_id *oid, const char *path,
2433 oid_array_append(data, oid);
2437 struct oid_array *odb_loose_cache(struct object_directory *odb,
2438 const struct object_id *oid)
2440 int subdir_nr = oid->hash[0];
2441 struct strbuf buf = STRBUF_INIT;
2443 if (subdir_nr < 0 ||
2444 subdir_nr >= ARRAY_SIZE(odb->loose_objects_subdir_seen))
2445 BUG("subdir_nr out of range");
2447 if (odb->loose_objects_subdir_seen[subdir_nr])
2448 return &odb->loose_objects_cache[subdir_nr];
2450 strbuf_addstr(&buf, odb->path);
2451 for_each_file_in_obj_subdir(subdir_nr, &buf,
2452 append_loose_object,
2454 &odb->loose_objects_cache[subdir_nr]);
2455 odb->loose_objects_subdir_seen[subdir_nr] = 1;
2456 strbuf_release(&buf);
2457 return &odb->loose_objects_cache[subdir_nr];
2460 void odb_clear_loose_cache(struct object_directory *odb)
2464 for (i = 0; i < ARRAY_SIZE(odb->loose_objects_cache); i++)
2465 oid_array_clear(&odb->loose_objects_cache[i]);
2466 memset(&odb->loose_objects_subdir_seen, 0,
2467 sizeof(odb->loose_objects_subdir_seen));
2470 static int check_stream_oid(git_zstream *stream,
2474 const struct object_id *expected_oid)
2477 struct object_id real_oid;
2478 unsigned char buf[4096];
2479 unsigned long total_read;
2482 the_hash_algo->init_fn(&c);
2483 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2486 * We already read some bytes into hdr, but the ones up to the NUL
2487 * do not count against the object's content size.
2489 total_read = stream->total_out - strlen(hdr) - 1;
2492 * This size comparison must be "<=" to read the final zlib packets;
2493 * see the comment in unpack_loose_rest for details.
2495 while (total_read <= size &&
2497 (status == Z_BUF_ERROR && !stream->avail_out))) {
2498 stream->next_out = buf;
2499 stream->avail_out = sizeof(buf);
2500 if (size - total_read < stream->avail_out)
2501 stream->avail_out = size - total_read;
2502 status = git_inflate(stream, Z_FINISH);
2503 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2504 total_read += stream->next_out - buf;
2506 git_inflate_end(stream);
2508 if (status != Z_STREAM_END) {
2509 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2512 if (stream->avail_in) {
2513 error(_("garbage at end of loose object '%s'"),
2514 oid_to_hex(expected_oid));
2518 the_hash_algo->final_oid_fn(&real_oid, &c);
2519 if (!oideq(expected_oid, &real_oid)) {
2520 error(_("hash mismatch for %s (expected %s)"), path,
2521 oid_to_hex(expected_oid));
2528 int read_loose_object(const char *path,
2529 const struct object_id *expected_oid,
2530 enum object_type *type,
2531 unsigned long *size,
2536 unsigned long mapsize;
2538 char hdr[MAX_HEADER_LEN];
2542 map = map_loose_object_1(the_repository, path, NULL, &mapsize);
2544 error_errno(_("unable to mmap %s"), path);
2548 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2549 error(_("unable to unpack header of %s"), path);
2553 *type = parse_loose_header(hdr, size);
2555 error(_("unable to parse header of %s"), path);
2556 git_inflate_end(&stream);
2560 if (*type == OBJ_BLOB && *size > big_file_threshold) {
2561 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2564 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2566 error(_("unable to unpack contents of %s"), path);
2567 git_inflate_end(&stream);
2570 if (check_object_signature(the_repository, expected_oid,
2572 type_name(*type))) {
2573 error(_("hash mismatch for %s (expected %s)"), path,
2574 oid_to_hex(expected_oid));
2580 ret = 0; /* everything checks out */
2584 munmap(map, mapsize);