buf_generic.h

filter: Statementstmt 55.7% 1250 / 2242 Branchbran 37.3% 417 / 1118 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 49.6% 1667 / 3360 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/f64.xs ↑ Summary xs/str.xs »
1 /*
2 * buf_generic.h -- Macro-template for shared-memory typed buffers.
3 *
4 * Before including, define:
5 * BUF_PREFIX -- function prefix (e.g., buf_i64)
6 * BUF_ELEM_TYPE -- C element type (e.g., int64_t)
7 * BUF_VARIANT_ID -- unique integer for header validation
8 * BUF_ELEM_SIZE -- sizeof(BUF_ELEM_TYPE) or fixed string length
9 *
10 * Optional:
11 * BUF_HAS_COUNTERS -- generate incr/decr/cas (integer types only)
12 * BUF_IS_FLOAT -- element is float/double (affects SV conversion)
13 * BUF_IS_FIXEDSTR -- element is fixed-length char array
14 */
15  
16 /* ================================================================
17 * Part 1: Shared definitions (included once)
18 * ================================================================ */
19  
20 #ifndef BUF_DEFS_H
21 #define BUF_DEFS_H
22  
23 #include <stddef.h>
24 #include <stdint.h>
25 #include <stdbool.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/mman.h>
31 #include <sys/stat.h>
32 #include <sys/file.h>
33 #include <sys/syscall.h>
34 #include <limits.h>
35 #include <signal.h>
36 #include <errno.h>
37 #include <linux/futex.h>
38 #include <sys/eventfd.h>
39 #include <pthread.h>
40  
41 /* ---- Constants ---- */
42  
43 #define BUF_MAGIC 0x42554631U /* "BUF1" */
44 #define BUF_VERSION 3 /* v3: added occupancy bitmap region (layout change) */
45 #define BUF_ERR_BUFLEN (PATH_MAX + 256)
46 #define BUF_READER_SLOTS 1024 /* per-handle reader slots */
47  
48 /* Occupancy bitmap: one bit per reader slot, set when a handle claims a slot and
49 * cleared on clean release. A writer scans these BUF_OCC_WORDS words to visit
50 * only OCCUPIED slots (O(words + live readers)) instead of all BUF_READER_SLOTS. */
51 #define BUF_OCC_WORDS (((BUF_READER_SLOTS) + 63) / 64) /* 16 for 1024 slots */
52 #define BUF_OCC_BYTES ((uint64_t)BUF_OCC_WORDS * 8) /* 128 bytes */
53  
54 /* ---- Reader-slot table (in shared memory) ----
55 * In the reader-slots-only rwlock a reader's ENTIRE contribution to the shared
56 * lock is `rdepth` in its OWN slot -- there is no separate shared reader counter
57 * to fall out of sync with it -- so a dead reader's contribution is exactly this
58 * one word, which a draining writer neutralises by clearing the slot's pid (the
59 * scan then ignores the slot). No orphaned counter can exist, so there is no
60 * quiescent force-reset and sustained readers cannot starve a writer.
61 * _rsv1/_rsv2 are kept only to preserve the 16-byte slot size across the
62 * already-released builds. */
63 typedef struct {
64 uint32_t pid; /* owning PID, 0 = free */
65 uint32_t rdepth; /* read locks held by this handle (recursion-safe) */
66 uint32_t _rsv1; /* reserved (was waiters_parked); unused, kept for layout size */
67 uint32_t _rsv2; /* reserved (was writers_parked); unused, kept for layout size */
68 } BufReaderSlot;
69  
70 /* ---- Shared memory header (128 bytes, 2 cache lines, in mmap) ---- */
71  
72 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
73 #define BUF_STATIC_ASSERT(cond, msg) _Static_assert(cond, msg)
74 #else
75 #define BUF_STATIC_ASSERT(cond, msg)
76 #endif
77  
78 typedef struct {
79 /* ---- Cache line 0 (0-63): immutable after create ---- */
80 uint32_t magic; /* 0 */
81 uint32_t version; /* 4 */
82 uint32_t variant_id; /* 8 */
83 uint32_t elem_size; /* 12 */
84 uint64_t capacity; /* 16: number of elements */
85 uint64_t total_size; /* 24: total mmap size */
86 uint64_t data_off; /* 32: offset to data array */
87 uint64_t reader_slots_off;/* 40: offset to BufReaderSlot[BUF_READER_SLOTS] */
88 uint8_t _reserved0[16]; /* 48-63 */
89  
90 /* ---- Cache line 1 (64-127): seqlock + rwlock + mutable state ---- */
91 uint32_t seq; /* 64: seqlock counter, odd = writer active */
92 uint32_t wlock; /* 68: WRITER word ONLY: 0 (free) or 0x80000000|pid. NOT a reader count. */
93 uint32_t rwait; /* 72: parked-waiter hint (readers+writers blocked on wlock); over-count-safe */
94 uint32_t stat_recoveries; /* 76 */
95 uint32_t drain_seq; /* 80: futex bumped by a reader releasing under a draining writer (wakes it) */
96 uint32_t slotless_rdepth; /* 84: readers holding with no reader-slot (documented residual) */
97 uint64_t _reserved1[5]; /* 88-127 */
98 } BufHeader;
99  
100 BUF_STATIC_ASSERT(sizeof(BufHeader) == 128, "BufHeader must be exactly 128 bytes (2 cache lines)");
101  
102 /* ---- Process-local handle ---- */
103  
104 typedef struct {
105 BufHeader *hdr;
106 void *data; /* pointer to element array in mmap */
107 BufReaderSlot *reader_slots; /* in mmap, BUF_READER_SLOTS entries */
108 uint64_t *occ; /* BUF_OCC_WORDS-word slot-occupancy bitmap (trusted layout offset) */
109 uint64_t capacity; /* cached at attach: immutable geometry (peer can't grow it live) */
110 uint32_t elem_size; /* cached at attach: immutable geometry */
111 size_t mmap_size;
112 char *path; /* backing file path (strdup'd, NULL for anon) */
113 int fd; /* kept open for memfd, -1 otherwise */
114 int efd; /* eventfd for notifications, -1 if none */
115 uint32_t my_slot_idx; /* UINT32_MAX = unclaimed; this handle's slot */
116 uint32_t cached_pid; /* getpid() at claim time */
117 uint32_t cached_fork_gen; /* fork-generation at claim time */
118 uint8_t wr_locked; /* process-local: 1 if lock_wr is held */
119 uint32_t slotless_held; /* read locks this handle published to slotless_rdepth
120 * because no reader slot was free. Decrements peel these
121 * off FIRST: a slot claimed mid-hold must not receive a
122 * decrement that was published to the slotless counter. */
123 uint32_t rd_held; /* read locks held by this handle */
124 uint8_t efd_owned; /* 1 if we created the eventfd (close on destroy) */
125 } BufHandle;
126  
127 /* ---- Futex-based read-write lock ---- */
128  
129 #define BUF_RWLOCK_SPIN_LIMIT 32
130 #define BUF_LOCK_TIMEOUT_SEC 2
131  
132 1 static inline void buf_spin_pause(void) {
133 #if defined(__x86_64__) || defined(__i386__)
134 1 __asm__ volatile("pause" ::: "memory");
135 #elif defined(__aarch64__)
136 __asm__ volatile("yield" ::: "memory");
137 #else
138 __asm__ volatile("" ::: "memory");
139 #endif
140 1 }
141  
142 #define BUF_RWLOCK_WRITER_BIT 0x80000000U
143 #define BUF_RWLOCK_PID_MASK 0x7FFFFFFFU
144 #define BUF_RWLOCK_WR(pid) (BUF_RWLOCK_WRITER_BIT | ((uint32_t)(pid) & BUF_RWLOCK_PID_MASK))
145  
146 /* Futex-based write-preferring read-write lock (reader-slots-only) with
147 * dead-process recovery. The reader count is NOT stored in a shared counter; it
148 * is DISTRIBUTED across reader slots: each slot's `rdepth` is its handle's
149 * entire contribution. A reader publishes its presence in its own slot
150 * then re-checks the writer word; a writer publishes the writer word then scans
151 * every slot until all live readers' rdepth reach 0. Sequentially-consistent
152 * store+load on each side (a Dekker handshake) gives mutual exclusion. A crashed
153 * reader is recovered by clearing its one slot (CAS pid->0) -- no second counter
154 * to strand, no orphaned +1, no quiescent force-reset -- so sustained read
155 * traffic can never starve a writer. Write-preference is inherent in the gate
156 * (new readers see wlock!=0 and yield). */
157  
158 /* A zombie (dead but not yet reaped) still answers kill(pid,0) as alive, so a
159 * process that crashed while holding the lock and lingers unreaped would never
160 * be recovered. Treat /proc/<pid>/stat state 'Z' as dead. Linux-only (as is
161 * this module); if /proc is unreadable we fall back to "alive" (safe: we never
162 * force-recover a possibly-live holder). */
163 1025 static inline int buf_pid_is_zombie(uint32_t pid) {
164 char path[32], buf[256];
165 1025 snprintf(path, sizeof(path), "/proc/%u/stat", (unsigned)pid);
166 1025 int fd = open(path, O_RDONLY | O_CLOEXEC);
167 1025 ▶ if (fd < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return 0; 0 1025 1025
168 1025 ssize_t n = read(fd, buf, sizeof(buf) - 1);
169 1025 close(fd);
170 1025 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 1025 1025
171 1025 buf[n] = '\0';
172 /* "pid (comm) state ..."; comm may contain ')', so scan to the last one. */
173 1025 char *rp = strrchr(buf, ')');
174 1025 ▶ if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */
Branch: 2 branches
BranchTrueFalseTotal
if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */ 1025 0 1025
if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */ 0 1025 1025
175 1025 ▶ return rp[1] == ' ' && rp[2] == 'Z';
Branch: 2 branches
BranchTrueFalseTotal
return rp[1] == ' ' && rp[2] == 'Z'; 1025 0 1025
return rp[1] == ' ' && rp[2] == 'Z'; 0 1025 1025
176 }
177 1029 static inline int buf_pid_alive(uint32_t pid) {
178 1029 ▶ if (pid == 0) return 0; /* no owner recorded, treat as dead */
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) return 0; /* no owner recorded, treat as dead */ 0 1029 1029
179 1029 ▶ if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */
Branch: 2 branches
BranchTrueFalseTotal
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 4 1025 1029
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 4 0 4
180 1025 return !buf_pid_is_zombie(pid); /* kill() also succeeds for a zombie -> treat as dead */
181 }
182  
183 /* ---- Slot lifecycle (dead-reader recovery) ----
184 * Each handle claims a slot lazily on its first lock operation; the owning PID
185 * lets writers reclaim the slot after a crash. */
186 static uint32_t buf_fork_gen = 0;
187 static pthread_once_t buf_atfork_once = PTHREAD_ONCE_INIT;
188 4 static void buf_on_fork_child(void) {
189 4 __atomic_add_fetch(&buf_fork_gen, 1, __ATOMIC_RELAXED);
190 4 }
191 16 static void buf_atfork_init(void) {
192 16 pthread_atfork(NULL, NULL, buf_on_fork_child);
193 16 }
194  
195 5030 static inline void buf_reset_after_fork(BufHandle *h) {
196 5030 uint32_t cur_gen = __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED);
197 5030 ▶ if (h->cached_fork_gen == cur_gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (h->cached_fork_gen == cur_gen) return; 5028 2 5030
198 2 h->cached_fork_gen = cur_gen;
199 2 h->cached_pid = 0;
200 2 h->my_slot_idx = UINT32_MAX;
201 2 h->rd_held = 0;
202 2 h->slotless_held = 0;
203 2 h->wr_locked = 0;
204 }
205  
206 /* An inherited write-lock flag belongs to the parent, not the child. */
207 617 static inline int buf_write_locked(BufHandle *h) {
208 631 ▶ return h->wr_locked &&
Branch: 1 branch
BranchTrueFalseTotal
return h->wr_locked && 14 603 617
209 14 ▶ h->cached_fork_gen == __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED);
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED); 14 0 14
210 }
211  
212 /* Occupancy bitmap: set a slot's bit when it is claimed, clear it on clean
213 * release. SEQ_CST so a set bit is ordered before the slot's rdepth can go
214 * non-zero (bit set in claim, which precedes any rdlock), letting a writer's
215 * SEQ_CST bitmap scan never miss a slot a committed reader holds. */
216 2094 static inline void buf_occ_set(BufHandle *h, uint32_t s) {
217 2094 __atomic_fetch_or(&h->occ[s >> 6], (uint64_t)1 << (s & 63), __ATOMIC_SEQ_CST);
218 2094 }
219 1068 static inline void buf_occ_clear(BufHandle *h, uint32_t s) {
220 1068 __atomic_fetch_and(&h->occ[s >> 6], ~((uint64_t)1 << (s & 63)), __ATOMIC_SEQ_CST);
221 1068 }
222  
223 2792 static inline void buf_claim_reader_slot(BufHandle *h) {
224 2792 ▶ if (!h->reader_slots) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h->reader_slots) return; 0 2792 2792
225 2792 pthread_once(&buf_atfork_once, buf_atfork_init);
226 2792 buf_reset_after_fork(h);
227 2792 ▶ if (h->my_slot_idx != UINT32_MAX) return;
Branch: 1 branch
BranchTrueFalseTotal
if (h->my_slot_idx != UINT32_MAX) return; 543 2249 2792
228 2249 uint32_t now_pid = (uint32_t)getpid();
229 2249 h->cached_pid = now_pid;
230 2249 uint32_t start = now_pid % BUF_READER_SLOTS;
231 /* Pass 1: take a free slot. */
232 1208920 ▶ for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) { 1208765 155 1208920
233 1208765 uint32_t s = (start + i) % BUF_READER_SLOTS;
234 1208765 uint32_t expected = 0;
235 1208765 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[s].pid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[s].pid, 2094 1206671 1208765
236 &expected, now_pid, 0,
237 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
238 /* Fresh owner holds no read locks yet; clear any stale rdepth left by
239 * a dead predecessor (its contribution is dropped as we take over). */
240 2094 __atomic_store_n(&h->reader_slots[s].rdepth, 0, __ATOMIC_RELAXED);
241 2094 buf_occ_set(h, s); /* mark occupied BEFORE any rdlock can bump rdepth */
242 2094 h->my_slot_idx = s;
243 2094 return;
244 }
245 }
246 /* Pass 2: no free slot -- reclaim one whose owner is dead. Safe to take even
247 * if its rdepth>0: clearing pid drops the dead reader's entire contribution
248 * (a writer scan ignores rdepth when pid==0) and we reset rdepth to 0 as we
249 * claim it. */
250 158875 ▶ for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < BUF_READER_SLOTS; i++) { 158720 155 158875
251 158720 uint32_t dpid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
252 158720 ▶ if (dpid == 0 || dpid == now_pid || buf_pid_alive(dpid)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (dpid == 0 || dpid == now_pid || buf_pid_alive(dpid)) continue; 158720 0 158720
if (dpid == 0 || dpid == now_pid || buf_pid_alive(dpid)) continue; 1024 157696 158720
if (dpid == 0 || dpid == now_pid || buf_pid_alive(dpid)) continue; 1024 0 1024
253 0 uint32_t expected = dpid;
254 0 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &expected, now_pid, 0,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &expected, now_pid, 0, 0 0 0
255 __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
256 0 __atomic_store_n(&h->reader_slots[i].rdepth, 0, __ATOMIC_RELAXED);
257 0 buf_occ_set(h, i);
258 0 h->my_slot_idx = i;
259 0 return;
260 }
261 }
262 /* Table full -- leave my_slot_idx = UINT32_MAX so this handle takes the
263 * slotless path (lock still works; recovery of THIS reader's death is the
264 * documented slotless limitation). */
265 }
266  
267 /* Bump/drop the parked-waiter hint. Both readers (blocked at the gate) and
268 * writers (blocked acquiring wlock) wait on the wlock futex and use this, so
269 * wrunlock/recover know whether a FUTEX_WAKE is worth a syscall. A waiter
270 * SIGKILLed while parked leaves rwait over-counted -> at most a spurious wake
271 * (harmless); it can never under-count, so no wakeup is lost. */
272 0 static inline void buf_park(BufHandle *h) {
273 0 __atomic_add_fetch(&h->hdr->rwait, 1, __ATOMIC_RELAXED);
274 0 }
275 0 static inline void buf_unpark(BufHandle *h) {
276 0 __atomic_sub_fetch(&h->hdr->rwait, 1, __ATOMIC_RELAXED);
277 0 }
278  
279 /* Publish (inc) / retract (dec) this reader's presence -- its ENTIRE
280 * contribution to the lock. A slotted reader uses its slot's rdepth; a reader
281 * that could not claim a slot uses the global slotless_rdepth. inc() is SEQ_CST
282 * so the wlock re-check that follows it in rdlock forms a Dekker handshake with
283 * the writer's SEQ_CST wlock-store + rdepth-scan. leave() peels slotless first
284 * so a slot claimed mid-hold cannot misattribute the decrement. */
285 2209 static inline void buf_rdepth_inc(BufHandle *h) {
286 2209 h->rd_held++; /* process-local: what THIS handle owes */
287 2209 ▶ if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->my_slot_idx != UINT32_MAX) { 2055 154 2209
288 2055 __atomic_add_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_SEQ_CST);
289 } else {
290 154 __atomic_add_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_SEQ_CST);
291 154 h->slotless_held++;
292 }
293 2209 }
294 2213 static inline void buf_rdepth_dec(BufHandle *h) {
295 /* Drop ONLY what this handle actually published. An unbalanced unlock_rd
296 * (more unlocks than locks) would otherwise decrement a slot rdepth of 0,
297 * wrapping it to UINT32_MAX: the owning pid is alive, so dead-reader
298 * recovery never fires and every writer on the buffer -- in every process --
299 * blocks forever inside the drain futex, uninterruptible by Perl signals. */
300 2213 ▶ if (h->rd_held == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (h->rd_held == 0) return; 4 2209 2213
301 2209 h->rd_held--;
302 /* Peel slotless holds first. A reader that published to slotless_rdepth and
303 * then claimed a freed slot mid-hold would otherwise decrement the SLOT,
304 * underflowing its rdepth and stranding slotless_rdepth at a nonzero value --
305 * which nothing ever recovers, so every future writer would block forever. */
306 2209 ▶ if (h->slotless_held > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->slotless_held > 0) { 154 2055 2209
307 154 h->slotless_held--;
308 154 __atomic_sub_fetch(&h->hdr->slotless_rdepth, 1, __ATOMIC_RELEASE);
309 2055 ▶ } else if (h->my_slot_idx != UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->my_slot_idx != UINT32_MAX) { 2055 0 2055
310 2055 __atomic_sub_fetch(&h->reader_slots[h->my_slot_idx].rdepth, 1, __ATOMIC_RELEASE);
311 }
312 }
313  
314 /* Wake a writer that may be draining readers (it waits on drain_seq). Called
315 * after every rdepth decrement so a released read lock lets the writer re-scan
316 * promptly instead of waiting out its timeout. */
317 2213 static inline void buf_reader_wake_drain(BufHandle *h) {
318 2213 ▶ if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_ACQUIRE) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&h->hdr->wlock, __ATOMIC_ACQUIRE) != 0) { 0 2213 2213
319 0 __atomic_add_fetch(&h->hdr->drain_seq, 1, __ATOMIC_RELEASE);
320 0 syscall(SYS_futex, &h->hdr->drain_seq, FUTEX_WAKE, 1, NULL, NULL, 0);
321 }
322 2213 }
323  
324 /* Force-recover a stale WRITE lock left by a dead writer (held or mid-drain).
325 * Using our pid (not a bare WRITER_BIT sentinel) means a subsequent recovering
326 * process can detect and re-recover if we crash mid-recovery. */
327 0 static inline void buf_recover_stale_lock(BufHeader *hdr, uint32_t observed_wlock) {
328 0 uint32_t mypid = BUF_RWLOCK_WR((uint32_t)getpid());
329 0 ▶ if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock,
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_compare_exchange_n(&hdr->wlock, &observed_wlock, 0 0 0
330 mypid, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
331 0 return;
332 0 uint32_t seq = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE);
333 0 ▶ if (seq & 1)
Branch: 1 branch
BranchTrueFalseTotal
if (seq & 1) 0 0 0
334 0 __atomic_store_n(&hdr->seq, seq + 1, __ATOMIC_RELEASE);
335 0 __atomic_add_fetch(&hdr->stat_recoveries, 1, __ATOMIC_RELAXED);
336 0 __atomic_store_n(&hdr->wlock, 0, __ATOMIC_RELEASE);
337 0 ▶ if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->rwait, __ATOMIC_RELAXED) > 0) 0 0 0
338 0 syscall(SYS_futex, &hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
339 }
340  
341 static const struct timespec buf_lock_timeout = { BUF_LOCK_TIMEOUT_SEC, 0 };
342  
343 /* Inspect the writer word after a futex-wait timeout. If a dead writer holds
344 * it, force-recover. Dead READERS need no action here: only a writer that owns
345 * wlock drains readers, and it clears dead readers inline in its own scan. */
346 0 static inline void buf_recover_after_timeout(BufHandle *h) {
347 0 BufHeader *hdr = h->hdr;
348 0 uint32_t val = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
349 0 ▶ if (val >= BUF_RWLOCK_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= BUF_RWLOCK_WRITER_BIT) { 0 0 0
350 0 uint32_t pid = val & BUF_RWLOCK_PID_MASK;
351 0 ▶ if (!buf_pid_alive(pid))
Branch: 1 branch
BranchTrueFalseTotal
if (!buf_pid_alive(pid)) 0 0 0
352 0 buf_recover_stale_lock(hdr, val);
353 }
354 0 }
355  
356 2209 static inline void buf_rwlock_rdlock(BufHandle *h) {
357 2209 BufHeader *hdr = h->hdr;
358 2209 buf_claim_reader_slot(h);
359 2209 for (int spin = 0; ; spin++) {
360 2209 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_ACQUIRE);
361 2209 ▶ if (cur == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur == 0) { 2209 0 2209
362 /* Optimistically take the read: publish rdepth, then re-check wlock.
363 * SEQ_CST inc + SEQ_CST load vs the writer's SEQ_CST wlock CAS +
364 * SEQ_CST rdepth scan: by the single total order of SEQ_CST ops the
365 * two sides cannot both miss each other, so we never hold
366 * concurrently with a writer. */
367 2209 buf_rdepth_inc(h);
368 2209 ▶ if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->wlock, __ATOMIC_SEQ_CST) == 0) 2209 0 2209
369 2209 return; /* no writer after our publish -> we hold the read lock */
370 /* A writer appeared during our publish -- yield to it (write-preferring). */
371 0 buf_rdepth_dec(h);
372 0 buf_reader_wake_drain(h); /* let the draining writer see rdepth drop */
373 0 spin = 0;
374 0 continue;
375 }
376 /* wlock != 0: a writer holds or is acquiring. Recover if it is dead. */
377 0 if (cur >= BUF_RWLOCK_WRITER_BIT &&
378 0 !buf_pid_alive(cur & BUF_RWLOCK_PID_MASK)) {
379 0 buf_recover_stale_lock(hdr, cur);
380 0 spin = 0;
381 0 continue;
382 }
383 0 ▶ if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) { 0 0 0
384 0 buf_spin_pause();
385 0 continue;
386 }
387 0 buf_park(h);
388 0 cur = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
389 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
390 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
391 &buf_lock_timeout, NULL, 0);
392 0 ▶ if (rc == -1 && errno == ETIMEDOUT) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
393 0 buf_unpark(h);
394 0 buf_recover_after_timeout(h);
395 0 spin = 0;
396 0 continue;
397 }
398 }
399 0 buf_unpark(h);
400 0 spin = 0;
401 }
402 }
403  
404 2213 static inline void buf_rwlock_rdunlock(BufHandle *h) {
405 2213 buf_rdepth_dec(h); /* RELEASE: drop our entire contribution */
406 2213 buf_reader_wake_drain(h); /* if a writer is draining, wake it to re-scan */
407 2213 }
408  
409 583 static inline void buf_rwlock_wrlock(BufHandle *h) {
410 583 BufHeader *hdr = h->hdr;
411 583 buf_claim_reader_slot(h);
412 583 uint32_t mypid = BUF_RWLOCK_WR((uint32_t)getpid());
413 /* Phase 1: acquire the writer word (mutual exclusion among writers). */
414 584 for (int spin = 0; ; spin++) {
415 584 uint32_t expected = 0;
416 584 ▶ if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&hdr->wlock, &expected, mypid, 583 1 584
417 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED))
418 583 break;
419 /* Contended: expected now holds the current wlock value. */
420 2 if (expected >= BUF_RWLOCK_WRITER_BIT &&
421 1 !buf_pid_alive(expected & BUF_RWLOCK_PID_MASK)) {
422 0 buf_recover_stale_lock(hdr, expected);
423 0 spin = 0;
424 1 continue;
425 }
426 1 ▶ if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < BUF_RWLOCK_SPIN_LIMIT, 1)) { 1 0 1
427 1 buf_spin_pause();
428 1 continue;
429 }
430 0 buf_park(h);
431 0 uint32_t cur = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
432 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
433 0 long rc = syscall(SYS_futex, &hdr->wlock, FUTEX_WAIT, cur,
434 &buf_lock_timeout, NULL, 0);
435 0 ▶ if (rc == -1 && errno == ETIMEDOUT) {
Branch: 2 branches
BranchTrueFalseTotal
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
if (rc == -1 && errno == ETIMEDOUT) { 0 0 0
436 0 buf_unpark(h);
437 0 buf_recover_after_timeout(h);
438 0 spin = 0;
439 0 continue;
440 }
441 }
442 0 buf_unpark(h);
443 0 spin = 0;
444 }
445 /* Phase 2: we own wlock, so no NEW reader can join (they see wlock!=0 and
446 * yield). Drain the readers that were already holding when we won the CAS.
447 * The SEQ_CST CAS above + the SEQ_CST rdepth loads below are the writer side
448 * of the Dekker handshake. */
449 0 for (;;) {
450 583 uint32_t v = __atomic_load_n(&hdr->drain_seq, __ATOMIC_ACQUIRE); /* snapshot BEFORE scan */
451 583 int busy = 0;
452 /* Visit only OCCUPIED slots via the occupancy bitmap (SEQ_CST: a committed
453 * reader's bit -- set in claim, before its rdepth++ -- is ordered before
454 * this scan, so no held slot is skipped). O(BUF_OCC_WORDS + live readers)
455 * instead of O(BUF_READER_SLOTS). */
456 9911 ▶ for (uint32_t w = 0; w < BUF_OCC_WORDS; w++) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t w = 0; w < BUF_OCC_WORDS; w++) { 9328 583 9911
457 9328 uint64_t word = __atomic_load_n(&h->occ[w], __ATOMIC_SEQ_CST);
458 11176 ▶ while (word) {
Branch: 1 branch
BranchTrueFalseTotal
while (word) { 1848 9328 11176
459 1848 uint32_t i = (w << 6) + (uint32_t)__builtin_ctzll(word);
460 1848 word &= word - 1; /* consume this bit (local copy) */
461 1848 uint32_t rd = __atomic_load_n(&h->reader_slots[i].rdepth, __ATOMIC_SEQ_CST);
462 1848 ▶ if (rd == 0) continue; /* occupied but not read-locking now */
Branch: 1 branch
BranchTrueFalseTotal
if (rd == 0) continue; /* occupied but not read-locking now */ 1844 4 1848
463 4 uint32_t pid = __atomic_load_n(&h->reader_slots[i].pid, __ATOMIC_ACQUIRE);
464 4 ▶ if (pid == 0) continue; /* stale rdepth on a freed slot */
Branch: 1 branch
BranchTrueFalseTotal
if (pid == 0) continue; /* stale rdepth on a freed slot */ 0 4 4
465 4 ▶ if (!buf_pid_alive(pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf_pid_alive(pid)) { 4 0 4
466 /* Dead reader: drop its pid so the slot no longer counts. Leave
467 * the occ bit set (harmless -- a later scan hits pid==0 and skips,
468 * a re-claim re-sets it) to avoid racing a concurrent claimant. */
469 4 uint32_t ep = pid;
470 4 ▶ if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &ep, 0,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&h->reader_slots[i].pid, &ep, 0, 4 0 4
471 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
472 4 __atomic_add_fetch(&hdr->stat_recoveries, 1, __ATOMIC_RELAXED);
473 4 continue;
474 }
475 0 busy = 1; /* live reader still holding */
476 }
477 }
478 /* A live slotless reader keeps us waiting; a crashed slotless reader that
479 * cannot be attributed to a pid is the documented slotless limitation. */
480 583 ▶ if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->slotless_rdepth, __ATOMIC_SEQ_CST) != 0) 0 583 583
481 0 busy = 1;
482 583 ▶ if (!busy)
Branch: 1 branch
BranchTrueFalseTotal
if (!busy) 583 0 583
483 583 return; /* exclusive: wlock held + every rdepth 0 */
484 /* Wait for a reader to release (drain_seq bump) or time out to re-scan
485 * (which reclaims any newly-dead slotted reader). */
486 0 syscall(SYS_futex, &hdr->drain_seq, FUTEX_WAIT, v, &buf_lock_timeout, NULL, 0);
487 }
488 }
489  
490 583 static inline void buf_rwlock_wrunlock(BufHandle *h) {
491 583 __atomic_store_n(&h->hdr->wlock, 0, __ATOMIC_RELEASE);
492 583 ▶ if (__atomic_load_n(&h->hdr->rwait, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&h->hdr->rwait, __ATOMIC_RELAXED) > 0) 9 574 583
493 9 syscall(SYS_futex, &h->hdr->wlock, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
494 583 }
495  
496 /* ---- Seqlock ---- */
497  
498 45 static inline uint32_t buf_seqlock_read_begin(BufHeader *hdr) {
499 45 int spin = 0;
500 0 for (;;) {
501 45 uint32_t s = __atomic_load_n(&hdr->seq, __ATOMIC_ACQUIRE);
502 45 ▶ if (__builtin_expect((s & 1) == 0, 1)) return s;
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect((s & 1) == 0, 1)) return s; 45 0 45
503 0 ▶ if (__builtin_expect(spin < 100000, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < 100000, 1)) { 0 0 0
504 0 buf_spin_pause();
505 0 spin++;
506 0 continue;
507 }
508 0 uint32_t val = __atomic_load_n(&hdr->wlock, __ATOMIC_RELAXED);
509 0 ▶ if (val >= BUF_RWLOCK_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= BUF_RWLOCK_WRITER_BIT) { 0 0 0
510 0 uint32_t pid = val & BUF_RWLOCK_PID_MASK;
511 0 ▶ if (!buf_pid_alive(pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf_pid_alive(pid)) { 0 0 0
512 0 buf_recover_stale_lock(hdr, val);
513 0 spin = 0;
514 0 continue;
515 }
516 }
517 0 struct timespec ts = {0, 1000000};
518 0 nanosleep(&ts, NULL);
519 0 spin = 0;
520 }
521 }
522  
523 45 static inline int buf_seqlock_read_retry(uint32_t *seq, uint32_t start) {
524 /* Acquire FENCE (LoadLoad): the section's data loads must retire before we
525 * re-read seq; a plain acquire load is the wrong direction (ARM64 torn read). */
526 45 __atomic_thread_fence(__ATOMIC_ACQUIRE);
527 45 return __atomic_load_n(seq, __ATOMIC_RELAXED) != start;
528 }
529  
530 583 static inline void buf_seqlock_write_begin(uint32_t *seq) {
531 583 __atomic_add_fetch(seq, 1, __ATOMIC_RELEASE); /* seq becomes odd */
532 /* StoreStore: publish the odd seq before the section's data writes, else an
533 * ARM64 reader could see an even seq with half-written data (Linux smp_wmb). */
534 583 __atomic_thread_fence(__ATOMIC_RELEASE);
535 583 }
536  
537 583 static inline void buf_seqlock_write_end(uint32_t *seq) {
538 583 __atomic_add_fetch(seq, 1, __ATOMIC_RELEASE);
539 583 }
540  
541 /* ---- mmap create/open ---- */
542  
543 /* Race-safe create-or-attach with restrictive perms + symlink refusal.
544 * The backing file is created 0600 by default (see file_mode); a local peer
545 * cannot pre-create it as a symlink (O_NOFOLLOW) nor open a wider-permissioned
546 * copy. Sets *created=1 iff this call won the O_EXCL race and made the file. */
547 2268 static int buf_secure_open(const char *path, mode_t file_mode, int *created, char *errbuf) {
548 2268 ▶ for (int attempt = 0; attempt < 100; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < 100; attempt++) { 2268 0 2268
549 2268 int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, file_mode);
550 2268 ▶ if (fd >= 0) { (void)fchmod(fd, file_mode); *created = 1; return fd; } /* exact mode: umask narrowed the create */
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { (void)fchmod(fd, file_mode); *created = 1; return fd; } /* exact mode: umask narrowed the create */ 49 2219 2268
551 2219 ▶ if (errno != EEXIST) {
Branch: 1 branch
BranchTrueFalseTotal
if (errno != EEXIST) { 0 2219 2219
552 0 snprintf(errbuf, BUF_ERR_BUFLEN, "create(%s): %s", path, strerror(errno));
553 0 return -1;
554 }
555 2219 fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
556 2219 ▶ if (fd >= 0) { *created = 0; return fd; }
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { *created = 0; return fd; } 2219 0 2219
557 0 ▶ if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */
Branch: 1 branch
BranchTrueFalseTotal
if (errno == ENOENT) continue; /* creator unlinked between our two opens; retry */ 0 0 0
558 0 snprintf(errbuf, BUF_ERR_BUFLEN, "open(%s): %s", path, strerror(errno));
559 0 return -1;
560 }
561 0 snprintf(errbuf, BUF_ERR_BUFLEN, "open(%s): create/attach kept racing", path);
562 0 return -1;
563 }
564  
565 /* True iff the whole file is zero -- what an abandoned mid-init
566 creator leaves. Lets recovery re-init only a provably-empty file, never
567 one that merely starts with a zero word. Cold path, so a byte scan is
568 fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
569 2 static int buf_file_is_zero(int fd, uint64_t size) {
570 char buf[16384];
571 5 ▶ for (uint64_t off = 0; off < size; ) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t off = 0; off < size; ) { 4 1 5
572 4 ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
573 4 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 4 4
574 49667 ▶ for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0;
Branch: 2 branches
BranchTrueFalseTotal
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 1 49663 49664
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 49664 3 49667
575 3 off += (uint64_t)n;
576 }
577 1 return 1;
578 }
579  
580 /* Opt-in (DATA_BUFFER_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
581 59 static int buf_reserve(int fd, uint64_t size) {
582 59 const char *sp = getenv("DATA_BUFFER_SHARED_SPARSE");
583 59 ▶ if (!sp || strcmp(sp, "0")) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!sp || strcmp(sp, "0")) return 0; 0 59 59
if (!sp || strcmp(sp, "0")) return 0; 0 0 0
584 /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
585 * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
586 sigset_t all, old;
587 0 sigfillset(&all);
588 0 sigprocmask(SIG_BLOCK, &all, &old);
589 int e;
590 0 ▶ do e = posix_fallocate(fd, 0, (off_t)size); while (e == EINTR);
Branch: 1 branch
BranchTrueFalseTotal
do e = posix_fallocate(fd, 0, (off_t)size); while (e == EINTR); 0 0 0
591 0 sigprocmask(SIG_SETMASK, &old, NULL);
592 0 ▶ if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0; 0 0 0
593 0 errno = e;
594 0 return -1;
595 }
596  
597 2222 static int buf_header_geometry_valid(const BufHeader *hdr, uint64_t size) {
598 2222 uint64_t data_off = sizeof(BufHeader) +
599 (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot) + BUF_OCC_BYTES;
600 4442 return hdr->reader_slots_off == sizeof(BufHeader) &&
601 2220 ▶ hdr->data_off == data_off && hdr->total_size == size &&
Branch: 2 branches
BranchTrueFalseTotal
hdr->data_off == data_off && hdr->total_size == size && 2216 4 2220
hdr->data_off == data_off && hdr->total_size == size && 2212 4 2216
602 6654 ▶ hdr->elem_size != 0 && size >= data_off &&
Branch: 3 branches
BranchTrueFalseTotal
hdr->elem_size != 0 && size >= data_off && 2220 2 2222
hdr->elem_size != 0 && size >= data_off && 2212 0 2212
hdr->elem_size != 0 && size >= data_off && 2212 0 2212
603 2212 ▶ hdr->capacity <= (size - data_off) / hdr->elem_size;
Branch: 1 branch
BranchTrueFalseTotal
hdr->capacity <= (size - data_off) / hdr->elem_size; 2212 0 2212
604 }
605  
606 2268 static BufHandle *buf_create_map(const char *path, uint64_t capacity,
607 uint32_t elem_size, uint32_t variant_id,
608 mode_t file_mode, char *errbuf) {
609 2268 errbuf[0] = '\0';
610 2268 int created = 0;
611 2268 int fd = buf_secure_open(path, file_mode, &created, errbuf);
612 2268 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 2268 2268
613 0 return NULL;
614 }
615  
616 /* Lock file for init race prevention */
617 2268 ▶ if (flock(fd, LOCK_EX) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (flock(fd, LOCK_EX) < 0) { 0 2268 2268
618 0 snprintf(errbuf, BUF_ERR_BUFLEN, "flock(%s): %s", path, strerror(errno));
619 0 close(fd);
620 0 return NULL;
621 }
622  
623 2268 uint64_t reader_slots_off = sizeof(BufHeader); /* 128 */
624 2268 uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
625 2268 uint64_t occ_off = reader_slots_off + reader_slots_size; /* occupancy bitmap */
626 2268 uint64_t data_off = occ_off + BUF_OCC_BYTES; /* cache-aligned */
627 2268 ▶ if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
Branch: 2 branches
BranchTrueFalseTotal
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 2268 0 2268
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 0 2268 2268
628 0 snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
629 0 flock(fd, LOCK_UN);
630 0 close(fd);
631 0 return NULL;
632 }
633 2268 uint64_t total_size = data_off + capacity * elem_size;
634  
635 struct stat st;
636 2268 ▶ if (fstat(fd, &st) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { 0 2268 2268
637 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(%s): %s", path, strerror(errno));
638 0 flock(fd, LOCK_UN);
639 0 close(fd);
640 0 return NULL;
641 }
642  
643 /* Not gated on `created`: winning O_EXCL does not mean the inode is still
644 * empty (see the resize comment below), so a non-empty file too small to hold
645 * a header must be refused here whether we created it or not -- otherwise the
646 * init memset below runs past the end of the mapping. */
647 2268 ▶ if (st.st_size > 0 && (uint64_t)st.st_size < sizeof(BufHeader)) {
Branch: 2 branches
BranchTrueFalseTotal
if (st.st_size > 0 && (uint64_t)st.st_size < sizeof(BufHeader)) { 2219 49 2268
if (st.st_size > 0 && (uint64_t)st.st_size < sizeof(BufHeader)) { 0 2219 2219
648 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: file too small (%lld)", path, (long long)st.st_size);
649 0 flock(fd, LOCK_UN); close(fd); return NULL;
650 }
651 2268 ▶ if (!created && st.st_size == 0 && (st.st_uid != geteuid() || fchmod(fd, file_mode) < 0)) {
Branch: 4 branches
BranchTrueFalseTotal
if (!created && st.st_size == 0 && (st.st_uid != geteuid() || fchmod(fd, file_mode) < 0)) { 2219 49 2268
if (!created && st.st_size == 0 && (st.st_uid != geteuid() || fchmod(fd, file_mode) < 0)) { 0 2219 2219
if (!created && st.st_size == 0 && (st.st_uid != geteuid() || fchmod(fd, file_mode) < 0)) { 0 0 0
if (!created && st.st_size == 0 && (st.st_uid != geteuid() || fchmod(fd, file_mode) < 0)) { 0 0 0
652 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: refusing to initialize file not owned by us", path);
653 0 flock(fd, LOCK_UN); close(fd); return NULL;
654 }
655 /* Never SHRINK: winning O_EXCL does not mean the inode is still empty. If we
656 * lose the race to flock, a peer publishes its buffer into this inode while we
657 * wait -- truncating it to our (smaller) total_size would discard the peer's
658 * data and SIGBUS it on its next access. Nor may we GROW one: extending a
659 * peer's published file past its recorded total_size makes buf_open_fd (which
660 * requires total_size == st_size) reject it forever. So resize only a file that
661 * is still uninitialized -- zero-length, or full-size with no magic committed. */
662 2268 int may_resize = (st.st_size == 0);
663 2268 ▶ if (!may_resize && created && (uint64_t)st.st_size >= sizeof(BufHeader)) {
Branch: 3 branches
BranchTrueFalseTotal
if (!may_resize && created && (uint64_t)st.st_size >= sizeof(BufHeader)) { 2219 49 2268
if (!may_resize && created && (uint64_t)st.st_size >= sizeof(BufHeader)) { 0 2219 2219
if (!may_resize && created && (uint64_t)st.st_size >= sizeof(BufHeader)) { 0 0 0
664 /* We won O_EXCL but the inode is not empty, so we lost the race to flock.
665 * Resize only if the peer has not committed yet; growing a published file
666 * past its recorded total_size makes buf_open_fd reject it forever. */
667 0 uint32_t probe = 0;
668 0 may_resize = (pread(fd, &probe, sizeof probe, 0) == (ssize_t)sizeof probe
669 0 ▶ && probe == 0);
Branch: 2 branches
BranchTrueFalseTotal
&& probe == 0); 0 0 0
&& probe == 0); 0 0 0
670 }
671 2268 int reserved = 0;
672 2268 ▶ if (may_resize && (uint64_t)st.st_size < total_size) {
Branch: 2 branches
BranchTrueFalseTotal
if (may_resize && (uint64_t)st.st_size < total_size) { 49 2219 2268
if (may_resize && (uint64_t)st.st_size < total_size) { 49 0 49
673 49 ▶ if (ftruncate(fd, (off_t)total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total_size) < 0) { 0 49 49
674 0 snprintf(errbuf, BUF_ERR_BUFLEN, "ftruncate(%s): %s", path, strerror(errno));
675 0 flock(fd, LOCK_UN);
676 0 close(fd);
677 0 return NULL;
678 }
679 49 ▶ if (buf_reserve(fd, total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf_reserve(fd, total_size) < 0) { 0 49 49
680 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total_size, strerror(errno));
681 0 if (ftruncate(fd, 0) < 0) { /* best effort */ }
682 0 flock(fd, LOCK_UN);
683 0 close(fd);
684 0 return NULL;
685 }
686 49 reserved = 1;
687 }
688  
689 /* Re-stat after possible truncate */
690 2268 ▶ if (fstat(fd, &st) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { 0 2268 2268
691 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(%s): %s", path, strerror(errno));
692 0 flock(fd, LOCK_UN);
693 0 close(fd);
694 0 return NULL;
695 }
696  
697 2268 void *base = mmap(NULL, (size_t)st.st_size, PROT_READ | PROT_WRITE,
698 MAP_SHARED, fd, 0);
699 2268 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 2268 2268
700 0 snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(%s): %s", path, strerror(errno));
701 0 flock(fd, LOCK_UN);
702 0 close(fd);
703 0 return NULL;
704 }
705  
706 2268 BufHeader *hdr = (BufHeader *)base;
707  
708 /* Gate on the header, not on `created`. A file we created is normally still
709 * zero here and initializes as usual -- but winning O_EXCL is not a guarantee:
710 * if we lose the race to flock, a peer publishes its buffer into this inode
711 * while we wait, and `created` is then true over an initialized header. Gating
712 * on `created` would memset that peer's buffer (and its lock state) out from
713 * under it; gating on the header attaches to it instead, which is correct. */
714 2268 ▶ if (hdr->magic == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic == 0) { 52 2216 2268
715 /* A pre-existing but uninitialized file (magic==0, not created by us) may
716 * be smaller than the region we are about to zero; a hostile peer could
717 * pre-create an undersized file to drive the init memset out of bounds. */
718 /* Also not gated on `created`: the resize above deliberately declines to
719 * grow a file it cannot prove is uninitialized, so a created file can
720 * still reach here undersized. Refuse rather than zero past the mapping. */
721 52 ▶ if ((uint64_t)st.st_size < total_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)st.st_size < total_size) { 1 51 52
722 1 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: file too small to initialize", path);
723 1 goto fail;
724 }
725 /* An abandoned mid-init file (magic==0, already ftruncate'd so st_size>0)
726 * skips the size==0 ownership check above; verify ownership here too so we
727 * never (re)initialize a file we do not own. */
728 51 ▶ if (!created && st.st_uid != geteuid()) {
Branch: 2 branches
BranchTrueFalseTotal
if (!created && st.st_uid != geteuid()) { 2 49 51
if (!created && st.st_uid != geteuid()) { 0 2 2
729 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: refusing to initialize file not owned by us", path);
730 0 goto fail;
731 }
732 /* Re-initialize a pre-existing file ONLY when it is provably all-zero (a
733 * fresh ftruncate, which is all an abandoned mid-init creator leaves), so
734 * a same-owner file that merely starts with a zero word is never clobbered. */
735 51 ▶ if (!created && !buf_file_is_zero(fd, (uint64_t)st.st_size)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!created && !buf_file_is_zero(fd, (uint64_t)st.st_size)) { 2 49 51
if (!created && !buf_file_is_zero(fd, (uint64_t)st.st_size)) { 1 1 2
736 1 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: uninitialized file is not empty; refusing to initialize", path);
737 1 goto fail;
738 }
739 /* Apply the requested mode only now that we have decided to adopt the file:
740 * doing it with the ownership test would rewrite the permissions of a file
741 * we then turn around and refuse. */
742 50 ▶ if (!created && fchmod(fd, file_mode) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!created && fchmod(fd, file_mode) < 0) { 1 49 50
if (!created && fchmod(fd, file_mode) < 0) { 0 1 1
743 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: fchmod: %s", path, strerror(errno));
744 0 goto fail;
745 }
746 50 ▶ if (!reserved && buf_reserve(fd, (uint64_t)st.st_size) < 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!reserved && buf_reserve(fd, (uint64_t)st.st_size) < 0) { 1 49 50
if (!reserved && buf_reserve(fd, (uint64_t)st.st_size) < 0) { 0 1 1
747 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: cannot reserve %llu bytes: %s", path, (unsigned long long)st.st_size, strerror(errno));
748 0 goto fail;
749 }
750 /* Zero reader_slots + occ bitmap, before any header field is written, so a
751 * creator killed here stays in the all-zero state the recovery below can
752 * re-initialize. The DATA area is deliberately not zeroed: every path that
753 * reaches here already has it zero (a fresh ftruncate extension, or a file
754 * the scan above proved all-zero), and writing it would fault in and
755 * allocate every page of an otherwise sparse file -- which on a filesystem
756 * with less free space than the buffer turns create into a SIGBUS. */
757 50 memset((char *)base + reader_slots_off, 0,
758 (size_t)(reader_slots_size + BUF_OCC_BYTES));
759 /* Initialize header */
760 50 memset(hdr, 0, sizeof(BufHeader));
761 50 hdr->version = BUF_VERSION;
762 50 hdr->variant_id = variant_id;
763 50 hdr->elem_size = elem_size;
764 50 hdr->capacity = capacity;
765 50 hdr->total_size = (uint64_t)st.st_size;
766 50 hdr->data_off = data_off;
767 50 hdr->reader_slots_off = reader_slots_off;
768 /* Publish magic LAST, as a release store: it is the commit point, so
769 * a creator killed before it leaves magic==0 and never a file
770 * mistaken for a valid one. A kill during the field stores leaves
771 * one to remove by hand. */
772 50 __atomic_store_n(&hdr->magic, BUF_MAGIC, __ATOMIC_RELEASE);
773 50 __atomic_thread_fence(__ATOMIC_RELEASE);
774 } else {
775 /* Validate existing header */
776 2216 ▶ if (hdr->magic != BUF_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic != BUF_MAGIC) { 2 2214 2216
777 2 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: bad magic (0x%08x)", path, hdr->magic);
778 2 goto fail;
779 }
780 2214 ▶ if (hdr->version != BUF_VERSION) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->version != BUF_VERSION) { 0 2214 2214
781 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: version mismatch (%u != %u)",
782 path, hdr->version, BUF_VERSION);
783 0 goto fail;
784 }
785 2214 ▶ if (hdr->variant_id != variant_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->variant_id != variant_id) { 1 2213 2214
786 1 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: variant mismatch (%u != %u)",
787 path, hdr->variant_id, variant_id);
788 1 goto fail;
789 }
790 2213 ▶ if (hdr->elem_size != elem_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->elem_size != elem_size) { 0 2213 2213
791 0 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: elem_size mismatch (%u != %u)",
792 path, hdr->elem_size, elem_size);
793 0 goto fail;
794 }
795 2213 ▶ if (!buf_header_geometry_valid(hdr, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf_header_geometry_valid(hdr, (uint64_t)st.st_size)) { 5 2208 2213
796 5 snprintf(errbuf, BUF_ERR_BUFLEN, "%s: corrupt header (data doesn't fit in file)", path);
797 5 goto fail;
798 }
799 }
800  
801 2258 flock(fd, LOCK_UN);
802 2258 close(fd);
803  
804 2258 BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
805 2258 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 2258 2258
806 0 snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
807 0 munmap(base, (size_t)st.st_size);
808 0 return NULL;
809 }
810 2258 h->hdr = hdr;
811 2258 h->data = (char *)base + hdr->data_off;
812 2258 h->reader_slots = (BufReaderSlot *)((char *)base + sizeof(BufHeader)); /* trusted layout, not the peer-writable header offset */
813 2258 h->occ = (uint64_t *)((char *)base + sizeof(BufHeader) + reader_slots_size); /* trusted layout offset */
814 2258 h->capacity = hdr->capacity; /* cache validated geometry; peer can't grow it under us */
815 2258 h->elem_size = hdr->elem_size;
816 2258 h->my_slot_idx = UINT32_MAX;
817 2258 h->mmap_size = (size_t)st.st_size;
818 2258 h->path = strdup(path);
819 2258 h->fd = -1;
820 2258 h->efd = -1;
821 2258 return h;
822  
823 10 fail:
824 10 munmap(base, (size_t)st.st_size);
825 10 flock(fd, LOCK_UN);
826 10 close(fd);
827 10 return NULL;
828 }
829  
830 /* ---- Anonymous mmap (no file, fork-only sharing) ---- */
831  
832 63 static BufHandle *buf_create_anon(uint64_t capacity, uint32_t elem_size,
833 uint32_t variant_id, char *errbuf) {
834 63 errbuf[0] = '\0';
835 63 uint64_t reader_slots_off = sizeof(BufHeader);
836 63 uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
837 63 uint64_t occ_off = reader_slots_off + reader_slots_size;
838 63 uint64_t data_off = occ_off + BUF_OCC_BYTES;
839 63 ▶ if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
Branch: 2 branches
BranchTrueFalseTotal
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 63 0 63
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 0 63 63
840 0 snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
841 0 return NULL;
842 }
843 63 uint64_t total_size = data_off + capacity * elem_size;
844  
845 63 void *base = mmap(NULL, (size_t)total_size, PROT_READ | PROT_WRITE,
846 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
847 63 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 63 63
848 0 snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(anon): %s", strerror(errno));
849 0 return NULL;
850 }
851  
852 63 BufHeader *hdr = (BufHeader *)base;
853 63 memset(hdr, 0, sizeof(BufHeader));
854 63 hdr->version = BUF_VERSION;
855 63 hdr->variant_id = variant_id;
856 63 hdr->elem_size = elem_size;
857 63 hdr->capacity = capacity;
858 63 hdr->total_size = total_size;
859 63 hdr->data_off = data_off;
860 63 hdr->reader_slots_off = reader_slots_off;
861 /* MAP_ANONYMOUS already zero-fills reader_slots, occ bitmap and data. */
862 /* Publish magic LAST, as a release store: it is the commit point, so a
863 creator killed before it leaves magic==0 and never a file mistaken for
864 a valid one. A kill during the field stores leaves one to remove by
865 hand. */
866 63 __atomic_store_n(&hdr->magic, BUF_MAGIC, __ATOMIC_RELEASE);
867  
868 63 BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
869 63 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 63 63
870 0 snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
871 0 munmap(base, (size_t)total_size);
872 0 return NULL;
873 }
874 63 h->hdr = hdr;
875 63 h->data = (char *)base + data_off;
876 63 h->reader_slots = (BufReaderSlot *)((char *)base + reader_slots_off);
877 63 h->occ = (uint64_t *)((char *)base + occ_off);
878 63 h->capacity = hdr->capacity; /* cache validated geometry */
879 63 h->elem_size = hdr->elem_size;
880 63 h->my_slot_idx = UINT32_MAX;
881 63 h->mmap_size = (size_t)total_size;
882 63 h->path = NULL;
883 63 h->fd = -1;
884 63 h->efd = -1;
885 63 return h;
886 }
887  
888 /* ---- memfd (named anonymous, shareable via fd passing) ---- */
889  
890 9 static BufHandle *buf_create_memfd(const char *name, uint64_t capacity,
891 uint32_t elem_size, uint32_t variant_id,
892 char *errbuf) {
893 9 errbuf[0] = '\0';
894 9 uint64_t reader_slots_off = sizeof(BufHeader);
895 9 uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
896 9 uint64_t occ_off = reader_slots_off + reader_slots_size;
897 9 uint64_t data_off = occ_off + BUF_OCC_BYTES;
898 9 ▶ if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) {
Branch: 2 branches
BranchTrueFalseTotal
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 9 0 9
if (elem_size > 0 && capacity > (UINT64_MAX - data_off) / elem_size) { 0 9 9
899 0 snprintf(errbuf, BUF_ERR_BUFLEN, "buffer size overflow");
900 0 return NULL;
901 }
902 9 uint64_t total_size = data_off + capacity * elem_size;
903  
904 9 int fd = (int)syscall(SYS_memfd_create, name, MFD_CLOEXEC | MFD_ALLOW_SEALING);
905 9 ▶ if (fd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) { 0 9 9
906 0 snprintf(errbuf, BUF_ERR_BUFLEN, "memfd_create: %s", strerror(errno));
907 0 return NULL;
908 }
909 9 ▶ if (ftruncate(fd, (off_t)total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total_size) < 0) { 0 9 9
910 0 snprintf(errbuf, BUF_ERR_BUFLEN, "ftruncate(memfd): %s", strerror(errno));
911 0 close(fd);
912 0 return NULL;
913 }
914 9 ▶ if (buf_reserve(fd, total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf_reserve(fd, total_size) < 0) { 0 9 9
915 0 snprintf(errbuf, BUF_ERR_BUFLEN, "memfd: cannot reserve %llu bytes: %s", (unsigned long long)total_size, strerror(errno));
916 0 close(fd);
917 0 return NULL;
918 }
919 9 (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
920  
921 9 void *base = mmap(NULL, (size_t)total_size, PROT_READ | PROT_WRITE,
922 MAP_SHARED, fd, 0);
923 9 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 9 9
924 0 snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(memfd): %s", strerror(errno));
925 0 close(fd);
926 0 return NULL;
927 }
928  
929 9 BufHeader *hdr = (BufHeader *)base;
930 9 memset(hdr, 0, sizeof(BufHeader));
931 9 hdr->version = BUF_VERSION;
932 9 hdr->variant_id = variant_id;
933 9 hdr->elem_size = elem_size;
934 9 hdr->capacity = capacity;
935 9 hdr->total_size = total_size;
936 9 hdr->data_off = data_off;
937 9 hdr->reader_slots_off = reader_slots_off;
938 /* Publish magic LAST, as a release store: it is the commit point, so a
939 creator killed before it leaves magic==0 and never a file mistaken for
940 a valid one. A kill during the field stores leaves one to remove by
941 hand. */
942 9 __atomic_store_n(&hdr->magic, BUF_MAGIC, __ATOMIC_RELEASE);
943  
944 9 BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
945 9 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 9 9
946 0 snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
947 0 munmap(base, (size_t)total_size);
948 0 close(fd);
949 0 return NULL;
950 }
951 9 h->hdr = hdr;
952 9 h->data = (char *)base + data_off;
953 9 h->reader_slots = (BufReaderSlot *)((char *)base + reader_slots_off);
954 9 h->occ = (uint64_t *)((char *)base + occ_off);
955 9 h->capacity = hdr->capacity; /* cache validated geometry */
956 9 h->elem_size = hdr->elem_size;
957 9 h->my_slot_idx = UINT32_MAX;
958 9 h->mmap_size = (size_t)total_size;
959 9 h->path = NULL;
960 9 h->fd = fd;
961 9 h->efd = -1;
962 9 return h;
963 }
964  
965 /* ---- Open from fd (received via SCM_RIGHTS or dup) ---- */
966  
967 10 static BufHandle *buf_open_fd(int fd, uint32_t elem_size, uint32_t variant_id,
968 char *errbuf) {
969 10 errbuf[0] = '\0';
970 struct stat st;
971 10 ▶ if (fstat(fd, &st) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { 0 10 10
972 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fstat(fd=%d): %s", fd, strerror(errno));
973 0 return NULL;
974 }
975 10 ▶ if ((uint64_t)st.st_size < sizeof(BufHeader)) {
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(BufHeader)) { 0 10 10
976 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: file too small for header", fd);
977 0 return NULL;
978 }
979 /* before mmap: a creator may truncate the file until it has set magic */
980 10 uint32_t magic = 0;
981 10 ▶ if (pread(fd, &magic, sizeof magic, offsetof(BufHeader, magic)) != (ssize_t)sizeof magic || magic != BUF_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(BufHeader, magic)) != (ssize_t)sizeof magic || magic != BUF_MAGIC) { 10 0 10
if (pread(fd, &magic, sizeof magic, offsetof(BufHeader, magic)) != (ssize_t)sizeof magic || magic != BUF_MAGIC) { 0 10 10
982 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: bad magic (0x%08x)", fd, magic);
983 0 return NULL;
984 }
985  
986 10 void *base = mmap(NULL, (size_t)st.st_size, PROT_READ | PROT_WRITE,
987 MAP_SHARED, fd, 0);
988 10 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 10 10
989 0 snprintf(errbuf, BUF_ERR_BUFLEN, "mmap(fd=%d): %s", fd, strerror(errno));
990 0 return NULL;
991 }
992  
993 10 BufHeader *hdr = (BufHeader *)base;
994 10 ▶ if (hdr->magic != BUF_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic != BUF_MAGIC) { 0 10 10
995 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: bad magic (0x%08x)", fd, hdr->magic);
996 0 goto fail;
997 }
998 10 ▶ if (hdr->version != BUF_VERSION) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->version != BUF_VERSION) { 0 10 10
999 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: version mismatch (%u != %u)",
1000 fd, hdr->version, BUF_VERSION);
1001 0 goto fail;
1002 }
1003 10 ▶ if (hdr->variant_id != variant_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->variant_id != variant_id) { 1 9 10
1004 1 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: variant mismatch (%u != %u)",
1005 fd, hdr->variant_id, variant_id);
1006 1 goto fail;
1007 }
1008 9 ▶ if (hdr->elem_size != elem_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->elem_size != elem_size) { 0 9 9
1009 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: elem_size mismatch (%u != %u)",
1010 fd, hdr->elem_size, elem_size);
1011 0 goto fail;
1012 }
1013 9 uint64_t reader_slots_size = (uint64_t)BUF_READER_SLOTS * sizeof(BufReaderSlot);
1014 9 ▶ if (!buf_header_geometry_valid(hdr, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!buf_header_geometry_valid(hdr, (uint64_t)st.st_size)) { 5 4 9
1015 5 snprintf(errbuf, BUF_ERR_BUFLEN, "fd=%d: corrupt header", fd);
1016 5 goto fail;
1017 }
1018  
1019 {
1020 4 int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1021 4 ▶ if (myfd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (myfd < 0) { 0 4 4
1022 0 snprintf(errbuf, BUF_ERR_BUFLEN, "fcntl(F_DUPFD_CLOEXEC, fd=%d): %s",
1023 0 fd, strerror(errno));
1024 0 munmap(base, (size_t)st.st_size);
1025 0 return NULL;
1026 }
1027 4 BufHandle *h = (BufHandle *)calloc(1, sizeof(BufHandle));
1028 4 ▶ if (!h) {
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { 0 4 4
1029 0 snprintf(errbuf, BUF_ERR_BUFLEN, "calloc: out of memory");
1030 0 close(myfd);
1031 0 munmap(base, (size_t)st.st_size);
1032 0 return NULL;
1033 }
1034 4 h->hdr = hdr;
1035 4 h->data = (char *)base + hdr->data_off;
1036 4 h->reader_slots = (BufReaderSlot *)((char *)base + sizeof(BufHeader)); /* trusted layout, not the peer-writable header offset */
1037 4 h->occ = (uint64_t *)((char *)base + sizeof(BufHeader) + reader_slots_size); /* trusted layout offset */
1038 4 h->capacity = hdr->capacity; /* cache validated geometry */
1039 4 h->elem_size = hdr->elem_size;
1040 4 h->my_slot_idx = UINT32_MAX;
1041 4 h->mmap_size = (size_t)st.st_size;
1042 4 h->path = NULL;
1043 4 h->fd = myfd;
1044 4 h->efd = -1;
1045 4 return h;
1046 }
1047  
1048 6 fail:
1049 6 munmap(base, (size_t)st.st_size);
1050 6 return NULL;
1051 }
1052  
1053 /* ---- msync ---- */
1054  
1055 3 static inline int buf_msync(BufHandle *h) {
1056 3 ▶ if (!h || !h->hdr) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !h->hdr) return 0; 3 0 3
if (!h || !h->hdr) return 0; 0 3 3
1057 3 return msync(h->hdr, h->mmap_size, MS_SYNC);
1058 }
1059  
1060 /* ---- Eventfd integration (opt-in notifications) ---- */
1061  
1062 19 static int buf_create_eventfd(BufHandle *h) {
1063 19 ▶ if (h->efd >= 0) return h->efd;
Branch: 1 branch
BranchTrueFalseTotal
if (h->efd >= 0) return h->efd; 1 18 19
1064 18 int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
1065 18 ▶ if (efd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (efd < 0) return -1; 0 18 18
1066 18 h->efd = efd;
1067 18 h->efd_owned = 1;
1068 18 return efd;
1069 }
1070  
1071 13 static void buf_attach_eventfd(BufHandle *h, int efd) {
1072 13 ▶ if (h->efd == efd) return;
Branch: 1 branch
BranchTrueFalseTotal
if (h->efd == efd) return; 11 2 13
1073 2 ▶ if (h->efd >= 0 && h->efd_owned) close(h->efd);
Branch: 2 branches
BranchTrueFalseTotal
if (h->efd >= 0 && h->efd_owned) close(h->efd); 0 2 2
if (h->efd >= 0 && h->efd_owned) close(h->efd); 0 0 0
1074 2 h->efd = efd;
1075 2 h->efd_owned = 0;
1076 }
1077  
1078 29 static int buf_notify(BufHandle *h) {
1079 29 ▶ if (h->efd < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (h->efd < 0) return 0; 1 28 29
1080 28 uint64_t val = 1;
1081 28 return write(h->efd, &val, sizeof(val)) == sizeof(val);
1082 }
1083  
1084 20 static int64_t buf_wait_notify(BufHandle *h) {
1085 20 ▶ if (h->efd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (h->efd < 0) return -1; 1 19 20
1086 19 uint64_t val = 0;
1087 19 ▶ if (read(h->efd, &val, sizeof(val)) != sizeof(val)) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (read(h->efd, &val, sizeof(val)) != sizeof(val)) return -1; 2 17 19
1088 17 return (int64_t)val;
1089 }
1090  
1091 2334 static void buf_close_map(BufHandle *h) {
1092 2334 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 2334 2334
1093 /* Release this handle's locks before freeing the mapping, so a live process
1094 * cannot strand its reader contribution or writer lock. */
1095 2334 ▶ if (h->hdr) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->hdr) { 2334 0 2334
1096 /* Release only locks THIS process took. A forked child inherits
1097 * rd_held/wr_locked verbatim, but those holds were published by the
1098 * parent (its slot rdepth, its pid in wlock): dropping them here
1099 * would unlock the parent's live critical section. Same owner test
1100 * as the slot-release guard below; cached_pid/cached_fork_gen are
1101 * recorded by buf_claim_reader_slot, which every lock op runs, so a
1102 * nonzero rd_held/wr_locked implies they are set. */
1103 2334 uint32_t cur_gen = __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED);
1104 2334 ▶ if (h->cached_pid && h->cached_pid == (uint32_t)getpid() &&
Branch: 2 branches
BranchTrueFalseTotal
if (h->cached_pid && h->cached_pid == (uint32_t)getpid() && 2245 89 2334
if (h->cached_pid && h->cached_pid == (uint32_t)getpid() && 1144 1101 2245
1105 1144 ▶ h->cached_fork_gen == cur_gen) {
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == cur_gen) { 1144 0 1144
1106 1144 ▶ while (h->rd_held > 0) buf_rwlock_rdunlock(h); /* decrements rd_held */
Branch: 1 branch
BranchTrueFalseTotal
while (h->rd_held > 0) buf_rwlock_rdunlock(h); /* decrements rd_held */ 0 1144 1144
1107 /* Mirror unlock_wr exactly: end the seqlock section BEFORE
1108 * dropping wlock. wrunlock alone leaves seq odd forever, and
1109 * every seqlock bulk reader then spins in its slow path with no
1110 * recovery (wlock == 0, so stale-writer recovery never fires). */
1111 1144 ▶ if (h->wr_locked) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->wr_locked) { 0 1144 1144
1112 0 buf_seqlock_write_end(&h->hdr->seq);
1113 0 buf_rwlock_wrunlock(h);
1114 0 h->wr_locked = 0;
1115 }
1116 }
1117 }
1118 /* Release reader slot -- only if we still own it AND no fork has happened
1119 * since we claimed it. A forked child that inherits the handle but never
1120 * acquired the lock itself must NOT clear the parent's slot. */
1121 2334 ▶ if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid &&
Branch: 3 branches
BranchTrueFalseTotal
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 2334 0 2334
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 2094 240 2334
if (h->reader_slots && h->my_slot_idx != UINT32_MAX && h->cached_pid && 2094 0 2094
1122 2094 ▶ h->cached_fork_gen == __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED) &&
Branch: 1 branch
BranchTrueFalseTotal
h->cached_fork_gen == __atomic_load_n(&buf_fork_gen, __ATOMIC_RELAXED) && 1068 1026 2094
1123 1068 ▶ __atomic_load_n(&h->reader_slots[h->my_slot_idx].rdepth, __ATOMIC_ACQUIRE) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
__atomic_load_n(&h->reader_slots[h->my_slot_idx].rdepth, __ATOMIC_ACQUIRE) == 0) { 1068 0 1068
1124 /* rdepth==0: a still-held read lock's slot must survive for recovery */
1125 /* Clear our occ bit BEFORE freeing the slot: we still own the pid so no
1126 * claimant can take the slot mid-clear, and rdepth==0 so no writer needs
1127 * to see us. (A crash skips this -> the bit is reclaimed lazily by a
1128 * writer scan / re-claim, same as the pid.) */
1129 1068 buf_occ_clear(h, h->my_slot_idx);
1130 1068 uint32_t expected = h->cached_pid;
1131 /* CAS pid -> 0; do NOT clear rdepth -- between the CAS and a follow-up
1132 * store, a new process could claim the slot, and our store would clobber
1133 * its state. buf_claim_reader_slot zeros rdepth on every claim, so
1134 * leaving a stale value is safe. */
1135 1068 __atomic_compare_exchange_n(&h->reader_slots[h->my_slot_idx].pid,
1136 &expected, 0, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
1137 }
1138 2334 ▶ if (h->efd >= 0 && h->efd_owned) close(h->efd);
Branch: 2 branches
BranchTrueFalseTotal
if (h->efd >= 0 && h->efd_owned) close(h->efd); 20 2314 2334
if (h->efd >= 0 && h->efd_owned) close(h->efd); 18 2 20
1139 2334 ▶ if (h->hdr) munmap(h->hdr, h->mmap_size);
Branch: 1 branch
BranchTrueFalseTotal
if (h->hdr) munmap(h->hdr, h->mmap_size); 2334 0 2334
1140 2334 ▶ if (h->fd >= 0) close(h->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->fd >= 0) close(h->fd); 13 2321 2334
1141 2334 ▶ if (h->path) free(h->path);
Branch: 1 branch
BranchTrueFalseTotal
if (h->path) free(h->path); 2258 76 2334
1142 2334 free(h);
1143 }
1144  
1145 #endif /* BUF_DEFS_H */
1146  
1147  
1148 /* ================================================================
1149 * Part 2: Per-variant functions (instantiated per include)
1150 * ================================================================ */
1151  
1152 #ifndef BUF_PREFIX
1153 #error "BUF_PREFIX must be defined before including buf_generic.h"
1154 #endif
1155  
1156 #define BUF_PASTE2(a, b) a##_##b
1157 #define BUF_PASTE(a, b) BUF_PASTE2(a, b)
1158 #define BUF_FN(name) BUF_PASTE(BUF_PREFIX, name)
1159  
1160 /* ---- Create ---- */
1161  
1162 #ifdef BUF_IS_FIXEDSTR
1163 4 static BufHandle *BUF_FN(create)(const char *path, uint64_t capacity,
1164 uint32_t str_len, mode_t file_mode, char *errbuf) {
1165 4 ▶ if (str_len == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (str_len == 0) { 0 4 4
1166 0 snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0");
1167 0 return NULL;
1168 }
1169 4 return buf_create_map(path, capacity, str_len, BUF_VARIANT_ID, file_mode, errbuf);
1170 }
1171 #else
1172 2264 static BufHandle *BUF_FN(create)(const char *path, uint64_t capacity, mode_t file_mode, char *errbuf) {
1173 2264 return buf_create_map(path, capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, file_mode, errbuf);
1174 }
1175 #endif
1176  
1177 /* ---- Create anonymous ---- */
1178  
1179 #ifdef BUF_IS_FIXEDSTR
1180 14 static BufHandle *BUF_FN(create_anon)(uint64_t capacity, uint32_t str_len, char *errbuf) {
1181 14 ▶ if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; } 0 14 14
1182 14 return buf_create_anon(capacity, str_len, BUF_VARIANT_ID, errbuf);
1183 }
1184 2 static BufHandle *BUF_FN(create_memfd)(const char *name, uint64_t capacity, uint32_t str_len, char *errbuf) {
1185 2 ▶ if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; } 0 2 2
1186 2 return buf_create_memfd(name, capacity, str_len, BUF_VARIANT_ID, errbuf);
1187 }
1188 1 static BufHandle *BUF_FN(open_fd)(int fd, uint32_t str_len, char *errbuf) {
1189 1 ▶ if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (str_len == 0) { snprintf(errbuf, BUF_ERR_BUFLEN, "str_len must be > 0"); return NULL; } 0 1 1
1190 1 return buf_open_fd(fd, str_len, BUF_VARIANT_ID, errbuf);
1191 }
1192 #else
1193 49 static BufHandle *BUF_FN(create_anon)(uint64_t capacity, char *errbuf) {
1194 49 return buf_create_anon(capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
1195 }
1196 0 static BufHandle *BUF_FN(create_memfd)(const char *name, uint64_t capacity, char *errbuf) {
1197 0 return buf_create_memfd(name, capacity, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
1198 }
1199 0 static BufHandle *BUF_FN(open_fd)(int fd, char *errbuf) {
1200 0 return buf_open_fd(fd, BUF_ELEM_SIZE, BUF_VARIANT_ID, errbuf);
1201 }
1202 #endif
1203  
1204 /* ---- Raw byte access (for packed binary interop) ---- */
1205  
1206 /* Byte-span validity WITHOUT allocating. The XS get_raw does newSV(nbytes) and
1207 writes a NUL at [nbytes] BEFORE this copy is called; a pathological nbytes
1208 (e.g. ~0) makes newSV's internal nbytes+1 integer-overflow to a tiny buffer,
1209 then the NUL write lands out of bounds. The XS calls this first to reject
1210 such args before allocating. */
1211 20 static int BUF_FN(raw_in_bounds)(BufHandle *h, uint64_t byte_off, uint64_t nbytes) {
1212 20 uint64_t data_size = h->capacity * (uint64_t)h->elem_size;
1213 20 ▶ return nbytes <= data_size && byte_off <= data_size - nbytes;
Branch: 22 branches
BranchTrueFalseTotal
return nbytes <= data_size && byte_off <= data_size - nbytes; 2 0 2
return nbytes <= data_size && byte_off <= data_size - nbytes; 2 0 2
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 2 0 2
return nbytes <= data_size && byte_off <= data_size - nbytes; 2 0 2
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 8 0 8
return nbytes <= data_size && byte_off <= data_size - nbytes; 6 2 8
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
return nbytes <= data_size && byte_off <= data_size - nbytes; 1 0 1
1214 }
1215  
1216 18 static int BUF_FN(get_raw)(BufHandle *h, uint64_t byte_off, uint64_t nbytes, void *out) {
1217 18 uint64_t data_size = h->capacity * (uint64_t)h->elem_size;
1218 18 ▶ if (nbytes > data_size || byte_off > data_size - nbytes) return 0;
Branch: 22 branches
BranchTrueFalseTotal
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 2 0 2
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 2 2
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 2 0 2
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 2 2
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 6 0 6
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 6 6
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
1219 18 char *data = (char *)h->data;
1220 18 ▶ if (buf_write_locked(h)) {
Branch: 11 branches
BranchTrueFalseTotal
if (buf_write_locked(h)) { 0 2 2
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 2 2
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 1 5 6
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
1221 0 memcpy(out, data + byte_off, (size_t)nbytes);
1222 } else {
1223 uint32_t seq_start;
1224 do {
1225 17 seq_start = buf_seqlock_read_begin(h->hdr);
1226 17 memcpy(out, data + byte_off, (size_t)nbytes);
1227 17 ▶ } while (buf_seqlock_read_retry(&h->hdr->seq, seq_start));
Branch: 11 branches
BranchTrueFalseTotal
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 2 2
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 2 2
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 5 5
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&h->hdr->seq, seq_start)); 0 1 1
1228 }
1229 18 return 1;
1230 }
1231  
1232 0 static int BUF_FN(set_raw)(BufHandle *h, uint64_t byte_off, uint64_t nbytes, const void *in) {
1233 0 uint64_t data_size = h->capacity * (uint64_t)h->elem_size;
1234 0 ▶ if (nbytes > data_size || byte_off > data_size - nbytes) return 0;
Branch: 22 branches
BranchTrueFalseTotal
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 1 0 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 1 1
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 7 0 7
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 4 3 7
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
if (nbytes > data_size || byte_off > data_size - nbytes) return 0; 0 0 0
1235 0 char *data = (char *)h->data;
1236 0 int nested = buf_write_locked(h);
1237 0 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); }
Branch: 11 branches
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 3 0 3
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&h->hdr->seq); } 0 0 0
1238 0 memcpy(data + byte_off, in, (size_t)nbytes);
1239 0 ▶ if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 11 branches
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 3 0 3
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&h->hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
1240 0 return 1;
1241 }
1242  
1243 /* ---- Clear (zero entire buffer) ---- */
1244  
1245 0 static void BUF_FN(clear)(BufHandle *h) {
1246 0 BufHeader *hdr = h->hdr;
1247 0 int nested = buf_write_locked(h);
1248 0 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 11 branches
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 4 1 5
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
1249 0 memset(h->data, 0, (size_t)((uint64_t)h->capacity * h->elem_size));
1250 0 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 11 branches
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 4 1 5
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
1251 0 }
1252  
1253 /* ---- Single-element atomic get (lock-free for numeric types) ---- */
1254  
1255 #ifdef BUF_IS_FIXEDSTR
1256  
1257 22 static int BUF_FN(get)(BufHandle *h, uint64_t idx, char *out, uint32_t *out_len) {
1258 22 BufHeader *hdr = h->hdr;
1259 22 uint32_t esz = h->elem_size;
1260 22 ▶ if (idx >= h->capacity) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 22 22
1261 22 char *data = (char *)h->data;
1262 22 ▶ if (buf_write_locked(h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf_write_locked(h)) { 1 21 22
1263 1 memcpy(out, data + idx * esz, esz);
1264 } else {
1265 uint32_t seq_start;
1266 do {
1267 21 seq_start = buf_seqlock_read_begin(hdr);
1268 21 memcpy(out, data + idx * esz, esz);
1269 21 ▶ } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
Branch: 1 branch
BranchTrueFalseTotal
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 21 21
1270 }
1271 22 uint32_t len = esz;
1272 259 ▶ while (len > 0 && out[len - 1] == '\0') len--;
Branch: 2 branches
BranchTrueFalseTotal
while (len > 0 && out[len - 1] == '\0') len--; 257 2 259
while (len > 0 && out[len - 1] == '\0') len--; 237 20 257
1273 22 *out_len = len;
1274 22 return 1;
1275 }
1276  
1277 526 static int BUF_FN(set)(BufHandle *h, uint64_t idx, const char *val, uint32_t len) {
1278 526 BufHeader *hdr = h->hdr;
1279 526 uint32_t esz = h->elem_size;
1280 526 ▶ if (idx >= h->capacity) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 526 526
1281 526 char *data = (char *)h->data;
1282 526 int nested = buf_write_locked(h);
1283 526 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 519 7 526
1284 526 memset(data + idx * esz, 0, esz);
1285 526 uint32_t copy_len = len < esz ? len : esz;
1286 526 memcpy(data + idx * esz, val, copy_len);
1287 526 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 519 7 526
1288 526 return 1;
1289 }
1290  
1291 #elif defined(BUF_IS_FLOAT)
1292  
1293 /* Float/double: GCC __atomic builtins don't support FP types.
1294 * Use same-sized integer atomic load/store + memcpy for lock-free access. */
1295  
1296 #if BUF_ELEM_SIZE == 4
1297 typedef uint32_t BUF_PASTE(BUF_PREFIX, _uint_t);
1298 #elif BUF_ELEM_SIZE == 8
1299 typedef uint64_t BUF_PASTE(BUF_PREFIX, _uint_t);
1300 #else
1301 #error "BUF_IS_FLOAT requires BUF_ELEM_SIZE of 4 or 8"
1302 #endif
1303  
1304 14 static int BUF_FN(get)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE *out) {
1305 14 ▶ if (idx >= h->capacity) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 9 9
if (idx >= h->capacity) return 0; 0 5 5
1306 typedef BUF_PASTE(BUF_PREFIX, _uint_t) uint_t;
1307 14 uint_t *idata = (uint_t *)h->data;
1308 14 uint_t tmp = __atomic_load_n(&idata[idx], __ATOMIC_RELAXED);
1309 14 memcpy(out, &tmp, sizeof(BUF_ELEM_TYPE));
1310 14 return 1;
1311 }
1312  
1313 1017 static int BUF_FN(set)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE val) {
1314 1017 ▶ if (idx >= h->capacity) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1013 1013
if (idx >= h->capacity) return 0; 0 4 4
1315 typedef BUF_PASTE(BUF_PREFIX, _uint_t) uint_t;
1316 1017 uint_t *idata = (uint_t *)h->data;
1317 uint_t tmp;
1318 1017 memcpy(&tmp, &val, sizeof(BUF_ELEM_TYPE));
1319 1017 __atomic_store_n(&idata[idx], tmp, __ATOMIC_RELAXED);
1320 1017 return 1;
1321 }
1322  
1323 #else /* integer types */
1324  
1325 1298 static int BUF_FN(get)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE *out) {
1326 1298 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 3 1272 1275
if (idx >= h->capacity) return 0; 0 10 10
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 3 3
1327 1295 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1328 1295 *out = __atomic_load_n(&data[idx], __ATOMIC_RELAXED);
1329 1295 return 1;
1330 }
1331  
1332 99 static int BUF_FN(set)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE val) {
1333 99 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 3 76 79
if (idx >= h->capacity) return 0; 0 9 9
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 3 3
if (idx >= h->capacity) return 0; 0 4 4
1334 96 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1335 96 __atomic_store_n(&data[idx], val, __ATOMIC_RELAXED);
1336 96 return 1;
1337 }
1338  
1339 #endif /* BUF_IS_FIXEDSTR */
1340  
1341 /* ---- Bulk operations (seqlock-guarded) ---- */
1342  
1343 #ifdef BUF_IS_FIXEDSTR
1344  
1345 2 static int BUF_FN(get_slice)(BufHandle *h, uint64_t from, uint64_t count,
1346 void *out) {
1347 2 BufHeader *hdr = h->hdr;
1348 2 uint32_t esz = h->elem_size;
1349 2 ▶ if (count > h->capacity || from > h->capacity - count) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (count > h->capacity || from > h->capacity - count) return 0; 2 0 2
if (count > h->capacity || from > h->capacity - count) return 0; 0 2 2
1350 2 char *data = (char *)h->data;
1351 2 ▶ if (buf_write_locked(h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (buf_write_locked(h)) { 1 1 2
1352 1 memcpy(out, data + from * esz, count * esz);
1353 } else {
1354 uint32_t seq_start;
1355 do {
1356 1 seq_start = buf_seqlock_read_begin(hdr);
1357 1 memcpy(out, data + from * esz, count * esz);
1358 1 ▶ } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
Branch: 1 branch
BranchTrueFalseTotal
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 1 1
1359 }
1360 2 return 1;
1361 }
1362  
1363 1 static int BUF_FN(set_slice)(BufHandle *h, uint64_t from, uint64_t count,
1364 const void *in) {
1365 1 BufHeader *hdr = h->hdr;
1366 1 uint32_t esz = h->elem_size;
1367 1 ▶ if (count > h->capacity || from > h->capacity - count) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
1368 1 char *data = (char *)h->data;
1369 1 int nested = buf_write_locked(h);
1370 1 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
1371 1 memcpy(data + from * esz, in, count * esz);
1372 1 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
1373 1 return 1;
1374 }
1375  
1376 #else /* numeric */
1377  
1378 0 static int BUF_FN(get_slice)(BufHandle *h, uint64_t from, uint64_t count,
1379 BUF_ELEM_TYPE *out) {
1380 0 BufHeader *hdr = h->hdr;
1381 0 ▶ if (count > h->capacity || from > h->capacity - count) return 0;
Branch: 20 branches
BranchTrueFalseTotal
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 5 0 5
if (count > h->capacity || from > h->capacity - count) return 0; 0 5 5
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
1382 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1383 0 ▶ if (buf_write_locked(h)) {
Branch: 10 branches
BranchTrueFalseTotal
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 1 1
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 1 4 5
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 0 0 0
if (buf_write_locked(h)) { 0 0 0
1384 0 memcpy(out, &data[from], count * sizeof(BUF_ELEM_TYPE));
1385 } else {
1386 uint32_t seq_start;
1387 do {
1388 0 seq_start = buf_seqlock_read_begin(hdr);
1389 0 memcpy(out, &data[from], count * sizeof(BUF_ELEM_TYPE));
1390 0 ▶ } while (buf_seqlock_read_retry(&hdr->seq, seq_start));
Branch: 10 branches
BranchTrueFalseTotal
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 1 1
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 4 4
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
} while (buf_seqlock_read_retry(&hdr->seq, seq_start)); 0 0 0
1391 }
1392 0 return 1;
1393 }
1394  
1395 0 static int BUF_FN(set_slice)(BufHandle *h, uint64_t from, uint64_t count,
1396 const BUF_ELEM_TYPE *in) {
1397 0 BufHeader *hdr = h->hdr;
1398 0 ▶ if (count > h->capacity || from > h->capacity - count) return 0;
Branch: 20 branches
BranchTrueFalseTotal
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 4 0 4
if (count > h->capacity || from > h->capacity - count) return 0; 1 3 4
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
1399 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1400 0 int nested = buf_write_locked(h);
1401 0 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 10 branches
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 2 1 3
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
1402 0 memcpy(&data[from], in, count * sizeof(BUF_ELEM_TYPE));
1403 0 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 10 branches
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 2 1 3
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
1404 0 return 1;
1405 }
1406  
1407 #endif /* BUF_IS_FIXEDSTR */
1408  
1409 /* ---- Fill ---- */
1410  
1411 #ifdef BUF_IS_FIXEDSTR
1412  
1413 7 static void BUF_FN(fill)(BufHandle *h, const char *val, uint32_t len) {
1414 7 BufHeader *hdr = h->hdr;
1415 7 uint32_t esz = h->elem_size;
1416 7 char *data = (char *)h->data;
1417 7 int nested = buf_write_locked(h);
1418 7 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 7 0 7
1419 7 uint32_t copy_len = len < esz ? len : esz;
1420 7 memset(data, 0, (size_t)h->capacity * esz);
1421 42 ▶ for (uint64_t i = 0; i < h->capacity; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t i = 0; i < h->capacity; i++) 35 7 42
1422 35 memcpy(data + i * esz, val, copy_len);
1423 7 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 1 branch
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 7 0 7
1424 7 }
1425  
1426 #else
1427  
1428 0 static void BUF_FN(fill)(BufHandle *h, BUF_ELEM_TYPE val) {
1429 0 BufHeader *hdr = h->hdr;
1430 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1431 0 int nested = buf_write_locked(h);
1432 0 ▶ if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); }
Branch: 10 branches
BranchTrueFalseTotal
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 2 0 2
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 1 0 1
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 14 1 15
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
if (!nested) { buf_rwlock_wrlock(h); buf_seqlock_write_begin(&hdr->seq); } 0 0 0
1433 0 ▶ for (uint64_t i = 0; i < h->capacity; i++)
Branch: 10 branches
BranchTrueFalseTotal
for (uint64_t i = 0; i < h->capacity; i++) 52 2 54
for (uint64_t i = 0; i < h->capacity; i++) 10 1 11
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 378 15 393
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
for (uint64_t i = 0; i < h->capacity; i++) 0 0 0
1434 0 data[i] = val;
1435 0 ▶ if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); }
Branch: 10 branches
BranchTrueFalseTotal
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 2 0 2
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 1 0 1
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 14 1 15
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
if (!nested) { buf_seqlock_write_end(&hdr->seq); buf_rwlock_wrunlock(h); } 0 0 0
1436 0 }
1437  
1438 #endif
1439  
1440 /* ---- Atomic operations (integer types only) ---- */
1441  
1442 #ifdef BUF_HAS_COUNTERS
1443  
1444 4519 static BUF_ELEM_TYPE BUF_FN(incr)(BufHandle *h, uint64_t idx) {
1445 4519 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 4510 4510
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 2 2
1446 4519 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1447 4519 return __atomic_add_fetch(&data[idx], 1, __ATOMIC_RELAXED);
1448 }
1449  
1450 13 static BUF_ELEM_TYPE BUF_FN(decr)(BufHandle *h, uint64_t idx) {
1451 13 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 4 4
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 2 2
1452 13 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1453 13 return __atomic_sub_fetch(&data[idx], 1, __ATOMIC_RELAXED);
1454 }
1455  
1456 14 static BUF_ELEM_TYPE BUF_FN(add)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE delta) {
1457 14 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 7 7
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
1458 14 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1459 14 return __atomic_add_fetch(&data[idx], delta, __ATOMIC_RELAXED);
1460 }
1461  
1462 1193 static int BUF_FN(cas)(BufHandle *h, uint64_t idx,
1463 BUF_ELEM_TYPE expected, BUF_ELEM_TYPE desired) {
1464 1193 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1186 1186
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
if (idx >= h->capacity) return 0; 0 1 1
1465 1193 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1466 1193 return __atomic_compare_exchange_n(&data[idx], &expected, desired,
1467 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
1468 }
1469  
1470 0 static BUF_ELEM_TYPE BUF_FN(cmpxchg)(BufHandle *h, uint64_t idx,
1471 BUF_ELEM_TYPE expected, BUF_ELEM_TYPE desired) {
1472 0 ▶ if (idx >= h->capacity) return expected;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 6 6
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 0 0
if (idx >= h->capacity) return expected; 0 0 0
1473 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1474 0 __atomic_compare_exchange_n(&data[idx], &expected, desired,
1475 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED);
1476 0 return expected; /* on failure, expected is updated to the current value */
1477 }
1478  
1479 0 static BUF_ELEM_TYPE BUF_FN(atomic_and)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
1480 0 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 4 4
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
1481 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1482 0 return __atomic_and_fetch(&data[idx], mask, __ATOMIC_RELAXED);
1483 }
1484  
1485 0 static BUF_ELEM_TYPE BUF_FN(atomic_or)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
1486 0 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 4 4
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
1487 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1488 0 return __atomic_or_fetch(&data[idx], mask, __ATOMIC_RELAXED);
1489 }
1490  
1491 0 static BUF_ELEM_TYPE BUF_FN(atomic_xor)(BufHandle *h, uint64_t idx, BUF_ELEM_TYPE mask) {
1492 0 ▶ if (idx >= h->capacity) return 0;
Branch: 8 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 2 2
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
if (idx >= h->capacity) return 0; 0 0 0
1493 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1494 0 return __atomic_xor_fetch(&data[idx], mask, __ATOMIC_RELAXED);
1495 }
1496  
1497 0 static int BUF_FN(add_slice)(BufHandle *h, uint64_t from, uint64_t count,
1498 const BUF_ELEM_TYPE *deltas) {
1499 0 ▶ if (count > h->capacity || from > h->capacity - count) return 0;
Branch: 16 branches
BranchTrueFalseTotal
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 1002 0 1002
if (count > h->capacity || from > h->capacity - count) return 0; 1 1001 1002
if (count > h->capacity || from > h->capacity - count) return 0; 1 0 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 1 1
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
if (count > h->capacity || from > h->capacity - count) return 0; 0 0 0
1500 0 BUF_ELEM_TYPE *data = (BUF_ELEM_TYPE *)h->data;
1501 0 ▶ for (uint64_t i = 0; i < count; i++)
Branch: 8 branches
BranchTrueFalseTotal
for (uint64_t i = 0; i < count; i++) 0 0 0
for (uint64_t i = 0; i < count; i++) 3003 1001 4004
for (uint64_t i = 0; i < count; i++) 2 1 3
for (uint64_t i = 0; i < count; i++) 0 0 0
for (uint64_t i = 0; i < count; i++) 0 0 0
for (uint64_t i = 0; i < count; i++) 0 0 0
for (uint64_t i = 0; i < count; i++) 0 0 0
for (uint64_t i = 0; i < count; i++) 0 0 0
1502 0 __atomic_add_fetch(&data[from + i], deltas[i], __ATOMIC_RELAXED);
1503 0 return 1;
1504 }
1505  
1506 #endif /* BUF_HAS_COUNTERS */
1507  
1508 /* ---- Diagnostics ---- */
1509  
1510 0 static inline uint64_t BUF_FN(capacity)(BufHandle *h) {
1511 0 return h->hdr->capacity;
1512 }
1513  
1514 0 static inline uint64_t BUF_FN(mmap_size)(BufHandle *h) {
1515 0 return (uint64_t)h->mmap_size;
1516 }
1517  
1518 0 static inline uint32_t BUF_FN(elem_size)(BufHandle *h) {
1519 0 return h->hdr->elem_size;
1520 }
1521  
1522 /* ---- Raw pointer access (for passing to external C/XS code) ---- */
1523  
1524 0 static inline void *BUF_FN(ptr)(BufHandle *h) {
1525 0 return h->data;
1526 }
1527  
1528 0 static inline void *BUF_FN(ptr_at)(BufHandle *h, uint64_t idx) {
1529 0 ▶ if (idx >= h->capacity) return NULL;
Branch: 11 branches
BranchTrueFalseTotal
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 1 3 4
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
if (idx >= h->capacity) return NULL; 0 0 0
1530 0 return (char *)h->data + idx * h->elem_size;
1531 }
1532  
1533 /* ---- Explicit locking for batch operations ---- */
1534  
1535 0 static inline void BUF_FN(lock_wr)(BufHandle *h) {
1536 0 buf_rwlock_wrlock(h);
1537 0 buf_seqlock_write_begin(&h->hdr->seq);
1538 0 h->wr_locked = 1;
1539 0 }
1540  
1541 0 static inline void BUF_FN(unlock_wr)(BufHandle *h) {
1542 0 buf_reset_after_fork(h);
1543 0 ▶ if (!h->wr_locked) return;
Branch: 11 branches
BranchTrueFalseTotal
if (!h->wr_locked) return; 0 7 7
if (!h->wr_locked) return; 0 1 1
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 17 17
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
if (!h->wr_locked) return; 0 0 0
1544 0 h->wr_locked = 0;
1545 0 buf_seqlock_write_end(&h->hdr->seq);
1546 0 buf_rwlock_wrunlock(h);
1547 }
1548  
1549 0 static inline void BUF_FN(lock_rd)(BufHandle *h) {
1550 0 buf_rwlock_rdlock(h);
1551 0 }
1552  
1553 0 static inline void BUF_FN(unlock_rd)(BufHandle *h) {
1554 0 buf_reset_after_fork(h);
1555 0 buf_rwlock_rdunlock(h);
1556 0 }
1557  
1558 /* ---- Cleanup ---- */
1559  
1560 #undef BUF_PASTE2
1561 #undef BUF_PASTE
1562 #undef BUF_FN
1563 #undef BUF_PREFIX
1564 #undef BUF_ELEM_TYPE
1565 #undef BUF_ELEM_SIZE
1566 #undef BUF_VARIANT_ID
1567 #ifdef BUF_HAS_COUNTERS
1568 #undef BUF_HAS_COUNTERS
1569 #endif
1570 #ifdef BUF_IS_FLOAT
1571 #undef BUF_IS_FLOAT
1572 #endif
1573 #ifdef BUF_IS_FIXEDSTR
1574 #undef BUF_IS_FIXEDSTR
1575 #endif
« xs/f64.xs ↑ Summary xs/str.xs »