]> git.ipfire.org Git - thirdparty/git.git/blame - object-file.c
t: teach lint that RHS of 'local VAR=VAL' needs to be quoted
[thirdparty/git.git] / object-file.c
CommitLineData
0fcfd160
LT
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
e5afd444 6 * This handles basic git object files - packing, unpacking,
0fcfd160
LT
7 * creation etc.
8 */
5e3f94df 9#include "git-compat-util.h"
0b027f6c 10#include "abspath.h"
b2141fc1 11#include "config.h"
73359a9b 12#include "convert.h"
32a8f510 13#include "environment.h"
f394e093 14#include "gettext.h"
41771fa4 15#include "hex.h"
6eac50d8 16#include "string-list.h"
697cc8ef 17#include "lockfile.h"
a733cb60 18#include "pack.h"
8e440259 19#include "commit.h"
4dd1fbc7 20#include "run-command.h"
f35a6d3b 21#include "refs.h"
568508e7 22#include "bulk-checkin.h"
031dc927 23#include "repository.h"
47f351e9 24#include "replace-object.h"
090ea126 25#include "streaming.h"
543c5caa 26#include "dir.h"
12d95ef6 27#include "list.h"
cf3c6352 28#include "quote.h"
4f39cd82 29#include "packfile.h"
87bed179 30#include "object-file.h"
90c62155 31#include "object-store.h"
e3d2f20e 32#include "oidtree.h"
c339932b 33#include "path.h"
b14ed5ad 34#include "promisor-remote.h"
e38da487 35#include "setup.h"
a35e03de 36#include "submodule.h"
69bbbe48 37#include "fsck.h"
63a6745a
EB
38#include "loose.h"
39#include "object-file-convert.h"
e05db0fd 40
1af64f73 41/* The maximum size for an object header. */
42#define MAX_HEADER_LEN 32
43
e1ccd7e2 44
45#define EMPTY_TREE_SHA1_BIN_LITERAL \
46 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
47 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
13eeedb5 48#define EMPTY_TREE_SHA256_BIN_LITERAL \
49 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
50 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
51 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
52 "\x53\x21"
e1ccd7e2 53
54#define EMPTY_BLOB_SHA1_BIN_LITERAL \
55 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
56 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
13eeedb5 57#define EMPTY_BLOB_SHA256_BIN_LITERAL \
58 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
59 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
60 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
61 "\x18\x13"
e1ccd7e2 62
e1ccd7e2 63static const struct object_id empty_tree_oid = {
5a6dce70 64 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
65 .algo = GIT_HASH_SHA1,
8576fde6 66};
e1ccd7e2 67static const struct object_id empty_blob_oid = {
5a6dce70 68 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
69 .algo = GIT_HASH_SHA1,
8576fde6 70};
14228447 71static const struct object_id null_oid_sha1 = {
72 .hash = {0},
73 .algo = GIT_HASH_SHA1,
74};
13eeedb5 75static const struct object_id empty_tree_oid_sha256 = {
5a6dce70 76 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
77 .algo = GIT_HASH_SHA256,
13eeedb5 78};
79static const struct object_id empty_blob_oid_sha256 = {
5a6dce70 80 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
81 .algo = GIT_HASH_SHA256,
13eeedb5 82};
14228447 83static const struct object_id null_oid_sha256 = {
84 .hash = {0},
85 .algo = GIT_HASH_SHA256,
86};
88cd621d 87
ac73cedf 88static void git_hash_sha1_init(git_hash_ctx *ctx)
f50e766b 89{
ac73cedf 90 git_SHA1_Init(&ctx->sha1);
f50e766b 91}
92
768e30ea 93static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
94{
95 git_SHA1_Clone(&dst->sha1, &src->sha1);
96}
97
ac73cedf 98static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
f50e766b 99{
ac73cedf 100 git_SHA1_Update(&ctx->sha1, data, len);
f50e766b 101}
102
ac73cedf 103static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
f50e766b 104{
ac73cedf 105 git_SHA1_Final(hash, &ctx->sha1);
f50e766b 106}
107
ab795f0d 108static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
109{
110 git_SHA1_Final(oid->hash, &ctx->sha1);
111 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
5a6dce70 112 oid->algo = GIT_HASH_SHA1;
ab795f0d 113}
114
13eeedb5 115
116static void git_hash_sha256_init(git_hash_ctx *ctx)
117{
118 git_SHA256_Init(&ctx->sha256);
119}
120
768e30ea 121static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
122{
123 git_SHA256_Clone(&dst->sha256, &src->sha256);
124}
125
13eeedb5 126static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
127{
128 git_SHA256_Update(&ctx->sha256, data, len);
129}
130
131static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
132{
133 git_SHA256_Final(hash, &ctx->sha256);
134}
135
ab795f0d 136static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
137{
138 git_SHA256_Final(oid->hash, &ctx->sha256);
139 /*
140 * This currently does nothing, so the compiler should optimize it out,
141 * but keep it in case we extend the hash size again.
142 */
143 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
5a6dce70 144 oid->algo = GIT_HASH_SHA256;
ab795f0d 145}
146
9eb6cdad 147static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
f50e766b 148{
1a07e59c 149 BUG("trying to init unknown hash");
f50e766b 150}
151
9eb6cdad
JK
152static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
153 const git_hash_ctx *src UNUSED)
768e30ea 154{
155 BUG("trying to clone unknown hash");
156}
157
9eb6cdad
JK
158static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
159 const void *data UNUSED,
160 size_t len UNUSED)
f50e766b 161{
1a07e59c 162 BUG("trying to update unknown hash");
f50e766b 163}
164
9eb6cdad
JK
165static void git_hash_unknown_final(unsigned char *hash UNUSED,
166 git_hash_ctx *ctx UNUSED)
f50e766b 167{
1a07e59c 168 BUG("trying to finalize unknown hash");
f50e766b 169}
170
9eb6cdad
JK
171static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
172 git_hash_ctx *ctx UNUSED)
ab795f0d 173{
174 BUG("trying to finalize unknown hash");
175}
176
f50e766b 177const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
178 {
0cb9872e
ÆAB
179 .name = NULL,
180 .format_id = 0x00000000,
181 .rawsz = 0,
182 .hexsz = 0,
183 .blksz = 0,
184 .init_fn = git_hash_unknown_init,
185 .clone_fn = git_hash_unknown_clone,
186 .update_fn = git_hash_unknown_update,
187 .final_fn = git_hash_unknown_final,
188 .final_oid_fn = git_hash_unknown_final_oid,
189 .empty_tree = NULL,
190 .empty_blob = NULL,
191 .null_oid = NULL,
f50e766b 192 },
193 {
0cb9872e
ÆAB
194 .name = "sha1",
195 .format_id = GIT_SHA1_FORMAT_ID,
196 .rawsz = GIT_SHA1_RAWSZ,
197 .hexsz = GIT_SHA1_HEXSZ,
198 .blksz = GIT_SHA1_BLKSZ,
199 .init_fn = git_hash_sha1_init,
200 .clone_fn = git_hash_sha1_clone,
201 .update_fn = git_hash_sha1_update,
202 .final_fn = git_hash_sha1_final,
203 .final_oid_fn = git_hash_sha1_final_oid,
204 .empty_tree = &empty_tree_oid,
205 .empty_blob = &empty_blob_oid,
206 .null_oid = &null_oid_sha1,
f50e766b 207 },
13eeedb5 208 {
0cb9872e
ÆAB
209 .name = "sha256",
210 .format_id = GIT_SHA256_FORMAT_ID,
211 .rawsz = GIT_SHA256_RAWSZ,
212 .hexsz = GIT_SHA256_HEXSZ,
213 .blksz = GIT_SHA256_BLKSZ,
214 .init_fn = git_hash_sha256_init,
215 .clone_fn = git_hash_sha256_clone,
216 .update_fn = git_hash_sha256_update,
217 .final_fn = git_hash_sha256_final,
218 .final_oid_fn = git_hash_sha256_final_oid,
219 .empty_tree = &empty_tree_oid_sha256,
220 .empty_blob = &empty_blob_oid_sha256,
221 .null_oid = &null_oid_sha256,
13eeedb5 222 }
f50e766b 223};
224
14228447 225const struct object_id *null_oid(void)
226{
227 return the_hash_algo->null_oid;
228}
229
d8a92ced 230const char *empty_tree_oid_hex(void)
231{
232 static char buf[GIT_MAX_HEXSZ + 1];
233 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
234}
235
236const char *empty_blob_oid_hex(void)
237{
238 static char buf[GIT_MAX_HEXSZ + 1];
239 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
240}
241
2f90b9d9 242int hash_algo_by_name(const char *name)
243{
244 int i;
245 if (!name)
246 return GIT_HASH_UNKNOWN;
247 for (i = 1; i < GIT_HASH_NALGOS; i++)
248 if (!strcmp(name, hash_algos[i].name))
249 return i;
250 return GIT_HASH_UNKNOWN;
251}
252
253int hash_algo_by_id(uint32_t format_id)
254{
255 int i;
256 for (i = 1; i < GIT_HASH_NALGOS; i++)
257 if (format_id == hash_algos[i].format_id)
258 return i;
259 return GIT_HASH_UNKNOWN;
260}
261
95399788 262int hash_algo_by_length(int len)
263{
264 int i;
265 for (i = 1; i < GIT_HASH_NALGOS; i++)
266 if (len == hash_algos[i].rawsz)
267 return i;
268 return GIT_HASH_UNKNOWN;
269}
2f90b9d9 270
c597ba80
NTND
271/*
272 * This is meant to hold a *small* number of objects that you would
c7c33f50 273 * want repo_read_object_file() to be able to return, but yet you do not want
c597ba80
NTND
274 * to write them into the object store (e.g. a browse-only
275 * application).
276 */
277static struct cached_object {
62ba93ea 278 struct object_id oid;
c597ba80
NTND
279 enum object_type type;
280 void *buf;
281 unsigned long size;
282} *cached_objects;
283static int cached_object_nr, cached_object_alloc;
284
285static struct cached_object empty_tree = {
50103649
ÆAB
286 .oid = {
287 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
288 },
289 .type = OBJ_TREE,
290 .buf = "",
c597ba80
NTND
291};
292
62ba93ea 293static struct cached_object *find_cached_object(const struct object_id *oid)
c597ba80
NTND
294{
295 int i;
296 struct cached_object *co = cached_objects;
297
298 for (i = 0; i < cached_object_nr; i++, co++) {
4a7e27e9 299 if (oideq(&co->oid, oid))
c597ba80
NTND
300 return co;
301 }
4a7e27e9 302 if (oideq(oid, the_hash_algo->empty_tree))
c597ba80
NTND
303 return &empty_tree;
304 return NULL;
305}
306
9472935d 307
8462ff43 308static int get_conv_flags(unsigned flags)
9472935d
TB
309{
310 if (flags & HASH_RENORMALIZE)
8462ff43 311 return CONV_EOL_RENORMALIZE;
9472935d 312 else if (flags & HASH_WRITE_OBJECT)
107642fe 313 return global_conv_flags_eol | CONV_WRITE_OBJECT;
9472935d 314 else
8462ff43 315 return 0;
9472935d
TB
316}
317
318
90a6464b
JH
319int mkdir_in_gitdir(const char *path)
320{
321 if (mkdir(path, 0777)) {
322 int saved_errno = errno;
323 struct stat st;
324 struct strbuf sb = STRBUF_INIT;
325
326 if (errno != EEXIST)
327 return -1;
328 /*
329 * Are we looking at a path in a symlinked worktree
330 * whose original repository does not yet have it?
331 * e.g. .git/rr-cache pointing at its original
332 * repository in which the user hasn't performed any
333 * conflict resolution yet?
334 */
335 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
336 strbuf_readlink(&sb, path, st.st_size) ||
337 !is_absolute_path(sb.buf) ||
338 mkdir(sb.buf, 0777)) {
339 strbuf_release(&sb);
340 errno = saved_errno;
341 return -1;
342 }
343 strbuf_release(&sb);
344 }
345 return adjust_shared_perm(path);
346}
347
eb3c027e 348static enum scld_error safe_create_leading_directories_1(char *path, int share)
b2cb9425 349{
26c8ae2a 350 char *next_component = path + offset_1st_component(path);
0be0521b 351 enum scld_error ret = SCLD_OK;
67d42212 352
0be0521b 353 while (ret == SCLD_OK && next_component) {
f0502332 354 struct stat st;
0f527403 355 char *slash = next_component, slash_character;
f0502332 356
0f527403
MH
357 while (*slash && !is_dir_sep(*slash))
358 slash++;
359
360 if (!*slash)
b2cb9425 361 break;
bf10cf70 362
26c8ae2a 363 next_component = slash + 1;
0f527403 364 while (is_dir_sep(*next_component))
bf10cf70 365 next_component++;
26c8ae2a 366 if (!*next_component)
5f0bdf50 367 break;
831651fd 368
0f527403 369 slash_character = *slash;
831651fd 370 *slash = '\0';
67d42212
JR
371 if (!stat(path, &st)) {
372 /* path exists */
204a047f
MH
373 if (!S_ISDIR(st.st_mode)) {
374 errno = ENOTDIR;
0be0521b 375 ret = SCLD_EXISTS;
204a047f 376 }
53a39721 377 } else if (mkdir(path, 0777)) {
928734d9 378 if (errno == EEXIST &&
9e6f885d 379 !stat(path, &st) && S_ISDIR(st.st_mode))
928734d9 380 ; /* somebody created it since we checked */
18d37e86
MH
381 else if (errno == ENOENT)
382 /*
383 * Either mkdir() failed because
384 * somebody just pruned the containing
385 * directory, or stat() failed because
386 * the file that was in our way was
387 * just removed. Either way, inform
388 * the caller that it might be worth
389 * trying again:
390 */
391 ret = SCLD_VANISHED;
9e6f885d 392 else
0be0521b 393 ret = SCLD_FAILED;
eb3c027e 394 } else if (share && adjust_shared_perm(path)) {
0be0521b 395 ret = SCLD_PERMS;
457f06d6 396 }
0f527403 397 *slash = slash_character;
b2cb9425 398 }
9e6f885d 399 return ret;
b2cb9425 400}
723c31fe 401
eb3c027e
MT
402enum scld_error safe_create_leading_directories(char *path)
403{
404 return safe_create_leading_directories_1(path, 1);
405}
406
407enum scld_error safe_create_leading_directories_no_share(char *path)
408{
409 return safe_create_leading_directories_1(path, 0);
410}
411
0be0521b 412enum scld_error safe_create_leading_directories_const(const char *path)
8e21d63b 413{
02944307 414 int save_errno;
8e21d63b
JK
415 /* path points to cache entries, so xstrdup before messing with it */
416 char *buf = xstrdup(path);
0be0521b 417 enum scld_error result = safe_create_leading_directories(buf);
02944307
MH
418
419 save_errno = errno;
8e21d63b 420 free(buf);
02944307 421 errno = save_errno;
8e21d63b
JK
422 return result;
423}
424
514c5fdd 425static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
ace1534d
JH
426{
427 int i;
94b5e093 428 for (i = 0; i < the_hash_algo->rawsz; i++) {
ace1534d 429 static char hex[] = "0123456789abcdef";
514c5fdd 430 unsigned int val = oid->hash[i];
f7b7774f
JK
431 strbuf_addch(buf, hex[val >> 4]);
432 strbuf_addch(buf, hex[val & 0xf]);
afbba2f0 433 if (!i)
f7b7774f 434 strbuf_addch(buf, '/');
ace1534d
JH
435 }
436}
437
f0eaf638
JK
438static const char *odb_loose_path(struct object_directory *odb,
439 struct strbuf *buf,
514c5fdd 440 const struct object_id *oid)
0fcfd160 441{
b69fb867 442 strbuf_reset(buf);
f0eaf638 443 strbuf_addstr(buf, odb->path);
34498471 444 strbuf_addch(buf, '/');
514c5fdd 445 fill_loose_path(buf, oid);
f3f043a1 446 return buf->buf;
0fcfd160
LT
447}
448
f3f043a1 449const char *loose_object_path(struct repository *r, struct strbuf *buf,
514c5fdd 450 const struct object_id *oid)
29ec6af2 451{
514c5fdd 452 return odb_loose_path(r->objects->odb, buf, oid);
0fcfd160
LT
453}
454
4ea82473
JK
455/*
456 * Return non-zero iff the path is usable as an alternate object database.
457 */
13313fc3
SB
458static int alt_odb_usable(struct raw_object_store *o,
459 struct strbuf *path,
cf2dc1c2 460 const char *normalized_objdir, khiter_t *pos)
4ea82473 461{
cf2dc1c2 462 int r;
4ea82473
JK
463
464 /* Detect cases where alternate disappeared */
465 if (!is_directory(path->buf)) {
259328b7
NTND
466 error(_("object directory %s does not exist; "
467 "check .git/objects/info/alternates"),
4ea82473
JK
468 path->buf);
469 return 0;
470 }
471
472 /*
473 * Prevent the common mistake of listing the same
474 * thing twice, or object directory itself.
475 */
cf2dc1c2
EW
476 if (!o->odb_by_path) {
477 khiter_t p;
478
479 o->odb_by_path = kh_init_odb_path_map();
480 assert(!o->odb->next);
481 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
482 assert(r == 1); /* never used */
483 kh_value(o->odb_by_path, p) = o->odb;
4ea82473 484 }
cf2dc1c2 485 if (fspatheq(path->buf, normalized_objdir))
4ea82473 486 return 0;
cf2dc1c2
EW
487 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
488 /* r: 0 = exists, 1 = never used, 2 = deleted */
489 return r == 0 ? 0 : 1;
4ea82473
JK
490}
491
ddd5d056
JH
492/*
493 * Prepare alternate object database registry.
d5a63b99
JH
494 *
495 * The variable alt_odb_list points at the list of struct
263db403 496 * object_directory. The elements on this list come from
d5a63b99
JH
497 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
498 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
1494e038
JH
499 * whose contents is similar to that environment variable but can be
500 * LF separated. Its base points at a statically allocated buffer that
d5a63b99
JH
501 * contains "/the/directory/corresponding/to/.git/objects/...", while
502 * its name points just after the slash at the end of ".git/objects/"
e5afd444
503 * in the example above, and has enough space to hold all hex characters
504 * of the object ID, an extra slash for the first level indirection, and
505 * the terminating NUL.
ddd5d056 506 */
77f012e8
SB
507static void read_info_alternates(struct repository *r,
508 const char *relative_base,
509 int depth);
407532f8 510static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
cfc62fc9 511 const char *relative_base, int depth, const char *normalized_objdir)
ace1534d 512{
263db403 513 struct object_directory *ent;
5bdf0a84 514 struct strbuf pathbuf = STRBUF_INIT;
199337d6 515 struct strbuf tmp = STRBUF_INIT;
cf2dc1c2 516 khiter_t pos;
199337d6 517 int ret = -1;
d5a63b99 518
407532f8 519 if (!is_absolute_path(entry->buf) && relative_base) {
4ac9006f 520 strbuf_realpath(&pathbuf, relative_base, 1);
5bdf0a84 521 strbuf_addch(&pathbuf, '/');
c2f493a4 522 }
407532f8 523 strbuf_addbuf(&pathbuf, entry);
c2f493a4 524
199337d6 525 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
259328b7 526 error(_("unable to normalize alternate object path: %s"),
670c359d 527 pathbuf.buf);
199337d6 528 goto error;
670c359d 529 }
199337d6 530 strbuf_swap(&pathbuf, &tmp);
5bdf0a84
HW
531
532 /*
533 * The trailing slash after the directory name is given by
534 * this function at the end. Remove duplicates.
535 */
4ea82473
JK
536 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
537 strbuf_setlen(&pathbuf, pathbuf.len - 1);
5bdf0a84 538
199337d6
GC
539 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
540 goto error;
c2f493a4 541
ca56dadb 542 CALLOC_ARRAY(ent, 1);
cf2dc1c2
EW
543 /* pathbuf.buf is already in r->objects->odb_by_path */
544 ent->path = strbuf_detach(&pathbuf, NULL);
c2f493a4
MW
545
546 /* add the alternate entry */
f0eaf638
JK
547 *r->objects->odb_tail = ent;
548 r->objects->odb_tail = &(ent->next);
c2f493a4 549 ent->next = NULL;
cf2dc1c2
EW
550 assert(r->objects->odb_by_path);
551 kh_value(r->objects->odb_by_path, pos) = ent;
c2f493a4
MW
552
553 /* recursively add alternates */
cf2dc1c2 554 read_info_alternates(r, ent->path, depth + 1);
199337d6
GC
555 ret = 0;
556 error:
557 strbuf_release(&tmp);
558 strbuf_release(&pathbuf);
559 return ret;
c2f493a4
MW
560}
561
cf3c6352
JK
562static const char *parse_alt_odb_entry(const char *string,
563 int sep,
564 struct strbuf *out)
565{
566 const char *end;
567
568 strbuf_reset(out);
569
570 if (*string == '#') {
571 /* comment; consume up to next separator */
572 end = strchrnul(string, sep);
573 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
574 /*
575 * quoted path; unquote_c_style has copied the
576 * data for us and set "end". Broken quoting (e.g.,
577 * an entry that doesn't end with a quote) falls
578 * back to the unquoted case below.
579 */
580 } else {
581 /* normal, unquoted path */
582 end = strchrnul(string, sep);
583 strbuf_add(out, string, end - string);
584 }
585
586 if (*end)
587 end++;
588 return end;
589}
590
77f012e8
SB
591static void link_alt_odb_entries(struct repository *r, const char *alt,
592 int sep, const char *relative_base, int depth)
c2f493a4 593{
539e7506 594 struct strbuf objdirbuf = STRBUF_INIT;
cf3c6352 595 struct strbuf entry = STRBUF_INIT;
c2f493a4 596
f28e3668
JK
597 if (!alt || !*alt)
598 return;
599
c2f493a4 600 if (depth > 5) {
259328b7 601 error(_("%s: ignoring alternate object stores, nesting too deep"),
c2f493a4
MW
602 relative_base);
603 return;
604 }
605
199337d6 606 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
539e7506 607
cf3c6352
JK
608 while (*alt) {
609 alt = parse_alt_odb_entry(alt, sep, &entry);
610 if (!entry.len)
9577e7e3 611 continue;
407532f8 612 link_alt_odb_entry(r, &entry,
cfc62fc9 613 relative_base, depth, objdirbuf.buf);
9577e7e3 614 }
cf3c6352 615 strbuf_release(&entry);
539e7506 616 strbuf_release(&objdirbuf);
d5a63b99
JH
617}
618
77f012e8
SB
619static void read_info_alternates(struct repository *r,
620 const char *relative_base,
621 int depth)
d5a63b99 622{
5015f01c 623 char *path;
dc732bd5 624 struct strbuf buf = STRBUF_INIT;
d5a63b99 625
5015f01c 626 path = xstrfmt("%s/info/alternates", relative_base);
dc732bd5 627 if (strbuf_read_file(&buf, path, 1024) < 0) {
f0f7bebe 628 warn_on_fopen_errors(path);
dc732bd5 629 free(path);
9a217f2a 630 return;
ace1534d 631 }
d5a63b99 632
77f012e8 633 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
dc732bd5
JK
634 strbuf_release(&buf);
635 free(path);
ace1534d
JH
636}
637
bef70b22
DB
638void add_to_alternates_file(const char *reference)
639{
f132a127 640 struct lock_file lock = LOCK_INIT;
77b9b1d1
JK
641 char *alts = git_pathdup("objects/info/alternates");
642 FILE *in, *out;
f132a127 643 int found = 0;
77b9b1d1 644
f132a127
645 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
646 out = fdopen_lock_file(&lock, "w");
77b9b1d1 647 if (!out)
259328b7 648 die_errno(_("unable to fdopen alternates lockfile"));
77b9b1d1
JK
649
650 in = fopen(alts, "r");
651 if (in) {
652 struct strbuf line = STRBUF_INIT;
77b9b1d1 653
3f163962 654 while (strbuf_getline(&line, in) != EOF) {
77b9b1d1
JK
655 if (!strcmp(reference, line.buf)) {
656 found = 1;
657 break;
658 }
659 fprintf_or_die(out, "%s\n", line.buf);
660 }
661
662 strbuf_release(&line);
663 fclose(in);
77b9b1d1
JK
664 }
665 else if (errno != ENOENT)
259328b7 666 die_errno(_("unable to read alternates file"));
77b9b1d1 667
f132a127
668 if (found) {
669 rollback_lock_file(&lock);
670 } else {
77b9b1d1 671 fprintf_or_die(out, "%s\n", reference);
f132a127 672 if (commit_lock_file(&lock))
259328b7 673 die_errno(_("unable to move new alternates file into place"));
f0eaf638 674 if (the_repository->objects->loaded_alternates)
93d8d1e2
SB
675 link_alt_odb_entries(the_repository, reference,
676 '\n', NULL, 0);
77b9b1d1
JK
677 }
678 free(alts);
bef70b22
DB
679}
680
a5b34d21
JK
681void add_to_alternates_memory(const char *reference)
682{
683 /*
684 * Make sure alternates are initialized, or else our entry may be
685 * overwritten when they are.
686 */
0b209034 687 prepare_alt_odb(the_repository);
a5b34d21 688
93d8d1e2
SB
689 link_alt_odb_entries(the_repository, reference,
690 '\n', NULL, 0);
a5b34d21
JK
691}
692
b3cecf49
NS
693struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
694{
695 struct object_directory *new_odb;
696
697 /*
698 * Make sure alternates are initialized, or else our entry may be
699 * overwritten when they are.
700 */
701 prepare_alt_odb(the_repository);
702
703 /*
704 * Make a new primary odb and link the old primary ODB in as an
705 * alternate
706 */
707 new_odb = xcalloc(1, sizeof(*new_odb));
708 new_odb->path = xstrdup(dir);
ecd81dfc
NS
709
710 /*
711 * Disable ref updates while a temporary odb is active, since
712 * the objects in the database may roll back.
713 */
714 new_odb->disable_ref_updates = 1;
b3cecf49
NS
715 new_odb->will_destroy = will_destroy;
716 new_odb->next = the_repository->objects->odb;
717 the_repository->objects->odb = new_odb;
718 return new_odb->next;
719}
720
721void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
722{
723 struct object_directory *cur_odb = the_repository->objects->odb;
724
725 if (strcmp(old_path, cur_odb->path))
726 BUG("expected %s as primary object store; found %s",
727 old_path, cur_odb->path);
728
729 if (cur_odb->next != restore_odb)
730 BUG("we expect the old primary object store to be the first alternate");
731
732 the_repository->objects->odb = restore_odb;
733 free_object_directory(cur_odb);
734}
735
9eeea7d2
SB
736/*
737 * Compute the exact path an alternate is at and returns it. In case of
738 * error NULL is returned and the human readable error is added to `err`
efde7b72 739 * `path` may be relative and should point to $GIT_DIR.
9eeea7d2
SB
740 * `err` must not be null.
741 */
742char *compute_alternate_path(const char *path, struct strbuf *err)
743{
744 char *ref_git = NULL;
4530a85b 745 const char *repo;
9eeea7d2
SB
746 int seen_error = 0;
747
4530a85b
AM
748 ref_git = real_pathdup(path, 0);
749 if (!ref_git) {
9eeea7d2
SB
750 seen_error = 1;
751 strbuf_addf(err, _("path '%s' does not exist"), path);
752 goto out;
4530a85b 753 }
9eeea7d2
SB
754
755 repo = read_gitfile(ref_git);
756 if (!repo)
757 repo = read_gitfile(mkpath("%s/.git", ref_git));
758 if (repo) {
759 free(ref_git);
760 ref_git = xstrdup(repo);
761 }
762
763 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
764 char *ref_git_git = mkpathdup("%s/.git", ref_git);
765 free(ref_git);
766 ref_git = ref_git_git;
767 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
768 struct strbuf sb = STRBUF_INIT;
769 seen_error = 1;
770 if (get_common_dir(&sb, ref_git)) {
771 strbuf_addf(err,
772 _("reference repository '%s' as a linked "
773 "checkout is not supported yet."),
774 path);
775 goto out;
776 }
777
778 strbuf_addf(err, _("reference repository '%s' is not a "
779 "local repository."), path);
780 goto out;
781 }
782
783 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
784 strbuf_addf(err, _("reference repository '%s' is shallow"),
785 path);
786 seen_error = 1;
787 goto out;
788 }
789
790 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
791 strbuf_addf(err,
792 _("reference repository '%s' is grafted"),
793 path);
794 seen_error = 1;
795 goto out;
796 }
797
798out:
799 if (seen_error) {
6a83d902 800 FREE_AND_NULL(ref_git);
9eeea7d2
SB
801 }
802
803 return ref_git;
804}
805
f57a7396
TB
806struct object_directory *find_odb(struct repository *r, const char *obj_dir)
807{
808 struct object_directory *odb;
809 char *obj_dir_real = real_pathdup(obj_dir, 1);
810 struct strbuf odb_path_real = STRBUF_INIT;
811
812 prepare_alt_odb(r);
813 for (odb = r->objects->odb; odb; odb = odb->next) {
814 strbuf_realpath(&odb_path_real, odb->path, 1);
815 if (!strcmp(obj_dir_real, odb_path_real.buf))
816 break;
817 }
818
819 free(obj_dir_real);
820 strbuf_release(&odb_path_real);
821
822 if (!odb)
823 die(_("could not find object directory matching %s"), obj_dir);
824 return odb;
825}
826
709dfa69
JK
827static void fill_alternate_refs_command(struct child_process *cmd,
828 const char *repo_path)
829{
830 const char *value;
831
832 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
833 cmd->use_shell = 1;
834
c972bf4c
JK
835 strvec_push(&cmd->args, value);
836 strvec_push(&cmd->args, repo_path);
709dfa69
JK
837 } else {
838 cmd->git_cmd = 1;
839
c972bf4c
JK
840 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
841 strvec_push(&cmd->args, "for-each-ref");
842 strvec_push(&cmd->args, "--format=%(objectname)");
709dfa69
JK
843
844 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
c972bf4c
JK
845 strvec_push(&cmd->args, "--");
846 strvec_split(&cmd->args, value);
709dfa69
JK
847 }
848 }
849
29fda24d 850 strvec_pushv(&cmd->env, (const char **)local_repo_env);
709dfa69
JK
851 cmd->out = -1;
852}
853
854static void read_alternate_refs(const char *path,
855 alternate_ref_fn *cb,
856 void *data)
857{
858 struct child_process cmd = CHILD_PROCESS_INIT;
859 struct strbuf line = STRBUF_INIT;
860 FILE *fh;
861
862 fill_alternate_refs_command(&cmd, path);
863
864 if (start_command(&cmd))
865 return;
866
867 fh = xfdopen(cmd.out, "r");
868 while (strbuf_getline_lf(&line, fh) != EOF) {
869 struct object_id oid;
870 const char *p;
871
872 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
873 warning(_("invalid line while parsing alternate refs: %s"),
874 line.buf);
875 break;
876 }
877
878 cb(&oid, data);
879 }
880
881 fclose(fh);
882 finish_command(&cmd);
86ad3ea5 883 strbuf_release(&line);
709dfa69
JK
884}
885
886struct alternate_refs_data {
887 alternate_ref_fn *fn;
888 void *data;
889};
890
891static int refs_from_alternate_cb(struct object_directory *e,
892 void *data)
893{
894 struct strbuf path = STRBUF_INIT;
895 size_t base_len;
896 struct alternate_refs_data *cb = data;
897
898 if (!strbuf_realpath(&path, e->path, 0))
899 goto out;
900 if (!strbuf_strip_suffix(&path, "/objects"))
901 goto out;
902 base_len = path.len;
903
904 /* Is this a git repository with refs? */
905 strbuf_addstr(&path, "/refs");
906 if (!is_directory(path.buf))
907 goto out;
908 strbuf_setlen(&path, base_len);
909
910 read_alternate_refs(path.buf, cb->fn, cb->data);
911
912out:
913 strbuf_release(&path);
914 return 0;
915}
916
917void for_each_alternate_ref(alternate_ref_fn fn, void *data)
918{
919 struct alternate_refs_data cb;
920 cb.fn = fn;
921 cb.data = data;
922 foreach_alt_odb(refs_from_alternate_cb, &cb);
923}
924
fe1b2268 925int foreach_alt_odb(alt_odb_fn fn, void *cb)
d79796bc 926{
263db403 927 struct object_directory *ent;
fe1b2268 928 int r = 0;
d79796bc 929
0b209034 930 prepare_alt_odb(the_repository);
f0eaf638 931 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
fe1b2268
JK
932 r = fn(ent, cb);
933 if (r)
934 break;
935 }
936 return r;
d79796bc
JH
937}
938
13068bf0 939void prepare_alt_odb(struct repository *r)
c2f493a4 940{
f0eaf638 941 if (r->objects->loaded_alternates)
7dc24aa5
SP
942 return;
943
13068bf0 944 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
c2f493a4 945
f0eaf638
JK
946 read_info_alternates(r, r->objects->odb->path, 0);
947 r->objects->loaded_alternates = 1;
c2f493a4
MW
948}
949
d85cd187
PS
950int has_alt_odb(struct repository *r)
951{
952 prepare_alt_odb(r);
953 return !!r->objects->odb->next;
954}
955
3096b2ec 956/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
33d4221c 957static int freshen_file(const char *fn)
ace1534d 958{
312cd761 959 return !utime(fn, NULL);
0f4dc14a 960}
ace1534d 961
3096b2ec
JK
962/*
963 * All of the check_and_freshen functions return 1 if the file exists and was
964 * freshened (if freshening was requested), 0 otherwise. If they return
965 * 0, you should not assume that it is safe to skip a write of the object (it
966 * either does not exist on disk, or has a stale mtime and may be subject to
967 * pruning).
968 */
6a5e6f5e 969int check_and_freshen_file(const char *fn, int freshen)
33d4221c
JK
970{
971 if (access(fn, F_OK))
972 return 0;
3096b2ec 973 if (freshen && !freshen_file(fn))
33d4221c
JK
974 return 0;
975 return 1;
976}
977
f0eaf638
JK
978static int check_and_freshen_odb(struct object_directory *odb,
979 const struct object_id *oid,
980 int freshen)
33d4221c 981{
f0eaf638 982 static struct strbuf path = STRBUF_INIT;
514c5fdd 983 odb_loose_path(odb, &path, oid);
f0eaf638
JK
984 return check_and_freshen_file(path.buf, freshen);
985}
ea657730 986
f0eaf638
JK
987static int check_and_freshen_local(const struct object_id *oid, int freshen)
988{
989 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
33d4221c
JK
990}
991
6862ebbf 992static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
0f4dc14a 993{
263db403 994 struct object_directory *odb;
f3f043a1 995
0b209034 996 prepare_alt_odb(the_repository);
f0eaf638
JK
997 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
998 if (check_and_freshen_odb(odb, oid, freshen))
c529d75a 999 return 1;
ace1534d 1000 }
c529d75a 1001 return 0;
ace1534d
JH
1002}
1003
6862ebbf 1004static int check_and_freshen(const struct object_id *oid, int freshen)
33d4221c 1005{
6862ebbf 1006 return check_and_freshen_local(oid, freshen) ||
1007 check_and_freshen_nonlocal(oid, freshen);
33d4221c
JK
1008}
1009
6862ebbf 1010int has_loose_object_nonlocal(const struct object_id *oid)
33d4221c 1011{
6862ebbf 1012 return check_and_freshen_nonlocal(oid, 0);
33d4221c
JK
1013}
1014
b7573536 1015int has_loose_object(const struct object_id *oid)
0f4dc14a 1016{
6862ebbf 1017 return check_and_freshen(oid, 0);
0f4dc14a
BC
1018}
1019
02710228
SP
1020static void mmap_limit_check(size_t length)
1021{
1022 static size_t limit = 0;
1023 if (!limit) {
1024 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1025 if (!limit)
1026 limit = SIZE_MAX;
1027 }
1028 if (length > limit)
259328b7 1029 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
02710228
SP
1030 (uintmax_t)length, (uintmax_t)limit);
1031}
1032
1570856b
JK
1033void *xmmap_gently(void *start, size_t length,
1034 int prot, int flags, int fd, off_t offset)
58ecbd5e 1035{
02710228
SP
1036 void *ret;
1037
1038 mmap_limit_check(length);
1039 ret = mmap(start, length, prot, flags, fd, offset);
9827d4c1
JK
1040 if (ret == MAP_FAILED && !length)
1041 ret = NULL;
58ecbd5e
JN
1042 return ret;
1043}
1044
dc059294
EW
1045const char *mmap_os_err(void)
1046{
1047 static const char blank[] = "";
1048#if defined(__linux__)
1049 if (errno == ENOMEM) {
1050 /* this continues an existing error message: */
1051 static const char enomem[] =
1052", check sys.vm.max_map_count and/or RLIMIT_DATA";
1053 return enomem;
1054 }
1055#endif /* OS-specific bits */
1056 return blank;
1057}
1058
1570856b
JK
1059void *xmmap(void *start, size_t length,
1060 int prot, int flags, int fd, off_t offset)
1061{
1062 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1063 if (ret == MAP_FAILED)
dc059294 1064 die_errno(_("mmap failed%s"), mmap_os_err());
1570856b
JK
1065 return ret;
1066}
1067
b04cdea4
ÆAB
1068static int format_object_header_literally(char *str, size_t size,
1069 const char *type, size_t objsize)
1070{
1071 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1072}
1073
1074int format_object_header(char *str, size_t size, enum object_type type,
1075 size_t objsize)
1076{
1077 const char *name = type_name(type);
1078
1079 if (!name)
1080 BUG("could not get a type name for 'enum object_type' value %d", type);
1081
1082 return format_object_header_literally(str, size, name, objsize);
1083}
1084
b98d1885 1085int check_object_signature(struct repository *r, const struct object_id *oid,
44439c1c
ÆAB
1086 void *buf, unsigned long size,
1087 enum object_type type)
88d0db55 1088{
8d691757
EB
1089 const struct git_hash_algo *algo =
1090 oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
0f156dbb
ÆAB
1091 struct object_id real_oid;
1092
8d691757 1093 hash_object_file(algo, buf, size, type, &real_oid);
0f156dbb
ÆAB
1094
1095 return !oideq(oid, &real_oid) ? -1 : 0;
1096}
1097
1098int stream_object_signature(struct repository *r, const struct object_id *oid)
1099{
1100 struct object_id real_oid;
1101 unsigned long size;
090ea126
NTND
1102 enum object_type obj_type;
1103 struct git_istream *st;
18e2588e 1104 git_hash_ctx c;
1af64f73 1105 char hdr[MAX_HEADER_LEN];
090ea126 1106 int hdrlen;
88d0db55 1107
b98d1885 1108 st = open_istream(r, oid, &obj_type, &size, NULL);
090ea126
NTND
1109 if (!st)
1110 return -1;
88d0db55 1111
090ea126 1112 /* Generate the header */
b04cdea4 1113 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
88d0db55 1114
090ea126 1115 /* Sha1.. */
b98d1885
MT
1116 r->hash_algo->init_fn(&c);
1117 r->hash_algo->update_fn(&c, hdr, hdrlen);
090ea126
NTND
1118 for (;;) {
1119 char buf[1024 * 16];
1120 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1f688557 1121
f54fac53
JK
1122 if (readlen < 0) {
1123 close_istream(st);
1124 return -1;
1125 }
090ea126
NTND
1126 if (!readlen)
1127 break;
b98d1885 1128 r->hash_algo->update_fn(&c, buf, readlen);
fa5fc15d 1129 }
0f156dbb 1130 r->hash_algo->final_oid_fn(&real_oid, &c);
090ea126 1131 close_istream(st);
0f156dbb 1132 return !oideq(oid, &real_oid) ? -1 : 0;
fa5fc15d
SP
1133}
1134
1b8ac5ea 1135int git_open_cloexec(const char *name, int flags)
a0788266 1136{
1e3001a8
JH
1137 int fd;
1138 static int o_cloexec = O_CLOEXEC;
a0788266 1139
1e3001a8
JH
1140 fd = open(name, flags | o_cloexec);
1141 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
cd66ada0 1142 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1e3001a8
JH
1143 o_cloexec &= ~O_CLOEXEC;
1144 fd = open(name, flags | o_cloexec);
491a8dec 1145 }
491a8dec 1146
9fb9495d 1147#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
491a8dec 1148 {
1e3001a8 1149 static int fd_cloexec = FD_CLOEXEC;
a0788266 1150
1e3001a8
JH
1151 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1152 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
9fb9495d
EW
1153 int flags = fcntl(fd, F_GETFD);
1154 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1e3001a8 1155 fd_cloexec = 0;
cd66ada0 1156 }
44d1c19e 1157 }
a0788266 1158#endif
1b8ac5ea 1159 return fd;
a0788266
JS
1160}
1161
3cf8b462 1162/*
514c5fdd 1163 * Find "oid" as a loose object in the local repository or in an alternate.
771e7d57
JK
1164 * Returns 0 on success, negative on failure.
1165 *
1166 * The "path" out-parameter will give the path of the object we found (if any).
1167 * Note that it may point to static storage and is only valid until another
514c5fdd 1168 * call to stat_loose_object().
3cf8b462 1169 */
514c5fdd
JK
1170static int stat_loose_object(struct repository *r, const struct object_id *oid,
1171 struct stat *st, const char **path)
1f688557 1172{
263db403 1173 struct object_directory *odb;
ea657730
CC
1174 static struct strbuf buf = STRBUF_INIT;
1175
d2607fa0 1176 prepare_alt_odb(r);
f0eaf638 1177 for (odb = r->objects->odb; odb; odb = odb->next) {
514c5fdd 1178 *path = odb_loose_path(odb, &buf, oid);
771e7d57 1179 if (!lstat(*path, st))
052fe5ea 1180 return 0;
c7934306
SP
1181 }
1182
3cf8b462
SP
1183 return -1;
1184}
1185
771e7d57 1186/*
514c5fdd 1187 * Like stat_loose_object(), but actually open the object and return the
771e7d57
JK
1188 * descriptor. See the caveats on the "path" parameter above.
1189 */
514c5fdd
JK
1190static int open_loose_object(struct repository *r,
1191 const struct object_id *oid, const char **path)
60bb8b14 1192{
44d1c19e 1193 int fd;
263db403 1194 struct object_directory *odb;
f0eaf638 1195 int most_interesting_errno = ENOENT;
ea657730
CC
1196 static struct strbuf buf = STRBUF_INIT;
1197
ec7283e5 1198 prepare_alt_odb(r);
f0eaf638 1199 for (odb = r->objects->odb; odb; odb = odb->next) {
514c5fdd 1200 *path = odb_loose_path(odb, &buf, oid);
771e7d57 1201 fd = git_open(*path);
44d1c19e
LT
1202 if (fd >= 0)
1203 return fd;
f0eaf638 1204
d6c8a05b
JK
1205 if (most_interesting_errno == ENOENT)
1206 most_interesting_errno = errno;
03e79c88 1207 }
d6c8a05b 1208 errno = most_interesting_errno;
44d1c19e 1209 return -1;
1f688557
JH
1210}
1211
61c7711c 1212static int quick_has_loose(struct repository *r,
d7a24573 1213 const struct object_id *oid)
61c7711c 1214{
61c7711c
JK
1215 struct object_directory *odb;
1216
61c7711c
JK
1217 prepare_alt_odb(r);
1218 for (odb = r->objects->odb; odb; odb = odb->next) {
92d8ed8a 1219 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
61c7711c
JK
1220 return 1;
1221 }
1222 return 0;
1223}
1224
f6371f92 1225/*
ae285ac4
JT
1226 * Map and close the given loose object fd. The path argument is used for
1227 * error reporting.
f6371f92 1228 */
ae285ac4 1229static void *map_fd(int fd, const char *path, unsigned long *size)
27d69a46 1230{
ae285ac4
JT
1231 void *map = NULL;
1232 struct stat st;
1f688557 1233
ae285ac4
JT
1234 if (!fstat(fd, &st)) {
1235 *size = xsize_t(st.st_size);
1236 if (!*size) {
1237 /* mmap() is forbidden on empty files */
1238 error(_("object file %s is empty"), path);
1239 close(fd);
1240 return NULL;
144bde78 1241 }
ae285ac4 1242 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
74e34e1f 1243 }
ae285ac4 1244 close(fd);
0fcfd160 1245 return map;
74e34e1f
NP
1246}
1247
514c5fdd
JK
1248void *map_loose_object(struct repository *r,
1249 const struct object_id *oid,
1250 unsigned long *size)
068f85e3 1251{
ae285ac4
JT
1252 const char *p;
1253 int fd = open_loose_object(r, oid, &p);
1254
1255 if (fd < 0)
1256 return NULL;
1257 return map_fd(fd, p, size);
068f85e3 1258}
1259
3b6a8db3
ÆAB
1260enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1261 unsigned char *map,
1262 unsigned long mapsize,
1263 void *buffer,
1264 unsigned long bufsiz,
1265 struct strbuf *header)
47fe3f6e 1266{
01cab976 1267 int status;
31877c9a 1268
c4483576
LT
1269 /* Get the data stream */
1270 memset(stream, 0, sizeof(*stream));
1271 stream->next_in = map;
1272 stream->avail_in = mapsize;
1273 stream->next_out = buffer;
93821bd9 1274 stream->avail_out = bufsiz;
47fe3f6e 1275
39c68542 1276 git_inflate_init(stream);
31877c9a 1277 obj_read_unlock();
01cab976 1278 status = git_inflate(stream, 0);
31877c9a 1279 obj_read_lock();
d21f8426 1280 if (status < Z_OK)
3b6a8db3 1281 return ULHR_BAD;
d131b7af 1282
46f03448
KN
1283 /*
1284 * Check if entire header is unpacked in the first iteration.
d131b7af 1285 */
46f03448 1286 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
3b6a8db3 1287 return ULHR_OK;
d131b7af 1288
01cab976
ÆAB
1289 /*
1290 * We have a header longer than MAX_HEADER_LEN. The "header"
1291 * here is only non-NULL when we run "cat-file
1292 * --allow-unknown-type".
1293 */
1294 if (!header)
5848fb11 1295 return ULHR_TOO_LONG;
d131b7af 1296
46f03448
KN
1297 /*
1298 * buffer[0..bufsiz] was not large enough. Copy the partial
1299 * result out to header, and then append the result of further
1300 * reading the stream.
1301 */
1302 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1303 stream->next_out = buffer;
1304 stream->avail_out = bufsiz;
d131b7af 1305
46f03448 1306 do {
31877c9a 1307 obj_read_unlock();
46f03448 1308 status = git_inflate(stream, 0);
31877c9a 1309 obj_read_lock();
46f03448
KN
1310 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1311 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1312 return 0;
1313 stream->next_out = buffer;
1314 stream->avail_out = bufsiz;
1315 } while (status != Z_STREAM_END);
5848fb11 1316 return ULHR_TOO_LONG;
d131b7af
SP
1317}
1318
00a7760e
JK
1319static void *unpack_loose_rest(git_zstream *stream,
1320 void *buffer, unsigned long size,
1321 const struct object_id *oid)
95099731 1322{
5180cacc 1323 int bytes = strlen(buffer) + 1;
3aee68aa 1324 unsigned char *buf = xmallocz(size);
93821bd9 1325 unsigned long n;
7efbff75 1326 int status = Z_OK;
95099731 1327
93821bd9
LT
1328 n = stream->total_out - bytes;
1329 if (n > size)
1330 n = size;
1331 memcpy(buf, (char *) buffer + bytes, n);
1332 bytes = n;
456cdf6e
LT
1333 if (bytes <= size) {
1334 /*
1335 * The above condition must be (bytes <= size), not
1336 * (bytes < size). In other words, even though we
ccf5ace0 1337 * expect no more output and set avail_out to zero,
456cdf6e
LT
1338 * the input zlib stream may have bytes that express
1339 * "this concludes the stream", and we *do* want to
1340 * eat that input.
1341 *
1342 * Otherwise we would not be able to test that we
1343 * consumed all the input to reach the expected size;
1344 * we also want to check that zlib tells us that all
1345 * went well with status == Z_STREAM_END at the end.
1346 */
5180cacc
LT
1347 stream->next_out = buf + bytes;
1348 stream->avail_out = size - bytes;
31877c9a
MT
1349 while (status == Z_OK) {
1350 obj_read_unlock();
39c68542 1351 status = git_inflate(stream, Z_FINISH);
31877c9a
MT
1352 obj_read_lock();
1353 }
5180cacc 1354 }
456cdf6e 1355 if (status == Z_STREAM_END && !stream->avail_in) {
39c68542 1356 git_inflate_end(stream);
7efbff75 1357 return buf;
95099731
NTND
1358 }
1359
7efbff75 1360 if (status < 0)
00a7760e 1361 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
7efbff75 1362 else if (stream->avail_in)
259328b7 1363 error(_("garbage at end of loose object '%s'"),
00a7760e 1364 oid_to_hex(oid));
7efbff75
JH
1365 free(buf);
1366 return NULL;
95099731
NTND
1367}
1368
d40d535b 1369/*
5180cacc
LT
1370 * We used to just use "sscanf()", but that's actually way
1371 * too permissive for what we want to check. So do an anal
1372 * object header parse by hand.
d40d535b 1373 */
dccb32bf 1374int parse_loose_header(const char *hdr, struct object_info *oi)
1f688557 1375{
46f03448 1376 const char *type_buf = hdr;
d6a09e79 1377 size_t size;
46f03448 1378 int type, type_len = 0;
43057304 1379
5180cacc 1380 /*
46f03448 1381 * The type can be of any size but is followed by
21666f1a 1382 * a space.
5180cacc 1383 */
5180cacc
LT
1384 for (;;) {
1385 char c = *hdr++;
d21f8426
JH
1386 if (!c)
1387 return -1;
5180cacc
LT
1388 if (c == ' ')
1389 break;
46f03448 1390 type_len++;
5180cacc 1391 }
1f688557 1392
46f03448 1393 type = type_from_string_gently(type_buf, type_len, 1);
6ca32f47
BW
1394 if (oi->type_name)
1395 strbuf_add(oi->type_name, type_buf, type_len);
46f03448
KN
1396 if (oi->typep)
1397 *oi->typep = type;
5180cacc
LT
1398
1399 /*
1400 * The length must follow immediately, and be in canonical
1401 * decimal format (ie "010" is not valid).
1402 */
1403 size = *hdr++ - '0';
1404 if (size > 9)
1405 return -1;
1406 if (size) {
1407 for (;;) {
1408 unsigned long c = *hdr - '0';
1409 if (c > 9)
1410 break;
1411 hdr++;
d6a09e79 1412 size = st_add(st_mult(size, 10), c);
1b1005d1 1413 }
c01f51cc 1414 }
46f03448
KN
1415
1416 if (oi->sizep)
d6a09e79 1417 *oi->sizep = cast_size_t_to_ulong(size);
5180cacc
LT
1418
1419 /*
1420 * The length must be followed by a zero byte
1421 */
dccb32bf
ÆAB
1422 if (*hdr)
1423 return -1;
21666f1a 1424
dccb32bf
ÆAB
1425 /*
1426 * The format is valid, but the type may still be bogus. The
1427 * Caller needs to check its oi->typep.
1428 */
1429 return 0;
bf592c50
DB
1430}
1431
514c5fdd
JK
1432static int loose_object_info(struct repository *r,
1433 const struct object_id *oid,
1434 struct object_info *oi, int flags)
65c2e0c3 1435{
46f03448 1436 int status = 0;
9e59b38c 1437 int fd;
46f03448 1438 unsigned long mapsize;
9e59b38c 1439 const char *path;
65c2e0c3 1440 void *map;
ef49a7a0 1441 git_zstream stream;
1af64f73 1442 char hdr[MAX_HEADER_LEN];
46f03448 1443 struct strbuf hdrbuf = STRBUF_INIT;
c84a1f3e 1444 unsigned long size_scratch;
dccb32bf 1445 enum object_type type_scratch;
01cab976 1446 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
65c2e0c3 1447
b99b6bcc
JK
1448 if (oi->delta_base_oid)
1449 oidclr(oi->delta_base_oid);
5d642e75 1450
052fe5ea
JK
1451 /*
1452 * If we don't care about type or size, then we don't
4ef8d1dd
JH
1453 * need to look inside the object at all. Note that we
1454 * do not optimize out the stat call, even if the
1455 * caller doesn't care about the disk-size, since our
1456 * return value implicitly indicates whether the
1457 * object even exists.
052fe5ea 1458 */
6ca32f47 1459 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
4ef8d1dd 1460 struct stat st;
61c7711c 1461 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
d7a24573 1462 return quick_has_loose(r, oid) ? 0 : -1;
514c5fdd 1463 if (stat_loose_object(r, oid, &st, &path) < 0)
4ef8d1dd
JH
1464 return -1;
1465 if (oi->disk_sizep)
23c339c0 1466 *oi->disk_sizep = st.st_size;
052fe5ea
JK
1467 return 0;
1468 }
1469
9e59b38c
JT
1470 fd = open_loose_object(r, oid, &path);
1471 if (fd < 0) {
1472 if (errno != ENOENT)
1473 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1474 return -1;
1475 }
1476 map = map_fd(fd, path, &mapsize);
f0df4ed5 1477 if (!map)
dbea72a8 1478 return -1;
c84a1f3e
JT
1479
1480 if (!oi->sizep)
1481 oi->sizep = &size_scratch;
dccb32bf
ÆAB
1482 if (!oi->typep)
1483 oi->typep = &type_scratch;
c84a1f3e 1484
23c339c0
JK
1485 if (oi->disk_sizep)
1486 *oi->disk_sizep = mapsize;
01cab976 1487
3b6a8db3
ÆAB
1488 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1489 allow_unknown ? &hdrbuf : NULL)) {
1490 case ULHR_OK:
dccb32bf
ÆAB
1491 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1492 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1493 else if (!allow_unknown && *oi->typep < 0)
1494 die(_("invalid object type"));
1495
1496 if (!oi->contentp)
1497 break;
1498 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1499 if (*oi->contentp)
1500 goto cleanup;
1501
1502 status = -1;
3b6a8db3
ÆAB
1503 break;
1504 case ULHR_BAD:
259328b7 1505 status = error(_("unable to unpack %s header"),
514c5fdd 1506 oid_to_hex(oid));
3b6a8db3 1507 break;
5848fb11
ÆAB
1508 case ULHR_TOO_LONG:
1509 status = error(_("header for %s too long, exceeds %d bytes"),
1510 oid_to_hex(oid), MAX_HEADER_LEN);
1511 break;
3b6a8db3 1512 }
c84a1f3e 1513
9e59b38c
JT
1514 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1515 die(_("loose object %s (stored in %s) is corrupt"),
1516 oid_to_hex(oid), path);
1517
dccb32bf
ÆAB
1518 git_inflate_end(&stream);
1519cleanup:
65c2e0c3 1520 munmap(map, mapsize);
c84a1f3e
JT
1521 if (oi->sizep == &size_scratch)
1522 oi->sizep = NULL;
46f03448 1523 strbuf_release(&hdrbuf);
dccb32bf
ÆAB
1524 if (oi->typep == &type_scratch)
1525 oi->typep = NULL;
3ab0fb06 1526 oi->whence = OI_LOOSE;
dccb32bf 1527 return status;
65c2e0c3
JH
1528}
1529
31877c9a
MT
1530int obj_read_use_lock = 0;
1531pthread_mutex_t obj_read_mutex;
1532
1533void enable_obj_read_lock(void)
1534{
1535 if (obj_read_use_lock)
1536 return;
1537
1538 obj_read_use_lock = 1;
1539 init_recursive_mutex(&obj_read_mutex);
1540}
1541
1542void disable_obj_read_lock(void)
1543{
1544 if (!obj_read_use_lock)
1545 return;
1546
1547 obj_read_use_lock = 0;
1548 pthread_mutex_destroy(&obj_read_mutex);
1549}
1550
8b4c0103
JT
1551int fetch_if_missing = 1;
1552
31877c9a
MT
1553static int do_oid_object_info_extended(struct repository *r,
1554 const struct object_id *oid,
1555 struct object_info *oi, unsigned flags)
f0df4ed5 1556{
cd585e2a 1557 static struct object_info blank_oi = OBJECT_INFO_INIT;
9c8a294a 1558 struct cached_object *co;
f0df4ed5 1559 struct pack_entry e;
5b086407 1560 int rtype;
b383a13c 1561 const struct object_id *real = oid;
8b4c0103 1562 int already_retried = 0;
f0df4ed5 1563
31877c9a 1564
b383a13c 1565 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
9d98354f 1566 real = lookup_replace_object(r, oid);
f0df4ed5 1567
b383a13c 1568 if (is_null_oid(real))
87b5e236
JK
1569 return -1;
1570
cd585e2a
JT
1571 if (!oi)
1572 oi = &blank_oi;
1573
9c8a294a
JT
1574 co = find_cached_object(real);
1575 if (co) {
1576 if (oi->typep)
1577 *(oi->typep) = co->type;
1578 if (oi->sizep)
1579 *(oi->sizep) = co->size;
1580 if (oi->disk_sizep)
1581 *(oi->disk_sizep) = 0;
b99b6bcc
JK
1582 if (oi->delta_base_oid)
1583 oidclr(oi->delta_base_oid);
9c8a294a
JT
1584 if (oi->type_name)
1585 strbuf_addstr(oi->type_name, type_name(co->type));
1586 if (oi->contentp)
1587 *oi->contentp = xmemdupz(co->buf, co->size);
1588 oi->whence = OI_CACHED;
1589 return 0;
c4d9986f
NTND
1590 }
1591
8b4c0103 1592 while (1) {
42c8ce1c 1593 if (find_pack_entry(r, real, &e))
8b4c0103
JT
1594 break;
1595
ddd63e64 1596 /* Most likely it's a loose object. */
514c5fdd 1597 if (!loose_object_info(r, real, oi, flags))
5b086407 1598 return 0;
ddd63e64
SG
1599
1600 /* Not a loose object; someone else may have just packed it. */
2b7750c9 1601 if (!(flags & OBJECT_INFO_QUICK)) {
9d98354f 1602 reprepare_packed_git(r);
42c8ce1c 1603 if (find_pack_entry(r, real, &e))
2b7750c9
JT
1604 break;
1605 }
8b4c0103 1606
eef71904
JT
1607 /*
1608 * If r is the_repository, this might be an attempt at
1609 * accessing a submodule object as if it were in the_repository
1610 * (having called add_submodule_odb() on that submodule's ODB).
1611 * If any such ODBs exist, register them and try again.
1612 */
1613 if (r == the_repository &&
1614 register_all_submodule_odb_as_alternates())
a35e03de
JT
1615 /* We added some alternates; retry */
1616 continue;
1617
8b4c0103 1618 /* Check if it is a missing object */
ef830cc4
JT
1619 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1620 !already_retried &&
31f5256c 1621 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
b14ed5ad 1622 promisor_remote_get_direct(r, real, 1);
8b4c0103
JT
1623 already_retried = 1;
1624 continue;
dfdd4afc 1625 }
8b4c0103 1626
9e59b38c
JT
1627 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1628 const struct packed_git *p;
1629 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1630 die(_("replacement %s not found for %s"),
1631 oid_to_hex(real), oid_to_hex(oid));
1632 if ((p = has_packed_and_bad(r, real)))
1633 die(_("packed object %s (stored in %s) is corrupt"),
1634 oid_to_hex(real), p->pack_name);
1635 }
8b4c0103 1636 return -1;
f0df4ed5 1637 }
3d77d877 1638
cd585e2a
JT
1639 if (oi == &blank_oi)
1640 /*
1641 * We know that the caller doesn't actually need the
1642 * information below, so return early.
1643 */
1644 return 0;
9d98354f 1645 rtype = packed_object_info(r, e.p, e.offset, oi);
412916ee 1646 if (rtype < 0) {
751530de 1647 mark_bad_packed_object(e.p, real);
31877c9a 1648 return do_oid_object_info_extended(r, real, oi, 0);
3ab0fb06 1649 } else if (oi->whence == OI_PACKED) {
9a490590
JH
1650 oi->u.packed.offset = e.offset;
1651 oi->u.packed.pack = e.p;
1652 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1653 rtype == OBJ_OFS_DELTA);
3d77d877
NP
1654 }
1655
5b086407 1656 return 0;
f0df4ed5
JS
1657}
1658
2328ebaa
EB
1659static int oid_object_info_convert(struct repository *r,
1660 const struct object_id *input_oid,
1661 struct object_info *input_oi, unsigned flags)
1662{
1663 const struct git_hash_algo *input_algo = &hash_algos[input_oid->algo];
1664 int do_die = flags & OBJECT_INFO_DIE_IF_CORRUPT;
1665 struct strbuf type_name = STRBUF_INIT;
1666 struct object_id oid, delta_base_oid;
1667 struct object_info new_oi, *oi;
1668 unsigned long size;
1669 void *content;
1670 int ret;
1671
1672 if (repo_oid_to_algop(r, input_oid, the_hash_algo, &oid)) {
1673 if (do_die)
1674 die(_("missing mapping of %s to %s"),
1675 oid_to_hex(input_oid), the_hash_algo->name);
1676 return -1;
1677 }
1678
1679 /* Is new_oi needed? */
1680 oi = input_oi;
1681 if (input_oi && (input_oi->delta_base_oid || input_oi->sizep ||
1682 input_oi->contentp)) {
1683 new_oi = *input_oi;
1684 /* Does delta_base_oid need to be converted? */
1685 if (input_oi->delta_base_oid)
1686 new_oi.delta_base_oid = &delta_base_oid;
1687 /* Will the attributes differ when converted? */
1688 if (input_oi->sizep || input_oi->contentp) {
1689 new_oi.contentp = &content;
1690 new_oi.sizep = &size;
1691 new_oi.type_name = &type_name;
1692 }
1693 oi = &new_oi;
1694 }
1695
1696 ret = oid_object_info_extended(r, &oid, oi, flags);
1697 if (ret)
1698 return -1;
1699 if (oi == input_oi)
1700 return ret;
1701
1702 if (new_oi.contentp) {
1703 struct strbuf outbuf = STRBUF_INIT;
1704 enum object_type type;
1705
1706 type = type_from_string_gently(type_name.buf, type_name.len,
1707 !do_die);
1708 if (type == -1)
1709 return -1;
1710 if (type != OBJ_BLOB) {
1711 ret = convert_object_file(&outbuf,
1712 the_hash_algo, input_algo,
1713 content, size, type, !do_die);
1714 if (ret == -1)
1715 return -1;
1716 free(content);
1717 size = outbuf.len;
1718 content = strbuf_detach(&outbuf, NULL);
1719 }
1720 if (input_oi->sizep)
1721 *input_oi->sizep = size;
1722 if (input_oi->contentp)
1723 *input_oi->contentp = content;
1724 else
1725 free(content);
1726 if (input_oi->type_name)
1727 *input_oi->type_name = type_name;
1728 else
1729 strbuf_release(&type_name);
1730 }
1731 if (new_oi.delta_base_oid == &delta_base_oid) {
1732 if (repo_oid_to_algop(r, &delta_base_oid, input_algo,
1733 input_oi->delta_base_oid)) {
1734 if (do_die)
1735 die(_("missing mapping of %s to %s"),
1736 oid_to_hex(&delta_base_oid),
1737 input_algo->name);
1738 return -1;
1739 }
1740 }
1741 input_oi->whence = new_oi.whence;
1742 input_oi->u = new_oi.u;
1743 return ret;
1744}
1745
31877c9a
MT
1746int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1747 struct object_info *oi, unsigned flags)
1748{
1749 int ret;
2328ebaa
EB
1750
1751 if (oid->algo && (hash_algo_by_ptr(r->hash_algo) != oid->algo))
1752 return oid_object_info_convert(r, oid, oi, flags);
1753
31877c9a
MT
1754 obj_read_lock();
1755 ret = do_oid_object_info_extended(r, oid, oi, flags);
1756 obj_read_unlock();
1757 return ret;
1758}
1759
1760
3fc0dca9 1761/* returns enum object_type or negative */
9d98354f
SB
1762int oid_object_info(struct repository *r,
1763 const struct object_id *oid,
1764 unsigned long *sizep)
9a490590 1765{
5b086407 1766 enum object_type type;
27b5c1a0 1767 struct object_info oi = OBJECT_INFO_INIT;
9a490590 1768
5b086407 1769 oi.typep = &type;
9a490590 1770 oi.sizep = sizep;
9d98354f
SB
1771 if (oid_object_info_extended(r, oid, &oi,
1772 OBJECT_INFO_LOOKUP_REPLACE) < 0)
5b086407
JK
1773 return -1;
1774 return type;
9a490590
JH
1775}
1776
829e5c3b
PO
1777int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1778 struct object_id *oid)
d66b37bb
JH
1779{
1780 struct cached_object *co;
1781
44439c1c 1782 hash_object_file(the_hash_algo, buf, len, type, oid);
bc726bd0 1783 if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
a64d2aae 1784 find_cached_object(oid))
d66b37bb 1785 return 0;
c7353967 1786 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
d66b37bb
JH
1787 co = &cached_objects[cached_object_nr++];
1788 co->size = len;
21666f1a 1789 co->type = type;
efa13f7b
JH
1790 co->buf = xmalloc(len);
1791 memcpy(co->buf, buf, len);
62ba93ea 1792 oidcpy(&co->oid, oid);
d66b37bb
JH
1793 return 0;
1794}
1795
b6c4cecc
JH
1796/*
1797 * This function dies on corrupt objects; the callers who want to
b25562e6
JK
1798 * deal with them should arrange to call oid_object_info_extended() and give
1799 * error messages themselves.
b6c4cecc 1800 */
0ba05cf2
JK
1801void *repo_read_object_file(struct repository *r,
1802 const struct object_id *oid,
1803 enum object_type *type,
1804 unsigned long *size)
ac939109 1805{
b25562e6 1806 struct object_info oi = OBJECT_INFO_INIT;
7be13f5f 1807 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
3ba7a065 1808 void *data;
b6c4cecc 1809
b25562e6
JK
1810 oi.typep = type;
1811 oi.sizep = size;
1812 oi.contentp = &data;
b25562e6 1813 if (oid_object_info_extended(r, oid, &oi, flags))
15b63689 1814 return NULL;
68095570 1815
b25562e6 1816 return data;
ac939109
NP
1817}
1818
d3b4705a
NTND
1819void *read_object_with_reference(struct repository *r,
1820 const struct object_id *oid,
6aea6bae 1821 enum object_type required_type,
40469ee9 1822 unsigned long *size,
02f0547e 1823 struct object_id *actual_oid_return)
f4913f91 1824{
6aea6bae 1825 enum object_type type;
f4913f91
JH
1826 void *buffer;
1827 unsigned long isize;
02f0547e 1828 struct object_id actual_oid;
f4913f91 1829
02f0547e 1830 oidcpy(&actual_oid, oid);
40469ee9
JH
1831 while (1) {
1832 int ref_length = -1;
1833 const char *ref_type = NULL;
f4913f91 1834
d3b4705a 1835 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
40469ee9
JH
1836 if (!buffer)
1837 return NULL;
21666f1a 1838 if (type == required_type) {
40469ee9 1839 *size = isize;
02f0547e 1840 if (actual_oid_return)
1841 oidcpy(actual_oid_return, &actual_oid);
40469ee9
JH
1842 return buffer;
1843 }
1844 /* Handle references */
21666f1a 1845 else if (type == OBJ_COMMIT)
40469ee9 1846 ref_type = "tree ";
21666f1a 1847 else if (type == OBJ_TAG)
40469ee9
JH
1848 ref_type = "object ";
1849 else {
1850 free(buffer);
1851 return NULL;
1852 }
1853 ref_length = strlen(ref_type);
f4913f91 1854
94b5e093 1855 if (ref_length + the_hash_algo->hexsz > isize ||
50974ec9 1856 memcmp(buffer, ref_type, ref_length) ||
02f0547e 1857 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
40469ee9
JH
1858 free(buffer);
1859 return NULL;
1860 }
1cf58e72 1861 free(buffer);
40469ee9 1862 /* Now we have the ID of the referred-to object in
02f0547e 1863 * actual_oid. Check again. */
f4913f91 1864 }
f4913f91
JH
1865}
1866
2bbb28a3
ÆAB
1867static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1868 const void *buf, unsigned long len,
1869 struct object_id *oid,
1870 char *hdr, int *hdrlen)
1871{
1872 algo->init_fn(c);
1873 algo->update_fn(c, hdr, *hdrlen);
1874 algo->update_fn(c, buf, len);
1875 algo->final_oid_fn(oid, c);
1876}
1877
7ad5c44d
MT
1878static void write_object_file_prepare(const struct git_hash_algo *algo,
1879 const void *buf, unsigned long len,
2bbb28a3 1880 enum object_type type, struct object_id *oid,
a09c985e 1881 char *hdr, int *hdrlen)
d410c0f5 1882{
18e2588e 1883 git_hash_ctx c;
d410c0f5
JH
1884
1885 /* Generate the header */
2bbb28a3 1886 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
d410c0f5
JH
1887
1888 /* Sha1.. */
2bbb28a3
ÆAB
1889 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1890}
1891
1892static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1893 const void *buf, unsigned long len,
1894 const char *type, struct object_id *oid,
1895 char *hdr, int *hdrlen)
1896{
1897 git_hash_ctx c;
1898
1899 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1900 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
d410c0f5
JH
1901}
1902
230f1322 1903/*
5a688fe4 1904 * Move the just written object into its final resting place.
230f1322 1905 */
cb5add58 1906int finalize_object_file(const char *tmpfile, const char *filename)
230f1322 1907{
e32c0a9c 1908 int ret = 0;
5a688fe4 1909
348df166 1910 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
be66a6c4
JS
1911 goto try_rename;
1912 else if (link(tmpfile, filename))
e32c0a9c 1913 ret = errno;
7ebb6fca
LT
1914
1915 /*
1916 * Coda hack - coda doesn't like cross-directory links,
1917 * so we fall back to a rename, which will mean that it
1918 * won't be able to check collisions, but that's not a
1919 * big deal.
1920 *
1921 * The same holds for FAT formatted media.
1922 *
3be1f18e 1923 * When this succeeds, we just return. We have nothing
7ebb6fca
LT
1924 * left to unlink.
1925 */
1926 if (ret && ret != EEXIST) {
be66a6c4 1927 try_rename:
7ebb6fca 1928 if (!rename(tmpfile, filename))
3be1f18e 1929 goto out;
9e48b389 1930 ret = errno;
230f1322 1931 }
691f1a28 1932 unlink_or_warn(tmpfile);
230f1322
LT
1933 if (ret) {
1934 if (ret != EEXIST) {
2c319886 1935 return error_errno(_("unable to write file %s"), filename);
230f1322
LT
1936 }
1937 /* FIXME!!! Collision check here ? */
1938 }
1939
3be1f18e 1940out:
5256b006 1941 if (adjust_shared_perm(filename))
259328b7 1942 return error(_("unable to set permission to '%s'"), filename);
230f1322
LT
1943 return 0;
1944}
1945
44439c1c
ÆAB
1946static void hash_object_file_literally(const struct git_hash_algo *algo,
1947 const void *buf, unsigned long len,
1948 const char *type, struct object_id *oid)
abdc3fc8 1949{
1af64f73 1950 char hdr[MAX_HEADER_LEN];
ef1286d3 1951 int hdrlen = sizeof(hdr);
44439c1c 1952
2bbb28a3 1953 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
abdc3fc8
RS
1954}
1955
44439c1c
ÆAB
1956void hash_object_file(const struct git_hash_algo *algo, const void *buf,
1957 unsigned long len, enum object_type type,
1958 struct object_id *oid)
1959{
1960 hash_object_file_literally(algo, buf, len, type_name(type), oid);
abdc3fc8
RS
1961}
1962
e9039dd3 1963/* Finalize a file on disk, and close it. */
c4e707f8 1964static void close_loose_object(int fd, const char *filename)
e9039dd3 1965{
020406ea
NS
1966 if (the_repository->objects->odb->will_destroy)
1967 goto out;
b3cecf49 1968
c0f4752e 1969 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
83937e95 1970 fsync_loose_object_bulk_checkin(fd, filename);
c0f4752e 1971 else if (fsync_object_files > 0)
c4e707f8 1972 fsync_or_die(fd, filename);
020406ea
NS
1973 else
1974 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
c4e707f8 1975 filename);
020406ea
NS
1976
1977out:
e9039dd3 1978 if (close(fd) != 0)
76011357 1979 die_errno(_("error when closing loose object file"));
e9039dd3
LT
1980}
1981
5723fe7e
LT
1982/* Size of directory component, including the ending '/' */
1983static inline int directory_size(const char *filename)
1984{
1985 const char *s = strrchr(filename, '/');
1986 if (!s)
1987 return 0;
1988 return s - filename + 1;
1989}
1990
1991/*
1992 * This creates a temporary file in the same directory as the final
1993 * 'filename'
1994 *
1995 * We want to avoid cross-directory filename renames, because those
1996 * can have problems on various filesystems (FAT, NFS, Coda).
1997 */
d4b3d11a 1998static int create_tmpfile(struct strbuf *tmp, const char *filename)
5723fe7e
LT
1999{
2000 int fd, dirlen = directory_size(filename);
2001
d4b3d11a
JK
2002 strbuf_reset(tmp);
2003 strbuf_add(tmp, filename, dirlen);
2004 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
2005 fd = git_mkstemp_mode(tmp->buf, 0444);
cbacbf4e 2006 if (fd < 0 && dirlen && errno == ENOENT) {
d4b3d11a
JK
2007 /*
2008 * Make sure the directory exists; note that the contents
2009 * of the buffer are undefined after mkstemp returns an
2010 * error, so we have to rewrite the whole buffer from
2011 * scratch.
2012 */
2013 strbuf_reset(tmp);
2014 strbuf_add(tmp, filename, dirlen - 1);
2015 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
b2476a60 2016 return -1;
d4b3d11a 2017 if (adjust_shared_perm(tmp->buf))
5723fe7e
LT
2018 return -1;
2019
2020 /* Try again */
d4b3d11a
JK
2021 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
2022 fd = git_mkstemp_mode(tmp->buf, 0444);
5723fe7e
LT
2023 }
2024 return fd;
2025}
2026
97a9db6f
HX
2027/**
2028 * Common steps for loose object writers to start writing loose
2029 * objects:
2030 *
2031 * - Create tmpfile for the loose object.
2032 * - Setup zlib stream for compression.
2033 * - Start to feed header to zlib stream.
2034 *
2035 * Returns a "fd", which should later be provided to
2036 * end_loose_object_common().
2037 */
2038static int start_loose_object_common(struct strbuf *tmp_file,
2039 const char *filename, unsigned flags,
2040 git_zstream *stream,
2041 unsigned char *buf, size_t buflen,
63a6745a 2042 git_hash_ctx *c, git_hash_ctx *compat_c,
97a9db6f
HX
2043 char *hdr, int hdrlen)
2044{
63a6745a
EB
2045 struct repository *repo = the_repository;
2046 const struct git_hash_algo *algo = repo->hash_algo;
2047 const struct git_hash_algo *compat = repo->compat_hash_algo;
97a9db6f
HX
2048 int fd;
2049
2050 fd = create_tmpfile(tmp_file, filename);
2051 if (fd < 0) {
2052 if (flags & HASH_SILENT)
2053 return -1;
2054 else if (errno == EACCES)
2055 return error(_("insufficient permission for adding "
2056 "an object to repository database %s"),
2057 get_object_directory());
2058 else
2059 return error_errno(
2060 _("unable to create temporary file"));
2061 }
2062
2063 /* Setup zlib stream for compression */
2064 git_deflate_init(stream, zlib_compression_level);
2065 stream->next_out = buf;
2066 stream->avail_out = buflen;
63a6745a
EB
2067 algo->init_fn(c);
2068 if (compat && compat_c)
2069 compat->init_fn(compat_c);
97a9db6f
HX
2070
2071 /* Start to feed header to zlib stream */
2072 stream->next_in = (unsigned char *)hdr;
2073 stream->avail_in = hdrlen;
2074 while (git_deflate(stream, 0) == Z_OK)
2075 ; /* nothing */
63a6745a
EB
2076 algo->update_fn(c, hdr, hdrlen);
2077 if (compat && compat_c)
2078 compat->update_fn(compat_c, hdr, hdrlen);
97a9db6f
HX
2079
2080 return fd;
2081}
2082
21e7d881
ÆAB
2083/**
2084 * Common steps for the inner git_deflate() loop for writing loose
2085 * objects. Returns what git_deflate() returns.
2086 */
63a6745a 2087static int write_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
21e7d881
ÆAB
2088 git_zstream *stream, const int flush,
2089 unsigned char *in0, const int fd,
2090 unsigned char *compressed,
2091 const size_t compressed_len)
2092{
63a6745a
EB
2093 struct repository *repo = the_repository;
2094 const struct git_hash_algo *algo = repo->hash_algo;
2095 const struct git_hash_algo *compat = repo->compat_hash_algo;
21e7d881
ÆAB
2096 int ret;
2097
2098 ret = git_deflate(stream, flush ? Z_FINISH : 0);
63a6745a
EB
2099 algo->update_fn(c, in0, stream->next_in - in0);
2100 if (compat && compat_c)
2101 compat->update_fn(compat_c, in0, stream->next_in - in0);
d422d061
RS
2102 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
2103 die_errno(_("unable to write loose object file"));
21e7d881
ÆAB
2104 stream->next_out = compressed;
2105 stream->avail_out = compressed_len;
2106
2107 return ret;
2108}
2109
97a9db6f
HX
2110/**
2111 * Common steps for loose object writers to end writing loose objects:
2112 *
2113 * - End the compression of zlib stream.
2114 * - Get the calculated oid to "oid".
2115 */
63a6745a
EB
2116static int end_loose_object_common(git_hash_ctx *c, git_hash_ctx *compat_c,
2117 git_zstream *stream, struct object_id *oid,
2118 struct object_id *compat_oid)
97a9db6f 2119{
63a6745a
EB
2120 struct repository *repo = the_repository;
2121 const struct git_hash_algo *algo = repo->hash_algo;
2122 const struct git_hash_algo *compat = repo->compat_hash_algo;
97a9db6f
HX
2123 int ret;
2124
2125 ret = git_deflate_end_gently(stream);
2126 if (ret != Z_OK)
2127 return ret;
63a6745a
EB
2128 algo->final_oid_fn(oid, c);
2129 if (compat && compat_c)
2130 compat->final_oid_fn(compat_oid, compat_c);
97a9db6f
HX
2131
2132 return Z_OK;
2133}
2134
3fc7281f
PO
2135static int write_loose_object(const struct object_id *oid, char *hdr,
2136 int hdrlen, const void *buf, unsigned long len,
4ef91a2d 2137 time_t mtime, unsigned flags)
0fcfd160 2138{
915308b1 2139 int fd, ret;
9892beba 2140 unsigned char compressed[4096];
ef49a7a0 2141 git_zstream stream;
18e2588e 2142 git_hash_ctx c;
3fc7281f 2143 struct object_id parano_oid;
d4b3d11a 2144 static struct strbuf tmp_file = STRBUF_INIT;
ea657730
CC
2145 static struct strbuf filename = STRBUF_INIT;
2146
c0f4752e
NS
2147 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2148 prepare_loose_object_bulk_checkin();
2149
514c5fdd 2150 loose_object_path(the_repository, &filename, oid);
a44c9a5e 2151
97a9db6f
HX
2152 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2153 &stream, compressed, sizeof(compressed),
63a6745a 2154 &c, NULL, hdr, hdrlen);
97a9db6f
HX
2155 if (fd < 0)
2156 return -1;
a44c9a5e
LT
2157
2158 /* Then the data itself.. */
c00e657d 2159 stream.next_in = (void *)buf;
a44c9a5e 2160 stream.avail_in = len;
9892beba 2161 do {
748af44c 2162 unsigned char *in0 = stream.next_in;
21e7d881 2163
63a6745a 2164 ret = write_loose_object_common(&c, NULL, &stream, 1, in0, fd,
21e7d881 2165 compressed, sizeof(compressed));
9892beba
NP
2166 } while (ret == Z_OK);
2167
ac54c277 2168 if (ret != Z_STREAM_END)
259328b7 2169 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
3fc7281f 2170 ret);
63a6745a 2171 ret = end_loose_object_common(&c, NULL, &stream, &parano_oid, NULL);
ac54c277 2172 if (ret != Z_OK)
259328b7 2173 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
3fc7281f 2174 ret);
9001dc2a 2175 if (!oideq(oid, &parano_oid))
259328b7 2176 die(_("confused by unstable object source data for %s"),
3fc7281f 2177 oid_to_hex(oid));
ac54c277 2178
c4e707f8 2179 close_loose_object(fd, tmp_file.buf);
0fcfd160 2180
bbac7311
NP
2181 if (mtime) {
2182 struct utimbuf utb;
2183 utb.actime = mtime;
2184 utb.modtime = mtime;
4ef91a2d
ÆAB
2185 if (utime(tmp_file.buf, &utb) < 0 &&
2186 !(flags & HASH_SILENT))
259328b7 2187 warning_errno(_("failed utime() on %s"), tmp_file.buf);
bbac7311
NP
2188 }
2189
ea657730 2190 return finalize_object_file(tmp_file.buf, filename.buf);
0fcfd160 2191}
8237b185 2192
6862ebbf 2193static int freshen_loose_object(const struct object_id *oid)
33d4221c 2194{
6862ebbf 2195 return check_and_freshen(oid, 1);
33d4221c
JK
2196}
2197
6862ebbf 2198static int freshen_packed_object(const struct object_id *oid)
33d4221c
JK
2199{
2200 struct pack_entry e;
544443cb 2201 if (!find_pack_entry(the_repository, oid, &e))
ee1c6c34 2202 return 0;
a6131642
TB
2203 if (e.p->is_cruft)
2204 return 0;
ee1c6c34
JK
2205 if (e.p->freshened)
2206 return 1;
2207 if (!freshen_file(e.p->pack_name))
2208 return 0;
2209 e.p->freshened = 1;
2210 return 1;
33d4221c
JK
2211}
2212
2b6070ac
HX
2213int stream_loose_object(struct input_stream *in_stream, size_t len,
2214 struct object_id *oid)
2215{
63a6745a
EB
2216 const struct git_hash_algo *compat = the_repository->compat_hash_algo;
2217 struct object_id compat_oid;
2b6070ac
HX
2218 int fd, ret, err = 0, flush = 0;
2219 unsigned char compressed[4096];
2220 git_zstream stream;
63a6745a 2221 git_hash_ctx c, compat_c;
2b6070ac
HX
2222 struct strbuf tmp_file = STRBUF_INIT;
2223 struct strbuf filename = STRBUF_INIT;
2224 int dirlen;
2225 char hdr[MAX_HEADER_LEN];
2226 int hdrlen;
2227
2228 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2229 prepare_loose_object_bulk_checkin();
2230
2231 /* Since oid is not determined, save tmp file to odb path. */
2232 strbuf_addf(&filename, "%s/", get_object_directory());
2233 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2234
2235 /*
2236 * Common steps for write_loose_object and stream_loose_object to
2237 * start writing loose objects:
2238 *
2239 * - Create tmpfile for the loose object.
2240 * - Setup zlib stream for compression.
2241 * - Start to feed header to zlib stream.
2242 */
2243 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2244 &stream, compressed, sizeof(compressed),
63a6745a 2245 &c, &compat_c, hdr, hdrlen);
2b6070ac
HX
2246 if (fd < 0) {
2247 err = -1;
2248 goto cleanup;
2249 }
2250
2251 /* Then the data itself.. */
2252 do {
2253 unsigned char *in0 = stream.next_in;
2254
2255 if (!stream.avail_in && !in_stream->is_finished) {
2256 const void *in = in_stream->read(in_stream, &stream.avail_in);
2257 stream.next_in = (void *)in;
2258 in0 = (unsigned char *)in;
2259 /* All data has been read. */
2260 if (in_stream->is_finished)
2261 flush = 1;
2262 }
63a6745a 2263 ret = write_loose_object_common(&c, &compat_c, &stream, flush, in0, fd,
2b6070ac
HX
2264 compressed, sizeof(compressed));
2265 /*
2266 * Unlike write_loose_object(), we do not have the entire
2267 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2268 * then we'll replenish them in the next input_stream->read()
2269 * call when we loop.
2270 */
2271 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2272
2273 if (stream.total_in != len + hdrlen)
2274 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2275 (uintmax_t)len + hdrlen);
2276
2277 /*
2278 * Common steps for write_loose_object and stream_loose_object to
2279 * end writing loose oject:
2280 *
2281 * - End the compression of zlib stream.
2282 * - Get the calculated oid.
2283 */
2284 if (ret != Z_STREAM_END)
2285 die(_("unable to stream deflate new object (%d)"), ret);
63a6745a 2286 ret = end_loose_object_common(&c, &compat_c, &stream, oid, &compat_oid);
2b6070ac
HX
2287 if (ret != Z_OK)
2288 die(_("deflateEnd on stream object failed (%d)"), ret);
2289 close_loose_object(fd, tmp_file.buf);
2290
2291 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2292 unlink_or_warn(tmp_file.buf);
2293 goto cleanup;
2294 }
2295
2296 loose_object_path(the_repository, &filename, oid);
2297
2298 /* We finally know the object path, and create the missing dir. */
2299 dirlen = directory_size(filename.buf);
2300 if (dirlen) {
2301 struct strbuf dir = STRBUF_INIT;
2302 strbuf_add(&dir, filename.buf, dirlen);
2303
2304 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2305 err = error_errno(_("unable to create directory %s"), dir.buf);
2306 strbuf_release(&dir);
2307 goto cleanup;
2308 }
2309 strbuf_release(&dir);
2310 }
2311
2312 err = finalize_object_file(tmp_file.buf, filename.buf);
63a6745a
EB
2313 if (!err && compat)
2314 err = repo_add_loose_object_map(the_repository, oid, &compat_oid);
2b6070ac
HX
2315cleanup:
2316 strbuf_release(&tmp_file);
2317 strbuf_release(&filename);
2318 return err;
2319}
2320
4ef91a2d 2321int write_object_file_flags(const void *buf, unsigned long len,
c80d226a 2322 enum object_type type, struct object_id *oid,
c2538492 2323 struct object_id *compat_oid_in, unsigned flags)
bbac7311 2324{
63a6745a
EB
2325 struct repository *repo = the_repository;
2326 const struct git_hash_algo *algo = repo->hash_algo;
2327 const struct git_hash_algo *compat = repo->compat_hash_algo;
2328 struct object_id compat_oid;
1af64f73 2329 char hdr[MAX_HEADER_LEN];
ef1286d3 2330 int hdrlen = sizeof(hdr);
bbac7311 2331
63a6745a
EB
2332 /* Generate compat_oid */
2333 if (compat) {
c2538492
EB
2334 if (compat_oid_in)
2335 oidcpy(&compat_oid, compat_oid_in);
2336 else if (type == OBJ_BLOB)
63a6745a
EB
2337 hash_object_file(compat, buf, len, type, &compat_oid);
2338 else {
2339 struct strbuf converted = STRBUF_INIT;
2340 convert_object_file(&converted, algo, compat,
2341 buf, len, type, 0);
2342 hash_object_file(compat, converted.buf, converted.len,
2343 type, &compat_oid);
2344 strbuf_release(&converted);
2345 }
2346 }
2347
bbac7311
NP
2348 /* Normally if we have it in the pack then we do not bother writing
2349 * it out into .git/objects/??/?{38} file.
2350 */
63a6745a 2351 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
6862ebbf 2352 if (freshen_packed_object(oid) || freshen_loose_object(oid))
bbac7311 2353 return 0;
63a6745a
EB
2354 if (write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags))
2355 return -1;
2356 if (compat)
2357 return repo_add_loose_object_map(repo, oid, &compat_oid);
2358 return 0;
bbac7311
NP
2359}
2360
0ff7b4f9
ÆAB
2361int write_object_file_literally(const void *buf, unsigned long len,
2362 const char *type, struct object_id *oid,
2363 unsigned flags)
0c3db67c
ES
2364{
2365 char *header;
63a6745a
EB
2366 struct repository *repo = the_repository;
2367 const struct git_hash_algo *algo = repo->hash_algo;
2368 const struct git_hash_algo *compat = repo->compat_hash_algo;
2369 struct object_id compat_oid;
0c3db67c 2370 int hdrlen, status = 0;
63a6745a
EB
2371 int compat_type = -1;
2372
2373 if (compat) {
2374 compat_type = type_from_string_gently(type, -1, 1);
2375 if (compat_type == OBJ_BLOB)
2376 hash_object_file(compat, buf, len, compat_type,
2377 &compat_oid);
2378 else if (compat_type != -1) {
2379 struct strbuf converted = STRBUF_INIT;
2380 convert_object_file(&converted, algo, compat,
2381 buf, len, compat_type, 0);
2382 hash_object_file(compat, converted.buf, converted.len,
2383 compat_type, &compat_oid);
2384 strbuf_release(&converted);
2385 }
2386 }
0c3db67c
ES
2387
2388 /* type string, SP, %lu of the length plus NUL must fit this */
1af64f73 2389 hdrlen = strlen(type) + MAX_HEADER_LEN;
ef1286d3 2390 header = xmalloc(hdrlen);
2bbb28a3
ÆAB
2391 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2392 oid, header, &hdrlen);
0c3db67c
ES
2393
2394 if (!(flags & HASH_WRITE_OBJECT))
2395 goto cleanup;
6862ebbf 2396 if (freshen_packed_object(oid) || freshen_loose_object(oid))
0c3db67c 2397 goto cleanup;
4ef91a2d 2398 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
63a6745a
EB
2399 if (compat_type != -1)
2400 return repo_add_loose_object_map(repo, oid, &compat_oid);
0c3db67c
ES
2401
2402cleanup:
2403 free(header);
2404 return status;
2405}
2406
4bdb70a4 2407int force_object_loose(const struct object_id *oid, time_t mtime)
bbac7311 2408{
63a6745a
EB
2409 struct repository *repo = the_repository;
2410 const struct git_hash_algo *compat = repo->compat_hash_algo;
bbac7311
NP
2411 void *buf;
2412 unsigned long len;
b25562e6 2413 struct object_info oi = OBJECT_INFO_INIT;
63a6745a 2414 struct object_id compat_oid;
bbac7311 2415 enum object_type type;
1af64f73 2416 char hdr[MAX_HEADER_LEN];
bbac7311 2417 int hdrlen;
1fb23e65 2418 int ret;
bbac7311 2419
6862ebbf 2420 if (has_loose_object(oid))
bbac7311 2421 return 0;
b25562e6
JK
2422 oi.typep = &type;
2423 oi.sizep = &len;
2424 oi.contentp = &buf;
2425 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2c319886 2426 return error(_("cannot read object for %s"), oid_to_hex(oid));
63a6745a
EB
2427 if (compat) {
2428 if (repo_oid_to_algop(repo, oid, compat, &compat_oid))
2429 return error(_("cannot map object %s to %s"),
2430 oid_to_hex(oid), compat->name);
2431 }
b04cdea4 2432 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
4ef91a2d 2433 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
63a6745a
EB
2434 if (!ret && compat)
2435 ret = repo_add_loose_object_map(the_repository, oid, &compat_oid);
1fb23e65
BS
2436 free(buf);
2437
2438 return ret;
bbac7311
NP
2439}
2440
1d8d9cb6
JT
2441int has_object(struct repository *r, const struct object_id *oid,
2442 unsigned flags)
2443{
2444 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2445 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2446 (quick ? OBJECT_INFO_QUICK : 0);
2447
2448 if (!startup_info->have_repository)
2449 return 0;
2450 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2451}
2452
cba595ab
JH
2453int repo_has_object_file_with_flags(struct repository *r,
2454 const struct object_id *oid, int flags)
8237b185 2455{
3e8b7d3c
JN
2456 if (!startup_info->have_repository)
2457 return 0;
9c8a294a 2458 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
b419aa25 2459}
2460
9b45f499
SB
2461int repo_has_object_file(struct repository *r,
2462 const struct object_id *oid)
b419aa25 2463{
cba595ab 2464 return repo_has_object_file_with_flags(r, oid, 0);
5827a035
JK
2465}
2466
69bbbe48
JK
2467/*
2468 * We can't use the normal fsck_error_function() for index_mem(),
2469 * because we don't yet have a valid oid for it to report. Instead,
2470 * report the minimal fsck error here, and rely on the caller to
2471 * give more context.
2472 */
0b4e9013
JK
2473static int hash_format_check_report(struct fsck_options *opts UNUSED,
2474 const struct object_id *oid UNUSED,
2475 enum object_type object_type UNUSED,
2476 enum fsck_msg_type msg_type UNUSED,
2477 enum fsck_msg_id msg_id UNUSED,
69bbbe48
JK
2478 const char *message)
2479{
2480 error(_("object fails fsck: %s"), message);
2481 return 1;
c879daa2
NTND
2482}
2483
58bf2a4c
NTND
2484static int index_mem(struct index_state *istate,
2485 struct object_id *oid, void *buf, size_t size,
c4ce46fc
JH
2486 enum object_type type,
2487 const char *path, unsigned flags)
e7332f96 2488{
63e05f90 2489 int ret = 0;
bbea0dde 2490 int re_allocated = 0;
c4ce46fc 2491 int write_object = flags & HASH_WRITE_OBJECT;
74400e71 2492
7672db20 2493 if (!type)
edaec3fb 2494 type = OBJ_BLOB;
6c510bee
LT
2495
2496 /*
2497 * Convert blobs to git internal format
2498 */
43df4f86 2499 if ((type == OBJ_BLOB) && path) {
f285a2d7 2500 struct strbuf nbuf = STRBUF_INIT;
58bf2a4c 2501 if (convert_to_git(istate, path, buf, size, &nbuf,
8462ff43 2502 get_conv_flags(flags))) {
b315c5c0 2503 buf = strbuf_detach(&nbuf, &size);
6c510bee
LT
2504 re_allocated = 1;
2505 }
2506 }
c4ce46fc 2507 if (flags & HASH_FORMAT_CHECK) {
69bbbe48
JK
2508 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2509
2510 opts.strict = 1;
2511 opts.error_func = hash_format_check_report;
2512 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2513 die(_("refusing to create malformed object"));
2514 fsck_finish(&opts);
c879daa2 2515 }
6c510bee 2516
7672db20 2517 if (write_object)
c80d226a 2518 ret = write_object_file(buf, size, type, oid);
abdc3fc8 2519 else
44439c1c 2520 hash_object_file(the_hash_algo, buf, size, type, oid);
43df4f86 2521 if (re_allocated)
6c510bee 2522 free(buf);
43df4f86
DP
2523 return ret;
2524}
2525
58bf2a4c
NTND
2526static int index_stream_convert_blob(struct index_state *istate,
2527 struct object_id *oid,
2528 int fd,
2529 const char *path,
2530 unsigned flags)
9035d75a 2531{
63e05f90 2532 int ret = 0;
9035d75a
SP
2533 const int write_object = flags & HASH_WRITE_OBJECT;
2534 struct strbuf sbuf = STRBUF_INIT;
2535
2536 assert(path);
58bf2a4c 2537 assert(would_convert_to_git_filter_fd(istate, path));
9035d75a 2538
58bf2a4c 2539 convert_to_git_filter_fd(istate, path, fd, &sbuf,
8462ff43 2540 get_conv_flags(flags));
9035d75a
SP
2541
2542 if (write_object)
c80d226a 2543 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
a09c985e 2544 oid);
9035d75a 2545 else
44439c1c
ÆAB
2546 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2547 oid);
9035d75a
SP
2548 strbuf_release(&sbuf);
2549 return ret;
2550}
2551
58bf2a4c
NTND
2552static int index_pipe(struct index_state *istate, struct object_id *oid,
2553 int fd, enum object_type type,
7b41e1e1
JH
2554 const char *path, unsigned flags)
2555{
2556 struct strbuf sbuf = STRBUF_INIT;
2557 int ret;
2558
2559 if (strbuf_read(&sbuf, fd, 4096) >= 0)
58bf2a4c 2560 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
7b41e1e1
JH
2561 else
2562 ret = -1;
2563 strbuf_release(&sbuf);
2564 return ret;
2565}
2566
ea68b0ce
DP
2567#define SMALL_FILE_SIZE (32*1024)
2568
58bf2a4c
NTND
2569static int index_core(struct index_state *istate,
2570 struct object_id *oid, int fd, size_t size,
7b41e1e1
JH
2571 enum object_type type, const char *path,
2572 unsigned flags)
43df4f86
DP
2573{
2574 int ret;
43df4f86 2575
7b41e1e1 2576 if (!size) {
58bf2a4c 2577 ret = index_mem(istate, oid, "", size, type, path, flags);
ea68b0ce
DP
2578 } else if (size <= SMALL_FILE_SIZE) {
2579 char *buf = xmalloc(size);
90dca671
JK
2580 ssize_t read_result = read_in_full(fd, buf, size);
2581 if (read_result < 0)
259328b7 2582 ret = error_errno(_("read error while indexing %s"),
90dca671
JK
2583 path ? path : "<unknown>");
2584 else if (read_result != size)
259328b7 2585 ret = error(_("short read while indexing %s"),
90dca671 2586 path ? path : "<unknown>");
ea68b0ce 2587 else
58bf2a4c 2588 ret = index_mem(istate, oid, buf, size, type, path, flags);
ea68b0ce 2589 free(buf);
08bda208 2590 } else {
43df4f86 2591 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
58bf2a4c 2592 ret = index_mem(istate, oid, buf, size, type, path, flags);
aac17941 2593 munmap(buf, size);
08bda208 2594 }
7b41e1e1
JH
2595 return ret;
2596}
2597
4dd1fbc7 2598/*
568508e7
JH
2599 * This creates one packfile per large blob unless bulk-checkin
2600 * machinery is "plugged".
4dd1fbc7
JH
2601 *
2602 * This also bypasses the usual "convert-to-git" dance, and that is on
2603 * purpose. We could write a streaming version of the converting
2604 * functions and insert that before feeding the data to fast-import
4f22b101
JK
2605 * (or equivalent in-core API described above). However, that is
2606 * somewhat complicated, as we do not know the size of the filter
2607 * result, which we need to know beforehand when writing a git object.
2608 * Since the primary motivation for trying to stream from the working
2609 * tree file and to avoid mmaping it in core is to deal with large
2610 * binary blobs, they generally do not want to get any conversion, and
2611 * callers should avoid this code path when filters are requested.
4dd1fbc7 2612 */
9eb54197
EB
2613static int index_blob_stream(struct object_id *oid, int fd, size_t size,
2614 const char *path,
2615 unsigned flags)
4dd1fbc7 2616{
9eb54197 2617 return index_blob_bulk_checkin(oid, fd, size, path, flags);
4dd1fbc7
JH
2618}
2619
58bf2a4c
NTND
2620int index_fd(struct index_state *istate, struct object_id *oid,
2621 int fd, struct stat *st,
7b41e1e1
JH
2622 enum object_type type, const char *path, unsigned flags)
2623{
2624 int ret;
7b41e1e1 2625
9079ab7c
SP
2626 /*
2627 * Call xsize_t() only when needed to avoid potentially unnecessary
2628 * die() for large files.
2629 */
58bf2a4c
NTND
2630 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2631 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
9035d75a 2632 else if (!S_ISREG(st->st_mode))
58bf2a4c 2633 ret = index_pipe(istate, oid, fd, type, path, flags);
9079ab7c 2634 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
58bf2a4c
NTND
2635 (path && would_convert_to_git(istate, path)))
2636 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2637 type, path, flags);
4dd1fbc7 2638 else
9eb54197
EB
2639 ret = index_blob_stream(oid, fd, xsize_t(st->st_size), path,
2640 flags);
43df4f86 2641 close(fd);
aac17941 2642 return ret;
74400e71 2643}
ec1fcc16 2644
58bf2a4c
NTND
2645int index_path(struct index_state *istate, struct object_id *oid,
2646 const char *path, struct stat *st, unsigned flags)
ec1fcc16
JH
2647{
2648 int fd;
b760d3aa 2649 struct strbuf sb = STRBUF_INIT;
ea8e0297 2650 int rc = 0;
ec1fcc16
JH
2651
2652 switch (st->st_mode & S_IFMT) {
2653 case S_IFREG:
2654 fd = open(path, O_RDONLY);
2655 if (fd < 0)
7616c6ca 2656 return error_errno("open(\"%s\")", path);
58bf2a4c 2657 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
259328b7 2658 return error(_("%s: failed to insert into database"),
ec1fcc16
JH
2659 path);
2660 break;
2661 case S_IFLNK:
7616c6ca
NTND
2662 if (strbuf_readlink(&sb, path, st->st_size))
2663 return error_errno("readlink(\"%s\")", path);
c4ce46fc 2664 if (!(flags & HASH_WRITE_OBJECT))
2dcde20e 2665 hash_object_file(the_hash_algo, sb.buf, sb.len,
44439c1c 2666 OBJ_BLOB, oid);
c80d226a 2667 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
259328b7 2668 rc = error(_("%s: failed to insert into database"), path);
b760d3aa 2669 strbuf_release(&sb);
ec1fcc16 2670 break;
f35a6d3b 2671 case S_IFDIR:
a98e6101 2672 return resolve_gitlink_ref(path, "HEAD", oid);
ec1fcc16 2673 default:
259328b7 2674 return error(_("%s: unsupported file type"), path);
ec1fcc16 2675 }
ea8e0297 2676 return rc;
ec1fcc16 2677}
a69e5429
JH
2678
2679int read_pack_header(int fd, struct pack_header *header)
2680{
f48ecd38 2681 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
c697ad14
HO
2682 /* "eof before pack header was fully read" */
2683 return PH_ERROR_EOF;
2684
a69e5429
JH
2685 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2686 /* "protocol error (pack signature mismatch detected)" */
2687 return PH_ERROR_PACK_SIGNATURE;
2688 if (!pack_version_ok(header->hdr_version))
2689 /* "protocol error (pack version unsupported)" */
2690 return PH_ERROR_PROTOCOL;
2691 return 0;
2692}
40d52ff7 2693
e816caa0 2694void assert_oid_type(const struct object_id *oid, enum object_type expect)
40d52ff7 2695{
0df8e965 2696 enum object_type type = oid_object_info(the_repository, oid, NULL);
40d52ff7 2697 if (type < 0)
259328b7 2698 die(_("%s is not a valid object"), oid_to_hex(oid));
40d52ff7 2699 if (type != expect)
259328b7 2700 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
debca9d2 2701 type_name(expect));
40d52ff7 2702}
27e1e22d 2703
70c49050 2704int for_each_file_in_obj_subdir(unsigned int subdir_nr,
cc817ca3
RS
2705 struct strbuf *path,
2706 each_loose_object_fn obj_cb,
2707 each_loose_cruft_fn cruft_cb,
2708 each_loose_subdir_fn subdir_cb,
2709 void *data)
27e1e22d 2710{
0375f472
RS
2711 size_t origlen, baselen;
2712 DIR *dir;
27e1e22d
JK
2713 struct dirent *de;
2714 int r = 0;
62a24c89 2715 struct object_id oid;
27e1e22d 2716
70c49050
RS
2717 if (subdir_nr > 0xff)
2718 BUG("invalid loose object subdirectory: %x", subdir_nr);
2719
0375f472
RS
2720 origlen = path->len;
2721 strbuf_complete(path, '/');
2722 strbuf_addf(path, "%02x", subdir_nr);
0375f472
RS
2723
2724 dir = opendir(path->buf);
27e1e22d 2725 if (!dir) {
0375f472 2726 if (errno != ENOENT)
259328b7 2727 r = error_errno(_("unable to open %s"), path->buf);
0375f472
RS
2728 strbuf_setlen(path, origlen);
2729 return r;
27e1e22d
JK
2730 }
2731
62a24c89 2732 oid.hash[0] = subdir_nr;
163ee5e6
DS
2733 strbuf_addch(path, '/');
2734 baselen = path->len;
62a24c89 2735
b548f0f1 2736 while ((de = readdir_skip_dot_and_dotdot(dir))) {
163ee5e6 2737 size_t namelen;
27e1e22d 2738
163ee5e6 2739 namelen = strlen(de->d_name);
27e1e22d 2740 strbuf_setlen(path, baselen);
163ee5e6 2741 strbuf_add(path, de->d_name, namelen);
94b5e093 2742 if (namelen == the_hash_algo->hexsz - 2 &&
62a24c89 2743 !hex_to_bytes(oid.hash + 1, de->d_name,
94b5e093 2744 the_hash_algo->rawsz - 1)) {
5a6dce70 2745 oid_set_algo(&oid, the_hash_algo);
62a24c89
RS
2746 if (obj_cb) {
2747 r = obj_cb(&oid, path->buf, data);
2748 if (r)
2749 break;
27e1e22d 2750 }
62a24c89 2751 continue;
27e1e22d
JK
2752 }
2753
2754 if (cruft_cb) {
2755 r = cruft_cb(de->d_name, path->buf, data);
2756 if (r)
2757 break;
2758 }
2759 }
094c7e63 2760 closedir(dir);
27e1e22d 2761
163ee5e6 2762 strbuf_setlen(path, baselen - 1);
27e1e22d
JK
2763 if (!r && subdir_cb)
2764 r = subdir_cb(subdir_nr, path->buf, data);
2765
0375f472
RS
2766 strbuf_setlen(path, origlen);
2767
27e1e22d
JK
2768 return r;
2769}
2770
e6f875e0 2771int for_each_loose_file_in_objdir_buf(struct strbuf *path,
27e1e22d
JK
2772 each_loose_object_fn obj_cb,
2773 each_loose_cruft_fn cruft_cb,
2774 each_loose_subdir_fn subdir_cb,
2775 void *data)
2776{
27e1e22d
JK
2777 int r = 0;
2778 int i;
2779
27e1e22d 2780 for (i = 0; i < 256; i++) {
e6f875e0 2781 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
27e1e22d 2782 subdir_cb, data);
27e1e22d
JK
2783 if (r)
2784 break;
2785 }
2786
e6f875e0
JK
2787 return r;
2788}
2789
2790int for_each_loose_file_in_objdir(const char *path,
2791 each_loose_object_fn obj_cb,
2792 each_loose_cruft_fn cruft_cb,
2793 each_loose_subdir_fn subdir_cb,
2794 void *data)
2795{
2796 struct strbuf buf = STRBUF_INIT;
2797 int r;
2798
2799 strbuf_addstr(&buf, path);
2800 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2801 subdir_cb, data);
27e1e22d 2802 strbuf_release(&buf);
e6f875e0 2803
27e1e22d
JK
2804 return r;
2805}
660c889e 2806
a7ff6f5a
JK
2807int for_each_loose_object(each_loose_object_fn cb, void *data,
2808 enum for_each_object_flags flags)
660c889e 2809{
f0eaf638 2810 struct object_directory *odb;
b0a42642 2811
f0eaf638
JK
2812 prepare_alt_odb(the_repository);
2813 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2814 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2815 NULL, data);
2816 if (r)
2817 return r;
660c889e 2818
f0eaf638
JK
2819 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2820 break;
2821 }
1385bb7b 2822
f0eaf638 2823 return 0;
660c889e
JK
2824}
2825
be252d33
JK
2826static int append_loose_object(const struct object_id *oid,
2827 const char *path UNUSED,
3a2e0824 2828 void *data)
660c889e 2829{
92d8ed8a 2830 oidtree_insert(data, oid);
3a2e0824
JK
2831 return 0;
2832}
660c889e 2833
92d8ed8a 2834struct oidtree *odb_loose_cache(struct object_directory *odb,
0000d654
RS
2835 const struct object_id *oid)
2836{
2837 int subdir_nr = oid->hash[0];
3a2e0824 2838 struct strbuf buf = STRBUF_INIT;
33f379ee
EW
2839 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2840 size_t word_index = subdir_nr / word_bits;
26de1fc0 2841 size_t mask = (size_t)1u << (subdir_nr % word_bits);
33f379ee 2842 uint32_t *bitmap;
660c889e 2843
3a2e0824 2844 if (subdir_nr < 0 ||
33f379ee 2845 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
3a2e0824 2846 BUG("subdir_nr out of range");
1385bb7b 2847
33f379ee
EW
2848 bitmap = &odb->loose_objects_subdir_seen[word_index];
2849 if (*bitmap & mask)
92d8ed8a
EW
2850 return odb->loose_objects_cache;
2851 if (!odb->loose_objects_cache) {
2852 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2853 oidtree_init(odb->loose_objects_cache);
2854 }
3a2e0824
JK
2855 strbuf_addstr(&buf, odb->path);
2856 for_each_file_in_obj_subdir(subdir_nr, &buf,
2857 append_loose_object,
2858 NULL, NULL,
92d8ed8a 2859 odb->loose_objects_cache);
33f379ee 2860 *bitmap |= mask;
7317aa71 2861 strbuf_release(&buf);
92d8ed8a 2862 return odb->loose_objects_cache;
660c889e
JK
2863}
2864
d4e19e51
RS
2865void odb_clear_loose_cache(struct object_directory *odb)
2866{
92d8ed8a
EW
2867 oidtree_clear(odb->loose_objects_cache);
2868 FREE_AND_NULL(odb->loose_objects_cache);
d4e19e51
RS
2869 memset(&odb->loose_objects_subdir_seen, 0,
2870 sizeof(odb->loose_objects_subdir_seen));
2871}
2872
00a7760e
JK
2873static int check_stream_oid(git_zstream *stream,
2874 const char *hdr,
2875 unsigned long size,
2876 const char *path,
2877 const struct object_id *expected_oid)
f6371f92 2878{
18e2588e 2879 git_hash_ctx c;
00a7760e 2880 struct object_id real_oid;
f6371f92
JK
2881 unsigned char buf[4096];
2882 unsigned long total_read;
2883 int status = Z_OK;
2884
18e2588e 2885 the_hash_algo->init_fn(&c);
2886 the_hash_algo->update_fn(&c, hdr, stream->total_out);
f6371f92
JK
2887
2888 /*
2889 * We already read some bytes into hdr, but the ones up to the NUL
2890 * do not count against the object's content size.
2891 */
2892 total_read = stream->total_out - strlen(hdr) - 1;
2893
2894 /*
2895 * This size comparison must be "<=" to read the final zlib packets;
00a7760e 2896 * see the comment in unpack_loose_rest for details.
f6371f92
JK
2897 */
2898 while (total_read <= size &&
18ad13e5
JH
2899 (status == Z_OK ||
2900 (status == Z_BUF_ERROR && !stream->avail_out))) {
f6371f92
JK
2901 stream->next_out = buf;
2902 stream->avail_out = sizeof(buf);
2903 if (size - total_read < stream->avail_out)
2904 stream->avail_out = size - total_read;
2905 status = git_inflate(stream, Z_FINISH);
18e2588e 2906 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
f6371f92
JK
2907 total_read += stream->next_out - buf;
2908 }
2909 git_inflate_end(stream);
2910
2911 if (status != Z_STREAM_END) {
00a7760e 2912 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
f6371f92
JK
2913 return -1;
2914 }
cce044df 2915 if (stream->avail_in) {
259328b7 2916 error(_("garbage at end of loose object '%s'"),
00a7760e 2917 oid_to_hex(expected_oid));
cce044df
JK
2918 return -1;
2919 }
f6371f92 2920
5951bf46 2921 the_hash_algo->final_oid_fn(&real_oid, &c);
00a7760e 2922 if (!oideq(expected_oid, &real_oid)) {
01f8d594 2923 error(_("hash mismatch for %s (expected %s)"), path,
00a7760e 2924 oid_to_hex(expected_oid));
f6371f92
JK
2925 return -1;
2926 }
2927
2928 return 0;
2929}
2930
2931int read_loose_object(const char *path,
d61d87bd 2932 const struct object_id *expected_oid,
96e41f58 2933 struct object_id *real_oid,
31deb28f
ÆAB
2934 void **contents,
2935 struct object_info *oi)
f6371f92
JK
2936{
2937 int ret = -1;
ae285ac4 2938 int fd;
f6371f92
JK
2939 void *map = NULL;
2940 unsigned long mapsize;
2941 git_zstream stream;
1af64f73 2942 char hdr[MAX_HEADER_LEN];
31deb28f 2943 unsigned long *size = oi->sizep;
f6371f92 2944
ae285ac4
JT
2945 fd = git_open(path);
2946 if (fd >= 0)
2947 map = map_fd(fd, path, &mapsize);
f6371f92 2948 if (!map) {
259328b7 2949 error_errno(_("unable to mmap %s"), path);
f6371f92
JK
2950 goto out;
2951 }
2952
8a50571a
DS
2953 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
2954 NULL) != ULHR_OK) {
259328b7 2955 error(_("unable to unpack header of %s"), path);
f6371f92
JK
2956 goto out;
2957 }
2958
31deb28f 2959 if (parse_loose_header(hdr, oi) < 0) {
259328b7 2960 error(_("unable to parse header of %s"), path);
f6371f92
JK
2961 git_inflate_end(&stream);
2962 goto out;
2963 }
2964
31deb28f 2965 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
00a7760e 2966 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
f6371f92
JK
2967 goto out;
2968 } else {
00a7760e 2969 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
f6371f92 2970 if (!*contents) {
259328b7 2971 error(_("unable to unpack contents of %s"), path);
f6371f92
JK
2972 git_inflate_end(&stream);
2973 goto out;
2974 }
44439c1c 2975 hash_object_file_literally(the_repository->hash_algo,
16235e3b 2976 *contents, *size,
44439c1c 2977 oi->type_name->buf, real_oid);
0f156dbb 2978 if (!oideq(expected_oid, real_oid))
f6371f92 2979 goto out;
f6371f92
JK
2980 }
2981
2982 ret = 0; /* everything checks out */
2983
2984out:
2985 if (map)
2986 munmap(map, mapsize);
f6371f92
JK
2987 return ret;
2988}