2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 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 "sha1-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 "fetch-object.h"
34 #include "object-store.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"
44 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
45 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
46 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
48 const unsigned char null_sha1[GIT_MAX_RAWSZ];
49 const struct object_id null_oid;
50 static const struct object_id empty_tree_oid = {
51 EMPTY_TREE_SHA1_BIN_LITERAL
53 static const struct object_id empty_blob_oid = {
54 EMPTY_BLOB_SHA1_BIN_LITERAL
57 static void git_hash_sha1_init(git_hash_ctx *ctx)
59 git_SHA1_Init(&ctx->sha1);
62 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
64 git_SHA1_Update(&ctx->sha1, data, len);
67 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
69 git_SHA1_Final(hash, &ctx->sha1);
72 static void git_hash_unknown_init(git_hash_ctx *ctx)
74 BUG("trying to init unknown hash");
77 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
79 BUG("trying to update unknown hash");
82 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
84 BUG("trying to finalize unknown hash");
87 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
93 git_hash_unknown_init,
94 git_hash_unknown_update,
95 git_hash_unknown_final,
101 /* "sha1", big-endian */
106 git_hash_sha1_update,
113 const char *empty_tree_oid_hex(void)
115 static char buf[GIT_MAX_HEXSZ + 1];
116 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
119 const char *empty_blob_oid_hex(void)
121 static char buf[GIT_MAX_HEXSZ + 1];
122 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
126 * This is meant to hold a *small* number of objects that you would
127 * want read_sha1_file() to be able to return, but yet you do not want
128 * to write them into the object store (e.g. a browse-only
131 static struct cached_object {
132 struct object_id oid;
133 enum object_type type;
137 static int cached_object_nr, cached_object_alloc;
139 static struct cached_object empty_tree = {
140 { EMPTY_TREE_SHA1_BIN_LITERAL },
146 static struct cached_object *find_cached_object(const struct object_id *oid)
149 struct cached_object *co = cached_objects;
151 for (i = 0; i < cached_object_nr; i++, co++) {
152 if (oideq(&co->oid, oid))
155 if (oideq(oid, the_hash_algo->empty_tree))
161 static int get_conv_flags(unsigned flags)
163 if (flags & HASH_RENORMALIZE)
164 return CONV_EOL_RENORMALIZE;
165 else if (flags & HASH_WRITE_OBJECT)
166 return global_conv_flags_eol | CONV_WRITE_OBJECT;
172 int mkdir_in_gitdir(const char *path)
174 if (mkdir(path, 0777)) {
175 int saved_errno = errno;
177 struct strbuf sb = STRBUF_INIT;
182 * Are we looking at a path in a symlinked worktree
183 * whose original repository does not yet have it?
184 * e.g. .git/rr-cache pointing at its original
185 * repository in which the user hasn't performed any
186 * conflict resolution yet?
188 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
189 strbuf_readlink(&sb, path, st.st_size) ||
190 !is_absolute_path(sb.buf) ||
191 mkdir(sb.buf, 0777)) {
198 return adjust_shared_perm(path);
201 enum scld_error safe_create_leading_directories(char *path)
203 char *next_component = path + offset_1st_component(path);
204 enum scld_error ret = SCLD_OK;
206 while (ret == SCLD_OK && next_component) {
208 char *slash = next_component, slash_character;
210 while (*slash && !is_dir_sep(*slash))
216 next_component = slash + 1;
217 while (is_dir_sep(*next_component))
219 if (!*next_component)
222 slash_character = *slash;
224 if (!stat(path, &st)) {
226 if (!S_ISDIR(st.st_mode)) {
230 } else if (mkdir(path, 0777)) {
231 if (errno == EEXIST &&
232 !stat(path, &st) && S_ISDIR(st.st_mode))
233 ; /* somebody created it since we checked */
234 else if (errno == ENOENT)
236 * Either mkdir() failed because
237 * somebody just pruned the containing
238 * directory, or stat() failed because
239 * the file that was in our way was
240 * just removed. Either way, inform
241 * the caller that it might be worth
247 } else if (adjust_shared_perm(path)) {
250 *slash = slash_character;
255 enum scld_error safe_create_leading_directories_const(const char *path)
258 /* path points to cache entries, so xstrdup before messing with it */
259 char *buf = xstrdup(path);
260 enum scld_error result = safe_create_leading_directories(buf);
268 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
271 * The number of times we will try to remove empty directories
272 * in the way of path. This is only 1 because if another
273 * process is racily creating directories that conflict with
274 * us, we don't want to fight against them.
276 int remove_directories_remaining = 1;
279 * The number of times that we will try to create the
280 * directories containing path. We are willing to attempt this
281 * more than once, because another process could be trying to
282 * clean up empty directories at the same time as we are
283 * trying to create them.
285 int create_directories_remaining = 3;
287 /* A scratch copy of path, filled lazily if we need it: */
288 struct strbuf path_copy = STRBUF_INIT;
301 if (errno == EISDIR && remove_directories_remaining-- > 0) {
303 * A directory is in the way. Maybe it is empty; try
307 strbuf_addstr(&path_copy, path);
309 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
311 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
313 * Maybe the containing directory didn't exist, or
314 * maybe it was just deleted by a process that is
315 * racing with us to clean up empty directories. Try
318 enum scld_error scld_result;
321 strbuf_addstr(&path_copy, path);
324 scld_result = safe_create_leading_directories(path_copy.buf);
325 if (scld_result == SCLD_OK)
327 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
331 strbuf_release(&path_copy);
336 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
339 for (i = 0; i < the_hash_algo->rawsz; i++) {
340 static char hex[] = "0123456789abcdef";
341 unsigned int val = sha1[i];
342 strbuf_addch(buf, hex[val >> 4]);
343 strbuf_addch(buf, hex[val & 0xf]);
345 strbuf_addch(buf, '/');
349 static const char *odb_loose_path(const char *path, struct strbuf *buf,
350 const unsigned char *sha1)
353 strbuf_addstr(buf, path);
354 strbuf_addch(buf, '/');
355 fill_sha1_path(buf, sha1);
359 const char *loose_object_path(struct repository *r, struct strbuf *buf,
360 const unsigned char *sha1)
362 return odb_loose_path(r->objects->objectdir, buf, sha1);
366 * Return non-zero iff the path is usable as an alternate object database.
368 static int alt_odb_usable(struct raw_object_store *o,
370 const char *normalized_objdir)
372 struct object_directory *odb;
374 /* Detect cases where alternate disappeared */
375 if (!is_directory(path->buf)) {
376 error(_("object directory %s does not exist; "
377 "check .git/objects/info/alternates"),
383 * Prevent the common mistake of listing the same
384 * thing twice, or object directory itself.
386 for (odb = o->alt_odb_list; odb; odb = odb->next) {
387 if (!fspathcmp(path->buf, odb->path))
390 if (!fspathcmp(path->buf, normalized_objdir))
397 * Prepare alternate object database registry.
399 * The variable alt_odb_list points at the list of struct
400 * object_directory. The elements on this list come from
401 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
402 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
403 * whose contents is similar to that environment variable but can be
404 * LF separated. Its base points at a statically allocated buffer that
405 * contains "/the/directory/corresponding/to/.git/objects/...", while
406 * its name points just after the slash at the end of ".git/objects/"
407 * in the example above, and has enough space to hold 40-byte hex
408 * SHA1, an extra slash for the first level indirection, and the
411 static void read_info_alternates(struct repository *r,
412 const char *relative_base,
414 static int link_alt_odb_entry(struct repository *r, const char *entry,
415 const char *relative_base, int depth, const char *normalized_objdir)
417 struct object_directory *ent;
418 struct strbuf pathbuf = STRBUF_INIT;
420 if (!is_absolute_path(entry) && relative_base) {
421 strbuf_realpath(&pathbuf, relative_base, 1);
422 strbuf_addch(&pathbuf, '/');
424 strbuf_addstr(&pathbuf, entry);
426 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
427 error(_("unable to normalize alternate object path: %s"),
429 strbuf_release(&pathbuf);
434 * The trailing slash after the directory name is given by
435 * this function at the end. Remove duplicates.
437 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
438 strbuf_setlen(&pathbuf, pathbuf.len - 1);
440 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
441 strbuf_release(&pathbuf);
445 ent = alloc_alt_odb(pathbuf.buf);
447 /* add the alternate entry */
448 *r->objects->alt_odb_tail = ent;
449 r->objects->alt_odb_tail = &(ent->next);
452 /* recursively add alternates */
453 read_info_alternates(r, pathbuf.buf, depth + 1);
455 strbuf_release(&pathbuf);
459 static const char *parse_alt_odb_entry(const char *string,
467 if (*string == '#') {
468 /* comment; consume up to next separator */
469 end = strchrnul(string, sep);
470 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
472 * quoted path; unquote_c_style has copied the
473 * data for us and set "end". Broken quoting (e.g.,
474 * an entry that doesn't end with a quote) falls
475 * back to the unquoted case below.
478 /* normal, unquoted path */
479 end = strchrnul(string, sep);
480 strbuf_add(out, string, end - string);
488 static void link_alt_odb_entries(struct repository *r, const char *alt,
489 int sep, const char *relative_base, int depth)
491 struct strbuf objdirbuf = STRBUF_INIT;
492 struct strbuf entry = STRBUF_INIT;
498 error(_("%s: ignoring alternate object stores, nesting too deep"),
503 strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
504 if (strbuf_normalize_path(&objdirbuf) < 0)
505 die(_("unable to normalize object directory: %s"),
509 alt = parse_alt_odb_entry(alt, sep, &entry);
512 link_alt_odb_entry(r, entry.buf,
513 relative_base, depth, objdirbuf.buf);
515 strbuf_release(&entry);
516 strbuf_release(&objdirbuf);
519 static void read_info_alternates(struct repository *r,
520 const char *relative_base,
524 struct strbuf buf = STRBUF_INIT;
526 path = xstrfmt("%s/info/alternates", relative_base);
527 if (strbuf_read_file(&buf, path, 1024) < 0) {
528 warn_on_fopen_errors(path);
533 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
534 strbuf_release(&buf);
538 struct object_directory *alloc_alt_odb(const char *dir)
540 struct object_directory *ent;
542 FLEX_ALLOC_STR(ent, path, dir);
547 void add_to_alternates_file(const char *reference)
549 struct lock_file lock = LOCK_INIT;
550 char *alts = git_pathdup("objects/info/alternates");
554 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
555 out = fdopen_lock_file(&lock, "w");
557 die_errno(_("unable to fdopen alternates lockfile"));
559 in = fopen(alts, "r");
561 struct strbuf line = STRBUF_INIT;
563 while (strbuf_getline(&line, in) != EOF) {
564 if (!strcmp(reference, line.buf)) {
568 fprintf_or_die(out, "%s\n", line.buf);
571 strbuf_release(&line);
574 else if (errno != ENOENT)
575 die_errno(_("unable to read alternates file"));
578 rollback_lock_file(&lock);
580 fprintf_or_die(out, "%s\n", reference);
581 if (commit_lock_file(&lock))
582 die_errno(_("unable to move new alternates file into place"));
583 if (the_repository->objects->alt_odb_tail)
584 link_alt_odb_entries(the_repository, reference,
590 void add_to_alternates_memory(const char *reference)
593 * Make sure alternates are initialized, or else our entry may be
594 * overwritten when they are.
596 prepare_alt_odb(the_repository);
598 link_alt_odb_entries(the_repository, reference,
603 * Compute the exact path an alternate is at and returns it. In case of
604 * error NULL is returned and the human readable error is added to `err`
605 * `path` may be relative and should point to $GIT_DIR.
606 * `err` must not be null.
608 char *compute_alternate_path(const char *path, struct strbuf *err)
610 char *ref_git = NULL;
611 const char *repo, *ref_git_s;
614 ref_git_s = real_path_if_valid(path);
617 strbuf_addf(err, _("path '%s' does not exist"), path);
621 * Beware: read_gitfile(), real_path() and mkpath()
622 * return static buffer
624 ref_git = xstrdup(ref_git_s);
626 repo = read_gitfile(ref_git);
628 repo = read_gitfile(mkpath("%s/.git", ref_git));
631 ref_git = xstrdup(repo);
634 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
635 char *ref_git_git = mkpathdup("%s/.git", ref_git);
637 ref_git = ref_git_git;
638 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
639 struct strbuf sb = STRBUF_INIT;
641 if (get_common_dir(&sb, ref_git)) {
643 _("reference repository '%s' as a linked "
644 "checkout is not supported yet."),
649 strbuf_addf(err, _("reference repository '%s' is not a "
650 "local repository."), path);
654 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
655 strbuf_addf(err, _("reference repository '%s' is shallow"),
661 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
663 _("reference repository '%s' is grafted"),
671 FREE_AND_NULL(ref_git);
677 int foreach_alt_odb(alt_odb_fn fn, void *cb)
679 struct object_directory *ent;
682 prepare_alt_odb(the_repository);
683 for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
691 void prepare_alt_odb(struct repository *r)
693 if (r->objects->alt_odb_tail)
696 r->objects->alt_odb_tail = &r->objects->alt_odb_list;
697 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
699 read_info_alternates(r, r->objects->objectdir, 0);
702 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
703 static int freshen_file(const char *fn)
706 t.actime = t.modtime = time(NULL);
707 return !utime(fn, &t);
711 * All of the check_and_freshen functions return 1 if the file exists and was
712 * freshened (if freshening was requested), 0 otherwise. If they return
713 * 0, you should not assume that it is safe to skip a write of the object (it
714 * either does not exist on disk, or has a stale mtime and may be subject to
717 int check_and_freshen_file(const char *fn, int freshen)
719 if (access(fn, F_OK))
721 if (freshen && !freshen_file(fn))
726 static int check_and_freshen_local(const struct object_id *oid, int freshen)
728 static struct strbuf buf = STRBUF_INIT;
730 loose_object_path(the_repository, &buf, oid->hash);
732 return check_and_freshen_file(buf.buf, freshen);
735 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
737 struct object_directory *odb;
738 static struct strbuf path = STRBUF_INIT;
740 prepare_alt_odb(the_repository);
741 for (odb = the_repository->objects->alt_odb_list; odb; odb = odb->next) {
742 odb_loose_path(odb->path, &path, oid->hash);
743 if (check_and_freshen_file(path.buf, freshen))
749 static int check_and_freshen(const struct object_id *oid, int freshen)
751 return check_and_freshen_local(oid, freshen) ||
752 check_and_freshen_nonlocal(oid, freshen);
755 int has_loose_object_nonlocal(const struct object_id *oid)
757 return check_and_freshen_nonlocal(oid, 0);
760 static int has_loose_object(const struct object_id *oid)
762 return check_and_freshen(oid, 0);
765 static void mmap_limit_check(size_t length)
767 static size_t limit = 0;
769 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
774 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
775 (uintmax_t)length, (uintmax_t)limit);
778 void *xmmap_gently(void *start, size_t length,
779 int prot, int flags, int fd, off_t offset)
783 mmap_limit_check(length);
784 ret = mmap(start, length, prot, flags, fd, offset);
785 if (ret == MAP_FAILED) {
788 release_pack_memory(length);
789 ret = mmap(start, length, prot, flags, fd, offset);
794 void *xmmap(void *start, size_t length,
795 int prot, int flags, int fd, off_t offset)
797 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
798 if (ret == MAP_FAILED)
799 die_errno(_("mmap failed"));
804 * With an in-core object data in "map", rehash it to make sure the
805 * object name actually matches "sha1" to detect object corruption.
806 * With "map" == NULL, try reading the object named with "sha1" using
807 * the streaming interface and rehash it to do the same.
809 int check_object_signature(const struct object_id *oid, void *map,
810 unsigned long size, const char *type)
812 struct object_id real_oid;
813 enum object_type obj_type;
814 struct git_istream *st;
816 char hdr[MAX_HEADER_LEN];
820 hash_object_file(map, size, type, &real_oid);
821 return !oideq(oid, &real_oid) ? -1 : 0;
824 st = open_istream(oid, &obj_type, &size, NULL);
828 /* Generate the header */
829 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
832 the_hash_algo->init_fn(&c);
833 the_hash_algo->update_fn(&c, hdr, hdrlen);
836 ssize_t readlen = read_istream(st, buf, sizeof(buf));
844 the_hash_algo->update_fn(&c, buf, readlen);
846 the_hash_algo->final_fn(real_oid.hash, &c);
848 return !oideq(oid, &real_oid) ? -1 : 0;
851 int git_open_cloexec(const char *name, int flags)
854 static int o_cloexec = O_CLOEXEC;
856 fd = open(name, flags | o_cloexec);
857 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
858 /* Try again w/o O_CLOEXEC: the kernel might not support it */
859 o_cloexec &= ~O_CLOEXEC;
860 fd = open(name, flags | o_cloexec);
863 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
865 static int fd_cloexec = FD_CLOEXEC;
867 if (!o_cloexec && 0 <= fd && fd_cloexec) {
868 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
869 int flags = fcntl(fd, F_GETFD);
870 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
879 * Find "sha1" as a loose object in the local repository or in an alternate.
880 * Returns 0 on success, negative on failure.
882 * The "path" out-parameter will give the path of the object we found (if any).
883 * Note that it may point to static storage and is only valid until another
884 * call to stat_sha1_file().
886 static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
887 struct stat *st, const char **path)
889 struct object_directory *odb;
890 static struct strbuf buf = STRBUF_INIT;
892 *path = loose_object_path(r, &buf, sha1);
893 if (!lstat(*path, st))
898 for (odb = r->objects->alt_odb_list; odb; odb = odb->next) {
899 *path = odb_loose_path(odb->path, &buf, sha1);
900 if (!lstat(*path, st))
908 * Like stat_sha1_file(), but actually open the object and return the
909 * descriptor. See the caveats on the "path" parameter above.
911 static int open_sha1_file(struct repository *r,
912 const unsigned char *sha1, const char **path)
915 struct object_directory *odb;
916 int most_interesting_errno;
917 static struct strbuf buf = STRBUF_INIT;
919 *path = loose_object_path(r, &buf, sha1);
920 fd = git_open(*path);
923 most_interesting_errno = errno;
926 for (odb = r->objects->alt_odb_list; odb; odb = odb->next) {
927 *path = odb_loose_path(odb->path, &buf, sha1);
928 fd = git_open(*path);
931 if (most_interesting_errno == ENOENT)
932 most_interesting_errno = errno;
934 errno = most_interesting_errno;
939 * Map the loose object at "path" if it is not NULL, or the path found by
940 * searching for a loose object named "sha1".
942 static void *map_sha1_file_1(struct repository *r, const char *path,
943 const unsigned char *sha1, unsigned long *size)
951 fd = open_sha1_file(r, sha1, &path);
956 if (!fstat(fd, &st)) {
957 *size = xsize_t(st.st_size);
959 /* mmap() is forbidden on empty files */
960 error(_("object file %s is empty"), path);
963 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
970 void *map_sha1_file(struct repository *r,
971 const unsigned char *sha1, unsigned long *size)
973 return map_sha1_file_1(r, NULL, sha1, size);
976 static int unpack_sha1_short_header(git_zstream *stream,
977 unsigned char *map, unsigned long mapsize,
978 void *buffer, unsigned long bufsiz)
980 /* Get the data stream */
981 memset(stream, 0, sizeof(*stream));
982 stream->next_in = map;
983 stream->avail_in = mapsize;
984 stream->next_out = buffer;
985 stream->avail_out = bufsiz;
987 git_inflate_init(stream);
988 return git_inflate(stream, 0);
991 int unpack_sha1_header(git_zstream *stream,
992 unsigned char *map, unsigned long mapsize,
993 void *buffer, unsigned long bufsiz)
995 int status = unpack_sha1_short_header(stream, map, mapsize,
1001 /* Make sure we have the terminating NUL */
1002 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1007 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1008 unsigned long mapsize, void *buffer,
1009 unsigned long bufsiz, struct strbuf *header)
1013 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1018 * Check if entire header is unpacked in the first iteration.
1020 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1024 * buffer[0..bufsiz] was not large enough. Copy the partial
1025 * result out to header, and then append the result of further
1026 * reading the stream.
1028 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1029 stream->next_out = buffer;
1030 stream->avail_out = bufsiz;
1033 status = git_inflate(stream, 0);
1034 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1035 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1037 stream->next_out = buffer;
1038 stream->avail_out = bufsiz;
1039 } while (status != Z_STREAM_END);
1043 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1045 int bytes = strlen(buffer) + 1;
1046 unsigned char *buf = xmallocz(size);
1050 n = stream->total_out - bytes;
1053 memcpy(buf, (char *) buffer + bytes, n);
1055 if (bytes <= size) {
1057 * The above condition must be (bytes <= size), not
1058 * (bytes < size). In other words, even though we
1059 * expect no more output and set avail_out to zero,
1060 * the input zlib stream may have bytes that express
1061 * "this concludes the stream", and we *do* want to
1064 * Otherwise we would not be able to test that we
1065 * consumed all the input to reach the expected size;
1066 * we also want to check that zlib tells us that all
1067 * went well with status == Z_STREAM_END at the end.
1069 stream->next_out = buf + bytes;
1070 stream->avail_out = size - bytes;
1071 while (status == Z_OK)
1072 status = git_inflate(stream, Z_FINISH);
1074 if (status == Z_STREAM_END && !stream->avail_in) {
1075 git_inflate_end(stream);
1080 error(_("corrupt loose object '%s'"), sha1_to_hex(sha1));
1081 else if (stream->avail_in)
1082 error(_("garbage at end of loose object '%s'"),
1089 * We used to just use "sscanf()", but that's actually way
1090 * too permissive for what we want to check. So do an anal
1091 * object header parse by hand.
1093 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1096 const char *type_buf = hdr;
1098 int type, type_len = 0;
1101 * The type can be of any size but is followed by
1113 type = type_from_string_gently(type_buf, type_len, 1);
1115 strbuf_add(oi->type_name, type_buf, type_len);
1117 * Set type to 0 if its an unknown object and
1118 * we're obtaining the type using '--allow-unknown-type'
1121 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1124 die(_("invalid object type"));
1129 * The length must follow immediately, and be in canonical
1130 * decimal format (ie "010" is not valid).
1132 size = *hdr++ - '0';
1137 unsigned long c = *hdr - '0';
1141 size = size * 10 + c;
1149 * The length must be followed by a zero byte
1151 return *hdr ? -1 : type;
1154 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1156 struct object_info oi = OBJECT_INFO_INIT;
1159 return parse_sha1_header_extended(hdr, &oi, 0);
1162 static int sha1_loose_object_info(struct repository *r,
1163 const unsigned char *sha1,
1164 struct object_info *oi, int flags)
1167 unsigned long mapsize;
1170 char hdr[MAX_HEADER_LEN];
1171 struct strbuf hdrbuf = STRBUF_INIT;
1172 unsigned long size_scratch;
1174 if (oi->delta_base_sha1)
1175 hashclr(oi->delta_base_sha1);
1178 * If we don't care about type or size, then we don't
1179 * need to look inside the object at all. Note that we
1180 * do not optimize out the stat call, even if the
1181 * caller doesn't care about the disk-size, since our
1182 * return value implicitly indicates whether the
1183 * object even exists.
1185 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1188 if (stat_sha1_file(r, sha1, &st, &path) < 0)
1191 *oi->disk_sizep = st.st_size;
1195 map = map_sha1_file(r, sha1, &mapsize);
1200 oi->sizep = &size_scratch;
1203 *oi->disk_sizep = mapsize;
1204 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1205 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1206 status = error(_("unable to unpack %s header with --allow-unknown-type"),
1208 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1209 status = error(_("unable to unpack %s header"),
1213 else if (hdrbuf.len) {
1214 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1215 status = error(_("unable to parse %s header with --allow-unknown-type"),
1217 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1218 status = error(_("unable to parse %s header"), sha1_to_hex(sha1));
1220 if (status >= 0 && oi->contentp) {
1221 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1223 if (!*oi->contentp) {
1224 git_inflate_end(&stream);
1228 git_inflate_end(&stream);
1230 munmap(map, mapsize);
1231 if (status && oi->typep)
1232 *oi->typep = status;
1233 if (oi->sizep == &size_scratch)
1235 strbuf_release(&hdrbuf);
1236 oi->whence = OI_LOOSE;
1237 return (status < 0) ? status : 0;
1240 int fetch_if_missing = 1;
1242 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1243 struct object_info *oi, unsigned flags)
1245 static struct object_info blank_oi = OBJECT_INFO_INIT;
1246 struct pack_entry e;
1248 const struct object_id *real = oid;
1249 int already_retried = 0;
1251 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1252 real = lookup_replace_object(r, oid);
1254 if (is_null_oid(real))
1260 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1261 struct cached_object *co = find_cached_object(real);
1264 *(oi->typep) = co->type;
1266 *(oi->sizep) = co->size;
1268 *(oi->disk_sizep) = 0;
1269 if (oi->delta_base_sha1)
1270 hashclr(oi->delta_base_sha1);
1272 strbuf_addstr(oi->type_name, type_name(co->type));
1274 *oi->contentp = xmemdupz(co->buf, co->size);
1275 oi->whence = OI_CACHED;
1281 if (find_pack_entry(r, real, &e))
1284 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1287 /* Most likely it's a loose object. */
1288 if (!sha1_loose_object_info(r, real->hash, oi, flags))
1291 /* Not a loose object; someone else may have just packed it. */
1292 if (!(flags & OBJECT_INFO_QUICK)) {
1293 reprepare_packed_git(r);
1294 if (find_pack_entry(r, real, &e))
1298 /* Check if it is a missing object */
1299 if (fetch_if_missing && repository_format_partial_clone &&
1300 !already_retried && r == the_repository) {
1302 * TODO Investigate having fetch_object() return
1303 * TODO error/success and stopping the music here.
1304 * TODO Pass a repository struct through fetch_object,
1305 * such that arbitrary repositories work.
1307 fetch_objects(repository_format_partial_clone, real, 1);
1308 already_retried = 1;
1315 if (oi == &blank_oi)
1317 * We know that the caller doesn't actually need the
1318 * information below, so return early.
1321 rtype = packed_object_info(r, e.p, e.offset, oi);
1323 mark_bad_packed_object(e.p, real->hash);
1324 return oid_object_info_extended(r, real, oi, 0);
1325 } else if (oi->whence == OI_PACKED) {
1326 oi->u.packed.offset = e.offset;
1327 oi->u.packed.pack = e.p;
1328 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1329 rtype == OBJ_OFS_DELTA);
1335 /* returns enum object_type or negative */
1336 int oid_object_info(struct repository *r,
1337 const struct object_id *oid,
1338 unsigned long *sizep)
1340 enum object_type type;
1341 struct object_info oi = OBJECT_INFO_INIT;
1345 if (oid_object_info_extended(r, oid, &oi,
1346 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1351 static void *read_object(const unsigned char *sha1, enum object_type *type,
1352 unsigned long *size)
1354 struct object_id oid;
1355 struct object_info oi = OBJECT_INFO_INIT;
1359 oi.contentp = &content;
1361 hashcpy(oid.hash, sha1);
1363 if (oid_object_info_extended(the_repository, &oid, &oi, 0) < 0)
1368 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1369 struct object_id *oid)
1371 struct cached_object *co;
1373 hash_object_file(buf, len, type_name(type), oid);
1374 if (has_sha1_file(oid->hash) || find_cached_object(oid))
1376 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1377 co = &cached_objects[cached_object_nr++];
1380 co->buf = xmalloc(len);
1381 memcpy(co->buf, buf, len);
1382 oidcpy(&co->oid, oid);
1387 * This function dies on corrupt objects; the callers who want to
1388 * deal with them should arrange to call read_object() and give error
1389 * messages themselves.
1391 void *read_object_file_extended(const struct object_id *oid,
1392 enum object_type *type,
1393 unsigned long *size,
1397 const struct packed_git *p;
1400 const struct object_id *repl = lookup_replace ?
1401 lookup_replace_object(the_repository, oid) : oid;
1404 data = read_object(repl->hash, type, size);
1408 if (errno && errno != ENOENT)
1409 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1411 /* die if we replaced an object with one that does not exist */
1413 die(_("replacement %s not found for %s"),
1414 oid_to_hex(repl), oid_to_hex(oid));
1416 if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1417 die(_("loose object %s (stored in %s) is corrupt"),
1418 oid_to_hex(repl), path);
1420 if ((p = has_packed_and_bad(repl->hash)) != NULL)
1421 die(_("packed object %s (stored in %s) is corrupt"),
1422 oid_to_hex(repl), p->pack_name);
1427 void *read_object_with_reference(const struct object_id *oid,
1428 const char *required_type_name,
1429 unsigned long *size,
1430 struct object_id *actual_oid_return)
1432 enum object_type type, required_type;
1434 unsigned long isize;
1435 struct object_id actual_oid;
1437 required_type = type_from_string(required_type_name);
1438 oidcpy(&actual_oid, oid);
1440 int ref_length = -1;
1441 const char *ref_type = NULL;
1443 buffer = read_object_file(&actual_oid, &type, &isize);
1446 if (type == required_type) {
1448 if (actual_oid_return)
1449 oidcpy(actual_oid_return, &actual_oid);
1452 /* Handle references */
1453 else if (type == OBJ_COMMIT)
1455 else if (type == OBJ_TAG)
1456 ref_type = "object ";
1461 ref_length = strlen(ref_type);
1463 if (ref_length + the_hash_algo->hexsz > isize ||
1464 memcmp(buffer, ref_type, ref_length) ||
1465 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1470 /* Now we have the ID of the referred-to object in
1471 * actual_oid. Check again. */
1475 static void write_object_file_prepare(const void *buf, unsigned long len,
1476 const char *type, struct object_id *oid,
1477 char *hdr, int *hdrlen)
1481 /* Generate the header */
1482 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1485 the_hash_algo->init_fn(&c);
1486 the_hash_algo->update_fn(&c, hdr, *hdrlen);
1487 the_hash_algo->update_fn(&c, buf, len);
1488 the_hash_algo->final_fn(oid->hash, &c);
1492 * Move the just written object into its final resting place.
1494 int finalize_object_file(const char *tmpfile, const char *filename)
1498 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1500 else if (link(tmpfile, filename))
1504 * Coda hack - coda doesn't like cross-directory links,
1505 * so we fall back to a rename, which will mean that it
1506 * won't be able to check collisions, but that's not a
1509 * The same holds for FAT formatted media.
1511 * When this succeeds, we just return. We have nothing
1514 if (ret && ret != EEXIST) {
1516 if (!rename(tmpfile, filename))
1520 unlink_or_warn(tmpfile);
1522 if (ret != EEXIST) {
1523 return error_errno(_("unable to write sha1 filename %s"), filename);
1525 /* FIXME!!! Collision check here ? */
1529 if (adjust_shared_perm(filename))
1530 return error(_("unable to set permission to '%s'"), filename);
1534 static int write_buffer(int fd, const void *buf, size_t len)
1536 if (write_in_full(fd, buf, len) < 0)
1537 return error_errno(_("file write error"));
1541 int hash_object_file(const void *buf, unsigned long len, const char *type,
1542 struct object_id *oid)
1544 char hdr[MAX_HEADER_LEN];
1545 int hdrlen = sizeof(hdr);
1546 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1550 /* Finalize a file on disk, and close it. */
1551 static void close_sha1_file(int fd)
1553 if (fsync_object_files)
1554 fsync_or_die(fd, "sha1 file");
1556 die_errno(_("error when closing sha1 file"));
1559 /* Size of directory component, including the ending '/' */
1560 static inline int directory_size(const char *filename)
1562 const char *s = strrchr(filename, '/');
1565 return s - filename + 1;
1569 * This creates a temporary file in the same directory as the final
1572 * We want to avoid cross-directory filename renames, because those
1573 * can have problems on various filesystems (FAT, NFS, Coda).
1575 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1577 int fd, dirlen = directory_size(filename);
1580 strbuf_add(tmp, filename, dirlen);
1581 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1582 fd = git_mkstemp_mode(tmp->buf, 0444);
1583 if (fd < 0 && dirlen && errno == ENOENT) {
1585 * Make sure the directory exists; note that the contents
1586 * of the buffer are undefined after mkstemp returns an
1587 * error, so we have to rewrite the whole buffer from
1591 strbuf_add(tmp, filename, dirlen - 1);
1592 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1594 if (adjust_shared_perm(tmp->buf))
1598 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1599 fd = git_mkstemp_mode(tmp->buf, 0444);
1604 static int write_loose_object(const struct object_id *oid, char *hdr,
1605 int hdrlen, const void *buf, unsigned long len,
1609 unsigned char compressed[4096];
1612 struct object_id parano_oid;
1613 static struct strbuf tmp_file = STRBUF_INIT;
1614 static struct strbuf filename = STRBUF_INIT;
1616 loose_object_path(the_repository, &filename, oid->hash);
1618 fd = create_tmpfile(&tmp_file, filename.buf);
1620 if (errno == EACCES)
1621 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1623 return error_errno(_("unable to create temporary file"));
1627 git_deflate_init(&stream, zlib_compression_level);
1628 stream.next_out = compressed;
1629 stream.avail_out = sizeof(compressed);
1630 the_hash_algo->init_fn(&c);
1632 /* First header.. */
1633 stream.next_in = (unsigned char *)hdr;
1634 stream.avail_in = hdrlen;
1635 while (git_deflate(&stream, 0) == Z_OK)
1637 the_hash_algo->update_fn(&c, hdr, hdrlen);
1639 /* Then the data itself.. */
1640 stream.next_in = (void *)buf;
1641 stream.avail_in = len;
1643 unsigned char *in0 = stream.next_in;
1644 ret = git_deflate(&stream, Z_FINISH);
1645 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1646 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1647 die(_("unable to write sha1 file"));
1648 stream.next_out = compressed;
1649 stream.avail_out = sizeof(compressed);
1650 } while (ret == Z_OK);
1652 if (ret != Z_STREAM_END)
1653 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1655 ret = git_deflate_end_gently(&stream);
1657 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1659 the_hash_algo->final_fn(parano_oid.hash, &c);
1660 if (!oideq(oid, ¶no_oid))
1661 die(_("confused by unstable object source data for %s"),
1664 close_sha1_file(fd);
1669 utb.modtime = mtime;
1670 if (utime(tmp_file.buf, &utb) < 0)
1671 warning_errno(_("failed utime() on %s"), tmp_file.buf);
1674 return finalize_object_file(tmp_file.buf, filename.buf);
1677 static int freshen_loose_object(const struct object_id *oid)
1679 return check_and_freshen(oid, 1);
1682 static int freshen_packed_object(const struct object_id *oid)
1684 struct pack_entry e;
1685 if (!find_pack_entry(the_repository, oid, &e))
1689 if (!freshen_file(e.p->pack_name))
1695 int write_object_file(const void *buf, unsigned long len, const char *type,
1696 struct object_id *oid)
1698 char hdr[MAX_HEADER_LEN];
1699 int hdrlen = sizeof(hdr);
1701 /* Normally if we have it in the pack then we do not bother writing
1702 * it out into .git/objects/??/?{38} file.
1704 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1705 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1707 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1710 int hash_object_file_literally(const void *buf, unsigned long len,
1711 const char *type, struct object_id *oid,
1715 int hdrlen, status = 0;
1717 /* type string, SP, %lu of the length plus NUL must fit this */
1718 hdrlen = strlen(type) + MAX_HEADER_LEN;
1719 header = xmalloc(hdrlen);
1720 write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1722 if (!(flags & HASH_WRITE_OBJECT))
1724 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1726 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1733 int force_object_loose(const struct object_id *oid, time_t mtime)
1737 enum object_type type;
1738 char hdr[MAX_HEADER_LEN];
1742 if (has_loose_object(oid))
1744 buf = read_object(oid->hash, &type, &len);
1746 return error(_("cannot read sha1_file for %s"), oid_to_hex(oid));
1747 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1748 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1754 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1756 struct object_id oid;
1757 if (!startup_info->have_repository)
1759 hashcpy(oid.hash, sha1);
1760 return oid_object_info_extended(the_repository, &oid, NULL,
1761 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1764 int has_object_file(const struct object_id *oid)
1766 return has_sha1_file(oid->hash);
1769 int has_object_file_with_flags(const struct object_id *oid, int flags)
1771 return has_sha1_file_with_flags(oid->hash, flags);
1774 static void check_tree(const void *buf, size_t size)
1776 struct tree_desc desc;
1777 struct name_entry entry;
1779 init_tree_desc(&desc, buf, size);
1780 while (tree_entry(&desc, &entry))
1782 * tree_entry() will die() on malformed entries */
1786 static void check_commit(const void *buf, size_t size)
1789 memset(&c, 0, sizeof(c));
1790 if (parse_commit_buffer(the_repository, &c, buf, size, 0))
1791 die(_("corrupt commit"));
1794 static void check_tag(const void *buf, size_t size)
1797 memset(&t, 0, sizeof(t));
1798 if (parse_tag_buffer(the_repository, &t, buf, size))
1799 die(_("corrupt tag"));
1802 static int index_mem(struct index_state *istate,
1803 struct object_id *oid, void *buf, size_t size,
1804 enum object_type type,
1805 const char *path, unsigned flags)
1807 int ret, re_allocated = 0;
1808 int write_object = flags & HASH_WRITE_OBJECT;
1814 * Convert blobs to git internal format
1816 if ((type == OBJ_BLOB) && path) {
1817 struct strbuf nbuf = STRBUF_INIT;
1818 if (convert_to_git(istate, path, buf, size, &nbuf,
1819 get_conv_flags(flags))) {
1820 buf = strbuf_detach(&nbuf, &size);
1824 if (flags & HASH_FORMAT_CHECK) {
1825 if (type == OBJ_TREE)
1826 check_tree(buf, size);
1827 if (type == OBJ_COMMIT)
1828 check_commit(buf, size);
1829 if (type == OBJ_TAG)
1830 check_tag(buf, size);
1834 ret = write_object_file(buf, size, type_name(type), oid);
1836 ret = hash_object_file(buf, size, type_name(type), oid);
1842 static int index_stream_convert_blob(struct index_state *istate,
1843 struct object_id *oid,
1849 const int write_object = flags & HASH_WRITE_OBJECT;
1850 struct strbuf sbuf = STRBUF_INIT;
1853 assert(would_convert_to_git_filter_fd(istate, path));
1855 convert_to_git_filter_fd(istate, path, fd, &sbuf,
1856 get_conv_flags(flags));
1859 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1862 ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1864 strbuf_release(&sbuf);
1868 static int index_pipe(struct index_state *istate, struct object_id *oid,
1869 int fd, enum object_type type,
1870 const char *path, unsigned flags)
1872 struct strbuf sbuf = STRBUF_INIT;
1875 if (strbuf_read(&sbuf, fd, 4096) >= 0)
1876 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
1879 strbuf_release(&sbuf);
1883 #define SMALL_FILE_SIZE (32*1024)
1885 static int index_core(struct index_state *istate,
1886 struct object_id *oid, int fd, size_t size,
1887 enum object_type type, const char *path,
1893 ret = index_mem(istate, oid, "", size, type, path, flags);
1894 } else if (size <= SMALL_FILE_SIZE) {
1895 char *buf = xmalloc(size);
1896 ssize_t read_result = read_in_full(fd, buf, size);
1897 if (read_result < 0)
1898 ret = error_errno(_("read error while indexing %s"),
1899 path ? path : "<unknown>");
1900 else if (read_result != size)
1901 ret = error(_("short read while indexing %s"),
1902 path ? path : "<unknown>");
1904 ret = index_mem(istate, oid, buf, size, type, path, flags);
1907 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1908 ret = index_mem(istate, oid, buf, size, type, path, flags);
1915 * This creates one packfile per large blob unless bulk-checkin
1916 * machinery is "plugged".
1918 * This also bypasses the usual "convert-to-git" dance, and that is on
1919 * purpose. We could write a streaming version of the converting
1920 * functions and insert that before feeding the data to fast-import
1921 * (or equivalent in-core API described above). However, that is
1922 * somewhat complicated, as we do not know the size of the filter
1923 * result, which we need to know beforehand when writing a git object.
1924 * Since the primary motivation for trying to stream from the working
1925 * tree file and to avoid mmaping it in core is to deal with large
1926 * binary blobs, they generally do not want to get any conversion, and
1927 * callers should avoid this code path when filters are requested.
1929 static int index_stream(struct object_id *oid, int fd, size_t size,
1930 enum object_type type, const char *path,
1933 return index_bulk_checkin(oid, fd, size, type, path, flags);
1936 int index_fd(struct index_state *istate, struct object_id *oid,
1937 int fd, struct stat *st,
1938 enum object_type type, const char *path, unsigned flags)
1943 * Call xsize_t() only when needed to avoid potentially unnecessary
1944 * die() for large files.
1946 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
1947 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
1948 else if (!S_ISREG(st->st_mode))
1949 ret = index_pipe(istate, oid, fd, type, path, flags);
1950 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1951 (path && would_convert_to_git(istate, path)))
1952 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
1955 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1961 int index_path(struct index_state *istate, struct object_id *oid,
1962 const char *path, struct stat *st, unsigned flags)
1965 struct strbuf sb = STRBUF_INIT;
1968 switch (st->st_mode & S_IFMT) {
1970 fd = open(path, O_RDONLY);
1972 return error_errno("open(\"%s\")", path);
1973 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
1974 return error(_("%s: failed to insert into database"),
1978 if (strbuf_readlink(&sb, path, st->st_size))
1979 return error_errno("readlink(\"%s\")", path);
1980 if (!(flags & HASH_WRITE_OBJECT))
1981 hash_object_file(sb.buf, sb.len, blob_type, oid);
1982 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
1983 rc = error(_("%s: failed to insert into database"), path);
1984 strbuf_release(&sb);
1987 return resolve_gitlink_ref(path, "HEAD", oid);
1989 return error(_("%s: unsupported file type"), path);
1994 int read_pack_header(int fd, struct pack_header *header)
1996 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1997 /* "eof before pack header was fully read" */
1998 return PH_ERROR_EOF;
2000 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2001 /* "protocol error (pack signature mismatch detected)" */
2002 return PH_ERROR_PACK_SIGNATURE;
2003 if (!pack_version_ok(header->hdr_version))
2004 /* "protocol error (pack version unsupported)" */
2005 return PH_ERROR_PROTOCOL;
2009 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2011 enum object_type type = oid_object_info(the_repository, oid, NULL);
2013 die(_("%s is not a valid object"), oid_to_hex(oid));
2015 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2019 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2020 struct strbuf *path,
2021 each_loose_object_fn obj_cb,
2022 each_loose_cruft_fn cruft_cb,
2023 each_loose_subdir_fn subdir_cb,
2026 size_t origlen, baselen;
2030 struct object_id oid;
2032 if (subdir_nr > 0xff)
2033 BUG("invalid loose object subdirectory: %x", subdir_nr);
2035 origlen = path->len;
2036 strbuf_complete(path, '/');
2037 strbuf_addf(path, "%02x", subdir_nr);
2039 dir = opendir(path->buf);
2041 if (errno != ENOENT)
2042 r = error_errno(_("unable to open %s"), path->buf);
2043 strbuf_setlen(path, origlen);
2047 oid.hash[0] = subdir_nr;
2048 strbuf_addch(path, '/');
2049 baselen = path->len;
2051 while ((de = readdir(dir))) {
2053 if (is_dot_or_dotdot(de->d_name))
2056 namelen = strlen(de->d_name);
2057 strbuf_setlen(path, baselen);
2058 strbuf_add(path, de->d_name, namelen);
2059 if (namelen == the_hash_algo->hexsz - 2 &&
2060 !hex_to_bytes(oid.hash + 1, de->d_name,
2061 the_hash_algo->rawsz - 1)) {
2063 r = obj_cb(&oid, path->buf, data);
2071 r = cruft_cb(de->d_name, path->buf, data);
2078 strbuf_setlen(path, baselen - 1);
2079 if (!r && subdir_cb)
2080 r = subdir_cb(subdir_nr, path->buf, data);
2082 strbuf_setlen(path, origlen);
2087 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2088 each_loose_object_fn obj_cb,
2089 each_loose_cruft_fn cruft_cb,
2090 each_loose_subdir_fn subdir_cb,
2096 for (i = 0; i < 256; i++) {
2097 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2106 int for_each_loose_file_in_objdir(const char *path,
2107 each_loose_object_fn obj_cb,
2108 each_loose_cruft_fn cruft_cb,
2109 each_loose_subdir_fn subdir_cb,
2112 struct strbuf buf = STRBUF_INIT;
2115 strbuf_addstr(&buf, path);
2116 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2118 strbuf_release(&buf);
2123 struct loose_alt_odb_data {
2124 each_loose_object_fn *cb;
2128 static int loose_from_alt_odb(struct object_directory *odb,
2131 struct loose_alt_odb_data *data = vdata;
2132 struct strbuf buf = STRBUF_INIT;
2135 strbuf_addstr(&buf, odb->path);
2136 r = for_each_loose_file_in_objdir_buf(&buf,
2137 data->cb, NULL, NULL,
2139 strbuf_release(&buf);
2143 int for_each_loose_object(each_loose_object_fn cb, void *data,
2144 enum for_each_object_flags flags)
2146 struct loose_alt_odb_data alt;
2149 r = for_each_loose_file_in_objdir(get_object_directory(),
2150 cb, NULL, NULL, data);
2154 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2159 return foreach_alt_odb(loose_from_alt_odb, &alt);
2162 static int check_stream_sha1(git_zstream *stream,
2166 const unsigned char *expected_sha1)
2169 unsigned char real_sha1[GIT_MAX_RAWSZ];
2170 unsigned char buf[4096];
2171 unsigned long total_read;
2174 the_hash_algo->init_fn(&c);
2175 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2178 * We already read some bytes into hdr, but the ones up to the NUL
2179 * do not count against the object's content size.
2181 total_read = stream->total_out - strlen(hdr) - 1;
2184 * This size comparison must be "<=" to read the final zlib packets;
2185 * see the comment in unpack_sha1_rest for details.
2187 while (total_read <= size &&
2188 (status == Z_OK || status == Z_BUF_ERROR)) {
2189 stream->next_out = buf;
2190 stream->avail_out = sizeof(buf);
2191 if (size - total_read < stream->avail_out)
2192 stream->avail_out = size - total_read;
2193 status = git_inflate(stream, Z_FINISH);
2194 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2195 total_read += stream->next_out - buf;
2197 git_inflate_end(stream);
2199 if (status != Z_STREAM_END) {
2200 error(_("corrupt loose object '%s'"), sha1_to_hex(expected_sha1));
2203 if (stream->avail_in) {
2204 error(_("garbage at end of loose object '%s'"),
2205 sha1_to_hex(expected_sha1));
2209 the_hash_algo->final_fn(real_sha1, &c);
2210 if (!hasheq(expected_sha1, real_sha1)) {
2211 error(_("sha1 mismatch for %s (expected %s)"), path,
2212 sha1_to_hex(expected_sha1));
2219 int read_loose_object(const char *path,
2220 const struct object_id *expected_oid,
2221 enum object_type *type,
2222 unsigned long *size,
2227 unsigned long mapsize;
2229 char hdr[MAX_HEADER_LEN];
2233 map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2235 error_errno(_("unable to mmap %s"), path);
2239 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2240 error(_("unable to unpack header of %s"), path);
2244 *type = parse_sha1_header(hdr, size);
2246 error(_("unable to parse header of %s"), path);
2247 git_inflate_end(&stream);
2251 if (*type == OBJ_BLOB && *size > big_file_threshold) {
2252 if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2255 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2257 error(_("unable to unpack contents of %s"), path);
2258 git_inflate_end(&stream);
2261 if (check_object_signature(expected_oid, *contents,
2262 *size, type_name(*type))) {
2263 error(_("sha1 mismatch for %s (expected %s)"), path,
2264 oid_to_hex(expected_oid));
2270 ret = 0; /* everything checks out */
2274 munmap(map, mapsize);