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