fetch: centralize logic to print remote URL
[alt-git.git] / object-file.c
blob939865c1ae0566ba577861505f2ecf2e9fd19eeb
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "hash-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "replace-object.h"
27 #include "streaming.h"
28 #include "dir.h"
29 #include "list.h"
30 #include "mergesort.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "promisor-remote.h"
35 #include "submodule.h"
36 #include "fsck.h"
38 /* The maximum size for an object header. */
39 #define MAX_HEADER_LEN 32
42 #define EMPTY_TREE_SHA1_BIN_LITERAL \
43 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
44 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
45 #define EMPTY_TREE_SHA256_BIN_LITERAL \
46 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
47 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
48 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
49 "\x53\x21"
51 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
52 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
53 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
54 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
55 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
56 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
57 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
58 "\x18\x13"
60 static const struct object_id empty_tree_oid = {
61 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
62 .algo = GIT_HASH_SHA1,
64 static const struct object_id empty_blob_oid = {
65 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
66 .algo = GIT_HASH_SHA1,
68 static const struct object_id null_oid_sha1 = {
69 .hash = {0},
70 .algo = GIT_HASH_SHA1,
72 static const struct object_id empty_tree_oid_sha256 = {
73 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
74 .algo = GIT_HASH_SHA256,
76 static const struct object_id empty_blob_oid_sha256 = {
77 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
78 .algo = GIT_HASH_SHA256,
80 static const struct object_id null_oid_sha256 = {
81 .hash = {0},
82 .algo = GIT_HASH_SHA256,
85 static void git_hash_sha1_init(git_hash_ctx *ctx)
87 git_SHA1_Init(&ctx->sha1);
90 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
92 git_SHA1_Clone(&dst->sha1, &src->sha1);
95 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
97 git_SHA1_Update(&ctx->sha1, data, len);
100 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
102 git_SHA1_Final(hash, &ctx->sha1);
105 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
107 git_SHA1_Final(oid->hash, &ctx->sha1);
108 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
109 oid->algo = GIT_HASH_SHA1;
113 static void git_hash_sha256_init(git_hash_ctx *ctx)
115 git_SHA256_Init(&ctx->sha256);
118 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
120 git_SHA256_Clone(&dst->sha256, &src->sha256);
123 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
125 git_SHA256_Update(&ctx->sha256, data, len);
128 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
130 git_SHA256_Final(hash, &ctx->sha256);
133 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
135 git_SHA256_Final(oid->hash, &ctx->sha256);
137 * This currently does nothing, so the compiler should optimize it out,
138 * but keep it in case we extend the hash size again.
140 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
141 oid->algo = GIT_HASH_SHA256;
144 static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
146 BUG("trying to init unknown hash");
149 static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
150 const git_hash_ctx *src UNUSED)
152 BUG("trying to clone unknown hash");
155 static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
156 const void *data UNUSED,
157 size_t len UNUSED)
159 BUG("trying to update unknown hash");
162 static void git_hash_unknown_final(unsigned char *hash UNUSED,
163 git_hash_ctx *ctx UNUSED)
165 BUG("trying to finalize unknown hash");
168 static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
169 git_hash_ctx *ctx UNUSED)
171 BUG("trying to finalize unknown hash");
174 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
176 .name = NULL,
177 .format_id = 0x00000000,
178 .rawsz = 0,
179 .hexsz = 0,
180 .blksz = 0,
181 .init_fn = git_hash_unknown_init,
182 .clone_fn = git_hash_unknown_clone,
183 .update_fn = git_hash_unknown_update,
184 .final_fn = git_hash_unknown_final,
185 .final_oid_fn = git_hash_unknown_final_oid,
186 .empty_tree = NULL,
187 .empty_blob = NULL,
188 .null_oid = NULL,
191 .name = "sha1",
192 .format_id = GIT_SHA1_FORMAT_ID,
193 .rawsz = GIT_SHA1_RAWSZ,
194 .hexsz = GIT_SHA1_HEXSZ,
195 .blksz = GIT_SHA1_BLKSZ,
196 .init_fn = git_hash_sha1_init,
197 .clone_fn = git_hash_sha1_clone,
198 .update_fn = git_hash_sha1_update,
199 .final_fn = git_hash_sha1_final,
200 .final_oid_fn = git_hash_sha1_final_oid,
201 .empty_tree = &empty_tree_oid,
202 .empty_blob = &empty_blob_oid,
203 .null_oid = &null_oid_sha1,
206 .name = "sha256",
207 .format_id = GIT_SHA256_FORMAT_ID,
208 .rawsz = GIT_SHA256_RAWSZ,
209 .hexsz = GIT_SHA256_HEXSZ,
210 .blksz = GIT_SHA256_BLKSZ,
211 .init_fn = git_hash_sha256_init,
212 .clone_fn = git_hash_sha256_clone,
213 .update_fn = git_hash_sha256_update,
214 .final_fn = git_hash_sha256_final,
215 .final_oid_fn = git_hash_sha256_final_oid,
216 .empty_tree = &empty_tree_oid_sha256,
217 .empty_blob = &empty_blob_oid_sha256,
218 .null_oid = &null_oid_sha256,
222 const struct object_id *null_oid(void)
224 return the_hash_algo->null_oid;
227 const char *empty_tree_oid_hex(void)
229 static char buf[GIT_MAX_HEXSZ + 1];
230 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
233 const char *empty_blob_oid_hex(void)
235 static char buf[GIT_MAX_HEXSZ + 1];
236 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
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 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 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 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
424 int i;
425 for (i = 0; i < the_hash_algo->rawsz; i++) {
426 static char hex[] = "0123456789abcdef";
427 unsigned int val = oid->hash[i];
428 strbuf_addch(buf, hex[val >> 4]);
429 strbuf_addch(buf, hex[val & 0xf]);
430 if (!i)
431 strbuf_addch(buf, '/');
435 static const char *odb_loose_path(struct object_directory *odb,
436 struct strbuf *buf,
437 const struct object_id *oid)
439 strbuf_reset(buf);
440 strbuf_addstr(buf, odb->path);
441 strbuf_addch(buf, '/');
442 fill_loose_path(buf, oid);
443 return buf->buf;
446 const char *loose_object_path(struct repository *r, struct strbuf *buf,
447 const struct object_id *oid)
449 return odb_loose_path(r->objects->odb, buf, oid);
453 * Return non-zero iff the path is usable as an alternate object database.
455 static int alt_odb_usable(struct raw_object_store *o,
456 struct strbuf *path,
457 const char *normalized_objdir, khiter_t *pos)
459 int r;
461 /* Detect cases where alternate disappeared */
462 if (!is_directory(path->buf)) {
463 error(_("object directory %s does not exist; "
464 "check .git/objects/info/alternates"),
465 path->buf);
466 return 0;
470 * Prevent the common mistake of listing the same
471 * thing twice, or object directory itself.
473 if (!o->odb_by_path) {
474 khiter_t p;
476 o->odb_by_path = kh_init_odb_path_map();
477 assert(!o->odb->next);
478 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
479 assert(r == 1); /* never used */
480 kh_value(o->odb_by_path, p) = o->odb;
482 if (fspatheq(path->buf, normalized_objdir))
483 return 0;
484 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
485 /* r: 0 = exists, 1 = never used, 2 = deleted */
486 return r == 0 ? 0 : 1;
490 * Prepare alternate object database registry.
492 * The variable alt_odb_list points at the list of struct
493 * object_directory. The elements on this list come from
494 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
495 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
496 * whose contents is similar to that environment variable but can be
497 * LF separated. Its base points at a statically allocated buffer that
498 * contains "/the/directory/corresponding/to/.git/objects/...", while
499 * its name points just after the slash at the end of ".git/objects/"
500 * in the example above, and has enough space to hold all hex characters
501 * of the object ID, an extra slash for the first level indirection, and
502 * the terminating NUL.
504 static void read_info_alternates(struct repository *r,
505 const char *relative_base,
506 int depth);
507 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
508 const char *relative_base, int depth, const char *normalized_objdir)
510 struct object_directory *ent;
511 struct strbuf pathbuf = STRBUF_INIT;
512 struct strbuf tmp = STRBUF_INIT;
513 khiter_t pos;
514 int ret = -1;
516 if (!is_absolute_path(entry->buf) && relative_base) {
517 strbuf_realpath(&pathbuf, relative_base, 1);
518 strbuf_addch(&pathbuf, '/');
520 strbuf_addbuf(&pathbuf, entry);
522 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
523 error(_("unable to normalize alternate object path: %s"),
524 pathbuf.buf);
525 goto error;
527 strbuf_swap(&pathbuf, &tmp);
530 * The trailing slash after the directory name is given by
531 * this function at the end. Remove duplicates.
533 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
534 strbuf_setlen(&pathbuf, pathbuf.len - 1);
536 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
537 goto error;
539 CALLOC_ARRAY(ent, 1);
540 /* pathbuf.buf is already in r->objects->odb_by_path */
541 ent->path = strbuf_detach(&pathbuf, NULL);
543 /* add the alternate entry */
544 *r->objects->odb_tail = ent;
545 r->objects->odb_tail = &(ent->next);
546 ent->next = NULL;
547 assert(r->objects->odb_by_path);
548 kh_value(r->objects->odb_by_path, pos) = ent;
550 /* recursively add alternates */
551 read_info_alternates(r, ent->path, depth + 1);
552 ret = 0;
553 error:
554 strbuf_release(&tmp);
555 strbuf_release(&pathbuf);
556 return ret;
559 static const char *parse_alt_odb_entry(const char *string,
560 int sep,
561 struct strbuf *out)
563 const char *end;
565 strbuf_reset(out);
567 if (*string == '#') {
568 /* comment; consume up to next separator */
569 end = strchrnul(string, sep);
570 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
572 * quoted path; unquote_c_style has copied the
573 * data for us and set "end". Broken quoting (e.g.,
574 * an entry that doesn't end with a quote) falls
575 * back to the unquoted case below.
577 } else {
578 /* normal, unquoted path */
579 end = strchrnul(string, sep);
580 strbuf_add(out, string, end - string);
583 if (*end)
584 end++;
585 return end;
588 static void link_alt_odb_entries(struct repository *r, const char *alt,
589 int sep, const char *relative_base, int depth)
591 struct strbuf objdirbuf = STRBUF_INIT;
592 struct strbuf entry = STRBUF_INIT;
594 if (!alt || !*alt)
595 return;
597 if (depth > 5) {
598 error(_("%s: ignoring alternate object stores, nesting too deep"),
599 relative_base);
600 return;
603 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
605 while (*alt) {
606 alt = parse_alt_odb_entry(alt, sep, &entry);
607 if (!entry.len)
608 continue;
609 link_alt_odb_entry(r, &entry,
610 relative_base, depth, objdirbuf.buf);
612 strbuf_release(&entry);
613 strbuf_release(&objdirbuf);
616 static void read_info_alternates(struct repository *r,
617 const char *relative_base,
618 int depth)
620 char *path;
621 struct strbuf buf = STRBUF_INIT;
623 path = xstrfmt("%s/info/alternates", relative_base);
624 if (strbuf_read_file(&buf, path, 1024) < 0) {
625 warn_on_fopen_errors(path);
626 free(path);
627 return;
630 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
631 strbuf_release(&buf);
632 free(path);
635 void add_to_alternates_file(const char *reference)
637 struct lock_file lock = LOCK_INIT;
638 char *alts = git_pathdup("objects/info/alternates");
639 FILE *in, *out;
640 int found = 0;
642 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
643 out = fdopen_lock_file(&lock, "w");
644 if (!out)
645 die_errno(_("unable to fdopen alternates lockfile"));
647 in = fopen(alts, "r");
648 if (in) {
649 struct strbuf line = STRBUF_INIT;
651 while (strbuf_getline(&line, in) != EOF) {
652 if (!strcmp(reference, line.buf)) {
653 found = 1;
654 break;
656 fprintf_or_die(out, "%s\n", line.buf);
659 strbuf_release(&line);
660 fclose(in);
662 else if (errno != ENOENT)
663 die_errno(_("unable to read alternates file"));
665 if (found) {
666 rollback_lock_file(&lock);
667 } else {
668 fprintf_or_die(out, "%s\n", reference);
669 if (commit_lock_file(&lock))
670 die_errno(_("unable to move new alternates file into place"));
671 if (the_repository->objects->loaded_alternates)
672 link_alt_odb_entries(the_repository, reference,
673 '\n', NULL, 0);
675 free(alts);
678 void add_to_alternates_memory(const char *reference)
681 * Make sure alternates are initialized, or else our entry may be
682 * overwritten when they are.
684 prepare_alt_odb(the_repository);
686 link_alt_odb_entries(the_repository, reference,
687 '\n', NULL, 0);
690 struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
692 struct object_directory *new_odb;
695 * Make sure alternates are initialized, or else our entry may be
696 * overwritten when they are.
698 prepare_alt_odb(the_repository);
701 * Make a new primary odb and link the old primary ODB in as an
702 * alternate
704 new_odb = xcalloc(1, sizeof(*new_odb));
705 new_odb->path = xstrdup(dir);
708 * Disable ref updates while a temporary odb is active, since
709 * the objects in the database may roll back.
711 new_odb->disable_ref_updates = 1;
712 new_odb->will_destroy = will_destroy;
713 new_odb->next = the_repository->objects->odb;
714 the_repository->objects->odb = new_odb;
715 return new_odb->next;
718 void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
720 struct object_directory *cur_odb = the_repository->objects->odb;
722 if (strcmp(old_path, cur_odb->path))
723 BUG("expected %s as primary object store; found %s",
724 old_path, cur_odb->path);
726 if (cur_odb->next != restore_odb)
727 BUG("we expect the old primary object store to be the first alternate");
729 the_repository->objects->odb = restore_odb;
730 free_object_directory(cur_odb);
734 * Compute the exact path an alternate is at and returns it. In case of
735 * error NULL is returned and the human readable error is added to `err`
736 * `path` may be relative and should point to $GIT_DIR.
737 * `err` must not be null.
739 char *compute_alternate_path(const char *path, struct strbuf *err)
741 char *ref_git = NULL;
742 const char *repo;
743 int seen_error = 0;
745 ref_git = real_pathdup(path, 0);
746 if (!ref_git) {
747 seen_error = 1;
748 strbuf_addf(err, _("path '%s' does not exist"), path);
749 goto out;
752 repo = read_gitfile(ref_git);
753 if (!repo)
754 repo = read_gitfile(mkpath("%s/.git", ref_git));
755 if (repo) {
756 free(ref_git);
757 ref_git = xstrdup(repo);
760 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
761 char *ref_git_git = mkpathdup("%s/.git", ref_git);
762 free(ref_git);
763 ref_git = ref_git_git;
764 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
765 struct strbuf sb = STRBUF_INIT;
766 seen_error = 1;
767 if (get_common_dir(&sb, ref_git)) {
768 strbuf_addf(err,
769 _("reference repository '%s' as a linked "
770 "checkout is not supported yet."),
771 path);
772 goto out;
775 strbuf_addf(err, _("reference repository '%s' is not a "
776 "local repository."), path);
777 goto out;
780 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
781 strbuf_addf(err, _("reference repository '%s' is shallow"),
782 path);
783 seen_error = 1;
784 goto out;
787 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
788 strbuf_addf(err,
789 _("reference repository '%s' is grafted"),
790 path);
791 seen_error = 1;
792 goto out;
795 out:
796 if (seen_error) {
797 FREE_AND_NULL(ref_git);
800 return ref_git;
803 struct object_directory *find_odb(struct repository *r, const char *obj_dir)
805 struct object_directory *odb;
806 char *obj_dir_real = real_pathdup(obj_dir, 1);
807 struct strbuf odb_path_real = STRBUF_INIT;
809 prepare_alt_odb(r);
810 for (odb = r->objects->odb; odb; odb = odb->next) {
811 strbuf_realpath(&odb_path_real, odb->path, 1);
812 if (!strcmp(obj_dir_real, odb_path_real.buf))
813 break;
816 free(obj_dir_real);
817 strbuf_release(&odb_path_real);
819 if (!odb)
820 die(_("could not find object directory matching %s"), obj_dir);
821 return odb;
824 static void fill_alternate_refs_command(struct child_process *cmd,
825 const char *repo_path)
827 const char *value;
829 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
830 cmd->use_shell = 1;
832 strvec_push(&cmd->args, value);
833 strvec_push(&cmd->args, repo_path);
834 } else {
835 cmd->git_cmd = 1;
837 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
838 strvec_push(&cmd->args, "for-each-ref");
839 strvec_push(&cmd->args, "--format=%(objectname)");
841 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
842 strvec_push(&cmd->args, "--");
843 strvec_split(&cmd->args, value);
847 strvec_pushv(&cmd->env, (const char **)local_repo_env);
848 cmd->out = -1;
851 static void read_alternate_refs(const char *path,
852 alternate_ref_fn *cb,
853 void *data)
855 struct child_process cmd = CHILD_PROCESS_INIT;
856 struct strbuf line = STRBUF_INIT;
857 FILE *fh;
859 fill_alternate_refs_command(&cmd, path);
861 if (start_command(&cmd))
862 return;
864 fh = xfdopen(cmd.out, "r");
865 while (strbuf_getline_lf(&line, fh) != EOF) {
866 struct object_id oid;
867 const char *p;
869 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
870 warning(_("invalid line while parsing alternate refs: %s"),
871 line.buf);
872 break;
875 cb(&oid, data);
878 fclose(fh);
879 finish_command(&cmd);
880 strbuf_release(&line);
883 struct alternate_refs_data {
884 alternate_ref_fn *fn;
885 void *data;
888 static int refs_from_alternate_cb(struct object_directory *e,
889 void *data)
891 struct strbuf path = STRBUF_INIT;
892 size_t base_len;
893 struct alternate_refs_data *cb = data;
895 if (!strbuf_realpath(&path, e->path, 0))
896 goto out;
897 if (!strbuf_strip_suffix(&path, "/objects"))
898 goto out;
899 base_len = path.len;
901 /* Is this a git repository with refs? */
902 strbuf_addstr(&path, "/refs");
903 if (!is_directory(path.buf))
904 goto out;
905 strbuf_setlen(&path, base_len);
907 read_alternate_refs(path.buf, cb->fn, cb->data);
909 out:
910 strbuf_release(&path);
911 return 0;
914 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
916 struct alternate_refs_data cb;
917 cb.fn = fn;
918 cb.data = data;
919 foreach_alt_odb(refs_from_alternate_cb, &cb);
922 int foreach_alt_odb(alt_odb_fn fn, void *cb)
924 struct object_directory *ent;
925 int r = 0;
927 prepare_alt_odb(the_repository);
928 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
929 r = fn(ent, cb);
930 if (r)
931 break;
933 return r;
936 void prepare_alt_odb(struct repository *r)
938 if (r->objects->loaded_alternates)
939 return;
941 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
943 read_info_alternates(r, r->objects->odb->path, 0);
944 r->objects->loaded_alternates = 1;
947 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
948 static int freshen_file(const char *fn)
950 return !utime(fn, NULL);
954 * All of the check_and_freshen functions return 1 if the file exists and was
955 * freshened (if freshening was requested), 0 otherwise. If they return
956 * 0, you should not assume that it is safe to skip a write of the object (it
957 * either does not exist on disk, or has a stale mtime and may be subject to
958 * pruning).
960 int check_and_freshen_file(const char *fn, int freshen)
962 if (access(fn, F_OK))
963 return 0;
964 if (freshen && !freshen_file(fn))
965 return 0;
966 return 1;
969 static int check_and_freshen_odb(struct object_directory *odb,
970 const struct object_id *oid,
971 int freshen)
973 static struct strbuf path = STRBUF_INIT;
974 odb_loose_path(odb, &path, oid);
975 return check_and_freshen_file(path.buf, freshen);
978 static int check_and_freshen_local(const struct object_id *oid, int freshen)
980 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
983 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
985 struct object_directory *odb;
987 prepare_alt_odb(the_repository);
988 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
989 if (check_and_freshen_odb(odb, oid, freshen))
990 return 1;
992 return 0;
995 static int check_and_freshen(const struct object_id *oid, int freshen)
997 return check_and_freshen_local(oid, freshen) ||
998 check_and_freshen_nonlocal(oid, freshen);
1001 int has_loose_object_nonlocal(const struct object_id *oid)
1003 return check_and_freshen_nonlocal(oid, 0);
1006 int has_loose_object(const struct object_id *oid)
1008 return check_and_freshen(oid, 0);
1011 static void mmap_limit_check(size_t length)
1013 static size_t limit = 0;
1014 if (!limit) {
1015 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1016 if (!limit)
1017 limit = SIZE_MAX;
1019 if (length > limit)
1020 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1021 (uintmax_t)length, (uintmax_t)limit);
1024 void *xmmap_gently(void *start, size_t length,
1025 int prot, int flags, int fd, off_t offset)
1027 void *ret;
1029 mmap_limit_check(length);
1030 ret = mmap(start, length, prot, flags, fd, offset);
1031 if (ret == MAP_FAILED && !length)
1032 ret = NULL;
1033 return ret;
1036 const char *mmap_os_err(void)
1038 static const char blank[] = "";
1039 #if defined(__linux__)
1040 if (errno == ENOMEM) {
1041 /* this continues an existing error message: */
1042 static const char enomem[] =
1043 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1044 return enomem;
1046 #endif /* OS-specific bits */
1047 return blank;
1050 void *xmmap(void *start, size_t length,
1051 int prot, int flags, int fd, off_t offset)
1053 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1054 if (ret == MAP_FAILED)
1055 die_errno(_("mmap failed%s"), mmap_os_err());
1056 return ret;
1059 static int format_object_header_literally(char *str, size_t size,
1060 const char *type, size_t objsize)
1062 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1065 int format_object_header(char *str, size_t size, enum object_type type,
1066 size_t objsize)
1068 const char *name = type_name(type);
1070 if (!name)
1071 BUG("could not get a type name for 'enum object_type' value %d", type);
1073 return format_object_header_literally(str, size, name, objsize);
1076 int check_object_signature(struct repository *r, const struct object_id *oid,
1077 void *buf, unsigned long size,
1078 enum object_type type)
1080 struct object_id real_oid;
1082 hash_object_file(r->hash_algo, buf, size, type, &real_oid);
1084 return !oideq(oid, &real_oid) ? -1 : 0;
1087 int stream_object_signature(struct repository *r, const struct object_id *oid)
1089 struct object_id real_oid;
1090 unsigned long size;
1091 enum object_type obj_type;
1092 struct git_istream *st;
1093 git_hash_ctx c;
1094 char hdr[MAX_HEADER_LEN];
1095 int hdrlen;
1097 st = open_istream(r, oid, &obj_type, &size, NULL);
1098 if (!st)
1099 return -1;
1101 /* Generate the header */
1102 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
1104 /* Sha1.. */
1105 r->hash_algo->init_fn(&c);
1106 r->hash_algo->update_fn(&c, hdr, hdrlen);
1107 for (;;) {
1108 char buf[1024 * 16];
1109 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1111 if (readlen < 0) {
1112 close_istream(st);
1113 return -1;
1115 if (!readlen)
1116 break;
1117 r->hash_algo->update_fn(&c, buf, readlen);
1119 r->hash_algo->final_oid_fn(&real_oid, &c);
1120 close_istream(st);
1121 return !oideq(oid, &real_oid) ? -1 : 0;
1124 int git_open_cloexec(const char *name, int flags)
1126 int fd;
1127 static int o_cloexec = O_CLOEXEC;
1129 fd = open(name, flags | o_cloexec);
1130 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1131 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1132 o_cloexec &= ~O_CLOEXEC;
1133 fd = open(name, flags | o_cloexec);
1136 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1138 static int fd_cloexec = FD_CLOEXEC;
1140 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1141 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1142 int flags = fcntl(fd, F_GETFD);
1143 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1144 fd_cloexec = 0;
1147 #endif
1148 return fd;
1152 * Find "oid" as a loose object in the local repository or in an alternate.
1153 * Returns 0 on success, negative on failure.
1155 * The "path" out-parameter will give the path of the object we found (if any).
1156 * Note that it may point to static storage and is only valid until another
1157 * call to stat_loose_object().
1159 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1160 struct stat *st, const char **path)
1162 struct object_directory *odb;
1163 static struct strbuf buf = STRBUF_INIT;
1165 prepare_alt_odb(r);
1166 for (odb = r->objects->odb; odb; odb = odb->next) {
1167 *path = odb_loose_path(odb, &buf, oid);
1168 if (!lstat(*path, st))
1169 return 0;
1172 return -1;
1176 * Like stat_loose_object(), but actually open the object and return the
1177 * descriptor. See the caveats on the "path" parameter above.
1179 static int open_loose_object(struct repository *r,
1180 const struct object_id *oid, const char **path)
1182 int fd;
1183 struct object_directory *odb;
1184 int most_interesting_errno = ENOENT;
1185 static struct strbuf buf = STRBUF_INIT;
1187 prepare_alt_odb(r);
1188 for (odb = r->objects->odb; odb; odb = odb->next) {
1189 *path = odb_loose_path(odb, &buf, oid);
1190 fd = git_open(*path);
1191 if (fd >= 0)
1192 return fd;
1194 if (most_interesting_errno == ENOENT)
1195 most_interesting_errno = errno;
1197 errno = most_interesting_errno;
1198 return -1;
1201 static int quick_has_loose(struct repository *r,
1202 const struct object_id *oid)
1204 struct object_directory *odb;
1206 prepare_alt_odb(r);
1207 for (odb = r->objects->odb; odb; odb = odb->next) {
1208 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1209 return 1;
1211 return 0;
1215 * Map and close the given loose object fd. The path argument is used for
1216 * error reporting.
1218 static void *map_fd(int fd, const char *path, unsigned long *size)
1220 void *map = NULL;
1221 struct stat st;
1223 if (!fstat(fd, &st)) {
1224 *size = xsize_t(st.st_size);
1225 if (!*size) {
1226 /* mmap() is forbidden on empty files */
1227 error(_("object file %s is empty"), path);
1228 close(fd);
1229 return NULL;
1231 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1233 close(fd);
1234 return map;
1237 void *map_loose_object(struct repository *r,
1238 const struct object_id *oid,
1239 unsigned long *size)
1241 const char *p;
1242 int fd = open_loose_object(r, oid, &p);
1244 if (fd < 0)
1245 return NULL;
1246 return map_fd(fd, p, size);
1249 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1250 unsigned char *map,
1251 unsigned long mapsize,
1252 void *buffer,
1253 unsigned long bufsiz,
1254 struct strbuf *header)
1256 int status;
1258 /* Get the data stream */
1259 memset(stream, 0, sizeof(*stream));
1260 stream->next_in = map;
1261 stream->avail_in = mapsize;
1262 stream->next_out = buffer;
1263 stream->avail_out = bufsiz;
1265 git_inflate_init(stream);
1266 obj_read_unlock();
1267 status = git_inflate(stream, 0);
1268 obj_read_lock();
1269 if (status < Z_OK)
1270 return ULHR_BAD;
1273 * Check if entire header is unpacked in the first iteration.
1275 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1276 return ULHR_OK;
1279 * We have a header longer than MAX_HEADER_LEN. The "header"
1280 * here is only non-NULL when we run "cat-file
1281 * --allow-unknown-type".
1283 if (!header)
1284 return ULHR_TOO_LONG;
1287 * buffer[0..bufsiz] was not large enough. Copy the partial
1288 * result out to header, and then append the result of further
1289 * reading the stream.
1291 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1292 stream->next_out = buffer;
1293 stream->avail_out = bufsiz;
1295 do {
1296 obj_read_unlock();
1297 status = git_inflate(stream, 0);
1298 obj_read_lock();
1299 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1300 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1301 return 0;
1302 stream->next_out = buffer;
1303 stream->avail_out = bufsiz;
1304 } while (status != Z_STREAM_END);
1305 return ULHR_TOO_LONG;
1308 static void *unpack_loose_rest(git_zstream *stream,
1309 void *buffer, unsigned long size,
1310 const struct object_id *oid)
1312 int bytes = strlen(buffer) + 1;
1313 unsigned char *buf = xmallocz(size);
1314 unsigned long n;
1315 int status = Z_OK;
1317 n = stream->total_out - bytes;
1318 if (n > size)
1319 n = size;
1320 memcpy(buf, (char *) buffer + bytes, n);
1321 bytes = n;
1322 if (bytes <= size) {
1324 * The above condition must be (bytes <= size), not
1325 * (bytes < size). In other words, even though we
1326 * expect no more output and set avail_out to zero,
1327 * the input zlib stream may have bytes that express
1328 * "this concludes the stream", and we *do* want to
1329 * eat that input.
1331 * Otherwise we would not be able to test that we
1332 * consumed all the input to reach the expected size;
1333 * we also want to check that zlib tells us that all
1334 * went well with status == Z_STREAM_END at the end.
1336 stream->next_out = buf + bytes;
1337 stream->avail_out = size - bytes;
1338 while (status == Z_OK) {
1339 obj_read_unlock();
1340 status = git_inflate(stream, Z_FINISH);
1341 obj_read_lock();
1344 if (status == Z_STREAM_END && !stream->avail_in) {
1345 git_inflate_end(stream);
1346 return buf;
1349 if (status < 0)
1350 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1351 else if (stream->avail_in)
1352 error(_("garbage at end of loose object '%s'"),
1353 oid_to_hex(oid));
1354 free(buf);
1355 return NULL;
1359 * We used to just use "sscanf()", but that's actually way
1360 * too permissive for what we want to check. So do an anal
1361 * object header parse by hand.
1363 int parse_loose_header(const char *hdr, struct object_info *oi)
1365 const char *type_buf = hdr;
1366 size_t size;
1367 int type, type_len = 0;
1370 * The type can be of any size but is followed by
1371 * a space.
1373 for (;;) {
1374 char c = *hdr++;
1375 if (!c)
1376 return -1;
1377 if (c == ' ')
1378 break;
1379 type_len++;
1382 type = type_from_string_gently(type_buf, type_len, 1);
1383 if (oi->type_name)
1384 strbuf_add(oi->type_name, type_buf, type_len);
1385 if (oi->typep)
1386 *oi->typep = type;
1389 * The length must follow immediately, and be in canonical
1390 * decimal format (ie "010" is not valid).
1392 size = *hdr++ - '0';
1393 if (size > 9)
1394 return -1;
1395 if (size) {
1396 for (;;) {
1397 unsigned long c = *hdr - '0';
1398 if (c > 9)
1399 break;
1400 hdr++;
1401 size = st_add(st_mult(size, 10), c);
1405 if (oi->sizep)
1406 *oi->sizep = cast_size_t_to_ulong(size);
1409 * The length must be followed by a zero byte
1411 if (*hdr)
1412 return -1;
1415 * The format is valid, but the type may still be bogus. The
1416 * Caller needs to check its oi->typep.
1418 return 0;
1421 static int loose_object_info(struct repository *r,
1422 const struct object_id *oid,
1423 struct object_info *oi, int flags)
1425 int status = 0;
1426 int fd;
1427 unsigned long mapsize;
1428 const char *path;
1429 void *map;
1430 git_zstream stream;
1431 char hdr[MAX_HEADER_LEN];
1432 struct strbuf hdrbuf = STRBUF_INIT;
1433 unsigned long size_scratch;
1434 enum object_type type_scratch;
1435 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
1437 if (oi->delta_base_oid)
1438 oidclr(oi->delta_base_oid);
1441 * If we don't care about type or size, then we don't
1442 * need to look inside the object at all. Note that we
1443 * do not optimize out the stat call, even if the
1444 * caller doesn't care about the disk-size, since our
1445 * return value implicitly indicates whether the
1446 * object even exists.
1448 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1449 struct stat st;
1450 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1451 return quick_has_loose(r, oid) ? 0 : -1;
1452 if (stat_loose_object(r, oid, &st, &path) < 0)
1453 return -1;
1454 if (oi->disk_sizep)
1455 *oi->disk_sizep = st.st_size;
1456 return 0;
1459 fd = open_loose_object(r, oid, &path);
1460 if (fd < 0) {
1461 if (errno != ENOENT)
1462 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1463 return -1;
1465 map = map_fd(fd, path, &mapsize);
1466 if (!map)
1467 return -1;
1469 if (!oi->sizep)
1470 oi->sizep = &size_scratch;
1471 if (!oi->typep)
1472 oi->typep = &type_scratch;
1474 if (oi->disk_sizep)
1475 *oi->disk_sizep = mapsize;
1477 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1478 allow_unknown ? &hdrbuf : NULL)) {
1479 case ULHR_OK:
1480 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1481 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1482 else if (!allow_unknown && *oi->typep < 0)
1483 die(_("invalid object type"));
1485 if (!oi->contentp)
1486 break;
1487 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1488 if (*oi->contentp)
1489 goto cleanup;
1491 status = -1;
1492 break;
1493 case ULHR_BAD:
1494 status = error(_("unable to unpack %s header"),
1495 oid_to_hex(oid));
1496 break;
1497 case ULHR_TOO_LONG:
1498 status = error(_("header for %s too long, exceeds %d bytes"),
1499 oid_to_hex(oid), MAX_HEADER_LEN);
1500 break;
1503 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1504 die(_("loose object %s (stored in %s) is corrupt"),
1505 oid_to_hex(oid), path);
1507 git_inflate_end(&stream);
1508 cleanup:
1509 munmap(map, mapsize);
1510 if (oi->sizep == &size_scratch)
1511 oi->sizep = NULL;
1512 strbuf_release(&hdrbuf);
1513 if (oi->typep == &type_scratch)
1514 oi->typep = NULL;
1515 oi->whence = OI_LOOSE;
1516 return status;
1519 int obj_read_use_lock = 0;
1520 pthread_mutex_t obj_read_mutex;
1522 void enable_obj_read_lock(void)
1524 if (obj_read_use_lock)
1525 return;
1527 obj_read_use_lock = 1;
1528 init_recursive_mutex(&obj_read_mutex);
1531 void disable_obj_read_lock(void)
1533 if (!obj_read_use_lock)
1534 return;
1536 obj_read_use_lock = 0;
1537 pthread_mutex_destroy(&obj_read_mutex);
1540 int fetch_if_missing = 1;
1542 static int do_oid_object_info_extended(struct repository *r,
1543 const struct object_id *oid,
1544 struct object_info *oi, unsigned flags)
1546 static struct object_info blank_oi = OBJECT_INFO_INIT;
1547 struct cached_object *co;
1548 struct pack_entry e;
1549 int rtype;
1550 const struct object_id *real = oid;
1551 int already_retried = 0;
1554 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1555 real = lookup_replace_object(r, oid);
1557 if (is_null_oid(real))
1558 return -1;
1560 if (!oi)
1561 oi = &blank_oi;
1563 co = find_cached_object(real);
1564 if (co) {
1565 if (oi->typep)
1566 *(oi->typep) = co->type;
1567 if (oi->sizep)
1568 *(oi->sizep) = co->size;
1569 if (oi->disk_sizep)
1570 *(oi->disk_sizep) = 0;
1571 if (oi->delta_base_oid)
1572 oidclr(oi->delta_base_oid);
1573 if (oi->type_name)
1574 strbuf_addstr(oi->type_name, type_name(co->type));
1575 if (oi->contentp)
1576 *oi->contentp = xmemdupz(co->buf, co->size);
1577 oi->whence = OI_CACHED;
1578 return 0;
1581 while (1) {
1582 if (find_pack_entry(r, real, &e))
1583 break;
1585 /* Most likely it's a loose object. */
1586 if (!loose_object_info(r, real, oi, flags))
1587 return 0;
1589 /* Not a loose object; someone else may have just packed it. */
1590 if (!(flags & OBJECT_INFO_QUICK)) {
1591 reprepare_packed_git(r);
1592 if (find_pack_entry(r, real, &e))
1593 break;
1597 * If r is the_repository, this might be an attempt at
1598 * accessing a submodule object as if it were in the_repository
1599 * (having called add_submodule_odb() on that submodule's ODB).
1600 * If any such ODBs exist, register them and try again.
1602 if (r == the_repository &&
1603 register_all_submodule_odb_as_alternates())
1604 /* We added some alternates; retry */
1605 continue;
1607 /* Check if it is a missing object */
1608 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1609 !already_retried &&
1610 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1611 promisor_remote_get_direct(r, real, 1);
1612 already_retried = 1;
1613 continue;
1616 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1617 const struct packed_git *p;
1618 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1619 die(_("replacement %s not found for %s"),
1620 oid_to_hex(real), oid_to_hex(oid));
1621 if ((p = has_packed_and_bad(r, real)))
1622 die(_("packed object %s (stored in %s) is corrupt"),
1623 oid_to_hex(real), p->pack_name);
1625 return -1;
1628 if (oi == &blank_oi)
1630 * We know that the caller doesn't actually need the
1631 * information below, so return early.
1633 return 0;
1634 rtype = packed_object_info(r, e.p, e.offset, oi);
1635 if (rtype < 0) {
1636 mark_bad_packed_object(e.p, real);
1637 return do_oid_object_info_extended(r, real, oi, 0);
1638 } else if (oi->whence == OI_PACKED) {
1639 oi->u.packed.offset = e.offset;
1640 oi->u.packed.pack = e.p;
1641 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1642 rtype == OBJ_OFS_DELTA);
1645 return 0;
1648 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1649 struct object_info *oi, unsigned flags)
1651 int ret;
1652 obj_read_lock();
1653 ret = do_oid_object_info_extended(r, oid, oi, flags);
1654 obj_read_unlock();
1655 return ret;
1659 /* returns enum object_type or negative */
1660 int oid_object_info(struct repository *r,
1661 const struct object_id *oid,
1662 unsigned long *sizep)
1664 enum object_type type;
1665 struct object_info oi = OBJECT_INFO_INIT;
1667 oi.typep = &type;
1668 oi.sizep = sizep;
1669 if (oid_object_info_extended(r, oid, &oi,
1670 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1671 return -1;
1672 return type;
1675 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1676 struct object_id *oid)
1678 struct cached_object *co;
1680 hash_object_file(the_hash_algo, buf, len, type, oid);
1681 if (has_object_file_with_flags(oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1682 find_cached_object(oid))
1683 return 0;
1684 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1685 co = &cached_objects[cached_object_nr++];
1686 co->size = len;
1687 co->type = type;
1688 co->buf = xmalloc(len);
1689 memcpy(co->buf, buf, len);
1690 oidcpy(&co->oid, oid);
1691 return 0;
1695 * This function dies on corrupt objects; the callers who want to
1696 * deal with them should arrange to call oid_object_info_extended() and give
1697 * error messages themselves.
1699 void *repo_read_object_file(struct repository *r,
1700 const struct object_id *oid,
1701 enum object_type *type,
1702 unsigned long *size)
1704 struct object_info oi = OBJECT_INFO_INIT;
1705 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
1706 void *data;
1708 oi.typep = type;
1709 oi.sizep = size;
1710 oi.contentp = &data;
1711 if (oid_object_info_extended(r, oid, &oi, flags))
1712 return NULL;
1714 return data;
1717 void *read_object_with_reference(struct repository *r,
1718 const struct object_id *oid,
1719 enum object_type required_type,
1720 unsigned long *size,
1721 struct object_id *actual_oid_return)
1723 enum object_type type;
1724 void *buffer;
1725 unsigned long isize;
1726 struct object_id actual_oid;
1728 oidcpy(&actual_oid, oid);
1729 while (1) {
1730 int ref_length = -1;
1731 const char *ref_type = NULL;
1733 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1734 if (!buffer)
1735 return NULL;
1736 if (type == required_type) {
1737 *size = isize;
1738 if (actual_oid_return)
1739 oidcpy(actual_oid_return, &actual_oid);
1740 return buffer;
1742 /* Handle references */
1743 else if (type == OBJ_COMMIT)
1744 ref_type = "tree ";
1745 else if (type == OBJ_TAG)
1746 ref_type = "object ";
1747 else {
1748 free(buffer);
1749 return NULL;
1751 ref_length = strlen(ref_type);
1753 if (ref_length + the_hash_algo->hexsz > isize ||
1754 memcmp(buffer, ref_type, ref_length) ||
1755 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1756 free(buffer);
1757 return NULL;
1759 free(buffer);
1760 /* Now we have the ID of the referred-to object in
1761 * actual_oid. Check again. */
1765 static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1766 const void *buf, unsigned long len,
1767 struct object_id *oid,
1768 char *hdr, int *hdrlen)
1770 algo->init_fn(c);
1771 algo->update_fn(c, hdr, *hdrlen);
1772 algo->update_fn(c, buf, len);
1773 algo->final_oid_fn(oid, c);
1776 static void write_object_file_prepare(const struct git_hash_algo *algo,
1777 const void *buf, unsigned long len,
1778 enum object_type type, struct object_id *oid,
1779 char *hdr, int *hdrlen)
1781 git_hash_ctx c;
1783 /* Generate the header */
1784 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
1786 /* Sha1.. */
1787 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1790 static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1791 const void *buf, unsigned long len,
1792 const char *type, struct object_id *oid,
1793 char *hdr, int *hdrlen)
1795 git_hash_ctx c;
1797 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1798 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1802 * Move the just written object into its final resting place.
1804 int finalize_object_file(const char *tmpfile, const char *filename)
1806 int ret = 0;
1808 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1809 goto try_rename;
1810 else if (link(tmpfile, filename))
1811 ret = errno;
1814 * Coda hack - coda doesn't like cross-directory links,
1815 * so we fall back to a rename, which will mean that it
1816 * won't be able to check collisions, but that's not a
1817 * big deal.
1819 * The same holds for FAT formatted media.
1821 * When this succeeds, we just return. We have nothing
1822 * left to unlink.
1824 if (ret && ret != EEXIST) {
1825 try_rename:
1826 if (!rename(tmpfile, filename))
1827 goto out;
1828 ret = errno;
1830 unlink_or_warn(tmpfile);
1831 if (ret) {
1832 if (ret != EEXIST) {
1833 return error_errno(_("unable to write file %s"), filename);
1835 /* FIXME!!! Collision check here ? */
1838 out:
1839 if (adjust_shared_perm(filename))
1840 return error(_("unable to set permission to '%s'"), filename);
1841 return 0;
1844 static void hash_object_file_literally(const struct git_hash_algo *algo,
1845 const void *buf, unsigned long len,
1846 const char *type, struct object_id *oid)
1848 char hdr[MAX_HEADER_LEN];
1849 int hdrlen = sizeof(hdr);
1851 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
1854 void hash_object_file(const struct git_hash_algo *algo, const void *buf,
1855 unsigned long len, enum object_type type,
1856 struct object_id *oid)
1858 hash_object_file_literally(algo, buf, len, type_name(type), oid);
1861 /* Finalize a file on disk, and close it. */
1862 static void close_loose_object(int fd, const char *filename)
1864 if (the_repository->objects->odb->will_destroy)
1865 goto out;
1867 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
1868 fsync_loose_object_bulk_checkin(fd, filename);
1869 else if (fsync_object_files > 0)
1870 fsync_or_die(fd, filename);
1871 else
1872 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
1873 filename);
1875 out:
1876 if (close(fd) != 0)
1877 die_errno(_("error when closing loose object file"));
1880 /* Size of directory component, including the ending '/' */
1881 static inline int directory_size(const char *filename)
1883 const char *s = strrchr(filename, '/');
1884 if (!s)
1885 return 0;
1886 return s - filename + 1;
1890 * This creates a temporary file in the same directory as the final
1891 * 'filename'
1893 * We want to avoid cross-directory filename renames, because those
1894 * can have problems on various filesystems (FAT, NFS, Coda).
1896 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1898 int fd, dirlen = directory_size(filename);
1900 strbuf_reset(tmp);
1901 strbuf_add(tmp, filename, dirlen);
1902 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1903 fd = git_mkstemp_mode(tmp->buf, 0444);
1904 if (fd < 0 && dirlen && errno == ENOENT) {
1906 * Make sure the directory exists; note that the contents
1907 * of the buffer are undefined after mkstemp returns an
1908 * error, so we have to rewrite the whole buffer from
1909 * scratch.
1911 strbuf_reset(tmp);
1912 strbuf_add(tmp, filename, dirlen - 1);
1913 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1914 return -1;
1915 if (adjust_shared_perm(tmp->buf))
1916 return -1;
1918 /* Try again */
1919 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1920 fd = git_mkstemp_mode(tmp->buf, 0444);
1922 return fd;
1926 * Common steps for loose object writers to start writing loose
1927 * objects:
1929 * - Create tmpfile for the loose object.
1930 * - Setup zlib stream for compression.
1931 * - Start to feed header to zlib stream.
1933 * Returns a "fd", which should later be provided to
1934 * end_loose_object_common().
1936 static int start_loose_object_common(struct strbuf *tmp_file,
1937 const char *filename, unsigned flags,
1938 git_zstream *stream,
1939 unsigned char *buf, size_t buflen,
1940 git_hash_ctx *c,
1941 char *hdr, int hdrlen)
1943 int fd;
1945 fd = create_tmpfile(tmp_file, filename);
1946 if (fd < 0) {
1947 if (flags & HASH_SILENT)
1948 return -1;
1949 else if (errno == EACCES)
1950 return error(_("insufficient permission for adding "
1951 "an object to repository database %s"),
1952 get_object_directory());
1953 else
1954 return error_errno(
1955 _("unable to create temporary file"));
1958 /* Setup zlib stream for compression */
1959 git_deflate_init(stream, zlib_compression_level);
1960 stream->next_out = buf;
1961 stream->avail_out = buflen;
1962 the_hash_algo->init_fn(c);
1964 /* Start to feed header to zlib stream */
1965 stream->next_in = (unsigned char *)hdr;
1966 stream->avail_in = hdrlen;
1967 while (git_deflate(stream, 0) == Z_OK)
1968 ; /* nothing */
1969 the_hash_algo->update_fn(c, hdr, hdrlen);
1971 return fd;
1975 * Common steps for the inner git_deflate() loop for writing loose
1976 * objects. Returns what git_deflate() returns.
1978 static int write_loose_object_common(git_hash_ctx *c,
1979 git_zstream *stream, const int flush,
1980 unsigned char *in0, const int fd,
1981 unsigned char *compressed,
1982 const size_t compressed_len)
1984 int ret;
1986 ret = git_deflate(stream, flush ? Z_FINISH : 0);
1987 the_hash_algo->update_fn(c, in0, stream->next_in - in0);
1988 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
1989 die_errno(_("unable to write loose object file"));
1990 stream->next_out = compressed;
1991 stream->avail_out = compressed_len;
1993 return ret;
1997 * Common steps for loose object writers to end writing loose objects:
1999 * - End the compression of zlib stream.
2000 * - Get the calculated oid to "oid".
2002 static int end_loose_object_common(git_hash_ctx *c, git_zstream *stream,
2003 struct object_id *oid)
2005 int ret;
2007 ret = git_deflate_end_gently(stream);
2008 if (ret != Z_OK)
2009 return ret;
2010 the_hash_algo->final_oid_fn(oid, c);
2012 return Z_OK;
2015 static int write_loose_object(const struct object_id *oid, char *hdr,
2016 int hdrlen, const void *buf, unsigned long len,
2017 time_t mtime, unsigned flags)
2019 int fd, ret;
2020 unsigned char compressed[4096];
2021 git_zstream stream;
2022 git_hash_ctx c;
2023 struct object_id parano_oid;
2024 static struct strbuf tmp_file = STRBUF_INIT;
2025 static struct strbuf filename = STRBUF_INIT;
2027 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2028 prepare_loose_object_bulk_checkin();
2030 loose_object_path(the_repository, &filename, oid);
2032 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2033 &stream, compressed, sizeof(compressed),
2034 &c, hdr, hdrlen);
2035 if (fd < 0)
2036 return -1;
2038 /* Then the data itself.. */
2039 stream.next_in = (void *)buf;
2040 stream.avail_in = len;
2041 do {
2042 unsigned char *in0 = stream.next_in;
2044 ret = write_loose_object_common(&c, &stream, 1, in0, fd,
2045 compressed, sizeof(compressed));
2046 } while (ret == Z_OK);
2048 if (ret != Z_STREAM_END)
2049 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
2050 ret);
2051 ret = end_loose_object_common(&c, &stream, &parano_oid);
2052 if (ret != Z_OK)
2053 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
2054 ret);
2055 if (!oideq(oid, &parano_oid))
2056 die(_("confused by unstable object source data for %s"),
2057 oid_to_hex(oid));
2059 close_loose_object(fd, tmp_file.buf);
2061 if (mtime) {
2062 struct utimbuf utb;
2063 utb.actime = mtime;
2064 utb.modtime = mtime;
2065 if (utime(tmp_file.buf, &utb) < 0 &&
2066 !(flags & HASH_SILENT))
2067 warning_errno(_("failed utime() on %s"), tmp_file.buf);
2070 return finalize_object_file(tmp_file.buf, filename.buf);
2073 static int freshen_loose_object(const struct object_id *oid)
2075 return check_and_freshen(oid, 1);
2078 static int freshen_packed_object(const struct object_id *oid)
2080 struct pack_entry e;
2081 if (!find_pack_entry(the_repository, oid, &e))
2082 return 0;
2083 if (e.p->is_cruft)
2084 return 0;
2085 if (e.p->freshened)
2086 return 1;
2087 if (!freshen_file(e.p->pack_name))
2088 return 0;
2089 e.p->freshened = 1;
2090 return 1;
2093 int stream_loose_object(struct input_stream *in_stream, size_t len,
2094 struct object_id *oid)
2096 int fd, ret, err = 0, flush = 0;
2097 unsigned char compressed[4096];
2098 git_zstream stream;
2099 git_hash_ctx c;
2100 struct strbuf tmp_file = STRBUF_INIT;
2101 struct strbuf filename = STRBUF_INIT;
2102 int dirlen;
2103 char hdr[MAX_HEADER_LEN];
2104 int hdrlen;
2106 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2107 prepare_loose_object_bulk_checkin();
2109 /* Since oid is not determined, save tmp file to odb path. */
2110 strbuf_addf(&filename, "%s/", get_object_directory());
2111 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2114 * Common steps for write_loose_object and stream_loose_object to
2115 * start writing loose objects:
2117 * - Create tmpfile for the loose object.
2118 * - Setup zlib stream for compression.
2119 * - Start to feed header to zlib stream.
2121 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2122 &stream, compressed, sizeof(compressed),
2123 &c, hdr, hdrlen);
2124 if (fd < 0) {
2125 err = -1;
2126 goto cleanup;
2129 /* Then the data itself.. */
2130 do {
2131 unsigned char *in0 = stream.next_in;
2133 if (!stream.avail_in && !in_stream->is_finished) {
2134 const void *in = in_stream->read(in_stream, &stream.avail_in);
2135 stream.next_in = (void *)in;
2136 in0 = (unsigned char *)in;
2137 /* All data has been read. */
2138 if (in_stream->is_finished)
2139 flush = 1;
2141 ret = write_loose_object_common(&c, &stream, flush, in0, fd,
2142 compressed, sizeof(compressed));
2144 * Unlike write_loose_object(), we do not have the entire
2145 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2146 * then we'll replenish them in the next input_stream->read()
2147 * call when we loop.
2149 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2151 if (stream.total_in != len + hdrlen)
2152 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2153 (uintmax_t)len + hdrlen);
2156 * Common steps for write_loose_object and stream_loose_object to
2157 * end writing loose oject:
2159 * - End the compression of zlib stream.
2160 * - Get the calculated oid.
2162 if (ret != Z_STREAM_END)
2163 die(_("unable to stream deflate new object (%d)"), ret);
2164 ret = end_loose_object_common(&c, &stream, oid);
2165 if (ret != Z_OK)
2166 die(_("deflateEnd on stream object failed (%d)"), ret);
2167 close_loose_object(fd, tmp_file.buf);
2169 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2170 unlink_or_warn(tmp_file.buf);
2171 goto cleanup;
2174 loose_object_path(the_repository, &filename, oid);
2176 /* We finally know the object path, and create the missing dir. */
2177 dirlen = directory_size(filename.buf);
2178 if (dirlen) {
2179 struct strbuf dir = STRBUF_INIT;
2180 strbuf_add(&dir, filename.buf, dirlen);
2182 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2183 err = error_errno(_("unable to create directory %s"), dir.buf);
2184 strbuf_release(&dir);
2185 goto cleanup;
2187 strbuf_release(&dir);
2190 err = finalize_object_file(tmp_file.buf, filename.buf);
2191 cleanup:
2192 strbuf_release(&tmp_file);
2193 strbuf_release(&filename);
2194 return err;
2197 int write_object_file_flags(const void *buf, unsigned long len,
2198 enum object_type type, struct object_id *oid,
2199 unsigned flags)
2201 char hdr[MAX_HEADER_LEN];
2202 int hdrlen = sizeof(hdr);
2204 /* Normally if we have it in the pack then we do not bother writing
2205 * it out into .git/objects/??/?{38} file.
2207 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
2208 &hdrlen);
2209 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2210 return 0;
2211 return write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags);
2214 int write_object_file_literally(const void *buf, unsigned long len,
2215 const char *type, struct object_id *oid,
2216 unsigned flags)
2218 char *header;
2219 int hdrlen, status = 0;
2221 /* type string, SP, %lu of the length plus NUL must fit this */
2222 hdrlen = strlen(type) + MAX_HEADER_LEN;
2223 header = xmalloc(hdrlen);
2224 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2225 oid, header, &hdrlen);
2227 if (!(flags & HASH_WRITE_OBJECT))
2228 goto cleanup;
2229 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2230 goto cleanup;
2231 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
2233 cleanup:
2234 free(header);
2235 return status;
2238 int force_object_loose(const struct object_id *oid, time_t mtime)
2240 void *buf;
2241 unsigned long len;
2242 struct object_info oi = OBJECT_INFO_INIT;
2243 enum object_type type;
2244 char hdr[MAX_HEADER_LEN];
2245 int hdrlen;
2246 int ret;
2248 if (has_loose_object(oid))
2249 return 0;
2250 oi.typep = &type;
2251 oi.sizep = &len;
2252 oi.contentp = &buf;
2253 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2254 return error(_("cannot read object for %s"), oid_to_hex(oid));
2255 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
2256 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
2257 free(buf);
2259 return ret;
2262 int has_object(struct repository *r, const struct object_id *oid,
2263 unsigned flags)
2265 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2266 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2267 (quick ? OBJECT_INFO_QUICK : 0);
2269 if (!startup_info->have_repository)
2270 return 0;
2271 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2274 int repo_has_object_file_with_flags(struct repository *r,
2275 const struct object_id *oid, int flags)
2277 if (!startup_info->have_repository)
2278 return 0;
2279 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2282 int repo_has_object_file(struct repository *r,
2283 const struct object_id *oid)
2285 return repo_has_object_file_with_flags(r, oid, 0);
2289 * We can't use the normal fsck_error_function() for index_mem(),
2290 * because we don't yet have a valid oid for it to report. Instead,
2291 * report the minimal fsck error here, and rely on the caller to
2292 * give more context.
2294 static int hash_format_check_report(struct fsck_options *opts,
2295 const struct object_id *oid,
2296 enum object_type object_type,
2297 enum fsck_msg_type msg_type,
2298 enum fsck_msg_id msg_id,
2299 const char *message)
2301 error(_("object fails fsck: %s"), message);
2302 return 1;
2305 static int index_mem(struct index_state *istate,
2306 struct object_id *oid, void *buf, size_t size,
2307 enum object_type type,
2308 const char *path, unsigned flags)
2310 int ret = 0;
2311 int re_allocated = 0;
2312 int write_object = flags & HASH_WRITE_OBJECT;
2314 if (!type)
2315 type = OBJ_BLOB;
2318 * Convert blobs to git internal format
2320 if ((type == OBJ_BLOB) && path) {
2321 struct strbuf nbuf = STRBUF_INIT;
2322 if (convert_to_git(istate, path, buf, size, &nbuf,
2323 get_conv_flags(flags))) {
2324 buf = strbuf_detach(&nbuf, &size);
2325 re_allocated = 1;
2328 if (flags & HASH_FORMAT_CHECK) {
2329 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2331 opts.strict = 1;
2332 opts.error_func = hash_format_check_report;
2333 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2334 die(_("refusing to create malformed object"));
2335 fsck_finish(&opts);
2338 if (write_object)
2339 ret = write_object_file(buf, size, type, oid);
2340 else
2341 hash_object_file(the_hash_algo, buf, size, type, oid);
2342 if (re_allocated)
2343 free(buf);
2344 return ret;
2347 static int index_stream_convert_blob(struct index_state *istate,
2348 struct object_id *oid,
2349 int fd,
2350 const char *path,
2351 unsigned flags)
2353 int ret = 0;
2354 const int write_object = flags & HASH_WRITE_OBJECT;
2355 struct strbuf sbuf = STRBUF_INIT;
2357 assert(path);
2358 assert(would_convert_to_git_filter_fd(istate, path));
2360 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2361 get_conv_flags(flags));
2363 if (write_object)
2364 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
2365 oid);
2366 else
2367 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2368 oid);
2369 strbuf_release(&sbuf);
2370 return ret;
2373 static int index_pipe(struct index_state *istate, struct object_id *oid,
2374 int fd, enum object_type type,
2375 const char *path, unsigned flags)
2377 struct strbuf sbuf = STRBUF_INIT;
2378 int ret;
2380 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2381 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2382 else
2383 ret = -1;
2384 strbuf_release(&sbuf);
2385 return ret;
2388 #define SMALL_FILE_SIZE (32*1024)
2390 static int index_core(struct index_state *istate,
2391 struct object_id *oid, int fd, size_t size,
2392 enum object_type type, const char *path,
2393 unsigned flags)
2395 int ret;
2397 if (!size) {
2398 ret = index_mem(istate, oid, "", size, type, path, flags);
2399 } else if (size <= SMALL_FILE_SIZE) {
2400 char *buf = xmalloc(size);
2401 ssize_t read_result = read_in_full(fd, buf, size);
2402 if (read_result < 0)
2403 ret = error_errno(_("read error while indexing %s"),
2404 path ? path : "<unknown>");
2405 else if (read_result != size)
2406 ret = error(_("short read while indexing %s"),
2407 path ? path : "<unknown>");
2408 else
2409 ret = index_mem(istate, oid, buf, size, type, path, flags);
2410 free(buf);
2411 } else {
2412 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2413 ret = index_mem(istate, oid, buf, size, type, path, flags);
2414 munmap(buf, size);
2416 return ret;
2420 * This creates one packfile per large blob unless bulk-checkin
2421 * machinery is "plugged".
2423 * This also bypasses the usual "convert-to-git" dance, and that is on
2424 * purpose. We could write a streaming version of the converting
2425 * functions and insert that before feeding the data to fast-import
2426 * (or equivalent in-core API described above). However, that is
2427 * somewhat complicated, as we do not know the size of the filter
2428 * result, which we need to know beforehand when writing a git object.
2429 * Since the primary motivation for trying to stream from the working
2430 * tree file and to avoid mmaping it in core is to deal with large
2431 * binary blobs, they generally do not want to get any conversion, and
2432 * callers should avoid this code path when filters are requested.
2434 static int index_stream(struct object_id *oid, int fd, size_t size,
2435 enum object_type type, const char *path,
2436 unsigned flags)
2438 return index_bulk_checkin(oid, fd, size, type, path, flags);
2441 int index_fd(struct index_state *istate, struct object_id *oid,
2442 int fd, struct stat *st,
2443 enum object_type type, const char *path, unsigned flags)
2445 int ret;
2448 * Call xsize_t() only when needed to avoid potentially unnecessary
2449 * die() for large files.
2451 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2452 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2453 else if (!S_ISREG(st->st_mode))
2454 ret = index_pipe(istate, oid, fd, type, path, flags);
2455 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2456 (path && would_convert_to_git(istate, path)))
2457 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2458 type, path, flags);
2459 else
2460 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2461 flags);
2462 close(fd);
2463 return ret;
2466 int index_path(struct index_state *istate, struct object_id *oid,
2467 const char *path, struct stat *st, unsigned flags)
2469 int fd;
2470 struct strbuf sb = STRBUF_INIT;
2471 int rc = 0;
2473 switch (st->st_mode & S_IFMT) {
2474 case S_IFREG:
2475 fd = open(path, O_RDONLY);
2476 if (fd < 0)
2477 return error_errno("open(\"%s\")", path);
2478 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2479 return error(_("%s: failed to insert into database"),
2480 path);
2481 break;
2482 case S_IFLNK:
2483 if (strbuf_readlink(&sb, path, st->st_size))
2484 return error_errno("readlink(\"%s\")", path);
2485 if (!(flags & HASH_WRITE_OBJECT))
2486 hash_object_file(the_hash_algo, sb.buf, sb.len,
2487 OBJ_BLOB, oid);
2488 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
2489 rc = error(_("%s: failed to insert into database"), path);
2490 strbuf_release(&sb);
2491 break;
2492 case S_IFDIR:
2493 return resolve_gitlink_ref(path, "HEAD", oid);
2494 default:
2495 return error(_("%s: unsupported file type"), path);
2497 return rc;
2500 int read_pack_header(int fd, struct pack_header *header)
2502 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2503 /* "eof before pack header was fully read" */
2504 return PH_ERROR_EOF;
2506 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2507 /* "protocol error (pack signature mismatch detected)" */
2508 return PH_ERROR_PACK_SIGNATURE;
2509 if (!pack_version_ok(header->hdr_version))
2510 /* "protocol error (pack version unsupported)" */
2511 return PH_ERROR_PROTOCOL;
2512 return 0;
2515 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2517 enum object_type type = oid_object_info(the_repository, oid, NULL);
2518 if (type < 0)
2519 die(_("%s is not a valid object"), oid_to_hex(oid));
2520 if (type != expect)
2521 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2522 type_name(expect));
2525 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2526 struct strbuf *path,
2527 each_loose_object_fn obj_cb,
2528 each_loose_cruft_fn cruft_cb,
2529 each_loose_subdir_fn subdir_cb,
2530 void *data)
2532 size_t origlen, baselen;
2533 DIR *dir;
2534 struct dirent *de;
2535 int r = 0;
2536 struct object_id oid;
2538 if (subdir_nr > 0xff)
2539 BUG("invalid loose object subdirectory: %x", subdir_nr);
2541 origlen = path->len;
2542 strbuf_complete(path, '/');
2543 strbuf_addf(path, "%02x", subdir_nr);
2545 dir = opendir(path->buf);
2546 if (!dir) {
2547 if (errno != ENOENT)
2548 r = error_errno(_("unable to open %s"), path->buf);
2549 strbuf_setlen(path, origlen);
2550 return r;
2553 oid.hash[0] = subdir_nr;
2554 strbuf_addch(path, '/');
2555 baselen = path->len;
2557 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2558 size_t namelen;
2560 namelen = strlen(de->d_name);
2561 strbuf_setlen(path, baselen);
2562 strbuf_add(path, de->d_name, namelen);
2563 if (namelen == the_hash_algo->hexsz - 2 &&
2564 !hex_to_bytes(oid.hash + 1, de->d_name,
2565 the_hash_algo->rawsz - 1)) {
2566 oid_set_algo(&oid, the_hash_algo);
2567 if (obj_cb) {
2568 r = obj_cb(&oid, path->buf, data);
2569 if (r)
2570 break;
2572 continue;
2575 if (cruft_cb) {
2576 r = cruft_cb(de->d_name, path->buf, data);
2577 if (r)
2578 break;
2581 closedir(dir);
2583 strbuf_setlen(path, baselen - 1);
2584 if (!r && subdir_cb)
2585 r = subdir_cb(subdir_nr, path->buf, data);
2587 strbuf_setlen(path, origlen);
2589 return r;
2592 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2593 each_loose_object_fn obj_cb,
2594 each_loose_cruft_fn cruft_cb,
2595 each_loose_subdir_fn subdir_cb,
2596 void *data)
2598 int r = 0;
2599 int i;
2601 for (i = 0; i < 256; i++) {
2602 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2603 subdir_cb, data);
2604 if (r)
2605 break;
2608 return r;
2611 int for_each_loose_file_in_objdir(const char *path,
2612 each_loose_object_fn obj_cb,
2613 each_loose_cruft_fn cruft_cb,
2614 each_loose_subdir_fn subdir_cb,
2615 void *data)
2617 struct strbuf buf = STRBUF_INIT;
2618 int r;
2620 strbuf_addstr(&buf, path);
2621 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2622 subdir_cb, data);
2623 strbuf_release(&buf);
2625 return r;
2628 int for_each_loose_object(each_loose_object_fn cb, void *data,
2629 enum for_each_object_flags flags)
2631 struct object_directory *odb;
2633 prepare_alt_odb(the_repository);
2634 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2635 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2636 NULL, data);
2637 if (r)
2638 return r;
2640 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2641 break;
2644 return 0;
2647 static int append_loose_object(const struct object_id *oid, const char *path,
2648 void *data)
2650 oidtree_insert(data, oid);
2651 return 0;
2654 struct oidtree *odb_loose_cache(struct object_directory *odb,
2655 const struct object_id *oid)
2657 int subdir_nr = oid->hash[0];
2658 struct strbuf buf = STRBUF_INIT;
2659 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2660 size_t word_index = subdir_nr / word_bits;
2661 size_t mask = (size_t)1u << (subdir_nr % word_bits);
2662 uint32_t *bitmap;
2664 if (subdir_nr < 0 ||
2665 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2666 BUG("subdir_nr out of range");
2668 bitmap = &odb->loose_objects_subdir_seen[word_index];
2669 if (*bitmap & mask)
2670 return odb->loose_objects_cache;
2671 if (!odb->loose_objects_cache) {
2672 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2673 oidtree_init(odb->loose_objects_cache);
2675 strbuf_addstr(&buf, odb->path);
2676 for_each_file_in_obj_subdir(subdir_nr, &buf,
2677 append_loose_object,
2678 NULL, NULL,
2679 odb->loose_objects_cache);
2680 *bitmap |= mask;
2681 strbuf_release(&buf);
2682 return odb->loose_objects_cache;
2685 void odb_clear_loose_cache(struct object_directory *odb)
2687 oidtree_clear(odb->loose_objects_cache);
2688 FREE_AND_NULL(odb->loose_objects_cache);
2689 memset(&odb->loose_objects_subdir_seen, 0,
2690 sizeof(odb->loose_objects_subdir_seen));
2693 static int check_stream_oid(git_zstream *stream,
2694 const char *hdr,
2695 unsigned long size,
2696 const char *path,
2697 const struct object_id *expected_oid)
2699 git_hash_ctx c;
2700 struct object_id real_oid;
2701 unsigned char buf[4096];
2702 unsigned long total_read;
2703 int status = Z_OK;
2705 the_hash_algo->init_fn(&c);
2706 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2709 * We already read some bytes into hdr, but the ones up to the NUL
2710 * do not count against the object's content size.
2712 total_read = stream->total_out - strlen(hdr) - 1;
2715 * This size comparison must be "<=" to read the final zlib packets;
2716 * see the comment in unpack_loose_rest for details.
2718 while (total_read <= size &&
2719 (status == Z_OK ||
2720 (status == Z_BUF_ERROR && !stream->avail_out))) {
2721 stream->next_out = buf;
2722 stream->avail_out = sizeof(buf);
2723 if (size - total_read < stream->avail_out)
2724 stream->avail_out = size - total_read;
2725 status = git_inflate(stream, Z_FINISH);
2726 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2727 total_read += stream->next_out - buf;
2729 git_inflate_end(stream);
2731 if (status != Z_STREAM_END) {
2732 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2733 return -1;
2735 if (stream->avail_in) {
2736 error(_("garbage at end of loose object '%s'"),
2737 oid_to_hex(expected_oid));
2738 return -1;
2741 the_hash_algo->final_oid_fn(&real_oid, &c);
2742 if (!oideq(expected_oid, &real_oid)) {
2743 error(_("hash mismatch for %s (expected %s)"), path,
2744 oid_to_hex(expected_oid));
2745 return -1;
2748 return 0;
2751 int read_loose_object(const char *path,
2752 const struct object_id *expected_oid,
2753 struct object_id *real_oid,
2754 void **contents,
2755 struct object_info *oi)
2757 int ret = -1;
2758 int fd;
2759 void *map = NULL;
2760 unsigned long mapsize;
2761 git_zstream stream;
2762 char hdr[MAX_HEADER_LEN];
2763 unsigned long *size = oi->sizep;
2765 fd = git_open(path);
2766 if (fd >= 0)
2767 map = map_fd(fd, path, &mapsize);
2768 if (!map) {
2769 error_errno(_("unable to mmap %s"), path);
2770 goto out;
2773 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
2774 NULL) != ULHR_OK) {
2775 error(_("unable to unpack header of %s"), path);
2776 goto out;
2779 if (parse_loose_header(hdr, oi) < 0) {
2780 error(_("unable to parse header of %s"), path);
2781 git_inflate_end(&stream);
2782 goto out;
2785 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
2786 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2787 goto out;
2788 } else {
2789 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2790 if (!*contents) {
2791 error(_("unable to unpack contents of %s"), path);
2792 git_inflate_end(&stream);
2793 goto out;
2795 hash_object_file_literally(the_repository->hash_algo,
2796 *contents, *size,
2797 oi->type_name->buf, real_oid);
2798 if (!oideq(expected_oid, real_oid))
2799 goto out;
2802 ret = 0; /* everything checks out */
2804 out:
2805 if (map)
2806 munmap(map, mapsize);
2807 return ret;