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