sha1_file: avoid overrunning alternate object base string
[git/raj.git] / sha1_file.c
blobdae6433c066e072ecf135c0a08e735cc0e2dfbe3
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];
39 static const char *no_log_pack_access = "no_log_pack_access";
40 static const char *log_pack_access;
43 * This is meant to hold a *small* number of objects that you would
44 * want read_sha1_file() to be able to return, but yet you do not want
45 * to write them into the object store (e.g. a browse-only
46 * application).
48 static struct cached_object {
49 unsigned char sha1[20];
50 enum object_type type;
51 void *buf;
52 unsigned long size;
53 } *cached_objects;
54 static int cached_object_nr, cached_object_alloc;
56 static struct cached_object empty_tree = {
57 EMPTY_TREE_SHA1_BIN_LITERAL,
58 OBJ_TREE,
59 "",
63 static struct packed_git *last_found_pack;
65 static struct cached_object *find_cached_object(const unsigned char *sha1)
67 int i;
68 struct cached_object *co = cached_objects;
70 for (i = 0; i < cached_object_nr; i++, co++) {
71 if (!hashcmp(co->sha1, sha1))
72 return co;
74 if (!hashcmp(sha1, empty_tree.sha1))
75 return &empty_tree;
76 return NULL;
79 int mkdir_in_gitdir(const char *path)
81 if (mkdir(path, 0777)) {
82 int saved_errno = errno;
83 struct stat st;
84 struct strbuf sb = STRBUF_INIT;
86 if (errno != EEXIST)
87 return -1;
89 * Are we looking at a path in a symlinked worktree
90 * whose original repository does not yet have it?
91 * e.g. .git/rr-cache pointing at its original
92 * repository in which the user hasn't performed any
93 * conflict resolution yet?
95 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
96 strbuf_readlink(&sb, path, st.st_size) ||
97 !is_absolute_path(sb.buf) ||
98 mkdir(sb.buf, 0777)) {
99 strbuf_release(&sb);
100 errno = saved_errno;
101 return -1;
103 strbuf_release(&sb);
105 return adjust_shared_perm(path);
108 int safe_create_leading_directories(char *path)
110 char *pos = path + offset_1st_component(path);
111 struct stat st;
113 while (pos) {
114 pos = strchr(pos, '/');
115 if (!pos)
116 break;
117 while (*++pos == '/')
119 if (!*pos)
120 break;
121 *--pos = '\0';
122 if (!stat(path, &st)) {
123 /* path exists */
124 if (!S_ISDIR(st.st_mode)) {
125 *pos = '/';
126 return -3;
129 else if (mkdir(path, 0777)) {
130 if (errno == EEXIST &&
131 !stat(path, &st) && S_ISDIR(st.st_mode)) {
132 ; /* somebody created it since we checked */
133 } else {
134 *pos = '/';
135 return -1;
138 else if (adjust_shared_perm(path)) {
139 *pos = '/';
140 return -2;
142 *pos++ = '/';
144 return 0;
147 int safe_create_leading_directories_const(const char *path)
149 /* path points to cache entries, so xstrdup before messing with it */
150 char *buf = xstrdup(path);
151 int result = safe_create_leading_directories(buf);
152 free(buf);
153 return result;
156 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
158 int i;
159 for (i = 0; i < 20; i++) {
160 static char hex[] = "0123456789abcdef";
161 unsigned int val = sha1[i];
162 char *pos = pathbuf + i*2 + (i > 0);
163 *pos++ = hex[val >> 4];
164 *pos = hex[val & 0xf];
169 * NOTE! This returns a statically allocated buffer, so you have to be
170 * careful about using it. Do an "xstrdup()" if you need to save the
171 * filename.
173 * Also note that this returns the location for creating. Reading
174 * SHA1 file can happen from any alternate directory listed in the
175 * DB_ENVIRONMENT environment variable if it is not found in
176 * the primary object database.
178 char *sha1_file_name(const unsigned char *sha1)
180 static char buf[PATH_MAX];
181 const char *objdir;
182 int len;
184 objdir = get_object_directory();
185 len = strlen(objdir);
187 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
188 if (len + 43 > PATH_MAX)
189 die("insanely long object directory %s", objdir);
190 memcpy(buf, objdir, len);
191 buf[len] = '/';
192 buf[len+3] = '/';
193 buf[len+42] = '\0';
194 fill_sha1_path(buf + len + 1, sha1);
195 return buf;
198 static char *sha1_get_pack_name(const unsigned char *sha1,
199 char **name, char **base, const char *which)
201 static const char hex[] = "0123456789abcdef";
202 char *buf;
203 int i;
205 if (!*base) {
206 const char *sha1_file_directory = get_object_directory();
207 int len = strlen(sha1_file_directory);
208 *base = xmalloc(len + 60);
209 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
210 sha1_file_directory, which);
211 *name = *base + len + 11;
214 buf = *name;
216 for (i = 0; i < 20; i++) {
217 unsigned int val = *sha1++;
218 *buf++ = hex[val >> 4];
219 *buf++ = hex[val & 0xf];
222 return *base;
225 char *sha1_pack_name(const unsigned char *sha1)
227 static char *name, *base;
229 return sha1_get_pack_name(sha1, &name, &base, "pack");
232 char *sha1_pack_index_name(const unsigned char *sha1)
234 static char *name, *base;
236 return sha1_get_pack_name(sha1, &name, &base, "idx");
239 struct alternate_object_database *alt_odb_list;
240 static struct alternate_object_database **alt_odb_tail;
242 static int git_open_noatime(const char *name);
245 * Prepare alternate object database registry.
247 * The variable alt_odb_list points at the list of struct
248 * alternate_object_database. The elements on this list come from
249 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
250 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
251 * whose contents is similar to that environment variable but can be
252 * LF separated. Its base points at a statically allocated buffer that
253 * contains "/the/directory/corresponding/to/.git/objects/...", while
254 * its name points just after the slash at the end of ".git/objects/"
255 * in the example above, and has enough space to hold 40-byte hex
256 * SHA1, an extra slash for the first level indirection, and the
257 * terminating NUL.
259 static int link_alt_odb_entry(const char *entry, const char *relative_base, int depth)
261 const char *objdir = get_object_directory();
262 struct alternate_object_database *ent;
263 struct alternate_object_database *alt;
264 int pfxlen, entlen;
265 struct strbuf pathbuf = STRBUF_INIT;
267 if (!is_absolute_path(entry) && relative_base) {
268 strbuf_addstr(&pathbuf, real_path(relative_base));
269 strbuf_addch(&pathbuf, '/');
271 strbuf_addstr(&pathbuf, entry);
273 normalize_path_copy(pathbuf.buf, pathbuf.buf);
275 pfxlen = strlen(pathbuf.buf);
278 * The trailing slash after the directory name is given by
279 * this function at the end. Remove duplicates.
281 while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
282 pfxlen -= 1;
284 entlen = pfxlen + 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
285 ent = xmalloc(sizeof(*ent) + entlen);
286 memcpy(ent->base, pathbuf.buf, pfxlen);
287 strbuf_release(&pathbuf);
289 ent->name = ent->base + pfxlen + 1;
290 ent->base[pfxlen + 3] = '/';
291 ent->base[pfxlen] = ent->base[entlen-1] = 0;
293 /* Detect cases where alternate disappeared */
294 if (!is_directory(ent->base)) {
295 error("object directory %s does not exist; "
296 "check .git/objects/info/alternates.",
297 ent->base);
298 free(ent);
299 return -1;
302 /* Prevent the common mistake of listing the same
303 * thing twice, or object directory itself.
305 for (alt = alt_odb_list; alt; alt = alt->next) {
306 if (pfxlen == alt->name - alt->base - 1 &&
307 !memcmp(ent->base, alt->base, pfxlen)) {
308 free(ent);
309 return -1;
312 if (!strcmp(ent->base, objdir)) {
313 free(ent);
314 return -1;
317 /* add the alternate entry */
318 *alt_odb_tail = ent;
319 alt_odb_tail = &(ent->next);
320 ent->next = NULL;
322 /* recursively add alternates */
323 read_info_alternates(ent->base, depth + 1);
325 ent->base[pfxlen] = '/';
327 return 0;
330 static void link_alt_odb_entries(const char *alt, int len, int sep,
331 const char *relative_base, int depth)
333 struct string_list entries = STRING_LIST_INIT_NODUP;
334 char *alt_copy;
335 int i;
337 if (depth > 5) {
338 error("%s: ignoring alternate object stores, nesting too deep.",
339 relative_base);
340 return;
343 alt_copy = xmemdupz(alt, len);
344 string_list_split_in_place(&entries, alt_copy, sep, -1);
345 for (i = 0; i < entries.nr; i++) {
346 const char *entry = entries.items[i].string;
347 if (entry[0] == '\0' || entry[0] == '#')
348 continue;
349 if (!is_absolute_path(entry) && depth) {
350 error("%s: ignoring relative alternate object store %s",
351 relative_base, entry);
352 } else {
353 link_alt_odb_entry(entry, relative_base, depth);
356 string_list_clear(&entries, 0);
357 free(alt_copy);
360 void read_info_alternates(const char * relative_base, int depth)
362 char *map;
363 size_t mapsz;
364 struct stat st;
365 const char alt_file_name[] = "info/alternates";
366 /* Given that relative_base is no longer than PATH_MAX,
367 ensure that "path" has enough space to append "/", the
368 file name, "info/alternates", and a trailing NUL. */
369 char path[PATH_MAX + 1 + sizeof alt_file_name];
370 int fd;
372 sprintf(path, "%s/%s", relative_base, alt_file_name);
373 fd = git_open_noatime(path);
374 if (fd < 0)
375 return;
376 if (fstat(fd, &st) || (st.st_size == 0)) {
377 close(fd);
378 return;
380 mapsz = xsize_t(st.st_size);
381 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
382 close(fd);
384 link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
386 munmap(map, mapsz);
389 void add_to_alternates_file(const char *reference)
391 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
392 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
393 char *alt = mkpath("%s\n", reference);
394 write_or_die(fd, alt, strlen(alt));
395 if (commit_lock_file(lock))
396 die("could not close alternates file");
397 if (alt_odb_tail)
398 link_alt_odb_entries(alt, strlen(alt), '\n', NULL, 0);
401 void foreach_alt_odb(alt_odb_fn fn, void *cb)
403 struct alternate_object_database *ent;
405 prepare_alt_odb();
406 for (ent = alt_odb_list; ent; ent = ent->next)
407 if (fn(ent, cb))
408 return;
411 void prepare_alt_odb(void)
413 const char *alt;
415 if (alt_odb_tail)
416 return;
418 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
419 if (!alt) alt = "";
421 alt_odb_tail = &alt_odb_list;
422 link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
424 read_info_alternates(get_object_directory(), 0);
427 static int has_loose_object_local(const unsigned char *sha1)
429 char *name = sha1_file_name(sha1);
430 return !access(name, F_OK);
433 int has_loose_object_nonlocal(const unsigned char *sha1)
435 struct alternate_object_database *alt;
436 prepare_alt_odb();
437 for (alt = alt_odb_list; alt; alt = alt->next) {
438 fill_sha1_path(alt->name, sha1);
439 if (!access(alt->base, F_OK))
440 return 1;
442 return 0;
445 static int has_loose_object(const unsigned char *sha1)
447 return has_loose_object_local(sha1) ||
448 has_loose_object_nonlocal(sha1);
451 static unsigned int pack_used_ctr;
452 static unsigned int pack_mmap_calls;
453 static unsigned int peak_pack_open_windows;
454 static unsigned int pack_open_windows;
455 static unsigned int pack_open_fds;
456 static unsigned int pack_max_fds;
457 static size_t peak_pack_mapped;
458 static size_t pack_mapped;
459 struct packed_git *packed_git;
461 void pack_report(void)
463 fprintf(stderr,
464 "pack_report: getpagesize() = %10" SZ_FMT "\n"
465 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
466 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
467 sz_fmt(getpagesize()),
468 sz_fmt(packed_git_window_size),
469 sz_fmt(packed_git_limit));
470 fprintf(stderr,
471 "pack_report: pack_used_ctr = %10u\n"
472 "pack_report: pack_mmap_calls = %10u\n"
473 "pack_report: pack_open_windows = %10u / %10u\n"
474 "pack_report: pack_mapped = "
475 "%10" SZ_FMT " / %10" SZ_FMT "\n",
476 pack_used_ctr,
477 pack_mmap_calls,
478 pack_open_windows, peak_pack_open_windows,
479 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
482 static int check_packed_git_idx(const char *path, struct packed_git *p)
484 void *idx_map;
485 struct pack_idx_header *hdr;
486 size_t idx_size;
487 uint32_t version, nr, i, *index;
488 int fd = git_open_noatime(path);
489 struct stat st;
491 if (fd < 0)
492 return -1;
493 if (fstat(fd, &st)) {
494 close(fd);
495 return -1;
497 idx_size = xsize_t(st.st_size);
498 if (idx_size < 4 * 256 + 20 + 20) {
499 close(fd);
500 return error("index file %s is too small", path);
502 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
503 close(fd);
505 hdr = idx_map;
506 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
507 version = ntohl(hdr->idx_version);
508 if (version < 2 || version > 2) {
509 munmap(idx_map, idx_size);
510 return error("index file %s is version %"PRIu32
511 " and is not supported by this binary"
512 " (try upgrading GIT to a newer version)",
513 path, version);
515 } else
516 version = 1;
518 nr = 0;
519 index = idx_map;
520 if (version > 1)
521 index += 2; /* skip index header */
522 for (i = 0; i < 256; i++) {
523 uint32_t n = ntohl(index[i]);
524 if (n < nr) {
525 munmap(idx_map, idx_size);
526 return error("non-monotonic index %s", path);
528 nr = n;
531 if (version == 1) {
533 * Total size:
534 * - 256 index entries 4 bytes each
535 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
536 * - 20-byte SHA1 of the packfile
537 * - 20-byte SHA1 file checksum
539 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
540 munmap(idx_map, idx_size);
541 return error("wrong index v1 file size in %s", path);
543 } else if (version == 2) {
545 * Minimum size:
546 * - 8 bytes of header
547 * - 256 index entries 4 bytes each
548 * - 20-byte sha1 entry * nr
549 * - 4-byte crc entry * nr
550 * - 4-byte offset entry * nr
551 * - 20-byte SHA1 of the packfile
552 * - 20-byte SHA1 file checksum
553 * And after the 4-byte offset table might be a
554 * variable sized table containing 8-byte entries
555 * for offsets larger than 2^31.
557 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
558 unsigned long max_size = min_size;
559 if (nr)
560 max_size += (nr - 1)*8;
561 if (idx_size < min_size || idx_size > max_size) {
562 munmap(idx_map, idx_size);
563 return error("wrong index v2 file size in %s", path);
565 if (idx_size != min_size &&
567 * make sure we can deal with large pack offsets.
568 * 31-bit signed offset won't be enough, neither
569 * 32-bit unsigned one will be.
571 (sizeof(off_t) <= 4)) {
572 munmap(idx_map, idx_size);
573 return error("pack too large for current definition of off_t in %s", path);
577 p->index_version = version;
578 p->index_data = idx_map;
579 p->index_size = idx_size;
580 p->num_objects = nr;
581 return 0;
584 int open_pack_index(struct packed_git *p)
586 char *idx_name;
587 int ret;
589 if (p->index_data)
590 return 0;
592 idx_name = xstrdup(p->pack_name);
593 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
594 ret = check_packed_git_idx(idx_name, p);
595 free(idx_name);
596 return ret;
599 static void scan_windows(struct packed_git *p,
600 struct packed_git **lru_p,
601 struct pack_window **lru_w,
602 struct pack_window **lru_l)
604 struct pack_window *w, *w_l;
606 for (w_l = NULL, w = p->windows; w; w = w->next) {
607 if (!w->inuse_cnt) {
608 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
609 *lru_p = p;
610 *lru_w = w;
611 *lru_l = w_l;
614 w_l = w;
618 static int unuse_one_window(struct packed_git *current)
620 struct packed_git *p, *lru_p = NULL;
621 struct pack_window *lru_w = NULL, *lru_l = NULL;
623 if (current)
624 scan_windows(current, &lru_p, &lru_w, &lru_l);
625 for (p = packed_git; p; p = p->next)
626 scan_windows(p, &lru_p, &lru_w, &lru_l);
627 if (lru_p) {
628 munmap(lru_w->base, lru_w->len);
629 pack_mapped -= lru_w->len;
630 if (lru_l)
631 lru_l->next = lru_w->next;
632 else
633 lru_p->windows = lru_w->next;
634 free(lru_w);
635 pack_open_windows--;
636 return 1;
638 return 0;
641 void release_pack_memory(size_t need)
643 size_t cur = pack_mapped;
644 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
645 ; /* nothing */
648 void *xmmap(void *start, size_t length,
649 int prot, int flags, int fd, off_t offset)
651 void *ret = mmap(start, length, prot, flags, fd, offset);
652 if (ret == MAP_FAILED) {
653 if (!length)
654 return NULL;
655 release_pack_memory(length);
656 ret = mmap(start, length, prot, flags, fd, offset);
657 if (ret == MAP_FAILED)
658 die_errno("Out of memory? mmap failed");
660 return ret;
663 void close_pack_windows(struct packed_git *p)
665 while (p->windows) {
666 struct pack_window *w = p->windows;
668 if (w->inuse_cnt)
669 die("pack '%s' still has open windows to it",
670 p->pack_name);
671 munmap(w->base, w->len);
672 pack_mapped -= w->len;
673 pack_open_windows--;
674 p->windows = w->next;
675 free(w);
680 * The LRU pack is the one with the oldest MRU window, preferring packs
681 * with no used windows, or the oldest mtime if it has no windows allocated.
683 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
685 struct pack_window *w, *this_mru_w;
686 int has_windows_inuse = 0;
689 * Reject this pack if it has windows and the previously selected
690 * one does not. If this pack does not have windows, reject
691 * it if the pack file is newer than the previously selected one.
693 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
694 return;
696 for (w = this_mru_w = p->windows; w; w = w->next) {
698 * Reject this pack if any of its windows are in use,
699 * but the previously selected pack did not have any
700 * inuse windows. Otherwise, record that this pack
701 * has windows in use.
703 if (w->inuse_cnt) {
704 if (*accept_windows_inuse)
705 has_windows_inuse = 1;
706 else
707 return;
710 if (w->last_used > this_mru_w->last_used)
711 this_mru_w = w;
714 * Reject this pack if it has windows that have been
715 * used more recently than the previously selected pack.
716 * If the previously selected pack had windows inuse and
717 * we have not encountered a window in this pack that is
718 * inuse, skip this check since we prefer a pack with no
719 * inuse windows to one that has inuse windows.
721 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
722 this_mru_w->last_used > (*mru_w)->last_used)
723 return;
727 * Select this pack.
729 *mru_w = this_mru_w;
730 *lru_p = p;
731 *accept_windows_inuse = has_windows_inuse;
734 static int close_one_pack(void)
736 struct packed_git *p, *lru_p = NULL;
737 struct pack_window *mru_w = NULL;
738 int accept_windows_inuse = 1;
740 for (p = packed_git; p; p = p->next) {
741 if (p->pack_fd == -1)
742 continue;
743 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
746 if (lru_p) {
747 close(lru_p->pack_fd);
748 pack_open_fds--;
749 lru_p->pack_fd = -1;
750 return 1;
753 return 0;
756 void unuse_pack(struct pack_window **w_cursor)
758 struct pack_window *w = *w_cursor;
759 if (w) {
760 w->inuse_cnt--;
761 *w_cursor = NULL;
765 void close_pack_index(struct packed_git *p)
767 if (p->index_data) {
768 munmap((void *)p->index_data, p->index_size);
769 p->index_data = NULL;
774 * This is used by git-repack in case a newly created pack happens to
775 * contain the same set of objects as an existing one. In that case
776 * the resulting file might be different even if its name would be the
777 * same. It is best to close any reference to the old pack before it is
778 * replaced on disk. Of course no index pointers nor windows for given pack
779 * must subsist at this point. If ever objects from this pack are requested
780 * again, the new version of the pack will be reinitialized through
781 * reprepare_packed_git().
783 void free_pack_by_name(const char *pack_name)
785 struct packed_git *p, **pp = &packed_git;
787 while (*pp) {
788 p = *pp;
789 if (strcmp(pack_name, p->pack_name) == 0) {
790 clear_delta_base_cache();
791 close_pack_windows(p);
792 if (p->pack_fd != -1) {
793 close(p->pack_fd);
794 pack_open_fds--;
796 close_pack_index(p);
797 free(p->bad_object_sha1);
798 *pp = p->next;
799 if (last_found_pack == p)
800 last_found_pack = NULL;
801 free(p);
802 return;
804 pp = &p->next;
808 static unsigned int get_max_fd_limit(void)
810 #ifdef RLIMIT_NOFILE
812 struct rlimit lim;
814 if (!getrlimit(RLIMIT_NOFILE, &lim))
815 return lim.rlim_cur;
817 #endif
819 #ifdef _SC_OPEN_MAX
821 long open_max = sysconf(_SC_OPEN_MAX);
822 if (0 < open_max)
823 return open_max;
825 * Otherwise, we got -1 for one of the two
826 * reasons:
828 * (1) sysconf() did not understand _SC_OPEN_MAX
829 * and signaled an error with -1; or
830 * (2) sysconf() said there is no limit.
832 * We _could_ clear errno before calling sysconf() to
833 * tell these two cases apart and return a huge number
834 * in the latter case to let the caller cap it to a
835 * value that is not so selfish, but letting the
836 * fallback OPEN_MAX codepath take care of these cases
837 * is a lot simpler.
840 #endif
842 #ifdef OPEN_MAX
843 return OPEN_MAX;
844 #else
845 return 1; /* see the caller ;-) */
846 #endif
850 * Do not call this directly as this leaks p->pack_fd on error return;
851 * call open_packed_git() instead.
853 static int open_packed_git_1(struct packed_git *p)
855 struct stat st;
856 struct pack_header hdr;
857 unsigned char sha1[20];
858 unsigned char *idx_sha1;
859 long fd_flag;
861 if (!p->index_data && open_pack_index(p))
862 return error("packfile %s index unavailable", p->pack_name);
864 if (!pack_max_fds) {
865 unsigned int max_fds = get_max_fd_limit();
867 /* Save 3 for stdin/stdout/stderr, 22 for work */
868 if (25 < max_fds)
869 pack_max_fds = max_fds - 25;
870 else
871 pack_max_fds = 1;
874 while (pack_max_fds <= pack_open_fds && close_one_pack())
875 ; /* nothing */
877 p->pack_fd = git_open_noatime(p->pack_name);
878 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
879 return -1;
880 pack_open_fds++;
882 /* If we created the struct before we had the pack we lack size. */
883 if (!p->pack_size) {
884 if (!S_ISREG(st.st_mode))
885 return error("packfile %s not a regular file", p->pack_name);
886 p->pack_size = st.st_size;
887 } else if (p->pack_size != st.st_size)
888 return error("packfile %s size changed", p->pack_name);
890 /* We leave these file descriptors open with sliding mmap;
891 * there is no point keeping them open across exec(), though.
893 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
894 if (fd_flag < 0)
895 return error("cannot determine file descriptor flags");
896 fd_flag |= FD_CLOEXEC;
897 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
898 return error("cannot set FD_CLOEXEC");
900 /* Verify we recognize this pack file format. */
901 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
902 return error("file %s is far too short to be a packfile", p->pack_name);
903 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
904 return error("file %s is not a GIT packfile", p->pack_name);
905 if (!pack_version_ok(hdr.hdr_version))
906 return error("packfile %s is version %"PRIu32" and not"
907 " supported (try upgrading GIT to a newer version)",
908 p->pack_name, ntohl(hdr.hdr_version));
910 /* Verify the pack matches its index. */
911 if (p->num_objects != ntohl(hdr.hdr_entries))
912 return error("packfile %s claims to have %"PRIu32" objects"
913 " while index indicates %"PRIu32" objects",
914 p->pack_name, ntohl(hdr.hdr_entries),
915 p->num_objects);
916 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
917 return error("end of packfile %s is unavailable", p->pack_name);
918 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
919 return error("packfile %s signature is unavailable", p->pack_name);
920 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
921 if (hashcmp(sha1, idx_sha1))
922 return error("packfile %s does not match index", p->pack_name);
923 return 0;
926 static int open_packed_git(struct packed_git *p)
928 if (!open_packed_git_1(p))
929 return 0;
930 if (p->pack_fd != -1) {
931 close(p->pack_fd);
932 pack_open_fds--;
933 p->pack_fd = -1;
935 return -1;
938 static int in_window(struct pack_window *win, off_t offset)
940 /* We must promise at least 20 bytes (one hash) after the
941 * offset is available from this window, otherwise the offset
942 * is not actually in this window and a different window (which
943 * has that one hash excess) must be used. This is to support
944 * the object header and delta base parsing routines below.
946 off_t win_off = win->offset;
947 return win_off <= offset
948 && (offset + 20) <= (win_off + win->len);
951 unsigned char *use_pack(struct packed_git *p,
952 struct pack_window **w_cursor,
953 off_t offset,
954 unsigned long *left)
956 struct pack_window *win = *w_cursor;
958 /* Since packfiles end in a hash of their content and it's
959 * pointless to ask for an offset into the middle of that
960 * hash, and the in_window function above wouldn't match
961 * don't allow an offset too close to the end of the file.
963 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
964 die("packfile %s cannot be accessed", p->pack_name);
965 if (offset > (p->pack_size - 20))
966 die("offset beyond end of packfile (truncated pack?)");
968 if (!win || !in_window(win, offset)) {
969 if (win)
970 win->inuse_cnt--;
971 for (win = p->windows; win; win = win->next) {
972 if (in_window(win, offset))
973 break;
975 if (!win) {
976 size_t window_align = packed_git_window_size / 2;
977 off_t len;
979 if (p->pack_fd == -1 && open_packed_git(p))
980 die("packfile %s cannot be accessed", p->pack_name);
982 win = xcalloc(1, sizeof(*win));
983 win->offset = (offset / window_align) * window_align;
984 len = p->pack_size - win->offset;
985 if (len > packed_git_window_size)
986 len = packed_git_window_size;
987 win->len = (size_t)len;
988 pack_mapped += win->len;
989 while (packed_git_limit < pack_mapped
990 && unuse_one_window(p))
991 ; /* nothing */
992 win->base = xmmap(NULL, win->len,
993 PROT_READ, MAP_PRIVATE,
994 p->pack_fd, win->offset);
995 if (win->base == MAP_FAILED)
996 die("packfile %s cannot be mapped: %s",
997 p->pack_name,
998 strerror(errno));
999 if (!win->offset && win->len == p->pack_size
1000 && !p->do_not_close) {
1001 close(p->pack_fd);
1002 pack_open_fds--;
1003 p->pack_fd = -1;
1005 pack_mmap_calls++;
1006 pack_open_windows++;
1007 if (pack_mapped > peak_pack_mapped)
1008 peak_pack_mapped = pack_mapped;
1009 if (pack_open_windows > peak_pack_open_windows)
1010 peak_pack_open_windows = pack_open_windows;
1011 win->next = p->windows;
1012 p->windows = win;
1015 if (win != *w_cursor) {
1016 win->last_used = pack_used_ctr++;
1017 win->inuse_cnt++;
1018 *w_cursor = win;
1020 offset -= win->offset;
1021 if (left)
1022 *left = win->len - xsize_t(offset);
1023 return win->base + offset;
1026 static struct packed_git *alloc_packed_git(int extra)
1028 struct packed_git *p = xmalloc(sizeof(*p) + extra);
1029 memset(p, 0, sizeof(*p));
1030 p->pack_fd = -1;
1031 return p;
1034 static void try_to_free_pack_memory(size_t size)
1036 release_pack_memory(size);
1039 struct packed_git *add_packed_git(const char *path, int path_len, int local)
1041 static int have_set_try_to_free_routine;
1042 struct stat st;
1043 struct packed_git *p = alloc_packed_git(path_len + 2);
1045 if (!have_set_try_to_free_routine) {
1046 have_set_try_to_free_routine = 1;
1047 set_try_to_free_routine(try_to_free_pack_memory);
1051 * Make sure a corresponding .pack file exists and that
1052 * the index looks sane.
1054 path_len -= strlen(".idx");
1055 if (path_len < 1) {
1056 free(p);
1057 return NULL;
1059 memcpy(p->pack_name, path, path_len);
1061 strcpy(p->pack_name + path_len, ".keep");
1062 if (!access(p->pack_name, F_OK))
1063 p->pack_keep = 1;
1065 strcpy(p->pack_name + path_len, ".pack");
1066 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1067 free(p);
1068 return NULL;
1071 /* ok, it looks sane as far as we can check without
1072 * actually mapping the pack file.
1074 p->pack_size = st.st_size;
1075 p->pack_local = local;
1076 p->mtime = st.st_mtime;
1077 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1078 hashclr(p->sha1);
1079 return p;
1082 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1084 const char *path = sha1_pack_name(sha1);
1085 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
1087 strcpy(p->pack_name, path);
1088 hashcpy(p->sha1, sha1);
1089 if (check_packed_git_idx(idx_path, p)) {
1090 free(p);
1091 return NULL;
1094 return p;
1097 void install_packed_git(struct packed_git *pack)
1099 if (pack->pack_fd != -1)
1100 pack_open_fds++;
1102 pack->next = packed_git;
1103 packed_git = pack;
1106 void (*report_garbage)(const char *desc, const char *path);
1108 static void report_helper(const struct string_list *list,
1109 int seen_bits, int first, int last)
1111 const char *msg;
1112 switch (seen_bits) {
1113 case 0:
1114 msg = "no corresponding .idx nor .pack";
1115 break;
1116 case 1:
1117 msg = "no corresponding .idx";
1118 break;
1119 case 2:
1120 msg = "no corresponding .pack";
1121 break;
1122 default:
1123 return;
1125 for (; first < last; first++)
1126 report_garbage(msg, list->items[first].string);
1129 static void report_pack_garbage(struct string_list *list)
1131 int i, baselen = -1, first = 0, seen_bits = 0;
1133 if (!report_garbage)
1134 return;
1136 sort_string_list(list);
1138 for (i = 0; i < list->nr; i++) {
1139 const char *path = list->items[i].string;
1140 if (baselen != -1 &&
1141 strncmp(path, list->items[first].string, baselen)) {
1142 report_helper(list, seen_bits, first, i);
1143 baselen = -1;
1144 seen_bits = 0;
1146 if (baselen == -1) {
1147 const char *dot = strrchr(path, '.');
1148 if (!dot) {
1149 report_garbage("garbage found", path);
1150 continue;
1152 baselen = dot - path + 1;
1153 first = i;
1155 if (!strcmp(path + baselen, "pack"))
1156 seen_bits |= 1;
1157 else if (!strcmp(path + baselen, "idx"))
1158 seen_bits |= 2;
1160 report_helper(list, seen_bits, first, list->nr);
1163 static void prepare_packed_git_one(char *objdir, int local)
1165 /* Ensure that this buffer is large enough so that we can
1166 append "/pack/" without clobbering the stack even if
1167 strlen(objdir) were PATH_MAX. */
1168 char path[PATH_MAX + 1 + 4 + 1 + 1];
1169 int len;
1170 DIR *dir;
1171 struct dirent *de;
1172 struct string_list garbage = STRING_LIST_INIT_DUP;
1174 sprintf(path, "%s/pack", objdir);
1175 len = strlen(path);
1176 dir = opendir(path);
1177 if (!dir) {
1178 if (errno != ENOENT)
1179 error("unable to open object pack directory: %s: %s",
1180 path, strerror(errno));
1181 return;
1183 path[len++] = '/';
1184 while ((de = readdir(dir)) != NULL) {
1185 int namelen = strlen(de->d_name);
1186 struct packed_git *p;
1188 if (len + namelen + 1 > sizeof(path)) {
1189 if (report_garbage) {
1190 struct strbuf sb = STRBUF_INIT;
1191 strbuf_addf(&sb, "%.*s/%s", len - 1, path, de->d_name);
1192 report_garbage("path too long", sb.buf);
1193 strbuf_release(&sb);
1195 continue;
1198 if (is_dot_or_dotdot(de->d_name))
1199 continue;
1201 strcpy(path + len, de->d_name);
1203 if (has_extension(de->d_name, ".idx")) {
1204 /* Don't reopen a pack we already have. */
1205 for (p = packed_git; p; p = p->next) {
1206 if (!memcmp(path, p->pack_name, len + namelen - 4))
1207 break;
1209 if (p == NULL &&
1211 * See if it really is a valid .idx file with
1212 * corresponding .pack file that we can map.
1214 (p = add_packed_git(path, len + namelen, local)) != NULL)
1215 install_packed_git(p);
1218 if (!report_garbage)
1219 continue;
1221 if (has_extension(de->d_name, ".idx") ||
1222 has_extension(de->d_name, ".pack") ||
1223 has_extension(de->d_name, ".keep"))
1224 string_list_append(&garbage, path);
1225 else
1226 report_garbage("garbage found", path);
1228 closedir(dir);
1229 report_pack_garbage(&garbage);
1230 string_list_clear(&garbage, 0);
1233 static int sort_pack(const void *a_, const void *b_)
1235 struct packed_git *a = *((struct packed_git **)a_);
1236 struct packed_git *b = *((struct packed_git **)b_);
1237 int st;
1240 * Local packs tend to contain objects specific to our
1241 * variant of the project than remote ones. In addition,
1242 * remote ones could be on a network mounted filesystem.
1243 * Favor local ones for these reasons.
1245 st = a->pack_local - b->pack_local;
1246 if (st)
1247 return -st;
1250 * Younger packs tend to contain more recent objects,
1251 * and more recent objects tend to get accessed more
1252 * often.
1254 if (a->mtime < b->mtime)
1255 return 1;
1256 else if (a->mtime == b->mtime)
1257 return 0;
1258 return -1;
1261 static void rearrange_packed_git(void)
1263 struct packed_git **ary, *p;
1264 int i, n;
1266 for (n = 0, p = packed_git; p; p = p->next)
1267 n++;
1268 if (n < 2)
1269 return;
1271 /* prepare an array of packed_git for easier sorting */
1272 ary = xcalloc(n, sizeof(struct packed_git *));
1273 for (n = 0, p = packed_git; p; p = p->next)
1274 ary[n++] = p;
1276 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1278 /* link them back again */
1279 for (i = 0; i < n - 1; i++)
1280 ary[i]->next = ary[i + 1];
1281 ary[n - 1]->next = NULL;
1282 packed_git = ary[0];
1284 free(ary);
1287 static int prepare_packed_git_run_once = 0;
1288 void prepare_packed_git(void)
1290 struct alternate_object_database *alt;
1292 if (prepare_packed_git_run_once)
1293 return;
1294 prepare_packed_git_one(get_object_directory(), 1);
1295 prepare_alt_odb();
1296 for (alt = alt_odb_list; alt; alt = alt->next) {
1297 alt->name[-1] = 0;
1298 prepare_packed_git_one(alt->base, 0);
1299 alt->name[-1] = '/';
1301 rearrange_packed_git();
1302 prepare_packed_git_run_once = 1;
1305 void reprepare_packed_git(void)
1307 discard_revindex();
1308 prepare_packed_git_run_once = 0;
1309 prepare_packed_git();
1312 static void mark_bad_packed_object(struct packed_git *p,
1313 const unsigned char *sha1)
1315 unsigned i;
1316 for (i = 0; i < p->num_bad_objects; i++)
1317 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1318 return;
1319 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1320 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1321 p->num_bad_objects++;
1324 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1326 struct packed_git *p;
1327 unsigned i;
1329 for (p = packed_git; p; p = p->next)
1330 for (i = 0; i < p->num_bad_objects; i++)
1331 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1332 return p;
1333 return NULL;
1337 * With an in-core object data in "map", rehash it to make sure the
1338 * object name actually matches "sha1" to detect object corruption.
1339 * With "map" == NULL, try reading the object named with "sha1" using
1340 * the streaming interface and rehash it to do the same.
1342 int check_sha1_signature(const unsigned char *sha1, void *map,
1343 unsigned long size, const char *type)
1345 unsigned char real_sha1[20];
1346 enum object_type obj_type;
1347 struct git_istream *st;
1348 git_SHA_CTX c;
1349 char hdr[32];
1350 int hdrlen;
1352 if (map) {
1353 hash_sha1_file(map, size, type, real_sha1);
1354 return hashcmp(sha1, real_sha1) ? -1 : 0;
1357 st = open_istream(sha1, &obj_type, &size, NULL);
1358 if (!st)
1359 return -1;
1361 /* Generate the header */
1362 hdrlen = sprintf(hdr, "%s %lu", typename(obj_type), size) + 1;
1364 /* Sha1.. */
1365 git_SHA1_Init(&c);
1366 git_SHA1_Update(&c, hdr, hdrlen);
1367 for (;;) {
1368 char buf[1024 * 16];
1369 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1371 if (readlen < 0) {
1372 close_istream(st);
1373 return -1;
1375 if (!readlen)
1376 break;
1377 git_SHA1_Update(&c, buf, readlen);
1379 git_SHA1_Final(real_sha1, &c);
1380 close_istream(st);
1381 return hashcmp(sha1, real_sha1) ? -1 : 0;
1384 static int git_open_noatime(const char *name)
1386 static int sha1_file_open_flag = O_NOATIME;
1388 for (;;) {
1389 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1390 if (fd >= 0)
1391 return fd;
1393 /* Might the failure be due to O_NOATIME? */
1394 if (errno != ENOENT && sha1_file_open_flag) {
1395 sha1_file_open_flag = 0;
1396 continue;
1399 return -1;
1403 static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1405 char *name = sha1_file_name(sha1);
1406 struct alternate_object_database *alt;
1408 if (!lstat(name, st))
1409 return 0;
1411 prepare_alt_odb();
1412 errno = ENOENT;
1413 for (alt = alt_odb_list; alt; alt = alt->next) {
1414 name = alt->name;
1415 fill_sha1_path(name, sha1);
1416 if (!lstat(alt->base, st))
1417 return 0;
1420 return -1;
1423 static int open_sha1_file(const unsigned char *sha1)
1425 int fd;
1426 char *name = sha1_file_name(sha1);
1427 struct alternate_object_database *alt;
1429 fd = git_open_noatime(name);
1430 if (fd >= 0)
1431 return fd;
1433 prepare_alt_odb();
1434 errno = ENOENT;
1435 for (alt = alt_odb_list; alt; alt = alt->next) {
1436 name = alt->name;
1437 fill_sha1_path(name, sha1);
1438 fd = git_open_noatime(alt->base);
1439 if (fd >= 0)
1440 return fd;
1442 return -1;
1445 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1447 void *map;
1448 int fd;
1450 fd = open_sha1_file(sha1);
1451 map = NULL;
1452 if (fd >= 0) {
1453 struct stat st;
1455 if (!fstat(fd, &st)) {
1456 *size = xsize_t(st.st_size);
1457 if (!*size) {
1458 /* mmap() is forbidden on empty files */
1459 error("object file %s is empty", sha1_file_name(sha1));
1460 return NULL;
1462 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1464 close(fd);
1466 return map;
1470 * There used to be a second loose object header format which
1471 * was meant to mimic the in-pack format, allowing for direct
1472 * copy of the object data. This format turned up not to be
1473 * really worth it and we no longer write loose objects in that
1474 * format.
1476 static int experimental_loose_object(unsigned char *map)
1478 unsigned int word;
1481 * We must determine if the buffer contains the standard
1482 * zlib-deflated stream or the experimental format based
1483 * on the in-pack object format. Compare the header byte
1484 * for each format:
1486 * RFC1950 zlib w/ deflate : 0www1000 : 0 <= www <= 7
1487 * Experimental pack-based : Stttssss : ttt = 1,2,3,4
1489 * If bit 7 is clear and bits 0-3 equal 8, the buffer MUST be
1490 * in standard loose-object format, UNLESS it is a Git-pack
1491 * format object *exactly* 8 bytes in size when inflated.
1493 * However, RFC1950 also specifies that the 1st 16-bit word
1494 * must be divisible by 31 - this checksum tells us our buffer
1495 * is in the standard format, giving a false positive only if
1496 * the 1st word of the Git-pack format object happens to be
1497 * divisible by 31, ie:
1498 * ((byte0 * 256) + byte1) % 31 = 0
1499 * => 0ttt10000www1000 % 31 = 0
1501 * As it happens, this case can only arise for www=3 & ttt=1
1502 * - ie, a Commit object, which would have to be 8 bytes in
1503 * size. As no Commit can be that small, we find that the
1504 * combination of these two criteria (bitmask & checksum)
1505 * can always correctly determine the buffer format.
1507 word = (map[0] << 8) + map[1];
1508 if ((map[0] & 0x8F) == 0x08 && !(word % 31))
1509 return 0;
1510 else
1511 return 1;
1514 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1515 unsigned long len, enum object_type *type, unsigned long *sizep)
1517 unsigned shift;
1518 unsigned long size, c;
1519 unsigned long used = 0;
1521 c = buf[used++];
1522 *type = (c >> 4) & 7;
1523 size = c & 15;
1524 shift = 4;
1525 while (c & 0x80) {
1526 if (len <= used || bitsizeof(long) <= shift) {
1527 error("bad object header");
1528 size = used = 0;
1529 break;
1531 c = buf[used++];
1532 size += (c & 0x7f) << shift;
1533 shift += 7;
1535 *sizep = size;
1536 return used;
1539 int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1541 unsigned long size, used;
1542 static const char valid_loose_object_type[8] = {
1543 0, /* OBJ_EXT */
1544 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1545 0, /* "delta" and others are invalid in a loose object */
1547 enum object_type type;
1549 /* Get the data stream */
1550 memset(stream, 0, sizeof(*stream));
1551 stream->next_in = map;
1552 stream->avail_in = mapsize;
1553 stream->next_out = buffer;
1554 stream->avail_out = bufsiz;
1556 if (experimental_loose_object(map)) {
1558 * The old experimental format we no longer produce;
1559 * we can still read it.
1561 used = unpack_object_header_buffer(map, mapsize, &type, &size);
1562 if (!used || !valid_loose_object_type[type])
1563 return -1;
1564 map += used;
1565 mapsize -= used;
1567 /* Set up the stream for the rest.. */
1568 stream->next_in = map;
1569 stream->avail_in = mapsize;
1570 git_inflate_init(stream);
1572 /* And generate the fake traditional header */
1573 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1574 typename(type), size);
1575 return 0;
1577 git_inflate_init(stream);
1578 return git_inflate(stream, 0);
1581 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1583 int bytes = strlen(buffer) + 1;
1584 unsigned char *buf = xmallocz(size);
1585 unsigned long n;
1586 int status = Z_OK;
1588 n = stream->total_out - bytes;
1589 if (n > size)
1590 n = size;
1591 memcpy(buf, (char *) buffer + bytes, n);
1592 bytes = n;
1593 if (bytes <= size) {
1595 * The above condition must be (bytes <= size), not
1596 * (bytes < size). In other words, even though we
1597 * expect no more output and set avail_out to zero,
1598 * the input zlib stream may have bytes that express
1599 * "this concludes the stream", and we *do* want to
1600 * eat that input.
1602 * Otherwise we would not be able to test that we
1603 * consumed all the input to reach the expected size;
1604 * we also want to check that zlib tells us that all
1605 * went well with status == Z_STREAM_END at the end.
1607 stream->next_out = buf + bytes;
1608 stream->avail_out = size - bytes;
1609 while (status == Z_OK)
1610 status = git_inflate(stream, Z_FINISH);
1612 if (status == Z_STREAM_END && !stream->avail_in) {
1613 git_inflate_end(stream);
1614 return buf;
1617 if (status < 0)
1618 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1619 else if (stream->avail_in)
1620 error("garbage at end of loose object '%s'",
1621 sha1_to_hex(sha1));
1622 free(buf);
1623 return NULL;
1627 * We used to just use "sscanf()", but that's actually way
1628 * too permissive for what we want to check. So do an anal
1629 * object header parse by hand.
1631 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1633 char type[10];
1634 int i;
1635 unsigned long size;
1638 * The type can be at most ten bytes (including the
1639 * terminating '\0' that we add), and is followed by
1640 * a space.
1642 i = 0;
1643 for (;;) {
1644 char c = *hdr++;
1645 if (c == ' ')
1646 break;
1647 type[i++] = c;
1648 if (i >= sizeof(type))
1649 return -1;
1651 type[i] = 0;
1654 * The length must follow immediately, and be in canonical
1655 * decimal format (ie "010" is not valid).
1657 size = *hdr++ - '0';
1658 if (size > 9)
1659 return -1;
1660 if (size) {
1661 for (;;) {
1662 unsigned long c = *hdr - '0';
1663 if (c > 9)
1664 break;
1665 hdr++;
1666 size = size * 10 + c;
1669 *sizep = size;
1672 * The length must be followed by a zero byte
1674 return *hdr ? -1 : type_from_string(type);
1677 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1679 int ret;
1680 git_zstream stream;
1681 char hdr[8192];
1683 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1684 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1685 return NULL;
1687 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1690 unsigned long get_size_from_delta(struct packed_git *p,
1691 struct pack_window **w_curs,
1692 off_t curpos)
1694 const unsigned char *data;
1695 unsigned char delta_head[20], *in;
1696 git_zstream stream;
1697 int st;
1699 memset(&stream, 0, sizeof(stream));
1700 stream.next_out = delta_head;
1701 stream.avail_out = sizeof(delta_head);
1703 git_inflate_init(&stream);
1704 do {
1705 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1706 stream.next_in = in;
1707 st = git_inflate(&stream, Z_FINISH);
1708 curpos += stream.next_in - in;
1709 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1710 stream.total_out < sizeof(delta_head));
1711 git_inflate_end(&stream);
1712 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1713 error("delta data unpack-initial failed");
1714 return 0;
1717 /* Examine the initial part of the delta to figure out
1718 * the result size.
1720 data = delta_head;
1722 /* ignore base size */
1723 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1725 /* Read the result size */
1726 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1729 static off_t get_delta_base(struct packed_git *p,
1730 struct pack_window **w_curs,
1731 off_t *curpos,
1732 enum object_type type,
1733 off_t delta_obj_offset)
1735 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1736 off_t base_offset;
1738 /* use_pack() assured us we have [base_info, base_info + 20)
1739 * as a range that we can look at without walking off the
1740 * end of the mapped window. Its actually the hash size
1741 * that is assured. An OFS_DELTA longer than the hash size
1742 * is stupid, as then a REF_DELTA would be smaller to store.
1744 if (type == OBJ_OFS_DELTA) {
1745 unsigned used = 0;
1746 unsigned char c = base_info[used++];
1747 base_offset = c & 127;
1748 while (c & 128) {
1749 base_offset += 1;
1750 if (!base_offset || MSB(base_offset, 7))
1751 return 0; /* overflow */
1752 c = base_info[used++];
1753 base_offset = (base_offset << 7) + (c & 127);
1755 base_offset = delta_obj_offset - base_offset;
1756 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1757 return 0; /* out of bound */
1758 *curpos += used;
1759 } else if (type == OBJ_REF_DELTA) {
1760 /* The base entry _must_ be in the same pack */
1761 base_offset = find_pack_entry_one(base_info, p);
1762 *curpos += 20;
1763 } else
1764 die("I am totally screwed");
1765 return base_offset;
1768 int unpack_object_header(struct packed_git *p,
1769 struct pack_window **w_curs,
1770 off_t *curpos,
1771 unsigned long *sizep)
1773 unsigned char *base;
1774 unsigned long left;
1775 unsigned long used;
1776 enum object_type type;
1778 /* use_pack() assures us we have [base, base + 20) available
1779 * as a range that we can look at. (Its actually the hash
1780 * size that is assured.) With our object header encoding
1781 * the maximum deflated object size is 2^137, which is just
1782 * insane, so we know won't exceed what we have been given.
1784 base = use_pack(p, w_curs, *curpos, &left);
1785 used = unpack_object_header_buffer(base, left, &type, sizep);
1786 if (!used) {
1787 type = OBJ_BAD;
1788 } else
1789 *curpos += used;
1791 return type;
1794 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1796 int type;
1797 struct revindex_entry *revidx;
1798 const unsigned char *sha1;
1799 revidx = find_pack_revindex(p, obj_offset);
1800 if (!revidx)
1801 return OBJ_BAD;
1802 sha1 = nth_packed_object_sha1(p, revidx->nr);
1803 mark_bad_packed_object(p, sha1);
1804 type = sha1_object_info(sha1, NULL);
1805 if (type <= OBJ_NONE)
1806 return OBJ_BAD;
1807 return type;
1810 #define POI_STACK_PREALLOC 64
1812 static enum object_type packed_to_object_type(struct packed_git *p,
1813 off_t obj_offset,
1814 enum object_type type,
1815 struct pack_window **w_curs,
1816 off_t curpos)
1818 off_t small_poi_stack[POI_STACK_PREALLOC];
1819 off_t *poi_stack = small_poi_stack;
1820 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1822 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1823 off_t base_offset;
1824 unsigned long size;
1825 /* Push the object we're going to leave behind */
1826 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1827 poi_stack_alloc = alloc_nr(poi_stack_nr);
1828 poi_stack = xmalloc(sizeof(off_t)*poi_stack_alloc);
1829 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1830 } else {
1831 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1833 poi_stack[poi_stack_nr++] = obj_offset;
1834 /* If parsing the base offset fails, just unwind */
1835 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1836 if (!base_offset)
1837 goto unwind;
1838 curpos = obj_offset = base_offset;
1839 type = unpack_object_header(p, w_curs, &curpos, &size);
1840 if (type <= OBJ_NONE) {
1841 /* If getting the base itself fails, we first
1842 * retry the base, otherwise unwind */
1843 type = retry_bad_packed_offset(p, base_offset);
1844 if (type > OBJ_NONE)
1845 goto out;
1846 goto unwind;
1850 switch (type) {
1851 case OBJ_BAD:
1852 case OBJ_COMMIT:
1853 case OBJ_TREE:
1854 case OBJ_BLOB:
1855 case OBJ_TAG:
1856 break;
1857 default:
1858 error("unknown object type %i at offset %"PRIuMAX" in %s",
1859 type, (uintmax_t)obj_offset, p->pack_name);
1860 type = OBJ_BAD;
1863 out:
1864 if (poi_stack != small_poi_stack)
1865 free(poi_stack);
1866 return type;
1868 unwind:
1869 while (poi_stack_nr) {
1870 obj_offset = poi_stack[--poi_stack_nr];
1871 type = retry_bad_packed_offset(p, obj_offset);
1872 if (type > OBJ_NONE)
1873 goto out;
1875 type = OBJ_BAD;
1876 goto out;
1879 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1880 struct object_info *oi)
1882 struct pack_window *w_curs = NULL;
1883 unsigned long size;
1884 off_t curpos = obj_offset;
1885 enum object_type type;
1888 * We always get the representation type, but only convert it to
1889 * a "real" type later if the caller is interested.
1891 type = unpack_object_header(p, &w_curs, &curpos, &size);
1893 if (oi->sizep) {
1894 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1895 off_t tmp_pos = curpos;
1896 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1897 type, obj_offset);
1898 if (!base_offset) {
1899 type = OBJ_BAD;
1900 goto out;
1902 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1903 if (*oi->sizep == 0) {
1904 type = OBJ_BAD;
1905 goto out;
1907 } else {
1908 *oi->sizep = size;
1912 if (oi->disk_sizep) {
1913 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1914 *oi->disk_sizep = revidx[1].offset - obj_offset;
1917 if (oi->typep) {
1918 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
1919 if (*oi->typep < 0) {
1920 type = OBJ_BAD;
1921 goto out;
1925 out:
1926 unuse_pack(&w_curs);
1927 return type;
1930 static void *unpack_compressed_entry(struct packed_git *p,
1931 struct pack_window **w_curs,
1932 off_t curpos,
1933 unsigned long size)
1935 int st;
1936 git_zstream stream;
1937 unsigned char *buffer, *in;
1939 buffer = xmallocz(size);
1940 memset(&stream, 0, sizeof(stream));
1941 stream.next_out = buffer;
1942 stream.avail_out = size + 1;
1944 git_inflate_init(&stream);
1945 do {
1946 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1947 stream.next_in = in;
1948 st = git_inflate(&stream, Z_FINISH);
1949 if (!stream.avail_out)
1950 break; /* the payload is larger than it should be */
1951 curpos += stream.next_in - in;
1952 } while (st == Z_OK || st == Z_BUF_ERROR);
1953 git_inflate_end(&stream);
1954 if ((st != Z_STREAM_END) || stream.total_out != size) {
1955 free(buffer);
1956 return NULL;
1959 return buffer;
1962 #define MAX_DELTA_CACHE (256)
1964 static size_t delta_base_cached;
1966 static struct delta_base_cache_lru_list {
1967 struct delta_base_cache_lru_list *prev;
1968 struct delta_base_cache_lru_list *next;
1969 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1971 static struct delta_base_cache_entry {
1972 struct delta_base_cache_lru_list lru;
1973 void *data;
1974 struct packed_git *p;
1975 off_t base_offset;
1976 unsigned long size;
1977 enum object_type type;
1978 } delta_base_cache[MAX_DELTA_CACHE];
1980 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1982 unsigned long hash;
1984 hash = (unsigned long)p + (unsigned long)base_offset;
1985 hash += (hash >> 8) + (hash >> 16);
1986 return hash % MAX_DELTA_CACHE;
1989 static struct delta_base_cache_entry *
1990 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1992 unsigned long hash = pack_entry_hash(p, base_offset);
1993 return delta_base_cache + hash;
1996 static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
1997 struct packed_git *p, off_t base_offset)
1999 return (ent->data && ent->p == p && ent->base_offset == base_offset);
2002 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2004 struct delta_base_cache_entry *ent;
2005 ent = get_delta_base_cache_entry(p, base_offset);
2006 return eq_delta_base_cache_entry(ent, p, base_offset);
2009 static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2011 ent->data = NULL;
2012 ent->lru.next->prev = ent->lru.prev;
2013 ent->lru.prev->next = ent->lru.next;
2014 delta_base_cached -= ent->size;
2017 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2018 unsigned long *base_size, enum object_type *type, int keep_cache)
2020 struct delta_base_cache_entry *ent;
2021 void *ret;
2023 ent = get_delta_base_cache_entry(p, base_offset);
2025 if (!eq_delta_base_cache_entry(ent, p, base_offset))
2026 return unpack_entry(p, base_offset, type, base_size);
2028 ret = ent->data;
2030 if (!keep_cache)
2031 clear_delta_base_cache_entry(ent);
2032 else
2033 ret = xmemdupz(ent->data, ent->size);
2034 *type = ent->type;
2035 *base_size = ent->size;
2036 return ret;
2039 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2041 if (ent->data) {
2042 free(ent->data);
2043 ent->data = NULL;
2044 ent->lru.next->prev = ent->lru.prev;
2045 ent->lru.prev->next = ent->lru.next;
2046 delta_base_cached -= ent->size;
2050 void clear_delta_base_cache(void)
2052 unsigned long p;
2053 for (p = 0; p < MAX_DELTA_CACHE; p++)
2054 release_delta_base_cache(&delta_base_cache[p]);
2057 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2058 void *base, unsigned long base_size, enum object_type type)
2060 unsigned long hash = pack_entry_hash(p, base_offset);
2061 struct delta_base_cache_entry *ent = delta_base_cache + hash;
2062 struct delta_base_cache_lru_list *lru;
2064 release_delta_base_cache(ent);
2065 delta_base_cached += base_size;
2067 for (lru = delta_base_cache_lru.next;
2068 delta_base_cached > delta_base_cache_limit
2069 && lru != &delta_base_cache_lru;
2070 lru = lru->next) {
2071 struct delta_base_cache_entry *f = (void *)lru;
2072 if (f->type == OBJ_BLOB)
2073 release_delta_base_cache(f);
2075 for (lru = delta_base_cache_lru.next;
2076 delta_base_cached > delta_base_cache_limit
2077 && lru != &delta_base_cache_lru;
2078 lru = lru->next) {
2079 struct delta_base_cache_entry *f = (void *)lru;
2080 release_delta_base_cache(f);
2083 ent->p = p;
2084 ent->base_offset = base_offset;
2085 ent->type = type;
2086 ent->data = base;
2087 ent->size = base_size;
2088 ent->lru.next = &delta_base_cache_lru;
2089 ent->lru.prev = delta_base_cache_lru.prev;
2090 delta_base_cache_lru.prev->next = &ent->lru;
2091 delta_base_cache_lru.prev = &ent->lru;
2094 static void *read_object(const unsigned char *sha1, enum object_type *type,
2095 unsigned long *size);
2097 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2099 static FILE *log_file;
2101 if (!log_pack_access)
2102 log_pack_access = getenv("GIT_TRACE_PACK_ACCESS");
2103 if (!log_pack_access)
2104 log_pack_access = no_log_pack_access;
2105 if (log_pack_access == no_log_pack_access)
2106 return;
2108 if (!log_file) {
2109 log_file = fopen(log_pack_access, "w");
2110 if (!log_file) {
2111 error("cannot open pack access log '%s' for writing: %s",
2112 log_pack_access, strerror(errno));
2113 log_pack_access = no_log_pack_access;
2114 return;
2117 fprintf(log_file, "%s %"PRIuMAX"\n",
2118 p->pack_name, (uintmax_t)obj_offset);
2119 fflush(log_file);
2122 int do_check_packed_object_crc;
2124 #define UNPACK_ENTRY_STACK_PREALLOC 64
2125 struct unpack_entry_stack_ent {
2126 off_t obj_offset;
2127 off_t curpos;
2128 unsigned long size;
2131 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2132 enum object_type *final_type, unsigned long *final_size)
2134 struct pack_window *w_curs = NULL;
2135 off_t curpos = obj_offset;
2136 void *data = NULL;
2137 unsigned long size;
2138 enum object_type type;
2139 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2140 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2141 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2142 int base_from_cache = 0;
2144 if (log_pack_access != no_log_pack_access)
2145 write_pack_access_log(p, obj_offset);
2147 /* PHASE 1: drill down to the innermost base object */
2148 for (;;) {
2149 off_t base_offset;
2150 int i;
2151 struct delta_base_cache_entry *ent;
2153 ent = get_delta_base_cache_entry(p, curpos);
2154 if (eq_delta_base_cache_entry(ent, p, curpos)) {
2155 type = ent->type;
2156 data = ent->data;
2157 size = ent->size;
2158 clear_delta_base_cache_entry(ent);
2159 base_from_cache = 1;
2160 break;
2163 if (do_check_packed_object_crc && p->index_version > 1) {
2164 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2165 unsigned long len = revidx[1].offset - obj_offset;
2166 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2167 const unsigned char *sha1 =
2168 nth_packed_object_sha1(p, revidx->nr);
2169 error("bad packed object CRC for %s",
2170 sha1_to_hex(sha1));
2171 mark_bad_packed_object(p, sha1);
2172 unuse_pack(&w_curs);
2173 return NULL;
2177 type = unpack_object_header(p, &w_curs, &curpos, &size);
2178 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2179 break;
2181 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2182 if (!base_offset) {
2183 error("failed to validate delta base reference "
2184 "at offset %"PRIuMAX" from %s",
2185 (uintmax_t)curpos, p->pack_name);
2186 /* bail to phase 2, in hopes of recovery */
2187 data = NULL;
2188 break;
2191 /* push object, proceed to base */
2192 if (delta_stack_nr >= delta_stack_alloc
2193 && delta_stack == small_delta_stack) {
2194 delta_stack_alloc = alloc_nr(delta_stack_nr);
2195 delta_stack = xmalloc(sizeof(*delta_stack)*delta_stack_alloc);
2196 memcpy(delta_stack, small_delta_stack,
2197 sizeof(*delta_stack)*delta_stack_nr);
2198 } else {
2199 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2201 i = delta_stack_nr++;
2202 delta_stack[i].obj_offset = obj_offset;
2203 delta_stack[i].curpos = curpos;
2204 delta_stack[i].size = size;
2206 curpos = obj_offset = base_offset;
2209 /* PHASE 2: handle the base */
2210 switch (type) {
2211 case OBJ_OFS_DELTA:
2212 case OBJ_REF_DELTA:
2213 if (data)
2214 die("BUG in unpack_entry: left loop at a valid delta");
2215 break;
2216 case OBJ_COMMIT:
2217 case OBJ_TREE:
2218 case OBJ_BLOB:
2219 case OBJ_TAG:
2220 if (!base_from_cache)
2221 data = unpack_compressed_entry(p, &w_curs, curpos, size);
2222 break;
2223 default:
2224 data = NULL;
2225 error("unknown object type %i at offset %"PRIuMAX" in %s",
2226 type, (uintmax_t)obj_offset, p->pack_name);
2229 /* PHASE 3: apply deltas in order */
2231 /* invariants:
2232 * 'data' holds the base data, or NULL if there was corruption
2234 while (delta_stack_nr) {
2235 void *delta_data;
2236 void *base = data;
2237 unsigned long delta_size, base_size = size;
2238 int i;
2240 data = NULL;
2242 if (base)
2243 add_delta_base_cache(p, obj_offset, base, base_size, type);
2245 if (!base) {
2247 * We're probably in deep shit, but let's try to fetch
2248 * the required base anyway from another pack or loose.
2249 * This is costly but should happen only in the presence
2250 * of a corrupted pack, and is better than failing outright.
2252 struct revindex_entry *revidx;
2253 const unsigned char *base_sha1;
2254 revidx = find_pack_revindex(p, obj_offset);
2255 if (revidx) {
2256 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2257 error("failed to read delta base object %s"
2258 " at offset %"PRIuMAX" from %s",
2259 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2260 p->pack_name);
2261 mark_bad_packed_object(p, base_sha1);
2262 base = read_object(base_sha1, &type, &base_size);
2266 i = --delta_stack_nr;
2267 obj_offset = delta_stack[i].obj_offset;
2268 curpos = delta_stack[i].curpos;
2269 delta_size = delta_stack[i].size;
2271 if (!base)
2272 continue;
2274 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2276 if (!delta_data) {
2277 error("failed to unpack compressed delta "
2278 "at offset %"PRIuMAX" from %s",
2279 (uintmax_t)curpos, p->pack_name);
2280 data = NULL;
2281 continue;
2284 data = patch_delta(base, base_size,
2285 delta_data, delta_size,
2286 &size);
2289 * We could not apply the delta; warn the user, but keep going.
2290 * Our failure will be noticed either in the next iteration of
2291 * the loop, or if this is the final delta, in the caller when
2292 * we return NULL. Those code paths will take care of making
2293 * a more explicit warning and retrying with another copy of
2294 * the object.
2296 if (!data)
2297 error("failed to apply delta");
2299 free(delta_data);
2302 *final_type = type;
2303 *final_size = size;
2305 unuse_pack(&w_curs);
2306 return data;
2309 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2310 uint32_t n)
2312 const unsigned char *index = p->index_data;
2313 if (!index) {
2314 if (open_pack_index(p))
2315 return NULL;
2316 index = p->index_data;
2318 if (n >= p->num_objects)
2319 return NULL;
2320 index += 4 * 256;
2321 if (p->index_version == 1) {
2322 return index + 24 * n + 4;
2323 } else {
2324 index += 8;
2325 return index + 20 * n;
2329 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2331 const unsigned char *index = p->index_data;
2332 index += 4 * 256;
2333 if (p->index_version == 1) {
2334 return ntohl(*((uint32_t *)(index + 24 * n)));
2335 } else {
2336 uint32_t off;
2337 index += 8 + p->num_objects * (20 + 4);
2338 off = ntohl(*((uint32_t *)(index + 4 * n)));
2339 if (!(off & 0x80000000))
2340 return off;
2341 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2342 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2343 ntohl(*((uint32_t *)(index + 4)));
2347 off_t find_pack_entry_one(const unsigned char *sha1,
2348 struct packed_git *p)
2350 const uint32_t *level1_ofs = p->index_data;
2351 const unsigned char *index = p->index_data;
2352 unsigned hi, lo, stride;
2353 static int use_lookup = -1;
2354 static int debug_lookup = -1;
2356 if (debug_lookup < 0)
2357 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2359 if (!index) {
2360 if (open_pack_index(p))
2361 return 0;
2362 level1_ofs = p->index_data;
2363 index = p->index_data;
2365 if (p->index_version > 1) {
2366 level1_ofs += 2;
2367 index += 8;
2369 index += 4 * 256;
2370 hi = ntohl(level1_ofs[*sha1]);
2371 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2372 if (p->index_version > 1) {
2373 stride = 20;
2374 } else {
2375 stride = 24;
2376 index += 4;
2379 if (debug_lookup)
2380 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2381 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2383 if (use_lookup < 0)
2384 use_lookup = !!getenv("GIT_USE_LOOKUP");
2385 if (use_lookup) {
2386 int pos = sha1_entry_pos(index, stride, 0,
2387 lo, hi, p->num_objects, sha1);
2388 if (pos < 0)
2389 return 0;
2390 return nth_packed_object_offset(p, pos);
2393 do {
2394 unsigned mi = (lo + hi) / 2;
2395 int cmp = hashcmp(index + mi * stride, sha1);
2397 if (debug_lookup)
2398 printf("lo %u hi %u rg %u mi %u\n",
2399 lo, hi, hi - lo, mi);
2400 if (!cmp)
2401 return nth_packed_object_offset(p, mi);
2402 if (cmp > 0)
2403 hi = mi;
2404 else
2405 lo = mi+1;
2406 } while (lo < hi);
2407 return 0;
2410 int is_pack_valid(struct packed_git *p)
2412 /* An already open pack is known to be valid. */
2413 if (p->pack_fd != -1)
2414 return 1;
2416 /* If the pack has one window completely covering the
2417 * file size, the pack is known to be valid even if
2418 * the descriptor is not currently open.
2420 if (p->windows) {
2421 struct pack_window *w = p->windows;
2423 if (!w->offset && w->len == p->pack_size)
2424 return 1;
2427 /* Force the pack to open to prove its valid. */
2428 return !open_packed_git(p);
2431 static int fill_pack_entry(const unsigned char *sha1,
2432 struct pack_entry *e,
2433 struct packed_git *p)
2435 off_t offset;
2437 if (p->num_bad_objects) {
2438 unsigned i;
2439 for (i = 0; i < p->num_bad_objects; i++)
2440 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2441 return 0;
2444 offset = find_pack_entry_one(sha1, p);
2445 if (!offset)
2446 return 0;
2449 * We are about to tell the caller where they can locate the
2450 * requested object. We better make sure the packfile is
2451 * still here and can be accessed before supplying that
2452 * answer, as it may have been deleted since the index was
2453 * loaded!
2455 if (!is_pack_valid(p)) {
2456 warning("packfile %s cannot be accessed", p->pack_name);
2457 return 0;
2459 e->offset = offset;
2460 e->p = p;
2461 hashcpy(e->sha1, sha1);
2462 return 1;
2465 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2467 struct packed_git *p;
2469 prepare_packed_git();
2470 if (!packed_git)
2471 return 0;
2473 if (last_found_pack && fill_pack_entry(sha1, e, last_found_pack))
2474 return 1;
2476 for (p = packed_git; p; p = p->next) {
2477 if (p == last_found_pack || !fill_pack_entry(sha1, e, p))
2478 continue;
2480 last_found_pack = p;
2481 return 1;
2483 return 0;
2486 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2487 struct packed_git *packs)
2489 struct packed_git *p;
2491 for (p = packs; p; p = p->next) {
2492 if (find_pack_entry_one(sha1, p))
2493 return p;
2495 return NULL;
2499 static int sha1_loose_object_info(const unsigned char *sha1,
2500 struct object_info *oi)
2502 int status;
2503 unsigned long mapsize, size;
2504 void *map;
2505 git_zstream stream;
2506 char hdr[32];
2509 * If we don't care about type or size, then we don't
2510 * need to look inside the object at all. Note that we
2511 * do not optimize out the stat call, even if the
2512 * caller doesn't care about the disk-size, since our
2513 * return value implicitly indicates whether the
2514 * object even exists.
2516 if (!oi->typep && !oi->sizep) {
2517 struct stat st;
2518 if (stat_sha1_file(sha1, &st) < 0)
2519 return -1;
2520 if (oi->disk_sizep)
2521 *oi->disk_sizep = st.st_size;
2522 return 0;
2525 map = map_sha1_file(sha1, &mapsize);
2526 if (!map)
2527 return -1;
2528 if (oi->disk_sizep)
2529 *oi->disk_sizep = mapsize;
2530 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2531 status = error("unable to unpack %s header",
2532 sha1_to_hex(sha1));
2533 else if ((status = parse_sha1_header(hdr, &size)) < 0)
2534 status = error("unable to parse %s header", sha1_to_hex(sha1));
2535 else if (oi->sizep)
2536 *oi->sizep = size;
2537 git_inflate_end(&stream);
2538 munmap(map, mapsize);
2539 if (oi->typep)
2540 *oi->typep = status;
2541 return 0;
2544 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi)
2546 struct cached_object *co;
2547 struct pack_entry e;
2548 int rtype;
2550 co = find_cached_object(sha1);
2551 if (co) {
2552 if (oi->typep)
2553 *(oi->typep) = co->type;
2554 if (oi->sizep)
2555 *(oi->sizep) = co->size;
2556 if (oi->disk_sizep)
2557 *(oi->disk_sizep) = 0;
2558 oi->whence = OI_CACHED;
2559 return 0;
2562 if (!find_pack_entry(sha1, &e)) {
2563 /* Most likely it's a loose object. */
2564 if (!sha1_loose_object_info(sha1, oi)) {
2565 oi->whence = OI_LOOSE;
2566 return 0;
2569 /* Not a loose object; someone else may have just packed it. */
2570 reprepare_packed_git();
2571 if (!find_pack_entry(sha1, &e))
2572 return -1;
2575 rtype = packed_object_info(e.p, e.offset, oi);
2576 if (rtype < 0) {
2577 mark_bad_packed_object(e.p, sha1);
2578 return sha1_object_info_extended(sha1, oi);
2579 } else if (in_delta_base_cache(e.p, e.offset)) {
2580 oi->whence = OI_DBCACHED;
2581 } else {
2582 oi->whence = OI_PACKED;
2583 oi->u.packed.offset = e.offset;
2584 oi->u.packed.pack = e.p;
2585 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2586 rtype == OBJ_OFS_DELTA);
2589 return 0;
2592 /* returns enum object_type or negative */
2593 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2595 enum object_type type;
2596 struct object_info oi = {NULL};
2598 oi.typep = &type;
2599 oi.sizep = sizep;
2600 if (sha1_object_info_extended(sha1, &oi) < 0)
2601 return -1;
2602 return type;
2605 static void *read_packed_sha1(const unsigned char *sha1,
2606 enum object_type *type, unsigned long *size)
2608 struct pack_entry e;
2609 void *data;
2611 if (!find_pack_entry(sha1, &e))
2612 return NULL;
2613 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2614 if (!data) {
2616 * We're probably in deep shit, but let's try to fetch
2617 * the required object anyway from another pack or loose.
2618 * This should happen only in the presence of a corrupted
2619 * pack, and is better than failing outright.
2621 error("failed to read object %s at offset %"PRIuMAX" from %s",
2622 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2623 mark_bad_packed_object(e.p, sha1);
2624 data = read_object(sha1, type, size);
2626 return data;
2629 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2630 unsigned char *sha1)
2632 struct cached_object *co;
2634 hash_sha1_file(buf, len, typename(type), sha1);
2635 if (has_sha1_file(sha1) || find_cached_object(sha1))
2636 return 0;
2637 if (cached_object_alloc <= cached_object_nr) {
2638 cached_object_alloc = alloc_nr(cached_object_alloc);
2639 cached_objects = xrealloc(cached_objects,
2640 sizeof(*cached_objects) *
2641 cached_object_alloc);
2643 co = &cached_objects[cached_object_nr++];
2644 co->size = len;
2645 co->type = type;
2646 co->buf = xmalloc(len);
2647 memcpy(co->buf, buf, len);
2648 hashcpy(co->sha1, sha1);
2649 return 0;
2652 static void *read_object(const unsigned char *sha1, enum object_type *type,
2653 unsigned long *size)
2655 unsigned long mapsize;
2656 void *map, *buf;
2657 struct cached_object *co;
2659 co = find_cached_object(sha1);
2660 if (co) {
2661 *type = co->type;
2662 *size = co->size;
2663 return xmemdupz(co->buf, co->size);
2666 buf = read_packed_sha1(sha1, type, size);
2667 if (buf)
2668 return buf;
2669 map = map_sha1_file(sha1, &mapsize);
2670 if (map) {
2671 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2672 munmap(map, mapsize);
2673 return buf;
2675 reprepare_packed_git();
2676 return read_packed_sha1(sha1, type, size);
2680 * This function dies on corrupt objects; the callers who want to
2681 * deal with them should arrange to call read_object() and give error
2682 * messages themselves.
2684 void *read_sha1_file_extended(const unsigned char *sha1,
2685 enum object_type *type,
2686 unsigned long *size,
2687 unsigned flag)
2689 void *data;
2690 char *path;
2691 const struct packed_git *p;
2692 const unsigned char *repl = (flag & READ_SHA1_FILE_REPLACE)
2693 ? lookup_replace_object(sha1) : sha1;
2695 errno = 0;
2696 data = read_object(repl, type, size);
2697 if (data)
2698 return data;
2700 if (errno && errno != ENOENT)
2701 die_errno("failed to read object %s", sha1_to_hex(sha1));
2703 /* die if we replaced an object with one that does not exist */
2704 if (repl != sha1)
2705 die("replacement %s not found for %s",
2706 sha1_to_hex(repl), sha1_to_hex(sha1));
2708 if (has_loose_object(repl)) {
2709 path = sha1_file_name(sha1);
2710 die("loose object %s (stored in %s) is corrupt",
2711 sha1_to_hex(repl), path);
2714 if ((p = has_packed_and_bad(repl)) != NULL)
2715 die("packed object %s (stored in %s) is corrupt",
2716 sha1_to_hex(repl), p->pack_name);
2718 return NULL;
2721 void *read_object_with_reference(const unsigned char *sha1,
2722 const char *required_type_name,
2723 unsigned long *size,
2724 unsigned char *actual_sha1_return)
2726 enum object_type type, required_type;
2727 void *buffer;
2728 unsigned long isize;
2729 unsigned char actual_sha1[20];
2731 required_type = type_from_string(required_type_name);
2732 hashcpy(actual_sha1, sha1);
2733 while (1) {
2734 int ref_length = -1;
2735 const char *ref_type = NULL;
2737 buffer = read_sha1_file(actual_sha1, &type, &isize);
2738 if (!buffer)
2739 return NULL;
2740 if (type == required_type) {
2741 *size = isize;
2742 if (actual_sha1_return)
2743 hashcpy(actual_sha1_return, actual_sha1);
2744 return buffer;
2746 /* Handle references */
2747 else if (type == OBJ_COMMIT)
2748 ref_type = "tree ";
2749 else if (type == OBJ_TAG)
2750 ref_type = "object ";
2751 else {
2752 free(buffer);
2753 return NULL;
2755 ref_length = strlen(ref_type);
2757 if (ref_length + 40 > isize ||
2758 memcmp(buffer, ref_type, ref_length) ||
2759 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2760 free(buffer);
2761 return NULL;
2763 free(buffer);
2764 /* Now we have the ID of the referred-to object in
2765 * actual_sha1. Check again. */
2769 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2770 const char *type, unsigned char *sha1,
2771 char *hdr, int *hdrlen)
2773 git_SHA_CTX c;
2775 /* Generate the header */
2776 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2778 /* Sha1.. */
2779 git_SHA1_Init(&c);
2780 git_SHA1_Update(&c, hdr, *hdrlen);
2781 git_SHA1_Update(&c, buf, len);
2782 git_SHA1_Final(sha1, &c);
2786 * Move the just written object into its final resting place.
2787 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2788 * "moving" is only a part of what it does, when no patch between
2789 * master to pu changes the call sites of this function.
2791 int move_temp_to_file(const char *tmpfile, const char *filename)
2793 int ret = 0;
2795 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2796 goto try_rename;
2797 else if (link(tmpfile, filename))
2798 ret = errno;
2801 * Coda hack - coda doesn't like cross-directory links,
2802 * so we fall back to a rename, which will mean that it
2803 * won't be able to check collisions, but that's not a
2804 * big deal.
2806 * The same holds for FAT formatted media.
2808 * When this succeeds, we just return. We have nothing
2809 * left to unlink.
2811 if (ret && ret != EEXIST) {
2812 try_rename:
2813 if (!rename(tmpfile, filename))
2814 goto out;
2815 ret = errno;
2817 unlink_or_warn(tmpfile);
2818 if (ret) {
2819 if (ret != EEXIST) {
2820 return error("unable to write sha1 filename %s: %s", filename, strerror(ret));
2822 /* FIXME!!! Collision check here ? */
2825 out:
2826 if (adjust_shared_perm(filename))
2827 return error("unable to set permission to '%s'", filename);
2828 return 0;
2831 static int write_buffer(int fd, const void *buf, size_t len)
2833 if (write_in_full(fd, buf, len) < 0)
2834 return error("file write error (%s)", strerror(errno));
2835 return 0;
2838 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2839 unsigned char *sha1)
2841 char hdr[32];
2842 int hdrlen;
2843 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2844 return 0;
2847 /* Finalize a file on disk, and close it. */
2848 static void close_sha1_file(int fd)
2850 if (fsync_object_files)
2851 fsync_or_die(fd, "sha1 file");
2852 if (close(fd) != 0)
2853 die_errno("error when closing sha1 file");
2856 /* Size of directory component, including the ending '/' */
2857 static inline int directory_size(const char *filename)
2859 const char *s = strrchr(filename, '/');
2860 if (!s)
2861 return 0;
2862 return s - filename + 1;
2866 * This creates a temporary file in the same directory as the final
2867 * 'filename'
2869 * We want to avoid cross-directory filename renames, because those
2870 * can have problems on various filesystems (FAT, NFS, Coda).
2872 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2874 int fd, dirlen = directory_size(filename);
2876 if (dirlen + 20 > bufsiz) {
2877 errno = ENAMETOOLONG;
2878 return -1;
2880 memcpy(buffer, filename, dirlen);
2881 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2882 fd = git_mkstemp_mode(buffer, 0444);
2883 if (fd < 0 && dirlen && errno == ENOENT) {
2884 /* Make sure the directory exists */
2885 memcpy(buffer, filename, dirlen);
2886 buffer[dirlen-1] = 0;
2887 if (mkdir(buffer, 0777) && errno != EEXIST)
2888 return -1;
2889 if (adjust_shared_perm(buffer))
2890 return -1;
2892 /* Try again */
2893 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2894 fd = git_mkstemp_mode(buffer, 0444);
2896 return fd;
2899 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2900 const void *buf, unsigned long len, time_t mtime)
2902 int fd, ret;
2903 unsigned char compressed[4096];
2904 git_zstream stream;
2905 git_SHA_CTX c;
2906 unsigned char parano_sha1[20];
2907 char *filename;
2908 static char tmp_file[PATH_MAX];
2910 filename = sha1_file_name(sha1);
2911 fd = create_tmpfile(tmp_file, sizeof(tmp_file), filename);
2912 if (fd < 0) {
2913 if (errno == EACCES)
2914 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2915 else
2916 return error("unable to create temporary file: %s", strerror(errno));
2919 /* Set it up */
2920 memset(&stream, 0, sizeof(stream));
2921 git_deflate_init(&stream, zlib_compression_level);
2922 stream.next_out = compressed;
2923 stream.avail_out = sizeof(compressed);
2924 git_SHA1_Init(&c);
2926 /* First header.. */
2927 stream.next_in = (unsigned char *)hdr;
2928 stream.avail_in = hdrlen;
2929 while (git_deflate(&stream, 0) == Z_OK)
2930 ; /* nothing */
2931 git_SHA1_Update(&c, hdr, hdrlen);
2933 /* Then the data itself.. */
2934 stream.next_in = (void *)buf;
2935 stream.avail_in = len;
2936 do {
2937 unsigned char *in0 = stream.next_in;
2938 ret = git_deflate(&stream, Z_FINISH);
2939 git_SHA1_Update(&c, in0, stream.next_in - in0);
2940 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2941 die("unable to write sha1 file");
2942 stream.next_out = compressed;
2943 stream.avail_out = sizeof(compressed);
2944 } while (ret == Z_OK);
2946 if (ret != Z_STREAM_END)
2947 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2948 ret = git_deflate_end_gently(&stream);
2949 if (ret != Z_OK)
2950 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2951 git_SHA1_Final(parano_sha1, &c);
2952 if (hashcmp(sha1, parano_sha1) != 0)
2953 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2955 close_sha1_file(fd);
2957 if (mtime) {
2958 struct utimbuf utb;
2959 utb.actime = mtime;
2960 utb.modtime = mtime;
2961 if (utime(tmp_file, &utb) < 0)
2962 warning("failed utime() on %s: %s",
2963 tmp_file, strerror(errno));
2966 return move_temp_to_file(tmp_file, filename);
2969 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2971 unsigned char sha1[20];
2972 char hdr[32];
2973 int hdrlen;
2975 /* Normally if we have it in the pack then we do not bother writing
2976 * it out into .git/objects/??/?{38} file.
2978 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2979 if (returnsha1)
2980 hashcpy(returnsha1, sha1);
2981 if (has_sha1_file(sha1))
2982 return 0;
2983 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2986 int force_object_loose(const unsigned char *sha1, time_t mtime)
2988 void *buf;
2989 unsigned long len;
2990 enum object_type type;
2991 char hdr[32];
2992 int hdrlen;
2993 int ret;
2995 if (has_loose_object(sha1))
2996 return 0;
2997 buf = read_packed_sha1(sha1, &type, &len);
2998 if (!buf)
2999 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3000 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
3001 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3002 free(buf);
3004 return ret;
3007 int has_pack_index(const unsigned char *sha1)
3009 struct stat st;
3010 if (stat(sha1_pack_index_name(sha1), &st))
3011 return 0;
3012 return 1;
3015 int has_sha1_pack(const unsigned char *sha1)
3017 struct pack_entry e;
3018 return find_pack_entry(sha1, &e);
3021 int has_sha1_file(const unsigned char *sha1)
3023 struct pack_entry e;
3025 if (find_pack_entry(sha1, &e))
3026 return 1;
3027 if (has_loose_object(sha1))
3028 return 1;
3029 reprepare_packed_git();
3030 return find_pack_entry(sha1, &e);
3033 static void check_tree(const void *buf, size_t size)
3035 struct tree_desc desc;
3036 struct name_entry entry;
3038 init_tree_desc(&desc, buf, size);
3039 while (tree_entry(&desc, &entry))
3040 /* do nothing
3041 * tree_entry() will die() on malformed entries */
3045 static void check_commit(const void *buf, size_t size)
3047 struct commit c;
3048 memset(&c, 0, sizeof(c));
3049 if (parse_commit_buffer(&c, buf, size))
3050 die("corrupt commit");
3053 static void check_tag(const void *buf, size_t size)
3055 struct tag t;
3056 memset(&t, 0, sizeof(t));
3057 if (parse_tag_buffer(&t, buf, size))
3058 die("corrupt tag");
3061 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3062 enum object_type type,
3063 const char *path, unsigned flags)
3065 int ret, re_allocated = 0;
3066 int write_object = flags & HASH_WRITE_OBJECT;
3068 if (!type)
3069 type = OBJ_BLOB;
3072 * Convert blobs to git internal format
3074 if ((type == OBJ_BLOB) && path) {
3075 struct strbuf nbuf = STRBUF_INIT;
3076 if (convert_to_git(path, buf, size, &nbuf,
3077 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3078 buf = strbuf_detach(&nbuf, &size);
3079 re_allocated = 1;
3082 if (flags & HASH_FORMAT_CHECK) {
3083 if (type == OBJ_TREE)
3084 check_tree(buf, size);
3085 if (type == OBJ_COMMIT)
3086 check_commit(buf, size);
3087 if (type == OBJ_TAG)
3088 check_tag(buf, size);
3091 if (write_object)
3092 ret = write_sha1_file(buf, size, typename(type), sha1);
3093 else
3094 ret = hash_sha1_file(buf, size, typename(type), sha1);
3095 if (re_allocated)
3096 free(buf);
3097 return ret;
3100 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3101 const char *path, unsigned flags)
3103 struct strbuf sbuf = STRBUF_INIT;
3104 int ret;
3106 if (strbuf_read(&sbuf, fd, 4096) >= 0)
3107 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3108 else
3109 ret = -1;
3110 strbuf_release(&sbuf);
3111 return ret;
3114 #define SMALL_FILE_SIZE (32*1024)
3116 static int index_core(unsigned char *sha1, int fd, size_t size,
3117 enum object_type type, const char *path,
3118 unsigned flags)
3120 int ret;
3122 if (!size) {
3123 ret = index_mem(sha1, NULL, size, type, path, flags);
3124 } else if (size <= SMALL_FILE_SIZE) {
3125 char *buf = xmalloc(size);
3126 if (size == read_in_full(fd, buf, size))
3127 ret = index_mem(sha1, buf, size, type, path, flags);
3128 else
3129 ret = error("short read %s", strerror(errno));
3130 free(buf);
3131 } else {
3132 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3133 ret = index_mem(sha1, buf, size, type, path, flags);
3134 munmap(buf, size);
3136 return ret;
3140 * This creates one packfile per large blob unless bulk-checkin
3141 * machinery is "plugged".
3143 * This also bypasses the usual "convert-to-git" dance, and that is on
3144 * purpose. We could write a streaming version of the converting
3145 * functions and insert that before feeding the data to fast-import
3146 * (or equivalent in-core API described above). However, that is
3147 * somewhat complicated, as we do not know the size of the filter
3148 * result, which we need to know beforehand when writing a git object.
3149 * Since the primary motivation for trying to stream from the working
3150 * tree file and to avoid mmaping it in core is to deal with large
3151 * binary blobs, they generally do not want to get any conversion, and
3152 * callers should avoid this code path when filters are requested.
3154 static int index_stream(unsigned char *sha1, int fd, size_t size,
3155 enum object_type type, const char *path,
3156 unsigned flags)
3158 return index_bulk_checkin(sha1, fd, size, type, path, flags);
3161 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3162 enum object_type type, const char *path, unsigned flags)
3164 int ret;
3165 size_t size = xsize_t(st->st_size);
3167 if (!S_ISREG(st->st_mode))
3168 ret = index_pipe(sha1, fd, type, path, flags);
3169 else if (size <= big_file_threshold || type != OBJ_BLOB ||
3170 (path && would_convert_to_git(path, NULL, 0, 0)))
3171 ret = index_core(sha1, fd, size, type, path, flags);
3172 else
3173 ret = index_stream(sha1, fd, size, type, path, flags);
3174 close(fd);
3175 return ret;
3178 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3180 int fd;
3181 struct strbuf sb = STRBUF_INIT;
3183 switch (st->st_mode & S_IFMT) {
3184 case S_IFREG:
3185 fd = open(path, O_RDONLY);
3186 if (fd < 0)
3187 return error("open(\"%s\"): %s", path,
3188 strerror(errno));
3189 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3190 return error("%s: failed to insert into database",
3191 path);
3192 break;
3193 case S_IFLNK:
3194 if (strbuf_readlink(&sb, path, st->st_size)) {
3195 char *errstr = strerror(errno);
3196 return error("readlink(\"%s\"): %s", path,
3197 errstr);
3199 if (!(flags & HASH_WRITE_OBJECT))
3200 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3201 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3202 return error("%s: failed to insert into database",
3203 path);
3204 strbuf_release(&sb);
3205 break;
3206 case S_IFDIR:
3207 return resolve_gitlink_ref(path, "HEAD", sha1);
3208 default:
3209 return error("%s: unsupported file type", path);
3211 return 0;
3214 int read_pack_header(int fd, struct pack_header *header)
3216 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3217 /* "eof before pack header was fully read" */
3218 return PH_ERROR_EOF;
3220 if (header->hdr_signature != htonl(PACK_SIGNATURE))
3221 /* "protocol error (pack signature mismatch detected)" */
3222 return PH_ERROR_PACK_SIGNATURE;
3223 if (!pack_version_ok(header->hdr_version))
3224 /* "protocol error (pack version unsupported)" */
3225 return PH_ERROR_PROTOCOL;
3226 return 0;
3229 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3231 enum object_type type = sha1_object_info(sha1, NULL);
3232 if (type < 0)
3233 die("%s is not a valid object", sha1_to_hex(sha1));
3234 if (type != expect)
3235 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3236 typename(expect));