Coverage Report

Created: 2026-03-31 06:24

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