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