4 #include "../gettext.h"
7 #include "refs-internal.h"
8 #include "packed-backend.h"
9 #include "../iterator.h"
10 #include "../lockfile.h"
11 #include "../chdir-notify.h"
12 #include "../write-or-die.h"
16 * Don't use mmap() at all for reading `packed-refs`.
21 * Can use mmap() for reading `packed-refs`, but the file must
22 * not remain mmapped. This is the usual option on Windows,
23 * where you cannot rename a new version of a file onto a file
24 * that is currently mmapped.
29 * It is OK to leave the `packed-refs` file mmapped while
30 * arbitrary other code is running.
36 static enum mmap_strategy mmap_strategy
= MMAP_NONE
;
37 #elif defined(MMAP_PREVENTS_DELETE)
38 static enum mmap_strategy mmap_strategy
= MMAP_TEMPORARY
;
40 static enum mmap_strategy mmap_strategy
= MMAP_OK
;
43 struct packed_ref_store
;
46 * A `snapshot` represents one snapshot of a `packed-refs` file.
48 * Normally, this will be a mmapped view of the contents of the
49 * `packed-refs` file at the time the snapshot was created. However,
50 * if the `packed-refs` file was not sorted, this might point at heap
51 * memory holding the contents of the `packed-refs` file with its
52 * records sorted by refname.
54 * `snapshot` instances are reference counted (via
55 * `acquire_snapshot()` and `release_snapshot()`). This is to prevent
56 * an instance from disappearing while an iterator is still iterating
57 * over it. Instances are garbage collected when their `referrers`
60 * The most recent `snapshot`, if available, is referenced by the
61 * `packed_ref_store`. Its freshness is checked whenever
62 * `get_snapshot()` is called; if the existing snapshot is obsolete, a
63 * new snapshot is taken.
67 * A back-pointer to the packed_ref_store with which this
68 * snapshot is associated:
70 struct packed_ref_store
*refs
;
72 /* Is the `packed-refs` file currently mmapped? */
76 * The contents of the `packed-refs` file:
78 * - buf -- a pointer to the start of the memory
79 * - start -- a pointer to the first byte of actual references
80 * (i.e., after the header line, if one is present)
81 * - eof -- a pointer just past the end of the reference
84 * If the `packed-refs` file was already sorted, `buf` points
85 * at the mmapped contents of the file. If not, it points at
86 * heap-allocated memory containing the contents, sorted. If
87 * there were no contents (e.g., because the file didn't
88 * exist), `buf`, `start`, and `eof` are all NULL.
90 char *buf
, *start
, *eof
;
93 * What is the peeled state of the `packed-refs` file that
94 * this snapshot represents? (This is usually determined from
97 enum { PEELED_NONE
, PEELED_TAGS
, PEELED_FULLY
} peeled
;
100 * Count of references to this instance, including the pointer
101 * from `packed_ref_store::snapshot`, if any. The instance
102 * will not be freed as long as the reference count is
105 unsigned int referrers
;
108 * The metadata of the `packed-refs` file from which this
109 * snapshot was created, used to tell if the file has been
110 * replaced since we read it.
112 struct stat_validity validity
;
116 * A `ref_store` representing references stored in a `packed-refs`
117 * file. It implements the `ref_store` interface, though it has some
120 * - It cannot store symbolic references.
122 * - It cannot store reflogs.
124 * - It does not support reference renaming (though it could).
126 * On the other hand, it can be locked outside of a reference
127 * transaction. In that case, it remains locked even after the
128 * transaction is done and the new `packed-refs` file is activated.
130 struct packed_ref_store
{
131 struct ref_store base
;
133 unsigned int store_flags
;
135 /* The path of the "packed-refs" file: */
139 * A snapshot of the values read from the `packed-refs` file,
140 * if it might still be current; otherwise, NULL.
142 struct snapshot
*snapshot
;
145 * Lock used for the "packed-refs" file. Note that this (and
146 * thus the enclosing `packed_ref_store`) must not be freed.
148 struct lock_file lock
;
151 * Temporary file used when rewriting new contents to the
152 * "packed-refs" file. Note that this (and thus the enclosing
153 * `packed_ref_store`) must not be freed.
155 struct tempfile
*tempfile
;
159 * Increment the reference count of `*snapshot`.
161 static void acquire_snapshot(struct snapshot
*snapshot
)
163 snapshot
->referrers
++;
167 * If the buffer in `snapshot` is active, then either munmap the
168 * memory and close the file, or free the memory. Then set the buffer
171 static void clear_snapshot_buffer(struct snapshot
*snapshot
)
173 if (snapshot
->mmapped
) {
174 if (munmap(snapshot
->buf
, snapshot
->eof
- snapshot
->buf
))
175 die_errno("error ummapping packed-refs file %s",
176 snapshot
->refs
->path
);
177 snapshot
->mmapped
= 0;
181 snapshot
->buf
= snapshot
->start
= snapshot
->eof
= NULL
;
185 * Decrease the reference count of `*snapshot`. If it goes to zero,
186 * free `*snapshot` and return true; otherwise return false.
188 static int release_snapshot(struct snapshot
*snapshot
)
190 if (!--snapshot
->referrers
) {
191 stat_validity_clear(&snapshot
->validity
);
192 clear_snapshot_buffer(snapshot
);
200 struct ref_store
*packed_ref_store_create(struct repository
*repo
,
202 unsigned int store_flags
)
204 struct packed_ref_store
*refs
= xcalloc(1, sizeof(*refs
));
205 struct ref_store
*ref_store
= (struct ref_store
*)refs
;
206 struct strbuf sb
= STRBUF_INIT
;
208 base_ref_store_init(ref_store
, repo
, gitdir
, &refs_be_packed
);
209 refs
->store_flags
= store_flags
;
211 strbuf_addf(&sb
, "%s/packed-refs", gitdir
);
212 refs
->path
= strbuf_detach(&sb
, NULL
);
213 chdir_notify_reparent("packed-refs", &refs
->path
);
218 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
219 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
220 * support at least the flags specified in `required_flags`. `caller`
221 * is used in any necessary error messages.
223 static struct packed_ref_store
*packed_downcast(struct ref_store
*ref_store
,
224 unsigned int required_flags
,
227 struct packed_ref_store
*refs
;
229 if (ref_store
->be
!= &refs_be_packed
)
230 BUG("ref_store is type \"%s\" not \"packed\" in %s",
231 ref_store
->be
->name
, caller
);
233 refs
= (struct packed_ref_store
*)ref_store
;
235 if ((refs
->store_flags
& required_flags
) != required_flags
)
236 BUG("unallowed operation (%s), requires %x, has %x\n",
237 caller
, required_flags
, refs
->store_flags
);
242 static void clear_snapshot(struct packed_ref_store
*refs
)
244 if (refs
->snapshot
) {
245 struct snapshot
*snapshot
= refs
->snapshot
;
247 refs
->snapshot
= NULL
;
248 release_snapshot(snapshot
);
252 static NORETURN
void die_unterminated_line(const char *path
,
253 const char *p
, size_t len
)
256 die("unterminated line in %s: %.*s", path
, (int)len
, p
);
258 die("unterminated line in %s: %.75s...", path
, p
);
261 static NORETURN
void die_invalid_line(const char *path
,
262 const char *p
, size_t len
)
264 const char *eol
= memchr(p
, '\n', len
);
267 die_unterminated_line(path
, p
, len
);
268 else if (eol
- p
< 80)
269 die("unexpected line in %s: %.*s", path
, (int)(eol
- p
), p
);
271 die("unexpected line in %s: %.75s...", path
, p
);
275 struct snapshot_record
{
280 static int cmp_packed_ref_records(const void *v1
, const void *v2
)
282 const struct snapshot_record
*e1
= v1
, *e2
= v2
;
283 const char *r1
= e1
->start
+ the_hash_algo
->hexsz
+ 1;
284 const char *r2
= e2
->start
+ the_hash_algo
->hexsz
+ 1;
288 return *r2
== '\n' ? 0 : -1;
293 return (unsigned char)*r1
< (unsigned char)*r2
? -1 : +1;
301 * Compare a snapshot record at `rec` to the specified NUL-terminated
304 static int cmp_record_to_refname(const char *rec
, const char *refname
)
306 const char *r1
= rec
+ the_hash_algo
->hexsz
+ 1;
307 const char *r2
= refname
;
315 return (unsigned char)*r1
< (unsigned char)*r2
? -1 : +1;
322 * `snapshot->buf` is not known to be sorted. Check whether it is, and
323 * if not, sort it into new memory and munmap/free the old storage.
325 static void sort_snapshot(struct snapshot
*snapshot
)
327 struct snapshot_record
*records
= NULL
;
328 size_t alloc
= 0, nr
= 0;
330 const char *pos
, *eof
, *eol
;
332 char *new_buffer
, *dst
;
334 pos
= snapshot
->start
;
343 * Initialize records based on a crude estimate of the number
344 * of references in the file (we'll grow it below if needed):
346 ALLOC_GROW(records
, len
/ 80 + 20, alloc
);
349 eol
= memchr(pos
, '\n', eof
- pos
);
351 /* The safety check should prevent this. */
352 BUG("unterminated line found in packed-refs");
353 if (eol
- pos
< the_hash_algo
->hexsz
+ 2)
354 die_invalid_line(snapshot
->refs
->path
,
357 if (eol
< eof
&& *eol
== '^') {
359 * Keep any peeled line together with its
362 const char *peeled_start
= eol
;
364 eol
= memchr(peeled_start
, '\n', eof
- peeled_start
);
366 /* The safety check should prevent this. */
367 BUG("unterminated peeled line found in packed-refs");
371 ALLOC_GROW(records
, nr
+ 1, alloc
);
372 records
[nr
].start
= pos
;
373 records
[nr
].len
= eol
- pos
;
378 cmp_packed_ref_records(&records
[nr
- 2],
379 &records
[nr
- 1]) >= 0)
388 /* We need to sort the memory. First we sort the records array: */
389 QSORT(records
, nr
, cmp_packed_ref_records
);
392 * Allocate a new chunk of memory, and copy the old memory to
393 * the new in the order indicated by `records` (not bothering
394 * with the header line):
396 new_buffer
= xmalloc(len
);
397 for (dst
= new_buffer
, i
= 0; i
< nr
; i
++) {
398 memcpy(dst
, records
[i
].start
, records
[i
].len
);
399 dst
+= records
[i
].len
;
403 * Now munmap the old buffer and use the sorted buffer in its
406 clear_snapshot_buffer(snapshot
);
407 snapshot
->buf
= snapshot
->start
= new_buffer
;
408 snapshot
->eof
= new_buffer
+ len
;
415 * Return a pointer to the start of the record that contains the
416 * character `*p` (which must be within the buffer). If no other
417 * record start is found, return `buf`.
419 static const char *find_start_of_record(const char *buf
, const char *p
)
421 while (p
> buf
&& (p
[-1] != '\n' || p
[0] == '^'))
427 * Return a pointer to the start of the record following the record
428 * that contains `*p`. If none is found before `end`, return `end`.
430 static const char *find_end_of_record(const char *p
, const char *end
)
432 while (++p
< end
&& (p
[-1] != '\n' || p
[0] == '^'))
438 * We want to be able to compare mmapped reference records quickly,
439 * without totally parsing them. We can do so because the records are
440 * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
441 * + 1) bytes past the beginning of the record.
443 * But what if the `packed-refs` file contains garbage? We're willing
444 * to tolerate not detecting the problem, as long as we don't produce
445 * totally garbled output (we can't afford to check the integrity of
446 * the whole file during every Git invocation). But we do want to be
447 * sure that we never read past the end of the buffer in memory and
448 * perform an illegal memory access.
450 * Guarantee that minimum level of safety by verifying that the last
451 * record in the file is LF-terminated, and that it has at least
452 * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
453 * these checks fails.
455 static void verify_buffer_safe(struct snapshot
*snapshot
)
457 const char *start
= snapshot
->start
;
458 const char *eof
= snapshot
->eof
;
459 const char *last_line
;
464 last_line
= find_start_of_record(start
, eof
- 1);
465 if (*(eof
- 1) != '\n' || eof
- last_line
< the_hash_algo
->hexsz
+ 2)
466 die_invalid_line(snapshot
->refs
->path
,
467 last_line
, eof
- last_line
);
470 #define SMALL_FILE_SIZE (32*1024)
473 * Depending on `mmap_strategy`, either mmap or read the contents of
474 * the `packed-refs` file into the snapshot. Return 1 if the file
475 * existed and was read, or 0 if the file was absent or empty. Die on
478 static int load_contents(struct snapshot
*snapshot
)
485 fd
= open(snapshot
->refs
->path
, O_RDONLY
);
487 if (errno
== ENOENT
) {
489 * This is OK; it just means that no
490 * "packed-refs" file has been written yet,
491 * which is equivalent to it being empty,
492 * which is its state when initialized with
497 die_errno("couldn't read %s", snapshot
->refs
->path
);
501 stat_validity_update(&snapshot
->validity
, fd
);
503 if (fstat(fd
, &st
) < 0)
504 die_errno("couldn't stat %s", snapshot
->refs
->path
);
505 size
= xsize_t(st
.st_size
);
510 } else if (mmap_strategy
== MMAP_NONE
|| size
<= SMALL_FILE_SIZE
) {
511 snapshot
->buf
= xmalloc(size
);
512 bytes_read
= read_in_full(fd
, snapshot
->buf
, size
);
513 if (bytes_read
< 0 || bytes_read
!= size
)
514 die_errno("couldn't read %s", snapshot
->refs
->path
);
515 snapshot
->mmapped
= 0;
517 snapshot
->buf
= xmmap(NULL
, size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
518 snapshot
->mmapped
= 1;
522 snapshot
->start
= snapshot
->buf
;
523 snapshot
->eof
= snapshot
->buf
+ size
;
529 * Find the place in `snapshot->buf` where the start of the record for
530 * `refname` starts. If `mustexist` is true and the reference doesn't
531 * exist, then return NULL. If `mustexist` is false and the reference
532 * doesn't exist, then return the point where that reference would be
533 * inserted, or `snapshot->eof` (which might be NULL) if it would be
534 * inserted at the end of the file. In the latter mode, `refname`
535 * doesn't have to be a proper reference name; for example, one could
536 * search for "refs/replace/" to find the start of any replace
539 * The record is sought using a binary search, so `snapshot->buf` must
542 static const char *find_reference_location(struct snapshot
*snapshot
,
543 const char *refname
, int mustexist
)
546 * This is not *quite* a garden-variety binary search, because
547 * the data we're searching is made up of records, and we
548 * always need to find the beginning of a record to do a
549 * comparison. A "record" here is one line for the reference
550 * itself and zero or one peel lines that start with '^'. Our
551 * loop invariant is described in the next two comments.
555 * A pointer to the character at the start of a record whose
556 * preceding records all have reference names that come
557 * *before* `refname`.
559 const char *lo
= snapshot
->start
;
562 * A pointer to a the first character of a record whose
563 * reference name comes *after* `refname`.
565 const char *hi
= snapshot
->eof
;
568 const char *mid
, *rec
;
571 mid
= lo
+ (hi
- lo
) / 2;
572 rec
= find_start_of_record(lo
, mid
);
573 cmp
= cmp_record_to_refname(rec
, refname
);
575 lo
= find_end_of_record(mid
, hi
);
576 } else if (cmp
> 0) {
590 * Create a newly-allocated `snapshot` of the `packed-refs` file in
591 * its current state and return it. The return value will already have
592 * its reference count incremented.
594 * A comment line of the form "# pack-refs with: " may contain zero or
595 * more traits. We interpret the traits as follows:
597 * Neither `peeled` nor `fully-peeled`:
599 * Probably no references are peeled. But if the file contains a
600 * peeled value for a reference, we will use it.
604 * References under "refs/tags/", if they *can* be peeled, *are*
605 * peeled in this file. References outside of "refs/tags/" are
606 * probably not peeled even if they could have been, but if we find
607 * a peeled value for such a reference we will use it.
611 * All references in the file that can be peeled are peeled.
612 * Inversely (and this is more important), any references in the
613 * file for which no peeled value is recorded is not peelable. This
614 * trait should typically be written alongside "peeled" for
615 * compatibility with older clients, but we do not require it
616 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
620 * The references in this file are known to be sorted by refname.
622 static struct snapshot
*create_snapshot(struct packed_ref_store
*refs
)
624 struct snapshot
*snapshot
= xcalloc(1, sizeof(*snapshot
));
627 snapshot
->refs
= refs
;
628 acquire_snapshot(snapshot
);
629 snapshot
->peeled
= PEELED_NONE
;
631 if (!load_contents(snapshot
))
634 /* If the file has a header line, process it: */
635 if (snapshot
->buf
< snapshot
->eof
&& *snapshot
->buf
== '#') {
637 struct string_list traits
= STRING_LIST_INIT_NODUP
;
639 eol
= memchr(snapshot
->buf
, '\n',
640 snapshot
->eof
- snapshot
->buf
);
642 die_unterminated_line(refs
->path
,
644 snapshot
->eof
- snapshot
->buf
);
646 tmp
= xmemdupz(snapshot
->buf
, eol
- snapshot
->buf
);
648 if (!skip_prefix(tmp
, "# pack-refs with:", (const char **)&p
))
649 die_invalid_line(refs
->path
,
651 snapshot
->eof
- snapshot
->buf
);
653 string_list_split_in_place(&traits
, p
, " ", -1);
655 if (unsorted_string_list_has_string(&traits
, "fully-peeled"))
656 snapshot
->peeled
= PEELED_FULLY
;
657 else if (unsorted_string_list_has_string(&traits
, "peeled"))
658 snapshot
->peeled
= PEELED_TAGS
;
660 sorted
= unsorted_string_list_has_string(&traits
, "sorted");
662 /* perhaps other traits later as well */
664 /* The "+ 1" is for the LF character. */
665 snapshot
->start
= eol
+ 1;
667 string_list_clear(&traits
, 0);
671 verify_buffer_safe(snapshot
);
674 sort_snapshot(snapshot
);
677 * Reordering the records might have moved a short one
678 * to the end of the buffer, so verify the buffer's
681 verify_buffer_safe(snapshot
);
684 if (mmap_strategy
!= MMAP_OK
&& snapshot
->mmapped
) {
686 * We don't want to leave the file mmapped, so we are
687 * forced to make a copy now:
689 size_t size
= snapshot
->eof
- snapshot
->start
;
690 char *buf_copy
= xmalloc(size
);
692 memcpy(buf_copy
, snapshot
->start
, size
);
693 clear_snapshot_buffer(snapshot
);
694 snapshot
->buf
= snapshot
->start
= buf_copy
;
695 snapshot
->eof
= buf_copy
+ size
;
702 * Check that `refs->snapshot` (if present) still reflects the
703 * contents of the `packed-refs` file. If not, clear the snapshot.
705 static void validate_snapshot(struct packed_ref_store
*refs
)
707 if (refs
->snapshot
&&
708 !stat_validity_check(&refs
->snapshot
->validity
, refs
->path
))
709 clear_snapshot(refs
);
713 * Get the `snapshot` for the specified packed_ref_store, creating and
714 * populating it if it hasn't been read before or if the file has been
715 * changed (according to its `validity` field) since it was last read.
716 * On the other hand, if we hold the lock, then assume that the file
717 * hasn't been changed out from under us, so skip the extra `stat()`
718 * call in `stat_validity_check()`. This function does *not* increase
719 * the snapshot's reference count on behalf of the caller.
721 static struct snapshot
*get_snapshot(struct packed_ref_store
*refs
)
723 if (!is_lock_file_locked(&refs
->lock
))
724 validate_snapshot(refs
);
727 refs
->snapshot
= create_snapshot(refs
);
729 return refs
->snapshot
;
732 static int packed_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
733 struct object_id
*oid
, struct strbuf
*referent UNUSED
,
734 unsigned int *type
, int *failure_errno
)
736 struct packed_ref_store
*refs
=
737 packed_downcast(ref_store
, REF_STORE_READ
, "read_raw_ref");
738 struct snapshot
*snapshot
= get_snapshot(refs
);
743 rec
= find_reference_location(snapshot
, refname
, 1);
746 /* refname is not a packed reference. */
747 *failure_errno
= ENOENT
;
751 if (get_oid_hex(rec
, oid
))
752 die_invalid_line(refs
->path
, rec
, snapshot
->eof
- rec
);
754 *type
= REF_ISPACKED
;
759 * This value is set in `base.flags` if the peeled value of the
760 * current reference is known. In that case, `peeled` contains the
761 * correct peeled value for the reference, which might be `null_oid`
762 * if the reference is not a tag or if it is broken.
764 #define REF_KNOWS_PEELED 0x40
767 * An iterator over a snapshot of a `packed-refs` file.
769 struct packed_ref_iterator
{
770 struct ref_iterator base
;
772 struct snapshot
*snapshot
;
774 /* The current position in the snapshot's buffer: */
777 /* The end of the part of the buffer that will be iterated over: */
780 /* Scratch space for current values: */
781 struct object_id oid
, peeled
;
782 struct strbuf refname_buf
;
784 struct repository
*repo
;
789 * Move the iterator to the next record in the snapshot, without
790 * respect for whether the record is actually required by the current
791 * iteration. Adjust the fields in `iter` and return `ITER_OK` or
792 * `ITER_DONE`. This function does not free the iterator in the case
795 static int next_record(struct packed_ref_iterator
*iter
)
797 const char *p
= iter
->pos
, *eol
;
799 strbuf_reset(&iter
->refname_buf
);
801 if (iter
->pos
== iter
->eof
)
804 iter
->base
.flags
= REF_ISPACKED
;
806 if (iter
->eof
- p
< the_hash_algo
->hexsz
+ 2 ||
807 parse_oid_hex(p
, &iter
->oid
, &p
) ||
809 die_invalid_line(iter
->snapshot
->refs
->path
,
810 iter
->pos
, iter
->eof
- iter
->pos
);
812 eol
= memchr(p
, '\n', iter
->eof
- p
);
814 die_unterminated_line(iter
->snapshot
->refs
->path
,
815 iter
->pos
, iter
->eof
- iter
->pos
);
817 strbuf_add(&iter
->refname_buf
, p
, eol
- p
);
818 iter
->base
.refname
= iter
->refname_buf
.buf
;
820 if (check_refname_format(iter
->base
.refname
, REFNAME_ALLOW_ONELEVEL
)) {
821 if (!refname_is_safe(iter
->base
.refname
))
822 die("packed refname is dangerous: %s",
825 iter
->base
.flags
|= REF_BAD_NAME
| REF_ISBROKEN
;
827 if (iter
->snapshot
->peeled
== PEELED_FULLY
||
828 (iter
->snapshot
->peeled
== PEELED_TAGS
&&
829 starts_with(iter
->base
.refname
, "refs/tags/")))
830 iter
->base
.flags
|= REF_KNOWS_PEELED
;
834 if (iter
->pos
< iter
->eof
&& *iter
->pos
== '^') {
836 if (iter
->eof
- p
< the_hash_algo
->hexsz
+ 1 ||
837 parse_oid_hex(p
, &iter
->peeled
, &p
) ||
839 die_invalid_line(iter
->snapshot
->refs
->path
,
840 iter
->pos
, iter
->eof
- iter
->pos
);
844 * Regardless of what the file header said, we
845 * definitely know the value of *this* reference. But
846 * we suppress it if the reference is broken:
848 if ((iter
->base
.flags
& REF_ISBROKEN
)) {
849 oidclr(&iter
->peeled
);
850 iter
->base
.flags
&= ~REF_KNOWS_PEELED
;
852 iter
->base
.flags
|= REF_KNOWS_PEELED
;
855 oidclr(&iter
->peeled
);
861 static int packed_ref_iterator_advance(struct ref_iterator
*ref_iterator
)
863 struct packed_ref_iterator
*iter
=
864 (struct packed_ref_iterator
*)ref_iterator
;
867 while ((ok
= next_record(iter
)) == ITER_OK
) {
868 if (iter
->flags
& DO_FOR_EACH_PER_WORKTREE_ONLY
&&
869 !is_per_worktree_ref(iter
->base
.refname
))
872 if (!(iter
->flags
& DO_FOR_EACH_INCLUDE_BROKEN
) &&
873 !ref_resolves_to_object(iter
->base
.refname
, iter
->repo
,
874 &iter
->oid
, iter
->flags
))
880 if (ref_iterator_abort(ref_iterator
) != ITER_DONE
)
886 static int packed_ref_iterator_peel(struct ref_iterator
*ref_iterator
,
887 struct object_id
*peeled
)
889 struct packed_ref_iterator
*iter
=
890 (struct packed_ref_iterator
*)ref_iterator
;
892 if (iter
->repo
!= the_repository
)
893 BUG("peeling for non-the_repository is not supported");
895 if ((iter
->base
.flags
& REF_KNOWS_PEELED
)) {
896 oidcpy(peeled
, &iter
->peeled
);
897 return is_null_oid(&iter
->peeled
) ? -1 : 0;
898 } else if ((iter
->base
.flags
& (REF_ISBROKEN
| REF_ISSYMREF
))) {
901 return peel_object(&iter
->oid
, peeled
) ? -1 : 0;
905 static int packed_ref_iterator_abort(struct ref_iterator
*ref_iterator
)
907 struct packed_ref_iterator
*iter
=
908 (struct packed_ref_iterator
*)ref_iterator
;
911 strbuf_release(&iter
->refname_buf
);
912 release_snapshot(iter
->snapshot
);
913 base_ref_iterator_free(ref_iterator
);
917 static struct ref_iterator_vtable packed_ref_iterator_vtable
= {
918 .advance
= packed_ref_iterator_advance
,
919 .peel
= packed_ref_iterator_peel
,
920 .abort
= packed_ref_iterator_abort
923 static struct ref_iterator
*packed_ref_iterator_begin(
924 struct ref_store
*ref_store
,
925 const char *prefix
, unsigned int flags
)
927 struct packed_ref_store
*refs
;
928 struct snapshot
*snapshot
;
930 struct packed_ref_iterator
*iter
;
931 struct ref_iterator
*ref_iterator
;
932 unsigned int required_flags
= REF_STORE_READ
;
934 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
))
935 required_flags
|= REF_STORE_ODB
;
936 refs
= packed_downcast(ref_store
, required_flags
, "ref_iterator_begin");
939 * Note that `get_snapshot()` internally checks whether the
940 * snapshot is up to date with what is on disk, and re-reads
943 snapshot
= get_snapshot(refs
);
945 if (prefix
&& *prefix
)
946 start
= find_reference_location(snapshot
, prefix
, 0);
948 start
= snapshot
->start
;
950 if (start
== snapshot
->eof
)
951 return empty_ref_iterator_begin();
953 CALLOC_ARRAY(iter
, 1);
954 ref_iterator
= &iter
->base
;
955 base_ref_iterator_init(ref_iterator
, &packed_ref_iterator_vtable
, 1);
957 iter
->snapshot
= snapshot
;
958 acquire_snapshot(snapshot
);
961 iter
->eof
= snapshot
->eof
;
962 strbuf_init(&iter
->refname_buf
, 0);
964 iter
->base
.oid
= &iter
->oid
;
966 iter
->repo
= ref_store
->repo
;
969 if (prefix
&& *prefix
)
970 /* Stop iteration after we've gone *past* prefix: */
971 ref_iterator
= prefix_ref_iterator_begin(ref_iterator
, prefix
, 0);
977 * Write an entry to the packed-refs file for the specified refname.
978 * If peeled is non-NULL, write it as the entry's peeled value. On
979 * error, return a nonzero value and leave errno set at the value left
980 * by the failing call to `fprintf()`.
982 static int write_packed_entry(FILE *fh
, const char *refname
,
983 const struct object_id
*oid
,
984 const struct object_id
*peeled
)
986 if (fprintf(fh
, "%s %s\n", oid_to_hex(oid
), refname
) < 0 ||
987 (peeled
&& fprintf(fh
, "^%s\n", oid_to_hex(peeled
)) < 0))
993 int packed_refs_lock(struct ref_store
*ref_store
, int flags
, struct strbuf
*err
)
995 struct packed_ref_store
*refs
=
996 packed_downcast(ref_store
, REF_STORE_WRITE
| REF_STORE_MAIN
,
998 static int timeout_configured
= 0;
999 static int timeout_value
= 1000;
1001 if (!timeout_configured
) {
1002 git_config_get_int("core.packedrefstimeout", &timeout_value
);
1003 timeout_configured
= 1;
1007 * Note that we close the lockfile immediately because we
1008 * don't write new content to it, but rather to a separate
1011 if (hold_lock_file_for_update_timeout(
1014 flags
, timeout_value
) < 0) {
1015 unable_to_lock_message(refs
->path
, errno
, err
);
1019 if (close_lock_file_gently(&refs
->lock
)) {
1020 strbuf_addf(err
, "unable to close %s: %s", refs
->path
, strerror(errno
));
1021 rollback_lock_file(&refs
->lock
);
1026 * There is a stat-validity problem might cause `update-ref -d`
1027 * lost the newly commit of a ref, because a new `packed-refs`
1028 * file might has the same on-disk file attributes such as
1029 * timestamp, file size and inode value, but has a changed
1032 * This could happen with a very small chance when
1033 * `update-ref -d` is called and at the same time another
1034 * `pack-refs --all` process is running.
1036 * Now that we hold the `packed-refs` lock, it is important
1037 * to make sure we could read the latest version of
1038 * `packed-refs` file no matter we have just mmap it or not.
1039 * So what need to do is clear the snapshot if we hold it
1042 clear_snapshot(refs
);
1045 * Now make sure that the packed-refs file as it exists in the
1046 * locked state is loaded into the snapshot:
1052 void packed_refs_unlock(struct ref_store
*ref_store
)
1054 struct packed_ref_store
*refs
= packed_downcast(
1056 REF_STORE_READ
| REF_STORE_WRITE
,
1057 "packed_refs_unlock");
1059 if (!is_lock_file_locked(&refs
->lock
))
1060 BUG("packed_refs_unlock() called when not locked");
1061 rollback_lock_file(&refs
->lock
);
1064 int packed_refs_is_locked(struct ref_store
*ref_store
)
1066 struct packed_ref_store
*refs
= packed_downcast(
1068 REF_STORE_READ
| REF_STORE_WRITE
,
1069 "packed_refs_is_locked");
1071 return is_lock_file_locked(&refs
->lock
);
1075 * The packed-refs header line that we write out. Perhaps other traits
1076 * will be added later.
1078 * Note that earlier versions of Git used to parse these traits by
1079 * looking for " trait " in the line. For this reason, the space after
1080 * the colon and the trailing space are required.
1082 static const char PACKED_REFS_HEADER
[] =
1083 "# pack-refs with: peeled fully-peeled sorted \n";
1085 static int packed_init_db(struct ref_store
*ref_store UNUSED
,
1086 struct strbuf
*err UNUSED
)
1088 /* Nothing to do. */
1093 * Write the packed refs from the current snapshot to the packed-refs
1094 * tempfile, incorporating any changes from `updates`. `updates` must
1095 * be a sorted string list whose keys are the refnames and whose util
1096 * values are `struct ref_update *`. On error, rollback the tempfile,
1097 * write an error message to `err`, and return a nonzero value.
1099 * The packfile must be locked before calling this function and will
1100 * remain locked when it is done.
1102 static int write_with_updates(struct packed_ref_store
*refs
,
1103 struct string_list
*updates
,
1106 struct ref_iterator
*iter
= NULL
;
1110 struct strbuf sb
= STRBUF_INIT
;
1111 char *packed_refs_path
;
1113 if (!is_lock_file_locked(&refs
->lock
))
1114 BUG("write_with_updates() called while unlocked");
1117 * If packed-refs is a symlink, we want to overwrite the
1118 * symlinked-to file, not the symlink itself. Also, put the
1119 * staging file next to it:
1121 packed_refs_path
= get_locked_file_path(&refs
->lock
);
1122 strbuf_addf(&sb
, "%s.new", packed_refs_path
);
1123 free(packed_refs_path
);
1124 refs
->tempfile
= create_tempfile(sb
.buf
);
1125 if (!refs
->tempfile
) {
1126 strbuf_addf(err
, "unable to create file %s: %s",
1127 sb
.buf
, strerror(errno
));
1128 strbuf_release(&sb
);
1131 strbuf_release(&sb
);
1133 out
= fdopen_tempfile(refs
->tempfile
, "w");
1135 strbuf_addf(err
, "unable to fdopen packed-refs tempfile: %s",
1140 if (fprintf(out
, "%s", PACKED_REFS_HEADER
) < 0)
1144 * We iterate in parallel through the current list of refs and
1145 * the list of updates, processing an entry from at least one
1146 * of the lists each time through the loop. When the current
1147 * list of refs is exhausted, set iter to NULL. When the list
1148 * of updates is exhausted, leave i set to updates->nr.
1150 iter
= packed_ref_iterator_begin(&refs
->base
, "",
1151 DO_FOR_EACH_INCLUDE_BROKEN
);
1152 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1157 while (iter
|| i
< updates
->nr
) {
1158 struct ref_update
*update
= NULL
;
1161 if (i
>= updates
->nr
) {
1164 update
= updates
->items
[i
].util
;
1169 cmp
= strcmp(iter
->refname
, update
->refname
);
1174 * There is both an old value and an update
1175 * for this reference. Check the old value if
1178 if ((update
->flags
& REF_HAVE_OLD
)) {
1179 if (is_null_oid(&update
->old_oid
)) {
1180 strbuf_addf(err
, "cannot update ref '%s': "
1181 "reference already exists",
1184 } else if (!oideq(&update
->old_oid
, iter
->oid
)) {
1185 strbuf_addf(err
, "cannot update ref '%s': "
1186 "is at %s but expected %s",
1188 oid_to_hex(iter
->oid
),
1189 oid_to_hex(&update
->old_oid
));
1194 /* Now figure out what to use for the new value: */
1195 if ((update
->flags
& REF_HAVE_NEW
)) {
1197 * The update takes precedence. Skip
1198 * the iterator over the unneeded
1201 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1206 * The update doesn't actually want to
1207 * change anything. We're done with it.
1212 } else if (cmp
> 0) {
1214 * There is no old value but there is an
1215 * update for this reference. Make sure that
1216 * the update didn't expect an existing value:
1218 if ((update
->flags
& REF_HAVE_OLD
) &&
1219 !is_null_oid(&update
->old_oid
)) {
1220 strbuf_addf(err
, "cannot update ref '%s': "
1221 "reference is missing but expected %s",
1223 oid_to_hex(&update
->old_oid
));
1229 /* Pass the old reference through. */
1231 struct object_id peeled
;
1232 int peel_error
= ref_iterator_peel(iter
, &peeled
);
1234 if (write_packed_entry(out
, iter
->refname
,
1236 peel_error
? NULL
: &peeled
))
1239 if ((ok
= ref_iterator_advance(iter
)) != ITER_OK
)
1241 } else if (is_null_oid(&update
->new_oid
)) {
1243 * The update wants to delete the reference,
1244 * and the reference either didn't exist or we
1245 * have already skipped it. So we're done with
1246 * the update (and don't have to write
1251 struct object_id peeled
;
1252 int peel_error
= peel_object(&update
->new_oid
,
1255 if (write_packed_entry(out
, update
->refname
,
1257 peel_error
? NULL
: &peeled
))
1264 if (ok
!= ITER_DONE
) {
1265 strbuf_addstr(err
, "unable to write packed-refs file: "
1266 "error iterating over old contents");
1271 fsync_component(FSYNC_COMPONENT_REFERENCE
, get_tempfile_fd(refs
->tempfile
)) ||
1272 close_tempfile_gently(refs
->tempfile
)) {
1273 strbuf_addf(err
, "error closing file %s: %s",
1274 get_tempfile_path(refs
->tempfile
),
1276 strbuf_release(&sb
);
1277 delete_tempfile(&refs
->tempfile
);
1284 strbuf_addf(err
, "error writing to %s: %s",
1285 get_tempfile_path(refs
->tempfile
), strerror(errno
));
1289 ref_iterator_abort(iter
);
1291 delete_tempfile(&refs
->tempfile
);
1295 int is_packed_transaction_needed(struct ref_store
*ref_store
,
1296 struct ref_transaction
*transaction
)
1298 struct packed_ref_store
*refs
= packed_downcast(
1301 "is_packed_transaction_needed");
1302 struct strbuf referent
= STRBUF_INIT
;
1306 if (!is_lock_file_locked(&refs
->lock
))
1307 BUG("is_packed_transaction_needed() called while unlocked");
1310 * We're only going to bother returning false for the common,
1311 * trivial case that references are only being deleted, their
1312 * old values are not being checked, and the old `packed-refs`
1313 * file doesn't contain any of those reference(s). This gives
1314 * false positives for some other cases that could
1315 * theoretically be optimized away:
1317 * 1. It could be that the old value is being verified without
1318 * setting a new value. In this case, we could verify the
1319 * old value here and skip the update if it agrees. If it
1320 * disagrees, we could either let the update go through
1321 * (the actual commit would re-detect and report the
1322 * problem), or come up with a way of reporting such an
1323 * error to *our* caller.
1325 * 2. It could be that a new value is being set, but that it
1326 * is identical to the current packed value of the
1329 * Neither of these cases will come up in the current code,
1330 * because the only caller of this function passes to it a
1331 * transaction that only includes `delete` updates with no
1332 * `old_id`. Even if that ever changes, false positives only
1333 * cause an optimization to be missed; they do not affect
1338 * Start with the cheap checks that don't require old
1339 * reference values to be read:
1341 for (i
= 0; i
< transaction
->nr
; i
++) {
1342 struct ref_update
*update
= transaction
->updates
[i
];
1344 if (update
->flags
& REF_HAVE_OLD
)
1345 /* Have to check the old value -> needed. */
1348 if ((update
->flags
& REF_HAVE_NEW
) && !is_null_oid(&update
->new_oid
))
1349 /* Have to set a new value -> needed. */
1354 * The transaction isn't checking any old values nor is it
1355 * setting any nonzero new values, so it still might be able
1356 * to be skipped. Now do the more expensive check: the update
1357 * is needed if any of the updates is a delete, and the old
1358 * `packed-refs` file contains a value for that reference.
1361 for (i
= 0; i
< transaction
->nr
; i
++) {
1362 struct ref_update
*update
= transaction
->updates
[i
];
1365 struct object_id oid
;
1367 if (!(update
->flags
& REF_HAVE_NEW
))
1369 * This reference isn't being deleted -> not
1374 if (!refs_read_raw_ref(ref_store
, update
->refname
, &oid
,
1375 &referent
, &type
, &failure_errno
) ||
1376 failure_errno
!= ENOENT
) {
1378 * We have to actually delete that reference
1379 * -> this transaction is needed.
1386 strbuf_release(&referent
);
1390 struct packed_transaction_backend_data
{
1391 /* True iff the transaction owns the packed-refs lock. */
1394 struct string_list updates
;
1397 static void packed_transaction_cleanup(struct packed_ref_store
*refs
,
1398 struct ref_transaction
*transaction
)
1400 struct packed_transaction_backend_data
*data
= transaction
->backend_data
;
1403 string_list_clear(&data
->updates
, 0);
1405 if (is_tempfile_active(refs
->tempfile
))
1406 delete_tempfile(&refs
->tempfile
);
1408 if (data
->own_lock
&& is_lock_file_locked(&refs
->lock
)) {
1409 packed_refs_unlock(&refs
->base
);
1414 transaction
->backend_data
= NULL
;
1417 transaction
->state
= REF_TRANSACTION_CLOSED
;
1420 static int packed_transaction_prepare(struct ref_store
*ref_store
,
1421 struct ref_transaction
*transaction
,
1424 struct packed_ref_store
*refs
= packed_downcast(
1426 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1427 "ref_transaction_prepare");
1428 struct packed_transaction_backend_data
*data
;
1430 int ret
= TRANSACTION_GENERIC_ERROR
;
1433 * Note that we *don't* skip transactions with zero updates,
1434 * because such a transaction might be executed for the side
1435 * effect of ensuring that all of the references are peeled or
1436 * ensuring that the `packed-refs` file is sorted. If the
1437 * caller wants to optimize away empty transactions, it should
1441 CALLOC_ARRAY(data
, 1);
1442 string_list_init_nodup(&data
->updates
);
1444 transaction
->backend_data
= data
;
1447 * Stick the updates in a string list by refname so that we
1450 for (i
= 0; i
< transaction
->nr
; i
++) {
1451 struct ref_update
*update
= transaction
->updates
[i
];
1452 struct string_list_item
*item
=
1453 string_list_append(&data
->updates
, update
->refname
);
1455 /* Store a pointer to update in item->util: */
1456 item
->util
= update
;
1458 string_list_sort(&data
->updates
);
1460 if (ref_update_reject_duplicates(&data
->updates
, err
))
1463 if (!is_lock_file_locked(&refs
->lock
)) {
1464 if (packed_refs_lock(ref_store
, 0, err
))
1469 if (write_with_updates(refs
, &data
->updates
, err
))
1472 transaction
->state
= REF_TRANSACTION_PREPARED
;
1476 packed_transaction_cleanup(refs
, transaction
);
1480 static int packed_transaction_abort(struct ref_store
*ref_store
,
1481 struct ref_transaction
*transaction
,
1482 struct strbuf
*err UNUSED
)
1484 struct packed_ref_store
*refs
= packed_downcast(
1486 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1487 "ref_transaction_abort");
1489 packed_transaction_cleanup(refs
, transaction
);
1493 static int packed_transaction_finish(struct ref_store
*ref_store
,
1494 struct ref_transaction
*transaction
,
1497 struct packed_ref_store
*refs
= packed_downcast(
1499 REF_STORE_READ
| REF_STORE_WRITE
| REF_STORE_ODB
,
1500 "ref_transaction_finish");
1501 int ret
= TRANSACTION_GENERIC_ERROR
;
1502 char *packed_refs_path
;
1504 clear_snapshot(refs
);
1506 packed_refs_path
= get_locked_file_path(&refs
->lock
);
1507 if (rename_tempfile(&refs
->tempfile
, packed_refs_path
)) {
1508 strbuf_addf(err
, "error replacing %s: %s",
1509 refs
->path
, strerror(errno
));
1516 free(packed_refs_path
);
1517 packed_transaction_cleanup(refs
, transaction
);
1521 static int packed_initial_transaction_commit(struct ref_store
*ref_store UNUSED
,
1522 struct ref_transaction
*transaction
,
1525 return ref_transaction_commit(transaction
, err
);
1528 static int packed_delete_refs(struct ref_store
*ref_store
, const char *msg
,
1529 struct string_list
*refnames
, unsigned int flags
)
1531 struct packed_ref_store
*refs
=
1532 packed_downcast(ref_store
, REF_STORE_WRITE
, "delete_refs");
1533 struct strbuf err
= STRBUF_INIT
;
1534 struct ref_transaction
*transaction
;
1535 struct string_list_item
*item
;
1538 (void)refs
; /* We need the check above, but don't use the variable */
1544 * Since we don't check the references' old_oids, the
1545 * individual updates can't fail, so we can pack all of the
1546 * updates into a single transaction.
1549 transaction
= ref_store_transaction_begin(ref_store
, &err
);
1553 for_each_string_list_item(item
, refnames
) {
1554 if (ref_transaction_delete(transaction
, item
->string
, NULL
,
1555 flags
, msg
, &err
)) {
1556 warning(_("could not delete reference %s: %s"),
1557 item
->string
, err
.buf
);
1562 ret
= ref_transaction_commit(transaction
, &err
);
1565 if (refnames
->nr
== 1)
1566 error(_("could not delete reference %s: %s"),
1567 refnames
->items
[0].string
, err
.buf
);
1569 error(_("could not delete references: %s"), err
.buf
);
1572 ref_transaction_free(transaction
);
1573 strbuf_release(&err
);
1577 static int packed_pack_refs(struct ref_store
*ref_store UNUSED
,
1578 unsigned int flags UNUSED
)
1581 * Packed refs are already packed. It might be that loose refs
1582 * are packed *into* a packed refs store, but that is done by
1583 * updating the packed references via a transaction.
1588 static struct ref_iterator
*packed_reflog_iterator_begin(struct ref_store
*ref_store UNUSED
)
1590 return empty_ref_iterator_begin();
1593 struct ref_storage_be refs_be_packed
= {
1596 .init
= packed_ref_store_create
,
1597 .init_db
= packed_init_db
,
1598 .transaction_prepare
= packed_transaction_prepare
,
1599 .transaction_finish
= packed_transaction_finish
,
1600 .transaction_abort
= packed_transaction_abort
,
1601 .initial_transaction_commit
= packed_initial_transaction_commit
,
1603 .pack_refs
= packed_pack_refs
,
1604 .create_symref
= NULL
,
1605 .delete_refs
= packed_delete_refs
,
1609 .iterator_begin
= packed_ref_iterator_begin
,
1610 .read_raw_ref
= packed_read_raw_ref
,
1611 .read_symbolic_ref
= NULL
,
1613 .reflog_iterator_begin
= packed_reflog_iterator_begin
,
1614 .for_each_reflog_ent
= NULL
,
1615 .for_each_reflog_ent_reverse
= NULL
,
1616 .reflog_exists
= NULL
,
1617 .create_reflog
= NULL
,
1618 .delete_reflog
= NULL
,
1619 .reflog_expire
= NULL
,