object-store.h: reduce unnecessary includes
[alt-git.git] / object-file.c
blob921a717d8a5e0bd849f49adf7883f9f6e64e8c87
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "git-compat-util.h"
10 #include "abspath.h"
11 #include "alloc.h"
12 #include "config.h"
13 #include "convert.h"
14 #include "environment.h"
15 #include "gettext.h"
16 #include "hex.h"
17 #include "string-list.h"
18 #include "lockfile.h"
19 #include "delta.h"
20 #include "pack.h"
21 #include "blob.h"
22 #include "commit.h"
23 #include "run-command.h"
24 #include "tag.h"
25 #include "tree.h"
26 #include "tree-walk.h"
27 #include "refs.h"
28 #include "pack-revindex.h"
29 #include "hash-lookup.h"
30 #include "bulk-checkin.h"
31 #include "repository.h"
32 #include "replace-object.h"
33 #include "streaming.h"
34 #include "dir.h"
35 #include "list.h"
36 #include "mergesort.h"
37 #include "quote.h"
38 #include "packfile.h"
39 #include "object-file.h"
40 #include "object-store.h"
41 #include "oidtree.h"
42 #include "promisor-remote.h"
43 #include "setup.h"
44 #include "submodule.h"
45 #include "fsck.h"
46 #include "wrapper.h"
48 /* The maximum size for an object header. */
49 #define MAX_HEADER_LEN 32
52 #define EMPTY_TREE_SHA1_BIN_LITERAL \
53 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
54 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
55 #define EMPTY_TREE_SHA256_BIN_LITERAL \
56 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
57 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
58 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
59 "\x53\x21"
61 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
62 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
63 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
64 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
65 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
66 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
67 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
68 "\x18\x13"
70 static const struct object_id empty_tree_oid = {
71 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
72 .algo = GIT_HASH_SHA1,
74 static const struct object_id empty_blob_oid = {
75 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
76 .algo = GIT_HASH_SHA1,
78 static const struct object_id null_oid_sha1 = {
79 .hash = {0},
80 .algo = GIT_HASH_SHA1,
82 static const struct object_id empty_tree_oid_sha256 = {
83 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
84 .algo = GIT_HASH_SHA256,
86 static const struct object_id empty_blob_oid_sha256 = {
87 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
88 .algo = GIT_HASH_SHA256,
90 static const struct object_id null_oid_sha256 = {
91 .hash = {0},
92 .algo = GIT_HASH_SHA256,
95 static void git_hash_sha1_init(git_hash_ctx *ctx)
97 git_SHA1_Init(&ctx->sha1);
100 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
102 git_SHA1_Clone(&dst->sha1, &src->sha1);
105 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
107 git_SHA1_Update(&ctx->sha1, data, len);
110 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
112 git_SHA1_Final(hash, &ctx->sha1);
115 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
117 git_SHA1_Final(oid->hash, &ctx->sha1);
118 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
119 oid->algo = GIT_HASH_SHA1;
123 static void git_hash_sha256_init(git_hash_ctx *ctx)
125 git_SHA256_Init(&ctx->sha256);
128 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
130 git_SHA256_Clone(&dst->sha256, &src->sha256);
133 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
135 git_SHA256_Update(&ctx->sha256, data, len);
138 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
140 git_SHA256_Final(hash, &ctx->sha256);
143 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
145 git_SHA256_Final(oid->hash, &ctx->sha256);
147 * This currently does nothing, so the compiler should optimize it out,
148 * but keep it in case we extend the hash size again.
150 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
151 oid->algo = GIT_HASH_SHA256;
154 static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
156 BUG("trying to init unknown hash");
159 static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
160 const git_hash_ctx *src UNUSED)
162 BUG("trying to clone unknown hash");
165 static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
166 const void *data UNUSED,
167 size_t len UNUSED)
169 BUG("trying to update unknown hash");
172 static void git_hash_unknown_final(unsigned char *hash UNUSED,
173 git_hash_ctx *ctx UNUSED)
175 BUG("trying to finalize unknown hash");
178 static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
179 git_hash_ctx *ctx UNUSED)
181 BUG("trying to finalize unknown hash");
184 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
186 .name = NULL,
187 .format_id = 0x00000000,
188 .rawsz = 0,
189 .hexsz = 0,
190 .blksz = 0,
191 .init_fn = git_hash_unknown_init,
192 .clone_fn = git_hash_unknown_clone,
193 .update_fn = git_hash_unknown_update,
194 .final_fn = git_hash_unknown_final,
195 .final_oid_fn = git_hash_unknown_final_oid,
196 .empty_tree = NULL,
197 .empty_blob = NULL,
198 .null_oid = NULL,
201 .name = "sha1",
202 .format_id = GIT_SHA1_FORMAT_ID,
203 .rawsz = GIT_SHA1_RAWSZ,
204 .hexsz = GIT_SHA1_HEXSZ,
205 .blksz = GIT_SHA1_BLKSZ,
206 .init_fn = git_hash_sha1_init,
207 .clone_fn = git_hash_sha1_clone,
208 .update_fn = git_hash_sha1_update,
209 .final_fn = git_hash_sha1_final,
210 .final_oid_fn = git_hash_sha1_final_oid,
211 .empty_tree = &empty_tree_oid,
212 .empty_blob = &empty_blob_oid,
213 .null_oid = &null_oid_sha1,
216 .name = "sha256",
217 .format_id = GIT_SHA256_FORMAT_ID,
218 .rawsz = GIT_SHA256_RAWSZ,
219 .hexsz = GIT_SHA256_HEXSZ,
220 .blksz = GIT_SHA256_BLKSZ,
221 .init_fn = git_hash_sha256_init,
222 .clone_fn = git_hash_sha256_clone,
223 .update_fn = git_hash_sha256_update,
224 .final_fn = git_hash_sha256_final,
225 .final_oid_fn = git_hash_sha256_final_oid,
226 .empty_tree = &empty_tree_oid_sha256,
227 .empty_blob = &empty_blob_oid_sha256,
228 .null_oid = &null_oid_sha256,
232 const struct object_id *null_oid(void)
234 return the_hash_algo->null_oid;
237 const char *empty_tree_oid_hex(void)
239 static char buf[GIT_MAX_HEXSZ + 1];
240 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
243 const char *empty_blob_oid_hex(void)
245 static char buf[GIT_MAX_HEXSZ + 1];
246 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
249 int hash_algo_by_name(const char *name)
251 int i;
252 if (!name)
253 return GIT_HASH_UNKNOWN;
254 for (i = 1; i < GIT_HASH_NALGOS; i++)
255 if (!strcmp(name, hash_algos[i].name))
256 return i;
257 return GIT_HASH_UNKNOWN;
260 int hash_algo_by_id(uint32_t format_id)
262 int i;
263 for (i = 1; i < GIT_HASH_NALGOS; i++)
264 if (format_id == hash_algos[i].format_id)
265 return i;
266 return GIT_HASH_UNKNOWN;
269 int hash_algo_by_length(int len)
271 int i;
272 for (i = 1; i < GIT_HASH_NALGOS; i++)
273 if (len == hash_algos[i].rawsz)
274 return i;
275 return GIT_HASH_UNKNOWN;
279 * This is meant to hold a *small* number of objects that you would
280 * want repo_read_object_file() to be able to return, but yet you do not want
281 * to write them into the object store (e.g. a browse-only
282 * application).
284 static struct cached_object {
285 struct object_id oid;
286 enum object_type type;
287 void *buf;
288 unsigned long size;
289 } *cached_objects;
290 static int cached_object_nr, cached_object_alloc;
292 static struct cached_object empty_tree = {
293 .oid = {
294 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
296 .type = OBJ_TREE,
297 .buf = "",
300 static struct cached_object *find_cached_object(const struct object_id *oid)
302 int i;
303 struct cached_object *co = cached_objects;
305 for (i = 0; i < cached_object_nr; i++, co++) {
306 if (oideq(&co->oid, oid))
307 return co;
309 if (oideq(oid, the_hash_algo->empty_tree))
310 return &empty_tree;
311 return NULL;
315 static int get_conv_flags(unsigned flags)
317 if (flags & HASH_RENORMALIZE)
318 return CONV_EOL_RENORMALIZE;
319 else if (flags & HASH_WRITE_OBJECT)
320 return global_conv_flags_eol | CONV_WRITE_OBJECT;
321 else
322 return 0;
326 int mkdir_in_gitdir(const char *path)
328 if (mkdir(path, 0777)) {
329 int saved_errno = errno;
330 struct stat st;
331 struct strbuf sb = STRBUF_INIT;
333 if (errno != EEXIST)
334 return -1;
336 * Are we looking at a path in a symlinked worktree
337 * whose original repository does not yet have it?
338 * e.g. .git/rr-cache pointing at its original
339 * repository in which the user hasn't performed any
340 * conflict resolution yet?
342 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
343 strbuf_readlink(&sb, path, st.st_size) ||
344 !is_absolute_path(sb.buf) ||
345 mkdir(sb.buf, 0777)) {
346 strbuf_release(&sb);
347 errno = saved_errno;
348 return -1;
350 strbuf_release(&sb);
352 return adjust_shared_perm(path);
355 static enum scld_error safe_create_leading_directories_1(char *path, int share)
357 char *next_component = path + offset_1st_component(path);
358 enum scld_error ret = SCLD_OK;
360 while (ret == SCLD_OK && next_component) {
361 struct stat st;
362 char *slash = next_component, slash_character;
364 while (*slash && !is_dir_sep(*slash))
365 slash++;
367 if (!*slash)
368 break;
370 next_component = slash + 1;
371 while (is_dir_sep(*next_component))
372 next_component++;
373 if (!*next_component)
374 break;
376 slash_character = *slash;
377 *slash = '\0';
378 if (!stat(path, &st)) {
379 /* path exists */
380 if (!S_ISDIR(st.st_mode)) {
381 errno = ENOTDIR;
382 ret = SCLD_EXISTS;
384 } else if (mkdir(path, 0777)) {
385 if (errno == EEXIST &&
386 !stat(path, &st) && S_ISDIR(st.st_mode))
387 ; /* somebody created it since we checked */
388 else if (errno == ENOENT)
390 * Either mkdir() failed because
391 * somebody just pruned the containing
392 * directory, or stat() failed because
393 * the file that was in our way was
394 * just removed. Either way, inform
395 * the caller that it might be worth
396 * trying again:
398 ret = SCLD_VANISHED;
399 else
400 ret = SCLD_FAILED;
401 } else if (share && adjust_shared_perm(path)) {
402 ret = SCLD_PERMS;
404 *slash = slash_character;
406 return ret;
409 enum scld_error safe_create_leading_directories(char *path)
411 return safe_create_leading_directories_1(path, 1);
414 enum scld_error safe_create_leading_directories_no_share(char *path)
416 return safe_create_leading_directories_1(path, 0);
419 enum scld_error safe_create_leading_directories_const(const char *path)
421 int save_errno;
422 /* path points to cache entries, so xstrdup before messing with it */
423 char *buf = xstrdup(path);
424 enum scld_error result = safe_create_leading_directories(buf);
426 save_errno = errno;
427 free(buf);
428 errno = save_errno;
429 return result;
432 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
434 int i;
435 for (i = 0; i < the_hash_algo->rawsz; i++) {
436 static char hex[] = "0123456789abcdef";
437 unsigned int val = oid->hash[i];
438 strbuf_addch(buf, hex[val >> 4]);
439 strbuf_addch(buf, hex[val & 0xf]);
440 if (!i)
441 strbuf_addch(buf, '/');
445 static const char *odb_loose_path(struct object_directory *odb,
446 struct strbuf *buf,
447 const struct object_id *oid)
449 strbuf_reset(buf);
450 strbuf_addstr(buf, odb->path);
451 strbuf_addch(buf, '/');
452 fill_loose_path(buf, oid);
453 return buf->buf;
456 const char *loose_object_path(struct repository *r, struct strbuf *buf,
457 const struct object_id *oid)
459 return odb_loose_path(r->objects->odb, buf, oid);
463 * Return non-zero iff the path is usable as an alternate object database.
465 static int alt_odb_usable(struct raw_object_store *o,
466 struct strbuf *path,
467 const char *normalized_objdir, khiter_t *pos)
469 int r;
471 /* Detect cases where alternate disappeared */
472 if (!is_directory(path->buf)) {
473 error(_("object directory %s does not exist; "
474 "check .git/objects/info/alternates"),
475 path->buf);
476 return 0;
480 * Prevent the common mistake of listing the same
481 * thing twice, or object directory itself.
483 if (!o->odb_by_path) {
484 khiter_t p;
486 o->odb_by_path = kh_init_odb_path_map();
487 assert(!o->odb->next);
488 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
489 assert(r == 1); /* never used */
490 kh_value(o->odb_by_path, p) = o->odb;
492 if (fspatheq(path->buf, normalized_objdir))
493 return 0;
494 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
495 /* r: 0 = exists, 1 = never used, 2 = deleted */
496 return r == 0 ? 0 : 1;
500 * Prepare alternate object database registry.
502 * The variable alt_odb_list points at the list of struct
503 * object_directory. The elements on this list come from
504 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
505 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
506 * whose contents is similar to that environment variable but can be
507 * LF separated. Its base points at a statically allocated buffer that
508 * contains "/the/directory/corresponding/to/.git/objects/...", while
509 * its name points just after the slash at the end of ".git/objects/"
510 * in the example above, and has enough space to hold all hex characters
511 * of the object ID, an extra slash for the first level indirection, and
512 * the terminating NUL.
514 static void read_info_alternates(struct repository *r,
515 const char *relative_base,
516 int depth);
517 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
518 const char *relative_base, int depth, const char *normalized_objdir)
520 struct object_directory *ent;
521 struct strbuf pathbuf = STRBUF_INIT;
522 struct strbuf tmp = STRBUF_INIT;
523 khiter_t pos;
524 int ret = -1;
526 if (!is_absolute_path(entry->buf) && relative_base) {
527 strbuf_realpath(&pathbuf, relative_base, 1);
528 strbuf_addch(&pathbuf, '/');
530 strbuf_addbuf(&pathbuf, entry);
532 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
533 error(_("unable to normalize alternate object path: %s"),
534 pathbuf.buf);
535 goto error;
537 strbuf_swap(&pathbuf, &tmp);
540 * The trailing slash after the directory name is given by
541 * this function at the end. Remove duplicates.
543 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
544 strbuf_setlen(&pathbuf, pathbuf.len - 1);
546 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
547 goto error;
549 CALLOC_ARRAY(ent, 1);
550 /* pathbuf.buf is already in r->objects->odb_by_path */
551 ent->path = strbuf_detach(&pathbuf, NULL);
553 /* add the alternate entry */
554 *r->objects->odb_tail = ent;
555 r->objects->odb_tail = &(ent->next);
556 ent->next = NULL;
557 assert(r->objects->odb_by_path);
558 kh_value(r->objects->odb_by_path, pos) = ent;
560 /* recursively add alternates */
561 read_info_alternates(r, ent->path, depth + 1);
562 ret = 0;
563 error:
564 strbuf_release(&tmp);
565 strbuf_release(&pathbuf);
566 return ret;
569 static const char *parse_alt_odb_entry(const char *string,
570 int sep,
571 struct strbuf *out)
573 const char *end;
575 strbuf_reset(out);
577 if (*string == '#') {
578 /* comment; consume up to next separator */
579 end = strchrnul(string, sep);
580 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
582 * quoted path; unquote_c_style has copied the
583 * data for us and set "end". Broken quoting (e.g.,
584 * an entry that doesn't end with a quote) falls
585 * back to the unquoted case below.
587 } else {
588 /* normal, unquoted path */
589 end = strchrnul(string, sep);
590 strbuf_add(out, string, end - string);
593 if (*end)
594 end++;
595 return end;
598 static void link_alt_odb_entries(struct repository *r, const char *alt,
599 int sep, const char *relative_base, int depth)
601 struct strbuf objdirbuf = STRBUF_INIT;
602 struct strbuf entry = STRBUF_INIT;
604 if (!alt || !*alt)
605 return;
607 if (depth > 5) {
608 error(_("%s: ignoring alternate object stores, nesting too deep"),
609 relative_base);
610 return;
613 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
615 while (*alt) {
616 alt = parse_alt_odb_entry(alt, sep, &entry);
617 if (!entry.len)
618 continue;
619 link_alt_odb_entry(r, &entry,
620 relative_base, depth, objdirbuf.buf);
622 strbuf_release(&entry);
623 strbuf_release(&objdirbuf);
626 static void read_info_alternates(struct repository *r,
627 const char *relative_base,
628 int depth)
630 char *path;
631 struct strbuf buf = STRBUF_INIT;
633 path = xstrfmt("%s/info/alternates", relative_base);
634 if (strbuf_read_file(&buf, path, 1024) < 0) {
635 warn_on_fopen_errors(path);
636 free(path);
637 return;
640 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
641 strbuf_release(&buf);
642 free(path);
645 void add_to_alternates_file(const char *reference)
647 struct lock_file lock = LOCK_INIT;
648 char *alts = git_pathdup("objects/info/alternates");
649 FILE *in, *out;
650 int found = 0;
652 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
653 out = fdopen_lock_file(&lock, "w");
654 if (!out)
655 die_errno(_("unable to fdopen alternates lockfile"));
657 in = fopen(alts, "r");
658 if (in) {
659 struct strbuf line = STRBUF_INIT;
661 while (strbuf_getline(&line, in) != EOF) {
662 if (!strcmp(reference, line.buf)) {
663 found = 1;
664 break;
666 fprintf_or_die(out, "%s\n", line.buf);
669 strbuf_release(&line);
670 fclose(in);
672 else if (errno != ENOENT)
673 die_errno(_("unable to read alternates file"));
675 if (found) {
676 rollback_lock_file(&lock);
677 } else {
678 fprintf_or_die(out, "%s\n", reference);
679 if (commit_lock_file(&lock))
680 die_errno(_("unable to move new alternates file into place"));
681 if (the_repository->objects->loaded_alternates)
682 link_alt_odb_entries(the_repository, reference,
683 '\n', NULL, 0);
685 free(alts);
688 void add_to_alternates_memory(const char *reference)
691 * Make sure alternates are initialized, or else our entry may be
692 * overwritten when they are.
694 prepare_alt_odb(the_repository);
696 link_alt_odb_entries(the_repository, reference,
697 '\n', NULL, 0);
700 struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
702 struct object_directory *new_odb;
705 * Make sure alternates are initialized, or else our entry may be
706 * overwritten when they are.
708 prepare_alt_odb(the_repository);
711 * Make a new primary odb and link the old primary ODB in as an
712 * alternate
714 new_odb = xcalloc(1, sizeof(*new_odb));
715 new_odb->path = xstrdup(dir);
718 * Disable ref updates while a temporary odb is active, since
719 * the objects in the database may roll back.
721 new_odb->disable_ref_updates = 1;
722 new_odb->will_destroy = will_destroy;
723 new_odb->next = the_repository->objects->odb;
724 the_repository->objects->odb = new_odb;
725 return new_odb->next;
728 void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
730 struct object_directory *cur_odb = the_repository->objects->odb;
732 if (strcmp(old_path, cur_odb->path))
733 BUG("expected %s as primary object store; found %s",
734 old_path, cur_odb->path);
736 if (cur_odb->next != restore_odb)
737 BUG("we expect the old primary object store to be the first alternate");
739 the_repository->objects->odb = restore_odb;
740 free_object_directory(cur_odb);
744 * Compute the exact path an alternate is at and returns it. In case of
745 * error NULL is returned and the human readable error is added to `err`
746 * `path` may be relative and should point to $GIT_DIR.
747 * `err` must not be null.
749 char *compute_alternate_path(const char *path, struct strbuf *err)
751 char *ref_git = NULL;
752 const char *repo;
753 int seen_error = 0;
755 ref_git = real_pathdup(path, 0);
756 if (!ref_git) {
757 seen_error = 1;
758 strbuf_addf(err, _("path '%s' does not exist"), path);
759 goto out;
762 repo = read_gitfile(ref_git);
763 if (!repo)
764 repo = read_gitfile(mkpath("%s/.git", ref_git));
765 if (repo) {
766 free(ref_git);
767 ref_git = xstrdup(repo);
770 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
771 char *ref_git_git = mkpathdup("%s/.git", ref_git);
772 free(ref_git);
773 ref_git = ref_git_git;
774 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
775 struct strbuf sb = STRBUF_INIT;
776 seen_error = 1;
777 if (get_common_dir(&sb, ref_git)) {
778 strbuf_addf(err,
779 _("reference repository '%s' as a linked "
780 "checkout is not supported yet."),
781 path);
782 goto out;
785 strbuf_addf(err, _("reference repository '%s' is not a "
786 "local repository."), path);
787 goto out;
790 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
791 strbuf_addf(err, _("reference repository '%s' is shallow"),
792 path);
793 seen_error = 1;
794 goto out;
797 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
798 strbuf_addf(err,
799 _("reference repository '%s' is grafted"),
800 path);
801 seen_error = 1;
802 goto out;
805 out:
806 if (seen_error) {
807 FREE_AND_NULL(ref_git);
810 return ref_git;
813 struct object_directory *find_odb(struct repository *r, const char *obj_dir)
815 struct object_directory *odb;
816 char *obj_dir_real = real_pathdup(obj_dir, 1);
817 struct strbuf odb_path_real = STRBUF_INIT;
819 prepare_alt_odb(r);
820 for (odb = r->objects->odb; odb; odb = odb->next) {
821 strbuf_realpath(&odb_path_real, odb->path, 1);
822 if (!strcmp(obj_dir_real, odb_path_real.buf))
823 break;
826 free(obj_dir_real);
827 strbuf_release(&odb_path_real);
829 if (!odb)
830 die(_("could not find object directory matching %s"), obj_dir);
831 return odb;
834 static void fill_alternate_refs_command(struct child_process *cmd,
835 const char *repo_path)
837 const char *value;
839 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
840 cmd->use_shell = 1;
842 strvec_push(&cmd->args, value);
843 strvec_push(&cmd->args, repo_path);
844 } else {
845 cmd->git_cmd = 1;
847 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
848 strvec_push(&cmd->args, "for-each-ref");
849 strvec_push(&cmd->args, "--format=%(objectname)");
851 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
852 strvec_push(&cmd->args, "--");
853 strvec_split(&cmd->args, value);
857 strvec_pushv(&cmd->env, (const char **)local_repo_env);
858 cmd->out = -1;
861 static void read_alternate_refs(const char *path,
862 alternate_ref_fn *cb,
863 void *data)
865 struct child_process cmd = CHILD_PROCESS_INIT;
866 struct strbuf line = STRBUF_INIT;
867 FILE *fh;
869 fill_alternate_refs_command(&cmd, path);
871 if (start_command(&cmd))
872 return;
874 fh = xfdopen(cmd.out, "r");
875 while (strbuf_getline_lf(&line, fh) != EOF) {
876 struct object_id oid;
877 const char *p;
879 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
880 warning(_("invalid line while parsing alternate refs: %s"),
881 line.buf);
882 break;
885 cb(&oid, data);
888 fclose(fh);
889 finish_command(&cmd);
890 strbuf_release(&line);
893 struct alternate_refs_data {
894 alternate_ref_fn *fn;
895 void *data;
898 static int refs_from_alternate_cb(struct object_directory *e,
899 void *data)
901 struct strbuf path = STRBUF_INIT;
902 size_t base_len;
903 struct alternate_refs_data *cb = data;
905 if (!strbuf_realpath(&path, e->path, 0))
906 goto out;
907 if (!strbuf_strip_suffix(&path, "/objects"))
908 goto out;
909 base_len = path.len;
911 /* Is this a git repository with refs? */
912 strbuf_addstr(&path, "/refs");
913 if (!is_directory(path.buf))
914 goto out;
915 strbuf_setlen(&path, base_len);
917 read_alternate_refs(path.buf, cb->fn, cb->data);
919 out:
920 strbuf_release(&path);
921 return 0;
924 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
926 struct alternate_refs_data cb;
927 cb.fn = fn;
928 cb.data = data;
929 foreach_alt_odb(refs_from_alternate_cb, &cb);
932 int foreach_alt_odb(alt_odb_fn fn, void *cb)
934 struct object_directory *ent;
935 int r = 0;
937 prepare_alt_odb(the_repository);
938 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
939 r = fn(ent, cb);
940 if (r)
941 break;
943 return r;
946 void prepare_alt_odb(struct repository *r)
948 if (r->objects->loaded_alternates)
949 return;
951 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
953 read_info_alternates(r, r->objects->odb->path, 0);
954 r->objects->loaded_alternates = 1;
957 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
958 static int freshen_file(const char *fn)
960 return !utime(fn, NULL);
964 * All of the check_and_freshen functions return 1 if the file exists and was
965 * freshened (if freshening was requested), 0 otherwise. If they return
966 * 0, you should not assume that it is safe to skip a write of the object (it
967 * either does not exist on disk, or has a stale mtime and may be subject to
968 * pruning).
970 int check_and_freshen_file(const char *fn, int freshen)
972 if (access(fn, F_OK))
973 return 0;
974 if (freshen && !freshen_file(fn))
975 return 0;
976 return 1;
979 static int check_and_freshen_odb(struct object_directory *odb,
980 const struct object_id *oid,
981 int freshen)
983 static struct strbuf path = STRBUF_INIT;
984 odb_loose_path(odb, &path, oid);
985 return check_and_freshen_file(path.buf, freshen);
988 static int check_and_freshen_local(const struct object_id *oid, int freshen)
990 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
993 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
995 struct object_directory *odb;
997 prepare_alt_odb(the_repository);
998 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
999 if (check_and_freshen_odb(odb, oid, freshen))
1000 return 1;
1002 return 0;
1005 static int check_and_freshen(const struct object_id *oid, int freshen)
1007 return check_and_freshen_local(oid, freshen) ||
1008 check_and_freshen_nonlocal(oid, freshen);
1011 int has_loose_object_nonlocal(const struct object_id *oid)
1013 return check_and_freshen_nonlocal(oid, 0);
1016 int has_loose_object(const struct object_id *oid)
1018 return check_and_freshen(oid, 0);
1021 static void mmap_limit_check(size_t length)
1023 static size_t limit = 0;
1024 if (!limit) {
1025 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1026 if (!limit)
1027 limit = SIZE_MAX;
1029 if (length > limit)
1030 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1031 (uintmax_t)length, (uintmax_t)limit);
1034 void *xmmap_gently(void *start, size_t length,
1035 int prot, int flags, int fd, off_t offset)
1037 void *ret;
1039 mmap_limit_check(length);
1040 ret = mmap(start, length, prot, flags, fd, offset);
1041 if (ret == MAP_FAILED && !length)
1042 ret = NULL;
1043 return ret;
1046 const char *mmap_os_err(void)
1048 static const char blank[] = "";
1049 #if defined(__linux__)
1050 if (errno == ENOMEM) {
1051 /* this continues an existing error message: */
1052 static const char enomem[] =
1053 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1054 return enomem;
1056 #endif /* OS-specific bits */
1057 return blank;
1060 void *xmmap(void *start, size_t length,
1061 int prot, int flags, int fd, off_t offset)
1063 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1064 if (ret == MAP_FAILED)
1065 die_errno(_("mmap failed%s"), mmap_os_err());
1066 return ret;
1069 static int format_object_header_literally(char *str, size_t size,
1070 const char *type, size_t objsize)
1072 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1075 int format_object_header(char *str, size_t size, enum object_type type,
1076 size_t objsize)
1078 const char *name = type_name(type);
1080 if (!name)
1081 BUG("could not get a type name for 'enum object_type' value %d", type);
1083 return format_object_header_literally(str, size, name, objsize);
1086 int check_object_signature(struct repository *r, const struct object_id *oid,
1087 void *buf, unsigned long size,
1088 enum object_type type)
1090 struct object_id real_oid;
1092 hash_object_file(r->hash_algo, buf, size, type, &real_oid);
1094 return !oideq(oid, &real_oid) ? -1 : 0;
1097 int stream_object_signature(struct repository *r, const struct object_id *oid)
1099 struct object_id real_oid;
1100 unsigned long size;
1101 enum object_type obj_type;
1102 struct git_istream *st;
1103 git_hash_ctx c;
1104 char hdr[MAX_HEADER_LEN];
1105 int hdrlen;
1107 st = open_istream(r, oid, &obj_type, &size, NULL);
1108 if (!st)
1109 return -1;
1111 /* Generate the header */
1112 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
1114 /* Sha1.. */
1115 r->hash_algo->init_fn(&c);
1116 r->hash_algo->update_fn(&c, hdr, hdrlen);
1117 for (;;) {
1118 char buf[1024 * 16];
1119 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1121 if (readlen < 0) {
1122 close_istream(st);
1123 return -1;
1125 if (!readlen)
1126 break;
1127 r->hash_algo->update_fn(&c, buf, readlen);
1129 r->hash_algo->final_oid_fn(&real_oid, &c);
1130 close_istream(st);
1131 return !oideq(oid, &real_oid) ? -1 : 0;
1134 int git_open_cloexec(const char *name, int flags)
1136 int fd;
1137 static int o_cloexec = O_CLOEXEC;
1139 fd = open(name, flags | o_cloexec);
1140 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1141 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1142 o_cloexec &= ~O_CLOEXEC;
1143 fd = open(name, flags | o_cloexec);
1146 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1148 static int fd_cloexec = FD_CLOEXEC;
1150 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1151 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1152 int flags = fcntl(fd, F_GETFD);
1153 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1154 fd_cloexec = 0;
1157 #endif
1158 return fd;
1162 * Find "oid" as a loose object in the local repository or in an alternate.
1163 * Returns 0 on success, negative on failure.
1165 * The "path" out-parameter will give the path of the object we found (if any).
1166 * Note that it may point to static storage and is only valid until another
1167 * call to stat_loose_object().
1169 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1170 struct stat *st, const char **path)
1172 struct object_directory *odb;
1173 static struct strbuf buf = STRBUF_INIT;
1175 prepare_alt_odb(r);
1176 for (odb = r->objects->odb; odb; odb = odb->next) {
1177 *path = odb_loose_path(odb, &buf, oid);
1178 if (!lstat(*path, st))
1179 return 0;
1182 return -1;
1186 * Like stat_loose_object(), but actually open the object and return the
1187 * descriptor. See the caveats on the "path" parameter above.
1189 static int open_loose_object(struct repository *r,
1190 const struct object_id *oid, const char **path)
1192 int fd;
1193 struct object_directory *odb;
1194 int most_interesting_errno = ENOENT;
1195 static struct strbuf buf = STRBUF_INIT;
1197 prepare_alt_odb(r);
1198 for (odb = r->objects->odb; odb; odb = odb->next) {
1199 *path = odb_loose_path(odb, &buf, oid);
1200 fd = git_open(*path);
1201 if (fd >= 0)
1202 return fd;
1204 if (most_interesting_errno == ENOENT)
1205 most_interesting_errno = errno;
1207 errno = most_interesting_errno;
1208 return -1;
1211 static int quick_has_loose(struct repository *r,
1212 const struct object_id *oid)
1214 struct object_directory *odb;
1216 prepare_alt_odb(r);
1217 for (odb = r->objects->odb; odb; odb = odb->next) {
1218 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1219 return 1;
1221 return 0;
1225 * Map and close the given loose object fd. The path argument is used for
1226 * error reporting.
1228 static void *map_fd(int fd, const char *path, unsigned long *size)
1230 void *map = NULL;
1231 struct stat st;
1233 if (!fstat(fd, &st)) {
1234 *size = xsize_t(st.st_size);
1235 if (!*size) {
1236 /* mmap() is forbidden on empty files */
1237 error(_("object file %s is empty"), path);
1238 close(fd);
1239 return NULL;
1241 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1243 close(fd);
1244 return map;
1247 void *map_loose_object(struct repository *r,
1248 const struct object_id *oid,
1249 unsigned long *size)
1251 const char *p;
1252 int fd = open_loose_object(r, oid, &p);
1254 if (fd < 0)
1255 return NULL;
1256 return map_fd(fd, p, size);
1259 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1260 unsigned char *map,
1261 unsigned long mapsize,
1262 void *buffer,
1263 unsigned long bufsiz,
1264 struct strbuf *header)
1266 int status;
1268 /* Get the data stream */
1269 memset(stream, 0, sizeof(*stream));
1270 stream->next_in = map;
1271 stream->avail_in = mapsize;
1272 stream->next_out = buffer;
1273 stream->avail_out = bufsiz;
1275 git_inflate_init(stream);
1276 obj_read_unlock();
1277 status = git_inflate(stream, 0);
1278 obj_read_lock();
1279 if (status < Z_OK)
1280 return ULHR_BAD;
1283 * Check if entire header is unpacked in the first iteration.
1285 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1286 return ULHR_OK;
1289 * We have a header longer than MAX_HEADER_LEN. The "header"
1290 * here is only non-NULL when we run "cat-file
1291 * --allow-unknown-type".
1293 if (!header)
1294 return ULHR_TOO_LONG;
1297 * buffer[0..bufsiz] was not large enough. Copy the partial
1298 * result out to header, and then append the result of further
1299 * reading the stream.
1301 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1302 stream->next_out = buffer;
1303 stream->avail_out = bufsiz;
1305 do {
1306 obj_read_unlock();
1307 status = git_inflate(stream, 0);
1308 obj_read_lock();
1309 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1310 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1311 return 0;
1312 stream->next_out = buffer;
1313 stream->avail_out = bufsiz;
1314 } while (status != Z_STREAM_END);
1315 return ULHR_TOO_LONG;
1318 static void *unpack_loose_rest(git_zstream *stream,
1319 void *buffer, unsigned long size,
1320 const struct object_id *oid)
1322 int bytes = strlen(buffer) + 1;
1323 unsigned char *buf = xmallocz(size);
1324 unsigned long n;
1325 int status = Z_OK;
1327 n = stream->total_out - bytes;
1328 if (n > size)
1329 n = size;
1330 memcpy(buf, (char *) buffer + bytes, n);
1331 bytes = n;
1332 if (bytes <= size) {
1334 * The above condition must be (bytes <= size), not
1335 * (bytes < size). In other words, even though we
1336 * expect no more output and set avail_out to zero,
1337 * the input zlib stream may have bytes that express
1338 * "this concludes the stream", and we *do* want to
1339 * eat that input.
1341 * Otherwise we would not be able to test that we
1342 * consumed all the input to reach the expected size;
1343 * we also want to check that zlib tells us that all
1344 * went well with status == Z_STREAM_END at the end.
1346 stream->next_out = buf + bytes;
1347 stream->avail_out = size - bytes;
1348 while (status == Z_OK) {
1349 obj_read_unlock();
1350 status = git_inflate(stream, Z_FINISH);
1351 obj_read_lock();
1354 if (status == Z_STREAM_END && !stream->avail_in) {
1355 git_inflate_end(stream);
1356 return buf;
1359 if (status < 0)
1360 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1361 else if (stream->avail_in)
1362 error(_("garbage at end of loose object '%s'"),
1363 oid_to_hex(oid));
1364 free(buf);
1365 return NULL;
1369 * We used to just use "sscanf()", but that's actually way
1370 * too permissive for what we want to check. So do an anal
1371 * object header parse by hand.
1373 int parse_loose_header(const char *hdr, struct object_info *oi)
1375 const char *type_buf = hdr;
1376 size_t size;
1377 int type, type_len = 0;
1380 * The type can be of any size but is followed by
1381 * a space.
1383 for (;;) {
1384 char c = *hdr++;
1385 if (!c)
1386 return -1;
1387 if (c == ' ')
1388 break;
1389 type_len++;
1392 type = type_from_string_gently(type_buf, type_len, 1);
1393 if (oi->type_name)
1394 strbuf_add(oi->type_name, type_buf, type_len);
1395 if (oi->typep)
1396 *oi->typep = type;
1399 * The length must follow immediately, and be in canonical
1400 * decimal format (ie "010" is not valid).
1402 size = *hdr++ - '0';
1403 if (size > 9)
1404 return -1;
1405 if (size) {
1406 for (;;) {
1407 unsigned long c = *hdr - '0';
1408 if (c > 9)
1409 break;
1410 hdr++;
1411 size = st_add(st_mult(size, 10), c);
1415 if (oi->sizep)
1416 *oi->sizep = cast_size_t_to_ulong(size);
1419 * The length must be followed by a zero byte
1421 if (*hdr)
1422 return -1;
1425 * The format is valid, but the type may still be bogus. The
1426 * Caller needs to check its oi->typep.
1428 return 0;
1431 static int loose_object_info(struct repository *r,
1432 const struct object_id *oid,
1433 struct object_info *oi, int flags)
1435 int status = 0;
1436 int fd;
1437 unsigned long mapsize;
1438 const char *path;
1439 void *map;
1440 git_zstream stream;
1441 char hdr[MAX_HEADER_LEN];
1442 struct strbuf hdrbuf = STRBUF_INIT;
1443 unsigned long size_scratch;
1444 enum object_type type_scratch;
1445 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
1447 if (oi->delta_base_oid)
1448 oidclr(oi->delta_base_oid);
1451 * If we don't care about type or size, then we don't
1452 * need to look inside the object at all. Note that we
1453 * do not optimize out the stat call, even if the
1454 * caller doesn't care about the disk-size, since our
1455 * return value implicitly indicates whether the
1456 * object even exists.
1458 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1459 struct stat st;
1460 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1461 return quick_has_loose(r, oid) ? 0 : -1;
1462 if (stat_loose_object(r, oid, &st, &path) < 0)
1463 return -1;
1464 if (oi->disk_sizep)
1465 *oi->disk_sizep = st.st_size;
1466 return 0;
1469 fd = open_loose_object(r, oid, &path);
1470 if (fd < 0) {
1471 if (errno != ENOENT)
1472 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1473 return -1;
1475 map = map_fd(fd, path, &mapsize);
1476 if (!map)
1477 return -1;
1479 if (!oi->sizep)
1480 oi->sizep = &size_scratch;
1481 if (!oi->typep)
1482 oi->typep = &type_scratch;
1484 if (oi->disk_sizep)
1485 *oi->disk_sizep = mapsize;
1487 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1488 allow_unknown ? &hdrbuf : NULL)) {
1489 case ULHR_OK:
1490 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1491 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1492 else if (!allow_unknown && *oi->typep < 0)
1493 die(_("invalid object type"));
1495 if (!oi->contentp)
1496 break;
1497 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1498 if (*oi->contentp)
1499 goto cleanup;
1501 status = -1;
1502 break;
1503 case ULHR_BAD:
1504 status = error(_("unable to unpack %s header"),
1505 oid_to_hex(oid));
1506 break;
1507 case ULHR_TOO_LONG:
1508 status = error(_("header for %s too long, exceeds %d bytes"),
1509 oid_to_hex(oid), MAX_HEADER_LEN);
1510 break;
1513 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1514 die(_("loose object %s (stored in %s) is corrupt"),
1515 oid_to_hex(oid), path);
1517 git_inflate_end(&stream);
1518 cleanup:
1519 munmap(map, mapsize);
1520 if (oi->sizep == &size_scratch)
1521 oi->sizep = NULL;
1522 strbuf_release(&hdrbuf);
1523 if (oi->typep == &type_scratch)
1524 oi->typep = NULL;
1525 oi->whence = OI_LOOSE;
1526 return status;
1529 int obj_read_use_lock = 0;
1530 pthread_mutex_t obj_read_mutex;
1532 void enable_obj_read_lock(void)
1534 if (obj_read_use_lock)
1535 return;
1537 obj_read_use_lock = 1;
1538 init_recursive_mutex(&obj_read_mutex);
1541 void disable_obj_read_lock(void)
1543 if (!obj_read_use_lock)
1544 return;
1546 obj_read_use_lock = 0;
1547 pthread_mutex_destroy(&obj_read_mutex);
1550 int fetch_if_missing = 1;
1552 static int do_oid_object_info_extended(struct repository *r,
1553 const struct object_id *oid,
1554 struct object_info *oi, unsigned flags)
1556 static struct object_info blank_oi = OBJECT_INFO_INIT;
1557 struct cached_object *co;
1558 struct pack_entry e;
1559 int rtype;
1560 const struct object_id *real = oid;
1561 int already_retried = 0;
1564 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1565 real = lookup_replace_object(r, oid);
1567 if (is_null_oid(real))
1568 return -1;
1570 if (!oi)
1571 oi = &blank_oi;
1573 co = find_cached_object(real);
1574 if (co) {
1575 if (oi->typep)
1576 *(oi->typep) = co->type;
1577 if (oi->sizep)
1578 *(oi->sizep) = co->size;
1579 if (oi->disk_sizep)
1580 *(oi->disk_sizep) = 0;
1581 if (oi->delta_base_oid)
1582 oidclr(oi->delta_base_oid);
1583 if (oi->type_name)
1584 strbuf_addstr(oi->type_name, type_name(co->type));
1585 if (oi->contentp)
1586 *oi->contentp = xmemdupz(co->buf, co->size);
1587 oi->whence = OI_CACHED;
1588 return 0;
1591 while (1) {
1592 if (find_pack_entry(r, real, &e))
1593 break;
1595 /* Most likely it's a loose object. */
1596 if (!loose_object_info(r, real, oi, flags))
1597 return 0;
1599 /* Not a loose object; someone else may have just packed it. */
1600 if (!(flags & OBJECT_INFO_QUICK)) {
1601 reprepare_packed_git(r);
1602 if (find_pack_entry(r, real, &e))
1603 break;
1607 * If r is the_repository, this might be an attempt at
1608 * accessing a submodule object as if it were in the_repository
1609 * (having called add_submodule_odb() on that submodule's ODB).
1610 * If any such ODBs exist, register them and try again.
1612 if (r == the_repository &&
1613 register_all_submodule_odb_as_alternates())
1614 /* We added some alternates; retry */
1615 continue;
1617 /* Check if it is a missing object */
1618 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1619 !already_retried &&
1620 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1621 promisor_remote_get_direct(r, real, 1);
1622 already_retried = 1;
1623 continue;
1626 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1627 const struct packed_git *p;
1628 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1629 die(_("replacement %s not found for %s"),
1630 oid_to_hex(real), oid_to_hex(oid));
1631 if ((p = has_packed_and_bad(r, real)))
1632 die(_("packed object %s (stored in %s) is corrupt"),
1633 oid_to_hex(real), p->pack_name);
1635 return -1;
1638 if (oi == &blank_oi)
1640 * We know that the caller doesn't actually need the
1641 * information below, so return early.
1643 return 0;
1644 rtype = packed_object_info(r, e.p, e.offset, oi);
1645 if (rtype < 0) {
1646 mark_bad_packed_object(e.p, real);
1647 return do_oid_object_info_extended(r, real, oi, 0);
1648 } else if (oi->whence == OI_PACKED) {
1649 oi->u.packed.offset = e.offset;
1650 oi->u.packed.pack = e.p;
1651 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1652 rtype == OBJ_OFS_DELTA);
1655 return 0;
1658 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1659 struct object_info *oi, unsigned flags)
1661 int ret;
1662 obj_read_lock();
1663 ret = do_oid_object_info_extended(r, oid, oi, flags);
1664 obj_read_unlock();
1665 return ret;
1669 /* returns enum object_type or negative */
1670 int oid_object_info(struct repository *r,
1671 const struct object_id *oid,
1672 unsigned long *sizep)
1674 enum object_type type;
1675 struct object_info oi = OBJECT_INFO_INIT;
1677 oi.typep = &type;
1678 oi.sizep = sizep;
1679 if (oid_object_info_extended(r, oid, &oi,
1680 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1681 return -1;
1682 return type;
1685 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1686 struct object_id *oid)
1688 struct cached_object *co;
1690 hash_object_file(the_hash_algo, buf, len, type, oid);
1691 if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1692 find_cached_object(oid))
1693 return 0;
1694 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1695 co = &cached_objects[cached_object_nr++];
1696 co->size = len;
1697 co->type = type;
1698 co->buf = xmalloc(len);
1699 memcpy(co->buf, buf, len);
1700 oidcpy(&co->oid, oid);
1701 return 0;
1705 * This function dies on corrupt objects; the callers who want to
1706 * deal with them should arrange to call oid_object_info_extended() and give
1707 * error messages themselves.
1709 void *repo_read_object_file(struct repository *r,
1710 const struct object_id *oid,
1711 enum object_type *type,
1712 unsigned long *size)
1714 struct object_info oi = OBJECT_INFO_INIT;
1715 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
1716 void *data;
1718 oi.typep = type;
1719 oi.sizep = size;
1720 oi.contentp = &data;
1721 if (oid_object_info_extended(r, oid, &oi, flags))
1722 return NULL;
1724 return data;
1727 void *read_object_with_reference(struct repository *r,
1728 const struct object_id *oid,
1729 enum object_type required_type,
1730 unsigned long *size,
1731 struct object_id *actual_oid_return)
1733 enum object_type type;
1734 void *buffer;
1735 unsigned long isize;
1736 struct object_id actual_oid;
1738 oidcpy(&actual_oid, oid);
1739 while (1) {
1740 int ref_length = -1;
1741 const char *ref_type = NULL;
1743 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1744 if (!buffer)
1745 return NULL;
1746 if (type == required_type) {
1747 *size = isize;
1748 if (actual_oid_return)
1749 oidcpy(actual_oid_return, &actual_oid);
1750 return buffer;
1752 /* Handle references */
1753 else if (type == OBJ_COMMIT)
1754 ref_type = "tree ";
1755 else if (type == OBJ_TAG)
1756 ref_type = "object ";
1757 else {
1758 free(buffer);
1759 return NULL;
1761 ref_length = strlen(ref_type);
1763 if (ref_length + the_hash_algo->hexsz > isize ||
1764 memcmp(buffer, ref_type, ref_length) ||
1765 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1766 free(buffer);
1767 return NULL;
1769 free(buffer);
1770 /* Now we have the ID of the referred-to object in
1771 * actual_oid. Check again. */
1775 static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1776 const void *buf, unsigned long len,
1777 struct object_id *oid,
1778 char *hdr, int *hdrlen)
1780 algo->init_fn(c);
1781 algo->update_fn(c, hdr, *hdrlen);
1782 algo->update_fn(c, buf, len);
1783 algo->final_oid_fn(oid, c);
1786 static void write_object_file_prepare(const struct git_hash_algo *algo,
1787 const void *buf, unsigned long len,
1788 enum object_type type, struct object_id *oid,
1789 char *hdr, int *hdrlen)
1791 git_hash_ctx c;
1793 /* Generate the header */
1794 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
1796 /* Sha1.. */
1797 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1800 static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1801 const void *buf, unsigned long len,
1802 const char *type, struct object_id *oid,
1803 char *hdr, int *hdrlen)
1805 git_hash_ctx c;
1807 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1808 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1812 * Move the just written object into its final resting place.
1814 int finalize_object_file(const char *tmpfile, const char *filename)
1816 int ret = 0;
1818 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1819 goto try_rename;
1820 else if (link(tmpfile, filename))
1821 ret = errno;
1824 * Coda hack - coda doesn't like cross-directory links,
1825 * so we fall back to a rename, which will mean that it
1826 * won't be able to check collisions, but that's not a
1827 * big deal.
1829 * The same holds for FAT formatted media.
1831 * When this succeeds, we just return. We have nothing
1832 * left to unlink.
1834 if (ret && ret != EEXIST) {
1835 try_rename:
1836 if (!rename(tmpfile, filename))
1837 goto out;
1838 ret = errno;
1840 unlink_or_warn(tmpfile);
1841 if (ret) {
1842 if (ret != EEXIST) {
1843 return error_errno(_("unable to write file %s"), filename);
1845 /* FIXME!!! Collision check here ? */
1848 out:
1849 if (adjust_shared_perm(filename))
1850 return error(_("unable to set permission to '%s'"), filename);
1851 return 0;
1854 static void hash_object_file_literally(const struct git_hash_algo *algo,
1855 const void *buf, unsigned long len,
1856 const char *type, struct object_id *oid)
1858 char hdr[MAX_HEADER_LEN];
1859 int hdrlen = sizeof(hdr);
1861 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
1864 void hash_object_file(const struct git_hash_algo *algo, const void *buf,
1865 unsigned long len, enum object_type type,
1866 struct object_id *oid)
1868 hash_object_file_literally(algo, buf, len, type_name(type), oid);
1871 /* Finalize a file on disk, and close it. */
1872 static void close_loose_object(int fd, const char *filename)
1874 if (the_repository->objects->odb->will_destroy)
1875 goto out;
1877 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
1878 fsync_loose_object_bulk_checkin(fd, filename);
1879 else if (fsync_object_files > 0)
1880 fsync_or_die(fd, filename);
1881 else
1882 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
1883 filename);
1885 out:
1886 if (close(fd) != 0)
1887 die_errno(_("error when closing loose object file"));
1890 /* Size of directory component, including the ending '/' */
1891 static inline int directory_size(const char *filename)
1893 const char *s = strrchr(filename, '/');
1894 if (!s)
1895 return 0;
1896 return s - filename + 1;
1900 * This creates a temporary file in the same directory as the final
1901 * 'filename'
1903 * We want to avoid cross-directory filename renames, because those
1904 * can have problems on various filesystems (FAT, NFS, Coda).
1906 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1908 int fd, dirlen = directory_size(filename);
1910 strbuf_reset(tmp);
1911 strbuf_add(tmp, filename, dirlen);
1912 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1913 fd = git_mkstemp_mode(tmp->buf, 0444);
1914 if (fd < 0 && dirlen && errno == ENOENT) {
1916 * Make sure the directory exists; note that the contents
1917 * of the buffer are undefined after mkstemp returns an
1918 * error, so we have to rewrite the whole buffer from
1919 * scratch.
1921 strbuf_reset(tmp);
1922 strbuf_add(tmp, filename, dirlen - 1);
1923 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1924 return -1;
1925 if (adjust_shared_perm(tmp->buf))
1926 return -1;
1928 /* Try again */
1929 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1930 fd = git_mkstemp_mode(tmp->buf, 0444);
1932 return fd;
1936 * Common steps for loose object writers to start writing loose
1937 * objects:
1939 * - Create tmpfile for the loose object.
1940 * - Setup zlib stream for compression.
1941 * - Start to feed header to zlib stream.
1943 * Returns a "fd", which should later be provided to
1944 * end_loose_object_common().
1946 static int start_loose_object_common(struct strbuf *tmp_file,
1947 const char *filename, unsigned flags,
1948 git_zstream *stream,
1949 unsigned char *buf, size_t buflen,
1950 git_hash_ctx *c,
1951 char *hdr, int hdrlen)
1953 int fd;
1955 fd = create_tmpfile(tmp_file, filename);
1956 if (fd < 0) {
1957 if (flags & HASH_SILENT)
1958 return -1;
1959 else if (errno == EACCES)
1960 return error(_("insufficient permission for adding "
1961 "an object to repository database %s"),
1962 get_object_directory());
1963 else
1964 return error_errno(
1965 _("unable to create temporary file"));
1968 /* Setup zlib stream for compression */
1969 git_deflate_init(stream, zlib_compression_level);
1970 stream->next_out = buf;
1971 stream->avail_out = buflen;
1972 the_hash_algo->init_fn(c);
1974 /* Start to feed header to zlib stream */
1975 stream->next_in = (unsigned char *)hdr;
1976 stream->avail_in = hdrlen;
1977 while (git_deflate(stream, 0) == Z_OK)
1978 ; /* nothing */
1979 the_hash_algo->update_fn(c, hdr, hdrlen);
1981 return fd;
1985 * Common steps for the inner git_deflate() loop for writing loose
1986 * objects. Returns what git_deflate() returns.
1988 static int write_loose_object_common(git_hash_ctx *c,
1989 git_zstream *stream, const int flush,
1990 unsigned char *in0, const int fd,
1991 unsigned char *compressed,
1992 const size_t compressed_len)
1994 int ret;
1996 ret = git_deflate(stream, flush ? Z_FINISH : 0);
1997 the_hash_algo->update_fn(c, in0, stream->next_in - in0);
1998 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
1999 die_errno(_("unable to write loose object file"));
2000 stream->next_out = compressed;
2001 stream->avail_out = compressed_len;
2003 return ret;
2007 * Common steps for loose object writers to end writing loose objects:
2009 * - End the compression of zlib stream.
2010 * - Get the calculated oid to "oid".
2012 static int end_loose_object_common(git_hash_ctx *c, git_zstream *stream,
2013 struct object_id *oid)
2015 int ret;
2017 ret = git_deflate_end_gently(stream);
2018 if (ret != Z_OK)
2019 return ret;
2020 the_hash_algo->final_oid_fn(oid, c);
2022 return Z_OK;
2025 static int write_loose_object(const struct object_id *oid, char *hdr,
2026 int hdrlen, const void *buf, unsigned long len,
2027 time_t mtime, unsigned flags)
2029 int fd, ret;
2030 unsigned char compressed[4096];
2031 git_zstream stream;
2032 git_hash_ctx c;
2033 struct object_id parano_oid;
2034 static struct strbuf tmp_file = STRBUF_INIT;
2035 static struct strbuf filename = STRBUF_INIT;
2037 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2038 prepare_loose_object_bulk_checkin();
2040 loose_object_path(the_repository, &filename, oid);
2042 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2043 &stream, compressed, sizeof(compressed),
2044 &c, hdr, hdrlen);
2045 if (fd < 0)
2046 return -1;
2048 /* Then the data itself.. */
2049 stream.next_in = (void *)buf;
2050 stream.avail_in = len;
2051 do {
2052 unsigned char *in0 = stream.next_in;
2054 ret = write_loose_object_common(&c, &stream, 1, in0, fd,
2055 compressed, sizeof(compressed));
2056 } while (ret == Z_OK);
2058 if (ret != Z_STREAM_END)
2059 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
2060 ret);
2061 ret = end_loose_object_common(&c, &stream, &parano_oid);
2062 if (ret != Z_OK)
2063 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
2064 ret);
2065 if (!oideq(oid, &parano_oid))
2066 die(_("confused by unstable object source data for %s"),
2067 oid_to_hex(oid));
2069 close_loose_object(fd, tmp_file.buf);
2071 if (mtime) {
2072 struct utimbuf utb;
2073 utb.actime = mtime;
2074 utb.modtime = mtime;
2075 if (utime(tmp_file.buf, &utb) < 0 &&
2076 !(flags & HASH_SILENT))
2077 warning_errno(_("failed utime() on %s"), tmp_file.buf);
2080 return finalize_object_file(tmp_file.buf, filename.buf);
2083 static int freshen_loose_object(const struct object_id *oid)
2085 return check_and_freshen(oid, 1);
2088 static int freshen_packed_object(const struct object_id *oid)
2090 struct pack_entry e;
2091 if (!find_pack_entry(the_repository, oid, &e))
2092 return 0;
2093 if (e.p->is_cruft)
2094 return 0;
2095 if (e.p->freshened)
2096 return 1;
2097 if (!freshen_file(e.p->pack_name))
2098 return 0;
2099 e.p->freshened = 1;
2100 return 1;
2103 int stream_loose_object(struct input_stream *in_stream, size_t len,
2104 struct object_id *oid)
2106 int fd, ret, err = 0, flush = 0;
2107 unsigned char compressed[4096];
2108 git_zstream stream;
2109 git_hash_ctx c;
2110 struct strbuf tmp_file = STRBUF_INIT;
2111 struct strbuf filename = STRBUF_INIT;
2112 int dirlen;
2113 char hdr[MAX_HEADER_LEN];
2114 int hdrlen;
2116 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2117 prepare_loose_object_bulk_checkin();
2119 /* Since oid is not determined, save tmp file to odb path. */
2120 strbuf_addf(&filename, "%s/", get_object_directory());
2121 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2124 * Common steps for write_loose_object and stream_loose_object to
2125 * start writing loose objects:
2127 * - Create tmpfile for the loose object.
2128 * - Setup zlib stream for compression.
2129 * - Start to feed header to zlib stream.
2131 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2132 &stream, compressed, sizeof(compressed),
2133 &c, hdr, hdrlen);
2134 if (fd < 0) {
2135 err = -1;
2136 goto cleanup;
2139 /* Then the data itself.. */
2140 do {
2141 unsigned char *in0 = stream.next_in;
2143 if (!stream.avail_in && !in_stream->is_finished) {
2144 const void *in = in_stream->read(in_stream, &stream.avail_in);
2145 stream.next_in = (void *)in;
2146 in0 = (unsigned char *)in;
2147 /* All data has been read. */
2148 if (in_stream->is_finished)
2149 flush = 1;
2151 ret = write_loose_object_common(&c, &stream, flush, in0, fd,
2152 compressed, sizeof(compressed));
2154 * Unlike write_loose_object(), we do not have the entire
2155 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2156 * then we'll replenish them in the next input_stream->read()
2157 * call when we loop.
2159 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2161 if (stream.total_in != len + hdrlen)
2162 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2163 (uintmax_t)len + hdrlen);
2166 * Common steps for write_loose_object and stream_loose_object to
2167 * end writing loose oject:
2169 * - End the compression of zlib stream.
2170 * - Get the calculated oid.
2172 if (ret != Z_STREAM_END)
2173 die(_("unable to stream deflate new object (%d)"), ret);
2174 ret = end_loose_object_common(&c, &stream, oid);
2175 if (ret != Z_OK)
2176 die(_("deflateEnd on stream object failed (%d)"), ret);
2177 close_loose_object(fd, tmp_file.buf);
2179 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2180 unlink_or_warn(tmp_file.buf);
2181 goto cleanup;
2184 loose_object_path(the_repository, &filename, oid);
2186 /* We finally know the object path, and create the missing dir. */
2187 dirlen = directory_size(filename.buf);
2188 if (dirlen) {
2189 struct strbuf dir = STRBUF_INIT;
2190 strbuf_add(&dir, filename.buf, dirlen);
2192 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2193 err = error_errno(_("unable to create directory %s"), dir.buf);
2194 strbuf_release(&dir);
2195 goto cleanup;
2197 strbuf_release(&dir);
2200 err = finalize_object_file(tmp_file.buf, filename.buf);
2201 cleanup:
2202 strbuf_release(&tmp_file);
2203 strbuf_release(&filename);
2204 return err;
2207 int write_object_file_flags(const void *buf, unsigned long len,
2208 enum object_type type, struct object_id *oid,
2209 unsigned flags)
2211 char hdr[MAX_HEADER_LEN];
2212 int hdrlen = sizeof(hdr);
2214 /* Normally if we have it in the pack then we do not bother writing
2215 * it out into .git/objects/??/?{38} file.
2217 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
2218 &hdrlen);
2219 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2220 return 0;
2221 return write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags);
2224 int write_object_file_literally(const void *buf, unsigned long len,
2225 const char *type, struct object_id *oid,
2226 unsigned flags)
2228 char *header;
2229 int hdrlen, status = 0;
2231 /* type string, SP, %lu of the length plus NUL must fit this */
2232 hdrlen = strlen(type) + MAX_HEADER_LEN;
2233 header = xmalloc(hdrlen);
2234 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2235 oid, header, &hdrlen);
2237 if (!(flags & HASH_WRITE_OBJECT))
2238 goto cleanup;
2239 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2240 goto cleanup;
2241 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
2243 cleanup:
2244 free(header);
2245 return status;
2248 int force_object_loose(const struct object_id *oid, time_t mtime)
2250 void *buf;
2251 unsigned long len;
2252 struct object_info oi = OBJECT_INFO_INIT;
2253 enum object_type type;
2254 char hdr[MAX_HEADER_LEN];
2255 int hdrlen;
2256 int ret;
2258 if (has_loose_object(oid))
2259 return 0;
2260 oi.typep = &type;
2261 oi.sizep = &len;
2262 oi.contentp = &buf;
2263 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2264 return error(_("cannot read object for %s"), oid_to_hex(oid));
2265 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
2266 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
2267 free(buf);
2269 return ret;
2272 int has_object(struct repository *r, const struct object_id *oid,
2273 unsigned flags)
2275 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2276 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2277 (quick ? OBJECT_INFO_QUICK : 0);
2279 if (!startup_info->have_repository)
2280 return 0;
2281 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2284 int repo_has_object_file_with_flags(struct repository *r,
2285 const struct object_id *oid, int flags)
2287 if (!startup_info->have_repository)
2288 return 0;
2289 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2292 int repo_has_object_file(struct repository *r,
2293 const struct object_id *oid)
2295 return repo_has_object_file_with_flags(r, oid, 0);
2299 * We can't use the normal fsck_error_function() for index_mem(),
2300 * because we don't yet have a valid oid for it to report. Instead,
2301 * report the minimal fsck error here, and rely on the caller to
2302 * give more context.
2304 static int hash_format_check_report(struct fsck_options *opts,
2305 const struct object_id *oid,
2306 enum object_type object_type,
2307 enum fsck_msg_type msg_type,
2308 enum fsck_msg_id msg_id,
2309 const char *message)
2311 error(_("object fails fsck: %s"), message);
2312 return 1;
2315 static int index_mem(struct index_state *istate,
2316 struct object_id *oid, void *buf, size_t size,
2317 enum object_type type,
2318 const char *path, unsigned flags)
2320 int ret = 0;
2321 int re_allocated = 0;
2322 int write_object = flags & HASH_WRITE_OBJECT;
2324 if (!type)
2325 type = OBJ_BLOB;
2328 * Convert blobs to git internal format
2330 if ((type == OBJ_BLOB) && path) {
2331 struct strbuf nbuf = STRBUF_INIT;
2332 if (convert_to_git(istate, path, buf, size, &nbuf,
2333 get_conv_flags(flags))) {
2334 buf = strbuf_detach(&nbuf, &size);
2335 re_allocated = 1;
2338 if (flags & HASH_FORMAT_CHECK) {
2339 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2341 opts.strict = 1;
2342 opts.error_func = hash_format_check_report;
2343 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2344 die(_("refusing to create malformed object"));
2345 fsck_finish(&opts);
2348 if (write_object)
2349 ret = write_object_file(buf, size, type, oid);
2350 else
2351 hash_object_file(the_hash_algo, buf, size, type, oid);
2352 if (re_allocated)
2353 free(buf);
2354 return ret;
2357 static int index_stream_convert_blob(struct index_state *istate,
2358 struct object_id *oid,
2359 int fd,
2360 const char *path,
2361 unsigned flags)
2363 int ret = 0;
2364 const int write_object = flags & HASH_WRITE_OBJECT;
2365 struct strbuf sbuf = STRBUF_INIT;
2367 assert(path);
2368 assert(would_convert_to_git_filter_fd(istate, path));
2370 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2371 get_conv_flags(flags));
2373 if (write_object)
2374 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
2375 oid);
2376 else
2377 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2378 oid);
2379 strbuf_release(&sbuf);
2380 return ret;
2383 static int index_pipe(struct index_state *istate, struct object_id *oid,
2384 int fd, enum object_type type,
2385 const char *path, unsigned flags)
2387 struct strbuf sbuf = STRBUF_INIT;
2388 int ret;
2390 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2391 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2392 else
2393 ret = -1;
2394 strbuf_release(&sbuf);
2395 return ret;
2398 #define SMALL_FILE_SIZE (32*1024)
2400 static int index_core(struct index_state *istate,
2401 struct object_id *oid, int fd, size_t size,
2402 enum object_type type, const char *path,
2403 unsigned flags)
2405 int ret;
2407 if (!size) {
2408 ret = index_mem(istate, oid, "", size, type, path, flags);
2409 } else if (size <= SMALL_FILE_SIZE) {
2410 char *buf = xmalloc(size);
2411 ssize_t read_result = read_in_full(fd, buf, size);
2412 if (read_result < 0)
2413 ret = error_errno(_("read error while indexing %s"),
2414 path ? path : "<unknown>");
2415 else if (read_result != size)
2416 ret = error(_("short read while indexing %s"),
2417 path ? path : "<unknown>");
2418 else
2419 ret = index_mem(istate, oid, buf, size, type, path, flags);
2420 free(buf);
2421 } else {
2422 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2423 ret = index_mem(istate, oid, buf, size, type, path, flags);
2424 munmap(buf, size);
2426 return ret;
2430 * This creates one packfile per large blob unless bulk-checkin
2431 * machinery is "plugged".
2433 * This also bypasses the usual "convert-to-git" dance, and that is on
2434 * purpose. We could write a streaming version of the converting
2435 * functions and insert that before feeding the data to fast-import
2436 * (or equivalent in-core API described above). However, that is
2437 * somewhat complicated, as we do not know the size of the filter
2438 * result, which we need to know beforehand when writing a git object.
2439 * Since the primary motivation for trying to stream from the working
2440 * tree file and to avoid mmaping it in core is to deal with large
2441 * binary blobs, they generally do not want to get any conversion, and
2442 * callers should avoid this code path when filters are requested.
2444 static int index_stream(struct object_id *oid, int fd, size_t size,
2445 enum object_type type, const char *path,
2446 unsigned flags)
2448 return index_bulk_checkin(oid, fd, size, type, path, flags);
2451 int index_fd(struct index_state *istate, struct object_id *oid,
2452 int fd, struct stat *st,
2453 enum object_type type, const char *path, unsigned flags)
2455 int ret;
2458 * Call xsize_t() only when needed to avoid potentially unnecessary
2459 * die() for large files.
2461 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2462 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2463 else if (!S_ISREG(st->st_mode))
2464 ret = index_pipe(istate, oid, fd, type, path, flags);
2465 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2466 (path && would_convert_to_git(istate, path)))
2467 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2468 type, path, flags);
2469 else
2470 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2471 flags);
2472 close(fd);
2473 return ret;
2476 int index_path(struct index_state *istate, struct object_id *oid,
2477 const char *path, struct stat *st, unsigned flags)
2479 int fd;
2480 struct strbuf sb = STRBUF_INIT;
2481 int rc = 0;
2483 switch (st->st_mode & S_IFMT) {
2484 case S_IFREG:
2485 fd = open(path, O_RDONLY);
2486 if (fd < 0)
2487 return error_errno("open(\"%s\")", path);
2488 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2489 return error(_("%s: failed to insert into database"),
2490 path);
2491 break;
2492 case S_IFLNK:
2493 if (strbuf_readlink(&sb, path, st->st_size))
2494 return error_errno("readlink(\"%s\")", path);
2495 if (!(flags & HASH_WRITE_OBJECT))
2496 hash_object_file(the_hash_algo, sb.buf, sb.len,
2497 OBJ_BLOB, oid);
2498 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
2499 rc = error(_("%s: failed to insert into database"), path);
2500 strbuf_release(&sb);
2501 break;
2502 case S_IFDIR:
2503 return resolve_gitlink_ref(path, "HEAD", oid);
2504 default:
2505 return error(_("%s: unsupported file type"), path);
2507 return rc;
2510 int read_pack_header(int fd, struct pack_header *header)
2512 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2513 /* "eof before pack header was fully read" */
2514 return PH_ERROR_EOF;
2516 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2517 /* "protocol error (pack signature mismatch detected)" */
2518 return PH_ERROR_PACK_SIGNATURE;
2519 if (!pack_version_ok(header->hdr_version))
2520 /* "protocol error (pack version unsupported)" */
2521 return PH_ERROR_PROTOCOL;
2522 return 0;
2525 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2527 enum object_type type = oid_object_info(the_repository, oid, NULL);
2528 if (type < 0)
2529 die(_("%s is not a valid object"), oid_to_hex(oid));
2530 if (type != expect)
2531 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2532 type_name(expect));
2535 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2536 struct strbuf *path,
2537 each_loose_object_fn obj_cb,
2538 each_loose_cruft_fn cruft_cb,
2539 each_loose_subdir_fn subdir_cb,
2540 void *data)
2542 size_t origlen, baselen;
2543 DIR *dir;
2544 struct dirent *de;
2545 int r = 0;
2546 struct object_id oid;
2548 if (subdir_nr > 0xff)
2549 BUG("invalid loose object subdirectory: %x", subdir_nr);
2551 origlen = path->len;
2552 strbuf_complete(path, '/');
2553 strbuf_addf(path, "%02x", subdir_nr);
2555 dir = opendir(path->buf);
2556 if (!dir) {
2557 if (errno != ENOENT)
2558 r = error_errno(_("unable to open %s"), path->buf);
2559 strbuf_setlen(path, origlen);
2560 return r;
2563 oid.hash[0] = subdir_nr;
2564 strbuf_addch(path, '/');
2565 baselen = path->len;
2567 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2568 size_t namelen;
2570 namelen = strlen(de->d_name);
2571 strbuf_setlen(path, baselen);
2572 strbuf_add(path, de->d_name, namelen);
2573 if (namelen == the_hash_algo->hexsz - 2 &&
2574 !hex_to_bytes(oid.hash + 1, de->d_name,
2575 the_hash_algo->rawsz - 1)) {
2576 oid_set_algo(&oid, the_hash_algo);
2577 if (obj_cb) {
2578 r = obj_cb(&oid, path->buf, data);
2579 if (r)
2580 break;
2582 continue;
2585 if (cruft_cb) {
2586 r = cruft_cb(de->d_name, path->buf, data);
2587 if (r)
2588 break;
2591 closedir(dir);
2593 strbuf_setlen(path, baselen - 1);
2594 if (!r && subdir_cb)
2595 r = subdir_cb(subdir_nr, path->buf, data);
2597 strbuf_setlen(path, origlen);
2599 return r;
2602 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2603 each_loose_object_fn obj_cb,
2604 each_loose_cruft_fn cruft_cb,
2605 each_loose_subdir_fn subdir_cb,
2606 void *data)
2608 int r = 0;
2609 int i;
2611 for (i = 0; i < 256; i++) {
2612 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2613 subdir_cb, data);
2614 if (r)
2615 break;
2618 return r;
2621 int for_each_loose_file_in_objdir(const char *path,
2622 each_loose_object_fn obj_cb,
2623 each_loose_cruft_fn cruft_cb,
2624 each_loose_subdir_fn subdir_cb,
2625 void *data)
2627 struct strbuf buf = STRBUF_INIT;
2628 int r;
2630 strbuf_addstr(&buf, path);
2631 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2632 subdir_cb, data);
2633 strbuf_release(&buf);
2635 return r;
2638 int for_each_loose_object(each_loose_object_fn cb, void *data,
2639 enum for_each_object_flags flags)
2641 struct object_directory *odb;
2643 prepare_alt_odb(the_repository);
2644 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2645 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2646 NULL, data);
2647 if (r)
2648 return r;
2650 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2651 break;
2654 return 0;
2657 static int append_loose_object(const struct object_id *oid,
2658 const char *path UNUSED,
2659 void *data)
2661 oidtree_insert(data, oid);
2662 return 0;
2665 struct oidtree *odb_loose_cache(struct object_directory *odb,
2666 const struct object_id *oid)
2668 int subdir_nr = oid->hash[0];
2669 struct strbuf buf = STRBUF_INIT;
2670 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2671 size_t word_index = subdir_nr / word_bits;
2672 size_t mask = (size_t)1u << (subdir_nr % word_bits);
2673 uint32_t *bitmap;
2675 if (subdir_nr < 0 ||
2676 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2677 BUG("subdir_nr out of range");
2679 bitmap = &odb->loose_objects_subdir_seen[word_index];
2680 if (*bitmap & mask)
2681 return odb->loose_objects_cache;
2682 if (!odb->loose_objects_cache) {
2683 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2684 oidtree_init(odb->loose_objects_cache);
2686 strbuf_addstr(&buf, odb->path);
2687 for_each_file_in_obj_subdir(subdir_nr, &buf,
2688 append_loose_object,
2689 NULL, NULL,
2690 odb->loose_objects_cache);
2691 *bitmap |= mask;
2692 strbuf_release(&buf);
2693 return odb->loose_objects_cache;
2696 void odb_clear_loose_cache(struct object_directory *odb)
2698 oidtree_clear(odb->loose_objects_cache);
2699 FREE_AND_NULL(odb->loose_objects_cache);
2700 memset(&odb->loose_objects_subdir_seen, 0,
2701 sizeof(odb->loose_objects_subdir_seen));
2704 static int check_stream_oid(git_zstream *stream,
2705 const char *hdr,
2706 unsigned long size,
2707 const char *path,
2708 const struct object_id *expected_oid)
2710 git_hash_ctx c;
2711 struct object_id real_oid;
2712 unsigned char buf[4096];
2713 unsigned long total_read;
2714 int status = Z_OK;
2716 the_hash_algo->init_fn(&c);
2717 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2720 * We already read some bytes into hdr, but the ones up to the NUL
2721 * do not count against the object's content size.
2723 total_read = stream->total_out - strlen(hdr) - 1;
2726 * This size comparison must be "<=" to read the final zlib packets;
2727 * see the comment in unpack_loose_rest for details.
2729 while (total_read <= size &&
2730 (status == Z_OK ||
2731 (status == Z_BUF_ERROR && !stream->avail_out))) {
2732 stream->next_out = buf;
2733 stream->avail_out = sizeof(buf);
2734 if (size - total_read < stream->avail_out)
2735 stream->avail_out = size - total_read;
2736 status = git_inflate(stream, Z_FINISH);
2737 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2738 total_read += stream->next_out - buf;
2740 git_inflate_end(stream);
2742 if (status != Z_STREAM_END) {
2743 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2744 return -1;
2746 if (stream->avail_in) {
2747 error(_("garbage at end of loose object '%s'"),
2748 oid_to_hex(expected_oid));
2749 return -1;
2752 the_hash_algo->final_oid_fn(&real_oid, &c);
2753 if (!oideq(expected_oid, &real_oid)) {
2754 error(_("hash mismatch for %s (expected %s)"), path,
2755 oid_to_hex(expected_oid));
2756 return -1;
2759 return 0;
2762 int read_loose_object(const char *path,
2763 const struct object_id *expected_oid,
2764 struct object_id *real_oid,
2765 void **contents,
2766 struct object_info *oi)
2768 int ret = -1;
2769 int fd;
2770 void *map = NULL;
2771 unsigned long mapsize;
2772 git_zstream stream;
2773 char hdr[MAX_HEADER_LEN];
2774 unsigned long *size = oi->sizep;
2776 fd = git_open(path);
2777 if (fd >= 0)
2778 map = map_fd(fd, path, &mapsize);
2779 if (!map) {
2780 error_errno(_("unable to mmap %s"), path);
2781 goto out;
2784 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
2785 NULL) != ULHR_OK) {
2786 error(_("unable to unpack header of %s"), path);
2787 goto out;
2790 if (parse_loose_header(hdr, oi) < 0) {
2791 error(_("unable to parse header of %s"), path);
2792 git_inflate_end(&stream);
2793 goto out;
2796 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
2797 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2798 goto out;
2799 } else {
2800 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2801 if (!*contents) {
2802 error(_("unable to unpack contents of %s"), path);
2803 git_inflate_end(&stream);
2804 goto out;
2806 hash_object_file_literally(the_repository->hash_algo,
2807 *contents, *size,
2808 oi->type_name->buf, real_oid);
2809 if (!oideq(expected_oid, real_oid))
2810 goto out;
2813 ret = 0; /* everything checks out */
2815 out:
2816 if (map)
2817 munmap(map, mapsize);
2818 return ret;