gitlab-ci: introduce stages and dependencies
[git/gitster.git] / object-file.c
blobb1a3463852c45105ccf2897e7b14228439c55bd7
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;
118 static void git_hash_sha1_init_unsafe(git_hash_ctx *ctx)
120 git_SHA1_Init_unsafe(&ctx->sha1_unsafe);
123 static void git_hash_sha1_clone_unsafe(git_hash_ctx *dst, const git_hash_ctx *src)
125 git_SHA1_Clone_unsafe(&dst->sha1_unsafe, &src->sha1_unsafe);
128 static void git_hash_sha1_update_unsafe(git_hash_ctx *ctx, const void *data,
129 size_t len)
131 git_SHA1_Update_unsafe(&ctx->sha1_unsafe, data, len);
134 static void git_hash_sha1_final_unsafe(unsigned char *hash, git_hash_ctx *ctx)
136 git_SHA1_Final_unsafe(hash, &ctx->sha1_unsafe);
139 static void git_hash_sha1_final_oid_unsafe(struct object_id *oid, git_hash_ctx *ctx)
141 git_SHA1_Final_unsafe(oid->hash, &ctx->sha1_unsafe);
142 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
143 oid->algo = GIT_HASH_SHA1;
146 static void git_hash_sha256_init(git_hash_ctx *ctx)
148 git_SHA256_Init(&ctx->sha256);
151 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
153 git_SHA256_Clone(&dst->sha256, &src->sha256);
156 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
158 git_SHA256_Update(&ctx->sha256, data, len);
161 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
163 git_SHA256_Final(hash, &ctx->sha256);
166 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
168 git_SHA256_Final(oid->hash, &ctx->sha256);
170 * This currently does nothing, so the compiler should optimize it out,
171 * but keep it in case we extend the hash size again.
173 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
174 oid->algo = GIT_HASH_SHA256;
177 static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
179 BUG("trying to init unknown hash");
182 static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
183 const git_hash_ctx *src UNUSED)
185 BUG("trying to clone unknown hash");
188 static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
189 const void *data UNUSED,
190 size_t len UNUSED)
192 BUG("trying to update unknown hash");
195 static void git_hash_unknown_final(unsigned char *hash UNUSED,
196 git_hash_ctx *ctx UNUSED)
198 BUG("trying to finalize unknown hash");
201 static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
202 git_hash_ctx *ctx UNUSED)
204 BUG("trying to finalize unknown hash");
207 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
209 .name = NULL,
210 .format_id = 0x00000000,
211 .rawsz = 0,
212 .hexsz = 0,
213 .blksz = 0,
214 .init_fn = git_hash_unknown_init,
215 .clone_fn = git_hash_unknown_clone,
216 .update_fn = git_hash_unknown_update,
217 .final_fn = git_hash_unknown_final,
218 .final_oid_fn = git_hash_unknown_final_oid,
219 .unsafe_init_fn = git_hash_unknown_init,
220 .unsafe_clone_fn = git_hash_unknown_clone,
221 .unsafe_update_fn = git_hash_unknown_update,
222 .unsafe_final_fn = git_hash_unknown_final,
223 .unsafe_final_oid_fn = git_hash_unknown_final_oid,
224 .empty_tree = NULL,
225 .empty_blob = NULL,
226 .null_oid = NULL,
229 .name = "sha1",
230 .format_id = GIT_SHA1_FORMAT_ID,
231 .rawsz = GIT_SHA1_RAWSZ,
232 .hexsz = GIT_SHA1_HEXSZ,
233 .blksz = GIT_SHA1_BLKSZ,
234 .init_fn = git_hash_sha1_init,
235 .clone_fn = git_hash_sha1_clone,
236 .update_fn = git_hash_sha1_update,
237 .final_fn = git_hash_sha1_final,
238 .final_oid_fn = git_hash_sha1_final_oid,
239 .unsafe_init_fn = git_hash_sha1_init_unsafe,
240 .unsafe_clone_fn = git_hash_sha1_clone_unsafe,
241 .unsafe_update_fn = git_hash_sha1_update_unsafe,
242 .unsafe_final_fn = git_hash_sha1_final_unsafe,
243 .unsafe_final_oid_fn = git_hash_sha1_final_oid_unsafe,
244 .empty_tree = &empty_tree_oid,
245 .empty_blob = &empty_blob_oid,
246 .null_oid = &null_oid_sha1,
249 .name = "sha256",
250 .format_id = GIT_SHA256_FORMAT_ID,
251 .rawsz = GIT_SHA256_RAWSZ,
252 .hexsz = GIT_SHA256_HEXSZ,
253 .blksz = GIT_SHA256_BLKSZ,
254 .init_fn = git_hash_sha256_init,
255 .clone_fn = git_hash_sha256_clone,
256 .update_fn = git_hash_sha256_update,
257 .final_fn = git_hash_sha256_final,
258 .final_oid_fn = git_hash_sha256_final_oid,
259 .unsafe_init_fn = git_hash_sha256_init,
260 .unsafe_clone_fn = git_hash_sha256_clone,
261 .unsafe_update_fn = git_hash_sha256_update,
262 .unsafe_final_fn = git_hash_sha256_final,
263 .unsafe_final_oid_fn = git_hash_sha256_final_oid,
264 .empty_tree = &empty_tree_oid_sha256,
265 .empty_blob = &empty_blob_oid_sha256,
266 .null_oid = &null_oid_sha256,
270 const struct object_id *null_oid(void)
272 return the_hash_algo->null_oid;
275 const char *empty_tree_oid_hex(const struct git_hash_algo *algop)
277 static char buf[GIT_MAX_HEXSZ + 1];
278 return oid_to_hex_r(buf, algop->empty_tree);
281 int hash_algo_by_name(const char *name)
283 int i;
284 if (!name)
285 return GIT_HASH_UNKNOWN;
286 for (i = 1; i < GIT_HASH_NALGOS; i++)
287 if (!strcmp(name, hash_algos[i].name))
288 return i;
289 return GIT_HASH_UNKNOWN;
292 int hash_algo_by_id(uint32_t format_id)
294 int i;
295 for (i = 1; i < GIT_HASH_NALGOS; i++)
296 if (format_id == hash_algos[i].format_id)
297 return i;
298 return GIT_HASH_UNKNOWN;
301 int hash_algo_by_length(int len)
303 int i;
304 for (i = 1; i < GIT_HASH_NALGOS; i++)
305 if (len == hash_algos[i].rawsz)
306 return i;
307 return GIT_HASH_UNKNOWN;
311 * This is meant to hold a *small* number of objects that you would
312 * want repo_read_object_file() to be able to return, but yet you do not want
313 * to write them into the object store (e.g. a browse-only
314 * application).
316 static struct cached_object {
317 struct object_id oid;
318 enum object_type type;
319 const void *buf;
320 unsigned long size;
321 } *cached_objects;
322 static int cached_object_nr, cached_object_alloc;
324 static struct cached_object empty_tree = {
325 .oid = {
326 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
328 .type = OBJ_TREE,
329 .buf = "",
332 static struct cached_object *find_cached_object(const struct object_id *oid)
334 int i;
335 struct cached_object *co = cached_objects;
337 for (i = 0; i < cached_object_nr; i++, co++) {
338 if (oideq(&co->oid, oid))
339 return co;
341 if (oideq(oid, the_hash_algo->empty_tree))
342 return &empty_tree;
343 return NULL;
347 static int get_conv_flags(unsigned flags)
349 if (flags & HASH_RENORMALIZE)
350 return CONV_EOL_RENORMALIZE;
351 else if (flags & HASH_WRITE_OBJECT)
352 return global_conv_flags_eol | CONV_WRITE_OBJECT;
353 else
354 return 0;
358 int mkdir_in_gitdir(const char *path)
360 if (mkdir(path, 0777)) {
361 int saved_errno = errno;
362 struct stat st;
363 struct strbuf sb = STRBUF_INIT;
365 if (errno != EEXIST)
366 return -1;
368 * Are we looking at a path in a symlinked worktree
369 * whose original repository does not yet have it?
370 * e.g. .git/rr-cache pointing at its original
371 * repository in which the user hasn't performed any
372 * conflict resolution yet?
374 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
375 strbuf_readlink(&sb, path, st.st_size) ||
376 !is_absolute_path(sb.buf) ||
377 mkdir(sb.buf, 0777)) {
378 strbuf_release(&sb);
379 errno = saved_errno;
380 return -1;
382 strbuf_release(&sb);
384 return adjust_shared_perm(path);
387 static enum scld_error safe_create_leading_directories_1(char *path, int share)
389 char *next_component = path + offset_1st_component(path);
390 enum scld_error ret = SCLD_OK;
392 while (ret == SCLD_OK && next_component) {
393 struct stat st;
394 char *slash = next_component, slash_character;
396 while (*slash && !is_dir_sep(*slash))
397 slash++;
399 if (!*slash)
400 break;
402 next_component = slash + 1;
403 while (is_dir_sep(*next_component))
404 next_component++;
405 if (!*next_component)
406 break;
408 slash_character = *slash;
409 *slash = '\0';
410 if (!stat(path, &st)) {
411 /* path exists */
412 if (!S_ISDIR(st.st_mode)) {
413 errno = ENOTDIR;
414 ret = SCLD_EXISTS;
416 } else if (mkdir(path, 0777)) {
417 if (errno == EEXIST &&
418 !stat(path, &st) && S_ISDIR(st.st_mode))
419 ; /* somebody created it since we checked */
420 else if (errno == ENOENT)
422 * Either mkdir() failed because
423 * somebody just pruned the containing
424 * directory, or stat() failed because
425 * the file that was in our way was
426 * just removed. Either way, inform
427 * the caller that it might be worth
428 * trying again:
430 ret = SCLD_VANISHED;
431 else
432 ret = SCLD_FAILED;
433 } else if (share && adjust_shared_perm(path)) {
434 ret = SCLD_PERMS;
436 *slash = slash_character;
438 return ret;
441 enum scld_error safe_create_leading_directories(char *path)
443 return safe_create_leading_directories_1(path, 1);
446 enum scld_error safe_create_leading_directories_no_share(char *path)
448 return safe_create_leading_directories_1(path, 0);
451 enum scld_error safe_create_leading_directories_const(const char *path)
453 int save_errno;
454 /* path points to cache entries, so xstrdup before messing with it */
455 char *buf = xstrdup(path);
456 enum scld_error result = safe_create_leading_directories(buf);
458 save_errno = errno;
459 free(buf);
460 errno = save_errno;
461 return result;
464 int odb_mkstemp(struct strbuf *temp_filename, const char *pattern)
466 int fd;
468 * we let the umask do its job, don't try to be more
469 * restrictive except to remove write permission.
471 int mode = 0444;
472 git_path_buf(temp_filename, "objects/%s", pattern);
473 fd = git_mkstemp_mode(temp_filename->buf, mode);
474 if (0 <= fd)
475 return fd;
477 /* slow path */
478 /* some mkstemp implementations erase temp_filename on failure */
479 git_path_buf(temp_filename, "objects/%s", pattern);
480 safe_create_leading_directories(temp_filename->buf);
481 return xmkstemp_mode(temp_filename->buf, mode);
484 int odb_pack_keep(const char *name)
486 int fd;
488 fd = open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
489 if (0 <= fd)
490 return fd;
492 /* slow path */
493 safe_create_leading_directories_const(name);
494 return open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
497 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
499 int i;
500 for (i = 0; i < the_hash_algo->rawsz; i++) {
501 static char hex[] = "0123456789abcdef";
502 unsigned int val = oid->hash[i];
503 strbuf_addch(buf, hex[val >> 4]);
504 strbuf_addch(buf, hex[val & 0xf]);
505 if (!i)
506 strbuf_addch(buf, '/');
510 static const char *odb_loose_path(struct object_directory *odb,
511 struct strbuf *buf,
512 const struct object_id *oid)
514 strbuf_reset(buf);
515 strbuf_addstr(buf, odb->path);
516 strbuf_addch(buf, '/');
517 fill_loose_path(buf, oid);
518 return buf->buf;
521 const char *loose_object_path(struct repository *r, struct strbuf *buf,
522 const struct object_id *oid)
524 return odb_loose_path(r->objects->odb, buf, oid);
528 * Return non-zero iff the path is usable as an alternate object database.
530 static int alt_odb_usable(struct raw_object_store *o,
531 struct strbuf *path,
532 const char *normalized_objdir, khiter_t *pos)
534 int r;
536 /* Detect cases where alternate disappeared */
537 if (!is_directory(path->buf)) {
538 error(_("object directory %s does not exist; "
539 "check .git/objects/info/alternates"),
540 path->buf);
541 return 0;
545 * Prevent the common mistake of listing the same
546 * thing twice, or object directory itself.
548 if (!o->odb_by_path) {
549 khiter_t p;
551 o->odb_by_path = kh_init_odb_path_map();
552 assert(!o->odb->next);
553 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
554 assert(r == 1); /* never used */
555 kh_value(o->odb_by_path, p) = o->odb;
557 if (fspatheq(path->buf, normalized_objdir))
558 return 0;
559 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
560 /* r: 0 = exists, 1 = never used, 2 = deleted */
561 return r == 0 ? 0 : 1;
565 * Prepare alternate object database registry.
567 * The variable alt_odb_list points at the list of struct
568 * object_directory. The elements on this list come from
569 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
570 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
571 * whose contents is similar to that environment variable but can be
572 * LF separated. Its base points at a statically allocated buffer that
573 * contains "/the/directory/corresponding/to/.git/objects/...", while
574 * its name points just after the slash at the end of ".git/objects/"
575 * in the example above, and has enough space to hold all hex characters
576 * of the object ID, an extra slash for the first level indirection, and
577 * the terminating NUL.
579 static void read_info_alternates(struct repository *r,
580 const char *relative_base,
581 int depth);
582 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
583 const char *relative_base, int depth, const char *normalized_objdir)
585 struct object_directory *ent;
586 struct strbuf pathbuf = STRBUF_INIT;
587 struct strbuf tmp = STRBUF_INIT;
588 khiter_t pos;
589 int ret = -1;
591 if (!is_absolute_path(entry->buf) && relative_base) {
592 strbuf_realpath(&pathbuf, relative_base, 1);
593 strbuf_addch(&pathbuf, '/');
595 strbuf_addbuf(&pathbuf, entry);
597 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
598 error(_("unable to normalize alternate object path: %s"),
599 pathbuf.buf);
600 goto error;
602 strbuf_swap(&pathbuf, &tmp);
605 * The trailing slash after the directory name is given by
606 * this function at the end. Remove duplicates.
608 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
609 strbuf_setlen(&pathbuf, pathbuf.len - 1);
611 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
612 goto error;
614 CALLOC_ARRAY(ent, 1);
615 /* pathbuf.buf is already in r->objects->odb_by_path */
616 ent->path = strbuf_detach(&pathbuf, NULL);
618 /* add the alternate entry */
619 *r->objects->odb_tail = ent;
620 r->objects->odb_tail = &(ent->next);
621 ent->next = NULL;
622 assert(r->objects->odb_by_path);
623 kh_value(r->objects->odb_by_path, pos) = ent;
625 /* recursively add alternates */
626 read_info_alternates(r, ent->path, depth + 1);
627 ret = 0;
628 error:
629 strbuf_release(&tmp);
630 strbuf_release(&pathbuf);
631 return ret;
634 static const char *parse_alt_odb_entry(const char *string,
635 int sep,
636 struct strbuf *out)
638 const char *end;
640 strbuf_reset(out);
642 if (*string == '#') {
643 /* comment; consume up to next separator */
644 end = strchrnul(string, sep);
645 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
647 * quoted path; unquote_c_style has copied the
648 * data for us and set "end". Broken quoting (e.g.,
649 * an entry that doesn't end with a quote) falls
650 * back to the unquoted case below.
652 } else {
653 /* normal, unquoted path */
654 end = strchrnul(string, sep);
655 strbuf_add(out, string, end - string);
658 if (*end)
659 end++;
660 return end;
663 static void link_alt_odb_entries(struct repository *r, const char *alt,
664 int sep, const char *relative_base, int depth)
666 struct strbuf objdirbuf = STRBUF_INIT;
667 struct strbuf entry = STRBUF_INIT;
669 if (!alt || !*alt)
670 return;
672 if (depth > 5) {
673 error(_("%s: ignoring alternate object stores, nesting too deep"),
674 relative_base);
675 return;
678 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
680 while (*alt) {
681 alt = parse_alt_odb_entry(alt, sep, &entry);
682 if (!entry.len)
683 continue;
684 link_alt_odb_entry(r, &entry,
685 relative_base, depth, objdirbuf.buf);
687 strbuf_release(&entry);
688 strbuf_release(&objdirbuf);
691 static void read_info_alternates(struct repository *r,
692 const char *relative_base,
693 int depth)
695 char *path;
696 struct strbuf buf = STRBUF_INIT;
698 path = xstrfmt("%s/info/alternates", relative_base);
699 if (strbuf_read_file(&buf, path, 1024) < 0) {
700 warn_on_fopen_errors(path);
701 free(path);
702 return;
705 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
706 strbuf_release(&buf);
707 free(path);
710 void add_to_alternates_file(const char *reference)
712 struct lock_file lock = LOCK_INIT;
713 char *alts = git_pathdup("objects/info/alternates");
714 FILE *in, *out;
715 int found = 0;
717 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
718 out = fdopen_lock_file(&lock, "w");
719 if (!out)
720 die_errno(_("unable to fdopen alternates lockfile"));
722 in = fopen(alts, "r");
723 if (in) {
724 struct strbuf line = STRBUF_INIT;
726 while (strbuf_getline(&line, in) != EOF) {
727 if (!strcmp(reference, line.buf)) {
728 found = 1;
729 break;
731 fprintf_or_die(out, "%s\n", line.buf);
734 strbuf_release(&line);
735 fclose(in);
737 else if (errno != ENOENT)
738 die_errno(_("unable to read alternates file"));
740 if (found) {
741 rollback_lock_file(&lock);
742 } else {
743 fprintf_or_die(out, "%s\n", reference);
744 if (commit_lock_file(&lock))
745 die_errno(_("unable to move new alternates file into place"));
746 if (the_repository->objects->loaded_alternates)
747 link_alt_odb_entries(the_repository, reference,
748 '\n', NULL, 0);
750 free(alts);
753 void add_to_alternates_memory(const char *reference)
756 * Make sure alternates are initialized, or else our entry may be
757 * overwritten when they are.
759 prepare_alt_odb(the_repository);
761 link_alt_odb_entries(the_repository, reference,
762 '\n', NULL, 0);
765 struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
767 struct object_directory *new_odb;
770 * Make sure alternates are initialized, or else our entry may be
771 * overwritten when they are.
773 prepare_alt_odb(the_repository);
776 * Make a new primary odb and link the old primary ODB in as an
777 * alternate
779 new_odb = xcalloc(1, sizeof(*new_odb));
780 new_odb->path = xstrdup(dir);
783 * Disable ref updates while a temporary odb is active, since
784 * the objects in the database may roll back.
786 new_odb->disable_ref_updates = 1;
787 new_odb->will_destroy = will_destroy;
788 new_odb->next = the_repository->objects->odb;
789 the_repository->objects->odb = new_odb;
790 return new_odb->next;
793 void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
795 struct object_directory *cur_odb = the_repository->objects->odb;
797 if (strcmp(old_path, cur_odb->path))
798 BUG("expected %s as primary object store; found %s",
799 old_path, cur_odb->path);
801 if (cur_odb->next != restore_odb)
802 BUG("we expect the old primary object store to be the first alternate");
804 the_repository->objects->odb = restore_odb;
805 free_object_directory(cur_odb);
809 * Compute the exact path an alternate is at and returns it. In case of
810 * error NULL is returned and the human readable error is added to `err`
811 * `path` may be relative and should point to $GIT_DIR.
812 * `err` must not be null.
814 char *compute_alternate_path(const char *path, struct strbuf *err)
816 char *ref_git = NULL;
817 const char *repo;
818 int seen_error = 0;
820 ref_git = real_pathdup(path, 0);
821 if (!ref_git) {
822 seen_error = 1;
823 strbuf_addf(err, _("path '%s' does not exist"), path);
824 goto out;
827 repo = read_gitfile(ref_git);
828 if (!repo)
829 repo = read_gitfile(mkpath("%s/.git", ref_git));
830 if (repo) {
831 free(ref_git);
832 ref_git = xstrdup(repo);
835 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
836 char *ref_git_git = mkpathdup("%s/.git", ref_git);
837 free(ref_git);
838 ref_git = ref_git_git;
839 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
840 struct strbuf sb = STRBUF_INIT;
841 seen_error = 1;
842 if (get_common_dir(&sb, ref_git)) {
843 strbuf_addf(err,
844 _("reference repository '%s' as a linked "
845 "checkout is not supported yet."),
846 path);
847 goto out;
850 strbuf_addf(err, _("reference repository '%s' is not a "
851 "local repository."), path);
852 goto out;
855 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
856 strbuf_addf(err, _("reference repository '%s' is shallow"),
857 path);
858 seen_error = 1;
859 goto out;
862 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
863 strbuf_addf(err,
864 _("reference repository '%s' is grafted"),
865 path);
866 seen_error = 1;
867 goto out;
870 out:
871 if (seen_error) {
872 FREE_AND_NULL(ref_git);
875 return ref_git;
878 struct object_directory *find_odb(struct repository *r, const char *obj_dir)
880 struct object_directory *odb;
881 char *obj_dir_real = real_pathdup(obj_dir, 1);
882 struct strbuf odb_path_real = STRBUF_INIT;
884 prepare_alt_odb(r);
885 for (odb = r->objects->odb; odb; odb = odb->next) {
886 strbuf_realpath(&odb_path_real, odb->path, 1);
887 if (!strcmp(obj_dir_real, odb_path_real.buf))
888 break;
891 free(obj_dir_real);
892 strbuf_release(&odb_path_real);
894 if (!odb)
895 die(_("could not find object directory matching %s"), obj_dir);
896 return odb;
899 static void fill_alternate_refs_command(struct child_process *cmd,
900 const char *repo_path)
902 const char *value;
904 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
905 cmd->use_shell = 1;
907 strvec_push(&cmd->args, value);
908 strvec_push(&cmd->args, repo_path);
909 } else {
910 cmd->git_cmd = 1;
912 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
913 strvec_push(&cmd->args, "for-each-ref");
914 strvec_push(&cmd->args, "--format=%(objectname)");
916 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
917 strvec_push(&cmd->args, "--");
918 strvec_split(&cmd->args, value);
922 strvec_pushv(&cmd->env, (const char **)local_repo_env);
923 cmd->out = -1;
926 static void read_alternate_refs(const char *path,
927 alternate_ref_fn *cb,
928 void *data)
930 struct child_process cmd = CHILD_PROCESS_INIT;
931 struct strbuf line = STRBUF_INIT;
932 FILE *fh;
934 fill_alternate_refs_command(&cmd, path);
936 if (start_command(&cmd))
937 return;
939 fh = xfdopen(cmd.out, "r");
940 while (strbuf_getline_lf(&line, fh) != EOF) {
941 struct object_id oid;
942 const char *p;
944 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
945 warning(_("invalid line while parsing alternate refs: %s"),
946 line.buf);
947 break;
950 cb(&oid, data);
953 fclose(fh);
954 finish_command(&cmd);
955 strbuf_release(&line);
958 struct alternate_refs_data {
959 alternate_ref_fn *fn;
960 void *data;
963 static int refs_from_alternate_cb(struct object_directory *e,
964 void *data)
966 struct strbuf path = STRBUF_INIT;
967 size_t base_len;
968 struct alternate_refs_data *cb = data;
970 if (!strbuf_realpath(&path, e->path, 0))
971 goto out;
972 if (!strbuf_strip_suffix(&path, "/objects"))
973 goto out;
974 base_len = path.len;
976 /* Is this a git repository with refs? */
977 strbuf_addstr(&path, "/refs");
978 if (!is_directory(path.buf))
979 goto out;
980 strbuf_setlen(&path, base_len);
982 read_alternate_refs(path.buf, cb->fn, cb->data);
984 out:
985 strbuf_release(&path);
986 return 0;
989 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
991 struct alternate_refs_data cb;
992 cb.fn = fn;
993 cb.data = data;
994 foreach_alt_odb(refs_from_alternate_cb, &cb);
997 int foreach_alt_odb(alt_odb_fn fn, void *cb)
999 struct object_directory *ent;
1000 int r = 0;
1002 prepare_alt_odb(the_repository);
1003 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
1004 r = fn(ent, cb);
1005 if (r)
1006 break;
1008 return r;
1011 void prepare_alt_odb(struct repository *r)
1013 if (r->objects->loaded_alternates)
1014 return;
1016 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
1018 read_info_alternates(r, r->objects->odb->path, 0);
1019 r->objects->loaded_alternates = 1;
1022 int has_alt_odb(struct repository *r)
1024 prepare_alt_odb(r);
1025 return !!r->objects->odb->next;
1028 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
1029 static int freshen_file(const char *fn)
1031 return !utime(fn, NULL);
1035 * All of the check_and_freshen functions return 1 if the file exists and was
1036 * freshened (if freshening was requested), 0 otherwise. If they return
1037 * 0, you should not assume that it is safe to skip a write of the object (it
1038 * either does not exist on disk, or has a stale mtime and may be subject to
1039 * pruning).
1041 int check_and_freshen_file(const char *fn, int freshen)
1043 if (access(fn, F_OK))
1044 return 0;
1045 if (freshen && !freshen_file(fn))
1046 return 0;
1047 return 1;
1050 static int check_and_freshen_odb(struct object_directory *odb,
1051 const struct object_id *oid,
1052 int freshen)
1054 static struct strbuf path = STRBUF_INIT;
1055 odb_loose_path(odb, &path, oid);
1056 return check_and_freshen_file(path.buf, freshen);
1059 static int check_and_freshen_local(const struct object_id *oid, int freshen)
1061 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
1064 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
1066 struct object_directory *odb;
1068 prepare_alt_odb(the_repository);
1069 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
1070 if (check_and_freshen_odb(odb, oid, freshen))
1071 return 1;
1073 return 0;
1076 static int check_and_freshen(const struct object_id *oid, int freshen)
1078 return check_and_freshen_local(oid, freshen) ||
1079 check_and_freshen_nonlocal(oid, freshen);
1082 int has_loose_object_nonlocal(const struct object_id *oid)
1084 return check_and_freshen_nonlocal(oid, 0);
1087 int has_loose_object(const struct object_id *oid)
1089 return check_and_freshen(oid, 0);
1092 static void mmap_limit_check(size_t length)
1094 static size_t limit = 0;
1095 if (!limit) {
1096 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1097 if (!limit)
1098 limit = SIZE_MAX;
1100 if (length > limit)
1101 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1102 (uintmax_t)length, (uintmax_t)limit);
1105 void *xmmap_gently(void *start, size_t length,
1106 int prot, int flags, int fd, off_t offset)
1108 void *ret;
1110 mmap_limit_check(length);
1111 ret = mmap(start, length, prot, flags, fd, offset);
1112 if (ret == MAP_FAILED && !length)
1113 ret = NULL;
1114 return ret;
1117 const char *mmap_os_err(void)
1119 static const char blank[] = "";
1120 #if defined(__linux__)
1121 if (errno == ENOMEM) {
1122 /* this continues an existing error message: */
1123 static const char enomem[] =
1124 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1125 return enomem;
1127 #endif /* OS-specific bits */
1128 return blank;
1131 void *xmmap(void *start, size_t length,
1132 int prot, int flags, int fd, off_t offset)
1134 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1135 if (ret == MAP_FAILED)
1136 die_errno(_("mmap failed%s"), mmap_os_err());
1137 return ret;
1140 static int format_object_header_literally(char *str, size_t size,
1141 const char *type, size_t objsize)
1143 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1146 int format_object_header(char *str, size_t size, enum object_type type,
1147 size_t objsize)
1149 const char *name = type_name(type);
1151 if (!name)
1152 BUG("could not get a type name for 'enum object_type' value %d", type);
1154 return format_object_header_literally(str, size, name, objsize);
1157 int check_object_signature(struct repository *r, const struct object_id *oid,
1158 void *buf, unsigned long size,
1159 enum object_type type)
1161 const struct git_hash_algo *algo =
1162 oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
1163 struct object_id real_oid;
1165 hash_object_file(algo, buf, size, type, &real_oid);
1167 return !oideq(oid, &real_oid) ? -1 : 0;
1170 int stream_object_signature(struct repository *r, const struct object_id *oid)
1172 struct object_id real_oid;
1173 unsigned long size;
1174 enum object_type obj_type;
1175 struct git_istream *st;
1176 git_hash_ctx c;
1177 char hdr[MAX_HEADER_LEN];
1178 int hdrlen;
1180 st = open_istream(r, oid, &obj_type, &size, NULL);
1181 if (!st)
1182 return -1;
1184 /* Generate the header */
1185 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
1187 /* Sha1.. */
1188 r->hash_algo->init_fn(&c);
1189 r->hash_algo->update_fn(&c, hdr, hdrlen);
1190 for (;;) {
1191 char buf[1024 * 16];
1192 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1194 if (readlen < 0) {
1195 close_istream(st);
1196 return -1;
1198 if (!readlen)
1199 break;
1200 r->hash_algo->update_fn(&c, buf, readlen);
1202 r->hash_algo->final_oid_fn(&real_oid, &c);
1203 close_istream(st);
1204 return !oideq(oid, &real_oid) ? -1 : 0;
1207 int git_open_cloexec(const char *name, int flags)
1209 int fd;
1210 static int o_cloexec = O_CLOEXEC;
1212 fd = open(name, flags | o_cloexec);
1213 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1214 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1215 o_cloexec &= ~O_CLOEXEC;
1216 fd = open(name, flags | o_cloexec);
1219 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1221 static int fd_cloexec = FD_CLOEXEC;
1223 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1224 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1225 int flags = fcntl(fd, F_GETFD);
1226 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1227 fd_cloexec = 0;
1230 #endif
1231 return fd;
1235 * Find "oid" as a loose object in the local repository or in an alternate.
1236 * Returns 0 on success, negative on failure.
1238 * The "path" out-parameter will give the path of the object we found (if any).
1239 * Note that it may point to static storage and is only valid until another
1240 * call to stat_loose_object().
1242 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1243 struct stat *st, const char **path)
1245 struct object_directory *odb;
1246 static struct strbuf buf = STRBUF_INIT;
1248 prepare_alt_odb(r);
1249 for (odb = r->objects->odb; odb; odb = odb->next) {
1250 *path = odb_loose_path(odb, &buf, oid);
1251 if (!lstat(*path, st))
1252 return 0;
1255 return -1;
1259 * Like stat_loose_object(), but actually open the object and return the
1260 * descriptor. See the caveats on the "path" parameter above.
1262 static int open_loose_object(struct repository *r,
1263 const struct object_id *oid, const char **path)
1265 int fd;
1266 struct object_directory *odb;
1267 int most_interesting_errno = ENOENT;
1268 static struct strbuf buf = STRBUF_INIT;
1270 prepare_alt_odb(r);
1271 for (odb = r->objects->odb; odb; odb = odb->next) {
1272 *path = odb_loose_path(odb, &buf, oid);
1273 fd = git_open(*path);
1274 if (fd >= 0)
1275 return fd;
1277 if (most_interesting_errno == ENOENT)
1278 most_interesting_errno = errno;
1280 errno = most_interesting_errno;
1281 return -1;
1284 static int quick_has_loose(struct repository *r,
1285 const struct object_id *oid)
1287 struct object_directory *odb;
1289 prepare_alt_odb(r);
1290 for (odb = r->objects->odb; odb; odb = odb->next) {
1291 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1292 return 1;
1294 return 0;
1298 * Map and close the given loose object fd. The path argument is used for
1299 * error reporting.
1301 static void *map_fd(int fd, const char *path, unsigned long *size)
1303 void *map = NULL;
1304 struct stat st;
1306 if (!fstat(fd, &st)) {
1307 *size = xsize_t(st.st_size);
1308 if (!*size) {
1309 /* mmap() is forbidden on empty files */
1310 error(_("object file %s is empty"), path);
1311 close(fd);
1312 return NULL;
1314 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1316 close(fd);
1317 return map;
1320 void *map_loose_object(struct repository *r,
1321 const struct object_id *oid,
1322 unsigned long *size)
1324 const char *p;
1325 int fd = open_loose_object(r, oid, &p);
1327 if (fd < 0)
1328 return NULL;
1329 return map_fd(fd, p, size);
1332 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1333 unsigned char *map,
1334 unsigned long mapsize,
1335 void *buffer,
1336 unsigned long bufsiz,
1337 struct strbuf *header)
1339 int status;
1341 /* Get the data stream */
1342 memset(stream, 0, sizeof(*stream));
1343 stream->next_in = map;
1344 stream->avail_in = mapsize;
1345 stream->next_out = buffer;
1346 stream->avail_out = bufsiz;
1348 git_inflate_init(stream);
1349 obj_read_unlock();
1350 status = git_inflate(stream, 0);
1351 obj_read_lock();
1352 if (status < Z_OK)
1353 return ULHR_BAD;
1356 * Check if entire header is unpacked in the first iteration.
1358 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1359 return ULHR_OK;
1362 * We have a header longer than MAX_HEADER_LEN. The "header"
1363 * here is only non-NULL when we run "cat-file
1364 * --allow-unknown-type".
1366 if (!header)
1367 return ULHR_TOO_LONG;
1370 * buffer[0..bufsiz] was not large enough. Copy the partial
1371 * result out to header, and then append the result of further
1372 * reading the stream.
1374 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1375 stream->next_out = buffer;
1376 stream->avail_out = bufsiz;
1378 do {
1379 obj_read_unlock();
1380 status = git_inflate(stream, 0);
1381 obj_read_lock();
1382 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1383 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1384 return 0;
1385 stream->next_out = buffer;
1386 stream->avail_out = bufsiz;
1387 } while (status != Z_STREAM_END);
1388 return ULHR_TOO_LONG;
1391 static void *unpack_loose_rest(git_zstream *stream,
1392 void *buffer, unsigned long size,
1393 const struct object_id *oid)
1395 int bytes = strlen(buffer) + 1;
1396 unsigned char *buf = xmallocz(size);
1397 unsigned long n;
1398 int status = Z_OK;
1400 n = stream->total_out - bytes;
1401 if (n > size)
1402 n = size;
1403 memcpy(buf, (char *) buffer + bytes, n);
1404 bytes = n;
1405 if (bytes <= size) {
1407 * The above condition must be (bytes <= size), not
1408 * (bytes < size). In other words, even though we
1409 * expect no more output and set avail_out to zero,
1410 * the input zlib stream may have bytes that express
1411 * "this concludes the stream", and we *do* want to
1412 * eat that input.
1414 * Otherwise we would not be able to test that we
1415 * consumed all the input to reach the expected size;
1416 * we also want to check that zlib tells us that all
1417 * went well with status == Z_STREAM_END at the end.
1419 stream->next_out = buf + bytes;
1420 stream->avail_out = size - bytes;
1421 while (status == Z_OK) {
1422 obj_read_unlock();
1423 status = git_inflate(stream, Z_FINISH);
1424 obj_read_lock();
1427 if (status == Z_STREAM_END && !stream->avail_in) {
1428 git_inflate_end(stream);
1429 return buf;
1432 if (status < 0)
1433 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1434 else if (stream->avail_in)
1435 error(_("garbage at end of loose object '%s'"),
1436 oid_to_hex(oid));
1437 free(buf);
1438 return NULL;
1442 * We used to just use "sscanf()", but that's actually way
1443 * too permissive for what we want to check. So do an anal
1444 * object header parse by hand.
1446 int parse_loose_header(const char *hdr, struct object_info *oi)
1448 const char *type_buf = hdr;
1449 size_t size;
1450 int type, type_len = 0;
1453 * The type can be of any size but is followed by
1454 * a space.
1456 for (;;) {
1457 char c = *hdr++;
1458 if (!c)
1459 return -1;
1460 if (c == ' ')
1461 break;
1462 type_len++;
1465 type = type_from_string_gently(type_buf, type_len, 1);
1466 if (oi->type_name)
1467 strbuf_add(oi->type_name, type_buf, type_len);
1468 if (oi->typep)
1469 *oi->typep = type;
1472 * The length must follow immediately, and be in canonical
1473 * decimal format (ie "010" is not valid).
1475 size = *hdr++ - '0';
1476 if (size > 9)
1477 return -1;
1478 if (size) {
1479 for (;;) {
1480 unsigned long c = *hdr - '0';
1481 if (c > 9)
1482 break;
1483 hdr++;
1484 size = st_add(st_mult(size, 10), c);
1488 if (oi->sizep)
1489 *oi->sizep = cast_size_t_to_ulong(size);
1492 * The length must be followed by a zero byte
1494 if (*hdr)
1495 return -1;
1498 * The format is valid, but the type may still be bogus. The
1499 * Caller needs to check its oi->typep.
1501 return 0;
1504 static int loose_object_info(struct repository *r,
1505 const struct object_id *oid,
1506 struct object_info *oi, int flags)
1508 int status = 0;
1509 int fd;
1510 unsigned long mapsize;
1511 const char *path;
1512 void *map;
1513 git_zstream stream;
1514 char hdr[MAX_HEADER_LEN];
1515 struct strbuf hdrbuf = STRBUF_INIT;
1516 unsigned long size_scratch;
1517 enum object_type type_scratch;
1518 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
1520 if (oi->delta_base_oid)
1521 oidclr(oi->delta_base_oid, the_repository->hash_algo);
1524 * If we don't care about type or size, then we don't
1525 * need to look inside the object at all. Note that we
1526 * do not optimize out the stat call, even if the
1527 * caller doesn't care about the disk-size, since our
1528 * return value implicitly indicates whether the
1529 * object even exists.
1531 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1532 struct stat st;
1533 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1534 return quick_has_loose(r, oid) ? 0 : -1;
1535 if (stat_loose_object(r, oid, &st, &path) < 0)
1536 return -1;
1537 if (oi->disk_sizep)
1538 *oi->disk_sizep = st.st_size;
1539 return 0;
1542 fd = open_loose_object(r, oid, &path);
1543 if (fd < 0) {
1544 if (errno != ENOENT)
1545 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1546 return -1;
1548 map = map_fd(fd, path, &mapsize);
1549 if (!map)
1550 return -1;
1552 if (!oi->sizep)
1553 oi->sizep = &size_scratch;
1554 if (!oi->typep)
1555 oi->typep = &type_scratch;
1557 if (oi->disk_sizep)
1558 *oi->disk_sizep = mapsize;
1560 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1561 allow_unknown ? &hdrbuf : NULL)) {
1562 case ULHR_OK:
1563 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1564 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1565 else if (!allow_unknown && *oi->typep < 0)
1566 die(_("invalid object type"));
1568 if (!oi->contentp)
1569 break;
1570 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1571 if (*oi->contentp)
1572 goto cleanup;
1574 status = -1;
1575 break;
1576 case ULHR_BAD:
1577 status = error(_("unable to unpack %s header"),
1578 oid_to_hex(oid));
1579 break;
1580 case ULHR_TOO_LONG:
1581 status = error(_("header for %s too long, exceeds %d bytes"),
1582 oid_to_hex(oid), MAX_HEADER_LEN);
1583 break;
1586 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1587 die(_("loose object %s (stored in %s) is corrupt"),
1588 oid_to_hex(oid), path);
1590 git_inflate_end(&stream);
1591 cleanup:
1592 munmap(map, mapsize);
1593 if (oi->sizep == &size_scratch)
1594 oi->sizep = NULL;
1595 strbuf_release(&hdrbuf);
1596 if (oi->typep == &type_scratch)
1597 oi->typep = NULL;
1598 oi->whence = OI_LOOSE;
1599 return status;
1602 int obj_read_use_lock = 0;
1603 pthread_mutex_t obj_read_mutex;
1605 void enable_obj_read_lock(void)
1607 if (obj_read_use_lock)
1608 return;
1610 obj_read_use_lock = 1;
1611 init_recursive_mutex(&obj_read_mutex);
1614 void disable_obj_read_lock(void)
1616 if (!obj_read_use_lock)
1617 return;
1619 obj_read_use_lock = 0;
1620 pthread_mutex_destroy(&obj_read_mutex);
1623 int fetch_if_missing = 1;
1625 static int do_oid_object_info_extended(struct repository *r,
1626 const struct object_id *oid,
1627 struct object_info *oi, unsigned flags)
1629 static struct object_info blank_oi = OBJECT_INFO_INIT;
1630 struct cached_object *co;
1631 struct pack_entry e;
1632 int rtype;
1633 const struct object_id *real = oid;
1634 int already_retried = 0;
1637 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1638 real = lookup_replace_object(r, oid);
1640 if (is_null_oid(real))
1641 return -1;
1643 if (!oi)
1644 oi = &blank_oi;
1646 co = find_cached_object(real);
1647 if (co) {
1648 if (oi->typep)
1649 *(oi->typep) = co->type;
1650 if (oi->sizep)
1651 *(oi->sizep) = co->size;
1652 if (oi->disk_sizep)
1653 *(oi->disk_sizep) = 0;
1654 if (oi->delta_base_oid)
1655 oidclr(oi->delta_base_oid, the_repository->hash_algo);
1656 if (oi->type_name)
1657 strbuf_addstr(oi->type_name, type_name(co->type));
1658 if (oi->contentp)
1659 *oi->contentp = xmemdupz(co->buf, co->size);
1660 oi->whence = OI_CACHED;
1661 return 0;
1664 while (1) {
1665 if (find_pack_entry(r, real, &e))
1666 break;
1668 /* Most likely it's a loose object. */
1669 if (!loose_object_info(r, real, oi, flags))
1670 return 0;
1672 /* Not a loose object; someone else may have just packed it. */
1673 if (!(flags & OBJECT_INFO_QUICK)) {
1674 reprepare_packed_git(r);
1675 if (find_pack_entry(r, real, &e))
1676 break;
1680 * If r is the_repository, this might be an attempt at
1681 * accessing a submodule object as if it were in the_repository
1682 * (having called add_submodule_odb() on that submodule's ODB).
1683 * If any such ODBs exist, register them and try again.
1685 if (r == the_repository &&
1686 register_all_submodule_odb_as_alternates())
1687 /* We added some alternates; retry */
1688 continue;
1690 /* Check if it is a missing object */
1691 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1692 !already_retried &&
1693 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1694 promisor_remote_get_direct(r, real, 1);
1695 already_retried = 1;
1696 continue;
1699 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1700 const struct packed_git *p;
1701 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1702 die(_("replacement %s not found for %s"),
1703 oid_to_hex(real), oid_to_hex(oid));
1704 if ((p = has_packed_and_bad(r, real)))
1705 die(_("packed object %s (stored in %s) is corrupt"),
1706 oid_to_hex(real), p->pack_name);
1708 return -1;
1711 if (oi == &blank_oi)
1713 * We know that the caller doesn't actually need the
1714 * information below, so return early.
1716 return 0;
1717 rtype = packed_object_info(r, e.p, e.offset, oi);
1718 if (rtype < 0) {
1719 mark_bad_packed_object(e.p, real);
1720 return do_oid_object_info_extended(r, real, oi, 0);
1721 } else if (oi->whence == OI_PACKED) {
1722 oi->u.packed.offset = e.offset;
1723 oi->u.packed.pack = e.p;
1724 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1725 rtype == OBJ_OFS_DELTA);
1728 return 0;
1731 static int oid_object_info_convert(struct repository *r,
1732 const struct object_id *input_oid,
1733 struct object_info *input_oi, unsigned flags)
1735 const struct git_hash_algo *input_algo = &hash_algos[input_oid->algo];
1736 int do_die = flags & OBJECT_INFO_DIE_IF_CORRUPT;
1737 struct strbuf type_name = STRBUF_INIT;
1738 struct object_id oid, delta_base_oid;
1739 struct object_info new_oi, *oi;
1740 unsigned long size;
1741 void *content;
1742 int ret;
1744 if (repo_oid_to_algop(r, input_oid, the_hash_algo, &oid)) {
1745 if (do_die)
1746 die(_("missing mapping of %s to %s"),
1747 oid_to_hex(input_oid), the_hash_algo->name);
1748 return -1;
1751 /* Is new_oi needed? */
1752 oi = input_oi;
1753 if (input_oi && (input_oi->delta_base_oid || input_oi->sizep ||
1754 input_oi->contentp)) {
1755 new_oi = *input_oi;
1756 /* Does delta_base_oid need to be converted? */
1757 if (input_oi->delta_base_oid)
1758 new_oi.delta_base_oid = &delta_base_oid;
1759 /* Will the attributes differ when converted? */
1760 if (input_oi->sizep || input_oi->contentp) {
1761 new_oi.contentp = &content;
1762 new_oi.sizep = &size;
1763 new_oi.type_name = &type_name;
1765 oi = &new_oi;
1768 ret = oid_object_info_extended(r, &oid, oi, flags);
1769 if (ret)
1770 return -1;
1771 if (oi == input_oi)
1772 return ret;
1774 if (new_oi.contentp) {
1775 struct strbuf outbuf = STRBUF_INIT;
1776 enum object_type type;
1778 type = type_from_string_gently(type_name.buf, type_name.len,
1779 !do_die);
1780 if (type == -1)
1781 return -1;
1782 if (type != OBJ_BLOB) {
1783 ret = convert_object_file(&outbuf,
1784 the_hash_algo, input_algo,
1785 content, size, type, !do_die);
1786 free(content);
1787 if (ret == -1)
1788 return -1;
1789 size = outbuf.len;
1790 content = strbuf_detach(&outbuf, NULL);
1792 if (input_oi->sizep)
1793 *input_oi->sizep = size;
1794 if (input_oi->contentp)
1795 *input_oi->contentp = content;
1796 else
1797 free(content);
1798 if (input_oi->type_name)
1799 *input_oi->type_name = type_name;
1800 else
1801 strbuf_release(&type_name);
1803 if (new_oi.delta_base_oid == &delta_base_oid) {
1804 if (repo_oid_to_algop(r, &delta_base_oid, input_algo,
1805 input_oi->delta_base_oid)) {
1806 if (do_die)
1807 die(_("missing mapping of %s to %s"),
1808 oid_to_hex(&delta_base_oid),
1809 input_algo->name);
1810 return -1;
1813 input_oi->whence = new_oi.whence;
1814 input_oi->u = new_oi.u;
1815 return ret;
1818 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1819 struct object_info *oi, unsigned flags)
1821 int ret;
1823 if (oid->algo && (hash_algo_by_ptr(r->hash_algo) != oid->algo))
1824 return oid_object_info_convert(r, oid, oi, flags);
1826 obj_read_lock();
1827 ret = do_oid_object_info_extended(r, oid, oi, flags);
1828 obj_read_unlock();
1829 return ret;
1833 /* returns enum object_type or negative */
1834 int oid_object_info(struct repository *r,
1835 const struct object_id *oid,
1836 unsigned long *sizep)
1838 enum object_type type;
1839 struct object_info oi = OBJECT_INFO_INIT;
1841 oi.typep = &type;
1842 oi.sizep = sizep;
1843 if (oid_object_info_extended(r, oid, &oi,
1844 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1845 return -1;
1846 return type;
1849 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1850 struct object_id *oid)
1852 struct cached_object *co;
1853 char *co_buf;
1855 hash_object_file(the_hash_algo, buf, len, type, oid);
1856 if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1857 find_cached_object(oid))
1858 return 0;
1859 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1860 co = &cached_objects[cached_object_nr++];
1861 co->size = len;
1862 co->type = type;
1863 co_buf = xmalloc(len);
1864 memcpy(co_buf, buf, len);
1865 co->buf = co_buf;
1866 oidcpy(&co->oid, oid);
1867 return 0;
1871 * This function dies on corrupt objects; the callers who want to
1872 * deal with them should arrange to call oid_object_info_extended() and give
1873 * error messages themselves.
1875 void *repo_read_object_file(struct repository *r,
1876 const struct object_id *oid,
1877 enum object_type *type,
1878 unsigned long *size)
1880 struct object_info oi = OBJECT_INFO_INIT;
1881 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
1882 void *data;
1884 oi.typep = type;
1885 oi.sizep = size;
1886 oi.contentp = &data;
1887 if (oid_object_info_extended(r, oid, &oi, flags))
1888 return NULL;
1890 return data;
1893 void *read_object_with_reference(struct repository *r,
1894 const struct object_id *oid,
1895 enum object_type required_type,
1896 unsigned long *size,
1897 struct object_id *actual_oid_return)
1899 enum object_type type;
1900 void *buffer;
1901 unsigned long isize;
1902 struct object_id actual_oid;
1904 oidcpy(&actual_oid, oid);
1905 while (1) {
1906 int ref_length = -1;
1907 const char *ref_type = NULL;
1909 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1910 if (!buffer)
1911 return NULL;
1912 if (type == required_type) {
1913 *size = isize;
1914 if (actual_oid_return)
1915 oidcpy(actual_oid_return, &actual_oid);
1916 return buffer;
1918 /* Handle references */
1919 else if (type == OBJ_COMMIT)
1920 ref_type = "tree ";
1921 else if (type == OBJ_TAG)
1922 ref_type = "object ";
1923 else {
1924 free(buffer);
1925 return NULL;
1927 ref_length = strlen(ref_type);
1929 if (ref_length + the_hash_algo->hexsz > isize ||
1930 memcmp(buffer, ref_type, ref_length) ||
1931 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1932 free(buffer);
1933 return NULL;
1935 free(buffer);
1936 /* Now we have the ID of the referred-to object in
1937 * actual_oid. Check again. */
1941 static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1942 const void *buf, unsigned long len,
1943 struct object_id *oid,
1944 char *hdr, int *hdrlen)
1946 algo->init_fn(c);
1947 algo->update_fn(c, hdr, *hdrlen);
1948 algo->update_fn(c, buf, len);
1949 algo->final_oid_fn(oid, c);
1952 static void write_object_file_prepare(const struct git_hash_algo *algo,
1953 const void *buf, unsigned long len,
1954 enum object_type type, struct object_id *oid,
1955 char *hdr, int *hdrlen)
1957 git_hash_ctx c;
1959 /* Generate the header */
1960 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
1962 /* Sha1.. */
1963 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1966 static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1967 const void *buf, unsigned long len,
1968 const char *type, struct object_id *oid,
1969 char *hdr, int *hdrlen)
1971 git_hash_ctx c;
1973 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1974 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1977 static int check_collision(const char *filename_a, const char *filename_b)
1979 char buf_a[4096], buf_b[4096];
1980 int fd_a = -1, fd_b = -1;
1981 int ret = 0;
1983 fd_a = open(filename_a, O_RDONLY);
1984 if (fd_a < 0) {
1985 ret = error_errno(_("unable to open %s"), filename_a);
1986 goto out;
1989 fd_b = open(filename_b, O_RDONLY);
1990 if (fd_b < 0) {
1991 ret = error_errno(_("unable to open %s"), filename_b);
1992 goto out;
1995 while (1) {
1996 ssize_t sz_a, sz_b;
1998 sz_a = read_in_full(fd_a, buf_a, sizeof(buf_a));
1999 if (sz_a < 0) {
2000 ret = error_errno(_("unable to read %s"), filename_a);
2001 goto out;
2004 sz_b = read_in_full(fd_b, buf_b, sizeof(buf_b));
2005 if (sz_b < 0) {
2006 ret = error_errno(_("unable to read %s"), filename_b);
2007 goto out;
2010 if (sz_a != sz_b || memcmp(buf_a, buf_b, sz_a)) {
2011 ret = error(_("files '%s' and '%s' differ in contents"),
2012 filename_a, filename_b);
2013 goto out;
2016 if (sz_a < sizeof(buf_a))
2017 break;
2020 out:
2021 if (fd_a > -1)
2022 close(fd_a);
2023 if (fd_b > -1)
2024 close(fd_b);
2025 return ret;
2029 * Move the just written object into its final resting place.
2031 int finalize_object_file(const char *tmpfile, const char *filename)
2033 return finalize_object_file_flags(tmpfile, filename, 0);
2036 int finalize_object_file_flags(const char *tmpfile, const char *filename,
2037 enum finalize_object_file_flags flags)
2039 struct stat st;
2040 int ret = 0;
2042 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2043 goto try_rename;
2044 else if (link(tmpfile, filename))
2045 ret = errno;
2046 else
2047 unlink_or_warn(tmpfile);
2050 * Coda hack - coda doesn't like cross-directory links,
2051 * so we fall back to a rename, which will mean that it
2052 * won't be able to check collisions, but that's not a
2053 * big deal.
2055 * The same holds for FAT formatted media.
2057 * When this succeeds, we just return. We have nothing
2058 * left to unlink.
2060 if (ret && ret != EEXIST) {
2061 try_rename:
2062 if (!stat(filename, &st))
2063 ret = EEXIST;
2064 else if (!rename(tmpfile, filename))
2065 goto out;
2066 else
2067 ret = errno;
2069 if (ret) {
2070 if (ret != EEXIST) {
2071 int saved_errno = errno;
2072 unlink_or_warn(tmpfile);
2073 errno = saved_errno;
2074 return error_errno(_("unable to write file %s"), filename);
2076 if (!(flags & FOF_SKIP_COLLISION_CHECK) &&
2077 check_collision(tmpfile, filename))
2078 return -1;
2079 unlink_or_warn(tmpfile);
2082 out:
2083 if (adjust_shared_perm(filename))
2084 return error(_("unable to set permission to '%s'"), filename);
2085 return 0;
2088 static void hash_object_file_literally(const struct git_hash_algo *algo,
2089 const void *buf, unsigned long len,
2090 const char *type, struct object_id *oid)
2092 char hdr[MAX_HEADER_LEN];
2093 int hdrlen = sizeof(hdr);
2095 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
2098 void hash_object_file(const struct git_hash_algo *algo, const void *buf,
2099 unsigned long len, enum object_type type,
2100 struct object_id *oid)
2102 hash_object_file_literally(algo, buf, len, type_name(type), oid);
2105 /* Finalize a file on disk, and close it. */
2106 static void close_loose_object(int fd, const char *filename)
2108 if (the_repository->objects->odb->will_destroy)
2109 goto out;
2111 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2112 fsync_loose_object_bulk_checkin(fd, filename);
2113 else if (fsync_object_files > 0)
2114 fsync_or_die(fd, filename);
2115 else
2116 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
2117 filename);
2119 out:
2120 if (close(fd) != 0)
2121 die_errno(_("error when closing loose object file"));
2124 /* Size of directory component, including the ending '/' */
2125 static inline int directory_size(const char *filename)
2127 const char *s = strrchr(filename, '/');
2128 if (!s)
2129 return 0;
2130 return s - filename + 1;
2134 * This creates a temporary file in the same directory as the final
2135 * 'filename'
2137 * We want to avoid cross-directory filename renames, because those
2138 * can have problems on various filesystems (FAT, NFS, Coda).
2140 static int create_tmpfile(struct strbuf *tmp, const char *filename)
2142 int fd, dirlen = directory_size(filename);
2144 strbuf_reset(tmp);
2145 strbuf_add(tmp, filename, dirlen);
2146 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2147 fd = git_mkstemp_mode(tmp->buf, 0444);
2148 if (fd < 0 && dirlen && errno == ENOENT) {
2150 * Make sure the directory exists; note that the contents
2151 * of the buffer are undefined after mkstemp returns an
2152 * error, so we have to rewrite the whole buffer from
2153 * scratch.
2155 strbuf_reset(tmp);
2156 strbuf_add(tmp, filename, dirlen - 1);
2157 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
2158 return -1;
2159 if (adjust_shared_perm(tmp->buf))
2160 return -1;
2162 /* Try again */
2163 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2164 fd = git_mkstemp_mode(tmp->buf, 0444);
2166 return fd;
2170 * Common steps for loose object writers to start writing loose
2171 * objects:
2173 * - Create tmpfile for the loose object.
2174 * - Setup zlib stream for compression.
2175 * - Start to feed header to zlib stream.
2177 * Returns a "fd", which should later be provided to
2178 * end_loose_object_common().
2180 static int start_loose_object_common(struct strbuf *tmp_file,
2181 const char *filename, unsigned flags,
2182 git_zstream *stream,
2183 unsigned char *buf, size_t buflen,
2184 git_hash_ctx *c, git_hash_ctx *compat_c,
2185 char *hdr, int hdrlen)
2187 struct repository *repo = the_repository;
2188 const struct git_hash_algo *algo = repo->hash_algo;
2189 const struct git_hash_algo *compat = repo->compat_hash_algo;
2190 int fd;
2192 fd = create_tmpfile(tmp_file, filename);
2193 if (fd < 0) {
2194 if (flags & HASH_SILENT)
2195 return -1;
2196 else if (errno == EACCES)
2197 return error(_("insufficient permission for adding "
2198 "an object to repository database %s"),
2199 repo_get_object_directory(the_repository));
2200 else
2201 return error_errno(
2202 _("unable to create temporary file"));
2205 /* Setup zlib stream for compression */
2206 git_deflate_init(stream, zlib_compression_level);
2207 stream->next_out = buf;
2208 stream->avail_out = buflen;
2209 algo->init_fn(c);
2210 if (compat && compat_c)
2211 compat->init_fn(compat_c);
2213 /* Start to feed header to zlib stream */
2214 stream->next_in = (unsigned char *)hdr;
2215 stream->avail_in = hdrlen;
2216 while (git_deflate(stream, 0) == Z_OK)
2217 ; /* nothing */
2218 algo->update_fn(c, hdr, hdrlen);
2219 if (compat && compat_c)
2220 compat->update_fn(compat_c, hdr, hdrlen);
2222 return fd;
2226 * Common steps for the inner git_deflate() loop for writing loose
2227 * objects. Returns what git_deflate() returns.
2229 static int write_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
2230 git_zstream *stream, const int flush,
2231 unsigned char *in0, const int fd,
2232 unsigned char *compressed,
2233 const size_t compressed_len)
2235 struct repository *repo = the_repository;
2236 const struct git_hash_algo *algo = repo->hash_algo;
2237 const struct git_hash_algo *compat = repo->compat_hash_algo;
2238 int ret;
2240 ret = git_deflate(stream, flush ? Z_FINISH : 0);
2241 algo->update_fn(c, in0, stream->next_in - in0);
2242 if (compat && compat_c)
2243 compat->update_fn(compat_c, in0, stream->next_in - in0);
2244 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
2245 die_errno(_("unable to write loose object file"));
2246 stream->next_out = compressed;
2247 stream->avail_out = compressed_len;
2249 return ret;
2253 * Common steps for loose object writers to end writing loose objects:
2255 * - End the compression of zlib stream.
2256 * - Get the calculated oid to "oid".
2258 static int end_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
2259 git_zstream *stream, struct object_id *oid,
2260 struct object_id *compat_oid)
2262 struct repository *repo = the_repository;
2263 const struct git_hash_algo *algo = repo->hash_algo;
2264 const struct git_hash_algo *compat = repo->compat_hash_algo;
2265 int ret;
2267 ret = git_deflate_end_gently(stream);
2268 if (ret != Z_OK)
2269 return ret;
2270 algo->final_oid_fn(oid, c);
2271 if (compat && compat_c)
2272 compat->final_oid_fn(compat_oid, compat_c);
2274 return Z_OK;
2277 static int write_loose_object(const struct object_id *oid, char *hdr,
2278 int hdrlen, const void *buf, unsigned long len,
2279 time_t mtime, unsigned flags)
2281 int fd, ret;
2282 unsigned char compressed[4096];
2283 git_zstream stream;
2284 git_hash_ctx c;
2285 struct object_id parano_oid;
2286 static struct strbuf tmp_file = STRBUF_INIT;
2287 static struct strbuf filename = STRBUF_INIT;
2289 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2290 prepare_loose_object_bulk_checkin();
2292 loose_object_path(the_repository, &filename, oid);
2294 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2295 &stream, compressed, sizeof(compressed),
2296 &c, NULL, hdr, hdrlen);
2297 if (fd < 0)
2298 return -1;
2300 /* Then the data itself.. */
2301 stream.next_in = (void *)buf;
2302 stream.avail_in = len;
2303 do {
2304 unsigned char *in0 = stream.next_in;
2306 ret = write_loose_object_common(&c, NULL, &stream, 1, in0, fd,
2307 compressed, sizeof(compressed));
2308 } while (ret == Z_OK);
2310 if (ret != Z_STREAM_END)
2311 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
2312 ret);
2313 ret = end_loose_object_common(&c, NULL, &stream, &parano_oid, NULL);
2314 if (ret != Z_OK)
2315 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
2316 ret);
2317 if (!oideq(oid, &parano_oid))
2318 die(_("confused by unstable object source data for %s"),
2319 oid_to_hex(oid));
2321 close_loose_object(fd, tmp_file.buf);
2323 if (mtime) {
2324 struct utimbuf utb;
2325 utb.actime = mtime;
2326 utb.modtime = mtime;
2327 if (utime(tmp_file.buf, &utb) < 0 &&
2328 !(flags & HASH_SILENT))
2329 warning_errno(_("failed utime() on %s"), tmp_file.buf);
2332 return finalize_object_file_flags(tmp_file.buf, filename.buf,
2333 FOF_SKIP_COLLISION_CHECK);
2336 static int freshen_loose_object(const struct object_id *oid)
2338 return check_and_freshen(oid, 1);
2341 static int freshen_packed_object(const struct object_id *oid)
2343 struct pack_entry e;
2344 if (!find_pack_entry(the_repository, oid, &e))
2345 return 0;
2346 if (e.p->is_cruft)
2347 return 0;
2348 if (e.p->freshened)
2349 return 1;
2350 if (!freshen_file(e.p->pack_name))
2351 return 0;
2352 e.p->freshened = 1;
2353 return 1;
2356 int stream_loose_object(struct input_stream *in_stream, size_t len,
2357 struct object_id *oid)
2359 const struct git_hash_algo *compat = the_repository->compat_hash_algo;
2360 struct object_id compat_oid;
2361 int fd, ret, err = 0, flush = 0;
2362 unsigned char compressed[4096];
2363 git_zstream stream;
2364 git_hash_ctx c, compat_c;
2365 struct strbuf tmp_file = STRBUF_INIT;
2366 struct strbuf filename = STRBUF_INIT;
2367 int dirlen;
2368 char hdr[MAX_HEADER_LEN];
2369 int hdrlen;
2371 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2372 prepare_loose_object_bulk_checkin();
2374 /* Since oid is not determined, save tmp file to odb path. */
2375 strbuf_addf(&filename, "%s/", repo_get_object_directory(the_repository));
2376 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2379 * Common steps for write_loose_object and stream_loose_object to
2380 * start writing loose objects:
2382 * - Create tmpfile for the loose object.
2383 * - Setup zlib stream for compression.
2384 * - Start to feed header to zlib stream.
2386 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2387 &stream, compressed, sizeof(compressed),
2388 &c, &compat_c, hdr, hdrlen);
2389 if (fd < 0) {
2390 err = -1;
2391 goto cleanup;
2394 /* Then the data itself.. */
2395 do {
2396 unsigned char *in0 = stream.next_in;
2398 if (!stream.avail_in && !in_stream->is_finished) {
2399 const void *in = in_stream->read(in_stream, &stream.avail_in);
2400 stream.next_in = (void *)in;
2401 in0 = (unsigned char *)in;
2402 /* All data has been read. */
2403 if (in_stream->is_finished)
2404 flush = 1;
2406 ret = write_loose_object_common(&c, &compat_c, &stream, flush, in0, fd,
2407 compressed, sizeof(compressed));
2409 * Unlike write_loose_object(), we do not have the entire
2410 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2411 * then we'll replenish them in the next input_stream->read()
2412 * call when we loop.
2414 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2416 if (stream.total_in != len + hdrlen)
2417 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2418 (uintmax_t)len + hdrlen);
2421 * Common steps for write_loose_object and stream_loose_object to
2422 * end writing loose object:
2424 * - End the compression of zlib stream.
2425 * - Get the calculated oid.
2427 if (ret != Z_STREAM_END)
2428 die(_("unable to stream deflate new object (%d)"), ret);
2429 ret = end_loose_object_common(&c, &compat_c, &stream, oid, &compat_oid);
2430 if (ret != Z_OK)
2431 die(_("deflateEnd on stream object failed (%d)"), ret);
2432 close_loose_object(fd, tmp_file.buf);
2434 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2435 unlink_or_warn(tmp_file.buf);
2436 goto cleanup;
2439 loose_object_path(the_repository, &filename, oid);
2441 /* We finally know the object path, and create the missing dir. */
2442 dirlen = directory_size(filename.buf);
2443 if (dirlen) {
2444 struct strbuf dir = STRBUF_INIT;
2445 strbuf_add(&dir, filename.buf, dirlen);
2447 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2448 err = error_errno(_("unable to create directory %s"), dir.buf);
2449 strbuf_release(&dir);
2450 goto cleanup;
2452 strbuf_release(&dir);
2455 err = finalize_object_file_flags(tmp_file.buf, filename.buf,
2456 FOF_SKIP_COLLISION_CHECK);
2457 if (!err && compat)
2458 err = repo_add_loose_object_map(the_repository, oid, &compat_oid);
2459 cleanup:
2460 strbuf_release(&tmp_file);
2461 strbuf_release(&filename);
2462 return err;
2465 int write_object_file_flags(const void *buf, unsigned long len,
2466 enum object_type type, struct object_id *oid,
2467 struct object_id *compat_oid_in, unsigned flags)
2469 struct repository *repo = the_repository;
2470 const struct git_hash_algo *algo = repo->hash_algo;
2471 const struct git_hash_algo *compat = repo->compat_hash_algo;
2472 struct object_id compat_oid;
2473 char hdr[MAX_HEADER_LEN];
2474 int hdrlen = sizeof(hdr);
2476 /* Generate compat_oid */
2477 if (compat) {
2478 if (compat_oid_in)
2479 oidcpy(&compat_oid, compat_oid_in);
2480 else if (type == OBJ_BLOB)
2481 hash_object_file(compat, buf, len, type, &compat_oid);
2482 else {
2483 struct strbuf converted = STRBUF_INIT;
2484 convert_object_file(&converted, algo, compat,
2485 buf, len, type, 0);
2486 hash_object_file(compat, converted.buf, converted.len,
2487 type, &compat_oid);
2488 strbuf_release(&converted);
2492 /* Normally if we have it in the pack then we do not bother writing
2493 * it out into .git/objects/??/?{38} file.
2495 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
2496 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2497 return 0;
2498 if (write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags))
2499 return -1;
2500 if (compat)
2501 return repo_add_loose_object_map(repo, oid, &compat_oid);
2502 return 0;
2505 int write_object_file_literally(const void *buf, unsigned long len,
2506 const char *type, struct object_id *oid,
2507 unsigned flags)
2509 char *header;
2510 struct repository *repo = the_repository;
2511 const struct git_hash_algo *algo = repo->hash_algo;
2512 const struct git_hash_algo *compat = repo->compat_hash_algo;
2513 struct object_id compat_oid;
2514 int hdrlen, status = 0;
2515 int compat_type = -1;
2517 if (compat) {
2518 compat_type = type_from_string_gently(type, -1, 1);
2519 if (compat_type == OBJ_BLOB)
2520 hash_object_file(compat, buf, len, compat_type,
2521 &compat_oid);
2522 else if (compat_type != -1) {
2523 struct strbuf converted = STRBUF_INIT;
2524 convert_object_file(&converted, algo, compat,
2525 buf, len, compat_type, 0);
2526 hash_object_file(compat, converted.buf, converted.len,
2527 compat_type, &compat_oid);
2528 strbuf_release(&converted);
2532 /* type string, SP, %lu of the length plus NUL must fit this */
2533 hdrlen = strlen(type) + MAX_HEADER_LEN;
2534 header = xmalloc(hdrlen);
2535 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2536 oid, header, &hdrlen);
2538 if (!(flags & HASH_WRITE_OBJECT))
2539 goto cleanup;
2540 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2541 goto cleanup;
2542 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
2543 if (compat_type != -1)
2544 return repo_add_loose_object_map(repo, oid, &compat_oid);
2546 cleanup:
2547 free(header);
2548 return status;
2551 int force_object_loose(const struct object_id *oid, time_t mtime)
2553 struct repository *repo = the_repository;
2554 const struct git_hash_algo *compat = repo->compat_hash_algo;
2555 void *buf;
2556 unsigned long len;
2557 struct object_info oi = OBJECT_INFO_INIT;
2558 struct object_id compat_oid;
2559 enum object_type type;
2560 char hdr[MAX_HEADER_LEN];
2561 int hdrlen;
2562 int ret;
2564 if (has_loose_object(oid))
2565 return 0;
2566 oi.typep = &type;
2567 oi.sizep = &len;
2568 oi.contentp = &buf;
2569 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2570 return error(_("cannot read object for %s"), oid_to_hex(oid));
2571 if (compat) {
2572 if (repo_oid_to_algop(repo, oid, compat, &compat_oid))
2573 return error(_("cannot map object %s to %s"),
2574 oid_to_hex(oid), compat->name);
2576 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
2577 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
2578 if (!ret && compat)
2579 ret = repo_add_loose_object_map(the_repository, oid, &compat_oid);
2580 free(buf);
2582 return ret;
2585 int has_object(struct repository *r, const struct object_id *oid,
2586 unsigned flags)
2588 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2589 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2590 (quick ? OBJECT_INFO_QUICK : 0);
2592 if (!startup_info->have_repository)
2593 return 0;
2594 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2597 int repo_has_object_file_with_flags(struct repository *r,
2598 const struct object_id *oid, int flags)
2600 if (!startup_info->have_repository)
2601 return 0;
2602 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2605 int repo_has_object_file(struct repository *r,
2606 const struct object_id *oid)
2608 return repo_has_object_file_with_flags(r, oid, 0);
2612 * We can't use the normal fsck_error_function() for index_mem(),
2613 * because we don't yet have a valid oid for it to report. Instead,
2614 * report the minimal fsck error here, and rely on the caller to
2615 * give more context.
2617 static int hash_format_check_report(struct fsck_options *opts UNUSED,
2618 void *fsck_report UNUSED,
2619 enum fsck_msg_type msg_type UNUSED,
2620 enum fsck_msg_id msg_id UNUSED,
2621 const char *message)
2623 error(_("object fails fsck: %s"), message);
2624 return 1;
2627 static int index_mem(struct index_state *istate,
2628 struct object_id *oid,
2629 const void *buf, size_t size,
2630 enum object_type type,
2631 const char *path, unsigned flags)
2633 struct strbuf nbuf = STRBUF_INIT;
2634 int ret = 0;
2635 int write_object = flags & HASH_WRITE_OBJECT;
2637 if (!type)
2638 type = OBJ_BLOB;
2641 * Convert blobs to git internal format
2643 if ((type == OBJ_BLOB) && path) {
2644 if (convert_to_git(istate, path, buf, size, &nbuf,
2645 get_conv_flags(flags))) {
2646 buf = nbuf.buf;
2647 size = nbuf.len;
2650 if (flags & HASH_FORMAT_CHECK) {
2651 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2653 opts.strict = 1;
2654 opts.error_func = hash_format_check_report;
2655 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2656 die(_("refusing to create malformed object"));
2657 fsck_finish(&opts);
2660 if (write_object)
2661 ret = write_object_file(buf, size, type, oid);
2662 else
2663 hash_object_file(the_hash_algo, buf, size, type, oid);
2665 strbuf_release(&nbuf);
2666 return ret;
2669 static int index_stream_convert_blob(struct index_state *istate,
2670 struct object_id *oid,
2671 int fd,
2672 const char *path,
2673 unsigned flags)
2675 int ret = 0;
2676 const int write_object = flags & HASH_WRITE_OBJECT;
2677 struct strbuf sbuf = STRBUF_INIT;
2679 assert(path);
2680 assert(would_convert_to_git_filter_fd(istate, path));
2682 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2683 get_conv_flags(flags));
2685 if (write_object)
2686 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
2687 oid);
2688 else
2689 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2690 oid);
2691 strbuf_release(&sbuf);
2692 return ret;
2695 static int index_pipe(struct index_state *istate, struct object_id *oid,
2696 int fd, enum object_type type,
2697 const char *path, unsigned flags)
2699 struct strbuf sbuf = STRBUF_INIT;
2700 int ret;
2702 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2703 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2704 else
2705 ret = -1;
2706 strbuf_release(&sbuf);
2707 return ret;
2710 #define SMALL_FILE_SIZE (32*1024)
2712 static int index_core(struct index_state *istate,
2713 struct object_id *oid, int fd, size_t size,
2714 enum object_type type, const char *path,
2715 unsigned flags)
2717 int ret;
2719 if (!size) {
2720 ret = index_mem(istate, oid, "", size, type, path, flags);
2721 } else if (size <= SMALL_FILE_SIZE) {
2722 char *buf = xmalloc(size);
2723 ssize_t read_result = read_in_full(fd, buf, size);
2724 if (read_result < 0)
2725 ret = error_errno(_("read error while indexing %s"),
2726 path ? path : "<unknown>");
2727 else if (read_result != size)
2728 ret = error(_("short read while indexing %s"),
2729 path ? path : "<unknown>");
2730 else
2731 ret = index_mem(istate, oid, buf, size, type, path, flags);
2732 free(buf);
2733 } else {
2734 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2735 ret = index_mem(istate, oid, buf, size, type, path, flags);
2736 munmap(buf, size);
2738 return ret;
2742 * This creates one packfile per large blob unless bulk-checkin
2743 * machinery is "plugged".
2745 * This also bypasses the usual "convert-to-git" dance, and that is on
2746 * purpose. We could write a streaming version of the converting
2747 * functions and insert that before feeding the data to fast-import
2748 * (or equivalent in-core API described above). However, that is
2749 * somewhat complicated, as we do not know the size of the filter
2750 * result, which we need to know beforehand when writing a git object.
2751 * Since the primary motivation for trying to stream from the working
2752 * tree file and to avoid mmaping it in core is to deal with large
2753 * binary blobs, they generally do not want to get any conversion, and
2754 * callers should avoid this code path when filters are requested.
2756 static int index_blob_stream(struct object_id *oid, int fd, size_t size,
2757 const char *path,
2758 unsigned flags)
2760 return index_blob_bulk_checkin(oid, fd, size, path, flags);
2763 int index_fd(struct index_state *istate, struct object_id *oid,
2764 int fd, struct stat *st,
2765 enum object_type type, const char *path, unsigned flags)
2767 int ret;
2770 * Call xsize_t() only when needed to avoid potentially unnecessary
2771 * die() for large files.
2773 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2774 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2775 else if (!S_ISREG(st->st_mode))
2776 ret = index_pipe(istate, oid, fd, type, path, flags);
2777 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2778 (path && would_convert_to_git(istate, path)))
2779 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2780 type, path, flags);
2781 else
2782 ret = index_blob_stream(oid, fd, xsize_t(st->st_size), path,
2783 flags);
2784 close(fd);
2785 return ret;
2788 int index_path(struct index_state *istate, struct object_id *oid,
2789 const char *path, struct stat *st, unsigned flags)
2791 int fd;
2792 struct strbuf sb = STRBUF_INIT;
2793 int rc = 0;
2795 switch (st->st_mode & S_IFMT) {
2796 case S_IFREG:
2797 fd = open(path, O_RDONLY);
2798 if (fd < 0)
2799 return error_errno("open(\"%s\")", path);
2800 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2801 return error(_("%s: failed to insert into database"),
2802 path);
2803 break;
2804 case S_IFLNK:
2805 if (strbuf_readlink(&sb, path, st->st_size))
2806 return error_errno("readlink(\"%s\")", path);
2807 if (!(flags & HASH_WRITE_OBJECT))
2808 hash_object_file(the_hash_algo, sb.buf, sb.len,
2809 OBJ_BLOB, oid);
2810 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
2811 rc = error(_("%s: failed to insert into database"), path);
2812 strbuf_release(&sb);
2813 break;
2814 case S_IFDIR:
2815 return repo_resolve_gitlink_ref(the_repository, path, "HEAD", oid);
2816 default:
2817 return error(_("%s: unsupported file type"), path);
2819 return rc;
2822 int read_pack_header(int fd, struct pack_header *header)
2824 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2825 /* "eof before pack header was fully read" */
2826 return PH_ERROR_EOF;
2828 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2829 /* "protocol error (pack signature mismatch detected)" */
2830 return PH_ERROR_PACK_SIGNATURE;
2831 if (!pack_version_ok(header->hdr_version))
2832 /* "protocol error (pack version unsupported)" */
2833 return PH_ERROR_PROTOCOL;
2834 return 0;
2837 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2839 enum object_type type = oid_object_info(the_repository, oid, NULL);
2840 if (type < 0)
2841 die(_("%s is not a valid object"), oid_to_hex(oid));
2842 if (type != expect)
2843 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2844 type_name(expect));
2847 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2848 struct strbuf *path,
2849 each_loose_object_fn obj_cb,
2850 each_loose_cruft_fn cruft_cb,
2851 each_loose_subdir_fn subdir_cb,
2852 void *data)
2854 size_t origlen, baselen;
2855 DIR *dir;
2856 struct dirent *de;
2857 int r = 0;
2858 struct object_id oid;
2860 if (subdir_nr > 0xff)
2861 BUG("invalid loose object subdirectory: %x", subdir_nr);
2863 origlen = path->len;
2864 strbuf_complete(path, '/');
2865 strbuf_addf(path, "%02x", subdir_nr);
2867 dir = opendir(path->buf);
2868 if (!dir) {
2869 if (errno != ENOENT)
2870 r = error_errno(_("unable to open %s"), path->buf);
2871 strbuf_setlen(path, origlen);
2872 return r;
2875 oid.hash[0] = subdir_nr;
2876 strbuf_addch(path, '/');
2877 baselen = path->len;
2879 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2880 size_t namelen;
2882 namelen = strlen(de->d_name);
2883 strbuf_setlen(path, baselen);
2884 strbuf_add(path, de->d_name, namelen);
2885 if (namelen == the_hash_algo->hexsz - 2 &&
2886 !hex_to_bytes(oid.hash + 1, de->d_name,
2887 the_hash_algo->rawsz - 1)) {
2888 oid_set_algo(&oid, the_hash_algo);
2889 memset(oid.hash + the_hash_algo->rawsz, 0,
2890 GIT_MAX_RAWSZ - the_hash_algo->rawsz);
2891 if (obj_cb) {
2892 r = obj_cb(&oid, path->buf, data);
2893 if (r)
2894 break;
2896 continue;
2899 if (cruft_cb) {
2900 r = cruft_cb(de->d_name, path->buf, data);
2901 if (r)
2902 break;
2905 closedir(dir);
2907 strbuf_setlen(path, baselen - 1);
2908 if (!r && subdir_cb)
2909 r = subdir_cb(subdir_nr, path->buf, data);
2911 strbuf_setlen(path, origlen);
2913 return r;
2916 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2917 each_loose_object_fn obj_cb,
2918 each_loose_cruft_fn cruft_cb,
2919 each_loose_subdir_fn subdir_cb,
2920 void *data)
2922 int r = 0;
2923 int i;
2925 for (i = 0; i < 256; i++) {
2926 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2927 subdir_cb, data);
2928 if (r)
2929 break;
2932 return r;
2935 int for_each_loose_file_in_objdir(const char *path,
2936 each_loose_object_fn obj_cb,
2937 each_loose_cruft_fn cruft_cb,
2938 each_loose_subdir_fn subdir_cb,
2939 void *data)
2941 struct strbuf buf = STRBUF_INIT;
2942 int r;
2944 strbuf_addstr(&buf, path);
2945 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2946 subdir_cb, data);
2947 strbuf_release(&buf);
2949 return r;
2952 int for_each_loose_object(each_loose_object_fn cb, void *data,
2953 enum for_each_object_flags flags)
2955 struct object_directory *odb;
2957 prepare_alt_odb(the_repository);
2958 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2959 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2960 NULL, data);
2961 if (r)
2962 return r;
2964 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2965 break;
2968 return 0;
2971 static int append_loose_object(const struct object_id *oid,
2972 const char *path UNUSED,
2973 void *data)
2975 oidtree_insert(data, oid);
2976 return 0;
2979 struct oidtree *odb_loose_cache(struct object_directory *odb,
2980 const struct object_id *oid)
2982 int subdir_nr = oid->hash[0];
2983 struct strbuf buf = STRBUF_INIT;
2984 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2985 size_t word_index = subdir_nr / word_bits;
2986 size_t mask = (size_t)1u << (subdir_nr % word_bits);
2987 uint32_t *bitmap;
2989 if (subdir_nr < 0 ||
2990 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2991 BUG("subdir_nr out of range");
2993 bitmap = &odb->loose_objects_subdir_seen[word_index];
2994 if (*bitmap & mask)
2995 return odb->loose_objects_cache;
2996 if (!odb->loose_objects_cache) {
2997 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2998 oidtree_init(odb->loose_objects_cache);
3000 strbuf_addstr(&buf, odb->path);
3001 for_each_file_in_obj_subdir(subdir_nr, &buf,
3002 append_loose_object,
3003 NULL, NULL,
3004 odb->loose_objects_cache);
3005 *bitmap |= mask;
3006 strbuf_release(&buf);
3007 return odb->loose_objects_cache;
3010 void odb_clear_loose_cache(struct object_directory *odb)
3012 oidtree_clear(odb->loose_objects_cache);
3013 FREE_AND_NULL(odb->loose_objects_cache);
3014 memset(&odb->loose_objects_subdir_seen, 0,
3015 sizeof(odb->loose_objects_subdir_seen));
3018 static int check_stream_oid(git_zstream *stream,
3019 const char *hdr,
3020 unsigned long size,
3021 const char *path,
3022 const struct object_id *expected_oid)
3024 git_hash_ctx c;
3025 struct object_id real_oid;
3026 unsigned char buf[4096];
3027 unsigned long total_read;
3028 int status = Z_OK;
3030 the_hash_algo->init_fn(&c);
3031 the_hash_algo->update_fn(&c, hdr, stream->total_out);
3034 * We already read some bytes into hdr, but the ones up to the NUL
3035 * do not count against the object's content size.
3037 total_read = stream->total_out - strlen(hdr) - 1;
3040 * This size comparison must be "<=" to read the final zlib packets;
3041 * see the comment in unpack_loose_rest for details.
3043 while (total_read <= size &&
3044 (status == Z_OK ||
3045 (status == Z_BUF_ERROR && !stream->avail_out))) {
3046 stream->next_out = buf;
3047 stream->avail_out = sizeof(buf);
3048 if (size - total_read < stream->avail_out)
3049 stream->avail_out = size - total_read;
3050 status = git_inflate(stream, Z_FINISH);
3051 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
3052 total_read += stream->next_out - buf;
3054 git_inflate_end(stream);
3056 if (status != Z_STREAM_END) {
3057 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
3058 return -1;
3060 if (stream->avail_in) {
3061 error(_("garbage at end of loose object '%s'"),
3062 oid_to_hex(expected_oid));
3063 return -1;
3066 the_hash_algo->final_oid_fn(&real_oid, &c);
3067 if (!oideq(expected_oid, &real_oid)) {
3068 error(_("hash mismatch for %s (expected %s)"), path,
3069 oid_to_hex(expected_oid));
3070 return -1;
3073 return 0;
3076 int read_loose_object(const char *path,
3077 const struct object_id *expected_oid,
3078 struct object_id *real_oid,
3079 void **contents,
3080 struct object_info *oi)
3082 int ret = -1;
3083 int fd;
3084 void *map = NULL;
3085 unsigned long mapsize;
3086 git_zstream stream;
3087 char hdr[MAX_HEADER_LEN];
3088 unsigned long *size = oi->sizep;
3090 fd = git_open(path);
3091 if (fd >= 0)
3092 map = map_fd(fd, path, &mapsize);
3093 if (!map) {
3094 error_errno(_("unable to mmap %s"), path);
3095 goto out;
3098 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
3099 NULL) != ULHR_OK) {
3100 error(_("unable to unpack header of %s"), path);
3101 git_inflate_end(&stream);
3102 goto out;
3105 if (parse_loose_header(hdr, oi) < 0) {
3106 error(_("unable to parse header of %s"), path);
3107 git_inflate_end(&stream);
3108 goto out;
3111 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
3112 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
3113 goto out;
3114 } else {
3115 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
3116 if (!*contents) {
3117 error(_("unable to unpack contents of %s"), path);
3118 git_inflate_end(&stream);
3119 goto out;
3121 hash_object_file_literally(the_repository->hash_algo,
3122 *contents, *size,
3123 oi->type_name->buf, real_oid);
3124 if (!oideq(expected_oid, real_oid))
3125 goto out;
3128 ret = 0; /* everything checks out */
3130 out:
3131 if (map)
3132 munmap(map, mapsize);
3133 return ret;