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