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