Coverage Report

Created: 2026-12-01 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/packfile.c
Line
Count
Source
1
#define DISABLE_SIGN_COMPARE_WARNINGS
2
3
#include "git-compat-util.h"
4
#include "environment.h"
5
#include "gettext.h"
6
#include "hex.h"
7
#include "list.h"
8
#include "pack.h"
9
#include "repository.h"
10
#include "dir.h"
11
#include "packfile.h"
12
#include "delta.h"
13
#include "hash-lookup.h"
14
#include "commit.h"
15
#include "object.h"
16
#include "tag.h"
17
#include "trace.h"
18
#include "tree-walk.h"
19
#include "tree.h"
20
#include "object-file.h"
21
#include "odb.h"
22
#include "odb/streaming.h"
23
#include "midx.h"
24
#include "commit-graph.h"
25
#include "pack-revindex.h"
26
#include "promisor-remote.h"
27
#include "pack-mtimes.h"
28
29
char *odb_pack_name(struct repository *r, struct strbuf *buf,
30
        const unsigned char *hash, const char *ext)
31
0
{
32
0
  strbuf_reset(buf);
33
0
  strbuf_addf(buf, "%s/pack/pack-%s.%s", repo_get_object_directory(r),
34
0
        hash_to_hex_algop(hash, r->hash_algo), ext);
35
0
  return buf->buf;
36
0
}
37
38
static unsigned int pack_used_ctr;
39
static unsigned int pack_mmap_calls;
40
static unsigned int peak_pack_open_windows;
41
static unsigned int pack_open_windows;
42
static unsigned int pack_open_fds;
43
static unsigned int pack_max_fds;
44
static size_t peak_pack_mapped;
45
static size_t pack_mapped;
46
47
#define SZ_FMT PRIuMAX
48
0
static inline uintmax_t sz_fmt(size_t s) { return s; }
49
50
void pack_report(struct repository *repo)
51
0
{
52
0
  fprintf(stderr,
53
0
    "pack_report: getpagesize()            = %10" SZ_FMT "\n"
54
0
    "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
55
0
    "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
56
0
    sz_fmt(getpagesize()),
57
0
    sz_fmt(repo->settings.packed_git_window_size),
58
0
    sz_fmt(repo->settings.packed_git_limit));
59
0
  fprintf(stderr,
60
0
    "pack_report: pack_used_ctr            = %10u\n"
61
0
    "pack_report: pack_mmap_calls          = %10u\n"
62
0
    "pack_report: pack_open_windows        = %10u / %10u\n"
63
0
    "pack_report: pack_mapped              = "
64
0
      "%10" SZ_FMT " / %10" SZ_FMT "\n",
65
0
    pack_used_ctr,
66
0
    pack_mmap_calls,
67
0
    pack_open_windows, peak_pack_open_windows,
68
0
    sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
69
0
}
70
71
/*
72
 * Open and mmap the index file at path, perform a couple of
73
 * consistency checks, then record its information to p.  Return 0 on
74
 * success.
75
 */
76
static int check_packed_git_idx(const char *path, struct packed_git *p)
77
0
{
78
0
  void *idx_map;
79
0
  size_t idx_size;
80
0
  int fd = git_open(path), ret;
81
0
  struct stat st;
82
0
  const unsigned int hashsz = p->repo->hash_algo->rawsz;
83
84
0
  if (fd < 0)
85
0
    return -1;
86
0
  if (fstat(fd, &st)) {
87
0
    close(fd);
88
0
    return -1;
89
0
  }
90
0
  idx_size = xsize_t(st.st_size);
91
0
  if (idx_size < 4 * 256 + hashsz + hashsz) {
92
0
    close(fd);
93
0
    return error("index file %s is too small", path);
94
0
  }
95
0
  idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
96
0
  close(fd);
97
98
0
  ret = load_idx(path, hashsz, idx_map, idx_size, p);
99
100
0
  if (ret)
101
0
    munmap(idx_map, idx_size);
102
103
0
  return ret;
104
0
}
105
106
int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
107
       size_t idx_size, struct packed_git *p)
108
305
{
109
305
  struct pack_idx_header *hdr = idx_map;
110
305
  uint32_t version, nr, i, *index;
111
112
305
  if (idx_size < 4 * 256 + hashsz + hashsz)
113
11
    return error("index file %s is too small", path);
114
294
  if (!idx_map)
115
0
    return error("empty data");
116
117
294
  if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
118
172
    version = ntohl(hdr->idx_version);
119
172
    if (version < 2 || version > 2)
120
63
      return error("index file %s is version %"PRIu32
121
172
             " and is not supported by this binary"
122
172
             " (try upgrading GIT to a newer version)",
123
172
             path, version);
124
172
  } else
125
122
    version = 1;
126
127
231
  nr = 0;
128
231
  index = idx_map;
129
231
  if (version > 1)
130
109
    index += 2;  /* skip index header */
131
44.2k
  for (i = 0; i < 256; i++) {
132
44.1k
    uint32_t n = ntohl(index[i]);
133
44.1k
    if (n < nr)
134
61
      return error("non-monotonic index %s", path);
135
44.0k
    nr = n;
136
44.0k
  }
137
138
170
  if (version == 1) {
139
    /*
140
     * Total size:
141
     *  - 256 index entries 4 bytes each
142
     *  - 24-byte entries * nr (object ID + 4-byte offset)
143
     *  - hash of the packfile
144
     *  - file checksum
145
     */
146
63
    if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
147
62
      return error("wrong index v1 file size in %s", path);
148
107
  } else if (version == 2) {
149
    /*
150
     * Minimum size:
151
     *  - 8 bytes of header
152
     *  - 256 index entries 4 bytes each
153
     *  - object ID entry * nr
154
     *  - 4-byte crc entry * nr
155
     *  - 4-byte offset entry * nr
156
     *  - hash of the packfile
157
     *  - file checksum
158
     * And after the 4-byte offset table might be a
159
     * variable sized table containing 8-byte entries
160
     * for offsets larger than 2^31.
161
     */
162
107
    size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
163
107
    size_t max_size = min_size;
164
107
    if (nr)
165
75
      max_size = st_add(max_size, st_mult(nr - 1, 8));
166
107
    if (idx_size < min_size || idx_size > max_size)
167
92
      return error("wrong index v2 file size in %s", path);
168
15
    if (idx_size != min_size &&
169
        /*
170
         * make sure we can deal with large pack offsets.
171
         * 31-bit signed offset won't be enough, neither
172
         * 32-bit unsigned one will be.
173
         */
174
13
        (sizeof(off_t) <= 4))
175
0
      return error("pack too large for current definition of off_t in %s", path);
176
15
    p->crc_offset = st_add(8 + 4 * 256, st_mult(nr, hashsz));
177
15
  }
178
179
16
  p->index_version = version;
180
16
  p->index_data = idx_map;
181
16
  p->index_size = idx_size;
182
16
  p->num_objects = nr;
183
16
  return 0;
184
170
}
185
186
int open_pack_index(struct packed_git *p)
187
0
{
188
0
  char *idx_name;
189
0
  size_t len;
190
0
  int ret;
191
192
0
  if (p->index_data)
193
0
    return 0;
194
195
0
  if (!strip_suffix(p->pack_name, ".pack", &len))
196
0
    BUG("pack_name does not end in .pack");
197
0
  idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
198
0
  ret = check_packed_git_idx(idx_name, p);
199
0
  free(idx_name);
200
0
  return ret;
201
0
}
202
203
uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
204
0
{
205
0
  const uint32_t *level1_ofs = p->index_data;
206
207
0
  if (!level1_ofs) {
208
0
    if (open_pack_index(p))
209
0
      return 0;
210
0
    level1_ofs = p->index_data;
211
0
  }
212
213
0
  if (p->index_version > 1) {
214
0
    level1_ofs += 2;
215
0
  }
216
217
0
  return ntohl(level1_ofs[value]);
218
0
}
219
220
static struct packed_git *alloc_packed_git(struct repository *r, int extra)
221
0
{
222
0
  struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
223
0
  memset(p, 0, sizeof(*p));
224
0
  p->pack_fd = -1;
225
0
  p->repo = r;
226
0
  return p;
227
0
}
228
229
static char *pack_path_from_idx(const char *idx_path)
230
0
{
231
0
  size_t len;
232
0
  if (!strip_suffix(idx_path, ".idx", &len))
233
0
    BUG("idx path does not end in .idx: %s", idx_path);
234
0
  return xstrfmt("%.*s.pack", (int)len, idx_path);
235
0
}
236
237
struct packed_git *parse_pack_index(struct repository *r, unsigned char *sha1,
238
            const char *idx_path)
239
0
{
240
0
  char *path = pack_path_from_idx(idx_path);
241
0
  size_t alloc = st_add(strlen(path), 1);
242
0
  struct packed_git *p = alloc_packed_git(r, alloc);
243
244
0
  memcpy(p->pack_name, path, alloc); /* includes NUL */
245
0
  free(path);
246
0
  hashcpy(p->hash, sha1, p->repo->hash_algo);
247
0
  if (check_packed_git_idx(idx_path, p)) {
248
0
    free(p);
249
0
    return NULL;
250
0
  }
251
252
0
  return p;
253
0
}
254
255
static void scan_windows(struct packed_git *p,
256
  struct packed_git **lru_p,
257
  struct pack_window **lru_w,
258
  struct pack_window **lru_l)
259
0
{
260
0
  struct pack_window *w, *w_l;
261
262
0
  for (w_l = NULL, w = p->windows; w; w = w->next) {
263
0
    if (!w->inuse_cnt) {
264
0
      if (!*lru_w || w->last_used < (*lru_w)->last_used) {
265
0
        *lru_p = p;
266
0
        *lru_w = w;
267
0
        *lru_l = w_l;
268
0
      }
269
0
    }
270
0
    w_l = w;
271
0
  }
272
0
}
273
274
static int unuse_one_window(struct object_database *odb)
275
0
{
276
0
  struct odb_source_files *files = odb_source_files_downcast(odb->source);
277
0
  struct packfile_list_entry *e;
278
0
  struct packed_git *lru_p = NULL;
279
0
  struct pack_window *lru_w = NULL, *lru_l = NULL;
280
281
0
  for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
282
0
    for (e = dir->packed->packs.head; e; e = e->next)
283
0
      scan_windows(e->pack, &lru_p, &lru_w, &lru_l);
284
0
  }
285
286
0
  if (lru_p) {
287
0
    munmap(lru_w->base, lru_w->len);
288
0
    pack_mapped -= lru_w->len;
289
0
    if (lru_l)
290
0
      lru_l->next = lru_w->next;
291
0
    else
292
0
      lru_p->windows = lru_w->next;
293
0
    free(lru_w);
294
0
    pack_open_windows--;
295
0
    return 1;
296
0
  }
297
0
  return 0;
298
0
}
299
300
void close_pack_windows(struct packed_git *p)
301
0
{
302
0
  while (p->windows) {
303
0
    struct pack_window *w = p->windows;
304
305
0
    if (w->inuse_cnt)
306
0
      die("pack '%s' still has open windows to it",
307
0
          p->pack_name);
308
0
    munmap(w->base, w->len);
309
0
    pack_mapped -= w->len;
310
0
    pack_open_windows--;
311
0
    p->windows = w->next;
312
0
    free(w);
313
0
  }
314
0
}
315
316
int close_pack_fd(struct packed_git *p)
317
0
{
318
0
  if (p->pack_fd < 0)
319
0
    return 0;
320
321
0
  close(p->pack_fd);
322
0
  pack_open_fds--;
323
0
  p->pack_fd = -1;
324
325
0
  return 1;
326
0
}
327
328
void close_pack_index(struct packed_git *p)
329
0
{
330
0
  if (p->index_data) {
331
0
    munmap((void *)p->index_data, p->index_size);
332
0
    p->index_data = NULL;
333
0
  }
334
0
}
335
336
static void close_pack_revindex(struct packed_git *p)
337
0
{
338
0
  FREE_AND_NULL(p->revindex);
339
340
0
  if (!p->revindex_map)
341
0
    return;
342
343
0
  munmap((void *)p->revindex_map, p->revindex_size);
344
0
  p->revindex_map = NULL;
345
0
  p->revindex_data = NULL;
346
0
}
347
348
static void close_pack_mtimes(struct packed_git *p)
349
0
{
350
0
  if (!p->mtimes_map)
351
0
    return;
352
353
0
  munmap((void *)p->mtimes_map, p->mtimes_size);
354
0
  p->mtimes_map = NULL;
355
0
}
356
357
void unlink_pack_path(const char *pack_name, int force_delete)
358
0
{
359
0
  static const char *exts[] = {".idx", ".pack", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
360
0
  int i;
361
0
  struct strbuf buf = STRBUF_INIT;
362
0
  size_t plen;
363
364
0
  strbuf_addstr(&buf, pack_name);
365
0
  strip_suffix_mem(buf.buf, &buf.len, ".pack");
366
0
  plen = buf.len;
367
368
0
  if (!force_delete) {
369
0
    strbuf_addstr(&buf, ".keep");
370
0
    if (!access(buf.buf, F_OK)) {
371
0
      strbuf_release(&buf);
372
0
      return;
373
0
    }
374
0
  }
375
376
0
  for (i = 0; i < ARRAY_SIZE(exts); i++) {
377
0
    strbuf_setlen(&buf, plen);
378
0
    strbuf_addstr(&buf, exts[i]);
379
0
    unlink(buf.buf);
380
0
  }
381
382
0
  strbuf_release(&buf);
383
0
}
384
385
/*
386
 * The LRU pack is the one with the oldest MRU window, preferring packs
387
 * with no used windows, or the oldest mtime if it has no windows allocated.
388
 */
389
static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
390
0
{
391
0
  struct pack_window *w, *this_mru_w;
392
0
  int has_windows_inuse = 0;
393
394
  /*
395
   * Reject this pack if it has windows and the previously selected
396
   * one does not.  If this pack does not have windows, reject
397
   * it if the pack file is newer than the previously selected one.
398
   */
399
0
  if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
400
0
    return;
401
402
0
  for (w = this_mru_w = p->windows; w; w = w->next) {
403
    /*
404
     * Reject this pack if any of its windows are in use,
405
     * but the previously selected pack did not have any
406
     * inuse windows.  Otherwise, record that this pack
407
     * has windows in use.
408
     */
409
0
    if (w->inuse_cnt) {
410
0
      if (*accept_windows_inuse)
411
0
        has_windows_inuse = 1;
412
0
      else
413
0
        return;
414
0
    }
415
416
0
    if (w->last_used > this_mru_w->last_used)
417
0
      this_mru_w = w;
418
419
    /*
420
     * Reject this pack if it has windows that have been
421
     * used more recently than the previously selected pack.
422
     * If the previously selected pack had windows inuse and
423
     * we have not encountered a window in this pack that is
424
     * inuse, skip this check since we prefer a pack with no
425
     * inuse windows to one that has inuse windows.
426
     */
427
0
    if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
428
0
        this_mru_w->last_used > (*mru_w)->last_used)
429
0
      return;
430
0
  }
431
432
  /*
433
   * Select this pack.
434
   */
435
0
  *mru_w = this_mru_w;
436
0
  *lru_p = p;
437
0
  *accept_windows_inuse = has_windows_inuse;
438
0
}
439
440
static int close_one_pack(struct repository *r)
441
0
{
442
0
  struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
443
0
  struct packfile_list_entry *e;
444
0
  struct packed_git *lru_p = NULL;
445
0
  struct pack_window *mru_w = NULL;
446
0
  int accept_windows_inuse = 1;
447
448
0
  for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
449
0
    for (e = dir->packed->packs.head; e; e = e->next) {
450
0
      if (e->pack->pack_fd == -1)
451
0
        continue;
452
0
      find_lru_pack(e->pack, &lru_p, &mru_w, &accept_windows_inuse);
453
0
    }
454
0
  }
455
456
0
  if (lru_p)
457
0
    return close_pack_fd(lru_p);
458
459
0
  return 0;
460
0
}
461
462
static unsigned int get_max_fd_limit(void)
463
0
{
464
0
#ifdef RLIMIT_NOFILE
465
0
  {
466
0
    struct rlimit lim;
467
468
0
    if (!getrlimit(RLIMIT_NOFILE, &lim))
469
0
      return lim.rlim_cur;
470
0
  }
471
0
#endif
472
473
0
#ifdef _SC_OPEN_MAX
474
0
  {
475
0
    long open_max = sysconf(_SC_OPEN_MAX);
476
0
    if (0 < open_max)
477
0
      return open_max;
478
    /*
479
     * Otherwise, we got -1 for one of the two
480
     * reasons:
481
     *
482
     * (1) sysconf() did not understand _SC_OPEN_MAX
483
     *     and signaled an error with -1; or
484
     * (2) sysconf() said there is no limit.
485
     *
486
     * We _could_ clear errno before calling sysconf() to
487
     * tell these two cases apart and return a huge number
488
     * in the latter case to let the caller cap it to a
489
     * value that is not so selfish, but letting the
490
     * fallback OPEN_MAX codepath take care of these cases
491
     * is a lot simpler.
492
     */
493
0
  }
494
0
#endif
495
496
#ifdef OPEN_MAX
497
  return OPEN_MAX;
498
#else
499
0
  return 1; /* see the caller ;-) */
500
0
#endif
501
0
}
502
503
const char *pack_basename(struct packed_git *p)
504
0
{
505
0
  const char *ret = strrchr(p->pack_name, '/');
506
0
  if (ret)
507
0
    ret = ret + 1; /* skip past slash */
508
0
  else
509
0
    ret = p->pack_name; /* we only have a base */
510
0
  return ret;
511
0
}
512
513
/*
514
 * Do not call this directly as this leaks p->pack_fd on error return;
515
 * call open_packed_git() instead.
516
 */
517
static int open_packed_git_1(struct packed_git *p)
518
0
{
519
0
  struct stat st;
520
0
  struct pack_header hdr;
521
0
  unsigned char hash[GIT_MAX_RAWSZ];
522
0
  unsigned char *idx_hash;
523
0
  ssize_t read_result;
524
0
  const unsigned hashsz = p->repo->hash_algo->rawsz;
525
526
0
  if (open_pack_index(p))
527
0
    return error("packfile %s index unavailable", p->pack_name);
528
529
0
  if (!pack_max_fds) {
530
0
    unsigned int max_fds = get_max_fd_limit();
531
532
    /* Save 3 for stdin/stdout/stderr, 22 for work */
533
0
    if (25 < max_fds)
534
0
      pack_max_fds = max_fds - 25;
535
0
    else
536
0
      pack_max_fds = 1;
537
0
  }
538
539
0
  while (pack_max_fds <= pack_open_fds && close_one_pack(p->repo))
540
0
    ; /* nothing */
541
542
0
  p->pack_fd = git_open(p->pack_name);
543
0
  if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
544
0
    return -1;
545
0
  pack_open_fds++;
546
547
  /* If we created the struct before we had the pack we lack size. */
548
0
  if (!p->pack_size) {
549
0
    if (!S_ISREG(st.st_mode))
550
0
      return error("packfile %s not a regular file", p->pack_name);
551
0
    p->pack_size = st.st_size;
552
0
  } else if (p->pack_size != st.st_size)
553
0
    return error("packfile %s size changed", p->pack_name);
554
555
  /* Verify we recognize this pack file format. */
556
0
  read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
557
0
  if (read_result < 0)
558
0
    return error_errno("error reading from %s", p->pack_name);
559
0
  if (read_result != sizeof(hdr))
560
0
    return error("file %s is far too short to be a packfile", p->pack_name);
561
0
  if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
562
0
    return error("file %s is not a GIT packfile", p->pack_name);
563
0
  if (!pack_version_ok(hdr.hdr_version))
564
0
    return error("packfile %s is version %"PRIu32" and not"
565
0
      " supported (try upgrading GIT to a newer version)",
566
0
      p->pack_name, ntohl(hdr.hdr_version));
567
568
  /* Verify the pack matches its index. */
569
0
  if (p->num_objects != ntohl(hdr.hdr_entries))
570
0
    return error("packfile %s claims to have %"PRIu32" objects"
571
0
           " while index indicates %"PRIu32" objects",
572
0
           p->pack_name, ntohl(hdr.hdr_entries),
573
0
           p->num_objects);
574
0
  read_result = pread_in_full(p->pack_fd, hash, hashsz,
575
0
          p->pack_size - hashsz);
576
0
  if (read_result < 0)
577
0
    return error_errno("error reading from %s", p->pack_name);
578
0
  if (read_result != hashsz)
579
0
    return error("packfile %s signature is unavailable", p->pack_name);
580
0
  idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
581
0
  if (!hasheq(hash, idx_hash, p->repo->hash_algo))
582
0
    return error("packfile %s does not match index", p->pack_name);
583
0
  return 0;
584
0
}
585
586
static int open_packed_git(struct packed_git *p)
587
0
{
588
0
  if (!open_packed_git_1(p))
589
0
    return 0;
590
0
  close_pack_fd(p);
591
0
  return -1;
592
0
}
593
594
static int in_window(struct repository *r, struct pack_window *win,
595
         off_t offset)
596
0
{
597
  /* We must promise at least one full hash after the
598
   * offset is available from this window, otherwise the offset
599
   * is not actually in this window and a different window (which
600
   * has that one hash excess) must be used.  This is to support
601
   * the object header and delta base parsing routines below.
602
   */
603
0
  off_t win_off = win->offset;
604
0
  return win_off <= offset
605
0
    && (offset + r->hash_algo->rawsz) <= (win_off + win->len);
606
0
}
607
608
unsigned char *use_pack(struct packed_git *p,
609
    struct pack_window **w_cursor,
610
    off_t offset,
611
    size_t *left)
612
0
{
613
0
  struct pack_window *win = *w_cursor;
614
615
  /* Since packfiles end in a hash of their content and it's
616
   * pointless to ask for an offset into the middle of that
617
   * hash, and the in_window function above wouldn't match
618
   * don't allow an offset too close to the end of the file.
619
   */
620
0
  if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
621
0
    die("packfile %s cannot be accessed", p->pack_name);
622
0
  if (offset > (p->pack_size - p->repo->hash_algo->rawsz))
623
0
    die("offset beyond end of packfile (truncated pack?)");
624
0
  if (offset < 0)
625
0
    die(_("offset before end of packfile (broken .idx?)"));
626
627
0
  if (!win || !in_window(p->repo, win, offset)) {
628
0
    if (win)
629
0
      win->inuse_cnt--;
630
0
    for (win = p->windows; win; win = win->next) {
631
0
      if (in_window(p->repo, win, offset))
632
0
        break;
633
0
    }
634
0
    if (!win) {
635
0
      size_t window_align;
636
0
      off_t len;
637
0
      struct repo_settings *settings;
638
639
      /* lazy load the settings in case it hasn't been setup */
640
0
      prepare_repo_settings(p->repo);
641
0
      settings = &p->repo->settings;
642
643
0
      window_align = settings->packed_git_window_size / 2;
644
645
0
      if (p->pack_fd == -1 && open_packed_git(p))
646
0
        die("packfile %s cannot be accessed", p->pack_name);
647
648
0
      CALLOC_ARRAY(win, 1);
649
0
      win->offset = (offset / window_align) * window_align;
650
0
      len = p->pack_size - win->offset;
651
0
      if (len > settings->packed_git_window_size)
652
0
        len = settings->packed_git_window_size;
653
0
      win->len = (size_t)len;
654
0
      pack_mapped += win->len;
655
656
0
      while (settings->packed_git_limit < pack_mapped &&
657
0
             unuse_one_window(p->repo->objects))
658
0
        ; /* nothing */
659
0
      win->base = xmmap_gently(NULL, win->len,
660
0
        PROT_READ, MAP_PRIVATE,
661
0
        p->pack_fd, win->offset);
662
0
      if (win->base == MAP_FAILED)
663
0
        die_errno(_("packfile %s cannot be mapped%s"),
664
0
            p->pack_name, mmap_os_err());
665
0
      if (!win->offset && win->len == p->pack_size
666
0
        && !p->do_not_close)
667
0
        close_pack_fd(p);
668
0
      pack_mmap_calls++;
669
0
      pack_open_windows++;
670
0
      if (pack_mapped > peak_pack_mapped)
671
0
        peak_pack_mapped = pack_mapped;
672
0
      if (pack_open_windows > peak_pack_open_windows)
673
0
        peak_pack_open_windows = pack_open_windows;
674
0
      win->next = p->windows;
675
0
      p->windows = win;
676
0
    }
677
0
  }
678
0
  if (win != *w_cursor) {
679
0
    win->last_used = pack_used_ctr++;
680
0
    win->inuse_cnt++;
681
0
    *w_cursor = win;
682
0
  }
683
0
  offset -= win->offset;
684
0
  if (left)
685
0
    *left = win->len - xsize_t(offset);
686
0
  return win->base + offset;
687
0
}
688
689
void unuse_pack(struct pack_window **w_cursor)
690
0
{
691
0
  struct pack_window *w = *w_cursor;
692
0
  if (w) {
693
0
    w->inuse_cnt--;
694
0
    *w_cursor = NULL;
695
0
  }
696
0
}
697
698
struct packed_git *add_packed_git(struct repository *r, const char *path,
699
          size_t path_len, int local)
700
0
{
701
0
  struct stat st;
702
0
  size_t alloc;
703
0
  struct packed_git *p;
704
0
  struct object_id oid;
705
706
  /*
707
   * Make sure a corresponding .pack file exists and that
708
   * the index looks sane.
709
   */
710
0
  if (!strip_suffix_mem(path, &path_len, ".idx"))
711
0
    return NULL;
712
713
  /*
714
   * ".promisor" is long enough to hold any suffix we're adding (and
715
   * the use xsnprintf double-checks that)
716
   */
717
0
  alloc = st_add3(path_len, strlen(".promisor"), 1);
718
0
  p = alloc_packed_git(r, alloc);
719
0
  memcpy(p->pack_name, path, path_len);
720
721
  /*
722
   * Note that we have to check auxiliary data structures before we check
723
   * for the ".pack" file to exist to avoid races with a packfile that is
724
   * in the process of being deleted. The ".pack" file is unlinked before
725
   * its auxiliary data structures, so we know that we either get a
726
   * consistent snapshot of all data structures or that we'll fail to
727
   * stat(3p) the packfile itself and thus return `NULL`.
728
   *
729
   * As such, we cannot bail out before the access(3p) calls in case the
730
   * packfile doesn't exist without doing two stat(3p) calls for it.
731
   */
732
0
  xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
733
0
  if (!access(p->pack_name, F_OK))
734
0
    p->pack_keep = 1;
735
736
0
  xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
737
0
  if (!access(p->pack_name, F_OK))
738
0
    p->pack_promisor = 1;
739
740
0
  xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
741
0
  if (!access(p->pack_name, F_OK))
742
0
    p->is_cruft = 1;
743
744
0
  xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
745
0
  if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
746
0
    free(p);
747
0
    return NULL;
748
0
  }
749
750
  /* ok, it looks sane as far as we can check without
751
   * actually mapping the pack file.
752
   */
753
0
  p->pack_size = st.st_size;
754
0
  p->pack_local = local;
755
0
  p->mtime = st.st_mtime;
756
0
  if (path_len < r->hash_algo->hexsz ||
757
0
      get_oid_hex_algop(path + path_len - r->hash_algo->hexsz, &oid,
758
0
            r->hash_algo))
759
0
    hashclr(p->hash, r->hash_algo);
760
0
  else
761
0
    hashcpy(p->hash, oid.hash, r->hash_algo);
762
763
0
  return p;
764
0
}
765
766
void packfile_store_add_pack(struct odb_source_packed *store,
767
           struct packed_git *pack)
768
0
{
769
0
  if (pack->pack_fd != -1)
770
0
    pack_open_fds++;
771
772
0
  packfile_list_append(&store->packs, pack, 1);
773
0
  strmap_put(&store->packs_by_path, pack->pack_name, pack);
774
0
}
775
776
struct packed_git *packfile_store_load_pack(struct odb_source_packed *store,
777
              const char *idx_path, int local)
778
0
{
779
0
  struct strbuf key = STRBUF_INIT;
780
0
  struct packed_git *p;
781
782
  /*
783
   * We're being called with the path to the index file, but `pack_map`
784
   * holds the path to the packfile itself.
785
   */
786
0
  strbuf_addstr(&key, idx_path);
787
0
  strbuf_strip_suffix(&key, ".idx");
788
0
  strbuf_addstr(&key, ".pack");
789
790
0
  p = strmap_get(&store->packs_by_path, key.buf);
791
0
  if (!p) {
792
0
    p = add_packed_git(store->base.odb->repo, idx_path,
793
0
           strlen(idx_path), local);
794
0
    if (p)
795
0
      packfile_store_add_pack(store, p);
796
0
  }
797
798
0
  strbuf_release(&key);
799
0
  return p;
800
0
}
801
802
void for_each_file_in_pack_subdir(const char *objdir,
803
          const char *subdir,
804
          each_file_in_pack_dir_fn fn,
805
          void *data)
806
0
{
807
0
  struct strbuf path = STRBUF_INIT;
808
0
  size_t dirnamelen;
809
0
  DIR *dir;
810
0
  struct dirent *de;
811
812
0
  strbuf_addstr(&path, objdir);
813
0
  strbuf_addstr(&path, "/pack");
814
0
  if (subdir)
815
0
    strbuf_addf(&path, "/%s", subdir);
816
0
  dir = opendir(path.buf);
817
0
  if (!dir) {
818
0
    if (errno != ENOENT)
819
0
      error_errno("unable to open object pack directory: %s",
820
0
            path.buf);
821
0
    strbuf_release(&path);
822
0
    return;
823
0
  }
824
0
  strbuf_addch(&path, '/');
825
0
  dirnamelen = path.len;
826
0
  while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
827
0
    strbuf_setlen(&path, dirnamelen);
828
0
    strbuf_addstr(&path, de->d_name);
829
830
0
    fn(path.buf, path.len, de->d_name, data);
831
0
  }
832
833
0
  closedir(dir);
834
0
  strbuf_release(&path);
835
0
}
836
837
void for_each_file_in_pack_dir(const char *objdir,
838
             each_file_in_pack_dir_fn fn,
839
             void *data)
840
0
{
841
0
  for_each_file_in_pack_subdir(objdir, NULL, fn, data);
842
0
}
843
844
struct packfile_list_entry *packfile_store_get_packs(struct odb_source_packed *store)
845
0
{
846
0
  odb_source_prepare(&store->base, 0);
847
848
0
  if (store->midx) {
849
0
    struct multi_pack_index *m = store->midx;
850
0
    for (uint32_t i = 0; i < m->num_packs + m->num_packs_in_base; i++)
851
0
      prepare_midx_pack(m, i);
852
0
  }
853
854
0
  return store->packs.head;
855
0
}
856
857
size_t unpack_object_header_buffer(const unsigned char *buf, size_t len,
858
           enum object_type *type, size_t *sizep)
859
89
{
860
89
  unsigned shift;
861
89
  size_t size, c, used = 0;
862
863
89
  c = buf[used++];
864
89
  *type = (c >> 4) & 7;
865
89
  size = c & 15;
866
89
  shift = 4;
867
491
  while (c & 0x80) {
868
    /*
869
     * Each continuation byte adds 7 bits. Ensure shift won't
870
     * overflow size_t (use size_t not long for 64-bit on Windows).
871
     */
872
471
    if (len <= used || (bitsizeof(size_t) - 7) < shift) {
873
69
      error("bad object header");
874
69
      size = used = 0;
875
69
      break;
876
69
    }
877
402
    c = buf[used++];
878
402
    size = st_add(size, st_left_shift(c & 0x7f, shift));
879
402
    shift += 7;
880
402
  }
881
89
  *sizep = size;
882
89
  return used;
883
89
}
884
885
/*
886
 * Read a delta object's header at curpos in p (already inflated as needed)
887
 * and return the size of the result object (the post-application target).
888
 */
889
size_t get_size_from_delta(struct packed_git *p,
890
         struct pack_window **w_curs,
891
         off_t curpos)
892
0
{
893
0
  const unsigned char *data;
894
0
  unsigned char delta_head[20], *in;
895
0
  git_zstream stream;
896
0
  int st;
897
898
0
  memset(&stream, 0, sizeof(stream));
899
0
  stream.next_out = delta_head;
900
0
  stream.avail_out = sizeof(delta_head);
901
902
0
  git_inflate_init(&stream);
903
0
  do {
904
0
    in = use_pack(p, w_curs, curpos, &stream.avail_in);
905
0
    stream.next_in = in;
906
    /*
907
     * Note: the window section returned by use_pack() must be
908
     * available throughout git_inflate()'s unlocked execution. To
909
     * ensure no other thread will modify the window in the
910
     * meantime, we rely on the packed_window.inuse_cnt. This
911
     * counter is incremented before window reading and checked
912
     * before window disposal.
913
     *
914
     * Other worrying sections could be the call to close_pack_fd(),
915
     * which can close packs even with in-use windows, and to
916
     * odb_reprepare(). Regarding the former, mmap doc says:
917
     * "closing the file descriptor does not unmap the region". And
918
     * for the latter, it won't re-open already available packs.
919
     */
920
0
    obj_read_unlock();
921
0
    st = git_inflate(&stream, Z_FINISH);
922
0
    obj_read_lock();
923
0
    curpos += stream.next_in - in;
924
0
  } while ((st == Z_OK || st == Z_BUF_ERROR) &&
925
0
     stream.total_out < sizeof(delta_head));
926
0
  git_inflate_end(&stream);
927
0
  if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
928
0
    error("delta data unpack-initial failed");
929
0
    return 0;
930
0
  }
931
932
  /* Examine the initial part of the delta to figure out
933
   * the result size.
934
   */
935
0
  data = delta_head;
936
937
  /* ignore base size */
938
0
  get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
939
940
  /* Read the result size */
941
0
  return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
942
0
}
943
944
int unpack_object_header(struct packed_git *p,
945
       struct pack_window **w_curs,
946
       off_t *curpos,
947
       size_t *sizep)
948
0
{
949
0
  unsigned char *base;
950
0
  size_t left, used;
951
0
  enum object_type type;
952
953
  /* use_pack() assures us we have [base, base + 20) available
954
   * as a range that we can look at.  (Its actually the hash
955
   * size that is assured.)  With our object header encoding
956
   * the maximum deflated object size is 2^137, which is just
957
   * insane, so we know won't exceed what we have been given.
958
   */
959
0
  base = use_pack(p, w_curs, *curpos, &left);
960
0
  used = unpack_object_header_buffer(base, left, &type, sizep);
961
0
  if (!used) {
962
0
    type = OBJ_BAD;
963
0
  } else
964
0
    *curpos += used;
965
966
0
  return type;
967
0
}
968
969
void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
970
0
{
971
0
  oidset_insert(&p->bad_objects, oid);
972
0
}
973
974
off_t get_delta_base(struct packed_git *p,
975
         struct pack_window **w_curs,
976
         off_t *curpos,
977
         enum object_type type,
978
         off_t delta_obj_offset)
979
0
{
980
0
  unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
981
0
  off_t base_offset;
982
983
  /* use_pack() assured us we have [base_info, base_info + 20)
984
   * as a range that we can look at without walking off the
985
   * end of the mapped window.  Its actually the hash size
986
   * that is assured.  An OFS_DELTA longer than the hash size
987
   * is stupid, as then a REF_DELTA would be smaller to store.
988
   */
989
0
  if (type == OBJ_OFS_DELTA) {
990
0
    unsigned used = 0;
991
0
    unsigned char c = base_info[used++];
992
0
    base_offset = c & 127;
993
0
    while (c & 128) {
994
0
      base_offset += 1;
995
0
      if (!base_offset || MSB(base_offset, 7))
996
0
        return 0;  /* overflow */
997
0
      c = base_info[used++];
998
0
      base_offset = (base_offset << 7) + (c & 127);
999
0
    }
1000
0
    base_offset = delta_obj_offset - base_offset;
1001
0
    if (base_offset <= 0 || base_offset >= delta_obj_offset)
1002
0
      return 0;  /* out of bound */
1003
0
    *curpos += used;
1004
0
  } else if (type == OBJ_REF_DELTA) {
1005
    /* The base entry _must_ be in the same pack */
1006
0
    struct object_id oid;
1007
0
    oidread(&oid, base_info, p->repo->hash_algo);
1008
0
    base_offset = find_pack_entry_one(&oid, p);
1009
0
    *curpos += p->repo->hash_algo->rawsz;
1010
0
  } else
1011
0
    die("I am totally screwed");
1012
0
  return base_offset;
1013
0
}
1014
1015
/*
1016
 * Like get_delta_base above, but we return the sha1 instead of the pack
1017
 * offset. This means it is cheaper for REF deltas (we do not have to do
1018
 * the final object lookup), but more expensive for OFS deltas (we
1019
 * have to load the revidx to convert the offset back into a sha1).
1020
 */
1021
static int get_delta_base_oid(struct packed_git *p,
1022
            struct pack_window **w_curs,
1023
            off_t curpos,
1024
            struct object_id *oid,
1025
            enum object_type type,
1026
            off_t delta_obj_offset)
1027
0
{
1028
0
  if (type == OBJ_REF_DELTA) {
1029
0
    unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1030
0
    oidread(oid, base, p->repo->hash_algo);
1031
0
    return 0;
1032
0
  } else if (type == OBJ_OFS_DELTA) {
1033
0
    uint32_t base_pos;
1034
0
    off_t base_offset = get_delta_base(p, w_curs, &curpos,
1035
0
               type, delta_obj_offset);
1036
1037
0
    if (!base_offset)
1038
0
      return -1;
1039
1040
0
    if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1041
0
      return -1;
1042
1043
0
    return nth_packed_object_id(oid, p,
1044
0
              pack_pos_to_index(p, base_pos));
1045
0
  } else
1046
0
    return -1;
1047
0
}
1048
1049
static int retry_bad_packed_offset(struct repository *r,
1050
           struct packed_git *p,
1051
           off_t obj_offset)
1052
0
{
1053
0
  int type;
1054
0
  uint32_t pos;
1055
0
  struct object_id oid;
1056
0
  if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1057
0
    return OBJ_BAD;
1058
0
  nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1059
0
  mark_bad_packed_object(p, &oid);
1060
0
  type = odb_read_object_info(r->objects, &oid, NULL);
1061
0
  if (type <= OBJ_NONE)
1062
0
    return OBJ_BAD;
1063
0
  return type;
1064
0
}
1065
1066
0
#define POI_STACK_PREALLOC 64
1067
1068
static enum object_type packed_to_object_type(struct repository *r,
1069
                struct packed_git *p,
1070
                off_t obj_offset,
1071
                enum object_type type,
1072
                struct pack_window **w_curs,
1073
                off_t curpos)
1074
0
{
1075
0
  off_t small_poi_stack[POI_STACK_PREALLOC];
1076
0
  off_t *poi_stack = small_poi_stack;
1077
0
  int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1078
1079
0
  while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1080
0
    off_t base_offset;
1081
0
    size_t size;
1082
    /* Push the object we're going to leave behind */
1083
0
    if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1084
0
      poi_stack_alloc = alloc_nr(poi_stack_nr);
1085
0
      ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1086
0
      COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1087
0
    } else {
1088
0
      ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1089
0
    }
1090
0
    poi_stack[poi_stack_nr++] = obj_offset;
1091
    /* If parsing the base offset fails, just unwind */
1092
0
    base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1093
0
    if (!base_offset)
1094
0
      goto unwind;
1095
0
    curpos = obj_offset = base_offset;
1096
0
    type = unpack_object_header(p, w_curs, &curpos, &size);
1097
0
    if (type <= OBJ_NONE) {
1098
      /* If getting the base itself fails, we first
1099
       * retry the base, otherwise unwind */
1100
0
      type = retry_bad_packed_offset(r, p, base_offset);
1101
0
      if (type > OBJ_NONE)
1102
0
        goto out;
1103
0
      goto unwind;
1104
0
    }
1105
0
  }
1106
1107
0
  switch (type) {
1108
0
  case OBJ_BAD:
1109
0
  case OBJ_COMMIT:
1110
0
  case OBJ_TREE:
1111
0
  case OBJ_BLOB:
1112
0
  case OBJ_TAG:
1113
0
    break;
1114
0
  default:
1115
0
    error("unknown object type %i at offset %"PRIuMAX" in %s",
1116
0
          type, (uintmax_t)obj_offset, p->pack_name);
1117
0
    type = OBJ_BAD;
1118
0
  }
1119
1120
0
out:
1121
0
  if (poi_stack != small_poi_stack)
1122
0
    free(poi_stack);
1123
0
  return type;
1124
1125
0
unwind:
1126
0
  while (poi_stack_nr) {
1127
0
    obj_offset = poi_stack[--poi_stack_nr];
1128
0
    type = retry_bad_packed_offset(r, p, obj_offset);
1129
0
    if (type > OBJ_NONE)
1130
0
      goto out;
1131
0
  }
1132
0
  type = OBJ_BAD;
1133
0
  goto out;
1134
0
}
1135
1136
static struct hashmap delta_base_cache;
1137
static size_t delta_base_cached;
1138
1139
static LIST_HEAD(delta_base_cache_lru);
1140
1141
struct delta_base_cache_key {
1142
  struct packed_git *p;
1143
  off_t base_offset;
1144
};
1145
1146
struct delta_base_cache_entry {
1147
  struct hashmap_entry ent;
1148
  struct delta_base_cache_key key;
1149
  struct list_head lru;
1150
  void *data;
1151
  size_t size;
1152
  enum object_type type;
1153
};
1154
1155
static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1156
0
{
1157
0
  unsigned int hash;
1158
1159
0
  hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1160
0
  hash += (hash >> 8) + (hash >> 16);
1161
0
  return hash;
1162
0
}
1163
1164
static struct delta_base_cache_entry *
1165
get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1166
0
{
1167
0
  struct hashmap_entry entry, *e;
1168
0
  struct delta_base_cache_key key;
1169
1170
0
  if (!delta_base_cache.cmpfn)
1171
0
    return NULL;
1172
1173
0
  hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1174
0
  key.p = p;
1175
0
  key.base_offset = base_offset;
1176
0
  e = hashmap_get(&delta_base_cache, &entry, &key);
1177
0
  return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1178
0
}
1179
1180
static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1181
           const struct delta_base_cache_key *b)
1182
0
{
1183
0
  return a->p == b->p && a->base_offset == b->base_offset;
1184
0
}
1185
1186
static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1187
             const struct hashmap_entry *va,
1188
             const struct hashmap_entry *vb,
1189
             const void *vkey)
1190
0
{
1191
0
  const struct delta_base_cache_entry *a, *b;
1192
0
  const struct delta_base_cache_key *key = vkey;
1193
1194
0
  a = container_of(va, const struct delta_base_cache_entry, ent);
1195
0
  b = container_of(vb, const struct delta_base_cache_entry, ent);
1196
1197
0
  if (key)
1198
0
    return !delta_base_cache_key_eq(&a->key, key);
1199
0
  else
1200
0
    return !delta_base_cache_key_eq(&a->key, &b->key);
1201
0
}
1202
1203
static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1204
0
{
1205
0
  return !!get_delta_base_cache_entry(p, base_offset);
1206
0
}
1207
1208
/*
1209
 * Remove the entry from the cache, but do _not_ free the associated
1210
 * entry data. The caller takes ownership of the "data" buffer, and
1211
 * should copy out any fields it wants before detaching.
1212
 */
1213
static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1214
0
{
1215
0
  hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1216
0
  list_del(&ent->lru);
1217
0
  delta_base_cached -= ent->size;
1218
0
  free(ent);
1219
0
}
1220
1221
static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1222
           off_t base_offset, size_t *base_size,
1223
           enum object_type *type)
1224
0
{
1225
0
  struct delta_base_cache_entry *ent;
1226
1227
0
  ent = get_delta_base_cache_entry(p, base_offset);
1228
0
  if (!ent)
1229
0
    return unpack_entry(r, p, base_offset, type, base_size);
1230
1231
0
  if (type)
1232
0
    *type = ent->type;
1233
0
  if (base_size)
1234
0
    *base_size = ent->size;
1235
0
  return xmemdupz(ent->data, ent->size);
1236
0
}
1237
1238
static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1239
0
{
1240
0
  free(ent->data);
1241
0
  detach_delta_base_cache_entry(ent);
1242
0
}
1243
1244
void clear_delta_base_cache(void)
1245
0
{
1246
0
  struct list_head *lru, *tmp;
1247
0
  list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1248
0
    struct delta_base_cache_entry *entry =
1249
0
      list_entry(lru, struct delta_base_cache_entry, lru);
1250
0
    release_delta_base_cache(entry);
1251
0
  }
1252
0
}
1253
1254
static void delta_base_cache_evict_entry(struct packed_git *p)
1255
0
{
1256
0
  struct list_head *lru, *tmp;
1257
1258
0
  list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1259
0
    struct delta_base_cache_entry *entry =
1260
0
      list_entry(lru, struct delta_base_cache_entry, lru);
1261
0
    if (entry->key.p == p)
1262
0
      release_delta_base_cache(entry);
1263
0
  }
1264
0
}
1265
1266
void close_pack(struct packed_git *p)
1267
0
{
1268
0
  close_pack_windows(p);
1269
0
  close_pack_fd(p);
1270
0
  close_pack_index(p);
1271
0
  close_pack_revindex(p);
1272
0
  close_pack_mtimes(p);
1273
0
  oidset_clear(&p->bad_objects);
1274
0
  delta_base_cache_evict_entry(p);
1275
0
}
1276
1277
static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1278
         void *base, size_t base_size,
1279
         size_t delta_base_cache_limit,
1280
         enum object_type type)
1281
0
{
1282
0
  struct delta_base_cache_entry *ent;
1283
0
  struct list_head *lru, *tmp;
1284
1285
  /*
1286
   * Check required to avoid redundant entries when more than one thread
1287
   * is unpacking the same object, in unpack_entry() (since its phases I
1288
   * and III might run concurrently across multiple threads).
1289
   */
1290
0
  if (in_delta_base_cache(p, base_offset)) {
1291
0
    free(base);
1292
0
    return;
1293
0
  }
1294
1295
0
  delta_base_cached += base_size;
1296
1297
0
  list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1298
0
    struct delta_base_cache_entry *f =
1299
0
      list_entry(lru, struct delta_base_cache_entry, lru);
1300
0
    if (delta_base_cached <= delta_base_cache_limit)
1301
0
      break;
1302
0
    release_delta_base_cache(f);
1303
0
  }
1304
1305
0
  ent = xmalloc(sizeof(*ent));
1306
0
  ent->key.p = p;
1307
0
  ent->key.base_offset = base_offset;
1308
0
  ent->type = type;
1309
0
  ent->data = base;
1310
0
  ent->size = base_size;
1311
0
  list_add_tail(&ent->lru, &delta_base_cache_lru);
1312
1313
0
  if (!delta_base_cache.cmpfn)
1314
0
    hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1315
0
  hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1316
0
  hashmap_add(&delta_base_cache, &ent->ent);
1317
0
}
1318
1319
int packed_object_info_with_index_pos(struct odb_source_packed *source,
1320
              struct packed_git *p, off_t obj_offset,
1321
              uint32_t *maybe_index_pos, struct object_info *oi)
1322
0
{
1323
0
  struct pack_window *w_curs = NULL;
1324
0
  size_t size;
1325
0
  off_t curpos = obj_offset;
1326
0
  enum object_type type = OBJ_NONE;
1327
0
  uint32_t pack_pos;
1328
0
  int ret;
1329
1330
  /*
1331
   * We always get the representation type, but only convert it to
1332
   * a "real" type later if the caller is interested.
1333
   */
1334
0
  if (oi->contentp) {
1335
0
    *oi->contentp = cache_or_unpack_entry(p->repo, p, obj_offset,
1336
0
                  oi->sizep, &type);
1337
0
    if (!*oi->contentp)
1338
0
      type = OBJ_BAD;
1339
0
  } else if (oi->sizep || oi->typep || oi->delta_base_oid) {
1340
0
    type = unpack_object_header(p, &w_curs, &curpos, &size);
1341
0
  }
1342
1343
0
  if (!oi->contentp && oi->sizep) {
1344
0
    if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1345
0
      off_t tmp_pos = curpos;
1346
0
      off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1347
0
                 type, obj_offset);
1348
0
      if (!base_offset) {
1349
0
        ret = -1;
1350
0
        goto out;
1351
0
      }
1352
0
      size = get_size_from_delta(p, &w_curs, tmp_pos);
1353
0
      if (size == 0) {
1354
0
        ret = -1;
1355
0
        goto out;
1356
0
      }
1357
0
    }
1358
0
    *oi->sizep = size;
1359
0
  }
1360
1361
0
  if (oi->disk_sizep || (oi->mtimep && p->is_cruft)) {
1362
0
    if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1363
0
      error("could not find object at offset %"PRIuMAX" "
1364
0
            "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1365
0
      ret = -1;
1366
0
      goto out;
1367
0
    }
1368
0
  }
1369
1370
0
  if (oi->disk_sizep)
1371
0
    *oi->disk_sizep = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1372
1373
0
  if (oi->mtimep) {
1374
0
    if (p->is_cruft) {
1375
0
      uint32_t index_pos;
1376
1377
0
      if (load_pack_mtimes(p) < 0)
1378
0
        die(_("could not load .mtimes for cruft pack '%s'"),
1379
0
            pack_basename(p));
1380
1381
0
      if (maybe_index_pos)
1382
0
        index_pos = *maybe_index_pos;
1383
0
      else
1384
0
        index_pos = pack_pos_to_index(p, pack_pos);
1385
1386
0
      *oi->mtimep = nth_packed_mtime(p, index_pos);
1387
0
    } else {
1388
0
      *oi->mtimep = p->mtime;
1389
0
    }
1390
0
  }
1391
1392
0
  if (oi->typep) {
1393
0
    enum object_type ptot;
1394
0
    ptot = packed_to_object_type(p->repo, p, obj_offset,
1395
0
               type, &w_curs, curpos);
1396
0
    if (oi->typep)
1397
0
      *oi->typep = ptot;
1398
0
    if (ptot < 0) {
1399
0
      ret = -1;
1400
0
      goto out;
1401
0
    }
1402
0
  }
1403
1404
0
  if (oi->delta_base_oid) {
1405
0
    if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1406
0
      if (get_delta_base_oid(p, &w_curs, curpos,
1407
0
                 oi->delta_base_oid,
1408
0
                 type, obj_offset) < 0) {
1409
0
        ret = -1;
1410
0
        goto out;
1411
0
      }
1412
0
    } else
1413
0
      oidclr(oi->delta_base_oid, p->repo->hash_algo);
1414
0
  }
1415
1416
0
  if (oi->source_infop) {
1417
0
    if (!source)
1418
0
      BUG("cannot request source without an owning source");
1419
0
    oi->source_infop->source = &source->base;
1420
1421
0
    oi->source_infop->u.packed.offset = obj_offset;
1422
0
    oi->source_infop->u.packed.pack = p;
1423
1424
0
    switch (type) {
1425
0
    case OBJ_NONE:
1426
0
      oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_UNKNOWN;
1427
0
      break;
1428
0
    case OBJ_REF_DELTA:
1429
0
      oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_REF_DELTA;
1430
0
      break;
1431
0
    case OBJ_OFS_DELTA:
1432
0
      oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_OFS_DELTA;
1433
0
      break;
1434
0
    default:
1435
0
      oi->source_infop->u.packed.type = PACKED_OBJECT_TYPE_FULL;
1436
0
      break;
1437
0
    }
1438
0
  }
1439
1440
0
  ret = 0;
1441
1442
0
out:
1443
0
  unuse_pack(&w_curs);
1444
0
  return ret;
1445
0
}
1446
1447
int packed_object_info(struct odb_source_packed *source,
1448
           struct packed_git *p, off_t obj_offset,
1449
           struct object_info *oi)
1450
0
{
1451
0
  return packed_object_info_with_index_pos(source, p, obj_offset, NULL, oi);
1452
0
}
1453
1454
static void *unpack_compressed_entry(struct packed_git *p,
1455
            struct pack_window **w_curs,
1456
            off_t curpos,
1457
            size_t size)
1458
0
{
1459
0
  int st;
1460
0
  git_zstream stream;
1461
0
  unsigned char *buffer, *in;
1462
1463
0
  buffer = xmallocz_gently(size);
1464
0
  if (!buffer)
1465
0
    return NULL;
1466
0
  memset(&stream, 0, sizeof(stream));
1467
0
  stream.next_out = buffer;
1468
0
  stream.avail_out = size + 1;
1469
1470
0
  git_inflate_init(&stream);
1471
0
  do {
1472
0
    in = use_pack(p, w_curs, curpos, &stream.avail_in);
1473
0
    stream.next_in = in;
1474
    /*
1475
     * Note: we must ensure the window section returned by
1476
     * use_pack() will be available throughout git_inflate()'s
1477
     * unlocked execution. Please refer to the comment at
1478
     * get_size_from_delta() to see how this is done.
1479
     */
1480
0
    obj_read_unlock();
1481
0
    st = git_inflate(&stream, Z_FINISH);
1482
0
    obj_read_lock();
1483
0
    if (!stream.avail_out)
1484
0
      break; /* the payload is larger than it should be */
1485
0
    curpos += stream.next_in - in;
1486
0
  } while (st == Z_OK || st == Z_BUF_ERROR);
1487
0
  git_inflate_end(&stream);
1488
0
  if ((st != Z_STREAM_END) || stream.total_out != size) {
1489
0
    free(buffer);
1490
0
    return NULL;
1491
0
  }
1492
1493
  /* versions of zlib can clobber unconsumed portion of outbuf */
1494
0
  buffer[size] = '\0';
1495
1496
0
  return buffer;
1497
0
}
1498
1499
static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1500
0
{
1501
0
  static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1502
0
  trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1503
0
       p->pack_name, (uintmax_t)obj_offset);
1504
0
}
1505
1506
int do_check_packed_object_crc;
1507
1508
0
#define UNPACK_ENTRY_STACK_PREALLOC 64
1509
struct unpack_entry_stack_ent {
1510
  off_t obj_offset;
1511
  off_t curpos;
1512
  size_t size;
1513
};
1514
1515
void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1516
       enum object_type *final_type, size_t *final_size)
1517
0
{
1518
0
  struct pack_window *w_curs = NULL;
1519
0
  off_t curpos = obj_offset;
1520
0
  void *data = NULL;
1521
0
  size_t size;
1522
0
  enum object_type type;
1523
0
  struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1524
0
  struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1525
0
  int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1526
0
  int base_from_cache = 0;
1527
1528
0
  prepare_repo_settings(p->repo);
1529
1530
0
  write_pack_access_log(p, obj_offset);
1531
1532
  /* PHASE 1: drill down to the innermost base object */
1533
0
  for (;;) {
1534
0
    off_t base_offset;
1535
0
    int i;
1536
0
    struct delta_base_cache_entry *ent;
1537
1538
0
    ent = get_delta_base_cache_entry(p, curpos);
1539
0
    if (ent) {
1540
0
      type = ent->type;
1541
0
      data = ent->data;
1542
0
      size = ent->size;
1543
0
      detach_delta_base_cache_entry(ent);
1544
0
      base_from_cache = 1;
1545
0
      break;
1546
0
    }
1547
1548
0
    if (do_check_packed_object_crc && p->index_version > 1) {
1549
0
      uint32_t pack_pos, index_pos;
1550
0
      off_t len;
1551
1552
0
      if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1553
0
        error("could not find object at offset %"PRIuMAX" in pack %s",
1554
0
              (uintmax_t)obj_offset, p->pack_name);
1555
0
        data = NULL;
1556
0
        goto out;
1557
0
      }
1558
1559
0
      len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1560
0
      index_pos = pack_pos_to_index(p, pack_pos);
1561
0
      if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1562
0
        struct object_id oid;
1563
0
        nth_packed_object_id(&oid, p, index_pos);
1564
0
        error("bad packed object CRC for %s",
1565
0
              oid_to_hex(&oid));
1566
0
        mark_bad_packed_object(p, &oid);
1567
0
        data = NULL;
1568
0
        goto out;
1569
0
      }
1570
0
    }
1571
1572
0
    type = unpack_object_header(p, &w_curs, &curpos, &size);
1573
0
    if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1574
0
      break;
1575
1576
0
    base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1577
0
    if (!base_offset) {
1578
0
      error("failed to validate delta base reference "
1579
0
            "at offset %"PRIuMAX" from %s",
1580
0
            (uintmax_t)curpos, p->pack_name);
1581
      /* bail to phase 2, in hopes of recovery */
1582
0
      data = NULL;
1583
0
      break;
1584
0
    }
1585
1586
    /* push object, proceed to base */
1587
0
    if (delta_stack_nr >= delta_stack_alloc
1588
0
        && delta_stack == small_delta_stack) {
1589
0
      delta_stack_alloc = alloc_nr(delta_stack_nr);
1590
0
      ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1591
0
      COPY_ARRAY(delta_stack, small_delta_stack,
1592
0
           delta_stack_nr);
1593
0
    } else {
1594
0
      ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1595
0
    }
1596
0
    i = delta_stack_nr++;
1597
0
    delta_stack[i].obj_offset = obj_offset;
1598
0
    delta_stack[i].curpos = curpos;
1599
0
    delta_stack[i].size = size;
1600
1601
0
    curpos = obj_offset = base_offset;
1602
0
  }
1603
1604
  /* PHASE 2: handle the base */
1605
0
  switch (type) {
1606
0
  case OBJ_OFS_DELTA:
1607
0
  case OBJ_REF_DELTA:
1608
0
    if (data)
1609
0
      BUG("unpack_entry: left loop at a valid delta");
1610
0
    break;
1611
0
  case OBJ_COMMIT:
1612
0
  case OBJ_TREE:
1613
0
  case OBJ_BLOB:
1614
0
  case OBJ_TAG:
1615
0
    if (!base_from_cache)
1616
0
      data = unpack_compressed_entry(p, &w_curs, curpos, size);
1617
0
    break;
1618
0
  default:
1619
0
    data = NULL;
1620
0
    error("unknown object type %i at offset %"PRIuMAX" in %s",
1621
0
          type, (uintmax_t)obj_offset, p->pack_name);
1622
0
  }
1623
1624
  /* PHASE 3: apply deltas in order */
1625
1626
  /* invariants:
1627
   *   'data' holds the base data, or NULL if there was corruption
1628
   */
1629
0
  while (delta_stack_nr) {
1630
0
    void *delta_data;
1631
0
    void *base = data;
1632
0
    void *external_base = NULL;
1633
0
    size_t delta_size, base_size = size;
1634
0
    int i;
1635
0
    off_t base_obj_offset = obj_offset;
1636
1637
0
    data = NULL;
1638
1639
0
    if (!base) {
1640
      /*
1641
       * We're probably in deep shit, but let's try to fetch
1642
       * the required base anyway from another pack or loose.
1643
       * This is costly but should happen only in the presence
1644
       * of a corrupted pack, and is better than failing outright.
1645
       */
1646
0
      uint32_t pos;
1647
0
      struct object_id base_oid;
1648
0
      if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1649
0
        struct object_info oi = OBJECT_INFO_INIT;
1650
1651
0
        nth_packed_object_id(&base_oid, p,
1652
0
                 pack_pos_to_index(p, pos));
1653
0
        error("failed to read delta base object %s"
1654
0
              " at offset %"PRIuMAX" from %s",
1655
0
              oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1656
0
              p->pack_name);
1657
0
        mark_bad_packed_object(p, &base_oid);
1658
1659
0
        oi.typep = &type;
1660
0
        oi.sizep = &base_size;
1661
0
        oi.contentp = &base;
1662
0
        if (odb_read_object_info_extended(r->objects, &base_oid,
1663
0
                  &oi, 0) < 0)
1664
0
          base = NULL;
1665
1666
0
        external_base = base;
1667
0
      }
1668
0
    }
1669
1670
0
    i = --delta_stack_nr;
1671
0
    obj_offset = delta_stack[i].obj_offset;
1672
0
    curpos = delta_stack[i].curpos;
1673
0
    delta_size = delta_stack[i].size;
1674
1675
0
    if (!base)
1676
0
      continue;
1677
1678
0
    delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1679
1680
0
    if (!delta_data) {
1681
0
      error("failed to unpack compressed delta "
1682
0
            "at offset %"PRIuMAX" from %s",
1683
0
            (uintmax_t)curpos, p->pack_name);
1684
0
      data = NULL;
1685
0
    } else {
1686
0
      data = patch_delta(base, base_size, delta_data,
1687
0
             delta_size, &size);
1688
1689
      /*
1690
       * We could not apply the delta; warn the user, but
1691
       * keep going. Our failure will be noticed either in
1692
       * the next iteration of the loop, or if this is the
1693
       * final delta, in the caller when we return NULL.
1694
       * Those code paths will take care of making a more
1695
       * explicit warning and retrying with another copy of
1696
       * the object.
1697
       */
1698
0
      if (!data)
1699
0
        error("failed to apply delta");
1700
0
    }
1701
1702
    /*
1703
     * We delay adding `base` to the cache until the end of the loop
1704
     * because unpack_compressed_entry() momentarily releases the
1705
     * obj_read_mutex, giving another thread the chance to access
1706
     * the cache. Therefore, if `base` was already there, this other
1707
     * thread could free() it (e.g. to make space for another entry)
1708
     * before we are done using it.
1709
     */
1710
0
    if (!external_base)
1711
0
      add_delta_base_cache(p, base_obj_offset, base, base_size,
1712
0
               p->repo->settings.delta_base_cache_limit,
1713
0
               type);
1714
1715
0
    free(delta_data);
1716
0
    free(external_base);
1717
0
  }
1718
1719
0
  if (final_type)
1720
0
    *final_type = type;
1721
0
  if (final_size)
1722
0
    *final_size = size;
1723
1724
0
out:
1725
0
  unuse_pack(&w_curs);
1726
1727
0
  if (delta_stack != small_delta_stack)
1728
0
    free(delta_stack);
1729
1730
0
  return data;
1731
0
}
1732
1733
int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1734
0
{
1735
0
  const unsigned char *index_fanout = p->index_data;
1736
0
  const unsigned char *index_lookup;
1737
0
  const unsigned int hashsz = p->repo->hash_algo->rawsz;
1738
0
  int index_lookup_width;
1739
1740
0
  if (!index_fanout)
1741
0
    BUG("bsearch_pack called without a valid pack-index");
1742
1743
0
  index_lookup = index_fanout + 4 * 256;
1744
0
  if (p->index_version == 1) {
1745
0
    index_lookup_width = hashsz + 4;
1746
0
    index_lookup += 4;
1747
0
  } else {
1748
0
    index_lookup_width = hashsz;
1749
0
    index_fanout += 8;
1750
0
    index_lookup += 8;
1751
0
  }
1752
1753
0
  return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1754
0
          index_lookup, index_lookup_width, result);
1755
0
}
1756
1757
int nth_packed_object_id(struct object_id *oid,
1758
       struct packed_git *p,
1759
       uint32_t n)
1760
0
{
1761
0
  const unsigned char *index = p->index_data;
1762
0
  const unsigned int hashsz = p->repo->hash_algo->rawsz;
1763
0
  if (!index) {
1764
0
    if (open_pack_index(p))
1765
0
      return -1;
1766
0
    index = p->index_data;
1767
0
  }
1768
0
  if (n >= p->num_objects)
1769
0
    return -1;
1770
0
  index += 4 * 256;
1771
0
  if (p->index_version == 1) {
1772
0
    oidread(oid, index + st_add(st_mult(hashsz + 4, n), 4),
1773
0
      p->repo->hash_algo);
1774
0
  } else {
1775
0
    index += 8;
1776
0
    oidread(oid, index + st_mult(hashsz, n), p->repo->hash_algo);
1777
0
  }
1778
0
  return 0;
1779
0
}
1780
1781
void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1782
0
{
1783
0
  const unsigned char *ptr = vptr;
1784
0
  const unsigned char *start = p->index_data;
1785
0
  const unsigned char *end = start + p->index_size;
1786
0
  if (ptr < start)
1787
0
    die(_("offset before start of pack index for %s (corrupt index?)"),
1788
0
        p->pack_name);
1789
  /* No need to check for underflow; .idx files must be at least 8 bytes */
1790
0
  if (ptr >= end - 8)
1791
0
    die(_("offset beyond end of pack index for %s (truncated index?)"),
1792
0
        p->pack_name);
1793
0
}
1794
1795
off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1796
0
{
1797
0
  const unsigned char *index = p->index_data;
1798
0
  const unsigned int hashsz = p->repo->hash_algo->rawsz;
1799
0
  index += 4 * 256;
1800
0
  if (p->index_version == 1) {
1801
0
    return ntohl(*((uint32_t *)(index + st_mult(hashsz + 4, n))));
1802
0
  } else {
1803
0
    uint32_t off;
1804
0
    index += st_add(8, st_mult(p->num_objects, hashsz + 4));
1805
0
    off = ntohl(*((uint32_t *)(index + st_mult(4, n))));
1806
0
    if (!(off & 0x80000000))
1807
0
      return off;
1808
0
    index += st_add(st_mult(p->num_objects, 4),
1809
0
        st_mult(off & 0x7fffffff, 8));
1810
0
    check_pack_index_ptr(p, index);
1811
0
    return get_be64(index);
1812
0
  }
1813
0
}
1814
1815
off_t find_pack_entry_one(const struct object_id *oid,
1816
        struct packed_git *p)
1817
0
{
1818
0
  const unsigned char *index = p->index_data;
1819
0
  uint32_t result;
1820
1821
0
  if (!index) {
1822
0
    if (open_pack_index(p))
1823
0
      return 0;
1824
0
  }
1825
1826
0
  if (bsearch_pack(oid, p, &result))
1827
0
    return nth_packed_object_offset(p, result);
1828
0
  return 0;
1829
0
}
1830
1831
int is_pack_valid(struct packed_git *p)
1832
0
{
1833
  /* An already open pack is known to be valid. */
1834
0
  if (p->pack_fd != -1)
1835
0
    return 1;
1836
1837
  /* If the pack has one window completely covering the
1838
   * file size, the pack is known to be valid even if
1839
   * the descriptor is not currently open.
1840
   */
1841
0
  if (p->windows) {
1842
0
    struct pack_window *w = p->windows;
1843
1844
0
    if (!w->offset && w->len == p->pack_size)
1845
0
      return 1;
1846
0
  }
1847
1848
  /* Force the pack to open to prove its valid. */
1849
0
  return !open_packed_git(p);
1850
0
}
1851
1852
int packfile_fill_entry(struct packed_git *p,
1853
      const struct object_id *oid,
1854
      struct pack_entry *e,
1855
      struct packed_git **bad_pack)
1856
0
{
1857
0
  off_t offset;
1858
1859
0
  if (oidset_size(&p->bad_objects) &&
1860
0
      oidset_contains(&p->bad_objects, oid)) {
1861
0
    if (bad_pack && !*bad_pack)
1862
0
      *bad_pack = p;
1863
0
    return 0;
1864
0
  }
1865
1866
0
  offset = find_pack_entry_one(oid, p);
1867
0
  if (!offset)
1868
0
    return 0;
1869
1870
  /*
1871
   * We are about to tell the caller where they can locate the
1872
   * requested object.  We better make sure the packfile is
1873
   * still here and can be accessed before supplying that
1874
   * answer, as it may have been deleted since the index was
1875
   * loaded!
1876
   */
1877
0
  if (!is_pack_valid(p))
1878
0
    return 0;
1879
0
  e->offset = offset;
1880
0
  e->p = p;
1881
0
  return 1;
1882
0
}
1883
1884
static void maybe_invalidate_kept_pack_cache(struct odb_source_packed *store,
1885
               unsigned flags)
1886
0
{
1887
0
  if (!store->kept_cache.packs)
1888
0
    return;
1889
0
  if (store->kept_cache.flags == flags)
1890
0
    return;
1891
0
  FREE_AND_NULL(store->kept_cache.packs);
1892
0
  store->kept_cache.flags = 0;
1893
0
}
1894
1895
struct packed_git **packfile_store_get_kept_pack_cache(struct odb_source_packed *store,
1896
                   unsigned flags)
1897
0
{
1898
0
  maybe_invalidate_kept_pack_cache(store, flags);
1899
1900
0
  if (!store->kept_cache.packs) {
1901
0
    struct packed_git **packs = NULL;
1902
0
    struct packfile_list_entry *e;
1903
0
    size_t nr = 0, alloc = 0;
1904
1905
    /*
1906
     * We want "all" packs here, because we need to cover ones that
1907
     * are used by a midx, as well. We need to look in every one of
1908
     * them (instead of the midx itself) to cover duplicates. It's
1909
     * possible that an object is found in two packs that the midx
1910
     * covers, one kept and one not kept, but the midx returns only
1911
     * the non-kept version.
1912
     */
1913
0
    for (e = packfile_store_get_packs(store); e; e = e->next) {
1914
0
      struct packed_git *p = e->pack;
1915
1916
0
      if ((p->pack_keep && (flags & KEPT_PACK_ON_DISK)) ||
1917
0
          (p->pack_keep_in_core && (flags & KEPT_PACK_IN_CORE)) ||
1918
0
          (p->pack_keep_in_core_open && (flags & KEPT_PACK_IN_CORE_OPEN))) {
1919
0
        ALLOC_GROW(packs, nr + 1, alloc);
1920
0
        packs[nr++] = p;
1921
0
      }
1922
0
    }
1923
0
    ALLOC_GROW(packs, nr + 1, alloc);
1924
0
    packs[nr] = NULL;
1925
1926
0
    store->kept_cache.packs = packs;
1927
0
    store->kept_cache.flags = flags;
1928
0
  }
1929
1930
0
  return store->kept_cache.packs;
1931
0
}
1932
1933
int has_object_pack(struct repository *r, const struct object_id *oid)
1934
0
{
1935
0
  struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
1936
1937
0
  for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
1938
0
    if (!odb_source_read_object_info(&dir->packed->base, oid, NULL, 0, NULL))
1939
0
      return 1;
1940
0
  }
1941
1942
0
  return 0;
1943
0
}
1944
1945
int has_object_kept_pack(struct repository *r, const struct object_id *oid,
1946
       unsigned flags)
1947
0
{
1948
0
  struct odb_source_files *files = odb_source_files_downcast(r->objects->source);
1949
0
  struct pack_entry e;
1950
1951
0
  for (struct odb_files_dir *dir = files->dirs; dir; dir = dir->next) {
1952
0
    struct packed_git **cache;
1953
1954
0
    cache = packfile_store_get_kept_pack_cache(dir->packed, flags);
1955
1956
0
    for (; *cache; cache++) {
1957
0
      struct packed_git *p = *cache;
1958
0
      if (packfile_fill_entry(p, oid, &e, NULL))
1959
0
        return 1;
1960
0
    }
1961
0
  }
1962
1963
0
  return 0;
1964
0
}
1965
1966
int for_each_object_in_pack(struct packed_git *p,
1967
          each_packed_object_fn cb, void *data,
1968
          enum odb_for_each_object_flags flags)
1969
0
{
1970
0
  uint32_t i;
1971
0
  int r = 0;
1972
1973
0
  if (flags & ODB_FOR_EACH_OBJECT_PACK_ORDER) {
1974
0
    if (load_pack_revindex(p->repo, p))
1975
0
      return -1;
1976
0
  }
1977
1978
0
  for (i = 0; i < p->num_objects; i++) {
1979
0
    uint32_t index_pos;
1980
0
    struct object_id oid;
1981
1982
    /*
1983
     * We are iterating "i" from 0 up to num_objects, but its
1984
     * meaning may be different, depending on the requested output
1985
     * order:
1986
     *
1987
     *   - in object-name order, it is the same as the index order
1988
     *     used by nth_packed_object_id(), so we can pass it
1989
     *     directly
1990
     *
1991
     *   - in pack-order, it is pack position, which we must
1992
     *     convert to an index position in order to get the oid.
1993
     */
1994
0
    if (flags & ODB_FOR_EACH_OBJECT_PACK_ORDER)
1995
0
      index_pos = pack_pos_to_index(p, i);
1996
0
    else
1997
0
      index_pos = i;
1998
1999
0
    if (nth_packed_object_id(&oid, p, index_pos) < 0)
2000
0
      return error("unable to get sha1 of object %u in %s",
2001
0
             index_pos, p->pack_name);
2002
2003
0
    r = cb(&oid, p, index_pos, data);
2004
0
    if (r)
2005
0
      break;
2006
0
  }
2007
0
  return r;
2008
0
}
2009
2010
struct add_promisor_object_data {
2011
  struct repository *repo;
2012
  struct oidset *set;
2013
};
2014
2015
static int add_promisor_object(const struct object_id *oid,
2016
             struct object_info *oi UNUSED,
2017
             void *cb_data)
2018
0
{
2019
0
  struct add_promisor_object_data *data = cb_data;
2020
0
  struct object *obj;
2021
0
  int we_parsed_object;
2022
2023
0
  obj = lookup_object(data->repo, oid);
2024
0
  if (obj && obj->parsed) {
2025
0
    we_parsed_object = 0;
2026
0
  } else {
2027
0
    we_parsed_object = 1;
2028
0
    obj = parse_object_with_flags(data->repo, oid,
2029
0
                PARSE_OBJECT_SKIP_HASH_CHECK);
2030
0
  }
2031
2032
0
  if (!obj)
2033
0
    return 1;
2034
2035
0
  oidset_insert(data->set, oid);
2036
2037
  /*
2038
   * If this is a tree, commit, or tag, the objects it refers
2039
   * to are also promisor objects. (Blobs refer to no objects->)
2040
   */
2041
0
  if (obj->type == OBJ_TREE) {
2042
0
    struct tree *tree = (struct tree *)obj;
2043
0
    struct tree_desc desc;
2044
0
    struct name_entry entry;
2045
0
    if (init_tree_desc_gently(&desc, &tree->object.oid,
2046
0
            tree->buffer, tree->size, 0))
2047
      /*
2048
       * Error messages are given when packs are
2049
       * verified, so do not print any here.
2050
       */
2051
0
      return 0;
2052
0
    while (tree_entry_gently(&desc, &entry))
2053
0
      oidset_insert(data->set, &entry.oid);
2054
0
    if (we_parsed_object)
2055
0
      free_tree_buffer(tree);
2056
0
  } else if (obj->type == OBJ_COMMIT) {
2057
0
    struct commit *commit = (struct commit *) obj;
2058
0
    struct commit_list *parents = commit->parents;
2059
2060
0
    oidset_insert(data->set, get_commit_tree_oid(commit));
2061
0
    for (; parents; parents = parents->next)
2062
0
      oidset_insert(data->set, &parents->item->object.oid);
2063
0
  } else if (obj->type == OBJ_TAG) {
2064
0
    struct tag *tag = (struct tag *) obj;
2065
0
    oidset_insert(data->set, get_tagged_oid(tag));
2066
0
  }
2067
0
  return 0;
2068
0
}
2069
2070
int is_promisor_object(struct repository *r, const struct object_id *oid)
2071
0
{
2072
0
  static struct oidset promisor_objects;
2073
0
  static int promisor_objects_prepared;
2074
2075
0
  if (!promisor_objects_prepared) {
2076
0
    if (repo_has_promisor_remote(r)) {
2077
0
      struct add_promisor_object_data data = {
2078
0
        .repo = r,
2079
0
        .set = &promisor_objects,
2080
0
      };
2081
2082
0
      odb_for_each_object(r->objects, NULL, add_promisor_object, &data,
2083
0
              ODB_FOR_EACH_OBJECT_PROMISOR_ONLY | ODB_FOR_EACH_OBJECT_PACK_ORDER);
2084
0
    }
2085
0
    promisor_objects_prepared = 1;
2086
0
  }
2087
0
  return oidset_contains(&promisor_objects, oid);
2088
0
}
2089
2090
int parse_pack_header_option(const char *in, unsigned char *out, unsigned int *len)
2091
0
{
2092
0
  unsigned char *hdr;
2093
0
  char *c;
2094
2095
0
  hdr = out;
2096
0
  put_be32(hdr, PACK_SIGNATURE);
2097
0
  hdr += 4;
2098
0
  put_be32(hdr, strtoul(in, &c, 10));
2099
0
  hdr += 4;
2100
0
  if (*c != ',')
2101
0
    return -1;
2102
0
  put_be32(hdr, strtoul(c + 1, &c, 10));
2103
0
  hdr += 4;
2104
0
  if (*c)
2105
0
    return -1;
2106
0
  *len = hdr - out;
2107
0
  return 0;
2108
0
}
2109
2110
struct odb_packed_read_stream {
2111
  struct odb_stream base;
2112
  struct packed_git *pack;
2113
  git_zstream z;
2114
  enum {
2115
    ODB_PACKED_READ_STREAM_UNINITIALIZED,
2116
    ODB_PACKED_READ_STREAM_INUSE,
2117
    ODB_PACKED_READ_STREAM_DONE,
2118
    ODB_PACKED_READ_STREAM_ERROR,
2119
  } z_state;
2120
  off_t pos;
2121
};
2122
2123
static ssize_t read_istream_pack_non_delta(struct odb_stream *_st, char *buf,
2124
             size_t sz)
2125
0
{
2126
0
  struct odb_packed_read_stream *st = (struct odb_packed_read_stream *)_st;
2127
0
  size_t total_read = 0;
2128
2129
0
  switch (st->z_state) {
2130
0
  case ODB_PACKED_READ_STREAM_UNINITIALIZED:
2131
0
    memset(&st->z, 0, sizeof(st->z));
2132
0
    git_inflate_init(&st->z);
2133
0
    st->z_state = ODB_PACKED_READ_STREAM_INUSE;
2134
0
    break;
2135
0
  case ODB_PACKED_READ_STREAM_DONE:
2136
0
    return 0;
2137
0
  case ODB_PACKED_READ_STREAM_ERROR:
2138
0
    return -1;
2139
0
  case ODB_PACKED_READ_STREAM_INUSE:
2140
0
    break;
2141
0
  }
2142
2143
0
  while (total_read < sz) {
2144
0
    int status;
2145
0
    struct pack_window *window = NULL;
2146
0
    unsigned char *mapped;
2147
2148
0
    mapped = use_pack(st->pack, &window,
2149
0
          st->pos, &st->z.avail_in);
2150
2151
0
    st->z.next_out = (unsigned char *)buf + total_read;
2152
0
    st->z.avail_out = sz - total_read;
2153
0
    st->z.next_in = mapped;
2154
0
    status = git_inflate(&st->z, Z_FINISH);
2155
2156
0
    st->pos += st->z.next_in - mapped;
2157
0
    total_read = st->z.next_out - (unsigned char *)buf;
2158
0
    unuse_pack(&window);
2159
2160
0
    if (status == Z_STREAM_END) {
2161
0
      git_inflate_end(&st->z);
2162
0
      st->z_state = ODB_PACKED_READ_STREAM_DONE;
2163
0
      break;
2164
0
    }
2165
2166
    /*
2167
     * Unlike the loose object case, we do not have to worry here
2168
     * about running out of input bytes and spinning infinitely. If
2169
     * we get Z_BUF_ERROR due to too few input bytes, then we'll
2170
     * replenish them in the next use_pack() call when we loop. If
2171
     * we truly hit the end of the pack (i.e., because it's corrupt
2172
     * or truncated), then use_pack() catches that and will die().
2173
     */
2174
0
    if (status != Z_OK && status != Z_BUF_ERROR) {
2175
0
      git_inflate_end(&st->z);
2176
0
      st->z_state = ODB_PACKED_READ_STREAM_ERROR;
2177
0
      return -1;
2178
0
    }
2179
0
  }
2180
0
  return total_read;
2181
0
}
2182
2183
static int close_istream_pack_non_delta(struct odb_stream *_st)
2184
0
{
2185
0
  struct odb_packed_read_stream *st = (struct odb_packed_read_stream *)_st;
2186
0
  if (st->z_state == ODB_PACKED_READ_STREAM_INUSE)
2187
0
    git_inflate_end(&st->z);
2188
0
  return 0;
2189
0
}
2190
2191
int packfile_read_object_stream(struct odb_stream **out,
2192
        const struct object_id *oid,
2193
        struct packed_git *pack,
2194
        off_t offset)
2195
0
{
2196
0
  struct odb_packed_read_stream *stream;
2197
0
  struct pack_window *window = NULL;
2198
0
  enum object_type in_pack_type;
2199
0
  size_t size;
2200
2201
0
  in_pack_type = unpack_object_header(pack, &window, &offset, &size);
2202
0
  unuse_pack(&window);
2203
2204
0
  if (repo_settings_get_big_file_threshold(pack->repo) >= size)
2205
0
    return -1;
2206
2207
0
  switch (in_pack_type) {
2208
0
  default:
2209
0
    return -1; /* we do not do deltas for now */
2210
0
  case OBJ_BAD:
2211
0
    mark_bad_packed_object(pack, oid);
2212
0
    return -1;
2213
0
  case OBJ_COMMIT:
2214
0
  case OBJ_TREE:
2215
0
  case OBJ_BLOB:
2216
0
  case OBJ_TAG:
2217
0
    break;
2218
0
  }
2219
2220
0
  CALLOC_ARRAY(stream, 1);
2221
0
  stream->base.close = close_istream_pack_non_delta;
2222
0
  stream->base.read = read_istream_pack_non_delta;
2223
0
  stream->base.type = in_pack_type;
2224
0
  stream->base.size = size;
2225
0
  stream->z_state = ODB_PACKED_READ_STREAM_UNINITIALIZED;
2226
0
  stream->pack = pack;
2227
0
  stream->pos = offset;
2228
2229
0
  *out = &stream->base;
2230
2231
0
  return 0;
2232
0
}