4 #include "refs-internal.h"
5 #include "packed-backend.h"
6 #include "../iterator.h"
7 #include "../lockfile.h"
8 #include "../chdir-notify.h"
12 * Don't use mmap() at all for reading `packed-refs`.
17 * Can use mmap() for reading `packed-refs`, but the file must
18 * not remain mmapped. This is the usual option on Windows,
19 * where you cannot rename a new version of a file onto a file
20 * that is currently mmapped.
25 * It is OK to leave the `packed-refs` file mmapped while
26 * arbitrary other code is running.
32 static enum mmap_strategy mmap_strategy
= MMAP_NONE
;
33 #elif defined(MMAP_PREVENTS_DELETE)
34 static enum mmap_strategy mmap_strategy
= MMAP_TEMPORARY
;
36 static enum mmap_strategy mmap_strategy
= MMAP_OK
;
39 struct packed_ref_store
;
42 * A `snapshot` represents one snapshot of a `packed-refs` file.
44 * Normally, this will be a mmapped view of the contents of the
45 * `packed-refs` file at the time the snapshot was created. However,
46 * if the `packed-refs` file was not sorted, this might point at heap
47 * memory holding the contents of the `packed-refs` file with its
48 * records sorted by refname.
50 * `snapshot` instances are reference counted (via
51 * `acquire_snapshot()` and `release_snapshot()`). This is to prevent
52 * an instance from disappearing while an iterator is still iterating
53 * over it. Instances are garbage collected when their `referrers`
56 * The most recent `snapshot`, if available, is referenced by the
57 * `packed_ref_store`. Its freshness is checked whenever
58 * `get_snapshot()` is called; if the existing snapshot is obsolete, a
59 * new snapshot is taken.
63 * A back-pointer to the packed_ref_store with which this
64 * snapshot is associated:
66 struct packed_ref_store
*refs
;
68 /* Is the `packed-refs` file currently mmapped? */
72 * The contents of the `packed-refs` file:
74 * - buf -- a pointer to the start of the memory
75 * - start -- a pointer to the first byte of actual references
76 * (i.e., after the header line, if one is present)
77 * - eof -- a pointer just past the end of the reference
80 * If the `packed-refs` file was already sorted, `buf` points
81 * at the mmapped contents of the file. If not, it points at
82 * heap-allocated memory containing the contents, sorted. If
83 * there were no contents (e.g., because the file didn't
84 * exist), `buf`, `start`, and `eof` are all NULL.
86 char *buf
, *start
, *eof
;
89 * What is the peeled state of the `packed-refs` file that
90 * this snapshot represents? (This is usually determined from
93 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
;
96 * Count of references to this instance, including the pointer
97 * from `packed_ref_store::snapshot`, if any. The instance
98 * will not be freed as long as the reference count is
101 unsigned int referrers
;
104 * The metadata of the `packed-refs` file from which this
105 * snapshot was created, used to tell if the file has been
106 * replaced since we read it.
108 struct stat_validity validity
;
112 * A `ref_store` representing references stored in a `packed-refs`
113 * file. It implements the `ref_store` interface, though it has some
116 * - It cannot store symbolic references.
118 * - It cannot store reflogs.
120 * - It does not support reference renaming (though it could).
122 * On the other hand, it can be locked outside of a reference
123 * transaction. In that case, it remains locked even after the
124 * transaction is done and the new `packed-refs` file is activated.
126 struct packed_ref_store
{
127 struct ref_store base
;
129 unsigned int store_flags
;
131 /* The path of the "packed-refs" file: */
135 * A snapshot of the values read from the `packed-refs` file,
136 * if it might still be current; otherwise, NULL.
138 struct snapshot
*snapshot
;
141 * Lock used for the "packed-refs" file. Note that this (and
142 * thus the enclosing `packed_ref_store`) must not be freed.
144 struct lock_file lock
;
147 * Temporary file used when rewriting new contents to the
148 * "packed-refs" file. Note that this (and thus the enclosing
149 * `packed_ref_store`) must not be freed.
151 struct tempfile
*tempfile
;
155 * Increment the reference count of `*snapshot`.
157 static void acquire_snapshot(struct snapshot
*snapshot
)
159 snapshot
->referrers
++;
163 * If the buffer in `snapshot` is active, then either munmap the
164 * memory and close the file, or free the memory. Then set the buffer
167 static void clear_snapshot_buffer(struct snapshot
*snapshot
)
169 if (snapshot
->mmapped
) {
170 if (munmap(snapshot
->buf
, snapshot
->eof
- snapshot
->buf
))
171 die_errno("error ummapping packed-refs file %s",
172 snapshot
->refs
->path
);
173 snapshot
->mmapped
= 0;
177 snapshot
->buf
= snapshot
->start
= snapshot
->eof
= NULL
;
181 * Decrease the reference count of `*snapshot`. If it goes to zero,
182 * free `*snapshot` and return true; otherwise return false.
184 static int release_snapshot(struct snapshot
*snapshot
)
186 if (!--snapshot
->referrers
) {
187 stat_validity_clear(&snapshot
->validity
);
188 clear_snapshot_buffer(snapshot
);
196 struct ref_store
*packed_ref_store_create(struct repository
*repo
,
198 unsigned int store_flags
)
200 struct packed_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
201 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
202 struct strbuf sb
= STRBUF_INIT
;
204 base_ref_store_init(ref_store
, repo
, gitdir
, &refs_be_packed
);
205 refs
->store_flags
= store_flags
;
207 strbuf_addf(&sb
, "%s/packed-refs", gitdir
);
208 refs
->path
= strbuf_detach(&sb
, NULL
);
209 chdir_notify_reparent("packed-refs", &refs
->path
);
214 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
215 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
216 * support at least the flags specified in `required_flags`. `caller`
217 * is used in any necessary error messages.
219 static struct packed_ref_store
*packed_downcast(struct ref_store
*ref_store
,
220 unsigned int required_flags
,
223 struct packed_ref_store
*refs
;
225 if (ref_store
->be
!= &refs_be_packed
)
226 BUG("ref_store is type \"%s\" not \"packed\" in %s",
227 ref_store
->be
->name
, caller
);
229 refs
= (struct packed_ref_store
*)ref_store
;
231 if ((refs
->store_flags
& required_flags
) != required_flags
)
232 BUG("unallowed operation (%s), requires %x, has %x\n",
233 caller
, required_flags
, refs
->store_flags
);
238 static void clear_snapshot(struct packed_ref_store
*refs
)
240 if (refs
->snapshot
) {
241 struct snapshot
*snapshot
= refs
->snapshot
;
243 refs
->snapshot
= NULL
;
244 release_snapshot(snapshot
);
248 static NORETURN
void die_unterminated_line(const char *path
,
249 const char *p
, size_t len
)
252 die("unterminated line in %s: %.*s", path
, (int)len
, p
);
254 die("unterminated line in %s: %.75s...", path
, p
);
257 static NORETURN
void die_invalid_line(const char *path
,
258 const char *p
, size_t len
)
260 const char *eol
= memchr(p
, '\n', len
);
263 die_unterminated_line(path
, p
, len
);
264 else if (eol
- p
< 80)
265 die("unexpected line in %s: %.*s", path
, (int)(eol
- p
), p
);
267 die("unexpected line in %s: %.75s...", path
, p
);
271 struct snapshot_record
{
276 static int cmp_packed_ref_records(const void *v1
, const void *v2
)
278 const struct snapshot_record
*e1
= v1
, *e2
= v2
;
279 const char *r1
= e1
->start
+ the_hash_algo
->hexsz
+ 1;
280 const char *r2
= e2
->start
+ the_hash_algo
->hexsz
+ 1;
284 return *r2
== '\n' ? 0 : -1;
289 return (unsigned char)*r1
< (unsigned char)*r2
? -1 : +1;
297 * Compare a snapshot record at `rec` to the specified NUL-terminated
300 static int cmp_record_to_refname(const char *rec
, const char *refname
)
302 const char *r1
= rec
+ the_hash_algo
->hexsz
+ 1;
303 const char *r2
= refname
;
311 return (unsigned char)*r1
< (unsigned char)*r2
? -1 : +1;
318 * `snapshot->buf` is not known to be sorted. Check whether it is, and
319 * if not, sort it into new memory and munmap/free the old storage.
321 static void sort_snapshot(struct snapshot
*snapshot
)
323 struct snapshot_record
*records
= NULL
;
324 size_t alloc
= 0, nr
= 0;
326 const char *pos
, *eof
, *eol
;
328 char *new_buffer
, *dst
;
330 pos
= snapshot
->start
;
339 * Initialize records based on a crude estimate of the number
340 * of references in the file (we'll grow it below if needed):
342 ALLOC_GROW(records
, len
/ 80 + 20, alloc
);
345 eol
= memchr(pos
, '\n', eof
- pos
);
347 /* The safety check should prevent this. */
348 BUG("unterminated line found in packed-refs");
349 if (eol
- pos
< the_hash_algo
->hexsz
+ 2)
350 die_invalid_line(snapshot
->refs
->path
,
353 if (eol
< eof
&& *eol
== '^') {
355 * Keep any peeled line together with its
358 const char *peeled_start
= eol
;
360 eol
= memchr(peeled_start
, '\n', eof
- peeled_start
);
362 /* The safety check should prevent this. */
363 BUG("unterminated peeled line found in packed-refs");
367 ALLOC_GROW(records
, nr
+ 1, alloc
);
368 records
[nr
].start
= pos
;
369 records
[nr
].len
= eol
- pos
;
374 cmp_packed_ref_records(&records
[nr
- 2],
375 &records
[nr
- 1]) >= 0)
384 /* We need to sort the memory. First we sort the records array: */
385 QSORT(records
, nr
, cmp_packed_ref_records
);
388 * Allocate a new chunk of memory, and copy the old memory to
389 * the new in the order indicated by `records` (not bothering
390 * with the header line):
392 new_buffer
= xmalloc(len
);
393 for (dst
= new_buffer
, i
= 0; i
< nr
; i
++) {
394 memcpy(dst
, records
[i
].start
, records
[i
].len
);
395 dst
+= records
[i
].len
;
399 * Now munmap the old buffer and use the sorted buffer in its
402 clear_snapshot_buffer(snapshot
);
403 snapshot
->buf
= snapshot
->start
= new_buffer
;
404 snapshot
->eof
= new_buffer
+ len
;
411 * Return a pointer to the start of the record that contains the
412 * character `*p` (which must be within the buffer). If no other
413 * record start is found, return `buf`.
415 static const char *find_start_of_record(const char *buf
, const char *p
)
417 while (p
> buf
&& (p
[-1] != '\n' || p
[0] == '^'))
423 * Return a pointer to the start of the record following the record
424 * that contains `*p`. If none is found before `end`, return `end`.
426 static const char *find_end_of_record(const char *p
, const char *end
)
428 while (++p
< end
&& (p
[-1] != '\n' || p
[0] == '^'))
434 * We want to be able to compare mmapped reference records quickly,
435 * without totally parsing them. We can do so because the records are
436 * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
437 * + 1) bytes past the beginning of the record.
439 * But what if the `packed-refs` file contains garbage? We're willing
440 * to tolerate not detecting the problem, as long as we don't produce
441 * totally garbled output (we can't afford to check the integrity of
442 * the whole file during every Git invocation). But we do want to be
443 * sure that we never read past the end of the buffer in memory and
444 * perform an illegal memory access.
446 * Guarantee that minimum level of safety by verifying that the last
447 * record in the file is LF-terminated, and that it has at least
448 * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
449 * these checks fails.
451 static void verify_buffer_safe(struct snapshot
*snapshot
)
453 const char *start
= snapshot
->start
;
454 const char *eof
= snapshot
->eof
;
455 const char *last_line
;
460 last_line
= find_start_of_record(start
, eof
- 1);
461 if (*(eof
- 1) != '\n' || eof
- last_line
< the_hash_algo
->hexsz
+ 2)
462 die_invalid_line(snapshot
->refs
->path
,
463 last_line
, eof
- last_line
);
466 #define SMALL_FILE_SIZE (32*1024)
469 * Depending on `mmap_strategy`, either mmap or read the contents of
470 * the `packed-refs` file into the snapshot. Return 1 if the file
471 * existed and was read, or 0 if the file was absent or empty. Die on
474 static int load_contents(struct snapshot
*snapshot
)
481 fd
= open(snapshot
->refs
->path
, O_RDONLY
);
483 if (errno
== ENOENT
) {
485 * This is OK; it just means that no
486 * "packed-refs" file has been written yet,
487 * which is equivalent to it being empty,
488 * which is its state when initialized with
493 die_errno("couldn't read %s", snapshot
->refs
->path
);
497 stat_validity_update(&snapshot
->validity
, fd
);
499 if (fstat(fd
, &st
) < 0)
500 die_errno("couldn't stat %s", snapshot
->refs
->path
);
501 size
= xsize_t(st
.st_size
);
506 } else if (mmap_strategy
== MMAP_NONE
|| size
<= SMALL_FILE_SIZE
) {
507 snapshot
->buf
= xmalloc(size
);
508 bytes_read
= read_in_full(fd
, snapshot
->buf
, size
);
509 if (bytes_read
< 0 || bytes_read
!= size
)
510 die_errno("couldn't read %s", snapshot
->refs
->path
);
511 snapshot
->mmapped
= 0;
513 snapshot
->buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
514 snapshot
->mmapped
= 1;
518 snapshot
->start
= snapshot
->buf
;
519 snapshot
->eof
= snapshot
->buf
+ size
;
525 * Find the place in `snapshot->buf` where the start of the record for
526 * `refname` starts. If `mustexist` is true and the reference doesn't
527 * exist, then return NULL. If `mustexist` is false and the reference
528 * doesn't exist, then return the point where that reference would be
529 * inserted, or `snapshot->eof` (which might be NULL) if it would be
530 * inserted at the end of the file. In the latter mode, `refname`
531 * doesn't have to be a proper reference name; for example, one could
532 * search for "refs/replace/" to find the start of any replace
535 * The record is sought using a binary search, so `snapshot->buf` must
538 static const char *find_reference_location(struct snapshot
*snapshot
,
539 const char *refname
, int mustexist
)
542 * This is not *quite* a garden-variety binary search, because
543 * the data we're searching is made up of records, and we
544 * always need to find the beginning of a record to do a
545 * comparison. A "record" here is one line for the reference
546 * itself and zero or one peel lines that start with '^'. Our
547 * loop invariant is described in the next two comments.
551 * A pointer to the character at the start of a record whose
552 * preceding records all have reference names that come
553 * *before* `refname`.
555 const char *lo
= snapshot
->start
;
558 * A pointer to a the first character of a record whose
559 * reference name comes *after* `refname`.
561 const char *hi
= snapshot
->eof
;
564 const char *mid
, *rec
;
567 mid
= lo
+ (hi
- lo
) / 2;
568 rec
= find_start_of_record(lo
, mid
);
569 cmp
= cmp_record_to_refname(rec
, refname
);
571 lo
= find_end_of_record(mid
, hi
);
572 } else if (cmp
> 0) {
586 * Create a newly-allocated `snapshot` of the `packed-refs` file in
587 * its current state and return it. The return value will already have
588 * its reference count incremented.
590 * A comment line of the form "# pack-refs with: " may contain zero or
591 * more traits. We interpret the traits as follows:
593 * Neither `peeled` nor `fully-peeled`:
595 * Probably no references are peeled. But if the file contains a
596 * peeled value for a reference, we will use it.
600 * References under "refs/tags/", if they *can* be peeled, *are*
601 * peeled in this file. References outside of "refs/tags/" are
602 * probably not peeled even if they could have been, but if we find
603 * a peeled value for such a reference we will use it.
607 * All references in the file that can be peeled are peeled.
608 * Inversely (and this is more important), any references in the
609 * file for which no peeled value is recorded is not peelable. This
610 * trait should typically be written alongside "peeled" for
611 * compatibility with older clients, but we do not require it
612 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
616 * The references in this file are known to be sorted by refname.
618 static struct snapshot
*create_snapshot(struct packed_ref_store
*refs
)
620 struct snapshot
*snapshot
= xcalloc(1, sizeof(*snapshot
));
623 snapshot
->refs
= refs
;
624 acquire_snapshot(snapshot
);
625 snapshot
->peeled
= PEELED_NONE
;
627 if (!load_contents(snapshot
))
630 /* If the file has a header line, process it: */
631 if (snapshot
->buf
< snapshot
->eof
&& *snapshot
->buf
== '#') {
633 struct string_list traits
= STRING_LIST_INIT_NODUP
;
635 eol
= memchr(snapshot
->buf
, '\n',
636 snapshot
->eof
- snapshot
->buf
);
638 die_unterminated_line(refs
->path
,
640 snapshot
->eof
- snapshot
->buf
);
642 tmp
= xmemdupz(snapshot
->buf
, eol
- snapshot
->buf
);
644 if (!skip_prefix(tmp
, "# pack-refs with:", (const char **)&p
))
645 die_invalid_line(refs
->path
,
647 snapshot
->eof
- snapshot
->buf
);
649 string_list_split_in_place(&traits
, p
, ' ', -1);
651 if (unsorted_string_list_has_string(&traits
, "fully-peeled"))
652 snapshot
->peeled
= PEELED_FULLY
;
653 else if (unsorted_string_list_has_string(&traits
, "peeled"))
654 snapshot
->peeled
= PEELED_TAGS
;
656 sorted
= unsorted_string_list_has_string(&traits
, "sorted");
658 /* perhaps other traits later as well */
660 /* The "+ 1" is for the LF character. */
661 snapshot
->start
= eol
+ 1;
663 string_list_clear(&traits
, 0);
667 verify_buffer_safe(snapshot
);
670 sort_snapshot(snapshot
);
673 * Reordering the records might have moved a short one
674 * to the end of the buffer, so verify the buffer's
677 verify_buffer_safe(snapshot
);
680 if (mmap_strategy
!= MMAP_OK
&& snapshot
->mmapped
) {
682 * We don't want to leave the file mmapped, so we are
683 * forced to make a copy now:
685 size_t size
= snapshot
->eof
- snapshot
->start
;
686 char *buf_copy
= xmalloc(size
);
688 memcpy(buf_copy
, snapshot
->start
, size
);
689 clear_snapshot_buffer(snapshot
);
690 snapshot
->buf
= snapshot
->start
= buf_copy
;
691 snapshot
->eof
= buf_copy
+ size
;
698 * Check that `refs->snapshot` (if present) still reflects the
699 * contents of the `packed-refs` file. If not, clear the snapshot.
701 static void validate_snapshot(struct packed_ref_store
*refs
)
703 if (refs
->snapshot
&&
704 !stat_validity_check(&refs
->snapshot
->validity
, refs
->path
))
705 clear_snapshot(refs
);
709 * Get the `snapshot` for the specified packed_ref_store, creating and
710 * populating it if it hasn't been read before or if the file has been
711 * changed (according to its `validity` field) since it was last read.
712 * On the other hand, if we hold the lock, then assume that the file
713 * hasn't been changed out from under us, so skip the extra `stat()`
714 * call in `stat_validity_check()`. This function does *not* increase
715 * the snapshot's reference count on behalf of the caller.
717 static struct snapshot
*get_snapshot(struct packed_ref_store
*refs
)
719 if (!is_lock_file_locked(&refs
->lock
))
720 validate_snapshot(refs
);
723 refs
->snapshot
= create_snapshot(refs
);
725 return refs
->snapshot
;
728 static int packed_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
729 struct object_id
*oid
, struct strbuf
*referent UNUSED
,
730 unsigned int *type
, int *failure_errno
)
732 struct packed_ref_store
*refs
=
733 packed_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
734 struct snapshot
*snapshot
= get_snapshot(refs
);
739 rec
= find_reference_location(snapshot
, refname
, 1);
742 /* refname is not a packed reference. */
743 *failure_errno
= ENOENT
;
747 if (get_oid_hex(rec
, oid
))
748 die_invalid_line(refs
->path
, rec
, snapshot
->eof
- rec
);
750 *type
= REF_ISPACKED
;
755 * This value is set in `base.flags` if the peeled value of the
756 * current reference is known. In that case, `peeled` contains the
757 * correct peeled value for the reference, which might be `null_oid`
758 * if the reference is not a tag or if it is broken.
760 #define REF_KNOWS_PEELED 0x40
763 * An iterator over a snapshot of a `packed-refs` file.
765 struct packed_ref_iterator
{
766 struct ref_iterator base
;
768 struct snapshot
*snapshot
;
770 /* The current position in the snapshot's buffer: */
773 /* The end of the part of the buffer that will be iterated over: */
776 /* Scratch space for current values: */
777 struct object_id oid
, peeled
;
778 struct strbuf refname_buf
;
780 struct repository
*repo
;
785 * Move the iterator to the next record in the snapshot, without
786 * respect for whether the record is actually required by the current
787 * iteration. Adjust the fields in `iter` and return `ITER_OK` or
788 * `ITER_DONE`. This function does not free the iterator in the case
791 static int next_record(struct packed_ref_iterator
*iter
)
793 const char *p
= iter
->pos
, *eol
;
795 strbuf_reset(&iter
->refname_buf
);
797 if (iter
->pos
== iter
->eof
)
800 iter
->base
.flags
= REF_ISPACKED
;
802 if (iter
->eof
- p
< the_hash_algo
->hexsz
+ 2 ||
803 parse_oid_hex(p
, &iter
->oid
, &p
) ||
805 die_invalid_line(iter
->snapshot
->refs
->path
,
806 iter
->pos
, iter
->eof
- iter
->pos
);
808 eol
= memchr(p
, '\n', iter
->eof
- p
);
810 die_unterminated_line(iter
->snapshot
->refs
->path
,
811 iter
->pos
, iter
->eof
- iter
->pos
);
813 strbuf_add(&iter
->refname_buf
, p
, eol
- p
);
814 iter
->base
.refname
= iter
->refname_buf
.buf
;
816 if (check_refname_format(iter
->base
.refname
, REFNAME_ALLOW_ONELEVEL
)) {
817 if (!refname_is_safe(iter
->base
.refname
))
818 die("packed refname is dangerous: %s",
821 iter
->base
.flags
|= REF_BAD_NAME
| REF_ISBROKEN
;
823 if (iter
->snapshot
->peeled
== PEELED_FULLY
||
824 (iter
->snapshot
->peeled
== PEELED_TAGS
&&
825 starts_with(iter
->base
.refname
, "refs/tags/")))
826 iter
->base
.flags
|= REF_KNOWS_PEELED
;
830 if (iter
->pos
< iter
->eof
&& *iter
->pos
== '^') {
832 if (iter
->eof
- p
< the_hash_algo
->hexsz
+ 1 ||
833 parse_oid_hex(p
, &iter
->peeled
, &p
) ||
835 die_invalid_line(iter
->snapshot
->refs
->path
,
836 iter
->pos
, iter
->eof
- iter
->pos
);
840 * Regardless of what the file header said, we
841 * definitely know the value of *this* reference. But
842 * we suppress it if the reference is broken:
844 if ((iter
->base
.flags
& REF_ISBROKEN
)) {
845 oidclr(&iter
->peeled
);
846 iter
->base
.flags
&= ~REF_KNOWS_PEELED
;
848 iter
->base
.flags
|= REF_KNOWS_PEELED
;
851 oidclr(&iter
->peeled
);
857 static int packed_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
859 struct packed_ref_iterator
*iter
=
860 (struct packed_ref_iterator
*)ref_iterator
;
863 while ((ok
= next_record(iter
)) == ITER_OK
) {
864 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
865 ref_type(iter
->base
.refname
) != REF_TYPE_PER_WORKTREE
)
868 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
869 !ref_resolves_to_object(iter
->base
.refname
, iter
->repo
,
870 &iter
->oid
, iter
->flags
))
876 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
882 static int packed_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
883 struct object_id
*peeled
)
885 struct packed_ref_iterator
*iter
=
886 (struct packed_ref_iterator
*)ref_iterator
;
888 if (iter
->repo
!= the_repository
)
889 BUG("peeling for non-the_repository is not supported");
891 if ((iter
->base
.flags
& REF_KNOWS_PEELED
)) {
892 oidcpy(peeled
, &iter
->peeled
);
893 return is_null_oid(&iter
->peeled
) ? -1 : 0;
894 } else if ((iter
->base
.flags
& (REF_ISBROKEN
| REF_ISSYMREF
))) {
897 return peel_object(&iter
->oid
, peeled
) ? -1 : 0;
901 static int packed_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
903 struct packed_ref_iterator
*iter
=
904 (struct packed_ref_iterator
*)ref_iterator
;
907 strbuf_release(&iter
->refname_buf
);
908 release_snapshot(iter
->snapshot
);
909 base_ref_iterator_free(ref_iterator
);
913 static struct ref_iterator_vtable packed_ref_iterator_vtable
= {
914 .advance
= packed_ref_iterator_advance
,
915 .peel
= packed_ref_iterator_peel
,
916 .abort
= packed_ref_iterator_abort
919 static struct ref_iterator
*packed_ref_iterator_begin(
920 struct ref_store
*ref_store
,
921 const char *prefix
, unsigned int flags
)
923 struct packed_ref_store
*refs
;
924 struct snapshot
*snapshot
;
926 struct packed_ref_iterator
*iter
;
927 struct ref_iterator
*ref_iterator
;
928 unsigned int required_flags
= REF_STORE_READ
;
930 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
931 required_flags
|= REF_STORE_ODB
;
932 refs
= packed_downcast(ref_store
, required_flags
, "ref_iterator_begin");
935 * Note that `get_snapshot()` internally checks whether the
936 * snapshot is up to date with what is on disk, and re-reads
939 snapshot
= get_snapshot(refs
);
941 if (prefix
&& *prefix
)
942 start
= find_reference_location(snapshot
, prefix
, 0);
944 start
= snapshot
->start
;
946 if (start
== snapshot
->eof
)
947 return empty_ref_iterator_begin();
949 CALLOC_ARRAY(iter
, 1);
950 ref_iterator
= &iter
->base
;
951 base_ref_iterator_init(ref_iterator
, &packed_ref_iterator_vtable
, 1);
953 iter
->snapshot
= snapshot
;
954 acquire_snapshot(snapshot
);
957 iter
->eof
= snapshot
->eof
;
958 strbuf_init(&iter
->refname_buf
, 0);
960 iter
->base
.oid
= &iter
->oid
;
962 iter
->repo
= ref_store
->repo
;
965 if (prefix
&& *prefix
)
966 /* Stop iteration after we've gone *past* prefix: */
967 ref_iterator
= prefix_ref_iterator_begin(ref_iterator
, prefix
, 0);
973 * Write an entry to the packed-refs file for the specified refname.
974 * If peeled is non-NULL, write it as the entry's peeled value. On
975 * error, return a nonzero value and leave errno set at the value left
976 * by the failing call to `fprintf()`.
978 static int write_packed_entry(FILE *fh
, const char *refname
,
979 const struct object_id
*oid
,
980 const struct object_id
*peeled
)
982 if (fprintf(fh
, "%s %s\n", oid_to_hex(oid
), refname
) < 0 ||
983 (peeled
&& fprintf(fh
, "^%s\n", oid_to_hex(peeled
)) < 0))
989 int packed_refs_lock(struct ref_store
*ref_store
, int flags
, struct strbuf
*err
)
991 struct packed_ref_store
*refs
=
992 packed_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_MAIN
,
994 static int timeout_configured
= 0;
995 static int timeout_value
= 1000;
997 if (!timeout_configured
) {
998 git_config_get_int("core.packedrefstimeout", &timeout_value
);
999 timeout_configured
= 1;
1003 * Note that we close the lockfile immediately because we
1004 * don't write new content to it, but rather to a separate
1007 if (hold_lock_file_for_update_timeout(
1010 flags
, timeout_value
) < 0) {
1011 unable_to_lock_message(refs
->path
, errno
, err
);
1015 if (close_lock_file_gently(&refs
->lock
)) {
1016 strbuf_addf(err
, "unable to close %s: %s", refs
->path
, strerror(errno
));
1017 rollback_lock_file(&refs
->lock
);
1022 * There is a stat-validity problem might cause `update-ref -d`
1023 * lost the newly commit of a ref, because a new `packed-refs`
1024 * file might has the same on-disk file attributes such as
1025 * timestamp, file size and inode value, but has a changed
1028 * This could happen with a very small chance when
1029 * `update-ref -d` is called and at the same time another
1030 * `pack-refs --all` process is running.
1032 * Now that we hold the `packed-refs` lock, it is important
1033 * to make sure we could read the latest version of
1034 * `packed-refs` file no matter we have just mmap it or not.
1035 * So what need to do is clear the snapshot if we hold it
1038 clear_snapshot(refs
);
1041 * Now make sure that the packed-refs file as it exists in the
1042 * locked state is loaded into the snapshot:
1048 void packed_refs_unlock(struct ref_store
*ref_store
)
1050 struct packed_ref_store
*refs
= packed_downcast(
1052 REF_STORE_READ
| REF_STORE_WRITE
,
1053 "packed_refs_unlock");
1055 if (!is_lock_file_locked(&refs
->lock
))
1056 BUG("packed_refs_unlock() called when not locked");
1057 rollback_lock_file(&refs
->lock
);
1060 int packed_refs_is_locked(struct ref_store
*ref_store
)
1062 struct packed_ref_store
*refs
= packed_downcast(
1064 REF_STORE_READ
| REF_STORE_WRITE
,
1065 "packed_refs_is_locked");
1067 return is_lock_file_locked(&refs
->lock
);
1071 * The packed-refs header line that we write out. Perhaps other traits
1072 * will be added later.
1074 * Note that earlier versions of Git used to parse these traits by
1075 * looking for " trait " in the line. For this reason, the space after
1076 * the colon and the trailing space are required.
1078 static const char PACKED_REFS_HEADER
[] =
1079 "# pack-refs with: peeled fully-peeled sorted \n";
1081 static int packed_init_db(struct ref_store
*ref_store UNUSED
,
1082 struct strbuf
*err UNUSED
)
1084 /* Nothing to do. */
1089 * Write the packed refs from the current snapshot to the packed-refs
1090 * tempfile, incorporating any changes from `updates`. `updates` must
1091 * be a sorted string list whose keys are the refnames and whose util
1092 * values are `struct ref_update *`. On error, rollback the tempfile,
1093 * write an error message to `err`, and return a nonzero value.
1095 * The packfile must be locked before calling this function and will
1096 * remain locked when it is done.
1098 static int write_with_updates(struct packed_ref_store
*refs
,
1099 struct string_list
*updates
,
1102 struct ref_iterator
*iter
= NULL
;
1106 struct strbuf sb
= STRBUF_INIT
;
1107 char *packed_refs_path
;
1109 if (!is_lock_file_locked(&refs
->lock
))
1110 BUG("write_with_updates() called while unlocked");
1113 * If packed-refs is a symlink, we want to overwrite the
1114 * symlinked-to file, not the symlink itself. Also, put the
1115 * staging file next to it:
1117 packed_refs_path
= get_locked_file_path(&refs
->lock
);
1118 strbuf_addf(&sb
, "%s.new", packed_refs_path
);
1119 free(packed_refs_path
);
1120 refs
->tempfile
= create_tempfile(sb
.buf
);
1121 if (!refs
->tempfile
) {
1122 strbuf_addf(err
, "unable to create file %s: %s",
1123 sb
.buf
, strerror(errno
));
1124 strbuf_release(&sb
);
1127 strbuf_release(&sb
);
1129 out
= fdopen_tempfile(refs
->tempfile
, "w");
1131 strbuf_addf(err
, "unable to fdopen packed-refs tempfile: %s",
1136 if (fprintf(out
, "%s", PACKED_REFS_HEADER
) < 0)
1140 * We iterate in parallel through the current list of refs and
1141 * the list of updates, processing an entry from at least one
1142 * of the lists each time through the loop. When the current
1143 * list of refs is exhausted, set iter to NULL. When the list
1144 * of updates is exhausted, leave i set to updates->nr.
1146 iter
= packed_ref_iterator_begin(&refs
->base
, "",
1147 DO_FOR_EACH_INCLUDE_BROKEN
);
1148 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1153 while (iter
|| i
< updates
->nr
) {
1154 struct ref_update
*update
= NULL
;
1157 if (i
>= updates
->nr
) {
1160 update
= updates
->items
[i
].util
;
1165 cmp
= strcmp(iter
->refname
, update
->refname
);
1170 * There is both an old value and an update
1171 * for this reference. Check the old value if
1174 if ((update
->flags
& REF_HAVE_OLD
)) {
1175 if (is_null_oid(&update
->old_oid
)) {
1176 strbuf_addf(err
, "cannot update ref '%s': "
1177 "reference already exists",
1180 } else if (!oideq(&update
->old_oid
, iter
->oid
)) {
1181 strbuf_addf(err
, "cannot update ref '%s': "
1182 "is at %s but expected %s",
1184 oid_to_hex(iter
->oid
),
1185 oid_to_hex(&update
->old_oid
));
1190 /* Now figure out what to use for the new value: */
1191 if ((update
->flags
& REF_HAVE_NEW
)) {
1193 * The update takes precedence. Skip
1194 * the iterator over the unneeded
1197 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1202 * The update doesn't actually want to
1203 * change anything. We're done with it.
1208 } else if (cmp
> 0) {
1210 * There is no old value but there is an
1211 * update for this reference. Make sure that
1212 * the update didn't expect an existing value:
1214 if ((update
->flags
& REF_HAVE_OLD
) &&
1215 !is_null_oid(&update
->old_oid
)) {
1216 strbuf_addf(err
, "cannot update ref '%s': "
1217 "reference is missing but expected %s",
1219 oid_to_hex(&update
->old_oid
));
1225 /* Pass the old reference through. */
1227 struct object_id peeled
;
1228 int peel_error
= ref_iterator_peel(iter
, &peeled
);
1230 if (write_packed_entry(out
, iter
->refname
,
1232 peel_error
? NULL
: &peeled
))
1235 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1237 } else if (is_null_oid(&update
->new_oid
)) {
1239 * The update wants to delete the reference,
1240 * and the reference either didn't exist or we
1241 * have already skipped it. So we're done with
1242 * the update (and don't have to write
1247 struct object_id peeled
;
1248 int peel_error
= peel_object(&update
->new_oid
,
1251 if (write_packed_entry(out
, update
->refname
,
1253 peel_error
? NULL
: &peeled
))
1260 if (ok
!= ITER_DONE
) {
1261 strbuf_addstr(err
, "unable to write packed-refs file: "
1262 "error iterating over old contents");
1266 if (fsync_component(FSYNC_COMPONENT_REFERENCE
, get_tempfile_fd(refs
->tempfile
)) ||
1267 close_tempfile_gently(refs
->tempfile
)) {
1268 strbuf_addf(err
, "error closing file %s: %s",
1269 get_tempfile_path(refs
->tempfile
),
1271 strbuf_release(&sb
);
1272 delete_tempfile(&refs
->tempfile
);
1279 strbuf_addf(err
, "error writing to %s: %s",
1280 get_tempfile_path(refs
->tempfile
), strerror(errno
));
1284 ref_iterator_abort(iter
);
1286 delete_tempfile(&refs
->tempfile
);
1290 int is_packed_transaction_needed(struct ref_store
*ref_store
,
1291 struct ref_transaction
*transaction
)
1293 struct packed_ref_store
*refs
= packed_downcast(
1296 "is_packed_transaction_needed");
1297 struct strbuf referent
= STRBUF_INIT
;
1301 if (!is_lock_file_locked(&refs
->lock
))
1302 BUG("is_packed_transaction_needed() called while unlocked");
1305 * We're only going to bother returning false for the common,
1306 * trivial case that references are only being deleted, their
1307 * old values are not being checked, and the old `packed-refs`
1308 * file doesn't contain any of those reference(s). This gives
1309 * false positives for some other cases that could
1310 * theoretically be optimized away:
1312 * 1. It could be that the old value is being verified without
1313 * setting a new value. In this case, we could verify the
1314 * old value here and skip the update if it agrees. If it
1315 * disagrees, we could either let the update go through
1316 * (the actual commit would re-detect and report the
1317 * problem), or come up with a way of reporting such an
1318 * error to *our* caller.
1320 * 2. It could be that a new value is being set, but that it
1321 * is identical to the current packed value of the
1324 * Neither of these cases will come up in the current code,
1325 * because the only caller of this function passes to it a
1326 * transaction that only includes `delete` updates with no
1327 * `old_id`. Even if that ever changes, false positives only
1328 * cause an optimization to be missed; they do not affect
1333 * Start with the cheap checks that don't require old
1334 * reference values to be read:
1336 for (i
= 0; i
< transaction
->nr
; i
++) {
1337 struct ref_update
*update
= transaction
->updates
[i
];
1339 if (update
->flags
& REF_HAVE_OLD
)
1340 /* Have to check the old value -> needed. */
1343 if ((update
->flags
& REF_HAVE_NEW
) && !is_null_oid(&update
->new_oid
))
1344 /* Have to set a new value -> needed. */
1349 * The transaction isn't checking any old values nor is it
1350 * setting any nonzero new values, so it still might be able
1351 * to be skipped. Now do the more expensive check: the update
1352 * is needed if any of the updates is a delete, and the old
1353 * `packed-refs` file contains a value for that reference.
1356 for (i
= 0; i
< transaction
->nr
; i
++) {
1357 struct ref_update
*update
= transaction
->updates
[i
];
1360 struct object_id oid
;
1362 if (!(update
->flags
& REF_HAVE_NEW
))
1364 * This reference isn't being deleted -> not
1369 if (!refs_read_raw_ref(ref_store
, update
->refname
, &oid
,
1370 &referent
, &type
, &failure_errno
) ||
1371 failure_errno
!= ENOENT
) {
1373 * We have to actually delete that reference
1374 * -> this transaction is needed.
1381 strbuf_release(&referent
);
1385 struct packed_transaction_backend_data
{
1386 /* True iff the transaction owns the packed-refs lock. */
1389 struct string_list updates
;
1392 static void packed_transaction_cleanup(struct packed_ref_store
*refs
,
1393 struct ref_transaction
*transaction
)
1395 struct packed_transaction_backend_data
*data
= transaction
->backend_data
;
1398 string_list_clear(&data
->updates
, 0);
1400 if (is_tempfile_active(refs
->tempfile
))
1401 delete_tempfile(&refs
->tempfile
);
1403 if (data
->own_lock
&& is_lock_file_locked(&refs
->lock
)) {
1404 packed_refs_unlock(&refs
->base
);
1409 transaction
->backend_data
= NULL
;
1412 transaction
->state
= REF_TRANSACTION_CLOSED
;
1415 static int packed_transaction_prepare(struct ref_store
*ref_store
,
1416 struct ref_transaction
*transaction
,
1419 struct packed_ref_store
*refs
= packed_downcast(
1421 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1422 "ref_transaction_prepare");
1423 struct packed_transaction_backend_data
*data
;
1425 int ret
= TRANSACTION_GENERIC_ERROR
;
1428 * Note that we *don't* skip transactions with zero updates,
1429 * because such a transaction might be executed for the side
1430 * effect of ensuring that all of the references are peeled or
1431 * ensuring that the `packed-refs` file is sorted. If the
1432 * caller wants to optimize away empty transactions, it should
1436 CALLOC_ARRAY(data
, 1);
1437 string_list_init_nodup(&data
->updates
);
1439 transaction
->backend_data
= data
;
1442 * Stick the updates in a string list by refname so that we
1445 for (i
= 0; i
< transaction
->nr
; i
++) {
1446 struct ref_update
*update
= transaction
->updates
[i
];
1447 struct string_list_item
*item
=
1448 string_list_append(&data
->updates
, update
->refname
);
1450 /* Store a pointer to update in item->util: */
1451 item
->util
= update
;
1453 string_list_sort(&data
->updates
);
1455 if (ref_update_reject_duplicates(&data
->updates
, err
))
1458 if (!is_lock_file_locked(&refs
->lock
)) {
1459 if (packed_refs_lock(ref_store
, 0, err
))
1464 if (write_with_updates(refs
, &data
->updates
, err
))
1467 transaction
->state
= REF_TRANSACTION_PREPARED
;
1471 packed_transaction_cleanup(refs
, transaction
);
1475 static int packed_transaction_abort(struct ref_store
*ref_store
,
1476 struct ref_transaction
*transaction
,
1477 struct strbuf
*err UNUSED
)
1479 struct packed_ref_store
*refs
= packed_downcast(
1481 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1482 "ref_transaction_abort");
1484 packed_transaction_cleanup(refs
, transaction
);
1488 static int packed_transaction_finish(struct ref_store
*ref_store
,
1489 struct ref_transaction
*transaction
,
1492 struct packed_ref_store
*refs
= packed_downcast(
1494 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1495 "ref_transaction_finish");
1496 int ret
= TRANSACTION_GENERIC_ERROR
;
1497 char *packed_refs_path
;
1499 clear_snapshot(refs
);
1501 packed_refs_path
= get_locked_file_path(&refs
->lock
);
1502 if (rename_tempfile(&refs
->tempfile
, packed_refs_path
)) {
1503 strbuf_addf(err
, "error replacing %s: %s",
1504 refs
->path
, strerror(errno
));
1511 free(packed_refs_path
);
1512 packed_transaction_cleanup(refs
, transaction
);
1516 static int packed_initial_transaction_commit(struct ref_store
*ref_store UNUSED
,
1517 struct ref_transaction
*transaction
,
1520 return ref_transaction_commit(transaction
, err
);
1523 static int packed_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1524 struct string_list
*refnames
, unsigned int flags
)
1526 struct packed_ref_store
*refs
=
1527 packed_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1528 struct strbuf err
= STRBUF_INIT
;
1529 struct ref_transaction
*transaction
;
1530 struct string_list_item
*item
;
1533 (void)refs
; /* We need the check above, but don't use the variable */
1539 * Since we don't check the references' old_oids, the
1540 * individual updates can't fail, so we can pack all of the
1541 * updates into a single transaction.
1544 transaction
= ref_store_transaction_begin(ref_store
, &err
);
1548 for_each_string_list_item(item
, refnames
) {
1549 if (ref_transaction_delete(transaction
, item
->string
, NULL
,
1550 flags
, msg
, &err
)) {
1551 warning(_("could not delete reference %s: %s"),
1552 item
->string
, err
.buf
);
1557 ret
= ref_transaction_commit(transaction
, &err
);
1560 if (refnames
->nr
== 1)
1561 error(_("could not delete reference %s: %s"),
1562 refnames
->items
[0].string
, err
.buf
);
1564 error(_("could not delete references: %s"), err
.buf
);
1567 ref_transaction_free(transaction
);
1568 strbuf_release(&err
);
1572 static int packed_pack_refs(struct ref_store
*ref_store UNUSED
,
1573 unsigned int flags UNUSED
)
1576 * Packed refs are already packed. It might be that loose refs
1577 * are packed *into* a packed refs store, but that is done by
1578 * updating the packed references via a transaction.
1583 static struct ref_iterator
*packed_reflog_iterator_begin(struct ref_store
*ref_store UNUSED
)
1585 return empty_ref_iterator_begin();
1588 struct ref_storage_be refs_be_packed
= {
1591 .init
= packed_ref_store_create
,
1592 .init_db
= packed_init_db
,
1593 .transaction_prepare
= packed_transaction_prepare
,
1594 .transaction_finish
= packed_transaction_finish
,
1595 .transaction_abort
= packed_transaction_abort
,
1596 .initial_transaction_commit
= packed_initial_transaction_commit
,
1598 .pack_refs
= packed_pack_refs
,
1599 .create_symref
= NULL
,
1600 .delete_refs
= packed_delete_refs
,
1604 .iterator_begin
= packed_ref_iterator_begin
,
1605 .read_raw_ref
= packed_read_raw_ref
,
1606 .read_symbolic_ref
= NULL
,
1608 .reflog_iterator_begin
= packed_reflog_iterator_begin
,
1609 .for_each_reflog_ent
= NULL
,
1610 .for_each_reflog_ent_reverse
= NULL
,
1611 .reflog_exists
= NULL
,
1612 .create_reflog
= NULL
,
1613 .delete_reflog
= NULL
,
1614 .reflog_expire
= NULL
,