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