Code

f963c3cadbb45b47310818eb63df292d91d8dca1
[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"
19 #include "diff.h"
20 #include "revision.h"
22 #ifndef O_NOATIME
23 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
24 #define O_NOATIME 01000000
25 #else
26 #define O_NOATIME 0
27 #endif
28 #endif
30 #ifdef NO_C99_FORMAT
31 #define SZ_FMT "lu"
32 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
33 #else
34 #define SZ_FMT "zu"
35 static size_t sz_fmt(size_t s) { return s; }
36 #endif
38 const unsigned char null_sha1[20];
40 const signed char hexval_table[256] = {
41          -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
42          -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
43          -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
44          -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
45          -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
46          -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
47           0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
48           8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
49          -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
50          -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
51          -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
52          -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
53          -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
54          -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
55          -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
56          -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
57          -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
58          -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
59          -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
60          -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
61          -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
62          -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
63          -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
64          -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
65          -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
66          -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
67          -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
68          -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
69          -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
70          -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
71          -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
72          -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
73 };
75 int get_sha1_hex(const char *hex, unsigned char *sha1)
76 {
77         int i;
78         for (i = 0; i < 20; i++) {
79                 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
80                 if (val & ~0xff)
81                         return -1;
82                 *sha1++ = val;
83                 hex += 2;
84         }
85         return 0;
86 }
88 static inline int offset_1st_component(const char *path)
89 {
90         if (has_dos_drive_prefix(path))
91                 return 2 + (path[2] == '/');
92         return *path == '/';
93 }
95 int safe_create_leading_directories(char *path)
96 {
97         char *pos = path + offset_1st_component(path);
98         struct stat st;
100         while (pos) {
101                 pos = strchr(pos, '/');
102                 if (!pos)
103                         break;
104                 *pos = 0;
105                 if (!stat(path, &st)) {
106                         /* path exists */
107                         if (!S_ISDIR(st.st_mode)) {
108                                 *pos = '/';
109                                 return -3;
110                         }
111                 }
112                 else if (mkdir(path, 0777)) {
113                         *pos = '/';
114                         return -1;
115                 }
116                 else if (adjust_shared_perm(path)) {
117                         *pos = '/';
118                         return -2;
119                 }
120                 *pos++ = '/';
121         }
122         return 0;
125 int safe_create_leading_directories_const(const char *path)
127         /* path points to cache entries, so xstrdup before messing with it */
128         char *buf = xstrdup(path);
129         int result = safe_create_leading_directories(buf);
130         free(buf);
131         return result;
134 char *sha1_to_hex(const unsigned char *sha1)
136         static int bufno;
137         static char hexbuffer[4][50];
138         static const char hex[] = "0123456789abcdef";
139         char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
140         int i;
142         for (i = 0; i < 20; i++) {
143                 unsigned int val = *sha1++;
144                 *buf++ = hex[val >> 4];
145                 *buf++ = hex[val & 0xf];
146         }
147         *buf = '\0';
149         return buffer;
152 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
154         int i;
155         for (i = 0; i < 20; i++) {
156                 static char hex[] = "0123456789abcdef";
157                 unsigned int val = sha1[i];
158                 char *pos = pathbuf + i*2 + (i > 0);
159                 *pos++ = hex[val >> 4];
160                 *pos = hex[val & 0xf];
161         }
164 /*
165  * NOTE! This returns a statically allocated buffer, so you have to be
166  * careful about using it. Do an "xstrdup()" if you need to save the
167  * filename.
168  *
169  * Also note that this returns the location for creating.  Reading
170  * SHA1 file can happen from any alternate directory listed in the
171  * DB_ENVIRONMENT environment variable if it is not found in
172  * the primary object database.
173  */
174 char *sha1_file_name(const unsigned char *sha1)
176         static char *name, *base;
178         if (!base) {
179                 const char *sha1_file_directory = get_object_directory();
180                 int len = strlen(sha1_file_directory);
181                 base = xmalloc(len + 60);
182                 memcpy(base, sha1_file_directory, len);
183                 memset(base+len, 0, 60);
184                 base[len] = '/';
185                 base[len+3] = '/';
186                 name = base + len + 1;
187         }
188         fill_sha1_path(name, sha1);
189         return base;
192 static char *sha1_get_pack_name(const unsigned char *sha1,
193                                 char **name, char **base, const char *which)
195         static const char hex[] = "0123456789abcdef";
196         char *buf;
197         int i;
199         if (!*base) {
200                 const char *sha1_file_directory = get_object_directory();
201                 int len = strlen(sha1_file_directory);
202                 *base = xmalloc(len + 60);
203                 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
204                         sha1_file_directory, which);
205                 *name = *base + len + 11;
206         }
208         buf = *name;
210         for (i = 0; i < 20; i++) {
211                 unsigned int val = *sha1++;
212                 *buf++ = hex[val >> 4];
213                 *buf++ = hex[val & 0xf];
214         }
216         return *base;
219 char *sha1_pack_name(const unsigned char *sha1)
221         static char *name, *base;
223         return sha1_get_pack_name(sha1, &name, &base, "pack");
226 char *sha1_pack_index_name(const unsigned char *sha1)
228         static char *name, *base;
230         return sha1_get_pack_name(sha1, &name, &base, "idx");
233 struct alternate_object_database *alt_odb_list;
234 static struct alternate_object_database **alt_odb_tail;
236 static void read_info_alternates(const char * alternates, int depth);
238 /*
239  * Prepare alternate object database registry.
240  *
241  * The variable alt_odb_list points at the list of struct
242  * alternate_object_database.  The elements on this list come from
243  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
244  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
245  * whose contents is similar to that environment variable but can be
246  * LF separated.  Its base points at a statically allocated buffer that
247  * contains "/the/directory/corresponding/to/.git/objects/...", while
248  * its name points just after the slash at the end of ".git/objects/"
249  * in the example above, and has enough space to hold 40-byte hex
250  * SHA1, an extra slash for the first level indirection, and the
251  * terminating NUL.
252  */
253 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
255         struct stat st;
256         const char *objdir = get_object_directory();
257         struct alternate_object_database *ent;
258         struct alternate_object_database *alt;
259         /* 43 = 40-byte + 2 '/' + terminating NUL */
260         int pfxlen = len;
261         int entlen = pfxlen + 43;
262         int base_len = -1;
264         if (!is_absolute_path(entry) && relative_base) {
265                 /* Relative alt-odb */
266                 if (base_len < 0)
267                         base_len = strlen(relative_base) + 1;
268                 entlen += base_len;
269                 pfxlen += base_len;
270         }
271         ent = xmalloc(sizeof(*ent) + entlen);
273         if (!is_absolute_path(entry) && relative_base) {
274                 memcpy(ent->base, relative_base, base_len - 1);
275                 ent->base[base_len - 1] = '/';
276                 memcpy(ent->base + base_len, entry, len);
277         }
278         else
279                 memcpy(ent->base, entry, pfxlen);
281         ent->name = ent->base + pfxlen + 1;
282         ent->base[pfxlen + 3] = '/';
283         ent->base[pfxlen] = ent->base[entlen-1] = 0;
285         /* Detect cases where alternate disappeared */
286         if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
287                 error("object directory %s does not exist; "
288                       "check .git/objects/info/alternates.",
289                       ent->base);
290                 free(ent);
291                 return -1;
292         }
294         /* Prevent the common mistake of listing the same
295          * thing twice, or object directory itself.
296          */
297         for (alt = alt_odb_list; alt; alt = alt->next) {
298                 if (!memcmp(ent->base, alt->base, pfxlen)) {
299                         free(ent);
300                         return -1;
301                 }
302         }
303         if (!memcmp(ent->base, objdir, pfxlen)) {
304                 free(ent);
305                 return -1;
306         }
308         /* add the alternate entry */
309         *alt_odb_tail = ent;
310         alt_odb_tail = &(ent->next);
311         ent->next = NULL;
313         /* recursively add alternates */
314         read_info_alternates(ent->base, depth + 1);
316         ent->base[pfxlen] = '/';
318         return 0;
321 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
322                                  const char *relative_base, int depth)
324         const char *cp, *last;
326         if (depth > 5) {
327                 error("%s: ignoring alternate object stores, nesting too deep.",
328                                 relative_base);
329                 return;
330         }
332         last = alt;
333         while (last < ep) {
334                 cp = last;
335                 if (cp < ep && *cp == '#') {
336                         while (cp < ep && *cp != sep)
337                                 cp++;
338                         last = cp + 1;
339                         continue;
340                 }
341                 while (cp < ep && *cp != sep)
342                         cp++;
343                 if (last != cp) {
344                         if (!is_absolute_path(last) && depth) {
345                                 error("%s: ignoring relative alternate object store %s",
346                                                 relative_base, last);
347                         } else {
348                                 link_alt_odb_entry(last, cp - last,
349                                                 relative_base, depth);
350                         }
351                 }
352                 while (cp < ep && *cp == sep)
353                         cp++;
354                 last = cp;
355         }
358 static void read_info_alternates(const char * relative_base, int depth)
360         char *map;
361         size_t mapsz;
362         struct stat st;
363         const char alt_file_name[] = "info/alternates";
364         /* Given that relative_base is no longer than PATH_MAX,
365            ensure that "path" has enough space to append "/", the
366            file name, "info/alternates", and a trailing NUL.  */
367         char path[PATH_MAX + 1 + sizeof alt_file_name];
368         int fd;
370         sprintf(path, "%s/%s", relative_base, alt_file_name);
371         fd = open(path, O_RDONLY);
372         if (fd < 0)
373                 return;
374         if (fstat(fd, &st) || (st.st_size == 0)) {
375                 close(fd);
376                 return;
377         }
378         mapsz = xsize_t(st.st_size);
379         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
380         close(fd);
382         link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
384         munmap(map, mapsz);
387 void add_to_alternates_file(const char *reference)
389         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
390         int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
391         char *alt = mkpath("%s/objects\n", reference);
392         write_or_die(fd, alt, strlen(alt));
393         if (commit_lock_file(lock))
394                 die("could not close alternates file");
395         if (alt_odb_tail)
396                 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
399 void prepare_alt_odb(void)
401         const char *alt;
403         if (alt_odb_tail)
404                 return;
406         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
407         if (!alt) alt = "";
409         alt_odb_tail = &alt_odb_list;
410         link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
412         read_info_alternates(get_object_directory(), 0);
415 static int has_loose_object_local(const unsigned char *sha1)
417         char *name = sha1_file_name(sha1);
418         return !access(name, F_OK);
421 int has_loose_object_nonlocal(const unsigned char *sha1)
423         struct alternate_object_database *alt;
424         prepare_alt_odb();
425         for (alt = alt_odb_list; alt; alt = alt->next) {
426                 fill_sha1_path(alt->name, sha1);
427                 if (!access(alt->base, F_OK))
428                         return 1;
429         }
430         return 0;
433 static int has_loose_object(const unsigned char *sha1)
435         return has_loose_object_local(sha1) ||
436                has_loose_object_nonlocal(sha1);
439 static unsigned int pack_used_ctr;
440 static unsigned int pack_mmap_calls;
441 static unsigned int peak_pack_open_windows;
442 static unsigned int pack_open_windows;
443 static size_t peak_pack_mapped;
444 static size_t pack_mapped;
445 struct packed_git *packed_git;
447 void pack_report(void)
449         fprintf(stderr,
450                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
451                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
452                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
453                 sz_fmt(getpagesize()),
454                 sz_fmt(packed_git_window_size),
455                 sz_fmt(packed_git_limit));
456         fprintf(stderr,
457                 "pack_report: pack_used_ctr            = %10u\n"
458                 "pack_report: pack_mmap_calls          = %10u\n"
459                 "pack_report: pack_open_windows        = %10u / %10u\n"
460                 "pack_report: pack_mapped              = "
461                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
462                 pack_used_ctr,
463                 pack_mmap_calls,
464                 pack_open_windows, peak_pack_open_windows,
465                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
468 static int check_packed_git_idx(const char *path,  struct packed_git *p)
470         void *idx_map;
471         struct pack_idx_header *hdr;
472         size_t idx_size;
473         uint32_t version, nr, i, *index;
474         int fd = open(path, O_RDONLY);
475         struct stat st;
477         if (fd < 0)
478                 return -1;
479         if (fstat(fd, &st)) {
480                 close(fd);
481                 return -1;
482         }
483         idx_size = xsize_t(st.st_size);
484         if (idx_size < 4 * 256 + 20 + 20) {
485                 close(fd);
486                 return error("index file %s is too small", path);
487         }
488         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
489         close(fd);
491         hdr = idx_map;
492         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
493                 version = ntohl(hdr->idx_version);
494                 if (version < 2 || version > 2) {
495                         munmap(idx_map, idx_size);
496                         return error("index file %s is version %"PRIu32
497                                      " and is not supported by this binary"
498                                      " (try upgrading GIT to a newer version)",
499                                      path, version);
500                 }
501         } else
502                 version = 1;
504         nr = 0;
505         index = idx_map;
506         if (version > 1)
507                 index += 2;  /* skip index header */
508         for (i = 0; i < 256; i++) {
509                 uint32_t n = ntohl(index[i]);
510                 if (n < nr) {
511                         munmap(idx_map, idx_size);
512                         return error("non-monotonic index %s", path);
513                 }
514                 nr = n;
515         }
517         if (version == 1) {
518                 /*
519                  * Total size:
520                  *  - 256 index entries 4 bytes each
521                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
522                  *  - 20-byte SHA1 of the packfile
523                  *  - 20-byte SHA1 file checksum
524                  */
525                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
526                         munmap(idx_map, idx_size);
527                         return error("wrong index v1 file size in %s", path);
528                 }
529         } else if (version == 2) {
530                 /*
531                  * Minimum size:
532                  *  - 8 bytes of header
533                  *  - 256 index entries 4 bytes each
534                  *  - 20-byte sha1 entry * nr
535                  *  - 4-byte crc entry * nr
536                  *  - 4-byte offset entry * nr
537                  *  - 20-byte SHA1 of the packfile
538                  *  - 20-byte SHA1 file checksum
539                  * And after the 4-byte offset table might be a
540                  * variable sized table containing 8-byte entries
541                  * for offsets larger than 2^31.
542                  */
543                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
544                 unsigned long max_size = min_size;
545                 if (nr)
546                         max_size += (nr - 1)*8;
547                 if (idx_size < min_size || idx_size > max_size) {
548                         munmap(idx_map, idx_size);
549                         return error("wrong index v2 file size in %s", path);
550                 }
551                 if (idx_size != min_size &&
552                     /*
553                      * make sure we can deal with large pack offsets.
554                      * 31-bit signed offset won't be enough, neither
555                      * 32-bit unsigned one will be.
556                      */
557                     (sizeof(off_t) <= 4)) {
558                         munmap(idx_map, idx_size);
559                         return error("pack too large for current definition of off_t in %s", path);
560                 }
561         }
563         p->index_version = version;
564         p->index_data = idx_map;
565         p->index_size = idx_size;
566         p->num_objects = nr;
567         return 0;
570 int open_pack_index(struct packed_git *p)
572         char *idx_name;
573         int ret;
575         if (p->index_data)
576                 return 0;
578         idx_name = xstrdup(p->pack_name);
579         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
580         ret = check_packed_git_idx(idx_name, p);
581         free(idx_name);
582         return ret;
585 static void scan_windows(struct packed_git *p,
586         struct packed_git **lru_p,
587         struct pack_window **lru_w,
588         struct pack_window **lru_l)
590         struct pack_window *w, *w_l;
592         for (w_l = NULL, w = p->windows; w; w = w->next) {
593                 if (!w->inuse_cnt) {
594                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
595                                 *lru_p = p;
596                                 *lru_w = w;
597                                 *lru_l = w_l;
598                         }
599                 }
600                 w_l = w;
601         }
604 static int unuse_one_window(struct packed_git *current, int keep_fd)
606         struct packed_git *p, *lru_p = NULL;
607         struct pack_window *lru_w = NULL, *lru_l = NULL;
609         if (current)
610                 scan_windows(current, &lru_p, &lru_w, &lru_l);
611         for (p = packed_git; p; p = p->next)
612                 scan_windows(p, &lru_p, &lru_w, &lru_l);
613         if (lru_p) {
614                 munmap(lru_w->base, lru_w->len);
615                 pack_mapped -= lru_w->len;
616                 if (lru_l)
617                         lru_l->next = lru_w->next;
618                 else {
619                         lru_p->windows = lru_w->next;
620                         if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
621                                 close(lru_p->pack_fd);
622                                 lru_p->pack_fd = -1;
623                         }
624                 }
625                 free(lru_w);
626                 pack_open_windows--;
627                 return 1;
628         }
629         return 0;
632 void release_pack_memory(size_t need, int fd)
634         size_t cur = pack_mapped;
635         while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
636                 ; /* nothing */
639 void close_pack_windows(struct packed_git *p)
641         while (p->windows) {
642                 struct pack_window *w = p->windows;
644                 if (w->inuse_cnt)
645                         die("pack '%s' still has open windows to it",
646                             p->pack_name);
647                 munmap(w->base, w->len);
648                 pack_mapped -= w->len;
649                 pack_open_windows--;
650                 p->windows = w->next;
651                 free(w);
652         }
655 void unuse_pack(struct pack_window **w_cursor)
657         struct pack_window *w = *w_cursor;
658         if (w) {
659                 w->inuse_cnt--;
660                 *w_cursor = NULL;
661         }
664 /*
665  * This is used by git-repack in case a newly created pack happens to
666  * contain the same set of objects as an existing one.  In that case
667  * the resulting file might be different even if its name would be the
668  * same.  It is best to close any reference to the old pack before it is
669  * replaced on disk.  Of course no index pointers nor windows for given pack
670  * must subsist at this point.  If ever objects from this pack are requested
671  * again, the new version of the pack will be reinitialized through
672  * reprepare_packed_git().
673  */
674 void free_pack_by_name(const char *pack_name)
676         struct packed_git *p, **pp = &packed_git;
678         while (*pp) {
679                 p = *pp;
680                 if (strcmp(pack_name, p->pack_name) == 0) {
681                         close_pack_windows(p);
682                         if (p->pack_fd != -1)
683                                 close(p->pack_fd);
684                         if (p->index_data)
685                                 munmap((void *)p->index_data, p->index_size);
686                         free(p->bad_object_sha1);
687                         *pp = p->next;
688                         free(p);
689                         return;
690                 }
691                 pp = &p->next;
692         }
695 /*
696  * Do not call this directly as this leaks p->pack_fd on error return;
697  * call open_packed_git() instead.
698  */
699 static int open_packed_git_1(struct packed_git *p)
701         struct stat st;
702         struct pack_header hdr;
703         unsigned char sha1[20];
704         unsigned char *idx_sha1;
705         long fd_flag;
707         if (!p->index_data && open_pack_index(p))
708                 return error("packfile %s index unavailable", p->pack_name);
710         p->pack_fd = open(p->pack_name, O_RDONLY);
711         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
712                 return -1;
714         /* If we created the struct before we had the pack we lack size. */
715         if (!p->pack_size) {
716                 if (!S_ISREG(st.st_mode))
717                         return error("packfile %s not a regular file", p->pack_name);
718                 p->pack_size = st.st_size;
719         } else if (p->pack_size != st.st_size)
720                 return error("packfile %s size changed", p->pack_name);
722         /* We leave these file descriptors open with sliding mmap;
723          * there is no point keeping them open across exec(), though.
724          */
725         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
726         if (fd_flag < 0)
727                 return error("cannot determine file descriptor flags");
728         fd_flag |= FD_CLOEXEC;
729         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
730                 return error("cannot set FD_CLOEXEC");
732         /* Verify we recognize this pack file format. */
733         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
734                 return error("file %s is far too short to be a packfile", p->pack_name);
735         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
736                 return error("file %s is not a GIT packfile", p->pack_name);
737         if (!pack_version_ok(hdr.hdr_version))
738                 return error("packfile %s is version %"PRIu32" and not"
739                         " supported (try upgrading GIT to a newer version)",
740                         p->pack_name, ntohl(hdr.hdr_version));
742         /* Verify the pack matches its index. */
743         if (p->num_objects != ntohl(hdr.hdr_entries))
744                 return error("packfile %s claims to have %"PRIu32" objects"
745                              " while index indicates %"PRIu32" objects",
746                              p->pack_name, ntohl(hdr.hdr_entries),
747                              p->num_objects);
748         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
749                 return error("end of packfile %s is unavailable", p->pack_name);
750         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
751                 return error("packfile %s signature is unavailable", p->pack_name);
752         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
753         if (hashcmp(sha1, idx_sha1))
754                 return error("packfile %s does not match index", p->pack_name);
755         return 0;
758 static int open_packed_git(struct packed_git *p)
760         if (!open_packed_git_1(p))
761                 return 0;
762         if (p->pack_fd != -1) {
763                 close(p->pack_fd);
764                 p->pack_fd = -1;
765         }
766         return -1;
769 static int in_window(struct pack_window *win, off_t offset)
771         /* We must promise at least 20 bytes (one hash) after the
772          * offset is available from this window, otherwise the offset
773          * is not actually in this window and a different window (which
774          * has that one hash excess) must be used.  This is to support
775          * the object header and delta base parsing routines below.
776          */
777         off_t win_off = win->offset;
778         return win_off <= offset
779                 && (offset + 20) <= (win_off + win->len);
782 unsigned char* use_pack(struct packed_git *p,
783                 struct pack_window **w_cursor,
784                 off_t offset,
785                 unsigned int *left)
787         struct pack_window *win = *w_cursor;
789         if (p->pack_fd == -1 && open_packed_git(p))
790                 die("packfile %s cannot be accessed", p->pack_name);
792         /* Since packfiles end in a hash of their content and its
793          * pointless to ask for an offset into the middle of that
794          * hash, and the in_window function above wouldn't match
795          * don't allow an offset too close to the end of the file.
796          */
797         if (offset > (p->pack_size - 20))
798                 die("offset beyond end of packfile (truncated pack?)");
800         if (!win || !in_window(win, offset)) {
801                 if (win)
802                         win->inuse_cnt--;
803                 for (win = p->windows; win; win = win->next) {
804                         if (in_window(win, offset))
805                                 break;
806                 }
807                 if (!win) {
808                         size_t window_align = packed_git_window_size / 2;
809                         off_t len;
810                         win = xcalloc(1, sizeof(*win));
811                         win->offset = (offset / window_align) * window_align;
812                         len = p->pack_size - win->offset;
813                         if (len > packed_git_window_size)
814                                 len = packed_git_window_size;
815                         win->len = (size_t)len;
816                         pack_mapped += win->len;
817                         while (packed_git_limit < pack_mapped
818                                 && unuse_one_window(p, p->pack_fd))
819                                 ; /* nothing */
820                         win->base = xmmap(NULL, win->len,
821                                 PROT_READ, MAP_PRIVATE,
822                                 p->pack_fd, win->offset);
823                         if (win->base == MAP_FAILED)
824                                 die("packfile %s cannot be mapped: %s",
825                                         p->pack_name,
826                                         strerror(errno));
827                         pack_mmap_calls++;
828                         pack_open_windows++;
829                         if (pack_mapped > peak_pack_mapped)
830                                 peak_pack_mapped = pack_mapped;
831                         if (pack_open_windows > peak_pack_open_windows)
832                                 peak_pack_open_windows = pack_open_windows;
833                         win->next = p->windows;
834                         p->windows = win;
835                 }
836         }
837         if (win != *w_cursor) {
838                 win->last_used = pack_used_ctr++;
839                 win->inuse_cnt++;
840                 *w_cursor = win;
841         }
842         offset -= win->offset;
843         if (left)
844                 *left = win->len - xsize_t(offset);
845         return win->base + offset;
848 static struct packed_git *alloc_packed_git(int extra)
850         struct packed_git *p = xmalloc(sizeof(*p) + extra);
851         memset(p, 0, sizeof(*p));
852         p->pack_fd = -1;
853         return p;
856 struct packed_git *add_packed_git(const char *path, int path_len, int local)
858         struct stat st;
859         struct packed_git *p = alloc_packed_git(path_len + 2);
861         /*
862          * Make sure a corresponding .pack file exists and that
863          * the index looks sane.
864          */
865         path_len -= strlen(".idx");
866         if (path_len < 1) {
867                 free(p);
868                 return NULL;
869         }
870         memcpy(p->pack_name, path, path_len);
872         strcpy(p->pack_name + path_len, ".keep");
873         if (!access(p->pack_name, F_OK))
874                 p->pack_keep = 1;
876         strcpy(p->pack_name + path_len, ".pack");
877         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
878                 free(p);
879                 return NULL;
880         }
882         /* ok, it looks sane as far as we can check without
883          * actually mapping the pack file.
884          */
885         p->pack_size = st.st_size;
886         p->pack_local = local;
887         p->mtime = st.st_mtime;
888         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
889                 hashclr(p->sha1);
890         return p;
893 struct packed_git *parse_pack_index(unsigned char *sha1)
895         const char *idx_path = sha1_pack_index_name(sha1);
896         const char *path = sha1_pack_name(sha1);
897         struct packed_git *p = alloc_packed_git(strlen(path) + 1);
899         strcpy(p->pack_name, path);
900         hashcpy(p->sha1, sha1);
901         if (check_packed_git_idx(idx_path, p)) {
902                 free(p);
903                 return NULL;
904         }
906         return p;
909 void install_packed_git(struct packed_git *pack)
911         pack->next = packed_git;
912         packed_git = pack;
915 static void prepare_packed_git_one(char *objdir, int local)
917         /* Ensure that this buffer is large enough so that we can
918            append "/pack/" without clobbering the stack even if
919            strlen(objdir) were PATH_MAX.  */
920         char path[PATH_MAX + 1 + 4 + 1 + 1];
921         int len;
922         DIR *dir;
923         struct dirent *de;
925         sprintf(path, "%s/pack", objdir);
926         len = strlen(path);
927         dir = opendir(path);
928         if (!dir) {
929                 if (errno != ENOENT)
930                         error("unable to open object pack directory: %s: %s",
931                               path, strerror(errno));
932                 return;
933         }
934         path[len++] = '/';
935         while ((de = readdir(dir)) != NULL) {
936                 int namelen = strlen(de->d_name);
937                 struct packed_git *p;
939                 if (!has_extension(de->d_name, ".idx"))
940                         continue;
942                 if (len + namelen + 1 > sizeof(path))
943                         continue;
945                 /* Don't reopen a pack we already have. */
946                 strcpy(path + len, de->d_name);
947                 for (p = packed_git; p; p = p->next) {
948                         if (!memcmp(path, p->pack_name, len + namelen - 4))
949                                 break;
950                 }
951                 if (p)
952                         continue;
953                 /* See if it really is a valid .idx file with corresponding
954                  * .pack file that we can map.
955                  */
956                 p = add_packed_git(path, len + namelen, local);
957                 if (!p)
958                         continue;
959                 install_packed_git(p);
960         }
961         closedir(dir);
964 static int sort_pack(const void *a_, const void *b_)
966         struct packed_git *a = *((struct packed_git **)a_);
967         struct packed_git *b = *((struct packed_git **)b_);
968         int st;
970         /*
971          * Local packs tend to contain objects specific to our
972          * variant of the project than remote ones.  In addition,
973          * remote ones could be on a network mounted filesystem.
974          * Favor local ones for these reasons.
975          */
976         st = a->pack_local - b->pack_local;
977         if (st)
978                 return -st;
980         /*
981          * Younger packs tend to contain more recent objects,
982          * and more recent objects tend to get accessed more
983          * often.
984          */
985         if (a->mtime < b->mtime)
986                 return 1;
987         else if (a->mtime == b->mtime)
988                 return 0;
989         return -1;
992 static void rearrange_packed_git(void)
994         struct packed_git **ary, *p;
995         int i, n;
997         for (n = 0, p = packed_git; p; p = p->next)
998                 n++;
999         if (n < 2)
1000                 return;
1002         /* prepare an array of packed_git for easier sorting */
1003         ary = xcalloc(n, sizeof(struct packed_git *));
1004         for (n = 0, p = packed_git; p; p = p->next)
1005                 ary[n++] = p;
1007         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1009         /* link them back again */
1010         for (i = 0; i < n - 1; i++)
1011                 ary[i]->next = ary[i + 1];
1012         ary[n - 1]->next = NULL;
1013         packed_git = ary[0];
1015         free(ary);
1018 static int prepare_packed_git_run_once = 0;
1019 void prepare_packed_git(void)
1021         struct alternate_object_database *alt;
1023         if (prepare_packed_git_run_once)
1024                 return;
1025         prepare_packed_git_one(get_object_directory(), 1);
1026         prepare_alt_odb();
1027         for (alt = alt_odb_list; alt; alt = alt->next) {
1028                 alt->name[-1] = 0;
1029                 prepare_packed_git_one(alt->base, 0);
1030                 alt->name[-1] = '/';
1031         }
1032         rearrange_packed_git();
1033         prepare_packed_git_run_once = 1;
1036 void reprepare_packed_git(void)
1038         discard_revindex();
1039         prepare_packed_git_run_once = 0;
1040         prepare_packed_git();
1043 static void mark_bad_packed_object(struct packed_git *p,
1044                                    const unsigned char *sha1)
1046         unsigned i;
1047         for (i = 0; i < p->num_bad_objects; i++)
1048                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1049                         return;
1050         p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1051         hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1052         p->num_bad_objects++;
1055 static int has_packed_and_bad(const unsigned char *sha1)
1057         struct packed_git *p;
1058         unsigned i;
1060         for (p = packed_git; p; p = p->next)
1061                 for (i = 0; i < p->num_bad_objects; i++)
1062                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1063                                 return 1;
1064         return 0;
1067 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1069         unsigned char real_sha1[20];
1070         hash_sha1_file(map, size, type, real_sha1);
1071         return hashcmp(sha1, real_sha1) ? -1 : 0;
1074 static int git_open_noatime(const char *name)
1076         static int sha1_file_open_flag = O_NOATIME;
1077         int fd = open(name, O_RDONLY | sha1_file_open_flag);
1079         /* Might the failure be due to O_NOATIME? */
1080         if (fd < 0 && errno != ENOENT && sha1_file_open_flag) {
1081                 fd = open(name, O_RDONLY);
1082                 if (fd >= 0)
1083                         sha1_file_open_flag = 0;
1084         }
1085         return fd;
1088 static int open_sha1_file(const unsigned char *sha1)
1090         int fd;
1091         char *name = sha1_file_name(sha1);
1092         struct alternate_object_database *alt;
1094         fd = git_open_noatime(name);
1095         if (fd >= 0)
1096                 return fd;
1098         prepare_alt_odb();
1099         errno = ENOENT;
1100         for (alt = alt_odb_list; alt; alt = alt->next) {
1101                 name = alt->name;
1102                 fill_sha1_path(name, sha1);
1103                 fd = git_open_noatime(alt->base);
1104                 if (fd >= 0)
1105                         return fd;
1106         }
1107         return -1;
1110 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1112         void *map;
1113         int fd;
1115         fd = open_sha1_file(sha1);
1116         map = NULL;
1117         if (fd >= 0) {
1118                 struct stat st;
1120                 if (!fstat(fd, &st)) {
1121                         *size = xsize_t(st.st_size);
1122                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1123                 }
1124                 close(fd);
1125         }
1126         return map;
1129 static int legacy_loose_object(unsigned char *map)
1131         unsigned int word;
1133         /*
1134          * Is it a zlib-compressed buffer? If so, the first byte
1135          * must be 0x78 (15-bit window size, deflated), and the
1136          * first 16-bit word is evenly divisible by 31
1137          */
1138         word = (map[0] << 8) + map[1];
1139         if (map[0] == 0x78 && !(word % 31))
1140                 return 1;
1141         else
1142                 return 0;
1145 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1147         unsigned shift;
1148         unsigned char c;
1149         unsigned long size;
1150         unsigned long used = 0;
1152         c = buf[used++];
1153         *type = (c >> 4) & 7;
1154         size = c & 15;
1155         shift = 4;
1156         while (c & 0x80) {
1157                 if (len <= used)
1158                         return 0;
1159                 if (sizeof(long) * 8 <= shift)
1160                         return 0;
1161                 c = buf[used++];
1162                 size += (c & 0x7f) << shift;
1163                 shift += 7;
1164         }
1165         *sizep = size;
1166         return used;
1169 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1171         unsigned long size, used;
1172         static const char valid_loose_object_type[8] = {
1173                 0, /* OBJ_EXT */
1174                 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1175                 0, /* "delta" and others are invalid in a loose object */
1176         };
1177         enum object_type type;
1179         /* Get the data stream */
1180         memset(stream, 0, sizeof(*stream));
1181         stream->next_in = map;
1182         stream->avail_in = mapsize;
1183         stream->next_out = buffer;
1184         stream->avail_out = bufsiz;
1186         if (legacy_loose_object(map)) {
1187                 inflateInit(stream);
1188                 return inflate(stream, 0);
1189         }
1192         /*
1193          * There used to be a second loose object header format which
1194          * was meant to mimic the in-pack format, allowing for direct
1195          * copy of the object data.  This format turned up not to be
1196          * really worth it and we don't write it any longer.  But we
1197          * can still read it.
1198          */
1199         used = unpack_object_header_gently(map, mapsize, &type, &size);
1200         if (!used || !valid_loose_object_type[type])
1201                 return -1;
1202         map += used;
1203         mapsize -= used;
1205         /* Set up the stream for the rest.. */
1206         stream->next_in = map;
1207         stream->avail_in = mapsize;
1208         inflateInit(stream);
1210         /* And generate the fake traditional header */
1211         stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1212                                          typename(type), size);
1213         return 0;
1216 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1218         int bytes = strlen(buffer) + 1;
1219         unsigned char *buf = xmalloc(1+size);
1220         unsigned long n;
1221         int status = Z_OK;
1223         n = stream->total_out - bytes;
1224         if (n > size)
1225                 n = size;
1226         memcpy(buf, (char *) buffer + bytes, n);
1227         bytes = n;
1228         if (bytes <= size) {
1229                 /*
1230                  * The above condition must be (bytes <= size), not
1231                  * (bytes < size).  In other words, even though we
1232                  * expect no more output and set avail_out to zer0,
1233                  * the input zlib stream may have bytes that express
1234                  * "this concludes the stream", and we *do* want to
1235                  * eat that input.
1236                  *
1237                  * Otherwise we would not be able to test that we
1238                  * consumed all the input to reach the expected size;
1239                  * we also want to check that zlib tells us that all
1240                  * went well with status == Z_STREAM_END at the end.
1241                  */
1242                 stream->next_out = buf + bytes;
1243                 stream->avail_out = size - bytes;
1244                 while (status == Z_OK)
1245                         status = inflate(stream, Z_FINISH);
1246         }
1247         buf[size] = 0;
1248         if (status == Z_STREAM_END && !stream->avail_in) {
1249                 inflateEnd(stream);
1250                 return buf;
1251         }
1253         if (status < 0)
1254                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1255         else if (stream->avail_in)
1256                 error("garbage at end of loose object '%s'",
1257                       sha1_to_hex(sha1));
1258         free(buf);
1259         return NULL;
1262 /*
1263  * We used to just use "sscanf()", but that's actually way
1264  * too permissive for what we want to check. So do an anal
1265  * object header parse by hand.
1266  */
1267 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1269         char type[10];
1270         int i;
1271         unsigned long size;
1273         /*
1274          * The type can be at most ten bytes (including the
1275          * terminating '\0' that we add), and is followed by
1276          * a space.
1277          */
1278         i = 0;
1279         for (;;) {
1280                 char c = *hdr++;
1281                 if (c == ' ')
1282                         break;
1283                 type[i++] = c;
1284                 if (i >= sizeof(type))
1285                         return -1;
1286         }
1287         type[i] = 0;
1289         /*
1290          * The length must follow immediately, and be in canonical
1291          * decimal format (ie "010" is not valid).
1292          */
1293         size = *hdr++ - '0';
1294         if (size > 9)
1295                 return -1;
1296         if (size) {
1297                 for (;;) {
1298                         unsigned long c = *hdr - '0';
1299                         if (c > 9)
1300                                 break;
1301                         hdr++;
1302                         size = size * 10 + c;
1303                 }
1304         }
1305         *sizep = size;
1307         /*
1308          * The length must be followed by a zero byte
1309          */
1310         return *hdr ? -1 : type_from_string(type);
1313 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1315         int ret;
1316         z_stream stream;
1317         char hdr[8192];
1319         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1320         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1321                 return NULL;
1323         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1326 unsigned long get_size_from_delta(struct packed_git *p,
1327                                   struct pack_window **w_curs,
1328                                   off_t curpos)
1330         const unsigned char *data;
1331         unsigned char delta_head[20], *in;
1332         z_stream stream;
1333         int st;
1335         memset(&stream, 0, sizeof(stream));
1336         stream.next_out = delta_head;
1337         stream.avail_out = sizeof(delta_head);
1339         inflateInit(&stream);
1340         do {
1341                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1342                 stream.next_in = in;
1343                 st = inflate(&stream, Z_FINISH);
1344                 curpos += stream.next_in - in;
1345         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1346                  stream.total_out < sizeof(delta_head));
1347         inflateEnd(&stream);
1348         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1349                 die("delta data unpack-initial failed");
1351         /* Examine the initial part of the delta to figure out
1352          * the result size.
1353          */
1354         data = delta_head;
1356         /* ignore base size */
1357         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1359         /* Read the result size */
1360         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1363 static off_t get_delta_base(struct packed_git *p,
1364                                     struct pack_window **w_curs,
1365                                     off_t *curpos,
1366                                     enum object_type type,
1367                                     off_t delta_obj_offset)
1369         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1370         off_t base_offset;
1372         /* use_pack() assured us we have [base_info, base_info + 20)
1373          * as a range that we can look at without walking off the
1374          * end of the mapped window.  Its actually the hash size
1375          * that is assured.  An OFS_DELTA longer than the hash size
1376          * is stupid, as then a REF_DELTA would be smaller to store.
1377          */
1378         if (type == OBJ_OFS_DELTA) {
1379                 unsigned used = 0;
1380                 unsigned char c = base_info[used++];
1381                 base_offset = c & 127;
1382                 while (c & 128) {
1383                         base_offset += 1;
1384                         if (!base_offset || MSB(base_offset, 7))
1385                                 return 0;  /* overflow */
1386                         c = base_info[used++];
1387                         base_offset = (base_offset << 7) + (c & 127);
1388                 }
1389                 base_offset = delta_obj_offset - base_offset;
1390                 if (base_offset >= delta_obj_offset)
1391                         return 0;  /* out of bound */
1392                 *curpos += used;
1393         } else if (type == OBJ_REF_DELTA) {
1394                 /* The base entry _must_ be in the same pack */
1395                 base_offset = find_pack_entry_one(base_info, p);
1396                 *curpos += 20;
1397         } else
1398                 die("I am totally screwed");
1399         return base_offset;
1402 /* forward declaration for a mutually recursive function */
1403 static int packed_object_info(struct packed_git *p, off_t offset,
1404                               unsigned long *sizep);
1406 static int packed_delta_info(struct packed_git *p,
1407                              struct pack_window **w_curs,
1408                              off_t curpos,
1409                              enum object_type type,
1410                              off_t obj_offset,
1411                              unsigned long *sizep)
1413         off_t base_offset;
1415         base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1416         type = packed_object_info(p, base_offset, NULL);
1418         /* We choose to only get the type of the base object and
1419          * ignore potentially corrupt pack file that expects the delta
1420          * based on a base with a wrong size.  This saves tons of
1421          * inflate() calls.
1422          */
1423         if (sizep)
1424                 *sizep = get_size_from_delta(p, w_curs, curpos);
1426         return type;
1429 static int unpack_object_header(struct packed_git *p,
1430                                 struct pack_window **w_curs,
1431                                 off_t *curpos,
1432                                 unsigned long *sizep)
1434         unsigned char *base;
1435         unsigned int left;
1436         unsigned long used;
1437         enum object_type type;
1439         /* use_pack() assures us we have [base, base + 20) available
1440          * as a range that we can look at at.  (Its actually the hash
1441          * size that is assured.)  With our object header encoding
1442          * the maximum deflated object size is 2^137, which is just
1443          * insane, so we know won't exceed what we have been given.
1444          */
1445         base = use_pack(p, w_curs, *curpos, &left);
1446         used = unpack_object_header_gently(base, left, &type, sizep);
1447         if (!used)
1448                 die("object offset outside of pack file");
1449         *curpos += used;
1451         return type;
1454 const char *packed_object_info_detail(struct packed_git *p,
1455                                       off_t obj_offset,
1456                                       unsigned long *size,
1457                                       unsigned long *store_size,
1458                                       unsigned int *delta_chain_length,
1459                                       unsigned char *base_sha1)
1461         struct pack_window *w_curs = NULL;
1462         off_t curpos;
1463         unsigned long dummy;
1464         unsigned char *next_sha1;
1465         enum object_type type;
1466         struct revindex_entry *revidx;
1468         *delta_chain_length = 0;
1469         curpos = obj_offset;
1470         type = unpack_object_header(p, &w_curs, &curpos, size);
1472         revidx = find_pack_revindex(p, obj_offset);
1473         *store_size = revidx[1].offset - obj_offset;
1475         for (;;) {
1476                 switch (type) {
1477                 default:
1478                         die("pack %s contains unknown object type %d",
1479                             p->pack_name, type);
1480                 case OBJ_COMMIT:
1481                 case OBJ_TREE:
1482                 case OBJ_BLOB:
1483                 case OBJ_TAG:
1484                         unuse_pack(&w_curs);
1485                         return typename(type);
1486                 case OBJ_OFS_DELTA:
1487                         obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1488                         if (!obj_offset)
1489                                 die("pack %s contains bad delta base reference of type %s",
1490                                     p->pack_name, typename(type));
1491                         if (*delta_chain_length == 0) {
1492                                 revidx = find_pack_revindex(p, obj_offset);
1493                                 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1494                         }
1495                         break;
1496                 case OBJ_REF_DELTA:
1497                         next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1498                         if (*delta_chain_length == 0)
1499                                 hashcpy(base_sha1, next_sha1);
1500                         obj_offset = find_pack_entry_one(next_sha1, p);
1501                         break;
1502                 }
1503                 (*delta_chain_length)++;
1504                 curpos = obj_offset;
1505                 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1506         }
1509 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1510                               unsigned long *sizep)
1512         struct pack_window *w_curs = NULL;
1513         unsigned long size;
1514         off_t curpos = obj_offset;
1515         enum object_type type;
1517         type = unpack_object_header(p, &w_curs, &curpos, &size);
1519         switch (type) {
1520         case OBJ_OFS_DELTA:
1521         case OBJ_REF_DELTA:
1522                 type = packed_delta_info(p, &w_curs, curpos,
1523                                          type, obj_offset, sizep);
1524                 break;
1525         case OBJ_COMMIT:
1526         case OBJ_TREE:
1527         case OBJ_BLOB:
1528         case OBJ_TAG:
1529                 if (sizep)
1530                         *sizep = size;
1531                 break;
1532         default:
1533                 die("pack %s contains unknown object type %d",
1534                     p->pack_name, type);
1535         }
1536         unuse_pack(&w_curs);
1537         return type;
1540 static void *unpack_compressed_entry(struct packed_git *p,
1541                                     struct pack_window **w_curs,
1542                                     off_t curpos,
1543                                     unsigned long size)
1545         int st;
1546         z_stream stream;
1547         unsigned char *buffer, *in;
1549         buffer = xmalloc(size + 1);
1550         buffer[size] = 0;
1551         memset(&stream, 0, sizeof(stream));
1552         stream.next_out = buffer;
1553         stream.avail_out = size;
1555         inflateInit(&stream);
1556         do {
1557                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1558                 stream.next_in = in;
1559                 st = inflate(&stream, Z_FINISH);
1560                 curpos += stream.next_in - in;
1561         } while (st == Z_OK || st == Z_BUF_ERROR);
1562         inflateEnd(&stream);
1563         if ((st != Z_STREAM_END) || stream.total_out != size) {
1564                 free(buffer);
1565                 return NULL;
1566         }
1568         return buffer;
1571 #define MAX_DELTA_CACHE (256)
1573 static size_t delta_base_cached;
1575 static struct delta_base_cache_lru_list {
1576         struct delta_base_cache_lru_list *prev;
1577         struct delta_base_cache_lru_list *next;
1578 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1580 static struct delta_base_cache_entry {
1581         struct delta_base_cache_lru_list lru;
1582         void *data;
1583         struct packed_git *p;
1584         off_t base_offset;
1585         unsigned long size;
1586         enum object_type type;
1587 } delta_base_cache[MAX_DELTA_CACHE];
1589 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1591         unsigned long hash;
1593         hash = (unsigned long)p + (unsigned long)base_offset;
1594         hash += (hash >> 8) + (hash >> 16);
1595         return hash % MAX_DELTA_CACHE;
1598 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1599         unsigned long *base_size, enum object_type *type, int keep_cache)
1601         void *ret;
1602         unsigned long hash = pack_entry_hash(p, base_offset);
1603         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1605         ret = ent->data;
1606         if (ret && ent->p == p && ent->base_offset == base_offset)
1607                 goto found_cache_entry;
1608         return unpack_entry(p, base_offset, type, base_size);
1610 found_cache_entry:
1611         if (!keep_cache) {
1612                 ent->data = NULL;
1613                 ent->lru.next->prev = ent->lru.prev;
1614                 ent->lru.prev->next = ent->lru.next;
1615                 delta_base_cached -= ent->size;
1616         } else {
1617                 ret = xmemdupz(ent->data, ent->size);
1618         }
1619         *type = ent->type;
1620         *base_size = ent->size;
1621         return ret;
1624 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1626         if (ent->data) {
1627                 free(ent->data);
1628                 ent->data = NULL;
1629                 ent->lru.next->prev = ent->lru.prev;
1630                 ent->lru.prev->next = ent->lru.next;
1631                 delta_base_cached -= ent->size;
1632         }
1635 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1636         void *base, unsigned long base_size, enum object_type type)
1638         unsigned long hash = pack_entry_hash(p, base_offset);
1639         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1640         struct delta_base_cache_lru_list *lru;
1642         release_delta_base_cache(ent);
1643         delta_base_cached += base_size;
1645         for (lru = delta_base_cache_lru.next;
1646              delta_base_cached > delta_base_cache_limit
1647              && lru != &delta_base_cache_lru;
1648              lru = lru->next) {
1649                 struct delta_base_cache_entry *f = (void *)lru;
1650                 if (f->type == OBJ_BLOB)
1651                         release_delta_base_cache(f);
1652         }
1653         for (lru = delta_base_cache_lru.next;
1654              delta_base_cached > delta_base_cache_limit
1655              && lru != &delta_base_cache_lru;
1656              lru = lru->next) {
1657                 struct delta_base_cache_entry *f = (void *)lru;
1658                 release_delta_base_cache(f);
1659         }
1661         ent->p = p;
1662         ent->base_offset = base_offset;
1663         ent->type = type;
1664         ent->data = base;
1665         ent->size = base_size;
1666         ent->lru.next = &delta_base_cache_lru;
1667         ent->lru.prev = delta_base_cache_lru.prev;
1668         delta_base_cache_lru.prev->next = &ent->lru;
1669         delta_base_cache_lru.prev = &ent->lru;
1672 static void *unpack_delta_entry(struct packed_git *p,
1673                                 struct pack_window **w_curs,
1674                                 off_t curpos,
1675                                 unsigned long delta_size,
1676                                 off_t obj_offset,
1677                                 enum object_type *type,
1678                                 unsigned long *sizep)
1680         void *delta_data, *result, *base;
1681         unsigned long base_size;
1682         off_t base_offset;
1684         base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1685         if (!base_offset) {
1686                 error("failed to validate delta base reference "
1687                       "at offset %"PRIuMAX" from %s",
1688                       (uintmax_t)curpos, p->pack_name);
1689                 return NULL;
1690         }
1691         unuse_pack(w_curs);
1692         base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1693         if (!base) {
1694                 /*
1695                  * We're probably in deep shit, but let's try to fetch
1696                  * the required base anyway from another pack or loose.
1697                  * This is costly but should happen only in the presence
1698                  * of a corrupted pack, and is better than failing outright.
1699                  */
1700                 struct revindex_entry *revidx = find_pack_revindex(p, base_offset);
1701                 const unsigned char *base_sha1 =
1702                                         nth_packed_object_sha1(p, revidx->nr);
1703                 error("failed to read delta base object %s"
1704                       " at offset %"PRIuMAX" from %s",
1705                       sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1706                       p->pack_name);
1707                 mark_bad_packed_object(p, base_sha1);
1708                 base = read_object(base_sha1, type, &base_size);
1709                 if (!base)
1710                         return NULL;
1711         }
1713         delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1714         if (!delta_data) {
1715                 error("failed to unpack compressed delta "
1716                       "at offset %"PRIuMAX" from %s",
1717                       (uintmax_t)curpos, p->pack_name);
1718                 free(base);
1719                 return NULL;
1720         }
1721         result = patch_delta(base, base_size,
1722                              delta_data, delta_size,
1723                              sizep);
1724         if (!result)
1725                 die("failed to apply delta");
1726         free(delta_data);
1727         add_delta_base_cache(p, base_offset, base, base_size, *type);
1728         return result;
1731 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1732                    enum object_type *type, unsigned long *sizep)
1734         struct pack_window *w_curs = NULL;
1735         off_t curpos = obj_offset;
1736         void *data;
1738         *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1739         switch (*type) {
1740         case OBJ_OFS_DELTA:
1741         case OBJ_REF_DELTA:
1742                 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1743                                           obj_offset, type, sizep);
1744                 break;
1745         case OBJ_COMMIT:
1746         case OBJ_TREE:
1747         case OBJ_BLOB:
1748         case OBJ_TAG:
1749                 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1750                 break;
1751         default:
1752                 data = NULL;
1753                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1754                       *type, (uintmax_t)obj_offset, p->pack_name);
1755         }
1756         unuse_pack(&w_curs);
1757         return data;
1760 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1761                                             uint32_t n)
1763         const unsigned char *index = p->index_data;
1764         if (!index) {
1765                 if (open_pack_index(p))
1766                         return NULL;
1767                 index = p->index_data;
1768         }
1769         if (n >= p->num_objects)
1770                 return NULL;
1771         index += 4 * 256;
1772         if (p->index_version == 1) {
1773                 return index + 24 * n + 4;
1774         } else {
1775                 index += 8;
1776                 return index + 20 * n;
1777         }
1780 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1782         const unsigned char *index = p->index_data;
1783         index += 4 * 256;
1784         if (p->index_version == 1) {
1785                 return ntohl(*((uint32_t *)(index + 24 * n)));
1786         } else {
1787                 uint32_t off;
1788                 index += 8 + p->num_objects * (20 + 4);
1789                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1790                 if (!(off & 0x80000000))
1791                         return off;
1792                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1793                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1794                                    ntohl(*((uint32_t *)(index + 4)));
1795         }
1798 off_t find_pack_entry_one(const unsigned char *sha1,
1799                                   struct packed_git *p)
1801         const uint32_t *level1_ofs = p->index_data;
1802         const unsigned char *index = p->index_data;
1803         unsigned hi, lo, stride;
1804         static int use_lookup = -1;
1805         static int debug_lookup = -1;
1807         if (debug_lookup < 0)
1808                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1810         if (!index) {
1811                 if (open_pack_index(p))
1812                         return 0;
1813                 level1_ofs = p->index_data;
1814                 index = p->index_data;
1815         }
1816         if (p->index_version > 1) {
1817                 level1_ofs += 2;
1818                 index += 8;
1819         }
1820         index += 4 * 256;
1821         hi = ntohl(level1_ofs[*sha1]);
1822         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1823         if (p->index_version > 1) {
1824                 stride = 20;
1825         } else {
1826                 stride = 24;
1827                 index += 4;
1828         }
1830         if (debug_lookup)
1831                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1832                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1834         if (use_lookup < 0)
1835                 use_lookup = !!getenv("GIT_USE_LOOKUP");
1836         if (use_lookup) {
1837                 int pos = sha1_entry_pos(index, stride, 0,
1838                                          lo, hi, p->num_objects, sha1);
1839                 if (pos < 0)
1840                         return 0;
1841                 return nth_packed_object_offset(p, pos);
1842         }
1844         do {
1845                 unsigned mi = (lo + hi) / 2;
1846                 int cmp = hashcmp(index + mi * stride, sha1);
1848                 if (debug_lookup)
1849                         printf("lo %u hi %u rg %u mi %u\n",
1850                                lo, hi, hi - lo, mi);
1851                 if (!cmp)
1852                         return nth_packed_object_offset(p, mi);
1853                 if (cmp > 0)
1854                         hi = mi;
1855                 else
1856                         lo = mi+1;
1857         } while (lo < hi);
1858         return 0;
1861 int matches_pack_name(struct packed_git *p, const char *name)
1863         const char *last_c, *c;
1865         if (!strcmp(p->pack_name, name))
1866                 return 1;
1868         for (c = p->pack_name, last_c = c; *c;)
1869                 if (*c == '/')
1870                         last_c = ++c;
1871                 else
1872                         ++c;
1873         if (!strcmp(last_c, name))
1874                 return 1;
1876         return 0;
1879 static int find_pack_ent(const unsigned char *sha1, struct pack_entry *e,
1880                          const struct rev_info *revs)
1882         static struct packed_git *last_found = (void *)1;
1883         struct packed_git *p;
1884         off_t offset;
1886         prepare_packed_git();
1887         if (!packed_git)
1888                 return 0;
1889         p = (last_found == (void *)1) ? packed_git : last_found;
1891         do {
1892                 if (revs->ignore_packed) {
1893                         const char **ig;
1894                         for (ig = revs->ignore_packed; *ig; ig++)
1895                                 if (matches_pack_name(p, *ig))
1896                                         break;
1897                         if (*ig)
1898                                 goto next;
1899                 }
1901                 if (p->num_bad_objects) {
1902                         unsigned i;
1903                         for (i = 0; i < p->num_bad_objects; i++)
1904                                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1905                                         goto next;
1906                 }
1908                 offset = find_pack_entry_one(sha1, p);
1909                 if (offset) {
1910                         /*
1911                          * We are about to tell the caller where they can
1912                          * locate the requested object.  We better make
1913                          * sure the packfile is still here and can be
1914                          * accessed before supplying that answer, as
1915                          * it may have been deleted since the index
1916                          * was loaded!
1917                          */
1918                         if (p->pack_fd == -1 && open_packed_git(p)) {
1919                                 error("packfile %s cannot be accessed", p->pack_name);
1920                                 goto next;
1921                         }
1922                         e->offset = offset;
1923                         e->p = p;
1924                         hashcpy(e->sha1, sha1);
1925                         last_found = p;
1926                         return 1;
1927                 }
1929                 next:
1930                 if (p == last_found)
1931                         p = packed_git;
1932                 else
1933                         p = p->next;
1934                 if (p == last_found)
1935                         p = p->next;
1936         } while (p);
1937         return 0;
1940 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1942         return find_pack_ent(sha1, e, NULL);
1945 static int find_kept_pack_entry(const unsigned char *sha1, struct pack_entry *e,
1946                                 const struct rev_info *revs)
1948         return find_pack_ent(sha1, e, revs);
1951 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1952                                   struct packed_git *packs)
1954         struct packed_git *p;
1956         for (p = packs; p; p = p->next) {
1957                 if (find_pack_entry_one(sha1, p))
1958                         return p;
1959         }
1960         return NULL;
1964 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1966         int status;
1967         unsigned long mapsize, size;
1968         void *map;
1969         z_stream stream;
1970         char hdr[32];
1972         map = map_sha1_file(sha1, &mapsize);
1973         if (!map)
1974                 return error("unable to find %s", sha1_to_hex(sha1));
1975         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1976                 status = error("unable to unpack %s header",
1977                                sha1_to_hex(sha1));
1978         else if ((status = parse_sha1_header(hdr, &size)) < 0)
1979                 status = error("unable to parse %s header", sha1_to_hex(sha1));
1980         else if (sizep)
1981                 *sizep = size;
1982         inflateEnd(&stream);
1983         munmap(map, mapsize);
1984         return status;
1987 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1989         struct pack_entry e;
1990         int status;
1992         if (!find_pack_entry(sha1, &e)) {
1993                 /* Most likely it's a loose object. */
1994                 status = sha1_loose_object_info(sha1, sizep);
1995                 if (status >= 0)
1996                         return status;
1998                 /* Not a loose object; someone else may have just packed it. */
1999                 reprepare_packed_git();
2000                 if (!find_pack_entry(sha1, &e))
2001                         return status;
2002         }
2003         return packed_object_info(e.p, e.offset, sizep);
2006 static void *read_packed_sha1(const unsigned char *sha1,
2007                               enum object_type *type, unsigned long *size)
2009         struct pack_entry e;
2010         void *data;
2012         if (!find_pack_entry(sha1, &e))
2013                 return NULL;
2014         data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2015         if (!data) {
2016                 /*
2017                  * We're probably in deep shit, but let's try to fetch
2018                  * the required object anyway from another pack or loose.
2019                  * This should happen only in the presence of a corrupted
2020                  * pack, and is better than failing outright.
2021                  */
2022                 error("failed to read object %s at offset %"PRIuMAX" from %s",
2023                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2024                 mark_bad_packed_object(e.p, sha1);
2025                 data = read_object(sha1, type, size);
2026         }
2027         return data;
2030 /*
2031  * This is meant to hold a *small* number of objects that you would
2032  * want read_sha1_file() to be able to return, but yet you do not want
2033  * to write them into the object store (e.g. a browse-only
2034  * application).
2035  */
2036 static struct cached_object {
2037         unsigned char sha1[20];
2038         enum object_type type;
2039         void *buf;
2040         unsigned long size;
2041 } *cached_objects;
2042 static int cached_object_nr, cached_object_alloc;
2044 static struct cached_object empty_tree = {
2045         /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
2046         "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
2047         "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
2048         OBJ_TREE,
2049         "",
2050         0
2051 };
2053 static struct cached_object *find_cached_object(const unsigned char *sha1)
2055         int i;
2056         struct cached_object *co = cached_objects;
2058         for (i = 0; i < cached_object_nr; i++, co++) {
2059                 if (!hashcmp(co->sha1, sha1))
2060                         return co;
2061         }
2062         if (!hashcmp(sha1, empty_tree.sha1))
2063                 return &empty_tree;
2064         return NULL;
2067 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2068                       unsigned char *sha1)
2070         struct cached_object *co;
2072         hash_sha1_file(buf, len, typename(type), sha1);
2073         if (has_sha1_file(sha1) || find_cached_object(sha1))
2074                 return 0;
2075         if (cached_object_alloc <= cached_object_nr) {
2076                 cached_object_alloc = alloc_nr(cached_object_alloc);
2077                 cached_objects = xrealloc(cached_objects,
2078                                           sizeof(*cached_objects) *
2079                                           cached_object_alloc);
2080         }
2081         co = &cached_objects[cached_object_nr++];
2082         co->size = len;
2083         co->type = type;
2084         co->buf = xmalloc(len);
2085         memcpy(co->buf, buf, len);
2086         hashcpy(co->sha1, sha1);
2087         return 0;
2090 void *read_object(const unsigned char *sha1, enum object_type *type,
2091                   unsigned long *size)
2093         unsigned long mapsize;
2094         void *map, *buf;
2095         struct cached_object *co;
2097         co = find_cached_object(sha1);
2098         if (co) {
2099                 *type = co->type;
2100                 *size = co->size;
2101                 return xmemdupz(co->buf, co->size);
2102         }
2104         buf = read_packed_sha1(sha1, type, size);
2105         if (buf)
2106                 return buf;
2107         map = map_sha1_file(sha1, &mapsize);
2108         if (map) {
2109                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2110                 munmap(map, mapsize);
2111                 return buf;
2112         }
2113         reprepare_packed_git();
2114         return read_packed_sha1(sha1, type, size);
2117 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
2118                      unsigned long *size)
2120         void *data = read_object(sha1, type, size);
2121         /* legacy behavior is to die on corrupted objects */
2122         if (!data && (has_loose_object(sha1) || has_packed_and_bad(sha1)))
2123                 die("object %s is corrupted", sha1_to_hex(sha1));
2124         return data;
2127 void *read_object_with_reference(const unsigned char *sha1,
2128                                  const char *required_type_name,
2129                                  unsigned long *size,
2130                                  unsigned char *actual_sha1_return)
2132         enum object_type type, required_type;
2133         void *buffer;
2134         unsigned long isize;
2135         unsigned char actual_sha1[20];
2137         required_type = type_from_string(required_type_name);
2138         hashcpy(actual_sha1, sha1);
2139         while (1) {
2140                 int ref_length = -1;
2141                 const char *ref_type = NULL;
2143                 buffer = read_sha1_file(actual_sha1, &type, &isize);
2144                 if (!buffer)
2145                         return NULL;
2146                 if (type == required_type) {
2147                         *size = isize;
2148                         if (actual_sha1_return)
2149                                 hashcpy(actual_sha1_return, actual_sha1);
2150                         return buffer;
2151                 }
2152                 /* Handle references */
2153                 else if (type == OBJ_COMMIT)
2154                         ref_type = "tree ";
2155                 else if (type == OBJ_TAG)
2156                         ref_type = "object ";
2157                 else {
2158                         free(buffer);
2159                         return NULL;
2160                 }
2161                 ref_length = strlen(ref_type);
2163                 if (ref_length + 40 > isize ||
2164                     memcmp(buffer, ref_type, ref_length) ||
2165                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2166                         free(buffer);
2167                         return NULL;
2168                 }
2169                 free(buffer);
2170                 /* Now we have the ID of the referred-to object in
2171                  * actual_sha1.  Check again. */
2172         }
2175 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2176                                     const char *type, unsigned char *sha1,
2177                                     char *hdr, int *hdrlen)
2179         SHA_CTX c;
2181         /* Generate the header */
2182         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2184         /* Sha1.. */
2185         SHA1_Init(&c);
2186         SHA1_Update(&c, hdr, *hdrlen);
2187         SHA1_Update(&c, buf, len);
2188         SHA1_Final(sha1, &c);
2191 /*
2192  * Move the just written object into its final resting place
2193  */
2194 int move_temp_to_file(const char *tmpfile, const char *filename)
2196         int ret = 0;
2197         if (link(tmpfile, filename))
2198                 ret = errno;
2200         /*
2201          * Coda hack - coda doesn't like cross-directory links,
2202          * so we fall back to a rename, which will mean that it
2203          * won't be able to check collisions, but that's not a
2204          * big deal.
2205          *
2206          * The same holds for FAT formatted media.
2207          *
2208          * When this succeeds, we just return 0. We have nothing
2209          * left to unlink.
2210          */
2211         if (ret && ret != EEXIST) {
2212                 if (!rename(tmpfile, filename))
2213                         return 0;
2214                 ret = errno;
2215         }
2216         unlink(tmpfile);
2217         if (ret) {
2218                 if (ret != EEXIST) {
2219                         return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2220                 }
2221                 /* FIXME!!! Collision check here ? */
2222         }
2224         return 0;
2227 static int write_buffer(int fd, const void *buf, size_t len)
2229         if (write_in_full(fd, buf, len) < 0)
2230                 return error("file write error (%s)", strerror(errno));
2231         return 0;
2234 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2235                    unsigned char *sha1)
2237         char hdr[32];
2238         int hdrlen;
2239         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2240         return 0;
2243 /* Finalize a file on disk, and close it. */
2244 static void close_sha1_file(int fd)
2246         if (fsync_object_files)
2247                 fsync_or_die(fd, "sha1 file");
2248         fchmod(fd, 0444);
2249         if (close(fd) != 0)
2250                 die("unable to write sha1 file");
2253 /* Size of directory component, including the ending '/' */
2254 static inline int directory_size(const char *filename)
2256         const char *s = strrchr(filename, '/');
2257         if (!s)
2258                 return 0;
2259         return s - filename + 1;
2262 /*
2263  * This creates a temporary file in the same directory as the final
2264  * 'filename'
2265  *
2266  * We want to avoid cross-directory filename renames, because those
2267  * can have problems on various filesystems (FAT, NFS, Coda).
2268  */
2269 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2271         int fd, dirlen = directory_size(filename);
2273         if (dirlen + 20 > bufsiz) {
2274                 errno = ENAMETOOLONG;
2275                 return -1;
2276         }
2277         memcpy(buffer, filename, dirlen);
2278         strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2279         fd = mkstemp(buffer);
2280         if (fd < 0 && dirlen && errno == ENOENT) {
2281                 /* Make sure the directory exists */
2282                 memcpy(buffer, filename, dirlen);
2283                 buffer[dirlen-1] = 0;
2284                 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2285                         return -1;
2287                 /* Try again */
2288                 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2289                 fd = mkstemp(buffer);
2290         }
2291         return fd;
2294 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2295                               void *buf, unsigned long len, time_t mtime)
2297         int fd, size, ret;
2298         unsigned char *compressed;
2299         z_stream stream;
2300         char *filename;
2301         static char tmpfile[PATH_MAX];
2303         filename = sha1_file_name(sha1);
2304         fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2305         if (fd < 0) {
2306                 if (errno == EACCES)
2307                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2308                 else
2309                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2310         }
2312         /* Set it up */
2313         memset(&stream, 0, sizeof(stream));
2314         deflateInit(&stream, zlib_compression_level);
2315         size = 8 + deflateBound(&stream, len+hdrlen);
2316         compressed = xmalloc(size);
2318         /* Compress it */
2319         stream.next_out = compressed;
2320         stream.avail_out = size;
2322         /* First header.. */
2323         stream.next_in = (unsigned char *)hdr;
2324         stream.avail_in = hdrlen;
2325         while (deflate(&stream, 0) == Z_OK)
2326                 /* nothing */;
2328         /* Then the data itself.. */
2329         stream.next_in = buf;
2330         stream.avail_in = len;
2331         ret = deflate(&stream, Z_FINISH);
2332         if (ret != Z_STREAM_END)
2333                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2335         ret = deflateEnd(&stream);
2336         if (ret != Z_OK)
2337                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2339         size = stream.total_out;
2341         if (write_buffer(fd, compressed, size) < 0)
2342                 die("unable to write sha1 file");
2343         close_sha1_file(fd);
2344         free(compressed);
2346         if (mtime) {
2347                 struct utimbuf utb;
2348                 utb.actime = mtime;
2349                 utb.modtime = mtime;
2350                 if (utime(tmpfile, &utb) < 0)
2351                         warning("failed utime() on %s: %s",
2352                                 tmpfile, strerror(errno));
2353         }
2355         return move_temp_to_file(tmpfile, filename);
2358 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2360         unsigned char sha1[20];
2361         char hdr[32];
2362         int hdrlen;
2364         /* Normally if we have it in the pack then we do not bother writing
2365          * it out into .git/objects/??/?{38} file.
2366          */
2367         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2368         if (returnsha1)
2369                 hashcpy(returnsha1, sha1);
2370         if (has_sha1_file(sha1))
2371                 return 0;
2372         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2375 int force_object_loose(const unsigned char *sha1, time_t mtime)
2377         void *buf;
2378         unsigned long len;
2379         enum object_type type;
2380         char hdr[32];
2381         int hdrlen;
2382         int ret;
2384         if (has_loose_object(sha1))
2385                 return 0;
2386         buf = read_packed_sha1(sha1, &type, &len);
2387         if (!buf)
2388                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2389         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2390         ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2391         free(buf);
2393         return ret;
2396 int has_pack_index(const unsigned char *sha1)
2398         struct stat st;
2399         if (stat(sha1_pack_index_name(sha1), &st))
2400                 return 0;
2401         return 1;
2404 int has_pack_file(const unsigned char *sha1)
2406         struct stat st;
2407         if (stat(sha1_pack_name(sha1), &st))
2408                 return 0;
2409         return 1;
2412 int has_sha1_pack(const unsigned char *sha1)
2414         struct pack_entry e;
2415         return find_pack_entry(sha1, &e);
2418 int has_sha1_kept_pack(const unsigned char *sha1, const struct rev_info *revs)
2420         struct pack_entry e;
2421         return find_kept_pack_entry(sha1, &e, revs);
2424 int has_sha1_file(const unsigned char *sha1)
2426         struct pack_entry e;
2428         if (find_pack_entry(sha1, &e))
2429                 return 1;
2430         return has_loose_object(sha1);
2433 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2435         struct strbuf buf;
2436         int ret;
2438         strbuf_init(&buf, 0);
2439         if (strbuf_read(&buf, fd, 4096) < 0) {
2440                 strbuf_release(&buf);
2441                 return -1;
2442         }
2444         if (!type)
2445                 type = blob_type;
2446         if (write_object)
2447                 ret = write_sha1_file(buf.buf, buf.len, type, sha1);
2448         else
2449                 ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2450         strbuf_release(&buf);
2452         return ret;
2455 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2456              enum object_type type, const char *path)
2458         size_t size = xsize_t(st->st_size);
2459         void *buf = NULL;
2460         int ret, re_allocated = 0;
2462         if (size)
2463                 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2464         close(fd);
2466         if (!type)
2467                 type = OBJ_BLOB;
2469         /*
2470          * Convert blobs to git internal format
2471          */
2472         if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2473                 struct strbuf nbuf;
2474                 strbuf_init(&nbuf, 0);
2475                 if (convert_to_git(path, buf, size, &nbuf,
2476                                    write_object ? safe_crlf : 0)) {
2477                         munmap(buf, size);
2478                         buf = strbuf_detach(&nbuf, &size);
2479                         re_allocated = 1;
2480                 }
2481         }
2483         if (write_object)
2484                 ret = write_sha1_file(buf, size, typename(type), sha1);
2485         else
2486                 ret = hash_sha1_file(buf, size, typename(type), sha1);
2487         if (re_allocated) {
2488                 free(buf);
2489                 return ret;
2490         }
2491         if (size)
2492                 munmap(buf, size);
2493         return ret;
2496 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2498         int fd;
2499         char *target;
2500         size_t len;
2502         switch (st->st_mode & S_IFMT) {
2503         case S_IFREG:
2504                 fd = open(path, O_RDONLY);
2505                 if (fd < 0)
2506                         return error("open(\"%s\"): %s", path,
2507                                      strerror(errno));
2508                 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2509                         return error("%s: failed to insert into database",
2510                                      path);
2511                 break;
2512         case S_IFLNK:
2513                 len = xsize_t(st->st_size);
2514                 target = xmalloc(len + 1);
2515                 if (readlink(path, target, len + 1) != st->st_size) {
2516                         char *errstr = strerror(errno);
2517                         free(target);
2518                         return error("readlink(\"%s\"): %s", path,
2519                                      errstr);
2520                 }
2521                 if (!write_object)
2522                         hash_sha1_file(target, len, blob_type, sha1);
2523                 else if (write_sha1_file(target, len, blob_type, sha1))
2524                         return error("%s: failed to insert into database",
2525                                      path);
2526                 free(target);
2527                 break;
2528         case S_IFDIR:
2529                 return resolve_gitlink_ref(path, "HEAD", sha1);
2530         default:
2531                 return error("%s: unsupported file type", path);
2532         }
2533         return 0;
2536 int read_pack_header(int fd, struct pack_header *header)
2538         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2539                 /* "eof before pack header was fully read" */
2540                 return PH_ERROR_EOF;
2542         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2543                 /* "protocol error (pack signature mismatch detected)" */
2544                 return PH_ERROR_PACK_SIGNATURE;
2545         if (!pack_version_ok(header->hdr_version))
2546                 /* "protocol error (pack version unsupported)" */
2547                 return PH_ERROR_PROTOCOL;
2548         return 0;