builtin: fix typos
[git/gitster.git] / object-file.c
blob968da27cd41970e855507cf30b9ee2c6b5974798
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 */
10 #define USE_THE_REPOSITORY_VARIABLE
12 #include "git-compat-util.h"
13 #include "abspath.h"
14 #include "config.h"
15 #include "convert.h"
16 #include "environment.h"
17 #include "gettext.h"
18 #include "hex.h"
19 #include "string-list.h"
20 #include "lockfile.h"
21 #include "pack.h"
22 #include "commit.h"
23 #include "run-command.h"
24 #include "refs.h"
25 #include "bulk-checkin.h"
26 #include "repository.h"
27 #include "replace-object.h"
28 #include "streaming.h"
29 #include "dir.h"
30 #include "list.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "object-file.h"
34 #include "object-store.h"
35 #include "oidtree.h"
36 #include "path.h"
37 #include "promisor-remote.h"
38 #include "setup.h"
39 #include "submodule.h"
40 #include "fsck.h"
41 #include "loose.h"
42 #include "object-file-convert.h"
44 /* The maximum size for an object header. */
45 #define MAX_HEADER_LEN 32
48 #define EMPTY_TREE_SHA1_BIN_LITERAL \
49 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
50 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
51 #define EMPTY_TREE_SHA256_BIN_LITERAL \
52 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
53 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
54 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
55 "\x53\x21"
57 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
58 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
59 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
60 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
61 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
62 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
63 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
64 "\x18\x13"
66 static const struct object_id empty_tree_oid = {
67 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
68 .algo = GIT_HASH_SHA1,
70 static const struct object_id empty_blob_oid = {
71 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
72 .algo = GIT_HASH_SHA1,
74 static const struct object_id null_oid_sha1 = {
75 .hash = {0},
76 .algo = GIT_HASH_SHA1,
78 static const struct object_id empty_tree_oid_sha256 = {
79 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
80 .algo = GIT_HASH_SHA256,
82 static const struct object_id empty_blob_oid_sha256 = {
83 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
84 .algo = GIT_HASH_SHA256,
86 static const struct object_id null_oid_sha256 = {
87 .hash = {0},
88 .algo = GIT_HASH_SHA256,
91 static void git_hash_sha1_init(git_hash_ctx *ctx)
93 git_SHA1_Init(&ctx->sha1);
96 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
98 git_SHA1_Clone(&dst->sha1, &src->sha1);
101 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
103 git_SHA1_Update(&ctx->sha1, data, len);
106 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
108 git_SHA1_Final(hash, &ctx->sha1);
111 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
113 git_SHA1_Final(oid->hash, &ctx->sha1);
114 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
115 oid->algo = GIT_HASH_SHA1;
119 static void git_hash_sha256_init(git_hash_ctx *ctx)
121 git_SHA256_Init(&ctx->sha256);
124 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
126 git_SHA256_Clone(&dst->sha256, &src->sha256);
129 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
131 git_SHA256_Update(&ctx->sha256, data, len);
134 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
136 git_SHA256_Final(hash, &ctx->sha256);
139 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
141 git_SHA256_Final(oid->hash, &ctx->sha256);
143 * This currently does nothing, so the compiler should optimize it out,
144 * but keep it in case we extend the hash size again.
146 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
147 oid->algo = GIT_HASH_SHA256;
150 static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
152 BUG("trying to init unknown hash");
155 static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
156 const git_hash_ctx *src UNUSED)
158 BUG("trying to clone unknown hash");
161 static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
162 const void *data UNUSED,
163 size_t len UNUSED)
165 BUG("trying to update unknown hash");
168 static void git_hash_unknown_final(unsigned char *hash UNUSED,
169 git_hash_ctx *ctx UNUSED)
171 BUG("trying to finalize unknown hash");
174 static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
175 git_hash_ctx *ctx UNUSED)
177 BUG("trying to finalize unknown hash");
180 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
182 .name = NULL,
183 .format_id = 0x00000000,
184 .rawsz = 0,
185 .hexsz = 0,
186 .blksz = 0,
187 .init_fn = git_hash_unknown_init,
188 .clone_fn = git_hash_unknown_clone,
189 .update_fn = git_hash_unknown_update,
190 .final_fn = git_hash_unknown_final,
191 .final_oid_fn = git_hash_unknown_final_oid,
192 .empty_tree = NULL,
193 .empty_blob = NULL,
194 .null_oid = NULL,
197 .name = "sha1",
198 .format_id = GIT_SHA1_FORMAT_ID,
199 .rawsz = GIT_SHA1_RAWSZ,
200 .hexsz = GIT_SHA1_HEXSZ,
201 .blksz = GIT_SHA1_BLKSZ,
202 .init_fn = git_hash_sha1_init,
203 .clone_fn = git_hash_sha1_clone,
204 .update_fn = git_hash_sha1_update,
205 .final_fn = git_hash_sha1_final,
206 .final_oid_fn = git_hash_sha1_final_oid,
207 .empty_tree = &empty_tree_oid,
208 .empty_blob = &empty_blob_oid,
209 .null_oid = &null_oid_sha1,
212 .name = "sha256",
213 .format_id = GIT_SHA256_FORMAT_ID,
214 .rawsz = GIT_SHA256_RAWSZ,
215 .hexsz = GIT_SHA256_HEXSZ,
216 .blksz = GIT_SHA256_BLKSZ,
217 .init_fn = git_hash_sha256_init,
218 .clone_fn = git_hash_sha256_clone,
219 .update_fn = git_hash_sha256_update,
220 .final_fn = git_hash_sha256_final,
221 .final_oid_fn = git_hash_sha256_final_oid,
222 .empty_tree = &empty_tree_oid_sha256,
223 .empty_blob = &empty_blob_oid_sha256,
224 .null_oid = &null_oid_sha256,
228 const struct object_id *null_oid(void)
230 return the_hash_algo->null_oid;
233 const char *empty_tree_oid_hex(const struct git_hash_algo *algop)
235 static char buf[GIT_MAX_HEXSZ + 1];
236 return oid_to_hex_r(buf, algop->empty_tree);
239 int hash_algo_by_name(const char *name)
241 int i;
242 if (!name)
243 return GIT_HASH_UNKNOWN;
244 for (i = 1; i < GIT_HASH_NALGOS; i++)
245 if (!strcmp(name, hash_algos[i].name))
246 return i;
247 return GIT_HASH_UNKNOWN;
250 int hash_algo_by_id(uint32_t format_id)
252 int i;
253 for (i = 1; i < GIT_HASH_NALGOS; i++)
254 if (format_id == hash_algos[i].format_id)
255 return i;
256 return GIT_HASH_UNKNOWN;
259 int hash_algo_by_length(int len)
261 int i;
262 for (i = 1; i < GIT_HASH_NALGOS; i++)
263 if (len == hash_algos[i].rawsz)
264 return i;
265 return GIT_HASH_UNKNOWN;
269 * This is meant to hold a *small* number of objects that you would
270 * want repo_read_object_file() to be able to return, but yet you do not want
271 * to write them into the object store (e.g. a browse-only
272 * application).
274 static struct cached_object {
275 struct object_id oid;
276 enum object_type type;
277 const void *buf;
278 unsigned long size;
279 } *cached_objects;
280 static int cached_object_nr, cached_object_alloc;
282 static struct cached_object empty_tree = {
283 .oid = {
284 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
286 .type = OBJ_TREE,
287 .buf = "",
290 static struct cached_object *find_cached_object(const struct object_id *oid)
292 int i;
293 struct cached_object *co = cached_objects;
295 for (i = 0; i < cached_object_nr; i++, co++) {
296 if (oideq(&co->oid, oid))
297 return co;
299 if (oideq(oid, the_hash_algo->empty_tree))
300 return &empty_tree;
301 return NULL;
305 static int get_conv_flags(unsigned flags)
307 if (flags & HASH_RENORMALIZE)
308 return CONV_EOL_RENORMALIZE;
309 else if (flags & HASH_WRITE_OBJECT)
310 return global_conv_flags_eol | CONV_WRITE_OBJECT;
311 else
312 return 0;
316 int mkdir_in_gitdir(const char *path)
318 if (mkdir(path, 0777)) {
319 int saved_errno = errno;
320 struct stat st;
321 struct strbuf sb = STRBUF_INIT;
323 if (errno != EEXIST)
324 return -1;
326 * Are we looking at a path in a symlinked worktree
327 * whose original repository does not yet have it?
328 * e.g. .git/rr-cache pointing at its original
329 * repository in which the user hasn't performed any
330 * conflict resolution yet?
332 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
333 strbuf_readlink(&sb, path, st.st_size) ||
334 !is_absolute_path(sb.buf) ||
335 mkdir(sb.buf, 0777)) {
336 strbuf_release(&sb);
337 errno = saved_errno;
338 return -1;
340 strbuf_release(&sb);
342 return adjust_shared_perm(path);
345 static enum scld_error safe_create_leading_directories_1(char *path, int share)
347 char *next_component = path + offset_1st_component(path);
348 enum scld_error ret = SCLD_OK;
350 while (ret == SCLD_OK && next_component) {
351 struct stat st;
352 char *slash = next_component, slash_character;
354 while (*slash && !is_dir_sep(*slash))
355 slash++;
357 if (!*slash)
358 break;
360 next_component = slash + 1;
361 while (is_dir_sep(*next_component))
362 next_component++;
363 if (!*next_component)
364 break;
366 slash_character = *slash;
367 *slash = '\0';
368 if (!stat(path, &st)) {
369 /* path exists */
370 if (!S_ISDIR(st.st_mode)) {
371 errno = ENOTDIR;
372 ret = SCLD_EXISTS;
374 } else if (mkdir(path, 0777)) {
375 if (errno == EEXIST &&
376 !stat(path, &st) && S_ISDIR(st.st_mode))
377 ; /* somebody created it since we checked */
378 else if (errno == ENOENT)
380 * Either mkdir() failed because
381 * somebody just pruned the containing
382 * directory, or stat() failed because
383 * the file that was in our way was
384 * just removed. Either way, inform
385 * the caller that it might be worth
386 * trying again:
388 ret = SCLD_VANISHED;
389 else
390 ret = SCLD_FAILED;
391 } else if (share && adjust_shared_perm(path)) {
392 ret = SCLD_PERMS;
394 *slash = slash_character;
396 return ret;
399 enum scld_error safe_create_leading_directories(char *path)
401 return safe_create_leading_directories_1(path, 1);
404 enum scld_error safe_create_leading_directories_no_share(char *path)
406 return safe_create_leading_directories_1(path, 0);
409 enum scld_error safe_create_leading_directories_const(const char *path)
411 int save_errno;
412 /* path points to cache entries, so xstrdup before messing with it */
413 char *buf = xstrdup(path);
414 enum scld_error result = safe_create_leading_directories(buf);
416 save_errno = errno;
417 free(buf);
418 errno = save_errno;
419 return result;
422 int odb_mkstemp(struct strbuf *temp_filename, const char *pattern)
424 int fd;
426 * we let the umask do its job, don't try to be more
427 * restrictive except to remove write permission.
429 int mode = 0444;
430 git_path_buf(temp_filename, "objects/%s", pattern);
431 fd = git_mkstemp_mode(temp_filename->buf, mode);
432 if (0 <= fd)
433 return fd;
435 /* slow path */
436 /* some mkstemp implementations erase temp_filename on failure */
437 git_path_buf(temp_filename, "objects/%s", pattern);
438 safe_create_leading_directories(temp_filename->buf);
439 return xmkstemp_mode(temp_filename->buf, mode);
442 int odb_pack_keep(const char *name)
444 int fd;
446 fd = open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
447 if (0 <= fd)
448 return fd;
450 /* slow path */
451 safe_create_leading_directories_const(name);
452 return open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
455 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
457 int i;
458 for (i = 0; i < the_hash_algo->rawsz; i++) {
459 static char hex[] = "0123456789abcdef";
460 unsigned int val = oid->hash[i];
461 strbuf_addch(buf, hex[val >> 4]);
462 strbuf_addch(buf, hex[val & 0xf]);
463 if (!i)
464 strbuf_addch(buf, '/');
468 static const char *odb_loose_path(struct object_directory *odb,
469 struct strbuf *buf,
470 const struct object_id *oid)
472 strbuf_reset(buf);
473 strbuf_addstr(buf, odb->path);
474 strbuf_addch(buf, '/');
475 fill_loose_path(buf, oid);
476 return buf->buf;
479 const char *loose_object_path(struct repository *r, struct strbuf *buf,
480 const struct object_id *oid)
482 return odb_loose_path(r->objects->odb, buf, oid);
486 * Return non-zero iff the path is usable as an alternate object database.
488 static int alt_odb_usable(struct raw_object_store *o,
489 struct strbuf *path,
490 const char *normalized_objdir, khiter_t *pos)
492 int r;
494 /* Detect cases where alternate disappeared */
495 if (!is_directory(path->buf)) {
496 error(_("object directory %s does not exist; "
497 "check .git/objects/info/alternates"),
498 path->buf);
499 return 0;
503 * Prevent the common mistake of listing the same
504 * thing twice, or object directory itself.
506 if (!o->odb_by_path) {
507 khiter_t p;
509 o->odb_by_path = kh_init_odb_path_map();
510 assert(!o->odb->next);
511 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
512 assert(r == 1); /* never used */
513 kh_value(o->odb_by_path, p) = o->odb;
515 if (fspatheq(path->buf, normalized_objdir))
516 return 0;
517 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
518 /* r: 0 = exists, 1 = never used, 2 = deleted */
519 return r == 0 ? 0 : 1;
523 * Prepare alternate object database registry.
525 * The variable alt_odb_list points at the list of struct
526 * object_directory. The elements on this list come from
527 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
528 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
529 * whose contents is similar to that environment variable but can be
530 * LF separated. Its base points at a statically allocated buffer that
531 * contains "/the/directory/corresponding/to/.git/objects/...", while
532 * its name points just after the slash at the end of ".git/objects/"
533 * in the example above, and has enough space to hold all hex characters
534 * of the object ID, an extra slash for the first level indirection, and
535 * the terminating NUL.
537 static void read_info_alternates(struct repository *r,
538 const char *relative_base,
539 int depth);
540 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
541 const char *relative_base, int depth, const char *normalized_objdir)
543 struct object_directory *ent;
544 struct strbuf pathbuf = STRBUF_INIT;
545 struct strbuf tmp = STRBUF_INIT;
546 khiter_t pos;
547 int ret = -1;
549 if (!is_absolute_path(entry->buf) && relative_base) {
550 strbuf_realpath(&pathbuf, relative_base, 1);
551 strbuf_addch(&pathbuf, '/');
553 strbuf_addbuf(&pathbuf, entry);
555 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
556 error(_("unable to normalize alternate object path: %s"),
557 pathbuf.buf);
558 goto error;
560 strbuf_swap(&pathbuf, &tmp);
563 * The trailing slash after the directory name is given by
564 * this function at the end. Remove duplicates.
566 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
567 strbuf_setlen(&pathbuf, pathbuf.len - 1);
569 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
570 goto error;
572 CALLOC_ARRAY(ent, 1);
573 /* pathbuf.buf is already in r->objects->odb_by_path */
574 ent->path = strbuf_detach(&pathbuf, NULL);
576 /* add the alternate entry */
577 *r->objects->odb_tail = ent;
578 r->objects->odb_tail = &(ent->next);
579 ent->next = NULL;
580 assert(r->objects->odb_by_path);
581 kh_value(r->objects->odb_by_path, pos) = ent;
583 /* recursively add alternates */
584 read_info_alternates(r, ent->path, depth + 1);
585 ret = 0;
586 error:
587 strbuf_release(&tmp);
588 strbuf_release(&pathbuf);
589 return ret;
592 static const char *parse_alt_odb_entry(const char *string,
593 int sep,
594 struct strbuf *out)
596 const char *end;
598 strbuf_reset(out);
600 if (*string == '#') {
601 /* comment; consume up to next separator */
602 end = strchrnul(string, sep);
603 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
605 * quoted path; unquote_c_style has copied the
606 * data for us and set "end". Broken quoting (e.g.,
607 * an entry that doesn't end with a quote) falls
608 * back to the unquoted case below.
610 } else {
611 /* normal, unquoted path */
612 end = strchrnul(string, sep);
613 strbuf_add(out, string, end - string);
616 if (*end)
617 end++;
618 return end;
621 static void link_alt_odb_entries(struct repository *r, const char *alt,
622 int sep, const char *relative_base, int depth)
624 struct strbuf objdirbuf = STRBUF_INIT;
625 struct strbuf entry = STRBUF_INIT;
627 if (!alt || !*alt)
628 return;
630 if (depth > 5) {
631 error(_("%s: ignoring alternate object stores, nesting too deep"),
632 relative_base);
633 return;
636 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
638 while (*alt) {
639 alt = parse_alt_odb_entry(alt, sep, &entry);
640 if (!entry.len)
641 continue;
642 link_alt_odb_entry(r, &entry,
643 relative_base, depth, objdirbuf.buf);
645 strbuf_release(&entry);
646 strbuf_release(&objdirbuf);
649 static void read_info_alternates(struct repository *r,
650 const char *relative_base,
651 int depth)
653 char *path;
654 struct strbuf buf = STRBUF_INIT;
656 path = xstrfmt("%s/info/alternates", relative_base);
657 if (strbuf_read_file(&buf, path, 1024) < 0) {
658 warn_on_fopen_errors(path);
659 free(path);
660 return;
663 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
664 strbuf_release(&buf);
665 free(path);
668 void add_to_alternates_file(const char *reference)
670 struct lock_file lock = LOCK_INIT;
671 char *alts = git_pathdup("objects/info/alternates");
672 FILE *in, *out;
673 int found = 0;
675 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
676 out = fdopen_lock_file(&lock, "w");
677 if (!out)
678 die_errno(_("unable to fdopen alternates lockfile"));
680 in = fopen(alts, "r");
681 if (in) {
682 struct strbuf line = STRBUF_INIT;
684 while (strbuf_getline(&line, in) != EOF) {
685 if (!strcmp(reference, line.buf)) {
686 found = 1;
687 break;
689 fprintf_or_die(out, "%s\n", line.buf);
692 strbuf_release(&line);
693 fclose(in);
695 else if (errno != ENOENT)
696 die_errno(_("unable to read alternates file"));
698 if (found) {
699 rollback_lock_file(&lock);
700 } else {
701 fprintf_or_die(out, "%s\n", reference);
702 if (commit_lock_file(&lock))
703 die_errno(_("unable to move new alternates file into place"));
704 if (the_repository->objects->loaded_alternates)
705 link_alt_odb_entries(the_repository, reference,
706 '\n', NULL, 0);
708 free(alts);
711 void add_to_alternates_memory(const char *reference)
714 * Make sure alternates are initialized, or else our entry may be
715 * overwritten when they are.
717 prepare_alt_odb(the_repository);
719 link_alt_odb_entries(the_repository, reference,
720 '\n', NULL, 0);
723 struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
725 struct object_directory *new_odb;
728 * Make sure alternates are initialized, or else our entry may be
729 * overwritten when they are.
731 prepare_alt_odb(the_repository);
734 * Make a new primary odb and link the old primary ODB in as an
735 * alternate
737 new_odb = xcalloc(1, sizeof(*new_odb));
738 new_odb->path = xstrdup(dir);
741 * Disable ref updates while a temporary odb is active, since
742 * the objects in the database may roll back.
744 new_odb->disable_ref_updates = 1;
745 new_odb->will_destroy = will_destroy;
746 new_odb->next = the_repository->objects->odb;
747 the_repository->objects->odb = new_odb;
748 return new_odb->next;
751 void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
753 struct object_directory *cur_odb = the_repository->objects->odb;
755 if (strcmp(old_path, cur_odb->path))
756 BUG("expected %s as primary object store; found %s",
757 old_path, cur_odb->path);
759 if (cur_odb->next != restore_odb)
760 BUG("we expect the old primary object store to be the first alternate");
762 the_repository->objects->odb = restore_odb;
763 free_object_directory(cur_odb);
767 * Compute the exact path an alternate is at and returns it. In case of
768 * error NULL is returned and the human readable error is added to `err`
769 * `path` may be relative and should point to $GIT_DIR.
770 * `err` must not be null.
772 char *compute_alternate_path(const char *path, struct strbuf *err)
774 char *ref_git = NULL;
775 const char *repo;
776 int seen_error = 0;
778 ref_git = real_pathdup(path, 0);
779 if (!ref_git) {
780 seen_error = 1;
781 strbuf_addf(err, _("path '%s' does not exist"), path);
782 goto out;
785 repo = read_gitfile(ref_git);
786 if (!repo)
787 repo = read_gitfile(mkpath("%s/.git", ref_git));
788 if (repo) {
789 free(ref_git);
790 ref_git = xstrdup(repo);
793 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
794 char *ref_git_git = mkpathdup("%s/.git", ref_git);
795 free(ref_git);
796 ref_git = ref_git_git;
797 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
798 struct strbuf sb = STRBUF_INIT;
799 seen_error = 1;
800 if (get_common_dir(&sb, ref_git)) {
801 strbuf_addf(err,
802 _("reference repository '%s' as a linked "
803 "checkout is not supported yet."),
804 path);
805 goto out;
808 strbuf_addf(err, _("reference repository '%s' is not a "
809 "local repository."), path);
810 goto out;
813 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
814 strbuf_addf(err, _("reference repository '%s' is shallow"),
815 path);
816 seen_error = 1;
817 goto out;
820 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
821 strbuf_addf(err,
822 _("reference repository '%s' is grafted"),
823 path);
824 seen_error = 1;
825 goto out;
828 out:
829 if (seen_error) {
830 FREE_AND_NULL(ref_git);
833 return ref_git;
836 struct object_directory *find_odb(struct repository *r, const char *obj_dir)
838 struct object_directory *odb;
839 char *obj_dir_real = real_pathdup(obj_dir, 1);
840 struct strbuf odb_path_real = STRBUF_INIT;
842 prepare_alt_odb(r);
843 for (odb = r->objects->odb; odb; odb = odb->next) {
844 strbuf_realpath(&odb_path_real, odb->path, 1);
845 if (!strcmp(obj_dir_real, odb_path_real.buf))
846 break;
849 free(obj_dir_real);
850 strbuf_release(&odb_path_real);
852 if (!odb)
853 die(_("could not find object directory matching %s"), obj_dir);
854 return odb;
857 static void fill_alternate_refs_command(struct child_process *cmd,
858 const char *repo_path)
860 const char *value;
862 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
863 cmd->use_shell = 1;
865 strvec_push(&cmd->args, value);
866 strvec_push(&cmd->args, repo_path);
867 } else {
868 cmd->git_cmd = 1;
870 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
871 strvec_push(&cmd->args, "for-each-ref");
872 strvec_push(&cmd->args, "--format=%(objectname)");
874 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
875 strvec_push(&cmd->args, "--");
876 strvec_split(&cmd->args, value);
880 strvec_pushv(&cmd->env, (const char **)local_repo_env);
881 cmd->out = -1;
884 static void read_alternate_refs(const char *path,
885 alternate_ref_fn *cb,
886 void *data)
888 struct child_process cmd = CHILD_PROCESS_INIT;
889 struct strbuf line = STRBUF_INIT;
890 FILE *fh;
892 fill_alternate_refs_command(&cmd, path);
894 if (start_command(&cmd))
895 return;
897 fh = xfdopen(cmd.out, "r");
898 while (strbuf_getline_lf(&line, fh) != EOF) {
899 struct object_id oid;
900 const char *p;
902 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
903 warning(_("invalid line while parsing alternate refs: %s"),
904 line.buf);
905 break;
908 cb(&oid, data);
911 fclose(fh);
912 finish_command(&cmd);
913 strbuf_release(&line);
916 struct alternate_refs_data {
917 alternate_ref_fn *fn;
918 void *data;
921 static int refs_from_alternate_cb(struct object_directory *e,
922 void *data)
924 struct strbuf path = STRBUF_INIT;
925 size_t base_len;
926 struct alternate_refs_data *cb = data;
928 if (!strbuf_realpath(&path, e->path, 0))
929 goto out;
930 if (!strbuf_strip_suffix(&path, "/objects"))
931 goto out;
932 base_len = path.len;
934 /* Is this a git repository with refs? */
935 strbuf_addstr(&path, "/refs");
936 if (!is_directory(path.buf))
937 goto out;
938 strbuf_setlen(&path, base_len);
940 read_alternate_refs(path.buf, cb->fn, cb->data);
942 out:
943 strbuf_release(&path);
944 return 0;
947 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
949 struct alternate_refs_data cb;
950 cb.fn = fn;
951 cb.data = data;
952 foreach_alt_odb(refs_from_alternate_cb, &cb);
955 int foreach_alt_odb(alt_odb_fn fn, void *cb)
957 struct object_directory *ent;
958 int r = 0;
960 prepare_alt_odb(the_repository);
961 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
962 r = fn(ent, cb);
963 if (r)
964 break;
966 return r;
969 void prepare_alt_odb(struct repository *r)
971 if (r->objects->loaded_alternates)
972 return;
974 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
976 read_info_alternates(r, r->objects->odb->path, 0);
977 r->objects->loaded_alternates = 1;
980 int has_alt_odb(struct repository *r)
982 prepare_alt_odb(r);
983 return !!r->objects->odb->next;
986 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
987 static int freshen_file(const char *fn)
989 return !utime(fn, NULL);
993 * All of the check_and_freshen functions return 1 if the file exists and was
994 * freshened (if freshening was requested), 0 otherwise. If they return
995 * 0, you should not assume that it is safe to skip a write of the object (it
996 * either does not exist on disk, or has a stale mtime and may be subject to
997 * pruning).
999 int check_and_freshen_file(const char *fn, int freshen)
1001 if (access(fn, F_OK))
1002 return 0;
1003 if (freshen && !freshen_file(fn))
1004 return 0;
1005 return 1;
1008 static int check_and_freshen_odb(struct object_directory *odb,
1009 const struct object_id *oid,
1010 int freshen)
1012 static struct strbuf path = STRBUF_INIT;
1013 odb_loose_path(odb, &path, oid);
1014 return check_and_freshen_file(path.buf, freshen);
1017 static int check_and_freshen_local(const struct object_id *oid, int freshen)
1019 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
1022 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
1024 struct object_directory *odb;
1026 prepare_alt_odb(the_repository);
1027 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
1028 if (check_and_freshen_odb(odb, oid, freshen))
1029 return 1;
1031 return 0;
1034 static int check_and_freshen(const struct object_id *oid, int freshen)
1036 return check_and_freshen_local(oid, freshen) ||
1037 check_and_freshen_nonlocal(oid, freshen);
1040 int has_loose_object_nonlocal(const struct object_id *oid)
1042 return check_and_freshen_nonlocal(oid, 0);
1045 int has_loose_object(const struct object_id *oid)
1047 return check_and_freshen(oid, 0);
1050 static void mmap_limit_check(size_t length)
1052 static size_t limit = 0;
1053 if (!limit) {
1054 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1055 if (!limit)
1056 limit = SIZE_MAX;
1058 if (length > limit)
1059 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1060 (uintmax_t)length, (uintmax_t)limit);
1063 void *xmmap_gently(void *start, size_t length,
1064 int prot, int flags, int fd, off_t offset)
1066 void *ret;
1068 mmap_limit_check(length);
1069 ret = mmap(start, length, prot, flags, fd, offset);
1070 if (ret == MAP_FAILED && !length)
1071 ret = NULL;
1072 return ret;
1075 const char *mmap_os_err(void)
1077 static const char blank[] = "";
1078 #if defined(__linux__)
1079 if (errno == ENOMEM) {
1080 /* this continues an existing error message: */
1081 static const char enomem[] =
1082 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1083 return enomem;
1085 #endif /* OS-specific bits */
1086 return blank;
1089 void *xmmap(void *start, size_t length,
1090 int prot, int flags, int fd, off_t offset)
1092 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1093 if (ret == MAP_FAILED)
1094 die_errno(_("mmap failed%s"), mmap_os_err());
1095 return ret;
1098 static int format_object_header_literally(char *str, size_t size,
1099 const char *type, size_t objsize)
1101 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1104 int format_object_header(char *str, size_t size, enum object_type type,
1105 size_t objsize)
1107 const char *name = type_name(type);
1109 if (!name)
1110 BUG("could not get a type name for 'enum object_type' value %d", type);
1112 return format_object_header_literally(str, size, name, objsize);
1115 int check_object_signature(struct repository *r, const struct object_id *oid,
1116 void *buf, unsigned long size,
1117 enum object_type type)
1119 const struct git_hash_algo *algo =
1120 oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
1121 struct object_id real_oid;
1123 hash_object_file(algo, buf, size, type, &real_oid);
1125 return !oideq(oid, &real_oid) ? -1 : 0;
1128 int stream_object_signature(struct repository *r, const struct object_id *oid)
1130 struct object_id real_oid;
1131 unsigned long size;
1132 enum object_type obj_type;
1133 struct git_istream *st;
1134 git_hash_ctx c;
1135 char hdr[MAX_HEADER_LEN];
1136 int hdrlen;
1138 st = open_istream(r, oid, &obj_type, &size, NULL);
1139 if (!st)
1140 return -1;
1142 /* Generate the header */
1143 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
1145 /* Sha1.. */
1146 r->hash_algo->init_fn(&c);
1147 r->hash_algo->update_fn(&c, hdr, hdrlen);
1148 for (;;) {
1149 char buf[1024 * 16];
1150 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1152 if (readlen < 0) {
1153 close_istream(st);
1154 return -1;
1156 if (!readlen)
1157 break;
1158 r->hash_algo->update_fn(&c, buf, readlen);
1160 r->hash_algo->final_oid_fn(&real_oid, &c);
1161 close_istream(st);
1162 return !oideq(oid, &real_oid) ? -1 : 0;
1165 int git_open_cloexec(const char *name, int flags)
1167 int fd;
1168 static int o_cloexec = O_CLOEXEC;
1170 fd = open(name, flags | o_cloexec);
1171 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1172 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1173 o_cloexec &= ~O_CLOEXEC;
1174 fd = open(name, flags | o_cloexec);
1177 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1179 static int fd_cloexec = FD_CLOEXEC;
1181 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1182 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1183 int flags = fcntl(fd, F_GETFD);
1184 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1185 fd_cloexec = 0;
1188 #endif
1189 return fd;
1193 * Find "oid" as a loose object in the local repository or in an alternate.
1194 * Returns 0 on success, negative on failure.
1196 * The "path" out-parameter will give the path of the object we found (if any).
1197 * Note that it may point to static storage and is only valid until another
1198 * call to stat_loose_object().
1200 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1201 struct stat *st, const char **path)
1203 struct object_directory *odb;
1204 static struct strbuf buf = STRBUF_INIT;
1206 prepare_alt_odb(r);
1207 for (odb = r->objects->odb; odb; odb = odb->next) {
1208 *path = odb_loose_path(odb, &buf, oid);
1209 if (!lstat(*path, st))
1210 return 0;
1213 return -1;
1217 * Like stat_loose_object(), but actually open the object and return the
1218 * descriptor. See the caveats on the "path" parameter above.
1220 static int open_loose_object(struct repository *r,
1221 const struct object_id *oid, const char **path)
1223 int fd;
1224 struct object_directory *odb;
1225 int most_interesting_errno = ENOENT;
1226 static struct strbuf buf = STRBUF_INIT;
1228 prepare_alt_odb(r);
1229 for (odb = r->objects->odb; odb; odb = odb->next) {
1230 *path = odb_loose_path(odb, &buf, oid);
1231 fd = git_open(*path);
1232 if (fd >= 0)
1233 return fd;
1235 if (most_interesting_errno == ENOENT)
1236 most_interesting_errno = errno;
1238 errno = most_interesting_errno;
1239 return -1;
1242 static int quick_has_loose(struct repository *r,
1243 const struct object_id *oid)
1245 struct object_directory *odb;
1247 prepare_alt_odb(r);
1248 for (odb = r->objects->odb; odb; odb = odb->next) {
1249 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1250 return 1;
1252 return 0;
1256 * Map and close the given loose object fd. The path argument is used for
1257 * error reporting.
1259 static void *map_fd(int fd, const char *path, unsigned long *size)
1261 void *map = NULL;
1262 struct stat st;
1264 if (!fstat(fd, &st)) {
1265 *size = xsize_t(st.st_size);
1266 if (!*size) {
1267 /* mmap() is forbidden on empty files */
1268 error(_("object file %s is empty"), path);
1269 close(fd);
1270 return NULL;
1272 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1274 close(fd);
1275 return map;
1278 void *map_loose_object(struct repository *r,
1279 const struct object_id *oid,
1280 unsigned long *size)
1282 const char *p;
1283 int fd = open_loose_object(r, oid, &p);
1285 if (fd < 0)
1286 return NULL;
1287 return map_fd(fd, p, size);
1290 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1291 unsigned char *map,
1292 unsigned long mapsize,
1293 void *buffer,
1294 unsigned long bufsiz,
1295 struct strbuf *header)
1297 int status;
1299 /* Get the data stream */
1300 memset(stream, 0, sizeof(*stream));
1301 stream->next_in = map;
1302 stream->avail_in = mapsize;
1303 stream->next_out = buffer;
1304 stream->avail_out = bufsiz;
1306 git_inflate_init(stream);
1307 obj_read_unlock();
1308 status = git_inflate(stream, 0);
1309 obj_read_lock();
1310 if (status < Z_OK)
1311 return ULHR_BAD;
1314 * Check if entire header is unpacked in the first iteration.
1316 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1317 return ULHR_OK;
1320 * We have a header longer than MAX_HEADER_LEN. The "header"
1321 * here is only non-NULL when we run "cat-file
1322 * --allow-unknown-type".
1324 if (!header)
1325 return ULHR_TOO_LONG;
1328 * buffer[0..bufsiz] was not large enough. Copy the partial
1329 * result out to header, and then append the result of further
1330 * reading the stream.
1332 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1333 stream->next_out = buffer;
1334 stream->avail_out = bufsiz;
1336 do {
1337 obj_read_unlock();
1338 status = git_inflate(stream, 0);
1339 obj_read_lock();
1340 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1341 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1342 return 0;
1343 stream->next_out = buffer;
1344 stream->avail_out = bufsiz;
1345 } while (status != Z_STREAM_END);
1346 return ULHR_TOO_LONG;
1349 static void *unpack_loose_rest(git_zstream *stream,
1350 void *buffer, unsigned long size,
1351 const struct object_id *oid)
1353 int bytes = strlen(buffer) + 1;
1354 unsigned char *buf = xmallocz(size);
1355 unsigned long n;
1356 int status = Z_OK;
1358 n = stream->total_out - bytes;
1359 if (n > size)
1360 n = size;
1361 memcpy(buf, (char *) buffer + bytes, n);
1362 bytes = n;
1363 if (bytes <= size) {
1365 * The above condition must be (bytes <= size), not
1366 * (bytes < size). In other words, even though we
1367 * expect no more output and set avail_out to zero,
1368 * the input zlib stream may have bytes that express
1369 * "this concludes the stream", and we *do* want to
1370 * eat that input.
1372 * Otherwise we would not be able to test that we
1373 * consumed all the input to reach the expected size;
1374 * we also want to check that zlib tells us that all
1375 * went well with status == Z_STREAM_END at the end.
1377 stream->next_out = buf + bytes;
1378 stream->avail_out = size - bytes;
1379 while (status == Z_OK) {
1380 obj_read_unlock();
1381 status = git_inflate(stream, Z_FINISH);
1382 obj_read_lock();
1385 if (status == Z_STREAM_END && !stream->avail_in) {
1386 git_inflate_end(stream);
1387 return buf;
1390 if (status < 0)
1391 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1392 else if (stream->avail_in)
1393 error(_("garbage at end of loose object '%s'"),
1394 oid_to_hex(oid));
1395 free(buf);
1396 return NULL;
1400 * We used to just use "sscanf()", but that's actually way
1401 * too permissive for what we want to check. So do an anal
1402 * object header parse by hand.
1404 int parse_loose_header(const char *hdr, struct object_info *oi)
1406 const char *type_buf = hdr;
1407 size_t size;
1408 int type, type_len = 0;
1411 * The type can be of any size but is followed by
1412 * a space.
1414 for (;;) {
1415 char c = *hdr++;
1416 if (!c)
1417 return -1;
1418 if (c == ' ')
1419 break;
1420 type_len++;
1423 type = type_from_string_gently(type_buf, type_len, 1);
1424 if (oi->type_name)
1425 strbuf_add(oi->type_name, type_buf, type_len);
1426 if (oi->typep)
1427 *oi->typep = type;
1430 * The length must follow immediately, and be in canonical
1431 * decimal format (ie "010" is not valid).
1433 size = *hdr++ - '0';
1434 if (size > 9)
1435 return -1;
1436 if (size) {
1437 for (;;) {
1438 unsigned long c = *hdr - '0';
1439 if (c > 9)
1440 break;
1441 hdr++;
1442 size = st_add(st_mult(size, 10), c);
1446 if (oi->sizep)
1447 *oi->sizep = cast_size_t_to_ulong(size);
1450 * The length must be followed by a zero byte
1452 if (*hdr)
1453 return -1;
1456 * The format is valid, but the type may still be bogus. The
1457 * Caller needs to check its oi->typep.
1459 return 0;
1462 static int loose_object_info(struct repository *r,
1463 const struct object_id *oid,
1464 struct object_info *oi, int flags)
1466 int status = 0;
1467 int fd;
1468 unsigned long mapsize;
1469 const char *path;
1470 void *map;
1471 git_zstream stream;
1472 char hdr[MAX_HEADER_LEN];
1473 struct strbuf hdrbuf = STRBUF_INIT;
1474 unsigned long size_scratch;
1475 enum object_type type_scratch;
1476 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
1478 if (oi->delta_base_oid)
1479 oidclr(oi->delta_base_oid, the_repository->hash_algo);
1482 * If we don't care about type or size, then we don't
1483 * need to look inside the object at all. Note that we
1484 * do not optimize out the stat call, even if the
1485 * caller doesn't care about the disk-size, since our
1486 * return value implicitly indicates whether the
1487 * object even exists.
1489 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1490 struct stat st;
1491 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1492 return quick_has_loose(r, oid) ? 0 : -1;
1493 if (stat_loose_object(r, oid, &st, &path) < 0)
1494 return -1;
1495 if (oi->disk_sizep)
1496 *oi->disk_sizep = st.st_size;
1497 return 0;
1500 fd = open_loose_object(r, oid, &path);
1501 if (fd < 0) {
1502 if (errno != ENOENT)
1503 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1504 return -1;
1506 map = map_fd(fd, path, &mapsize);
1507 if (!map)
1508 return -1;
1510 if (!oi->sizep)
1511 oi->sizep = &size_scratch;
1512 if (!oi->typep)
1513 oi->typep = &type_scratch;
1515 if (oi->disk_sizep)
1516 *oi->disk_sizep = mapsize;
1518 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1519 allow_unknown ? &hdrbuf : NULL)) {
1520 case ULHR_OK:
1521 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1522 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1523 else if (!allow_unknown && *oi->typep < 0)
1524 die(_("invalid object type"));
1526 if (!oi->contentp)
1527 break;
1528 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1529 if (*oi->contentp)
1530 goto cleanup;
1532 status = -1;
1533 break;
1534 case ULHR_BAD:
1535 status = error(_("unable to unpack %s header"),
1536 oid_to_hex(oid));
1537 break;
1538 case ULHR_TOO_LONG:
1539 status = error(_("header for %s too long, exceeds %d bytes"),
1540 oid_to_hex(oid), MAX_HEADER_LEN);
1541 break;
1544 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1545 die(_("loose object %s (stored in %s) is corrupt"),
1546 oid_to_hex(oid), path);
1548 git_inflate_end(&stream);
1549 cleanup:
1550 munmap(map, mapsize);
1551 if (oi->sizep == &size_scratch)
1552 oi->sizep = NULL;
1553 strbuf_release(&hdrbuf);
1554 if (oi->typep == &type_scratch)
1555 oi->typep = NULL;
1556 oi->whence = OI_LOOSE;
1557 return status;
1560 int obj_read_use_lock = 0;
1561 pthread_mutex_t obj_read_mutex;
1563 void enable_obj_read_lock(void)
1565 if (obj_read_use_lock)
1566 return;
1568 obj_read_use_lock = 1;
1569 init_recursive_mutex(&obj_read_mutex);
1572 void disable_obj_read_lock(void)
1574 if (!obj_read_use_lock)
1575 return;
1577 obj_read_use_lock = 0;
1578 pthread_mutex_destroy(&obj_read_mutex);
1581 int fetch_if_missing = 1;
1583 static int do_oid_object_info_extended(struct repository *r,
1584 const struct object_id *oid,
1585 struct object_info *oi, unsigned flags)
1587 static struct object_info blank_oi = OBJECT_INFO_INIT;
1588 struct cached_object *co;
1589 struct pack_entry e;
1590 int rtype;
1591 const struct object_id *real = oid;
1592 int already_retried = 0;
1595 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1596 real = lookup_replace_object(r, oid);
1598 if (is_null_oid(real))
1599 return -1;
1601 if (!oi)
1602 oi = &blank_oi;
1604 co = find_cached_object(real);
1605 if (co) {
1606 if (oi->typep)
1607 *(oi->typep) = co->type;
1608 if (oi->sizep)
1609 *(oi->sizep) = co->size;
1610 if (oi->disk_sizep)
1611 *(oi->disk_sizep) = 0;
1612 if (oi->delta_base_oid)
1613 oidclr(oi->delta_base_oid, the_repository->hash_algo);
1614 if (oi->type_name)
1615 strbuf_addstr(oi->type_name, type_name(co->type));
1616 if (oi->contentp)
1617 *oi->contentp = xmemdupz(co->buf, co->size);
1618 oi->whence = OI_CACHED;
1619 return 0;
1622 while (1) {
1623 if (find_pack_entry(r, real, &e))
1624 break;
1626 /* Most likely it's a loose object. */
1627 if (!loose_object_info(r, real, oi, flags))
1628 return 0;
1630 /* Not a loose object; someone else may have just packed it. */
1631 if (!(flags & OBJECT_INFO_QUICK)) {
1632 reprepare_packed_git(r);
1633 if (find_pack_entry(r, real, &e))
1634 break;
1638 * If r is the_repository, this might be an attempt at
1639 * accessing a submodule object as if it were in the_repository
1640 * (having called add_submodule_odb() on that submodule's ODB).
1641 * If any such ODBs exist, register them and try again.
1643 if (r == the_repository &&
1644 register_all_submodule_odb_as_alternates())
1645 /* We added some alternates; retry */
1646 continue;
1648 /* Check if it is a missing object */
1649 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1650 !already_retried &&
1651 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1652 promisor_remote_get_direct(r, real, 1);
1653 already_retried = 1;
1654 continue;
1657 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1658 const struct packed_git *p;
1659 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1660 die(_("replacement %s not found for %s"),
1661 oid_to_hex(real), oid_to_hex(oid));
1662 if ((p = has_packed_and_bad(r, real)))
1663 die(_("packed object %s (stored in %s) is corrupt"),
1664 oid_to_hex(real), p->pack_name);
1666 return -1;
1669 if (oi == &blank_oi)
1671 * We know that the caller doesn't actually need the
1672 * information below, so return early.
1674 return 0;
1675 rtype = packed_object_info(r, e.p, e.offset, oi);
1676 if (rtype < 0) {
1677 mark_bad_packed_object(e.p, real);
1678 return do_oid_object_info_extended(r, real, oi, 0);
1679 } else if (oi->whence == OI_PACKED) {
1680 oi->u.packed.offset = e.offset;
1681 oi->u.packed.pack = e.p;
1682 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1683 rtype == OBJ_OFS_DELTA);
1686 return 0;
1689 static int oid_object_info_convert(struct repository *r,
1690 const struct object_id *input_oid,
1691 struct object_info *input_oi, unsigned flags)
1693 const struct git_hash_algo *input_algo = &hash_algos[input_oid->algo];
1694 int do_die = flags & OBJECT_INFO_DIE_IF_CORRUPT;
1695 struct strbuf type_name = STRBUF_INIT;
1696 struct object_id oid, delta_base_oid;
1697 struct object_info new_oi, *oi;
1698 unsigned long size;
1699 void *content;
1700 int ret;
1702 if (repo_oid_to_algop(r, input_oid, the_hash_algo, &oid)) {
1703 if (do_die)
1704 die(_("missing mapping of %s to %s"),
1705 oid_to_hex(input_oid), the_hash_algo->name);
1706 return -1;
1709 /* Is new_oi needed? */
1710 oi = input_oi;
1711 if (input_oi && (input_oi->delta_base_oid || input_oi->sizep ||
1712 input_oi->contentp)) {
1713 new_oi = *input_oi;
1714 /* Does delta_base_oid need to be converted? */
1715 if (input_oi->delta_base_oid)
1716 new_oi.delta_base_oid = &delta_base_oid;
1717 /* Will the attributes differ when converted? */
1718 if (input_oi->sizep || input_oi->contentp) {
1719 new_oi.contentp = &content;
1720 new_oi.sizep = &size;
1721 new_oi.type_name = &type_name;
1723 oi = &new_oi;
1726 ret = oid_object_info_extended(r, &oid, oi, flags);
1727 if (ret)
1728 return -1;
1729 if (oi == input_oi)
1730 return ret;
1732 if (new_oi.contentp) {
1733 struct strbuf outbuf = STRBUF_INIT;
1734 enum object_type type;
1736 type = type_from_string_gently(type_name.buf, type_name.len,
1737 !do_die);
1738 if (type == -1)
1739 return -1;
1740 if (type != OBJ_BLOB) {
1741 ret = convert_object_file(&outbuf,
1742 the_hash_algo, input_algo,
1743 content, size, type, !do_die);
1744 free(content);
1745 if (ret == -1)
1746 return -1;
1747 size = outbuf.len;
1748 content = strbuf_detach(&outbuf, NULL);
1750 if (input_oi->sizep)
1751 *input_oi->sizep = size;
1752 if (input_oi->contentp)
1753 *input_oi->contentp = content;
1754 else
1755 free(content);
1756 if (input_oi->type_name)
1757 *input_oi->type_name = type_name;
1758 else
1759 strbuf_release(&type_name);
1761 if (new_oi.delta_base_oid == &delta_base_oid) {
1762 if (repo_oid_to_algop(r, &delta_base_oid, input_algo,
1763 input_oi->delta_base_oid)) {
1764 if (do_die)
1765 die(_("missing mapping of %s to %s"),
1766 oid_to_hex(&delta_base_oid),
1767 input_algo->name);
1768 return -1;
1771 input_oi->whence = new_oi.whence;
1772 input_oi->u = new_oi.u;
1773 return ret;
1776 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1777 struct object_info *oi, unsigned flags)
1779 int ret;
1781 if (oid->algo && (hash_algo_by_ptr(r->hash_algo) != oid->algo))
1782 return oid_object_info_convert(r, oid, oi, flags);
1784 obj_read_lock();
1785 ret = do_oid_object_info_extended(r, oid, oi, flags);
1786 obj_read_unlock();
1787 return ret;
1791 /* returns enum object_type or negative */
1792 int oid_object_info(struct repository *r,
1793 const struct object_id *oid,
1794 unsigned long *sizep)
1796 enum object_type type;
1797 struct object_info oi = OBJECT_INFO_INIT;
1799 oi.typep = &type;
1800 oi.sizep = sizep;
1801 if (oid_object_info_extended(r, oid, &oi,
1802 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1803 return -1;
1804 return type;
1807 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1808 struct object_id *oid)
1810 struct cached_object *co;
1811 char *co_buf;
1813 hash_object_file(the_hash_algo, buf, len, type, oid);
1814 if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1815 find_cached_object(oid))
1816 return 0;
1817 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1818 co = &cached_objects[cached_object_nr++];
1819 co->size = len;
1820 co->type = type;
1821 co_buf = xmalloc(len);
1822 memcpy(co_buf, buf, len);
1823 co->buf = co_buf;
1824 oidcpy(&co->oid, oid);
1825 return 0;
1829 * This function dies on corrupt objects; the callers who want to
1830 * deal with them should arrange to call oid_object_info_extended() and give
1831 * error messages themselves.
1833 void *repo_read_object_file(struct repository *r,
1834 const struct object_id *oid,
1835 enum object_type *type,
1836 unsigned long *size)
1838 struct object_info oi = OBJECT_INFO_INIT;
1839 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
1840 void *data;
1842 oi.typep = type;
1843 oi.sizep = size;
1844 oi.contentp = &data;
1845 if (oid_object_info_extended(r, oid, &oi, flags))
1846 return NULL;
1848 return data;
1851 void *read_object_with_reference(struct repository *r,
1852 const struct object_id *oid,
1853 enum object_type required_type,
1854 unsigned long *size,
1855 struct object_id *actual_oid_return)
1857 enum object_type type;
1858 void *buffer;
1859 unsigned long isize;
1860 struct object_id actual_oid;
1862 oidcpy(&actual_oid, oid);
1863 while (1) {
1864 int ref_length = -1;
1865 const char *ref_type = NULL;
1867 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1868 if (!buffer)
1869 return NULL;
1870 if (type == required_type) {
1871 *size = isize;
1872 if (actual_oid_return)
1873 oidcpy(actual_oid_return, &actual_oid);
1874 return buffer;
1876 /* Handle references */
1877 else if (type == OBJ_COMMIT)
1878 ref_type = "tree ";
1879 else if (type == OBJ_TAG)
1880 ref_type = "object ";
1881 else {
1882 free(buffer);
1883 return NULL;
1885 ref_length = strlen(ref_type);
1887 if (ref_length + the_hash_algo->hexsz > isize ||
1888 memcmp(buffer, ref_type, ref_length) ||
1889 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1890 free(buffer);
1891 return NULL;
1893 free(buffer);
1894 /* Now we have the ID of the referred-to object in
1895 * actual_oid. Check again. */
1899 static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1900 const void *buf, unsigned long len,
1901 struct object_id *oid,
1902 char *hdr, int *hdrlen)
1904 algo->init_fn(c);
1905 algo->update_fn(c, hdr, *hdrlen);
1906 algo->update_fn(c, buf, len);
1907 algo->final_oid_fn(oid, c);
1910 static void write_object_file_prepare(const struct git_hash_algo *algo,
1911 const void *buf, unsigned long len,
1912 enum object_type type, struct object_id *oid,
1913 char *hdr, int *hdrlen)
1915 git_hash_ctx c;
1917 /* Generate the header */
1918 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
1920 /* Sha1.. */
1921 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1924 static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1925 const void *buf, unsigned long len,
1926 const char *type, struct object_id *oid,
1927 char *hdr, int *hdrlen)
1929 git_hash_ctx c;
1931 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1932 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1936 * Move the just written object into its final resting place.
1938 int finalize_object_file(const char *tmpfile, const char *filename)
1940 int ret = 0;
1942 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1943 goto try_rename;
1944 else if (link(tmpfile, filename))
1945 ret = errno;
1948 * Coda hack - coda doesn't like cross-directory links,
1949 * so we fall back to a rename, which will mean that it
1950 * won't be able to check collisions, but that's not a
1951 * big deal.
1953 * The same holds for FAT formatted media.
1955 * When this succeeds, we just return. We have nothing
1956 * left to unlink.
1958 if (ret && ret != EEXIST) {
1959 try_rename:
1960 if (!rename(tmpfile, filename))
1961 goto out;
1962 ret = errno;
1964 unlink_or_warn(tmpfile);
1965 if (ret) {
1966 if (ret != EEXIST) {
1967 return error_errno(_("unable to write file %s"), filename);
1969 /* FIXME!!! Collision check here ? */
1972 out:
1973 if (adjust_shared_perm(filename))
1974 return error(_("unable to set permission to '%s'"), filename);
1975 return 0;
1978 static void hash_object_file_literally(const struct git_hash_algo *algo,
1979 const void *buf, unsigned long len,
1980 const char *type, struct object_id *oid)
1982 char hdr[MAX_HEADER_LEN];
1983 int hdrlen = sizeof(hdr);
1985 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
1988 void hash_object_file(const struct git_hash_algo *algo, const void *buf,
1989 unsigned long len, enum object_type type,
1990 struct object_id *oid)
1992 hash_object_file_literally(algo, buf, len, type_name(type), oid);
1995 /* Finalize a file on disk, and close it. */
1996 static void close_loose_object(int fd, const char *filename)
1998 if (the_repository->objects->odb->will_destroy)
1999 goto out;
2001 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2002 fsync_loose_object_bulk_checkin(fd, filename);
2003 else if (fsync_object_files > 0)
2004 fsync_or_die(fd, filename);
2005 else
2006 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
2007 filename);
2009 out:
2010 if (close(fd) != 0)
2011 die_errno(_("error when closing loose object file"));
2014 /* Size of directory component, including the ending '/' */
2015 static inline int directory_size(const char *filename)
2017 const char *s = strrchr(filename, '/');
2018 if (!s)
2019 return 0;
2020 return s - filename + 1;
2024 * This creates a temporary file in the same directory as the final
2025 * 'filename'
2027 * We want to avoid cross-directory filename renames, because those
2028 * can have problems on various filesystems (FAT, NFS, Coda).
2030 static int create_tmpfile(struct strbuf *tmp, const char *filename)
2032 int fd, dirlen = directory_size(filename);
2034 strbuf_reset(tmp);
2035 strbuf_add(tmp, filename, dirlen);
2036 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2037 fd = git_mkstemp_mode(tmp->buf, 0444);
2038 if (fd < 0 && dirlen && errno == ENOENT) {
2040 * Make sure the directory exists; note that the contents
2041 * of the buffer are undefined after mkstemp returns an
2042 * error, so we have to rewrite the whole buffer from
2043 * scratch.
2045 strbuf_reset(tmp);
2046 strbuf_add(tmp, filename, dirlen - 1);
2047 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
2048 return -1;
2049 if (adjust_shared_perm(tmp->buf))
2050 return -1;
2052 /* Try again */
2053 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2054 fd = git_mkstemp_mode(tmp->buf, 0444);
2056 return fd;
2060 * Common steps for loose object writers to start writing loose
2061 * objects:
2063 * - Create tmpfile for the loose object.
2064 * - Setup zlib stream for compression.
2065 * - Start to feed header to zlib stream.
2067 * Returns a "fd", which should later be provided to
2068 * end_loose_object_common().
2070 static int start_loose_object_common(struct strbuf *tmp_file,
2071 const char *filename, unsigned flags,
2072 git_zstream *stream,
2073 unsigned char *buf, size_t buflen,
2074 git_hash_ctx *c, git_hash_ctx *compat_c,
2075 char *hdr, int hdrlen)
2077 struct repository *repo = the_repository;
2078 const struct git_hash_algo *algo = repo->hash_algo;
2079 const struct git_hash_algo *compat = repo->compat_hash_algo;
2080 int fd;
2082 fd = create_tmpfile(tmp_file, filename);
2083 if (fd < 0) {
2084 if (flags & HASH_SILENT)
2085 return -1;
2086 else if (errno == EACCES)
2087 return error(_("insufficient permission for adding "
2088 "an object to repository database %s"),
2089 repo_get_object_directory(the_repository));
2090 else
2091 return error_errno(
2092 _("unable to create temporary file"));
2095 /* Setup zlib stream for compression */
2096 git_deflate_init(stream, zlib_compression_level);
2097 stream->next_out = buf;
2098 stream->avail_out = buflen;
2099 algo->init_fn(c);
2100 if (compat && compat_c)
2101 compat->init_fn(compat_c);
2103 /* Start to feed header to zlib stream */
2104 stream->next_in = (unsigned char *)hdr;
2105 stream->avail_in = hdrlen;
2106 while (git_deflate(stream, 0) == Z_OK)
2107 ; /* nothing */
2108 algo->update_fn(c, hdr, hdrlen);
2109 if (compat && compat_c)
2110 compat->update_fn(compat_c, hdr, hdrlen);
2112 return fd;
2116 * Common steps for the inner git_deflate() loop for writing loose
2117 * objects. Returns what git_deflate() returns.
2119 static int write_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
2120 git_zstream *stream, const int flush,
2121 unsigned char *in0, const int fd,
2122 unsigned char *compressed,
2123 const size_t compressed_len)
2125 struct repository *repo = the_repository;
2126 const struct git_hash_algo *algo = repo->hash_algo;
2127 const struct git_hash_algo *compat = repo->compat_hash_algo;
2128 int ret;
2130 ret = git_deflate(stream, flush ? Z_FINISH : 0);
2131 algo->update_fn(c, in0, stream->next_in - in0);
2132 if (compat && compat_c)
2133 compat->update_fn(compat_c, in0, stream->next_in - in0);
2134 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
2135 die_errno(_("unable to write loose object file"));
2136 stream->next_out = compressed;
2137 stream->avail_out = compressed_len;
2139 return ret;
2143 * Common steps for loose object writers to end writing loose objects:
2145 * - End the compression of zlib stream.
2146 * - Get the calculated oid to "oid".
2148 static int end_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
2149 git_zstream *stream, struct object_id *oid,
2150 struct object_id *compat_oid)
2152 struct repository *repo = the_repository;
2153 const struct git_hash_algo *algo = repo->hash_algo;
2154 const struct git_hash_algo *compat = repo->compat_hash_algo;
2155 int ret;
2157 ret = git_deflate_end_gently(stream);
2158 if (ret != Z_OK)
2159 return ret;
2160 algo->final_oid_fn(oid, c);
2161 if (compat && compat_c)
2162 compat->final_oid_fn(compat_oid, compat_c);
2164 return Z_OK;
2167 static int write_loose_object(const struct object_id *oid, char *hdr,
2168 int hdrlen, const void *buf, unsigned long len,
2169 time_t mtime, unsigned flags)
2171 int fd, ret;
2172 unsigned char compressed[4096];
2173 git_zstream stream;
2174 git_hash_ctx c;
2175 struct object_id parano_oid;
2176 static struct strbuf tmp_file = STRBUF_INIT;
2177 static struct strbuf filename = STRBUF_INIT;
2179 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2180 prepare_loose_object_bulk_checkin();
2182 loose_object_path(the_repository, &filename, oid);
2184 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2185 &stream, compressed, sizeof(compressed),
2186 &c, NULL, hdr, hdrlen);
2187 if (fd < 0)
2188 return -1;
2190 /* Then the data itself.. */
2191 stream.next_in = (void *)buf;
2192 stream.avail_in = len;
2193 do {
2194 unsigned char *in0 = stream.next_in;
2196 ret = write_loose_object_common(&c, NULL, &stream, 1, in0, fd,
2197 compressed, sizeof(compressed));
2198 } while (ret == Z_OK);
2200 if (ret != Z_STREAM_END)
2201 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
2202 ret);
2203 ret = end_loose_object_common(&c, NULL, &stream, &parano_oid, NULL);
2204 if (ret != Z_OK)
2205 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
2206 ret);
2207 if (!oideq(oid, &parano_oid))
2208 die(_("confused by unstable object source data for %s"),
2209 oid_to_hex(oid));
2211 close_loose_object(fd, tmp_file.buf);
2213 if (mtime) {
2214 struct utimbuf utb;
2215 utb.actime = mtime;
2216 utb.modtime = mtime;
2217 if (utime(tmp_file.buf, &utb) < 0 &&
2218 !(flags & HASH_SILENT))
2219 warning_errno(_("failed utime() on %s"), tmp_file.buf);
2222 return finalize_object_file(tmp_file.buf, filename.buf);
2225 static int freshen_loose_object(const struct object_id *oid)
2227 return check_and_freshen(oid, 1);
2230 static int freshen_packed_object(const struct object_id *oid)
2232 struct pack_entry e;
2233 if (!find_pack_entry(the_repository, oid, &e))
2234 return 0;
2235 if (e.p->is_cruft)
2236 return 0;
2237 if (e.p->freshened)
2238 return 1;
2239 if (!freshen_file(e.p->pack_name))
2240 return 0;
2241 e.p->freshened = 1;
2242 return 1;
2245 int stream_loose_object(struct input_stream *in_stream, size_t len,
2246 struct object_id *oid)
2248 const struct git_hash_algo *compat = the_repository->compat_hash_algo;
2249 struct object_id compat_oid;
2250 int fd, ret, err = 0, flush = 0;
2251 unsigned char compressed[4096];
2252 git_zstream stream;
2253 git_hash_ctx c, compat_c;
2254 struct strbuf tmp_file = STRBUF_INIT;
2255 struct strbuf filename = STRBUF_INIT;
2256 int dirlen;
2257 char hdr[MAX_HEADER_LEN];
2258 int hdrlen;
2260 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2261 prepare_loose_object_bulk_checkin();
2263 /* Since oid is not determined, save tmp file to odb path. */
2264 strbuf_addf(&filename, "%s/", repo_get_object_directory(the_repository));
2265 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2268 * Common steps for write_loose_object and stream_loose_object to
2269 * start writing loose objects:
2271 * - Create tmpfile for the loose object.
2272 * - Setup zlib stream for compression.
2273 * - Start to feed header to zlib stream.
2275 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2276 &stream, compressed, sizeof(compressed),
2277 &c, &compat_c, hdr, hdrlen);
2278 if (fd < 0) {
2279 err = -1;
2280 goto cleanup;
2283 /* Then the data itself.. */
2284 do {
2285 unsigned char *in0 = stream.next_in;
2287 if (!stream.avail_in && !in_stream->is_finished) {
2288 const void *in = in_stream->read(in_stream, &stream.avail_in);
2289 stream.next_in = (void *)in;
2290 in0 = (unsigned char *)in;
2291 /* All data has been read. */
2292 if (in_stream->is_finished)
2293 flush = 1;
2295 ret = write_loose_object_common(&c, &compat_c, &stream, flush, in0, fd,
2296 compressed, sizeof(compressed));
2298 * Unlike write_loose_object(), we do not have the entire
2299 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2300 * then we'll replenish them in the next input_stream->read()
2301 * call when we loop.
2303 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2305 if (stream.total_in != len + hdrlen)
2306 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2307 (uintmax_t)len + hdrlen);
2310 * Common steps for write_loose_object and stream_loose_object to
2311 * end writing loose oject:
2313 * - End the compression of zlib stream.
2314 * - Get the calculated oid.
2316 if (ret != Z_STREAM_END)
2317 die(_("unable to stream deflate new object (%d)"), ret);
2318 ret = end_loose_object_common(&c, &compat_c, &stream, oid, &compat_oid);
2319 if (ret != Z_OK)
2320 die(_("deflateEnd on stream object failed (%d)"), ret);
2321 close_loose_object(fd, tmp_file.buf);
2323 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2324 unlink_or_warn(tmp_file.buf);
2325 goto cleanup;
2328 loose_object_path(the_repository, &filename, oid);
2330 /* We finally know the object path, and create the missing dir. */
2331 dirlen = directory_size(filename.buf);
2332 if (dirlen) {
2333 struct strbuf dir = STRBUF_INIT;
2334 strbuf_add(&dir, filename.buf, dirlen);
2336 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2337 err = error_errno(_("unable to create directory %s"), dir.buf);
2338 strbuf_release(&dir);
2339 goto cleanup;
2341 strbuf_release(&dir);
2344 err = finalize_object_file(tmp_file.buf, filename.buf);
2345 if (!err && compat)
2346 err = repo_add_loose_object_map(the_repository, oid, &compat_oid);
2347 cleanup:
2348 strbuf_release(&tmp_file);
2349 strbuf_release(&filename);
2350 return err;
2353 int write_object_file_flags(const void *buf, unsigned long len,
2354 enum object_type type, struct object_id *oid,
2355 struct object_id *compat_oid_in, unsigned flags)
2357 struct repository *repo = the_repository;
2358 const struct git_hash_algo *algo = repo->hash_algo;
2359 const struct git_hash_algo *compat = repo->compat_hash_algo;
2360 struct object_id compat_oid;
2361 char hdr[MAX_HEADER_LEN];
2362 int hdrlen = sizeof(hdr);
2364 /* Generate compat_oid */
2365 if (compat) {
2366 if (compat_oid_in)
2367 oidcpy(&compat_oid, compat_oid_in);
2368 else if (type == OBJ_BLOB)
2369 hash_object_file(compat, buf, len, type, &compat_oid);
2370 else {
2371 struct strbuf converted = STRBUF_INIT;
2372 convert_object_file(&converted, algo, compat,
2373 buf, len, type, 0);
2374 hash_object_file(compat, converted.buf, converted.len,
2375 type, &compat_oid);
2376 strbuf_release(&converted);
2380 /* Normally if we have it in the pack then we do not bother writing
2381 * it out into .git/objects/??/?{38} file.
2383 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
2384 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2385 return 0;
2386 if (write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags))
2387 return -1;
2388 if (compat)
2389 return repo_add_loose_object_map(repo, oid, &compat_oid);
2390 return 0;
2393 int write_object_file_literally(const void *buf, unsigned long len,
2394 const char *type, struct object_id *oid,
2395 unsigned flags)
2397 char *header;
2398 struct repository *repo = the_repository;
2399 const struct git_hash_algo *algo = repo->hash_algo;
2400 const struct git_hash_algo *compat = repo->compat_hash_algo;
2401 struct object_id compat_oid;
2402 int hdrlen, status = 0;
2403 int compat_type = -1;
2405 if (compat) {
2406 compat_type = type_from_string_gently(type, -1, 1);
2407 if (compat_type == OBJ_BLOB)
2408 hash_object_file(compat, buf, len, compat_type,
2409 &compat_oid);
2410 else if (compat_type != -1) {
2411 struct strbuf converted = STRBUF_INIT;
2412 convert_object_file(&converted, algo, compat,
2413 buf, len, compat_type, 0);
2414 hash_object_file(compat, converted.buf, converted.len,
2415 compat_type, &compat_oid);
2416 strbuf_release(&converted);
2420 /* type string, SP, %lu of the length plus NUL must fit this */
2421 hdrlen = strlen(type) + MAX_HEADER_LEN;
2422 header = xmalloc(hdrlen);
2423 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2424 oid, header, &hdrlen);
2426 if (!(flags & HASH_WRITE_OBJECT))
2427 goto cleanup;
2428 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2429 goto cleanup;
2430 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
2431 if (compat_type != -1)
2432 return repo_add_loose_object_map(repo, oid, &compat_oid);
2434 cleanup:
2435 free(header);
2436 return status;
2439 int force_object_loose(const struct object_id *oid, time_t mtime)
2441 struct repository *repo = the_repository;
2442 const struct git_hash_algo *compat = repo->compat_hash_algo;
2443 void *buf;
2444 unsigned long len;
2445 struct object_info oi = OBJECT_INFO_INIT;
2446 struct object_id compat_oid;
2447 enum object_type type;
2448 char hdr[MAX_HEADER_LEN];
2449 int hdrlen;
2450 int ret;
2452 if (has_loose_object(oid))
2453 return 0;
2454 oi.typep = &type;
2455 oi.sizep = &len;
2456 oi.contentp = &buf;
2457 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2458 return error(_("cannot read object for %s"), oid_to_hex(oid));
2459 if (compat) {
2460 if (repo_oid_to_algop(repo, oid, compat, &compat_oid))
2461 return error(_("cannot map object %s to %s"),
2462 oid_to_hex(oid), compat->name);
2464 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
2465 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
2466 if (!ret && compat)
2467 ret = repo_add_loose_object_map(the_repository, oid, &compat_oid);
2468 free(buf);
2470 return ret;
2473 int has_object(struct repository *r, const struct object_id *oid,
2474 unsigned flags)
2476 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2477 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2478 (quick ? OBJECT_INFO_QUICK : 0);
2480 if (!startup_info->have_repository)
2481 return 0;
2482 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2485 int repo_has_object_file_with_flags(struct repository *r,
2486 const struct object_id *oid, int flags)
2488 if (!startup_info->have_repository)
2489 return 0;
2490 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2493 int repo_has_object_file(struct repository *r,
2494 const struct object_id *oid)
2496 return repo_has_object_file_with_flags(r, oid, 0);
2500 * We can't use the normal fsck_error_function() for index_mem(),
2501 * because we don't yet have a valid oid for it to report. Instead,
2502 * report the minimal fsck error here, and rely on the caller to
2503 * give more context.
2505 static int hash_format_check_report(struct fsck_options *opts UNUSED,
2506 void *fsck_report UNUSED,
2507 enum fsck_msg_type msg_type UNUSED,
2508 enum fsck_msg_id msg_id UNUSED,
2509 const char *message)
2511 error(_("object fails fsck: %s"), message);
2512 return 1;
2515 static int index_mem(struct index_state *istate,
2516 struct object_id *oid,
2517 const void *buf, size_t size,
2518 enum object_type type,
2519 const char *path, unsigned flags)
2521 struct strbuf nbuf = STRBUF_INIT;
2522 int ret = 0;
2523 int write_object = flags & HASH_WRITE_OBJECT;
2525 if (!type)
2526 type = OBJ_BLOB;
2529 * Convert blobs to git internal format
2531 if ((type == OBJ_BLOB) && path) {
2532 if (convert_to_git(istate, path, buf, size, &nbuf,
2533 get_conv_flags(flags))) {
2534 buf = nbuf.buf;
2535 size = nbuf.len;
2538 if (flags & HASH_FORMAT_CHECK) {
2539 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2541 opts.strict = 1;
2542 opts.error_func = hash_format_check_report;
2543 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2544 die(_("refusing to create malformed object"));
2545 fsck_finish(&opts);
2548 if (write_object)
2549 ret = write_object_file(buf, size, type, oid);
2550 else
2551 hash_object_file(the_hash_algo, buf, size, type, oid);
2553 strbuf_release(&nbuf);
2554 return ret;
2557 static int index_stream_convert_blob(struct index_state *istate,
2558 struct object_id *oid,
2559 int fd,
2560 const char *path,
2561 unsigned flags)
2563 int ret = 0;
2564 const int write_object = flags & HASH_WRITE_OBJECT;
2565 struct strbuf sbuf = STRBUF_INIT;
2567 assert(path);
2568 assert(would_convert_to_git_filter_fd(istate, path));
2570 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2571 get_conv_flags(flags));
2573 if (write_object)
2574 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
2575 oid);
2576 else
2577 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2578 oid);
2579 strbuf_release(&sbuf);
2580 return ret;
2583 static int index_pipe(struct index_state *istate, struct object_id *oid,
2584 int fd, enum object_type type,
2585 const char *path, unsigned flags)
2587 struct strbuf sbuf = STRBUF_INIT;
2588 int ret;
2590 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2591 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2592 else
2593 ret = -1;
2594 strbuf_release(&sbuf);
2595 return ret;
2598 #define SMALL_FILE_SIZE (32*1024)
2600 static int index_core(struct index_state *istate,
2601 struct object_id *oid, int fd, size_t size,
2602 enum object_type type, const char *path,
2603 unsigned flags)
2605 int ret;
2607 if (!size) {
2608 ret = index_mem(istate, oid, "", size, type, path, flags);
2609 } else if (size <= SMALL_FILE_SIZE) {
2610 char *buf = xmalloc(size);
2611 ssize_t read_result = read_in_full(fd, buf, size);
2612 if (read_result < 0)
2613 ret = error_errno(_("read error while indexing %s"),
2614 path ? path : "<unknown>");
2615 else if (read_result != size)
2616 ret = error(_("short read while indexing %s"),
2617 path ? path : "<unknown>");
2618 else
2619 ret = index_mem(istate, oid, buf, size, type, path, flags);
2620 free(buf);
2621 } else {
2622 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2623 ret = index_mem(istate, oid, buf, size, type, path, flags);
2624 munmap(buf, size);
2626 return ret;
2630 * This creates one packfile per large blob unless bulk-checkin
2631 * machinery is "plugged".
2633 * This also bypasses the usual "convert-to-git" dance, and that is on
2634 * purpose. We could write a streaming version of the converting
2635 * functions and insert that before feeding the data to fast-import
2636 * (or equivalent in-core API described above). However, that is
2637 * somewhat complicated, as we do not know the size of the filter
2638 * result, which we need to know beforehand when writing a git object.
2639 * Since the primary motivation for trying to stream from the working
2640 * tree file and to avoid mmaping it in core is to deal with large
2641 * binary blobs, they generally do not want to get any conversion, and
2642 * callers should avoid this code path when filters are requested.
2644 static int index_blob_stream(struct object_id *oid, int fd, size_t size,
2645 const char *path,
2646 unsigned flags)
2648 return index_blob_bulk_checkin(oid, fd, size, path, flags);
2651 int index_fd(struct index_state *istate, struct object_id *oid,
2652 int fd, struct stat *st,
2653 enum object_type type, const char *path, unsigned flags)
2655 int ret;
2658 * Call xsize_t() only when needed to avoid potentially unnecessary
2659 * die() for large files.
2661 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2662 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2663 else if (!S_ISREG(st->st_mode))
2664 ret = index_pipe(istate, oid, fd, type, path, flags);
2665 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2666 (path && would_convert_to_git(istate, path)))
2667 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2668 type, path, flags);
2669 else
2670 ret = index_blob_stream(oid, fd, xsize_t(st->st_size), path,
2671 flags);
2672 close(fd);
2673 return ret;
2676 int index_path(struct index_state *istate, struct object_id *oid,
2677 const char *path, struct stat *st, unsigned flags)
2679 int fd;
2680 struct strbuf sb = STRBUF_INIT;
2681 int rc = 0;
2683 switch (st->st_mode & S_IFMT) {
2684 case S_IFREG:
2685 fd = open(path, O_RDONLY);
2686 if (fd < 0)
2687 return error_errno("open(\"%s\")", path);
2688 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2689 return error(_("%s: failed to insert into database"),
2690 path);
2691 break;
2692 case S_IFLNK:
2693 if (strbuf_readlink(&sb, path, st->st_size))
2694 return error_errno("readlink(\"%s\")", path);
2695 if (!(flags & HASH_WRITE_OBJECT))
2696 hash_object_file(the_hash_algo, sb.buf, sb.len,
2697 OBJ_BLOB, oid);
2698 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
2699 rc = error(_("%s: failed to insert into database"), path);
2700 strbuf_release(&sb);
2701 break;
2702 case S_IFDIR:
2703 return repo_resolve_gitlink_ref(the_repository, path, "HEAD", oid);
2704 default:
2705 return error(_("%s: unsupported file type"), path);
2707 return rc;
2710 int read_pack_header(int fd, struct pack_header *header)
2712 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2713 /* "eof before pack header was fully read" */
2714 return PH_ERROR_EOF;
2716 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2717 /* "protocol error (pack signature mismatch detected)" */
2718 return PH_ERROR_PACK_SIGNATURE;
2719 if (!pack_version_ok(header->hdr_version))
2720 /* "protocol error (pack version unsupported)" */
2721 return PH_ERROR_PROTOCOL;
2722 return 0;
2725 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2727 enum object_type type = oid_object_info(the_repository, oid, NULL);
2728 if (type < 0)
2729 die(_("%s is not a valid object"), oid_to_hex(oid));
2730 if (type != expect)
2731 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2732 type_name(expect));
2735 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2736 struct strbuf *path,
2737 each_loose_object_fn obj_cb,
2738 each_loose_cruft_fn cruft_cb,
2739 each_loose_subdir_fn subdir_cb,
2740 void *data)
2742 size_t origlen, baselen;
2743 DIR *dir;
2744 struct dirent *de;
2745 int r = 0;
2746 struct object_id oid;
2748 if (subdir_nr > 0xff)
2749 BUG("invalid loose object subdirectory: %x", subdir_nr);
2751 origlen = path->len;
2752 strbuf_complete(path, '/');
2753 strbuf_addf(path, "%02x", subdir_nr);
2755 dir = opendir(path->buf);
2756 if (!dir) {
2757 if (errno != ENOENT)
2758 r = error_errno(_("unable to open %s"), path->buf);
2759 strbuf_setlen(path, origlen);
2760 return r;
2763 oid.hash[0] = subdir_nr;
2764 strbuf_addch(path, '/');
2765 baselen = path->len;
2767 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2768 size_t namelen;
2770 namelen = strlen(de->d_name);
2771 strbuf_setlen(path, baselen);
2772 strbuf_add(path, de->d_name, namelen);
2773 if (namelen == the_hash_algo->hexsz - 2 &&
2774 !hex_to_bytes(oid.hash + 1, de->d_name,
2775 the_hash_algo->rawsz - 1)) {
2776 oid_set_algo(&oid, the_hash_algo);
2777 memset(oid.hash + the_hash_algo->rawsz, 0,
2778 GIT_MAX_RAWSZ - the_hash_algo->rawsz);
2779 if (obj_cb) {
2780 r = obj_cb(&oid, path->buf, data);
2781 if (r)
2782 break;
2784 continue;
2787 if (cruft_cb) {
2788 r = cruft_cb(de->d_name, path->buf, data);
2789 if (r)
2790 break;
2793 closedir(dir);
2795 strbuf_setlen(path, baselen - 1);
2796 if (!r && subdir_cb)
2797 r = subdir_cb(subdir_nr, path->buf, data);
2799 strbuf_setlen(path, origlen);
2801 return r;
2804 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2805 each_loose_object_fn obj_cb,
2806 each_loose_cruft_fn cruft_cb,
2807 each_loose_subdir_fn subdir_cb,
2808 void *data)
2810 int r = 0;
2811 int i;
2813 for (i = 0; i < 256; i++) {
2814 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2815 subdir_cb, data);
2816 if (r)
2817 break;
2820 return r;
2823 int for_each_loose_file_in_objdir(const char *path,
2824 each_loose_object_fn obj_cb,
2825 each_loose_cruft_fn cruft_cb,
2826 each_loose_subdir_fn subdir_cb,
2827 void *data)
2829 struct strbuf buf = STRBUF_INIT;
2830 int r;
2832 strbuf_addstr(&buf, path);
2833 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2834 subdir_cb, data);
2835 strbuf_release(&buf);
2837 return r;
2840 int for_each_loose_object(each_loose_object_fn cb, void *data,
2841 enum for_each_object_flags flags)
2843 struct object_directory *odb;
2845 prepare_alt_odb(the_repository);
2846 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2847 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2848 NULL, data);
2849 if (r)
2850 return r;
2852 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2853 break;
2856 return 0;
2859 static int append_loose_object(const struct object_id *oid,
2860 const char *path UNUSED,
2861 void *data)
2863 oidtree_insert(data, oid);
2864 return 0;
2867 struct oidtree *odb_loose_cache(struct object_directory *odb,
2868 const struct object_id *oid)
2870 int subdir_nr = oid->hash[0];
2871 struct strbuf buf = STRBUF_INIT;
2872 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2873 size_t word_index = subdir_nr / word_bits;
2874 size_t mask = (size_t)1u << (subdir_nr % word_bits);
2875 uint32_t *bitmap;
2877 if (subdir_nr < 0 ||
2878 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2879 BUG("subdir_nr out of range");
2881 bitmap = &odb->loose_objects_subdir_seen[word_index];
2882 if (*bitmap & mask)
2883 return odb->loose_objects_cache;
2884 if (!odb->loose_objects_cache) {
2885 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2886 oidtree_init(odb->loose_objects_cache);
2888 strbuf_addstr(&buf, odb->path);
2889 for_each_file_in_obj_subdir(subdir_nr, &buf,
2890 append_loose_object,
2891 NULL, NULL,
2892 odb->loose_objects_cache);
2893 *bitmap |= mask;
2894 strbuf_release(&buf);
2895 return odb->loose_objects_cache;
2898 void odb_clear_loose_cache(struct object_directory *odb)
2900 oidtree_clear(odb->loose_objects_cache);
2901 FREE_AND_NULL(odb->loose_objects_cache);
2902 memset(&odb->loose_objects_subdir_seen, 0,
2903 sizeof(odb->loose_objects_subdir_seen));
2906 static int check_stream_oid(git_zstream *stream,
2907 const char *hdr,
2908 unsigned long size,
2909 const char *path,
2910 const struct object_id *expected_oid)
2912 git_hash_ctx c;
2913 struct object_id real_oid;
2914 unsigned char buf[4096];
2915 unsigned long total_read;
2916 int status = Z_OK;
2918 the_hash_algo->init_fn(&c);
2919 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2922 * We already read some bytes into hdr, but the ones up to the NUL
2923 * do not count against the object's content size.
2925 total_read = stream->total_out - strlen(hdr) - 1;
2928 * This size comparison must be "<=" to read the final zlib packets;
2929 * see the comment in unpack_loose_rest for details.
2931 while (total_read <= size &&
2932 (status == Z_OK ||
2933 (status == Z_BUF_ERROR && !stream->avail_out))) {
2934 stream->next_out = buf;
2935 stream->avail_out = sizeof(buf);
2936 if (size - total_read < stream->avail_out)
2937 stream->avail_out = size - total_read;
2938 status = git_inflate(stream, Z_FINISH);
2939 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2940 total_read += stream->next_out - buf;
2942 git_inflate_end(stream);
2944 if (status != Z_STREAM_END) {
2945 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2946 return -1;
2948 if (stream->avail_in) {
2949 error(_("garbage at end of loose object '%s'"),
2950 oid_to_hex(expected_oid));
2951 return -1;
2954 the_hash_algo->final_oid_fn(&real_oid, &c);
2955 if (!oideq(expected_oid, &real_oid)) {
2956 error(_("hash mismatch for %s (expected %s)"), path,
2957 oid_to_hex(expected_oid));
2958 return -1;
2961 return 0;
2964 int read_loose_object(const char *path,
2965 const struct object_id *expected_oid,
2966 struct object_id *real_oid,
2967 void **contents,
2968 struct object_info *oi)
2970 int ret = -1;
2971 int fd;
2972 void *map = NULL;
2973 unsigned long mapsize;
2974 git_zstream stream;
2975 char hdr[MAX_HEADER_LEN];
2976 unsigned long *size = oi->sizep;
2978 fd = git_open(path);
2979 if (fd >= 0)
2980 map = map_fd(fd, path, &mapsize);
2981 if (!map) {
2982 error_errno(_("unable to mmap %s"), path);
2983 goto out;
2986 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
2987 NULL) != ULHR_OK) {
2988 error(_("unable to unpack header of %s"), path);
2989 git_inflate_end(&stream);
2990 goto out;
2993 if (parse_loose_header(hdr, oi) < 0) {
2994 error(_("unable to parse header of %s"), path);
2995 git_inflate_end(&stream);
2996 goto out;
2999 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
3000 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
3001 goto out;
3002 } else {
3003 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
3004 if (!*contents) {
3005 error(_("unable to unpack contents of %s"), path);
3006 git_inflate_end(&stream);
3007 goto out;
3009 hash_object_file_literally(the_repository->hash_algo,
3010 *contents, *size,
3011 oi->type_name->buf, real_oid);
3012 if (!oideq(expected_oid, real_oid))
3013 goto out;
3016 ret = 0; /* everything checks out */
3018 out:
3019 if (map)
3020 munmap(map, mapsize);
3021 return ret;