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(const char *path,
197 unsigned int store_flags)
199 struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
200 struct ref_store *ref_store = (struct ref_store *)refs;
202 base_ref_store_init(ref_store, &refs_be_packed);
203 ref_store->gitdir = xstrdup(path);
204 refs->store_flags = store_flags;
206 refs->path = xstrdup(path);
207 chdir_notify_reparent("packed-refs", &refs->path);
213 * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
214 * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
215 * support at least the flags specified in `required_flags`. `caller`
216 * is used in any necessary error messages.
218 static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
219 unsigned int required_flags,
222 struct packed_ref_store *refs;
224 if (ref_store->be != &refs_be_packed)
225 BUG("ref_store is type \"%s\" not \"packed\" in %s",
226 ref_store->be->name, caller);
228 refs = (struct packed_ref_store *)ref_store;
230 if ((refs->store_flags & required_flags) != required_flags)
231 BUG("unallowed operation (%s), requires %x, has %x\n",
232 caller, required_flags, refs->store_flags);
237 static void clear_snapshot(struct packed_ref_store *refs)
239 if (refs->snapshot) {
240 struct snapshot *snapshot = refs->snapshot;
242 refs->snapshot = NULL;
243 release_snapshot(snapshot);
247 static NORETURN void die_unterminated_line(const char *path,
248 const char *p, size_t len)
251 die("unterminated line in %s: %.*s", path, (int)len, p);
253 die("unterminated line in %s: %.75s...", path, p);
256 static NORETURN void die_invalid_line(const char *path,
257 const char *p, size_t len)
259 const char *eol = memchr(p, '\n', len);
262 die_unterminated_line(path, p, len);
263 else if (eol - p < 80)
264 die("unexpected line in %s: %.*s", path, (int)(eol - p), p);
266 die("unexpected line in %s: %.75s...", path, p);
270 struct snapshot_record {
275 static int cmp_packed_ref_records(const void *v1, const void *v2)
277 const struct snapshot_record *e1 = v1, *e2 = v2;
278 const char *r1 = e1->start + the_hash_algo->hexsz + 1;
279 const char *r2 = e2->start + the_hash_algo->hexsz + 1;
283 return *r2 == '\n' ? 0 : -1;
288 return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
296 * Compare a snapshot record at `rec` to the specified NUL-terminated
299 static int cmp_record_to_refname(const char *rec, const char *refname)
301 const char *r1 = rec + the_hash_algo->hexsz + 1;
302 const char *r2 = refname;
310 return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
317 * `snapshot->buf` is not known to be sorted. Check whether it is, and
318 * if not, sort it into new memory and munmap/free the old storage.
320 static void sort_snapshot(struct snapshot *snapshot)
322 struct snapshot_record *records = NULL;
323 size_t alloc = 0, nr = 0;
325 const char *pos, *eof, *eol;
327 char *new_buffer, *dst;
329 pos = snapshot->start;
338 * Initialize records based on a crude estimate of the number
339 * of references in the file (we'll grow it below if needed):
341 ALLOC_GROW(records, len / 80 + 20, alloc);
344 eol = memchr(pos, '\n', eof - pos);
346 /* The safety check should prevent this. */
347 BUG("unterminated line found in packed-refs");
348 if (eol - pos < the_hash_algo->hexsz + 2)
349 die_invalid_line(snapshot->refs->path,
352 if (eol < eof && *eol == '^') {
354 * Keep any peeled line together with its
357 const char *peeled_start = eol;
359 eol = memchr(peeled_start, '\n', eof - peeled_start);
361 /* The safety check should prevent this. */
362 BUG("unterminated peeled line found in packed-refs");
366 ALLOC_GROW(records, nr + 1, alloc);
367 records[nr].start = pos;
368 records[nr].len = eol - pos;
373 cmp_packed_ref_records(&records[nr - 2],
374 &records[nr - 1]) >= 0)
383 /* We need to sort the memory. First we sort the records array: */
384 QSORT(records, nr, cmp_packed_ref_records);
387 * Allocate a new chunk of memory, and copy the old memory to
388 * the new in the order indicated by `records` (not bothering
389 * with the header line):
391 new_buffer = xmalloc(len);
392 for (dst = new_buffer, i = 0; i < nr; i++) {
393 memcpy(dst, records[i].start, records[i].len);
394 dst += records[i].len;
398 * Now munmap the old buffer and use the sorted buffer in its
401 clear_snapshot_buffer(snapshot);
402 snapshot->buf = snapshot->start = new_buffer;
403 snapshot->eof = new_buffer + len;
410 * Return a pointer to the start of the record that contains the
411 * character `*p` (which must be within the buffer). If no other
412 * record start is found, return `buf`.
414 static const char *find_start_of_record(const char *buf, const char *p)
416 while (p > buf && (p[-1] != '\n' || p[0] == '^'))
422 * Return a pointer to the start of the record following the record
423 * that contains `*p`. If none is found before `end`, return `end`.
425 static const char *find_end_of_record(const char *p, const char *end)
427 while (++p < end && (p[-1] != '\n' || p[0] == '^'))
433 * We want to be able to compare mmapped reference records quickly,
434 * without totally parsing them. We can do so because the records are
435 * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
436 * + 1) bytes past the beginning of the record.
438 * But what if the `packed-refs` file contains garbage? We're willing
439 * to tolerate not detecting the problem, as long as we don't produce
440 * totally garbled output (we can't afford to check the integrity of
441 * the whole file during every Git invocation). But we do want to be
442 * sure that we never read past the end of the buffer in memory and
443 * perform an illegal memory access.
445 * Guarantee that minimum level of safety by verifying that the last
446 * record in the file is LF-terminated, and that it has at least
447 * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
448 * these checks fails.
450 static void verify_buffer_safe(struct snapshot *snapshot)
452 const char *start = snapshot->start;
453 const char *eof = snapshot->eof;
454 const char *last_line;
459 last_line = find_start_of_record(start, eof - 1);
460 if (*(eof - 1) != '\n' || eof - last_line < the_hash_algo->hexsz + 2)
461 die_invalid_line(snapshot->refs->path,
462 last_line, eof - last_line);
465 #define SMALL_FILE_SIZE (32*1024)
468 * Depending on `mmap_strategy`, either mmap or read the contents of
469 * the `packed-refs` file into the snapshot. Return 1 if the file
470 * existed and was read, or 0 if the file was absent or empty. Die on
473 static int load_contents(struct snapshot *snapshot)
480 fd = open(snapshot->refs->path, O_RDONLY);
482 if (errno == ENOENT) {
484 * This is OK; it just means that no
485 * "packed-refs" file has been written yet,
486 * which is equivalent to it being empty,
487 * which is its state when initialized with
492 die_errno("couldn't read %s", snapshot->refs->path);
496 stat_validity_update(&snapshot->validity, fd);
498 if (fstat(fd, &st) < 0)
499 die_errno("couldn't stat %s", snapshot->refs->path);
500 size = xsize_t(st.st_size);
505 } else if (mmap_strategy == MMAP_NONE || size <= SMALL_FILE_SIZE) {
506 snapshot->buf = xmalloc(size);
507 bytes_read = read_in_full(fd, snapshot->buf, size);
508 if (bytes_read < 0 || bytes_read != size)
509 die_errno("couldn't read %s", snapshot->refs->path);
510 snapshot->mmapped = 0;
512 snapshot->buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
513 snapshot->mmapped = 1;
517 snapshot->start = snapshot->buf;
518 snapshot->eof = snapshot->buf + size;
524 * Find the place in `snapshot->buf` where the start of the record for
525 * `refname` starts. If `mustexist` is true and the reference doesn't
526 * exist, then return NULL. If `mustexist` is false and the reference
527 * doesn't exist, then return the point where that reference would be
528 * inserted, or `snapshot->eof` (which might be NULL) if it would be
529 * inserted at the end of the file. In the latter mode, `refname`
530 * doesn't have to be a proper reference name; for example, one could
531 * search for "refs/replace/" to find the start of any replace
534 * The record is sought using a binary search, so `snapshot->buf` must
537 static const char *find_reference_location(struct snapshot *snapshot,
538 const char *refname, int mustexist)
541 * This is not *quite* a garden-variety binary search, because
542 * the data we're searching is made up of records, and we
543 * always need to find the beginning of a record to do a
544 * comparison. A "record" here is one line for the reference
545 * itself and zero or one peel lines that start with '^'. Our
546 * loop invariant is described in the next two comments.
550 * A pointer to the character at the start of a record whose
551 * preceding records all have reference names that come
552 * *before* `refname`.
554 const char *lo = snapshot->start;
557 * A pointer to a the first character of a record whose
558 * reference name comes *after* `refname`.
560 const char *hi = snapshot->eof;
563 const char *mid, *rec;
566 mid = lo + (hi - lo) / 2;
567 rec = find_start_of_record(lo, mid);
568 cmp = cmp_record_to_refname(rec, refname);
570 lo = find_end_of_record(mid, hi);
571 } else if (cmp > 0) {
585 * Create a newly-allocated `snapshot` of the `packed-refs` file in
586 * its current state and return it. The return value will already have
587 * its reference count incremented.
589 * A comment line of the form "# pack-refs with: " may contain zero or
590 * more traits. We interpret the traits as follows:
592 * Neither `peeled` nor `fully-peeled`:
594 * Probably no references are peeled. But if the file contains a
595 * peeled value for a reference, we will use it.
599 * References under "refs/tags/", if they *can* be peeled, *are*
600 * peeled in this file. References outside of "refs/tags/" are
601 * probably not peeled even if they could have been, but if we find
602 * a peeled value for such a reference we will use it.
606 * All references in the file that can be peeled are peeled.
607 * Inversely (and this is more important), any references in the
608 * file for which no peeled value is recorded is not peelable. This
609 * trait should typically be written alongside "peeled" for
610 * compatibility with older clients, but we do not require it
611 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
615 * The references in this file are known to be sorted by refname.
617 static struct snapshot *create_snapshot(struct packed_ref_store *refs)
619 struct snapshot *snapshot = xcalloc(1, sizeof(*snapshot));
622 snapshot->refs = refs;
623 acquire_snapshot(snapshot);
624 snapshot->peeled = PEELED_NONE;
626 if (!load_contents(snapshot))
629 /* If the file has a header line, process it: */
630 if (snapshot->buf < snapshot->eof && *snapshot->buf == '#') {
632 struct string_list traits = STRING_LIST_INIT_NODUP;
634 eol = memchr(snapshot->buf, '\n',
635 snapshot->eof - snapshot->buf);
637 die_unterminated_line(refs->path,
639 snapshot->eof - snapshot->buf);
641 tmp = xmemdupz(snapshot->buf, eol - snapshot->buf);
643 if (!skip_prefix(tmp, "# pack-refs with:", (const char **)&p))
644 die_invalid_line(refs->path,
646 snapshot->eof - snapshot->buf);
648 string_list_split_in_place(&traits, p, ' ', -1);
650 if (unsorted_string_list_has_string(&traits, "fully-peeled"))
651 snapshot->peeled = PEELED_FULLY;
652 else if (unsorted_string_list_has_string(&traits, "peeled"))
653 snapshot->peeled = PEELED_TAGS;
655 sorted = unsorted_string_list_has_string(&traits, "sorted");
657 /* perhaps other traits later as well */
659 /* The "+ 1" is for the LF character. */
660 snapshot->start = eol + 1;
662 string_list_clear(&traits, 0);
666 verify_buffer_safe(snapshot);
669 sort_snapshot(snapshot);
672 * Reordering the records might have moved a short one
673 * to the end of the buffer, so verify the buffer's
676 verify_buffer_safe(snapshot);
679 if (mmap_strategy != MMAP_OK && snapshot->mmapped) {
681 * We don't want to leave the file mmapped, so we are
682 * forced to make a copy now:
684 size_t size = snapshot->eof - snapshot->start;
685 char *buf_copy = xmalloc(size);
687 memcpy(buf_copy, snapshot->start, size);
688 clear_snapshot_buffer(snapshot);
689 snapshot->buf = snapshot->start = buf_copy;
690 snapshot->eof = buf_copy + size;
697 * Check that `refs->snapshot` (if present) still reflects the
698 * contents of the `packed-refs` file. If not, clear the snapshot.
700 static void validate_snapshot(struct packed_ref_store *refs)
702 if (refs->snapshot &&
703 !stat_validity_check(&refs->snapshot->validity, refs->path))
704 clear_snapshot(refs);
708 * Get the `snapshot` for the specified packed_ref_store, creating and
709 * populating it if it hasn't been read before or if the file has been
710 * changed (according to its `validity` field) since it was last read.
711 * On the other hand, if we hold the lock, then assume that the file
712 * hasn't been changed out from under us, so skip the extra `stat()`
713 * call in `stat_validity_check()`. This function does *not* increase
714 * the snapshot's reference count on behalf of the caller.
716 static struct snapshot *get_snapshot(struct packed_ref_store *refs)
718 if (!is_lock_file_locked(&refs->lock))
719 validate_snapshot(refs);
722 refs->snapshot = create_snapshot(refs);
724 return refs->snapshot;
727 static int packed_read_raw_ref(struct ref_store *ref_store, const char *refname,
728 struct object_id *oid, struct strbuf *referent,
729 unsigned int *type, int *failure_errno)
731 struct packed_ref_store *refs =
732 packed_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
733 struct snapshot *snapshot = get_snapshot(refs);
738 rec = find_reference_location(snapshot, refname, 1);
741 /* 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;
784 * Move the iterator to the next record in the snapshot, without
785 * respect for whether the record is actually required by the current
786 * iteration. Adjust the fields in `iter` and return `ITER_OK` or
787 * `ITER_DONE`. This function does not free the iterator in the case
790 static int next_record(struct packed_ref_iterator *iter)
792 const char *p = iter->pos, *eol;
794 strbuf_reset(&iter->refname_buf);
796 if (iter->pos == iter->eof)
799 iter->base.flags = REF_ISPACKED;
801 if (iter->eof - p < the_hash_algo->hexsz + 2 ||
802 parse_oid_hex(p, &iter->oid, &p) ||
804 die_invalid_line(iter->snapshot->refs->path,
805 iter->pos, iter->eof - iter->pos);
807 eol = memchr(p, '\n', iter->eof - p);
809 die_unterminated_line(iter->snapshot->refs->path,
810 iter->pos, iter->eof - iter->pos);
812 strbuf_add(&iter->refname_buf, p, eol - p);
813 iter->base.refname = iter->refname_buf.buf;
815 if (check_refname_format(iter->base.refname, REFNAME_ALLOW_ONELEVEL)) {
816 if (!refname_is_safe(iter->base.refname))
817 die("packed refname is dangerous: %s",
820 iter->base.flags |= REF_BAD_NAME | REF_ISBROKEN;
822 if (iter->snapshot->peeled == PEELED_FULLY ||
823 (iter->snapshot->peeled == PEELED_TAGS &&
824 starts_with(iter->base.refname, "refs/tags/")))
825 iter->base.flags |= REF_KNOWS_PEELED;
829 if (iter->pos < iter->eof && *iter->pos == '^') {
831 if (iter->eof - p < the_hash_algo->hexsz + 1 ||
832 parse_oid_hex(p, &iter->peeled, &p) ||
834 die_invalid_line(iter->snapshot->refs->path,
835 iter->pos, iter->eof - iter->pos);
839 * Regardless of what the file header said, we
840 * definitely know the value of *this* reference. But
841 * we suppress it if the reference is broken:
843 if ((iter->base.flags & REF_ISBROKEN)) {
844 oidclr(&iter->peeled);
845 iter->base.flags &= ~REF_KNOWS_PEELED;
847 iter->base.flags |= REF_KNOWS_PEELED;
850 oidclr(&iter->peeled);
856 static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
858 struct packed_ref_iterator *iter =
859 (struct packed_ref_iterator *)ref_iterator;
862 while ((ok = next_record(iter)) == ITER_OK) {
863 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
864 ref_type(iter->base.refname) != REF_TYPE_PER_WORKTREE)
867 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
868 !ref_resolves_to_object(iter->base.refname, &iter->oid,
875 if (ref_iterator_abort(ref_iterator) != ITER_DONE)
881 static int packed_ref_iterator_peel(struct ref_iterator *ref_iterator,
882 struct object_id *peeled)
884 struct packed_ref_iterator *iter =
885 (struct packed_ref_iterator *)ref_iterator;
887 if ((iter->base.flags & REF_KNOWS_PEELED)) {
888 oidcpy(peeled, &iter->peeled);
889 return is_null_oid(&iter->peeled) ? -1 : 0;
890 } else if ((iter->base.flags & (REF_ISBROKEN | REF_ISSYMREF))) {
893 return !!peel_object(&iter->oid, peeled);
897 static int packed_ref_iterator_abort(struct ref_iterator *ref_iterator)
899 struct packed_ref_iterator *iter =
900 (struct packed_ref_iterator *)ref_iterator;
903 strbuf_release(&iter->refname_buf);
904 release_snapshot(iter->snapshot);
905 base_ref_iterator_free(ref_iterator);
909 static struct ref_iterator_vtable packed_ref_iterator_vtable = {
910 packed_ref_iterator_advance,
911 packed_ref_iterator_peel,
912 packed_ref_iterator_abort
915 static struct ref_iterator *packed_ref_iterator_begin(
916 struct ref_store *ref_store,
917 const char *prefix, unsigned int flags)
919 struct packed_ref_store *refs;
920 struct snapshot *snapshot;
922 struct packed_ref_iterator *iter;
923 struct ref_iterator *ref_iterator;
924 unsigned int required_flags = REF_STORE_READ;
926 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
927 required_flags |= REF_STORE_ODB;
928 refs = packed_downcast(ref_store, required_flags, "ref_iterator_begin");
931 * Note that `get_snapshot()` internally checks whether the
932 * snapshot is up to date with what is on disk, and re-reads
935 snapshot = get_snapshot(refs);
937 if (prefix && *prefix)
938 start = find_reference_location(snapshot, prefix, 0);
940 start = snapshot->start;
942 if (start == snapshot->eof)
943 return empty_ref_iterator_begin();
945 CALLOC_ARRAY(iter, 1);
946 ref_iterator = &iter->base;
947 base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable, 1);
949 iter->snapshot = snapshot;
950 acquire_snapshot(snapshot);
953 iter->eof = snapshot->eof;
954 strbuf_init(&iter->refname_buf, 0);
956 iter->base.oid = &iter->oid;
960 if (prefix && *prefix)
961 /* Stop iteration after we've gone *past* prefix: */
962 ref_iterator = prefix_ref_iterator_begin(ref_iterator, prefix, 0);
968 * Write an entry to the packed-refs file for the specified refname.
969 * If peeled is non-NULL, write it as the entry's peeled value. On
970 * error, return a nonzero value and leave errno set at the value left
971 * by the failing call to `fprintf()`.
973 static int write_packed_entry(FILE *fh, const char *refname,
974 const struct object_id *oid,
975 const struct object_id *peeled)
977 if (fprintf(fh, "%s %s\n", oid_to_hex(oid), refname) < 0 ||
978 (peeled && fprintf(fh, "^%s\n", oid_to_hex(peeled)) < 0))
984 int packed_refs_lock(struct ref_store *ref_store, int flags, struct strbuf *err)
986 struct packed_ref_store *refs =
987 packed_downcast(ref_store, REF_STORE_WRITE | REF_STORE_MAIN,
989 static int timeout_configured = 0;
990 static int timeout_value = 1000;
992 if (!timeout_configured) {
993 git_config_get_int("core.packedrefstimeout", &timeout_value);
994 timeout_configured = 1;
998 * Note that we close the lockfile immediately because we
999 * don't write new content to it, but rather to a separate
1002 if (hold_lock_file_for_update_timeout(
1005 flags, timeout_value) < 0) {
1006 unable_to_lock_message(refs->path, errno, err);
1010 if (close_lock_file_gently(&refs->lock)) {
1011 strbuf_addf(err, "unable to close %s: %s", refs->path, strerror(errno));
1012 rollback_lock_file(&refs->lock);
1017 * There is a stat-validity problem might cause `update-ref -d`
1018 * lost the newly commit of a ref, because a new `packed-refs`
1019 * file might has the same on-disk file attributes such as
1020 * timestamp, file size and inode value, but has a changed
1023 * This could happen with a very small chance when
1024 * `update-ref -d` is called and at the same time another
1025 * `pack-refs --all` process is running.
1027 * Now that we hold the `packed-refs` lock, it is important
1028 * to make sure we could read the latest version of
1029 * `packed-refs` file no matter we have just mmap it or not.
1030 * So what need to do is clear the snapshot if we hold it
1033 clear_snapshot(refs);
1036 * Now make sure that the packed-refs file as it exists in the
1037 * locked state is loaded into the snapshot:
1043 void packed_refs_unlock(struct ref_store *ref_store)
1045 struct packed_ref_store *refs = packed_downcast(
1047 REF_STORE_READ | REF_STORE_WRITE,
1048 "packed_refs_unlock");
1050 if (!is_lock_file_locked(&refs->lock))
1051 BUG("packed_refs_unlock() called when not locked");
1052 rollback_lock_file(&refs->lock);
1055 int packed_refs_is_locked(struct ref_store *ref_store)
1057 struct packed_ref_store *refs = packed_downcast(
1059 REF_STORE_READ | REF_STORE_WRITE,
1060 "packed_refs_is_locked");
1062 return is_lock_file_locked(&refs->lock);
1066 * The packed-refs header line that we write out. Perhaps other traits
1067 * will be added later.
1069 * Note that earlier versions of Git used to parse these traits by
1070 * looking for " trait " in the line. For this reason, the space after
1071 * the colon and the trailing space are required.
1073 static const char PACKED_REFS_HEADER[] =
1074 "# pack-refs with: peeled fully-peeled sorted \n";
1076 static int packed_init_db(struct ref_store *ref_store, struct strbuf *err)
1078 /* Nothing to do. */
1083 * Write the packed refs from the current snapshot to the packed-refs
1084 * tempfile, incorporating any changes from `updates`. `updates` must
1085 * be a sorted string list whose keys are the refnames and whose util
1086 * values are `struct ref_update *`. On error, rollback the tempfile,
1087 * write an error message to `err`, and return a nonzero value.
1089 * The packfile must be locked before calling this function and will
1090 * remain locked when it is done.
1092 static int write_with_updates(struct packed_ref_store *refs,
1093 struct string_list *updates,
1096 struct ref_iterator *iter = NULL;
1100 struct strbuf sb = STRBUF_INIT;
1101 char *packed_refs_path;
1103 if (!is_lock_file_locked(&refs->lock))
1104 BUG("write_with_updates() called while unlocked");
1107 * If packed-refs is a symlink, we want to overwrite the
1108 * symlinked-to file, not the symlink itself. Also, put the
1109 * staging file next to it:
1111 packed_refs_path = get_locked_file_path(&refs->lock);
1112 strbuf_addf(&sb, "%s.new", packed_refs_path);
1113 free(packed_refs_path);
1114 refs->tempfile = create_tempfile(sb.buf);
1115 if (!refs->tempfile) {
1116 strbuf_addf(err, "unable to create file %s: %s",
1117 sb.buf, strerror(errno));
1118 strbuf_release(&sb);
1121 strbuf_release(&sb);
1123 out = fdopen_tempfile(refs->tempfile, "w");
1125 strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
1130 if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
1134 * We iterate in parallel through the current list of refs and
1135 * the list of updates, processing an entry from at least one
1136 * of the lists each time through the loop. When the current
1137 * list of refs is exhausted, set iter to NULL. When the list
1138 * of updates is exhausted, leave i set to updates->nr.
1140 iter = packed_ref_iterator_begin(&refs->base, "",
1141 DO_FOR_EACH_INCLUDE_BROKEN);
1142 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1147 while (iter || i < updates->nr) {
1148 struct ref_update *update = NULL;
1151 if (i >= updates->nr) {
1154 update = updates->items[i].util;
1159 cmp = strcmp(iter->refname, update->refname);
1164 * There is both an old value and an update
1165 * for this reference. Check the old value if
1168 if ((update->flags & REF_HAVE_OLD)) {
1169 if (is_null_oid(&update->old_oid)) {
1170 strbuf_addf(err, "cannot update ref '%s': "
1171 "reference already exists",
1174 } else if (!oideq(&update->old_oid, iter->oid)) {
1175 strbuf_addf(err, "cannot update ref '%s': "
1176 "is at %s but expected %s",
1178 oid_to_hex(iter->oid),
1179 oid_to_hex(&update->old_oid));
1184 /* Now figure out what to use for the new value: */
1185 if ((update->flags & REF_HAVE_NEW)) {
1187 * The update takes precedence. Skip
1188 * the iterator over the unneeded
1191 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1196 * The update doesn't actually want to
1197 * change anything. We're done with it.
1202 } else if (cmp > 0) {
1204 * There is no old value but there is an
1205 * update for this reference. Make sure that
1206 * the update didn't expect an existing value:
1208 if ((update->flags & REF_HAVE_OLD) &&
1209 !is_null_oid(&update->old_oid)) {
1210 strbuf_addf(err, "cannot update ref '%s': "
1211 "reference is missing but expected %s",
1213 oid_to_hex(&update->old_oid));
1219 /* Pass the old reference through. */
1221 struct object_id peeled;
1222 int peel_error = ref_iterator_peel(iter, &peeled);
1224 if (write_packed_entry(out, iter->refname,
1226 peel_error ? NULL : &peeled))
1229 if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1231 } else if (is_null_oid(&update->new_oid)) {
1233 * The update wants to delete the reference,
1234 * and the reference either didn't exist or we
1235 * have already skipped it. So we're done with
1236 * the update (and don't have to write
1241 struct object_id peeled;
1242 int peel_error = peel_object(&update->new_oid,
1245 if (write_packed_entry(out, update->refname,
1247 peel_error ? NULL : &peeled))
1254 if (ok != ITER_DONE) {
1255 strbuf_addstr(err, "unable to write packed-refs file: "
1256 "error iterating over old contents");
1260 if (close_tempfile_gently(refs->tempfile)) {
1261 strbuf_addf(err, "error closing file %s: %s",
1262 get_tempfile_path(refs->tempfile),
1264 strbuf_release(&sb);
1265 delete_tempfile(&refs->tempfile);
1272 strbuf_addf(err, "error writing to %s: %s",
1273 get_tempfile_path(refs->tempfile), strerror(errno));
1277 ref_iterator_abort(iter);
1279 delete_tempfile(&refs->tempfile);
1283 int is_packed_transaction_needed(struct ref_store *ref_store,
1284 struct ref_transaction *transaction)
1286 struct packed_ref_store *refs = packed_downcast(
1289 "is_packed_transaction_needed");
1290 struct strbuf referent = STRBUF_INIT;
1294 if (!is_lock_file_locked(&refs->lock))
1295 BUG("is_packed_transaction_needed() called while unlocked");
1298 * We're only going to bother returning false for the common,
1299 * trivial case that references are only being deleted, their
1300 * old values are not being checked, and the old `packed-refs`
1301 * file doesn't contain any of those reference(s). This gives
1302 * false positives for some other cases that could
1303 * theoretically be optimized away:
1305 * 1. It could be that the old value is being verified without
1306 * setting a new value. In this case, we could verify the
1307 * old value here and skip the update if it agrees. If it
1308 * disagrees, we could either let the update go through
1309 * (the actual commit would re-detect and report the
1310 * problem), or come up with a way of reporting such an
1311 * error to *our* caller.
1313 * 2. It could be that a new value is being set, but that it
1314 * is identical to the current packed value of the
1317 * Neither of these cases will come up in the current code,
1318 * because the only caller of this function passes to it a
1319 * transaction that only includes `delete` updates with no
1320 * `old_id`. Even if that ever changes, false positives only
1321 * cause an optimization to be missed; they do not affect
1326 * Start with the cheap checks that don't require old
1327 * reference values to be read:
1329 for (i = 0; i < transaction->nr; i++) {
1330 struct ref_update *update = transaction->updates[i];
1332 if (update->flags & REF_HAVE_OLD)
1333 /* Have to check the old value -> needed. */
1336 if ((update->flags & REF_HAVE_NEW) && !is_null_oid(&update->new_oid))
1337 /* Have to set a new value -> needed. */
1342 * The transaction isn't checking any old values nor is it
1343 * setting any nonzero new values, so it still might be able
1344 * to be skipped. Now do the more expensive check: the update
1345 * is needed if any of the updates is a delete, and the old
1346 * `packed-refs` file contains a value for that reference.
1349 for (i = 0; i < transaction->nr; i++) {
1350 struct ref_update *update = transaction->updates[i];
1353 struct object_id oid;
1355 if (!(update->flags & REF_HAVE_NEW))
1357 * This reference isn't being deleted -> not
1362 if (!refs_read_raw_ref(ref_store, update->refname, &oid,
1363 &referent, &type, &failure) ||
1364 failure != ENOENT) {
1366 * We have to actually delete that reference
1367 * -> this transaction is needed.
1374 strbuf_release(&referent);
1378 struct packed_transaction_backend_data {
1379 /* True iff the transaction owns the packed-refs lock. */
1382 struct string_list updates;
1385 static void packed_transaction_cleanup(struct packed_ref_store *refs,
1386 struct ref_transaction *transaction)
1388 struct packed_transaction_backend_data *data = transaction->backend_data;
1391 string_list_clear(&data->updates, 0);
1393 if (is_tempfile_active(refs->tempfile))
1394 delete_tempfile(&refs->tempfile);
1396 if (data->own_lock && is_lock_file_locked(&refs->lock)) {
1397 packed_refs_unlock(&refs->base);
1402 transaction->backend_data = NULL;
1405 transaction->state = REF_TRANSACTION_CLOSED;
1408 static int packed_transaction_prepare(struct ref_store *ref_store,
1409 struct ref_transaction *transaction,
1412 struct packed_ref_store *refs = packed_downcast(
1414 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1415 "ref_transaction_prepare");
1416 struct packed_transaction_backend_data *data;
1418 int ret = TRANSACTION_GENERIC_ERROR;
1421 * Note that we *don't* skip transactions with zero updates,
1422 * because such a transaction might be executed for the side
1423 * effect of ensuring that all of the references are peeled or
1424 * ensuring that the `packed-refs` file is sorted. If the
1425 * caller wants to optimize away empty transactions, it should
1429 CALLOC_ARRAY(data, 1);
1430 string_list_init(&data->updates, 0);
1432 transaction->backend_data = data;
1435 * Stick the updates in a string list by refname so that we
1438 for (i = 0; i < transaction->nr; i++) {
1439 struct ref_update *update = transaction->updates[i];
1440 struct string_list_item *item =
1441 string_list_append(&data->updates, update->refname);
1443 /* Store a pointer to update in item->util: */
1444 item->util = update;
1446 string_list_sort(&data->updates);
1448 if (ref_update_reject_duplicates(&data->updates, err))
1451 if (!is_lock_file_locked(&refs->lock)) {
1452 if (packed_refs_lock(ref_store, 0, err))
1457 if (write_with_updates(refs, &data->updates, err))
1460 transaction->state = REF_TRANSACTION_PREPARED;
1464 packed_transaction_cleanup(refs, transaction);
1468 static int packed_transaction_abort(struct ref_store *ref_store,
1469 struct ref_transaction *transaction,
1472 struct packed_ref_store *refs = packed_downcast(
1474 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1475 "ref_transaction_abort");
1477 packed_transaction_cleanup(refs, transaction);
1481 static int packed_transaction_finish(struct ref_store *ref_store,
1482 struct ref_transaction *transaction,
1485 struct packed_ref_store *refs = packed_downcast(
1487 REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1488 "ref_transaction_finish");
1489 int ret = TRANSACTION_GENERIC_ERROR;
1490 char *packed_refs_path;
1492 clear_snapshot(refs);
1494 packed_refs_path = get_locked_file_path(&refs->lock);
1495 if (rename_tempfile(&refs->tempfile, packed_refs_path)) {
1496 strbuf_addf(err, "error replacing %s: %s",
1497 refs->path, strerror(errno));
1504 free(packed_refs_path);
1505 packed_transaction_cleanup(refs, transaction);
1509 static int packed_initial_transaction_commit(struct ref_store *ref_store,
1510 struct ref_transaction *transaction,
1513 return ref_transaction_commit(transaction, err);
1516 static int packed_delete_refs(struct ref_store *ref_store, const char *msg,
1517 struct string_list *refnames, unsigned int flags)
1519 struct packed_ref_store *refs =
1520 packed_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1521 struct strbuf err = STRBUF_INIT;
1522 struct ref_transaction *transaction;
1523 struct string_list_item *item;
1526 (void)refs; /* We need the check above, but don't use the variable */
1532 * Since we don't check the references' old_oids, the
1533 * individual updates can't fail, so we can pack all of the
1534 * updates into a single transaction.
1537 transaction = ref_store_transaction_begin(ref_store, &err);
1541 for_each_string_list_item(item, refnames) {
1542 if (ref_transaction_delete(transaction, item->string, NULL,
1543 flags, msg, &err)) {
1544 warning(_("could not delete reference %s: %s"),
1545 item->string, err.buf);
1550 ret = ref_transaction_commit(transaction, &err);
1553 if (refnames->nr == 1)
1554 error(_("could not delete reference %s: %s"),
1555 refnames->items[0].string, err.buf);
1557 error(_("could not delete references: %s"), err.buf);
1560 ref_transaction_free(transaction);
1561 strbuf_release(&err);
1565 static int packed_pack_refs(struct ref_store *ref_store, unsigned int flags)
1568 * Packed refs are already packed. It might be that loose refs
1569 * are packed *into* a packed refs store, but that is done by
1570 * updating the packed references via a transaction.
1575 static int packed_create_symref(struct ref_store *ref_store,
1576 const char *refname, const char *target,
1579 BUG("packed reference store does not support symrefs");
1582 static int packed_rename_ref(struct ref_store *ref_store,
1583 const char *oldrefname, const char *newrefname,
1586 BUG("packed reference store does not support renaming references");
1589 static int packed_copy_ref(struct ref_store *ref_store,
1590 const char *oldrefname, const char *newrefname,
1593 BUG("packed reference store does not support copying references");
1596 static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store)
1598 return empty_ref_iterator_begin();
1601 static int packed_for_each_reflog_ent(struct ref_store *ref_store,
1602 const char *refname,
1603 each_reflog_ent_fn fn, void *cb_data)
1608 static int packed_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1609 const char *refname,
1610 each_reflog_ent_fn fn,
1616 static int packed_reflog_exists(struct ref_store *ref_store,
1617 const char *refname)
1622 static int packed_create_reflog(struct ref_store *ref_store,
1623 const char *refname, int force_create,
1626 BUG("packed reference store does not support reflogs");
1629 static int packed_delete_reflog(struct ref_store *ref_store,
1630 const char *refname)
1635 static int packed_reflog_expire(struct ref_store *ref_store,
1636 const char *refname, const struct object_id *oid,
1638 reflog_expiry_prepare_fn prepare_fn,
1639 reflog_expiry_should_prune_fn should_prune_fn,
1640 reflog_expiry_cleanup_fn cleanup_fn,
1641 void *policy_cb_data)
1646 struct ref_storage_be refs_be_packed = {
1649 packed_ref_store_create,
1651 packed_transaction_prepare,
1652 packed_transaction_finish,
1653 packed_transaction_abort,
1654 packed_initial_transaction_commit,
1657 packed_create_symref,
1662 packed_ref_iterator_begin,
1663 packed_read_raw_ref,
1665 packed_reflog_iterator_begin,
1666 packed_for_each_reflog_ent,
1667 packed_for_each_reflog_ent_reverse,
1668 packed_reflog_exists,
1669 packed_create_reflog,
1670 packed_delete_reflog,
1671 packed_reflog_expire