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