Code

Bigfile: teach "git add" to send a large file straight to a pack
[git.git] / sha1_file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
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 "run-command.h"
15 #include "tag.h"
16 #include "tree.h"
17 #include "tree-walk.h"
18 #include "refs.h"
19 #include "pack-revindex.h"
20 #include "sha1-lookup.h"
22 #ifndef O_NOATIME
23 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
24 #define O_NOATIME 01000000
25 #else
26 #define O_NOATIME 0
27 #endif
28 #endif
30 #define SZ_FMT PRIuMAX
31 static inline uintmax_t sz_fmt(size_t s) { return s; }
33 const unsigned char null_sha1[20];
35 static int git_open_noatime(const char *name, struct packed_git *p);
37 /*
38  * This is meant to hold a *small* number of objects that you would
39  * want read_sha1_file() to be able to return, but yet you do not want
40  * to write them into the object store (e.g. a browse-only
41  * application).
42  */
43 static struct cached_object {
44         unsigned char sha1[20];
45         enum object_type type;
46         void *buf;
47         unsigned long size;
48 } *cached_objects;
49 static int cached_object_nr, cached_object_alloc;
51 static struct cached_object empty_tree = {
52         EMPTY_TREE_SHA1_BIN_LITERAL,
53         OBJ_TREE,
54         "",
55         0
56 };
58 static struct cached_object *find_cached_object(const unsigned char *sha1)
59 {
60         int i;
61         struct cached_object *co = cached_objects;
63         for (i = 0; i < cached_object_nr; i++, co++) {
64                 if (!hashcmp(co->sha1, sha1))
65                         return co;
66         }
67         if (!hashcmp(sha1, empty_tree.sha1))
68                 return &empty_tree;
69         return NULL;
70 }
72 int mkdir_in_gitdir(const char *path)
73 {
74         if (mkdir(path, 0777)) {
75                 int saved_errno = errno;
76                 struct stat st;
77                 struct strbuf sb = STRBUF_INIT;
79                 if (errno != EEXIST)
80                         return -1;
81                 /*
82                  * Are we looking at a path in a symlinked worktree
83                  * whose original repository does not yet have it?
84                  * e.g. .git/rr-cache pointing at its original
85                  * repository in which the user hasn't performed any
86                  * conflict resolution yet?
87                  */
88                 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
89                     strbuf_readlink(&sb, path, st.st_size) ||
90                     !is_absolute_path(sb.buf) ||
91                     mkdir(sb.buf, 0777)) {
92                         strbuf_release(&sb);
93                         errno = saved_errno;
94                         return -1;
95                 }
96                 strbuf_release(&sb);
97         }
98         return adjust_shared_perm(path);
99 }
101 int safe_create_leading_directories(char *path)
103         char *pos = path + offset_1st_component(path);
104         struct stat st;
106         while (pos) {
107                 pos = strchr(pos, '/');
108                 if (!pos)
109                         break;
110                 while (*++pos == '/')
111                         ;
112                 if (!*pos)
113                         break;
114                 *--pos = '\0';
115                 if (!stat(path, &st)) {
116                         /* path exists */
117                         if (!S_ISDIR(st.st_mode)) {
118                                 *pos = '/';
119                                 return -3;
120                         }
121                 }
122                 else if (mkdir(path, 0777)) {
123                         *pos = '/';
124                         return -1;
125                 }
126                 else if (adjust_shared_perm(path)) {
127                         *pos = '/';
128                         return -2;
129                 }
130                 *pos++ = '/';
131         }
132         return 0;
135 int safe_create_leading_directories_const(const char *path)
137         /* path points to cache entries, so xstrdup before messing with it */
138         char *buf = xstrdup(path);
139         int result = safe_create_leading_directories(buf);
140         free(buf);
141         return result;
144 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
146         int i;
147         for (i = 0; i < 20; i++) {
148                 static char hex[] = "0123456789abcdef";
149                 unsigned int val = sha1[i];
150                 char *pos = pathbuf + i*2 + (i > 0);
151                 *pos++ = hex[val >> 4];
152                 *pos = hex[val & 0xf];
153         }
156 /*
157  * NOTE! This returns a statically allocated buffer, so you have to be
158  * careful about using it. Do an "xstrdup()" if you need to save the
159  * filename.
160  *
161  * Also note that this returns the location for creating.  Reading
162  * SHA1 file can happen from any alternate directory listed in the
163  * DB_ENVIRONMENT environment variable if it is not found in
164  * the primary object database.
165  */
166 char *sha1_file_name(const unsigned char *sha1)
168         static char buf[PATH_MAX];
169         const char *objdir;
170         int len;
172         objdir = get_object_directory();
173         len = strlen(objdir);
175         /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
176         if (len + 43 > PATH_MAX)
177                 die("insanely long object directory %s", objdir);
178         memcpy(buf, objdir, len);
179         buf[len] = '/';
180         buf[len+3] = '/';
181         buf[len+42] = '\0';
182         fill_sha1_path(buf + len + 1, sha1);
183         return buf;
186 static char *sha1_get_pack_name(const unsigned char *sha1,
187                                 char **name, char **base, const char *which)
189         static const char hex[] = "0123456789abcdef";
190         char *buf;
191         int i;
193         if (!*base) {
194                 const char *sha1_file_directory = get_object_directory();
195                 int len = strlen(sha1_file_directory);
196                 *base = xmalloc(len + 60);
197                 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
198                         sha1_file_directory, which);
199                 *name = *base + len + 11;
200         }
202         buf = *name;
204         for (i = 0; i < 20; i++) {
205                 unsigned int val = *sha1++;
206                 *buf++ = hex[val >> 4];
207                 *buf++ = hex[val & 0xf];
208         }
210         return *base;
213 char *sha1_pack_name(const unsigned char *sha1)
215         static char *name, *base;
217         return sha1_get_pack_name(sha1, &name, &base, "pack");
220 char *sha1_pack_index_name(const unsigned char *sha1)
222         static char *name, *base;
224         return sha1_get_pack_name(sha1, &name, &base, "idx");
227 struct alternate_object_database *alt_odb_list;
228 static struct alternate_object_database **alt_odb_tail;
230 static void read_info_alternates(const char * alternates, int depth);
232 /*
233  * Prepare alternate object database registry.
234  *
235  * The variable alt_odb_list points at the list of struct
236  * alternate_object_database.  The elements on this list come from
237  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
238  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
239  * whose contents is similar to that environment variable but can be
240  * LF separated.  Its base points at a statically allocated buffer that
241  * contains "/the/directory/corresponding/to/.git/objects/...", while
242  * its name points just after the slash at the end of ".git/objects/"
243  * in the example above, and has enough space to hold 40-byte hex
244  * SHA1, an extra slash for the first level indirection, and the
245  * terminating NUL.
246  */
247 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
249         const char *objdir = get_object_directory();
250         struct alternate_object_database *ent;
251         struct alternate_object_database *alt;
252         /* 43 = 40-byte + 2 '/' + terminating NUL */
253         int pfxlen = len;
254         int entlen = pfxlen + 43;
255         int base_len = -1;
257         if (!is_absolute_path(entry) && relative_base) {
258                 /* Relative alt-odb */
259                 if (base_len < 0)
260                         base_len = strlen(relative_base) + 1;
261                 entlen += base_len;
262                 pfxlen += base_len;
263         }
264         ent = xmalloc(sizeof(*ent) + entlen);
266         if (!is_absolute_path(entry) && relative_base) {
267                 memcpy(ent->base, relative_base, base_len - 1);
268                 ent->base[base_len - 1] = '/';
269                 memcpy(ent->base + base_len, entry, len);
270         }
271         else
272                 memcpy(ent->base, entry, pfxlen);
274         ent->name = ent->base + pfxlen + 1;
275         ent->base[pfxlen + 3] = '/';
276         ent->base[pfxlen] = ent->base[entlen-1] = 0;
278         /* Detect cases where alternate disappeared */
279         if (!is_directory(ent->base)) {
280                 error("object directory %s does not exist; "
281                       "check .git/objects/info/alternates.",
282                       ent->base);
283                 free(ent);
284                 return -1;
285         }
287         /* Prevent the common mistake of listing the same
288          * thing twice, or object directory itself.
289          */
290         for (alt = alt_odb_list; alt; alt = alt->next) {
291                 if (!memcmp(ent->base, alt->base, pfxlen)) {
292                         free(ent);
293                         return -1;
294                 }
295         }
296         if (!memcmp(ent->base, objdir, pfxlen)) {
297                 free(ent);
298                 return -1;
299         }
301         /* add the alternate entry */
302         *alt_odb_tail = ent;
303         alt_odb_tail = &(ent->next);
304         ent->next = NULL;
306         /* recursively add alternates */
307         read_info_alternates(ent->base, depth + 1);
309         ent->base[pfxlen] = '/';
311         return 0;
314 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
315                                  const char *relative_base, int depth)
317         const char *cp, *last;
319         if (depth > 5) {
320                 error("%s: ignoring alternate object stores, nesting too deep.",
321                                 relative_base);
322                 return;
323         }
325         last = alt;
326         while (last < ep) {
327                 cp = last;
328                 if (cp < ep && *cp == '#') {
329                         while (cp < ep && *cp != sep)
330                                 cp++;
331                         last = cp + 1;
332                         continue;
333                 }
334                 while (cp < ep && *cp != sep)
335                         cp++;
336                 if (last != cp) {
337                         if (!is_absolute_path(last) && depth) {
338                                 error("%s: ignoring relative alternate object store %s",
339                                                 relative_base, last);
340                         } else {
341                                 link_alt_odb_entry(last, cp - last,
342                                                 relative_base, depth);
343                         }
344                 }
345                 while (cp < ep && *cp == sep)
346                         cp++;
347                 last = cp;
348         }
351 static void read_info_alternates(const char * relative_base, int depth)
353         char *map;
354         size_t mapsz;
355         struct stat st;
356         const char alt_file_name[] = "info/alternates";
357         /* Given that relative_base is no longer than PATH_MAX,
358            ensure that "path" has enough space to append "/", the
359            file name, "info/alternates", and a trailing NUL.  */
360         char path[PATH_MAX + 1 + sizeof alt_file_name];
361         int fd;
363         sprintf(path, "%s/%s", relative_base, alt_file_name);
364         fd = git_open_noatime(path, NULL);
365         if (fd < 0)
366                 return;
367         if (fstat(fd, &st) || (st.st_size == 0)) {
368                 close(fd);
369                 return;
370         }
371         mapsz = xsize_t(st.st_size);
372         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
373         close(fd);
375         link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
377         munmap(map, mapsz);
380 void add_to_alternates_file(const char *reference)
382         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
383         int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
384         char *alt = mkpath("%s/objects\n", reference);
385         write_or_die(fd, alt, strlen(alt));
386         if (commit_lock_file(lock))
387                 die("could not close alternates file");
388         if (alt_odb_tail)
389                 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
392 void foreach_alt_odb(alt_odb_fn fn, void *cb)
394         struct alternate_object_database *ent;
396         prepare_alt_odb();
397         for (ent = alt_odb_list; ent; ent = ent->next)
398                 if (fn(ent, cb))
399                         return;
402 void prepare_alt_odb(void)
404         const char *alt;
406         if (alt_odb_tail)
407                 return;
409         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
410         if (!alt) alt = "";
412         alt_odb_tail = &alt_odb_list;
413         link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
415         read_info_alternates(get_object_directory(), 0);
418 static int has_loose_object_local(const unsigned char *sha1)
420         char *name = sha1_file_name(sha1);
421         return !access(name, F_OK);
424 int has_loose_object_nonlocal(const unsigned char *sha1)
426         struct alternate_object_database *alt;
427         prepare_alt_odb();
428         for (alt = alt_odb_list; alt; alt = alt->next) {
429                 fill_sha1_path(alt->name, sha1);
430                 if (!access(alt->base, F_OK))
431                         return 1;
432         }
433         return 0;
436 static int has_loose_object(const unsigned char *sha1)
438         return has_loose_object_local(sha1) ||
439                has_loose_object_nonlocal(sha1);
442 static unsigned int pack_used_ctr;
443 static unsigned int pack_mmap_calls;
444 static unsigned int peak_pack_open_windows;
445 static unsigned int pack_open_windows;
446 static unsigned int pack_open_fds;
447 static unsigned int pack_max_fds;
448 static size_t peak_pack_mapped;
449 static size_t pack_mapped;
450 struct packed_git *packed_git;
452 void pack_report(void)
454         fprintf(stderr,
455                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
456                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
457                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
458                 sz_fmt(getpagesize()),
459                 sz_fmt(packed_git_window_size),
460                 sz_fmt(packed_git_limit));
461         fprintf(stderr,
462                 "pack_report: pack_used_ctr            = %10u\n"
463                 "pack_report: pack_mmap_calls          = %10u\n"
464                 "pack_report: pack_open_windows        = %10u / %10u\n"
465                 "pack_report: pack_mapped              = "
466                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
467                 pack_used_ctr,
468                 pack_mmap_calls,
469                 pack_open_windows, peak_pack_open_windows,
470                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
473 static int check_packed_git_idx(const char *path,  struct packed_git *p)
475         void *idx_map;
476         struct pack_idx_header *hdr;
477         size_t idx_size;
478         uint32_t version, nr, i, *index;
479         int fd = git_open_noatime(path, p);
480         struct stat st;
482         if (fd < 0)
483                 return -1;
484         if (fstat(fd, &st)) {
485                 close(fd);
486                 return -1;
487         }
488         idx_size = xsize_t(st.st_size);
489         if (idx_size < 4 * 256 + 20 + 20) {
490                 close(fd);
491                 return error("index file %s is too small", path);
492         }
493         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
494         close(fd);
496         hdr = idx_map;
497         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
498                 version = ntohl(hdr->idx_version);
499                 if (version < 2 || version > 2) {
500                         munmap(idx_map, idx_size);
501                         return error("index file %s is version %"PRIu32
502                                      " and is not supported by this binary"
503                                      " (try upgrading GIT to a newer version)",
504                                      path, version);
505                 }
506         } else
507                 version = 1;
509         nr = 0;
510         index = idx_map;
511         if (version > 1)
512                 index += 2;  /* skip index header */
513         for (i = 0; i < 256; i++) {
514                 uint32_t n = ntohl(index[i]);
515                 if (n < nr) {
516                         munmap(idx_map, idx_size);
517                         return error("non-monotonic index %s", path);
518                 }
519                 nr = n;
520         }
522         if (version == 1) {
523                 /*
524                  * Total size:
525                  *  - 256 index entries 4 bytes each
526                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
527                  *  - 20-byte SHA1 of the packfile
528                  *  - 20-byte SHA1 file checksum
529                  */
530                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
531                         munmap(idx_map, idx_size);
532                         return error("wrong index v1 file size in %s", path);
533                 }
534         } else if (version == 2) {
535                 /*
536                  * Minimum size:
537                  *  - 8 bytes of header
538                  *  - 256 index entries 4 bytes each
539                  *  - 20-byte sha1 entry * nr
540                  *  - 4-byte crc entry * nr
541                  *  - 4-byte offset entry * nr
542                  *  - 20-byte SHA1 of the packfile
543                  *  - 20-byte SHA1 file checksum
544                  * And after the 4-byte offset table might be a
545                  * variable sized table containing 8-byte entries
546                  * for offsets larger than 2^31.
547                  */
548                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
549                 unsigned long max_size = min_size;
550                 if (nr)
551                         max_size += (nr - 1)*8;
552                 if (idx_size < min_size || idx_size > max_size) {
553                         munmap(idx_map, idx_size);
554                         return error("wrong index v2 file size in %s", path);
555                 }
556                 if (idx_size != min_size &&
557                     /*
558                      * make sure we can deal with large pack offsets.
559                      * 31-bit signed offset won't be enough, neither
560                      * 32-bit unsigned one will be.
561                      */
562                     (sizeof(off_t) <= 4)) {
563                         munmap(idx_map, idx_size);
564                         return error("pack too large for current definition of off_t in %s", path);
565                 }
566         }
568         p->index_version = version;
569         p->index_data = idx_map;
570         p->index_size = idx_size;
571         p->num_objects = nr;
572         return 0;
575 int open_pack_index(struct packed_git *p)
577         char *idx_name;
578         int ret;
580         if (p->index_data)
581                 return 0;
583         idx_name = xstrdup(p->pack_name);
584         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
585         ret = check_packed_git_idx(idx_name, p);
586         free(idx_name);
587         return ret;
590 static void scan_windows(struct packed_git *p,
591         struct packed_git **lru_p,
592         struct pack_window **lru_w,
593         struct pack_window **lru_l)
595         struct pack_window *w, *w_l;
597         for (w_l = NULL, w = p->windows; w; w = w->next) {
598                 if (!w->inuse_cnt) {
599                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
600                                 *lru_p = p;
601                                 *lru_w = w;
602                                 *lru_l = w_l;
603                         }
604                 }
605                 w_l = w;
606         }
609 static int unuse_one_window(struct packed_git *current, int keep_fd)
611         struct packed_git *p, *lru_p = NULL;
612         struct pack_window *lru_w = NULL, *lru_l = NULL;
614         if (current)
615                 scan_windows(current, &lru_p, &lru_w, &lru_l);
616         for (p = packed_git; p; p = p->next)
617                 scan_windows(p, &lru_p, &lru_w, &lru_l);
618         if (lru_p) {
619                 munmap(lru_w->base, lru_w->len);
620                 pack_mapped -= lru_w->len;
621                 if (lru_l)
622                         lru_l->next = lru_w->next;
623                 else {
624                         lru_p->windows = lru_w->next;
625                         if (!lru_p->windows && lru_p->pack_fd != -1
626                                 && lru_p->pack_fd != keep_fd) {
627                                 close(lru_p->pack_fd);
628                                 pack_open_fds--;
629                                 lru_p->pack_fd = -1;
630                         }
631                 }
632                 free(lru_w);
633                 pack_open_windows--;
634                 return 1;
635         }
636         return 0;
639 void release_pack_memory(size_t need, int fd)
641         size_t cur = pack_mapped;
642         while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
643                 ; /* nothing */
646 void *xmmap(void *start, size_t length,
647         int prot, int flags, int fd, off_t offset)
649         void *ret = mmap(start, length, prot, flags, fd, offset);
650         if (ret == MAP_FAILED) {
651                 if (!length)
652                         return NULL;
653                 release_pack_memory(length, fd);
654                 ret = mmap(start, length, prot, flags, fd, offset);
655                 if (ret == MAP_FAILED)
656                         die_errno("Out of memory? mmap failed");
657         }
658         return ret;
661 void close_pack_windows(struct packed_git *p)
663         while (p->windows) {
664                 struct pack_window *w = p->windows;
666                 if (w->inuse_cnt)
667                         die("pack '%s' still has open windows to it",
668                             p->pack_name);
669                 munmap(w->base, w->len);
670                 pack_mapped -= w->len;
671                 pack_open_windows--;
672                 p->windows = w->next;
673                 free(w);
674         }
677 void unuse_pack(struct pack_window **w_cursor)
679         struct pack_window *w = *w_cursor;
680         if (w) {
681                 w->inuse_cnt--;
682                 *w_cursor = NULL;
683         }
686 void close_pack_index(struct packed_git *p)
688         if (p->index_data) {
689                 munmap((void *)p->index_data, p->index_size);
690                 p->index_data = NULL;
691         }
694 /*
695  * This is used by git-repack in case a newly created pack happens to
696  * contain the same set of objects as an existing one.  In that case
697  * the resulting file might be different even if its name would be the
698  * same.  It is best to close any reference to the old pack before it is
699  * replaced on disk.  Of course no index pointers nor windows for given pack
700  * must subsist at this point.  If ever objects from this pack are requested
701  * again, the new version of the pack will be reinitialized through
702  * reprepare_packed_git().
703  */
704 void free_pack_by_name(const char *pack_name)
706         struct packed_git *p, **pp = &packed_git;
708         while (*pp) {
709                 p = *pp;
710                 if (strcmp(pack_name, p->pack_name) == 0) {
711                         clear_delta_base_cache();
712                         close_pack_windows(p);
713                         if (p->pack_fd != -1) {
714                                 close(p->pack_fd);
715                                 pack_open_fds--;
716                         }
717                         close_pack_index(p);
718                         free(p->bad_object_sha1);
719                         *pp = p->next;
720                         free(p);
721                         return;
722                 }
723                 pp = &p->next;
724         }
727 /*
728  * Do not call this directly as this leaks p->pack_fd on error return;
729  * call open_packed_git() instead.
730  */
731 static int open_packed_git_1(struct packed_git *p)
733         struct stat st;
734         struct pack_header hdr;
735         unsigned char sha1[20];
736         unsigned char *idx_sha1;
737         long fd_flag;
739         if (!p->index_data && open_pack_index(p))
740                 return error("packfile %s index unavailable", p->pack_name);
742         if (!pack_max_fds) {
743                 struct rlimit lim;
744                 unsigned int max_fds;
746                 if (getrlimit(RLIMIT_NOFILE, &lim))
747                         die_errno("cannot get RLIMIT_NOFILE");
749                 max_fds = lim.rlim_cur;
751                 /* Save 3 for stdin/stdout/stderr, 22 for work */
752                 if (25 < max_fds)
753                         pack_max_fds = max_fds - 25;
754                 else
755                         pack_max_fds = 1;
756         }
758         while (pack_max_fds <= pack_open_fds && unuse_one_window(NULL, -1))
759                 ; /* nothing */
761         p->pack_fd = git_open_noatime(p->pack_name, p);
762         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
763                 return -1;
764         pack_open_fds++;
766         /* If we created the struct before we had the pack we lack size. */
767         if (!p->pack_size) {
768                 if (!S_ISREG(st.st_mode))
769                         return error("packfile %s not a regular file", p->pack_name);
770                 p->pack_size = st.st_size;
771         } else if (p->pack_size != st.st_size)
772                 return error("packfile %s size changed", p->pack_name);
774         /* We leave these file descriptors open with sliding mmap;
775          * there is no point keeping them open across exec(), though.
776          */
777         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
778         if (fd_flag < 0)
779                 return error("cannot determine file descriptor flags");
780         fd_flag |= FD_CLOEXEC;
781         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
782                 return error("cannot set FD_CLOEXEC");
784         /* Verify we recognize this pack file format. */
785         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
786                 return error("file %s is far too short to be a packfile", p->pack_name);
787         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
788                 return error("file %s is not a GIT packfile", p->pack_name);
789         if (!pack_version_ok(hdr.hdr_version))
790                 return error("packfile %s is version %"PRIu32" and not"
791                         " supported (try upgrading GIT to a newer version)",
792                         p->pack_name, ntohl(hdr.hdr_version));
794         /* Verify the pack matches its index. */
795         if (p->num_objects != ntohl(hdr.hdr_entries))
796                 return error("packfile %s claims to have %"PRIu32" objects"
797                              " while index indicates %"PRIu32" objects",
798                              p->pack_name, ntohl(hdr.hdr_entries),
799                              p->num_objects);
800         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
801                 return error("end of packfile %s is unavailable", p->pack_name);
802         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
803                 return error("packfile %s signature is unavailable", p->pack_name);
804         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
805         if (hashcmp(sha1, idx_sha1))
806                 return error("packfile %s does not match index", p->pack_name);
807         return 0;
810 static int open_packed_git(struct packed_git *p)
812         if (!open_packed_git_1(p))
813                 return 0;
814         if (p->pack_fd != -1) {
815                 close(p->pack_fd);
816                 pack_open_fds--;
817                 p->pack_fd = -1;
818         }
819         return -1;
822 static int in_window(struct pack_window *win, off_t offset)
824         /* We must promise at least 20 bytes (one hash) after the
825          * offset is available from this window, otherwise the offset
826          * is not actually in this window and a different window (which
827          * has that one hash excess) must be used.  This is to support
828          * the object header and delta base parsing routines below.
829          */
830         off_t win_off = win->offset;
831         return win_off <= offset
832                 && (offset + 20) <= (win_off + win->len);
835 unsigned char *use_pack(struct packed_git *p,
836                 struct pack_window **w_cursor,
837                 off_t offset,
838                 unsigned int *left)
840         struct pack_window *win = *w_cursor;
842         /* Since packfiles end in a hash of their content and it's
843          * pointless to ask for an offset into the middle of that
844          * hash, and the in_window function above wouldn't match
845          * don't allow an offset too close to the end of the file.
846          */
847         if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
848                 die("packfile %s cannot be accessed", p->pack_name);
849         if (offset > (p->pack_size - 20))
850                 die("offset beyond end of packfile (truncated pack?)");
852         if (!win || !in_window(win, offset)) {
853                 if (win)
854                         win->inuse_cnt--;
855                 for (win = p->windows; win; win = win->next) {
856                         if (in_window(win, offset))
857                                 break;
858                 }
859                 if (!win) {
860                         size_t window_align = packed_git_window_size / 2;
861                         off_t len;
863                         if (p->pack_fd == -1 && open_packed_git(p))
864                                 die("packfile %s cannot be accessed", p->pack_name);
866                         win = xcalloc(1, sizeof(*win));
867                         win->offset = (offset / window_align) * window_align;
868                         len = p->pack_size - win->offset;
869                         if (len > packed_git_window_size)
870                                 len = packed_git_window_size;
871                         win->len = (size_t)len;
872                         pack_mapped += win->len;
873                         while (packed_git_limit < pack_mapped
874                                 && unuse_one_window(p, p->pack_fd))
875                                 ; /* nothing */
876                         win->base = xmmap(NULL, win->len,
877                                 PROT_READ, MAP_PRIVATE,
878                                 p->pack_fd, win->offset);
879                         if (win->base == MAP_FAILED)
880                                 die("packfile %s cannot be mapped: %s",
881                                         p->pack_name,
882                                         strerror(errno));
883                         if (!win->offset && win->len == p->pack_size
884                                 && !p->do_not_close) {
885                                 close(p->pack_fd);
886                                 pack_open_fds--;
887                                 p->pack_fd = -1;
888                         }
889                         pack_mmap_calls++;
890                         pack_open_windows++;
891                         if (pack_mapped > peak_pack_mapped)
892                                 peak_pack_mapped = pack_mapped;
893                         if (pack_open_windows > peak_pack_open_windows)
894                                 peak_pack_open_windows = pack_open_windows;
895                         win->next = p->windows;
896                         p->windows = win;
897                 }
898         }
899         if (win != *w_cursor) {
900                 win->last_used = pack_used_ctr++;
901                 win->inuse_cnt++;
902                 *w_cursor = win;
903         }
904         offset -= win->offset;
905         if (left)
906                 *left = win->len - xsize_t(offset);
907         return win->base + offset;
910 static struct packed_git *alloc_packed_git(int extra)
912         struct packed_git *p = xmalloc(sizeof(*p) + extra);
913         memset(p, 0, sizeof(*p));
914         p->pack_fd = -1;
915         return p;
918 static void try_to_free_pack_memory(size_t size)
920         release_pack_memory(size, -1);
923 struct packed_git *add_packed_git(const char *path, int path_len, int local)
925         static int have_set_try_to_free_routine;
926         struct stat st;
927         struct packed_git *p = alloc_packed_git(path_len + 2);
929         if (!have_set_try_to_free_routine) {
930                 have_set_try_to_free_routine = 1;
931                 set_try_to_free_routine(try_to_free_pack_memory);
932         }
934         /*
935          * Make sure a corresponding .pack file exists and that
936          * the index looks sane.
937          */
938         path_len -= strlen(".idx");
939         if (path_len < 1) {
940                 free(p);
941                 return NULL;
942         }
943         memcpy(p->pack_name, path, path_len);
945         strcpy(p->pack_name + path_len, ".keep");
946         if (!access(p->pack_name, F_OK))
947                 p->pack_keep = 1;
949         strcpy(p->pack_name + path_len, ".pack");
950         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
951                 free(p);
952                 return NULL;
953         }
955         /* ok, it looks sane as far as we can check without
956          * actually mapping the pack file.
957          */
958         p->pack_size = st.st_size;
959         p->pack_local = local;
960         p->mtime = st.st_mtime;
961         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
962                 hashclr(p->sha1);
963         return p;
966 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
968         const char *path = sha1_pack_name(sha1);
969         struct packed_git *p = alloc_packed_git(strlen(path) + 1);
971         strcpy(p->pack_name, path);
972         hashcpy(p->sha1, sha1);
973         if (check_packed_git_idx(idx_path, p)) {
974                 free(p);
975                 return NULL;
976         }
978         return p;
981 void install_packed_git(struct packed_git *pack)
983         if (pack->pack_fd != -1)
984                 pack_open_fds++;
986         pack->next = packed_git;
987         packed_git = pack;
990 static void prepare_packed_git_one(char *objdir, int local)
992         /* Ensure that this buffer is large enough so that we can
993            append "/pack/" without clobbering the stack even if
994            strlen(objdir) were PATH_MAX.  */
995         char path[PATH_MAX + 1 + 4 + 1 + 1];
996         int len;
997         DIR *dir;
998         struct dirent *de;
1000         sprintf(path, "%s/pack", objdir);
1001         len = strlen(path);
1002         dir = opendir(path);
1003         if (!dir) {
1004                 if (errno != ENOENT)
1005                         error("unable to open object pack directory: %s: %s",
1006                               path, strerror(errno));
1007                 return;
1008         }
1009         path[len++] = '/';
1010         while ((de = readdir(dir)) != NULL) {
1011                 int namelen = strlen(de->d_name);
1012                 struct packed_git *p;
1014                 if (!has_extension(de->d_name, ".idx"))
1015                         continue;
1017                 if (len + namelen + 1 > sizeof(path))
1018                         continue;
1020                 /* Don't reopen a pack we already have. */
1021                 strcpy(path + len, de->d_name);
1022                 for (p = packed_git; p; p = p->next) {
1023                         if (!memcmp(path, p->pack_name, len + namelen - 4))
1024                                 break;
1025                 }
1026                 if (p)
1027                         continue;
1028                 /* See if it really is a valid .idx file with corresponding
1029                  * .pack file that we can map.
1030                  */
1031                 p = add_packed_git(path, len + namelen, local);
1032                 if (!p)
1033                         continue;
1034                 install_packed_git(p);
1035         }
1036         closedir(dir);
1039 static int sort_pack(const void *a_, const void *b_)
1041         struct packed_git *a = *((struct packed_git **)a_);
1042         struct packed_git *b = *((struct packed_git **)b_);
1043         int st;
1045         /*
1046          * Local packs tend to contain objects specific to our
1047          * variant of the project than remote ones.  In addition,
1048          * remote ones could be on a network mounted filesystem.
1049          * Favor local ones for these reasons.
1050          */
1051         st = a->pack_local - b->pack_local;
1052         if (st)
1053                 return -st;
1055         /*
1056          * Younger packs tend to contain more recent objects,
1057          * and more recent objects tend to get accessed more
1058          * often.
1059          */
1060         if (a->mtime < b->mtime)
1061                 return 1;
1062         else if (a->mtime == b->mtime)
1063                 return 0;
1064         return -1;
1067 static void rearrange_packed_git(void)
1069         struct packed_git **ary, *p;
1070         int i, n;
1072         for (n = 0, p = packed_git; p; p = p->next)
1073                 n++;
1074         if (n < 2)
1075                 return;
1077         /* prepare an array of packed_git for easier sorting */
1078         ary = xcalloc(n, sizeof(struct packed_git *));
1079         for (n = 0, p = packed_git; p; p = p->next)
1080                 ary[n++] = p;
1082         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1084         /* link them back again */
1085         for (i = 0; i < n - 1; i++)
1086                 ary[i]->next = ary[i + 1];
1087         ary[n - 1]->next = NULL;
1088         packed_git = ary[0];
1090         free(ary);
1093 static int prepare_packed_git_run_once = 0;
1094 void prepare_packed_git(void)
1096         struct alternate_object_database *alt;
1098         if (prepare_packed_git_run_once)
1099                 return;
1100         prepare_packed_git_one(get_object_directory(), 1);
1101         prepare_alt_odb();
1102         for (alt = alt_odb_list; alt; alt = alt->next) {
1103                 alt->name[-1] = 0;
1104                 prepare_packed_git_one(alt->base, 0);
1105                 alt->name[-1] = '/';
1106         }
1107         rearrange_packed_git();
1108         prepare_packed_git_run_once = 1;
1111 void reprepare_packed_git(void)
1113         discard_revindex();
1114         prepare_packed_git_run_once = 0;
1115         prepare_packed_git();
1118 static void mark_bad_packed_object(struct packed_git *p,
1119                                    const unsigned char *sha1)
1121         unsigned i;
1122         for (i = 0; i < p->num_bad_objects; i++)
1123                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1124                         return;
1125         p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1126         hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1127         p->num_bad_objects++;
1130 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1132         struct packed_git *p;
1133         unsigned i;
1135         for (p = packed_git; p; p = p->next)
1136                 for (i = 0; i < p->num_bad_objects; i++)
1137                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1138                                 return p;
1139         return NULL;
1142 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1144         unsigned char real_sha1[20];
1145         hash_sha1_file(map, size, type, real_sha1);
1146         return hashcmp(sha1, real_sha1) ? -1 : 0;
1149 static int git_open_noatime(const char *name, struct packed_git *p)
1151         static int sha1_file_open_flag = O_NOATIME;
1153         for (;;) {
1154                 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1155                 if (fd >= 0)
1156                         return fd;
1158                 /* Might the failure be due to O_NOATIME? */
1159                 if (errno != ENOENT && sha1_file_open_flag) {
1160                         sha1_file_open_flag = 0;
1161                         continue;
1162                 }
1164                 return -1;
1165         }
1168 static int open_sha1_file(const unsigned char *sha1)
1170         int fd;
1171         char *name = sha1_file_name(sha1);
1172         struct alternate_object_database *alt;
1174         fd = git_open_noatime(name, NULL);
1175         if (fd >= 0)
1176                 return fd;
1178         prepare_alt_odb();
1179         errno = ENOENT;
1180         for (alt = alt_odb_list; alt; alt = alt->next) {
1181                 name = alt->name;
1182                 fill_sha1_path(name, sha1);
1183                 fd = git_open_noatime(alt->base, NULL);
1184                 if (fd >= 0)
1185                         return fd;
1186         }
1187         return -1;
1190 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1192         void *map;
1193         int fd;
1195         fd = open_sha1_file(sha1);
1196         map = NULL;
1197         if (fd >= 0) {
1198                 struct stat st;
1200                 if (!fstat(fd, &st)) {
1201                         *size = xsize_t(st.st_size);
1202                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1203                 }
1204                 close(fd);
1205         }
1206         return map;
1209 static int legacy_loose_object(unsigned char *map)
1211         unsigned int word;
1213         /*
1214          * Is it a zlib-compressed buffer? If so, the first byte
1215          * must be 0x78 (15-bit window size, deflated), and the
1216          * first 16-bit word is evenly divisible by 31
1217          */
1218         word = (map[0] << 8) + map[1];
1219         if (map[0] == 0x78 && !(word % 31))
1220                 return 1;
1221         else
1222                 return 0;
1225 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1226                 unsigned long len, enum object_type *type, unsigned long *sizep)
1228         unsigned shift;
1229         unsigned long size, c;
1230         unsigned long used = 0;
1232         c = buf[used++];
1233         *type = (c >> 4) & 7;
1234         size = c & 15;
1235         shift = 4;
1236         while (c & 0x80) {
1237                 if (len <= used || bitsizeof(long) <= shift) {
1238                         error("bad object header");
1239                         return 0;
1240                 }
1241                 c = buf[used++];
1242                 size += (c & 0x7f) << shift;
1243                 shift += 7;
1244         }
1245         *sizep = size;
1246         return used;
1249 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1251         unsigned long size, used;
1252         static const char valid_loose_object_type[8] = {
1253                 0, /* OBJ_EXT */
1254                 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1255                 0, /* "delta" and others are invalid in a loose object */
1256         };
1257         enum object_type type;
1259         /* Get the data stream */
1260         memset(stream, 0, sizeof(*stream));
1261         stream->next_in = map;
1262         stream->avail_in = mapsize;
1263         stream->next_out = buffer;
1264         stream->avail_out = bufsiz;
1266         if (legacy_loose_object(map)) {
1267                 git_inflate_init(stream);
1268                 return git_inflate(stream, 0);
1269         }
1272         /*
1273          * There used to be a second loose object header format which
1274          * was meant to mimic the in-pack format, allowing for direct
1275          * copy of the object data.  This format turned up not to be
1276          * really worth it and we don't write it any longer.  But we
1277          * can still read it.
1278          */
1279         used = unpack_object_header_buffer(map, mapsize, &type, &size);
1280         if (!used || !valid_loose_object_type[type])
1281                 return -1;
1282         map += used;
1283         mapsize -= used;
1285         /* Set up the stream for the rest.. */
1286         stream->next_in = map;
1287         stream->avail_in = mapsize;
1288         git_inflate_init(stream);
1290         /* And generate the fake traditional header */
1291         stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1292                                          typename(type), size);
1293         return 0;
1296 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1298         int bytes = strlen(buffer) + 1;
1299         unsigned char *buf = xmallocz(size);
1300         unsigned long n;
1301         int status = Z_OK;
1303         n = stream->total_out - bytes;
1304         if (n > size)
1305                 n = size;
1306         memcpy(buf, (char *) buffer + bytes, n);
1307         bytes = n;
1308         if (bytes <= size) {
1309                 /*
1310                  * The above condition must be (bytes <= size), not
1311                  * (bytes < size).  In other words, even though we
1312                  * expect no more output and set avail_out to zer0,
1313                  * the input zlib stream may have bytes that express
1314                  * "this concludes the stream", and we *do* want to
1315                  * eat that input.
1316                  *
1317                  * Otherwise we would not be able to test that we
1318                  * consumed all the input to reach the expected size;
1319                  * we also want to check that zlib tells us that all
1320                  * went well with status == Z_STREAM_END at the end.
1321                  */
1322                 stream->next_out = buf + bytes;
1323                 stream->avail_out = size - bytes;
1324                 while (status == Z_OK)
1325                         status = git_inflate(stream, Z_FINISH);
1326         }
1327         if (status == Z_STREAM_END && !stream->avail_in) {
1328                 git_inflate_end(stream);
1329                 return buf;
1330         }
1332         if (status < 0)
1333                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1334         else if (stream->avail_in)
1335                 error("garbage at end of loose object '%s'",
1336                       sha1_to_hex(sha1));
1337         free(buf);
1338         return NULL;
1341 /*
1342  * We used to just use "sscanf()", but that's actually way
1343  * too permissive for what we want to check. So do an anal
1344  * object header parse by hand.
1345  */
1346 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1348         char type[10];
1349         int i;
1350         unsigned long size;
1352         /*
1353          * The type can be at most ten bytes (including the
1354          * terminating '\0' that we add), and is followed by
1355          * a space.
1356          */
1357         i = 0;
1358         for (;;) {
1359                 char c = *hdr++;
1360                 if (c == ' ')
1361                         break;
1362                 type[i++] = c;
1363                 if (i >= sizeof(type))
1364                         return -1;
1365         }
1366         type[i] = 0;
1368         /*
1369          * The length must follow immediately, and be in canonical
1370          * decimal format (ie "010" is not valid).
1371          */
1372         size = *hdr++ - '0';
1373         if (size > 9)
1374                 return -1;
1375         if (size) {
1376                 for (;;) {
1377                         unsigned long c = *hdr - '0';
1378                         if (c > 9)
1379                                 break;
1380                         hdr++;
1381                         size = size * 10 + c;
1382                 }
1383         }
1384         *sizep = size;
1386         /*
1387          * The length must be followed by a zero byte
1388          */
1389         return *hdr ? -1 : type_from_string(type);
1392 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1394         int ret;
1395         z_stream stream;
1396         char hdr[8192];
1398         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1399         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1400                 return NULL;
1402         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1405 unsigned long get_size_from_delta(struct packed_git *p,
1406                                   struct pack_window **w_curs,
1407                                   off_t curpos)
1409         const unsigned char *data;
1410         unsigned char delta_head[20], *in;
1411         z_stream stream;
1412         int st;
1414         memset(&stream, 0, sizeof(stream));
1415         stream.next_out = delta_head;
1416         stream.avail_out = sizeof(delta_head);
1418         git_inflate_init(&stream);
1419         do {
1420                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1421                 stream.next_in = in;
1422                 st = git_inflate(&stream, Z_FINISH);
1423                 curpos += stream.next_in - in;
1424         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1425                  stream.total_out < sizeof(delta_head));
1426         git_inflate_end(&stream);
1427         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1428                 error("delta data unpack-initial failed");
1429                 return 0;
1430         }
1432         /* Examine the initial part of the delta to figure out
1433          * the result size.
1434          */
1435         data = delta_head;
1437         /* ignore base size */
1438         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1440         /* Read the result size */
1441         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1444 static off_t get_delta_base(struct packed_git *p,
1445                                     struct pack_window **w_curs,
1446                                     off_t *curpos,
1447                                     enum object_type type,
1448                                     off_t delta_obj_offset)
1450         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1451         off_t base_offset;
1453         /* use_pack() assured us we have [base_info, base_info + 20)
1454          * as a range that we can look at without walking off the
1455          * end of the mapped window.  Its actually the hash size
1456          * that is assured.  An OFS_DELTA longer than the hash size
1457          * is stupid, as then a REF_DELTA would be smaller to store.
1458          */
1459         if (type == OBJ_OFS_DELTA) {
1460                 unsigned used = 0;
1461                 unsigned char c = base_info[used++];
1462                 base_offset = c & 127;
1463                 while (c & 128) {
1464                         base_offset += 1;
1465                         if (!base_offset || MSB(base_offset, 7))
1466                                 return 0;  /* overflow */
1467                         c = base_info[used++];
1468                         base_offset = (base_offset << 7) + (c & 127);
1469                 }
1470                 base_offset = delta_obj_offset - base_offset;
1471                 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1472                         return 0;  /* out of bound */
1473                 *curpos += used;
1474         } else if (type == OBJ_REF_DELTA) {
1475                 /* The base entry _must_ be in the same pack */
1476                 base_offset = find_pack_entry_one(base_info, p);
1477                 *curpos += 20;
1478         } else
1479                 die("I am totally screwed");
1480         return base_offset;
1483 /* forward declaration for a mutually recursive function */
1484 static int packed_object_info(struct packed_git *p, off_t offset,
1485                               unsigned long *sizep);
1487 static int packed_delta_info(struct packed_git *p,
1488                              struct pack_window **w_curs,
1489                              off_t curpos,
1490                              enum object_type type,
1491                              off_t obj_offset,
1492                              unsigned long *sizep)
1494         off_t base_offset;
1496         base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1497         if (!base_offset)
1498                 return OBJ_BAD;
1499         type = packed_object_info(p, base_offset, NULL);
1500         if (type <= OBJ_NONE) {
1501                 struct revindex_entry *revidx;
1502                 const unsigned char *base_sha1;
1503                 revidx = find_pack_revindex(p, base_offset);
1504                 if (!revidx)
1505                         return OBJ_BAD;
1506                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1507                 mark_bad_packed_object(p, base_sha1);
1508                 type = sha1_object_info(base_sha1, NULL);
1509                 if (type <= OBJ_NONE)
1510                         return OBJ_BAD;
1511         }
1513         /* We choose to only get the type of the base object and
1514          * ignore potentially corrupt pack file that expects the delta
1515          * based on a base with a wrong size.  This saves tons of
1516          * inflate() calls.
1517          */
1518         if (sizep) {
1519                 *sizep = get_size_from_delta(p, w_curs, curpos);
1520                 if (*sizep == 0)
1521                         type = OBJ_BAD;
1522         }
1524         return type;
1527 static int unpack_object_header(struct packed_git *p,
1528                                 struct pack_window **w_curs,
1529                                 off_t *curpos,
1530                                 unsigned long *sizep)
1532         unsigned char *base;
1533         unsigned int left;
1534         unsigned long used;
1535         enum object_type type;
1537         /* use_pack() assures us we have [base, base + 20) available
1538          * as a range that we can look at.  (Its actually the hash
1539          * size that is assured.)  With our object header encoding
1540          * the maximum deflated object size is 2^137, which is just
1541          * insane, so we know won't exceed what we have been given.
1542          */
1543         base = use_pack(p, w_curs, *curpos, &left);
1544         used = unpack_object_header_buffer(base, left, &type, sizep);
1545         if (!used) {
1546                 type = OBJ_BAD;
1547         } else
1548                 *curpos += used;
1550         return type;
1553 const char *packed_object_info_detail(struct packed_git *p,
1554                                       off_t obj_offset,
1555                                       unsigned long *size,
1556                                       unsigned long *store_size,
1557                                       unsigned int *delta_chain_length,
1558                                       unsigned char *base_sha1)
1560         struct pack_window *w_curs = NULL;
1561         off_t curpos;
1562         unsigned long dummy;
1563         unsigned char *next_sha1;
1564         enum object_type type;
1565         struct revindex_entry *revidx;
1567         *delta_chain_length = 0;
1568         curpos = obj_offset;
1569         type = unpack_object_header(p, &w_curs, &curpos, size);
1571         revidx = find_pack_revindex(p, obj_offset);
1572         *store_size = revidx[1].offset - obj_offset;
1574         for (;;) {
1575                 switch (type) {
1576                 default:
1577                         die("pack %s contains unknown object type %d",
1578                             p->pack_name, type);
1579                 case OBJ_COMMIT:
1580                 case OBJ_TREE:
1581                 case OBJ_BLOB:
1582                 case OBJ_TAG:
1583                         unuse_pack(&w_curs);
1584                         return typename(type);
1585                 case OBJ_OFS_DELTA:
1586                         obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1587                         if (!obj_offset)
1588                                 die("pack %s contains bad delta base reference of type %s",
1589                                     p->pack_name, typename(type));
1590                         if (*delta_chain_length == 0) {
1591                                 revidx = find_pack_revindex(p, obj_offset);
1592                                 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1593                         }
1594                         break;
1595                 case OBJ_REF_DELTA:
1596                         next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1597                         if (*delta_chain_length == 0)
1598                                 hashcpy(base_sha1, next_sha1);
1599                         obj_offset = find_pack_entry_one(next_sha1, p);
1600                         break;
1601                 }
1602                 (*delta_chain_length)++;
1603                 curpos = obj_offset;
1604                 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1605         }
1608 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1609                               unsigned long *sizep)
1611         struct pack_window *w_curs = NULL;
1612         unsigned long size;
1613         off_t curpos = obj_offset;
1614         enum object_type type;
1616         type = unpack_object_header(p, &w_curs, &curpos, &size);
1618         switch (type) {
1619         case OBJ_OFS_DELTA:
1620         case OBJ_REF_DELTA:
1621                 type = packed_delta_info(p, &w_curs, curpos,
1622                                          type, obj_offset, sizep);
1623                 break;
1624         case OBJ_COMMIT:
1625         case OBJ_TREE:
1626         case OBJ_BLOB:
1627         case OBJ_TAG:
1628                 if (sizep)
1629                         *sizep = size;
1630                 break;
1631         default:
1632                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1633                       type, (uintmax_t)obj_offset, p->pack_name);
1634                 type = OBJ_BAD;
1635         }
1636         unuse_pack(&w_curs);
1637         return type;
1640 static void *unpack_compressed_entry(struct packed_git *p,
1641                                     struct pack_window **w_curs,
1642                                     off_t curpos,
1643                                     unsigned long size)
1645         int st;
1646         z_stream stream;
1647         unsigned char *buffer, *in;
1649         buffer = xmallocz(size);
1650         memset(&stream, 0, sizeof(stream));
1651         stream.next_out = buffer;
1652         stream.avail_out = size + 1;
1654         git_inflate_init(&stream);
1655         do {
1656                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1657                 stream.next_in = in;
1658                 st = git_inflate(&stream, Z_FINISH);
1659                 if (!stream.avail_out)
1660                         break; /* the payload is larger than it should be */
1661                 curpos += stream.next_in - in;
1662         } while (st == Z_OK || st == Z_BUF_ERROR);
1663         git_inflate_end(&stream);
1664         if ((st != Z_STREAM_END) || stream.total_out != size) {
1665                 free(buffer);
1666                 return NULL;
1667         }
1669         return buffer;
1672 #define MAX_DELTA_CACHE (256)
1674 static size_t delta_base_cached;
1676 static struct delta_base_cache_lru_list {
1677         struct delta_base_cache_lru_list *prev;
1678         struct delta_base_cache_lru_list *next;
1679 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1681 static struct delta_base_cache_entry {
1682         struct delta_base_cache_lru_list lru;
1683         void *data;
1684         struct packed_git *p;
1685         off_t base_offset;
1686         unsigned long size;
1687         enum object_type type;
1688 } delta_base_cache[MAX_DELTA_CACHE];
1690 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1692         unsigned long hash;
1694         hash = (unsigned long)p + (unsigned long)base_offset;
1695         hash += (hash >> 8) + (hash >> 16);
1696         return hash % MAX_DELTA_CACHE;
1699 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1700         unsigned long *base_size, enum object_type *type, int keep_cache)
1702         void *ret;
1703         unsigned long hash = pack_entry_hash(p, base_offset);
1704         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1706         ret = ent->data;
1707         if (!ret || ent->p != p || ent->base_offset != base_offset)
1708                 return unpack_entry(p, base_offset, type, base_size);
1710         if (!keep_cache) {
1711                 ent->data = NULL;
1712                 ent->lru.next->prev = ent->lru.prev;
1713                 ent->lru.prev->next = ent->lru.next;
1714                 delta_base_cached -= ent->size;
1715         } else {
1716                 ret = xmemdupz(ent->data, ent->size);
1717         }
1718         *type = ent->type;
1719         *base_size = ent->size;
1720         return ret;
1723 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1725         if (ent->data) {
1726                 free(ent->data);
1727                 ent->data = NULL;
1728                 ent->lru.next->prev = ent->lru.prev;
1729                 ent->lru.prev->next = ent->lru.next;
1730                 delta_base_cached -= ent->size;
1731         }
1734 void clear_delta_base_cache(void)
1736         unsigned long p;
1737         for (p = 0; p < MAX_DELTA_CACHE; p++)
1738                 release_delta_base_cache(&delta_base_cache[p]);
1741 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1742         void *base, unsigned long base_size, enum object_type type)
1744         unsigned long hash = pack_entry_hash(p, base_offset);
1745         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1746         struct delta_base_cache_lru_list *lru;
1748         release_delta_base_cache(ent);
1749         delta_base_cached += base_size;
1751         for (lru = delta_base_cache_lru.next;
1752              delta_base_cached > delta_base_cache_limit
1753              && lru != &delta_base_cache_lru;
1754              lru = lru->next) {
1755                 struct delta_base_cache_entry *f = (void *)lru;
1756                 if (f->type == OBJ_BLOB)
1757                         release_delta_base_cache(f);
1758         }
1759         for (lru = delta_base_cache_lru.next;
1760              delta_base_cached > delta_base_cache_limit
1761              && lru != &delta_base_cache_lru;
1762              lru = lru->next) {
1763                 struct delta_base_cache_entry *f = (void *)lru;
1764                 release_delta_base_cache(f);
1765         }
1767         ent->p = p;
1768         ent->base_offset = base_offset;
1769         ent->type = type;
1770         ent->data = base;
1771         ent->size = base_size;
1772         ent->lru.next = &delta_base_cache_lru;
1773         ent->lru.prev = delta_base_cache_lru.prev;
1774         delta_base_cache_lru.prev->next = &ent->lru;
1775         delta_base_cache_lru.prev = &ent->lru;
1778 static void *read_object(const unsigned char *sha1, enum object_type *type,
1779                          unsigned long *size);
1781 static void *unpack_delta_entry(struct packed_git *p,
1782                                 struct pack_window **w_curs,
1783                                 off_t curpos,
1784                                 unsigned long delta_size,
1785                                 off_t obj_offset,
1786                                 enum object_type *type,
1787                                 unsigned long *sizep)
1789         void *delta_data, *result, *base;
1790         unsigned long base_size;
1791         off_t base_offset;
1793         base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1794         if (!base_offset) {
1795                 error("failed to validate delta base reference "
1796                       "at offset %"PRIuMAX" from %s",
1797                       (uintmax_t)curpos, p->pack_name);
1798                 return NULL;
1799         }
1800         unuse_pack(w_curs);
1801         base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1802         if (!base) {
1803                 /*
1804                  * We're probably in deep shit, but let's try to fetch
1805                  * the required base anyway from another pack or loose.
1806                  * This is costly but should happen only in the presence
1807                  * of a corrupted pack, and is better than failing outright.
1808                  */
1809                 struct revindex_entry *revidx;
1810                 const unsigned char *base_sha1;
1811                 revidx = find_pack_revindex(p, base_offset);
1812                 if (!revidx)
1813                         return NULL;
1814                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1815                 error("failed to read delta base object %s"
1816                       " at offset %"PRIuMAX" from %s",
1817                       sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1818                       p->pack_name);
1819                 mark_bad_packed_object(p, base_sha1);
1820                 base = read_object(base_sha1, type, &base_size);
1821                 if (!base)
1822                         return NULL;
1823         }
1825         delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1826         if (!delta_data) {
1827                 error("failed to unpack compressed delta "
1828                       "at offset %"PRIuMAX" from %s",
1829                       (uintmax_t)curpos, p->pack_name);
1830                 free(base);
1831                 return NULL;
1832         }
1833         result = patch_delta(base, base_size,
1834                              delta_data, delta_size,
1835                              sizep);
1836         if (!result)
1837                 die("failed to apply delta");
1838         free(delta_data);
1839         add_delta_base_cache(p, base_offset, base, base_size, *type);
1840         return result;
1843 int do_check_packed_object_crc;
1845 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1846                    enum object_type *type, unsigned long *sizep)
1848         struct pack_window *w_curs = NULL;
1849         off_t curpos = obj_offset;
1850         void *data;
1852         if (do_check_packed_object_crc && p->index_version > 1) {
1853                 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1854                 unsigned long len = revidx[1].offset - obj_offset;
1855                 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1856                         const unsigned char *sha1 =
1857                                 nth_packed_object_sha1(p, revidx->nr);
1858                         error("bad packed object CRC for %s",
1859                               sha1_to_hex(sha1));
1860                         mark_bad_packed_object(p, sha1);
1861                         unuse_pack(&w_curs);
1862                         return NULL;
1863                 }
1864         }
1866         *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1867         switch (*type) {
1868         case OBJ_OFS_DELTA:
1869         case OBJ_REF_DELTA:
1870                 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1871                                           obj_offset, type, sizep);
1872                 break;
1873         case OBJ_COMMIT:
1874         case OBJ_TREE:
1875         case OBJ_BLOB:
1876         case OBJ_TAG:
1877                 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1878                 break;
1879         default:
1880                 data = NULL;
1881                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1882                       *type, (uintmax_t)obj_offset, p->pack_name);
1883         }
1884         unuse_pack(&w_curs);
1885         return data;
1888 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1889                                             uint32_t n)
1891         const unsigned char *index = p->index_data;
1892         if (!index) {
1893                 if (open_pack_index(p))
1894                         return NULL;
1895                 index = p->index_data;
1896         }
1897         if (n >= p->num_objects)
1898                 return NULL;
1899         index += 4 * 256;
1900         if (p->index_version == 1) {
1901                 return index + 24 * n + 4;
1902         } else {
1903                 index += 8;
1904                 return index + 20 * n;
1905         }
1908 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1910         const unsigned char *index = p->index_data;
1911         index += 4 * 256;
1912         if (p->index_version == 1) {
1913                 return ntohl(*((uint32_t *)(index + 24 * n)));
1914         } else {
1915                 uint32_t off;
1916                 index += 8 + p->num_objects * (20 + 4);
1917                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1918                 if (!(off & 0x80000000))
1919                         return off;
1920                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1921                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1922                                    ntohl(*((uint32_t *)(index + 4)));
1923         }
1926 off_t find_pack_entry_one(const unsigned char *sha1,
1927                                   struct packed_git *p)
1929         const uint32_t *level1_ofs = p->index_data;
1930         const unsigned char *index = p->index_data;
1931         unsigned hi, lo, stride;
1932         static int use_lookup = -1;
1933         static int debug_lookup = -1;
1935         if (debug_lookup < 0)
1936                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1938         if (!index) {
1939                 if (open_pack_index(p))
1940                         return 0;
1941                 level1_ofs = p->index_data;
1942                 index = p->index_data;
1943         }
1944         if (p->index_version > 1) {
1945                 level1_ofs += 2;
1946                 index += 8;
1947         }
1948         index += 4 * 256;
1949         hi = ntohl(level1_ofs[*sha1]);
1950         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1951         if (p->index_version > 1) {
1952                 stride = 20;
1953         } else {
1954                 stride = 24;
1955                 index += 4;
1956         }
1958         if (debug_lookup)
1959                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1960                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1962         if (use_lookup < 0)
1963                 use_lookup = !!getenv("GIT_USE_LOOKUP");
1964         if (use_lookup) {
1965                 int pos = sha1_entry_pos(index, stride, 0,
1966                                          lo, hi, p->num_objects, sha1);
1967                 if (pos < 0)
1968                         return 0;
1969                 return nth_packed_object_offset(p, pos);
1970         }
1972         do {
1973                 unsigned mi = (lo + hi) / 2;
1974                 int cmp = hashcmp(index + mi * stride, sha1);
1976                 if (debug_lookup)
1977                         printf("lo %u hi %u rg %u mi %u\n",
1978                                lo, hi, hi - lo, mi);
1979                 if (!cmp)
1980                         return nth_packed_object_offset(p, mi);
1981                 if (cmp > 0)
1982                         hi = mi;
1983                 else
1984                         lo = mi+1;
1985         } while (lo < hi);
1986         return 0;
1989 static int is_pack_valid(struct packed_git *p)
1991         /* An already open pack is known to be valid. */
1992         if (p->pack_fd != -1)
1993                 return 1;
1995         /* If the pack has one window completely covering the
1996          * file size, the pack is known to be valid even if
1997          * the descriptor is not currently open.
1998          */
1999         if (p->windows) {
2000                 struct pack_window *w = p->windows;
2002                 if (!w->offset && w->len == p->pack_size)
2003                         return 1;
2004         }
2006         /* Force the pack to open to prove its valid. */
2007         return !open_packed_git(p);
2010 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2012         static struct packed_git *last_found = (void *)1;
2013         struct packed_git *p;
2014         off_t offset;
2016         prepare_packed_git();
2017         if (!packed_git)
2018                 return 0;
2019         p = (last_found == (void *)1) ? packed_git : last_found;
2021         do {
2022                 if (p->num_bad_objects) {
2023                         unsigned i;
2024                         for (i = 0; i < p->num_bad_objects; i++)
2025                                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2026                                         goto next;
2027                 }
2029                 offset = find_pack_entry_one(sha1, p);
2030                 if (offset) {
2031                         /*
2032                          * We are about to tell the caller where they can
2033                          * locate the requested object.  We better make
2034                          * sure the packfile is still here and can be
2035                          * accessed before supplying that answer, as
2036                          * it may have been deleted since the index
2037                          * was loaded!
2038                          */
2039                         if (!is_pack_valid(p)) {
2040                                 error("packfile %s cannot be accessed", p->pack_name);
2041                                 goto next;
2042                         }
2043                         e->offset = offset;
2044                         e->p = p;
2045                         hashcpy(e->sha1, sha1);
2046                         last_found = p;
2047                         return 1;
2048                 }
2050                 next:
2051                 if (p == last_found)
2052                         p = packed_git;
2053                 else
2054                         p = p->next;
2055                 if (p == last_found)
2056                         p = p->next;
2057         } while (p);
2058         return 0;
2061 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2062                                   struct packed_git *packs)
2064         struct packed_git *p;
2066         for (p = packs; p; p = p->next) {
2067                 if (find_pack_entry_one(sha1, p))
2068                         return p;
2069         }
2070         return NULL;
2074 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
2076         int status;
2077         unsigned long mapsize, size;
2078         void *map;
2079         z_stream stream;
2080         char hdr[32];
2082         map = map_sha1_file(sha1, &mapsize);
2083         if (!map)
2084                 return error("unable to find %s", sha1_to_hex(sha1));
2085         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2086                 status = error("unable to unpack %s header",
2087                                sha1_to_hex(sha1));
2088         else if ((status = parse_sha1_header(hdr, &size)) < 0)
2089                 status = error("unable to parse %s header", sha1_to_hex(sha1));
2090         else if (sizep)
2091                 *sizep = size;
2092         git_inflate_end(&stream);
2093         munmap(map, mapsize);
2094         return status;
2097 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2099         struct cached_object *co;
2100         struct pack_entry e;
2101         int status;
2103         co = find_cached_object(sha1);
2104         if (co) {
2105                 if (sizep)
2106                         *sizep = co->size;
2107                 return co->type;
2108         }
2110         if (!find_pack_entry(sha1, &e)) {
2111                 /* Most likely it's a loose object. */
2112                 status = sha1_loose_object_info(sha1, sizep);
2113                 if (status >= 0)
2114                         return status;
2116                 /* Not a loose object; someone else may have just packed it. */
2117                 reprepare_packed_git();
2118                 if (!find_pack_entry(sha1, &e))
2119                         return status;
2120         }
2122         status = packed_object_info(e.p, e.offset, sizep);
2123         if (status < 0) {
2124                 mark_bad_packed_object(e.p, sha1);
2125                 status = sha1_object_info(sha1, sizep);
2126         }
2128         return status;
2131 static void *read_packed_sha1(const unsigned char *sha1,
2132                               enum object_type *type, unsigned long *size)
2134         struct pack_entry e;
2135         void *data;
2137         if (!find_pack_entry(sha1, &e))
2138                 return NULL;
2139         data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2140         if (!data) {
2141                 /*
2142                  * We're probably in deep shit, but let's try to fetch
2143                  * the required object anyway from another pack or loose.
2144                  * This should happen only in the presence of a corrupted
2145                  * pack, and is better than failing outright.
2146                  */
2147                 error("failed to read object %s at offset %"PRIuMAX" from %s",
2148                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2149                 mark_bad_packed_object(e.p, sha1);
2150                 data = read_object(sha1, type, size);
2151         }
2152         return data;
2155 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2156                       unsigned char *sha1)
2158         struct cached_object *co;
2160         hash_sha1_file(buf, len, typename(type), sha1);
2161         if (has_sha1_file(sha1) || find_cached_object(sha1))
2162                 return 0;
2163         if (cached_object_alloc <= cached_object_nr) {
2164                 cached_object_alloc = alloc_nr(cached_object_alloc);
2165                 cached_objects = xrealloc(cached_objects,
2166                                           sizeof(*cached_objects) *
2167                                           cached_object_alloc);
2168         }
2169         co = &cached_objects[cached_object_nr++];
2170         co->size = len;
2171         co->type = type;
2172         co->buf = xmalloc(len);
2173         memcpy(co->buf, buf, len);
2174         hashcpy(co->sha1, sha1);
2175         return 0;
2178 static void *read_object(const unsigned char *sha1, enum object_type *type,
2179                          unsigned long *size)
2181         unsigned long mapsize;
2182         void *map, *buf;
2183         struct cached_object *co;
2185         co = find_cached_object(sha1);
2186         if (co) {
2187                 *type = co->type;
2188                 *size = co->size;
2189                 return xmemdupz(co->buf, co->size);
2190         }
2192         buf = read_packed_sha1(sha1, type, size);
2193         if (buf)
2194                 return buf;
2195         map = map_sha1_file(sha1, &mapsize);
2196         if (map) {
2197                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2198                 munmap(map, mapsize);
2199                 return buf;
2200         }
2201         reprepare_packed_git();
2202         return read_packed_sha1(sha1, type, size);
2205 /*
2206  * This function dies on corrupt objects; the callers who want to
2207  * deal with them should arrange to call read_object() and give error
2208  * messages themselves.
2209  */
2210 void *read_sha1_file_repl(const unsigned char *sha1,
2211                           enum object_type *type,
2212                           unsigned long *size,
2213                           const unsigned char **replacement)
2215         const unsigned char *repl = lookup_replace_object(sha1);
2216         void *data;
2217         char *path;
2218         const struct packed_git *p;
2220         errno = 0;
2221         data = read_object(repl, type, size);
2222         if (data) {
2223                 if (replacement)
2224                         *replacement = repl;
2225                 return data;
2226         }
2228         if (errno && errno != ENOENT)
2229                 die_errno("failed to read object %s", sha1_to_hex(sha1));
2231         /* die if we replaced an object with one that does not exist */
2232         if (repl != sha1)
2233                 die("replacement %s not found for %s",
2234                     sha1_to_hex(repl), sha1_to_hex(sha1));
2236         if (has_loose_object(repl)) {
2237                 path = sha1_file_name(sha1);
2238                 die("loose object %s (stored in %s) is corrupt",
2239                     sha1_to_hex(repl), path);
2240         }
2242         if ((p = has_packed_and_bad(repl)) != NULL)
2243                 die("packed object %s (stored in %s) is corrupt",
2244                     sha1_to_hex(repl), p->pack_name);
2246         return NULL;
2249 void *read_object_with_reference(const unsigned char *sha1,
2250                                  const char *required_type_name,
2251                                  unsigned long *size,
2252                                  unsigned char *actual_sha1_return)
2254         enum object_type type, required_type;
2255         void *buffer;
2256         unsigned long isize;
2257         unsigned char actual_sha1[20];
2259         required_type = type_from_string(required_type_name);
2260         hashcpy(actual_sha1, sha1);
2261         while (1) {
2262                 int ref_length = -1;
2263                 const char *ref_type = NULL;
2265                 buffer = read_sha1_file(actual_sha1, &type, &isize);
2266                 if (!buffer)
2267                         return NULL;
2268                 if (type == required_type) {
2269                         *size = isize;
2270                         if (actual_sha1_return)
2271                                 hashcpy(actual_sha1_return, actual_sha1);
2272                         return buffer;
2273                 }
2274                 /* Handle references */
2275                 else if (type == OBJ_COMMIT)
2276                         ref_type = "tree ";
2277                 else if (type == OBJ_TAG)
2278                         ref_type = "object ";
2279                 else {
2280                         free(buffer);
2281                         return NULL;
2282                 }
2283                 ref_length = strlen(ref_type);
2285                 if (ref_length + 40 > isize ||
2286                     memcmp(buffer, ref_type, ref_length) ||
2287                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2288                         free(buffer);
2289                         return NULL;
2290                 }
2291                 free(buffer);
2292                 /* Now we have the ID of the referred-to object in
2293                  * actual_sha1.  Check again. */
2294         }
2297 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2298                                     const char *type, unsigned char *sha1,
2299                                     char *hdr, int *hdrlen)
2301         git_SHA_CTX c;
2303         /* Generate the header */
2304         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2306         /* Sha1.. */
2307         git_SHA1_Init(&c);
2308         git_SHA1_Update(&c, hdr, *hdrlen);
2309         git_SHA1_Update(&c, buf, len);
2310         git_SHA1_Final(sha1, &c);
2313 /*
2314  * Move the just written object into its final resting place.
2315  * NEEDSWORK: this should be renamed to finalize_temp_file() as
2316  * "moving" is only a part of what it does, when no patch between
2317  * master to pu changes the call sites of this function.
2318  */
2319 int move_temp_to_file(const char *tmpfile, const char *filename)
2321         int ret = 0;
2323         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2324                 goto try_rename;
2325         else if (link(tmpfile, filename))
2326                 ret = errno;
2328         /*
2329          * Coda hack - coda doesn't like cross-directory links,
2330          * so we fall back to a rename, which will mean that it
2331          * won't be able to check collisions, but that's not a
2332          * big deal.
2333          *
2334          * The same holds for FAT formatted media.
2335          *
2336          * When this succeeds, we just return.  We have nothing
2337          * left to unlink.
2338          */
2339         if (ret && ret != EEXIST) {
2340         try_rename:
2341                 if (!rename(tmpfile, filename))
2342                         goto out;
2343                 ret = errno;
2344         }
2345         unlink_or_warn(tmpfile);
2346         if (ret) {
2347                 if (ret != EEXIST) {
2348                         return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2349                 }
2350                 /* FIXME!!! Collision check here ? */
2351         }
2353 out:
2354         if (adjust_shared_perm(filename))
2355                 return error("unable to set permission to '%s'", filename);
2356         return 0;
2359 static int write_buffer(int fd, const void *buf, size_t len)
2361         if (write_in_full(fd, buf, len) < 0)
2362                 return error("file write error (%s)", strerror(errno));
2363         return 0;
2366 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2367                    unsigned char *sha1)
2369         char hdr[32];
2370         int hdrlen;
2371         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2372         return 0;
2375 /* Finalize a file on disk, and close it. */
2376 static void close_sha1_file(int fd)
2378         if (fsync_object_files)
2379                 fsync_or_die(fd, "sha1 file");
2380         if (close(fd) != 0)
2381                 die_errno("error when closing sha1 file");
2384 /* Size of directory component, including the ending '/' */
2385 static inline int directory_size(const char *filename)
2387         const char *s = strrchr(filename, '/');
2388         if (!s)
2389                 return 0;
2390         return s - filename + 1;
2393 /*
2394  * This creates a temporary file in the same directory as the final
2395  * 'filename'
2396  *
2397  * We want to avoid cross-directory filename renames, because those
2398  * can have problems on various filesystems (FAT, NFS, Coda).
2399  */
2400 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2402         int fd, dirlen = directory_size(filename);
2404         if (dirlen + 20 > bufsiz) {
2405                 errno = ENAMETOOLONG;
2406                 return -1;
2407         }
2408         memcpy(buffer, filename, dirlen);
2409         strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2410         fd = git_mkstemp_mode(buffer, 0444);
2411         if (fd < 0 && dirlen && errno == ENOENT) {
2412                 /* Make sure the directory exists */
2413                 memcpy(buffer, filename, dirlen);
2414                 buffer[dirlen-1] = 0;
2415                 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2416                         return -1;
2418                 /* Try again */
2419                 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2420                 fd = git_mkstemp_mode(buffer, 0444);
2421         }
2422         return fd;
2425 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2426                               const void *buf, unsigned long len, time_t mtime)
2428         int fd, ret;
2429         unsigned char compressed[4096];
2430         z_stream stream;
2431         git_SHA_CTX c;
2432         unsigned char parano_sha1[20];
2433         char *filename;
2434         static char tmpfile[PATH_MAX];
2436         filename = sha1_file_name(sha1);
2437         fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2438         if (fd < 0) {
2439                 if (errno == EACCES)
2440                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2441                 else
2442                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2443         }
2445         /* Set it up */
2446         memset(&stream, 0, sizeof(stream));
2447         deflateInit(&stream, zlib_compression_level);
2448         stream.next_out = compressed;
2449         stream.avail_out = sizeof(compressed);
2450         git_SHA1_Init(&c);
2452         /* First header.. */
2453         stream.next_in = (unsigned char *)hdr;
2454         stream.avail_in = hdrlen;
2455         while (deflate(&stream, 0) == Z_OK)
2456                 /* nothing */;
2457         git_SHA1_Update(&c, hdr, hdrlen);
2459         /* Then the data itself.. */
2460         stream.next_in = (void *)buf;
2461         stream.avail_in = len;
2462         do {
2463                 unsigned char *in0 = stream.next_in;
2464                 ret = deflate(&stream, Z_FINISH);
2465                 git_SHA1_Update(&c, in0, stream.next_in - in0);
2466                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2467                         die("unable to write sha1 file");
2468                 stream.next_out = compressed;
2469                 stream.avail_out = sizeof(compressed);
2470         } while (ret == Z_OK);
2472         if (ret != Z_STREAM_END)
2473                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2474         ret = deflateEnd(&stream);
2475         if (ret != Z_OK)
2476                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2477         git_SHA1_Final(parano_sha1, &c);
2478         if (hashcmp(sha1, parano_sha1) != 0)
2479                 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2481         close_sha1_file(fd);
2483         if (mtime) {
2484                 struct utimbuf utb;
2485                 utb.actime = mtime;
2486                 utb.modtime = mtime;
2487                 if (utime(tmpfile, &utb) < 0)
2488                         warning("failed utime() on %s: %s",
2489                                 tmpfile, strerror(errno));
2490         }
2492         return move_temp_to_file(tmpfile, filename);
2495 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2497         unsigned char sha1[20];
2498         char hdr[32];
2499         int hdrlen;
2501         /* Normally if we have it in the pack then we do not bother writing
2502          * it out into .git/objects/??/?{38} file.
2503          */
2504         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2505         if (returnsha1)
2506                 hashcpy(returnsha1, sha1);
2507         if (has_sha1_file(sha1))
2508                 return 0;
2509         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2512 int force_object_loose(const unsigned char *sha1, time_t mtime)
2514         void *buf;
2515         unsigned long len;
2516         enum object_type type;
2517         char hdr[32];
2518         int hdrlen;
2519         int ret;
2521         if (has_loose_object(sha1))
2522                 return 0;
2523         buf = read_packed_sha1(sha1, &type, &len);
2524         if (!buf)
2525                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2526         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2527         ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2528         free(buf);
2530         return ret;
2533 int has_pack_index(const unsigned char *sha1)
2535         struct stat st;
2536         if (stat(sha1_pack_index_name(sha1), &st))
2537                 return 0;
2538         return 1;
2541 int has_sha1_pack(const unsigned char *sha1)
2543         struct pack_entry e;
2544         return find_pack_entry(sha1, &e);
2547 int has_sha1_file(const unsigned char *sha1)
2549         struct pack_entry e;
2551         if (find_pack_entry(sha1, &e))
2552                 return 1;
2553         return has_loose_object(sha1);
2556 static void check_tree(const void *buf, size_t size)
2558         struct tree_desc desc;
2559         struct name_entry entry;
2561         init_tree_desc(&desc, buf, size);
2562         while (tree_entry(&desc, &entry))
2563                 /* do nothing
2564                  * tree_entry() will die() on malformed entries */
2565                 ;
2568 static void check_commit(const void *buf, size_t size)
2570         struct commit c;
2571         memset(&c, 0, sizeof(c));
2572         if (parse_commit_buffer(&c, buf, size))
2573                 die("corrupt commit");
2576 static void check_tag(const void *buf, size_t size)
2578         struct tag t;
2579         memset(&t, 0, sizeof(t));
2580         if (parse_tag_buffer(&t, buf, size))
2581                 die("corrupt tag");
2584 static int index_mem(unsigned char *sha1, void *buf, size_t size,
2585                      enum object_type type,
2586                      const char *path, unsigned flags)
2588         int ret, re_allocated = 0;
2589         int write_object = flags & HASH_WRITE_OBJECT;
2591         if (!type)
2592                 type = OBJ_BLOB;
2594         /*
2595          * Convert blobs to git internal format
2596          */
2597         if ((type == OBJ_BLOB) && path) {
2598                 struct strbuf nbuf = STRBUF_INIT;
2599                 if (convert_to_git(path, buf, size, &nbuf,
2600                                    write_object ? safe_crlf : 0)) {
2601                         buf = strbuf_detach(&nbuf, &size);
2602                         re_allocated = 1;
2603                 }
2604         }
2605         if (flags & HASH_FORMAT_CHECK) {
2606                 if (type == OBJ_TREE)
2607                         check_tree(buf, size);
2608                 if (type == OBJ_COMMIT)
2609                         check_commit(buf, size);
2610                 if (type == OBJ_TAG)
2611                         check_tag(buf, size);
2612         }
2614         if (write_object)
2615                 ret = write_sha1_file(buf, size, typename(type), sha1);
2616         else
2617                 ret = hash_sha1_file(buf, size, typename(type), sha1);
2618         if (re_allocated)
2619                 free(buf);
2620         return ret;
2623 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
2624                       const char *path, unsigned flags)
2626         struct strbuf sbuf = STRBUF_INIT;
2627         int ret;
2629         if (strbuf_read(&sbuf, fd, 4096) >= 0)
2630                 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
2631         else
2632                 ret = -1;
2633         strbuf_release(&sbuf);
2634         return ret;
2637 #define SMALL_FILE_SIZE (32*1024)
2639 static int index_core(unsigned char *sha1, int fd, size_t size,
2640                       enum object_type type, const char *path,
2641                       unsigned flags)
2643         int ret;
2645         if (!size) {
2646                 ret = index_mem(sha1, NULL, size, type, path, flags);
2647         } else if (size <= SMALL_FILE_SIZE) {
2648                 char *buf = xmalloc(size);
2649                 if (size == read_in_full(fd, buf, size))
2650                         ret = index_mem(sha1, buf, size, type, path, flags);
2651                 else
2652                         ret = error("short read %s", strerror(errno));
2653                 free(buf);
2654         } else {
2655                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2656                 ret = index_mem(sha1, buf, size, type, path, flags);
2657                 munmap(buf, size);
2658         }
2659         return ret;
2662 /*
2663  * This creates one packfile per large blob, because the caller
2664  * immediately wants the result sha1, and fast-import can report the
2665  * object name via marks mechanism only by closing the created
2666  * packfile.
2667  *
2668  * This also bypasses the usual "convert-to-git" dance, and that is on
2669  * purpose. We could write a streaming version of the converting
2670  * functions and insert that before feeding the data to fast-import
2671  * (or equivalent in-core API described above), but the primary
2672  * motivation for trying to stream from the working tree file and to
2673  * avoid mmaping it in core is to deal with large binary blobs, and
2674  * by definition they do _not_ want to get any conversion.
2675  */
2676 static int index_stream(unsigned char *sha1, int fd, size_t size,
2677                         enum object_type type, const char *path,
2678                         unsigned flags)
2680         struct child_process fast_import;
2681         char export_marks[512];
2682         const char *argv[] = { "fast-import", "--quiet", export_marks, NULL };
2683         char tmpfile[512];
2684         char fast_import_cmd[512];
2685         char buf[512];
2686         int len, tmpfd;
2688         strcpy(tmpfile, git_path("hashstream_XXXXXX"));
2689         tmpfd = git_mkstemp_mode(tmpfile, 0600);
2690         if (tmpfd < 0)
2691                 die_errno("cannot create tempfile: %s", tmpfile);
2692         if (close(tmpfd))
2693                 die_errno("cannot close tempfile: %s", tmpfile);
2694         sprintf(export_marks, "--export-marks=%s", tmpfile);
2696         memset(&fast_import, 0, sizeof(fast_import));
2697         fast_import.in = -1;
2698         fast_import.argv = argv;
2699         fast_import.git_cmd = 1;
2700         if (start_command(&fast_import))
2701                 die_errno("index-stream: git fast-import failed");
2703         len = sprintf(fast_import_cmd, "blob\nmark :1\ndata %lu\n",
2704                       (unsigned long) size);
2705         write_or_whine(fast_import.in, fast_import_cmd, len,
2706                        "index-stream: feeding fast-import");
2707         while (size) {
2708                 char buf[10240];
2709                 size_t sz = size < sizeof(buf) ? size : sizeof(buf);
2710                 size_t actual;
2712                 actual = read_in_full(fd, buf, sz);
2713                 if (actual < 0)
2714                         die_errno("index-stream: reading input");
2715                 if (write_in_full(fast_import.in, buf, actual) != actual)
2716                         die_errno("index-stream: feeding fast-import");
2717                 size -= actual;
2718         }
2719         if (close(fast_import.in))
2720                 die_errno("index-stream: closing fast-import");
2721         if (finish_command(&fast_import))
2722                 die_errno("index-stream: finishing fast-import");
2724         tmpfd = open(tmpfile, O_RDONLY);
2725         if (tmpfd < 0)
2726                 die_errno("index-stream: cannot open fast-import mark");
2727         len = read(tmpfd, buf, sizeof(buf));
2728         if (len < 0)
2729                 die_errno("index-stream: reading fast-import mark");
2730         if (close(tmpfd) < 0)
2731                 die_errno("index-stream: closing fast-import mark");
2732         if (unlink(tmpfile))
2733                 die_errno("index-stream: unlinking fast-import mark");
2734         if (len != 44 ||
2735             memcmp(":1 ", buf, 3) ||
2736             get_sha1_hex(buf + 3, sha1))
2737                 die_errno("index-stream: unexpected fast-import mark: <%s>", buf);
2738         return 0;
2741 int index_fd(unsigned char *sha1, int fd, struct stat *st,
2742              enum object_type type, const char *path, unsigned flags)
2744         int ret;
2745         size_t size = xsize_t(st->st_size);
2747         if (!S_ISREG(st->st_mode))
2748                 ret = index_pipe(sha1, fd, type, path, flags);
2749         else if (size <= big_file_threshold || type != OBJ_BLOB)
2750                 ret = index_core(sha1, fd, size, type, path, flags);
2751         else
2752                 ret = index_stream(sha1, fd, size, type, path, flags);
2753         close(fd);
2754         return ret;
2757 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
2759         int fd;
2760         struct strbuf sb = STRBUF_INIT;
2762         switch (st->st_mode & S_IFMT) {
2763         case S_IFREG:
2764                 fd = open(path, O_RDONLY);
2765                 if (fd < 0)
2766                         return error("open(\"%s\"): %s", path,
2767                                      strerror(errno));
2768                 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
2769                         return error("%s: failed to insert into database",
2770                                      path);
2771                 break;
2772         case S_IFLNK:
2773                 if (strbuf_readlink(&sb, path, st->st_size)) {
2774                         char *errstr = strerror(errno);
2775                         return error("readlink(\"%s\"): %s", path,
2776                                      errstr);
2777                 }
2778                 if (!(flags & HASH_WRITE_OBJECT))
2779                         hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2780                 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2781                         return error("%s: failed to insert into database",
2782                                      path);
2783                 strbuf_release(&sb);
2784                 break;
2785         case S_IFDIR:
2786                 return resolve_gitlink_ref(path, "HEAD", sha1);
2787         default:
2788                 return error("%s: unsupported file type", path);
2789         }
2790         return 0;
2793 int read_pack_header(int fd, struct pack_header *header)
2795         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2796                 /* "eof before pack header was fully read" */
2797                 return PH_ERROR_EOF;
2799         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2800                 /* "protocol error (pack signature mismatch detected)" */
2801                 return PH_ERROR_PACK_SIGNATURE;
2802         if (!pack_version_ok(header->hdr_version))
2803                 /* "protocol error (pack version unsupported)" */
2804                 return PH_ERROR_PROTOCOL;
2805         return 0;
2808 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2810         enum object_type type = sha1_object_info(sha1, NULL);
2811         if (type < 0)
2812                 die("%s is not a valid object", sha1_to_hex(sha1));
2813         if (type != expect)
2814                 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
2815                     typename(expect));