make add_object_array_with_context interface more sane
[git.git] / sha1_file.c
blobc63264198ea3b52c78387e2f949b3cac7a7a256f
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 "string-list.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "blob.h"
14 #include "commit.h"
15 #include "run-command.h"
16 #include "tag.h"
17 #include "tree.h"
18 #include "tree-walk.h"
19 #include "refs.h"
20 #include "pack-revindex.h"
21 #include "sha1-lookup.h"
22 #include "bulk-checkin.h"
23 #include "streaming.h"
24 #include "dir.h"
26 #ifndef O_NOATIME
27 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
28 #define O_NOATIME 01000000
29 #else
30 #define O_NOATIME 0
31 #endif
32 #endif
34 #define SZ_FMT PRIuMAX
35 static inline uintmax_t sz_fmt(size_t s) { return s; }
37 const unsigned char null_sha1[20];
40 * This is meant to hold a *small* number of objects that you would
41 * want read_sha1_file() to be able to return, but yet you do not want
42 * to write them into the object store (e.g. a browse-only
43 * application).
45 static struct cached_object {
46 unsigned char sha1[20];
47 enum object_type type;
48 void *buf;
49 unsigned long size;
50 } *cached_objects;
51 static int cached_object_nr, cached_object_alloc;
53 static struct cached_object empty_tree = {
54 EMPTY_TREE_SHA1_BIN_LITERAL,
55 OBJ_TREE,
56 "",
61 * A pointer to the last packed_git in which an object was found.
62 * When an object is sought, we look in this packfile first, because
63 * objects that are looked up at similar times are often in the same
64 * packfile as one another.
66 static struct packed_git *last_found_pack;
68 static struct cached_object *find_cached_object(const unsigned char *sha1)
70 int i;
71 struct cached_object *co = cached_objects;
73 for (i = 0; i < cached_object_nr; i++, co++) {
74 if (!hashcmp(co->sha1, sha1))
75 return co;
77 if (!hashcmp(sha1, empty_tree.sha1))
78 return &empty_tree;
79 return NULL;
82 int mkdir_in_gitdir(const char *path)
84 if (mkdir(path, 0777)) {
85 int saved_errno = errno;
86 struct stat st;
87 struct strbuf sb = STRBUF_INIT;
89 if (errno != EEXIST)
90 return -1;
92 * Are we looking at a path in a symlinked worktree
93 * whose original repository does not yet have it?
94 * e.g. .git/rr-cache pointing at its original
95 * repository in which the user hasn't performed any
96 * conflict resolution yet?
98 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
99 strbuf_readlink(&sb, path, st.st_size) ||
100 !is_absolute_path(sb.buf) ||
101 mkdir(sb.buf, 0777)) {
102 strbuf_release(&sb);
103 errno = saved_errno;
104 return -1;
106 strbuf_release(&sb);
108 return adjust_shared_perm(path);
111 enum scld_error safe_create_leading_directories(char *path)
113 char *next_component = path + offset_1st_component(path);
114 enum scld_error ret = SCLD_OK;
116 while (ret == SCLD_OK && next_component) {
117 struct stat st;
118 char *slash = next_component, slash_character;
120 while (*slash && !is_dir_sep(*slash))
121 slash++;
123 if (!*slash)
124 break;
126 next_component = slash + 1;
127 while (is_dir_sep(*next_component))
128 next_component++;
129 if (!*next_component)
130 break;
132 slash_character = *slash;
133 *slash = '\0';
134 if (!stat(path, &st)) {
135 /* path exists */
136 if (!S_ISDIR(st.st_mode))
137 ret = SCLD_EXISTS;
138 } else if (mkdir(path, 0777)) {
139 if (errno == EEXIST &&
140 !stat(path, &st) && S_ISDIR(st.st_mode))
141 ; /* somebody created it since we checked */
142 else if (errno == ENOENT)
144 * Either mkdir() failed because
145 * somebody just pruned the containing
146 * directory, or stat() failed because
147 * the file that was in our way was
148 * just removed. Either way, inform
149 * the caller that it might be worth
150 * trying again:
152 ret = SCLD_VANISHED;
153 else
154 ret = SCLD_FAILED;
155 } else if (adjust_shared_perm(path)) {
156 ret = SCLD_PERMS;
158 *slash = slash_character;
160 return ret;
163 enum scld_error safe_create_leading_directories_const(const char *path)
165 /* path points to cache entries, so xstrdup before messing with it */
166 char *buf = xstrdup(path);
167 enum scld_error result = safe_create_leading_directories(buf);
168 free(buf);
169 return result;
172 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
174 int i;
175 for (i = 0; i < 20; i++) {
176 static char hex[] = "0123456789abcdef";
177 unsigned int val = sha1[i];
178 char *pos = pathbuf + i*2 + (i > 0);
179 *pos++ = hex[val >> 4];
180 *pos = hex[val & 0xf];
184 const char *sha1_file_name(const unsigned char *sha1)
186 static char buf[PATH_MAX];
187 const char *objdir;
188 int len;
190 objdir = get_object_directory();
191 len = strlen(objdir);
193 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
194 if (len + 43 > PATH_MAX)
195 die("insanely long object directory %s", objdir);
196 memcpy(buf, objdir, len);
197 buf[len] = '/';
198 buf[len+3] = '/';
199 buf[len+42] = '\0';
200 fill_sha1_path(buf + len + 1, sha1);
201 return buf;
205 * Return the name of the pack or index file with the specified sha1
206 * in its filename. *base and *name are scratch space that must be
207 * provided by the caller. which should be "pack" or "idx".
209 static char *sha1_get_pack_name(const unsigned char *sha1,
210 char **name, char **base, const char *which)
212 static const char hex[] = "0123456789abcdef";
213 char *buf;
214 int i;
216 if (!*base) {
217 const char *sha1_file_directory = get_object_directory();
218 int len = strlen(sha1_file_directory);
219 *base = xmalloc(len + 60);
220 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
221 sha1_file_directory, which);
222 *name = *base + len + 11;
225 buf = *name;
227 for (i = 0; i < 20; i++) {
228 unsigned int val = *sha1++;
229 *buf++ = hex[val >> 4];
230 *buf++ = hex[val & 0xf];
233 return *base;
236 char *sha1_pack_name(const unsigned char *sha1)
238 static char *name, *base;
240 return sha1_get_pack_name(sha1, &name, &base, "pack");
243 char *sha1_pack_index_name(const unsigned char *sha1)
245 static char *name, *base;
247 return sha1_get_pack_name(sha1, &name, &base, "idx");
250 struct alternate_object_database *alt_odb_list;
251 static struct alternate_object_database **alt_odb_tail;
254 * Prepare alternate object database registry.
256 * The variable alt_odb_list points at the list of struct
257 * alternate_object_database. The elements on this list come from
258 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
259 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
260 * whose contents is similar to that environment variable but can be
261 * LF separated. Its base points at a statically allocated buffer that
262 * contains "/the/directory/corresponding/to/.git/objects/...", while
263 * its name points just after the slash at the end of ".git/objects/"
264 * in the example above, and has enough space to hold 40-byte hex
265 * SHA1, an extra slash for the first level indirection, and the
266 * terminating NUL.
268 static int link_alt_odb_entry(const char *entry, const char *relative_base,
269 int depth, const char *normalized_objdir)
271 struct alternate_object_database *ent;
272 struct alternate_object_database *alt;
273 int pfxlen, entlen;
274 struct strbuf pathbuf = STRBUF_INIT;
276 if (!is_absolute_path(entry) && relative_base) {
277 strbuf_addstr(&pathbuf, real_path(relative_base));
278 strbuf_addch(&pathbuf, '/');
280 strbuf_addstr(&pathbuf, entry);
282 normalize_path_copy(pathbuf.buf, pathbuf.buf);
284 pfxlen = strlen(pathbuf.buf);
287 * The trailing slash after the directory name is given by
288 * this function at the end. Remove duplicates.
290 while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
291 pfxlen -= 1;
293 entlen = pfxlen + 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
294 ent = xmalloc(sizeof(*ent) + entlen);
295 memcpy(ent->base, pathbuf.buf, pfxlen);
296 strbuf_release(&pathbuf);
298 ent->name = ent->base + pfxlen + 1;
299 ent->base[pfxlen + 3] = '/';
300 ent->base[pfxlen] = ent->base[entlen-1] = 0;
302 /* Detect cases where alternate disappeared */
303 if (!is_directory(ent->base)) {
304 error("object directory %s does not exist; "
305 "check .git/objects/info/alternates.",
306 ent->base);
307 free(ent);
308 return -1;
311 /* Prevent the common mistake of listing the same
312 * thing twice, or object directory itself.
314 for (alt = alt_odb_list; alt; alt = alt->next) {
315 if (pfxlen == alt->name - alt->base - 1 &&
316 !memcmp(ent->base, alt->base, pfxlen)) {
317 free(ent);
318 return -1;
321 if (!strcmp_icase(ent->base, normalized_objdir)) {
322 free(ent);
323 return -1;
326 /* add the alternate entry */
327 *alt_odb_tail = ent;
328 alt_odb_tail = &(ent->next);
329 ent->next = NULL;
331 /* recursively add alternates */
332 read_info_alternates(ent->base, depth + 1);
334 ent->base[pfxlen] = '/';
336 return 0;
339 static void link_alt_odb_entries(const char *alt, int len, int sep,
340 const char *relative_base, int depth)
342 struct string_list entries = STRING_LIST_INIT_NODUP;
343 char *alt_copy;
344 int i;
345 struct strbuf objdirbuf = STRBUF_INIT;
347 if (depth > 5) {
348 error("%s: ignoring alternate object stores, nesting too deep.",
349 relative_base);
350 return;
353 strbuf_add_absolute_path(&objdirbuf, get_object_directory());
354 normalize_path_copy(objdirbuf.buf, objdirbuf.buf);
356 alt_copy = xmemdupz(alt, len);
357 string_list_split_in_place(&entries, alt_copy, sep, -1);
358 for (i = 0; i < entries.nr; i++) {
359 const char *entry = entries.items[i].string;
360 if (entry[0] == '\0' || entry[0] == '#')
361 continue;
362 if (!is_absolute_path(entry) && depth) {
363 error("%s: ignoring relative alternate object store %s",
364 relative_base, entry);
365 } else {
366 link_alt_odb_entry(entry, relative_base, depth, objdirbuf.buf);
369 string_list_clear(&entries, 0);
370 free(alt_copy);
371 strbuf_release(&objdirbuf);
374 void read_info_alternates(const char * relative_base, int depth)
376 char *map;
377 size_t mapsz;
378 struct stat st;
379 const char alt_file_name[] = "info/alternates";
380 /* Given that relative_base is no longer than PATH_MAX,
381 ensure that "path" has enough space to append "/", the
382 file name, "info/alternates", and a trailing NUL. */
383 char path[PATH_MAX + 1 + sizeof alt_file_name];
384 int fd;
386 sprintf(path, "%s/%s", relative_base, alt_file_name);
387 fd = git_open_noatime(path);
388 if (fd < 0)
389 return;
390 if (fstat(fd, &st) || (st.st_size == 0)) {
391 close(fd);
392 return;
394 mapsz = xsize_t(st.st_size);
395 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
396 close(fd);
398 link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
400 munmap(map, mapsz);
403 void add_to_alternates_file(const char *reference)
405 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
406 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
407 char *alt = mkpath("%s\n", reference);
408 write_or_die(fd, alt, strlen(alt));
409 if (commit_lock_file(lock))
410 die("could not close alternates file");
411 if (alt_odb_tail)
412 link_alt_odb_entries(alt, strlen(alt), '\n', NULL, 0);
415 int foreach_alt_odb(alt_odb_fn fn, void *cb)
417 struct alternate_object_database *ent;
418 int r = 0;
420 prepare_alt_odb();
421 for (ent = alt_odb_list; ent; ent = ent->next) {
422 r = fn(ent, cb);
423 if (r)
424 break;
426 return r;
429 void prepare_alt_odb(void)
431 const char *alt;
433 if (alt_odb_tail)
434 return;
436 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
437 if (!alt) alt = "";
439 alt_odb_tail = &alt_odb_list;
440 link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
442 read_info_alternates(get_object_directory(), 0);
445 static int freshen_file(const char *fn)
447 struct utimbuf t;
448 t.actime = t.modtime = time(NULL);
449 return !utime(fn, &t);
452 static int check_and_freshen_file(const char *fn, int freshen)
454 if (access(fn, F_OK))
455 return 0;
456 if (freshen && freshen_file(fn))
457 return 0;
458 return 1;
461 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
463 return check_and_freshen_file(sha1_file_name(sha1), freshen);
466 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
468 struct alternate_object_database *alt;
469 prepare_alt_odb();
470 for (alt = alt_odb_list; alt; alt = alt->next) {
471 fill_sha1_path(alt->name, sha1);
472 if (check_and_freshen_file(alt->base, freshen))
473 return 1;
475 return 0;
478 static int check_and_freshen(const unsigned char *sha1, int freshen)
480 return check_and_freshen_local(sha1, freshen) ||
481 check_and_freshen_nonlocal(sha1, freshen);
484 int has_loose_object_nonlocal(const unsigned char *sha1)
486 return check_and_freshen_nonlocal(sha1, 0);
489 static int has_loose_object(const unsigned char *sha1)
491 return check_and_freshen(sha1, 0);
494 static unsigned int pack_used_ctr;
495 static unsigned int pack_mmap_calls;
496 static unsigned int peak_pack_open_windows;
497 static unsigned int pack_open_windows;
498 static unsigned int pack_open_fds;
499 static unsigned int pack_max_fds;
500 static size_t peak_pack_mapped;
501 static size_t pack_mapped;
502 struct packed_git *packed_git;
504 void pack_report(void)
506 fprintf(stderr,
507 "pack_report: getpagesize() = %10" SZ_FMT "\n"
508 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
509 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
510 sz_fmt(getpagesize()),
511 sz_fmt(packed_git_window_size),
512 sz_fmt(packed_git_limit));
513 fprintf(stderr,
514 "pack_report: pack_used_ctr = %10u\n"
515 "pack_report: pack_mmap_calls = %10u\n"
516 "pack_report: pack_open_windows = %10u / %10u\n"
517 "pack_report: pack_mapped = "
518 "%10" SZ_FMT " / %10" SZ_FMT "\n",
519 pack_used_ctr,
520 pack_mmap_calls,
521 pack_open_windows, peak_pack_open_windows,
522 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
526 * Open and mmap the index file at path, perform a couple of
527 * consistency checks, then record its information to p. Return 0 on
528 * success.
530 static int check_packed_git_idx(const char *path, struct packed_git *p)
532 void *idx_map;
533 struct pack_idx_header *hdr;
534 size_t idx_size;
535 uint32_t version, nr, i, *index;
536 int fd = git_open_noatime(path);
537 struct stat st;
539 if (fd < 0)
540 return -1;
541 if (fstat(fd, &st)) {
542 close(fd);
543 return -1;
545 idx_size = xsize_t(st.st_size);
546 if (idx_size < 4 * 256 + 20 + 20) {
547 close(fd);
548 return error("index file %s is too small", path);
550 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
551 close(fd);
553 hdr = idx_map;
554 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
555 version = ntohl(hdr->idx_version);
556 if (version < 2 || version > 2) {
557 munmap(idx_map, idx_size);
558 return error("index file %s is version %"PRIu32
559 " and is not supported by this binary"
560 " (try upgrading GIT to a newer version)",
561 path, version);
563 } else
564 version = 1;
566 nr = 0;
567 index = idx_map;
568 if (version > 1)
569 index += 2; /* skip index header */
570 for (i = 0; i < 256; i++) {
571 uint32_t n = ntohl(index[i]);
572 if (n < nr) {
573 munmap(idx_map, idx_size);
574 return error("non-monotonic index %s", path);
576 nr = n;
579 if (version == 1) {
581 * Total size:
582 * - 256 index entries 4 bytes each
583 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
584 * - 20-byte SHA1 of the packfile
585 * - 20-byte SHA1 file checksum
587 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
588 munmap(idx_map, idx_size);
589 return error("wrong index v1 file size in %s", path);
591 } else if (version == 2) {
593 * Minimum size:
594 * - 8 bytes of header
595 * - 256 index entries 4 bytes each
596 * - 20-byte sha1 entry * nr
597 * - 4-byte crc entry * nr
598 * - 4-byte offset entry * nr
599 * - 20-byte SHA1 of the packfile
600 * - 20-byte SHA1 file checksum
601 * And after the 4-byte offset table might be a
602 * variable sized table containing 8-byte entries
603 * for offsets larger than 2^31.
605 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
606 unsigned long max_size = min_size;
607 if (nr)
608 max_size += (nr - 1)*8;
609 if (idx_size < min_size || idx_size > max_size) {
610 munmap(idx_map, idx_size);
611 return error("wrong index v2 file size in %s", path);
613 if (idx_size != min_size &&
615 * make sure we can deal with large pack offsets.
616 * 31-bit signed offset won't be enough, neither
617 * 32-bit unsigned one will be.
619 (sizeof(off_t) <= 4)) {
620 munmap(idx_map, idx_size);
621 return error("pack too large for current definition of off_t in %s", path);
625 p->index_version = version;
626 p->index_data = idx_map;
627 p->index_size = idx_size;
628 p->num_objects = nr;
629 return 0;
632 int open_pack_index(struct packed_git *p)
634 char *idx_name;
635 int ret;
637 if (p->index_data)
638 return 0;
640 idx_name = xstrdup(p->pack_name);
641 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
642 ret = check_packed_git_idx(idx_name, p);
643 free(idx_name);
644 return ret;
647 static void scan_windows(struct packed_git *p,
648 struct packed_git **lru_p,
649 struct pack_window **lru_w,
650 struct pack_window **lru_l)
652 struct pack_window *w, *w_l;
654 for (w_l = NULL, w = p->windows; w; w = w->next) {
655 if (!w->inuse_cnt) {
656 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
657 *lru_p = p;
658 *lru_w = w;
659 *lru_l = w_l;
662 w_l = w;
666 static int unuse_one_window(struct packed_git *current)
668 struct packed_git *p, *lru_p = NULL;
669 struct pack_window *lru_w = NULL, *lru_l = NULL;
671 if (current)
672 scan_windows(current, &lru_p, &lru_w, &lru_l);
673 for (p = packed_git; p; p = p->next)
674 scan_windows(p, &lru_p, &lru_w, &lru_l);
675 if (lru_p) {
676 munmap(lru_w->base, lru_w->len);
677 pack_mapped -= lru_w->len;
678 if (lru_l)
679 lru_l->next = lru_w->next;
680 else
681 lru_p->windows = lru_w->next;
682 free(lru_w);
683 pack_open_windows--;
684 return 1;
686 return 0;
689 void release_pack_memory(size_t need)
691 size_t cur = pack_mapped;
692 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
693 ; /* nothing */
696 static void mmap_limit_check(size_t length)
698 static size_t limit = 0;
699 if (!limit) {
700 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
701 if (!limit)
702 limit = SIZE_MAX;
704 if (length > limit)
705 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
706 (uintmax_t)length, (uintmax_t)limit);
709 void *xmmap(void *start, size_t length,
710 int prot, int flags, int fd, off_t offset)
712 void *ret;
714 mmap_limit_check(length);
715 ret = mmap(start, length, prot, flags, fd, offset);
716 if (ret == MAP_FAILED) {
717 if (!length)
718 return NULL;
719 release_pack_memory(length);
720 ret = mmap(start, length, prot, flags, fd, offset);
721 if (ret == MAP_FAILED)
722 die_errno("Out of memory? mmap failed");
724 return ret;
727 void close_pack_windows(struct packed_git *p)
729 while (p->windows) {
730 struct pack_window *w = p->windows;
732 if (w->inuse_cnt)
733 die("pack '%s' still has open windows to it",
734 p->pack_name);
735 munmap(w->base, w->len);
736 pack_mapped -= w->len;
737 pack_open_windows--;
738 p->windows = w->next;
739 free(w);
744 * The LRU pack is the one with the oldest MRU window, preferring packs
745 * with no used windows, or the oldest mtime if it has no windows allocated.
747 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
749 struct pack_window *w, *this_mru_w;
750 int has_windows_inuse = 0;
753 * Reject this pack if it has windows and the previously selected
754 * one does not. If this pack does not have windows, reject
755 * it if the pack file is newer than the previously selected one.
757 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
758 return;
760 for (w = this_mru_w = p->windows; w; w = w->next) {
762 * Reject this pack if any of its windows are in use,
763 * but the previously selected pack did not have any
764 * inuse windows. Otherwise, record that this pack
765 * has windows in use.
767 if (w->inuse_cnt) {
768 if (*accept_windows_inuse)
769 has_windows_inuse = 1;
770 else
771 return;
774 if (w->last_used > this_mru_w->last_used)
775 this_mru_w = w;
778 * Reject this pack if it has windows that have been
779 * used more recently than the previously selected pack.
780 * If the previously selected pack had windows inuse and
781 * we have not encountered a window in this pack that is
782 * inuse, skip this check since we prefer a pack with no
783 * inuse windows to one that has inuse windows.
785 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
786 this_mru_w->last_used > (*mru_w)->last_used)
787 return;
791 * Select this pack.
793 *mru_w = this_mru_w;
794 *lru_p = p;
795 *accept_windows_inuse = has_windows_inuse;
798 static int close_one_pack(void)
800 struct packed_git *p, *lru_p = NULL;
801 struct pack_window *mru_w = NULL;
802 int accept_windows_inuse = 1;
804 for (p = packed_git; p; p = p->next) {
805 if (p->pack_fd == -1)
806 continue;
807 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
810 if (lru_p) {
811 close(lru_p->pack_fd);
812 pack_open_fds--;
813 lru_p->pack_fd = -1;
814 return 1;
817 return 0;
820 void unuse_pack(struct pack_window **w_cursor)
822 struct pack_window *w = *w_cursor;
823 if (w) {
824 w->inuse_cnt--;
825 *w_cursor = NULL;
829 void close_pack_index(struct packed_git *p)
831 if (p->index_data) {
832 munmap((void *)p->index_data, p->index_size);
833 p->index_data = NULL;
838 * This is used by git-repack in case a newly created pack happens to
839 * contain the same set of objects as an existing one. In that case
840 * the resulting file might be different even if its name would be the
841 * same. It is best to close any reference to the old pack before it is
842 * replaced on disk. Of course no index pointers or windows for given pack
843 * must subsist at this point. If ever objects from this pack are requested
844 * again, the new version of the pack will be reinitialized through
845 * reprepare_packed_git().
847 void free_pack_by_name(const char *pack_name)
849 struct packed_git *p, **pp = &packed_git;
851 while (*pp) {
852 p = *pp;
853 if (strcmp(pack_name, p->pack_name) == 0) {
854 clear_delta_base_cache();
855 close_pack_windows(p);
856 if (p->pack_fd != -1) {
857 close(p->pack_fd);
858 pack_open_fds--;
860 close_pack_index(p);
861 free(p->bad_object_sha1);
862 *pp = p->next;
863 if (last_found_pack == p)
864 last_found_pack = NULL;
865 free(p);
866 return;
868 pp = &p->next;
872 static unsigned int get_max_fd_limit(void)
874 #ifdef RLIMIT_NOFILE
876 struct rlimit lim;
878 if (!getrlimit(RLIMIT_NOFILE, &lim))
879 return lim.rlim_cur;
881 #endif
883 #ifdef _SC_OPEN_MAX
885 long open_max = sysconf(_SC_OPEN_MAX);
886 if (0 < open_max)
887 return open_max;
889 * Otherwise, we got -1 for one of the two
890 * reasons:
892 * (1) sysconf() did not understand _SC_OPEN_MAX
893 * and signaled an error with -1; or
894 * (2) sysconf() said there is no limit.
896 * We _could_ clear errno before calling sysconf() to
897 * tell these two cases apart and return a huge number
898 * in the latter case to let the caller cap it to a
899 * value that is not so selfish, but letting the
900 * fallback OPEN_MAX codepath take care of these cases
901 * is a lot simpler.
904 #endif
906 #ifdef OPEN_MAX
907 return OPEN_MAX;
908 #else
909 return 1; /* see the caller ;-) */
910 #endif
914 * Do not call this directly as this leaks p->pack_fd on error return;
915 * call open_packed_git() instead.
917 static int open_packed_git_1(struct packed_git *p)
919 struct stat st;
920 struct pack_header hdr;
921 unsigned char sha1[20];
922 unsigned char *idx_sha1;
923 long fd_flag;
925 if (!p->index_data && open_pack_index(p))
926 return error("packfile %s index unavailable", p->pack_name);
928 if (!pack_max_fds) {
929 unsigned int max_fds = get_max_fd_limit();
931 /* Save 3 for stdin/stdout/stderr, 22 for work */
932 if (25 < max_fds)
933 pack_max_fds = max_fds - 25;
934 else
935 pack_max_fds = 1;
938 while (pack_max_fds <= pack_open_fds && close_one_pack())
939 ; /* nothing */
941 p->pack_fd = git_open_noatime(p->pack_name);
942 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
943 return -1;
944 pack_open_fds++;
946 /* If we created the struct before we had the pack we lack size. */
947 if (!p->pack_size) {
948 if (!S_ISREG(st.st_mode))
949 return error("packfile %s not a regular file", p->pack_name);
950 p->pack_size = st.st_size;
951 } else if (p->pack_size != st.st_size)
952 return error("packfile %s size changed", p->pack_name);
954 /* We leave these file descriptors open with sliding mmap;
955 * there is no point keeping them open across exec(), though.
957 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
958 if (fd_flag < 0)
959 return error("cannot determine file descriptor flags");
960 fd_flag |= FD_CLOEXEC;
961 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
962 return error("cannot set FD_CLOEXEC");
964 /* Verify we recognize this pack file format. */
965 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
966 return error("file %s is far too short to be a packfile", p->pack_name);
967 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
968 return error("file %s is not a GIT packfile", p->pack_name);
969 if (!pack_version_ok(hdr.hdr_version))
970 return error("packfile %s is version %"PRIu32" and not"
971 " supported (try upgrading GIT to a newer version)",
972 p->pack_name, ntohl(hdr.hdr_version));
974 /* Verify the pack matches its index. */
975 if (p->num_objects != ntohl(hdr.hdr_entries))
976 return error("packfile %s claims to have %"PRIu32" objects"
977 " while index indicates %"PRIu32" objects",
978 p->pack_name, ntohl(hdr.hdr_entries),
979 p->num_objects);
980 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
981 return error("end of packfile %s is unavailable", p->pack_name);
982 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
983 return error("packfile %s signature is unavailable", p->pack_name);
984 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
985 if (hashcmp(sha1, idx_sha1))
986 return error("packfile %s does not match index", p->pack_name);
987 return 0;
990 static int open_packed_git(struct packed_git *p)
992 if (!open_packed_git_1(p))
993 return 0;
994 if (p->pack_fd != -1) {
995 close(p->pack_fd);
996 pack_open_fds--;
997 p->pack_fd = -1;
999 return -1;
1002 static int in_window(struct pack_window *win, off_t offset)
1004 /* We must promise at least 20 bytes (one hash) after the
1005 * offset is available from this window, otherwise the offset
1006 * is not actually in this window and a different window (which
1007 * has that one hash excess) must be used. This is to support
1008 * the object header and delta base parsing routines below.
1010 off_t win_off = win->offset;
1011 return win_off <= offset
1012 && (offset + 20) <= (win_off + win->len);
1015 unsigned char *use_pack(struct packed_git *p,
1016 struct pack_window **w_cursor,
1017 off_t offset,
1018 unsigned long *left)
1020 struct pack_window *win = *w_cursor;
1022 /* Since packfiles end in a hash of their content and it's
1023 * pointless to ask for an offset into the middle of that
1024 * hash, and the in_window function above wouldn't match
1025 * don't allow an offset too close to the end of the file.
1027 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1028 die("packfile %s cannot be accessed", p->pack_name);
1029 if (offset > (p->pack_size - 20))
1030 die("offset beyond end of packfile (truncated pack?)");
1032 if (!win || !in_window(win, offset)) {
1033 if (win)
1034 win->inuse_cnt--;
1035 for (win = p->windows; win; win = win->next) {
1036 if (in_window(win, offset))
1037 break;
1039 if (!win) {
1040 size_t window_align = packed_git_window_size / 2;
1041 off_t len;
1043 if (p->pack_fd == -1 && open_packed_git(p))
1044 die("packfile %s cannot be accessed", p->pack_name);
1046 win = xcalloc(1, sizeof(*win));
1047 win->offset = (offset / window_align) * window_align;
1048 len = p->pack_size - win->offset;
1049 if (len > packed_git_window_size)
1050 len = packed_git_window_size;
1051 win->len = (size_t)len;
1052 pack_mapped += win->len;
1053 while (packed_git_limit < pack_mapped
1054 && unuse_one_window(p))
1055 ; /* nothing */
1056 win->base = xmmap(NULL, win->len,
1057 PROT_READ, MAP_PRIVATE,
1058 p->pack_fd, win->offset);
1059 if (win->base == MAP_FAILED)
1060 die("packfile %s cannot be mapped: %s",
1061 p->pack_name,
1062 strerror(errno));
1063 if (!win->offset && win->len == p->pack_size
1064 && !p->do_not_close) {
1065 close(p->pack_fd);
1066 pack_open_fds--;
1067 p->pack_fd = -1;
1069 pack_mmap_calls++;
1070 pack_open_windows++;
1071 if (pack_mapped > peak_pack_mapped)
1072 peak_pack_mapped = pack_mapped;
1073 if (pack_open_windows > peak_pack_open_windows)
1074 peak_pack_open_windows = pack_open_windows;
1075 win->next = p->windows;
1076 p->windows = win;
1079 if (win != *w_cursor) {
1080 win->last_used = pack_used_ctr++;
1081 win->inuse_cnt++;
1082 *w_cursor = win;
1084 offset -= win->offset;
1085 if (left)
1086 *left = win->len - xsize_t(offset);
1087 return win->base + offset;
1090 static struct packed_git *alloc_packed_git(int extra)
1092 struct packed_git *p = xmalloc(sizeof(*p) + extra);
1093 memset(p, 0, sizeof(*p));
1094 p->pack_fd = -1;
1095 return p;
1098 static void try_to_free_pack_memory(size_t size)
1100 release_pack_memory(size);
1103 struct packed_git *add_packed_git(const char *path, int path_len, int local)
1105 static int have_set_try_to_free_routine;
1106 struct stat st;
1107 struct packed_git *p = alloc_packed_git(path_len + 2);
1109 if (!have_set_try_to_free_routine) {
1110 have_set_try_to_free_routine = 1;
1111 set_try_to_free_routine(try_to_free_pack_memory);
1115 * Make sure a corresponding .pack file exists and that
1116 * the index looks sane.
1118 path_len -= strlen(".idx");
1119 if (path_len < 1) {
1120 free(p);
1121 return NULL;
1123 memcpy(p->pack_name, path, path_len);
1125 strcpy(p->pack_name + path_len, ".keep");
1126 if (!access(p->pack_name, F_OK))
1127 p->pack_keep = 1;
1129 strcpy(p->pack_name + path_len, ".pack");
1130 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1131 free(p);
1132 return NULL;
1135 /* ok, it looks sane as far as we can check without
1136 * actually mapping the pack file.
1138 p->pack_size = st.st_size;
1139 p->pack_local = local;
1140 p->mtime = st.st_mtime;
1141 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1142 hashclr(p->sha1);
1143 return p;
1146 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1148 const char *path = sha1_pack_name(sha1);
1149 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
1151 strcpy(p->pack_name, path);
1152 hashcpy(p->sha1, sha1);
1153 if (check_packed_git_idx(idx_path, p)) {
1154 free(p);
1155 return NULL;
1158 return p;
1161 void install_packed_git(struct packed_git *pack)
1163 if (pack->pack_fd != -1)
1164 pack_open_fds++;
1166 pack->next = packed_git;
1167 packed_git = pack;
1170 void (*report_garbage)(const char *desc, const char *path);
1172 static void report_helper(const struct string_list *list,
1173 int seen_bits, int first, int last)
1175 const char *msg;
1176 switch (seen_bits) {
1177 case 0:
1178 msg = "no corresponding .idx or .pack";
1179 break;
1180 case 1:
1181 msg = "no corresponding .idx";
1182 break;
1183 case 2:
1184 msg = "no corresponding .pack";
1185 break;
1186 default:
1187 return;
1189 for (; first < last; first++)
1190 report_garbage(msg, list->items[first].string);
1193 static void report_pack_garbage(struct string_list *list)
1195 int i, baselen = -1, first = 0, seen_bits = 0;
1197 if (!report_garbage)
1198 return;
1200 sort_string_list(list);
1202 for (i = 0; i < list->nr; i++) {
1203 const char *path = list->items[i].string;
1204 if (baselen != -1 &&
1205 strncmp(path, list->items[first].string, baselen)) {
1206 report_helper(list, seen_bits, first, i);
1207 baselen = -1;
1208 seen_bits = 0;
1210 if (baselen == -1) {
1211 const char *dot = strrchr(path, '.');
1212 if (!dot) {
1213 report_garbage("garbage found", path);
1214 continue;
1216 baselen = dot - path + 1;
1217 first = i;
1219 if (!strcmp(path + baselen, "pack"))
1220 seen_bits |= 1;
1221 else if (!strcmp(path + baselen, "idx"))
1222 seen_bits |= 2;
1224 report_helper(list, seen_bits, first, list->nr);
1227 static void prepare_packed_git_one(char *objdir, int local)
1229 struct strbuf path = STRBUF_INIT;
1230 size_t dirnamelen;
1231 DIR *dir;
1232 struct dirent *de;
1233 struct string_list garbage = STRING_LIST_INIT_DUP;
1235 strbuf_addstr(&path, objdir);
1236 strbuf_addstr(&path, "/pack");
1237 dir = opendir(path.buf);
1238 if (!dir) {
1239 if (errno != ENOENT)
1240 error("unable to open object pack directory: %s: %s",
1241 path.buf, strerror(errno));
1242 strbuf_release(&path);
1243 return;
1245 strbuf_addch(&path, '/');
1246 dirnamelen = path.len;
1247 while ((de = readdir(dir)) != NULL) {
1248 struct packed_git *p;
1249 size_t base_len;
1251 if (is_dot_or_dotdot(de->d_name))
1252 continue;
1254 strbuf_setlen(&path, dirnamelen);
1255 strbuf_addstr(&path, de->d_name);
1257 base_len = path.len;
1258 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1259 /* Don't reopen a pack we already have. */
1260 for (p = packed_git; p; p = p->next) {
1261 size_t len;
1262 if (strip_suffix(p->pack_name, ".pack", &len) &&
1263 len == base_len &&
1264 !memcmp(p->pack_name, path.buf, len))
1265 break;
1267 if (p == NULL &&
1269 * See if it really is a valid .idx file with
1270 * corresponding .pack file that we can map.
1272 (p = add_packed_git(path.buf, path.len, local)) != NULL)
1273 install_packed_git(p);
1276 if (!report_garbage)
1277 continue;
1279 if (ends_with(de->d_name, ".idx") ||
1280 ends_with(de->d_name, ".pack") ||
1281 ends_with(de->d_name, ".bitmap") ||
1282 ends_with(de->d_name, ".keep"))
1283 string_list_append(&garbage, path.buf);
1284 else
1285 report_garbage("garbage found", path.buf);
1287 closedir(dir);
1288 report_pack_garbage(&garbage);
1289 string_list_clear(&garbage, 0);
1290 strbuf_release(&path);
1293 static int sort_pack(const void *a_, const void *b_)
1295 struct packed_git *a = *((struct packed_git **)a_);
1296 struct packed_git *b = *((struct packed_git **)b_);
1297 int st;
1300 * Local packs tend to contain objects specific to our
1301 * variant of the project than remote ones. In addition,
1302 * remote ones could be on a network mounted filesystem.
1303 * Favor local ones for these reasons.
1305 st = a->pack_local - b->pack_local;
1306 if (st)
1307 return -st;
1310 * Younger packs tend to contain more recent objects,
1311 * and more recent objects tend to get accessed more
1312 * often.
1314 if (a->mtime < b->mtime)
1315 return 1;
1316 else if (a->mtime == b->mtime)
1317 return 0;
1318 return -1;
1321 static void rearrange_packed_git(void)
1323 struct packed_git **ary, *p;
1324 int i, n;
1326 for (n = 0, p = packed_git; p; p = p->next)
1327 n++;
1328 if (n < 2)
1329 return;
1331 /* prepare an array of packed_git for easier sorting */
1332 ary = xcalloc(n, sizeof(struct packed_git *));
1333 for (n = 0, p = packed_git; p; p = p->next)
1334 ary[n++] = p;
1336 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1338 /* link them back again */
1339 for (i = 0; i < n - 1; i++)
1340 ary[i]->next = ary[i + 1];
1341 ary[n - 1]->next = NULL;
1342 packed_git = ary[0];
1344 free(ary);
1347 static int prepare_packed_git_run_once = 0;
1348 void prepare_packed_git(void)
1350 struct alternate_object_database *alt;
1352 if (prepare_packed_git_run_once)
1353 return;
1354 prepare_packed_git_one(get_object_directory(), 1);
1355 prepare_alt_odb();
1356 for (alt = alt_odb_list; alt; alt = alt->next) {
1357 alt->name[-1] = 0;
1358 prepare_packed_git_one(alt->base, 0);
1359 alt->name[-1] = '/';
1361 rearrange_packed_git();
1362 prepare_packed_git_run_once = 1;
1365 void reprepare_packed_git(void)
1367 prepare_packed_git_run_once = 0;
1368 prepare_packed_git();
1371 static void mark_bad_packed_object(struct packed_git *p,
1372 const unsigned char *sha1)
1374 unsigned i;
1375 for (i = 0; i < p->num_bad_objects; i++)
1376 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1377 return;
1378 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1379 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1380 p->num_bad_objects++;
1383 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1385 struct packed_git *p;
1386 unsigned i;
1388 for (p = packed_git; p; p = p->next)
1389 for (i = 0; i < p->num_bad_objects; i++)
1390 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1391 return p;
1392 return NULL;
1396 * With an in-core object data in "map", rehash it to make sure the
1397 * object name actually matches "sha1" to detect object corruption.
1398 * With "map" == NULL, try reading the object named with "sha1" using
1399 * the streaming interface and rehash it to do the same.
1401 int check_sha1_signature(const unsigned char *sha1, void *map,
1402 unsigned long size, const char *type)
1404 unsigned char real_sha1[20];
1405 enum object_type obj_type;
1406 struct git_istream *st;
1407 git_SHA_CTX c;
1408 char hdr[32];
1409 int hdrlen;
1411 if (map) {
1412 hash_sha1_file(map, size, type, real_sha1);
1413 return hashcmp(sha1, real_sha1) ? -1 : 0;
1416 st = open_istream(sha1, &obj_type, &size, NULL);
1417 if (!st)
1418 return -1;
1420 /* Generate the header */
1421 hdrlen = sprintf(hdr, "%s %lu", typename(obj_type), size) + 1;
1423 /* Sha1.. */
1424 git_SHA1_Init(&c);
1425 git_SHA1_Update(&c, hdr, hdrlen);
1426 for (;;) {
1427 char buf[1024 * 16];
1428 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1430 if (readlen < 0) {
1431 close_istream(st);
1432 return -1;
1434 if (!readlen)
1435 break;
1436 git_SHA1_Update(&c, buf, readlen);
1438 git_SHA1_Final(real_sha1, &c);
1439 close_istream(st);
1440 return hashcmp(sha1, real_sha1) ? -1 : 0;
1443 int git_open_noatime(const char *name)
1445 static int sha1_file_open_flag = O_NOATIME;
1447 for (;;) {
1448 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1449 if (fd >= 0)
1450 return fd;
1452 /* Might the failure be due to O_NOATIME? */
1453 if (errno != ENOENT && sha1_file_open_flag) {
1454 sha1_file_open_flag = 0;
1455 continue;
1458 return -1;
1462 static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1464 struct alternate_object_database *alt;
1466 if (!lstat(sha1_file_name(sha1), st))
1467 return 0;
1469 prepare_alt_odb();
1470 errno = ENOENT;
1471 for (alt = alt_odb_list; alt; alt = alt->next) {
1472 fill_sha1_path(alt->name, sha1);
1473 if (!lstat(alt->base, st))
1474 return 0;
1477 return -1;
1480 static int open_sha1_file(const unsigned char *sha1)
1482 int fd;
1483 struct alternate_object_database *alt;
1484 int most_interesting_errno;
1486 fd = git_open_noatime(sha1_file_name(sha1));
1487 if (fd >= 0)
1488 return fd;
1489 most_interesting_errno = errno;
1491 prepare_alt_odb();
1492 for (alt = alt_odb_list; alt; alt = alt->next) {
1493 fill_sha1_path(alt->name, sha1);
1494 fd = git_open_noatime(alt->base);
1495 if (fd >= 0)
1496 return fd;
1497 if (most_interesting_errno == ENOENT)
1498 most_interesting_errno = errno;
1500 errno = most_interesting_errno;
1501 return -1;
1504 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1506 void *map;
1507 int fd;
1509 fd = open_sha1_file(sha1);
1510 map = NULL;
1511 if (fd >= 0) {
1512 struct stat st;
1514 if (!fstat(fd, &st)) {
1515 *size = xsize_t(st.st_size);
1516 if (!*size) {
1517 /* mmap() is forbidden on empty files */
1518 error("object file %s is empty", sha1_file_name(sha1));
1519 return NULL;
1521 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1523 close(fd);
1525 return map;
1528 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1529 unsigned long len, enum object_type *type, unsigned long *sizep)
1531 unsigned shift;
1532 unsigned long size, c;
1533 unsigned long used = 0;
1535 c = buf[used++];
1536 *type = (c >> 4) & 7;
1537 size = c & 15;
1538 shift = 4;
1539 while (c & 0x80) {
1540 if (len <= used || bitsizeof(long) <= shift) {
1541 error("bad object header");
1542 size = used = 0;
1543 break;
1545 c = buf[used++];
1546 size += (c & 0x7f) << shift;
1547 shift += 7;
1549 *sizep = size;
1550 return used;
1553 int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1555 /* Get the data stream */
1556 memset(stream, 0, sizeof(*stream));
1557 stream->next_in = map;
1558 stream->avail_in = mapsize;
1559 stream->next_out = buffer;
1560 stream->avail_out = bufsiz;
1562 git_inflate_init(stream);
1563 return git_inflate(stream, 0);
1566 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1568 int bytes = strlen(buffer) + 1;
1569 unsigned char *buf = xmallocz(size);
1570 unsigned long n;
1571 int status = Z_OK;
1573 n = stream->total_out - bytes;
1574 if (n > size)
1575 n = size;
1576 memcpy(buf, (char *) buffer + bytes, n);
1577 bytes = n;
1578 if (bytes <= size) {
1580 * The above condition must be (bytes <= size), not
1581 * (bytes < size). In other words, even though we
1582 * expect no more output and set avail_out to zero,
1583 * the input zlib stream may have bytes that express
1584 * "this concludes the stream", and we *do* want to
1585 * eat that input.
1587 * Otherwise we would not be able to test that we
1588 * consumed all the input to reach the expected size;
1589 * we also want to check that zlib tells us that all
1590 * went well with status == Z_STREAM_END at the end.
1592 stream->next_out = buf + bytes;
1593 stream->avail_out = size - bytes;
1594 while (status == Z_OK)
1595 status = git_inflate(stream, Z_FINISH);
1597 if (status == Z_STREAM_END && !stream->avail_in) {
1598 git_inflate_end(stream);
1599 return buf;
1602 if (status < 0)
1603 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1604 else if (stream->avail_in)
1605 error("garbage at end of loose object '%s'",
1606 sha1_to_hex(sha1));
1607 free(buf);
1608 return NULL;
1612 * We used to just use "sscanf()", but that's actually way
1613 * too permissive for what we want to check. So do an anal
1614 * object header parse by hand.
1616 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1618 char type[10];
1619 int i;
1620 unsigned long size;
1623 * The type can be at most ten bytes (including the
1624 * terminating '\0' that we add), and is followed by
1625 * a space.
1627 i = 0;
1628 for (;;) {
1629 char c = *hdr++;
1630 if (c == ' ')
1631 break;
1632 type[i++] = c;
1633 if (i >= sizeof(type))
1634 return -1;
1636 type[i] = 0;
1639 * The length must follow immediately, and be in canonical
1640 * decimal format (ie "010" is not valid).
1642 size = *hdr++ - '0';
1643 if (size > 9)
1644 return -1;
1645 if (size) {
1646 for (;;) {
1647 unsigned long c = *hdr - '0';
1648 if (c > 9)
1649 break;
1650 hdr++;
1651 size = size * 10 + c;
1654 *sizep = size;
1657 * The length must be followed by a zero byte
1659 return *hdr ? -1 : type_from_string(type);
1662 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1664 int ret;
1665 git_zstream stream;
1666 char hdr[8192];
1668 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1669 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1670 return NULL;
1672 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1675 unsigned long get_size_from_delta(struct packed_git *p,
1676 struct pack_window **w_curs,
1677 off_t curpos)
1679 const unsigned char *data;
1680 unsigned char delta_head[20], *in;
1681 git_zstream stream;
1682 int st;
1684 memset(&stream, 0, sizeof(stream));
1685 stream.next_out = delta_head;
1686 stream.avail_out = sizeof(delta_head);
1688 git_inflate_init(&stream);
1689 do {
1690 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1691 stream.next_in = in;
1692 st = git_inflate(&stream, Z_FINISH);
1693 curpos += stream.next_in - in;
1694 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1695 stream.total_out < sizeof(delta_head));
1696 git_inflate_end(&stream);
1697 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1698 error("delta data unpack-initial failed");
1699 return 0;
1702 /* Examine the initial part of the delta to figure out
1703 * the result size.
1705 data = delta_head;
1707 /* ignore base size */
1708 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1710 /* Read the result size */
1711 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1714 static off_t get_delta_base(struct packed_git *p,
1715 struct pack_window **w_curs,
1716 off_t *curpos,
1717 enum object_type type,
1718 off_t delta_obj_offset)
1720 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1721 off_t base_offset;
1723 /* use_pack() assured us we have [base_info, base_info + 20)
1724 * as a range that we can look at without walking off the
1725 * end of the mapped window. Its actually the hash size
1726 * that is assured. An OFS_DELTA longer than the hash size
1727 * is stupid, as then a REF_DELTA would be smaller to store.
1729 if (type == OBJ_OFS_DELTA) {
1730 unsigned used = 0;
1731 unsigned char c = base_info[used++];
1732 base_offset = c & 127;
1733 while (c & 128) {
1734 base_offset += 1;
1735 if (!base_offset || MSB(base_offset, 7))
1736 return 0; /* overflow */
1737 c = base_info[used++];
1738 base_offset = (base_offset << 7) + (c & 127);
1740 base_offset = delta_obj_offset - base_offset;
1741 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1742 return 0; /* out of bound */
1743 *curpos += used;
1744 } else if (type == OBJ_REF_DELTA) {
1745 /* The base entry _must_ be in the same pack */
1746 base_offset = find_pack_entry_one(base_info, p);
1747 *curpos += 20;
1748 } else
1749 die("I am totally screwed");
1750 return base_offset;
1754 * Like get_delta_base above, but we return the sha1 instead of the pack
1755 * offset. This means it is cheaper for REF deltas (we do not have to do
1756 * the final object lookup), but more expensive for OFS deltas (we
1757 * have to load the revidx to convert the offset back into a sha1).
1759 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1760 struct pack_window **w_curs,
1761 off_t curpos,
1762 enum object_type type,
1763 off_t delta_obj_offset)
1765 if (type == OBJ_REF_DELTA) {
1766 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1767 return base;
1768 } else if (type == OBJ_OFS_DELTA) {
1769 struct revindex_entry *revidx;
1770 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1771 type, delta_obj_offset);
1773 if (!base_offset)
1774 return NULL;
1776 revidx = find_pack_revindex(p, base_offset);
1777 if (!revidx)
1778 return NULL;
1780 return nth_packed_object_sha1(p, revidx->nr);
1781 } else
1782 return NULL;
1785 int unpack_object_header(struct packed_git *p,
1786 struct pack_window **w_curs,
1787 off_t *curpos,
1788 unsigned long *sizep)
1790 unsigned char *base;
1791 unsigned long left;
1792 unsigned long used;
1793 enum object_type type;
1795 /* use_pack() assures us we have [base, base + 20) available
1796 * as a range that we can look at. (Its actually the hash
1797 * size that is assured.) With our object header encoding
1798 * the maximum deflated object size is 2^137, which is just
1799 * insane, so we know won't exceed what we have been given.
1801 base = use_pack(p, w_curs, *curpos, &left);
1802 used = unpack_object_header_buffer(base, left, &type, sizep);
1803 if (!used) {
1804 type = OBJ_BAD;
1805 } else
1806 *curpos += used;
1808 return type;
1811 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1813 int type;
1814 struct revindex_entry *revidx;
1815 const unsigned char *sha1;
1816 revidx = find_pack_revindex(p, obj_offset);
1817 if (!revidx)
1818 return OBJ_BAD;
1819 sha1 = nth_packed_object_sha1(p, revidx->nr);
1820 mark_bad_packed_object(p, sha1);
1821 type = sha1_object_info(sha1, NULL);
1822 if (type <= OBJ_NONE)
1823 return OBJ_BAD;
1824 return type;
1827 #define POI_STACK_PREALLOC 64
1829 static enum object_type packed_to_object_type(struct packed_git *p,
1830 off_t obj_offset,
1831 enum object_type type,
1832 struct pack_window **w_curs,
1833 off_t curpos)
1835 off_t small_poi_stack[POI_STACK_PREALLOC];
1836 off_t *poi_stack = small_poi_stack;
1837 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1839 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1840 off_t base_offset;
1841 unsigned long size;
1842 /* Push the object we're going to leave behind */
1843 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1844 poi_stack_alloc = alloc_nr(poi_stack_nr);
1845 poi_stack = xmalloc(sizeof(off_t)*poi_stack_alloc);
1846 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1847 } else {
1848 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1850 poi_stack[poi_stack_nr++] = obj_offset;
1851 /* If parsing the base offset fails, just unwind */
1852 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1853 if (!base_offset)
1854 goto unwind;
1855 curpos = obj_offset = base_offset;
1856 type = unpack_object_header(p, w_curs, &curpos, &size);
1857 if (type <= OBJ_NONE) {
1858 /* If getting the base itself fails, we first
1859 * retry the base, otherwise unwind */
1860 type = retry_bad_packed_offset(p, base_offset);
1861 if (type > OBJ_NONE)
1862 goto out;
1863 goto unwind;
1867 switch (type) {
1868 case OBJ_BAD:
1869 case OBJ_COMMIT:
1870 case OBJ_TREE:
1871 case OBJ_BLOB:
1872 case OBJ_TAG:
1873 break;
1874 default:
1875 error("unknown object type %i at offset %"PRIuMAX" in %s",
1876 type, (uintmax_t)obj_offset, p->pack_name);
1877 type = OBJ_BAD;
1880 out:
1881 if (poi_stack != small_poi_stack)
1882 free(poi_stack);
1883 return type;
1885 unwind:
1886 while (poi_stack_nr) {
1887 obj_offset = poi_stack[--poi_stack_nr];
1888 type = retry_bad_packed_offset(p, obj_offset);
1889 if (type > OBJ_NONE)
1890 goto out;
1892 type = OBJ_BAD;
1893 goto out;
1896 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1897 struct object_info *oi)
1899 struct pack_window *w_curs = NULL;
1900 unsigned long size;
1901 off_t curpos = obj_offset;
1902 enum object_type type;
1905 * We always get the representation type, but only convert it to
1906 * a "real" type later if the caller is interested.
1908 type = unpack_object_header(p, &w_curs, &curpos, &size);
1910 if (oi->sizep) {
1911 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1912 off_t tmp_pos = curpos;
1913 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1914 type, obj_offset);
1915 if (!base_offset) {
1916 type = OBJ_BAD;
1917 goto out;
1919 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1920 if (*oi->sizep == 0) {
1921 type = OBJ_BAD;
1922 goto out;
1924 } else {
1925 *oi->sizep = size;
1929 if (oi->disk_sizep) {
1930 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1931 *oi->disk_sizep = revidx[1].offset - obj_offset;
1934 if (oi->typep) {
1935 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
1936 if (*oi->typep < 0) {
1937 type = OBJ_BAD;
1938 goto out;
1942 if (oi->delta_base_sha1) {
1943 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1944 const unsigned char *base;
1946 base = get_delta_base_sha1(p, &w_curs, curpos,
1947 type, obj_offset);
1948 if (!base) {
1949 type = OBJ_BAD;
1950 goto out;
1953 hashcpy(oi->delta_base_sha1, base);
1954 } else
1955 hashclr(oi->delta_base_sha1);
1958 out:
1959 unuse_pack(&w_curs);
1960 return type;
1963 static void *unpack_compressed_entry(struct packed_git *p,
1964 struct pack_window **w_curs,
1965 off_t curpos,
1966 unsigned long size)
1968 int st;
1969 git_zstream stream;
1970 unsigned char *buffer, *in;
1972 buffer = xmallocz_gently(size);
1973 if (!buffer)
1974 return NULL;
1975 memset(&stream, 0, sizeof(stream));
1976 stream.next_out = buffer;
1977 stream.avail_out = size + 1;
1979 git_inflate_init(&stream);
1980 do {
1981 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1982 stream.next_in = in;
1983 st = git_inflate(&stream, Z_FINISH);
1984 if (!stream.avail_out)
1985 break; /* the payload is larger than it should be */
1986 curpos += stream.next_in - in;
1987 } while (st == Z_OK || st == Z_BUF_ERROR);
1988 git_inflate_end(&stream);
1989 if ((st != Z_STREAM_END) || stream.total_out != size) {
1990 free(buffer);
1991 return NULL;
1994 return buffer;
1997 #define MAX_DELTA_CACHE (256)
1999 static size_t delta_base_cached;
2001 static struct delta_base_cache_lru_list {
2002 struct delta_base_cache_lru_list *prev;
2003 struct delta_base_cache_lru_list *next;
2004 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
2006 static struct delta_base_cache_entry {
2007 struct delta_base_cache_lru_list lru;
2008 void *data;
2009 struct packed_git *p;
2010 off_t base_offset;
2011 unsigned long size;
2012 enum object_type type;
2013 } delta_base_cache[MAX_DELTA_CACHE];
2015 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
2017 unsigned long hash;
2019 hash = (unsigned long)p + (unsigned long)base_offset;
2020 hash += (hash >> 8) + (hash >> 16);
2021 return hash % MAX_DELTA_CACHE;
2024 static struct delta_base_cache_entry *
2025 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2027 unsigned long hash = pack_entry_hash(p, base_offset);
2028 return delta_base_cache + hash;
2031 static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
2032 struct packed_git *p, off_t base_offset)
2034 return (ent->data && ent->p == p && ent->base_offset == base_offset);
2037 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2039 struct delta_base_cache_entry *ent;
2040 ent = get_delta_base_cache_entry(p, base_offset);
2041 return eq_delta_base_cache_entry(ent, p, base_offset);
2044 static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2046 ent->data = NULL;
2047 ent->lru.next->prev = ent->lru.prev;
2048 ent->lru.prev->next = ent->lru.next;
2049 delta_base_cached -= ent->size;
2052 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2053 unsigned long *base_size, enum object_type *type, int keep_cache)
2055 struct delta_base_cache_entry *ent;
2056 void *ret;
2058 ent = get_delta_base_cache_entry(p, base_offset);
2060 if (!eq_delta_base_cache_entry(ent, p, base_offset))
2061 return unpack_entry(p, base_offset, type, base_size);
2063 ret = ent->data;
2065 if (!keep_cache)
2066 clear_delta_base_cache_entry(ent);
2067 else
2068 ret = xmemdupz(ent->data, ent->size);
2069 *type = ent->type;
2070 *base_size = ent->size;
2071 return ret;
2074 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2076 if (ent->data) {
2077 free(ent->data);
2078 ent->data = NULL;
2079 ent->lru.next->prev = ent->lru.prev;
2080 ent->lru.prev->next = ent->lru.next;
2081 delta_base_cached -= ent->size;
2085 void clear_delta_base_cache(void)
2087 unsigned long p;
2088 for (p = 0; p < MAX_DELTA_CACHE; p++)
2089 release_delta_base_cache(&delta_base_cache[p]);
2092 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2093 void *base, unsigned long base_size, enum object_type type)
2095 unsigned long hash = pack_entry_hash(p, base_offset);
2096 struct delta_base_cache_entry *ent = delta_base_cache + hash;
2097 struct delta_base_cache_lru_list *lru;
2099 release_delta_base_cache(ent);
2100 delta_base_cached += base_size;
2102 for (lru = delta_base_cache_lru.next;
2103 delta_base_cached > delta_base_cache_limit
2104 && lru != &delta_base_cache_lru;
2105 lru = lru->next) {
2106 struct delta_base_cache_entry *f = (void *)lru;
2107 if (f->type == OBJ_BLOB)
2108 release_delta_base_cache(f);
2110 for (lru = delta_base_cache_lru.next;
2111 delta_base_cached > delta_base_cache_limit
2112 && lru != &delta_base_cache_lru;
2113 lru = lru->next) {
2114 struct delta_base_cache_entry *f = (void *)lru;
2115 release_delta_base_cache(f);
2118 ent->p = p;
2119 ent->base_offset = base_offset;
2120 ent->type = type;
2121 ent->data = base;
2122 ent->size = base_size;
2123 ent->lru.next = &delta_base_cache_lru;
2124 ent->lru.prev = delta_base_cache_lru.prev;
2125 delta_base_cache_lru.prev->next = &ent->lru;
2126 delta_base_cache_lru.prev = &ent->lru;
2129 static void *read_object(const unsigned char *sha1, enum object_type *type,
2130 unsigned long *size);
2132 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2134 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2135 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2136 p->pack_name, (uintmax_t)obj_offset);
2139 int do_check_packed_object_crc;
2141 #define UNPACK_ENTRY_STACK_PREALLOC 64
2142 struct unpack_entry_stack_ent {
2143 off_t obj_offset;
2144 off_t curpos;
2145 unsigned long size;
2148 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2149 enum object_type *final_type, unsigned long *final_size)
2151 struct pack_window *w_curs = NULL;
2152 off_t curpos = obj_offset;
2153 void *data = NULL;
2154 unsigned long size;
2155 enum object_type type;
2156 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2157 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2158 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2159 int base_from_cache = 0;
2161 write_pack_access_log(p, obj_offset);
2163 /* PHASE 1: drill down to the innermost base object */
2164 for (;;) {
2165 off_t base_offset;
2166 int i;
2167 struct delta_base_cache_entry *ent;
2169 ent = get_delta_base_cache_entry(p, curpos);
2170 if (eq_delta_base_cache_entry(ent, p, curpos)) {
2171 type = ent->type;
2172 data = ent->data;
2173 size = ent->size;
2174 clear_delta_base_cache_entry(ent);
2175 base_from_cache = 1;
2176 break;
2179 if (do_check_packed_object_crc && p->index_version > 1) {
2180 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2181 unsigned long len = revidx[1].offset - obj_offset;
2182 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2183 const unsigned char *sha1 =
2184 nth_packed_object_sha1(p, revidx->nr);
2185 error("bad packed object CRC for %s",
2186 sha1_to_hex(sha1));
2187 mark_bad_packed_object(p, sha1);
2188 unuse_pack(&w_curs);
2189 return NULL;
2193 type = unpack_object_header(p, &w_curs, &curpos, &size);
2194 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2195 break;
2197 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2198 if (!base_offset) {
2199 error("failed to validate delta base reference "
2200 "at offset %"PRIuMAX" from %s",
2201 (uintmax_t)curpos, p->pack_name);
2202 /* bail to phase 2, in hopes of recovery */
2203 data = NULL;
2204 break;
2207 /* push object, proceed to base */
2208 if (delta_stack_nr >= delta_stack_alloc
2209 && delta_stack == small_delta_stack) {
2210 delta_stack_alloc = alloc_nr(delta_stack_nr);
2211 delta_stack = xmalloc(sizeof(*delta_stack)*delta_stack_alloc);
2212 memcpy(delta_stack, small_delta_stack,
2213 sizeof(*delta_stack)*delta_stack_nr);
2214 } else {
2215 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2217 i = delta_stack_nr++;
2218 delta_stack[i].obj_offset = obj_offset;
2219 delta_stack[i].curpos = curpos;
2220 delta_stack[i].size = size;
2222 curpos = obj_offset = base_offset;
2225 /* PHASE 2: handle the base */
2226 switch (type) {
2227 case OBJ_OFS_DELTA:
2228 case OBJ_REF_DELTA:
2229 if (data)
2230 die("BUG in unpack_entry: left loop at a valid delta");
2231 break;
2232 case OBJ_COMMIT:
2233 case OBJ_TREE:
2234 case OBJ_BLOB:
2235 case OBJ_TAG:
2236 if (!base_from_cache)
2237 data = unpack_compressed_entry(p, &w_curs, curpos, size);
2238 break;
2239 default:
2240 data = NULL;
2241 error("unknown object type %i at offset %"PRIuMAX" in %s",
2242 type, (uintmax_t)obj_offset, p->pack_name);
2245 /* PHASE 3: apply deltas in order */
2247 /* invariants:
2248 * 'data' holds the base data, or NULL if there was corruption
2250 while (delta_stack_nr) {
2251 void *delta_data;
2252 void *base = data;
2253 unsigned long delta_size, base_size = size;
2254 int i;
2256 data = NULL;
2258 if (base)
2259 add_delta_base_cache(p, obj_offset, base, base_size, type);
2261 if (!base) {
2263 * We're probably in deep shit, but let's try to fetch
2264 * the required base anyway from another pack or loose.
2265 * This is costly but should happen only in the presence
2266 * of a corrupted pack, and is better than failing outright.
2268 struct revindex_entry *revidx;
2269 const unsigned char *base_sha1;
2270 revidx = find_pack_revindex(p, obj_offset);
2271 if (revidx) {
2272 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2273 error("failed to read delta base object %s"
2274 " at offset %"PRIuMAX" from %s",
2275 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2276 p->pack_name);
2277 mark_bad_packed_object(p, base_sha1);
2278 base = read_object(base_sha1, &type, &base_size);
2282 i = --delta_stack_nr;
2283 obj_offset = delta_stack[i].obj_offset;
2284 curpos = delta_stack[i].curpos;
2285 delta_size = delta_stack[i].size;
2287 if (!base)
2288 continue;
2290 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2292 if (!delta_data) {
2293 error("failed to unpack compressed delta "
2294 "at offset %"PRIuMAX" from %s",
2295 (uintmax_t)curpos, p->pack_name);
2296 data = NULL;
2297 continue;
2300 data = patch_delta(base, base_size,
2301 delta_data, delta_size,
2302 &size);
2305 * We could not apply the delta; warn the user, but keep going.
2306 * Our failure will be noticed either in the next iteration of
2307 * the loop, or if this is the final delta, in the caller when
2308 * we return NULL. Those code paths will take care of making
2309 * a more explicit warning and retrying with another copy of
2310 * the object.
2312 if (!data)
2313 error("failed to apply delta");
2315 free(delta_data);
2318 *final_type = type;
2319 *final_size = size;
2321 unuse_pack(&w_curs);
2323 if (delta_stack != small_delta_stack)
2324 free(delta_stack);
2326 return data;
2329 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2330 uint32_t n)
2332 const unsigned char *index = p->index_data;
2333 if (!index) {
2334 if (open_pack_index(p))
2335 return NULL;
2336 index = p->index_data;
2338 if (n >= p->num_objects)
2339 return NULL;
2340 index += 4 * 256;
2341 if (p->index_version == 1) {
2342 return index + 24 * n + 4;
2343 } else {
2344 index += 8;
2345 return index + 20 * n;
2349 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2351 const unsigned char *index = p->index_data;
2352 index += 4 * 256;
2353 if (p->index_version == 1) {
2354 return ntohl(*((uint32_t *)(index + 24 * n)));
2355 } else {
2356 uint32_t off;
2357 index += 8 + p->num_objects * (20 + 4);
2358 off = ntohl(*((uint32_t *)(index + 4 * n)));
2359 if (!(off & 0x80000000))
2360 return off;
2361 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2362 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2363 ntohl(*((uint32_t *)(index + 4)));
2367 off_t find_pack_entry_one(const unsigned char *sha1,
2368 struct packed_git *p)
2370 const uint32_t *level1_ofs = p->index_data;
2371 const unsigned char *index = p->index_data;
2372 unsigned hi, lo, stride;
2373 static int use_lookup = -1;
2374 static int debug_lookup = -1;
2376 if (debug_lookup < 0)
2377 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2379 if (!index) {
2380 if (open_pack_index(p))
2381 return 0;
2382 level1_ofs = p->index_data;
2383 index = p->index_data;
2385 if (p->index_version > 1) {
2386 level1_ofs += 2;
2387 index += 8;
2389 index += 4 * 256;
2390 hi = ntohl(level1_ofs[*sha1]);
2391 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2392 if (p->index_version > 1) {
2393 stride = 20;
2394 } else {
2395 stride = 24;
2396 index += 4;
2399 if (debug_lookup)
2400 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2401 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2403 if (use_lookup < 0)
2404 use_lookup = !!getenv("GIT_USE_LOOKUP");
2405 if (use_lookup) {
2406 int pos = sha1_entry_pos(index, stride, 0,
2407 lo, hi, p->num_objects, sha1);
2408 if (pos < 0)
2409 return 0;
2410 return nth_packed_object_offset(p, pos);
2413 do {
2414 unsigned mi = (lo + hi) / 2;
2415 int cmp = hashcmp(index + mi * stride, sha1);
2417 if (debug_lookup)
2418 printf("lo %u hi %u rg %u mi %u\n",
2419 lo, hi, hi - lo, mi);
2420 if (!cmp)
2421 return nth_packed_object_offset(p, mi);
2422 if (cmp > 0)
2423 hi = mi;
2424 else
2425 lo = mi+1;
2426 } while (lo < hi);
2427 return 0;
2430 int is_pack_valid(struct packed_git *p)
2432 /* An already open pack is known to be valid. */
2433 if (p->pack_fd != -1)
2434 return 1;
2436 /* If the pack has one window completely covering the
2437 * file size, the pack is known to be valid even if
2438 * the descriptor is not currently open.
2440 if (p->windows) {
2441 struct pack_window *w = p->windows;
2443 if (!w->offset && w->len == p->pack_size)
2444 return 1;
2447 /* Force the pack to open to prove its valid. */
2448 return !open_packed_git(p);
2451 static int fill_pack_entry(const unsigned char *sha1,
2452 struct pack_entry *e,
2453 struct packed_git *p)
2455 off_t offset;
2457 if (p->num_bad_objects) {
2458 unsigned i;
2459 for (i = 0; i < p->num_bad_objects; i++)
2460 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2461 return 0;
2464 offset = find_pack_entry_one(sha1, p);
2465 if (!offset)
2466 return 0;
2469 * We are about to tell the caller where they can locate the
2470 * requested object. We better make sure the packfile is
2471 * still here and can be accessed before supplying that
2472 * answer, as it may have been deleted since the index was
2473 * loaded!
2475 if (!is_pack_valid(p)) {
2476 warning("packfile %s cannot be accessed", p->pack_name);
2477 return 0;
2479 e->offset = offset;
2480 e->p = p;
2481 hashcpy(e->sha1, sha1);
2482 return 1;
2486 * Iff a pack file contains the object named by sha1, return true and
2487 * store its location to e.
2489 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2491 struct packed_git *p;
2493 prepare_packed_git();
2494 if (!packed_git)
2495 return 0;
2497 if (last_found_pack && fill_pack_entry(sha1, e, last_found_pack))
2498 return 1;
2500 for (p = packed_git; p; p = p->next) {
2501 if (p == last_found_pack)
2502 continue; /* we already checked this one */
2504 if (fill_pack_entry(sha1, e, p)) {
2505 last_found_pack = p;
2506 return 1;
2509 return 0;
2512 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2513 struct packed_git *packs)
2515 struct packed_git *p;
2517 for (p = packs; p; p = p->next) {
2518 if (find_pack_entry_one(sha1, p))
2519 return p;
2521 return NULL;
2525 static int sha1_loose_object_info(const unsigned char *sha1,
2526 struct object_info *oi)
2528 int status;
2529 unsigned long mapsize, size;
2530 void *map;
2531 git_zstream stream;
2532 char hdr[32];
2534 if (oi->delta_base_sha1)
2535 hashclr(oi->delta_base_sha1);
2538 * If we don't care about type or size, then we don't
2539 * need to look inside the object at all. Note that we
2540 * do not optimize out the stat call, even if the
2541 * caller doesn't care about the disk-size, since our
2542 * return value implicitly indicates whether the
2543 * object even exists.
2545 if (!oi->typep && !oi->sizep) {
2546 struct stat st;
2547 if (stat_sha1_file(sha1, &st) < 0)
2548 return -1;
2549 if (oi->disk_sizep)
2550 *oi->disk_sizep = st.st_size;
2551 return 0;
2554 map = map_sha1_file(sha1, &mapsize);
2555 if (!map)
2556 return -1;
2557 if (oi->disk_sizep)
2558 *oi->disk_sizep = mapsize;
2559 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2560 status = error("unable to unpack %s header",
2561 sha1_to_hex(sha1));
2562 else if ((status = parse_sha1_header(hdr, &size)) < 0)
2563 status = error("unable to parse %s header", sha1_to_hex(sha1));
2564 else if (oi->sizep)
2565 *oi->sizep = size;
2566 git_inflate_end(&stream);
2567 munmap(map, mapsize);
2568 if (oi->typep)
2569 *oi->typep = status;
2570 return 0;
2573 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2575 struct cached_object *co;
2576 struct pack_entry e;
2577 int rtype;
2578 const unsigned char *real = lookup_replace_object_extended(sha1, flags);
2580 co = find_cached_object(real);
2581 if (co) {
2582 if (oi->typep)
2583 *(oi->typep) = co->type;
2584 if (oi->sizep)
2585 *(oi->sizep) = co->size;
2586 if (oi->disk_sizep)
2587 *(oi->disk_sizep) = 0;
2588 if (oi->delta_base_sha1)
2589 hashclr(oi->delta_base_sha1);
2590 oi->whence = OI_CACHED;
2591 return 0;
2594 if (!find_pack_entry(real, &e)) {
2595 /* Most likely it's a loose object. */
2596 if (!sha1_loose_object_info(real, oi)) {
2597 oi->whence = OI_LOOSE;
2598 return 0;
2601 /* Not a loose object; someone else may have just packed it. */
2602 reprepare_packed_git();
2603 if (!find_pack_entry(real, &e))
2604 return -1;
2607 rtype = packed_object_info(e.p, e.offset, oi);
2608 if (rtype < 0) {
2609 mark_bad_packed_object(e.p, real);
2610 return sha1_object_info_extended(real, oi, 0);
2611 } else if (in_delta_base_cache(e.p, e.offset)) {
2612 oi->whence = OI_DBCACHED;
2613 } else {
2614 oi->whence = OI_PACKED;
2615 oi->u.packed.offset = e.offset;
2616 oi->u.packed.pack = e.p;
2617 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2618 rtype == OBJ_OFS_DELTA);
2621 return 0;
2624 /* returns enum object_type or negative */
2625 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2627 enum object_type type;
2628 struct object_info oi = {NULL};
2630 oi.typep = &type;
2631 oi.sizep = sizep;
2632 if (sha1_object_info_extended(sha1, &oi, LOOKUP_REPLACE_OBJECT) < 0)
2633 return -1;
2634 return type;
2637 static void *read_packed_sha1(const unsigned char *sha1,
2638 enum object_type *type, unsigned long *size)
2640 struct pack_entry e;
2641 void *data;
2643 if (!find_pack_entry(sha1, &e))
2644 return NULL;
2645 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2646 if (!data) {
2648 * We're probably in deep shit, but let's try to fetch
2649 * the required object anyway from another pack or loose.
2650 * This should happen only in the presence of a corrupted
2651 * pack, and is better than failing outright.
2653 error("failed to read object %s at offset %"PRIuMAX" from %s",
2654 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2655 mark_bad_packed_object(e.p, sha1);
2656 data = read_object(sha1, type, size);
2658 return data;
2661 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2662 unsigned char *sha1)
2664 struct cached_object *co;
2666 hash_sha1_file(buf, len, typename(type), sha1);
2667 if (has_sha1_file(sha1) || find_cached_object(sha1))
2668 return 0;
2669 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2670 co = &cached_objects[cached_object_nr++];
2671 co->size = len;
2672 co->type = type;
2673 co->buf = xmalloc(len);
2674 memcpy(co->buf, buf, len);
2675 hashcpy(co->sha1, sha1);
2676 return 0;
2679 static void *read_object(const unsigned char *sha1, enum object_type *type,
2680 unsigned long *size)
2682 unsigned long mapsize;
2683 void *map, *buf;
2684 struct cached_object *co;
2686 co = find_cached_object(sha1);
2687 if (co) {
2688 *type = co->type;
2689 *size = co->size;
2690 return xmemdupz(co->buf, co->size);
2693 buf = read_packed_sha1(sha1, type, size);
2694 if (buf)
2695 return buf;
2696 map = map_sha1_file(sha1, &mapsize);
2697 if (map) {
2698 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2699 munmap(map, mapsize);
2700 return buf;
2702 reprepare_packed_git();
2703 return read_packed_sha1(sha1, type, size);
2707 * This function dies on corrupt objects; the callers who want to
2708 * deal with them should arrange to call read_object() and give error
2709 * messages themselves.
2711 void *read_sha1_file_extended(const unsigned char *sha1,
2712 enum object_type *type,
2713 unsigned long *size,
2714 unsigned flag)
2716 void *data;
2717 const struct packed_git *p;
2718 const unsigned char *repl = lookup_replace_object_extended(sha1, flag);
2720 errno = 0;
2721 data = read_object(repl, type, size);
2722 if (data)
2723 return data;
2725 if (errno && errno != ENOENT)
2726 die_errno("failed to read object %s", sha1_to_hex(sha1));
2728 /* die if we replaced an object with one that does not exist */
2729 if (repl != sha1)
2730 die("replacement %s not found for %s",
2731 sha1_to_hex(repl), sha1_to_hex(sha1));
2733 if (has_loose_object(repl)) {
2734 const char *path = sha1_file_name(sha1);
2736 die("loose object %s (stored in %s) is corrupt",
2737 sha1_to_hex(repl), path);
2740 if ((p = has_packed_and_bad(repl)) != NULL)
2741 die("packed object %s (stored in %s) is corrupt",
2742 sha1_to_hex(repl), p->pack_name);
2744 return NULL;
2747 void *read_object_with_reference(const unsigned char *sha1,
2748 const char *required_type_name,
2749 unsigned long *size,
2750 unsigned char *actual_sha1_return)
2752 enum object_type type, required_type;
2753 void *buffer;
2754 unsigned long isize;
2755 unsigned char actual_sha1[20];
2757 required_type = type_from_string(required_type_name);
2758 hashcpy(actual_sha1, sha1);
2759 while (1) {
2760 int ref_length = -1;
2761 const char *ref_type = NULL;
2763 buffer = read_sha1_file(actual_sha1, &type, &isize);
2764 if (!buffer)
2765 return NULL;
2766 if (type == required_type) {
2767 *size = isize;
2768 if (actual_sha1_return)
2769 hashcpy(actual_sha1_return, actual_sha1);
2770 return buffer;
2772 /* Handle references */
2773 else if (type == OBJ_COMMIT)
2774 ref_type = "tree ";
2775 else if (type == OBJ_TAG)
2776 ref_type = "object ";
2777 else {
2778 free(buffer);
2779 return NULL;
2781 ref_length = strlen(ref_type);
2783 if (ref_length + 40 > isize ||
2784 memcmp(buffer, ref_type, ref_length) ||
2785 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2786 free(buffer);
2787 return NULL;
2789 free(buffer);
2790 /* Now we have the ID of the referred-to object in
2791 * actual_sha1. Check again. */
2795 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2796 const char *type, unsigned char *sha1,
2797 char *hdr, int *hdrlen)
2799 git_SHA_CTX c;
2801 /* Generate the header */
2802 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2804 /* Sha1.. */
2805 git_SHA1_Init(&c);
2806 git_SHA1_Update(&c, hdr, *hdrlen);
2807 git_SHA1_Update(&c, buf, len);
2808 git_SHA1_Final(sha1, &c);
2812 * Move the just written object into its final resting place.
2813 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2814 * "moving" is only a part of what it does, when no patch between
2815 * master to pu changes the call sites of this function.
2817 int move_temp_to_file(const char *tmpfile, const char *filename)
2819 int ret = 0;
2821 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2822 goto try_rename;
2823 else if (link(tmpfile, filename))
2824 ret = errno;
2827 * Coda hack - coda doesn't like cross-directory links,
2828 * so we fall back to a rename, which will mean that it
2829 * won't be able to check collisions, but that's not a
2830 * big deal.
2832 * The same holds for FAT formatted media.
2834 * When this succeeds, we just return. We have nothing
2835 * left to unlink.
2837 if (ret && ret != EEXIST) {
2838 try_rename:
2839 if (!rename(tmpfile, filename))
2840 goto out;
2841 ret = errno;
2843 unlink_or_warn(tmpfile);
2844 if (ret) {
2845 if (ret != EEXIST) {
2846 return error("unable to write sha1 filename %s: %s", filename, strerror(ret));
2848 /* FIXME!!! Collision check here ? */
2851 out:
2852 if (adjust_shared_perm(filename))
2853 return error("unable to set permission to '%s'", filename);
2854 return 0;
2857 static int write_buffer(int fd, const void *buf, size_t len)
2859 if (write_in_full(fd, buf, len) < 0)
2860 return error("file write error (%s)", strerror(errno));
2861 return 0;
2864 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2865 unsigned char *sha1)
2867 char hdr[32];
2868 int hdrlen;
2869 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2870 return 0;
2873 /* Finalize a file on disk, and close it. */
2874 static void close_sha1_file(int fd)
2876 if (fsync_object_files)
2877 fsync_or_die(fd, "sha1 file");
2878 if (close(fd) != 0)
2879 die_errno("error when closing sha1 file");
2882 /* Size of directory component, including the ending '/' */
2883 static inline int directory_size(const char *filename)
2885 const char *s = strrchr(filename, '/');
2886 if (!s)
2887 return 0;
2888 return s - filename + 1;
2892 * This creates a temporary file in the same directory as the final
2893 * 'filename'
2895 * We want to avoid cross-directory filename renames, because those
2896 * can have problems on various filesystems (FAT, NFS, Coda).
2898 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2900 int fd, dirlen = directory_size(filename);
2902 if (dirlen + 20 > bufsiz) {
2903 errno = ENAMETOOLONG;
2904 return -1;
2906 memcpy(buffer, filename, dirlen);
2907 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2908 fd = git_mkstemp_mode(buffer, 0444);
2909 if (fd < 0 && dirlen && errno == ENOENT) {
2910 /* Make sure the directory exists */
2911 memcpy(buffer, filename, dirlen);
2912 buffer[dirlen-1] = 0;
2913 if (mkdir(buffer, 0777) && errno != EEXIST)
2914 return -1;
2915 if (adjust_shared_perm(buffer))
2916 return -1;
2918 /* Try again */
2919 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2920 fd = git_mkstemp_mode(buffer, 0444);
2922 return fd;
2925 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2926 const void *buf, unsigned long len, time_t mtime)
2928 int fd, ret;
2929 unsigned char compressed[4096];
2930 git_zstream stream;
2931 git_SHA_CTX c;
2932 unsigned char parano_sha1[20];
2933 static char tmp_file[PATH_MAX];
2934 const char *filename = sha1_file_name(sha1);
2936 fd = create_tmpfile(tmp_file, sizeof(tmp_file), filename);
2937 if (fd < 0) {
2938 if (errno == EACCES)
2939 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2940 else
2941 return error("unable to create temporary file: %s", strerror(errno));
2944 /* Set it up */
2945 memset(&stream, 0, sizeof(stream));
2946 git_deflate_init(&stream, zlib_compression_level);
2947 stream.next_out = compressed;
2948 stream.avail_out = sizeof(compressed);
2949 git_SHA1_Init(&c);
2951 /* First header.. */
2952 stream.next_in = (unsigned char *)hdr;
2953 stream.avail_in = hdrlen;
2954 while (git_deflate(&stream, 0) == Z_OK)
2955 ; /* nothing */
2956 git_SHA1_Update(&c, hdr, hdrlen);
2958 /* Then the data itself.. */
2959 stream.next_in = (void *)buf;
2960 stream.avail_in = len;
2961 do {
2962 unsigned char *in0 = stream.next_in;
2963 ret = git_deflate(&stream, Z_FINISH);
2964 git_SHA1_Update(&c, in0, stream.next_in - in0);
2965 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2966 die("unable to write sha1 file");
2967 stream.next_out = compressed;
2968 stream.avail_out = sizeof(compressed);
2969 } while (ret == Z_OK);
2971 if (ret != Z_STREAM_END)
2972 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2973 ret = git_deflate_end_gently(&stream);
2974 if (ret != Z_OK)
2975 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2976 git_SHA1_Final(parano_sha1, &c);
2977 if (hashcmp(sha1, parano_sha1) != 0)
2978 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2980 close_sha1_file(fd);
2982 if (mtime) {
2983 struct utimbuf utb;
2984 utb.actime = mtime;
2985 utb.modtime = mtime;
2986 if (utime(tmp_file, &utb) < 0)
2987 warning("failed utime() on %s: %s",
2988 tmp_file, strerror(errno));
2991 return move_temp_to_file(tmp_file, filename);
2994 static int freshen_loose_object(const unsigned char *sha1)
2996 return check_and_freshen(sha1, 1);
2999 static int freshen_packed_object(const unsigned char *sha1)
3001 struct pack_entry e;
3002 return find_pack_entry(sha1, &e) && freshen_file(e.p->pack_name);
3005 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
3007 unsigned char sha1[20];
3008 char hdr[32];
3009 int hdrlen;
3011 /* Normally if we have it in the pack then we do not bother writing
3012 * it out into .git/objects/??/?{38} file.
3014 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3015 if (returnsha1)
3016 hashcpy(returnsha1, sha1);
3017 if (freshen_loose_object(sha1) || freshen_packed_object(sha1))
3018 return 0;
3019 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3022 int force_object_loose(const unsigned char *sha1, time_t mtime)
3024 void *buf;
3025 unsigned long len;
3026 enum object_type type;
3027 char hdr[32];
3028 int hdrlen;
3029 int ret;
3031 if (has_loose_object(sha1))
3032 return 0;
3033 buf = read_packed_sha1(sha1, &type, &len);
3034 if (!buf)
3035 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3036 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
3037 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3038 free(buf);
3040 return ret;
3043 int has_pack_index(const unsigned char *sha1)
3045 struct stat st;
3046 if (stat(sha1_pack_index_name(sha1), &st))
3047 return 0;
3048 return 1;
3051 int has_sha1_pack(const unsigned char *sha1)
3053 struct pack_entry e;
3054 return find_pack_entry(sha1, &e);
3057 int has_sha1_file(const unsigned char *sha1)
3059 struct pack_entry e;
3061 if (find_pack_entry(sha1, &e))
3062 return 1;
3063 if (has_loose_object(sha1))
3064 return 1;
3065 reprepare_packed_git();
3066 return find_pack_entry(sha1, &e);
3069 static void check_tree(const void *buf, size_t size)
3071 struct tree_desc desc;
3072 struct name_entry entry;
3074 init_tree_desc(&desc, buf, size);
3075 while (tree_entry(&desc, &entry))
3076 /* do nothing
3077 * tree_entry() will die() on malformed entries */
3081 static void check_commit(const void *buf, size_t size)
3083 struct commit c;
3084 memset(&c, 0, sizeof(c));
3085 if (parse_commit_buffer(&c, buf, size))
3086 die("corrupt commit");
3089 static void check_tag(const void *buf, size_t size)
3091 struct tag t;
3092 memset(&t, 0, sizeof(t));
3093 if (parse_tag_buffer(&t, buf, size))
3094 die("corrupt tag");
3097 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3098 enum object_type type,
3099 const char *path, unsigned flags)
3101 int ret, re_allocated = 0;
3102 int write_object = flags & HASH_WRITE_OBJECT;
3104 if (!type)
3105 type = OBJ_BLOB;
3108 * Convert blobs to git internal format
3110 if ((type == OBJ_BLOB) && path) {
3111 struct strbuf nbuf = STRBUF_INIT;
3112 if (convert_to_git(path, buf, size, &nbuf,
3113 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3114 buf = strbuf_detach(&nbuf, &size);
3115 re_allocated = 1;
3118 if (flags & HASH_FORMAT_CHECK) {
3119 if (type == OBJ_TREE)
3120 check_tree(buf, size);
3121 if (type == OBJ_COMMIT)
3122 check_commit(buf, size);
3123 if (type == OBJ_TAG)
3124 check_tag(buf, size);
3127 if (write_object)
3128 ret = write_sha1_file(buf, size, typename(type), sha1);
3129 else
3130 ret = hash_sha1_file(buf, size, typename(type), sha1);
3131 if (re_allocated)
3132 free(buf);
3133 return ret;
3136 static int index_stream_convert_blob(unsigned char *sha1, int fd,
3137 const char *path, unsigned flags)
3139 int ret;
3140 const int write_object = flags & HASH_WRITE_OBJECT;
3141 struct strbuf sbuf = STRBUF_INIT;
3143 assert(path);
3144 assert(would_convert_to_git_filter_fd(path));
3146 convert_to_git_filter_fd(path, fd, &sbuf,
3147 write_object ? safe_crlf : SAFE_CRLF_FALSE);
3149 if (write_object)
3150 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3151 sha1);
3152 else
3153 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3154 sha1);
3155 strbuf_release(&sbuf);
3156 return ret;
3159 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3160 const char *path, unsigned flags)
3162 struct strbuf sbuf = STRBUF_INIT;
3163 int ret;
3165 if (strbuf_read(&sbuf, fd, 4096) >= 0)
3166 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3167 else
3168 ret = -1;
3169 strbuf_release(&sbuf);
3170 return ret;
3173 #define SMALL_FILE_SIZE (32*1024)
3175 static int index_core(unsigned char *sha1, int fd, size_t size,
3176 enum object_type type, const char *path,
3177 unsigned flags)
3179 int ret;
3181 if (!size) {
3182 ret = index_mem(sha1, NULL, size, type, path, flags);
3183 } else if (size <= SMALL_FILE_SIZE) {
3184 char *buf = xmalloc(size);
3185 if (size == read_in_full(fd, buf, size))
3186 ret = index_mem(sha1, buf, size, type, path, flags);
3187 else
3188 ret = error("short read %s", strerror(errno));
3189 free(buf);
3190 } else {
3191 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3192 ret = index_mem(sha1, buf, size, type, path, flags);
3193 munmap(buf, size);
3195 return ret;
3199 * This creates one packfile per large blob unless bulk-checkin
3200 * machinery is "plugged".
3202 * This also bypasses the usual "convert-to-git" dance, and that is on
3203 * purpose. We could write a streaming version of the converting
3204 * functions and insert that before feeding the data to fast-import
3205 * (or equivalent in-core API described above). However, that is
3206 * somewhat complicated, as we do not know the size of the filter
3207 * result, which we need to know beforehand when writing a git object.
3208 * Since the primary motivation for trying to stream from the working
3209 * tree file and to avoid mmaping it in core is to deal with large
3210 * binary blobs, they generally do not want to get any conversion, and
3211 * callers should avoid this code path when filters are requested.
3213 static int index_stream(unsigned char *sha1, int fd, size_t size,
3214 enum object_type type, const char *path,
3215 unsigned flags)
3217 return index_bulk_checkin(sha1, fd, size, type, path, flags);
3220 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3221 enum object_type type, const char *path, unsigned flags)
3223 int ret;
3226 * Call xsize_t() only when needed to avoid potentially unnecessary
3227 * die() for large files.
3229 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3230 ret = index_stream_convert_blob(sha1, fd, path, flags);
3231 else if (!S_ISREG(st->st_mode))
3232 ret = index_pipe(sha1, fd, type, path, flags);
3233 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3234 (path && would_convert_to_git(path)))
3235 ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3236 flags);
3237 else
3238 ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3239 flags);
3240 close(fd);
3241 return ret;
3244 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3246 int fd;
3247 struct strbuf sb = STRBUF_INIT;
3249 switch (st->st_mode & S_IFMT) {
3250 case S_IFREG:
3251 fd = open(path, O_RDONLY);
3252 if (fd < 0)
3253 return error("open(\"%s\"): %s", path,
3254 strerror(errno));
3255 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3256 return error("%s: failed to insert into database",
3257 path);
3258 break;
3259 case S_IFLNK:
3260 if (strbuf_readlink(&sb, path, st->st_size)) {
3261 char *errstr = strerror(errno);
3262 return error("readlink(\"%s\"): %s", path,
3263 errstr);
3265 if (!(flags & HASH_WRITE_OBJECT))
3266 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3267 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3268 return error("%s: failed to insert into database",
3269 path);
3270 strbuf_release(&sb);
3271 break;
3272 case S_IFDIR:
3273 return resolve_gitlink_ref(path, "HEAD", sha1);
3274 default:
3275 return error("%s: unsupported file type", path);
3277 return 0;
3280 int read_pack_header(int fd, struct pack_header *header)
3282 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3283 /* "eof before pack header was fully read" */
3284 return PH_ERROR_EOF;
3286 if (header->hdr_signature != htonl(PACK_SIGNATURE))
3287 /* "protocol error (pack signature mismatch detected)" */
3288 return PH_ERROR_PACK_SIGNATURE;
3289 if (!pack_version_ok(header->hdr_version))
3290 /* "protocol error (pack version unsupported)" */
3291 return PH_ERROR_PROTOCOL;
3292 return 0;
3295 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3297 enum object_type type = sha1_object_info(sha1, NULL);
3298 if (type < 0)
3299 die("%s is not a valid object", sha1_to_hex(sha1));
3300 if (type != expect)
3301 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3302 typename(expect));
3305 static int for_each_file_in_obj_subdir(int subdir_nr,
3306 struct strbuf *path,
3307 each_loose_object_fn obj_cb,
3308 each_loose_cruft_fn cruft_cb,
3309 each_loose_subdir_fn subdir_cb,
3310 void *data)
3312 size_t baselen = path->len;
3313 DIR *dir = opendir(path->buf);
3314 struct dirent *de;
3315 int r = 0;
3317 if (!dir) {
3318 if (errno == ENOENT)
3319 return 0;
3320 return error("unable to open %s: %s", path->buf, strerror(errno));
3323 while ((de = readdir(dir))) {
3324 if (is_dot_or_dotdot(de->d_name))
3325 continue;
3327 strbuf_setlen(path, baselen);
3328 strbuf_addf(path, "/%s", de->d_name);
3330 if (strlen(de->d_name) == 38) {
3331 char hex[41];
3332 unsigned char sha1[20];
3334 snprintf(hex, sizeof(hex), "%02x%s",
3335 subdir_nr, de->d_name);
3336 if (!get_sha1_hex(hex, sha1)) {
3337 if (obj_cb) {
3338 r = obj_cb(sha1, path->buf, data);
3339 if (r)
3340 break;
3342 continue;
3346 if (cruft_cb) {
3347 r = cruft_cb(de->d_name, path->buf, data);
3348 if (r)
3349 break;
3352 strbuf_setlen(path, baselen);
3354 if (!r && subdir_cb)
3355 r = subdir_cb(subdir_nr, path->buf, data);
3357 closedir(dir);
3358 return r;
3361 int for_each_loose_file_in_objdir(const char *path,
3362 each_loose_object_fn obj_cb,
3363 each_loose_cruft_fn cruft_cb,
3364 each_loose_subdir_fn subdir_cb,
3365 void *data)
3367 struct strbuf buf = STRBUF_INIT;
3368 size_t baselen;
3369 int r = 0;
3370 int i;
3372 strbuf_addstr(&buf, path);
3373 strbuf_addch(&buf, '/');
3374 baselen = buf.len;
3376 for (i = 0; i < 256; i++) {
3377 strbuf_addf(&buf, "%02x", i);
3378 r = for_each_file_in_obj_subdir(i, &buf, obj_cb, cruft_cb,
3379 subdir_cb, data);
3380 strbuf_setlen(&buf, baselen);
3381 if (r)
3382 break;
3385 strbuf_release(&buf);
3386 return r;
3389 struct loose_alt_odb_data {
3390 each_loose_object_fn *cb;
3391 void *data;
3394 static int loose_from_alt_odb(struct alternate_object_database *alt,
3395 void *vdata)
3397 struct loose_alt_odb_data *data = vdata;
3398 return for_each_loose_file_in_objdir(alt->base,
3399 data->cb, NULL, NULL,
3400 data->data);
3403 int for_each_loose_object(each_loose_object_fn cb, void *data)
3405 struct loose_alt_odb_data alt;
3406 int r;
3408 r = for_each_loose_file_in_objdir(get_object_directory(),
3409 cb, NULL, NULL, data);
3410 if (r)
3411 return r;
3413 alt.cb = cb;
3414 alt.data = data;
3415 return foreach_alt_odb(loose_from_alt_odb, &alt);
3418 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3420 uint32_t i;
3421 int r = 0;
3423 for (i = 0; i < p->num_objects; i++) {
3424 const unsigned char *sha1 = nth_packed_object_sha1(p, i);
3426 if (!sha1)
3427 return error("unable to get sha1 of object %u in %s",
3428 i, p->pack_name);
3430 r = cb(sha1, p, i, data);
3431 if (r)
3432 break;
3434 return r;
3437 int for_each_packed_object(each_packed_object_fn cb, void *data)
3439 struct packed_git *p;
3440 int r = 0;
3442 prepare_packed_git();
3443 for (p = packed_git; p; p = p->next) {
3444 r = for_each_object_in_pack(p, cb, data);
3445 if (r)
3446 break;
3448 return r;