rebase --root: fix amending root commit messages
[git.git] / sha1-file.c
blob77ccaab928529d37aa971168c54e31358e12ef8e
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 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 "sha1-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "streaming.h"
27 #include "dir.h"
28 #include "list.h"
29 #include "mergesort.h"
30 #include "quote.h"
31 #include "packfile.h"
32 #include "fetch-object.h"
33 #include "object-store.h"
35 /* The maximum size for an object header. */
36 #define MAX_HEADER_LEN 32
38 const unsigned char null_sha1[GIT_MAX_RAWSZ];
39 const struct object_id null_oid;
40 const struct object_id empty_tree_oid = {
41 EMPTY_TREE_SHA1_BIN_LITERAL
43 const struct object_id empty_blob_oid = {
44 EMPTY_BLOB_SHA1_BIN_LITERAL
47 static void git_hash_sha1_init(git_hash_ctx *ctx)
49 git_SHA1_Init(&ctx->sha1);
52 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
54 git_SHA1_Update(&ctx->sha1, data, len);
57 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
59 git_SHA1_Final(hash, &ctx->sha1);
62 static void git_hash_unknown_init(git_hash_ctx *ctx)
64 die("trying to init unknown hash");
67 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
69 die("trying to update unknown hash");
72 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
74 die("trying to finalize unknown hash");
77 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
79 NULL,
80 0x00000000,
83 git_hash_unknown_init,
84 git_hash_unknown_update,
85 git_hash_unknown_final,
86 NULL,
87 NULL,
90 "sha-1",
91 /* "sha1", big-endian */
92 0x73686131,
93 GIT_SHA1_RAWSZ,
94 GIT_SHA1_HEXSZ,
95 git_hash_sha1_init,
96 git_hash_sha1_update,
97 git_hash_sha1_final,
98 &empty_tree_oid,
99 &empty_blob_oid,
104 * This is meant to hold a *small* number of objects that you would
105 * want read_sha1_file() to be able to return, but yet you do not want
106 * to write them into the object store (e.g. a browse-only
107 * application).
109 static struct cached_object {
110 unsigned char sha1[20];
111 enum object_type type;
112 void *buf;
113 unsigned long size;
114 } *cached_objects;
115 static int cached_object_nr, cached_object_alloc;
117 static struct cached_object empty_tree = {
118 EMPTY_TREE_SHA1_BIN_LITERAL,
119 OBJ_TREE,
124 static struct cached_object *find_cached_object(const unsigned char *sha1)
126 int i;
127 struct cached_object *co = cached_objects;
129 for (i = 0; i < cached_object_nr; i++, co++) {
130 if (!hashcmp(co->sha1, sha1))
131 return co;
133 if (!hashcmp(sha1, empty_tree.sha1))
134 return &empty_tree;
135 return NULL;
139 static int get_conv_flags(unsigned flags)
141 if (flags & HASH_RENORMALIZE)
142 return CONV_EOL_RENORMALIZE;
143 else if (flags & HASH_WRITE_OBJECT)
144 return global_conv_flags_eol;
145 else
146 return 0;
150 int mkdir_in_gitdir(const char *path)
152 if (mkdir(path, 0777)) {
153 int saved_errno = errno;
154 struct stat st;
155 struct strbuf sb = STRBUF_INIT;
157 if (errno != EEXIST)
158 return -1;
160 * Are we looking at a path in a symlinked worktree
161 * whose original repository does not yet have it?
162 * e.g. .git/rr-cache pointing at its original
163 * repository in which the user hasn't performed any
164 * conflict resolution yet?
166 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
167 strbuf_readlink(&sb, path, st.st_size) ||
168 !is_absolute_path(sb.buf) ||
169 mkdir(sb.buf, 0777)) {
170 strbuf_release(&sb);
171 errno = saved_errno;
172 return -1;
174 strbuf_release(&sb);
176 return adjust_shared_perm(path);
179 enum scld_error safe_create_leading_directories(char *path)
181 char *next_component = path + offset_1st_component(path);
182 enum scld_error ret = SCLD_OK;
184 while (ret == SCLD_OK && next_component) {
185 struct stat st;
186 char *slash = next_component, slash_character;
188 while (*slash && !is_dir_sep(*slash))
189 slash++;
191 if (!*slash)
192 break;
194 next_component = slash + 1;
195 while (is_dir_sep(*next_component))
196 next_component++;
197 if (!*next_component)
198 break;
200 slash_character = *slash;
201 *slash = '\0';
202 if (!stat(path, &st)) {
203 /* path exists */
204 if (!S_ISDIR(st.st_mode)) {
205 errno = ENOTDIR;
206 ret = SCLD_EXISTS;
208 } else if (mkdir(path, 0777)) {
209 if (errno == EEXIST &&
210 !stat(path, &st) && S_ISDIR(st.st_mode))
211 ; /* somebody created it since we checked */
212 else if (errno == ENOENT)
214 * Either mkdir() failed because
215 * somebody just pruned the containing
216 * directory, or stat() failed because
217 * the file that was in our way was
218 * just removed. Either way, inform
219 * the caller that it might be worth
220 * trying again:
222 ret = SCLD_VANISHED;
223 else
224 ret = SCLD_FAILED;
225 } else if (adjust_shared_perm(path)) {
226 ret = SCLD_PERMS;
228 *slash = slash_character;
230 return ret;
233 enum scld_error safe_create_leading_directories_const(const char *path)
235 int save_errno;
236 /* path points to cache entries, so xstrdup before messing with it */
237 char *buf = xstrdup(path);
238 enum scld_error result = safe_create_leading_directories(buf);
240 save_errno = errno;
241 free(buf);
242 errno = save_errno;
243 return result;
246 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
249 * The number of times we will try to remove empty directories
250 * in the way of path. This is only 1 because if another
251 * process is racily creating directories that conflict with
252 * us, we don't want to fight against them.
254 int remove_directories_remaining = 1;
257 * The number of times that we will try to create the
258 * directories containing path. We are willing to attempt this
259 * more than once, because another process could be trying to
260 * clean up empty directories at the same time as we are
261 * trying to create them.
263 int create_directories_remaining = 3;
265 /* A scratch copy of path, filled lazily if we need it: */
266 struct strbuf path_copy = STRBUF_INIT;
268 int ret, save_errno;
270 /* Sanity check: */
271 assert(*path);
273 retry_fn:
274 ret = fn(path, cb);
275 save_errno = errno;
276 if (!ret)
277 goto out;
279 if (errno == EISDIR && remove_directories_remaining-- > 0) {
281 * A directory is in the way. Maybe it is empty; try
282 * to remove it:
284 if (!path_copy.len)
285 strbuf_addstr(&path_copy, path);
287 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
288 goto retry_fn;
289 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
291 * Maybe the containing directory didn't exist, or
292 * maybe it was just deleted by a process that is
293 * racing with us to clean up empty directories. Try
294 * to create it:
296 enum scld_error scld_result;
298 if (!path_copy.len)
299 strbuf_addstr(&path_copy, path);
301 do {
302 scld_result = safe_create_leading_directories(path_copy.buf);
303 if (scld_result == SCLD_OK)
304 goto retry_fn;
305 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
308 out:
309 strbuf_release(&path_copy);
310 errno = save_errno;
311 return ret;
314 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
316 int i;
317 for (i = 0; i < 20; i++) {
318 static char hex[] = "0123456789abcdef";
319 unsigned int val = sha1[i];
320 strbuf_addch(buf, hex[val >> 4]);
321 strbuf_addch(buf, hex[val & 0xf]);
322 if (!i)
323 strbuf_addch(buf, '/');
327 void sha1_file_name(struct repository *r, struct strbuf *buf, const unsigned char *sha1)
329 strbuf_addstr(buf, r->objects->objectdir);
330 strbuf_addch(buf, '/');
331 fill_sha1_path(buf, sha1);
334 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
336 strbuf_setlen(&alt->scratch, alt->base_len);
337 return &alt->scratch;
340 static const char *alt_sha1_path(struct alternate_object_database *alt,
341 const unsigned char *sha1)
343 struct strbuf *buf = alt_scratch_buf(alt);
344 fill_sha1_path(buf, sha1);
345 return buf->buf;
349 * Return non-zero iff the path is usable as an alternate object database.
351 static int alt_odb_usable(struct raw_object_store *o,
352 struct strbuf *path,
353 const char *normalized_objdir)
355 struct alternate_object_database *alt;
357 /* Detect cases where alternate disappeared */
358 if (!is_directory(path->buf)) {
359 error("object directory %s does not exist; "
360 "check .git/objects/info/alternates.",
361 path->buf);
362 return 0;
366 * Prevent the common mistake of listing the same
367 * thing twice, or object directory itself.
369 for (alt = o->alt_odb_list; alt; alt = alt->next) {
370 if (!fspathcmp(path->buf, alt->path))
371 return 0;
373 if (!fspathcmp(path->buf, normalized_objdir))
374 return 0;
376 return 1;
380 * Prepare alternate object database registry.
382 * The variable alt_odb_list points at the list of struct
383 * alternate_object_database. The elements on this list come from
384 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
385 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
386 * whose contents is similar to that environment variable but can be
387 * LF separated. Its base points at a statically allocated buffer that
388 * contains "/the/directory/corresponding/to/.git/objects/...", while
389 * its name points just after the slash at the end of ".git/objects/"
390 * in the example above, and has enough space to hold 40-byte hex
391 * SHA1, an extra slash for the first level indirection, and the
392 * terminating NUL.
394 static void read_info_alternates(struct repository *r,
395 const char *relative_base,
396 int depth);
397 static int link_alt_odb_entry(struct repository *r, const char *entry,
398 const char *relative_base, int depth, const char *normalized_objdir)
400 struct alternate_object_database *ent;
401 struct strbuf pathbuf = STRBUF_INIT;
403 if (!is_absolute_path(entry) && relative_base) {
404 strbuf_realpath(&pathbuf, relative_base, 1);
405 strbuf_addch(&pathbuf, '/');
407 strbuf_addstr(&pathbuf, entry);
409 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
410 error("unable to normalize alternate object path: %s",
411 pathbuf.buf);
412 strbuf_release(&pathbuf);
413 return -1;
417 * The trailing slash after the directory name is given by
418 * this function at the end. Remove duplicates.
420 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
421 strbuf_setlen(&pathbuf, pathbuf.len - 1);
423 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
424 strbuf_release(&pathbuf);
425 return -1;
428 ent = alloc_alt_odb(pathbuf.buf);
430 /* add the alternate entry */
431 *r->objects->alt_odb_tail = ent;
432 r->objects->alt_odb_tail = &(ent->next);
433 ent->next = NULL;
435 /* recursively add alternates */
436 read_info_alternates(r, pathbuf.buf, depth + 1);
438 strbuf_release(&pathbuf);
439 return 0;
442 static const char *parse_alt_odb_entry(const char *string,
443 int sep,
444 struct strbuf *out)
446 const char *end;
448 strbuf_reset(out);
450 if (*string == '#') {
451 /* comment; consume up to next separator */
452 end = strchrnul(string, sep);
453 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
455 * quoted path; unquote_c_style has copied the
456 * data for us and set "end". Broken quoting (e.g.,
457 * an entry that doesn't end with a quote) falls
458 * back to the unquoted case below.
460 } else {
461 /* normal, unquoted path */
462 end = strchrnul(string, sep);
463 strbuf_add(out, string, end - string);
466 if (*end)
467 end++;
468 return end;
471 static void link_alt_odb_entries(struct repository *r, const char *alt,
472 int sep, const char *relative_base, int depth)
474 struct strbuf objdirbuf = STRBUF_INIT;
475 struct strbuf entry = STRBUF_INIT;
477 if (!alt || !*alt)
478 return;
480 if (depth > 5) {
481 error("%s: ignoring alternate object stores, nesting too deep.",
482 relative_base);
483 return;
486 strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
487 if (strbuf_normalize_path(&objdirbuf) < 0)
488 die("unable to normalize object directory: %s",
489 objdirbuf.buf);
491 while (*alt) {
492 alt = parse_alt_odb_entry(alt, sep, &entry);
493 if (!entry.len)
494 continue;
495 link_alt_odb_entry(r, entry.buf,
496 relative_base, depth, objdirbuf.buf);
498 strbuf_release(&entry);
499 strbuf_release(&objdirbuf);
502 static void read_info_alternates(struct repository *r,
503 const char *relative_base,
504 int depth)
506 char *path;
507 struct strbuf buf = STRBUF_INIT;
509 path = xstrfmt("%s/info/alternates", relative_base);
510 if (strbuf_read_file(&buf, path, 1024) < 0) {
511 warn_on_fopen_errors(path);
512 free(path);
513 return;
516 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
517 strbuf_release(&buf);
518 free(path);
521 struct alternate_object_database *alloc_alt_odb(const char *dir)
523 struct alternate_object_database *ent;
525 FLEX_ALLOC_STR(ent, path, dir);
526 strbuf_init(&ent->scratch, 0);
527 strbuf_addf(&ent->scratch, "%s/", dir);
528 ent->base_len = ent->scratch.len;
530 return ent;
533 void add_to_alternates_file(const char *reference)
535 struct lock_file lock = LOCK_INIT;
536 char *alts = git_pathdup("objects/info/alternates");
537 FILE *in, *out;
538 int found = 0;
540 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
541 out = fdopen_lock_file(&lock, "w");
542 if (!out)
543 die_errno("unable to fdopen alternates lockfile");
545 in = fopen(alts, "r");
546 if (in) {
547 struct strbuf line = STRBUF_INIT;
549 while (strbuf_getline(&line, in) != EOF) {
550 if (!strcmp(reference, line.buf)) {
551 found = 1;
552 break;
554 fprintf_or_die(out, "%s\n", line.buf);
557 strbuf_release(&line);
558 fclose(in);
560 else if (errno != ENOENT)
561 die_errno("unable to read alternates file");
563 if (found) {
564 rollback_lock_file(&lock);
565 } else {
566 fprintf_or_die(out, "%s\n", reference);
567 if (commit_lock_file(&lock))
568 die_errno("unable to move new alternates file into place");
569 if (the_repository->objects->alt_odb_tail)
570 link_alt_odb_entries(the_repository, reference,
571 '\n', NULL, 0);
573 free(alts);
576 void add_to_alternates_memory(const char *reference)
579 * Make sure alternates are initialized, or else our entry may be
580 * overwritten when they are.
582 prepare_alt_odb(the_repository);
584 link_alt_odb_entries(the_repository, reference,
585 '\n', NULL, 0);
589 * Compute the exact path an alternate is at and returns it. In case of
590 * error NULL is returned and the human readable error is added to `err`
591 * `path` may be relative and should point to $GITDIR.
592 * `err` must not be null.
594 char *compute_alternate_path(const char *path, struct strbuf *err)
596 char *ref_git = NULL;
597 const char *repo, *ref_git_s;
598 int seen_error = 0;
600 ref_git_s = real_path_if_valid(path);
601 if (!ref_git_s) {
602 seen_error = 1;
603 strbuf_addf(err, _("path '%s' does not exist"), path);
604 goto out;
605 } else
607 * Beware: read_gitfile(), real_path() and mkpath()
608 * return static buffer
610 ref_git = xstrdup(ref_git_s);
612 repo = read_gitfile(ref_git);
613 if (!repo)
614 repo = read_gitfile(mkpath("%s/.git", ref_git));
615 if (repo) {
616 free(ref_git);
617 ref_git = xstrdup(repo);
620 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
621 char *ref_git_git = mkpathdup("%s/.git", ref_git);
622 free(ref_git);
623 ref_git = ref_git_git;
624 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
625 struct strbuf sb = STRBUF_INIT;
626 seen_error = 1;
627 if (get_common_dir(&sb, ref_git)) {
628 strbuf_addf(err,
629 _("reference repository '%s' as a linked "
630 "checkout is not supported yet."),
631 path);
632 goto out;
635 strbuf_addf(err, _("reference repository '%s' is not a "
636 "local repository."), path);
637 goto out;
640 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
641 strbuf_addf(err, _("reference repository '%s' is shallow"),
642 path);
643 seen_error = 1;
644 goto out;
647 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
648 strbuf_addf(err,
649 _("reference repository '%s' is grafted"),
650 path);
651 seen_error = 1;
652 goto out;
655 out:
656 if (seen_error) {
657 FREE_AND_NULL(ref_git);
660 return ref_git;
663 int foreach_alt_odb(alt_odb_fn fn, void *cb)
665 struct alternate_object_database *ent;
666 int r = 0;
668 prepare_alt_odb(the_repository);
669 for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
670 r = fn(ent, cb);
671 if (r)
672 break;
674 return r;
677 void prepare_alt_odb(struct repository *r)
679 if (r->objects->alt_odb_tail)
680 return;
682 r->objects->alt_odb_tail = &r->objects->alt_odb_list;
683 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
685 read_info_alternates(r, r->objects->objectdir, 0);
688 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
689 static int freshen_file(const char *fn)
691 struct utimbuf t;
692 t.actime = t.modtime = time(NULL);
693 return !utime(fn, &t);
697 * All of the check_and_freshen functions return 1 if the file exists and was
698 * freshened (if freshening was requested), 0 otherwise. If they return
699 * 0, you should not assume that it is safe to skip a write of the object (it
700 * either does not exist on disk, or has a stale mtime and may be subject to
701 * pruning).
703 int check_and_freshen_file(const char *fn, int freshen)
705 if (access(fn, F_OK))
706 return 0;
707 if (freshen && !freshen_file(fn))
708 return 0;
709 return 1;
712 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
714 static struct strbuf buf = STRBUF_INIT;
716 strbuf_reset(&buf);
717 sha1_file_name(the_repository, &buf, sha1);
719 return check_and_freshen_file(buf.buf, freshen);
722 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
724 struct alternate_object_database *alt;
725 prepare_alt_odb(the_repository);
726 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
727 const char *path = alt_sha1_path(alt, sha1);
728 if (check_and_freshen_file(path, freshen))
729 return 1;
731 return 0;
734 static int check_and_freshen(const unsigned char *sha1, int freshen)
736 return check_and_freshen_local(sha1, freshen) ||
737 check_and_freshen_nonlocal(sha1, freshen);
740 int has_loose_object_nonlocal(const unsigned char *sha1)
742 return check_and_freshen_nonlocal(sha1, 0);
745 static int has_loose_object(const unsigned char *sha1)
747 return check_and_freshen(sha1, 0);
750 static void mmap_limit_check(size_t length)
752 static size_t limit = 0;
753 if (!limit) {
754 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
755 if (!limit)
756 limit = SIZE_MAX;
758 if (length > limit)
759 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
760 (uintmax_t)length, (uintmax_t)limit);
763 void *xmmap_gently(void *start, size_t length,
764 int prot, int flags, int fd, off_t offset)
766 void *ret;
768 mmap_limit_check(length);
769 ret = mmap(start, length, prot, flags, fd, offset);
770 if (ret == MAP_FAILED) {
771 if (!length)
772 return NULL;
773 release_pack_memory(length);
774 ret = mmap(start, length, prot, flags, fd, offset);
776 return ret;
779 void *xmmap(void *start, size_t length,
780 int prot, int flags, int fd, off_t offset)
782 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
783 if (ret == MAP_FAILED)
784 die_errno("mmap failed");
785 return ret;
789 * With an in-core object data in "map", rehash it to make sure the
790 * object name actually matches "sha1" to detect object corruption.
791 * With "map" == NULL, try reading the object named with "sha1" using
792 * the streaming interface and rehash it to do the same.
794 int check_object_signature(const struct object_id *oid, void *map,
795 unsigned long size, const char *type)
797 struct object_id real_oid;
798 enum object_type obj_type;
799 struct git_istream *st;
800 git_hash_ctx c;
801 char hdr[MAX_HEADER_LEN];
802 int hdrlen;
804 if (map) {
805 hash_object_file(map, size, type, &real_oid);
806 return oidcmp(oid, &real_oid) ? -1 : 0;
809 st = open_istream(oid, &obj_type, &size, NULL);
810 if (!st)
811 return -1;
813 /* Generate the header */
814 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
816 /* Sha1.. */
817 the_hash_algo->init_fn(&c);
818 the_hash_algo->update_fn(&c, hdr, hdrlen);
819 for (;;) {
820 char buf[1024 * 16];
821 ssize_t readlen = read_istream(st, buf, sizeof(buf));
823 if (readlen < 0) {
824 close_istream(st);
825 return -1;
827 if (!readlen)
828 break;
829 the_hash_algo->update_fn(&c, buf, readlen);
831 the_hash_algo->final_fn(real_oid.hash, &c);
832 close_istream(st);
833 return oidcmp(oid, &real_oid) ? -1 : 0;
836 int git_open_cloexec(const char *name, int flags)
838 int fd;
839 static int o_cloexec = O_CLOEXEC;
841 fd = open(name, flags | o_cloexec);
842 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
843 /* Try again w/o O_CLOEXEC: the kernel might not support it */
844 o_cloexec &= ~O_CLOEXEC;
845 fd = open(name, flags | o_cloexec);
848 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
850 static int fd_cloexec = FD_CLOEXEC;
852 if (!o_cloexec && 0 <= fd && fd_cloexec) {
853 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
854 int flags = fcntl(fd, F_GETFD);
855 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
856 fd_cloexec = 0;
859 #endif
860 return fd;
864 * Find "sha1" as a loose object in the local repository or in an alternate.
865 * Returns 0 on success, negative on failure.
867 * The "path" out-parameter will give the path of the object we found (if any).
868 * Note that it may point to static storage and is only valid until another
869 * call to sha1_file_name(), etc.
871 static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
872 struct stat *st, const char **path)
874 struct alternate_object_database *alt;
875 static struct strbuf buf = STRBUF_INIT;
877 strbuf_reset(&buf);
878 sha1_file_name(r, &buf, sha1);
879 *path = buf.buf;
881 if (!lstat(*path, st))
882 return 0;
884 prepare_alt_odb(r);
885 errno = ENOENT;
886 for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
887 *path = alt_sha1_path(alt, sha1);
888 if (!lstat(*path, st))
889 return 0;
892 return -1;
896 * Like stat_sha1_file(), but actually open the object and return the
897 * descriptor. See the caveats on the "path" parameter above.
899 static int open_sha1_file(struct repository *r,
900 const unsigned char *sha1, const char **path)
902 int fd;
903 struct alternate_object_database *alt;
904 int most_interesting_errno;
905 static struct strbuf buf = STRBUF_INIT;
907 strbuf_reset(&buf);
908 sha1_file_name(r, &buf, sha1);
909 *path = buf.buf;
911 fd = git_open(*path);
912 if (fd >= 0)
913 return fd;
914 most_interesting_errno = errno;
916 prepare_alt_odb(r);
917 for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
918 *path = alt_sha1_path(alt, sha1);
919 fd = git_open(*path);
920 if (fd >= 0)
921 return fd;
922 if (most_interesting_errno == ENOENT)
923 most_interesting_errno = errno;
925 errno = most_interesting_errno;
926 return -1;
930 * Map the loose object at "path" if it is not NULL, or the path found by
931 * searching for a loose object named "sha1".
933 static void *map_sha1_file_1(struct repository *r, const char *path,
934 const unsigned char *sha1, unsigned long *size)
936 void *map;
937 int fd;
939 if (path)
940 fd = git_open(path);
941 else
942 fd = open_sha1_file(r, sha1, &path);
943 map = NULL;
944 if (fd >= 0) {
945 struct stat st;
947 if (!fstat(fd, &st)) {
948 *size = xsize_t(st.st_size);
949 if (!*size) {
950 /* mmap() is forbidden on empty files */
951 error("object file %s is empty", path);
952 return NULL;
954 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
956 close(fd);
958 return map;
961 void *map_sha1_file(struct repository *r,
962 const unsigned char *sha1, unsigned long *size)
964 return map_sha1_file_1(r, NULL, sha1, size);
967 static int unpack_sha1_short_header(git_zstream *stream,
968 unsigned char *map, unsigned long mapsize,
969 void *buffer, unsigned long bufsiz)
971 /* Get the data stream */
972 memset(stream, 0, sizeof(*stream));
973 stream->next_in = map;
974 stream->avail_in = mapsize;
975 stream->next_out = buffer;
976 stream->avail_out = bufsiz;
978 git_inflate_init(stream);
979 return git_inflate(stream, 0);
982 int unpack_sha1_header(git_zstream *stream,
983 unsigned char *map, unsigned long mapsize,
984 void *buffer, unsigned long bufsiz)
986 int status = unpack_sha1_short_header(stream, map, mapsize,
987 buffer, bufsiz);
989 if (status < Z_OK)
990 return status;
992 /* Make sure we have the terminating NUL */
993 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
994 return -1;
995 return 0;
998 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
999 unsigned long mapsize, void *buffer,
1000 unsigned long bufsiz, struct strbuf *header)
1002 int status;
1004 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1005 if (status < Z_OK)
1006 return -1;
1009 * Check if entire header is unpacked in the first iteration.
1011 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1012 return 0;
1015 * buffer[0..bufsiz] was not large enough. Copy the partial
1016 * result out to header, and then append the result of further
1017 * reading the stream.
1019 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1020 stream->next_out = buffer;
1021 stream->avail_out = bufsiz;
1023 do {
1024 status = git_inflate(stream, 0);
1025 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1026 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1027 return 0;
1028 stream->next_out = buffer;
1029 stream->avail_out = bufsiz;
1030 } while (status != Z_STREAM_END);
1031 return -1;
1034 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1036 int bytes = strlen(buffer) + 1;
1037 unsigned char *buf = xmallocz(size);
1038 unsigned long n;
1039 int status = Z_OK;
1041 n = stream->total_out - bytes;
1042 if (n > size)
1043 n = size;
1044 memcpy(buf, (char *) buffer + bytes, n);
1045 bytes = n;
1046 if (bytes <= size) {
1048 * The above condition must be (bytes <= size), not
1049 * (bytes < size). In other words, even though we
1050 * expect no more output and set avail_out to zero,
1051 * the input zlib stream may have bytes that express
1052 * "this concludes the stream", and we *do* want to
1053 * eat that input.
1055 * Otherwise we would not be able to test that we
1056 * consumed all the input to reach the expected size;
1057 * we also want to check that zlib tells us that all
1058 * went well with status == Z_STREAM_END at the end.
1060 stream->next_out = buf + bytes;
1061 stream->avail_out = size - bytes;
1062 while (status == Z_OK)
1063 status = git_inflate(stream, Z_FINISH);
1065 if (status == Z_STREAM_END && !stream->avail_in) {
1066 git_inflate_end(stream);
1067 return buf;
1070 if (status < 0)
1071 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1072 else if (stream->avail_in)
1073 error("garbage at end of loose object '%s'",
1074 sha1_to_hex(sha1));
1075 free(buf);
1076 return NULL;
1080 * We used to just use "sscanf()", but that's actually way
1081 * too permissive for what we want to check. So do an anal
1082 * object header parse by hand.
1084 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1085 unsigned int flags)
1087 const char *type_buf = hdr;
1088 unsigned long size;
1089 int type, type_len = 0;
1092 * The type can be of any size but is followed by
1093 * a space.
1095 for (;;) {
1096 char c = *hdr++;
1097 if (!c)
1098 return -1;
1099 if (c == ' ')
1100 break;
1101 type_len++;
1104 type = type_from_string_gently(type_buf, type_len, 1);
1105 if (oi->type_name)
1106 strbuf_add(oi->type_name, type_buf, type_len);
1108 * Set type to 0 if its an unknown object and
1109 * we're obtaining the type using '--allow-unknown-type'
1110 * option.
1112 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1113 type = 0;
1114 else if (type < 0)
1115 die("invalid object type");
1116 if (oi->typep)
1117 *oi->typep = type;
1120 * The length must follow immediately, and be in canonical
1121 * decimal format (ie "010" is not valid).
1123 size = *hdr++ - '0';
1124 if (size > 9)
1125 return -1;
1126 if (size) {
1127 for (;;) {
1128 unsigned long c = *hdr - '0';
1129 if (c > 9)
1130 break;
1131 hdr++;
1132 size = size * 10 + c;
1136 if (oi->sizep)
1137 *oi->sizep = size;
1140 * The length must be followed by a zero byte
1142 return *hdr ? -1 : type;
1145 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1147 struct object_info oi = OBJECT_INFO_INIT;
1149 oi.sizep = sizep;
1150 return parse_sha1_header_extended(hdr, &oi, 0);
1153 static int sha1_loose_object_info(struct repository *r,
1154 const unsigned char *sha1,
1155 struct object_info *oi, int flags)
1157 int status = 0;
1158 unsigned long mapsize;
1159 void *map;
1160 git_zstream stream;
1161 char hdr[MAX_HEADER_LEN];
1162 struct strbuf hdrbuf = STRBUF_INIT;
1163 unsigned long size_scratch;
1165 if (oi->delta_base_sha1)
1166 hashclr(oi->delta_base_sha1);
1169 * If we don't care about type or size, then we don't
1170 * need to look inside the object at all. Note that we
1171 * do not optimize out the stat call, even if the
1172 * caller doesn't care about the disk-size, since our
1173 * return value implicitly indicates whether the
1174 * object even exists.
1176 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1177 const char *path;
1178 struct stat st;
1179 if (stat_sha1_file(r, sha1, &st, &path) < 0)
1180 return -1;
1181 if (oi->disk_sizep)
1182 *oi->disk_sizep = st.st_size;
1183 return 0;
1186 map = map_sha1_file(r, sha1, &mapsize);
1187 if (!map)
1188 return -1;
1190 if (!oi->sizep)
1191 oi->sizep = &size_scratch;
1193 if (oi->disk_sizep)
1194 *oi->disk_sizep = mapsize;
1195 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1196 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1197 status = error("unable to unpack %s header with --allow-unknown-type",
1198 sha1_to_hex(sha1));
1199 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1200 status = error("unable to unpack %s header",
1201 sha1_to_hex(sha1));
1202 if (status < 0)
1203 ; /* Do nothing */
1204 else if (hdrbuf.len) {
1205 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1206 status = error("unable to parse %s header with --allow-unknown-type",
1207 sha1_to_hex(sha1));
1208 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1209 status = error("unable to parse %s header", sha1_to_hex(sha1));
1211 if (status >= 0 && oi->contentp) {
1212 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1213 *oi->sizep, sha1);
1214 if (!*oi->contentp) {
1215 git_inflate_end(&stream);
1216 status = -1;
1218 } else
1219 git_inflate_end(&stream);
1221 munmap(map, mapsize);
1222 if (status && oi->typep)
1223 *oi->typep = status;
1224 if (oi->sizep == &size_scratch)
1225 oi->sizep = NULL;
1226 strbuf_release(&hdrbuf);
1227 oi->whence = OI_LOOSE;
1228 return (status < 0) ? status : 0;
1231 int fetch_if_missing = 1;
1233 int oid_object_info_extended(const struct object_id *oid, struct object_info *oi, unsigned flags)
1235 static struct object_info blank_oi = OBJECT_INFO_INIT;
1236 struct pack_entry e;
1237 int rtype;
1238 const struct object_id *real = oid;
1239 int already_retried = 0;
1241 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1242 real = lookup_replace_object(oid);
1244 if (is_null_oid(real))
1245 return -1;
1247 if (!oi)
1248 oi = &blank_oi;
1250 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1251 struct cached_object *co = find_cached_object(real->hash);
1252 if (co) {
1253 if (oi->typep)
1254 *(oi->typep) = co->type;
1255 if (oi->sizep)
1256 *(oi->sizep) = co->size;
1257 if (oi->disk_sizep)
1258 *(oi->disk_sizep) = 0;
1259 if (oi->delta_base_sha1)
1260 hashclr(oi->delta_base_sha1);
1261 if (oi->type_name)
1262 strbuf_addstr(oi->type_name, type_name(co->type));
1263 if (oi->contentp)
1264 *oi->contentp = xmemdupz(co->buf, co->size);
1265 oi->whence = OI_CACHED;
1266 return 0;
1270 while (1) {
1271 if (find_pack_entry(the_repository, real->hash, &e))
1272 break;
1274 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1275 return -1;
1277 /* Most likely it's a loose object. */
1278 if (!sha1_loose_object_info(the_repository, real->hash, oi, flags))
1279 return 0;
1281 /* Not a loose object; someone else may have just packed it. */
1282 if (!(flags & OBJECT_INFO_QUICK)) {
1283 reprepare_packed_git(the_repository);
1284 if (find_pack_entry(the_repository, real->hash, &e))
1285 break;
1288 /* Check if it is a missing object */
1289 if (fetch_if_missing && repository_format_partial_clone &&
1290 !already_retried) {
1292 * TODO Investigate haveing fetch_object() return
1293 * TODO error/success and stopping the music here.
1295 fetch_object(repository_format_partial_clone, real->hash);
1296 already_retried = 1;
1297 continue;
1300 return -1;
1303 if (oi == &blank_oi)
1305 * We know that the caller doesn't actually need the
1306 * information below, so return early.
1308 return 0;
1309 rtype = packed_object_info(e.p, e.offset, oi);
1310 if (rtype < 0) {
1311 mark_bad_packed_object(e.p, real->hash);
1312 return oid_object_info_extended(real, oi, 0);
1313 } else if (oi->whence == OI_PACKED) {
1314 oi->u.packed.offset = e.offset;
1315 oi->u.packed.pack = e.p;
1316 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1317 rtype == OBJ_OFS_DELTA);
1320 return 0;
1323 /* returns enum object_type or negative */
1324 int oid_object_info(const struct object_id *oid, unsigned long *sizep)
1326 enum object_type type;
1327 struct object_info oi = OBJECT_INFO_INIT;
1329 oi.typep = &type;
1330 oi.sizep = sizep;
1331 if (oid_object_info_extended(oid, &oi,
1332 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1333 return -1;
1334 return type;
1337 static void *read_object(const unsigned char *sha1, enum object_type *type,
1338 unsigned long *size)
1340 struct object_id oid;
1341 struct object_info oi = OBJECT_INFO_INIT;
1342 void *content;
1343 oi.typep = type;
1344 oi.sizep = size;
1345 oi.contentp = &content;
1347 hashcpy(oid.hash, sha1);
1349 if (oid_object_info_extended(&oid, &oi, 0) < 0)
1350 return NULL;
1351 return content;
1354 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1355 struct object_id *oid)
1357 struct cached_object *co;
1359 hash_object_file(buf, len, type_name(type), oid);
1360 if (has_sha1_file(oid->hash) || find_cached_object(oid->hash))
1361 return 0;
1362 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1363 co = &cached_objects[cached_object_nr++];
1364 co->size = len;
1365 co->type = type;
1366 co->buf = xmalloc(len);
1367 memcpy(co->buf, buf, len);
1368 hashcpy(co->sha1, oid->hash);
1369 return 0;
1373 * This function dies on corrupt objects; the callers who want to
1374 * deal with them should arrange to call read_object() and give error
1375 * messages themselves.
1377 void *read_object_file_extended(const struct object_id *oid,
1378 enum object_type *type,
1379 unsigned long *size,
1380 int lookup_replace)
1382 void *data;
1383 const struct packed_git *p;
1384 const char *path;
1385 struct stat st;
1386 const struct object_id *repl = lookup_replace ? lookup_replace_object(oid)
1387 : oid;
1389 errno = 0;
1390 data = read_object(repl->hash, type, size);
1391 if (data)
1392 return data;
1394 if (errno && errno != ENOENT)
1395 die_errno("failed to read object %s", oid_to_hex(oid));
1397 /* die if we replaced an object with one that does not exist */
1398 if (repl != oid)
1399 die("replacement %s not found for %s",
1400 oid_to_hex(repl), oid_to_hex(oid));
1402 if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1403 die("loose object %s (stored in %s) is corrupt",
1404 oid_to_hex(repl), path);
1406 if ((p = has_packed_and_bad(repl->hash)) != NULL)
1407 die("packed object %s (stored in %s) is corrupt",
1408 oid_to_hex(repl), p->pack_name);
1410 return NULL;
1413 void *read_object_with_reference(const struct object_id *oid,
1414 const char *required_type_name,
1415 unsigned long *size,
1416 struct object_id *actual_oid_return)
1418 enum object_type type, required_type;
1419 void *buffer;
1420 unsigned long isize;
1421 struct object_id actual_oid;
1423 required_type = type_from_string(required_type_name);
1424 oidcpy(&actual_oid, oid);
1425 while (1) {
1426 int ref_length = -1;
1427 const char *ref_type = NULL;
1429 buffer = read_object_file(&actual_oid, &type, &isize);
1430 if (!buffer)
1431 return NULL;
1432 if (type == required_type) {
1433 *size = isize;
1434 if (actual_oid_return)
1435 oidcpy(actual_oid_return, &actual_oid);
1436 return buffer;
1438 /* Handle references */
1439 else if (type == OBJ_COMMIT)
1440 ref_type = "tree ";
1441 else if (type == OBJ_TAG)
1442 ref_type = "object ";
1443 else {
1444 free(buffer);
1445 return NULL;
1447 ref_length = strlen(ref_type);
1449 if (ref_length + GIT_SHA1_HEXSZ > isize ||
1450 memcmp(buffer, ref_type, ref_length) ||
1451 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1452 free(buffer);
1453 return NULL;
1455 free(buffer);
1456 /* Now we have the ID of the referred-to object in
1457 * actual_oid. Check again. */
1461 static void write_object_file_prepare(const void *buf, unsigned long len,
1462 const char *type, struct object_id *oid,
1463 char *hdr, int *hdrlen)
1465 git_hash_ctx c;
1467 /* Generate the header */
1468 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1470 /* Sha1.. */
1471 the_hash_algo->init_fn(&c);
1472 the_hash_algo->update_fn(&c, hdr, *hdrlen);
1473 the_hash_algo->update_fn(&c, buf, len);
1474 the_hash_algo->final_fn(oid->hash, &c);
1478 * Move the just written object into its final resting place.
1480 int finalize_object_file(const char *tmpfile, const char *filename)
1482 int ret = 0;
1484 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1485 goto try_rename;
1486 else if (link(tmpfile, filename))
1487 ret = errno;
1490 * Coda hack - coda doesn't like cross-directory links,
1491 * so we fall back to a rename, which will mean that it
1492 * won't be able to check collisions, but that's not a
1493 * big deal.
1495 * The same holds for FAT formatted media.
1497 * When this succeeds, we just return. We have nothing
1498 * left to unlink.
1500 if (ret && ret != EEXIST) {
1501 try_rename:
1502 if (!rename(tmpfile, filename))
1503 goto out;
1504 ret = errno;
1506 unlink_or_warn(tmpfile);
1507 if (ret) {
1508 if (ret != EEXIST) {
1509 return error_errno("unable to write sha1 filename %s", filename);
1511 /* FIXME!!! Collision check here ? */
1514 out:
1515 if (adjust_shared_perm(filename))
1516 return error("unable to set permission to '%s'", filename);
1517 return 0;
1520 static int write_buffer(int fd, const void *buf, size_t len)
1522 if (write_in_full(fd, buf, len) < 0)
1523 return error_errno("file write error");
1524 return 0;
1527 int hash_object_file(const void *buf, unsigned long len, const char *type,
1528 struct object_id *oid)
1530 char hdr[MAX_HEADER_LEN];
1531 int hdrlen = sizeof(hdr);
1532 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1533 return 0;
1536 /* Finalize a file on disk, and close it. */
1537 static void close_sha1_file(int fd)
1539 if (fsync_object_files)
1540 fsync_or_die(fd, "sha1 file");
1541 if (close(fd) != 0)
1542 die_errno("error when closing sha1 file");
1545 /* Size of directory component, including the ending '/' */
1546 static inline int directory_size(const char *filename)
1548 const char *s = strrchr(filename, '/');
1549 if (!s)
1550 return 0;
1551 return s - filename + 1;
1555 * This creates a temporary file in the same directory as the final
1556 * 'filename'
1558 * We want to avoid cross-directory filename renames, because those
1559 * can have problems on various filesystems (FAT, NFS, Coda).
1561 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1563 int fd, dirlen = directory_size(filename);
1565 strbuf_reset(tmp);
1566 strbuf_add(tmp, filename, dirlen);
1567 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1568 fd = git_mkstemp_mode(tmp->buf, 0444);
1569 if (fd < 0 && dirlen && errno == ENOENT) {
1571 * Make sure the directory exists; note that the contents
1572 * of the buffer are undefined after mkstemp returns an
1573 * error, so we have to rewrite the whole buffer from
1574 * scratch.
1576 strbuf_reset(tmp);
1577 strbuf_add(tmp, filename, dirlen - 1);
1578 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1579 return -1;
1580 if (adjust_shared_perm(tmp->buf))
1581 return -1;
1583 /* Try again */
1584 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1585 fd = git_mkstemp_mode(tmp->buf, 0444);
1587 return fd;
1590 static int write_loose_object(const struct object_id *oid, char *hdr,
1591 int hdrlen, const void *buf, unsigned long len,
1592 time_t mtime)
1594 int fd, ret;
1595 unsigned char compressed[4096];
1596 git_zstream stream;
1597 git_hash_ctx c;
1598 struct object_id parano_oid;
1599 static struct strbuf tmp_file = STRBUF_INIT;
1600 static struct strbuf filename = STRBUF_INIT;
1602 strbuf_reset(&filename);
1603 sha1_file_name(the_repository, &filename, oid->hash);
1605 fd = create_tmpfile(&tmp_file, filename.buf);
1606 if (fd < 0) {
1607 if (errno == EACCES)
1608 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
1609 else
1610 return error_errno("unable to create temporary file");
1613 /* Set it up */
1614 git_deflate_init(&stream, zlib_compression_level);
1615 stream.next_out = compressed;
1616 stream.avail_out = sizeof(compressed);
1617 the_hash_algo->init_fn(&c);
1619 /* First header.. */
1620 stream.next_in = (unsigned char *)hdr;
1621 stream.avail_in = hdrlen;
1622 while (git_deflate(&stream, 0) == Z_OK)
1623 ; /* nothing */
1624 the_hash_algo->update_fn(&c, hdr, hdrlen);
1626 /* Then the data itself.. */
1627 stream.next_in = (void *)buf;
1628 stream.avail_in = len;
1629 do {
1630 unsigned char *in0 = stream.next_in;
1631 ret = git_deflate(&stream, Z_FINISH);
1632 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1633 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1634 die("unable to write sha1 file");
1635 stream.next_out = compressed;
1636 stream.avail_out = sizeof(compressed);
1637 } while (ret == Z_OK);
1639 if (ret != Z_STREAM_END)
1640 die("unable to deflate new object %s (%d)", oid_to_hex(oid),
1641 ret);
1642 ret = git_deflate_end_gently(&stream);
1643 if (ret != Z_OK)
1644 die("deflateEnd on object %s failed (%d)", oid_to_hex(oid),
1645 ret);
1646 the_hash_algo->final_fn(parano_oid.hash, &c);
1647 if (oidcmp(oid, &parano_oid) != 0)
1648 die("confused by unstable object source data for %s",
1649 oid_to_hex(oid));
1651 close_sha1_file(fd);
1653 if (mtime) {
1654 struct utimbuf utb;
1655 utb.actime = mtime;
1656 utb.modtime = mtime;
1657 if (utime(tmp_file.buf, &utb) < 0)
1658 warning_errno("failed utime() on %s", tmp_file.buf);
1661 return finalize_object_file(tmp_file.buf, filename.buf);
1664 static int freshen_loose_object(const unsigned char *sha1)
1666 return check_and_freshen(sha1, 1);
1669 static int freshen_packed_object(const unsigned char *sha1)
1671 struct pack_entry e;
1672 if (!find_pack_entry(the_repository, sha1, &e))
1673 return 0;
1674 if (e.p->freshened)
1675 return 1;
1676 if (!freshen_file(e.p->pack_name))
1677 return 0;
1678 e.p->freshened = 1;
1679 return 1;
1682 int write_object_file(const void *buf, unsigned long len, const char *type,
1683 struct object_id *oid)
1685 char hdr[MAX_HEADER_LEN];
1686 int hdrlen = sizeof(hdr);
1688 /* Normally if we have it in the pack then we do not bother writing
1689 * it out into .git/objects/??/?{38} file.
1691 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1692 if (freshen_packed_object(oid->hash) || freshen_loose_object(oid->hash))
1693 return 0;
1694 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1697 int hash_object_file_literally(const void *buf, unsigned long len,
1698 const char *type, struct object_id *oid,
1699 unsigned flags)
1701 char *header;
1702 int hdrlen, status = 0;
1704 /* type string, SP, %lu of the length plus NUL must fit this */
1705 hdrlen = strlen(type) + MAX_HEADER_LEN;
1706 header = xmalloc(hdrlen);
1707 write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1709 if (!(flags & HASH_WRITE_OBJECT))
1710 goto cleanup;
1711 if (freshen_packed_object(oid->hash) || freshen_loose_object(oid->hash))
1712 goto cleanup;
1713 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1715 cleanup:
1716 free(header);
1717 return status;
1720 int force_object_loose(const struct object_id *oid, time_t mtime)
1722 void *buf;
1723 unsigned long len;
1724 enum object_type type;
1725 char hdr[MAX_HEADER_LEN];
1726 int hdrlen;
1727 int ret;
1729 if (has_loose_object(oid->hash))
1730 return 0;
1731 buf = read_object(oid->hash, &type, &len);
1732 if (!buf)
1733 return error("cannot read sha1_file for %s", oid_to_hex(oid));
1734 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1735 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1736 free(buf);
1738 return ret;
1741 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1743 struct object_id oid;
1744 if (!startup_info->have_repository)
1745 return 0;
1746 hashcpy(oid.hash, sha1);
1747 return oid_object_info_extended(&oid, NULL,
1748 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1751 int has_object_file(const struct object_id *oid)
1753 return has_sha1_file(oid->hash);
1756 int has_object_file_with_flags(const struct object_id *oid, int flags)
1758 return has_sha1_file_with_flags(oid->hash, flags);
1761 static void check_tree(const void *buf, size_t size)
1763 struct tree_desc desc;
1764 struct name_entry entry;
1766 init_tree_desc(&desc, buf, size);
1767 while (tree_entry(&desc, &entry))
1768 /* do nothing
1769 * tree_entry() will die() on malformed entries */
1773 static void check_commit(const void *buf, size_t size)
1775 struct commit c;
1776 memset(&c, 0, sizeof(c));
1777 if (parse_commit_buffer(&c, buf, size))
1778 die("corrupt commit");
1781 static void check_tag(const void *buf, size_t size)
1783 struct tag t;
1784 memset(&t, 0, sizeof(t));
1785 if (parse_tag_buffer(&t, buf, size))
1786 die("corrupt tag");
1789 static int index_mem(struct object_id *oid, void *buf, size_t size,
1790 enum object_type type,
1791 const char *path, unsigned flags)
1793 int ret, re_allocated = 0;
1794 int write_object = flags & HASH_WRITE_OBJECT;
1796 if (!type)
1797 type = OBJ_BLOB;
1800 * Convert blobs to git internal format
1802 if ((type == OBJ_BLOB) && path) {
1803 struct strbuf nbuf = STRBUF_INIT;
1804 if (convert_to_git(&the_index, path, buf, size, &nbuf,
1805 get_conv_flags(flags))) {
1806 buf = strbuf_detach(&nbuf, &size);
1807 re_allocated = 1;
1810 if (flags & HASH_FORMAT_CHECK) {
1811 if (type == OBJ_TREE)
1812 check_tree(buf, size);
1813 if (type == OBJ_COMMIT)
1814 check_commit(buf, size);
1815 if (type == OBJ_TAG)
1816 check_tag(buf, size);
1819 if (write_object)
1820 ret = write_object_file(buf, size, type_name(type), oid);
1821 else
1822 ret = hash_object_file(buf, size, type_name(type), oid);
1823 if (re_allocated)
1824 free(buf);
1825 return ret;
1828 static int index_stream_convert_blob(struct object_id *oid, int fd,
1829 const char *path, unsigned flags)
1831 int ret;
1832 const int write_object = flags & HASH_WRITE_OBJECT;
1833 struct strbuf sbuf = STRBUF_INIT;
1835 assert(path);
1836 assert(would_convert_to_git_filter_fd(path));
1838 convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
1839 get_conv_flags(flags));
1841 if (write_object)
1842 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1843 oid);
1844 else
1845 ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1846 oid);
1847 strbuf_release(&sbuf);
1848 return ret;
1851 static int index_pipe(struct object_id *oid, int fd, enum object_type type,
1852 const char *path, unsigned flags)
1854 struct strbuf sbuf = STRBUF_INIT;
1855 int ret;
1857 if (strbuf_read(&sbuf, fd, 4096) >= 0)
1858 ret = index_mem(oid, sbuf.buf, sbuf.len, type, path, flags);
1859 else
1860 ret = -1;
1861 strbuf_release(&sbuf);
1862 return ret;
1865 #define SMALL_FILE_SIZE (32*1024)
1867 static int index_core(struct object_id *oid, int fd, size_t size,
1868 enum object_type type, const char *path,
1869 unsigned flags)
1871 int ret;
1873 if (!size) {
1874 ret = index_mem(oid, "", size, type, path, flags);
1875 } else if (size <= SMALL_FILE_SIZE) {
1876 char *buf = xmalloc(size);
1877 ssize_t read_result = read_in_full(fd, buf, size);
1878 if (read_result < 0)
1879 ret = error_errno("read error while indexing %s",
1880 path ? path : "<unknown>");
1881 else if (read_result != size)
1882 ret = error("short read while indexing %s",
1883 path ? path : "<unknown>");
1884 else
1885 ret = index_mem(oid, buf, size, type, path, flags);
1886 free(buf);
1887 } else {
1888 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1889 ret = index_mem(oid, buf, size, type, path, flags);
1890 munmap(buf, size);
1892 return ret;
1896 * This creates one packfile per large blob unless bulk-checkin
1897 * machinery is "plugged".
1899 * This also bypasses the usual "convert-to-git" dance, and that is on
1900 * purpose. We could write a streaming version of the converting
1901 * functions and insert that before feeding the data to fast-import
1902 * (or equivalent in-core API described above). However, that is
1903 * somewhat complicated, as we do not know the size of the filter
1904 * result, which we need to know beforehand when writing a git object.
1905 * Since the primary motivation for trying to stream from the working
1906 * tree file and to avoid mmaping it in core is to deal with large
1907 * binary blobs, they generally do not want to get any conversion, and
1908 * callers should avoid this code path when filters are requested.
1910 static int index_stream(struct object_id *oid, int fd, size_t size,
1911 enum object_type type, const char *path,
1912 unsigned flags)
1914 return index_bulk_checkin(oid, fd, size, type, path, flags);
1917 int index_fd(struct object_id *oid, int fd, struct stat *st,
1918 enum object_type type, const char *path, unsigned flags)
1920 int ret;
1923 * Call xsize_t() only when needed to avoid potentially unnecessary
1924 * die() for large files.
1926 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
1927 ret = index_stream_convert_blob(oid, fd, path, flags);
1928 else if (!S_ISREG(st->st_mode))
1929 ret = index_pipe(oid, fd, type, path, flags);
1930 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1931 (path && would_convert_to_git(&the_index, path)))
1932 ret = index_core(oid, fd, xsize_t(st->st_size), type, path,
1933 flags);
1934 else
1935 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1936 flags);
1937 close(fd);
1938 return ret;
1941 int index_path(struct object_id *oid, const char *path, struct stat *st, unsigned flags)
1943 int fd;
1944 struct strbuf sb = STRBUF_INIT;
1945 int rc = 0;
1947 switch (st->st_mode & S_IFMT) {
1948 case S_IFREG:
1949 fd = open(path, O_RDONLY);
1950 if (fd < 0)
1951 return error_errno("open(\"%s\")", path);
1952 if (index_fd(oid, fd, st, OBJ_BLOB, path, flags) < 0)
1953 return error("%s: failed to insert into database",
1954 path);
1955 break;
1956 case S_IFLNK:
1957 if (strbuf_readlink(&sb, path, st->st_size))
1958 return error_errno("readlink(\"%s\")", path);
1959 if (!(flags & HASH_WRITE_OBJECT))
1960 hash_object_file(sb.buf, sb.len, blob_type, oid);
1961 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
1962 rc = error("%s: failed to insert into database", path);
1963 strbuf_release(&sb);
1964 break;
1965 case S_IFDIR:
1966 return resolve_gitlink_ref(path, "HEAD", oid);
1967 default:
1968 return error("%s: unsupported file type", path);
1970 return rc;
1973 int read_pack_header(int fd, struct pack_header *header)
1975 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1976 /* "eof before pack header was fully read" */
1977 return PH_ERROR_EOF;
1979 if (header->hdr_signature != htonl(PACK_SIGNATURE))
1980 /* "protocol error (pack signature mismatch detected)" */
1981 return PH_ERROR_PACK_SIGNATURE;
1982 if (!pack_version_ok(header->hdr_version))
1983 /* "protocol error (pack version unsupported)" */
1984 return PH_ERROR_PROTOCOL;
1985 return 0;
1988 void assert_oid_type(const struct object_id *oid, enum object_type expect)
1990 enum object_type type = oid_object_info(oid, NULL);
1991 if (type < 0)
1992 die("%s is not a valid object", oid_to_hex(oid));
1993 if (type != expect)
1994 die("%s is not a valid '%s' object", oid_to_hex(oid),
1995 type_name(expect));
1998 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
1999 struct strbuf *path,
2000 each_loose_object_fn obj_cb,
2001 each_loose_cruft_fn cruft_cb,
2002 each_loose_subdir_fn subdir_cb,
2003 void *data)
2005 size_t origlen, baselen;
2006 DIR *dir;
2007 struct dirent *de;
2008 int r = 0;
2009 struct object_id oid;
2011 if (subdir_nr > 0xff)
2012 BUG("invalid loose object subdirectory: %x", subdir_nr);
2014 origlen = path->len;
2015 strbuf_complete(path, '/');
2016 strbuf_addf(path, "%02x", subdir_nr);
2018 dir = opendir(path->buf);
2019 if (!dir) {
2020 if (errno != ENOENT)
2021 r = error_errno("unable to open %s", path->buf);
2022 strbuf_setlen(path, origlen);
2023 return r;
2026 oid.hash[0] = subdir_nr;
2027 strbuf_addch(path, '/');
2028 baselen = path->len;
2030 while ((de = readdir(dir))) {
2031 size_t namelen;
2032 if (is_dot_or_dotdot(de->d_name))
2033 continue;
2035 namelen = strlen(de->d_name);
2036 strbuf_setlen(path, baselen);
2037 strbuf_add(path, de->d_name, namelen);
2038 if (namelen == GIT_SHA1_HEXSZ - 2 &&
2039 !hex_to_bytes(oid.hash + 1, de->d_name,
2040 GIT_SHA1_RAWSZ - 1)) {
2041 if (obj_cb) {
2042 r = obj_cb(&oid, path->buf, data);
2043 if (r)
2044 break;
2046 continue;
2049 if (cruft_cb) {
2050 r = cruft_cb(de->d_name, path->buf, data);
2051 if (r)
2052 break;
2055 closedir(dir);
2057 strbuf_setlen(path, baselen - 1);
2058 if (!r && subdir_cb)
2059 r = subdir_cb(subdir_nr, path->buf, data);
2061 strbuf_setlen(path, origlen);
2063 return r;
2066 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2067 each_loose_object_fn obj_cb,
2068 each_loose_cruft_fn cruft_cb,
2069 each_loose_subdir_fn subdir_cb,
2070 void *data)
2072 int r = 0;
2073 int i;
2075 for (i = 0; i < 256; i++) {
2076 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2077 subdir_cb, data);
2078 if (r)
2079 break;
2082 return r;
2085 int for_each_loose_file_in_objdir(const char *path,
2086 each_loose_object_fn obj_cb,
2087 each_loose_cruft_fn cruft_cb,
2088 each_loose_subdir_fn subdir_cb,
2089 void *data)
2091 struct strbuf buf = STRBUF_INIT;
2092 int r;
2094 strbuf_addstr(&buf, path);
2095 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2096 subdir_cb, data);
2097 strbuf_release(&buf);
2099 return r;
2102 struct loose_alt_odb_data {
2103 each_loose_object_fn *cb;
2104 void *data;
2107 static int loose_from_alt_odb(struct alternate_object_database *alt,
2108 void *vdata)
2110 struct loose_alt_odb_data *data = vdata;
2111 struct strbuf buf = STRBUF_INIT;
2112 int r;
2114 strbuf_addstr(&buf, alt->path);
2115 r = for_each_loose_file_in_objdir_buf(&buf,
2116 data->cb, NULL, NULL,
2117 data->data);
2118 strbuf_release(&buf);
2119 return r;
2122 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
2124 struct loose_alt_odb_data alt;
2125 int r;
2127 r = for_each_loose_file_in_objdir(get_object_directory(),
2128 cb, NULL, NULL, data);
2129 if (r)
2130 return r;
2132 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2133 return 0;
2135 alt.cb = cb;
2136 alt.data = data;
2137 return foreach_alt_odb(loose_from_alt_odb, &alt);
2140 static int check_stream_sha1(git_zstream *stream,
2141 const char *hdr,
2142 unsigned long size,
2143 const char *path,
2144 const unsigned char *expected_sha1)
2146 git_hash_ctx c;
2147 unsigned char real_sha1[GIT_MAX_RAWSZ];
2148 unsigned char buf[4096];
2149 unsigned long total_read;
2150 int status = Z_OK;
2152 the_hash_algo->init_fn(&c);
2153 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2156 * We already read some bytes into hdr, but the ones up to the NUL
2157 * do not count against the object's content size.
2159 total_read = stream->total_out - strlen(hdr) - 1;
2162 * This size comparison must be "<=" to read the final zlib packets;
2163 * see the comment in unpack_sha1_rest for details.
2165 while (total_read <= size &&
2166 (status == Z_OK || status == Z_BUF_ERROR)) {
2167 stream->next_out = buf;
2168 stream->avail_out = sizeof(buf);
2169 if (size - total_read < stream->avail_out)
2170 stream->avail_out = size - total_read;
2171 status = git_inflate(stream, Z_FINISH);
2172 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2173 total_read += stream->next_out - buf;
2175 git_inflate_end(stream);
2177 if (status != Z_STREAM_END) {
2178 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
2179 return -1;
2181 if (stream->avail_in) {
2182 error("garbage at end of loose object '%s'",
2183 sha1_to_hex(expected_sha1));
2184 return -1;
2187 the_hash_algo->final_fn(real_sha1, &c);
2188 if (hashcmp(expected_sha1, real_sha1)) {
2189 error("sha1 mismatch for %s (expected %s)", path,
2190 sha1_to_hex(expected_sha1));
2191 return -1;
2194 return 0;
2197 int read_loose_object(const char *path,
2198 const struct object_id *expected_oid,
2199 enum object_type *type,
2200 unsigned long *size,
2201 void **contents)
2203 int ret = -1;
2204 void *map = NULL;
2205 unsigned long mapsize;
2206 git_zstream stream;
2207 char hdr[MAX_HEADER_LEN];
2209 *contents = NULL;
2211 map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2212 if (!map) {
2213 error_errno("unable to mmap %s", path);
2214 goto out;
2217 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2218 error("unable to unpack header of %s", path);
2219 goto out;
2222 *type = parse_sha1_header(hdr, size);
2223 if (*type < 0) {
2224 error("unable to parse header of %s", path);
2225 git_inflate_end(&stream);
2226 goto out;
2229 if (*type == OBJ_BLOB) {
2230 if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2231 goto out;
2232 } else {
2233 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2234 if (!*contents) {
2235 error("unable to unpack contents of %s", path);
2236 git_inflate_end(&stream);
2237 goto out;
2239 if (check_object_signature(expected_oid, *contents,
2240 *size, type_name(*type))) {
2241 error("sha1 mismatch for %s (expected %s)", path,
2242 oid_to_hex(expected_oid));
2243 free(*contents);
2244 goto out;
2248 ret = 0; /* everything checks out */
2250 out:
2251 if (map)
2252 munmap(map, mapsize);
2253 return ret;