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