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