coccinelle: make use of the "type" FREE_AND_NULL() rule
[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 "string-list.h"
11 #include "lockfile.h"
12 #include "delta.h"
13 #include "pack.h"
14 #include "blob.h"
15 #include "commit.h"
16 #include "run-command.h"
17 #include "tag.h"
18 #include "tree.h"
19 #include "tree-walk.h"
20 #include "refs.h"
21 #include "pack-revindex.h"
22 #include "sha1-lookup.h"
23 #include "bulk-checkin.h"
24 #include "streaming.h"
25 #include "dir.h"
26 #include "mru.h"
27 #include "list.h"
28 #include "mergesort.h"
29 #include "quote.h"
30
31 #define SZ_FMT PRIuMAX
32 static inline uintmax_t sz_fmt(size_t s) { return s; }
33
34 const unsigned char null_sha1[20];
35 const struct object_id null_oid;
36 const struct object_id empty_tree_oid = {
37         EMPTY_TREE_SHA1_BIN_LITERAL
38 };
39 const struct object_id empty_blob_oid = {
40         EMPTY_BLOB_SHA1_BIN_LITERAL
41 };
42
43 /*
44  * This is meant to hold a *small* number of objects that you would
45  * want read_sha1_file() to be able to return, but yet you do not want
46  * to write them into the object store (e.g. a browse-only
47  * application).
48  */
49 static struct cached_object {
50         unsigned char sha1[20];
51         enum object_type type;
52         void *buf;
53         unsigned long size;
54 } *cached_objects;
55 static int cached_object_nr, cached_object_alloc;
56
57 static struct cached_object empty_tree = {
58         EMPTY_TREE_SHA1_BIN_LITERAL,
59         OBJ_TREE,
60         "",
61         0
62 };
63
64 static struct cached_object *find_cached_object(const unsigned char *sha1)
65 {
66         int i;
67         struct cached_object *co = cached_objects;
68
69         for (i = 0; i < cached_object_nr; i++, co++) {
70                 if (!hashcmp(co->sha1, sha1))
71                         return co;
72         }
73         if (!hashcmp(sha1, empty_tree.sha1))
74                 return &empty_tree;
75         return NULL;
76 }
77
78 int mkdir_in_gitdir(const char *path)
79 {
80         if (mkdir(path, 0777)) {
81                 int saved_errno = errno;
82                 struct stat st;
83                 struct strbuf sb = STRBUF_INIT;
84
85                 if (errno != EEXIST)
86                         return -1;
87                 /*
88                  * Are we looking at a path in a symlinked worktree
89                  * whose original repository does not yet have it?
90                  * e.g. .git/rr-cache pointing at its original
91                  * repository in which the user hasn't performed any
92                  * conflict resolution yet?
93                  */
94                 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
95                     strbuf_readlink(&sb, path, st.st_size) ||
96                     !is_absolute_path(sb.buf) ||
97                     mkdir(sb.buf, 0777)) {
98                         strbuf_release(&sb);
99                         errno = saved_errno;
100                         return -1;
101                 }
102                 strbuf_release(&sb);
103         }
104         return adjust_shared_perm(path);
105 }
106
107 enum scld_error safe_create_leading_directories(char *path)
108 {
109         char *next_component = path + offset_1st_component(path);
110         enum scld_error ret = SCLD_OK;
111
112         while (ret == SCLD_OK && next_component) {
113                 struct stat st;
114                 char *slash = next_component, slash_character;
115
116                 while (*slash && !is_dir_sep(*slash))
117                         slash++;
118
119                 if (!*slash)
120                         break;
121
122                 next_component = slash + 1;
123                 while (is_dir_sep(*next_component))
124                         next_component++;
125                 if (!*next_component)
126                         break;
127
128                 slash_character = *slash;
129                 *slash = '\0';
130                 if (!stat(path, &st)) {
131                         /* path exists */
132                         if (!S_ISDIR(st.st_mode)) {
133                                 errno = ENOTDIR;
134                                 ret = SCLD_EXISTS;
135                         }
136                 } else if (mkdir(path, 0777)) {
137                         if (errno == EEXIST &&
138                             !stat(path, &st) && S_ISDIR(st.st_mode))
139                                 ; /* somebody created it since we checked */
140                         else if (errno == ENOENT)
141                                 /*
142                                  * Either mkdir() failed because
143                                  * somebody just pruned the containing
144                                  * directory, or stat() failed because
145                                  * the file that was in our way was
146                                  * just removed.  Either way, inform
147                                  * the caller that it might be worth
148                                  * trying again:
149                                  */
150                                 ret = SCLD_VANISHED;
151                         else
152                                 ret = SCLD_FAILED;
153                 } else if (adjust_shared_perm(path)) {
154                         ret = SCLD_PERMS;
155                 }
156                 *slash = slash_character;
157         }
158         return ret;
159 }
160
161 enum scld_error safe_create_leading_directories_const(const char *path)
162 {
163         int save_errno;
164         /* path points to cache entries, so xstrdup before messing with it */
165         char *buf = xstrdup(path);
166         enum scld_error result = safe_create_leading_directories(buf);
167
168         save_errno = errno;
169         free(buf);
170         errno = save_errno;
171         return result;
172 }
173
174 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
175 {
176         /*
177          * The number of times we will try to remove empty directories
178          * in the way of path. This is only 1 because if another
179          * process is racily creating directories that conflict with
180          * us, we don't want to fight against them.
181          */
182         int remove_directories_remaining = 1;
183
184         /*
185          * The number of times that we will try to create the
186          * directories containing path. We are willing to attempt this
187          * more than once, because another process could be trying to
188          * clean up empty directories at the same time as we are
189          * trying to create them.
190          */
191         int create_directories_remaining = 3;
192
193         /* A scratch copy of path, filled lazily if we need it: */
194         struct strbuf path_copy = STRBUF_INIT;
195
196         int ret, save_errno;
197
198         /* Sanity check: */
199         assert(*path);
200
201 retry_fn:
202         ret = fn(path, cb);
203         save_errno = errno;
204         if (!ret)
205                 goto out;
206
207         if (errno == EISDIR && remove_directories_remaining-- > 0) {
208                 /*
209                  * A directory is in the way. Maybe it is empty; try
210                  * to remove it:
211                  */
212                 if (!path_copy.len)
213                         strbuf_addstr(&path_copy, path);
214
215                 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
216                         goto retry_fn;
217         } else if (errno == ENOENT && create_directories_remaining-- > 0) {
218                 /*
219                  * Maybe the containing directory didn't exist, or
220                  * maybe it was just deleted by a process that is
221                  * racing with us to clean up empty directories. Try
222                  * to create it:
223                  */
224                 enum scld_error scld_result;
225
226                 if (!path_copy.len)
227                         strbuf_addstr(&path_copy, path);
228
229                 do {
230                         scld_result = safe_create_leading_directories(path_copy.buf);
231                         if (scld_result == SCLD_OK)
232                                 goto retry_fn;
233                 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
234         }
235
236 out:
237         strbuf_release(&path_copy);
238         errno = save_errno;
239         return ret;
240 }
241
242 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
243 {
244         int i;
245         for (i = 0; i < 20; i++) {
246                 static char hex[] = "0123456789abcdef";
247                 unsigned int val = sha1[i];
248                 strbuf_addch(buf, hex[val >> 4]);
249                 strbuf_addch(buf, hex[val & 0xf]);
250                 if (!i)
251                         strbuf_addch(buf, '/');
252         }
253 }
254
255 const char *sha1_file_name(const unsigned char *sha1)
256 {
257         static struct strbuf buf = STRBUF_INIT;
258
259         strbuf_reset(&buf);
260         strbuf_addf(&buf, "%s/", get_object_directory());
261
262         fill_sha1_path(&buf, sha1);
263         return buf.buf;
264 }
265
266 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
267 {
268         strbuf_setlen(&alt->scratch, alt->base_len);
269         return &alt->scratch;
270 }
271
272 static const char *alt_sha1_path(struct alternate_object_database *alt,
273                                  const unsigned char *sha1)
274 {
275         struct strbuf *buf = alt_scratch_buf(alt);
276         fill_sha1_path(buf, sha1);
277         return buf->buf;
278 }
279
280  char *odb_pack_name(struct strbuf *buf,
281                      const unsigned char *sha1,
282                      const char *ext)
283 {
284         strbuf_reset(buf);
285         strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
286                     sha1_to_hex(sha1), ext);
287         return buf->buf;
288 }
289
290 char *sha1_pack_name(const unsigned char *sha1)
291 {
292         static struct strbuf buf = STRBUF_INIT;
293         return odb_pack_name(&buf, sha1, "pack");
294 }
295
296 char *sha1_pack_index_name(const unsigned char *sha1)
297 {
298         static struct strbuf buf = STRBUF_INIT;
299         return odb_pack_name(&buf, sha1, "idx");
300 }
301
302 struct alternate_object_database *alt_odb_list;
303 static struct alternate_object_database **alt_odb_tail;
304
305 /*
306  * Return non-zero iff the path is usable as an alternate object database.
307  */
308 static int alt_odb_usable(struct strbuf *path, const char *normalized_objdir)
309 {
310         struct alternate_object_database *alt;
311
312         /* Detect cases where alternate disappeared */
313         if (!is_directory(path->buf)) {
314                 error("object directory %s does not exist; "
315                       "check .git/objects/info/alternates.",
316                       path->buf);
317                 return 0;
318         }
319
320         /*
321          * Prevent the common mistake of listing the same
322          * thing twice, or object directory itself.
323          */
324         for (alt = alt_odb_list; alt; alt = alt->next) {
325                 if (!fspathcmp(path->buf, alt->path))
326                         return 0;
327         }
328         if (!fspathcmp(path->buf, normalized_objdir))
329                 return 0;
330
331         return 1;
332 }
333
334 /*
335  * Prepare alternate object database registry.
336  *
337  * The variable alt_odb_list points at the list of struct
338  * alternate_object_database.  The elements on this list come from
339  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
340  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
341  * whose contents is similar to that environment variable but can be
342  * LF separated.  Its base points at a statically allocated buffer that
343  * contains "/the/directory/corresponding/to/.git/objects/...", while
344  * its name points just after the slash at the end of ".git/objects/"
345  * in the example above, and has enough space to hold 40-byte hex
346  * SHA1, an extra slash for the first level indirection, and the
347  * terminating NUL.
348  */
349 static int link_alt_odb_entry(const char *entry, const char *relative_base,
350         int depth, const char *normalized_objdir)
351 {
352         struct alternate_object_database *ent;
353         struct strbuf pathbuf = STRBUF_INIT;
354
355         if (!is_absolute_path(entry) && relative_base) {
356                 strbuf_realpath(&pathbuf, relative_base, 1);
357                 strbuf_addch(&pathbuf, '/');
358         }
359         strbuf_addstr(&pathbuf, entry);
360
361         if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
362                 error("unable to normalize alternate object path: %s",
363                       pathbuf.buf);
364                 strbuf_release(&pathbuf);
365                 return -1;
366         }
367
368         /*
369          * The trailing slash after the directory name is given by
370          * this function at the end. Remove duplicates.
371          */
372         while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
373                 strbuf_setlen(&pathbuf, pathbuf.len - 1);
374
375         if (!alt_odb_usable(&pathbuf, normalized_objdir)) {
376                 strbuf_release(&pathbuf);
377                 return -1;
378         }
379
380         ent = alloc_alt_odb(pathbuf.buf);
381
382         /* add the alternate entry */
383         *alt_odb_tail = ent;
384         alt_odb_tail = &(ent->next);
385         ent->next = NULL;
386
387         /* recursively add alternates */
388         read_info_alternates(pathbuf.buf, depth + 1);
389
390         strbuf_release(&pathbuf);
391         return 0;
392 }
393
394 static const char *parse_alt_odb_entry(const char *string,
395                                        int sep,
396                                        struct strbuf *out)
397 {
398         const char *end;
399
400         strbuf_reset(out);
401
402         if (*string == '#') {
403                 /* comment; consume up to next separator */
404                 end = strchrnul(string, sep);
405         } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
406                 /*
407                  * quoted path; unquote_c_style has copied the
408                  * data for us and set "end". Broken quoting (e.g.,
409                  * an entry that doesn't end with a quote) falls
410                  * back to the unquoted case below.
411                  */
412         } else {
413                 /* normal, unquoted path */
414                 end = strchrnul(string, sep);
415                 strbuf_add(out, string, end - string);
416         }
417
418         if (*end)
419                 end++;
420         return end;
421 }
422
423 static void link_alt_odb_entries(const char *alt, int len, int sep,
424                                  const char *relative_base, int depth)
425 {
426         struct strbuf objdirbuf = STRBUF_INIT;
427         struct strbuf entry = STRBUF_INIT;
428
429         if (depth > 5) {
430                 error("%s: ignoring alternate object stores, nesting too deep.",
431                                 relative_base);
432                 return;
433         }
434
435         strbuf_add_absolute_path(&objdirbuf, get_object_directory());
436         if (strbuf_normalize_path(&objdirbuf) < 0)
437                 die("unable to normalize object directory: %s",
438                     objdirbuf.buf);
439
440         while (*alt) {
441                 alt = parse_alt_odb_entry(alt, sep, &entry);
442                 if (!entry.len)
443                         continue;
444                 link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf);
445         }
446         strbuf_release(&entry);
447         strbuf_release(&objdirbuf);
448 }
449
450 void read_info_alternates(const char * relative_base, int depth)
451 {
452         char *map;
453         size_t mapsz;
454         struct stat st;
455         char *path;
456         int fd;
457
458         path = xstrfmt("%s/info/alternates", relative_base);
459         fd = git_open(path);
460         free(path);
461         if (fd < 0)
462                 return;
463         if (fstat(fd, &st) || (st.st_size == 0)) {
464                 close(fd);
465                 return;
466         }
467         mapsz = xsize_t(st.st_size);
468         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
469         close(fd);
470
471         link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
472
473         munmap(map, mapsz);
474 }
475
476 struct alternate_object_database *alloc_alt_odb(const char *dir)
477 {
478         struct alternate_object_database *ent;
479
480         FLEX_ALLOC_STR(ent, path, dir);
481         strbuf_init(&ent->scratch, 0);
482         strbuf_addf(&ent->scratch, "%s/", dir);
483         ent->base_len = ent->scratch.len;
484
485         return ent;
486 }
487
488 void add_to_alternates_file(const char *reference)
489 {
490         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
491         char *alts = git_pathdup("objects/info/alternates");
492         FILE *in, *out;
493
494         hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
495         out = fdopen_lock_file(lock, "w");
496         if (!out)
497                 die_errno("unable to fdopen alternates lockfile");
498
499         in = fopen(alts, "r");
500         if (in) {
501                 struct strbuf line = STRBUF_INIT;
502                 int found = 0;
503
504                 while (strbuf_getline(&line, in) != EOF) {
505                         if (!strcmp(reference, line.buf)) {
506                                 found = 1;
507                                 break;
508                         }
509                         fprintf_or_die(out, "%s\n", line.buf);
510                 }
511
512                 strbuf_release(&line);
513                 fclose(in);
514
515                 if (found) {
516                         rollback_lock_file(lock);
517                         lock = NULL;
518                 }
519         }
520         else if (errno != ENOENT)
521                 die_errno("unable to read alternates file");
522
523         if (lock) {
524                 fprintf_or_die(out, "%s\n", reference);
525                 if (commit_lock_file(lock))
526                         die_errno("unable to move new alternates file into place");
527                 if (alt_odb_tail)
528                         link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
529         }
530         free(alts);
531 }
532
533 void add_to_alternates_memory(const char *reference)
534 {
535         /*
536          * Make sure alternates are initialized, or else our entry may be
537          * overwritten when they are.
538          */
539         prepare_alt_odb();
540
541         link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
542 }
543
544 /*
545  * Compute the exact path an alternate is at and returns it. In case of
546  * error NULL is returned and the human readable error is added to `err`
547  * `path` may be relative and should point to $GITDIR.
548  * `err` must not be null.
549  */
550 char *compute_alternate_path(const char *path, struct strbuf *err)
551 {
552         char *ref_git = NULL;
553         const char *repo, *ref_git_s;
554         int seen_error = 0;
555
556         ref_git_s = real_path_if_valid(path);
557         if (!ref_git_s) {
558                 seen_error = 1;
559                 strbuf_addf(err, _("path '%s' does not exist"), path);
560                 goto out;
561         } else
562                 /*
563                  * Beware: read_gitfile(), real_path() and mkpath()
564                  * return static buffer
565                  */
566                 ref_git = xstrdup(ref_git_s);
567
568         repo = read_gitfile(ref_git);
569         if (!repo)
570                 repo = read_gitfile(mkpath("%s/.git", ref_git));
571         if (repo) {
572                 free(ref_git);
573                 ref_git = xstrdup(repo);
574         }
575
576         if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
577                 char *ref_git_git = mkpathdup("%s/.git", ref_git);
578                 free(ref_git);
579                 ref_git = ref_git_git;
580         } else if (!is_directory(mkpath("%s/objects", ref_git))) {
581                 struct strbuf sb = STRBUF_INIT;
582                 seen_error = 1;
583                 if (get_common_dir(&sb, ref_git)) {
584                         strbuf_addf(err,
585                                     _("reference repository '%s' as a linked "
586                                       "checkout is not supported yet."),
587                                     path);
588                         goto out;
589                 }
590
591                 strbuf_addf(err, _("reference repository '%s' is not a "
592                                         "local repository."), path);
593                 goto out;
594         }
595
596         if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
597                 strbuf_addf(err, _("reference repository '%s' is shallow"),
598                             path);
599                 seen_error = 1;
600                 goto out;
601         }
602
603         if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
604                 strbuf_addf(err,
605                             _("reference repository '%s' is grafted"),
606                             path);
607                 seen_error = 1;
608                 goto out;
609         }
610
611 out:
612         if (seen_error) {
613                 FREE_AND_NULL(ref_git);
614         }
615
616         return ref_git;
617 }
618
619 int foreach_alt_odb(alt_odb_fn fn, void *cb)
620 {
621         struct alternate_object_database *ent;
622         int r = 0;
623
624         prepare_alt_odb();
625         for (ent = alt_odb_list; ent; ent = ent->next) {
626                 r = fn(ent, cb);
627                 if (r)
628                         break;
629         }
630         return r;
631 }
632
633 void prepare_alt_odb(void)
634 {
635         const char *alt;
636
637         if (alt_odb_tail)
638                 return;
639
640         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
641         if (!alt) alt = "";
642
643         alt_odb_tail = &alt_odb_list;
644         link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
645
646         read_info_alternates(get_object_directory(), 0);
647 }
648
649 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
650 static int freshen_file(const char *fn)
651 {
652         struct utimbuf t;
653         t.actime = t.modtime = time(NULL);
654         return !utime(fn, &t);
655 }
656
657 /*
658  * All of the check_and_freshen functions return 1 if the file exists and was
659  * freshened (if freshening was requested), 0 otherwise. If they return
660  * 0, you should not assume that it is safe to skip a write of the object (it
661  * either does not exist on disk, or has a stale mtime and may be subject to
662  * pruning).
663  */
664 int check_and_freshen_file(const char *fn, int freshen)
665 {
666         if (access(fn, F_OK))
667                 return 0;
668         if (freshen && !freshen_file(fn))
669                 return 0;
670         return 1;
671 }
672
673 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
674 {
675         return check_and_freshen_file(sha1_file_name(sha1), freshen);
676 }
677
678 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
679 {
680         struct alternate_object_database *alt;
681         prepare_alt_odb();
682         for (alt = alt_odb_list; alt; alt = alt->next) {
683                 const char *path = alt_sha1_path(alt, sha1);
684                 if (check_and_freshen_file(path, freshen))
685                         return 1;
686         }
687         return 0;
688 }
689
690 static int check_and_freshen(const unsigned char *sha1, int freshen)
691 {
692         return check_and_freshen_local(sha1, freshen) ||
693                check_and_freshen_nonlocal(sha1, freshen);
694 }
695
696 int has_loose_object_nonlocal(const unsigned char *sha1)
697 {
698         return check_and_freshen_nonlocal(sha1, 0);
699 }
700
701 static int has_loose_object(const unsigned char *sha1)
702 {
703         return check_and_freshen(sha1, 0);
704 }
705
706 static unsigned int pack_used_ctr;
707 static unsigned int pack_mmap_calls;
708 static unsigned int peak_pack_open_windows;
709 static unsigned int pack_open_windows;
710 static unsigned int pack_open_fds;
711 static unsigned int pack_max_fds;
712 static size_t peak_pack_mapped;
713 static size_t pack_mapped;
714 struct packed_git *packed_git;
715
716 static struct mru packed_git_mru_storage;
717 struct mru *packed_git_mru = &packed_git_mru_storage;
718
719 void pack_report(void)
720 {
721         fprintf(stderr,
722                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
723                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
724                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
725                 sz_fmt(getpagesize()),
726                 sz_fmt(packed_git_window_size),
727                 sz_fmt(packed_git_limit));
728         fprintf(stderr,
729                 "pack_report: pack_used_ctr            = %10u\n"
730                 "pack_report: pack_mmap_calls          = %10u\n"
731                 "pack_report: pack_open_windows        = %10u / %10u\n"
732                 "pack_report: pack_mapped              = "
733                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
734                 pack_used_ctr,
735                 pack_mmap_calls,
736                 pack_open_windows, peak_pack_open_windows,
737                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
738 }
739
740 /*
741  * Open and mmap the index file at path, perform a couple of
742  * consistency checks, then record its information to p.  Return 0 on
743  * success.
744  */
745 static int check_packed_git_idx(const char *path, struct packed_git *p)
746 {
747         void *idx_map;
748         struct pack_idx_header *hdr;
749         size_t idx_size;
750         uint32_t version, nr, i, *index;
751         int fd = git_open(path);
752         struct stat st;
753
754         if (fd < 0)
755                 return -1;
756         if (fstat(fd, &st)) {
757                 close(fd);
758                 return -1;
759         }
760         idx_size = xsize_t(st.st_size);
761         if (idx_size < 4 * 256 + 20 + 20) {
762                 close(fd);
763                 return error("index file %s is too small", path);
764         }
765         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
766         close(fd);
767
768         hdr = idx_map;
769         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
770                 version = ntohl(hdr->idx_version);
771                 if (version < 2 || version > 2) {
772                         munmap(idx_map, idx_size);
773                         return error("index file %s is version %"PRIu32
774                                      " and is not supported by this binary"
775                                      " (try upgrading GIT to a newer version)",
776                                      path, version);
777                 }
778         } else
779                 version = 1;
780
781         nr = 0;
782         index = idx_map;
783         if (version > 1)
784                 index += 2;  /* skip index header */
785         for (i = 0; i < 256; i++) {
786                 uint32_t n = ntohl(index[i]);
787                 if (n < nr) {
788                         munmap(idx_map, idx_size);
789                         return error("non-monotonic index %s", path);
790                 }
791                 nr = n;
792         }
793
794         if (version == 1) {
795                 /*
796                  * Total size:
797                  *  - 256 index entries 4 bytes each
798                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
799                  *  - 20-byte SHA1 of the packfile
800                  *  - 20-byte SHA1 file checksum
801                  */
802                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
803                         munmap(idx_map, idx_size);
804                         return error("wrong index v1 file size in %s", path);
805                 }
806         } else if (version == 2) {
807                 /*
808                  * Minimum size:
809                  *  - 8 bytes of header
810                  *  - 256 index entries 4 bytes each
811                  *  - 20-byte sha1 entry * nr
812                  *  - 4-byte crc entry * nr
813                  *  - 4-byte offset entry * nr
814                  *  - 20-byte SHA1 of the packfile
815                  *  - 20-byte SHA1 file checksum
816                  * And after the 4-byte offset table might be a
817                  * variable sized table containing 8-byte entries
818                  * for offsets larger than 2^31.
819                  */
820                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
821                 unsigned long max_size = min_size;
822                 if (nr)
823                         max_size += (nr - 1)*8;
824                 if (idx_size < min_size || idx_size > max_size) {
825                         munmap(idx_map, idx_size);
826                         return error("wrong index v2 file size in %s", path);
827                 }
828                 if (idx_size != min_size &&
829                     /*
830                      * make sure we can deal with large pack offsets.
831                      * 31-bit signed offset won't be enough, neither
832                      * 32-bit unsigned one will be.
833                      */
834                     (sizeof(off_t) <= 4)) {
835                         munmap(idx_map, idx_size);
836                         return error("pack too large for current definition of off_t in %s", path);
837                 }
838         }
839
840         p->index_version = version;
841         p->index_data = idx_map;
842         p->index_size = idx_size;
843         p->num_objects = nr;
844         return 0;
845 }
846
847 int open_pack_index(struct packed_git *p)
848 {
849         char *idx_name;
850         size_t len;
851         int ret;
852
853         if (p->index_data)
854                 return 0;
855
856         if (!strip_suffix(p->pack_name, ".pack", &len))
857                 die("BUG: pack_name does not end in .pack");
858         idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
859         ret = check_packed_git_idx(idx_name, p);
860         free(idx_name);
861         return ret;
862 }
863
864 static void scan_windows(struct packed_git *p,
865         struct packed_git **lru_p,
866         struct pack_window **lru_w,
867         struct pack_window **lru_l)
868 {
869         struct pack_window *w, *w_l;
870
871         for (w_l = NULL, w = p->windows; w; w = w->next) {
872                 if (!w->inuse_cnt) {
873                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
874                                 *lru_p = p;
875                                 *lru_w = w;
876                                 *lru_l = w_l;
877                         }
878                 }
879                 w_l = w;
880         }
881 }
882
883 static int unuse_one_window(struct packed_git *current)
884 {
885         struct packed_git *p, *lru_p = NULL;
886         struct pack_window *lru_w = NULL, *lru_l = NULL;
887
888         if (current)
889                 scan_windows(current, &lru_p, &lru_w, &lru_l);
890         for (p = packed_git; p; p = p->next)
891                 scan_windows(p, &lru_p, &lru_w, &lru_l);
892         if (lru_p) {
893                 munmap(lru_w->base, lru_w->len);
894                 pack_mapped -= lru_w->len;
895                 if (lru_l)
896                         lru_l->next = lru_w->next;
897                 else
898                         lru_p->windows = lru_w->next;
899                 free(lru_w);
900                 pack_open_windows--;
901                 return 1;
902         }
903         return 0;
904 }
905
906 void release_pack_memory(size_t need)
907 {
908         size_t cur = pack_mapped;
909         while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
910                 ; /* nothing */
911 }
912
913 static void mmap_limit_check(size_t length)
914 {
915         static size_t limit = 0;
916         if (!limit) {
917                 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
918                 if (!limit)
919                         limit = SIZE_MAX;
920         }
921         if (length > limit)
922                 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
923                     (uintmax_t)length, (uintmax_t)limit);
924 }
925
926 void *xmmap_gently(void *start, size_t length,
927                   int prot, int flags, int fd, off_t offset)
928 {
929         void *ret;
930
931         mmap_limit_check(length);
932         ret = mmap(start, length, prot, flags, fd, offset);
933         if (ret == MAP_FAILED) {
934                 if (!length)
935                         return NULL;
936                 release_pack_memory(length);
937                 ret = mmap(start, length, prot, flags, fd, offset);
938         }
939         return ret;
940 }
941
942 void *xmmap(void *start, size_t length,
943         int prot, int flags, int fd, off_t offset)
944 {
945         void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
946         if (ret == MAP_FAILED)
947                 die_errno("mmap failed");
948         return ret;
949 }
950
951 void close_pack_windows(struct packed_git *p)
952 {
953         while (p->windows) {
954                 struct pack_window *w = p->windows;
955
956                 if (w->inuse_cnt)
957                         die("pack '%s' still has open windows to it",
958                             p->pack_name);
959                 munmap(w->base, w->len);
960                 pack_mapped -= w->len;
961                 pack_open_windows--;
962                 p->windows = w->next;
963                 free(w);
964         }
965 }
966
967 static int close_pack_fd(struct packed_git *p)
968 {
969         if (p->pack_fd < 0)
970                 return 0;
971
972         close(p->pack_fd);
973         pack_open_fds--;
974         p->pack_fd = -1;
975
976         return 1;
977 }
978
979 static void close_pack(struct packed_git *p)
980 {
981         close_pack_windows(p);
982         close_pack_fd(p);
983         close_pack_index(p);
984 }
985
986 void close_all_packs(void)
987 {
988         struct packed_git *p;
989
990         for (p = packed_git; p; p = p->next)
991                 if (p->do_not_close)
992                         die("BUG: want to close pack marked 'do-not-close'");
993                 else
994                         close_pack(p);
995 }
996
997
998 /*
999  * The LRU pack is the one with the oldest MRU window, preferring packs
1000  * with no used windows, or the oldest mtime if it has no windows allocated.
1001  */
1002 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
1003 {
1004         struct pack_window *w, *this_mru_w;
1005         int has_windows_inuse = 0;
1006
1007         /*
1008          * Reject this pack if it has windows and the previously selected
1009          * one does not.  If this pack does not have windows, reject
1010          * it if the pack file is newer than the previously selected one.
1011          */
1012         if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
1013                 return;
1014
1015         for (w = this_mru_w = p->windows; w; w = w->next) {
1016                 /*
1017                  * Reject this pack if any of its windows are in use,
1018                  * but the previously selected pack did not have any
1019                  * inuse windows.  Otherwise, record that this pack
1020                  * has windows in use.
1021                  */
1022                 if (w->inuse_cnt) {
1023                         if (*accept_windows_inuse)
1024                                 has_windows_inuse = 1;
1025                         else
1026                                 return;
1027                 }
1028
1029                 if (w->last_used > this_mru_w->last_used)
1030                         this_mru_w = w;
1031
1032                 /*
1033                  * Reject this pack if it has windows that have been
1034                  * used more recently than the previously selected pack.
1035                  * If the previously selected pack had windows inuse and
1036                  * we have not encountered a window in this pack that is
1037                  * inuse, skip this check since we prefer a pack with no
1038                  * inuse windows to one that has inuse windows.
1039                  */
1040                 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
1041                     this_mru_w->last_used > (*mru_w)->last_used)
1042                         return;
1043         }
1044
1045         /*
1046          * Select this pack.
1047          */
1048         *mru_w = this_mru_w;
1049         *lru_p = p;
1050         *accept_windows_inuse = has_windows_inuse;
1051 }
1052
1053 static int close_one_pack(void)
1054 {
1055         struct packed_git *p, *lru_p = NULL;
1056         struct pack_window *mru_w = NULL;
1057         int accept_windows_inuse = 1;
1058
1059         for (p = packed_git; p; p = p->next) {
1060                 if (p->pack_fd == -1)
1061                         continue;
1062                 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
1063         }
1064
1065         if (lru_p)
1066                 return close_pack_fd(lru_p);
1067
1068         return 0;
1069 }
1070
1071 void unuse_pack(struct pack_window **w_cursor)
1072 {
1073         struct pack_window *w = *w_cursor;
1074         if (w) {
1075                 w->inuse_cnt--;
1076                 *w_cursor = NULL;
1077         }
1078 }
1079
1080 void close_pack_index(struct packed_git *p)
1081 {
1082         if (p->index_data) {
1083                 munmap((void *)p->index_data, p->index_size);
1084                 p->index_data = NULL;
1085         }
1086 }
1087
1088 static unsigned int get_max_fd_limit(void)
1089 {
1090 #ifdef RLIMIT_NOFILE
1091         {
1092                 struct rlimit lim;
1093
1094                 if (!getrlimit(RLIMIT_NOFILE, &lim))
1095                         return lim.rlim_cur;
1096         }
1097 #endif
1098
1099 #ifdef _SC_OPEN_MAX
1100         {
1101                 long open_max = sysconf(_SC_OPEN_MAX);
1102                 if (0 < open_max)
1103                         return open_max;
1104                 /*
1105                  * Otherwise, we got -1 for one of the two
1106                  * reasons:
1107                  *
1108                  * (1) sysconf() did not understand _SC_OPEN_MAX
1109                  *     and signaled an error with -1; or
1110                  * (2) sysconf() said there is no limit.
1111                  *
1112                  * We _could_ clear errno before calling sysconf() to
1113                  * tell these two cases apart and return a huge number
1114                  * in the latter case to let the caller cap it to a
1115                  * value that is not so selfish, but letting the
1116                  * fallback OPEN_MAX codepath take care of these cases
1117                  * is a lot simpler.
1118                  */
1119         }
1120 #endif
1121
1122 #ifdef OPEN_MAX
1123         return OPEN_MAX;
1124 #else
1125         return 1; /* see the caller ;-) */
1126 #endif
1127 }
1128
1129 /*
1130  * Do not call this directly as this leaks p->pack_fd on error return;
1131  * call open_packed_git() instead.
1132  */
1133 static int open_packed_git_1(struct packed_git *p)
1134 {
1135         struct stat st;
1136         struct pack_header hdr;
1137         unsigned char sha1[20];
1138         unsigned char *idx_sha1;
1139         long fd_flag;
1140
1141         if (!p->index_data && open_pack_index(p))
1142                 return error("packfile %s index unavailable", p->pack_name);
1143
1144         if (!pack_max_fds) {
1145                 unsigned int max_fds = get_max_fd_limit();
1146
1147                 /* Save 3 for stdin/stdout/stderr, 22 for work */
1148                 if (25 < max_fds)
1149                         pack_max_fds = max_fds - 25;
1150                 else
1151                         pack_max_fds = 1;
1152         }
1153
1154         while (pack_max_fds <= pack_open_fds && close_one_pack())
1155                 ; /* nothing */
1156
1157         p->pack_fd = git_open(p->pack_name);
1158         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
1159                 return -1;
1160         pack_open_fds++;
1161
1162         /* If we created the struct before we had the pack we lack size. */
1163         if (!p->pack_size) {
1164                 if (!S_ISREG(st.st_mode))
1165                         return error("packfile %s not a regular file", p->pack_name);
1166                 p->pack_size = st.st_size;
1167         } else if (p->pack_size != st.st_size)
1168                 return error("packfile %s size changed", p->pack_name);
1169
1170         /* We leave these file descriptors open with sliding mmap;
1171          * there is no point keeping them open across exec(), though.
1172          */
1173         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
1174         if (fd_flag < 0)
1175                 return error("cannot determine file descriptor flags");
1176         fd_flag |= FD_CLOEXEC;
1177         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
1178                 return error("cannot set FD_CLOEXEC");
1179
1180         /* Verify we recognize this pack file format. */
1181         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
1182                 return error("file %s is far too short to be a packfile", p->pack_name);
1183         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
1184                 return error("file %s is not a GIT packfile", p->pack_name);
1185         if (!pack_version_ok(hdr.hdr_version))
1186                 return error("packfile %s is version %"PRIu32" and not"
1187                         " supported (try upgrading GIT to a newer version)",
1188                         p->pack_name, ntohl(hdr.hdr_version));
1189
1190         /* Verify the pack matches its index. */
1191         if (p->num_objects != ntohl(hdr.hdr_entries))
1192                 return error("packfile %s claims to have %"PRIu32" objects"
1193                              " while index indicates %"PRIu32" objects",
1194                              p->pack_name, ntohl(hdr.hdr_entries),
1195                              p->num_objects);
1196         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
1197                 return error("end of packfile %s is unavailable", p->pack_name);
1198         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
1199                 return error("packfile %s signature is unavailable", p->pack_name);
1200         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
1201         if (hashcmp(sha1, idx_sha1))
1202                 return error("packfile %s does not match index", p->pack_name);
1203         return 0;
1204 }
1205
1206 static int open_packed_git(struct packed_git *p)
1207 {
1208         if (!open_packed_git_1(p))
1209                 return 0;
1210         close_pack_fd(p);
1211         return -1;
1212 }
1213
1214 static int in_window(struct pack_window *win, off_t offset)
1215 {
1216         /* We must promise at least 20 bytes (one hash) after the
1217          * offset is available from this window, otherwise the offset
1218          * is not actually in this window and a different window (which
1219          * has that one hash excess) must be used.  This is to support
1220          * the object header and delta base parsing routines below.
1221          */
1222         off_t win_off = win->offset;
1223         return win_off <= offset
1224                 && (offset + 20) <= (win_off + win->len);
1225 }
1226
1227 unsigned char *use_pack(struct packed_git *p,
1228                 struct pack_window **w_cursor,
1229                 off_t offset,
1230                 unsigned long *left)
1231 {
1232         struct pack_window *win = *w_cursor;
1233
1234         /* Since packfiles end in a hash of their content and it's
1235          * pointless to ask for an offset into the middle of that
1236          * hash, and the in_window function above wouldn't match
1237          * don't allow an offset too close to the end of the file.
1238          */
1239         if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1240                 die("packfile %s cannot be accessed", p->pack_name);
1241         if (offset > (p->pack_size - 20))
1242                 die("offset beyond end of packfile (truncated pack?)");
1243         if (offset < 0)
1244                 die(_("offset before end of packfile (broken .idx?)"));
1245
1246         if (!win || !in_window(win, offset)) {
1247                 if (win)
1248                         win->inuse_cnt--;
1249                 for (win = p->windows; win; win = win->next) {
1250                         if (in_window(win, offset))
1251                                 break;
1252                 }
1253                 if (!win) {
1254                         size_t window_align = packed_git_window_size / 2;
1255                         off_t len;
1256
1257                         if (p->pack_fd == -1 && open_packed_git(p))
1258                                 die("packfile %s cannot be accessed", p->pack_name);
1259
1260                         win = xcalloc(1, sizeof(*win));
1261                         win->offset = (offset / window_align) * window_align;
1262                         len = p->pack_size - win->offset;
1263                         if (len > packed_git_window_size)
1264                                 len = packed_git_window_size;
1265                         win->len = (size_t)len;
1266                         pack_mapped += win->len;
1267                         while (packed_git_limit < pack_mapped
1268                                 && unuse_one_window(p))
1269                                 ; /* nothing */
1270                         win->base = xmmap(NULL, win->len,
1271                                 PROT_READ, MAP_PRIVATE,
1272                                 p->pack_fd, win->offset);
1273                         if (win->base == MAP_FAILED)
1274                                 die_errno("packfile %s cannot be mapped",
1275                                           p->pack_name);
1276                         if (!win->offset && win->len == p->pack_size
1277                                 && !p->do_not_close)
1278                                 close_pack_fd(p);
1279                         pack_mmap_calls++;
1280                         pack_open_windows++;
1281                         if (pack_mapped > peak_pack_mapped)
1282                                 peak_pack_mapped = pack_mapped;
1283                         if (pack_open_windows > peak_pack_open_windows)
1284                                 peak_pack_open_windows = pack_open_windows;
1285                         win->next = p->windows;
1286                         p->windows = win;
1287                 }
1288         }
1289         if (win != *w_cursor) {
1290                 win->last_used = pack_used_ctr++;
1291                 win->inuse_cnt++;
1292                 *w_cursor = win;
1293         }
1294         offset -= win->offset;
1295         if (left)
1296                 *left = win->len - xsize_t(offset);
1297         return win->base + offset;
1298 }
1299
1300 static struct packed_git *alloc_packed_git(int extra)
1301 {
1302         struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
1303         memset(p, 0, sizeof(*p));
1304         p->pack_fd = -1;
1305         return p;
1306 }
1307
1308 static void try_to_free_pack_memory(size_t size)
1309 {
1310         release_pack_memory(size);
1311 }
1312
1313 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
1314 {
1315         static int have_set_try_to_free_routine;
1316         struct stat st;
1317         size_t alloc;
1318         struct packed_git *p;
1319
1320         if (!have_set_try_to_free_routine) {
1321                 have_set_try_to_free_routine = 1;
1322                 set_try_to_free_routine(try_to_free_pack_memory);
1323         }
1324
1325         /*
1326          * Make sure a corresponding .pack file exists and that
1327          * the index looks sane.
1328          */
1329         if (!strip_suffix_mem(path, &path_len, ".idx"))
1330                 return NULL;
1331
1332         /*
1333          * ".pack" is long enough to hold any suffix we're adding (and
1334          * the use xsnprintf double-checks that)
1335          */
1336         alloc = st_add3(path_len, strlen(".pack"), 1);
1337         p = alloc_packed_git(alloc);
1338         memcpy(p->pack_name, path, path_len);
1339
1340         xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
1341         if (!access(p->pack_name, F_OK))
1342                 p->pack_keep = 1;
1343
1344         xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
1345         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1346                 free(p);
1347                 return NULL;
1348         }
1349
1350         /* ok, it looks sane as far as we can check without
1351          * actually mapping the pack file.
1352          */
1353         p->pack_size = st.st_size;
1354         p->pack_local = local;
1355         p->mtime = st.st_mtime;
1356         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1357                 hashclr(p->sha1);
1358         return p;
1359 }
1360
1361 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1362 {
1363         const char *path = sha1_pack_name(sha1);
1364         size_t alloc = st_add(strlen(path), 1);
1365         struct packed_git *p = alloc_packed_git(alloc);
1366
1367         memcpy(p->pack_name, path, alloc); /* includes NUL */
1368         hashcpy(p->sha1, sha1);
1369         if (check_packed_git_idx(idx_path, p)) {
1370                 free(p);
1371                 return NULL;
1372         }
1373
1374         return p;
1375 }
1376
1377 void install_packed_git(struct packed_git *pack)
1378 {
1379         if (pack->pack_fd != -1)
1380                 pack_open_fds++;
1381
1382         pack->next = packed_git;
1383         packed_git = pack;
1384 }
1385
1386 void (*report_garbage)(unsigned seen_bits, const char *path);
1387
1388 static void report_helper(const struct string_list *list,
1389                           int seen_bits, int first, int last)
1390 {
1391         if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
1392                 return;
1393
1394         for (; first < last; first++)
1395                 report_garbage(seen_bits, list->items[first].string);
1396 }
1397
1398 static void report_pack_garbage(struct string_list *list)
1399 {
1400         int i, baselen = -1, first = 0, seen_bits = 0;
1401
1402         if (!report_garbage)
1403                 return;
1404
1405         string_list_sort(list);
1406
1407         for (i = 0; i < list->nr; i++) {
1408                 const char *path = list->items[i].string;
1409                 if (baselen != -1 &&
1410                     strncmp(path, list->items[first].string, baselen)) {
1411                         report_helper(list, seen_bits, first, i);
1412                         baselen = -1;
1413                         seen_bits = 0;
1414                 }
1415                 if (baselen == -1) {
1416                         const char *dot = strrchr(path, '.');
1417                         if (!dot) {
1418                                 report_garbage(PACKDIR_FILE_GARBAGE, path);
1419                                 continue;
1420                         }
1421                         baselen = dot - path + 1;
1422                         first = i;
1423                 }
1424                 if (!strcmp(path + baselen, "pack"))
1425                         seen_bits |= 1;
1426                 else if (!strcmp(path + baselen, "idx"))
1427                         seen_bits |= 2;
1428         }
1429         report_helper(list, seen_bits, first, list->nr);
1430 }
1431
1432 static void prepare_packed_git_one(char *objdir, int local)
1433 {
1434         struct strbuf path = STRBUF_INIT;
1435         size_t dirnamelen;
1436         DIR *dir;
1437         struct dirent *de;
1438         struct string_list garbage = STRING_LIST_INIT_DUP;
1439
1440         strbuf_addstr(&path, objdir);
1441         strbuf_addstr(&path, "/pack");
1442         dir = opendir(path.buf);
1443         if (!dir) {
1444                 if (errno != ENOENT)
1445                         error_errno("unable to open object pack directory: %s",
1446                                     path.buf);
1447                 strbuf_release(&path);
1448                 return;
1449         }
1450         strbuf_addch(&path, '/');
1451         dirnamelen = path.len;
1452         while ((de = readdir(dir)) != NULL) {
1453                 struct packed_git *p;
1454                 size_t base_len;
1455
1456                 if (is_dot_or_dotdot(de->d_name))
1457                         continue;
1458
1459                 strbuf_setlen(&path, dirnamelen);
1460                 strbuf_addstr(&path, de->d_name);
1461
1462                 base_len = path.len;
1463                 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1464                         /* Don't reopen a pack we already have. */
1465                         for (p = packed_git; p; p = p->next) {
1466                                 size_t len;
1467                                 if (strip_suffix(p->pack_name, ".pack", &len) &&
1468                                     len == base_len &&
1469                                     !memcmp(p->pack_name, path.buf, len))
1470                                         break;
1471                         }
1472                         if (p == NULL &&
1473                             /*
1474                              * See if it really is a valid .idx file with
1475                              * corresponding .pack file that we can map.
1476                              */
1477                             (p = add_packed_git(path.buf, path.len, local)) != NULL)
1478                                 install_packed_git(p);
1479                 }
1480
1481                 if (!report_garbage)
1482                         continue;
1483
1484                 if (ends_with(de->d_name, ".idx") ||
1485                     ends_with(de->d_name, ".pack") ||
1486                     ends_with(de->d_name, ".bitmap") ||
1487                     ends_with(de->d_name, ".keep"))
1488                         string_list_append(&garbage, path.buf);
1489                 else
1490                         report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
1491         }
1492         closedir(dir);
1493         report_pack_garbage(&garbage);
1494         string_list_clear(&garbage, 0);
1495         strbuf_release(&path);
1496 }
1497
1498 static int approximate_object_count_valid;
1499
1500 /*
1501  * Give a fast, rough count of the number of objects in the repository. This
1502  * ignores loose objects completely. If you have a lot of them, then either
1503  * you should repack because your performance will be awful, or they are
1504  * all unreachable objects about to be pruned, in which case they're not really
1505  * interesting as a measure of repo size in the first place.
1506  */
1507 unsigned long approximate_object_count(void)
1508 {
1509         static unsigned long count;
1510         if (!approximate_object_count_valid) {
1511                 struct packed_git *p;
1512
1513                 prepare_packed_git();
1514                 count = 0;
1515                 for (p = packed_git; p; p = p->next) {
1516                         if (open_pack_index(p))
1517                                 continue;
1518                         count += p->num_objects;
1519                 }
1520         }
1521         return count;
1522 }
1523
1524 static void *get_next_packed_git(const void *p)
1525 {
1526         return ((const struct packed_git *)p)->next;
1527 }
1528
1529 static void set_next_packed_git(void *p, void *next)
1530 {
1531         ((struct packed_git *)p)->next = next;
1532 }
1533
1534 static int sort_pack(const void *a_, const void *b_)
1535 {
1536         const struct packed_git *a = a_;
1537         const struct packed_git *b = b_;
1538         int st;
1539
1540         /*
1541          * Local packs tend to contain objects specific to our
1542          * variant of the project than remote ones.  In addition,
1543          * remote ones could be on a network mounted filesystem.
1544          * Favor local ones for these reasons.
1545          */
1546         st = a->pack_local - b->pack_local;
1547         if (st)
1548                 return -st;
1549
1550         /*
1551          * Younger packs tend to contain more recent objects,
1552          * and more recent objects tend to get accessed more
1553          * often.
1554          */
1555         if (a->mtime < b->mtime)
1556                 return 1;
1557         else if (a->mtime == b->mtime)
1558                 return 0;
1559         return -1;
1560 }
1561
1562 static void rearrange_packed_git(void)
1563 {
1564         packed_git = llist_mergesort(packed_git, get_next_packed_git,
1565                                      set_next_packed_git, sort_pack);
1566 }
1567
1568 static void prepare_packed_git_mru(void)
1569 {
1570         struct packed_git *p;
1571
1572         mru_clear(packed_git_mru);
1573         for (p = packed_git; p; p = p->next)
1574                 mru_append(packed_git_mru, p);
1575 }
1576
1577 static int prepare_packed_git_run_once = 0;
1578 void prepare_packed_git(void)
1579 {
1580         struct alternate_object_database *alt;
1581
1582         if (prepare_packed_git_run_once)
1583                 return;
1584         prepare_packed_git_one(get_object_directory(), 1);
1585         prepare_alt_odb();
1586         for (alt = alt_odb_list; alt; alt = alt->next)
1587                 prepare_packed_git_one(alt->path, 0);
1588         rearrange_packed_git();
1589         prepare_packed_git_mru();
1590         prepare_packed_git_run_once = 1;
1591 }
1592
1593 void reprepare_packed_git(void)
1594 {
1595         approximate_object_count_valid = 0;
1596         prepare_packed_git_run_once = 0;
1597         prepare_packed_git();
1598 }
1599
1600 static void mark_bad_packed_object(struct packed_git *p,
1601                                    const unsigned char *sha1)
1602 {
1603         unsigned i;
1604         for (i = 0; i < p->num_bad_objects; i++)
1605                 if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1606                         return;
1607         p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1608                                       st_mult(GIT_MAX_RAWSZ,
1609                                               st_add(p->num_bad_objects, 1)));
1610         hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1611         p->num_bad_objects++;
1612 }
1613
1614 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1615 {
1616         struct packed_git *p;
1617         unsigned i;
1618
1619         for (p = packed_git; p; p = p->next)
1620                 for (i = 0; i < p->num_bad_objects; i++)
1621                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1622                                 return p;
1623         return NULL;
1624 }
1625
1626 /*
1627  * With an in-core object data in "map", rehash it to make sure the
1628  * object name actually matches "sha1" to detect object corruption.
1629  * With "map" == NULL, try reading the object named with "sha1" using
1630  * the streaming interface and rehash it to do the same.
1631  */
1632 int check_sha1_signature(const unsigned char *sha1, void *map,
1633                          unsigned long size, const char *type)
1634 {
1635         unsigned char real_sha1[20];
1636         enum object_type obj_type;
1637         struct git_istream *st;
1638         git_SHA_CTX c;
1639         char hdr[32];
1640         int hdrlen;
1641
1642         if (map) {
1643                 hash_sha1_file(map, size, type, real_sha1);
1644                 return hashcmp(sha1, real_sha1) ? -1 : 0;
1645         }
1646
1647         st = open_istream(sha1, &obj_type, &size, NULL);
1648         if (!st)
1649                 return -1;
1650
1651         /* Generate the header */
1652         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1653
1654         /* Sha1.. */
1655         git_SHA1_Init(&c);
1656         git_SHA1_Update(&c, hdr, hdrlen);
1657         for (;;) {
1658                 char buf[1024 * 16];
1659                 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1660
1661                 if (readlen < 0) {
1662                         close_istream(st);
1663                         return -1;
1664                 }
1665                 if (!readlen)
1666                         break;
1667                 git_SHA1_Update(&c, buf, readlen);
1668         }
1669         git_SHA1_Final(real_sha1, &c);
1670         close_istream(st);
1671         return hashcmp(sha1, real_sha1) ? -1 : 0;
1672 }
1673
1674 int git_open_cloexec(const char *name, int flags)
1675 {
1676         int fd;
1677         static int o_cloexec = O_CLOEXEC;
1678
1679         fd = open(name, flags | o_cloexec);
1680         if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1681                 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1682                 o_cloexec &= ~O_CLOEXEC;
1683                 fd = open(name, flags | o_cloexec);
1684         }
1685
1686 #if defined(F_GETFL) && defined(F_SETFL) && defined(FD_CLOEXEC)
1687         {
1688                 static int fd_cloexec = FD_CLOEXEC;
1689
1690                 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1691                         /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
1692                         int flags = fcntl(fd, F_GETFL);
1693                         if (fcntl(fd, F_SETFL, flags | fd_cloexec))
1694                                 fd_cloexec = 0;
1695                 }
1696         }
1697 #endif
1698         return fd;
1699 }
1700
1701 /*
1702  * Find "sha1" as a loose object in the local repository or in an alternate.
1703  * Returns 0 on success, negative on failure.
1704  *
1705  * The "path" out-parameter will give the path of the object we found (if any).
1706  * Note that it may point to static storage and is only valid until another
1707  * call to sha1_file_name(), etc.
1708  */
1709 static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
1710                           const char **path)
1711 {
1712         struct alternate_object_database *alt;
1713
1714         *path = sha1_file_name(sha1);
1715         if (!lstat(*path, st))
1716                 return 0;
1717
1718         prepare_alt_odb();
1719         errno = ENOENT;
1720         for (alt = alt_odb_list; alt; alt = alt->next) {
1721                 *path = alt_sha1_path(alt, sha1);
1722                 if (!lstat(*path, st))
1723                         return 0;
1724         }
1725
1726         return -1;
1727 }
1728
1729 /*
1730  * Like stat_sha1_file(), but actually open the object and return the
1731  * descriptor. See the caveats on the "path" parameter above.
1732  */
1733 static int open_sha1_file(const unsigned char *sha1, const char **path)
1734 {
1735         int fd;
1736         struct alternate_object_database *alt;
1737         int most_interesting_errno;
1738
1739         *path = sha1_file_name(sha1);
1740         fd = git_open(*path);
1741         if (fd >= 0)
1742                 return fd;
1743         most_interesting_errno = errno;
1744
1745         prepare_alt_odb();
1746         for (alt = alt_odb_list; alt; alt = alt->next) {
1747                 *path = alt_sha1_path(alt, sha1);
1748                 fd = git_open(*path);
1749                 if (fd >= 0)
1750                         return fd;
1751                 if (most_interesting_errno == ENOENT)
1752                         most_interesting_errno = errno;
1753         }
1754         errno = most_interesting_errno;
1755         return -1;
1756 }
1757
1758 /*
1759  * Map the loose object at "path" if it is not NULL, or the path found by
1760  * searching for a loose object named "sha1".
1761  */
1762 static void *map_sha1_file_1(const char *path,
1763                              const unsigned char *sha1,
1764                              unsigned long *size)
1765 {
1766         void *map;
1767         int fd;
1768
1769         if (path)
1770                 fd = git_open(path);
1771         else
1772                 fd = open_sha1_file(sha1, &path);
1773         map = NULL;
1774         if (fd >= 0) {
1775                 struct stat st;
1776
1777                 if (!fstat(fd, &st)) {
1778                         *size = xsize_t(st.st_size);
1779                         if (!*size) {
1780                                 /* mmap() is forbidden on empty files */
1781                                 error("object file %s is empty", path);
1782                                 return NULL;
1783                         }
1784                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1785                 }
1786                 close(fd);
1787         }
1788         return map;
1789 }
1790
1791 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1792 {
1793         return map_sha1_file_1(NULL, sha1, size);
1794 }
1795
1796 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1797                 unsigned long len, enum object_type *type, unsigned long *sizep)
1798 {
1799         unsigned shift;
1800         unsigned long size, c;
1801         unsigned long used = 0;
1802
1803         c = buf[used++];
1804         *type = (c >> 4) & 7;
1805         size = c & 15;
1806         shift = 4;
1807         while (c & 0x80) {
1808                 if (len <= used || bitsizeof(long) <= shift) {
1809                         error("bad object header");
1810                         size = used = 0;
1811                         break;
1812                 }
1813                 c = buf[used++];
1814                 size += (c & 0x7f) << shift;
1815                 shift += 7;
1816         }
1817         *sizep = size;
1818         return used;
1819 }
1820
1821 static int unpack_sha1_short_header(git_zstream *stream,
1822                                     unsigned char *map, unsigned long mapsize,
1823                                     void *buffer, unsigned long bufsiz)
1824 {
1825         /* Get the data stream */
1826         memset(stream, 0, sizeof(*stream));
1827         stream->next_in = map;
1828         stream->avail_in = mapsize;
1829         stream->next_out = buffer;
1830         stream->avail_out = bufsiz;
1831
1832         git_inflate_init(stream);
1833         return git_inflate(stream, 0);
1834 }
1835
1836 int unpack_sha1_header(git_zstream *stream,
1837                        unsigned char *map, unsigned long mapsize,
1838                        void *buffer, unsigned long bufsiz)
1839 {
1840         int status = unpack_sha1_short_header(stream, map, mapsize,
1841                                               buffer, bufsiz);
1842
1843         if (status < Z_OK)
1844                 return status;
1845
1846         /* Make sure we have the terminating NUL */
1847         if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1848                 return -1;
1849         return 0;
1850 }
1851
1852 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1853                                         unsigned long mapsize, void *buffer,
1854                                         unsigned long bufsiz, struct strbuf *header)
1855 {
1856         int status;
1857
1858         status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1859         if (status < Z_OK)
1860                 return -1;
1861
1862         /*
1863          * Check if entire header is unpacked in the first iteration.
1864          */
1865         if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1866                 return 0;
1867
1868         /*
1869          * buffer[0..bufsiz] was not large enough.  Copy the partial
1870          * result out to header, and then append the result of further
1871          * reading the stream.
1872          */
1873         strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1874         stream->next_out = buffer;
1875         stream->avail_out = bufsiz;
1876
1877         do {
1878                 status = git_inflate(stream, 0);
1879                 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1880                 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1881                         return 0;
1882                 stream->next_out = buffer;
1883                 stream->avail_out = bufsiz;
1884         } while (status != Z_STREAM_END);
1885         return -1;
1886 }
1887
1888 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1889 {
1890         int bytes = strlen(buffer) + 1;
1891         unsigned char *buf = xmallocz(size);
1892         unsigned long n;
1893         int status = Z_OK;
1894
1895         n = stream->total_out - bytes;
1896         if (n > size)
1897                 n = size;
1898         memcpy(buf, (char *) buffer + bytes, n);
1899         bytes = n;
1900         if (bytes <= size) {
1901                 /*
1902                  * The above condition must be (bytes <= size), not
1903                  * (bytes < size).  In other words, even though we
1904                  * expect no more output and set avail_out to zero,
1905                  * the input zlib stream may have bytes that express
1906                  * "this concludes the stream", and we *do* want to
1907                  * eat that input.
1908                  *
1909                  * Otherwise we would not be able to test that we
1910                  * consumed all the input to reach the expected size;
1911                  * we also want to check that zlib tells us that all
1912                  * went well with status == Z_STREAM_END at the end.
1913                  */
1914                 stream->next_out = buf + bytes;
1915                 stream->avail_out = size - bytes;
1916                 while (status == Z_OK)
1917                         status = git_inflate(stream, Z_FINISH);
1918         }
1919         if (status == Z_STREAM_END && !stream->avail_in) {
1920                 git_inflate_end(stream);
1921                 return buf;
1922         }
1923
1924         if (status < 0)
1925                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1926         else if (stream->avail_in)
1927                 error("garbage at end of loose object '%s'",
1928                       sha1_to_hex(sha1));
1929         free(buf);
1930         return NULL;
1931 }
1932
1933 /*
1934  * We used to just use "sscanf()", but that's actually way
1935  * too permissive for what we want to check. So do an anal
1936  * object header parse by hand.
1937  */
1938 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1939                                unsigned int flags)
1940 {
1941         const char *type_buf = hdr;
1942         unsigned long size;
1943         int type, type_len = 0;
1944
1945         /*
1946          * The type can be of any size but is followed by
1947          * a space.
1948          */
1949         for (;;) {
1950                 char c = *hdr++;
1951                 if (!c)
1952                         return -1;
1953                 if (c == ' ')
1954                         break;
1955                 type_len++;
1956         }
1957
1958         type = type_from_string_gently(type_buf, type_len, 1);
1959         if (oi->typename)
1960                 strbuf_add(oi->typename, type_buf, type_len);
1961         /*
1962          * Set type to 0 if its an unknown object and
1963          * we're obtaining the type using '--allow-unknown-type'
1964          * option.
1965          */
1966         if ((flags & LOOKUP_UNKNOWN_OBJECT) && (type < 0))
1967                 type = 0;
1968         else if (type < 0)
1969                 die("invalid object type");
1970         if (oi->typep)
1971                 *oi->typep = type;
1972
1973         /*
1974          * The length must follow immediately, and be in canonical
1975          * decimal format (ie "010" is not valid).
1976          */
1977         size = *hdr++ - '0';
1978         if (size > 9)
1979                 return -1;
1980         if (size) {
1981                 for (;;) {
1982                         unsigned long c = *hdr - '0';
1983                         if (c > 9)
1984                                 break;
1985                         hdr++;
1986                         size = size * 10 + c;
1987                 }
1988         }
1989
1990         if (oi->sizep)
1991                 *oi->sizep = size;
1992
1993         /*
1994          * The length must be followed by a zero byte
1995          */
1996         return *hdr ? -1 : type;
1997 }
1998
1999 int parse_sha1_header(const char *hdr, unsigned long *sizep)
2000 {
2001         struct object_info oi = OBJECT_INFO_INIT;
2002
2003         oi.sizep = sizep;
2004         return parse_sha1_header_extended(hdr, &oi, LOOKUP_REPLACE_OBJECT);
2005 }
2006
2007 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
2008 {
2009         int ret;
2010         git_zstream stream;
2011         char hdr[8192];
2012
2013         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
2014         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
2015                 return NULL;
2016
2017         return unpack_sha1_rest(&stream, hdr, *size, sha1);
2018 }
2019
2020 unsigned long get_size_from_delta(struct packed_git *p,
2021                                   struct pack_window **w_curs,
2022                                   off_t curpos)
2023 {
2024         const unsigned char *data;
2025         unsigned char delta_head[20], *in;
2026         git_zstream stream;
2027         int st;
2028
2029         memset(&stream, 0, sizeof(stream));
2030         stream.next_out = delta_head;
2031         stream.avail_out = sizeof(delta_head);
2032
2033         git_inflate_init(&stream);
2034         do {
2035                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
2036                 stream.next_in = in;
2037                 st = git_inflate(&stream, Z_FINISH);
2038                 curpos += stream.next_in - in;
2039         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
2040                  stream.total_out < sizeof(delta_head));
2041         git_inflate_end(&stream);
2042         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
2043                 error("delta data unpack-initial failed");
2044                 return 0;
2045         }
2046
2047         /* Examine the initial part of the delta to figure out
2048          * the result size.
2049          */
2050         data = delta_head;
2051
2052         /* ignore base size */
2053         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
2054
2055         /* Read the result size */
2056         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
2057 }
2058
2059 static off_t get_delta_base(struct packed_git *p,
2060                                     struct pack_window **w_curs,
2061                                     off_t *curpos,
2062                                     enum object_type type,
2063                                     off_t delta_obj_offset)
2064 {
2065         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
2066         off_t base_offset;
2067
2068         /* use_pack() assured us we have [base_info, base_info + 20)
2069          * as a range that we can look at without walking off the
2070          * end of the mapped window.  Its actually the hash size
2071          * that is assured.  An OFS_DELTA longer than the hash size
2072          * is stupid, as then a REF_DELTA would be smaller to store.
2073          */
2074         if (type == OBJ_OFS_DELTA) {
2075                 unsigned used = 0;
2076                 unsigned char c = base_info[used++];
2077                 base_offset = c & 127;
2078                 while (c & 128) {
2079                         base_offset += 1;
2080                         if (!base_offset || MSB(base_offset, 7))
2081                                 return 0;  /* overflow */
2082                         c = base_info[used++];
2083                         base_offset = (base_offset << 7) + (c & 127);
2084                 }
2085                 base_offset = delta_obj_offset - base_offset;
2086                 if (base_offset <= 0 || base_offset >= delta_obj_offset)
2087                         return 0;  /* out of bound */
2088                 *curpos += used;
2089         } else if (type == OBJ_REF_DELTA) {
2090                 /* The base entry _must_ be in the same pack */
2091                 base_offset = find_pack_entry_one(base_info, p);
2092                 *curpos += 20;
2093         } else
2094                 die("I am totally screwed");
2095         return base_offset;
2096 }
2097
2098 /*
2099  * Like get_delta_base above, but we return the sha1 instead of the pack
2100  * offset. This means it is cheaper for REF deltas (we do not have to do
2101  * the final object lookup), but more expensive for OFS deltas (we
2102  * have to load the revidx to convert the offset back into a sha1).
2103  */
2104 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
2105                                                 struct pack_window **w_curs,
2106                                                 off_t curpos,
2107                                                 enum object_type type,
2108                                                 off_t delta_obj_offset)
2109 {
2110         if (type == OBJ_REF_DELTA) {
2111                 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
2112                 return base;
2113         } else if (type == OBJ_OFS_DELTA) {
2114                 struct revindex_entry *revidx;
2115                 off_t base_offset = get_delta_base(p, w_curs, &curpos,
2116                                                    type, delta_obj_offset);
2117
2118                 if (!base_offset)
2119                         return NULL;
2120
2121                 revidx = find_pack_revindex(p, base_offset);
2122                 if (!revidx)
2123                         return NULL;
2124
2125                 return nth_packed_object_sha1(p, revidx->nr);
2126         } else
2127                 return NULL;
2128 }
2129
2130 int unpack_object_header(struct packed_git *p,
2131                          struct pack_window **w_curs,
2132                          off_t *curpos,
2133                          unsigned long *sizep)
2134 {
2135         unsigned char *base;
2136         unsigned long left;
2137         unsigned long used;
2138         enum object_type type;
2139
2140         /* use_pack() assures us we have [base, base + 20) available
2141          * as a range that we can look at.  (Its actually the hash
2142          * size that is assured.)  With our object header encoding
2143          * the maximum deflated object size is 2^137, which is just
2144          * insane, so we know won't exceed what we have been given.
2145          */
2146         base = use_pack(p, w_curs, *curpos, &left);
2147         used = unpack_object_header_buffer(base, left, &type, sizep);
2148         if (!used) {
2149                 type = OBJ_BAD;
2150         } else
2151                 *curpos += used;
2152
2153         return type;
2154 }
2155
2156 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
2157 {
2158         int type;
2159         struct revindex_entry *revidx;
2160         const unsigned char *sha1;
2161         revidx = find_pack_revindex(p, obj_offset);
2162         if (!revidx)
2163                 return OBJ_BAD;
2164         sha1 = nth_packed_object_sha1(p, revidx->nr);
2165         mark_bad_packed_object(p, sha1);
2166         type = sha1_object_info(sha1, NULL);
2167         if (type <= OBJ_NONE)
2168                 return OBJ_BAD;
2169         return type;
2170 }
2171
2172 #define POI_STACK_PREALLOC 64
2173
2174 static enum object_type packed_to_object_type(struct packed_git *p,
2175                                               off_t obj_offset,
2176                                               enum object_type type,
2177                                               struct pack_window **w_curs,
2178                                               off_t curpos)
2179 {
2180         off_t small_poi_stack[POI_STACK_PREALLOC];
2181         off_t *poi_stack = small_poi_stack;
2182         int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
2183
2184         while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2185                 off_t base_offset;
2186                 unsigned long size;
2187                 /* Push the object we're going to leave behind */
2188                 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
2189                         poi_stack_alloc = alloc_nr(poi_stack_nr);
2190                         ALLOC_ARRAY(poi_stack, poi_stack_alloc);
2191                         memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
2192                 } else {
2193                         ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
2194                 }
2195                 poi_stack[poi_stack_nr++] = obj_offset;
2196                 /* If parsing the base offset fails, just unwind */
2197                 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
2198                 if (!base_offset)
2199                         goto unwind;
2200                 curpos = obj_offset = base_offset;
2201                 type = unpack_object_header(p, w_curs, &curpos, &size);
2202                 if (type <= OBJ_NONE) {
2203                         /* If getting the base itself fails, we first
2204                          * retry the base, otherwise unwind */
2205                         type = retry_bad_packed_offset(p, base_offset);
2206                         if (type > OBJ_NONE)
2207                                 goto out;
2208                         goto unwind;
2209                 }
2210         }
2211
2212         switch (type) {
2213         case OBJ_BAD:
2214         case OBJ_COMMIT:
2215         case OBJ_TREE:
2216         case OBJ_BLOB:
2217         case OBJ_TAG:
2218                 break;
2219         default:
2220                 error("unknown object type %i at offset %"PRIuMAX" in %s",
2221                       type, (uintmax_t)obj_offset, p->pack_name);
2222                 type = OBJ_BAD;
2223         }
2224
2225 out:
2226         if (poi_stack != small_poi_stack)
2227                 free(poi_stack);
2228         return type;
2229
2230 unwind:
2231         while (poi_stack_nr) {
2232                 obj_offset = poi_stack[--poi_stack_nr];
2233                 type = retry_bad_packed_offset(p, obj_offset);
2234                 if (type > OBJ_NONE)
2235                         goto out;
2236         }
2237         type = OBJ_BAD;
2238         goto out;
2239 }
2240
2241 int packed_object_info(struct packed_git *p, off_t obj_offset,
2242                        struct object_info *oi)
2243 {
2244         struct pack_window *w_curs = NULL;
2245         unsigned long size;
2246         off_t curpos = obj_offset;
2247         enum object_type type;
2248
2249         /*
2250          * We always get the representation type, but only convert it to
2251          * a "real" type later if the caller is interested.
2252          */
2253         type = unpack_object_header(p, &w_curs, &curpos, &size);
2254
2255         if (oi->sizep) {
2256                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2257                         off_t tmp_pos = curpos;
2258                         off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
2259                                                            type, obj_offset);
2260                         if (!base_offset) {
2261                                 type = OBJ_BAD;
2262                                 goto out;
2263                         }
2264                         *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
2265                         if (*oi->sizep == 0) {
2266                                 type = OBJ_BAD;
2267                                 goto out;
2268                         }
2269                 } else {
2270                         *oi->sizep = size;
2271                 }
2272         }
2273
2274         if (oi->disk_sizep) {
2275                 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2276                 *oi->disk_sizep = revidx[1].offset - obj_offset;
2277         }
2278
2279         if (oi->typep) {
2280                 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
2281                 if (*oi->typep < 0) {
2282                         type = OBJ_BAD;
2283                         goto out;
2284                 }
2285         }
2286
2287         if (oi->delta_base_sha1) {
2288                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2289                         const unsigned char *base;
2290
2291                         base = get_delta_base_sha1(p, &w_curs, curpos,
2292                                                    type, obj_offset);
2293                         if (!base) {
2294                                 type = OBJ_BAD;
2295                                 goto out;
2296                         }
2297
2298                         hashcpy(oi->delta_base_sha1, base);
2299                 } else
2300                         hashclr(oi->delta_base_sha1);
2301         }
2302
2303 out:
2304         unuse_pack(&w_curs);
2305         return type;
2306 }
2307
2308 static void *unpack_compressed_entry(struct packed_git *p,
2309                                     struct pack_window **w_curs,
2310                                     off_t curpos,
2311                                     unsigned long size)
2312 {
2313         int st;
2314         git_zstream stream;
2315         unsigned char *buffer, *in;
2316
2317         buffer = xmallocz_gently(size);
2318         if (!buffer)
2319                 return NULL;
2320         memset(&stream, 0, sizeof(stream));
2321         stream.next_out = buffer;
2322         stream.avail_out = size + 1;
2323
2324         git_inflate_init(&stream);
2325         do {
2326                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
2327                 stream.next_in = in;
2328                 st = git_inflate(&stream, Z_FINISH);
2329                 if (!stream.avail_out)
2330                         break; /* the payload is larger than it should be */
2331                 curpos += stream.next_in - in;
2332         } while (st == Z_OK || st == Z_BUF_ERROR);
2333         git_inflate_end(&stream);
2334         if ((st != Z_STREAM_END) || stream.total_out != size) {
2335                 free(buffer);
2336                 return NULL;
2337         }
2338
2339         return buffer;
2340 }
2341
2342 static struct hashmap delta_base_cache;
2343 static size_t delta_base_cached;
2344
2345 static LIST_HEAD(delta_base_cache_lru);
2346
2347 struct delta_base_cache_key {
2348         struct packed_git *p;
2349         off_t base_offset;
2350 };
2351
2352 struct delta_base_cache_entry {
2353         struct hashmap hash;
2354         struct delta_base_cache_key key;
2355         struct list_head lru;
2356         void *data;
2357         unsigned long size;
2358         enum object_type type;
2359 };
2360
2361 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
2362 {
2363         unsigned int hash;
2364
2365         hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
2366         hash += (hash >> 8) + (hash >> 16);
2367         return hash;
2368 }
2369
2370 static struct delta_base_cache_entry *
2371 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2372 {
2373         struct hashmap_entry entry;
2374         struct delta_base_cache_key key;
2375
2376         if (!delta_base_cache.cmpfn)
2377                 return NULL;
2378
2379         hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
2380         key.p = p;
2381         key.base_offset = base_offset;
2382         return hashmap_get(&delta_base_cache, &entry, &key);
2383 }
2384
2385 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
2386                                    const struct delta_base_cache_key *b)
2387 {
2388         return a->p == b->p && a->base_offset == b->base_offset;
2389 }
2390
2391 static int delta_base_cache_hash_cmp(const void *va, const void *vb,
2392                                      const void *vkey)
2393 {
2394         const struct delta_base_cache_entry *a = va, *b = vb;
2395         const struct delta_base_cache_key *key = vkey;
2396         if (key)
2397                 return !delta_base_cache_key_eq(&a->key, key);
2398         else
2399                 return !delta_base_cache_key_eq(&a->key, &b->key);
2400 }
2401
2402 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2403 {
2404         return !!get_delta_base_cache_entry(p, base_offset);
2405 }
2406
2407 /*
2408  * Remove the entry from the cache, but do _not_ free the associated
2409  * entry data. The caller takes ownership of the "data" buffer, and
2410  * should copy out any fields it wants before detaching.
2411  */
2412 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2413 {
2414         hashmap_remove(&delta_base_cache, ent, &ent->key);
2415         list_del(&ent->lru);
2416         delta_base_cached -= ent->size;
2417         free(ent);
2418 }
2419
2420 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2421         unsigned long *base_size, enum object_type *type)
2422 {
2423         struct delta_base_cache_entry *ent;
2424
2425         ent = get_delta_base_cache_entry(p, base_offset);
2426         if (!ent)
2427                 return unpack_entry(p, base_offset, type, base_size);
2428
2429         *type = ent->type;
2430         *base_size = ent->size;
2431         return xmemdupz(ent->data, ent->size);
2432 }
2433
2434 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2435 {
2436         free(ent->data);
2437         detach_delta_base_cache_entry(ent);
2438 }
2439
2440 void clear_delta_base_cache(void)
2441 {
2442         struct list_head *lru, *tmp;
2443         list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2444                 struct delta_base_cache_entry *entry =
2445                         list_entry(lru, struct delta_base_cache_entry, lru);
2446                 release_delta_base_cache(entry);
2447         }
2448 }
2449
2450 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2451         void *base, unsigned long base_size, enum object_type type)
2452 {
2453         struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
2454         struct list_head *lru, *tmp;
2455
2456         delta_base_cached += base_size;
2457
2458         list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2459                 struct delta_base_cache_entry *f =
2460                         list_entry(lru, struct delta_base_cache_entry, lru);
2461                 if (delta_base_cached <= delta_base_cache_limit)
2462                         break;
2463                 release_delta_base_cache(f);
2464         }
2465
2466         ent->key.p = p;
2467         ent->key.base_offset = base_offset;
2468         ent->type = type;
2469         ent->data = base;
2470         ent->size = base_size;
2471         list_add_tail(&ent->lru, &delta_base_cache_lru);
2472
2473         if (!delta_base_cache.cmpfn)
2474                 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, 0);
2475         hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
2476         hashmap_add(&delta_base_cache, ent);
2477 }
2478
2479 static void *read_object(const unsigned char *sha1, enum object_type *type,
2480                          unsigned long *size);
2481
2482 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2483 {
2484         static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2485         trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2486                          p->pack_name, (uintmax_t)obj_offset);
2487 }
2488
2489 int do_check_packed_object_crc;
2490
2491 #define UNPACK_ENTRY_STACK_PREALLOC 64
2492 struct unpack_entry_stack_ent {
2493         off_t obj_offset;
2494         off_t curpos;
2495         unsigned long size;
2496 };
2497
2498 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2499                    enum object_type *final_type, unsigned long *final_size)
2500 {
2501         struct pack_window *w_curs = NULL;
2502         off_t curpos = obj_offset;
2503         void *data = NULL;
2504         unsigned long size;
2505         enum object_type type;
2506         struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2507         struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2508         int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2509         int base_from_cache = 0;
2510
2511         write_pack_access_log(p, obj_offset);
2512
2513         /* PHASE 1: drill down to the innermost base object */
2514         for (;;) {
2515                 off_t base_offset;
2516                 int i;
2517                 struct delta_base_cache_entry *ent;
2518
2519                 ent = get_delta_base_cache_entry(p, curpos);
2520                 if (ent) {
2521                         type = ent->type;
2522                         data = ent->data;
2523                         size = ent->size;
2524                         detach_delta_base_cache_entry(ent);
2525                         base_from_cache = 1;
2526                         break;
2527                 }
2528
2529                 if (do_check_packed_object_crc && p->index_version > 1) {
2530                         struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2531                         off_t len = revidx[1].offset - obj_offset;
2532                         if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2533                                 const unsigned char *sha1 =
2534                                         nth_packed_object_sha1(p, revidx->nr);
2535                                 error("bad packed object CRC for %s",
2536                                       sha1_to_hex(sha1));
2537                                 mark_bad_packed_object(p, sha1);
2538                                 unuse_pack(&w_curs);
2539                                 return NULL;
2540                         }
2541                 }
2542
2543                 type = unpack_object_header(p, &w_curs, &curpos, &size);
2544                 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2545                         break;
2546
2547                 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2548                 if (!base_offset) {
2549                         error("failed to validate delta base reference "
2550                               "at offset %"PRIuMAX" from %s",
2551                               (uintmax_t)curpos, p->pack_name);
2552                         /* bail to phase 2, in hopes of recovery */
2553                         data = NULL;
2554                         break;
2555                 }
2556
2557                 /* push object, proceed to base */
2558                 if (delta_stack_nr >= delta_stack_alloc
2559                     && delta_stack == small_delta_stack) {
2560                         delta_stack_alloc = alloc_nr(delta_stack_nr);
2561                         ALLOC_ARRAY(delta_stack, delta_stack_alloc);
2562                         memcpy(delta_stack, small_delta_stack,
2563                                sizeof(*delta_stack)*delta_stack_nr);
2564                 } else {
2565                         ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2566                 }
2567                 i = delta_stack_nr++;
2568                 delta_stack[i].obj_offset = obj_offset;
2569                 delta_stack[i].curpos = curpos;
2570                 delta_stack[i].size = size;
2571
2572                 curpos = obj_offset = base_offset;
2573         }
2574
2575         /* PHASE 2: handle the base */
2576         switch (type) {
2577         case OBJ_OFS_DELTA:
2578         case OBJ_REF_DELTA:
2579                 if (data)
2580                         die("BUG: unpack_entry: left loop at a valid delta");
2581                 break;
2582         case OBJ_COMMIT:
2583         case OBJ_TREE:
2584         case OBJ_BLOB:
2585         case OBJ_TAG:
2586                 if (!base_from_cache)
2587                         data = unpack_compressed_entry(p, &w_curs, curpos, size);
2588                 break;
2589         default:
2590                 data = NULL;
2591                 error("unknown object type %i at offset %"PRIuMAX" in %s",
2592                       type, (uintmax_t)obj_offset, p->pack_name);
2593         }
2594
2595         /* PHASE 3: apply deltas in order */
2596
2597         /* invariants:
2598          *   'data' holds the base data, or NULL if there was corruption
2599          */
2600         while (delta_stack_nr) {
2601                 void *delta_data;
2602                 void *base = data;
2603                 void *external_base = NULL;
2604                 unsigned long delta_size, base_size = size;
2605                 int i;
2606
2607                 data = NULL;
2608
2609                 if (base)
2610                         add_delta_base_cache(p, obj_offset, base, base_size, type);
2611
2612                 if (!base) {
2613                         /*
2614                          * We're probably in deep shit, but let's try to fetch
2615                          * the required base anyway from another pack or loose.
2616                          * This is costly but should happen only in the presence
2617                          * of a corrupted pack, and is better than failing outright.
2618                          */
2619                         struct revindex_entry *revidx;
2620                         const unsigned char *base_sha1;
2621                         revidx = find_pack_revindex(p, obj_offset);
2622                         if (revidx) {
2623                                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2624                                 error("failed to read delta base object %s"
2625                                       " at offset %"PRIuMAX" from %s",
2626                                       sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2627                                       p->pack_name);
2628                                 mark_bad_packed_object(p, base_sha1);
2629                                 base = read_object(base_sha1, &type, &base_size);
2630                                 external_base = base;
2631                         }
2632                 }
2633
2634                 i = --delta_stack_nr;
2635                 obj_offset = delta_stack[i].obj_offset;
2636                 curpos = delta_stack[i].curpos;
2637                 delta_size = delta_stack[i].size;
2638
2639                 if (!base)
2640                         continue;
2641
2642                 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2643
2644                 if (!delta_data) {
2645                         error("failed to unpack compressed delta "
2646                               "at offset %"PRIuMAX" from %s",
2647                               (uintmax_t)curpos, p->pack_name);
2648                         data = NULL;
2649                         free(external_base);
2650                         continue;
2651                 }
2652
2653                 data = patch_delta(base, base_size,
2654                                    delta_data, delta_size,
2655                                    &size);
2656
2657                 /*
2658                  * We could not apply the delta; warn the user, but keep going.
2659                  * Our failure will be noticed either in the next iteration of
2660                  * the loop, or if this is the final delta, in the caller when
2661                  * we return NULL. Those code paths will take care of making
2662                  * a more explicit warning and retrying with another copy of
2663                  * the object.
2664                  */
2665                 if (!data)
2666                         error("failed to apply delta");
2667
2668                 free(delta_data);
2669                 free(external_base);
2670         }
2671
2672         *final_type = type;
2673         *final_size = size;
2674
2675         unuse_pack(&w_curs);
2676
2677         if (delta_stack != small_delta_stack)
2678                 free(delta_stack);
2679
2680         return data;
2681 }
2682
2683 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2684                                             uint32_t n)
2685 {
2686         const unsigned char *index = p->index_data;
2687         if (!index) {
2688                 if (open_pack_index(p))
2689                         return NULL;
2690                 index = p->index_data;
2691         }
2692         if (n >= p->num_objects)
2693                 return NULL;
2694         index += 4 * 256;
2695         if (p->index_version == 1) {
2696                 return index + 24 * n + 4;
2697         } else {
2698                 index += 8;
2699                 return index + 20 * n;
2700         }
2701 }
2702
2703 const struct object_id *nth_packed_object_oid(struct object_id *oid,
2704                                               struct packed_git *p,
2705                                               uint32_t n)
2706 {
2707         const unsigned char *hash = nth_packed_object_sha1(p, n);
2708         if (!hash)
2709                 return NULL;
2710         hashcpy(oid->hash, hash);
2711         return oid;
2712 }
2713
2714 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2715 {
2716         const unsigned char *ptr = vptr;
2717         const unsigned char *start = p->index_data;
2718         const unsigned char *end = start + p->index_size;
2719         if (ptr < start)
2720                 die(_("offset before start of pack index for %s (corrupt index?)"),
2721                     p->pack_name);
2722         /* No need to check for underflow; .idx files must be at least 8 bytes */
2723         if (ptr >= end - 8)
2724                 die(_("offset beyond end of pack index for %s (truncated index?)"),
2725                     p->pack_name);
2726 }
2727
2728 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2729 {
2730         const unsigned char *index = p->index_data;
2731         index += 4 * 256;
2732         if (p->index_version == 1) {
2733                 return ntohl(*((uint32_t *)(index + 24 * n)));
2734         } else {
2735                 uint32_t off;
2736                 index += 8 + p->num_objects * (20 + 4);
2737                 off = ntohl(*((uint32_t *)(index + 4 * n)));
2738                 if (!(off & 0x80000000))
2739                         return off;
2740                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2741                 check_pack_index_ptr(p, index);
2742                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2743                                    ntohl(*((uint32_t *)(index + 4)));
2744         }
2745 }
2746
2747 off_t find_pack_entry_one(const unsigned char *sha1,
2748                                   struct packed_git *p)
2749 {
2750         const uint32_t *level1_ofs = p->index_data;
2751         const unsigned char *index = p->index_data;
2752         unsigned hi, lo, stride;
2753         static int use_lookup = -1;
2754         static int debug_lookup = -1;
2755
2756         if (debug_lookup < 0)
2757                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2758
2759         if (!index) {
2760                 if (open_pack_index(p))
2761                         return 0;
2762                 level1_ofs = p->index_data;
2763                 index = p->index_data;
2764         }
2765         if (p->index_version > 1) {
2766                 level1_ofs += 2;
2767                 index += 8;
2768         }
2769         index += 4 * 256;
2770         hi = ntohl(level1_ofs[*sha1]);
2771         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2772         if (p->index_version > 1) {
2773                 stride = 20;
2774         } else {
2775                 stride = 24;
2776                 index += 4;
2777         }
2778
2779         if (debug_lookup)
2780                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2781                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2782
2783         if (use_lookup < 0)
2784                 use_lookup = !!getenv("GIT_USE_LOOKUP");
2785         if (use_lookup) {
2786                 int pos = sha1_entry_pos(index, stride, 0,
2787                                          lo, hi, p->num_objects, sha1);
2788                 if (pos < 0)
2789                         return 0;
2790                 return nth_packed_object_offset(p, pos);
2791         }
2792
2793         do {
2794                 unsigned mi = (lo + hi) / 2;
2795                 int cmp = hashcmp(index + mi * stride, sha1);
2796
2797                 if (debug_lookup)
2798                         printf("lo %u hi %u rg %u mi %u\n",
2799                                lo, hi, hi - lo, mi);
2800                 if (!cmp)
2801                         return nth_packed_object_offset(p, mi);
2802                 if (cmp > 0)
2803                         hi = mi;
2804                 else
2805                         lo = mi+1;
2806         } while (lo < hi);
2807         return 0;
2808 }
2809
2810 int is_pack_valid(struct packed_git *p)
2811 {
2812         /* An already open pack is known to be valid. */
2813         if (p->pack_fd != -1)
2814                 return 1;
2815
2816         /* If the pack has one window completely covering the
2817          * file size, the pack is known to be valid even if
2818          * the descriptor is not currently open.
2819          */
2820         if (p->windows) {
2821                 struct pack_window *w = p->windows;
2822
2823                 if (!w->offset && w->len == p->pack_size)
2824                         return 1;
2825         }
2826
2827         /* Force the pack to open to prove its valid. */
2828         return !open_packed_git(p);
2829 }
2830
2831 static int fill_pack_entry(const unsigned char *sha1,
2832                            struct pack_entry *e,
2833                            struct packed_git *p)
2834 {
2835         off_t offset;
2836
2837         if (p->num_bad_objects) {
2838                 unsigned i;
2839                 for (i = 0; i < p->num_bad_objects; i++)
2840                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2841                                 return 0;
2842         }
2843
2844         offset = find_pack_entry_one(sha1, p);
2845         if (!offset)
2846                 return 0;
2847
2848         /*
2849          * We are about to tell the caller where they can locate the
2850          * requested object.  We better make sure the packfile is
2851          * still here and can be accessed before supplying that
2852          * answer, as it may have been deleted since the index was
2853          * loaded!
2854          */
2855         if (!is_pack_valid(p))
2856                 return 0;
2857         e->offset = offset;
2858         e->p = p;
2859         hashcpy(e->sha1, sha1);
2860         return 1;
2861 }
2862
2863 /*
2864  * Iff a pack file contains the object named by sha1, return true and
2865  * store its location to e.
2866  */
2867 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2868 {
2869         struct mru_entry *p;
2870
2871         prepare_packed_git();
2872         if (!packed_git)
2873                 return 0;
2874
2875         for (p = packed_git_mru->head; p; p = p->next) {
2876                 if (fill_pack_entry(sha1, e, p->item)) {
2877                         mru_mark(packed_git_mru, p);
2878                         return 1;
2879                 }
2880         }
2881         return 0;
2882 }
2883
2884 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2885                                   struct packed_git *packs)
2886 {
2887         struct packed_git *p;
2888
2889         for (p = packs; p; p = p->next) {
2890                 if (find_pack_entry_one(sha1, p))
2891                         return p;
2892         }
2893         return NULL;
2894
2895 }
2896
2897 static int sha1_loose_object_info(const unsigned char *sha1,
2898                                   struct object_info *oi,
2899                                   int flags)
2900 {
2901         int status = 0;
2902         unsigned long mapsize;
2903         void *map;
2904         git_zstream stream;
2905         char hdr[32];
2906         struct strbuf hdrbuf = STRBUF_INIT;
2907
2908         if (oi->delta_base_sha1)
2909                 hashclr(oi->delta_base_sha1);
2910
2911         /*
2912          * If we don't care about type or size, then we don't
2913          * need to look inside the object at all. Note that we
2914          * do not optimize out the stat call, even if the
2915          * caller doesn't care about the disk-size, since our
2916          * return value implicitly indicates whether the
2917          * object even exists.
2918          */
2919         if (!oi->typep && !oi->typename && !oi->sizep) {
2920                 const char *path;
2921                 struct stat st;
2922                 if (stat_sha1_file(sha1, &st, &path) < 0)
2923                         return -1;
2924                 if (oi->disk_sizep)
2925                         *oi->disk_sizep = st.st_size;
2926                 return 0;
2927         }
2928
2929         map = map_sha1_file(sha1, &mapsize);
2930         if (!map)
2931                 return -1;
2932         if (oi->disk_sizep)
2933                 *oi->disk_sizep = mapsize;
2934         if ((flags & LOOKUP_UNKNOWN_OBJECT)) {
2935                 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2936                         status = error("unable to unpack %s header with --allow-unknown-type",
2937                                        sha1_to_hex(sha1));
2938         } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2939                 status = error("unable to unpack %s header",
2940                                sha1_to_hex(sha1));
2941         if (status < 0)
2942                 ; /* Do nothing */
2943         else if (hdrbuf.len) {
2944                 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2945                         status = error("unable to parse %s header with --allow-unknown-type",
2946                                        sha1_to_hex(sha1));
2947         } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2948                 status = error("unable to parse %s header", sha1_to_hex(sha1));
2949         git_inflate_end(&stream);
2950         munmap(map, mapsize);
2951         if (status && oi->typep)
2952                 *oi->typep = status;
2953         strbuf_release(&hdrbuf);
2954         return (status < 0) ? status : 0;
2955 }
2956
2957 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2958 {
2959         struct cached_object *co;
2960         struct pack_entry e;
2961         int rtype;
2962         enum object_type real_type;
2963         const unsigned char *real = lookup_replace_object_extended(sha1, flags);
2964
2965         co = find_cached_object(real);
2966         if (co) {
2967                 if (oi->typep)
2968                         *(oi->typep) = co->type;
2969                 if (oi->sizep)
2970                         *(oi->sizep) = co->size;
2971                 if (oi->disk_sizep)
2972                         *(oi->disk_sizep) = 0;
2973                 if (oi->delta_base_sha1)
2974                         hashclr(oi->delta_base_sha1);
2975                 if (oi->typename)
2976                         strbuf_addstr(oi->typename, typename(co->type));
2977                 oi->whence = OI_CACHED;
2978                 return 0;
2979         }
2980
2981         if (!find_pack_entry(real, &e)) {
2982                 /* Most likely it's a loose object. */
2983                 if (!sha1_loose_object_info(real, oi, flags)) {
2984                         oi->whence = OI_LOOSE;
2985                         return 0;
2986                 }
2987
2988                 /* Not a loose object; someone else may have just packed it. */
2989                 reprepare_packed_git();
2990                 if (!find_pack_entry(real, &e))
2991                         return -1;
2992         }
2993
2994         /*
2995          * packed_object_info() does not follow the delta chain to
2996          * find out the real type, unless it is given oi->typep.
2997          */
2998         if (oi->typename && !oi->typep)
2999                 oi->typep = &real_type;
3000
3001         rtype = packed_object_info(e.p, e.offset, oi);
3002         if (rtype < 0) {
3003                 mark_bad_packed_object(e.p, real);
3004                 if (oi->typep == &real_type)
3005                         oi->typep = NULL;
3006                 return sha1_object_info_extended(real, oi, 0);
3007         } else if (in_delta_base_cache(e.p, e.offset)) {
3008                 oi->whence = OI_DBCACHED;
3009         } else {
3010                 oi->whence = OI_PACKED;
3011                 oi->u.packed.offset = e.offset;
3012                 oi->u.packed.pack = e.p;
3013                 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
3014                                          rtype == OBJ_OFS_DELTA);
3015         }
3016         if (oi->typename)
3017                 strbuf_addstr(oi->typename, typename(*oi->typep));
3018         if (oi->typep == &real_type)
3019                 oi->typep = NULL;
3020
3021         return 0;
3022 }
3023
3024 /* returns enum object_type or negative */
3025 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
3026 {
3027         enum object_type type;
3028         struct object_info oi = OBJECT_INFO_INIT;
3029
3030         oi.typep = &type;
3031         oi.sizep = sizep;
3032         if (sha1_object_info_extended(sha1, &oi, LOOKUP_REPLACE_OBJECT) < 0)
3033                 return -1;
3034         return type;
3035 }
3036
3037 static void *read_packed_sha1(const unsigned char *sha1,
3038                               enum object_type *type, unsigned long *size)
3039 {
3040         struct pack_entry e;
3041         void *data;
3042
3043         if (!find_pack_entry(sha1, &e))
3044                 return NULL;
3045         data = cache_or_unpack_entry(e.p, e.offset, size, type);
3046         if (!data) {
3047                 /*
3048                  * We're probably in deep shit, but let's try to fetch
3049                  * the required object anyway from another pack or loose.
3050                  * This should happen only in the presence of a corrupted
3051                  * pack, and is better than failing outright.
3052                  */
3053                 error("failed to read object %s at offset %"PRIuMAX" from %s",
3054                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
3055                 mark_bad_packed_object(e.p, sha1);
3056                 data = read_object(sha1, type, size);
3057         }
3058         return data;
3059 }
3060
3061 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
3062                       unsigned char *sha1)
3063 {
3064         struct cached_object *co;
3065
3066         hash_sha1_file(buf, len, typename(type), sha1);
3067         if (has_sha1_file(sha1) || find_cached_object(sha1))
3068                 return 0;
3069         ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
3070         co = &cached_objects[cached_object_nr++];
3071         co->size = len;
3072         co->type = type;
3073         co->buf = xmalloc(len);
3074         memcpy(co->buf, buf, len);
3075         hashcpy(co->sha1, sha1);
3076         return 0;
3077 }
3078
3079 static void *read_object(const unsigned char *sha1, enum object_type *type,
3080                          unsigned long *size)
3081 {
3082         unsigned long mapsize;
3083         void *map, *buf;
3084         struct cached_object *co;
3085
3086         co = find_cached_object(sha1);
3087         if (co) {
3088                 *type = co->type;
3089                 *size = co->size;
3090                 return xmemdupz(co->buf, co->size);
3091         }
3092
3093         buf = read_packed_sha1(sha1, type, size);
3094         if (buf)
3095                 return buf;
3096         map = map_sha1_file(sha1, &mapsize);
3097         if (map) {
3098                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
3099                 munmap(map, mapsize);
3100                 return buf;
3101         }
3102         reprepare_packed_git();
3103         return read_packed_sha1(sha1, type, size);
3104 }
3105
3106 /*
3107  * This function dies on corrupt objects; the callers who want to
3108  * deal with them should arrange to call read_object() and give error
3109  * messages themselves.
3110  */
3111 void *read_sha1_file_extended(const unsigned char *sha1,
3112                               enum object_type *type,
3113                               unsigned long *size,
3114                               unsigned flag)
3115 {
3116         void *data;
3117         const struct packed_git *p;
3118         const char *path;
3119         struct stat st;
3120         const unsigned char *repl = lookup_replace_object_extended(sha1, flag);
3121
3122         errno = 0;
3123         data = read_object(repl, type, size);
3124         if (data)
3125                 return data;
3126
3127         if (errno && errno != ENOENT)
3128                 die_errno("failed to read object %s", sha1_to_hex(sha1));
3129
3130         /* die if we replaced an object with one that does not exist */
3131         if (repl != sha1)
3132                 die("replacement %s not found for %s",
3133                     sha1_to_hex(repl), sha1_to_hex(sha1));
3134
3135         if (!stat_sha1_file(repl, &st, &path))
3136                 die("loose object %s (stored in %s) is corrupt",
3137                     sha1_to_hex(repl), path);
3138
3139         if ((p = has_packed_and_bad(repl)) != NULL)
3140                 die("packed object %s (stored in %s) is corrupt",
3141                     sha1_to_hex(repl), p->pack_name);
3142
3143         return NULL;
3144 }
3145
3146 void *read_object_with_reference(const unsigned char *sha1,
3147                                  const char *required_type_name,
3148                                  unsigned long *size,
3149                                  unsigned char *actual_sha1_return)
3150 {
3151         enum object_type type, required_type;
3152         void *buffer;
3153         unsigned long isize;
3154         unsigned char actual_sha1[20];
3155
3156         required_type = type_from_string(required_type_name);
3157         hashcpy(actual_sha1, sha1);
3158         while (1) {
3159                 int ref_length = -1;
3160                 const char *ref_type = NULL;
3161
3162                 buffer = read_sha1_file(actual_sha1, &type, &isize);
3163                 if (!buffer)
3164                         return NULL;
3165                 if (type == required_type) {
3166                         *size = isize;
3167                         if (actual_sha1_return)
3168                                 hashcpy(actual_sha1_return, actual_sha1);
3169                         return buffer;
3170                 }
3171                 /* Handle references */
3172                 else if (type == OBJ_COMMIT)
3173                         ref_type = "tree ";
3174                 else if (type == OBJ_TAG)
3175                         ref_type = "object ";
3176                 else {
3177                         free(buffer);
3178                         return NULL;
3179                 }
3180                 ref_length = strlen(ref_type);
3181
3182                 if (ref_length + 40 > isize ||
3183                     memcmp(buffer, ref_type, ref_length) ||
3184                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
3185                         free(buffer);
3186                         return NULL;
3187                 }
3188                 free(buffer);
3189                 /* Now we have the ID of the referred-to object in
3190                  * actual_sha1.  Check again. */
3191         }
3192 }
3193
3194 static void write_sha1_file_prepare(const void *buf, unsigned long len,
3195                                     const char *type, unsigned char *sha1,
3196                                     char *hdr, int *hdrlen)
3197 {
3198         git_SHA_CTX c;
3199
3200         /* Generate the header */
3201         *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
3202
3203         /* Sha1.. */
3204         git_SHA1_Init(&c);
3205         git_SHA1_Update(&c, hdr, *hdrlen);
3206         git_SHA1_Update(&c, buf, len);
3207         git_SHA1_Final(sha1, &c);
3208 }
3209
3210 /*
3211  * Move the just written object into its final resting place.
3212  */
3213 int finalize_object_file(const char *tmpfile, const char *filename)
3214 {
3215         int ret = 0;
3216
3217         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
3218                 goto try_rename;
3219         else if (link(tmpfile, filename))
3220                 ret = errno;
3221
3222         /*
3223          * Coda hack - coda doesn't like cross-directory links,
3224          * so we fall back to a rename, which will mean that it
3225          * won't be able to check collisions, but that's not a
3226          * big deal.
3227          *
3228          * The same holds for FAT formatted media.
3229          *
3230          * When this succeeds, we just return.  We have nothing
3231          * left to unlink.
3232          */
3233         if (ret && ret != EEXIST) {
3234         try_rename:
3235                 if (!rename(tmpfile, filename))
3236                         goto out;
3237                 ret = errno;
3238         }
3239         unlink_or_warn(tmpfile);
3240         if (ret) {
3241                 if (ret != EEXIST) {
3242                         return error_errno("unable to write sha1 filename %s", filename);
3243                 }
3244                 /* FIXME!!! Collision check here ? */
3245         }
3246
3247 out:
3248         if (adjust_shared_perm(filename))
3249                 return error("unable to set permission to '%s'", filename);
3250         return 0;
3251 }
3252
3253 static int write_buffer(int fd, const void *buf, size_t len)
3254 {
3255         if (write_in_full(fd, buf, len) < 0)
3256                 return error_errno("file write error");
3257         return 0;
3258 }
3259
3260 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
3261                    unsigned char *sha1)
3262 {
3263         char hdr[32];
3264         int hdrlen = sizeof(hdr);
3265         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3266         return 0;
3267 }
3268
3269 /* Finalize a file on disk, and close it. */
3270 static void close_sha1_file(int fd)
3271 {
3272         if (fsync_object_files)
3273                 fsync_or_die(fd, "sha1 file");
3274         if (close(fd) != 0)
3275                 die_errno("error when closing sha1 file");
3276 }
3277
3278 /* Size of directory component, including the ending '/' */
3279 static inline int directory_size(const char *filename)
3280 {
3281         const char *s = strrchr(filename, '/');
3282         if (!s)
3283                 return 0;
3284         return s - filename + 1;
3285 }
3286
3287 /*
3288  * This creates a temporary file in the same directory as the final
3289  * 'filename'
3290  *
3291  * We want to avoid cross-directory filename renames, because those
3292  * can have problems on various filesystems (FAT, NFS, Coda).
3293  */
3294 static int create_tmpfile(struct strbuf *tmp, const char *filename)
3295 {
3296         int fd, dirlen = directory_size(filename);
3297
3298         strbuf_reset(tmp);
3299         strbuf_add(tmp, filename, dirlen);
3300         strbuf_addstr(tmp, "tmp_obj_XXXXXX");
3301         fd = git_mkstemp_mode(tmp->buf, 0444);
3302         if (fd < 0 && dirlen && errno == ENOENT) {
3303                 /*
3304                  * Make sure the directory exists; note that the contents
3305                  * of the buffer are undefined after mkstemp returns an
3306                  * error, so we have to rewrite the whole buffer from
3307                  * scratch.
3308                  */
3309                 strbuf_reset(tmp);
3310                 strbuf_add(tmp, filename, dirlen - 1);
3311                 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
3312                         return -1;
3313                 if (adjust_shared_perm(tmp->buf))
3314                         return -1;
3315
3316                 /* Try again */
3317                 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
3318                 fd = git_mkstemp_mode(tmp->buf, 0444);
3319         }
3320         return fd;
3321 }
3322
3323 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
3324                               const void *buf, unsigned long len, time_t mtime)
3325 {
3326         int fd, ret;
3327         unsigned char compressed[4096];
3328         git_zstream stream;
3329         git_SHA_CTX c;
3330         unsigned char parano_sha1[20];
3331         static struct strbuf tmp_file = STRBUF_INIT;
3332         const char *filename = sha1_file_name(sha1);
3333
3334         fd = create_tmpfile(&tmp_file, filename);
3335         if (fd < 0) {
3336                 if (errno == EACCES)
3337                         return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3338                 else
3339                         return error_errno("unable to create temporary file");
3340         }
3341
3342         /* Set it up */
3343         git_deflate_init(&stream, zlib_compression_level);
3344         stream.next_out = compressed;
3345         stream.avail_out = sizeof(compressed);
3346         git_SHA1_Init(&c);
3347
3348         /* First header.. */
3349         stream.next_in = (unsigned char *)hdr;
3350         stream.avail_in = hdrlen;
3351         while (git_deflate(&stream, 0) == Z_OK)
3352                 ; /* nothing */
3353         git_SHA1_Update(&c, hdr, hdrlen);
3354
3355         /* Then the data itself.. */
3356         stream.next_in = (void *)buf;
3357         stream.avail_in = len;
3358         do {
3359                 unsigned char *in0 = stream.next_in;
3360                 ret = git_deflate(&stream, Z_FINISH);
3361                 git_SHA1_Update(&c, in0, stream.next_in - in0);
3362                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
3363                         die("unable to write sha1 file");
3364                 stream.next_out = compressed;
3365                 stream.avail_out = sizeof(compressed);
3366         } while (ret == Z_OK);
3367
3368         if (ret != Z_STREAM_END)
3369                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
3370         ret = git_deflate_end_gently(&stream);
3371         if (ret != Z_OK)
3372                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
3373         git_SHA1_Final(parano_sha1, &c);
3374         if (hashcmp(sha1, parano_sha1) != 0)
3375                 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
3376
3377         close_sha1_file(fd);
3378
3379         if (mtime) {
3380                 struct utimbuf utb;
3381                 utb.actime = mtime;
3382                 utb.modtime = mtime;
3383                 if (utime(tmp_file.buf, &utb) < 0)
3384                         warning_errno("failed utime() on %s", tmp_file.buf);
3385         }
3386
3387         return finalize_object_file(tmp_file.buf, filename);
3388 }
3389
3390 static int freshen_loose_object(const unsigned char *sha1)
3391 {
3392         return check_and_freshen(sha1, 1);
3393 }
3394
3395 static int freshen_packed_object(const unsigned char *sha1)
3396 {
3397         struct pack_entry e;
3398         if (!find_pack_entry(sha1, &e))
3399                 return 0;
3400         if (e.p->freshened)
3401                 return 1;
3402         if (!freshen_file(e.p->pack_name))
3403                 return 0;
3404         e.p->freshened = 1;
3405         return 1;
3406 }
3407
3408 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
3409 {
3410         char hdr[32];
3411         int hdrlen = sizeof(hdr);
3412
3413         /* Normally if we have it in the pack then we do not bother writing
3414          * it out into .git/objects/??/?{38} file.
3415          */
3416         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3417         if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3418                 return 0;
3419         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3420 }
3421
3422 int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
3423                              unsigned char *sha1, unsigned flags)
3424 {
3425         char *header;
3426         int hdrlen, status = 0;
3427
3428         /* type string, SP, %lu of the length plus NUL must fit this */
3429         hdrlen = strlen(type) + 32;
3430         header = xmalloc(hdrlen);
3431         write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
3432
3433         if (!(flags & HASH_WRITE_OBJECT))
3434                 goto cleanup;
3435         if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3436                 goto cleanup;
3437         status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
3438
3439 cleanup:
3440         free(header);
3441         return status;
3442 }
3443
3444 int force_object_loose(const unsigned char *sha1, time_t mtime)
3445 {
3446         void *buf;
3447         unsigned long len;
3448         enum object_type type;
3449         char hdr[32];
3450         int hdrlen;
3451         int ret;
3452
3453         if (has_loose_object(sha1))
3454                 return 0;
3455         buf = read_packed_sha1(sha1, &type, &len);
3456         if (!buf)
3457                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3458         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
3459         ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3460         free(buf);
3461
3462         return ret;
3463 }
3464
3465 int has_pack_index(const unsigned char *sha1)
3466 {
3467         struct stat st;
3468         if (stat(sha1_pack_index_name(sha1), &st))
3469                 return 0;
3470         return 1;
3471 }
3472
3473 int has_sha1_pack(const unsigned char *sha1)
3474 {
3475         struct pack_entry e;
3476         return find_pack_entry(sha1, &e);
3477 }
3478
3479 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
3480 {
3481         struct pack_entry e;
3482
3483         if (!startup_info->have_repository)
3484                 return 0;
3485         if (find_pack_entry(sha1, &e))
3486                 return 1;
3487         if (has_loose_object(sha1))
3488                 return 1;
3489         if (flags & HAS_SHA1_QUICK)
3490                 return 0;
3491         reprepare_packed_git();
3492         return find_pack_entry(sha1, &e);
3493 }
3494
3495 int has_object_file(const struct object_id *oid)
3496 {
3497         return has_sha1_file(oid->hash);
3498 }
3499
3500 int has_object_file_with_flags(const struct object_id *oid, int flags)
3501 {
3502         return has_sha1_file_with_flags(oid->hash, flags);
3503 }
3504
3505 static void check_tree(const void *buf, size_t size)
3506 {
3507         struct tree_desc desc;
3508         struct name_entry entry;
3509
3510         init_tree_desc(&desc, buf, size);
3511         while (tree_entry(&desc, &entry))
3512                 /* do nothing
3513                  * tree_entry() will die() on malformed entries */
3514                 ;
3515 }
3516
3517 static void check_commit(const void *buf, size_t size)
3518 {
3519         struct commit c;
3520         memset(&c, 0, sizeof(c));
3521         if (parse_commit_buffer(&c, buf, size))
3522                 die("corrupt commit");
3523 }
3524
3525 static void check_tag(const void *buf, size_t size)
3526 {
3527         struct tag t;
3528         memset(&t, 0, sizeof(t));
3529         if (parse_tag_buffer(&t, buf, size))
3530                 die("corrupt tag");
3531 }
3532
3533 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3534                      enum object_type type,
3535                      const char *path, unsigned flags)
3536 {
3537         int ret, re_allocated = 0;
3538         int write_object = flags & HASH_WRITE_OBJECT;
3539
3540         if (!type)
3541                 type = OBJ_BLOB;
3542
3543         /*
3544          * Convert blobs to git internal format
3545          */
3546         if ((type == OBJ_BLOB) && path) {
3547                 struct strbuf nbuf = STRBUF_INIT;
3548                 if (convert_to_git(path, buf, size, &nbuf,
3549                                    write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3550                         buf = strbuf_detach(&nbuf, &size);
3551                         re_allocated = 1;
3552                 }
3553         }
3554         if (flags & HASH_FORMAT_CHECK) {
3555                 if (type == OBJ_TREE)
3556                         check_tree(buf, size);
3557                 if (type == OBJ_COMMIT)
3558                         check_commit(buf, size);
3559                 if (type == OBJ_TAG)
3560                         check_tag(buf, size);
3561         }
3562
3563         if (write_object)
3564                 ret = write_sha1_file(buf, size, typename(type), sha1);
3565         else
3566                 ret = hash_sha1_file(buf, size, typename(type), sha1);
3567         if (re_allocated)
3568                 free(buf);
3569         return ret;
3570 }
3571
3572 static int index_stream_convert_blob(unsigned char *sha1, int fd,
3573                                      const char *path, unsigned flags)
3574 {
3575         int ret;
3576         const int write_object = flags & HASH_WRITE_OBJECT;
3577         struct strbuf sbuf = STRBUF_INIT;
3578
3579         assert(path);
3580         assert(would_convert_to_git_filter_fd(path));
3581
3582         convert_to_git_filter_fd(path, fd, &sbuf,
3583                                  write_object ? safe_crlf : SAFE_CRLF_FALSE);
3584
3585         if (write_object)
3586                 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3587                                       sha1);
3588         else
3589                 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3590                                      sha1);
3591         strbuf_release(&sbuf);
3592         return ret;
3593 }
3594
3595 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3596                       const char *path, unsigned flags)
3597 {
3598         struct strbuf sbuf = STRBUF_INIT;
3599         int ret;
3600
3601         if (strbuf_read(&sbuf, fd, 4096) >= 0)
3602                 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3603         else
3604                 ret = -1;
3605         strbuf_release(&sbuf);
3606         return ret;
3607 }
3608
3609 #define SMALL_FILE_SIZE (32*1024)
3610
3611 static int index_core(unsigned char *sha1, int fd, size_t size,
3612                       enum object_type type, const char *path,
3613                       unsigned flags)
3614 {
3615         int ret;
3616
3617         if (!size) {
3618                 ret = index_mem(sha1, "", size, type, path, flags);
3619         } else if (size <= SMALL_FILE_SIZE) {
3620                 char *buf = xmalloc(size);
3621                 if (size == read_in_full(fd, buf, size))
3622                         ret = index_mem(sha1, buf, size, type, path, flags);
3623                 else
3624                         ret = error_errno("short read");
3625                 free(buf);
3626         } else {
3627                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3628                 ret = index_mem(sha1, buf, size, type, path, flags);
3629                 munmap(buf, size);
3630         }
3631         return ret;
3632 }
3633
3634 /*
3635  * This creates one packfile per large blob unless bulk-checkin
3636  * machinery is "plugged".
3637  *
3638  * This also bypasses the usual "convert-to-git" dance, and that is on
3639  * purpose. We could write a streaming version of the converting
3640  * functions and insert that before feeding the data to fast-import
3641  * (or equivalent in-core API described above). However, that is
3642  * somewhat complicated, as we do not know the size of the filter
3643  * result, which we need to know beforehand when writing a git object.
3644  * Since the primary motivation for trying to stream from the working
3645  * tree file and to avoid mmaping it in core is to deal with large
3646  * binary blobs, they generally do not want to get any conversion, and
3647  * callers should avoid this code path when filters are requested.
3648  */
3649 static int index_stream(unsigned char *sha1, int fd, size_t size,
3650                         enum object_type type, const char *path,
3651                         unsigned flags)
3652 {
3653         return index_bulk_checkin(sha1, fd, size, type, path, flags);
3654 }
3655
3656 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3657              enum object_type type, const char *path, unsigned flags)
3658 {
3659         int ret;
3660
3661         /*
3662          * Call xsize_t() only when needed to avoid potentially unnecessary
3663          * die() for large files.
3664          */
3665         if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3666                 ret = index_stream_convert_blob(sha1, fd, path, flags);
3667         else if (!S_ISREG(st->st_mode))
3668                 ret = index_pipe(sha1, fd, type, path, flags);
3669         else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3670                  (path && would_convert_to_git(path)))
3671                 ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3672                                  flags);
3673         else
3674                 ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3675                                    flags);
3676         close(fd);
3677         return ret;
3678 }
3679
3680 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3681 {
3682         int fd;
3683         struct strbuf sb = STRBUF_INIT;
3684
3685         switch (st->st_mode & S_IFMT) {
3686         case S_IFREG:
3687                 fd = open(path, O_RDONLY);
3688                 if (fd < 0)
3689                         return error_errno("open(\"%s\")", path);
3690                 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3691                         return error("%s: failed to insert into database",
3692                                      path);
3693                 break;
3694         case S_IFLNK:
3695                 if (strbuf_readlink(&sb, path, st->st_size))
3696                         return error_errno("readlink(\"%s\")", path);
3697                 if (!(flags & HASH_WRITE_OBJECT))
3698                         hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3699                 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3700                         return error("%s: failed to insert into database",
3701                                      path);
3702                 strbuf_release(&sb);
3703                 break;
3704         case S_IFDIR:
3705                 return resolve_gitlink_ref(path, "HEAD", sha1);
3706         default:
3707                 return error("%s: unsupported file type", path);
3708         }
3709         return 0;
3710 }
3711
3712 int read_pack_header(int fd, struct pack_header *header)
3713 {
3714         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3715                 /* "eof before pack header was fully read" */
3716                 return PH_ERROR_EOF;
3717
3718         if (header->hdr_signature != htonl(PACK_SIGNATURE))
3719                 /* "protocol error (pack signature mismatch detected)" */
3720                 return PH_ERROR_PACK_SIGNATURE;
3721         if (!pack_version_ok(header->hdr_version))
3722                 /* "protocol error (pack version unsupported)" */
3723                 return PH_ERROR_PROTOCOL;
3724         return 0;
3725 }
3726
3727 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3728 {
3729         enum object_type type = sha1_object_info(sha1, NULL);
3730         if (type < 0)
3731                 die("%s is not a valid object", sha1_to_hex(sha1));
3732         if (type != expect)
3733                 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3734                     typename(expect));
3735 }
3736
3737 static int for_each_file_in_obj_subdir(int subdir_nr,
3738                                        struct strbuf *path,
3739                                        each_loose_object_fn obj_cb,
3740                                        each_loose_cruft_fn cruft_cb,
3741                                        each_loose_subdir_fn subdir_cb,
3742                                        void *data)
3743 {
3744         size_t baselen = path->len;
3745         DIR *dir = opendir(path->buf);
3746         struct dirent *de;
3747         int r = 0;
3748
3749         if (!dir) {
3750                 if (errno == ENOENT)
3751                         return 0;
3752                 return error_errno("unable to open %s", path->buf);
3753         }
3754
3755         while ((de = readdir(dir))) {
3756                 if (is_dot_or_dotdot(de->d_name))
3757                         continue;
3758
3759                 strbuf_setlen(path, baselen);
3760                 strbuf_addf(path, "/%s", de->d_name);
3761
3762                 if (strlen(de->d_name) == GIT_SHA1_HEXSZ - 2)  {
3763                         char hex[GIT_MAX_HEXSZ+1];
3764                         struct object_id oid;
3765
3766                         xsnprintf(hex, sizeof(hex), "%02x%s",
3767                                   subdir_nr, de->d_name);
3768                         if (!get_oid_hex(hex, &oid)) {
3769                                 if (obj_cb) {
3770                                         r = obj_cb(&oid, path->buf, data);
3771                                         if (r)
3772                                                 break;
3773                                 }
3774                                 continue;
3775                         }
3776                 }
3777
3778                 if (cruft_cb) {
3779                         r = cruft_cb(de->d_name, path->buf, data);
3780                         if (r)
3781                                 break;
3782                 }
3783         }
3784         closedir(dir);
3785
3786         strbuf_setlen(path, baselen);
3787         if (!r && subdir_cb)
3788                 r = subdir_cb(subdir_nr, path->buf, data);
3789
3790         return r;
3791 }
3792
3793 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3794                             each_loose_object_fn obj_cb,
3795                             each_loose_cruft_fn cruft_cb,
3796                             each_loose_subdir_fn subdir_cb,
3797                             void *data)
3798 {
3799         size_t baselen = path->len;
3800         int r = 0;
3801         int i;
3802
3803         for (i = 0; i < 256; i++) {
3804                 strbuf_addf(path, "/%02x", i);
3805                 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3806                                                 subdir_cb, data);
3807                 strbuf_setlen(path, baselen);
3808                 if (r)
3809                         break;
3810         }
3811
3812         return r;
3813 }
3814
3815 int for_each_loose_file_in_objdir(const char *path,
3816                                   each_loose_object_fn obj_cb,
3817                                   each_loose_cruft_fn cruft_cb,
3818                                   each_loose_subdir_fn subdir_cb,
3819                                   void *data)
3820 {
3821         struct strbuf buf = STRBUF_INIT;
3822         int r;
3823
3824         strbuf_addstr(&buf, path);
3825         r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3826                                               subdir_cb, data);
3827         strbuf_release(&buf);
3828
3829         return r;
3830 }
3831
3832 struct loose_alt_odb_data {
3833         each_loose_object_fn *cb;
3834         void *data;
3835 };
3836
3837 static int loose_from_alt_odb(struct alternate_object_database *alt,
3838                               void *vdata)
3839 {
3840         struct loose_alt_odb_data *data = vdata;
3841         struct strbuf buf = STRBUF_INIT;
3842         int r;
3843
3844         strbuf_addstr(&buf, alt->path);
3845         r = for_each_loose_file_in_objdir_buf(&buf,
3846                                               data->cb, NULL, NULL,
3847                                               data->data);
3848         strbuf_release(&buf);
3849         return r;
3850 }
3851
3852 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3853 {
3854         struct loose_alt_odb_data alt;
3855         int r;
3856
3857         r = for_each_loose_file_in_objdir(get_object_directory(),
3858                                           cb, NULL, NULL, data);
3859         if (r)
3860                 return r;
3861
3862         if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3863                 return 0;
3864
3865         alt.cb = cb;
3866         alt.data = data;
3867         return foreach_alt_odb(loose_from_alt_odb, &alt);
3868 }
3869
3870 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3871 {
3872         uint32_t i;
3873         int r = 0;
3874
3875         for (i = 0; i < p->num_objects; i++) {
3876                 struct object_id oid;
3877
3878                 if (!nth_packed_object_oid(&oid, p, i))
3879                         return error("unable to get sha1 of object %u in %s",
3880                                      i, p->pack_name);
3881
3882                 r = cb(&oid, p, i, data);
3883                 if (r)
3884                         break;
3885         }
3886         return r;
3887 }
3888
3889 int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3890 {
3891         struct packed_git *p;
3892         int r = 0;
3893         int pack_errors = 0;
3894
3895         prepare_packed_git();
3896         for (p = packed_git; p; p = p->next) {
3897                 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3898                         continue;
3899                 if (open_pack_index(p)) {
3900                         pack_errors = 1;
3901                         continue;
3902                 }
3903                 r = for_each_object_in_pack(p, cb, data);
3904                 if (r)
3905                         break;
3906         }
3907         return r ? r : pack_errors;
3908 }
3909
3910 static int check_stream_sha1(git_zstream *stream,
3911                              const char *hdr,
3912                              unsigned long size,
3913                              const char *path,
3914                              const unsigned char *expected_sha1)
3915 {
3916         git_SHA_CTX c;
3917         unsigned char real_sha1[GIT_MAX_RAWSZ];
3918         unsigned char buf[4096];
3919         unsigned long total_read;
3920         int status = Z_OK;
3921
3922         git_SHA1_Init(&c);
3923         git_SHA1_Update(&c, hdr, stream->total_out);
3924
3925         /*
3926          * We already read some bytes into hdr, but the ones up to the NUL
3927          * do not count against the object's content size.
3928          */
3929         total_read = stream->total_out - strlen(hdr) - 1;
3930
3931         /*
3932          * This size comparison must be "<=" to read the final zlib packets;
3933          * see the comment in unpack_sha1_rest for details.
3934          */
3935         while (total_read <= size &&
3936                (status == Z_OK || status == Z_BUF_ERROR)) {
3937                 stream->next_out = buf;
3938                 stream->avail_out = sizeof(buf);
3939                 if (size - total_read < stream->avail_out)
3940                         stream->avail_out = size - total_read;
3941                 status = git_inflate(stream, Z_FINISH);
3942                 git_SHA1_Update(&c, buf, stream->next_out - buf);
3943                 total_read += stream->next_out - buf;
3944         }
3945         git_inflate_end(stream);
3946
3947         if (status != Z_STREAM_END) {
3948                 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
3949                 return -1;
3950         }
3951         if (stream->avail_in) {
3952                 error("garbage at end of loose object '%s'",
3953                       sha1_to_hex(expected_sha1));
3954                 return -1;
3955         }
3956
3957         git_SHA1_Final(real_sha1, &c);
3958         if (hashcmp(expected_sha1, real_sha1)) {
3959                 error("sha1 mismatch for %s (expected %s)", path,
3960                       sha1_to_hex(expected_sha1));
3961                 return -1;
3962         }
3963
3964         return 0;
3965 }
3966
3967 int read_loose_object(const char *path,
3968                       const unsigned char *expected_sha1,
3969                       enum object_type *type,
3970                       unsigned long *size,
3971                       void **contents)
3972 {
3973         int ret = -1;
3974         void *map = NULL;
3975         unsigned long mapsize;
3976         git_zstream stream;
3977         char hdr[32];
3978
3979         *contents = NULL;
3980
3981         map = map_sha1_file_1(path, NULL, &mapsize);
3982         if (!map) {
3983                 error_errno("unable to mmap %s", path);
3984                 goto out;
3985         }
3986
3987         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
3988                 error("unable to unpack header of %s", path);
3989                 goto out;
3990         }
3991
3992         *type = parse_sha1_header(hdr, size);
3993         if (*type < 0) {
3994                 error("unable to parse header of %s", path);
3995                 git_inflate_end(&stream);
3996                 goto out;
3997         }
3998
3999         if (*type == OBJ_BLOB) {
4000                 if (check_stream_sha1(&stream, hdr, *size, path, expected_sha1) < 0)
4001                         goto out;
4002         } else {
4003                 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_sha1);
4004                 if (!*contents) {
4005                         error("unable to unpack contents of %s", path);
4006                         git_inflate_end(&stream);
4007                         goto out;
4008                 }
4009                 if (check_sha1_signature(expected_sha1, *contents,
4010                                          *size, typename(*type))) {
4011                         error("sha1 mismatch for %s (expected %s)", path,
4012                               sha1_to_hex(expected_sha1));
4013                         free(*contents);
4014                         goto out;
4015                 }
4016         }
4017
4018         ret = 0; /* everything checks out */
4019
4020 out:
4021         if (map)
4022                 munmap(map, mapsize);
4023         return ret;
4024 }