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