Make hash-object more robust against malformed objects
[git/mingw.git] / sha1_file.c
blob58ca85835b6d5d8d45c195139c594711dcac2228
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 "delta.h"
11 #include "pack.h"
12 #include "blob.h"
13 #include "commit.h"
14 #include "tag.h"
15 #include "tree.h"
16 #include "tree-walk.h"
17 #include "refs.h"
18 #include "pack-revindex.h"
19 #include "sha1-lookup.h"
21 #ifndef O_NOATIME
22 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
23 #define O_NOATIME 01000000
24 #else
25 #define O_NOATIME 0
26 #endif
27 #endif
29 #ifdef NO_C99_FORMAT
30 #define SZ_FMT "lu"
31 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
32 #else
33 #define SZ_FMT "zu"
34 static size_t sz_fmt(size_t s) { return s; }
35 #endif
37 const unsigned char null_sha1[20];
39 static int git_open_noatime(const char *name, struct packed_git *p);
41 int safe_create_leading_directories(char *path)
43 char *pos = path + offset_1st_component(path);
44 struct stat st;
46 while (pos) {
47 pos = strchr(pos, '/');
48 if (!pos)
49 break;
50 while (*++pos == '/')
52 if (!*pos)
53 break;
54 *--pos = '\0';
55 if (!stat(path, &st)) {
56 /* path exists */
57 if (!S_ISDIR(st.st_mode)) {
58 *pos = '/';
59 return -3;
62 else if (mkdir(path, 0777)) {
63 *pos = '/';
64 return -1;
66 else if (adjust_shared_perm(path)) {
67 *pos = '/';
68 return -2;
70 *pos++ = '/';
72 return 0;
75 int safe_create_leading_directories_const(const char *path)
77 /* path points to cache entries, so xstrdup before messing with it */
78 char *buf = xstrdup(path);
79 int result = safe_create_leading_directories(buf);
80 free(buf);
81 return result;
84 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
86 int i;
87 for (i = 0; i < 20; i++) {
88 static char hex[] = "0123456789abcdef";
89 unsigned int val = sha1[i];
90 char *pos = pathbuf + i*2 + (i > 0);
91 *pos++ = hex[val >> 4];
92 *pos = hex[val & 0xf];
97 * NOTE! This returns a statically allocated buffer, so you have to be
98 * careful about using it. Do an "xstrdup()" if you need to save the
99 * filename.
101 * Also note that this returns the location for creating. Reading
102 * SHA1 file can happen from any alternate directory listed in the
103 * DB_ENVIRONMENT environment variable if it is not found in
104 * the primary object database.
106 char *sha1_file_name(const unsigned char *sha1)
108 static char buf[PATH_MAX];
109 const char *objdir;
110 int len;
112 objdir = get_object_directory();
113 len = strlen(objdir);
115 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
116 if (len + 43 > PATH_MAX)
117 die("insanely long object directory %s", objdir);
118 memcpy(buf, objdir, len);
119 buf[len] = '/';
120 buf[len+3] = '/';
121 buf[len+42] = '\0';
122 fill_sha1_path(buf + len + 1, sha1);
123 return buf;
126 static char *sha1_get_pack_name(const unsigned char *sha1,
127 char **name, char **base, const char *which)
129 static const char hex[] = "0123456789abcdef";
130 char *buf;
131 int i;
133 if (!*base) {
134 const char *sha1_file_directory = get_object_directory();
135 int len = strlen(sha1_file_directory);
136 *base = xmalloc(len + 60);
137 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
138 sha1_file_directory, which);
139 *name = *base + len + 11;
142 buf = *name;
144 for (i = 0; i < 20; i++) {
145 unsigned int val = *sha1++;
146 *buf++ = hex[val >> 4];
147 *buf++ = hex[val & 0xf];
150 return *base;
153 char *sha1_pack_name(const unsigned char *sha1)
155 static char *name, *base;
157 return sha1_get_pack_name(sha1, &name, &base, "pack");
160 char *sha1_pack_index_name(const unsigned char *sha1)
162 static char *name, *base;
164 return sha1_get_pack_name(sha1, &name, &base, "idx");
167 struct alternate_object_database *alt_odb_list;
168 static struct alternate_object_database **alt_odb_tail;
170 static void read_info_alternates(const char * alternates, int depth);
173 * Prepare alternate object database registry.
175 * The variable alt_odb_list points at the list of struct
176 * alternate_object_database. The elements on this list come from
177 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
178 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
179 * whose contents is similar to that environment variable but can be
180 * LF separated. Its base points at a statically allocated buffer that
181 * contains "/the/directory/corresponding/to/.git/objects/...", while
182 * its name points just after the slash at the end of ".git/objects/"
183 * in the example above, and has enough space to hold 40-byte hex
184 * SHA1, an extra slash for the first level indirection, and the
185 * terminating NUL.
187 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
189 const char *objdir = get_object_directory();
190 struct alternate_object_database *ent;
191 struct alternate_object_database *alt;
192 /* 43 = 40-byte + 2 '/' + terminating NUL */
193 int pfxlen = len;
194 int entlen = pfxlen + 43;
195 int base_len = -1;
197 if (!is_absolute_path(entry) && relative_base) {
198 /* Relative alt-odb */
199 if (base_len < 0)
200 base_len = strlen(relative_base) + 1;
201 entlen += base_len;
202 pfxlen += base_len;
204 ent = xmalloc(sizeof(*ent) + entlen);
206 if (!is_absolute_path(entry) && relative_base) {
207 memcpy(ent->base, relative_base, base_len - 1);
208 ent->base[base_len - 1] = '/';
209 memcpy(ent->base + base_len, entry, len);
211 else
212 memcpy(ent->base, entry, pfxlen);
214 ent->name = ent->base + pfxlen + 1;
215 ent->base[pfxlen + 3] = '/';
216 ent->base[pfxlen] = ent->base[entlen-1] = 0;
218 /* Detect cases where alternate disappeared */
219 if (!is_directory(ent->base)) {
220 error("object directory %s does not exist; "
221 "check .git/objects/info/alternates.",
222 ent->base);
223 free(ent);
224 return -1;
227 /* Prevent the common mistake of listing the same
228 * thing twice, or object directory itself.
230 for (alt = alt_odb_list; alt; alt = alt->next) {
231 if (!memcmp(ent->base, alt->base, pfxlen)) {
232 free(ent);
233 return -1;
236 if (!memcmp(ent->base, objdir, pfxlen)) {
237 free(ent);
238 return -1;
241 /* add the alternate entry */
242 *alt_odb_tail = ent;
243 alt_odb_tail = &(ent->next);
244 ent->next = NULL;
246 /* recursively add alternates */
247 read_info_alternates(ent->base, depth + 1);
249 ent->base[pfxlen] = '/';
251 return 0;
254 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
255 const char *relative_base, int depth)
257 const char *cp, *last;
259 if (depth > 5) {
260 error("%s: ignoring alternate object stores, nesting too deep.",
261 relative_base);
262 return;
265 last = alt;
266 while (last < ep) {
267 cp = last;
268 if (cp < ep && *cp == '#') {
269 while (cp < ep && *cp != sep)
270 cp++;
271 last = cp + 1;
272 continue;
274 while (cp < ep && *cp != sep)
275 cp++;
276 if (last != cp) {
277 if (!is_absolute_path(last) && depth) {
278 error("%s: ignoring relative alternate object store %s",
279 relative_base, last);
280 } else {
281 link_alt_odb_entry(last, cp - last,
282 relative_base, depth);
285 while (cp < ep && *cp == sep)
286 cp++;
287 last = cp;
291 static void read_info_alternates(const char * relative_base, int depth)
293 char *map;
294 size_t mapsz;
295 struct stat st;
296 const char alt_file_name[] = "info/alternates";
297 /* Given that relative_base is no longer than PATH_MAX,
298 ensure that "path" has enough space to append "/", the
299 file name, "info/alternates", and a trailing NUL. */
300 char path[PATH_MAX + 1 + sizeof alt_file_name];
301 int fd;
303 sprintf(path, "%s/%s", relative_base, alt_file_name);
304 fd = git_open_noatime(path, NULL);
305 if (fd < 0)
306 return;
307 if (fstat(fd, &st) || (st.st_size == 0)) {
308 close(fd);
309 return;
311 mapsz = xsize_t(st.st_size);
312 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
313 close(fd);
315 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
317 munmap(map, mapsz);
320 void add_to_alternates_file(const char *reference)
322 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
323 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
324 char *alt = mkpath("%s/objects\n", reference);
325 write_or_die(fd, alt, strlen(alt));
326 if (commit_lock_file(lock))
327 die("could not close alternates file");
328 if (alt_odb_tail)
329 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
332 void foreach_alt_odb(alt_odb_fn fn, void *cb)
334 struct alternate_object_database *ent;
336 prepare_alt_odb();
337 for (ent = alt_odb_list; ent; ent = ent->next)
338 if (fn(ent, cb))
339 return;
342 void prepare_alt_odb(void)
344 const char *alt;
346 if (alt_odb_tail)
347 return;
349 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
350 if (!alt) alt = "";
352 alt_odb_tail = &alt_odb_list;
353 link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
355 read_info_alternates(get_object_directory(), 0);
358 static int has_loose_object_local(const unsigned char *sha1)
360 char *name = sha1_file_name(sha1);
361 return !access(name, F_OK);
364 int has_loose_object_nonlocal(const unsigned char *sha1)
366 struct alternate_object_database *alt;
367 prepare_alt_odb();
368 for (alt = alt_odb_list; alt; alt = alt->next) {
369 fill_sha1_path(alt->name, sha1);
370 if (!access(alt->base, F_OK))
371 return 1;
373 return 0;
376 static int has_loose_object(const unsigned char *sha1)
378 return has_loose_object_local(sha1) ||
379 has_loose_object_nonlocal(sha1);
382 static unsigned int pack_used_ctr;
383 static unsigned int pack_mmap_calls;
384 static unsigned int peak_pack_open_windows;
385 static unsigned int pack_open_windows;
386 static size_t peak_pack_mapped;
387 static size_t pack_mapped;
388 struct packed_git *packed_git;
390 void pack_report(void)
392 fprintf(stderr,
393 "pack_report: getpagesize() = %10" SZ_FMT "\n"
394 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
395 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
396 sz_fmt(getpagesize()),
397 sz_fmt(packed_git_window_size),
398 sz_fmt(packed_git_limit));
399 fprintf(stderr,
400 "pack_report: pack_used_ctr = %10u\n"
401 "pack_report: pack_mmap_calls = %10u\n"
402 "pack_report: pack_open_windows = %10u / %10u\n"
403 "pack_report: pack_mapped = "
404 "%10" SZ_FMT " / %10" SZ_FMT "\n",
405 pack_used_ctr,
406 pack_mmap_calls,
407 pack_open_windows, peak_pack_open_windows,
408 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
411 static int check_packed_git_idx(const char *path, struct packed_git *p)
413 void *idx_map;
414 struct pack_idx_header *hdr;
415 size_t idx_size;
416 uint32_t version, nr, i, *index;
417 int fd = git_open_noatime(path, p);
418 struct stat st;
420 if (fd < 0)
421 return -1;
422 if (fstat(fd, &st)) {
423 close(fd);
424 return -1;
426 idx_size = xsize_t(st.st_size);
427 if (idx_size < 4 * 256 + 20 + 20) {
428 close(fd);
429 return error("index file %s is too small", path);
431 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
432 close(fd);
434 hdr = idx_map;
435 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
436 version = ntohl(hdr->idx_version);
437 if (version < 2 || version > 2) {
438 munmap(idx_map, idx_size);
439 return error("index file %s is version %"PRIu32
440 " and is not supported by this binary"
441 " (try upgrading GIT to a newer version)",
442 path, version);
444 } else
445 version = 1;
447 nr = 0;
448 index = idx_map;
449 if (version > 1)
450 index += 2; /* skip index header */
451 for (i = 0; i < 256; i++) {
452 uint32_t n = ntohl(index[i]);
453 if (n < nr) {
454 munmap(idx_map, idx_size);
455 return error("non-monotonic index %s", path);
457 nr = n;
460 if (version == 1) {
462 * Total size:
463 * - 256 index entries 4 bytes each
464 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
465 * - 20-byte SHA1 of the packfile
466 * - 20-byte SHA1 file checksum
468 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
469 munmap(idx_map, idx_size);
470 return error("wrong index v1 file size in %s", path);
472 } else if (version == 2) {
474 * Minimum size:
475 * - 8 bytes of header
476 * - 256 index entries 4 bytes each
477 * - 20-byte sha1 entry * nr
478 * - 4-byte crc entry * nr
479 * - 4-byte offset entry * nr
480 * - 20-byte SHA1 of the packfile
481 * - 20-byte SHA1 file checksum
482 * And after the 4-byte offset table might be a
483 * variable sized table containing 8-byte entries
484 * for offsets larger than 2^31.
486 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
487 unsigned long max_size = min_size;
488 if (nr)
489 max_size += (nr - 1)*8;
490 if (idx_size < min_size || idx_size > max_size) {
491 munmap(idx_map, idx_size);
492 return error("wrong index v2 file size in %s", path);
494 if (idx_size != min_size &&
496 * make sure we can deal with large pack offsets.
497 * 31-bit signed offset won't be enough, neither
498 * 32-bit unsigned one will be.
500 (sizeof(off_t) <= 4)) {
501 munmap(idx_map, idx_size);
502 return error("pack too large for current definition of off_t in %s", path);
506 p->index_version = version;
507 p->index_data = idx_map;
508 p->index_size = idx_size;
509 p->num_objects = nr;
510 return 0;
513 int open_pack_index(struct packed_git *p)
515 char *idx_name;
516 int ret;
518 if (p->index_data)
519 return 0;
521 idx_name = xstrdup(p->pack_name);
522 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
523 ret = check_packed_git_idx(idx_name, p);
524 free(idx_name);
525 return ret;
528 static void scan_windows(struct packed_git *p,
529 struct packed_git **lru_p,
530 struct pack_window **lru_w,
531 struct pack_window **lru_l)
533 struct pack_window *w, *w_l;
535 for (w_l = NULL, w = p->windows; w; w = w->next) {
536 if (!w->inuse_cnt) {
537 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
538 *lru_p = p;
539 *lru_w = w;
540 *lru_l = w_l;
543 w_l = w;
547 static int unuse_one_window(struct packed_git *current, int keep_fd)
549 struct packed_git *p, *lru_p = NULL;
550 struct pack_window *lru_w = NULL, *lru_l = NULL;
552 if (current)
553 scan_windows(current, &lru_p, &lru_w, &lru_l);
554 for (p = packed_git; p; p = p->next)
555 scan_windows(p, &lru_p, &lru_w, &lru_l);
556 if (lru_p) {
557 munmap(lru_w->base, lru_w->len);
558 pack_mapped -= lru_w->len;
559 if (lru_l)
560 lru_l->next = lru_w->next;
561 else {
562 lru_p->windows = lru_w->next;
563 if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
564 close(lru_p->pack_fd);
565 lru_p->pack_fd = -1;
568 free(lru_w);
569 pack_open_windows--;
570 return 1;
572 return 0;
575 void release_pack_memory(size_t need, int fd)
577 size_t cur = pack_mapped;
578 while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
579 ; /* nothing */
582 void *xmmap(void *start, size_t length,
583 int prot, int flags, int fd, off_t offset)
585 void *ret = mmap(start, length, prot, flags, fd, offset);
586 if (ret == MAP_FAILED) {
587 if (!length)
588 return NULL;
589 release_pack_memory(length, fd);
590 ret = mmap(start, length, prot, flags, fd, offset);
591 if (ret == MAP_FAILED)
592 die_errno("Out of memory? mmap failed");
594 return ret;
597 void close_pack_windows(struct packed_git *p)
599 while (p->windows) {
600 struct pack_window *w = p->windows;
602 if (w->inuse_cnt)
603 die("pack '%s' still has open windows to it",
604 p->pack_name);
605 munmap(w->base, w->len);
606 pack_mapped -= w->len;
607 pack_open_windows--;
608 p->windows = w->next;
609 free(w);
613 void unuse_pack(struct pack_window **w_cursor)
615 struct pack_window *w = *w_cursor;
616 if (w) {
617 w->inuse_cnt--;
618 *w_cursor = NULL;
622 void close_pack_index(struct packed_git *p)
624 if (p->index_data) {
625 munmap((void *)p->index_data, p->index_size);
626 p->index_data = NULL;
631 * This is used by git-repack in case a newly created pack happens to
632 * contain the same set of objects as an existing one. In that case
633 * the resulting file might be different even if its name would be the
634 * same. It is best to close any reference to the old pack before it is
635 * replaced on disk. Of course no index pointers nor windows for given pack
636 * must subsist at this point. If ever objects from this pack are requested
637 * again, the new version of the pack will be reinitialized through
638 * reprepare_packed_git().
640 void free_pack_by_name(const char *pack_name)
642 struct packed_git *p, **pp = &packed_git;
644 while (*pp) {
645 p = *pp;
646 if (strcmp(pack_name, p->pack_name) == 0) {
647 clear_delta_base_cache();
648 close_pack_windows(p);
649 if (p->pack_fd != -1)
650 close(p->pack_fd);
651 close_pack_index(p);
652 free(p->bad_object_sha1);
653 *pp = p->next;
654 free(p);
655 return;
657 pp = &p->next;
662 * Do not call this directly as this leaks p->pack_fd on error return;
663 * call open_packed_git() instead.
665 static int open_packed_git_1(struct packed_git *p)
667 struct stat st;
668 struct pack_header hdr;
669 unsigned char sha1[20];
670 unsigned char *idx_sha1;
671 long fd_flag;
673 if (!p->index_data && open_pack_index(p))
674 return error("packfile %s index unavailable", p->pack_name);
676 p->pack_fd = git_open_noatime(p->pack_name, p);
677 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
678 return -1;
680 /* If we created the struct before we had the pack we lack size. */
681 if (!p->pack_size) {
682 if (!S_ISREG(st.st_mode))
683 return error("packfile %s not a regular file", p->pack_name);
684 p->pack_size = st.st_size;
685 } else if (p->pack_size != st.st_size)
686 return error("packfile %s size changed", p->pack_name);
688 /* We leave these file descriptors open with sliding mmap;
689 * there is no point keeping them open across exec(), though.
691 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
692 if (fd_flag < 0)
693 return error("cannot determine file descriptor flags");
694 fd_flag |= FD_CLOEXEC;
695 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
696 return error("cannot set FD_CLOEXEC");
698 /* Verify we recognize this pack file format. */
699 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
700 return error("file %s is far too short to be a packfile", p->pack_name);
701 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
702 return error("file %s is not a GIT packfile", p->pack_name);
703 if (!pack_version_ok(hdr.hdr_version))
704 return error("packfile %s is version %"PRIu32" and not"
705 " supported (try upgrading GIT to a newer version)",
706 p->pack_name, ntohl(hdr.hdr_version));
708 /* Verify the pack matches its index. */
709 if (p->num_objects != ntohl(hdr.hdr_entries))
710 return error("packfile %s claims to have %"PRIu32" objects"
711 " while index indicates %"PRIu32" objects",
712 p->pack_name, ntohl(hdr.hdr_entries),
713 p->num_objects);
714 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
715 return error("end of packfile %s is unavailable", p->pack_name);
716 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
717 return error("packfile %s signature is unavailable", p->pack_name);
718 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
719 if (hashcmp(sha1, idx_sha1))
720 return error("packfile %s does not match index", p->pack_name);
721 return 0;
724 static int open_packed_git(struct packed_git *p)
726 if (!open_packed_git_1(p))
727 return 0;
728 if (p->pack_fd != -1) {
729 close(p->pack_fd);
730 p->pack_fd = -1;
732 return -1;
735 static int in_window(struct pack_window *win, off_t offset)
737 /* We must promise at least 20 bytes (one hash) after the
738 * offset is available from this window, otherwise the offset
739 * is not actually in this window and a different window (which
740 * has that one hash excess) must be used. This is to support
741 * the object header and delta base parsing routines below.
743 off_t win_off = win->offset;
744 return win_off <= offset
745 && (offset + 20) <= (win_off + win->len);
748 unsigned char *use_pack(struct packed_git *p,
749 struct pack_window **w_cursor,
750 off_t offset,
751 unsigned int *left)
753 struct pack_window *win = *w_cursor;
755 if (p->pack_fd == -1 && open_packed_git(p))
756 die("packfile %s cannot be accessed", p->pack_name);
758 /* Since packfiles end in a hash of their content and it's
759 * pointless to ask for an offset into the middle of that
760 * hash, and the in_window function above wouldn't match
761 * don't allow an offset too close to the end of the file.
763 if (offset > (p->pack_size - 20))
764 die("offset beyond end of packfile (truncated pack?)");
766 if (!win || !in_window(win, offset)) {
767 if (win)
768 win->inuse_cnt--;
769 for (win = p->windows; win; win = win->next) {
770 if (in_window(win, offset))
771 break;
773 if (!win) {
774 size_t window_align = packed_git_window_size / 2;
775 off_t len;
776 win = xcalloc(1, sizeof(*win));
777 win->offset = (offset / window_align) * window_align;
778 len = p->pack_size - win->offset;
779 if (len > packed_git_window_size)
780 len = packed_git_window_size;
781 win->len = (size_t)len;
782 pack_mapped += win->len;
783 while (packed_git_limit < pack_mapped
784 && unuse_one_window(p, p->pack_fd))
785 ; /* nothing */
786 win->base = xmmap(NULL, win->len,
787 PROT_READ, MAP_PRIVATE,
788 p->pack_fd, win->offset);
789 if (win->base == MAP_FAILED)
790 die("packfile %s cannot be mapped: %s",
791 p->pack_name,
792 strerror(errno));
793 pack_mmap_calls++;
794 pack_open_windows++;
795 if (pack_mapped > peak_pack_mapped)
796 peak_pack_mapped = pack_mapped;
797 if (pack_open_windows > peak_pack_open_windows)
798 peak_pack_open_windows = pack_open_windows;
799 win->next = p->windows;
800 p->windows = win;
803 if (win != *w_cursor) {
804 win->last_used = pack_used_ctr++;
805 win->inuse_cnt++;
806 *w_cursor = win;
808 offset -= win->offset;
809 if (left)
810 *left = win->len - xsize_t(offset);
811 return win->base + offset;
814 static struct packed_git *alloc_packed_git(int extra)
816 struct packed_git *p = xmalloc(sizeof(*p) + extra);
817 memset(p, 0, sizeof(*p));
818 p->pack_fd = -1;
819 return p;
822 static void try_to_free_pack_memory(size_t size)
824 release_pack_memory(size, -1);
827 struct packed_git *add_packed_git(const char *path, int path_len, int local)
829 static int have_set_try_to_free_routine;
830 struct stat st;
831 struct packed_git *p = alloc_packed_git(path_len + 2);
833 if (!have_set_try_to_free_routine) {
834 have_set_try_to_free_routine = 1;
835 set_try_to_free_routine(try_to_free_pack_memory);
839 * Make sure a corresponding .pack file exists and that
840 * the index looks sane.
842 path_len -= strlen(".idx");
843 if (path_len < 1) {
844 free(p);
845 return NULL;
847 memcpy(p->pack_name, path, path_len);
849 strcpy(p->pack_name + path_len, ".keep");
850 if (!access(p->pack_name, F_OK))
851 p->pack_keep = 1;
853 strcpy(p->pack_name + path_len, ".pack");
854 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
855 free(p);
856 return NULL;
859 /* ok, it looks sane as far as we can check without
860 * actually mapping the pack file.
862 p->pack_size = st.st_size;
863 p->pack_local = local;
864 p->mtime = st.st_mtime;
865 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
866 hashclr(p->sha1);
867 return p;
870 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
872 const char *path = sha1_pack_name(sha1);
873 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
875 strcpy(p->pack_name, path);
876 hashcpy(p->sha1, sha1);
877 if (check_packed_git_idx(idx_path, p)) {
878 free(p);
879 return NULL;
882 return p;
885 void install_packed_git(struct packed_git *pack)
887 pack->next = packed_git;
888 packed_git = pack;
891 static void prepare_packed_git_one(char *objdir, int local)
893 /* Ensure that this buffer is large enough so that we can
894 append "/pack/" without clobbering the stack even if
895 strlen(objdir) were PATH_MAX. */
896 char path[PATH_MAX + 1 + 4 + 1 + 1];
897 int len;
898 DIR *dir;
899 struct dirent *de;
901 sprintf(path, "%s/pack", objdir);
902 len = strlen(path);
903 dir = opendir(path);
904 while (!dir && errno == EMFILE && unuse_one_window(NULL, -1))
905 dir = opendir(path);
906 if (!dir) {
907 if (errno != ENOENT)
908 error("unable to open object pack directory: %s: %s",
909 path, strerror(errno));
910 return;
912 path[len++] = '/';
913 while ((de = readdir(dir)) != NULL) {
914 int namelen = strlen(de->d_name);
915 struct packed_git *p;
917 if (!has_extension(de->d_name, ".idx"))
918 continue;
920 if (len + namelen + 1 > sizeof(path))
921 continue;
923 /* Don't reopen a pack we already have. */
924 strcpy(path + len, de->d_name);
925 for (p = packed_git; p; p = p->next) {
926 if (!memcmp(path, p->pack_name, len + namelen - 4))
927 break;
929 if (p)
930 continue;
931 /* See if it really is a valid .idx file with corresponding
932 * .pack file that we can map.
934 p = add_packed_git(path, len + namelen, local);
935 if (!p)
936 continue;
937 install_packed_git(p);
939 closedir(dir);
942 static int sort_pack(const void *a_, const void *b_)
944 struct packed_git *a = *((struct packed_git **)a_);
945 struct packed_git *b = *((struct packed_git **)b_);
946 int st;
949 * Local packs tend to contain objects specific to our
950 * variant of the project than remote ones. In addition,
951 * remote ones could be on a network mounted filesystem.
952 * Favor local ones for these reasons.
954 st = a->pack_local - b->pack_local;
955 if (st)
956 return -st;
959 * Younger packs tend to contain more recent objects,
960 * and more recent objects tend to get accessed more
961 * often.
963 if (a->mtime < b->mtime)
964 return 1;
965 else if (a->mtime == b->mtime)
966 return 0;
967 return -1;
970 static void rearrange_packed_git(void)
972 struct packed_git **ary, *p;
973 int i, n;
975 for (n = 0, p = packed_git; p; p = p->next)
976 n++;
977 if (n < 2)
978 return;
980 /* prepare an array of packed_git for easier sorting */
981 ary = xcalloc(n, sizeof(struct packed_git *));
982 for (n = 0, p = packed_git; p; p = p->next)
983 ary[n++] = p;
985 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
987 /* link them back again */
988 for (i = 0; i < n - 1; i++)
989 ary[i]->next = ary[i + 1];
990 ary[n - 1]->next = NULL;
991 packed_git = ary[0];
993 free(ary);
996 static int prepare_packed_git_run_once = 0;
997 void prepare_packed_git(void)
999 struct alternate_object_database *alt;
1001 if (prepare_packed_git_run_once)
1002 return;
1003 prepare_packed_git_one(get_object_directory(), 1);
1004 prepare_alt_odb();
1005 for (alt = alt_odb_list; alt; alt = alt->next) {
1006 alt->name[-1] = 0;
1007 prepare_packed_git_one(alt->base, 0);
1008 alt->name[-1] = '/';
1010 rearrange_packed_git();
1011 prepare_packed_git_run_once = 1;
1014 void reprepare_packed_git(void)
1016 discard_revindex();
1017 prepare_packed_git_run_once = 0;
1018 prepare_packed_git();
1021 static void mark_bad_packed_object(struct packed_git *p,
1022 const unsigned char *sha1)
1024 unsigned i;
1025 for (i = 0; i < p->num_bad_objects; i++)
1026 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1027 return;
1028 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1029 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1030 p->num_bad_objects++;
1033 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1035 struct packed_git *p;
1036 unsigned i;
1038 for (p = packed_git; p; p = p->next)
1039 for (i = 0; i < p->num_bad_objects; i++)
1040 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1041 return p;
1042 return NULL;
1045 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1047 unsigned char real_sha1[20];
1048 hash_sha1_file(map, size, type, real_sha1);
1049 return hashcmp(sha1, real_sha1) ? -1 : 0;
1052 static int git_open_noatime(const char *name, struct packed_git *p)
1054 static int sha1_file_open_flag = O_NOATIME;
1056 for (;;) {
1057 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1058 if (fd >= 0)
1059 return fd;
1061 /* Might the failure be insufficient file descriptors? */
1062 if (errno == EMFILE) {
1063 if (unuse_one_window(p, -1))
1064 continue;
1065 else
1066 return -1;
1069 /* Might the failure be due to O_NOATIME? */
1070 if (errno != ENOENT && sha1_file_open_flag) {
1071 sha1_file_open_flag = 0;
1072 continue;
1075 return -1;
1079 static int open_sha1_file(const unsigned char *sha1)
1081 int fd;
1082 char *name = sha1_file_name(sha1);
1083 struct alternate_object_database *alt;
1085 fd = git_open_noatime(name, NULL);
1086 if (fd >= 0)
1087 return fd;
1089 prepare_alt_odb();
1090 errno = ENOENT;
1091 for (alt = alt_odb_list; alt; alt = alt->next) {
1092 name = alt->name;
1093 fill_sha1_path(name, sha1);
1094 fd = git_open_noatime(alt->base, NULL);
1095 if (fd >= 0)
1096 return fd;
1098 return -1;
1101 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1103 void *map;
1104 int fd;
1106 fd = open_sha1_file(sha1);
1107 map = NULL;
1108 if (fd >= 0) {
1109 struct stat st;
1111 if (!fstat(fd, &st)) {
1112 *size = xsize_t(st.st_size);
1113 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1115 close(fd);
1117 return map;
1120 static int legacy_loose_object(unsigned char *map)
1122 unsigned int word;
1125 * Is it a zlib-compressed buffer? If so, the first byte
1126 * must be 0x78 (15-bit window size, deflated), and the
1127 * first 16-bit word is evenly divisible by 31
1129 word = (map[0] << 8) + map[1];
1130 if (map[0] == 0x78 && !(word % 31))
1131 return 1;
1132 else
1133 return 0;
1136 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1137 unsigned long len, enum object_type *type, unsigned long *sizep)
1139 unsigned shift;
1140 unsigned long size, c;
1141 unsigned long used = 0;
1143 c = buf[used++];
1144 *type = (c >> 4) & 7;
1145 size = c & 15;
1146 shift = 4;
1147 while (c & 0x80) {
1148 if (len <= used || bitsizeof(long) <= shift) {
1149 error("bad object header");
1150 return 0;
1152 c = buf[used++];
1153 size += (c & 0x7f) << shift;
1154 shift += 7;
1156 *sizep = size;
1157 return used;
1160 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1162 unsigned long size, used;
1163 static const char valid_loose_object_type[8] = {
1164 0, /* OBJ_EXT */
1165 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1166 0, /* "delta" and others are invalid in a loose object */
1168 enum object_type type;
1170 /* Get the data stream */
1171 memset(stream, 0, sizeof(*stream));
1172 stream->next_in = map;
1173 stream->avail_in = mapsize;
1174 stream->next_out = buffer;
1175 stream->avail_out = bufsiz;
1177 if (legacy_loose_object(map)) {
1178 git_inflate_init(stream);
1179 return git_inflate(stream, 0);
1184 * There used to be a second loose object header format which
1185 * was meant to mimic the in-pack format, allowing for direct
1186 * copy of the object data. This format turned up not to be
1187 * really worth it and we don't write it any longer. But we
1188 * can still read it.
1190 used = unpack_object_header_buffer(map, mapsize, &type, &size);
1191 if (!used || !valid_loose_object_type[type])
1192 return -1;
1193 map += used;
1194 mapsize -= used;
1196 /* Set up the stream for the rest.. */
1197 stream->next_in = map;
1198 stream->avail_in = mapsize;
1199 git_inflate_init(stream);
1201 /* And generate the fake traditional header */
1202 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1203 typename(type), size);
1204 return 0;
1207 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1209 int bytes = strlen(buffer) + 1;
1210 unsigned char *buf = xmallocz(size);
1211 unsigned long n;
1212 int status = Z_OK;
1214 n = stream->total_out - bytes;
1215 if (n > size)
1216 n = size;
1217 memcpy(buf, (char *) buffer + bytes, n);
1218 bytes = n;
1219 if (bytes <= size) {
1221 * The above condition must be (bytes <= size), not
1222 * (bytes < size). In other words, even though we
1223 * expect no more output and set avail_out to zer0,
1224 * the input zlib stream may have bytes that express
1225 * "this concludes the stream", and we *do* want to
1226 * eat that input.
1228 * Otherwise we would not be able to test that we
1229 * consumed all the input to reach the expected size;
1230 * we also want to check that zlib tells us that all
1231 * went well with status == Z_STREAM_END at the end.
1233 stream->next_out = buf + bytes;
1234 stream->avail_out = size - bytes;
1235 while (status == Z_OK)
1236 status = git_inflate(stream, Z_FINISH);
1238 if (status == Z_STREAM_END && !stream->avail_in) {
1239 git_inflate_end(stream);
1240 return buf;
1243 if (status < 0)
1244 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1245 else if (stream->avail_in)
1246 error("garbage at end of loose object '%s'",
1247 sha1_to_hex(sha1));
1248 free(buf);
1249 return NULL;
1253 * We used to just use "sscanf()", but that's actually way
1254 * too permissive for what we want to check. So do an anal
1255 * object header parse by hand.
1257 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1259 char type[10];
1260 int i;
1261 unsigned long size;
1264 * The type can be at most ten bytes (including the
1265 * terminating '\0' that we add), and is followed by
1266 * a space.
1268 i = 0;
1269 for (;;) {
1270 char c = *hdr++;
1271 if (c == ' ')
1272 break;
1273 type[i++] = c;
1274 if (i >= sizeof(type))
1275 return -1;
1277 type[i] = 0;
1280 * The length must follow immediately, and be in canonical
1281 * decimal format (ie "010" is not valid).
1283 size = *hdr++ - '0';
1284 if (size > 9)
1285 return -1;
1286 if (size) {
1287 for (;;) {
1288 unsigned long c = *hdr - '0';
1289 if (c > 9)
1290 break;
1291 hdr++;
1292 size = size * 10 + c;
1295 *sizep = size;
1298 * The length must be followed by a zero byte
1300 return *hdr ? -1 : type_from_string(type);
1303 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1305 int ret;
1306 z_stream stream;
1307 char hdr[8192];
1309 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1310 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1311 return NULL;
1313 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1316 unsigned long get_size_from_delta(struct packed_git *p,
1317 struct pack_window **w_curs,
1318 off_t curpos)
1320 const unsigned char *data;
1321 unsigned char delta_head[20], *in;
1322 z_stream stream;
1323 int st;
1325 memset(&stream, 0, sizeof(stream));
1326 stream.next_out = delta_head;
1327 stream.avail_out = sizeof(delta_head);
1329 git_inflate_init(&stream);
1330 do {
1331 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1332 stream.next_in = in;
1333 st = git_inflate(&stream, Z_FINISH);
1334 curpos += stream.next_in - in;
1335 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1336 stream.total_out < sizeof(delta_head));
1337 git_inflate_end(&stream);
1338 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1339 error("delta data unpack-initial failed");
1340 return 0;
1343 /* Examine the initial part of the delta to figure out
1344 * the result size.
1346 data = delta_head;
1348 /* ignore base size */
1349 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1351 /* Read the result size */
1352 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1355 static off_t get_delta_base(struct packed_git *p,
1356 struct pack_window **w_curs,
1357 off_t *curpos,
1358 enum object_type type,
1359 off_t delta_obj_offset)
1361 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1362 off_t base_offset;
1364 /* use_pack() assured us we have [base_info, base_info + 20)
1365 * as a range that we can look at without walking off the
1366 * end of the mapped window. Its actually the hash size
1367 * that is assured. An OFS_DELTA longer than the hash size
1368 * is stupid, as then a REF_DELTA would be smaller to store.
1370 if (type == OBJ_OFS_DELTA) {
1371 unsigned used = 0;
1372 unsigned char c = base_info[used++];
1373 base_offset = c & 127;
1374 while (c & 128) {
1375 base_offset += 1;
1376 if (!base_offset || MSB(base_offset, 7))
1377 return 0; /* overflow */
1378 c = base_info[used++];
1379 base_offset = (base_offset << 7) + (c & 127);
1381 base_offset = delta_obj_offset - base_offset;
1382 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1383 return 0; /* out of bound */
1384 *curpos += used;
1385 } else if (type == OBJ_REF_DELTA) {
1386 /* The base entry _must_ be in the same pack */
1387 base_offset = find_pack_entry_one(base_info, p);
1388 *curpos += 20;
1389 } else
1390 die("I am totally screwed");
1391 return base_offset;
1394 /* forward declaration for a mutually recursive function */
1395 static int packed_object_info(struct packed_git *p, off_t offset,
1396 unsigned long *sizep);
1398 static int packed_delta_info(struct packed_git *p,
1399 struct pack_window **w_curs,
1400 off_t curpos,
1401 enum object_type type,
1402 off_t obj_offset,
1403 unsigned long *sizep)
1405 off_t base_offset;
1407 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1408 if (!base_offset)
1409 return OBJ_BAD;
1410 type = packed_object_info(p, base_offset, NULL);
1411 if (type <= OBJ_NONE) {
1412 struct revindex_entry *revidx;
1413 const unsigned char *base_sha1;
1414 revidx = find_pack_revindex(p, base_offset);
1415 if (!revidx)
1416 return OBJ_BAD;
1417 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1418 mark_bad_packed_object(p, base_sha1);
1419 type = sha1_object_info(base_sha1, NULL);
1420 if (type <= OBJ_NONE)
1421 return OBJ_BAD;
1424 /* We choose to only get the type of the base object and
1425 * ignore potentially corrupt pack file that expects the delta
1426 * based on a base with a wrong size. This saves tons of
1427 * inflate() calls.
1429 if (sizep) {
1430 *sizep = get_size_from_delta(p, w_curs, curpos);
1431 if (*sizep == 0)
1432 type = OBJ_BAD;
1435 return type;
1438 static int unpack_object_header(struct packed_git *p,
1439 struct pack_window **w_curs,
1440 off_t *curpos,
1441 unsigned long *sizep)
1443 unsigned char *base;
1444 unsigned int left;
1445 unsigned long used;
1446 enum object_type type;
1448 /* use_pack() assures us we have [base, base + 20) available
1449 * as a range that we can look at at. (Its actually the hash
1450 * size that is assured.) With our object header encoding
1451 * the maximum deflated object size is 2^137, which is just
1452 * insane, so we know won't exceed what we have been given.
1454 base = use_pack(p, w_curs, *curpos, &left);
1455 used = unpack_object_header_buffer(base, left, &type, sizep);
1456 if (!used) {
1457 type = OBJ_BAD;
1458 } else
1459 *curpos += used;
1461 return type;
1464 const char *packed_object_info_detail(struct packed_git *p,
1465 off_t obj_offset,
1466 unsigned long *size,
1467 unsigned long *store_size,
1468 unsigned int *delta_chain_length,
1469 unsigned char *base_sha1)
1471 struct pack_window *w_curs = NULL;
1472 off_t curpos;
1473 unsigned long dummy;
1474 unsigned char *next_sha1;
1475 enum object_type type;
1476 struct revindex_entry *revidx;
1478 *delta_chain_length = 0;
1479 curpos = obj_offset;
1480 type = unpack_object_header(p, &w_curs, &curpos, size);
1482 revidx = find_pack_revindex(p, obj_offset);
1483 *store_size = revidx[1].offset - obj_offset;
1485 for (;;) {
1486 switch (type) {
1487 default:
1488 die("pack %s contains unknown object type %d",
1489 p->pack_name, type);
1490 case OBJ_COMMIT:
1491 case OBJ_TREE:
1492 case OBJ_BLOB:
1493 case OBJ_TAG:
1494 unuse_pack(&w_curs);
1495 return typename(type);
1496 case OBJ_OFS_DELTA:
1497 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1498 if (!obj_offset)
1499 die("pack %s contains bad delta base reference of type %s",
1500 p->pack_name, typename(type));
1501 if (*delta_chain_length == 0) {
1502 revidx = find_pack_revindex(p, obj_offset);
1503 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1505 break;
1506 case OBJ_REF_DELTA:
1507 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1508 if (*delta_chain_length == 0)
1509 hashcpy(base_sha1, next_sha1);
1510 obj_offset = find_pack_entry_one(next_sha1, p);
1511 break;
1513 (*delta_chain_length)++;
1514 curpos = obj_offset;
1515 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1519 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1520 unsigned long *sizep)
1522 struct pack_window *w_curs = NULL;
1523 unsigned long size;
1524 off_t curpos = obj_offset;
1525 enum object_type type;
1527 type = unpack_object_header(p, &w_curs, &curpos, &size);
1529 switch (type) {
1530 case OBJ_OFS_DELTA:
1531 case OBJ_REF_DELTA:
1532 type = packed_delta_info(p, &w_curs, curpos,
1533 type, obj_offset, sizep);
1534 break;
1535 case OBJ_COMMIT:
1536 case OBJ_TREE:
1537 case OBJ_BLOB:
1538 case OBJ_TAG:
1539 if (sizep)
1540 *sizep = size;
1541 break;
1542 default:
1543 error("unknown object type %i at offset %"PRIuMAX" in %s",
1544 type, (uintmax_t)obj_offset, p->pack_name);
1545 type = OBJ_BAD;
1547 unuse_pack(&w_curs);
1548 return type;
1551 static void *unpack_compressed_entry(struct packed_git *p,
1552 struct pack_window **w_curs,
1553 off_t curpos,
1554 unsigned long size)
1556 int st;
1557 z_stream stream;
1558 unsigned char *buffer, *in;
1560 buffer = xmallocz(size);
1561 memset(&stream, 0, sizeof(stream));
1562 stream.next_out = buffer;
1563 stream.avail_out = size + 1;
1565 git_inflate_init(&stream);
1566 do {
1567 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1568 stream.next_in = in;
1569 st = git_inflate(&stream, Z_FINISH);
1570 if (!stream.avail_out)
1571 break; /* the payload is larger than it should be */
1572 curpos += stream.next_in - in;
1573 } while (st == Z_OK || st == Z_BUF_ERROR);
1574 git_inflate_end(&stream);
1575 if ((st != Z_STREAM_END) || stream.total_out != size) {
1576 free(buffer);
1577 return NULL;
1580 return buffer;
1583 #define MAX_DELTA_CACHE (256)
1585 static size_t delta_base_cached;
1587 static struct delta_base_cache_lru_list {
1588 struct delta_base_cache_lru_list *prev;
1589 struct delta_base_cache_lru_list *next;
1590 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1592 static struct delta_base_cache_entry {
1593 struct delta_base_cache_lru_list lru;
1594 void *data;
1595 struct packed_git *p;
1596 off_t base_offset;
1597 unsigned long size;
1598 enum object_type type;
1599 } delta_base_cache[MAX_DELTA_CACHE];
1601 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1603 unsigned long hash;
1605 hash = (unsigned long)p + (unsigned long)base_offset;
1606 hash += (hash >> 8) + (hash >> 16);
1607 return hash % MAX_DELTA_CACHE;
1610 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1611 unsigned long *base_size, enum object_type *type, int keep_cache)
1613 void *ret;
1614 unsigned long hash = pack_entry_hash(p, base_offset);
1615 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1617 ret = ent->data;
1618 if (!ret || ent->p != p || ent->base_offset != base_offset)
1619 return unpack_entry(p, base_offset, type, base_size);
1621 if (!keep_cache) {
1622 ent->data = NULL;
1623 ent->lru.next->prev = ent->lru.prev;
1624 ent->lru.prev->next = ent->lru.next;
1625 delta_base_cached -= ent->size;
1626 } else {
1627 ret = xmemdupz(ent->data, ent->size);
1629 *type = ent->type;
1630 *base_size = ent->size;
1631 return ret;
1634 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1636 if (ent->data) {
1637 free(ent->data);
1638 ent->data = NULL;
1639 ent->lru.next->prev = ent->lru.prev;
1640 ent->lru.prev->next = ent->lru.next;
1641 delta_base_cached -= ent->size;
1645 void clear_delta_base_cache(void)
1647 unsigned long p;
1648 for (p = 0; p < MAX_DELTA_CACHE; p++)
1649 release_delta_base_cache(&delta_base_cache[p]);
1652 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1653 void *base, unsigned long base_size, enum object_type type)
1655 unsigned long hash = pack_entry_hash(p, base_offset);
1656 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1657 struct delta_base_cache_lru_list *lru;
1659 release_delta_base_cache(ent);
1660 delta_base_cached += base_size;
1662 for (lru = delta_base_cache_lru.next;
1663 delta_base_cached > delta_base_cache_limit
1664 && lru != &delta_base_cache_lru;
1665 lru = lru->next) {
1666 struct delta_base_cache_entry *f = (void *)lru;
1667 if (f->type == OBJ_BLOB)
1668 release_delta_base_cache(f);
1670 for (lru = delta_base_cache_lru.next;
1671 delta_base_cached > delta_base_cache_limit
1672 && lru != &delta_base_cache_lru;
1673 lru = lru->next) {
1674 struct delta_base_cache_entry *f = (void *)lru;
1675 release_delta_base_cache(f);
1678 ent->p = p;
1679 ent->base_offset = base_offset;
1680 ent->type = type;
1681 ent->data = base;
1682 ent->size = base_size;
1683 ent->lru.next = &delta_base_cache_lru;
1684 ent->lru.prev = delta_base_cache_lru.prev;
1685 delta_base_cache_lru.prev->next = &ent->lru;
1686 delta_base_cache_lru.prev = &ent->lru;
1689 static void *read_object(const unsigned char *sha1, enum object_type *type,
1690 unsigned long *size);
1692 static void *unpack_delta_entry(struct packed_git *p,
1693 struct pack_window **w_curs,
1694 off_t curpos,
1695 unsigned long delta_size,
1696 off_t obj_offset,
1697 enum object_type *type,
1698 unsigned long *sizep)
1700 void *delta_data, *result, *base;
1701 unsigned long base_size;
1702 off_t base_offset;
1704 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1705 if (!base_offset) {
1706 error("failed to validate delta base reference "
1707 "at offset %"PRIuMAX" from %s",
1708 (uintmax_t)curpos, p->pack_name);
1709 return NULL;
1711 unuse_pack(w_curs);
1712 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1713 if (!base) {
1715 * We're probably in deep shit, but let's try to fetch
1716 * the required base anyway from another pack or loose.
1717 * This is costly but should happen only in the presence
1718 * of a corrupted pack, and is better than failing outright.
1720 struct revindex_entry *revidx;
1721 const unsigned char *base_sha1;
1722 revidx = find_pack_revindex(p, base_offset);
1723 if (!revidx)
1724 return NULL;
1725 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1726 error("failed to read delta base object %s"
1727 " at offset %"PRIuMAX" from %s",
1728 sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1729 p->pack_name);
1730 mark_bad_packed_object(p, base_sha1);
1731 base = read_object(base_sha1, type, &base_size);
1732 if (!base)
1733 return NULL;
1736 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1737 if (!delta_data) {
1738 error("failed to unpack compressed delta "
1739 "at offset %"PRIuMAX" from %s",
1740 (uintmax_t)curpos, p->pack_name);
1741 free(base);
1742 return NULL;
1744 result = patch_delta(base, base_size,
1745 delta_data, delta_size,
1746 sizep);
1747 if (!result)
1748 die("failed to apply delta");
1749 free(delta_data);
1750 add_delta_base_cache(p, base_offset, base, base_size, *type);
1751 return result;
1754 int do_check_packed_object_crc;
1756 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1757 enum object_type *type, unsigned long *sizep)
1759 struct pack_window *w_curs = NULL;
1760 off_t curpos = obj_offset;
1761 void *data;
1763 if (do_check_packed_object_crc && p->index_version > 1) {
1764 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1765 unsigned long len = revidx[1].offset - obj_offset;
1766 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1767 const unsigned char *sha1 =
1768 nth_packed_object_sha1(p, revidx->nr);
1769 error("bad packed object CRC for %s",
1770 sha1_to_hex(sha1));
1771 mark_bad_packed_object(p, sha1);
1772 unuse_pack(&w_curs);
1773 return NULL;
1777 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1778 switch (*type) {
1779 case OBJ_OFS_DELTA:
1780 case OBJ_REF_DELTA:
1781 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1782 obj_offset, type, sizep);
1783 break;
1784 case OBJ_COMMIT:
1785 case OBJ_TREE:
1786 case OBJ_BLOB:
1787 case OBJ_TAG:
1788 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1789 break;
1790 default:
1791 data = NULL;
1792 error("unknown object type %i at offset %"PRIuMAX" in %s",
1793 *type, (uintmax_t)obj_offset, p->pack_name);
1795 unuse_pack(&w_curs);
1796 return data;
1799 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1800 uint32_t n)
1802 const unsigned char *index = p->index_data;
1803 if (!index) {
1804 if (open_pack_index(p))
1805 return NULL;
1806 index = p->index_data;
1808 if (n >= p->num_objects)
1809 return NULL;
1810 index += 4 * 256;
1811 if (p->index_version == 1) {
1812 return index + 24 * n + 4;
1813 } else {
1814 index += 8;
1815 return index + 20 * n;
1819 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1821 const unsigned char *index = p->index_data;
1822 index += 4 * 256;
1823 if (p->index_version == 1) {
1824 return ntohl(*((uint32_t *)(index + 24 * n)));
1825 } else {
1826 uint32_t off;
1827 index += 8 + p->num_objects * (20 + 4);
1828 off = ntohl(*((uint32_t *)(index + 4 * n)));
1829 if (!(off & 0x80000000))
1830 return off;
1831 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1832 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1833 ntohl(*((uint32_t *)(index + 4)));
1837 off_t find_pack_entry_one(const unsigned char *sha1,
1838 struct packed_git *p)
1840 const uint32_t *level1_ofs = p->index_data;
1841 const unsigned char *index = p->index_data;
1842 unsigned hi, lo, stride;
1843 static int use_lookup = -1;
1844 static int debug_lookup = -1;
1846 if (debug_lookup < 0)
1847 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1849 if (!index) {
1850 if (open_pack_index(p))
1851 return 0;
1852 level1_ofs = p->index_data;
1853 index = p->index_data;
1855 if (p->index_version > 1) {
1856 level1_ofs += 2;
1857 index += 8;
1859 index += 4 * 256;
1860 hi = ntohl(level1_ofs[*sha1]);
1861 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1862 if (p->index_version > 1) {
1863 stride = 20;
1864 } else {
1865 stride = 24;
1866 index += 4;
1869 if (debug_lookup)
1870 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1871 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1873 if (use_lookup < 0)
1874 use_lookup = !!getenv("GIT_USE_LOOKUP");
1875 if (use_lookup) {
1876 int pos = sha1_entry_pos(index, stride, 0,
1877 lo, hi, p->num_objects, sha1);
1878 if (pos < 0)
1879 return 0;
1880 return nth_packed_object_offset(p, pos);
1883 do {
1884 unsigned mi = (lo + hi) / 2;
1885 int cmp = hashcmp(index + mi * stride, sha1);
1887 if (debug_lookup)
1888 printf("lo %u hi %u rg %u mi %u\n",
1889 lo, hi, hi - lo, mi);
1890 if (!cmp)
1891 return nth_packed_object_offset(p, mi);
1892 if (cmp > 0)
1893 hi = mi;
1894 else
1895 lo = mi+1;
1896 } while (lo < hi);
1897 return 0;
1900 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1902 static struct packed_git *last_found = (void *)1;
1903 struct packed_git *p;
1904 off_t offset;
1906 prepare_packed_git();
1907 if (!packed_git)
1908 return 0;
1909 p = (last_found == (void *)1) ? packed_git : last_found;
1911 do {
1912 if (p->num_bad_objects) {
1913 unsigned i;
1914 for (i = 0; i < p->num_bad_objects; i++)
1915 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1916 goto next;
1919 offset = find_pack_entry_one(sha1, p);
1920 if (offset) {
1922 * We are about to tell the caller where they can
1923 * locate the requested object. We better make
1924 * sure the packfile is still here and can be
1925 * accessed before supplying that answer, as
1926 * it may have been deleted since the index
1927 * was loaded!
1929 if (p->pack_fd == -1 && open_packed_git(p)) {
1930 error("packfile %s cannot be accessed", p->pack_name);
1931 goto next;
1933 e->offset = offset;
1934 e->p = p;
1935 hashcpy(e->sha1, sha1);
1936 last_found = p;
1937 return 1;
1940 next:
1941 if (p == last_found)
1942 p = packed_git;
1943 else
1944 p = p->next;
1945 if (p == last_found)
1946 p = p->next;
1947 } while (p);
1948 return 0;
1951 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1952 struct packed_git *packs)
1954 struct packed_git *p;
1956 for (p = packs; p; p = p->next) {
1957 if (find_pack_entry_one(sha1, p))
1958 return p;
1960 return NULL;
1964 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1966 int status;
1967 unsigned long mapsize, size;
1968 void *map;
1969 z_stream stream;
1970 char hdr[32];
1972 map = map_sha1_file(sha1, &mapsize);
1973 if (!map)
1974 return error("unable to find %s", sha1_to_hex(sha1));
1975 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1976 status = error("unable to unpack %s header",
1977 sha1_to_hex(sha1));
1978 else if ((status = parse_sha1_header(hdr, &size)) < 0)
1979 status = error("unable to parse %s header", sha1_to_hex(sha1));
1980 else if (sizep)
1981 *sizep = size;
1982 git_inflate_end(&stream);
1983 munmap(map, mapsize);
1984 return status;
1987 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1989 struct pack_entry e;
1990 int status;
1992 if (!find_pack_entry(sha1, &e)) {
1993 /* Most likely it's a loose object. */
1994 status = sha1_loose_object_info(sha1, sizep);
1995 if (status >= 0)
1996 return status;
1998 /* Not a loose object; someone else may have just packed it. */
1999 reprepare_packed_git();
2000 if (!find_pack_entry(sha1, &e))
2001 return status;
2004 status = packed_object_info(e.p, e.offset, sizep);
2005 if (status < 0) {
2006 mark_bad_packed_object(e.p, sha1);
2007 status = sha1_object_info(sha1, sizep);
2010 return status;
2013 static void *read_packed_sha1(const unsigned char *sha1,
2014 enum object_type *type, unsigned long *size)
2016 struct pack_entry e;
2017 void *data;
2019 if (!find_pack_entry(sha1, &e))
2020 return NULL;
2021 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2022 if (!data) {
2024 * We're probably in deep shit, but let's try to fetch
2025 * the required object anyway from another pack or loose.
2026 * This should happen only in the presence of a corrupted
2027 * pack, and is better than failing outright.
2029 error("failed to read object %s at offset %"PRIuMAX" from %s",
2030 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2031 mark_bad_packed_object(e.p, sha1);
2032 data = read_object(sha1, type, size);
2034 return data;
2038 * This is meant to hold a *small* number of objects that you would
2039 * want read_sha1_file() to be able to return, but yet you do not want
2040 * to write them into the object store (e.g. a browse-only
2041 * application).
2043 static struct cached_object {
2044 unsigned char sha1[20];
2045 enum object_type type;
2046 void *buf;
2047 unsigned long size;
2048 } *cached_objects;
2049 static int cached_object_nr, cached_object_alloc;
2051 static struct cached_object empty_tree = {
2052 EMPTY_TREE_SHA1_BIN,
2053 OBJ_TREE,
2058 static struct cached_object *find_cached_object(const unsigned char *sha1)
2060 int i;
2061 struct cached_object *co = cached_objects;
2063 for (i = 0; i < cached_object_nr; i++, co++) {
2064 if (!hashcmp(co->sha1, sha1))
2065 return co;
2067 if (!hashcmp(sha1, empty_tree.sha1))
2068 return &empty_tree;
2069 return NULL;
2072 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2073 unsigned char *sha1)
2075 struct cached_object *co;
2077 hash_sha1_file(buf, len, typename(type), sha1);
2078 if (has_sha1_file(sha1) || find_cached_object(sha1))
2079 return 0;
2080 if (cached_object_alloc <= cached_object_nr) {
2081 cached_object_alloc = alloc_nr(cached_object_alloc);
2082 cached_objects = xrealloc(cached_objects,
2083 sizeof(*cached_objects) *
2084 cached_object_alloc);
2086 co = &cached_objects[cached_object_nr++];
2087 co->size = len;
2088 co->type = type;
2089 co->buf = xmalloc(len);
2090 memcpy(co->buf, buf, len);
2091 hashcpy(co->sha1, sha1);
2092 return 0;
2095 static void *read_object(const unsigned char *sha1, enum object_type *type,
2096 unsigned long *size)
2098 unsigned long mapsize;
2099 void *map, *buf;
2100 struct cached_object *co;
2102 co = find_cached_object(sha1);
2103 if (co) {
2104 *type = co->type;
2105 *size = co->size;
2106 return xmemdupz(co->buf, co->size);
2109 buf = read_packed_sha1(sha1, type, size);
2110 if (buf)
2111 return buf;
2112 map = map_sha1_file(sha1, &mapsize);
2113 if (map) {
2114 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2115 munmap(map, mapsize);
2116 return buf;
2118 reprepare_packed_git();
2119 return read_packed_sha1(sha1, type, size);
2123 * This function dies on corrupt objects; the callers who want to
2124 * deal with them should arrange to call read_object() and give error
2125 * messages themselves.
2127 void *read_sha1_file_repl(const unsigned char *sha1,
2128 enum object_type *type,
2129 unsigned long *size,
2130 const unsigned char **replacement)
2132 const unsigned char *repl = lookup_replace_object(sha1);
2133 void *data;
2134 char *path;
2135 const struct packed_git *p;
2137 errno = 0;
2138 data = read_object(repl, type, size);
2139 if (data) {
2140 if (replacement)
2141 *replacement = repl;
2142 return data;
2145 if (errno && errno != ENOENT)
2146 die_errno("failed to read object %s", sha1_to_hex(sha1));
2148 /* die if we replaced an object with one that does not exist */
2149 if (repl != sha1)
2150 die("replacement %s not found for %s",
2151 sha1_to_hex(repl), sha1_to_hex(sha1));
2153 if (has_loose_object(repl)) {
2154 path = sha1_file_name(sha1);
2155 die("loose object %s (stored in %s) is corrupt",
2156 sha1_to_hex(repl), path);
2159 if ((p = has_packed_and_bad(repl)) != NULL)
2160 die("packed object %s (stored in %s) is corrupt",
2161 sha1_to_hex(repl), p->pack_name);
2163 return NULL;
2166 void *read_object_with_reference(const unsigned char *sha1,
2167 const char *required_type_name,
2168 unsigned long *size,
2169 unsigned char *actual_sha1_return)
2171 enum object_type type, required_type;
2172 void *buffer;
2173 unsigned long isize;
2174 unsigned char actual_sha1[20];
2176 required_type = type_from_string(required_type_name);
2177 hashcpy(actual_sha1, sha1);
2178 while (1) {
2179 int ref_length = -1;
2180 const char *ref_type = NULL;
2182 buffer = read_sha1_file(actual_sha1, &type, &isize);
2183 if (!buffer)
2184 return NULL;
2185 if (type == required_type) {
2186 *size = isize;
2187 if (actual_sha1_return)
2188 hashcpy(actual_sha1_return, actual_sha1);
2189 return buffer;
2191 /* Handle references */
2192 else if (type == OBJ_COMMIT)
2193 ref_type = "tree ";
2194 else if (type == OBJ_TAG)
2195 ref_type = "object ";
2196 else {
2197 free(buffer);
2198 return NULL;
2200 ref_length = strlen(ref_type);
2202 if (ref_length + 40 > isize ||
2203 memcmp(buffer, ref_type, ref_length) ||
2204 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2205 free(buffer);
2206 return NULL;
2208 free(buffer);
2209 /* Now we have the ID of the referred-to object in
2210 * actual_sha1. Check again. */
2214 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2215 const char *type, unsigned char *sha1,
2216 char *hdr, int *hdrlen)
2218 git_SHA_CTX c;
2220 /* Generate the header */
2221 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2223 /* Sha1.. */
2224 git_SHA1_Init(&c);
2225 git_SHA1_Update(&c, hdr, *hdrlen);
2226 git_SHA1_Update(&c, buf, len);
2227 git_SHA1_Final(sha1, &c);
2231 * Move the just written object into its final resting place.
2232 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2233 * "moving" is only a part of what it does, when no patch between
2234 * master to pu changes the call sites of this function.
2236 int move_temp_to_file(const char *tmpfile, const char *filename)
2238 int ret = 0;
2240 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2241 goto try_rename;
2242 else if (link(tmpfile, filename))
2243 ret = errno;
2246 * Coda hack - coda doesn't like cross-directory links,
2247 * so we fall back to a rename, which will mean that it
2248 * won't be able to check collisions, but that's not a
2249 * big deal.
2251 * The same holds for FAT formatted media.
2253 * When this succeeds, we just return. We have nothing
2254 * left to unlink.
2256 if (ret && ret != EEXIST) {
2257 try_rename:
2258 if (!rename(tmpfile, filename))
2259 goto out;
2260 ret = errno;
2262 unlink_or_warn(tmpfile);
2263 if (ret) {
2264 if (ret != EEXIST) {
2265 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2267 /* FIXME!!! Collision check here ? */
2270 out:
2271 if (adjust_shared_perm(filename))
2272 return error("unable to set permission to '%s'", filename);
2273 return 0;
2276 static int write_buffer(int fd, const void *buf, size_t len)
2278 if (write_in_full(fd, buf, len) < 0)
2279 return error("file write error (%s)", strerror(errno));
2280 return 0;
2283 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2284 unsigned char *sha1)
2286 char hdr[32];
2287 int hdrlen;
2288 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2289 return 0;
2292 /* Finalize a file on disk, and close it. */
2293 static void close_sha1_file(int fd)
2295 if (fsync_object_files)
2296 fsync_or_die(fd, "sha1 file");
2297 if (close(fd) != 0)
2298 die_errno("error when closing sha1 file");
2301 /* Size of directory component, including the ending '/' */
2302 static inline int directory_size(const char *filename)
2304 const char *s = strrchr(filename, '/');
2305 if (!s)
2306 return 0;
2307 return s - filename + 1;
2311 * This creates a temporary file in the same directory as the final
2312 * 'filename'
2314 * We want to avoid cross-directory filename renames, because those
2315 * can have problems on various filesystems (FAT, NFS, Coda).
2317 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2319 int fd, dirlen = directory_size(filename);
2321 if (dirlen + 20 > bufsiz) {
2322 errno = ENAMETOOLONG;
2323 return -1;
2325 memcpy(buffer, filename, dirlen);
2326 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2327 fd = git_mkstemp_mode(buffer, 0444);
2328 if (fd < 0 && dirlen && errno == ENOENT) {
2329 /* Make sure the directory exists */
2330 memcpy(buffer, filename, dirlen);
2331 buffer[dirlen-1] = 0;
2332 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2333 return -1;
2335 /* Try again */
2336 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2337 fd = git_mkstemp_mode(buffer, 0444);
2339 return fd;
2342 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2343 const void *buf, unsigned long len, time_t mtime)
2345 int fd, ret;
2346 unsigned char compressed[4096];
2347 z_stream stream;
2348 git_SHA_CTX c;
2349 unsigned char parano_sha1[20];
2350 char *filename;
2351 static char tmpfile[PATH_MAX];
2353 filename = sha1_file_name(sha1);
2354 fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2355 while (fd < 0 && errno == EMFILE && unuse_one_window(NULL, -1))
2356 fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2357 if (fd < 0) {
2358 if (errno == EACCES)
2359 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2360 else
2361 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2364 /* Set it up */
2365 memset(&stream, 0, sizeof(stream));
2366 deflateInit(&stream, zlib_compression_level);
2367 stream.next_out = compressed;
2368 stream.avail_out = sizeof(compressed);
2369 git_SHA1_Init(&c);
2371 /* First header.. */
2372 stream.next_in = (unsigned char *)hdr;
2373 stream.avail_in = hdrlen;
2374 while (deflate(&stream, 0) == Z_OK)
2375 /* nothing */;
2376 git_SHA1_Update(&c, hdr, hdrlen);
2378 /* Then the data itself.. */
2379 stream.next_in = (void *)buf;
2380 stream.avail_in = len;
2381 do {
2382 unsigned char *in0 = stream.next_in;
2383 ret = deflate(&stream, Z_FINISH);
2384 git_SHA1_Update(&c, in0, stream.next_in - in0);
2385 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2386 die("unable to write sha1 file");
2387 stream.next_out = compressed;
2388 stream.avail_out = sizeof(compressed);
2389 } while (ret == Z_OK);
2391 if (ret != Z_STREAM_END)
2392 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2393 ret = deflateEnd(&stream);
2394 if (ret != Z_OK)
2395 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2396 git_SHA1_Final(parano_sha1, &c);
2397 if (hashcmp(sha1, parano_sha1) != 0)
2398 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2400 close_sha1_file(fd);
2402 if (mtime) {
2403 struct utimbuf utb;
2404 utb.actime = mtime;
2405 utb.modtime = mtime;
2406 if (utime(tmpfile, &utb) < 0)
2407 warning("failed utime() on %s: %s",
2408 tmpfile, strerror(errno));
2411 return move_temp_to_file(tmpfile, filename);
2414 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2416 unsigned char sha1[20];
2417 char hdr[32];
2418 int hdrlen;
2420 /* Normally if we have it in the pack then we do not bother writing
2421 * it out into .git/objects/??/?{38} file.
2423 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2424 if (returnsha1)
2425 hashcpy(returnsha1, sha1);
2426 if (has_sha1_file(sha1))
2427 return 0;
2428 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2431 int force_object_loose(const unsigned char *sha1, time_t mtime)
2433 void *buf;
2434 unsigned long len;
2435 enum object_type type;
2436 char hdr[32];
2437 int hdrlen;
2438 int ret;
2440 if (has_loose_object(sha1))
2441 return 0;
2442 buf = read_packed_sha1(sha1, &type, &len);
2443 if (!buf)
2444 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2445 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2446 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2447 free(buf);
2449 return ret;
2452 int has_pack_index(const unsigned char *sha1)
2454 struct stat st;
2455 if (stat(sha1_pack_index_name(sha1), &st))
2456 return 0;
2457 return 1;
2460 int has_sha1_pack(const unsigned char *sha1)
2462 struct pack_entry e;
2463 return find_pack_entry(sha1, &e);
2466 int has_sha1_file(const unsigned char *sha1)
2468 struct pack_entry e;
2470 if (find_pack_entry(sha1, &e))
2471 return 1;
2472 return has_loose_object(sha1);
2475 static void check_tree(const void *buf, size_t size)
2477 struct tree_desc desc;
2478 struct name_entry entry;
2480 init_tree_desc(&desc, buf, size);
2481 while (tree_entry(&desc, &entry))
2482 /* do nothing
2483 * tree_entry() will die() on malformed entries */
2487 static void check_commit(const void *buf, size_t size)
2489 struct commit c;
2490 memset(&c, 0, sizeof(c));
2491 if (parse_commit_buffer(&c, buf, size))
2492 die("corrupt commit");
2495 static void check_tag(const void *buf, size_t size)
2497 struct tag t;
2498 memset(&t, 0, sizeof(t));
2499 if (parse_tag_buffer(&t, buf, size))
2500 die("corrupt tag");
2503 static int index_mem(unsigned char *sha1, void *buf, size_t size,
2504 int write_object, enum object_type type,
2505 const char *path, int format_check)
2507 int ret, re_allocated = 0;
2509 if (!type)
2510 type = OBJ_BLOB;
2513 * Convert blobs to git internal format
2515 if ((type == OBJ_BLOB) && path) {
2516 struct strbuf nbuf = STRBUF_INIT;
2517 if (convert_to_git(path, buf, size, &nbuf,
2518 write_object ? safe_crlf : 0)) {
2519 buf = strbuf_detach(&nbuf, &size);
2520 re_allocated = 1;
2523 if (format_check) {
2524 if (type == OBJ_TREE)
2525 check_tree(buf, size);
2526 if (type == OBJ_COMMIT)
2527 check_commit(buf, size);
2528 if (type == OBJ_TAG)
2529 check_tag(buf, size);
2532 if (write_object)
2533 ret = write_sha1_file(buf, size, typename(type), sha1);
2534 else
2535 ret = hash_sha1_file(buf, size, typename(type), sha1);
2536 if (re_allocated)
2537 free(buf);
2538 return ret;
2541 #define SMALL_FILE_SIZE (32*1024)
2543 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2544 enum object_type type, const char *path, int format_check)
2546 int ret;
2547 size_t size = xsize_t(st->st_size);
2549 if (!S_ISREG(st->st_mode)) {
2550 struct strbuf sbuf = STRBUF_INIT;
2551 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2552 ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object,
2553 type, path, format_check);
2554 else
2555 ret = -1;
2556 strbuf_release(&sbuf);
2557 } else if (!size) {
2558 ret = index_mem(sha1, NULL, size, write_object, type, path,
2559 format_check);
2560 } else if (size <= SMALL_FILE_SIZE) {
2561 char *buf = xmalloc(size);
2562 if (size == read_in_full(fd, buf, size))
2563 ret = index_mem(sha1, buf, size, write_object, type,
2564 path, format_check);
2565 else
2566 ret = error("short read %s", strerror(errno));
2567 free(buf);
2568 } else {
2569 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2570 ret = index_mem(sha1, buf, size, write_object, type, path,
2571 format_check);
2572 munmap(buf, size);
2574 close(fd);
2575 return ret;
2578 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2580 int fd;
2581 struct strbuf sb = STRBUF_INIT;
2583 switch (st->st_mode & S_IFMT) {
2584 case S_IFREG:
2585 fd = open(path, O_RDONLY);
2586 if (fd < 0)
2587 return error("open(\"%s\"): %s", path,
2588 strerror(errno));
2589 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path, 0) < 0)
2590 return error("%s: failed to insert into database",
2591 path);
2592 break;
2593 case S_IFLNK:
2594 if (strbuf_readlink(&sb, path, st->st_size)) {
2595 char *errstr = strerror(errno);
2596 return error("readlink(\"%s\"): %s", path,
2597 errstr);
2599 if (!write_object)
2600 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2601 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2602 return error("%s: failed to insert into database",
2603 path);
2604 strbuf_release(&sb);
2605 break;
2606 case S_IFDIR:
2607 return resolve_gitlink_ref(path, "HEAD", sha1);
2608 default:
2609 return error("%s: unsupported file type", path);
2611 return 0;
2614 int read_pack_header(int fd, struct pack_header *header)
2616 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2617 /* "eof before pack header was fully read" */
2618 return PH_ERROR_EOF;
2620 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2621 /* "protocol error (pack signature mismatch detected)" */
2622 return PH_ERROR_PACK_SIGNATURE;
2623 if (!pack_version_ok(header->hdr_version))
2624 /* "protocol error (pack version unsupported)" */
2625 return PH_ERROR_PROTOCOL;
2626 return 0;
2629 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2631 enum object_type type = sha1_object_info(sha1, NULL);
2632 if (type < 0)
2633 die("%s is not a valid object", sha1_to_hex(sha1));
2634 if (type != expect)
2635 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
2636 typename(expect));