Coverage Report

Created: 2023-11-27 06:56

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