Code

Restructure documentation for git-merge-base.
[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 "tag.h"
15 #include "tree.h"
16 #include "refs.h"
17 #include "pack-revindex.h"
18 #include "sha1-lookup.h"
20 #ifndef O_NOATIME
21 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
22 #define O_NOATIME 01000000
23 #else
24 #define O_NOATIME 0
25 #endif
26 #endif
28 #ifdef NO_C99_FORMAT
29 #define SZ_FMT "lu"
30 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
31 #else
32 #define SZ_FMT "zu"
33 static size_t sz_fmt(size_t s) { return s; }
34 #endif
36 const unsigned char null_sha1[20];
38 static int git_open_noatime(const char *name, struct packed_git *p);
40 /*
41  * This is meant to hold a *small* number of objects that you would
42  * want read_sha1_file() to be able to return, but yet you do not want
43  * to write them into the object store (e.g. a browse-only
44  * application).
45  */
46 static struct cached_object {
47         unsigned char sha1[20];
48         enum object_type type;
49         void *buf;
50         unsigned long size;
51 } *cached_objects;
52 static int cached_object_nr, cached_object_alloc;
54 static struct cached_object empty_tree = {
55         EMPTY_TREE_SHA1_BIN_LITERAL,
56         OBJ_TREE,
57         "",
58         0
59 };
61 static struct cached_object *find_cached_object(const unsigned char *sha1)
62 {
63         int i;
64         struct cached_object *co = cached_objects;
66         for (i = 0; i < cached_object_nr; i++, co++) {
67                 if (!hashcmp(co->sha1, sha1))
68                         return co;
69         }
70         if (!hashcmp(sha1, empty_tree.sha1))
71                 return &empty_tree;
72         return NULL;
73 }
75 int safe_create_leading_directories(char *path)
76 {
77         char *pos = path + offset_1st_component(path);
78         struct stat st;
80         while (pos) {
81                 pos = strchr(pos, '/');
82                 if (!pos)
83                         break;
84                 while (*++pos == '/')
85                         ;
86                 if (!*pos)
87                         break;
88                 *--pos = '\0';
89                 if (!stat(path, &st)) {
90                         /* path exists */
91                         if (!S_ISDIR(st.st_mode)) {
92                                 *pos = '/';
93                                 return -3;
94                         }
95                 }
96                 else if (mkdir(path, 0777)) {
97                         *pos = '/';
98                         return -1;
99                 }
100                 else if (adjust_shared_perm(path)) {
101                         *pos = '/';
102                         return -2;
103                 }
104                 *pos++ = '/';
105         }
106         return 0;
109 int safe_create_leading_directories_const(const char *path)
111         /* path points to cache entries, so xstrdup before messing with it */
112         char *buf = xstrdup(path);
113         int result = safe_create_leading_directories(buf);
114         free(buf);
115         return result;
118 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
120         int i;
121         for (i = 0; i < 20; i++) {
122                 static char hex[] = "0123456789abcdef";
123                 unsigned int val = sha1[i];
124                 char *pos = pathbuf + i*2 + (i > 0);
125                 *pos++ = hex[val >> 4];
126                 *pos = hex[val & 0xf];
127         }
130 /*
131  * NOTE! This returns a statically allocated buffer, so you have to be
132  * careful about using it. Do an "xstrdup()" if you need to save the
133  * filename.
134  *
135  * Also note that this returns the location for creating.  Reading
136  * SHA1 file can happen from any alternate directory listed in the
137  * DB_ENVIRONMENT environment variable if it is not found in
138  * the primary object database.
139  */
140 char *sha1_file_name(const unsigned char *sha1)
142         static char buf[PATH_MAX];
143         const char *objdir;
144         int len;
146         objdir = get_object_directory();
147         len = strlen(objdir);
149         /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
150         if (len + 43 > PATH_MAX)
151                 die("insanely long object directory %s", objdir);
152         memcpy(buf, objdir, len);
153         buf[len] = '/';
154         buf[len+3] = '/';
155         buf[len+42] = '\0';
156         fill_sha1_path(buf + len + 1, sha1);
157         return buf;
160 static char *sha1_get_pack_name(const unsigned char *sha1,
161                                 char **name, char **base, const char *which)
163         static const char hex[] = "0123456789abcdef";
164         char *buf;
165         int i;
167         if (!*base) {
168                 const char *sha1_file_directory = get_object_directory();
169                 int len = strlen(sha1_file_directory);
170                 *base = xmalloc(len + 60);
171                 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
172                         sha1_file_directory, which);
173                 *name = *base + len + 11;
174         }
176         buf = *name;
178         for (i = 0; i < 20; i++) {
179                 unsigned int val = *sha1++;
180                 *buf++ = hex[val >> 4];
181                 *buf++ = hex[val & 0xf];
182         }
184         return *base;
187 char *sha1_pack_name(const unsigned char *sha1)
189         static char *name, *base;
191         return sha1_get_pack_name(sha1, &name, &base, "pack");
194 char *sha1_pack_index_name(const unsigned char *sha1)
196         static char *name, *base;
198         return sha1_get_pack_name(sha1, &name, &base, "idx");
201 struct alternate_object_database *alt_odb_list;
202 static struct alternate_object_database **alt_odb_tail;
204 static void read_info_alternates(const char * alternates, int depth);
206 /*
207  * Prepare alternate object database registry.
208  *
209  * The variable alt_odb_list points at the list of struct
210  * alternate_object_database.  The elements on this list come from
211  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
212  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
213  * whose contents is similar to that environment variable but can be
214  * LF separated.  Its base points at a statically allocated buffer that
215  * contains "/the/directory/corresponding/to/.git/objects/...", while
216  * its name points just after the slash at the end of ".git/objects/"
217  * in the example above, and has enough space to hold 40-byte hex
218  * SHA1, an extra slash for the first level indirection, and the
219  * terminating NUL.
220  */
221 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
223         const char *objdir = get_object_directory();
224         struct alternate_object_database *ent;
225         struct alternate_object_database *alt;
226         /* 43 = 40-byte + 2 '/' + terminating NUL */
227         int pfxlen = len;
228         int entlen = pfxlen + 43;
229         int base_len = -1;
231         if (!is_absolute_path(entry) && relative_base) {
232                 /* Relative alt-odb */
233                 if (base_len < 0)
234                         base_len = strlen(relative_base) + 1;
235                 entlen += base_len;
236                 pfxlen += base_len;
237         }
238         ent = xmalloc(sizeof(*ent) + entlen);
240         if (!is_absolute_path(entry) && relative_base) {
241                 memcpy(ent->base, relative_base, base_len - 1);
242                 ent->base[base_len - 1] = '/';
243                 memcpy(ent->base + base_len, entry, len);
244         }
245         else
246                 memcpy(ent->base, entry, pfxlen);
248         ent->name = ent->base + pfxlen + 1;
249         ent->base[pfxlen + 3] = '/';
250         ent->base[pfxlen] = ent->base[entlen-1] = 0;
252         /* Detect cases where alternate disappeared */
253         if (!is_directory(ent->base)) {
254                 error("object directory %s does not exist; "
255                       "check .git/objects/info/alternates.",
256                       ent->base);
257                 free(ent);
258                 return -1;
259         }
261         /* Prevent the common mistake of listing the same
262          * thing twice, or object directory itself.
263          */
264         for (alt = alt_odb_list; alt; alt = alt->next) {
265                 if (!memcmp(ent->base, alt->base, pfxlen)) {
266                         free(ent);
267                         return -1;
268                 }
269         }
270         if (!memcmp(ent->base, objdir, pfxlen)) {
271                 free(ent);
272                 return -1;
273         }
275         /* add the alternate entry */
276         *alt_odb_tail = ent;
277         alt_odb_tail = &(ent->next);
278         ent->next = NULL;
280         /* recursively add alternates */
281         read_info_alternates(ent->base, depth + 1);
283         ent->base[pfxlen] = '/';
285         return 0;
288 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
289                                  const char *relative_base, int depth)
291         const char *cp, *last;
293         if (depth > 5) {
294                 error("%s: ignoring alternate object stores, nesting too deep.",
295                                 relative_base);
296                 return;
297         }
299         last = alt;
300         while (last < ep) {
301                 cp = last;
302                 if (cp < ep && *cp == '#') {
303                         while (cp < ep && *cp != sep)
304                                 cp++;
305                         last = cp + 1;
306                         continue;
307                 }
308                 while (cp < ep && *cp != sep)
309                         cp++;
310                 if (last != cp) {
311                         if (!is_absolute_path(last) && depth) {
312                                 error("%s: ignoring relative alternate object store %s",
313                                                 relative_base, last);
314                         } else {
315                                 link_alt_odb_entry(last, cp - last,
316                                                 relative_base, depth);
317                         }
318                 }
319                 while (cp < ep && *cp == sep)
320                         cp++;
321                 last = cp;
322         }
325 static void read_info_alternates(const char * relative_base, int depth)
327         char *map;
328         size_t mapsz;
329         struct stat st;
330         const char alt_file_name[] = "info/alternates";
331         /* Given that relative_base is no longer than PATH_MAX,
332            ensure that "path" has enough space to append "/", the
333            file name, "info/alternates", and a trailing NUL.  */
334         char path[PATH_MAX + 1 + sizeof alt_file_name];
335         int fd;
337         sprintf(path, "%s/%s", relative_base, alt_file_name);
338         fd = git_open_noatime(path, NULL);
339         if (fd < 0)
340                 return;
341         if (fstat(fd, &st) || (st.st_size == 0)) {
342                 close(fd);
343                 return;
344         }
345         mapsz = xsize_t(st.st_size);
346         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
347         close(fd);
349         link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
351         munmap(map, mapsz);
354 void add_to_alternates_file(const char *reference)
356         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
357         int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
358         char *alt = mkpath("%s/objects\n", reference);
359         write_or_die(fd, alt, strlen(alt));
360         if (commit_lock_file(lock))
361                 die("could not close alternates file");
362         if (alt_odb_tail)
363                 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
366 void foreach_alt_odb(alt_odb_fn fn, void *cb)
368         struct alternate_object_database *ent;
370         prepare_alt_odb();
371         for (ent = alt_odb_list; ent; ent = ent->next)
372                 if (fn(ent, cb))
373                         return;
376 void prepare_alt_odb(void)
378         const char *alt;
380         if (alt_odb_tail)
381                 return;
383         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
384         if (!alt) alt = "";
386         alt_odb_tail = &alt_odb_list;
387         link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
389         read_info_alternates(get_object_directory(), 0);
392 static int has_loose_object_local(const unsigned char *sha1)
394         char *name = sha1_file_name(sha1);
395         return !access(name, F_OK);
398 int has_loose_object_nonlocal(const unsigned char *sha1)
400         struct alternate_object_database *alt;
401         prepare_alt_odb();
402         for (alt = alt_odb_list; alt; alt = alt->next) {
403                 fill_sha1_path(alt->name, sha1);
404                 if (!access(alt->base, F_OK))
405                         return 1;
406         }
407         return 0;
410 static int has_loose_object(const unsigned char *sha1)
412         return has_loose_object_local(sha1) ||
413                has_loose_object_nonlocal(sha1);
416 static unsigned int pack_used_ctr;
417 static unsigned int pack_mmap_calls;
418 static unsigned int peak_pack_open_windows;
419 static unsigned int pack_open_windows;
420 static unsigned int pack_open_fds;
421 static unsigned int pack_max_fds;
422 static size_t peak_pack_mapped;
423 static size_t pack_mapped;
424 struct packed_git *packed_git;
426 void pack_report(void)
428         fprintf(stderr,
429                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
430                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
431                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
432                 sz_fmt(getpagesize()),
433                 sz_fmt(packed_git_window_size),
434                 sz_fmt(packed_git_limit));
435         fprintf(stderr,
436                 "pack_report: pack_used_ctr            = %10u\n"
437                 "pack_report: pack_mmap_calls          = %10u\n"
438                 "pack_report: pack_open_windows        = %10u / %10u\n"
439                 "pack_report: pack_mapped              = "
440                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
441                 pack_used_ctr,
442                 pack_mmap_calls,
443                 pack_open_windows, peak_pack_open_windows,
444                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
447 static int check_packed_git_idx(const char *path,  struct packed_git *p)
449         void *idx_map;
450         struct pack_idx_header *hdr;
451         size_t idx_size;
452         uint32_t version, nr, i, *index;
453         int fd = git_open_noatime(path, p);
454         struct stat st;
456         if (fd < 0)
457                 return -1;
458         if (fstat(fd, &st)) {
459                 close(fd);
460                 return -1;
461         }
462         idx_size = xsize_t(st.st_size);
463         if (idx_size < 4 * 256 + 20 + 20) {
464                 close(fd);
465                 return error("index file %s is too small", path);
466         }
467         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
468         close(fd);
470         hdr = idx_map;
471         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
472                 version = ntohl(hdr->idx_version);
473                 if (version < 2 || version > 2) {
474                         munmap(idx_map, idx_size);
475                         return error("index file %s is version %"PRIu32
476                                      " and is not supported by this binary"
477                                      " (try upgrading GIT to a newer version)",
478                                      path, version);
479                 }
480         } else
481                 version = 1;
483         nr = 0;
484         index = idx_map;
485         if (version > 1)
486                 index += 2;  /* skip index header */
487         for (i = 0; i < 256; i++) {
488                 uint32_t n = ntohl(index[i]);
489                 if (n < nr) {
490                         munmap(idx_map, idx_size);
491                         return error("non-monotonic index %s", path);
492                 }
493                 nr = n;
494         }
496         if (version == 1) {
497                 /*
498                  * Total size:
499                  *  - 256 index entries 4 bytes each
500                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
501                  *  - 20-byte SHA1 of the packfile
502                  *  - 20-byte SHA1 file checksum
503                  */
504                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
505                         munmap(idx_map, idx_size);
506                         return error("wrong index v1 file size in %s", path);
507                 }
508         } else if (version == 2) {
509                 /*
510                  * Minimum size:
511                  *  - 8 bytes of header
512                  *  - 256 index entries 4 bytes each
513                  *  - 20-byte sha1 entry * nr
514                  *  - 4-byte crc entry * nr
515                  *  - 4-byte offset entry * nr
516                  *  - 20-byte SHA1 of the packfile
517                  *  - 20-byte SHA1 file checksum
518                  * And after the 4-byte offset table might be a
519                  * variable sized table containing 8-byte entries
520                  * for offsets larger than 2^31.
521                  */
522                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
523                 unsigned long max_size = min_size;
524                 if (nr)
525                         max_size += (nr - 1)*8;
526                 if (idx_size < min_size || idx_size > max_size) {
527                         munmap(idx_map, idx_size);
528                         return error("wrong index v2 file size in %s", path);
529                 }
530                 if (idx_size != min_size &&
531                     /*
532                      * make sure we can deal with large pack offsets.
533                      * 31-bit signed offset won't be enough, neither
534                      * 32-bit unsigned one will be.
535                      */
536                     (sizeof(off_t) <= 4)) {
537                         munmap(idx_map, idx_size);
538                         return error("pack too large for current definition of off_t in %s", path);
539                 }
540         }
542         p->index_version = version;
543         p->index_data = idx_map;
544         p->index_size = idx_size;
545         p->num_objects = nr;
546         return 0;
549 int open_pack_index(struct packed_git *p)
551         char *idx_name;
552         int ret;
554         if (p->index_data)
555                 return 0;
557         idx_name = xstrdup(p->pack_name);
558         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
559         ret = check_packed_git_idx(idx_name, p);
560         free(idx_name);
561         return ret;
564 static void scan_windows(struct packed_git *p,
565         struct packed_git **lru_p,
566         struct pack_window **lru_w,
567         struct pack_window **lru_l)
569         struct pack_window *w, *w_l;
571         for (w_l = NULL, w = p->windows; w; w = w->next) {
572                 if (!w->inuse_cnt) {
573                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
574                                 *lru_p = p;
575                                 *lru_w = w;
576                                 *lru_l = w_l;
577                         }
578                 }
579                 w_l = w;
580         }
583 static int unuse_one_window(struct packed_git *current, int keep_fd)
585         struct packed_git *p, *lru_p = NULL;
586         struct pack_window *lru_w = NULL, *lru_l = NULL;
588         if (current)
589                 scan_windows(current, &lru_p, &lru_w, &lru_l);
590         for (p = packed_git; p; p = p->next)
591                 scan_windows(p, &lru_p, &lru_w, &lru_l);
592         if (lru_p) {
593                 munmap(lru_w->base, lru_w->len);
594                 pack_mapped -= lru_w->len;
595                 if (lru_l)
596                         lru_l->next = lru_w->next;
597                 else {
598                         lru_p->windows = lru_w->next;
599                         if (!lru_p->windows && lru_p->pack_fd != -1
600                                 && lru_p->pack_fd != keep_fd) {
601                                 close(lru_p->pack_fd);
602                                 pack_open_fds--;
603                                 lru_p->pack_fd = -1;
604                         }
605                 }
606                 free(lru_w);
607                 pack_open_windows--;
608                 return 1;
609         }
610         return 0;
613 void release_pack_memory(size_t need, int fd)
615         size_t cur = pack_mapped;
616         while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
617                 ; /* nothing */
620 void *xmmap(void *start, size_t length,
621         int prot, int flags, int fd, off_t offset)
623         void *ret = mmap(start, length, prot, flags, fd, offset);
624         if (ret == MAP_FAILED) {
625                 if (!length)
626                         return NULL;
627                 release_pack_memory(length, fd);
628                 ret = mmap(start, length, prot, flags, fd, offset);
629                 if (ret == MAP_FAILED)
630                         die_errno("Out of memory? mmap failed");
631         }
632         return ret;
635 void close_pack_windows(struct packed_git *p)
637         while (p->windows) {
638                 struct pack_window *w = p->windows;
640                 if (w->inuse_cnt)
641                         die("pack '%s' still has open windows to it",
642                             p->pack_name);
643                 munmap(w->base, w->len);
644                 pack_mapped -= w->len;
645                 pack_open_windows--;
646                 p->windows = w->next;
647                 free(w);
648         }
651 void unuse_pack(struct pack_window **w_cursor)
653         struct pack_window *w = *w_cursor;
654         if (w) {
655                 w->inuse_cnt--;
656                 *w_cursor = NULL;
657         }
660 void close_pack_index(struct packed_git *p)
662         if (p->index_data) {
663                 munmap((void *)p->index_data, p->index_size);
664                 p->index_data = NULL;
665         }
668 /*
669  * This is used by git-repack in case a newly created pack happens to
670  * contain the same set of objects as an existing one.  In that case
671  * the resulting file might be different even if its name would be the
672  * same.  It is best to close any reference to the old pack before it is
673  * replaced on disk.  Of course no index pointers nor windows for given pack
674  * must subsist at this point.  If ever objects from this pack are requested
675  * again, the new version of the pack will be reinitialized through
676  * reprepare_packed_git().
677  */
678 void free_pack_by_name(const char *pack_name)
680         struct packed_git *p, **pp = &packed_git;
682         while (*pp) {
683                 p = *pp;
684                 if (strcmp(pack_name, p->pack_name) == 0) {
685                         clear_delta_base_cache();
686                         close_pack_windows(p);
687                         if (p->pack_fd != -1) {
688                                 close(p->pack_fd);
689                                 pack_open_fds--;
690                         }
691                         close_pack_index(p);
692                         free(p->bad_object_sha1);
693                         *pp = p->next;
694                         free(p);
695                         return;
696                 }
697                 pp = &p->next;
698         }
701 /*
702  * Do not call this directly as this leaks p->pack_fd on error return;
703  * call open_packed_git() instead.
704  */
705 static int open_packed_git_1(struct packed_git *p)
707         struct stat st;
708         struct pack_header hdr;
709         unsigned char sha1[20];
710         unsigned char *idx_sha1;
711         long fd_flag;
713         if (!p->index_data && open_pack_index(p))
714                 return error("packfile %s index unavailable", p->pack_name);
716         if (!pack_max_fds) {
717                 struct rlimit lim;
718                 unsigned int max_fds;
720                 if (getrlimit(RLIMIT_NOFILE, &lim))
721                         die_errno("cannot get RLIMIT_NOFILE");
723                 max_fds = lim.rlim_cur;
725                 /* Save 3 for stdin/stdout/stderr, 22 for work */
726                 if (25 < max_fds)
727                         pack_max_fds = max_fds - 25;
728                 else
729                         pack_max_fds = 1;
730         }
732         while (pack_max_fds <= pack_open_fds && unuse_one_window(NULL, -1))
733                 ; /* nothing */
735         p->pack_fd = git_open_noatime(p->pack_name, p);
736         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
737                 return -1;
738         pack_open_fds++;
740         /* If we created the struct before we had the pack we lack size. */
741         if (!p->pack_size) {
742                 if (!S_ISREG(st.st_mode))
743                         return error("packfile %s not a regular file", p->pack_name);
744                 p->pack_size = st.st_size;
745         } else if (p->pack_size != st.st_size)
746                 return error("packfile %s size changed", p->pack_name);
748         /* We leave these file descriptors open with sliding mmap;
749          * there is no point keeping them open across exec(), though.
750          */
751         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
752         if (fd_flag < 0)
753                 return error("cannot determine file descriptor flags");
754         fd_flag |= FD_CLOEXEC;
755         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
756                 return error("cannot set FD_CLOEXEC");
758         /* Verify we recognize this pack file format. */
759         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
760                 return error("file %s is far too short to be a packfile", p->pack_name);
761         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
762                 return error("file %s is not a GIT packfile", p->pack_name);
763         if (!pack_version_ok(hdr.hdr_version))
764                 return error("packfile %s is version %"PRIu32" and not"
765                         " supported (try upgrading GIT to a newer version)",
766                         p->pack_name, ntohl(hdr.hdr_version));
768         /* Verify the pack matches its index. */
769         if (p->num_objects != ntohl(hdr.hdr_entries))
770                 return error("packfile %s claims to have %"PRIu32" objects"
771                              " while index indicates %"PRIu32" objects",
772                              p->pack_name, ntohl(hdr.hdr_entries),
773                              p->num_objects);
774         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
775                 return error("end of packfile %s is unavailable", p->pack_name);
776         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
777                 return error("packfile %s signature is unavailable", p->pack_name);
778         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
779         if (hashcmp(sha1, idx_sha1))
780                 return error("packfile %s does not match index", p->pack_name);
781         return 0;
784 static int open_packed_git(struct packed_git *p)
786         if (!open_packed_git_1(p))
787                 return 0;
788         if (p->pack_fd != -1) {
789                 close(p->pack_fd);
790                 pack_open_fds--;
791                 p->pack_fd = -1;
792         }
793         return -1;
796 static int in_window(struct pack_window *win, off_t offset)
798         /* We must promise at least 20 bytes (one hash) after the
799          * offset is available from this window, otherwise the offset
800          * is not actually in this window and a different window (which
801          * has that one hash excess) must be used.  This is to support
802          * the object header and delta base parsing routines below.
803          */
804         off_t win_off = win->offset;
805         return win_off <= offset
806                 && (offset + 20) <= (win_off + win->len);
809 unsigned char *use_pack(struct packed_git *p,
810                 struct pack_window **w_cursor,
811                 off_t offset,
812                 unsigned int *left)
814         struct pack_window *win = *w_cursor;
816         /* Since packfiles end in a hash of their content and it's
817          * pointless to ask for an offset into the middle of that
818          * hash, and the in_window function above wouldn't match
819          * don't allow an offset too close to the end of the file.
820          */
821         if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
822                 die("packfile %s cannot be accessed", p->pack_name);
823         if (offset > (p->pack_size - 20))
824                 die("offset beyond end of packfile (truncated pack?)");
826         if (!win || !in_window(win, offset)) {
827                 if (win)
828                         win->inuse_cnt--;
829                 for (win = p->windows; win; win = win->next) {
830                         if (in_window(win, offset))
831                                 break;
832                 }
833                 if (!win) {
834                         size_t window_align = packed_git_window_size / 2;
835                         off_t len;
837                         if (p->pack_fd == -1 && open_packed_git(p))
838                                 die("packfile %s cannot be accessed", p->pack_name);
840                         win = xcalloc(1, sizeof(*win));
841                         win->offset = (offset / window_align) * window_align;
842                         len = p->pack_size - win->offset;
843                         if (len > packed_git_window_size)
844                                 len = packed_git_window_size;
845                         win->len = (size_t)len;
846                         pack_mapped += win->len;
847                         while (packed_git_limit < pack_mapped
848                                 && unuse_one_window(p, p->pack_fd))
849                                 ; /* nothing */
850                         win->base = xmmap(NULL, win->len,
851                                 PROT_READ, MAP_PRIVATE,
852                                 p->pack_fd, win->offset);
853                         if (win->base == MAP_FAILED)
854                                 die("packfile %s cannot be mapped: %s",
855                                         p->pack_name,
856                                         strerror(errno));
857                         if (!win->offset && win->len == p->pack_size
858                                 && !p->do_not_close) {
859                                 close(p->pack_fd);
860                                 pack_open_fds--;
861                                 p->pack_fd = -1;
862                         }
863                         pack_mmap_calls++;
864                         pack_open_windows++;
865                         if (pack_mapped > peak_pack_mapped)
866                                 peak_pack_mapped = pack_mapped;
867                         if (pack_open_windows > peak_pack_open_windows)
868                                 peak_pack_open_windows = pack_open_windows;
869                         win->next = p->windows;
870                         p->windows = win;
871                 }
872         }
873         if (win != *w_cursor) {
874                 win->last_used = pack_used_ctr++;
875                 win->inuse_cnt++;
876                 *w_cursor = win;
877         }
878         offset -= win->offset;
879         if (left)
880                 *left = win->len - xsize_t(offset);
881         return win->base + offset;
884 static struct packed_git *alloc_packed_git(int extra)
886         struct packed_git *p = xmalloc(sizeof(*p) + extra);
887         memset(p, 0, sizeof(*p));
888         p->pack_fd = -1;
889         return p;
892 static void try_to_free_pack_memory(size_t size)
894         release_pack_memory(size, -1);
897 struct packed_git *add_packed_git(const char *path, int path_len, int local)
899         static int have_set_try_to_free_routine;
900         struct stat st;
901         struct packed_git *p = alloc_packed_git(path_len + 2);
903         if (!have_set_try_to_free_routine) {
904                 have_set_try_to_free_routine = 1;
905                 set_try_to_free_routine(try_to_free_pack_memory);
906         }
908         /*
909          * Make sure a corresponding .pack file exists and that
910          * the index looks sane.
911          */
912         path_len -= strlen(".idx");
913         if (path_len < 1) {
914                 free(p);
915                 return NULL;
916         }
917         memcpy(p->pack_name, path, path_len);
919         strcpy(p->pack_name + path_len, ".keep");
920         if (!access(p->pack_name, F_OK))
921                 p->pack_keep = 1;
923         strcpy(p->pack_name + path_len, ".pack");
924         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
925                 free(p);
926                 return NULL;
927         }
929         /* ok, it looks sane as far as we can check without
930          * actually mapping the pack file.
931          */
932         p->pack_size = st.st_size;
933         p->pack_local = local;
934         p->mtime = st.st_mtime;
935         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
936                 hashclr(p->sha1);
937         return p;
940 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
942         const char *path = sha1_pack_name(sha1);
943         struct packed_git *p = alloc_packed_git(strlen(path) + 1);
945         strcpy(p->pack_name, path);
946         hashcpy(p->sha1, sha1);
947         if (check_packed_git_idx(idx_path, p)) {
948                 free(p);
949                 return NULL;
950         }
952         return p;
955 void install_packed_git(struct packed_git *pack)
957         if (pack->pack_fd != -1)
958                 pack_open_fds++;
960         pack->next = packed_git;
961         packed_git = pack;
964 static void prepare_packed_git_one(char *objdir, int local)
966         /* Ensure that this buffer is large enough so that we can
967            append "/pack/" without clobbering the stack even if
968            strlen(objdir) were PATH_MAX.  */
969         char path[PATH_MAX + 1 + 4 + 1 + 1];
970         int len;
971         DIR *dir;
972         struct dirent *de;
974         sprintf(path, "%s/pack", objdir);
975         len = strlen(path);
976         dir = opendir(path);
977         if (!dir) {
978                 if (errno != ENOENT)
979                         error("unable to open object pack directory: %s: %s",
980                               path, strerror(errno));
981                 return;
982         }
983         path[len++] = '/';
984         while ((de = readdir(dir)) != NULL) {
985                 int namelen = strlen(de->d_name);
986                 struct packed_git *p;
988                 if (!has_extension(de->d_name, ".idx"))
989                         continue;
991                 if (len + namelen + 1 > sizeof(path))
992                         continue;
994                 /* Don't reopen a pack we already have. */
995                 strcpy(path + len, de->d_name);
996                 for (p = packed_git; p; p = p->next) {
997                         if (!memcmp(path, p->pack_name, len + namelen - 4))
998                                 break;
999                 }
1000                 if (p)
1001                         continue;
1002                 /* See if it really is a valid .idx file with corresponding
1003                  * .pack file that we can map.
1004                  */
1005                 p = add_packed_git(path, len + namelen, local);
1006                 if (!p)
1007                         continue;
1008                 install_packed_git(p);
1009         }
1010         closedir(dir);
1013 static int sort_pack(const void *a_, const void *b_)
1015         struct packed_git *a = *((struct packed_git **)a_);
1016         struct packed_git *b = *((struct packed_git **)b_);
1017         int st;
1019         /*
1020          * Local packs tend to contain objects specific to our
1021          * variant of the project than remote ones.  In addition,
1022          * remote ones could be on a network mounted filesystem.
1023          * Favor local ones for these reasons.
1024          */
1025         st = a->pack_local - b->pack_local;
1026         if (st)
1027                 return -st;
1029         /*
1030          * Younger packs tend to contain more recent objects,
1031          * and more recent objects tend to get accessed more
1032          * often.
1033          */
1034         if (a->mtime < b->mtime)
1035                 return 1;
1036         else if (a->mtime == b->mtime)
1037                 return 0;
1038         return -1;
1041 static void rearrange_packed_git(void)
1043         struct packed_git **ary, *p;
1044         int i, n;
1046         for (n = 0, p = packed_git; p; p = p->next)
1047                 n++;
1048         if (n < 2)
1049                 return;
1051         /* prepare an array of packed_git for easier sorting */
1052         ary = xcalloc(n, sizeof(struct packed_git *));
1053         for (n = 0, p = packed_git; p; p = p->next)
1054                 ary[n++] = p;
1056         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1058         /* link them back again */
1059         for (i = 0; i < n - 1; i++)
1060                 ary[i]->next = ary[i + 1];
1061         ary[n - 1]->next = NULL;
1062         packed_git = ary[0];
1064         free(ary);
1067 static int prepare_packed_git_run_once = 0;
1068 void prepare_packed_git(void)
1070         struct alternate_object_database *alt;
1072         if (prepare_packed_git_run_once)
1073                 return;
1074         prepare_packed_git_one(get_object_directory(), 1);
1075         prepare_alt_odb();
1076         for (alt = alt_odb_list; alt; alt = alt->next) {
1077                 alt->name[-1] = 0;
1078                 prepare_packed_git_one(alt->base, 0);
1079                 alt->name[-1] = '/';
1080         }
1081         rearrange_packed_git();
1082         prepare_packed_git_run_once = 1;
1085 void reprepare_packed_git(void)
1087         discard_revindex();
1088         prepare_packed_git_run_once = 0;
1089         prepare_packed_git();
1092 static void mark_bad_packed_object(struct packed_git *p,
1093                                    const unsigned char *sha1)
1095         unsigned i;
1096         for (i = 0; i < p->num_bad_objects; i++)
1097                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1098                         return;
1099         p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1100         hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1101         p->num_bad_objects++;
1104 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1106         struct packed_git *p;
1107         unsigned i;
1109         for (p = packed_git; p; p = p->next)
1110                 for (i = 0; i < p->num_bad_objects; i++)
1111                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1112                                 return p;
1113         return NULL;
1116 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1118         unsigned char real_sha1[20];
1119         hash_sha1_file(map, size, type, real_sha1);
1120         return hashcmp(sha1, real_sha1) ? -1 : 0;
1123 static int git_open_noatime(const char *name, struct packed_git *p)
1125         static int sha1_file_open_flag = O_NOATIME;
1127         for (;;) {
1128                 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1129                 if (fd >= 0)
1130                         return fd;
1132                 /* Might the failure be due to O_NOATIME? */
1133                 if (errno != ENOENT && sha1_file_open_flag) {
1134                         sha1_file_open_flag = 0;
1135                         continue;
1136                 }
1138                 return -1;
1139         }
1142 static int open_sha1_file(const unsigned char *sha1)
1144         int fd;
1145         char *name = sha1_file_name(sha1);
1146         struct alternate_object_database *alt;
1148         fd = git_open_noatime(name, NULL);
1149         if (fd >= 0)
1150                 return fd;
1152         prepare_alt_odb();
1153         errno = ENOENT;
1154         for (alt = alt_odb_list; alt; alt = alt->next) {
1155                 name = alt->name;
1156                 fill_sha1_path(name, sha1);
1157                 fd = git_open_noatime(alt->base, NULL);
1158                 if (fd >= 0)
1159                         return fd;
1160         }
1161         return -1;
1164 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1166         void *map;
1167         int fd;
1169         fd = open_sha1_file(sha1);
1170         map = NULL;
1171         if (fd >= 0) {
1172                 struct stat st;
1174                 if (!fstat(fd, &st)) {
1175                         *size = xsize_t(st.st_size);
1176                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1177                 }
1178                 close(fd);
1179         }
1180         return map;
1183 static int legacy_loose_object(unsigned char *map)
1185         unsigned int word;
1187         /*
1188          * Is it a zlib-compressed buffer? If so, the first byte
1189          * must be 0x78 (15-bit window size, deflated), and the
1190          * first 16-bit word is evenly divisible by 31
1191          */
1192         word = (map[0] << 8) + map[1];
1193         if (map[0] == 0x78 && !(word % 31))
1194                 return 1;
1195         else
1196                 return 0;
1199 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1200                 unsigned long len, enum object_type *type, unsigned long *sizep)
1202         unsigned shift;
1203         unsigned long size, c;
1204         unsigned long used = 0;
1206         c = buf[used++];
1207         *type = (c >> 4) & 7;
1208         size = c & 15;
1209         shift = 4;
1210         while (c & 0x80) {
1211                 if (len <= used || bitsizeof(long) <= shift) {
1212                         error("bad object header");
1213                         return 0;
1214                 }
1215                 c = buf[used++];
1216                 size += (c & 0x7f) << shift;
1217                 shift += 7;
1218         }
1219         *sizep = size;
1220         return used;
1223 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1225         unsigned long size, used;
1226         static const char valid_loose_object_type[8] = {
1227                 0, /* OBJ_EXT */
1228                 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1229                 0, /* "delta" and others are invalid in a loose object */
1230         };
1231         enum object_type type;
1233         /* Get the data stream */
1234         memset(stream, 0, sizeof(*stream));
1235         stream->next_in = map;
1236         stream->avail_in = mapsize;
1237         stream->next_out = buffer;
1238         stream->avail_out = bufsiz;
1240         if (legacy_loose_object(map)) {
1241                 git_inflate_init(stream);
1242                 return git_inflate(stream, 0);
1243         }
1246         /*
1247          * There used to be a second loose object header format which
1248          * was meant to mimic the in-pack format, allowing for direct
1249          * copy of the object data.  This format turned up not to be
1250          * really worth it and we don't write it any longer.  But we
1251          * can still read it.
1252          */
1253         used = unpack_object_header_buffer(map, mapsize, &type, &size);
1254         if (!used || !valid_loose_object_type[type])
1255                 return -1;
1256         map += used;
1257         mapsize -= used;
1259         /* Set up the stream for the rest.. */
1260         stream->next_in = map;
1261         stream->avail_in = mapsize;
1262         git_inflate_init(stream);
1264         /* And generate the fake traditional header */
1265         stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1266                                          typename(type), size);
1267         return 0;
1270 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1272         int bytes = strlen(buffer) + 1;
1273         unsigned char *buf = xmallocz(size);
1274         unsigned long n;
1275         int status = Z_OK;
1277         n = stream->total_out - bytes;
1278         if (n > size)
1279                 n = size;
1280         memcpy(buf, (char *) buffer + bytes, n);
1281         bytes = n;
1282         if (bytes <= size) {
1283                 /*
1284                  * The above condition must be (bytes <= size), not
1285                  * (bytes < size).  In other words, even though we
1286                  * expect no more output and set avail_out to zer0,
1287                  * the input zlib stream may have bytes that express
1288                  * "this concludes the stream", and we *do* want to
1289                  * eat that input.
1290                  *
1291                  * Otherwise we would not be able to test that we
1292                  * consumed all the input to reach the expected size;
1293                  * we also want to check that zlib tells us that all
1294                  * went well with status == Z_STREAM_END at the end.
1295                  */
1296                 stream->next_out = buf + bytes;
1297                 stream->avail_out = size - bytes;
1298                 while (status == Z_OK)
1299                         status = git_inflate(stream, Z_FINISH);
1300         }
1301         if (status == Z_STREAM_END && !stream->avail_in) {
1302                 git_inflate_end(stream);
1303                 return buf;
1304         }
1306         if (status < 0)
1307                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1308         else if (stream->avail_in)
1309                 error("garbage at end of loose object '%s'",
1310                       sha1_to_hex(sha1));
1311         free(buf);
1312         return NULL;
1315 /*
1316  * We used to just use "sscanf()", but that's actually way
1317  * too permissive for what we want to check. So do an anal
1318  * object header parse by hand.
1319  */
1320 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1322         char type[10];
1323         int i;
1324         unsigned long size;
1326         /*
1327          * The type can be at most ten bytes (including the
1328          * terminating '\0' that we add), and is followed by
1329          * a space.
1330          */
1331         i = 0;
1332         for (;;) {
1333                 char c = *hdr++;
1334                 if (c == ' ')
1335                         break;
1336                 type[i++] = c;
1337                 if (i >= sizeof(type))
1338                         return -1;
1339         }
1340         type[i] = 0;
1342         /*
1343          * The length must follow immediately, and be in canonical
1344          * decimal format (ie "010" is not valid).
1345          */
1346         size = *hdr++ - '0';
1347         if (size > 9)
1348                 return -1;
1349         if (size) {
1350                 for (;;) {
1351                         unsigned long c = *hdr - '0';
1352                         if (c > 9)
1353                                 break;
1354                         hdr++;
1355                         size = size * 10 + c;
1356                 }
1357         }
1358         *sizep = size;
1360         /*
1361          * The length must be followed by a zero byte
1362          */
1363         return *hdr ? -1 : type_from_string(type);
1366 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1368         int ret;
1369         z_stream stream;
1370         char hdr[8192];
1372         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1373         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1374                 return NULL;
1376         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1379 unsigned long get_size_from_delta(struct packed_git *p,
1380                                   struct pack_window **w_curs,
1381                                   off_t curpos)
1383         const unsigned char *data;
1384         unsigned char delta_head[20], *in;
1385         z_stream stream;
1386         int st;
1388         memset(&stream, 0, sizeof(stream));
1389         stream.next_out = delta_head;
1390         stream.avail_out = sizeof(delta_head);
1392         git_inflate_init(&stream);
1393         do {
1394                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1395                 stream.next_in = in;
1396                 st = git_inflate(&stream, Z_FINISH);
1397                 curpos += stream.next_in - in;
1398         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1399                  stream.total_out < sizeof(delta_head));
1400         git_inflate_end(&stream);
1401         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1402                 error("delta data unpack-initial failed");
1403                 return 0;
1404         }
1406         /* Examine the initial part of the delta to figure out
1407          * the result size.
1408          */
1409         data = delta_head;
1411         /* ignore base size */
1412         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1414         /* Read the result size */
1415         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1418 static off_t get_delta_base(struct packed_git *p,
1419                                     struct pack_window **w_curs,
1420                                     off_t *curpos,
1421                                     enum object_type type,
1422                                     off_t delta_obj_offset)
1424         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1425         off_t base_offset;
1427         /* use_pack() assured us we have [base_info, base_info + 20)
1428          * as a range that we can look at without walking off the
1429          * end of the mapped window.  Its actually the hash size
1430          * that is assured.  An OFS_DELTA longer than the hash size
1431          * is stupid, as then a REF_DELTA would be smaller to store.
1432          */
1433         if (type == OBJ_OFS_DELTA) {
1434                 unsigned used = 0;
1435                 unsigned char c = base_info[used++];
1436                 base_offset = c & 127;
1437                 while (c & 128) {
1438                         base_offset += 1;
1439                         if (!base_offset || MSB(base_offset, 7))
1440                                 return 0;  /* overflow */
1441                         c = base_info[used++];
1442                         base_offset = (base_offset << 7) + (c & 127);
1443                 }
1444                 base_offset = delta_obj_offset - base_offset;
1445                 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1446                         return 0;  /* out of bound */
1447                 *curpos += used;
1448         } else if (type == OBJ_REF_DELTA) {
1449                 /* The base entry _must_ be in the same pack */
1450                 base_offset = find_pack_entry_one(base_info, p);
1451                 *curpos += 20;
1452         } else
1453                 die("I am totally screwed");
1454         return base_offset;
1457 /* forward declaration for a mutually recursive function */
1458 static int packed_object_info(struct packed_git *p, off_t offset,
1459                               unsigned long *sizep);
1461 static int packed_delta_info(struct packed_git *p,
1462                              struct pack_window **w_curs,
1463                              off_t curpos,
1464                              enum object_type type,
1465                              off_t obj_offset,
1466                              unsigned long *sizep)
1468         off_t base_offset;
1470         base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1471         if (!base_offset)
1472                 return OBJ_BAD;
1473         type = packed_object_info(p, base_offset, NULL);
1474         if (type <= OBJ_NONE) {
1475                 struct revindex_entry *revidx;
1476                 const unsigned char *base_sha1;
1477                 revidx = find_pack_revindex(p, base_offset);
1478                 if (!revidx)
1479                         return OBJ_BAD;
1480                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1481                 mark_bad_packed_object(p, base_sha1);
1482                 type = sha1_object_info(base_sha1, NULL);
1483                 if (type <= OBJ_NONE)
1484                         return OBJ_BAD;
1485         }
1487         /* We choose to only get the type of the base object and
1488          * ignore potentially corrupt pack file that expects the delta
1489          * based on a base with a wrong size.  This saves tons of
1490          * inflate() calls.
1491          */
1492         if (sizep) {
1493                 *sizep = get_size_from_delta(p, w_curs, curpos);
1494                 if (*sizep == 0)
1495                         type = OBJ_BAD;
1496         }
1498         return type;
1501 static int unpack_object_header(struct packed_git *p,
1502                                 struct pack_window **w_curs,
1503                                 off_t *curpos,
1504                                 unsigned long *sizep)
1506         unsigned char *base;
1507         unsigned int left;
1508         unsigned long used;
1509         enum object_type type;
1511         /* use_pack() assures us we have [base, base + 20) available
1512          * as a range that we can look at at.  (Its actually the hash
1513          * size that is assured.)  With our object header encoding
1514          * the maximum deflated object size is 2^137, which is just
1515          * insane, so we know won't exceed what we have been given.
1516          */
1517         base = use_pack(p, w_curs, *curpos, &left);
1518         used = unpack_object_header_buffer(base, left, &type, sizep);
1519         if (!used) {
1520                 type = OBJ_BAD;
1521         } else
1522                 *curpos += used;
1524         return type;
1527 const char *packed_object_info_detail(struct packed_git *p,
1528                                       off_t obj_offset,
1529                                       unsigned long *size,
1530                                       unsigned long *store_size,
1531                                       unsigned int *delta_chain_length,
1532                                       unsigned char *base_sha1)
1534         struct pack_window *w_curs = NULL;
1535         off_t curpos;
1536         unsigned long dummy;
1537         unsigned char *next_sha1;
1538         enum object_type type;
1539         struct revindex_entry *revidx;
1541         *delta_chain_length = 0;
1542         curpos = obj_offset;
1543         type = unpack_object_header(p, &w_curs, &curpos, size);
1545         revidx = find_pack_revindex(p, obj_offset);
1546         *store_size = revidx[1].offset - obj_offset;
1548         for (;;) {
1549                 switch (type) {
1550                 default:
1551                         die("pack %s contains unknown object type %d",
1552                             p->pack_name, type);
1553                 case OBJ_COMMIT:
1554                 case OBJ_TREE:
1555                 case OBJ_BLOB:
1556                 case OBJ_TAG:
1557                         unuse_pack(&w_curs);
1558                         return typename(type);
1559                 case OBJ_OFS_DELTA:
1560                         obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1561                         if (!obj_offset)
1562                                 die("pack %s contains bad delta base reference of type %s",
1563                                     p->pack_name, typename(type));
1564                         if (*delta_chain_length == 0) {
1565                                 revidx = find_pack_revindex(p, obj_offset);
1566                                 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1567                         }
1568                         break;
1569                 case OBJ_REF_DELTA:
1570                         next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1571                         if (*delta_chain_length == 0)
1572                                 hashcpy(base_sha1, next_sha1);
1573                         obj_offset = find_pack_entry_one(next_sha1, p);
1574                         break;
1575                 }
1576                 (*delta_chain_length)++;
1577                 curpos = obj_offset;
1578                 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1579         }
1582 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1583                               unsigned long *sizep)
1585         struct pack_window *w_curs = NULL;
1586         unsigned long size;
1587         off_t curpos = obj_offset;
1588         enum object_type type;
1590         type = unpack_object_header(p, &w_curs, &curpos, &size);
1592         switch (type) {
1593         case OBJ_OFS_DELTA:
1594         case OBJ_REF_DELTA:
1595                 type = packed_delta_info(p, &w_curs, curpos,
1596                                          type, obj_offset, sizep);
1597                 break;
1598         case OBJ_COMMIT:
1599         case OBJ_TREE:
1600         case OBJ_BLOB:
1601         case OBJ_TAG:
1602                 if (sizep)
1603                         *sizep = size;
1604                 break;
1605         default:
1606                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1607                       type, (uintmax_t)obj_offset, p->pack_name);
1608                 type = OBJ_BAD;
1609         }
1610         unuse_pack(&w_curs);
1611         return type;
1614 static void *unpack_compressed_entry(struct packed_git *p,
1615                                     struct pack_window **w_curs,
1616                                     off_t curpos,
1617                                     unsigned long size)
1619         int st;
1620         z_stream stream;
1621         unsigned char *buffer, *in;
1623         buffer = xmallocz(size);
1624         memset(&stream, 0, sizeof(stream));
1625         stream.next_out = buffer;
1626         stream.avail_out = size + 1;
1628         git_inflate_init(&stream);
1629         do {
1630                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1631                 stream.next_in = in;
1632                 st = git_inflate(&stream, Z_FINISH);
1633                 if (!stream.avail_out)
1634                         break; /* the payload is larger than it should be */
1635                 curpos += stream.next_in - in;
1636         } while (st == Z_OK || st == Z_BUF_ERROR);
1637         git_inflate_end(&stream);
1638         if ((st != Z_STREAM_END) || stream.total_out != size) {
1639                 free(buffer);
1640                 return NULL;
1641         }
1643         return buffer;
1646 #define MAX_DELTA_CACHE (256)
1648 static size_t delta_base_cached;
1650 static struct delta_base_cache_lru_list {
1651         struct delta_base_cache_lru_list *prev;
1652         struct delta_base_cache_lru_list *next;
1653 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1655 static struct delta_base_cache_entry {
1656         struct delta_base_cache_lru_list lru;
1657         void *data;
1658         struct packed_git *p;
1659         off_t base_offset;
1660         unsigned long size;
1661         enum object_type type;
1662 } delta_base_cache[MAX_DELTA_CACHE];
1664 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1666         unsigned long hash;
1668         hash = (unsigned long)p + (unsigned long)base_offset;
1669         hash += (hash >> 8) + (hash >> 16);
1670         return hash % MAX_DELTA_CACHE;
1673 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1674         unsigned long *base_size, enum object_type *type, int keep_cache)
1676         void *ret;
1677         unsigned long hash = pack_entry_hash(p, base_offset);
1678         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1680         ret = ent->data;
1681         if (!ret || ent->p != p || ent->base_offset != base_offset)
1682                 return unpack_entry(p, base_offset, type, base_size);
1684         if (!keep_cache) {
1685                 ent->data = NULL;
1686                 ent->lru.next->prev = ent->lru.prev;
1687                 ent->lru.prev->next = ent->lru.next;
1688                 delta_base_cached -= ent->size;
1689         } else {
1690                 ret = xmemdupz(ent->data, ent->size);
1691         }
1692         *type = ent->type;
1693         *base_size = ent->size;
1694         return ret;
1697 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1699         if (ent->data) {
1700                 free(ent->data);
1701                 ent->data = NULL;
1702                 ent->lru.next->prev = ent->lru.prev;
1703                 ent->lru.prev->next = ent->lru.next;
1704                 delta_base_cached -= ent->size;
1705         }
1708 void clear_delta_base_cache(void)
1710         unsigned long p;
1711         for (p = 0; p < MAX_DELTA_CACHE; p++)
1712                 release_delta_base_cache(&delta_base_cache[p]);
1715 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1716         void *base, unsigned long base_size, enum object_type type)
1718         unsigned long hash = pack_entry_hash(p, base_offset);
1719         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1720         struct delta_base_cache_lru_list *lru;
1722         release_delta_base_cache(ent);
1723         delta_base_cached += base_size;
1725         for (lru = delta_base_cache_lru.next;
1726              delta_base_cached > delta_base_cache_limit
1727              && lru != &delta_base_cache_lru;
1728              lru = lru->next) {
1729                 struct delta_base_cache_entry *f = (void *)lru;
1730                 if (f->type == OBJ_BLOB)
1731                         release_delta_base_cache(f);
1732         }
1733         for (lru = delta_base_cache_lru.next;
1734              delta_base_cached > delta_base_cache_limit
1735              && lru != &delta_base_cache_lru;
1736              lru = lru->next) {
1737                 struct delta_base_cache_entry *f = (void *)lru;
1738                 release_delta_base_cache(f);
1739         }
1741         ent->p = p;
1742         ent->base_offset = base_offset;
1743         ent->type = type;
1744         ent->data = base;
1745         ent->size = base_size;
1746         ent->lru.next = &delta_base_cache_lru;
1747         ent->lru.prev = delta_base_cache_lru.prev;
1748         delta_base_cache_lru.prev->next = &ent->lru;
1749         delta_base_cache_lru.prev = &ent->lru;
1752 static void *read_object(const unsigned char *sha1, enum object_type *type,
1753                          unsigned long *size);
1755 static void *unpack_delta_entry(struct packed_git *p,
1756                                 struct pack_window **w_curs,
1757                                 off_t curpos,
1758                                 unsigned long delta_size,
1759                                 off_t obj_offset,
1760                                 enum object_type *type,
1761                                 unsigned long *sizep)
1763         void *delta_data, *result, *base;
1764         unsigned long base_size;
1765         off_t base_offset;
1767         base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1768         if (!base_offset) {
1769                 error("failed to validate delta base reference "
1770                       "at offset %"PRIuMAX" from %s",
1771                       (uintmax_t)curpos, p->pack_name);
1772                 return NULL;
1773         }
1774         unuse_pack(w_curs);
1775         base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1776         if (!base) {
1777                 /*
1778                  * We're probably in deep shit, but let's try to fetch
1779                  * the required base anyway from another pack or loose.
1780                  * This is costly but should happen only in the presence
1781                  * of a corrupted pack, and is better than failing outright.
1782                  */
1783                 struct revindex_entry *revidx;
1784                 const unsigned char *base_sha1;
1785                 revidx = find_pack_revindex(p, base_offset);
1786                 if (!revidx)
1787                         return NULL;
1788                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
1789                 error("failed to read delta base object %s"
1790                       " at offset %"PRIuMAX" from %s",
1791                       sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1792                       p->pack_name);
1793                 mark_bad_packed_object(p, base_sha1);
1794                 base = read_object(base_sha1, type, &base_size);
1795                 if (!base)
1796                         return NULL;
1797         }
1799         delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1800         if (!delta_data) {
1801                 error("failed to unpack compressed delta "
1802                       "at offset %"PRIuMAX" from %s",
1803                       (uintmax_t)curpos, p->pack_name);
1804                 free(base);
1805                 return NULL;
1806         }
1807         result = patch_delta(base, base_size,
1808                              delta_data, delta_size,
1809                              sizep);
1810         if (!result)
1811                 die("failed to apply delta");
1812         free(delta_data);
1813         add_delta_base_cache(p, base_offset, base, base_size, *type);
1814         return result;
1817 int do_check_packed_object_crc;
1819 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1820                    enum object_type *type, unsigned long *sizep)
1822         struct pack_window *w_curs = NULL;
1823         off_t curpos = obj_offset;
1824         void *data;
1826         if (do_check_packed_object_crc && p->index_version > 1) {
1827                 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1828                 unsigned long len = revidx[1].offset - obj_offset;
1829                 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1830                         const unsigned char *sha1 =
1831                                 nth_packed_object_sha1(p, revidx->nr);
1832                         error("bad packed object CRC for %s",
1833                               sha1_to_hex(sha1));
1834                         mark_bad_packed_object(p, sha1);
1835                         unuse_pack(&w_curs);
1836                         return NULL;
1837                 }
1838         }
1840         *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1841         switch (*type) {
1842         case OBJ_OFS_DELTA:
1843         case OBJ_REF_DELTA:
1844                 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1845                                           obj_offset, type, sizep);
1846                 break;
1847         case OBJ_COMMIT:
1848         case OBJ_TREE:
1849         case OBJ_BLOB:
1850         case OBJ_TAG:
1851                 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1852                 break;
1853         default:
1854                 data = NULL;
1855                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1856                       *type, (uintmax_t)obj_offset, p->pack_name);
1857         }
1858         unuse_pack(&w_curs);
1859         return data;
1862 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1863                                             uint32_t n)
1865         const unsigned char *index = p->index_data;
1866         if (!index) {
1867                 if (open_pack_index(p))
1868                         return NULL;
1869                 index = p->index_data;
1870         }
1871         if (n >= p->num_objects)
1872                 return NULL;
1873         index += 4 * 256;
1874         if (p->index_version == 1) {
1875                 return index + 24 * n + 4;
1876         } else {
1877                 index += 8;
1878                 return index + 20 * n;
1879         }
1882 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1884         const unsigned char *index = p->index_data;
1885         index += 4 * 256;
1886         if (p->index_version == 1) {
1887                 return ntohl(*((uint32_t *)(index + 24 * n)));
1888         } else {
1889                 uint32_t off;
1890                 index += 8 + p->num_objects * (20 + 4);
1891                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1892                 if (!(off & 0x80000000))
1893                         return off;
1894                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1895                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1896                                    ntohl(*((uint32_t *)(index + 4)));
1897         }
1900 off_t find_pack_entry_one(const unsigned char *sha1,
1901                                   struct packed_git *p)
1903         const uint32_t *level1_ofs = p->index_data;
1904         const unsigned char *index = p->index_data;
1905         unsigned hi, lo, stride;
1906         static int use_lookup = -1;
1907         static int debug_lookup = -1;
1909         if (debug_lookup < 0)
1910                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1912         if (!index) {
1913                 if (open_pack_index(p))
1914                         return 0;
1915                 level1_ofs = p->index_data;
1916                 index = p->index_data;
1917         }
1918         if (p->index_version > 1) {
1919                 level1_ofs += 2;
1920                 index += 8;
1921         }
1922         index += 4 * 256;
1923         hi = ntohl(level1_ofs[*sha1]);
1924         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1925         if (p->index_version > 1) {
1926                 stride = 20;
1927         } else {
1928                 stride = 24;
1929                 index += 4;
1930         }
1932         if (debug_lookup)
1933                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1934                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1936         if (use_lookup < 0)
1937                 use_lookup = !!getenv("GIT_USE_LOOKUP");
1938         if (use_lookup) {
1939                 int pos = sha1_entry_pos(index, stride, 0,
1940                                          lo, hi, p->num_objects, sha1);
1941                 if (pos < 0)
1942                         return 0;
1943                 return nth_packed_object_offset(p, pos);
1944         }
1946         do {
1947                 unsigned mi = (lo + hi) / 2;
1948                 int cmp = hashcmp(index + mi * stride, sha1);
1950                 if (debug_lookup)
1951                         printf("lo %u hi %u rg %u mi %u\n",
1952                                lo, hi, hi - lo, mi);
1953                 if (!cmp)
1954                         return nth_packed_object_offset(p, mi);
1955                 if (cmp > 0)
1956                         hi = mi;
1957                 else
1958                         lo = mi+1;
1959         } while (lo < hi);
1960         return 0;
1963 static int is_pack_valid(struct packed_git *p)
1965         /* An already open pack is known to be valid. */
1966         if (p->pack_fd != -1)
1967                 return 1;
1969         /* If the pack has one window completely covering the
1970          * file size, the pack is known to be valid even if
1971          * the descriptor is not currently open.
1972          */
1973         if (p->windows) {
1974                 struct pack_window *w = p->windows;
1976                 if (!w->offset && w->len == p->pack_size)
1977                         return 1;
1978         }
1980         /* Force the pack to open to prove its valid. */
1981         return !open_packed_git(p);
1984 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1986         static struct packed_git *last_found = (void *)1;
1987         struct packed_git *p;
1988         off_t offset;
1990         prepare_packed_git();
1991         if (!packed_git)
1992                 return 0;
1993         p = (last_found == (void *)1) ? packed_git : last_found;
1995         do {
1996                 if (p->num_bad_objects) {
1997                         unsigned i;
1998                         for (i = 0; i < p->num_bad_objects; i++)
1999                                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2000                                         goto next;
2001                 }
2003                 offset = find_pack_entry_one(sha1, p);
2004                 if (offset) {
2005                         /*
2006                          * We are about to tell the caller where they can
2007                          * locate the requested object.  We better make
2008                          * sure the packfile is still here and can be
2009                          * accessed before supplying that answer, as
2010                          * it may have been deleted since the index
2011                          * was loaded!
2012                          */
2013                         if (!is_pack_valid(p)) {
2014                                 error("packfile %s cannot be accessed", p->pack_name);
2015                                 goto next;
2016                         }
2017                         e->offset = offset;
2018                         e->p = p;
2019                         hashcpy(e->sha1, sha1);
2020                         last_found = p;
2021                         return 1;
2022                 }
2024                 next:
2025                 if (p == last_found)
2026                         p = packed_git;
2027                 else
2028                         p = p->next;
2029                 if (p == last_found)
2030                         p = p->next;
2031         } while (p);
2032         return 0;
2035 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2036                                   struct packed_git *packs)
2038         struct packed_git *p;
2040         for (p = packs; p; p = p->next) {
2041                 if (find_pack_entry_one(sha1, p))
2042                         return p;
2043         }
2044         return NULL;
2048 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
2050         int status;
2051         unsigned long mapsize, size;
2052         void *map;
2053         z_stream stream;
2054         char hdr[32];
2056         map = map_sha1_file(sha1, &mapsize);
2057         if (!map)
2058                 return error("unable to find %s", sha1_to_hex(sha1));
2059         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2060                 status = error("unable to unpack %s header",
2061                                sha1_to_hex(sha1));
2062         else if ((status = parse_sha1_header(hdr, &size)) < 0)
2063                 status = error("unable to parse %s header", sha1_to_hex(sha1));
2064         else if (sizep)
2065                 *sizep = size;
2066         git_inflate_end(&stream);
2067         munmap(map, mapsize);
2068         return status;
2071 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2073         struct cached_object *co;
2074         struct pack_entry e;
2075         int status;
2077         co = find_cached_object(sha1);
2078         if (co) {
2079                 if (sizep)
2080                         *sizep = co->size;
2081                 return co->type;
2082         }
2084         if (!find_pack_entry(sha1, &e)) {
2085                 /* Most likely it's a loose object. */
2086                 status = sha1_loose_object_info(sha1, sizep);
2087                 if (status >= 0)
2088                         return status;
2090                 /* Not a loose object; someone else may have just packed it. */
2091                 reprepare_packed_git();
2092                 if (!find_pack_entry(sha1, &e))
2093                         return status;
2094         }
2096         status = packed_object_info(e.p, e.offset, sizep);
2097         if (status < 0) {
2098                 mark_bad_packed_object(e.p, sha1);
2099                 status = sha1_object_info(sha1, sizep);
2100         }
2102         return status;
2105 static void *read_packed_sha1(const unsigned char *sha1,
2106                               enum object_type *type, unsigned long *size)
2108         struct pack_entry e;
2109         void *data;
2111         if (!find_pack_entry(sha1, &e))
2112                 return NULL;
2113         data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2114         if (!data) {
2115                 /*
2116                  * We're probably in deep shit, but let's try to fetch
2117                  * the required object anyway from another pack or loose.
2118                  * This should happen only in the presence of a corrupted
2119                  * pack, and is better than failing outright.
2120                  */
2121                 error("failed to read object %s at offset %"PRIuMAX" from %s",
2122                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2123                 mark_bad_packed_object(e.p, sha1);
2124                 data = read_object(sha1, type, size);
2125         }
2126         return data;
2129 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2130                       unsigned char *sha1)
2132         struct cached_object *co;
2134         hash_sha1_file(buf, len, typename(type), sha1);
2135         if (has_sha1_file(sha1) || find_cached_object(sha1))
2136                 return 0;
2137         if (cached_object_alloc <= cached_object_nr) {
2138                 cached_object_alloc = alloc_nr(cached_object_alloc);
2139                 cached_objects = xrealloc(cached_objects,
2140                                           sizeof(*cached_objects) *
2141                                           cached_object_alloc);
2142         }
2143         co = &cached_objects[cached_object_nr++];
2144         co->size = len;
2145         co->type = type;
2146         co->buf = xmalloc(len);
2147         memcpy(co->buf, buf, len);
2148         hashcpy(co->sha1, sha1);
2149         return 0;
2152 static void *read_object(const unsigned char *sha1, enum object_type *type,
2153                          unsigned long *size)
2155         unsigned long mapsize;
2156         void *map, *buf;
2157         struct cached_object *co;
2159         co = find_cached_object(sha1);
2160         if (co) {
2161                 *type = co->type;
2162                 *size = co->size;
2163                 return xmemdupz(co->buf, co->size);
2164         }
2166         buf = read_packed_sha1(sha1, type, size);
2167         if (buf)
2168                 return buf;
2169         map = map_sha1_file(sha1, &mapsize);
2170         if (map) {
2171                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2172                 munmap(map, mapsize);
2173                 return buf;
2174         }
2175         reprepare_packed_git();
2176         return read_packed_sha1(sha1, type, size);
2179 /*
2180  * This function dies on corrupt objects; the callers who want to
2181  * deal with them should arrange to call read_object() and give error
2182  * messages themselves.
2183  */
2184 void *read_sha1_file_repl(const unsigned char *sha1,
2185                           enum object_type *type,
2186                           unsigned long *size,
2187                           const unsigned char **replacement)
2189         const unsigned char *repl = lookup_replace_object(sha1);
2190         void *data;
2191         char *path;
2192         const struct packed_git *p;
2194         errno = 0;
2195         data = read_object(repl, type, size);
2196         if (data) {
2197                 if (replacement)
2198                         *replacement = repl;
2199                 return data;
2200         }
2202         if (errno && errno != ENOENT)
2203                 die_errno("failed to read object %s", sha1_to_hex(sha1));
2205         /* die if we replaced an object with one that does not exist */
2206         if (repl != sha1)
2207                 die("replacement %s not found for %s",
2208                     sha1_to_hex(repl), sha1_to_hex(sha1));
2210         if (has_loose_object(repl)) {
2211                 path = sha1_file_name(sha1);
2212                 die("loose object %s (stored in %s) is corrupt",
2213                     sha1_to_hex(repl), path);
2214         }
2216         if ((p = has_packed_and_bad(repl)) != NULL)
2217                 die("packed object %s (stored in %s) is corrupt",
2218                     sha1_to_hex(repl), p->pack_name);
2220         return NULL;
2223 void *read_object_with_reference(const unsigned char *sha1,
2224                                  const char *required_type_name,
2225                                  unsigned long *size,
2226                                  unsigned char *actual_sha1_return)
2228         enum object_type type, required_type;
2229         void *buffer;
2230         unsigned long isize;
2231         unsigned char actual_sha1[20];
2233         required_type = type_from_string(required_type_name);
2234         hashcpy(actual_sha1, sha1);
2235         while (1) {
2236                 int ref_length = -1;
2237                 const char *ref_type = NULL;
2239                 buffer = read_sha1_file(actual_sha1, &type, &isize);
2240                 if (!buffer)
2241                         return NULL;
2242                 if (type == required_type) {
2243                         *size = isize;
2244                         if (actual_sha1_return)
2245                                 hashcpy(actual_sha1_return, actual_sha1);
2246                         return buffer;
2247                 }
2248                 /* Handle references */
2249                 else if (type == OBJ_COMMIT)
2250                         ref_type = "tree ";
2251                 else if (type == OBJ_TAG)
2252                         ref_type = "object ";
2253                 else {
2254                         free(buffer);
2255                         return NULL;
2256                 }
2257                 ref_length = strlen(ref_type);
2259                 if (ref_length + 40 > isize ||
2260                     memcmp(buffer, ref_type, ref_length) ||
2261                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2262                         free(buffer);
2263                         return NULL;
2264                 }
2265                 free(buffer);
2266                 /* Now we have the ID of the referred-to object in
2267                  * actual_sha1.  Check again. */
2268         }
2271 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2272                                     const char *type, unsigned char *sha1,
2273                                     char *hdr, int *hdrlen)
2275         git_SHA_CTX c;
2277         /* Generate the header */
2278         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2280         /* Sha1.. */
2281         git_SHA1_Init(&c);
2282         git_SHA1_Update(&c, hdr, *hdrlen);
2283         git_SHA1_Update(&c, buf, len);
2284         git_SHA1_Final(sha1, &c);
2287 /*
2288  * Move the just written object into its final resting place.
2289  * NEEDSWORK: this should be renamed to finalize_temp_file() as
2290  * "moving" is only a part of what it does, when no patch between
2291  * master to pu changes the call sites of this function.
2292  */
2293 int move_temp_to_file(const char *tmpfile, const char *filename)
2295         int ret = 0;
2297         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2298                 goto try_rename;
2299         else if (link(tmpfile, filename))
2300                 ret = errno;
2302         /*
2303          * Coda hack - coda doesn't like cross-directory links,
2304          * so we fall back to a rename, which will mean that it
2305          * won't be able to check collisions, but that's not a
2306          * big deal.
2307          *
2308          * The same holds for FAT formatted media.
2309          *
2310          * When this succeeds, we just return.  We have nothing
2311          * left to unlink.
2312          */
2313         if (ret && ret != EEXIST) {
2314         try_rename:
2315                 if (!rename(tmpfile, filename))
2316                         goto out;
2317                 ret = errno;
2318         }
2319         unlink_or_warn(tmpfile);
2320         if (ret) {
2321                 if (ret != EEXIST) {
2322                         return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2323                 }
2324                 /* FIXME!!! Collision check here ? */
2325         }
2327 out:
2328         if (adjust_shared_perm(filename))
2329                 return error("unable to set permission to '%s'", filename);
2330         return 0;
2333 static int write_buffer(int fd, const void *buf, size_t len)
2335         if (write_in_full(fd, buf, len) < 0)
2336                 return error("file write error (%s)", strerror(errno));
2337         return 0;
2340 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2341                    unsigned char *sha1)
2343         char hdr[32];
2344         int hdrlen;
2345         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2346         return 0;
2349 /* Finalize a file on disk, and close it. */
2350 static void close_sha1_file(int fd)
2352         if (fsync_object_files)
2353                 fsync_or_die(fd, "sha1 file");
2354         if (close(fd) != 0)
2355                 die_errno("error when closing sha1 file");
2358 /* Size of directory component, including the ending '/' */
2359 static inline int directory_size(const char *filename)
2361         const char *s = strrchr(filename, '/');
2362         if (!s)
2363                 return 0;
2364         return s - filename + 1;
2367 /*
2368  * This creates a temporary file in the same directory as the final
2369  * 'filename'
2370  *
2371  * We want to avoid cross-directory filename renames, because those
2372  * can have problems on various filesystems (FAT, NFS, Coda).
2373  */
2374 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2376         int fd, dirlen = directory_size(filename);
2378         if (dirlen + 20 > bufsiz) {
2379                 errno = ENAMETOOLONG;
2380                 return -1;
2381         }
2382         memcpy(buffer, filename, dirlen);
2383         strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2384         fd = git_mkstemp_mode(buffer, 0444);
2385         if (fd < 0 && dirlen && errno == ENOENT) {
2386                 /* Make sure the directory exists */
2387                 memcpy(buffer, filename, dirlen);
2388                 buffer[dirlen-1] = 0;
2389                 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2390                         return -1;
2392                 /* Try again */
2393                 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2394                 fd = git_mkstemp_mode(buffer, 0444);
2395         }
2396         return fd;
2399 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2400                               const void *buf, unsigned long len, time_t mtime)
2402         int fd, ret;
2403         unsigned char compressed[4096];
2404         z_stream stream;
2405         git_SHA_CTX c;
2406         unsigned char parano_sha1[20];
2407         char *filename;
2408         static char tmpfile[PATH_MAX];
2410         filename = sha1_file_name(sha1);
2411         fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2412         if (fd < 0) {
2413                 if (errno == EACCES)
2414                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2415                 else
2416                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2417         }
2419         /* Set it up */
2420         memset(&stream, 0, sizeof(stream));
2421         deflateInit(&stream, zlib_compression_level);
2422         stream.next_out = compressed;
2423         stream.avail_out = sizeof(compressed);
2424         git_SHA1_Init(&c);
2426         /* First header.. */
2427         stream.next_in = (unsigned char *)hdr;
2428         stream.avail_in = hdrlen;
2429         while (deflate(&stream, 0) == Z_OK)
2430                 /* nothing */;
2431         git_SHA1_Update(&c, hdr, hdrlen);
2433         /* Then the data itself.. */
2434         stream.next_in = (void *)buf;
2435         stream.avail_in = len;
2436         do {
2437                 unsigned char *in0 = stream.next_in;
2438                 ret = deflate(&stream, Z_FINISH);
2439                 git_SHA1_Update(&c, in0, stream.next_in - in0);
2440                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2441                         die("unable to write sha1 file");
2442                 stream.next_out = compressed;
2443                 stream.avail_out = sizeof(compressed);
2444         } while (ret == Z_OK);
2446         if (ret != Z_STREAM_END)
2447                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2448         ret = deflateEnd(&stream);
2449         if (ret != Z_OK)
2450                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2451         git_SHA1_Final(parano_sha1, &c);
2452         if (hashcmp(sha1, parano_sha1) != 0)
2453                 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2455         close_sha1_file(fd);
2457         if (mtime) {
2458                 struct utimbuf utb;
2459                 utb.actime = mtime;
2460                 utb.modtime = mtime;
2461                 if (utime(tmpfile, &utb) < 0)
2462                         warning("failed utime() on %s: %s",
2463                                 tmpfile, strerror(errno));
2464         }
2466         return move_temp_to_file(tmpfile, filename);
2469 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2471         unsigned char sha1[20];
2472         char hdr[32];
2473         int hdrlen;
2475         /* Normally if we have it in the pack then we do not bother writing
2476          * it out into .git/objects/??/?{38} file.
2477          */
2478         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2479         if (returnsha1)
2480                 hashcpy(returnsha1, sha1);
2481         if (has_sha1_file(sha1))
2482                 return 0;
2483         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2486 int force_object_loose(const unsigned char *sha1, time_t mtime)
2488         void *buf;
2489         unsigned long len;
2490         enum object_type type;
2491         char hdr[32];
2492         int hdrlen;
2493         int ret;
2495         if (has_loose_object(sha1))
2496                 return 0;
2497         buf = read_packed_sha1(sha1, &type, &len);
2498         if (!buf)
2499                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2500         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2501         ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2502         free(buf);
2504         return ret;
2507 int has_pack_index(const unsigned char *sha1)
2509         struct stat st;
2510         if (stat(sha1_pack_index_name(sha1), &st))
2511                 return 0;
2512         return 1;
2515 int has_sha1_pack(const unsigned char *sha1)
2517         struct pack_entry e;
2518         return find_pack_entry(sha1, &e);
2521 int has_sha1_file(const unsigned char *sha1)
2523         struct pack_entry e;
2525         if (find_pack_entry(sha1, &e))
2526                 return 1;
2527         return has_loose_object(sha1);
2530 static int index_mem(unsigned char *sha1, void *buf, size_t size,
2531                      int write_object, enum object_type type, const char *path)
2533         int ret, re_allocated = 0;
2535         if (!type)
2536                 type = OBJ_BLOB;
2538         /*
2539          * Convert blobs to git internal format
2540          */
2541         if ((type == OBJ_BLOB) && path) {
2542                 struct strbuf nbuf = STRBUF_INIT;
2543                 if (convert_to_git(path, buf, size, &nbuf,
2544                                    write_object ? safe_crlf : 0)) {
2545                         buf = strbuf_detach(&nbuf, &size);
2546                         re_allocated = 1;
2547                 }
2548         }
2550         if (write_object)
2551                 ret = write_sha1_file(buf, size, typename(type), sha1);
2552         else
2553                 ret = hash_sha1_file(buf, size, typename(type), sha1);
2554         if (re_allocated)
2555                 free(buf);
2556         return ret;
2559 #define SMALL_FILE_SIZE (32*1024)
2561 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2562              enum object_type type, const char *path)
2564         int ret;
2565         size_t size = xsize_t(st->st_size);
2567         if (!S_ISREG(st->st_mode)) {
2568                 struct strbuf sbuf = STRBUF_INIT;
2569                 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2570                         ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object,
2571                                         type, path);
2572                 else
2573                         ret = -1;
2574                 strbuf_release(&sbuf);
2575         } else if (!size) {
2576                 ret = index_mem(sha1, NULL, size, write_object, type, path);
2577         } else if (size <= SMALL_FILE_SIZE) {
2578                 char *buf = xmalloc(size);
2579                 if (size == read_in_full(fd, buf, size))
2580                         ret = index_mem(sha1, buf, size, write_object, type,
2581                                         path);
2582                 else
2583                         ret = error("short read %s", strerror(errno));
2584                 free(buf);
2585         } else {
2586                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2587                 ret = index_mem(sha1, buf, size, write_object, type, path);
2588                 munmap(buf, size);
2589         }
2590         close(fd);
2591         return ret;
2594 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2596         int fd;
2597         struct strbuf sb = STRBUF_INIT;
2599         switch (st->st_mode & S_IFMT) {
2600         case S_IFREG:
2601                 fd = open(path, O_RDONLY);
2602                 if (fd < 0)
2603                         return error("open(\"%s\"): %s", path,
2604                                      strerror(errno));
2605                 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2606                         return error("%s: failed to insert into database",
2607                                      path);
2608                 break;
2609         case S_IFLNK:
2610                 if (strbuf_readlink(&sb, path, st->st_size)) {
2611                         char *errstr = strerror(errno);
2612                         return error("readlink(\"%s\"): %s", path,
2613                                      errstr);
2614                 }
2615                 if (!write_object)
2616                         hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
2617                 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
2618                         return error("%s: failed to insert into database",
2619                                      path);
2620                 strbuf_release(&sb);
2621                 break;
2622         case S_IFDIR:
2623                 return resolve_gitlink_ref(path, "HEAD", sha1);
2624         default:
2625                 return error("%s: unsupported file type", path);
2626         }
2627         return 0;
2630 int read_pack_header(int fd, struct pack_header *header)
2632         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2633                 /* "eof before pack header was fully read" */
2634                 return PH_ERROR_EOF;
2636         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2637                 /* "protocol error (pack signature mismatch detected)" */
2638                 return PH_ERROR_PACK_SIGNATURE;
2639         if (!pack_version_ok(header->hdr_version))
2640                 /* "protocol error (pack version unsupported)" */
2641                 return PH_ERROR_PROTOCOL;
2642         return 0;
2645 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
2647         enum object_type type = sha1_object_info(sha1, NULL);
2648         if (type < 0)
2649                 die("%s is not a valid object", sha1_to_hex(sha1));
2650         if (type != expect)
2651                 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
2652                     typename(expect));