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