Coverage Report

Created: 2026-10-17 07:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/refs/packed-backend.c
Line
Count
Source
1
#define DISABLE_SIGN_COMPARE_WARNINGS
2
3
#include "../git-compat-util.h"
4
#include "../config.h"
5
#include "../dir.h"
6
#include "../fsck.h"
7
#include "../gettext.h"
8
#include "../hash.h"
9
#include "../hex.h"
10
#include "../refs.h"
11
#include "refs-internal.h"
12
#include "packed-backend.h"
13
#include "../iterator.h"
14
#include "../lockfile.h"
15
#include "../chdir-notify.h"
16
#include "../statinfo.h"
17
#include "../worktree.h"
18
#include "../wrapper.h"
19
#include "../write-or-die.h"
20
#include "../trace2.h"
21
22
enum mmap_strategy {
23
  /*
24
   * Don't use mmap() at all for reading `packed-refs`.
25
   */
26
  MMAP_NONE,
27
28
  /*
29
   * Can use mmap() for reading `packed-refs`, but the file must
30
   * not remain mmapped. This is the usual option on Windows,
31
   * where you cannot rename a new version of a file onto a file
32
   * that is currently mmapped.
33
   */
34
  MMAP_TEMPORARY,
35
36
  /*
37
   * It is OK to leave the `packed-refs` file mmapped while
38
   * arbitrary other code is running.
39
   */
40
  MMAP_OK
41
};
42
43
#if defined(NO_MMAP)
44
static enum mmap_strategy mmap_strategy = MMAP_NONE;
45
#elif defined(MMAP_PREVENTS_DELETE)
46
static enum mmap_strategy mmap_strategy = MMAP_TEMPORARY;
47
#else
48
static enum mmap_strategy mmap_strategy = MMAP_OK;
49
#endif
50
51
struct packed_ref_store;
52
53
/*
54
 * A `snapshot` represents one snapshot of a `packed-refs` file.
55
 *
56
 * Normally, this will be a mmapped view of the contents of the
57
 * `packed-refs` file at the time the snapshot was created. However,
58
 * if the `packed-refs` file was not sorted, this might point at heap
59
 * memory holding the contents of the `packed-refs` file with its
60
 * records sorted by refname.
61
 *
62
 * `snapshot` instances are reference counted (via
63
 * `acquire_snapshot()` and `release_snapshot()`). This is to prevent
64
 * an instance from disappearing while an iterator is still iterating
65
 * over it. Instances are garbage collected when their `referrers`
66
 * count goes to zero.
67
 *
68
 * The most recent `snapshot`, if available, is referenced by the
69
 * `packed_ref_store`. Its freshness is checked whenever
70
 * `get_snapshot()` is called; if the existing snapshot is obsolete, a
71
 * new snapshot is taken.
72
 */
73
struct snapshot {
74
  /*
75
   * A back-pointer to the packed_ref_store with which this
76
   * snapshot is associated:
77
   */
78
  struct packed_ref_store *refs;
79
80
  /* Is the `packed-refs` file currently mmapped? */
81
  int mmapped;
82
83
  /*
84
   * The contents of the `packed-refs` file:
85
   *
86
   * - buf -- a pointer to the start of the memory
87
   * - start -- a pointer to the first byte of actual references
88
   *   (i.e., after the header line, if one is present)
89
   * - eof -- a pointer just past the end of the reference
90
   *   contents
91
   *
92
   * If the `packed-refs` file was already sorted, `buf` points
93
   * at the mmapped contents of the file. If not, it points at
94
   * heap-allocated memory containing the contents, sorted. If
95
   * there were no contents (e.g., because the file didn't
96
   * exist), `buf`, `start`, and `eof` are all NULL.
97
   */
98
  char *buf, *start, *eof;
99
100
  /*
101
   * What is the peeled state of the `packed-refs` file that
102
   * this snapshot represents? (This is usually determined from
103
   * the file's header.)
104
   */
105
  enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled;
106
107
  /*
108
   * Count of references to this instance, including the pointer
109
   * from `packed_ref_store::snapshot`, if any. The instance
110
   * will not be freed as long as the reference count is
111
   * nonzero.
112
   */
113
  unsigned int referrers;
114
115
  /*
116
   * The metadata of the `packed-refs` file from which this
117
   * snapshot was created, used to tell if the file has been
118
   * replaced since we read it.
119
   */
120
  struct stat_validity validity;
121
};
122
123
/*
124
 * A `ref_store` representing references stored in a `packed-refs`
125
 * file. It implements the `ref_store` interface, though it has some
126
 * limitations:
127
 *
128
 * - It cannot store symbolic references.
129
 *
130
 * - It cannot store reflogs.
131
 *
132
 * - It does not support reference renaming (though it could).
133
 *
134
 * On the other hand, it can be locked outside of a reference
135
 * transaction. In that case, it remains locked even after the
136
 * transaction is done and the new `packed-refs` file is activated.
137
 */
138
struct packed_ref_store {
139
  struct ref_store base;
140
141
  unsigned int store_flags;
142
143
  /* The path of the "packed-refs" file: */
144
  char *path;
145
146
  /*
147
   * A snapshot of the values read from the `packed-refs` file,
148
   * if it might still be current; otherwise, NULL.
149
   */
150
  struct snapshot *snapshot;
151
152
  /*
153
   * Lock used for the "packed-refs" file. Note that this (and
154
   * thus the enclosing `packed_ref_store`) must not be freed.
155
   */
156
  struct lock_file lock;
157
158
  /*
159
   * Temporary file used when rewriting new contents to the
160
   * "packed-refs" file. Note that this (and thus the enclosing
161
   * `packed_ref_store`) must not be freed.
162
   */
163
  struct tempfile *tempfile;
164
165
  /*
166
   * Timeout when taking the "packed-refs.lock" file. configurable via
167
   * "core.packedRefsTimeout".
168
   */
169
  bool timeout_configured;
170
  int timeout_value;
171
};
172
173
/*
174
 * Increment the reference count of `*snapshot`.
175
 */
176
static void acquire_snapshot(struct snapshot *snapshot)
177
0
{
178
0
  snapshot->referrers++;
179
0
}
180
181
/*
182
 * If the buffer in `snapshot` is active, then either munmap the
183
 * memory and close the file, or free the memory. Then set the buffer
184
 * pointers to NULL.
185
 */
186
static void clear_snapshot_buffer(struct snapshot *snapshot)
187
0
{
188
0
  if (snapshot->mmapped) {
189
0
    if (munmap(snapshot->buf, snapshot->eof - snapshot->buf))
190
0
      die_errno("error ummapping packed-refs file %s",
191
0
          snapshot->refs->path);
192
0
    snapshot->mmapped = 0;
193
0
  } else {
194
0
    free(snapshot->buf);
195
0
  }
196
0
  snapshot->buf = snapshot->start = snapshot->eof = NULL;
197
0
}
198
199
/*
200
 * Decrease the reference count of `*snapshot`. If it goes to zero,
201
 * free `*snapshot` and return true; otherwise return false.
202
 */
203
static int release_snapshot(struct snapshot *snapshot)
204
0
{
205
0
  if (!--snapshot->referrers) {
206
0
    stat_validity_clear(&snapshot->validity);
207
0
    clear_snapshot_buffer(snapshot);
208
0
    free(snapshot);
209
0
    return 1;
210
0
  } else {
211
0
    return 0;
212
0
  }
213
0
}
214
215
static size_t snapshot_hexsz(const struct snapshot *snapshot)
216
0
{
217
0
  return snapshot->refs->base.repo->hash_algo->hexsz;
218
0
}
219
220
static void packed_ref_store_reparent(const char *old_cwd,
221
              const char *new_cwd,
222
              void *payload)
223
0
{
224
0
  struct packed_ref_store *refs = payload;
225
0
  char *tmp;
226
227
0
  tmp = reparent_relative_path(old_cwd, new_cwd, refs->path);
228
0
  free(refs->path);
229
0
  refs->path = tmp;
230
0
}
231
232
/*
233
 * Since packed-refs is only stored in the common dir, don't parse the
234
 * payload and rely on the files-backend to set 'gitdir' correctly.
235
 */
236
struct ref_store *packed_ref_store_init(struct repository *repo,
237
          const char *payload UNUSED,
238
          const char *gitdir,
239
          const struct ref_store_init_options *opts)
240
0
{
241
0
  struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
242
0
  struct ref_store *ref_store = (struct ref_store *)refs;
243
0
  struct strbuf sb = STRBUF_INIT;
244
245
0
  base_ref_store_init(ref_store, repo, gitdir, &refs_be_packed);
246
0
  refs->store_flags = opts->access_flags;
247
248
0
  strbuf_addf(&sb, "%s/packed-refs", gitdir);
249
0
  refs->path = strbuf_detach(&sb, NULL);
250
0
  chdir_notify_register(packed_ref_store_reparent, refs);
251
0
  return ref_store;
252
0
}
253
254
/*
255
 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
256
 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
257
 * support at least the flags specified in `required_flags`. `caller`
258
 * is used in any necessary error messages.
259
 */
260
static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
261
            unsigned int required_flags,
262
            const char *caller)
263
0
{
264
0
  struct packed_ref_store *refs;
265
266
0
  if (ref_store->be != &refs_be_packed)
267
0
    BUG("ref_store is type \"%s\" not \"packed\" in %s",
268
0
        ref_store->be->name, caller);
269
270
0
  refs = (struct packed_ref_store *)ref_store;
271
272
0
  if ((refs->store_flags & required_flags) != required_flags)
273
0
    BUG("unallowed operation (%s), requires %x, has %x\n",
274
0
        caller, required_flags, refs->store_flags);
275
276
0
  return refs;
277
0
}
278
279
static void clear_snapshot(struct packed_ref_store *refs)
280
0
{
281
0
  if (refs->snapshot) {
282
0
    struct snapshot *snapshot = refs->snapshot;
283
284
0
    refs->snapshot = NULL;
285
0
    release_snapshot(snapshot);
286
0
  }
287
0
}
288
289
static void packed_ref_store_release(struct ref_store *ref_store)
290
0
{
291
0
  struct packed_ref_store *refs = packed_downcast(ref_store, 0, "release");
292
0
  clear_snapshot(refs);
293
0
  rollback_lock_file(&refs->lock);
294
0
  delete_tempfile(&refs->tempfile);
295
0
  chdir_notify_unregister(packed_ref_store_reparent, refs);
296
0
  free(refs->path);
297
0
}
298
299
static NORETURN void die_unterminated_line(const char *path,
300
             const char *p, size_t len)
301
0
{
302
0
  if (len < 80)
303
0
    die("unterminated line in %s: %.*s", path, (int)len, p);
304
0
  else
305
0
    die("unterminated line in %s: %.75s...", path, p);
306
0
}
307
308
static NORETURN void die_invalid_line(const char *path,
309
              const char *p, size_t len)
310
0
{
311
0
  const char *eol = memchr(p, '\n', len);
312
313
0
  if (!eol)
314
0
    die_unterminated_line(path, p, len);
315
0
  else if (eol - p < 80)
316
0
    die("unexpected line in %s: %.*s", path, (int)(eol - p), p);
317
0
  else
318
0
    die("unexpected line in %s: %.75s...", path, p);
319
320
0
}
321
322
struct snapshot_record {
323
  const char *start;
324
  size_t len;
325
};
326
327
328
static int cmp_packed_refname(const char *r1, const char *r2)
329
0
{
330
0
  while (1) {
331
0
    if (*r1 == '\n')
332
0
      return *r2 == '\n' ? 0 : -1;
333
0
    if (*r1 != *r2) {
334
0
      if (*r2 == '\n')
335
0
        return 1;
336
0
      else
337
0
        return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
338
0
    }
339
0
    r1++;
340
0
    r2++;
341
0
  }
342
0
}
343
344
static int cmp_packed_ref_records(const void *v1, const void *v2,
345
          void *cb_data)
346
0
{
347
0
  const struct snapshot *snapshot = cb_data;
348
0
  const struct snapshot_record *e1 = v1, *e2 = v2;
349
0
  const char *r1 = e1->start + snapshot_hexsz(snapshot) + 1;
350
0
  const char *r2 = e2->start + snapshot_hexsz(snapshot) + 1;
351
352
0
  return cmp_packed_refname(r1, r2);
353
0
}
354
355
/*
356
 * Compare a snapshot record at `rec` to the specified NUL-terminated
357
 * refname.
358
 */
359
static int cmp_record_to_refname(const char *rec, const char *refname,
360
         int start, const struct snapshot *snapshot)
361
0
{
362
0
  const char *r1 = rec + snapshot_hexsz(snapshot) + 1;
363
0
  const char *r2 = refname;
364
365
0
  while (1) {
366
0
    if (*r1 == '\n')
367
0
      return *r2 ? -1 : 0;
368
0
    if (!*r2)
369
0
      return start ? 1 : -1;
370
0
    if (*r1 != *r2)
371
0
      return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
372
0
    r1++;
373
0
    r2++;
374
0
  }
375
0
}
376
377
/*
378
 * `snapshot->buf` is not known to be sorted. Check whether it is, and
379
 * if not, sort it into new memory and munmap/free the old storage.
380
 */
381
static void sort_snapshot(struct snapshot *snapshot)
382
0
{
383
0
  struct snapshot_record *records = NULL;
384
0
  size_t alloc = 0, nr = 0;
385
0
  int sorted = 1;
386
0
  const char *pos, *eof, *eol;
387
0
  size_t len, i;
388
0
  char *new_buffer, *dst;
389
390
0
  pos = snapshot->start;
391
0
  eof = snapshot->eof;
392
393
0
  if (pos == eof)
394
0
    return;
395
396
0
  len = eof - pos;
397
398
  /*
399
   * Initialize records based on a crude estimate of the number
400
   * of references in the file (we'll grow it below if needed):
401
   */
402
0
  ALLOC_GROW(records, len / 80 + 20, alloc);
403
404
0
  while (pos < eof) {
405
0
    eol = memchr(pos, '\n', eof - pos);
406
0
    if (!eol)
407
      /* The safety check should prevent this. */
408
0
      BUG("unterminated line found in packed-refs");
409
0
    if (eol - pos < snapshot_hexsz(snapshot) + 2)
410
0
      die_invalid_line(snapshot->refs->path,
411
0
           pos, eof - pos);
412
0
    eol++;
413
0
    if (eol < eof && *eol == '^') {
414
      /*
415
       * Keep any peeled line together with its
416
       * reference:
417
       */
418
0
      const char *peeled_start = eol;
419
420
0
      eol = memchr(peeled_start, '\n', eof - peeled_start);
421
0
      if (!eol)
422
        /* The safety check should prevent this. */
423
0
        BUG("unterminated peeled line found in packed-refs");
424
0
      eol++;
425
0
    }
426
427
0
    ALLOC_GROW(records, nr + 1, alloc);
428
0
    records[nr].start = pos;
429
0
    records[nr].len = eol - pos;
430
0
    nr++;
431
432
0
    if (sorted &&
433
0
        nr > 1 &&
434
0
        cmp_packed_ref_records(&records[nr - 2],
435
0
             &records[nr - 1], snapshot) >= 0)
436
0
      sorted = 0;
437
438
0
    pos = eol;
439
0
  }
440
441
0
  if (sorted)
442
0
    goto cleanup;
443
444
  /* We need to sort the memory. First we sort the records array: */
445
0
  QSORT_S(records, nr, cmp_packed_ref_records, snapshot);
446
447
  /*
448
   * Allocate a new chunk of memory, and copy the old memory to
449
   * the new in the order indicated by `records` (not bothering
450
   * with the header line):
451
   */
452
0
  new_buffer = xmalloc(len);
453
0
  for (dst = new_buffer, i = 0; i < nr; i++) {
454
0
    memcpy(dst, records[i].start, records[i].len);
455
0
    dst += records[i].len;
456
0
  }
457
458
  /*
459
   * Now munmap the old buffer and use the sorted buffer in its
460
   * place:
461
   */
462
0
  clear_snapshot_buffer(snapshot);
463
0
  snapshot->buf = snapshot->start = new_buffer;
464
0
  snapshot->eof = new_buffer + len;
465
466
0
cleanup:
467
0
  free(records);
468
0
}
469
470
/*
471
 * Return a pointer to the start of the record that contains the
472
 * character `*p` (which must be within the buffer). If no other
473
 * record start is found, return `buf`.
474
 */
475
static const char *find_start_of_record(const char *buf, const char *p)
476
0
{
477
0
  while (p > buf && (p[-1] != '\n' || p[0] == '^'))
478
0
    p--;
479
0
  return p;
480
0
}
481
482
/*
483
 * Return a pointer to the start of the record following the record
484
 * that contains `*p`. If none is found before `end`, return `end`.
485
 */
486
static const char *find_end_of_record(const char *p, const char *end)
487
0
{
488
0
  while (++p < end && (p[-1] != '\n' || p[0] == '^'))
489
0
    ;
490
0
  return p;
491
0
}
492
493
/*
494
 * We want to be able to compare mmapped reference records quickly,
495
 * without totally parsing them. We can do so because the records are
496
 * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
497
 * + 1) bytes past the beginning of the record.
498
 *
499
 * But what if the `packed-refs` file contains garbage? We're willing
500
 * to tolerate not detecting the problem, as long as we don't produce
501
 * totally garbled output (we can't afford to check the integrity of
502
 * the whole file during every Git invocation). But we do want to be
503
 * sure that we never read past the end of the buffer in memory and
504
 * perform an illegal memory access.
505
 *
506
 * Guarantee that minimum level of safety by verifying that the last
507
 * record in the file is LF-terminated, and that it has at least
508
 * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
509
 * these checks fails.
510
 */
511
static void verify_buffer_safe(struct snapshot *snapshot)
512
0
{
513
0
  const char *start = snapshot->start;
514
0
  const char *eof = snapshot->eof;
515
0
  const char *last_line;
516
517
0
  if (start == eof)
518
0
    return;
519
520
0
  last_line = find_start_of_record(start, eof - 1);
521
0
  if (*(eof - 1) != '\n' ||
522
0
      eof - last_line < snapshot_hexsz(snapshot) + 2)
523
0
    die_invalid_line(snapshot->refs->path,
524
0
         last_line, eof - last_line);
525
0
}
526
527
/*
528
 * When parsing the "packed-refs" file, we will parse it line by line.
529
 * Because we know the start pointer of the refname and the next
530
 * newline pointer, we could calculate the length of the refname by
531
 * subtracting the two pointers. However, there is a corner case where
532
 * the refname contains corrupted embedded NUL characters. And
533
 * `check_refname_format()` will not catch this when the truncated
534
 * refname is still a valid refname. To prevent this, we need to check
535
 * whether the refname contains the NUL characters.
536
 */
537
static int refname_contains_nul(struct strbuf *refname)
538
0
{
539
0
  return !!memchr(refname->buf, '\0', refname->len);
540
0
}
541
542
0
#define SMALL_FILE_SIZE (32*1024)
543
544
static int allocate_snapshot_buffer(struct snapshot *snapshot, int fd, struct stat *st)
545
0
{
546
0
  ssize_t bytes_read;
547
0
  size_t size;
548
549
0
  size = xsize_t(st->st_size);
550
0
  if (!size)
551
0
    return 0;
552
553
0
  if (mmap_strategy == MMAP_NONE || size <= SMALL_FILE_SIZE) {
554
0
    snapshot->buf = xmalloc(size);
555
0
    bytes_read = read_in_full(fd, snapshot->buf, size);
556
0
    if (bytes_read < 0 || bytes_read != size)
557
0
      die_errno("couldn't read %s", snapshot->refs->path);
558
0
    snapshot->mmapped = 0;
559
0
  } else {
560
0
    snapshot->buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
561
0
    snapshot->mmapped = 1;
562
0
  }
563
564
0
  snapshot->start = snapshot->buf;
565
0
  snapshot->eof = snapshot->buf + size;
566
567
0
  return 1;
568
0
}
569
570
/*
571
 * Depending on `mmap_strategy`, either mmap or read the contents of
572
 * the `packed-refs` file into the snapshot. Return 1 if the file
573
 * existed and was read, or 0 if the file was absent or empty. Die on
574
 * errors.
575
 */
576
static int load_contents(struct snapshot *snapshot)
577
0
{
578
0
  struct stat st;
579
0
  int ret;
580
0
  int fd;
581
582
0
  fd = open(snapshot->refs->path, O_RDONLY);
583
0
  if (fd < 0) {
584
0
    if (errno == ENOENT) {
585
      /*
586
       * This is OK; it just means that no
587
       * "packed-refs" file has been written yet,
588
       * which is equivalent to it being empty,
589
       * which is its state when initialized with
590
       * zeros.
591
       */
592
0
      return 0;
593
0
    } else {
594
0
      die_errno("couldn't read %s", snapshot->refs->path);
595
0
    }
596
0
  }
597
598
0
  stat_validity_update(&snapshot->validity, fd);
599
600
0
  if (fstat(fd, &st) < 0)
601
0
    die_errno("couldn't stat %s", snapshot->refs->path);
602
603
0
  ret = allocate_snapshot_buffer(snapshot, fd, &st);
604
605
0
  close(fd);
606
0
  return ret;
607
0
}
608
609
static const char *find_reference_location_1(struct snapshot *snapshot,
610
               const char *refname, int mustexist,
611
               int start)
612
0
{
613
  /*
614
   * This is not *quite* a garden-variety binary search, because
615
   * the data we're searching is made up of records, and we
616
   * always need to find the beginning of a record to do a
617
   * comparison. A "record" here is one line for the reference
618
   * itself and zero or one peel lines that start with '^'. Our
619
   * loop invariant is described in the next two comments.
620
   */
621
622
  /*
623
   * A pointer to the character at the start of a record whose
624
   * preceding records all have reference names that come
625
   * *before* `refname`.
626
   */
627
0
  const char *lo = snapshot->start;
628
629
  /*
630
   * A pointer to a the first character of a record whose
631
   * reference name comes *after* `refname`.
632
   */
633
0
  const char *hi = snapshot->eof;
634
635
0
  while (lo != hi) {
636
0
    const char *mid, *rec;
637
0
    int cmp;
638
639
0
    mid = lo + (hi - lo) / 2;
640
0
    rec = find_start_of_record(lo, mid);
641
0
    cmp = cmp_record_to_refname(rec, refname, start, snapshot);
642
0
    if (cmp < 0) {
643
0
      lo = find_end_of_record(mid, hi);
644
0
    } else if (cmp > 0) {
645
0
      hi = rec;
646
0
    } else {
647
0
      return rec;
648
0
    }
649
0
  }
650
651
0
  if (mustexist)
652
0
    return NULL;
653
0
  else
654
0
    return lo;
655
0
}
656
657
/*
658
 * Find the place in `snapshot->buf` where the start of the record for
659
 * `refname` starts. If `mustexist` is true and the reference doesn't
660
 * exist, then return NULL. If `mustexist` is false and the reference
661
 * doesn't exist, then return the point where that reference would be
662
 * inserted, or `snapshot->eof` (which might be NULL) if it would be
663
 * inserted at the end of the file. In the latter mode, `refname`
664
 * doesn't have to be a proper reference name; for example, one could
665
 * search for "refs/replace/" to find the start of any replace
666
 * references.
667
 *
668
 * The record is sought using a binary search, so `snapshot->buf` must
669
 * be sorted.
670
 */
671
static const char *find_reference_location(struct snapshot *snapshot,
672
             const char *refname, int mustexist)
673
0
{
674
0
  return find_reference_location_1(snapshot, refname, mustexist, 1);
675
0
}
676
677
/*
678
 * Find the place in `snapshot->buf` after the end of the record for
679
 * `refname`. In other words, find the location of first thing *after*
680
 * `refname`.
681
 *
682
 * Other semantics are identical to the ones in
683
 * `find_reference_location()`.
684
 */
685
static const char *find_reference_location_end(struct snapshot *snapshot,
686
                 const char *refname,
687
                 int mustexist)
688
0
{
689
0
  return find_reference_location_1(snapshot, refname, mustexist, 0);
690
0
}
691
692
/*
693
 * Create a newly-allocated `snapshot` of the `packed-refs` file in
694
 * its current state and return it. The return value will already have
695
 * its reference count incremented.
696
 *
697
 * A comment line of the form "# pack-refs with: " may contain zero or
698
 * more traits. We interpret the traits as follows:
699
 *
700
 *   Neither `peeled` nor `fully-peeled`:
701
 *
702
 *      Probably no references are peeled. But if the file contains a
703
 *      peeled value for a reference, we will use it.
704
 *
705
 *   `peeled`:
706
 *
707
 *      References under "refs/tags/", if they *can* be peeled, *are*
708
 *      peeled in this file. References outside of "refs/tags/" are
709
 *      probably not peeled even if they could have been, but if we find
710
 *      a peeled value for such a reference we will use it.
711
 *
712
 *   `fully-peeled`:
713
 *
714
 *      All references in the file that can be peeled are peeled.
715
 *      Inversely (and this is more important), any references in the
716
 *      file for which no peeled value is recorded is not peelable. This
717
 *      trait should typically be written alongside "peeled" for
718
 *      compatibility with older clients, but we do not require it
719
 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
720
 *
721
 *   `sorted`:
722
 *
723
 *      The references in this file are known to be sorted by refname.
724
 */
725
static struct snapshot *create_snapshot(struct packed_ref_store *refs)
726
0
{
727
0
  struct snapshot *snapshot = xcalloc(1, sizeof(*snapshot));
728
0
  int sorted = 0;
729
730
0
  snapshot->refs = refs;
731
0
  acquire_snapshot(snapshot);
732
0
  snapshot->peeled = PEELED_NONE;
733
734
0
  if (!load_contents(snapshot))
735
0
    return snapshot;
736
737
  /* If the file has a header line, process it: */
738
0
  if (snapshot->buf < snapshot->eof && *snapshot->buf == '#') {
739
0
    char *tmp, *p, *eol;
740
0
    struct string_list traits = STRING_LIST_INIT_NODUP;
741
742
0
    eol = memchr(snapshot->buf, '\n',
743
0
           snapshot->eof - snapshot->buf);
744
0
    if (!eol)
745
0
      die_unterminated_line(refs->path,
746
0
                snapshot->buf,
747
0
                snapshot->eof - snapshot->buf);
748
749
0
    tmp = xmemdupz(snapshot->buf, eol - snapshot->buf);
750
751
0
    if (!skip_prefix(tmp, "# pack-refs with: ", (const char **)&p))
752
0
      die_invalid_line(refs->path,
753
0
           snapshot->buf,
754
0
           snapshot->eof - snapshot->buf);
755
756
0
    string_list_split_in_place(&traits, p, " ", -1);
757
758
0
    if (unsorted_string_list_has_string(&traits, "fully-peeled"))
759
0
      snapshot->peeled = PEELED_FULLY;
760
0
    else if (unsorted_string_list_has_string(&traits, "peeled"))
761
0
      snapshot->peeled = PEELED_TAGS;
762
763
0
    sorted = unsorted_string_list_has_string(&traits, "sorted");
764
765
    /* perhaps other traits later as well */
766
767
    /* The "+ 1" is for the LF character. */
768
0
    snapshot->start = eol + 1;
769
770
0
    string_list_clear(&traits, 0);
771
0
    free(tmp);
772
0
  }
773
774
0
  verify_buffer_safe(snapshot);
775
776
0
  if (!sorted) {
777
0
    sort_snapshot(snapshot);
778
779
    /*
780
     * Reordering the records might have moved a short one
781
     * to the end of the buffer, so verify the buffer's
782
     * safety again:
783
     */
784
0
    verify_buffer_safe(snapshot);
785
0
  }
786
787
0
  if (mmap_strategy != MMAP_OK && snapshot->mmapped) {
788
    /*
789
     * We don't want to leave the file mmapped, so we are
790
     * forced to make a copy now:
791
     */
792
0
    size_t size = snapshot->eof - snapshot->start;
793
0
    char *buf_copy = xmalloc(size);
794
795
0
    memcpy(buf_copy, snapshot->start, size);
796
0
    clear_snapshot_buffer(snapshot);
797
0
    snapshot->buf = snapshot->start = buf_copy;
798
0
    snapshot->eof = buf_copy + size;
799
0
  }
800
801
0
  return snapshot;
802
0
}
803
804
/*
805
 * Check that `refs->snapshot` (if present) still reflects the
806
 * contents of the `packed-refs` file. If not, clear the snapshot.
807
 */
808
static void validate_snapshot(struct packed_ref_store *refs)
809
0
{
810
0
  if (refs->snapshot &&
811
0
      !stat_validity_check(&refs->snapshot->validity, refs->path))
812
0
    clear_snapshot(refs);
813
0
}
814
815
/*
816
 * Get the `snapshot` for the specified packed_ref_store, creating and
817
 * populating it if it hasn't been read before or if the file has been
818
 * changed (according to its `validity` field) since it was last read.
819
 * On the other hand, if we hold the lock, then assume that the file
820
 * hasn't been changed out from under us, so skip the extra `stat()`
821
 * call in `stat_validity_check()`. This function does *not* increase
822
 * the snapshot's reference count on behalf of the caller.
823
 */
824
static struct snapshot *get_snapshot(struct packed_ref_store *refs)
825
0
{
826
0
  if (!is_lock_file_locked(&refs->lock))
827
0
    validate_snapshot(refs);
828
829
0
  if (!refs->snapshot)
830
0
    refs->snapshot = create_snapshot(refs);
831
832
0
  return refs->snapshot;
833
0
}
834
835
static int packed_read_raw_ref(struct ref_store *ref_store, const char *refname,
836
             struct object_id *oid, struct strbuf *referent UNUSED,
837
             unsigned int *type, int *failure_errno)
838
0
{
839
0
  struct packed_ref_store *refs =
840
0
    packed_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
841
0
  struct snapshot *snapshot = get_snapshot(refs);
842
0
  const char *rec;
843
844
0
  *type = 0;
845
846
0
  rec = find_reference_location(snapshot, refname, 1);
847
848
0
  if (!rec) {
849
    /* refname is not a packed reference. */
850
0
    *failure_errno = ENOENT;
851
0
    return -1;
852
0
  }
853
854
0
  if (get_oid_hex_algop(rec, oid, ref_store->repo->hash_algo))
855
0
    die_invalid_line(refs->path, rec, snapshot->eof - rec);
856
857
0
  *type = REF_ISPACKED;
858
0
  return 0;
859
0
}
860
861
/*
862
 * This value is set in `base.flags` if the peeled value of the
863
 * current reference is known. In that case, `peeled` contains the
864
 * correct peeled value for the reference, which might be `null_oid`
865
 * if the reference is not a tag or if it is broken.
866
 */
867
0
#define REF_KNOWS_PEELED 0x40
868
869
/*
870
 * An iterator over a snapshot of a `packed-refs` file.
871
 */
872
struct packed_ref_iterator {
873
  struct ref_iterator base;
874
875
  struct snapshot *snapshot;
876
877
  char *prefix;
878
879
  /* The current position in the snapshot's buffer: */
880
  const char *pos;
881
882
  /* The end of the part of the buffer that will be iterated over: */
883
  const char *eof;
884
885
  struct jump_list_entry {
886
    const char *start;
887
    const char *end;
888
  } *jump;
889
  size_t jump_nr, jump_alloc;
890
  size_t jump_cur;
891
892
  /* Scratch space for current values: */
893
  struct object_id oid, peeled;
894
  struct strbuf refname_buf;
895
896
  struct repository *repo;
897
  unsigned int flags;
898
};
899
900
/*
901
 * Move the iterator to the next record in the snapshot. Adjust the fields in
902
 * `iter` and return `ITER_OK` or `ITER_DONE`. This function does not free the
903
 * iterator in the case of `ITER_DONE`.
904
 */
905
static int next_record(struct packed_ref_iterator *iter)
906
0
{
907
0
  const char *p, *eol;
908
909
0
  memset(&iter->base.ref, 0, sizeof(iter->base.ref));
910
0
  strbuf_reset(&iter->refname_buf);
911
912
  /*
913
   * If iter->pos is contained within a skipped region, jump past
914
   * it.
915
   *
916
   * Note that each skipped region is considered at most once,
917
   * since they are ordered based on their starting position.
918
   */
919
0
  while (iter->jump_cur < iter->jump_nr) {
920
0
    struct jump_list_entry *curr = &iter->jump[iter->jump_cur];
921
0
    if (iter->pos < curr->start)
922
0
      break; /* not to the next jump yet */
923
924
0
    iter->jump_cur++;
925
0
    if (iter->pos < curr->end) {
926
0
      iter->pos = curr->end;
927
0
      trace2_counter_add(TRACE2_COUNTER_ID_PACKED_REFS_JUMPS, 1);
928
      /* jumps are coalesced, so only one jump is necessary */
929
0
      break;
930
0
    }
931
0
  }
932
933
0
  if (iter->pos == iter->eof)
934
0
    return ITER_DONE;
935
936
0
  iter->base.ref.flags = REF_ISPACKED;
937
0
  p = iter->pos;
938
939
0
  if (iter->eof - p < snapshot_hexsz(iter->snapshot) + 2 ||
940
0
      parse_oid_hex_algop(p, &iter->oid, &p, iter->repo->hash_algo) ||
941
0
      !isspace(*p++))
942
0
    die_invalid_line(iter->snapshot->refs->path,
943
0
         iter->pos, iter->eof - iter->pos);
944
0
  iter->base.ref.oid = &iter->oid;
945
946
0
  eol = memchr(p, '\n', iter->eof - p);
947
0
  if (!eol)
948
0
    die_unterminated_line(iter->snapshot->refs->path,
949
0
              iter->pos, iter->eof - iter->pos);
950
951
0
  strbuf_add(&iter->refname_buf, p, eol - p);
952
0
  iter->base.ref.name = iter->refname_buf.buf;
953
954
0
  if (refname_contains_nul(&iter->refname_buf))
955
0
    die("packed refname contains embedded NULL: %s", iter->base.ref.name);
956
957
0
  if (check_refname_format(iter->base.ref.name, REFNAME_ALLOW_ONELEVEL)) {
958
0
    if (!refname_is_safe(iter->base.ref.name))
959
0
      die("packed refname is dangerous: %s",
960
0
          iter->base.ref.name);
961
0
    oidclr(&iter->oid, iter->repo->hash_algo);
962
0
    iter->base.ref.flags |= REF_BAD_NAME | REF_ISBROKEN;
963
0
  }
964
0
  if (iter->snapshot->peeled == PEELED_FULLY ||
965
0
      (iter->snapshot->peeled == PEELED_TAGS &&
966
0
       starts_with(iter->base.ref.name, "refs/tags/")))
967
0
    iter->base.ref.flags |= REF_KNOWS_PEELED;
968
969
0
  iter->pos = eol + 1;
970
971
0
  if (iter->pos < iter->eof && *iter->pos == '^') {
972
0
    p = iter->pos + 1;
973
0
    if (iter->eof - p < snapshot_hexsz(iter->snapshot) + 1 ||
974
0
        parse_oid_hex_algop(p, &iter->peeled, &p, iter->repo->hash_algo) ||
975
0
        *p++ != '\n')
976
0
      die_invalid_line(iter->snapshot->refs->path,
977
0
           iter->pos, iter->eof - iter->pos);
978
0
    iter->pos = p;
979
980
    /*
981
     * Regardless of what the file header said, we
982
     * definitely know the value of *this* reference. But
983
     * we suppress it if the reference is broken:
984
     */
985
0
    if ((iter->base.ref.flags & REF_ISBROKEN)) {
986
0
      oidclr(&iter->peeled, iter->repo->hash_algo);
987
0
      iter->base.ref.flags &= ~REF_KNOWS_PEELED;
988
0
    } else {
989
0
      iter->base.ref.flags |= REF_KNOWS_PEELED;
990
0
      iter->base.ref.peeled_oid = &iter->peeled;
991
0
    }
992
0
  } else {
993
0
    oidclr(&iter->peeled, iter->repo->hash_algo);
994
0
  }
995
996
0
  return ITER_OK;
997
0
}
998
999
static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
1000
0
{
1001
0
  struct packed_ref_iterator *iter =
1002
0
    (struct packed_ref_iterator *)ref_iterator;
1003
0
  int ok;
1004
1005
0
  while ((ok = next_record(iter)) == ITER_OK) {
1006
0
    const char *refname = iter->base.ref.name;
1007
0
    const char *prefix = iter->prefix;
1008
1009
0
    if (iter->flags & REFS_FOR_EACH_PER_WORKTREE_ONLY &&
1010
0
        !is_per_worktree_ref(iter->base.ref.name))
1011
0
      continue;
1012
1013
0
    if (!(iter->flags & REFS_FOR_EACH_INCLUDE_BROKEN) &&
1014
0
        !ref_resolves_to_object(iter->base.ref.name, iter->repo,
1015
0
              &iter->oid, iter->flags))
1016
0
      continue;
1017
1018
0
    while (prefix && *prefix) {
1019
0
      if ((unsigned char)*refname < (unsigned char)*prefix)
1020
0
        BUG("packed-refs backend yielded reference preceding its prefix");
1021
0
      else if ((unsigned char)*refname > (unsigned char)*prefix)
1022
0
        return ITER_DONE;
1023
0
      prefix++;
1024
0
      refname++;
1025
0
    }
1026
1027
0
    return ITER_OK;
1028
0
  }
1029
1030
0
  return ok;
1031
0
}
1032
1033
static int packed_ref_iterator_seek(struct ref_iterator *ref_iterator,
1034
            const char *refname, unsigned int flags)
1035
0
{
1036
0
  struct packed_ref_iterator *iter =
1037
0
    (struct packed_ref_iterator *)ref_iterator;
1038
0
  const char *start;
1039
1040
0
  if (refname && *refname)
1041
0
    start = find_reference_location(iter->snapshot, refname, 0);
1042
0
  else
1043
0
    start = iter->snapshot->start;
1044
1045
  /* Unset any previously set prefix */
1046
0
  FREE_AND_NULL(iter->prefix);
1047
1048
0
  if (flags & REF_ITERATOR_SEEK_SET_PREFIX)
1049
0
    iter->prefix = xstrdup_or_null(refname);
1050
1051
0
  iter->pos = start;
1052
0
  iter->eof = iter->snapshot->eof;
1053
1054
0
  return 0;
1055
0
}
1056
1057
static void packed_ref_iterator_release(struct ref_iterator *ref_iterator)
1058
0
{
1059
0
  struct packed_ref_iterator *iter =
1060
0
    (struct packed_ref_iterator *)ref_iterator;
1061
0
  strbuf_release(&iter->refname_buf);
1062
0
  free(iter->jump);
1063
0
  free(iter->prefix);
1064
0
  release_snapshot(iter->snapshot);
1065
0
}
1066
1067
static struct ref_iterator_vtable packed_ref_iterator_vtable = {
1068
  .advance = packed_ref_iterator_advance,
1069
  .seek = packed_ref_iterator_seek,
1070
  .release = packed_ref_iterator_release,
1071
};
1072
1073
static int jump_list_entry_cmp(const void *va, const void *vb)
1074
0
{
1075
0
  const struct jump_list_entry *a = va;
1076
0
  const struct jump_list_entry *b = vb;
1077
1078
0
  if (a->start < b->start)
1079
0
    return -1;
1080
0
  if (a->start > b->start)
1081
0
    return 1;
1082
0
  return 0;
1083
0
}
1084
1085
static int has_glob_special(const char *str)
1086
0
{
1087
0
  const char *p;
1088
0
  for (p = str; *p; p++) {
1089
0
    if (is_glob_special(*p))
1090
0
      return 1;
1091
0
  }
1092
0
  return 0;
1093
0
}
1094
1095
static void populate_excluded_jump_list(struct packed_ref_iterator *iter,
1096
          struct snapshot *snapshot,
1097
          const char **excluded_patterns)
1098
0
{
1099
0
  size_t i, j;
1100
0
  const char **pattern;
1101
0
  struct jump_list_entry *last_disjoint;
1102
1103
0
  if (!excluded_patterns)
1104
0
    return;
1105
1106
0
  for (pattern = excluded_patterns; *pattern; pattern++) {
1107
0
    struct jump_list_entry *e;
1108
0
    const char *start, *end;
1109
1110
    /*
1111
     * We can't feed any excludes with globs in them to the
1112
     * refs machinery.  It only understands prefix matching.
1113
     * We likewise can't even feed the string leading up to
1114
     * the first meta-character, as something like "foo[a]"
1115
     * should not exclude "foobar" (but the prefix "foo"
1116
     * would match that and mark it for exclusion).
1117
     */
1118
0
    if (has_glob_special(*pattern))
1119
0
      continue;
1120
1121
0
    start = find_reference_location(snapshot, *pattern, 0);
1122
0
    end = find_reference_location_end(snapshot, *pattern, 0);
1123
1124
0
    if (start == end)
1125
0
      continue; /* nothing to jump over */
1126
1127
0
    ALLOC_GROW(iter->jump, iter->jump_nr + 1, iter->jump_alloc);
1128
1129
0
    e = &iter->jump[iter->jump_nr++];
1130
0
    e->start = start;
1131
0
    e->end = end;
1132
0
  }
1133
1134
0
  if (!iter->jump_nr) {
1135
    /*
1136
     * Every entry in exclude_patterns has a meta-character,
1137
     * nothing to do here.
1138
     */
1139
0
    return;
1140
0
  }
1141
1142
0
  QSORT(iter->jump, iter->jump_nr, jump_list_entry_cmp);
1143
1144
  /*
1145
   * As an optimization, merge adjacent entries in the jump list
1146
   * to jump forwards as far as possible when entering a skipped
1147
   * region.
1148
   *
1149
   * For example, if we have two skipped regions:
1150
   *
1151
   *  [[A, B], [B, C]]
1152
   *
1153
   * we want to combine that into a single entry jumping from A to
1154
   * C.
1155
   */
1156
0
  last_disjoint = iter->jump;
1157
1158
0
  for (i = 1, j = 1; i < iter->jump_nr; i++) {
1159
0
    struct jump_list_entry *ours = &iter->jump[i];
1160
0
    if (ours->start <= last_disjoint->end) {
1161
      /* overlapping regions extend the previous one */
1162
0
      last_disjoint->end = last_disjoint->end > ours->end
1163
0
        ? last_disjoint->end : ours->end;
1164
0
    } else {
1165
      /* otherwise, insert a new region */
1166
0
      iter->jump[j++] = *ours;
1167
0
      last_disjoint = ours;
1168
0
    }
1169
0
  }
1170
1171
0
  iter->jump_nr = j;
1172
0
  iter->jump_cur = 0;
1173
0
}
1174
1175
static struct ref_iterator *packed_ref_iterator_begin(
1176
    struct ref_store *ref_store,
1177
    const char *prefix, const char **exclude_patterns,
1178
    unsigned int flags)
1179
0
{
1180
0
  struct packed_ref_store *refs;
1181
0
  struct snapshot *snapshot;
1182
0
  struct packed_ref_iterator *iter;
1183
0
  struct ref_iterator *ref_iterator;
1184
0
  unsigned int required_flags = REF_STORE_READ;
1185
1186
0
  if (!(flags & REFS_FOR_EACH_INCLUDE_BROKEN))
1187
0
    required_flags |= REF_STORE_ODB;
1188
0
  refs = packed_downcast(ref_store, required_flags, "ref_iterator_begin");
1189
1190
  /*
1191
   * Note that `get_snapshot()` internally checks whether the
1192
   * snapshot is up to date with what is on disk, and re-reads
1193
   * it if not.
1194
   */
1195
0
  snapshot = get_snapshot(refs);
1196
1197
0
  CALLOC_ARRAY(iter, 1);
1198
0
  ref_iterator = &iter->base;
1199
0
  base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable);
1200
1201
0
  if (exclude_patterns)
1202
0
    populate_excluded_jump_list(iter, snapshot, exclude_patterns);
1203
1204
0
  iter->snapshot = snapshot;
1205
0
  acquire_snapshot(snapshot);
1206
0
  strbuf_init(&iter->refname_buf, 0);
1207
0
  iter->repo = ref_store->repo;
1208
0
  iter->flags = flags;
1209
1210
0
  if (packed_ref_iterator_seek(&iter->base, prefix,
1211
0
             REF_ITERATOR_SEEK_SET_PREFIX) < 0) {
1212
0
    ref_iterator_free(&iter->base);
1213
0
    return NULL;
1214
0
  }
1215
1216
0
  return ref_iterator;
1217
0
}
1218
1219
/*
1220
 * Write an entry to the packed-refs file for the specified refname.
1221
 * If peeled is non-NULL, write it as the entry's peeled value. On
1222
 * error, return a nonzero value and leave errno set at the value left
1223
 * by the failing call to `fprintf()`.
1224
 */
1225
static int write_packed_entry(FILE *fh, const char *refname,
1226
            const struct object_id *oid,
1227
            const struct object_id *peeled)
1228
0
{
1229
0
  if (fprintf(fh, "%s %s\n", oid_to_hex(oid), refname) < 0 ||
1230
0
      (peeled && fprintf(fh, "^%s\n", oid_to_hex(peeled)) < 0))
1231
0
    return -1;
1232
1233
0
  return 0;
1234
0
}
1235
1236
int packed_refs_lock(struct ref_store *ref_store, int flags, struct strbuf *err)
1237
0
{
1238
0
  struct packed_ref_store *refs =
1239
0
    packed_downcast(ref_store, REF_STORE_WRITE | REF_STORE_MAIN,
1240
0
        "packed_refs_lock");
1241
1242
0
  if (!refs->timeout_configured) {
1243
0
    if (repo_config_get_int(ref_store->repo, "core.packedrefstimeout",
1244
0
          &refs->timeout_value))
1245
0
      refs->timeout_value = 1000;
1246
0
    refs->timeout_configured = true;
1247
0
  }
1248
1249
  /*
1250
   * Note that we close the lockfile immediately because we
1251
   * don't write new content to it, but rather to a separate
1252
   * tempfile.
1253
   */
1254
0
  if (repo_hold_lock_file_for_update_timeout(ref_store->repo, &refs->lock,
1255
0
               refs->path, flags,
1256
0
               refs->timeout_value) < 0) {
1257
0
    unable_to_lock_message(refs->path, errno, err);
1258
0
    return -1;
1259
0
  }
1260
1261
0
  if (close_lock_file_gently(&refs->lock)) {
1262
0
    strbuf_addf(err, "unable to close %s: %s", refs->path, strerror(errno));
1263
0
    rollback_lock_file(&refs->lock);
1264
0
    return -1;
1265
0
  }
1266
1267
  /*
1268
   * There is a stat-validity problem might cause `update-ref -d`
1269
   * lost the newly commit of a ref, because a new `packed-refs`
1270
   * file might has the same on-disk file attributes such as
1271
   * timestamp, file size and inode value, but has a changed
1272
   * ref value.
1273
   *
1274
   * This could happen with a very small chance when
1275
   * `update-ref -d` is called and at the same time another
1276
   * `pack-refs --all` process is running.
1277
   *
1278
   * Now that we hold the `packed-refs` lock, it is important
1279
   * to make sure we could read the latest version of
1280
   * `packed-refs` file no matter we have just mmap it or not.
1281
   * So what need to do is clear the snapshot if we hold it
1282
   * already.
1283
   */
1284
0
  clear_snapshot(refs);
1285
1286
  /*
1287
   * Now make sure that the packed-refs file as it exists in the
1288
   * locked state is loaded into the snapshot:
1289
   */
1290
0
  get_snapshot(refs);
1291
0
  return 0;
1292
0
}
1293
1294
void packed_refs_unlock(struct ref_store *ref_store)
1295
0
{
1296
0
  struct packed_ref_store *refs = packed_downcast(
1297
0
      ref_store,
1298
0
      REF_STORE_READ | REF_STORE_WRITE,
1299
0
      "packed_refs_unlock");
1300
1301
0
  if (!is_lock_file_locked(&refs->lock))
1302
0
    BUG("packed_refs_unlock() called when not locked");
1303
0
  rollback_lock_file(&refs->lock);
1304
0
}
1305
1306
int packed_refs_is_locked(struct ref_store *ref_store)
1307
0
{
1308
0
  struct packed_ref_store *refs = packed_downcast(
1309
0
      ref_store,
1310
0
      REF_STORE_READ | REF_STORE_WRITE,
1311
0
      "packed_refs_is_locked");
1312
1313
0
  return is_lock_file_locked(&refs->lock);
1314
0
}
1315
1316
int packed_refs_size(struct ref_store *ref_store,
1317
         size_t *out)
1318
0
{
1319
0
  struct packed_ref_store *refs = packed_downcast(ref_store, REF_STORE_READ,
1320
0
              "packed_refs_size");
1321
0
  struct stat st;
1322
1323
0
  if (stat(refs->path, &st) < 0) {
1324
0
    if (errno != ENOENT)
1325
0
      return -1;
1326
0
    *out = 0;
1327
0
    return 0;
1328
0
  }
1329
1330
0
  *out = st.st_size;
1331
0
  return 0;
1332
0
}
1333
1334
/*
1335
 * The packed-refs header line that we write out. Perhaps other traits
1336
 * will be added later.
1337
 *
1338
 * Note that earlier versions of Git used to parse these traits by
1339
 * looking for " trait " in the line. For this reason, the space after
1340
 * the colon and the trailing space are required.
1341
 */
1342
static const char PACKED_REFS_HEADER[] =
1343
  "# pack-refs with: peeled fully-peeled sorted \n";
1344
1345
static int packed_ref_store_create_on_disk(struct ref_store *ref_store UNUSED,
1346
             int flags UNUSED,
1347
             struct strbuf *err UNUSED)
1348
0
{
1349
  /* Nothing to do. */
1350
0
  return 0;
1351
0
}
1352
1353
static int packed_ref_store_remove_on_disk(struct ref_store *ref_store,
1354
             struct strbuf *err)
1355
0
{
1356
0
  struct packed_ref_store *refs = packed_downcast(ref_store, 0, "remove");
1357
1358
0
  if (remove_path(refs->path) < 0) {
1359
0
    strbuf_addstr(err, "could not delete packed-refs");
1360
0
    return -1;
1361
0
  }
1362
1363
0
  return 0;
1364
0
}
1365
1366
/*
1367
 * Write the packed refs from the current snapshot to the packed-refs
1368
 * tempfile, incorporating any changes from `updates`. `updates` must
1369
 * be a sorted string list whose keys are the refnames and whose util
1370
 * values are `struct ref_update *`. On error, rollback the tempfile,
1371
 * write an error message to `err`, and return a nonzero value.
1372
 *
1373
 * The packfile must be locked before calling this function and will
1374
 * remain locked when it is done.
1375
 */
1376
static enum ref_transaction_error write_with_updates(struct packed_ref_store *refs,
1377
                 struct ref_transaction *transaction,
1378
                 struct strbuf *err)
1379
0
{
1380
0
  enum ref_transaction_error ret = REF_TRANSACTION_ERROR_GENERIC;
1381
0
  struct string_list *updates = &transaction->refnames;
1382
0
  struct ref_iterator *iter = NULL;
1383
0
  size_t i;
1384
0
  int ok;
1385
0
  FILE *out;
1386
0
  struct strbuf sb = STRBUF_INIT;
1387
0
  char *packed_refs_path;
1388
1389
0
  if (!is_lock_file_locked(&refs->lock))
1390
0
    BUG("write_with_updates() called while unlocked");
1391
1392
  /*
1393
   * If packed-refs is a symlink, we want to overwrite the
1394
   * symlinked-to file, not the symlink itself. Also, put the
1395
   * staging file next to it:
1396
   */
1397
0
  packed_refs_path = get_locked_file_path(&refs->lock);
1398
0
  strbuf_addf(&sb, "%s.new", packed_refs_path);
1399
0
  free(packed_refs_path);
1400
0
  refs->tempfile = repo_create_tempfile(refs->base.repo, sb.buf);
1401
0
  if (!refs->tempfile) {
1402
0
    strbuf_addf(err, "unable to create file %s: %s",
1403
0
          sb.buf, strerror(errno));
1404
0
    strbuf_release(&sb);
1405
0
    return REF_TRANSACTION_ERROR_GENERIC;
1406
0
  }
1407
0
  strbuf_release(&sb);
1408
1409
0
  out = fdopen_tempfile(refs->tempfile, "w");
1410
0
  if (!out) {
1411
0
    strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
1412
0
          strerror(errno));
1413
0
    goto error;
1414
0
  }
1415
1416
0
  if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
1417
0
    goto write_error;
1418
1419
  /*
1420
   * We iterate in parallel through the current list of refs and
1421
   * the list of updates, processing an entry from at least one
1422
   * of the lists each time through the loop. When the current
1423
   * list of refs is exhausted, set iter to NULL. When the list
1424
   * of updates is exhausted, leave i set to updates->nr.
1425
   */
1426
0
  iter = packed_ref_iterator_begin(&refs->base, "", NULL,
1427
0
           REFS_FOR_EACH_INCLUDE_BROKEN);
1428
0
  if ((ok = ref_iterator_advance(iter)) != ITER_OK) {
1429
0
    ref_iterator_free(iter);
1430
0
    iter = NULL;
1431
0
  }
1432
1433
0
  i = 0;
1434
1435
0
  while (iter || i < updates->nr) {
1436
0
    struct ref_update *update = NULL;
1437
0
    int cmp;
1438
1439
0
    if (i >= updates->nr) {
1440
0
      cmp = -1;
1441
0
    } else {
1442
0
      update = updates->items[i].util;
1443
1444
0
      if (!iter)
1445
0
        cmp = +1;
1446
0
      else
1447
0
        cmp = strcmp(iter->ref.name, update->refname);
1448
0
    }
1449
1450
0
    if (!cmp) {
1451
      /*
1452
       * There is both an old value and an update
1453
       * for this reference. Check the old value if
1454
       * necessary:
1455
       */
1456
0
      if ((update->flags & REF_HAVE_OLD)) {
1457
0
        if (is_null_oid(&update->old_oid)) {
1458
0
          strbuf_addf(err, "cannot update ref '%s': "
1459
0
                "reference already exists",
1460
0
                update->refname);
1461
0
          ret = REF_TRANSACTION_ERROR_CREATE_EXISTS;
1462
1463
0
          if (ref_transaction_maybe_set_rejected(transaction, i,
1464
0
                         ret, err)) {
1465
0
            ret = 0;
1466
0
            continue;
1467
0
          }
1468
1469
0
          goto error;
1470
0
        } else if (!oideq(&update->old_oid, iter->ref.oid)) {
1471
0
          strbuf_addf(err, "cannot update ref '%s': "
1472
0
                "is at %s but expected %s",
1473
0
                update->refname,
1474
0
                oid_to_hex(iter->ref.oid),
1475
0
                oid_to_hex(&update->old_oid));
1476
0
          ret = REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE;
1477
1478
0
          if (ref_transaction_maybe_set_rejected(transaction, i,
1479
0
                         ret, err)) {
1480
0
            ret = 0;
1481
0
            continue;
1482
0
          }
1483
1484
0
          goto error;
1485
0
        }
1486
0
      }
1487
1488
      /* Now figure out what to use for the new value: */
1489
0
      if ((update->flags & REF_HAVE_NEW)) {
1490
        /*
1491
         * The update takes precedence. Skip
1492
         * the iterator over the unneeded
1493
         * value.
1494
         */
1495
0
        if ((ok = ref_iterator_advance(iter)) != ITER_OK) {
1496
0
          ref_iterator_free(iter);
1497
0
          iter = NULL;
1498
0
        }
1499
0
        cmp = +1;
1500
0
      } else {
1501
        /*
1502
         * The update doesn't actually want to
1503
         * change anything. We're done with it.
1504
         */
1505
0
        i++;
1506
0
        cmp = -1;
1507
0
      }
1508
0
    } else if (cmp > 0) {
1509
      /*
1510
       * There is no old value but there is an
1511
       * update for this reference. Make sure that
1512
       * the update didn't expect an existing value:
1513
       */
1514
0
      if ((update->flags & REF_HAVE_OLD) &&
1515
0
          !is_null_oid(&update->old_oid)) {
1516
0
        strbuf_addf(err, "cannot update ref '%s': "
1517
0
              "reference is missing but expected %s",
1518
0
              update->refname,
1519
0
              oid_to_hex(&update->old_oid));
1520
0
        ret = REF_TRANSACTION_ERROR_NONEXISTENT_REF;
1521
1522
0
        if (ref_transaction_maybe_set_rejected(transaction, i,
1523
0
                       ret, err)) {
1524
0
          ret = 0;
1525
0
          continue;
1526
0
        }
1527
1528
0
        goto error;
1529
0
      }
1530
0
    }
1531
1532
0
    if (cmp < 0) {
1533
      /* Pass the old reference through. */
1534
0
      if (write_packed_entry(out, iter->ref.name,
1535
0
                 iter->ref.oid, iter->ref.peeled_oid))
1536
0
        goto write_error;
1537
1538
0
      if ((ok = ref_iterator_advance(iter)) != ITER_OK) {
1539
0
        ref_iterator_free(iter);
1540
0
        iter = NULL;
1541
0
      }
1542
0
    } else if (is_null_oid(&update->new_oid)) {
1543
      /*
1544
       * The update wants to delete the reference,
1545
       * and the reference either didn't exist or we
1546
       * have already skipped it. So we're done with
1547
       * the update (and don't have to write
1548
       * anything).
1549
       */
1550
0
      i++;
1551
0
    } else {
1552
0
      bool peeled = update->flags & REF_HAVE_PEELED;
1553
1554
0
      if (write_packed_entry(out, update->refname,
1555
0
                 &update->new_oid,
1556
0
                 peeled ? &update->peeled : NULL))
1557
0
        goto write_error;
1558
1559
0
      i++;
1560
0
    }
1561
0
  }
1562
1563
0
  if (ok != ITER_DONE) {
1564
0
    strbuf_addstr(err, "unable to write packed-refs file: "
1565
0
            "error iterating over old contents");
1566
0
    goto error;
1567
0
  }
1568
1569
0
  if (fflush(out) ||
1570
0
      fsync_component(FSYNC_COMPONENT_REFERENCE, get_tempfile_fd(refs->tempfile)) ||
1571
0
      close_tempfile_gently(refs->tempfile)) {
1572
0
    strbuf_addf(err, "error closing file %s: %s",
1573
0
          get_tempfile_path(refs->tempfile),
1574
0
          strerror(errno));
1575
0
    strbuf_release(&sb);
1576
0
    delete_tempfile(&refs->tempfile);
1577
0
    return REF_TRANSACTION_ERROR_GENERIC;
1578
0
  }
1579
1580
0
  return 0;
1581
1582
0
write_error:
1583
0
  strbuf_addf(err, "error writing to %s: %s",
1584
0
        get_tempfile_path(refs->tempfile), strerror(errno));
1585
0
  ret = REF_TRANSACTION_ERROR_GENERIC;
1586
1587
0
error:
1588
0
  ref_iterator_free(iter);
1589
0
  delete_tempfile(&refs->tempfile);
1590
0
  return ret;
1591
0
}
1592
1593
int is_packed_transaction_needed(struct ref_store *ref_store,
1594
         struct ref_transaction *transaction)
1595
0
{
1596
0
  struct packed_ref_store *refs = packed_downcast(
1597
0
      ref_store,
1598
0
      REF_STORE_READ,
1599
0
      "is_packed_transaction_needed");
1600
0
  struct strbuf referent = STRBUF_INIT;
1601
0
  size_t i;
1602
0
  int ret;
1603
1604
0
  if (!is_lock_file_locked(&refs->lock))
1605
0
    BUG("is_packed_transaction_needed() called while unlocked");
1606
1607
  /*
1608
   * We're only going to bother returning false for the common,
1609
   * trivial case that references are only being deleted, their
1610
   * old values are not being checked, and the old `packed-refs`
1611
   * file doesn't contain any of those reference(s). This gives
1612
   * false positives for some other cases that could
1613
   * theoretically be optimized away:
1614
   *
1615
   * 1. It could be that the old value is being verified without
1616
   *    setting a new value. In this case, we could verify the
1617
   *    old value here and skip the update if it agrees. If it
1618
   *    disagrees, we could either let the update go through
1619
   *    (the actual commit would re-detect and report the
1620
   *    problem), or come up with a way of reporting such an
1621
   *    error to *our* caller.
1622
   *
1623
   * 2. It could be that a new value is being set, but that it
1624
   *    is identical to the current packed value of the
1625
   *    reference.
1626
   *
1627
   * Neither of these cases will come up in the current code,
1628
   * because the only caller of this function passes to it a
1629
   * transaction that only includes `delete` updates with no
1630
   * `old_id`. Even if that ever changes, false positives only
1631
   * cause an optimization to be missed; they do not affect
1632
   * correctness.
1633
   */
1634
1635
  /*
1636
   * Start with the cheap checks that don't require old
1637
   * reference values to be read:
1638
   */
1639
0
  for (i = 0; i < transaction->nr; i++) {
1640
0
    struct ref_update *update = transaction->updates[i];
1641
1642
0
    if (update->flags & REF_HAVE_OLD)
1643
      /* Have to check the old value -> needed. */
1644
0
      return 1;
1645
1646
0
    if ((update->flags & REF_HAVE_NEW) && !is_null_oid(&update->new_oid))
1647
      /* Have to set a new value -> needed. */
1648
0
      return 1;
1649
0
  }
1650
1651
  /*
1652
   * The transaction isn't checking any old values nor is it
1653
   * setting any nonzero new values, so it still might be able
1654
   * to be skipped. Now do the more expensive check: the update
1655
   * is needed if any of the updates is a delete, and the old
1656
   * `packed-refs` file contains a value for that reference.
1657
   */
1658
0
  ret = 0;
1659
0
  for (i = 0; i < transaction->nr; i++) {
1660
0
    struct ref_update *update = transaction->updates[i];
1661
0
    int failure_errno;
1662
0
    unsigned int type;
1663
0
    struct object_id oid;
1664
1665
0
    if (!(update->flags & REF_HAVE_NEW))
1666
      /*
1667
       * This reference isn't being deleted -> not
1668
       * needed.
1669
       */
1670
0
      continue;
1671
1672
0
    if (!refs_read_raw_ref(ref_store, update->refname, &oid,
1673
0
               &referent, &type, &failure_errno) ||
1674
0
        failure_errno != ENOENT) {
1675
      /*
1676
       * We have to actually delete that reference
1677
       * -> this transaction is needed.
1678
       */
1679
0
      ret = 1;
1680
0
      break;
1681
0
    }
1682
0
  }
1683
1684
0
  strbuf_release(&referent);
1685
0
  return ret;
1686
0
}
1687
1688
struct packed_transaction_backend_data {
1689
  /* True iff the transaction owns the packed-refs lock. */
1690
  int own_lock;
1691
};
1692
1693
static void packed_transaction_cleanup(struct packed_ref_store *refs,
1694
               struct ref_transaction *transaction)
1695
0
{
1696
0
  struct packed_transaction_backend_data *data = transaction->backend_data;
1697
1698
0
  if (data) {
1699
0
    if (is_tempfile_active(refs->tempfile))
1700
0
      delete_tempfile(&refs->tempfile);
1701
1702
0
    if (data->own_lock && is_lock_file_locked(&refs->lock)) {
1703
0
      packed_refs_unlock(&refs->base);
1704
0
      data->own_lock = 0;
1705
0
    }
1706
1707
0
    free(data);
1708
0
    transaction->backend_data = NULL;
1709
0
  }
1710
1711
0
  transaction->state = REF_TRANSACTION_CLOSED;
1712
0
}
1713
1714
static int packed_transaction_prepare(struct ref_store *ref_store,
1715
              struct ref_transaction *transaction,
1716
              struct strbuf *err)
1717
0
{
1718
0
  struct packed_ref_store *refs = packed_downcast(
1719
0
      ref_store,
1720
0
      REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1721
0
      "ref_transaction_prepare");
1722
0
  struct packed_transaction_backend_data *data;
1723
0
  enum ref_transaction_error ret = REF_TRANSACTION_ERROR_GENERIC;
1724
1725
  /*
1726
   * Note that we *don't* skip transactions with zero updates,
1727
   * because such a transaction might be executed for the side
1728
   * effect of ensuring that all of the references are peeled or
1729
   * ensuring that the `packed-refs` file is sorted. If the
1730
   * caller wants to optimize away empty transactions, it should
1731
   * do so itself.
1732
   */
1733
1734
0
  CALLOC_ARRAY(data, 1);
1735
1736
0
  transaction->backend_data = data;
1737
1738
0
  if (!is_lock_file_locked(&refs->lock)) {
1739
0
    if (packed_refs_lock(ref_store, 0, err))
1740
0
      goto failure;
1741
0
    data->own_lock = 1;
1742
0
  }
1743
1744
0
  ret = write_with_updates(refs, transaction, err);
1745
0
  if (ret)
1746
0
    goto failure;
1747
1748
0
  transaction->state = REF_TRANSACTION_PREPARED;
1749
0
  return 0;
1750
1751
0
failure:
1752
0
  packed_transaction_cleanup(refs, transaction);
1753
0
  return ret;
1754
0
}
1755
1756
static int packed_transaction_abort(struct ref_store *ref_store,
1757
            struct ref_transaction *transaction,
1758
            struct strbuf *err UNUSED)
1759
0
{
1760
0
  struct packed_ref_store *refs = packed_downcast(
1761
0
      ref_store,
1762
0
      REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1763
0
      "ref_transaction_abort");
1764
1765
0
  packed_transaction_cleanup(refs, transaction);
1766
0
  return 0;
1767
0
}
1768
1769
static int packed_transaction_finish(struct ref_store *ref_store,
1770
             struct ref_transaction *transaction,
1771
             struct strbuf *err)
1772
0
{
1773
0
  struct packed_ref_store *refs = packed_downcast(
1774
0
      ref_store,
1775
0
      REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1776
0
      "ref_transaction_finish");
1777
0
  int ret = REF_TRANSACTION_ERROR_GENERIC;
1778
0
  char *packed_refs_path;
1779
1780
0
  clear_snapshot(refs);
1781
1782
0
  packed_refs_path = get_locked_file_path(&refs->lock);
1783
0
  if (rename_tempfile(&refs->tempfile, packed_refs_path)) {
1784
0
    strbuf_addf(err, "error replacing %s: %s",
1785
0
          refs->path, strerror(errno));
1786
0
    goto cleanup;
1787
0
  }
1788
1789
0
  ret = 0;
1790
1791
0
cleanup:
1792
0
  free(packed_refs_path);
1793
0
  packed_transaction_cleanup(refs, transaction);
1794
0
  return ret;
1795
0
}
1796
1797
static int packed_optimize(struct ref_store *ref_store UNUSED,
1798
         struct refs_optimize_opts *opts UNUSED)
1799
0
{
1800
  /*
1801
   * Packed refs are already packed. It might be that loose refs
1802
   * are packed *into* a packed refs store, but that is done by
1803
   * updating the packed references via a transaction.
1804
   */
1805
0
  return 0;
1806
0
}
1807
1808
static int packed_optimize_required(struct ref_store *ref_store UNUSED,
1809
            struct refs_optimize_opts *opts UNUSED,
1810
            bool *required)
1811
0
{
1812
  /*
1813
   * Packed refs are already optimized.
1814
   */
1815
0
  *required = false;
1816
0
  return 0;
1817
0
}
1818
1819
static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store UNUSED)
1820
0
{
1821
0
  return empty_ref_iterator_begin();
1822
0
}
1823
1824
static int packed_fsck_ref_next_line(struct fsck_options *o,
1825
             unsigned long line_number, const char *start,
1826
             const char *eof, const char **eol)
1827
0
{
1828
0
  int ret = 0;
1829
1830
0
  *eol = memchr(start, '\n', eof - start);
1831
0
  if (!*eol) {
1832
0
    struct strbuf packed_entry = STRBUF_INIT;
1833
0
    struct fsck_ref_report report = { 0 };
1834
1835
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1836
0
    report.path = packed_entry.buf;
1837
0
    ret = fsck_report_ref(o, &report,
1838
0
              FSCK_MSG_PACKED_REF_ENTRY_NOT_TERMINATED,
1839
0
              "'%.*s' is not terminated with a newline",
1840
0
              (int)(eof - start), start);
1841
1842
    /*
1843
     * There is no newline but we still want to parse it to the end of
1844
     * the buffer.
1845
     */
1846
0
    *eol = eof;
1847
0
    strbuf_release(&packed_entry);
1848
0
  }
1849
1850
0
  return ret;
1851
0
}
1852
1853
static int packed_fsck_ref_header(struct fsck_options *o,
1854
          const char *start, const char *eol,
1855
          unsigned int *sorted)
1856
0
{
1857
0
  struct string_list traits = STRING_LIST_INIT_NODUP;
1858
0
  char *tmp_line;
1859
0
  int ret = 0;
1860
0
  char *p;
1861
1862
0
  tmp_line = xmemdupz(start, eol - start);
1863
0
  if (!skip_prefix(tmp_line, "# pack-refs with: ", (const char **)&p)) {
1864
0
    struct fsck_ref_report report = { 0 };
1865
0
    report.path = "packed-refs.header";
1866
1867
0
    ret = fsck_report_ref(o, &report,
1868
0
              FSCK_MSG_BAD_PACKED_REF_HEADER,
1869
0
              "'%.*s' does not start with '# pack-refs with: '",
1870
0
              (int)(eol - start), start);
1871
0
    goto cleanup;
1872
0
  }
1873
1874
0
  string_list_split_in_place(&traits, p, " ", -1);
1875
0
  *sorted = unsorted_string_list_has_string(&traits, "sorted");
1876
1877
0
cleanup:
1878
0
  free(tmp_line);
1879
0
  string_list_clear(&traits, 0);
1880
0
  return ret;
1881
0
}
1882
1883
static int packed_fsck_ref_peeled_line(struct fsck_options *o,
1884
               struct ref_store *ref_store,
1885
               unsigned long line_number,
1886
               const char *start, const char *eol)
1887
0
{
1888
0
  struct strbuf packed_entry = STRBUF_INIT;
1889
0
  struct fsck_ref_report report = { 0 };
1890
0
  struct object_id peeled;
1891
0
  const char *p;
1892
0
  int ret = 0;
1893
1894
  /*
1895
   * Skip the '^' and parse the peeled oid.
1896
   */
1897
0
  start++;
1898
0
  if (parse_oid_hex_algop(start, &peeled, &p, ref_store->repo->hash_algo)) {
1899
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1900
0
    report.path = packed_entry.buf;
1901
1902
0
    ret = fsck_report_ref(o, &report,
1903
0
              FSCK_MSG_BAD_PACKED_REF_ENTRY,
1904
0
              "'%.*s' has invalid peeled oid",
1905
0
              (int)(eol - start), start);
1906
0
    goto cleanup;
1907
0
  }
1908
1909
0
  if (p != eol) {
1910
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1911
0
    report.path = packed_entry.buf;
1912
1913
0
    ret = fsck_report_ref(o, &report,
1914
0
              FSCK_MSG_BAD_PACKED_REF_ENTRY,
1915
0
              "has trailing garbage after peeled oid '%.*s'",
1916
0
              (int)(eol - p), p);
1917
0
    goto cleanup;
1918
0
  }
1919
1920
0
cleanup:
1921
0
  strbuf_release(&packed_entry);
1922
0
  return ret;
1923
0
}
1924
1925
static int packed_fsck_ref_main_line(struct fsck_options *o,
1926
             struct ref_store *ref_store,
1927
             unsigned long line_number,
1928
             struct strbuf *refname,
1929
             const char *start, const char *eol)
1930
0
{
1931
0
  struct strbuf packed_entry = STRBUF_INIT;
1932
0
  struct fsck_ref_report report = { 0 };
1933
0
  struct object_id oid;
1934
0
  const char *p;
1935
0
  int ret = 0;
1936
1937
0
  if (parse_oid_hex_algop(start, &oid, &p, ref_store->repo->hash_algo)) {
1938
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1939
0
    report.path = packed_entry.buf;
1940
1941
0
    ret = fsck_report_ref(o, &report,
1942
0
              FSCK_MSG_BAD_PACKED_REF_ENTRY,
1943
0
              "'%.*s' has invalid oid",
1944
0
              (int)(eol - start), start);
1945
0
    goto cleanup;
1946
0
  }
1947
1948
0
  if (p == eol || !isspace(*p)) {
1949
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1950
0
    report.path = packed_entry.buf;
1951
1952
0
    ret = fsck_report_ref(o, &report,
1953
0
              FSCK_MSG_BAD_PACKED_REF_ENTRY,
1954
0
              "has no space after oid '%s' but with '%.*s'",
1955
0
              oid_to_hex(&oid), (int)(eol - p), p);
1956
0
    goto cleanup;
1957
0
  }
1958
1959
0
  p++;
1960
0
  strbuf_reset(refname);
1961
0
  strbuf_add(refname, p, eol - p);
1962
0
  if (refname_contains_nul(refname)) {
1963
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1964
0
    report.path = packed_entry.buf;
1965
1966
0
    ret = fsck_report_ref(o, &report,
1967
0
              FSCK_MSG_BAD_PACKED_REF_ENTRY,
1968
0
              "refname '%s' contains NULL binaries",
1969
0
              refname->buf);
1970
0
  }
1971
1972
0
  if (check_refname_format(refname->buf, 0)) {
1973
0
    strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
1974
0
    report.path = packed_entry.buf;
1975
1976
0
    ret = fsck_report_ref(o, &report,
1977
0
              FSCK_MSG_BAD_REF_NAME,
1978
0
              "has bad refname '%s'", refname->buf);
1979
0
  }
1980
1981
0
cleanup:
1982
0
  strbuf_release(&packed_entry);
1983
0
  return ret;
1984
0
}
1985
1986
static int packed_fsck_ref_sorted(struct fsck_options *o,
1987
          struct ref_store *ref_store,
1988
          const char *start, const char *eof)
1989
0
{
1990
0
  size_t hexsz = ref_store->repo->hash_algo->hexsz;
1991
0
  struct strbuf packed_entry = STRBUF_INIT;
1992
0
  struct fsck_ref_report report = { 0 };
1993
0
  struct strbuf refname1 = STRBUF_INIT;
1994
0
  struct strbuf refname2 = STRBUF_INIT;
1995
0
  unsigned long line_number = 1;
1996
0
  const char *former = NULL;
1997
0
  const char *current;
1998
0
  const char *eol;
1999
0
  int ret = 0;
2000
2001
0
  if (*start == '#') {
2002
0
    eol = memchr(start, '\n', eof - start);
2003
0
    start = eol + 1;
2004
0
    line_number++;
2005
0
  }
2006
2007
0
  for (; start < eof; line_number++, start = eol + 1) {
2008
0
    eol = memchr(start, '\n', eof - start);
2009
2010
0
    if (*start == '^')
2011
0
      continue;
2012
2013
0
    if (!former) {
2014
0
      former = start + hexsz + 1;
2015
0
      continue;
2016
0
    }
2017
2018
0
    current = start + hexsz + 1;
2019
0
    if (cmp_packed_refname(former, current) >= 0) {
2020
0
      const char *err_fmt =
2021
0
        "refname '%s' is less than previous refname '%s'";
2022
2023
0
      eol = memchr(former, '\n', eof - former);
2024
0
      strbuf_add(&refname1, former, eol - former);
2025
0
      eol = memchr(current, '\n', eof - current);
2026
0
      strbuf_add(&refname2, current, eol - current);
2027
2028
0
      strbuf_addf(&packed_entry, "packed-refs line %lu", line_number);
2029
0
      report.path = packed_entry.buf;
2030
0
      ret = fsck_report_ref(o, &report,
2031
0
                FSCK_MSG_PACKED_REF_UNSORTED,
2032
0
                err_fmt, refname2.buf, refname1.buf);
2033
0
      goto cleanup;
2034
0
    }
2035
0
    former = current;
2036
0
  }
2037
2038
0
cleanup:
2039
0
  strbuf_release(&packed_entry);
2040
0
  strbuf_release(&refname1);
2041
0
  strbuf_release(&refname2);
2042
0
  return ret;
2043
0
}
2044
2045
static int packed_fsck_ref_content(struct fsck_options *o,
2046
           struct ref_store *ref_store,
2047
           unsigned int *sorted,
2048
           const char *start, const char *eof)
2049
0
{
2050
0
  struct strbuf refname = STRBUF_INIT;
2051
0
  unsigned long line_number = 1;
2052
0
  const char *eol;
2053
0
  int ret = 0;
2054
2055
0
  ret |= packed_fsck_ref_next_line(o, line_number, start, eof, &eol);
2056
0
  if (*start == '#') {
2057
0
    ret |= packed_fsck_ref_header(o, start, eol, sorted);
2058
2059
0
    start = eol + 1;
2060
0
    line_number++;
2061
0
  }
2062
2063
0
  while (start < eof) {
2064
0
    ret |= packed_fsck_ref_next_line(o, line_number, start, eof, &eol);
2065
0
    ret |= packed_fsck_ref_main_line(o, ref_store, line_number, &refname, start, eol);
2066
0
    start = eol + 1;
2067
0
    line_number++;
2068
0
    if (start < eof && *start == '^') {
2069
0
      ret |= packed_fsck_ref_next_line(o, line_number, start, eof, &eol);
2070
0
      ret |= packed_fsck_ref_peeled_line(o, ref_store, line_number,
2071
0
                 start, eol);
2072
0
      start = eol + 1;
2073
0
      line_number++;
2074
0
    }
2075
0
  }
2076
2077
0
  strbuf_release(&refname);
2078
0
  return ret;
2079
0
}
2080
2081
static int packed_fsck(struct ref_store *ref_store,
2082
           struct fsck_options *o,
2083
           struct worktree *wt)
2084
0
{
2085
0
  struct packed_ref_store *refs = packed_downcast(ref_store,
2086
0
              REF_STORE_READ, "fsck");
2087
0
  struct snapshot snapshot = { 0 };
2088
0
  unsigned int sorted = 0;
2089
0
  struct stat st;
2090
0
  int ret = 0;
2091
0
  int fd = -1;
2092
2093
0
  if (!is_main_worktree(wt))
2094
0
    goto cleanup;
2095
2096
0
  if (o->verbose)
2097
0
    fprintf_ln(stderr, "Checking packed-refs file %s", refs->path);
2098
2099
0
  fd = open_nofollow(refs->path, O_RDONLY);
2100
0
  if (fd < 0) {
2101
    /*
2102
     * If the packed-refs file doesn't exist, there's nothing
2103
     * to check.
2104
     */
2105
0
    if (errno == ENOENT)
2106
0
      goto cleanup;
2107
2108
0
    if (errno == ELOOP) {
2109
0
      struct fsck_ref_report report = { 0 };
2110
0
      report.path = "packed-refs";
2111
0
      ret = fsck_report_ref(o, &report,
2112
0
                FSCK_MSG_BAD_REF_FILETYPE,
2113
0
                "not a regular file but a symlink");
2114
0
      goto cleanup;
2115
0
    }
2116
2117
0
    ret = error_errno(_("unable to open '%s'"), refs->path);
2118
0
    goto cleanup;
2119
0
  } else if (fstat(fd, &st) < 0) {
2120
0
    ret = error_errno(_("unable to stat '%s'"), refs->path);
2121
0
    goto cleanup;
2122
0
  } else if (!S_ISREG(st.st_mode)) {
2123
0
    struct fsck_ref_report report = { 0 };
2124
0
    report.path = "packed-refs";
2125
0
    ret = fsck_report_ref(o, &report,
2126
0
              FSCK_MSG_BAD_REF_FILETYPE,
2127
0
              "not a regular file");
2128
0
    goto cleanup;
2129
0
  }
2130
2131
0
  if (!allocate_snapshot_buffer(&snapshot, fd, &st)) {
2132
0
    struct fsck_ref_report report = { 0 };
2133
0
    report.path = "packed-refs";
2134
0
    ret = fsck_report_ref(o, &report,
2135
0
              FSCK_MSG_EMPTY_PACKED_REFS_FILE,
2136
0
              "file is empty");
2137
0
    goto cleanup;
2138
0
  }
2139
2140
0
  ret = packed_fsck_ref_content(o, ref_store, &sorted, snapshot.start,
2141
0
              snapshot.eof);
2142
0
  if (!ret && sorted)
2143
0
    ret = packed_fsck_ref_sorted(o, ref_store, snapshot.start,
2144
0
               snapshot.eof);
2145
2146
0
cleanup:
2147
0
  if (fd >= 0)
2148
0
    close(fd);
2149
0
  clear_snapshot_buffer(&snapshot);
2150
0
  return ret;
2151
0
}
2152
2153
struct ref_storage_be refs_be_packed = {
2154
  .name = "packed",
2155
  .init = packed_ref_store_init,
2156
  .release = packed_ref_store_release,
2157
  .create_on_disk = packed_ref_store_create_on_disk,
2158
  .remove_on_disk = packed_ref_store_remove_on_disk,
2159
2160
  .transaction_prepare = packed_transaction_prepare,
2161
  .transaction_finish = packed_transaction_finish,
2162
  .transaction_abort = packed_transaction_abort,
2163
2164
  .optimize = packed_optimize,
2165
  .optimize_required = packed_optimize_required,
2166
2167
  .rename_ref = NULL,
2168
  .copy_ref = NULL,
2169
2170
  .iterator_begin = packed_ref_iterator_begin,
2171
  .read_raw_ref = packed_read_raw_ref,
2172
  .read_symbolic_ref = NULL,
2173
2174
  .reflog_iterator_begin = packed_reflog_iterator_begin,
2175
  .for_each_reflog_ent = NULL,
2176
  .for_each_reflog_ent_reverse = NULL,
2177
  .reflog_exists = NULL,
2178
  .create_reflog = NULL,
2179
  .delete_reflog = NULL,
2180
  .reflog_expire = NULL,
2181
2182
  .fsck = packed_fsck,
2183
};