Coverage Report

Created: 2026-12-01 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/odb/source-loose.c
Line
Count
Source
1
#include "git-compat-util.h"
2
#include "abspath.h"
3
#include "chdir-notify.h"
4
#include "gettext.h"
5
#include "hex.h"
6
#include "loose.h"
7
#include "object-file.h"
8
#include "object-file-convert.h"
9
#include "odb.h"
10
#include "odb/source-files.h"
11
#include "odb/source-loose.h"
12
#include "odb/streaming.h"
13
#include "oidtree.h"
14
#include "path.h"
15
#include "progress.h"
16
#include "repository.h"
17
#include "strbuf.h"
18
#include "tempfile.h"
19
#include "write-or-die.h"
20
21
static int append_loose_object(const struct object_id *oid,
22
             const char *path UNUSED,
23
             void *data)
24
0
{
25
0
  oidtree_insert(data, oid, NULL);
26
0
  return 0;
27
0
}
28
29
static uint32_t *subdir_seen_bitmap(struct odb_source_loose *loose,
30
            const struct object_id *oid,
31
            uint32_t *mask)
32
0
{
33
0
  int subdir_nr = oid->hash[0];
34
0
  size_t word_bits = bitsizeof(loose->subdir_seen[0]);
35
0
  size_t word_index = subdir_nr / word_bits;
36
37
0
  if (subdir_nr < 0 ||
38
0
      (size_t) subdir_nr >= bitsizeof(loose->subdir_seen))
39
0
    BUG("subdir_nr out of range");
40
41
0
  *mask = (size_t)1u << (subdir_nr % word_bits);
42
43
0
  return &loose->subdir_seen[word_index];
44
0
}
45
46
static struct oidtree *odb_source_loose_cache(struct odb_source_loose *loose,
47
                const struct object_id *oid)
48
0
{
49
0
  struct strbuf buf = STRBUF_INIT;
50
0
  uint32_t *bitmap, mask;
51
52
0
  bitmap = subdir_seen_bitmap(loose, oid, &mask);
53
0
  if (*bitmap & mask)
54
0
    return loose->cache;
55
56
0
  if (!loose->cache) {
57
0
    ALLOC_ARRAY(loose->cache, 1);
58
0
    oidtree_init(loose->cache);
59
0
  }
60
0
  strbuf_addstr(&buf, loose->base.path);
61
0
  for_each_file_in_obj_subdir(oid->hash[0], &buf,
62
0
            loose->base.odb->repo->hash_algo,
63
0
            append_loose_object,
64
0
            NULL, NULL,
65
0
            loose->cache);
66
0
  *bitmap |= mask;
67
0
  strbuf_release(&buf);
68
0
  return loose->cache;
69
0
}
70
71
/*
72
 * Mark an object as seen in the loose cache. Note that we only do this in case
73
 * the particular subdirectory was scanned already. If it wasn't, then the next
74
 * read would populate it anyway.
75
 */
76
static void loose_cache_mark_seen(struct odb_source_loose *loose,
77
          const struct object_id *oid)
78
0
{
79
0
  uint32_t mask, *bitmap = subdir_seen_bitmap(loose, oid, &mask);
80
0
  if (*bitmap & mask)
81
0
    oidtree_insert(loose->cache, oid, NULL);
82
0
}
83
84
static int quick_has_loose(struct odb_source_loose *loose,
85
         const struct object_id *oid)
86
0
{
87
0
  return !!oidtree_contains(odb_source_loose_cache(loose, oid), oid);
88
0
}
89
90
static int read_object_info_from_path(struct odb_source_loose *loose,
91
              const char *path,
92
              const struct object_id *oid,
93
              struct object_info *oi,
94
              enum object_info_flags flags,
95
              struct strbuf *errmsg)
96
0
{
97
0
  int ret;
98
0
  int fd;
99
0
  unsigned long mapsize;
100
0
  void *map = NULL;
101
0
  git_zstream stream, *stream_to_end = NULL;
102
0
  char hdr[MAX_HEADER_LEN];
103
0
  size_t size_scratch;
104
0
  enum object_type type_scratch;
105
0
  struct stat st;
106
107
  /*
108
   * If we don't care about type or size, then we don't
109
   * need to look inside the object at all. Note that we
110
   * do not optimize out the stat call, even if the
111
   * caller doesn't care about the disk-size, since our
112
   * return value implicitly indicates whether the
113
   * object even exists.
114
   */
115
0
  if (!oi || (!oi->typep && !oi->sizep && !oi->contentp)) {
116
0
    struct stat st;
117
118
0
    if ((!oi || (!oi->disk_sizep && !oi->mtimep)) && (flags & OBJECT_INFO_QUICK)) {
119
0
      ret = quick_has_loose(loose, oid) ? 0 : ODB_READ_NOT_FOUND;
120
0
      goto out;
121
0
    }
122
123
0
    if (lstat(path, &st) < 0) {
124
0
      if (errno == ENOENT) {
125
0
        ret = ODB_READ_NOT_FOUND;
126
0
        goto out;
127
0
      }
128
129
0
      ret = -1;
130
0
      goto out;
131
0
    }
132
133
0
    if (oi) {
134
0
      if (oi->disk_sizep)
135
0
        *oi->disk_sizep = st.st_size;
136
0
      if (oi->mtimep)
137
0
        *oi->mtimep = st.st_mtime;
138
0
    }
139
140
0
    ret = 0;
141
0
    goto out;
142
0
  }
143
144
0
  fd = git_open(path);
145
0
  if (fd < 0) {
146
0
    if (errno == ENOENT) {
147
0
      ret = ODB_READ_NOT_FOUND;
148
0
      goto out;
149
0
    }
150
151
0
    ret = error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
152
0
    goto out;
153
0
  }
154
155
0
  if (fstat(fd, &st)) {
156
0
    close(fd);
157
0
    ret = -1;
158
0
    goto out;
159
0
  }
160
161
0
  mapsize = xsize_t(st.st_size);
162
0
  if (!mapsize) {
163
0
    close(fd);
164
0
    ret = error(_("object file %s is empty"), path);
165
0
    goto out;
166
0
  }
167
168
0
  map = xmmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
169
0
  close(fd);
170
0
  if (!map) {
171
0
    ret = -1;
172
0
    goto out;
173
0
  }
174
175
0
  if (oi->disk_sizep)
176
0
    *oi->disk_sizep = mapsize;
177
0
  if (oi->mtimep)
178
0
    *oi->mtimep = st.st_mtime;
179
180
0
  stream_to_end = &stream;
181
182
0
  switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr))) {
183
0
  case ULHR_OK:
184
0
    if (!oi->sizep)
185
0
      oi->sizep = &size_scratch;
186
0
    if (!oi->typep)
187
0
      oi->typep = &type_scratch;
188
189
0
    if (parse_loose_header(hdr, oi) < 0) {
190
0
      ret = error(_("unable to parse %s header"), oid_to_hex(oid));
191
0
      goto out;
192
0
    }
193
194
0
    if (*oi->typep < 0)
195
0
      die(_("invalid object type"));
196
197
0
    if (oi->contentp) {
198
0
      *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
199
0
      if (!*oi->contentp) {
200
0
        ret = -1;
201
0
        goto out;
202
0
      }
203
0
    }
204
205
0
    break;
206
0
  case ULHR_BAD:
207
0
    ret = error(_("unable to unpack %s header"),
208
0
          oid_to_hex(oid));
209
0
    goto out;
210
0
  case ULHR_TOO_LONG:
211
0
    ret = error(_("header for %s too long, exceeds %d bytes"),
212
0
          oid_to_hex(oid), MAX_HEADER_LEN);
213
0
    goto out;
214
0
  }
215
216
0
  ret = 0;
217
218
0
out:
219
0
  if (ret && ret != ODB_READ_NOT_FOUND && errmsg)
220
0
    strbuf_addf(errmsg, _("loose object %s (stored in %s) is corrupt"),
221
0
          oid_to_hex(oid), path);
222
0
  if (stream_to_end)
223
0
    git_inflate_end(stream_to_end);
224
0
  if (map)
225
0
    munmap(map, mapsize);
226
0
  if (oi) {
227
0
    if (oi->sizep == &size_scratch)
228
0
      oi->sizep = NULL;
229
0
    if (oi->typep == &type_scratch)
230
0
      oi->typep = NULL;
231
0
    if (oi->delta_base_oid)
232
0
      oidclr(oi->delta_base_oid, loose->base.odb->repo->hash_algo);
233
0
    if (oi->source_infop && !ret)
234
0
      oi->source_infop->source = &loose->base;
235
0
  }
236
237
0
  return ret;
238
0
}
239
240
static enum odb_read_status odb_source_loose_read_object_info(struct odb_source *source,
241
                    const struct object_id *oid,
242
                    struct object_info *oi,
243
                    enum object_info_flags flags,
244
                    struct strbuf *errmsg)
245
0
{
246
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
247
0
  static struct strbuf buf = STRBUF_INIT;
248
0
  odb_loose_path(loose, &buf, oid);
249
0
  return read_object_info_from_path(loose, buf.buf, oid, oi, flags, errmsg);
250
0
}
251
252
/*
253
 * Find "oid" as a loose object in given source, open the object and return its
254
 * file descriptor. Returns the file descriptor on success, negative on failure.
255
 *
256
 * The "path" out-parameter will give the path of the object we found (if any).
257
 * Note that it may point to static storage and is only valid until another
258
 * call to open_loose_object().
259
 */
260
static int open_loose_object(struct odb_source_loose *loose,
261
           const struct object_id *oid, const char **path)
262
0
{
263
0
  static struct strbuf buf = STRBUF_INIT;
264
0
  int fd;
265
266
0
  *path = odb_loose_path(loose, &buf, oid);
267
0
  fd = git_open(*path);
268
0
  if (fd >= 0)
269
0
    return fd;
270
271
0
  return -1;
272
0
}
273
274
static void *odb_source_loose_map_object(struct odb_source_loose *loose,
275
           const struct object_id *oid,
276
           unsigned long *size)
277
0
{
278
0
  const char *p;
279
0
  int fd = open_loose_object(loose, oid, &p);
280
0
  void *map = NULL;
281
0
  struct stat st;
282
283
0
  if (fd < 0)
284
0
    return NULL;
285
286
0
  if (!fstat(fd, &st)) {
287
0
    *size = xsize_t(st.st_size);
288
0
    if (!*size) {
289
      /* mmap() is forbidden on empty files */
290
0
      error(_("object file %s is empty"), p);
291
0
      goto out;
292
0
    }
293
294
0
    map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
295
0
  }
296
297
0
out:
298
0
  close(fd);
299
0
  return map;
300
0
}
301
302
struct odb_loose_read_stream {
303
  struct odb_stream base;
304
  git_zstream z;
305
  enum {
306
    ODB_LOOSE_READ_STREAM_INUSE,
307
    ODB_LOOSE_READ_STREAM_DONE,
308
    ODB_LOOSE_READ_STREAM_ERROR,
309
  } z_state;
310
  void *mapped;
311
  unsigned long mapsize;
312
  char hdr[32];
313
  int hdr_avail;
314
  int hdr_used;
315
};
316
317
static ssize_t read_istream_loose(struct odb_stream *_st, char *buf, size_t sz)
318
0
{
319
0
  struct odb_loose_read_stream *st =
320
0
    container_of(_st, struct odb_loose_read_stream, base);
321
0
  size_t total_read = 0;
322
323
0
  switch (st->z_state) {
324
0
  case ODB_LOOSE_READ_STREAM_DONE:
325
0
    return 0;
326
0
  case ODB_LOOSE_READ_STREAM_ERROR:
327
0
    return -1;
328
0
  default:
329
0
    break;
330
0
  }
331
332
0
  if (st->hdr_used < st->hdr_avail) {
333
0
    size_t to_copy = st->hdr_avail - st->hdr_used;
334
0
    if (sz < to_copy)
335
0
      to_copy = sz;
336
0
    memcpy(buf, st->hdr + st->hdr_used, to_copy);
337
0
    st->hdr_used += to_copy;
338
0
    total_read += to_copy;
339
0
  }
340
341
0
  while (total_read < sz) {
342
0
    int status;
343
344
0
    st->z.next_out = (unsigned char *)buf + total_read;
345
0
    st->z.avail_out = sz - total_read;
346
0
    status = git_inflate(&st->z, Z_FINISH);
347
348
0
    total_read = st->z.next_out - (unsigned char *)buf;
349
350
0
    if (status == Z_STREAM_END) {
351
0
      git_inflate_end(&st->z);
352
0
      st->z_state = ODB_LOOSE_READ_STREAM_DONE;
353
0
      break;
354
0
    }
355
0
    if (status != Z_OK && (status != Z_BUF_ERROR || total_read < sz)) {
356
0
      git_inflate_end(&st->z);
357
0
      st->z_state = ODB_LOOSE_READ_STREAM_ERROR;
358
0
      return -1;
359
0
    }
360
0
  }
361
0
  return total_read;
362
0
}
363
364
static int close_istream_loose(struct odb_stream *_st)
365
0
{
366
0
  struct odb_loose_read_stream *st =
367
0
    container_of(_st, struct odb_loose_read_stream, base);
368
369
0
  if (st->z_state == ODB_LOOSE_READ_STREAM_INUSE)
370
0
    git_inflate_end(&st->z);
371
0
  munmap(st->mapped, st->mapsize);
372
0
  return 0;
373
0
}
374
375
static int odb_source_loose_read_object_stream(struct odb_stream **out,
376
                 struct odb_source *source,
377
                 const struct object_id *oid)
378
0
{
379
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
380
0
  struct object_info oi = OBJECT_INFO_INIT;
381
0
  struct odb_loose_read_stream *st;
382
0
  unsigned long mapsize;
383
0
  void *mapped;
384
385
0
  mapped = odb_source_loose_map_object(loose, oid, &mapsize);
386
0
  if (!mapped)
387
0
    return -1;
388
389
  /*
390
   * Note: we must allocate this structure early even though we may still
391
   * fail. This is because we need to initialize the zlib stream, and it
392
   * is not possible to copy the stream around after the fact because it
393
   * has self-referencing pointers.
394
   */
395
0
  CALLOC_ARRAY(st, 1);
396
397
0
  switch (unpack_loose_header(&st->z, mapped, mapsize, st->hdr,
398
0
            sizeof(st->hdr))) {
399
0
  case ULHR_OK:
400
0
    break;
401
0
  case ULHR_BAD:
402
0
  case ULHR_TOO_LONG:
403
0
    goto error;
404
0
  }
405
406
0
  oi.sizep = &st->base.size;
407
0
  oi.typep = &st->base.type;
408
409
0
  if (parse_loose_header(st->hdr, &oi) < 0 || st->base.type < 0)
410
0
    goto error;
411
412
0
  st->mapped = mapped;
413
0
  st->mapsize = mapsize;
414
0
  st->hdr_used = strlen(st->hdr) + 1;
415
0
  st->hdr_avail = st->z.total_out;
416
0
  st->z_state = ODB_LOOSE_READ_STREAM_INUSE;
417
0
  st->base.close = close_istream_loose;
418
0
  st->base.read = read_istream_loose;
419
420
0
  *out = &st->base;
421
422
0
  return 0;
423
0
error:
424
0
  git_inflate_end(&st->z);
425
0
  munmap(mapped, mapsize);
426
0
  free(st);
427
0
  return -1;
428
0
}
429
430
struct for_each_object_wrapper_data {
431
  struct odb_source_loose *loose;
432
  const struct object_info *request;
433
  odb_for_each_object_cb cb;
434
  void *cb_data;
435
};
436
437
static int for_each_object_wrapper_cb(const struct object_id *oid,
438
              const char *path,
439
              void *cb_data)
440
0
{
441
0
  struct for_each_object_wrapper_data *data = cb_data;
442
443
0
  if (data->request) {
444
0
    struct object_info oi = *data->request;
445
446
0
    if (read_object_info_from_path(data->loose, path, oid, &oi, 0, NULL) < 0)
447
0
      return -1;
448
449
0
    return data->cb(oid, &oi, data->cb_data);
450
0
  } else {
451
0
    return data->cb(oid, NULL, data->cb_data);
452
0
  }
453
0
}
454
455
static int for_each_prefixed_object_wrapper_cb(const struct object_id *oid,
456
                 void *node_data UNUSED,
457
                 void *cb_data)
458
0
{
459
0
  struct for_each_object_wrapper_data *data = cb_data;
460
0
  if (data->request) {
461
0
    struct object_info oi = *data->request;
462
463
0
    if (odb_source_read_object_info(&data->loose->base,
464
0
            oid, &oi, 0, NULL) < 0)
465
0
      return -1;
466
467
0
    return data->cb(oid, &oi, data->cb_data);
468
0
  } else {
469
0
    return data->cb(oid, NULL, data->cb_data);
470
0
  }
471
0
}
472
473
static int odb_source_loose_for_each_object(struct odb_source *source,
474
              const struct object_info *request,
475
              odb_for_each_object_cb cb,
476
              void *cb_data,
477
              const struct odb_for_each_object_options *opts)
478
0
{
479
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
480
0
  struct for_each_object_wrapper_data data = {
481
0
    .loose = loose,
482
0
    .request = request,
483
0
    .cb = cb,
484
0
    .cb_data = cb_data,
485
0
  };
486
487
  /* There are no loose promisor objects, so we can return immediately. */
488
0
  if ((opts->flags & ODB_FOR_EACH_OBJECT_PROMISOR_ONLY))
489
0
    return 0;
490
491
0
  if (opts->prefix)
492
0
    return oidtree_each(odb_source_loose_cache(loose, opts->prefix),
493
0
            opts->prefix, opts->prefix_hex_len,
494
0
            for_each_prefixed_object_wrapper_cb, &data);
495
496
0
  return for_each_loose_file_in_source(source, for_each_object_wrapper_cb,
497
0
               NULL, NULL, &data);
498
0
}
499
500
struct find_abbrev_len_data {
501
  const struct object_id *oid;
502
  unsigned len;
503
};
504
505
static int find_abbrev_len_cb(const struct object_id *oid,
506
            struct object_info *oi UNUSED,
507
            void *cb_data)
508
0
{
509
0
  struct find_abbrev_len_data *data = cb_data;
510
0
  unsigned len = oid_common_prefix_hexlen(oid, data->oid);
511
0
  if (len != hash_algos[oid->algo].hexsz && len >= data->len)
512
0
    data->len = len + 1;
513
0
  return 0;
514
0
}
515
516
static int odb_source_loose_find_abbrev_len(struct odb_source *source,
517
              const struct object_id *oid,
518
              unsigned min_len,
519
              unsigned *out)
520
0
{
521
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
522
0
  struct odb_for_each_object_options opts = {
523
0
    .prefix = oid,
524
0
    .prefix_hex_len = min_len,
525
0
  };
526
0
  struct find_abbrev_len_data data = {
527
0
    .oid = oid,
528
0
    .len = min_len,
529
0
  };
530
0
  int ret;
531
532
0
  ret = odb_source_for_each_object(&loose->base, NULL, find_abbrev_len_cb,
533
0
           &data, &opts);
534
0
  *out = data.len;
535
536
0
  return ret;
537
0
}
538
539
static int count_loose_object(const struct object_id *oid UNUSED,
540
            struct object_info *oi UNUSED,
541
            void *payload)
542
0
{
543
0
  unsigned long *count = payload;
544
0
  (*count)++;
545
0
  return 0;
546
0
}
547
548
static int odb_source_loose_count_objects(struct odb_source *source,
549
            enum odb_count_objects_flags flags,
550
            unsigned long *out)
551
0
{
552
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
553
0
  const unsigned hexsz = source->odb->repo->hash_algo->hexsz - 2;
554
0
  char *path = NULL;
555
0
  DIR *dir = NULL;
556
0
  int ret;
557
558
0
  if (flags & ODB_COUNT_OBJECTS_APPROXIMATE) {
559
0
    unsigned long count = 0;
560
0
    struct dirent *ent;
561
562
0
    path = xstrfmt("%s/17", source->path);
563
564
0
    dir = opendir(path);
565
0
    if (!dir) {
566
0
      if (errno == ENOENT) {
567
0
        *out = 0;
568
0
        ret = 0;
569
0
        goto out;
570
0
      }
571
572
0
      ret = error_errno("cannot open object shard '%s'", path);
573
0
      goto out;
574
0
    }
575
576
0
    while ((ent = readdir(dir)) != NULL) {
577
0
      if (strspn(ent->d_name, "0123456789abcdef") != hexsz ||
578
0
          ent->d_name[hexsz] != '\0')
579
0
        continue;
580
0
      count++;
581
0
    }
582
583
0
    *out = count * 256;
584
0
    ret = 0;
585
0
  } else {
586
0
    struct odb_for_each_object_options opts = { 0 };
587
0
    *out = 0;
588
0
    ret = odb_source_for_each_object(&loose->base, NULL, count_loose_object,
589
0
             out, &opts);
590
0
  }
591
592
0
out:
593
0
  if (dir)
594
0
    closedir(dir);
595
0
  free(path);
596
0
  return ret;
597
0
}
598
599
static int odb_source_loose_freshen_object(struct odb_source *source,
600
             const struct object_id *oid,
601
             const time_t *mtime)
602
0
{
603
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
604
0
  static struct strbuf path = STRBUF_INIT;
605
0
  odb_loose_path(loose, &path, oid);
606
0
  return !!check_and_freshen_file(path.buf, 1, mtime);
607
0
}
608
609
/* Finalize a file on disk, and close it. */
610
static void close_loose_object(struct odb_source_loose *loose,
611
             int fd, const char *filename)
612
0
{
613
0
  if (loose->will_destroy)
614
0
    goto out;
615
616
0
  if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
617
0
    odb_transaction_files_fsync(loose->base.odb->transaction, fd, filename);
618
0
  else if (fsync_object_files > 0)
619
0
    fsync_or_die(fd, filename);
620
0
  else
621
0
    fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
622
0
               filename);
623
624
0
out:
625
0
  if (close(fd) != 0)
626
0
    die_errno(_("error when closing loose object file"));
627
0
}
628
629
/* Size of directory component, including the ending '/' */
630
static inline int directory_size(const char *filename)
631
0
{
632
0
  const char *s = strrchr(filename, '/');
633
0
  if (!s)
634
0
    return 0;
635
0
  return s - filename + 1;
636
0
}
637
638
/*
639
 * This creates a temporary file in the same directory as the final
640
 * 'filename'
641
 *
642
 * We want to avoid cross-directory filename renames, because those
643
 * can have problems on various filesystems (FAT, NFS, Coda).
644
 */
645
static int create_tmpfile(struct repository *repo,
646
        struct strbuf *tmp, const char *filename)
647
0
{
648
0
  int fd, dirlen = directory_size(filename);
649
650
0
  strbuf_reset(tmp);
651
0
  strbuf_add(tmp, filename, dirlen);
652
0
  strbuf_addstr(tmp, "tmp_obj_XXXXXX");
653
0
  fd = git_mkstemp_mode(tmp->buf, 0444);
654
0
  if (fd < 0 && dirlen && errno == ENOENT) {
655
    /*
656
     * Make sure the directory exists; note that the contents
657
     * of the buffer are undefined after mkstemp returns an
658
     * error, so we have to rewrite the whole buffer from
659
     * scratch.
660
     */
661
0
    strbuf_reset(tmp);
662
0
    strbuf_add(tmp, filename, dirlen - 1);
663
0
    if (mkdir(tmp->buf, 0777) && errno != EEXIST)
664
0
      return -1;
665
0
    if (adjust_shared_perm(repo, tmp->buf))
666
0
      return -1;
667
668
    /* Try again */
669
0
    strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
670
0
    fd = git_mkstemp_mode(tmp->buf, 0444);
671
0
  }
672
0
  return fd;
673
0
}
674
675
/**
676
 * Common steps for loose object writers to start writing loose
677
 * objects:
678
 *
679
 * - Create tmpfile for the loose object.
680
 * - Setup zlib stream for compression.
681
 * - Start to feed header to zlib stream.
682
 *
683
 * Returns a "fd", which should later be provided to
684
 * end_loose_object_common().
685
 */
686
static int start_loose_object_common(struct odb_source_loose *loose,
687
             struct strbuf *tmp_file,
688
             const char *filename, unsigned flags,
689
             git_zstream *stream,
690
             unsigned char *buf, size_t buflen,
691
             struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
692
             char *hdr, int hdrlen)
693
0
{
694
0
  const struct git_hash_algo *algo = loose->base.odb->repo->hash_algo;
695
0
  const struct git_hash_algo *compat = loose->base.odb->repo->compat_hash_algo;
696
0
  int fd;
697
0
  struct repo_config_values *cfg = repo_config_values(loose->base.odb->repo);
698
699
0
  fd = create_tmpfile(loose->base.odb->repo, tmp_file, filename);
700
0
  if (fd < 0) {
701
0
    if (flags & ODB_WRITE_OBJECT_SILENT)
702
0
      return -1;
703
0
    else if (errno == EACCES)
704
0
      return error(_("insufficient permission for adding "
705
0
               "an object to repository database %s"),
706
0
             loose->base.path);
707
0
    else
708
0
      return error_errno(
709
0
        _("unable to create temporary file"));
710
0
  }
711
712
  /*  Setup zlib stream for compression */
713
0
  git_deflate_init(stream, cfg->zlib_compression_level);
714
0
  stream->next_out = buf;
715
0
  stream->avail_out = buflen;
716
0
  git_hash_init(c, algo);
717
0
  if (compat && compat_c)
718
0
    git_hash_init(compat_c, compat);
719
720
  /*  Start to feed header to zlib stream */
721
0
  stream->next_in = (unsigned char *)hdr;
722
0
  stream->avail_in = hdrlen;
723
0
  while (git_deflate(stream, 0) == Z_OK)
724
0
    ; /* nothing */
725
0
  git_hash_update(c, hdr, hdrlen);
726
0
  if (compat && compat_c)
727
0
    git_hash_update(compat_c, hdr, hdrlen);
728
729
0
  return fd;
730
0
}
731
732
/**
733
 * Common steps for the inner git_deflate() loop for writing loose
734
 * objects. Returns what git_deflate() returns.
735
 */
736
static int write_loose_object_common(struct odb_source_loose *loose,
737
             struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
738
             git_zstream *stream, const int flush,
739
             unsigned char *in0, const int fd,
740
             unsigned char *compressed,
741
             const size_t compressed_len)
742
0
{
743
0
  const struct git_hash_algo *compat = loose->base.odb->repo->compat_hash_algo;
744
0
  int ret;
745
746
0
  ret = git_deflate(stream, flush ? Z_FINISH : 0);
747
0
  git_hash_update(c, in0, stream->next_in - in0);
748
0
  if (compat && compat_c)
749
0
    git_hash_update(compat_c, in0, stream->next_in - in0);
750
0
  if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
751
0
    die_errno(_("unable to write loose object file"));
752
0
  stream->next_out = compressed;
753
0
  stream->avail_out = compressed_len;
754
755
0
  return ret;
756
0
}
757
758
/**
759
 * Common steps for loose object writers to end writing loose objects:
760
 *
761
 * - End the compression of zlib stream.
762
 * - Get the calculated oid to "oid".
763
 */
764
static int end_loose_object_common(struct odb_source_loose *loose,
765
           struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
766
           git_zstream *stream, struct object_id *oid,
767
           struct object_id *compat_oid)
768
0
{
769
0
  const struct git_hash_algo *compat = loose->base.odb->repo->compat_hash_algo;
770
0
  int ret;
771
772
0
  ret = git_deflate_end_gently(stream);
773
0
  if (ret != Z_OK)
774
0
    return ret;
775
0
  git_hash_final_oid(oid, c);
776
0
  if (compat && compat_c)
777
0
    git_hash_final_oid(compat_oid, compat_c);
778
779
0
  return Z_OK;
780
0
}
781
782
static int write_loose_object(struct odb_source_loose *loose,
783
            const struct object_id *oid, char *hdr,
784
            int hdrlen, const void *buf, unsigned long len,
785
            const time_t *mtime, unsigned flags)
786
0
{
787
0
  int fd, ret;
788
0
  unsigned char compressed[4096];
789
0
  git_zstream stream;
790
0
  struct git_hash_ctx c;
791
0
  struct object_id parano_oid;
792
0
  static struct strbuf tmp_file = STRBUF_INIT;
793
0
  static struct strbuf filename = STRBUF_INIT;
794
795
0
  odb_loose_path(loose, &filename, oid);
796
797
0
  fd = start_loose_object_common(loose, &tmp_file, filename.buf, flags,
798
0
               &stream, compressed, sizeof(compressed),
799
0
               &c, NULL, hdr, hdrlen);
800
0
  if (fd < 0)
801
0
    return -1;
802
803
  /* Then the data itself.. */
804
0
  stream.next_in = (void *)buf;
805
0
  stream.avail_in = len;
806
0
  do {
807
0
    unsigned char *in0 = stream.next_in;
808
809
0
    ret = write_loose_object_common(loose, &c, NULL, &stream, 1, in0, fd,
810
0
            compressed, sizeof(compressed));
811
0
  } while (ret == Z_OK);
812
813
0
  if (ret != Z_STREAM_END)
814
0
    die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
815
0
        ret);
816
0
  ret = end_loose_object_common(loose, &c, NULL, &stream, &parano_oid, NULL);
817
0
  if (ret != Z_OK)
818
0
    die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
819
0
        ret);
820
0
  if (!oideq(oid, &parano_oid))
821
0
    die(_("confused by unstable object source data for %s"),
822
0
        oid_to_hex(oid));
823
824
0
  close_loose_object(loose, fd, tmp_file.buf);
825
826
0
  if (mtime) {
827
0
    struct utimbuf utb = {
828
0
      .actime = *mtime,
829
0
      .modtime = *mtime,
830
0
    };
831
832
0
    if (utime(tmp_file.buf, &utb) < 0 &&
833
0
        !(flags & ODB_WRITE_OBJECT_SILENT))
834
0
      warning_errno(_("failed utime() on %s"), tmp_file.buf);
835
0
  }
836
837
0
  ret = finalize_object_file_flags(loose->base.odb->repo, tmp_file.buf, filename.buf,
838
0
           FOF_SKIP_COLLISION_CHECK);
839
0
  if (ret < 0)
840
0
    return ret;
841
842
0
  loose_cache_mark_seen(loose, oid);
843
0
  return 0;
844
0
}
845
846
static int odb_source_loose_write_object(struct odb_source *source,
847
           const void *buf, size_t len,
848
           enum object_type type,
849
           const struct object_id *oid,
850
           const struct object_id *compat_oid,
851
           const time_t *mtime,
852
           enum odb_write_object_flags flags)
853
0
{
854
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
855
0
  char hdr[MAX_HEADER_LEN];
856
0
  int hdrlen;
857
858
0
  hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
859
860
0
  if (write_loose_object(loose, oid, hdr, hdrlen, buf, len, mtime, flags))
861
0
    return -1;
862
863
0
  if (compat_oid)
864
0
    return repo_add_loose_object_map(loose, oid, compat_oid);
865
866
0
  return 0;
867
0
}
868
869
static int odb_source_loose_write_object_stream(struct odb_source *source,
870
            struct odb_stream *in_stream,
871
            struct object_id *oid)
872
0
{
873
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
874
0
  const struct git_hash_algo *compat = loose->base.odb->repo->compat_hash_algo;
875
0
  struct object_id compat_oid;
876
0
  int fd, ret, err = 0, flush = 0;
877
0
  unsigned char compressed[4096];
878
0
  git_zstream stream;
879
0
  struct git_hash_ctx c, compat_c;
880
0
  struct strbuf tmp_file = STRBUF_INIT;
881
0
  struct strbuf filename = STRBUF_INIT;
882
0
  unsigned char buf[8192];
883
0
  int dirlen;
884
0
  bool is_finished = false;
885
0
  char hdr[MAX_HEADER_LEN];
886
0
  int hdrlen;
887
888
  /* Since oid is not determined, save tmp file to odb path. */
889
0
  strbuf_addf(&filename, "%s/", loose->base.path);
890
0
  hdrlen = format_object_header(hdr, sizeof(hdr), in_stream->type, in_stream->size);
891
892
  /*
893
   * Common steps for write_loose_object and stream_loose_object to
894
   * start writing loose objects:
895
   *
896
   *  - Create tmpfile for the loose object.
897
   *  - Setup zlib stream for compression.
898
   *  - Start to feed header to zlib stream.
899
   */
900
0
  fd = start_loose_object_common(loose, &tmp_file, filename.buf, 0,
901
0
               &stream, compressed, sizeof(compressed),
902
0
               &c, &compat_c, hdr, hdrlen);
903
0
  if (fd < 0) {
904
0
    err = -1;
905
0
    goto cleanup;
906
0
  }
907
908
  /* Then the data itself.. */
909
0
  do {
910
0
    unsigned char *in0 = stream.next_in;
911
912
0
    if (!stream.avail_in && !is_finished) {
913
0
      ssize_t read_len = odb_stream_read(in_stream, buf,
914
0
                 sizeof(buf));
915
0
      if (read_len < 0) {
916
0
        close(fd);
917
0
        err = -1;
918
0
        goto cleanup;
919
0
      }
920
921
      /* All data has been read. */
922
0
      if (!read_len) {
923
0
        is_finished = true;
924
0
        flush = 1;
925
0
      }
926
927
0
      stream.avail_in = read_len;
928
0
      stream.next_in = buf;
929
0
      in0 = buf;
930
0
    }
931
0
    ret = write_loose_object_common(loose, &c, &compat_c, &stream, flush, in0, fd,
932
0
            compressed, sizeof(compressed));
933
    /*
934
     * Unlike write_loose_object(), we do not have the entire
935
     * buffer. If we get Z_BUF_ERROR due to too few input bytes,
936
     * then we'll replenish them in the next input_stream->read()
937
     * call when we loop.
938
     */
939
0
  } while (ret == Z_OK || ret == Z_BUF_ERROR);
940
941
0
  if (stream.total_in != in_stream->size + hdrlen)
942
0
    die(_("write stream object %"PRIuMAX" != %"PRIuMAX), (uintmax_t)stream.total_in,
943
0
        (uintmax_t)in_stream->size + hdrlen);
944
945
  /*
946
   * Common steps for write_loose_object and stream_loose_object to
947
   * end writing loose object:
948
   *
949
   *  - End the compression of zlib stream.
950
   *  - Get the calculated oid.
951
   */
952
0
  if (ret != Z_STREAM_END)
953
0
    die(_("unable to stream deflate new object (%d)"), ret);
954
0
  ret = end_loose_object_common(loose, &c, &compat_c, &stream, oid, &compat_oid);
955
0
  if (ret != Z_OK)
956
0
    die(_("deflateEnd on stream object failed (%d)"), ret);
957
0
  close_loose_object(loose, fd, tmp_file.buf);
958
959
0
  if (odb_freshen_object(loose->base.odb, oid)) {
960
0
    unlink_or_warn(tmp_file.buf);
961
0
    goto cleanup;
962
0
  }
963
0
  odb_loose_path(loose, &filename, oid);
964
965
  /* We finally know the object path, and create the missing dir. */
966
0
  dirlen = directory_size(filename.buf);
967
0
  if (dirlen) {
968
0
    struct strbuf dir = STRBUF_INIT;
969
0
    strbuf_add(&dir, filename.buf, dirlen);
970
971
0
    if (safe_create_dir_in_gitdir(loose->base.odb->repo, dir.buf) &&
972
0
        errno != EEXIST) {
973
0
      err = error_errno(_("unable to create directory %s"), dir.buf);
974
0
      strbuf_release(&dir);
975
0
      goto cleanup;
976
0
    }
977
0
    strbuf_release(&dir);
978
0
  }
979
980
0
  err = finalize_object_file_flags(loose->base.odb->repo, tmp_file.buf, filename.buf,
981
0
           FOF_SKIP_COLLISION_CHECK);
982
0
  if (err < 0)
983
0
    goto cleanup;
984
985
0
  loose_cache_mark_seen(loose, oid);
986
987
0
  if (compat)
988
0
    err = repo_add_loose_object_map(loose, oid, &compat_oid);
989
990
0
cleanup:
991
0
  strbuf_release(&tmp_file);
992
0
  strbuf_release(&filename);
993
0
  return err;
994
0
}
995
996
static int odb_source_loose_begin_transaction(struct odb_source *source UNUSED,
997
                struct odb_transaction **out UNUSED,
998
                enum odb_transaction_flags flags UNUSED)
999
0
{
1000
  /* TODO: this is a known omission that we'll want to address eventually. */
1001
0
  return error("loose source does not support transactions");
1002
0
}
1003
1004
static void odb_source_loose_clear_cache(struct odb_source_loose *loose)
1005
0
{
1006
0
  oidtree_clear(loose->cache);
1007
0
  FREE_AND_NULL(loose->cache);
1008
0
  memset(&loose->subdir_seen, 0,
1009
0
         sizeof(loose->subdir_seen));
1010
0
}
1011
1012
static void odb_source_loose_prepare(struct odb_source *source,
1013
             enum odb_prepare_flags flags)
1014
0
{
1015
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
1016
0
  if (flags & ODB_PREPARE_FLUSH_CACHES)
1017
0
    odb_source_loose_clear_cache(loose);
1018
0
}
1019
1020
static void odb_source_loose_close(struct odb_source *source UNUSED)
1021
0
{
1022
  /* Nothing to do. */
1023
0
}
1024
1025
static void odb_source_loose_reparent(const char *old_cwd,
1026
              const char *new_cwd,
1027
              void *cb_data)
1028
0
{
1029
0
  struct odb_source_loose *loose = cb_data;
1030
0
  char *path = reparent_relative_path(old_cwd, new_cwd,
1031
0
              loose->base.path);
1032
0
  free(loose->base.path);
1033
0
  loose->base.path = path;
1034
0
}
1035
1036
static void odb_source_loose_free(struct odb_source *source)
1037
0
{
1038
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
1039
0
  odb_source_loose_clear_cache(loose);
1040
0
  loose_object_map_clear(&loose->map);
1041
0
  chdir_notify_unregister(odb_source_loose_reparent, loose);
1042
0
  odb_source_release(&loose->base);
1043
0
  free(loose);
1044
0
}
1045
1046
struct fsck_loose_data {
1047
  struct odb_source_loose *source;
1048
  struct odb_fsck_options *opts;
1049
  struct progress *progress;
1050
  bool error_found;
1051
};
1052
1053
static int fsck_loose(const struct object_id *oid, const char *path,
1054
          void *cb_data)
1055
0
{
1056
0
  struct fsck_loose_data *data = cb_data;
1057
0
  enum object_type type = OBJ_NONE;
1058
0
  size_t size;
1059
0
  void *contents = NULL;
1060
0
  int eaten = 0;
1061
0
  struct object_info oi = OBJECT_INFO_INIT;
1062
0
  struct object_id real_oid = *null_oid(data->source->base.odb->repo->hash_algo);
1063
0
  int err = 0;
1064
1065
0
  oi.sizep = &size;
1066
0
  oi.typep = &type;
1067
1068
0
  if (read_loose_object(data->source->base.odb->repo,
1069
0
            path, oid, &real_oid, &contents, &oi) < 0) {
1070
0
    if (contents && !oideq(&real_oid, oid))
1071
0
      err = error(_("%s: hash-path mismatch, found at: %s"),
1072
0
            oid_to_hex(&real_oid), path);
1073
0
    else
1074
0
      err = error(_("%s: object corrupt or missing: %s"),
1075
0
            oid_to_hex(oid), path);
1076
0
  }
1077
0
  if (err < 0)
1078
0
    goto out;
1079
1080
0
  if (!contents && type != OBJ_BLOB)
1081
0
    BUG("read_loose_object streamed a non-blob");
1082
1083
0
  if (data->opts->object_cb(oid, type, size, contents, &eaten,
1084
0
          data->opts->object_payload)) {
1085
0
    err = -1;
1086
0
    goto out;
1087
0
  }
1088
1089
0
out:
1090
0
  if (err)
1091
0
    data->error_found = true;
1092
0
  if (!eaten)
1093
0
    free(contents);
1094
0
  return 0; /* keep checking other objects, even if we saw an error */
1095
0
}
1096
1097
static int fsck_cruft(const char *basename, const char *path,
1098
          void *data UNUSED)
1099
0
{
1100
0
  if (!starts_with(basename, "tmp_obj_"))
1101
0
    fprintf_ln(stderr, _("bad sha1 file: %s"), path);
1102
0
  return 0;
1103
0
}
1104
1105
static int fsck_subdir(unsigned int nr, const char *path UNUSED, void *cb_data)
1106
0
{
1107
0
  struct fsck_loose_data *data = cb_data;
1108
0
  display_progress(data->progress, nr + 1);
1109
0
  return 0;
1110
0
}
1111
1112
static int odb_source_loose_fsck(struct odb_source *source,
1113
         struct odb_fsck_options *opts)
1114
0
{
1115
0
  struct odb_source_loose *loose = odb_source_loose_downcast(source);
1116
0
  struct fsck_loose_data data = {
1117
0
    .source = loose,
1118
0
    .opts = opts,
1119
0
  };
1120
1121
0
  if (opts->flags & ODB_FSCK_VERBOSE)
1122
0
    fprintf_ln(stderr, _("Checking object directory"));
1123
1124
0
  if (opts->flags & ODB_FSCK_PROGRESS)
1125
0
    data.progress = start_progress(source->odb->repo,
1126
0
                 _("Checking object directories"), 256);
1127
1128
0
  for_each_loose_file_in_source(source, fsck_loose,
1129
0
              fsck_cruft, fsck_subdir, &data);
1130
0
  display_progress(data.progress, 256);
1131
0
  stop_progress(&data.progress);
1132
1133
0
  return data.error_found ? -1 : 0;
1134
0
}
1135
1136
struct odb_source_loose *odb_source_loose_new(struct object_database *odb,
1137
                const char *path)
1138
0
{
1139
0
  struct odb_source_loose *loose;
1140
1141
0
  CALLOC_ARRAY(loose, 1);
1142
0
  odb_source_init(&loose->base, odb, ODB_SOURCE_LOOSE, path);
1143
1144
0
  loose->base.free = odb_source_loose_free;
1145
0
  loose->base.close = odb_source_loose_close;
1146
0
  loose->base.prepare = odb_source_loose_prepare;
1147
0
  loose->base.fsck = odb_source_loose_fsck;
1148
0
  loose->base.read_object_info = odb_source_loose_read_object_info;
1149
0
  loose->base.read_object_stream = odb_source_loose_read_object_stream;
1150
0
  loose->base.for_each_object = odb_source_loose_for_each_object;
1151
0
  loose->base.find_abbrev_len = odb_source_loose_find_abbrev_len;
1152
0
  loose->base.count_objects = odb_source_loose_count_objects;
1153
0
  loose->base.freshen_object = odb_source_loose_freshen_object;
1154
0
  loose->base.write_object = odb_source_loose_write_object;
1155
0
  loose->base.write_object_stream = odb_source_loose_write_object_stream;
1156
0
  loose->base.begin_transaction = odb_source_loose_begin_transaction;
1157
1158
0
  if (!is_absolute_path(loose->base.path))
1159
0
    chdir_notify_register(odb_source_loose_reparent, loose);
1160
1161
0
  loose_object_map_load(loose);
1162
1163
0
  return loose;
1164
0
}