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"
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 unsigned char null_sha1
[GIT_MAX_RAWSZ
];
59 const struct object_id null_oid
;
60 static const struct object_id empty_tree_oid
= {
61 EMPTY_TREE_SHA1_BIN_LITERAL
63 static const struct object_id empty_blob_oid
= {
64 EMPTY_BLOB_SHA1_BIN_LITERAL
66 static const struct object_id empty_tree_oid_sha256
= {
67 EMPTY_TREE_SHA256_BIN_LITERAL
69 static const struct object_id empty_blob_oid_sha256
= {
70 EMPTY_BLOB_SHA256_BIN_LITERAL
73 static void git_hash_sha1_init(git_hash_ctx
*ctx
)
75 git_SHA1_Init(&ctx
->sha1
);
78 static void git_hash_sha1_update(git_hash_ctx
*ctx
, const void *data
, size_t len
)
80 git_SHA1_Update(&ctx
->sha1
, data
, len
);
83 static void git_hash_sha1_final(unsigned char *hash
, git_hash_ctx
*ctx
)
85 git_SHA1_Final(hash
, &ctx
->sha1
);
89 static void git_hash_sha256_init(git_hash_ctx
*ctx
)
91 git_SHA256_Init(&ctx
->sha256
);
94 static void git_hash_sha256_update(git_hash_ctx
*ctx
, const void *data
, size_t len
)
96 git_SHA256_Update(&ctx
->sha256
, data
, len
);
99 static void git_hash_sha256_final(unsigned char *hash
, git_hash_ctx
*ctx
)
101 git_SHA256_Final(hash
, &ctx
->sha256
);
104 static void git_hash_unknown_init(git_hash_ctx
*ctx
)
106 BUG("trying to init unknown hash");
109 static void git_hash_unknown_update(git_hash_ctx
*ctx
, const void *data
, size_t len
)
111 BUG("trying to update unknown hash");
114 static void git_hash_unknown_final(unsigned char *hash
, git_hash_ctx
*ctx
)
116 BUG("trying to finalize unknown hash");
119 const struct git_hash_algo hash_algos
[GIT_HASH_NALGOS
] = {
126 git_hash_unknown_init
,
127 git_hash_unknown_update
,
128 git_hash_unknown_final
,
134 /* "sha1", big-endian */
140 git_hash_sha1_update
,
147 /* "s256", big-endian */
152 git_hash_sha256_init
,
153 git_hash_sha256_update
,
154 git_hash_sha256_final
,
155 &empty_tree_oid_sha256
,
156 &empty_blob_oid_sha256
,
160 const char *empty_tree_oid_hex(void)
162 static char buf
[GIT_MAX_HEXSZ
+ 1];
163 return oid_to_hex_r(buf
, the_hash_algo
->empty_tree
);
166 const char *empty_blob_oid_hex(void)
168 static char buf
[GIT_MAX_HEXSZ
+ 1];
169 return oid_to_hex_r(buf
, the_hash_algo
->empty_blob
);
172 int hash_algo_by_name(const char *name
)
176 return GIT_HASH_UNKNOWN
;
177 for (i
= 1; i
< GIT_HASH_NALGOS
; i
++)
178 if (!strcmp(name
, hash_algos
[i
].name
))
180 return GIT_HASH_UNKNOWN
;
183 int hash_algo_by_id(uint32_t format_id
)
186 for (i
= 1; i
< GIT_HASH_NALGOS
; i
++)
187 if (format_id
== hash_algos
[i
].format_id
)
189 return GIT_HASH_UNKNOWN
;
194 * This is meant to hold a *small* number of objects that you would
195 * want read_sha1_file() to be able to return, but yet you do not want
196 * to write them into the object store (e.g. a browse-only
199 static struct cached_object
{
200 struct object_id oid
;
201 enum object_type type
;
205 static int cached_object_nr
, cached_object_alloc
;
207 static struct cached_object empty_tree
= {
208 { EMPTY_TREE_SHA1_BIN_LITERAL
},
214 static struct cached_object
*find_cached_object(const struct object_id
*oid
)
217 struct cached_object
*co
= cached_objects
;
219 for (i
= 0; i
< cached_object_nr
; i
++, co
++) {
220 if (oideq(&co
->oid
, oid
))
223 if (oideq(oid
, the_hash_algo
->empty_tree
))
229 static int get_conv_flags(unsigned flags
)
231 if (flags
& HASH_RENORMALIZE
)
232 return CONV_EOL_RENORMALIZE
;
233 else if (flags
& HASH_WRITE_OBJECT
)
234 return global_conv_flags_eol
| CONV_WRITE_OBJECT
;
240 int mkdir_in_gitdir(const char *path
)
242 if (mkdir(path
, 0777)) {
243 int saved_errno
= errno
;
245 struct strbuf sb
= STRBUF_INIT
;
250 * Are we looking at a path in a symlinked worktree
251 * whose original repository does not yet have it?
252 * e.g. .git/rr-cache pointing at its original
253 * repository in which the user hasn't performed any
254 * conflict resolution yet?
256 if (lstat(path
, &st
) || !S_ISLNK(st
.st_mode
) ||
257 strbuf_readlink(&sb
, path
, st
.st_size
) ||
258 !is_absolute_path(sb
.buf
) ||
259 mkdir(sb
.buf
, 0777)) {
266 return adjust_shared_perm(path
);
269 enum scld_error
safe_create_leading_directories(char *path
)
271 char *next_component
= path
+ offset_1st_component(path
);
272 enum scld_error ret
= SCLD_OK
;
274 while (ret
== SCLD_OK
&& next_component
) {
276 char *slash
= next_component
, slash_character
;
278 while (*slash
&& !is_dir_sep(*slash
))
284 next_component
= slash
+ 1;
285 while (is_dir_sep(*next_component
))
287 if (!*next_component
)
290 slash_character
= *slash
;
292 if (!stat(path
, &st
)) {
294 if (!S_ISDIR(st
.st_mode
)) {
298 } else if (mkdir(path
, 0777)) {
299 if (errno
== EEXIST
&&
300 !stat(path
, &st
) && S_ISDIR(st
.st_mode
))
301 ; /* somebody created it since we checked */
302 else if (errno
== ENOENT
)
304 * Either mkdir() failed because
305 * somebody just pruned the containing
306 * directory, or stat() failed because
307 * the file that was in our way was
308 * just removed. Either way, inform
309 * the caller that it might be worth
315 } else if (adjust_shared_perm(path
)) {
318 *slash
= slash_character
;
323 enum scld_error
safe_create_leading_directories_const(const char *path
)
326 /* path points to cache entries, so xstrdup before messing with it */
327 char *buf
= xstrdup(path
);
328 enum scld_error result
= safe_create_leading_directories(buf
);
336 int raceproof_create_file(const char *path
, create_file_fn fn
, void *cb
)
339 * The number of times we will try to remove empty directories
340 * in the way of path. This is only 1 because if another
341 * process is racily creating directories that conflict with
342 * us, we don't want to fight against them.
344 int remove_directories_remaining
= 1;
347 * The number of times that we will try to create the
348 * directories containing path. We are willing to attempt this
349 * more than once, because another process could be trying to
350 * clean up empty directories at the same time as we are
351 * trying to create them.
353 int create_directories_remaining
= 3;
355 /* A scratch copy of path, filled lazily if we need it: */
356 struct strbuf path_copy
= STRBUF_INIT
;
369 if (errno
== EISDIR
&& remove_directories_remaining
-- > 0) {
371 * A directory is in the way. Maybe it is empty; try
375 strbuf_addstr(&path_copy
, path
);
377 if (!remove_dir_recursively(&path_copy
, REMOVE_DIR_EMPTY_ONLY
))
379 } else if (errno
== ENOENT
&& create_directories_remaining
-- > 0) {
381 * Maybe the containing directory didn't exist, or
382 * maybe it was just deleted by a process that is
383 * racing with us to clean up empty directories. Try
386 enum scld_error scld_result
;
389 strbuf_addstr(&path_copy
, path
);
392 scld_result
= safe_create_leading_directories(path_copy
.buf
);
393 if (scld_result
== SCLD_OK
)
395 } while (scld_result
== SCLD_VANISHED
&& create_directories_remaining
-- > 0);
399 strbuf_release(&path_copy
);
404 static void fill_sha1_path(struct strbuf
*buf
, const unsigned char *sha1
)
407 for (i
= 0; i
< the_hash_algo
->rawsz
; i
++) {
408 static char hex
[] = "0123456789abcdef";
409 unsigned int val
= sha1
[i
];
410 strbuf_addch(buf
, hex
[val
>> 4]);
411 strbuf_addch(buf
, hex
[val
& 0xf]);
413 strbuf_addch(buf
, '/');
417 void sha1_file_name(struct repository
*r
, struct strbuf
*buf
, const unsigned char *sha1
)
419 strbuf_addstr(buf
, r
->objects
->objectdir
);
420 strbuf_addch(buf
, '/');
421 fill_sha1_path(buf
, sha1
);
424 struct strbuf
*alt_scratch_buf(struct alternate_object_database
*alt
)
426 strbuf_setlen(&alt
->scratch
, alt
->base_len
);
427 return &alt
->scratch
;
430 static const char *alt_sha1_path(struct alternate_object_database
*alt
,
431 const unsigned char *sha1
)
433 struct strbuf
*buf
= alt_scratch_buf(alt
);
434 fill_sha1_path(buf
, sha1
);
439 * Return non-zero iff the path is usable as an alternate object database.
441 static int alt_odb_usable(struct raw_object_store
*o
,
443 const char *normalized_objdir
)
445 struct alternate_object_database
*alt
;
447 /* Detect cases where alternate disappeared */
448 if (!is_directory(path
->buf
)) {
449 error(_("object directory %s does not exist; "
450 "check .git/objects/info/alternates"),
456 * Prevent the common mistake of listing the same
457 * thing twice, or object directory itself.
459 for (alt
= o
->alt_odb_list
; alt
; alt
= alt
->next
) {
460 if (!fspathcmp(path
->buf
, alt
->path
))
463 if (!fspathcmp(path
->buf
, normalized_objdir
))
470 * Prepare alternate object database registry.
472 * The variable alt_odb_list points at the list of struct
473 * alternate_object_database. The elements on this list come from
474 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
475 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
476 * whose contents is similar to that environment variable but can be
477 * LF separated. Its base points at a statically allocated buffer that
478 * contains "/the/directory/corresponding/to/.git/objects/...", while
479 * its name points just after the slash at the end of ".git/objects/"
480 * in the example above, and has enough space to hold 40-byte hex
481 * SHA1, an extra slash for the first level indirection, and the
484 static void read_info_alternates(struct repository
*r
,
485 const char *relative_base
,
487 static int link_alt_odb_entry(struct repository
*r
, const char *entry
,
488 const char *relative_base
, int depth
, const char *normalized_objdir
)
490 struct alternate_object_database
*ent
;
491 struct strbuf pathbuf
= STRBUF_INIT
;
493 if (!is_absolute_path(entry
) && relative_base
) {
494 strbuf_realpath(&pathbuf
, relative_base
, 1);
495 strbuf_addch(&pathbuf
, '/');
497 strbuf_addstr(&pathbuf
, entry
);
499 if (strbuf_normalize_path(&pathbuf
) < 0 && relative_base
) {
500 error(_("unable to normalize alternate object path: %s"),
502 strbuf_release(&pathbuf
);
507 * The trailing slash after the directory name is given by
508 * this function at the end. Remove duplicates.
510 while (pathbuf
.len
&& pathbuf
.buf
[pathbuf
.len
- 1] == '/')
511 strbuf_setlen(&pathbuf
, pathbuf
.len
- 1);
513 if (!alt_odb_usable(r
->objects
, &pathbuf
, normalized_objdir
)) {
514 strbuf_release(&pathbuf
);
518 ent
= alloc_alt_odb(pathbuf
.buf
);
520 /* add the alternate entry */
521 *r
->objects
->alt_odb_tail
= ent
;
522 r
->objects
->alt_odb_tail
= &(ent
->next
);
525 /* recursively add alternates */
526 read_info_alternates(r
, pathbuf
.buf
, depth
+ 1);
528 strbuf_release(&pathbuf
);
532 static const char *parse_alt_odb_entry(const char *string
,
540 if (*string
== '#') {
541 /* comment; consume up to next separator */
542 end
= strchrnul(string
, sep
);
543 } else if (*string
== '"' && !unquote_c_style(out
, string
, &end
)) {
545 * quoted path; unquote_c_style has copied the
546 * data for us and set "end". Broken quoting (e.g.,
547 * an entry that doesn't end with a quote) falls
548 * back to the unquoted case below.
551 /* normal, unquoted path */
552 end
= strchrnul(string
, sep
);
553 strbuf_add(out
, string
, end
- string
);
561 static void link_alt_odb_entries(struct repository
*r
, const char *alt
,
562 int sep
, const char *relative_base
, int depth
)
564 struct strbuf objdirbuf
= STRBUF_INIT
;
565 struct strbuf entry
= STRBUF_INIT
;
571 error(_("%s: ignoring alternate object stores, nesting too deep"),
576 strbuf_add_absolute_path(&objdirbuf
, r
->objects
->objectdir
);
577 if (strbuf_normalize_path(&objdirbuf
) < 0)
578 die(_("unable to normalize object directory: %s"),
582 alt
= parse_alt_odb_entry(alt
, sep
, &entry
);
585 link_alt_odb_entry(r
, entry
.buf
,
586 relative_base
, depth
, objdirbuf
.buf
);
588 strbuf_release(&entry
);
589 strbuf_release(&objdirbuf
);
592 static void read_info_alternates(struct repository
*r
,
593 const char *relative_base
,
597 struct strbuf buf
= STRBUF_INIT
;
599 path
= xstrfmt("%s/info/alternates", relative_base
);
600 if (strbuf_read_file(&buf
, path
, 1024) < 0) {
601 warn_on_fopen_errors(path
);
606 link_alt_odb_entries(r
, buf
.buf
, '\n', relative_base
, depth
);
607 strbuf_release(&buf
);
611 struct alternate_object_database
*alloc_alt_odb(const char *dir
)
613 struct alternate_object_database
*ent
;
615 FLEX_ALLOC_STR(ent
, path
, dir
);
616 strbuf_init(&ent
->scratch
, 0);
617 strbuf_addf(&ent
->scratch
, "%s/", dir
);
618 ent
->base_len
= ent
->scratch
.len
;
623 void add_to_alternates_file(const char *reference
)
625 struct lock_file lock
= LOCK_INIT
;
626 char *alts
= git_pathdup("objects/info/alternates");
630 hold_lock_file_for_update(&lock
, alts
, LOCK_DIE_ON_ERROR
);
631 out
= fdopen_lock_file(&lock
, "w");
633 die_errno(_("unable to fdopen alternates lockfile"));
635 in
= fopen(alts
, "r");
637 struct strbuf line
= STRBUF_INIT
;
639 while (strbuf_getline(&line
, in
) != EOF
) {
640 if (!strcmp(reference
, line
.buf
)) {
644 fprintf_or_die(out
, "%s\n", line
.buf
);
647 strbuf_release(&line
);
650 else if (errno
!= ENOENT
)
651 die_errno(_("unable to read alternates file"));
654 rollback_lock_file(&lock
);
656 fprintf_or_die(out
, "%s\n", reference
);
657 if (commit_lock_file(&lock
))
658 die_errno(_("unable to move new alternates file into place"));
659 if (the_repository
->objects
->alt_odb_tail
)
660 link_alt_odb_entries(the_repository
, reference
,
666 void add_to_alternates_memory(const char *reference
)
669 * Make sure alternates are initialized, or else our entry may be
670 * overwritten when they are.
672 prepare_alt_odb(the_repository
);
674 link_alt_odb_entries(the_repository
, reference
,
679 * Compute the exact path an alternate is at and returns it. In case of
680 * error NULL is returned and the human readable error is added to `err`
681 * `path` may be relative and should point to $GIT_DIR.
682 * `err` must not be null.
684 char *compute_alternate_path(const char *path
, struct strbuf
*err
)
686 char *ref_git
= NULL
;
687 const char *repo
, *ref_git_s
;
690 ref_git_s
= real_path_if_valid(path
);
693 strbuf_addf(err
, _("path '%s' does not exist"), path
);
697 * Beware: read_gitfile(), real_path() and mkpath()
698 * return static buffer
700 ref_git
= xstrdup(ref_git_s
);
702 repo
= read_gitfile(ref_git
);
704 repo
= read_gitfile(mkpath("%s/.git", ref_git
));
707 ref_git
= xstrdup(repo
);
710 if (!repo
&& is_directory(mkpath("%s/.git/objects", ref_git
))) {
711 char *ref_git_git
= mkpathdup("%s/.git", ref_git
);
713 ref_git
= ref_git_git
;
714 } else if (!is_directory(mkpath("%s/objects", ref_git
))) {
715 struct strbuf sb
= STRBUF_INIT
;
717 if (get_common_dir(&sb
, ref_git
)) {
719 _("reference repository '%s' as a linked "
720 "checkout is not supported yet."),
725 strbuf_addf(err
, _("reference repository '%s' is not a "
726 "local repository."), path
);
730 if (!access(mkpath("%s/shallow", ref_git
), F_OK
)) {
731 strbuf_addf(err
, _("reference repository '%s' is shallow"),
737 if (!access(mkpath("%s/info/grafts", ref_git
), F_OK
)) {
739 _("reference repository '%s' is grafted"),
747 FREE_AND_NULL(ref_git
);
753 int foreach_alt_odb(alt_odb_fn fn
, void *cb
)
755 struct alternate_object_database
*ent
;
758 prepare_alt_odb(the_repository
);
759 for (ent
= the_repository
->objects
->alt_odb_list
; ent
; ent
= ent
->next
) {
767 void prepare_alt_odb(struct repository
*r
)
769 if (r
->objects
->alt_odb_tail
)
772 r
->objects
->alt_odb_tail
= &r
->objects
->alt_odb_list
;
773 link_alt_odb_entries(r
, r
->objects
->alternate_db
, PATH_SEP
, NULL
, 0);
775 read_info_alternates(r
, r
->objects
->objectdir
, 0);
778 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
779 static int freshen_file(const char *fn
)
782 t
.actime
= t
.modtime
= time(NULL
);
783 return !utime(fn
, &t
);
787 * All of the check_and_freshen functions return 1 if the file exists and was
788 * freshened (if freshening was requested), 0 otherwise. If they return
789 * 0, you should not assume that it is safe to skip a write of the object (it
790 * either does not exist on disk, or has a stale mtime and may be subject to
793 int check_and_freshen_file(const char *fn
, int freshen
)
795 if (access(fn
, F_OK
))
797 if (freshen
&& !freshen_file(fn
))
802 static int check_and_freshen_local(const struct object_id
*oid
, int freshen
)
804 static struct strbuf buf
= STRBUF_INIT
;
807 sha1_file_name(the_repository
, &buf
, oid
->hash
);
809 return check_and_freshen_file(buf
.buf
, freshen
);
812 static int check_and_freshen_nonlocal(const struct object_id
*oid
, int freshen
)
814 struct alternate_object_database
*alt
;
815 prepare_alt_odb(the_repository
);
816 for (alt
= the_repository
->objects
->alt_odb_list
; alt
; alt
= alt
->next
) {
817 const char *path
= alt_sha1_path(alt
, oid
->hash
);
818 if (check_and_freshen_file(path
, freshen
))
824 static int check_and_freshen(const struct object_id
*oid
, int freshen
)
826 return check_and_freshen_local(oid
, freshen
) ||
827 check_and_freshen_nonlocal(oid
, freshen
);
830 int has_loose_object_nonlocal(const struct object_id
*oid
)
832 return check_and_freshen_nonlocal(oid
, 0);
835 static int has_loose_object(const struct object_id
*oid
)
837 return check_and_freshen(oid
, 0);
840 static void mmap_limit_check(size_t length
)
842 static size_t limit
= 0;
844 limit
= git_env_ulong("GIT_MMAP_LIMIT", 0);
849 die(_("attempting to mmap %"PRIuMAX
" over limit %"PRIuMAX
),
850 (uintmax_t)length
, (uintmax_t)limit
);
853 void *xmmap_gently(void *start
, size_t length
,
854 int prot
, int flags
, int fd
, off_t offset
)
858 mmap_limit_check(length
);
859 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
860 if (ret
== MAP_FAILED
) {
863 release_pack_memory(length
);
864 ret
= mmap(start
, length
, prot
, flags
, fd
, offset
);
869 void *xmmap(void *start
, size_t length
,
870 int prot
, int flags
, int fd
, off_t offset
)
872 void *ret
= xmmap_gently(start
, length
, prot
, flags
, fd
, offset
);
873 if (ret
== MAP_FAILED
)
874 die_errno(_("mmap failed"));
879 * With an in-core object data in "map", rehash it to make sure the
880 * object name actually matches "sha1" to detect object corruption.
881 * With "map" == NULL, try reading the object named with "sha1" using
882 * the streaming interface and rehash it to do the same.
884 int check_object_signature(const struct object_id
*oid
, void *map
,
885 unsigned long size
, const char *type
)
887 struct object_id real_oid
;
888 enum object_type obj_type
;
889 struct git_istream
*st
;
891 char hdr
[MAX_HEADER_LEN
];
895 hash_object_file(map
, size
, type
, &real_oid
);
896 return !oideq(oid
, &real_oid
) ? -1 : 0;
899 st
= open_istream(oid
, &obj_type
, &size
, NULL
);
903 /* Generate the header */
904 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", type_name(obj_type
), size
) + 1;
907 the_hash_algo
->init_fn(&c
);
908 the_hash_algo
->update_fn(&c
, hdr
, hdrlen
);
911 ssize_t readlen
= read_istream(st
, buf
, sizeof(buf
));
919 the_hash_algo
->update_fn(&c
, buf
, readlen
);
921 the_hash_algo
->final_fn(real_oid
.hash
, &c
);
923 return !oideq(oid
, &real_oid
) ? -1 : 0;
926 int git_open_cloexec(const char *name
, int flags
)
929 static int o_cloexec
= O_CLOEXEC
;
931 fd
= open(name
, flags
| o_cloexec
);
932 if ((o_cloexec
& O_CLOEXEC
) && fd
< 0 && errno
== EINVAL
) {
933 /* Try again w/o O_CLOEXEC: the kernel might not support it */
934 o_cloexec
&= ~O_CLOEXEC
;
935 fd
= open(name
, flags
| o_cloexec
);
938 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
940 static int fd_cloexec
= FD_CLOEXEC
;
942 if (!o_cloexec
&& 0 <= fd
&& fd_cloexec
) {
943 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
944 int flags
= fcntl(fd
, F_GETFD
);
945 if (fcntl(fd
, F_SETFD
, flags
| fd_cloexec
))
954 * Find "sha1" as a loose object in the local repository or in an alternate.
955 * Returns 0 on success, negative on failure.
957 * The "path" out-parameter will give the path of the object we found (if any).
958 * Note that it may point to static storage and is only valid until another
959 * call to sha1_file_name(), etc.
961 static int stat_sha1_file(struct repository
*r
, const unsigned char *sha1
,
962 struct stat
*st
, const char **path
)
964 struct alternate_object_database
*alt
;
965 static struct strbuf buf
= STRBUF_INIT
;
968 sha1_file_name(r
, &buf
, sha1
);
971 if (!lstat(*path
, st
))
976 for (alt
= r
->objects
->alt_odb_list
; alt
; alt
= alt
->next
) {
977 *path
= alt_sha1_path(alt
, sha1
);
978 if (!lstat(*path
, st
))
986 * Like stat_sha1_file(), but actually open the object and return the
987 * descriptor. See the caveats on the "path" parameter above.
989 static int open_sha1_file(struct repository
*r
,
990 const unsigned char *sha1
, const char **path
)
993 struct alternate_object_database
*alt
;
994 int most_interesting_errno
;
995 static struct strbuf buf
= STRBUF_INIT
;
998 sha1_file_name(r
, &buf
, sha1
);
1001 fd
= git_open(*path
);
1004 most_interesting_errno
= errno
;
1007 for (alt
= r
->objects
->alt_odb_list
; alt
; alt
= alt
->next
) {
1008 *path
= alt_sha1_path(alt
, sha1
);
1009 fd
= git_open(*path
);
1012 if (most_interesting_errno
== ENOENT
)
1013 most_interesting_errno
= errno
;
1015 errno
= most_interesting_errno
;
1020 * Map the loose object at "path" if it is not NULL, or the path found by
1021 * searching for a loose object named "sha1".
1023 static void *map_sha1_file_1(struct repository
*r
, const char *path
,
1024 const unsigned char *sha1
, unsigned long *size
)
1030 fd
= git_open(path
);
1032 fd
= open_sha1_file(r
, sha1
, &path
);
1037 if (!fstat(fd
, &st
)) {
1038 *size
= xsize_t(st
.st_size
);
1040 /* mmap() is forbidden on empty files */
1041 error(_("object file %s is empty"), path
);
1044 map
= xmmap(NULL
, *size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1051 void *map_sha1_file(struct repository
*r
,
1052 const unsigned char *sha1
, unsigned long *size
)
1054 return map_sha1_file_1(r
, NULL
, sha1
, size
);
1057 static int unpack_sha1_short_header(git_zstream
*stream
,
1058 unsigned char *map
, unsigned long mapsize
,
1059 void *buffer
, unsigned long bufsiz
)
1061 /* Get the data stream */
1062 memset(stream
, 0, sizeof(*stream
));
1063 stream
->next_in
= map
;
1064 stream
->avail_in
= mapsize
;
1065 stream
->next_out
= buffer
;
1066 stream
->avail_out
= bufsiz
;
1068 git_inflate_init(stream
);
1069 return git_inflate(stream
, 0);
1072 int unpack_sha1_header(git_zstream
*stream
,
1073 unsigned char *map
, unsigned long mapsize
,
1074 void *buffer
, unsigned long bufsiz
)
1076 int status
= unpack_sha1_short_header(stream
, map
, mapsize
,
1082 /* Make sure we have the terminating NUL */
1083 if (!memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1088 static int unpack_sha1_header_to_strbuf(git_zstream
*stream
, unsigned char *map
,
1089 unsigned long mapsize
, void *buffer
,
1090 unsigned long bufsiz
, struct strbuf
*header
)
1094 status
= unpack_sha1_short_header(stream
, map
, mapsize
, buffer
, bufsiz
);
1099 * Check if entire header is unpacked in the first iteration.
1101 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1105 * buffer[0..bufsiz] was not large enough. Copy the partial
1106 * result out to header, and then append the result of further
1107 * reading the stream.
1109 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1110 stream
->next_out
= buffer
;
1111 stream
->avail_out
= bufsiz
;
1114 status
= git_inflate(stream
, 0);
1115 strbuf_add(header
, buffer
, stream
->next_out
- (unsigned char *)buffer
);
1116 if (memchr(buffer
, '\0', stream
->next_out
- (unsigned char *)buffer
))
1118 stream
->next_out
= buffer
;
1119 stream
->avail_out
= bufsiz
;
1120 } while (status
!= Z_STREAM_END
);
1124 static void *unpack_sha1_rest(git_zstream
*stream
, void *buffer
, unsigned long size
, const unsigned char *sha1
)
1126 int bytes
= strlen(buffer
) + 1;
1127 unsigned char *buf
= xmallocz(size
);
1131 n
= stream
->total_out
- bytes
;
1134 memcpy(buf
, (char *) buffer
+ bytes
, n
);
1136 if (bytes
<= size
) {
1138 * The above condition must be (bytes <= size), not
1139 * (bytes < size). In other words, even though we
1140 * expect no more output and set avail_out to zero,
1141 * the input zlib stream may have bytes that express
1142 * "this concludes the stream", and we *do* want to
1145 * Otherwise we would not be able to test that we
1146 * consumed all the input to reach the expected size;
1147 * we also want to check that zlib tells us that all
1148 * went well with status == Z_STREAM_END at the end.
1150 stream
->next_out
= buf
+ bytes
;
1151 stream
->avail_out
= size
- bytes
;
1152 while (status
== Z_OK
)
1153 status
= git_inflate(stream
, Z_FINISH
);
1155 if (status
== Z_STREAM_END
&& !stream
->avail_in
) {
1156 git_inflate_end(stream
);
1161 error(_("corrupt loose object '%s'"), sha1_to_hex(sha1
));
1162 else if (stream
->avail_in
)
1163 error(_("garbage at end of loose object '%s'"),
1170 * We used to just use "sscanf()", but that's actually way
1171 * too permissive for what we want to check. So do an anal
1172 * object header parse by hand.
1174 static int parse_sha1_header_extended(const char *hdr
, struct object_info
*oi
,
1177 const char *type_buf
= hdr
;
1179 int type
, type_len
= 0;
1182 * The type can be of any size but is followed by
1194 type
= type_from_string_gently(type_buf
, type_len
, 1);
1196 strbuf_add(oi
->type_name
, type_buf
, type_len
);
1198 * Set type to 0 if its an unknown object and
1199 * we're obtaining the type using '--allow-unknown-type'
1202 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
) && (type
< 0))
1205 die(_("invalid object type"));
1210 * The length must follow immediately, and be in canonical
1211 * decimal format (ie "010" is not valid).
1213 size
= *hdr
++ - '0';
1218 unsigned long c
= *hdr
- '0';
1222 size
= size
* 10 + c
;
1230 * The length must be followed by a zero byte
1232 return *hdr
? -1 : type
;
1235 int parse_sha1_header(const char *hdr
, unsigned long *sizep
)
1237 struct object_info oi
= OBJECT_INFO_INIT
;
1240 return parse_sha1_header_extended(hdr
, &oi
, 0);
1243 static int sha1_loose_object_info(struct repository
*r
,
1244 const unsigned char *sha1
,
1245 struct object_info
*oi
, int flags
)
1248 unsigned long mapsize
;
1251 char hdr
[MAX_HEADER_LEN
];
1252 struct strbuf hdrbuf
= STRBUF_INIT
;
1253 unsigned long size_scratch
;
1255 if (oi
->delta_base_sha1
)
1256 hashclr(oi
->delta_base_sha1
);
1259 * If we don't care about type or size, then we don't
1260 * need to look inside the object at all. Note that we
1261 * do not optimize out the stat call, even if the
1262 * caller doesn't care about the disk-size, since our
1263 * return value implicitly indicates whether the
1264 * object even exists.
1266 if (!oi
->typep
&& !oi
->type_name
&& !oi
->sizep
&& !oi
->contentp
) {
1269 if (stat_sha1_file(r
, sha1
, &st
, &path
) < 0)
1272 *oi
->disk_sizep
= st
.st_size
;
1276 map
= map_sha1_file(r
, sha1
, &mapsize
);
1281 oi
->sizep
= &size_scratch
;
1284 *oi
->disk_sizep
= mapsize
;
1285 if ((flags
& OBJECT_INFO_ALLOW_UNKNOWN_TYPE
)) {
1286 if (unpack_sha1_header_to_strbuf(&stream
, map
, mapsize
, hdr
, sizeof(hdr
), &hdrbuf
) < 0)
1287 status
= error(_("unable to unpack %s header with --allow-unknown-type"),
1289 } else if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0)
1290 status
= error(_("unable to unpack %s header"),
1294 else if (hdrbuf
.len
) {
1295 if ((status
= parse_sha1_header_extended(hdrbuf
.buf
, oi
, flags
)) < 0)
1296 status
= error(_("unable to parse %s header with --allow-unknown-type"),
1298 } else if ((status
= parse_sha1_header_extended(hdr
, oi
, flags
)) < 0)
1299 status
= error(_("unable to parse %s header"), sha1_to_hex(sha1
));
1301 if (status
>= 0 && oi
->contentp
) {
1302 *oi
->contentp
= unpack_sha1_rest(&stream
, hdr
,
1304 if (!*oi
->contentp
) {
1305 git_inflate_end(&stream
);
1309 git_inflate_end(&stream
);
1311 munmap(map
, mapsize
);
1312 if (status
&& oi
->typep
)
1313 *oi
->typep
= status
;
1314 if (oi
->sizep
== &size_scratch
)
1316 strbuf_release(&hdrbuf
);
1317 oi
->whence
= OI_LOOSE
;
1318 return (status
< 0) ? status
: 0;
1321 int fetch_if_missing
= 1;
1323 int oid_object_info_extended(struct repository
*r
, const struct object_id
*oid
,
1324 struct object_info
*oi
, unsigned flags
)
1326 static struct object_info blank_oi
= OBJECT_INFO_INIT
;
1327 struct pack_entry e
;
1329 const struct object_id
*real
= oid
;
1330 int already_retried
= 0;
1332 if (flags
& OBJECT_INFO_LOOKUP_REPLACE
)
1333 real
= lookup_replace_object(r
, oid
);
1335 if (is_null_oid(real
))
1341 if (!(flags
& OBJECT_INFO_SKIP_CACHED
)) {
1342 struct cached_object
*co
= find_cached_object(real
);
1345 *(oi
->typep
) = co
->type
;
1347 *(oi
->sizep
) = co
->size
;
1349 *(oi
->disk_sizep
) = 0;
1350 if (oi
->delta_base_sha1
)
1351 hashclr(oi
->delta_base_sha1
);
1353 strbuf_addstr(oi
->type_name
, type_name(co
->type
));
1355 *oi
->contentp
= xmemdupz(co
->buf
, co
->size
);
1356 oi
->whence
= OI_CACHED
;
1362 if (find_pack_entry(r
, real
, &e
))
1365 if (flags
& OBJECT_INFO_IGNORE_LOOSE
)
1368 /* Most likely it's a loose object. */
1369 if (!sha1_loose_object_info(r
, real
->hash
, oi
, flags
))
1372 /* Not a loose object; someone else may have just packed it. */
1373 if (!(flags
& OBJECT_INFO_QUICK
)) {
1374 reprepare_packed_git(r
);
1375 if (find_pack_entry(r
, real
, &e
))
1379 /* Check if it is a missing object */
1380 if (fetch_if_missing
&& repository_format_partial_clone
&&
1381 !already_retried
&& r
== the_repository
) {
1383 * TODO Investigate having fetch_object() return
1384 * TODO error/success and stopping the music here.
1385 * TODO Pass a repository struct through fetch_object,
1386 * such that arbitrary repositories work.
1388 fetch_objects(repository_format_partial_clone
, real
, 1);
1389 already_retried
= 1;
1396 if (oi
== &blank_oi
)
1398 * We know that the caller doesn't actually need the
1399 * information below, so return early.
1402 rtype
= packed_object_info(r
, e
.p
, e
.offset
, oi
);
1404 mark_bad_packed_object(e
.p
, real
->hash
);
1405 return oid_object_info_extended(r
, real
, oi
, 0);
1406 } else if (oi
->whence
== OI_PACKED
) {
1407 oi
->u
.packed
.offset
= e
.offset
;
1408 oi
->u
.packed
.pack
= e
.p
;
1409 oi
->u
.packed
.is_delta
= (rtype
== OBJ_REF_DELTA
||
1410 rtype
== OBJ_OFS_DELTA
);
1416 /* returns enum object_type or negative */
1417 int oid_object_info(struct repository
*r
,
1418 const struct object_id
*oid
,
1419 unsigned long *sizep
)
1421 enum object_type type
;
1422 struct object_info oi
= OBJECT_INFO_INIT
;
1426 if (oid_object_info_extended(r
, oid
, &oi
,
1427 OBJECT_INFO_LOOKUP_REPLACE
) < 0)
1432 static void *read_object(const unsigned char *sha1
, enum object_type
*type
,
1433 unsigned long *size
)
1435 struct object_id oid
;
1436 struct object_info oi
= OBJECT_INFO_INIT
;
1440 oi
.contentp
= &content
;
1442 hashcpy(oid
.hash
, sha1
);
1444 if (oid_object_info_extended(the_repository
, &oid
, &oi
, 0) < 0)
1449 int pretend_object_file(void *buf
, unsigned long len
, enum object_type type
,
1450 struct object_id
*oid
)
1452 struct cached_object
*co
;
1454 hash_object_file(buf
, len
, type_name(type
), oid
);
1455 if (has_sha1_file(oid
->hash
) || find_cached_object(oid
))
1457 ALLOC_GROW(cached_objects
, cached_object_nr
+ 1, cached_object_alloc
);
1458 co
= &cached_objects
[cached_object_nr
++];
1461 co
->buf
= xmalloc(len
);
1462 memcpy(co
->buf
, buf
, len
);
1463 oidcpy(&co
->oid
, oid
);
1468 * This function dies on corrupt objects; the callers who want to
1469 * deal with them should arrange to call read_object() and give error
1470 * messages themselves.
1472 void *read_object_file_extended(const struct object_id
*oid
,
1473 enum object_type
*type
,
1474 unsigned long *size
,
1478 const struct packed_git
*p
;
1481 const struct object_id
*repl
= lookup_replace
?
1482 lookup_replace_object(the_repository
, oid
) : oid
;
1485 data
= read_object(repl
->hash
, type
, size
);
1489 if (errno
&& errno
!= ENOENT
)
1490 die_errno(_("failed to read object %s"), oid_to_hex(oid
));
1492 /* die if we replaced an object with one that does not exist */
1494 die(_("replacement %s not found for %s"),
1495 oid_to_hex(repl
), oid_to_hex(oid
));
1497 if (!stat_sha1_file(the_repository
, repl
->hash
, &st
, &path
))
1498 die(_("loose object %s (stored in %s) is corrupt"),
1499 oid_to_hex(repl
), path
);
1501 if ((p
= has_packed_and_bad(repl
->hash
)) != NULL
)
1502 die(_("packed object %s (stored in %s) is corrupt"),
1503 oid_to_hex(repl
), p
->pack_name
);
1508 void *read_object_with_reference(const struct object_id
*oid
,
1509 const char *required_type_name
,
1510 unsigned long *size
,
1511 struct object_id
*actual_oid_return
)
1513 enum object_type type
, required_type
;
1515 unsigned long isize
;
1516 struct object_id actual_oid
;
1518 required_type
= type_from_string(required_type_name
);
1519 oidcpy(&actual_oid
, oid
);
1521 int ref_length
= -1;
1522 const char *ref_type
= NULL
;
1524 buffer
= read_object_file(&actual_oid
, &type
, &isize
);
1527 if (type
== required_type
) {
1529 if (actual_oid_return
)
1530 oidcpy(actual_oid_return
, &actual_oid
);
1533 /* Handle references */
1534 else if (type
== OBJ_COMMIT
)
1536 else if (type
== OBJ_TAG
)
1537 ref_type
= "object ";
1542 ref_length
= strlen(ref_type
);
1544 if (ref_length
+ the_hash_algo
->hexsz
> isize
||
1545 memcmp(buffer
, ref_type
, ref_length
) ||
1546 get_oid_hex((char *) buffer
+ ref_length
, &actual_oid
)) {
1551 /* Now we have the ID of the referred-to object in
1552 * actual_oid. Check again. */
1556 static void write_object_file_prepare(const void *buf
, unsigned long len
,
1557 const char *type
, struct object_id
*oid
,
1558 char *hdr
, int *hdrlen
)
1562 /* Generate the header */
1563 *hdrlen
= xsnprintf(hdr
, *hdrlen
, "%s %lu", type
, len
)+1;
1566 the_hash_algo
->init_fn(&c
);
1567 the_hash_algo
->update_fn(&c
, hdr
, *hdrlen
);
1568 the_hash_algo
->update_fn(&c
, buf
, len
);
1569 the_hash_algo
->final_fn(oid
->hash
, &c
);
1573 * Move the just written object into its final resting place.
1575 int finalize_object_file(const char *tmpfile
, const char *filename
)
1579 if (object_creation_mode
== OBJECT_CREATION_USES_RENAMES
)
1581 else if (link(tmpfile
, filename
))
1585 * Coda hack - coda doesn't like cross-directory links,
1586 * so we fall back to a rename, which will mean that it
1587 * won't be able to check collisions, but that's not a
1590 * The same holds for FAT formatted media.
1592 * When this succeeds, we just return. We have nothing
1595 if (ret
&& ret
!= EEXIST
) {
1597 if (!rename(tmpfile
, filename
))
1601 unlink_or_warn(tmpfile
);
1603 if (ret
!= EEXIST
) {
1604 return error_errno(_("unable to write sha1 filename %s"), filename
);
1606 /* FIXME!!! Collision check here ? */
1610 if (adjust_shared_perm(filename
))
1611 return error(_("unable to set permission to '%s'"), filename
);
1615 static int write_buffer(int fd
, const void *buf
, size_t len
)
1617 if (write_in_full(fd
, buf
, len
) < 0)
1618 return error_errno(_("file write error"));
1622 int hash_object_file(const void *buf
, unsigned long len
, const char *type
,
1623 struct object_id
*oid
)
1625 char hdr
[MAX_HEADER_LEN
];
1626 int hdrlen
= sizeof(hdr
);
1627 write_object_file_prepare(buf
, len
, type
, oid
, hdr
, &hdrlen
);
1631 /* Finalize a file on disk, and close it. */
1632 static void close_sha1_file(int fd
)
1634 if (fsync_object_files
)
1635 fsync_or_die(fd
, "sha1 file");
1637 die_errno(_("error when closing sha1 file"));
1640 /* Size of directory component, including the ending '/' */
1641 static inline int directory_size(const char *filename
)
1643 const char *s
= strrchr(filename
, '/');
1646 return s
- filename
+ 1;
1650 * This creates a temporary file in the same directory as the final
1653 * We want to avoid cross-directory filename renames, because those
1654 * can have problems on various filesystems (FAT, NFS, Coda).
1656 static int create_tmpfile(struct strbuf
*tmp
, const char *filename
)
1658 int fd
, dirlen
= directory_size(filename
);
1661 strbuf_add(tmp
, filename
, dirlen
);
1662 strbuf_addstr(tmp
, "tmp_obj_XXXXXX");
1663 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
1664 if (fd
< 0 && dirlen
&& errno
== ENOENT
) {
1666 * Make sure the directory exists; note that the contents
1667 * of the buffer are undefined after mkstemp returns an
1668 * error, so we have to rewrite the whole buffer from
1672 strbuf_add(tmp
, filename
, dirlen
- 1);
1673 if (mkdir(tmp
->buf
, 0777) && errno
!= EEXIST
)
1675 if (adjust_shared_perm(tmp
->buf
))
1679 strbuf_addstr(tmp
, "/tmp_obj_XXXXXX");
1680 fd
= git_mkstemp_mode(tmp
->buf
, 0444);
1685 static int write_loose_object(const struct object_id
*oid
, char *hdr
,
1686 int hdrlen
, const void *buf
, unsigned long len
,
1690 unsigned char compressed
[4096];
1693 struct object_id parano_oid
;
1694 static struct strbuf tmp_file
= STRBUF_INIT
;
1695 static struct strbuf filename
= STRBUF_INIT
;
1697 strbuf_reset(&filename
);
1698 sha1_file_name(the_repository
, &filename
, oid
->hash
);
1700 fd
= create_tmpfile(&tmp_file
, filename
.buf
);
1702 if (errno
== EACCES
)
1703 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1705 return error_errno(_("unable to create temporary file"));
1709 git_deflate_init(&stream
, zlib_compression_level
);
1710 stream
.next_out
= compressed
;
1711 stream
.avail_out
= sizeof(compressed
);
1712 the_hash_algo
->init_fn(&c
);
1714 /* First header.. */
1715 stream
.next_in
= (unsigned char *)hdr
;
1716 stream
.avail_in
= hdrlen
;
1717 while (git_deflate(&stream
, 0) == Z_OK
)
1719 the_hash_algo
->update_fn(&c
, hdr
, hdrlen
);
1721 /* Then the data itself.. */
1722 stream
.next_in
= (void *)buf
;
1723 stream
.avail_in
= len
;
1725 unsigned char *in0
= stream
.next_in
;
1726 ret
= git_deflate(&stream
, Z_FINISH
);
1727 the_hash_algo
->update_fn(&c
, in0
, stream
.next_in
- in0
);
1728 if (write_buffer(fd
, compressed
, stream
.next_out
- compressed
) < 0)
1729 die(_("unable to write sha1 file"));
1730 stream
.next_out
= compressed
;
1731 stream
.avail_out
= sizeof(compressed
);
1732 } while (ret
== Z_OK
);
1734 if (ret
!= Z_STREAM_END
)
1735 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid
),
1737 ret
= git_deflate_end_gently(&stream
);
1739 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid
),
1741 the_hash_algo
->final_fn(parano_oid
.hash
, &c
);
1742 if (!oideq(oid
, ¶no_oid
))
1743 die(_("confused by unstable object source data for %s"),
1746 close_sha1_file(fd
);
1751 utb
.modtime
= mtime
;
1752 if (utime(tmp_file
.buf
, &utb
) < 0)
1753 warning_errno(_("failed utime() on %s"), tmp_file
.buf
);
1756 return finalize_object_file(tmp_file
.buf
, filename
.buf
);
1759 static int freshen_loose_object(const struct object_id
*oid
)
1761 return check_and_freshen(oid
, 1);
1764 static int freshen_packed_object(const struct object_id
*oid
)
1766 struct pack_entry e
;
1767 if (!find_pack_entry(the_repository
, oid
, &e
))
1771 if (!freshen_file(e
.p
->pack_name
))
1777 int write_object_file(const void *buf
, unsigned long len
, const char *type
,
1778 struct object_id
*oid
)
1780 char hdr
[MAX_HEADER_LEN
];
1781 int hdrlen
= sizeof(hdr
);
1783 /* Normally if we have it in the pack then we do not bother writing
1784 * it out into .git/objects/??/?{38} file.
1786 write_object_file_prepare(buf
, len
, type
, oid
, hdr
, &hdrlen
);
1787 if (freshen_packed_object(oid
) || freshen_loose_object(oid
))
1789 return write_loose_object(oid
, hdr
, hdrlen
, buf
, len
, 0);
1792 int hash_object_file_literally(const void *buf
, unsigned long len
,
1793 const char *type
, struct object_id
*oid
,
1797 int hdrlen
, status
= 0;
1799 /* type string, SP, %lu of the length plus NUL must fit this */
1800 hdrlen
= strlen(type
) + MAX_HEADER_LEN
;
1801 header
= xmalloc(hdrlen
);
1802 write_object_file_prepare(buf
, len
, type
, oid
, header
, &hdrlen
);
1804 if (!(flags
& HASH_WRITE_OBJECT
))
1806 if (freshen_packed_object(oid
) || freshen_loose_object(oid
))
1808 status
= write_loose_object(oid
, header
, hdrlen
, buf
, len
, 0);
1815 int force_object_loose(const struct object_id
*oid
, time_t mtime
)
1819 enum object_type type
;
1820 char hdr
[MAX_HEADER_LEN
];
1824 if (has_loose_object(oid
))
1826 buf
= read_object(oid
->hash
, &type
, &len
);
1828 return error(_("cannot read sha1_file for %s"), oid_to_hex(oid
));
1829 hdrlen
= xsnprintf(hdr
, sizeof(hdr
), "%s %lu", type_name(type
), len
) + 1;
1830 ret
= write_loose_object(oid
, hdr
, hdrlen
, buf
, len
, mtime
);
1836 int has_sha1_file_with_flags(const unsigned char *sha1
, int flags
)
1838 struct object_id oid
;
1839 if (!startup_info
->have_repository
)
1841 hashcpy(oid
.hash
, sha1
);
1842 return oid_object_info_extended(the_repository
, &oid
, NULL
,
1843 flags
| OBJECT_INFO_SKIP_CACHED
) >= 0;
1846 int has_object_file(const struct object_id
*oid
)
1848 return has_sha1_file(oid
->hash
);
1851 int has_object_file_with_flags(const struct object_id
*oid
, int flags
)
1853 return has_sha1_file_with_flags(oid
->hash
, flags
);
1856 static void check_tree(const void *buf
, size_t size
)
1858 struct tree_desc desc
;
1859 struct name_entry entry
;
1861 init_tree_desc(&desc
, buf
, size
);
1862 while (tree_entry(&desc
, &entry
))
1864 * tree_entry() will die() on malformed entries */
1868 static void check_commit(const void *buf
, size_t size
)
1871 memset(&c
, 0, sizeof(c
));
1872 if (parse_commit_buffer(the_repository
, &c
, buf
, size
, 0))
1873 die(_("corrupt commit"));
1876 static void check_tag(const void *buf
, size_t size
)
1879 memset(&t
, 0, sizeof(t
));
1880 if (parse_tag_buffer(the_repository
, &t
, buf
, size
))
1881 die(_("corrupt tag"));
1884 static int index_mem(struct object_id
*oid
, void *buf
, size_t size
,
1885 enum object_type type
,
1886 const char *path
, unsigned flags
)
1888 int ret
, re_allocated
= 0;
1889 int write_object
= flags
& HASH_WRITE_OBJECT
;
1895 * Convert blobs to git internal format
1897 if ((type
== OBJ_BLOB
) && path
) {
1898 struct strbuf nbuf
= STRBUF_INIT
;
1899 if (convert_to_git(&the_index
, path
, buf
, size
, &nbuf
,
1900 get_conv_flags(flags
))) {
1901 buf
= strbuf_detach(&nbuf
, &size
);
1905 if (flags
& HASH_FORMAT_CHECK
) {
1906 if (type
== OBJ_TREE
)
1907 check_tree(buf
, size
);
1908 if (type
== OBJ_COMMIT
)
1909 check_commit(buf
, size
);
1910 if (type
== OBJ_TAG
)
1911 check_tag(buf
, size
);
1915 ret
= write_object_file(buf
, size
, type_name(type
), oid
);
1917 ret
= hash_object_file(buf
, size
, type_name(type
), oid
);
1923 static int index_stream_convert_blob(struct object_id
*oid
, int fd
,
1924 const char *path
, unsigned flags
)
1927 const int write_object
= flags
& HASH_WRITE_OBJECT
;
1928 struct strbuf sbuf
= STRBUF_INIT
;
1931 assert(would_convert_to_git_filter_fd(&the_index
, path
));
1933 convert_to_git_filter_fd(&the_index
, path
, fd
, &sbuf
,
1934 get_conv_flags(flags
));
1937 ret
= write_object_file(sbuf
.buf
, sbuf
.len
, type_name(OBJ_BLOB
),
1940 ret
= hash_object_file(sbuf
.buf
, sbuf
.len
, type_name(OBJ_BLOB
),
1942 strbuf_release(&sbuf
);
1946 static int index_pipe(struct object_id
*oid
, int fd
, enum object_type type
,
1947 const char *path
, unsigned flags
)
1949 struct strbuf sbuf
= STRBUF_INIT
;
1952 if (strbuf_read(&sbuf
, fd
, 4096) >= 0)
1953 ret
= index_mem(oid
, sbuf
.buf
, sbuf
.len
, type
, path
, flags
);
1956 strbuf_release(&sbuf
);
1960 #define SMALL_FILE_SIZE (32*1024)
1962 static int index_core(struct object_id
*oid
, int fd
, size_t size
,
1963 enum object_type type
, const char *path
,
1969 ret
= index_mem(oid
, "", size
, type
, path
, flags
);
1970 } else if (size
<= SMALL_FILE_SIZE
) {
1971 char *buf
= xmalloc(size
);
1972 ssize_t read_result
= read_in_full(fd
, buf
, size
);
1973 if (read_result
< 0)
1974 ret
= error_errno(_("read error while indexing %s"),
1975 path
? path
: "<unknown>");
1976 else if (read_result
!= size
)
1977 ret
= error(_("short read while indexing %s"),
1978 path
? path
: "<unknown>");
1980 ret
= index_mem(oid
, buf
, size
, type
, path
, flags
);
1983 void *buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1984 ret
= index_mem(oid
, buf
, size
, type
, path
, flags
);
1991 * This creates one packfile per large blob unless bulk-checkin
1992 * machinery is "plugged".
1994 * This also bypasses the usual "convert-to-git" dance, and that is on
1995 * purpose. We could write a streaming version of the converting
1996 * functions and insert that before feeding the data to fast-import
1997 * (or equivalent in-core API described above). However, that is
1998 * somewhat complicated, as we do not know the size of the filter
1999 * result, which we need to know beforehand when writing a git object.
2000 * Since the primary motivation for trying to stream from the working
2001 * tree file and to avoid mmaping it in core is to deal with large
2002 * binary blobs, they generally do not want to get any conversion, and
2003 * callers should avoid this code path when filters are requested.
2005 static int index_stream(struct object_id
*oid
, int fd
, size_t size
,
2006 enum object_type type
, const char *path
,
2009 return index_bulk_checkin(oid
, fd
, size
, type
, path
, flags
);
2012 int index_fd(struct object_id
*oid
, int fd
, struct stat
*st
,
2013 enum object_type type
, const char *path
, unsigned flags
)
2018 * Call xsize_t() only when needed to avoid potentially unnecessary
2019 * die() for large files.
2021 if (type
== OBJ_BLOB
&& path
&& would_convert_to_git_filter_fd(&the_index
, path
))
2022 ret
= index_stream_convert_blob(oid
, fd
, path
, flags
);
2023 else if (!S_ISREG(st
->st_mode
))
2024 ret
= index_pipe(oid
, fd
, type
, path
, flags
);
2025 else if (st
->st_size
<= big_file_threshold
|| type
!= OBJ_BLOB
||
2026 (path
&& would_convert_to_git(&the_index
, path
)))
2027 ret
= index_core(oid
, fd
, xsize_t(st
->st_size
), type
, path
,
2030 ret
= index_stream(oid
, fd
, xsize_t(st
->st_size
), type
, path
,
2036 int index_path(struct object_id
*oid
, const char *path
, struct stat
*st
, unsigned flags
)
2039 struct strbuf sb
= STRBUF_INIT
;
2042 switch (st
->st_mode
& S_IFMT
) {
2044 fd
= open(path
, O_RDONLY
);
2046 return error_errno("open(\"%s\")", path
);
2047 if (index_fd(oid
, fd
, st
, OBJ_BLOB
, path
, flags
) < 0)
2048 return error(_("%s: failed to insert into database"),
2052 if (strbuf_readlink(&sb
, path
, st
->st_size
))
2053 return error_errno("readlink(\"%s\")", path
);
2054 if (!(flags
& HASH_WRITE_OBJECT
))
2055 hash_object_file(sb
.buf
, sb
.len
, blob_type
, oid
);
2056 else if (write_object_file(sb
.buf
, sb
.len
, blob_type
, oid
))
2057 rc
= error(_("%s: failed to insert into database"), path
);
2058 strbuf_release(&sb
);
2061 return resolve_gitlink_ref(path
, "HEAD", oid
);
2063 return error(_("%s: unsupported file type"), path
);
2068 int read_pack_header(int fd
, struct pack_header
*header
)
2070 if (read_in_full(fd
, header
, sizeof(*header
)) != sizeof(*header
))
2071 /* "eof before pack header was fully read" */
2072 return PH_ERROR_EOF
;
2074 if (header
->hdr_signature
!= htonl(PACK_SIGNATURE
))
2075 /* "protocol error (pack signature mismatch detected)" */
2076 return PH_ERROR_PACK_SIGNATURE
;
2077 if (!pack_version_ok(header
->hdr_version
))
2078 /* "protocol error (pack version unsupported)" */
2079 return PH_ERROR_PROTOCOL
;
2083 void assert_oid_type(const struct object_id
*oid
, enum object_type expect
)
2085 enum object_type type
= oid_object_info(the_repository
, oid
, NULL
);
2087 die(_("%s is not a valid object"), oid_to_hex(oid
));
2089 die(_("%s is not a valid '%s' object"), oid_to_hex(oid
),
2093 int for_each_file_in_obj_subdir(unsigned int subdir_nr
,
2094 struct strbuf
*path
,
2095 each_loose_object_fn obj_cb
,
2096 each_loose_cruft_fn cruft_cb
,
2097 each_loose_subdir_fn subdir_cb
,
2100 size_t origlen
, baselen
;
2104 struct object_id oid
;
2106 if (subdir_nr
> 0xff)
2107 BUG("invalid loose object subdirectory: %x", subdir_nr
);
2109 origlen
= path
->len
;
2110 strbuf_complete(path
, '/');
2111 strbuf_addf(path
, "%02x", subdir_nr
);
2113 dir
= opendir(path
->buf
);
2115 if (errno
!= ENOENT
)
2116 r
= error_errno(_("unable to open %s"), path
->buf
);
2117 strbuf_setlen(path
, origlen
);
2121 oid
.hash
[0] = subdir_nr
;
2122 strbuf_addch(path
, '/');
2123 baselen
= path
->len
;
2125 while ((de
= readdir(dir
))) {
2127 if (is_dot_or_dotdot(de
->d_name
))
2130 namelen
= strlen(de
->d_name
);
2131 strbuf_setlen(path
, baselen
);
2132 strbuf_add(path
, de
->d_name
, namelen
);
2133 if (namelen
== the_hash_algo
->hexsz
- 2 &&
2134 !hex_to_bytes(oid
.hash
+ 1, de
->d_name
,
2135 the_hash_algo
->rawsz
- 1)) {
2137 r
= obj_cb(&oid
, path
->buf
, data
);
2145 r
= cruft_cb(de
->d_name
, path
->buf
, data
);
2152 strbuf_setlen(path
, baselen
- 1);
2153 if (!r
&& subdir_cb
)
2154 r
= subdir_cb(subdir_nr
, path
->buf
, data
);
2156 strbuf_setlen(path
, origlen
);
2161 int for_each_loose_file_in_objdir_buf(struct strbuf
*path
,
2162 each_loose_object_fn obj_cb
,
2163 each_loose_cruft_fn cruft_cb
,
2164 each_loose_subdir_fn subdir_cb
,
2170 for (i
= 0; i
< 256; i
++) {
2171 r
= for_each_file_in_obj_subdir(i
, path
, obj_cb
, cruft_cb
,
2180 int for_each_loose_file_in_objdir(const char *path
,
2181 each_loose_object_fn obj_cb
,
2182 each_loose_cruft_fn cruft_cb
,
2183 each_loose_subdir_fn subdir_cb
,
2186 struct strbuf buf
= STRBUF_INIT
;
2189 strbuf_addstr(&buf
, path
);
2190 r
= for_each_loose_file_in_objdir_buf(&buf
, obj_cb
, cruft_cb
,
2192 strbuf_release(&buf
);
2197 struct loose_alt_odb_data
{
2198 each_loose_object_fn
*cb
;
2202 static int loose_from_alt_odb(struct alternate_object_database
*alt
,
2205 struct loose_alt_odb_data
*data
= vdata
;
2206 struct strbuf buf
= STRBUF_INIT
;
2209 strbuf_addstr(&buf
, alt
->path
);
2210 r
= for_each_loose_file_in_objdir_buf(&buf
,
2211 data
->cb
, NULL
, NULL
,
2213 strbuf_release(&buf
);
2217 int for_each_loose_object(each_loose_object_fn cb
, void *data
,
2218 enum for_each_object_flags flags
)
2220 struct loose_alt_odb_data alt
;
2223 r
= for_each_loose_file_in_objdir(get_object_directory(),
2224 cb
, NULL
, NULL
, data
);
2228 if (flags
& FOR_EACH_OBJECT_LOCAL_ONLY
)
2233 return foreach_alt_odb(loose_from_alt_odb
, &alt
);
2236 static int check_stream_sha1(git_zstream
*stream
,
2240 const unsigned char *expected_sha1
)
2243 unsigned char real_sha1
[GIT_MAX_RAWSZ
];
2244 unsigned char buf
[4096];
2245 unsigned long total_read
;
2248 the_hash_algo
->init_fn(&c
);
2249 the_hash_algo
->update_fn(&c
, hdr
, stream
->total_out
);
2252 * We already read some bytes into hdr, but the ones up to the NUL
2253 * do not count against the object's content size.
2255 total_read
= stream
->total_out
- strlen(hdr
) - 1;
2258 * This size comparison must be "<=" to read the final zlib packets;
2259 * see the comment in unpack_sha1_rest for details.
2261 while (total_read
<= size
&&
2262 (status
== Z_OK
|| status
== Z_BUF_ERROR
)) {
2263 stream
->next_out
= buf
;
2264 stream
->avail_out
= sizeof(buf
);
2265 if (size
- total_read
< stream
->avail_out
)
2266 stream
->avail_out
= size
- total_read
;
2267 status
= git_inflate(stream
, Z_FINISH
);
2268 the_hash_algo
->update_fn(&c
, buf
, stream
->next_out
- buf
);
2269 total_read
+= stream
->next_out
- buf
;
2271 git_inflate_end(stream
);
2273 if (status
!= Z_STREAM_END
) {
2274 error(_("corrupt loose object '%s'"), sha1_to_hex(expected_sha1
));
2277 if (stream
->avail_in
) {
2278 error(_("garbage at end of loose object '%s'"),
2279 sha1_to_hex(expected_sha1
));
2283 the_hash_algo
->final_fn(real_sha1
, &c
);
2284 if (!hasheq(expected_sha1
, real_sha1
)) {
2285 error(_("sha1 mismatch for %s (expected %s)"), path
,
2286 sha1_to_hex(expected_sha1
));
2293 int read_loose_object(const char *path
,
2294 const struct object_id
*expected_oid
,
2295 enum object_type
*type
,
2296 unsigned long *size
,
2301 unsigned long mapsize
;
2303 char hdr
[MAX_HEADER_LEN
];
2307 map
= map_sha1_file_1(the_repository
, path
, NULL
, &mapsize
);
2309 error_errno(_("unable to mmap %s"), path
);
2313 if (unpack_sha1_header(&stream
, map
, mapsize
, hdr
, sizeof(hdr
)) < 0) {
2314 error(_("unable to unpack header of %s"), path
);
2318 *type
= parse_sha1_header(hdr
, size
);
2320 error(_("unable to parse header of %s"), path
);
2321 git_inflate_end(&stream
);
2325 if (*type
== OBJ_BLOB
&& *size
> big_file_threshold
) {
2326 if (check_stream_sha1(&stream
, hdr
, *size
, path
, expected_oid
->hash
) < 0)
2329 *contents
= unpack_sha1_rest(&stream
, hdr
, *size
, expected_oid
->hash
);
2331 error(_("unable to unpack contents of %s"), path
);
2332 git_inflate_end(&stream
);
2335 if (check_object_signature(expected_oid
, *contents
,
2336 *size
, type_name(*type
))) {
2337 error(_("sha1 mismatch for %s (expected %s)"), path
,
2338 oid_to_hex(expected_oid
));
2344 ret
= 0; /* everything checks out */
2348 munmap(map
, mapsize
);