pubsub.h

filter: Statementstmt 76.4% 422 / 552 Branchbran 51.2% 299 / 584 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 63.4% 721 / 1136 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« Shared.xs ↑ Summary blib/lib/Data/PubSub/Shared/Int.pm »
1 /*
2 * pubsub.h -- Shared-memory broadcast pub/sub for Linux
3 *
4 * Two variants:
5 * Int -- MPMC publish (lock-free where a slot-wide CAS is available, else
6 * serialized on the header mutex), lock-free subscribe (int64 values)
7 * Str -- mutex-protected publish, lock-free subscribe (variable-length
8 * byte strings up to msg_size, one fixed arena region per slot)
9 *
10 * Ring buffer broadcast: publishers write, each subscriber independently
11 * reads with its own cursor. Messages are never consumed -- the ring
12 * overwrites old data when it wraps. Subscribers auto-recover from
13 * overflow by resetting to the oldest available position.
14 *
15 * File-backed mmap(MAP_SHARED) for cross-process sharing,
16 * futex for blocking poll, PID-based stale lock recovery (Str mode).
17 */
18  
19 #ifndef PUBSUB_H
20 #define PUBSUB_H
21  
22 #include <stddef.h>
23 #include <stdint.h>
24 #include <stdbool.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <time.h>
31 #include <limits.h>
32 #include <signal.h>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35 #include <sys/file.h>
36 #include <sys/syscall.h>
37 #include <linux/futex.h>
38 #include <sys/eventfd.h>
39  
40 /* ================================================================
41 * Constants
42 * ================================================================ */
43  
44 #define PUBSUB_MAGIC 0x50534231U /* "PSB1" */
45 #define PUBSUB_VERSION 1
46 #define PUBSUB_MODE_INT 0
47 #define PUBSUB_MODE_STR 1
48 #define PUBSUB_MODE_INT32 2
49 #define PUBSUB_MODE_INT16 3
50 #define PUBSUB_ERR_BUFLEN (PATH_MAX + 256)
51 #define PUBSUB_SPIN_LIMIT 32
52 #define PUBSUB_LOCK_TIMEOUT_SEC 2
53 #define PUBSUB_DEFAULT_MSG_SIZE 256
54 #define PUBSUB_STR_UTF8_FLAG 0x80000000U
55 #define PUBSUB_STR_LEN_MASK 0x7FFFFFFFU
56 #define PUBSUB_POLL_RETRIES 8
57  
58 #ifndef PUBSUB_WAIT_INTERRUPTED
59 #define PUBSUB_WAIT_INTERRUPTED() 0
60 #endif
61  
62 /* ================================================================
63 * Header (256 bytes = 4 cache lines)
64 * ================================================================ */
65  
66 typedef struct {
67 /* ---- Cache line 0 (0-63): immutable after create ---- */
68 uint32_t magic; /* 0 */
69 uint32_t version; /* 4 */
70 uint32_t mode; /* 8 */
71 uint32_t capacity; /* 12 */
72 uint64_t total_size; /* 16 */
73 uint64_t slots_off; /* 24 */
74 uint64_t data_off; /* 32: str: offset to arena; int: 0 */
75 uint32_t msg_size; /* 40: str: max bytes per message; int: 0 */
76 uint32_t _reserved0; /* 44 */
77 uint64_t arena_cap; /* 48: str: arena byte capacity; int: 0 */
78 uint8_t _pad0[8]; /* 56-63 */
79  
80 /* ---- Cache line 1 (64-127): writer hot ---- */
81 uint64_t write_pos; /* 64 */
82 uint32_t mutex; /* 72: str: futex mutex */
83 uint32_t mutex_waiters; /* 76 */
84 uint32_t arena_wpos; /* 80: str: next write position in arena */
85 uint8_t _pad1[44]; /* 84-127 */
86  
87 /* ---- Cache line 2 (128-191): subscriber notification ---- */
88 uint32_t sub_futex; /* 128 */
89 uint32_t sub_waiters; /* 132 */
90 uint8_t _pad2[56]; /* 136-191 */
91  
92 /* ---- Cache line 3 (192-255): stats ---- */
93 uint64_t stat_publish_ok; /* 192 */
94 uint64_t stat_recoveries; /* 200 */
95 uint8_t _pad3[48]; /* 208-255 */
96 } PubSubHeader;
97  
98 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
99 _Static_assert(sizeof(PubSubHeader) == 256, "PubSubHeader must be 256 bytes");
100 #endif
101  
102 /* ================================================================
103 * Slot types
104 * ================================================================ */
105  
106 typedef struct {
107 uint64_t sequence;
108 int64_t value;
109 } PubSubIntSlot; /* 16 bytes */
110  
111 /* Compact int slots: 32-bit sequence + value = 8 bytes (2x cache density) */
112 typedef struct {
113 uint32_t sequence;
114 int32_t value;
115 } PubSubInt32Slot; /* 8 bytes */
116  
117 typedef struct {
118 uint32_t sequence;
119 int16_t value;
120 int16_t _pad;
121 } PubSubInt16Slot; /* 8 bytes */
122  
123 typedef struct {
124 uint64_t sequence;
125 uint32_t packed_len; /* bit 31 = UTF-8, bits 0-30 = byte length */
126 uint32_t arena_off; /* offset into data arena */
127 } PubSubStrSlot; /* 16 bytes */
128  
129 /* ================================================================
130 * Process-local handles
131 * ================================================================ */
132  
133 typedef struct {
134 PubSubHeader *hdr;
135 void *slots;
136 char *data; /* NULL for int mode */
137 size_t mmap_size;
138 uint32_t capacity;
139 uint32_t cap_mask;
140 uint32_t msg_size;
141 uint32_t mode; /* validated variant; NOT re-read from peer-writable hdr->mode */
142 uint64_t arena_cap;
143 char *path;
144 int notify_fd;
145 int backing_fd;
146 } PubSubHandle;
147  
148 typedef struct {
149 PubSubHeader *hdr;
150 void *slots;
151 char *data;
152 uint64_t cursor;
153 uint32_t capacity;
154 uint32_t cap_mask;
155 uint32_t msg_size;
156 uint64_t arena_cap;
157 char *copy_buf;
158 uint32_t copy_buf_cap;
159 uint64_t overflow_count;
160 int notify_fd;
161 void *userdata;
162 } PubSubSub;
163  
164 /* ================================================================
165 * Utility
166 * ================================================================ */
167  
168 168 static inline uint32_t pubsub_next_pow2(uint32_t v) {
169 168 ▶ if (v < 2) return 2;
Branch: 1 branch
BranchTrueFalseTotal
if (v < 2) return 2; 0 168 168
170 168 ▶ if (v > 0x80000000U) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (v > 0x80000000U) return 0; 0 168 168
171 168 v--;
172 168 v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16;
173 168 return v + 1;
174 }
175  
176 0 static inline void pubsub_spin_pause(void) {
177 #if defined(__x86_64__) || defined(__i386__)
178 0 __asm__ volatile("pause" ::: "memory");
179 #elif defined(__aarch64__)
180 __asm__ volatile("yield" ::: "memory");
181 #else
182 __asm__ volatile("" ::: "memory");
183 #endif
184 0 }
185  
186 966 static inline int pubsub_ensure_copy_buf(PubSubSub *sub, uint32_t needed) {
187 966 ▶ if (needed <= sub->copy_buf_cap) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (needed <= sub->copy_buf_cap) return 1; 692 274 966
188 274 ▶ uint32_t ns = sub->copy_buf_cap ? sub->copy_buf_cap : 64;
Branch: 1 branch
BranchTrueFalseTotal
uint32_t ns = sub->copy_buf_cap ? sub->copy_buf_cap : 64; 33 241 274
189 343 ▶ while (ns < needed) {
Branch: 1 branch
BranchTrueFalseTotal
while (ns < needed) { 69 274 343
190 69 uint32_t n2 = ns * 2;
191 69 ▶ if (n2 <= ns) { ns = needed; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (n2 <= ns) { ns = needed; break; } 0 69 69
192 69 ns = n2;
193 }
194 274 char *nb = (char *)realloc(sub->copy_buf, ns);
195 274 ▶ if (!nb) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!nb) return 0; 0 274 274
196 274 sub->copy_buf = nb;
197 274 sub->copy_buf_cap = ns;
198 274 return 1;
199 }
200  
201 /* ================================================================
202 * Futex helpers
203 * ================================================================ */
204  
205 #define PUBSUB_MUTEX_WRITER_BIT 0x80000000U
206 #define PUBSUB_MUTEX_PID_MASK 0x7FFFFFFFU
207 #define PUBSUB_MUTEX_VAL(pid) (PUBSUB_MUTEX_WRITER_BIT | ((uint32_t)(pid) & PUBSUB_MUTEX_PID_MASK))
208  
209 /* A zombie (dead but not yet reaped) still answers kill(pid,0) as alive, so a
210 * process that crashed while holding the lock and lingers unreaped would never
211 * be recovered. Treat /proc/<pid>/stat state 'Z' as dead. Linux-only (as is
212 * this module); if /proc is unreadable we fall back to "alive" (safe: we never
213 * force-recover a possibly-live holder). */
214 0 static inline int pubsub_pid_is_zombie(uint32_t pid) {
215 char path[32], buf[256];
216 0 snprintf(path, sizeof(path), "/proc/%u/stat", (unsigned)pid);
217 0 int fd = open(path, O_RDONLY | O_CLOEXEC);
218 0 ▶ if (fd < 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return 0; 0 0 0
219 0 ssize_t n = read(fd, buf, sizeof(buf) - 1);
220 0 close(fd);
221 0 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 0 0
222 0 buf[n] = '\0';
223 /* "pid (comm) state ..."; comm may contain ')', so scan to the last one. */
224 0 char *rp = strrchr(buf, ')');
225 0 ▶ 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 */ 0 0 0
if (!rp || rp + 2 >= buf + n) return 0; /* need ") X" within the bytes read */ 0 0 0
226 0 ▶ return rp[1] == ' ' && rp[2] == 'Z';
Branch: 2 branches
BranchTrueFalseTotal
return rp[1] == ' ' && rp[2] == 'Z'; 0 0 0
return rp[1] == ' ' && rp[2] == 'Z'; 0 0 0
227 }
228 0 static inline int pubsub_pid_alive(uint32_t pid) {
229 0 ▶ 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 0 0
230 0 ▶ 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 */ 0 0 0
if (kill((pid_t)pid, 0) == -1 && errno == ESRCH) return 0; /* definitely dead */ 0 0 0
231 0 return !pubsub_pid_is_zombie(pid); /* kill() also succeeds for a zombie -> treat as dead */
232 }
233  
234 static inline int pubsub_remaining_time(const struct timespec *deadline,
235 struct timespec *remaining);
236 static inline void pubsub_make_deadline(double timeout, struct timespec *deadline);
237  
238 0 static inline void pubsub_recover_stale_mutex(PubSubHeader *hdr, uint32_t observed) {
239 0 ▶ if (!__atomic_compare_exchange_n(&hdr->mutex, &observed, 0,
Branch: 1 branch
BranchTrueFalseTotal
if (!__atomic_compare_exchange_n(&hdr->mutex, &observed, 0, 0 0 0
240 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED))
241 0 return;
242 0 __atomic_add_fetch(&hdr->stat_recoveries, 1, __ATOMIC_RELAXED);
243 0 __atomic_thread_fence(__ATOMIC_SEQ_CST);
244 0 ▶ if (__atomic_load_n(&hdr->mutex_waiters, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->mutex_waiters, __ATOMIC_RELAXED) > 0) 0 0 0
245 0 syscall(SYS_futex, &hdr->mutex, FUTEX_WAKE, 1, NULL, NULL, 0);
246 }
247  
248 403 static inline int pubsub_mutex_lock_until(PubSubHeader *hdr,
249 struct timespec *deadline, int interruptible) {
250 403 uint32_t mypid = PUBSUB_MUTEX_VAL((uint32_t)getpid());
251 struct timespec remaining;
252 403 for (int spin = 0; ; spin++) {
253 403 uint32_t expected = 0;
254 403 ▶ if (__atomic_compare_exchange_n(&hdr->mutex, &expected, mypid,
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_compare_exchange_n(&hdr->mutex, &expected, mypid, 403 0 403
255 1, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
256 403 return 0;
257 0 ▶ if (__builtin_expect(spin < PUBSUB_SPIN_LIMIT, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(spin < PUBSUB_SPIN_LIMIT, 1)) { 0 0 0
258 0 pubsub_spin_pause();
259 0 continue;
260 }
261 0 __atomic_add_fetch(&hdr->mutex_waiters, 1, __ATOMIC_SEQ_CST);
262 0 uint32_t cur = __atomic_load_n(&hdr->mutex, __ATOMIC_RELAXED);
263 0 int timed_out = 0;
264 0 ▶ if (cur != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cur != 0) { 0 0 0
265 0 ▶ if (!pubsub_remaining_time(deadline, &remaining)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_remaining_time(deadline, &remaining)) { 0 0 0
266 0 timed_out = 1;
267 } else {
268 0 long rc = syscall(SYS_futex, &hdr->mutex, FUTEX_WAIT, cur,
269 &remaining, NULL, 0);
270 0 ▶ timed_out = rc == -1 && errno == ETIMEDOUT;
Branch: 2 branches
BranchTrueFalseTotal
timed_out = rc == -1 && errno == ETIMEDOUT; 0 0 0
timed_out = rc == -1 && errno == ETIMEDOUT; 0 0 0
271 }
272 }
273 0 __atomic_sub_fetch(&hdr->mutex_waiters, 1, __ATOMIC_RELAXED);
274 0 ▶ if (timed_out) {
Branch: 1 branch
BranchTrueFalseTotal
if (timed_out) { 0 0 0
275 0 uint32_t val = __atomic_load_n(&hdr->mutex, __ATOMIC_RELAXED);
276 0 ▶ if (val >= PUBSUB_MUTEX_WRITER_BIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (val >= PUBSUB_MUTEX_WRITER_BIT) { 0 0 0
277 0 uint32_t pid = val & PUBSUB_MUTEX_PID_MASK;
278 0 ▶ if (!pubsub_pid_alive(pid))
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_pid_alive(pid)) 0 0 0
279 0 pubsub_recover_stale_mutex(hdr, val);
280 }
281 0 pubsub_make_deadline(PUBSUB_LOCK_TIMEOUT_SEC, deadline);
282 }
283 0 ▶ if (interruptible && PUBSUB_WAIT_INTERRUPTED()) {
Branch: 2 branches
BranchTrueFalseTotal
if (interruptible && PUBSUB_WAIT_INTERRUPTED()) { 0 0 0
if (interruptible && PUBSUB_WAIT_INTERRUPTED()) { 0 0 0
284 0 errno = EINTR;
285 0 return -1;
286 }
287 0 spin = 0;
288 }
289 }
290  
291 0 static inline void pubsub_mutex_lock(PubSubHeader *hdr) {
292 struct timespec deadline;
293 0 pubsub_make_deadline(PUBSUB_LOCK_TIMEOUT_SEC, &deadline);
294 0 (void)pubsub_mutex_lock_until(hdr, &deadline, 0);
295 0 }
296  
297 403 static inline void pubsub_mutex_unlock(PubSubHeader *hdr) {
298 403 __atomic_store_n(&hdr->mutex, 0, __ATOMIC_RELEASE);
299 403 __atomic_thread_fence(__ATOMIC_SEQ_CST);
300 403 ▶ if (__atomic_load_n(&hdr->mutex_waiters, __ATOMIC_RELAXED) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->mutex_waiters, __ATOMIC_RELAXED) > 0) 0 403 403
301 0 syscall(SYS_futex, &hdr->mutex, FUTEX_WAKE, 1, NULL, NULL, 0);
302 403 }
303  
304 991 static inline void pubsub_wake_subscribers_fenced(PubSubHeader *hdr) {
305 991 ▶ if (__atomic_load_n(&hdr->sub_waiters, __ATOMIC_RELAXED) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (__atomic_load_n(&hdr->sub_waiters, __ATOMIC_RELAXED) > 0) { 55 936 991
306 55 __atomic_add_fetch(&hdr->sub_futex, 1, __ATOMIC_RELEASE);
307 55 syscall(SYS_futex, &hdr->sub_futex, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
308 }
309 991 }
310  
311 590 static inline void pubsub_wake_subscribers(PubSubHeader *hdr) {
312 /* Pair with the reader's waiters increment before testing for sleepers. */
313 590 __atomic_thread_fence(__ATOMIC_SEQ_CST);
314 590 pubsub_wake_subscribers_fenced(hdr);
315 590 }
316  
317 12 static inline int pubsub_remaining_time(const struct timespec *deadline,
318 struct timespec *remaining) {
319 struct timespec now;
320 12 clock_gettime(CLOCK_MONOTONIC, &now);
321 12 remaining->tv_sec = deadline->tv_sec - now.tv_sec;
322 12 remaining->tv_nsec = deadline->tv_nsec - now.tv_nsec;
323 12 ▶ if (remaining->tv_nsec < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (remaining->tv_nsec < 0) { 7 5 12
324 7 remaining->tv_sec--;
325 7 remaining->tv_nsec += 1000000000L;
326 }
327 12 return remaining->tv_sec >= 0;
328 }
329  
330 486 static inline void pubsub_make_deadline(double timeout, struct timespec *deadline) {
331 486 clock_gettime(CLOCK_MONOTONIC, deadline);
332 486 ▶ if (!(timeout < 1e9)) timeout = 1e9; /* clamp Inf/NaN/huge: avoid UB (time_t) cast -> instant spurious timeout */
Branch: 1 branch
BranchTrueFalseTotal
if (!(timeout < 1e9)) timeout = 1e9; /* clamp Inf/NaN/huge: avoid UB (time_t) cast -> instant spurious timeout */ 0 486 486
333 486 deadline->tv_sec += (time_t)timeout;
334 486 deadline->tv_nsec += (long)((timeout - (double)(time_t)timeout) * 1e9);
335 486 ▶ if (deadline->tv_nsec >= 1000000000L) {
Branch: 1 branch
BranchTrueFalseTotal
if (deadline->tv_nsec >= 1000000000L) { 0 486 486
336 0 deadline->tv_sec++;
337 0 deadline->tv_nsec -= 1000000000L;
338 }
339 486 }
340  
341 /* ================================================================
342 * Header validation
343 * ================================================================ */
344  
345 29 static inline int pubsub_validate_header(PubSubHeader *hdr, uint32_t mode,
346 uint64_t file_size) {
347 29 ▶ if (hdr->magic != PUBSUB_MAGIC ||
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->magic != PUBSUB_MAGIC || 25 4 29
348 25 ▶ hdr->version != PUBSUB_VERSION ||
Branch: 1 branch
BranchTrueFalseTotal
hdr->version != PUBSUB_VERSION || 25 0 25
349 25 ▶ hdr->mode != mode ||
Branch: 1 branch
BranchTrueFalseTotal
hdr->mode != mode || 21 4 25
350 21 ▶ hdr->capacity < 2 ||
Branch: 1 branch
BranchTrueFalseTotal
hdr->capacity < 2 || 21 0 21
351 21 ▶ (hdr->capacity & (hdr->capacity - 1)) != 0 ||
Branch: 1 branch
BranchTrueFalseTotal
(hdr->capacity & (hdr->capacity - 1)) != 0 || 21 0 21
352 21 ▶ hdr->total_size != file_size ||
Branch: 1 branch
BranchTrueFalseTotal
hdr->total_size != file_size || 21 0 21
353 21 ▶ hdr->slots_off != sizeof(PubSubHeader))
Branch: 1 branch
BranchTrueFalseTotal
hdr->slots_off != sizeof(PubSubHeader)) 0 21 21
354 8 return 0;
355 /* Slot array must fit within file. */
356 21 uint64_t slot_size = (mode == PUBSUB_MODE_INT) ? sizeof(PubSubIntSlot)
357 30 ▶ : (mode == PUBSUB_MODE_INT32) ? sizeof(PubSubInt32Slot)
Branch: 1 branch
BranchTrueFalseTotal
: (mode == PUBSUB_MODE_INT32) ? sizeof(PubSubInt32Slot) 9 12 21
358 16 ▶ : (mode == PUBSUB_MODE_INT16) ? sizeof(PubSubInt16Slot)
Branch: 1 branch
BranchTrueFalseTotal
: (mode == PUBSUB_MODE_INT16) ? sizeof(PubSubInt16Slot) 7 2 9
359 7 ▶ : sizeof(PubSubStrSlot);
Branch: 1 branch
BranchTrueFalseTotal
: sizeof(PubSubStrSlot); 2 5 7
360 21 ▶ if (hdr->capacity > (hdr->total_size - hdr->slots_off) / slot_size)
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->capacity > (hdr->total_size - hdr->slots_off) / slot_size) 0 21 21
361 0 return 0;
362 21 ▶ if (mode == PUBSUB_MODE_STR) {
Branch: 1 branch
BranchTrueFalseTotal
if (mode == PUBSUB_MODE_STR) { 5 16 21
363 5 ▶ if (hdr->data_off == 0 || hdr->msg_size == 0 ||
Branch: 2 branches
BranchTrueFalseTotal
if (hdr->data_off == 0 || hdr->msg_size == 0 || 5 0 5
if (hdr->data_off == 0 || hdr->msg_size == 0 || 5 0 5
364 5 ▶ hdr->msg_size > PUBSUB_STR_LEN_MASK || hdr->arena_cap > UINT32_MAX ||
Branch: 2 branches
BranchTrueFalseTotal
hdr->msg_size > PUBSUB_STR_LEN_MASK || hdr->arena_cap > UINT32_MAX || 5 0 5
hdr->msg_size > PUBSUB_STR_LEN_MASK || hdr->arena_cap > UINT32_MAX || 5 0 5
365 5 ▶ hdr->arena_cap != (uint64_t)hdr->capacity * ((uint64_t)hdr->msg_size + 8))
Branch: 1 branch
BranchTrueFalseTotal
hdr->arena_cap != (uint64_t)hdr->capacity * ((uint64_t)hdr->msg_size + 8)) 0 5 5
366 0 return 0;
367 5 uint64_t slots_end = hdr->slots_off + (uint64_t)hdr->capacity * slot_size;
368 5 ▶ if (hdr->data_off < slots_end ||
Branch: 1 branch
BranchTrueFalseTotal
if (hdr->data_off < slots_end || 5 0 5
369 5 ▶ hdr->data_off > hdr->total_size ||
Branch: 1 branch
BranchTrueFalseTotal
hdr->data_off > hdr->total_size || 5 0 5
370 5 ▶ hdr->arena_cap > hdr->total_size - hdr->data_off) /* overflow-safe: no data_off+arena_cap wrap */
Branch: 1 branch
BranchTrueFalseTotal
hdr->arena_cap > hdr->total_size - hdr->data_off) /* overflow-safe: no data_off+arena_cap wrap */ 0 5 5
371 0 return 0;
372 }
373 21 return 1;
374 }
375  
376 /* ================================================================
377 * Create / Open / Close
378 * ================================================================ */
379  
380 #define PUBSUB_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, PUBSUB_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while(0)
381  
382 169 static PubSubHandle *pubsub_init_handle(void *base, size_t map_size,
383 uint32_t mode, const char *path) {
384 169 PubSubHeader *hdr = (PubSubHeader *)base;
385 169 PubSubHandle *h = (PubSubHandle *)calloc(1, sizeof(PubSubHandle));
386 169 ▶ if (!h) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return NULL; 0 169 169
387  
388 169 h->hdr = hdr;
389 169 h->slots = (char *)base + hdr->slots_off;
390 169 ▶ h->data = (mode == PUBSUB_MODE_STR) ? (char *)base + hdr->data_off : NULL;
Branch: 1 branch
BranchTrueFalseTotal
h->data = (mode == PUBSUB_MODE_STR) ? (char *)base + hdr->data_off : NULL; 64 105 169
391 169 h->mmap_size = map_size;
392 169 h->capacity = hdr->capacity;
393 169 h->cap_mask = hdr->capacity - 1;
394 169 h->msg_size = hdr->msg_size;
395 169 h->mode = mode;
396 169 h->arena_cap = hdr->arena_cap;
397 169 ▶ h->path = path ? strdup(path) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
h->path = path ? strdup(path) : NULL; 51 118 169
398 169 ▶ if (path && !h->path) { free(h); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (path && !h->path) { free(h); return NULL; } 51 118 169
if (path && !h->path) { free(h); return NULL; } 0 51 51
399 169 h->notify_fd = -1;
400 169 h->backing_fd = -1;
401  
402 169 return h;
403 }
404  
405 148 static void pubsub_init_header(void *base, uint32_t mode, uint32_t cap,
406 uint64_t total_size, uint64_t slots_off,
407 uint64_t data_off, uint32_t msg_size,
408 uint64_t arena_cap) {
409 148 PubSubHeader *hdr = (PubSubHeader *)base;
410 148 memset(hdr, 0, sizeof(PubSubHeader));
411 148 hdr->version = PUBSUB_VERSION;
412 148 hdr->mode = mode;
413 148 hdr->capacity = cap;
414 148 hdr->total_size = total_size;
415 148 hdr->slots_off = slots_off;
416 148 hdr->data_off = data_off;
417 148 hdr->msg_size = msg_size;
418 148 hdr->arena_cap = arena_cap;
419 /* Publish magic LAST, as a release store: it is the commit point, so a
420 creator killed before it leaves magic==0 and never a file mistaken for
421 a valid one. A kill during the field stores leaves one to remove by
422 hand. */
423 148 __atomic_store_n(&hdr->magic, PUBSUB_MAGIC, __ATOMIC_RELEASE);
424  
425 148 }
426  
427 /* Returns 1 on success, 0 if the requested capacity * msg_size would
428 * exceed the 32-bit arena addressing limit (out_arena_cap is set to 0). */
429 168 static int pubsub_calc_layout(uint32_t cap, uint32_t mode, uint32_t msg_size,
430 uint64_t *out_slots_off, uint64_t *out_data_off,
431 uint64_t *out_arena_cap, uint64_t *out_total_size) {
432 168 uint64_t slots_off = sizeof(PubSubHeader);
433 168 uint64_t slot_size = (mode == PUBSUB_MODE_INT) ? sizeof(PubSubIntSlot)
434 260 ▶ : (mode == PUBSUB_MODE_INT32) ? sizeof(PubSubInt32Slot)
Branch: 1 branch
BranchTrueFalseTotal
: (mode == PUBSUB_MODE_INT32) ? sizeof(PubSubInt32Slot) 92 76 168
435 169 ▶ : (mode == PUBSUB_MODE_INT16) ? sizeof(PubSubInt16Slot)
Branch: 1 branch
BranchTrueFalseTotal
: (mode == PUBSUB_MODE_INT16) ? sizeof(PubSubInt16Slot) 77 15 92
436 77 ▶ : sizeof(PubSubStrSlot);
Branch: 1 branch
BranchTrueFalseTotal
: sizeof(PubSubStrSlot); 14 63 77
437 168 uint64_t data_off = 0, arena_cap = 0, total_size;
438  
439 168 ▶ if (mode == PUBSUB_MODE_STR) {
Branch: 1 branch
BranchTrueFalseTotal
if (mode == PUBSUB_MODE_STR) { 63 105 168
440 63 uint64_t slots_end = slots_off + (uint64_t)cap * slot_size;
441 63 data_off = (slots_end + 63) & ~(uint64_t)63;
442 63 arena_cap = (uint64_t)cap * ((uint64_t)msg_size + 8);
443 /* Safety invariant: in any window of `capacity` consecutive publishes
444 * (one full slot-ring wrap), the arena must not wrap. Otherwise a
445 * publish to slot K could overwrite slot N's still-current arena
446 * region without bumping slot N's sequence -- the seqlock would
447 * not catch the corruption. arena_cap = capacity*(msg_size+8)
448 * guarantees this; silently capping to UINT32_MAX would break the
449 * invariant for extreme (capacity, msg_size) combinations. */
450 63 ▶ if (arena_cap > UINT32_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (arena_cap > UINT32_MAX) { 0 63 63
451 0 *out_arena_cap = 0;
452 0 return 0;
453 }
454 63 total_size = data_off + arena_cap;
455 } else {
456 105 total_size = slots_off + (uint64_t)cap * slot_size;
457 }
458  
459 168 *out_slots_off = slots_off;
460 168 *out_data_off = data_off;
461 168 *out_arena_cap = arena_cap;
462 168 *out_total_size = total_size;
463 168 return 1;
464 }
465  
466 /* Securely obtain a fd: create exclusively (O_CREAT|O_EXCL|O_NOFOLLOW at mode,
467 * default 0600), or attach an existing file (O_RDWR|O_NOFOLLOW, no O_CREAT). */
468 58 static int pubsub_secure_open(const char *path, mode_t mode, char *errbuf) {
469 58 ▶ for (int attempt = 0; attempt < 100; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < 100; attempt++) { 58 0 58
470 58 int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
471 58 ▶ if (fd >= 0) { (void)fchmod(fd, mode); return fd; } /* exact mode: umask narrowed the O_EXCL create */
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { (void)fchmod(fd, mode); return fd; } /* exact mode: umask narrowed the O_EXCL create */ 37 21 58
472 21 ▶ if (errno != EEXIST) { PUBSUB_ERR("create %s: %s", path, strerror(errno)); return -1; }
Branch: 2 branches
BranchTrueFalseTotal
if (errno != EEXIST) { PUBSUB_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 21 21
if (errno != EEXIST) { PUBSUB_ERR("create %s: %s", path, strerror(errno)); return -1; } 0 0 0
473 21 fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
474 21 ▶ if (fd >= 0) return fd;
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) return fd; 21 0 21
475 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
476 0 ▶ PUBSUB_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("open %s: %s", path, strerror(errno)); /* ELOOP => symlink rejected */ 0 0 0
477 0 return -1;
478 }
479 0 ▶ PUBSUB_ERR("open %s: create/attach kept racing", path);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("open %s: create/attach kept racing", path); 0 0 0
480 0 return -1;
481 }
482  
483 /* True iff the whole file is zero -- what an abandoned mid-init
484 creator leaves. Lets recovery re-init only a provably-empty file, never
485 one that merely starts with a zero word. Cold path, so a byte scan is
486 fine. Read, not mapped: a read fault on a tmpfs hole allocates the page. */
487 2 static int pubsub_file_is_zero(int fd, uint64_t size) {
488 char buf[16384];
489 3 ▶ for (uint64_t off = 0; off < size; ) {
Branch: 1 branch
BranchTrueFalseTotal
for (uint64_t off = 0; off < size; ) { 2 1 3
490 2 ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
491 2 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 2 2
492 2561 ▶ 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 2559 2560
for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0; 2560 1 2561
493 1 off += (uint64_t)n;
494 }
495 1 return 1;
496 }
497  
498 /* Opt-in (DATA_PUBSUB_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
499 46 static int pubsub_reserve(int fd, uint64_t size) {
500 46 const char *sp = getenv("DATA_PUBSUB_SHARED_SPARSE");
501 46 ▶ if (!sp || strcmp(sp, "0")) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!sp || strcmp(sp, "0")) return 0; 0 46 46
if (!sp || strcmp(sp, "0")) return 0; 0 0 0
502 /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
503 * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
504 sigset_t all, old;
505 0 sigfillset(&all);
506 0 sigprocmask(SIG_BLOCK, &all, &old);
507 int e;
508 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
509 0 sigprocmask(SIG_SETMASK, &old, NULL);
510 0 ▶ if (e == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (e == 0) return 0; 0 0 0
511 0 errno = e;
512 0 return -1;
513 }
514  
515 160 static PubSubHandle *pubsub_create(const char *path, uint32_t capacity,
516 uint32_t mode, uint32_t msg_size,
517 mode_t fmode, char *errbuf) {
518 160 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 160 0 160
519  
520 160 uint32_t cap = pubsub_next_pow2(capacity);
521 160 ▶ if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; } 0 160 160
if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; } 0 0 0
522 160 ▶ if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; } 0 160 160
if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; } 0 0 0
523  
524 160 ▶ if (mode == PUBSUB_MODE_STR && msg_size == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (mode == PUBSUB_MODE_STR && msg_size == 0) 61 99 160
if (mode == PUBSUB_MODE_STR && msg_size == 0) 39 22 61
525 39 msg_size = PUBSUB_DEFAULT_MSG_SIZE;
526  
527 uint64_t slots_off, data_off, arena_cap, total_size;
528 160 ▶ if (!pubsub_calc_layout(cap, mode, msg_size, &slots_off, &data_off, &arena_cap, &total_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_calc_layout(cap, mode, msg_size, &slots_off, &data_off, &arena_cap, &total_size)) { 0 160 160
529 0 ▶ PUBSUB_ERR("capacity * (msg_size+8) exceeds 4GB arena limit");
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("capacity * (msg_size+8) exceeds 4GB arena limit"); 0 0 0
530 0 return NULL;
531 }
532  
533 160 int anonymous = (path == NULL);
534 size_t map_size;
535 void *base;
536  
537 160 ▶ if (anonymous) {
Branch: 1 branch
BranchTrueFalseTotal
if (anonymous) { 102 58 160
538 102 map_size = (size_t)total_size;
539 102 base = mmap(NULL, map_size, PROT_READ | PROT_WRITE,
540 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
541 102 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 102 102
542 0 ▶ PUBSUB_ERR("mmap(anonymous): %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("mmap(anonymous): %s", strerror(errno)); 0 0 0
543 0 return NULL;
544 }
545 102 pubsub_init_header(base, mode, cap, total_size, slots_off, data_off,
546 msg_size, arena_cap);
547 } else {
548 58 int fd = pubsub_secure_open(path, fmode, errbuf);
549 79 ▶ if (fd < 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (fd < 0) return NULL; 0 58 58
550  
551 58 ▶ if (flock(fd, LOCK_EX) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (flock(fd, LOCK_EX) < 0) { 0 58 58
552 0 ▶ PUBSUB_ERR("flock(%s): %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("flock(%s): %s", path, strerror(errno)); 0 0 0
553 0 close(fd); return NULL;
554 }
555  
556 struct stat st;
557 58 ▶ if (fstat(fd, &st) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { 0 58 58
558 0 ▶ PUBSUB_ERR("fstat(%s): %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fstat(%s): %s", path, strerror(errno)); 0 0 0
559 0 flock(fd, LOCK_UN); close(fd); return NULL;
560 }
561  
562 58 int is_new = (st.st_size == 0);
563  
564 58 ▶ if (!is_new && (uint64_t)st.st_size < sizeof(PubSubHeader)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!is_new && (uint64_t)st.st_size < sizeof(PubSubHeader)) { 21 37 58
if (!is_new && (uint64_t)st.st_size < sizeof(PubSubHeader)) { 0 21 21
565 0 ▶ PUBSUB_ERR("%s: file too small (%lld)", path, (long long)st.st_size);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: file too small (%lld)", path, (long long)st.st_size); 0 0 0
566 0 flock(fd, LOCK_UN); close(fd); return NULL;
567 }
568  
569 58 ▶ if (is_new && (st.st_uid != geteuid() || fchmod(fd, fmode) < 0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (is_new && (st.st_uid != geteuid() || fchmod(fd, fmode) < 0)) { 37 21 58
if (is_new && (st.st_uid != geteuid() || fchmod(fd, fmode) < 0)) { 37 0 37
if (is_new && (st.st_uid != geteuid() || fchmod(fd, fmode) < 0)) { 0 37 37
570 0 ▶ PUBSUB_ERR("%s: refusing to initialize file not owned by us", path);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: refusing to initialize file not owned by us", path); 0 0 0
571 0 flock(fd, LOCK_UN); close(fd); return NULL;
572 }
573 58 ▶ if (is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_new) { 37 21 58
574 37 ▶ if (ftruncate(fd, (off_t)total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total_size) < 0) { 0 37 37
575 0 ▶ PUBSUB_ERR("ftruncate(%s): %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("ftruncate(%s): %s", path, strerror(errno)); 0 0 0
576 0 flock(fd, LOCK_UN); close(fd); return NULL;
577 }
578 37 ▶ if (pubsub_reserve(fd, total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pubsub_reserve(fd, total_size) < 0) { 0 37 37
579 0 ▶ PUBSUB_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total_size, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total_size, strerror(errno)); 0 0 0
580 0 if (ftruncate(fd, 0) < 0) { /* best effort */ }
581 0 flock(fd, LOCK_UN); close(fd); return NULL;
582 }
583 }
584  
585 58 ▶ map_size = is_new ? (size_t)total_size : (size_t)st.st_size;
Branch: 1 branch
BranchTrueFalseTotal
map_size = is_new ? (size_t)total_size : (size_t)st.st_size; 21 37 58
586 58 base = mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
587 58 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 58 58
588 0 ▶ PUBSUB_ERR("mmap(%s): %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("mmap(%s): %s", path, strerror(errno)); 0 0 0
589 0 ▶ if (is_new && ftruncate(fd, 0) < 0) { /* best effort */ }
Branch: 1 branch
BranchTrueFalseTotal
if (is_new && ftruncate(fd, 0) < 0) { /* best effort */ } 0 0 0
590 0 flock(fd, LOCK_UN); close(fd); return NULL;
591 }
592  
593 58 ▶ if (!is_new) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_new) { 21 37 58
594 21 ▶ if (!pubsub_validate_header((PubSubHeader *)base, mode, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_validate_header((PubSubHeader *)base, mode, (uint64_t)st.st_size)) { 8 13 21
595 /* Recover an abandoned mid-init file: a creator killed
596 * between the ftruncate and the header init leaves a
597 * full-size, all-zero (magic==0) file that would brick every
598 * future open of this path. Re-initialize ONLY when it is
599 * exactly our size, still uninitialized, and owned by us;
600 * anything else still errors. */
601 8 ▶ if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size
Branch: 2 branches
BranchTrueFalseTotal
if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size 3 5 8
if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size 2 1 3
602 2 ▶ && st.st_uid == geteuid() && pubsub_file_is_zero(fd, map_size)) {
Branch: 2 branches
BranchTrueFalseTotal
&& st.st_uid == geteuid() && pubsub_file_is_zero(fd, map_size)) { 2 0 2
&& st.st_uid == geteuid() && pubsub_file_is_zero(fd, map_size)) { 1 1 2
603 1 ▶ if (fchmod(fd, fmode) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fchmod(fd, fmode) < 0) { 0 1 1
604 0 ▶ PUBSUB_ERR("%s: fchmod: %s", path, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: fchmod: %s", path, strerror(errno)); 0 0 0
605 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
606 }
607 1 ▶ if (pubsub_reserve(fd, total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pubsub_reserve(fd, total_size) < 0) { 0 1 1
608 0 ▶ PUBSUB_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total_size, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: cannot reserve %llu bytes: %s", path, (unsigned long long)total_size, strerror(errno)); 0 0 0
609 0 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
610 }
611 1 pubsub_init_header(base, mode, cap, total_size, slots_off, data_off,
612 msg_size, arena_cap);
613 1 flock(fd, LOCK_UN); close(fd);
614 1 PubSubHandle *h = pubsub_init_handle(base, map_size, mode, path);
615 1 ▶ if (!h) { munmap(base, map_size); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { munmap(base, map_size); return NULL; } 0 1 1
616 1 return h;
617 }
618 7 ▶ if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size
Branch: 2 branches
BranchTrueFalseTotal
if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size 2 5 7
if (((PubSubHeader *)base)->magic == 0 && (uint64_t)st.st_size == total_size 1 1 2
619 1 ▶ && st.st_uid == geteuid())
Branch: 1 branch
BranchTrueFalseTotal
&& st.st_uid == geteuid()) 1 0 1
620 1 ▶ PUBSUB_ERR("%s: incomplete pubsub file left by an interrupted create; remove it and retry", path);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: incomplete pubsub file left by an interrupted create; remove it and retry", path); 1 0 1
621 else
622 6 ▶ PUBSUB_ERR("%s: invalid or incompatible pubsub file", path);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("%s: invalid or incompatible pubsub file", path); 6 0 6
623 7 munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
624 }
625 13 flock(fd, LOCK_UN);
626 13 close(fd);
627 13 PubSubHandle *h = pubsub_init_handle(base, map_size, mode, path);
628 13 ▶ if (!h) munmap(base, map_size);
Branch: 1 branch
BranchTrueFalseTotal
if (!h) munmap(base, map_size); 0 13 13
629 13 return h;
630 }
631  
632 37 pubsub_init_header(base, mode, cap, total_size, slots_off, data_off,
633 msg_size, arena_cap);
634 37 flock(fd, LOCK_UN);
635 37 close(fd);
636 }
637  
638 139 PubSubHandle *h = pubsub_init_handle(base, (size_t)total_size, mode, path);
639 139 ▶ if (!h) { munmap(base, (size_t)total_size); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { munmap(base, (size_t)total_size); return NULL; } 0 139 139
640 139 return h;
641 }
642  
643 8 static PubSubHandle *pubsub_create_memfd(const char *name, uint32_t capacity,
644 uint32_t mode, uint32_t msg_size,
645 char *errbuf) {
646 8 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 8 0 8
647  
648 8 uint32_t cap = pubsub_next_pow2(capacity);
649 8 ▶ if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; } 0 8 8
if (cap == 0) { PUBSUB_ERR("invalid capacity"); return NULL; } 0 0 0
650 8 ▶ if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; } 0 8 8
if (mode > PUBSUB_MODE_INT16) { PUBSUB_ERR("unknown mode %u", mode); return NULL; } 0 0 0
651  
652 8 ▶ if (mode == PUBSUB_MODE_STR && msg_size == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (mode == PUBSUB_MODE_STR && msg_size == 0) 2 6 8
if (mode == PUBSUB_MODE_STR && msg_size == 0) 2 0 2
653 2 msg_size = PUBSUB_DEFAULT_MSG_SIZE;
654  
655 uint64_t slots_off, data_off, arena_cap, total_size;
656 8 ▶ if (!pubsub_calc_layout(cap, mode, msg_size, &slots_off, &data_off, &arena_cap, &total_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_calc_layout(cap, mode, msg_size, &slots_off, &data_off, &arena_cap, &total_size)) { 0 8 8
657 0 ▶ PUBSUB_ERR("capacity * (msg_size+8) exceeds 4GB arena limit");
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("capacity * (msg_size+8) exceeds 4GB arena limit"); 0 0 0
658 0 return NULL;
659 }
660  
661 8 ▶ int fd = memfd_create(name ? name : "pubsub", MFD_CLOEXEC | MFD_ALLOW_SEALING);
Branch: 1 branch
BranchTrueFalseTotal
int fd = memfd_create(name ? name : "pubsub", MFD_CLOEXEC | MFD_ALLOW_SEALING); 8 0 8
662 8 ▶ if (fd < 0) { PUBSUB_ERR("memfd_create: %s", strerror(errno)); return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (fd < 0) { PUBSUB_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 8 8
if (fd < 0) { PUBSUB_ERR("memfd_create: %s", strerror(errno)); return NULL; } 0 0 0
663  
664 8 ▶ if (ftruncate(fd, (off_t)total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ftruncate(fd, (off_t)total_size) < 0) { 0 8 8
665 0 ▶ PUBSUB_ERR("ftruncate(memfd): %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("ftruncate(memfd): %s", strerror(errno)); 0 0 0
666 0 close(fd); return NULL;
667 }
668 8 ▶ if (pubsub_reserve(fd, total_size) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (pubsub_reserve(fd, total_size) < 0) { 0 8 8
669 0 ▶ PUBSUB_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total_size, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("memfd: cannot reserve %llu bytes: %s", (unsigned long long)total_size, strerror(errno)); 0 0 0
670 0 close(fd); return NULL;
671 }
672 8 (void)fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
673  
674 8 void *base = mmap(NULL, (size_t)total_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
675 8 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 8 8
676 0 ▶ PUBSUB_ERR("mmap(memfd): %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("mmap(memfd): %s", strerror(errno)); 0 0 0
677 0 close(fd); return NULL;
678 }
679  
680 8 pubsub_init_header(base, mode, cap, total_size, slots_off, data_off,
681 msg_size, arena_cap);
682  
683 8 PubSubHandle *h = pubsub_init_handle(base, (size_t)total_size, mode, NULL);
684 8 ▶ if (!h) { munmap(base, (size_t)total_size); close(fd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { munmap(base, (size_t)total_size); close(fd); return NULL; } 0 8 8
685 8 h->backing_fd = fd;
686 8 return h;
687 }
688  
689 8 static PubSubHandle *pubsub_open_fd(int fd, uint32_t mode, char *errbuf) {
690 8 ▶ if (errbuf) errbuf[0] = '\0';
Branch: 1 branch
BranchTrueFalseTotal
if (errbuf) errbuf[0] = '\0'; 8 0 8
691  
692 struct stat st;
693 8 ▶ if (fstat(fd, &st) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fstat(fd, &st) < 0) { 0 8 8
694 0 ▶ PUBSUB_ERR("fstat(fd=%d): %s", fd, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fstat(fd=%d): %s", fd, strerror(errno)); 0 0 0
695 0 return NULL;
696 }
697  
698 8 ▶ if ((uint64_t)st.st_size < sizeof(PubSubHeader)) {
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)st.st_size < sizeof(PubSubHeader)) { 0 8 8
699 0 ▶ PUBSUB_ERR("fd %d: too small (%lld)", fd, (long long)st.st_size);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fd %d: too small (%lld)", fd, (long long)st.st_size); 0 0 0
700 0 return NULL;
701 }
702  
703 /* before mmap: a creator may truncate the file until it has set magic */
704 uint32_t magic;
705 8 ▶ if (pread(fd, &magic, sizeof magic, offsetof(PubSubHeader, magic)) != (ssize_t)sizeof magic || magic != PUBSUB_MAGIC) {
Branch: 2 branches
BranchTrueFalseTotal
if (pread(fd, &magic, sizeof magic, offsetof(PubSubHeader, magic)) != (ssize_t)sizeof magic || magic != PUBSUB_MAGIC) { 8 0 8
if (pread(fd, &magic, sizeof magic, offsetof(PubSubHeader, magic)) != (ssize_t)sizeof magic || magic != PUBSUB_MAGIC) { 0 8 8
706 0 ▶ PUBSUB_ERR("fd %d: invalid or incompatible pubsub", fd);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fd %d: invalid or incompatible pubsub", fd); 0 0 0
707 0 return NULL;
708 }
709  
710 8 size_t map_size = (size_t)st.st_size;
711 8 void *base = mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
712 8 ▶ if (base == MAP_FAILED) {
Branch: 1 branch
BranchTrueFalseTotal
if (base == MAP_FAILED) { 0 8 8
713 0 ▶ PUBSUB_ERR("mmap(fd=%d): %s", fd, strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("mmap(fd=%d): %s", fd, strerror(errno)); 0 0 0
714 0 return NULL;
715 }
716  
717 8 ▶ if (!pubsub_validate_header((PubSubHeader *)base, mode, (uint64_t)st.st_size)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_validate_header((PubSubHeader *)base, mode, (uint64_t)st.st_size)) { 0 8 8
718 0 ▶ PUBSUB_ERR("fd %d: invalid or incompatible pubsub", fd);
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fd %d: invalid or incompatible pubsub", fd); 0 0 0
719 0 munmap(base, map_size);
720 0 return NULL;
721 }
722  
723 8 int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
724 8 ▶ if (myfd < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (myfd < 0) { 0 8 8
725 0 ▶ PUBSUB_ERR("fcntl(F_DUPFD_CLOEXEC): %s", strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
PUBSUB_ERR("fcntl(F_DUPFD_CLOEXEC): %s", strerror(errno)); 0 0 0
726 0 munmap(base, map_size);
727 0 return NULL;
728 }
729  
730 8 PubSubHandle *h = pubsub_init_handle(base, map_size, mode, NULL);
731 8 ▶ if (!h) { munmap(base, map_size); close(myfd); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!h) { munmap(base, map_size); close(myfd); return NULL; } 0 8 8
732 8 h->backing_fd = myfd;
733 8 return h;
734 }
735  
736 169 static void pubsub_destroy(PubSubHandle *h) {
737 169 ▶ if (!h) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) return; 0 169 169
738 169 ▶ if (h->notify_fd >= 0) close(h->notify_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->notify_fd >= 0) close(h->notify_fd); 25 144 169
739 169 ▶ if (h->backing_fd >= 0) close(h->backing_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->backing_fd >= 0) close(h->backing_fd); 16 153 169
740 169 ▶ if (h->hdr) munmap(h->hdr, h->mmap_size);
Branch: 1 branch
BranchTrueFalseTotal
if (h->hdr) munmap(h->hdr, h->mmap_size); 169 0 169
741 169 free(h->path);
742 169 free(h);
743 }
744  
745 /* ================================================================
746 * Subscribe
747 * ================================================================ */
748  
749 321 static PubSubSub *pubsub_subscribe(PubSubHandle *h, int from_oldest) {
750 321 PubSubSub *sub = (PubSubSub *)calloc(1, sizeof(PubSubSub));
751 321 ▶ if (!sub) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!sub) return NULL; 0 321 321
752  
753 321 sub->hdr = h->hdr;
754 321 sub->slots = h->slots;
755 321 sub->data = h->data;
756 321 sub->capacity = h->capacity;
757 321 sub->cap_mask = h->cap_mask;
758 321 sub->msg_size = h->msg_size;
759 321 sub->arena_cap = h->arena_cap;
760  
761 321 sub->notify_fd = h->notify_fd;
762  
763 321 uint64_t wp = __atomic_load_n(&h->hdr->write_pos, __ATOMIC_ACQUIRE);
764 321 ▶ if (from_oldest && wp > h->capacity)
Branch: 2 branches
BranchTrueFalseTotal
if (from_oldest && wp > h->capacity) 69 252 321
if (from_oldest && wp > h->capacity) 1 68 69
765 1 sub->cursor = wp - h->capacity;
766 320 ▶ else if (from_oldest)
Branch: 1 branch
BranchTrueFalseTotal
else if (from_oldest) 68 252 320
767 68 sub->cursor = 0;
768 else
769 252 sub->cursor = wp;
770  
771 321 return sub;
772 }
773  
774 321 static void pubsub_sub_destroy(PubSubSub *sub) {
775 321 ▶ if (!sub) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sub) return; 0 321 321
776 321 free(sub->copy_buf);
777 321 free(sub);
778 }
779  
780 /* ================================================================
781 * Common: lag (shared between Int and Str)
782 * ================================================================ */
783  
784 37 static inline uint64_t pubsub_lag(PubSubSub *sub) {
785 37 uint64_t wp = __atomic_load_n(&sub->hdr->write_pos, __ATOMIC_RELAXED);
786 37 ▶ return (wp > sub->cursor) ? (wp - sub->cursor) : 0;
Branch: 1 branch
BranchTrueFalseTotal
return (wp > sub->cursor) ? (wp - sub->cursor) : 0; 27 10 37
787 }
788  
789 /* ================================================================
790 * Int publish/poll macro template
791 *
792 * DEFINE_INT_PUBSUB(prefix, SlotType, ValType, SeqType, DiffType, COMMIT)
793 * generates: pubsub_<prefix>_commit_at, _publish, _publish_multi, _poll,
794 * _poll_wait. COMMIT is the slot-commit primitive (see below).
795 * ================================================================ */
796  
797 /* ---- slot commit: write (value, sequence) so a publisher preempted for a
798 * full lap between its write_pos claim and here can never revert the slot to
799 * stale contents (which would permanently stall a subscriber sitting on it) or
800 * clobber a fresher value. Two implementations, chosen per slot width. ---- */
801  
802 /* Drop iff a lap at or past ours already owns the slot. Sequence 0 is
803 * ambiguous: it is both "never written" and the truncated sequence of the
804 * publisher at pos == 2^bits-1 (Int32/Int16 store (uint32_t)(pos+1)). Only the
805 * genuinely-uncomparable case -- our own sequence is also 0 -- bypasses the
806 * comparison (write the boundary/empty publish); an occupant sitting at a
807 * truncated 0 is still compared, so a stale writer one lap behind it is
808 * correctly dropped instead of reverting the slot. Without the both-zero
809 * guard, a lone `curseq != 0` bypass would re-open the lap-ABA revert once per
810 * 2^32 publishes on Int32/Int16. */
811 #define PUBSUB_LAP_SUPERSEDED(STYPE, DTYPE, NEWSEQ, CURSEQ) \
812 ((DTYPE)((STYPE)(NEWSEQ) - (STYPE)(CURSEQ)) <= 0 && \
813 !((STYPE)(CURSEQ) == 0 && (STYPE)(NEWSEQ) == 0))
814  
815 /* Lock-free: commit (value, sequence) as one indivisible slot update via a
816 * slot-wide CAS, and DROP the store if a later lap already owns the slot (its
817 * sequence is at or past the one we would write). Keeps value and sequence
818 * mutually consistent for the reader's seqlock, and makes the lapped-writer
819 * test-and-drop atomic against other publishers. Used for the 8-byte
820 * Int32/Int16 slots everywhere, and the 16-byte Int slot where a lock-free
821 * 16-byte CAS is available.
822 *
823 * The slot is punned to a same-width unsigned integer (WORDT) and driven with
824 * __sync_bool_compare_and_swap: gcc inlines that to cmpxchg16b (with -mcx16)
825 * for the 16-byte case, whereas the __atomic builtins route 16-byte ops through
826 * libatomic -- which we must avoid, since a lock-based libatomic fallback is
827 * not shared-memory safe across processes. sequence and value are read with
828 * their own narrow inline atomic loads to form the CAS expectation; a torn or
829 * stale expectation just fails the CAS and the loop re-reads. memset zeroes
830 * any padding (Int16's _pad) so the punned expectation matches the slot, whose
831 * padding is invariantly zero (mmap zero-fill; no path writes it nonzero). */
832 #define PUBSUB_COMMIT_ATOMIC(SLOTT, WORDT, STYPE, DTYPE, HDR, SLOTP, NEWSEQ, VAL) \
833 do { \
834 _Static_assert(sizeof(WORDT) == sizeof(SLOTT), \
835 "PubSub: CAS word type must match slot size"); \
836 WORDT *_wp = (WORDT *)(SLOTP); \
837 for (;;) { \
838 STYPE _cseq = __atomic_load_n(&(SLOTP)->sequence, __ATOMIC_RELAXED);\
839 if (PUBSUB_LAP_SUPERSEDED(STYPE, DTYPE, NEWSEQ, _cseq)) \
840 break; /* a >= lap owns the slot -> drop */ \
841 SLOTT _cur, _des; WORDT _ecur, _edes; \
842 memset(&_cur, 0, sizeof _cur); \
843 _cur.sequence = _cseq; \
844 _cur.value = __atomic_load_n(&(SLOTP)->value, __ATOMIC_RELAXED); \
845 _des = _cur; _des.sequence = (NEWSEQ); _des.value = (VAL); \
846 memcpy(&_ecur, &_cur, sizeof _ecur); \
847 memcpy(&_edes, &_des, sizeof _edes); \
848 if (__sync_bool_compare_and_swap(_wp, _ecur, _edes)) \
849 break; /* committed */ \
850 /* CAS failed (stale/torn expectation or a racing publisher): retry*/\
851 } \
852 (void)(HDR); \
853 } while (0)
854  
855 /* Fallback for a platform without a lock-free CAS as wide as the slot:
856 * serialize publishers on the header mutex (the one the Str variant uses).
857 * Same test-and-drop; readers stay lock-free. Only ever selected for the
858 * 16-byte Int slot where PUBSUB_INT_ATOMIC16 is 0. WORDT is unused here. */
859 #define PUBSUB_COMMIT_MUTEX(SLOTT, WORDT, STYPE, DTYPE, HDR, SLOTP, NEWSEQ, VAL) \
860 do { \
861 pubsub_mutex_lock(HDR); \
862 SLOTT *_s = (SLOTP); \
863 if (!PUBSUB_LAP_SUPERSEDED(STYPE, DTYPE, NEWSEQ, _s->sequence)) { \
864 /* A busy sequence cannot match this slot's readable positions. */ \
865 __atomic_store_n(&_s->sequence, (STYPE)((NEWSEQ) - 1), __ATOMIC_RELAXED); \
866 __atomic_thread_fence(__ATOMIC_RELEASE); \
867 __atomic_store_n(&_s->value, (VAL), __ATOMIC_RELAXED); \
868 __atomic_store_n(&_s->sequence, (NEWSEQ), __ATOMIC_RELEASE); \
869 } \
870 pubsub_mutex_unlock(HDR); \
871 (void)sizeof(WORDT); \
872 } while (0)
873  
874 /* Is a lock-free CAS as wide as the 16-byte Int slot available? Needs a
875 * 128-bit integer (__int128) and, on x86-64, -mcx16 (added by Makefile.PL) so
876 * gcc inlines cmpxchg16b; arm64 has it natively. Build with
877 * -DPUBSUB_INT_FORCE_MUTEX to force the fallback (used to test it). */
878 #if defined(PUBSUB_INT_FORCE_MUTEX) || !defined(__SIZEOF_INT128__)
879 # define PUBSUB_INT_ATOMIC16 0
880 #elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) || defined(__aarch64__) || defined(__ARM_FEATURE_ATOMICS)
881 # define PUBSUB_INT_ATOMIC16 1
882 #else
883 # define PUBSUB_INT_ATOMIC16 0
884 #endif
885  
886 #if PUBSUB_INT_ATOMIC16
887 typedef unsigned __int128 PubSubIntWord;
888 # define PUBSUB_COMMIT_INT PUBSUB_COMMIT_ATOMIC
889 #else
890 typedef uint64_t PubSubIntWord; /* mutex fallback: WORDT is only sizeof'd */
891 # define PUBSUB_COMMIT_INT PUBSUB_COMMIT_MUTEX
892 #endif
893  
894 /* The 8-byte Int32/Int16 slots need a lock-free 8-byte CAS -- inline on
895 * x86-64/aarch64/armv7+ but a libatomic (locked, not shared-memory safe) call
896 * on ancient 32-bit targets without one (armv6, i486/i586, mips/riscv32).
897 * Fall back to the header mutex there too. -DPUBSUB_INT8_FORCE_MUTEX forces
898 * it for testing. */
899 #if defined(PUBSUB_INT8_FORCE_MUTEX) || defined(PUBSUB_INT_FORCE_MUTEX)
900 # define PUBSUB_INT_ATOMIC8 0
901 #elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) || defined(__x86_64__) || defined(__aarch64__)
902 # define PUBSUB_INT_ATOMIC8 1
903 #else
904 # define PUBSUB_INT_ATOMIC8 0
905 #endif
906  
907 #if PUBSUB_INT_ATOMIC8
908 # define PUBSUB_COMMIT_INT8 PUBSUB_COMMIT_ATOMIC
909 #else
910 # define PUBSUB_COMMIT_INT8 PUBSUB_COMMIT_MUTEX
911 #endif
912  
913 #define DEFINE_INT_PUBSUB(PFX, SLOT, WORDT, VTYPE, STYPE, DTYPE, COMMIT) \
914 \
915 static inline void pubsub_##PFX##_commit_at(PubSubHandle *h, uint64_t pos, \
916 VTYPE value) { \
917 SLOT *slots = (SLOT *)h->slots; \
918 uint32_t idx = pos & h->cap_mask; \
919 COMMIT(SLOT, WORDT, STYPE, DTYPE, h->hdr, &slots[idx], (STYPE)(pos + 1), value);\
920 } \
921 \
922 static inline int pubsub_##PFX##_publish(PubSubHandle *h, VTYPE value) { \
923 PubSubHeader *hdr = h->hdr; \
924 uint64_t pos = __atomic_fetch_add(&hdr->write_pos, 1, __ATOMIC_RELAXED); \
925 pubsub_##PFX##_commit_at(h, pos, value); \
926 __atomic_add_fetch(&hdr->stat_publish_ok, 1, __ATOMIC_RELAXED); \
927 pubsub_wake_subscribers(hdr); \
928 return 1; \
929 } \
930 \
931 static inline uint32_t pubsub_##PFX##_publish_multi(PubSubHandle *h, \
932 const VTYPE *values, uint32_t count) { \
933 PubSubHeader *hdr = h->hdr; \
934 uint64_t pos = __atomic_fetch_add(&hdr->write_pos, count, __ATOMIC_RELAXED);\
935 for (uint32_t i = 0; i < count; i++) \
936 pubsub_##PFX##_commit_at(h, pos + i, values[i]); \
937 __atomic_add_fetch(&hdr->stat_publish_ok, count, __ATOMIC_RELAXED); \
938 pubsub_wake_subscribers(hdr); \
939 return count; \
940 } \
941 \
942 static inline int pubsub_##PFX##_poll(PubSubSub *sub, VTYPE *value) { \
943 PubSubHeader *hdr = sub->hdr; \
944 SLOT *slots = (SLOT *)sub->slots; \
945 for (int attempt = 0; attempt < PUBSUB_POLL_RETRIES; attempt++) { \
946 uint64_t cursor = sub->cursor; \
947 uint64_t wp = __atomic_load_n(&hdr->write_pos, __ATOMIC_ACQUIRE); \
948 if (cursor >= wp) return 0; \
949 if (wp - cursor > sub->capacity) { \
950 sub->overflow_count += wp - cursor - sub->capacity; \
951 sub->cursor = wp - sub->capacity; \
952 continue; \
953 } \
954 uint32_t idx = cursor & sub->cap_mask; \
955 SLOT *slot = &slots[idx]; \
956 STYPE seq1 = __atomic_load_n(&slot->sequence, __ATOMIC_ACQUIRE); \
957 /* Subtract as UNSIGNED STYPE, then cast to DTYPE (wraparound-safe, \
958 * same idiom as PUBSUB_LAP_SUPERSEDED); the signed subtraction of \
959 * two DTYPEs here would be UB on displacement > 2^31 without -fwrapv. */ \
960 DTYPE diff = (DTYPE)((STYPE)seq1 - (STYPE)(cursor + 1)); \
961 if (__builtin_expect(diff != 0, 0)) { \
962 if (diff > 0) { \
963 wp = __atomic_load_n(&hdr->write_pos, __ATOMIC_ACQUIRE); \
964 uint64_t nc = wp > sub->capacity ? wp - sub->capacity : 0; \
965 if (nc > cursor) { \
966 sub->overflow_count += nc - cursor; \
967 sub->cursor = nc; \
968 } \
969 continue; \
970 } \
971 return 0; \
972 } \
973 VTYPE v = __atomic_load_n(&slot->value, __ATOMIC_RELAXED); \
974 __atomic_thread_fence(__ATOMIC_ACQUIRE); \
975 STYPE seq2 = __atomic_load_n(&slot->sequence, __ATOMIC_RELAXED); \
976 if (seq2 != seq1) continue; \
977 *value = v; \
978 sub->cursor = cursor + 1; \
979 return 1; \
980 } \
981 return 0; \
982 } \
983 \
984 static int pubsub_##PFX##_poll_wait(PubSubSub *sub, VTYPE *value, \
985 double timeout) { \
986 int r = pubsub_##PFX##_poll(sub, value); \
987 if (r != 0) return r; \
988 if (timeout == 0.0) return 0; \
989 PubSubHeader *hdr = sub->hdr; \
990 struct timespec deadline, remaining; \
991 int has_deadline = (timeout > 0); \
992 if (has_deadline) pubsub_make_deadline(timeout, &deadline); \
993 for (;;) { \
994 /* Increment waiters BEFORE loading fseq/polling. SEQ_CST pairs \
995 * with publisher's SEQ_CST fence in pubsub_wake_subscribers so a \
996 * publisher that races our poll() either sees waiters > 0 and \
997 * wakes us, or publishes data we observe in the post-increment \
998 * poll. Without this ordering, we could sleep forever on an \
999 * unchanged fseq while data sits in the ring. */ \
1000 __atomic_add_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST); \
1001 uint32_t fseq = __atomic_load_n(&hdr->sub_futex, __ATOMIC_ACQUIRE); \
1002 r = pubsub_##PFX##_poll(sub, value); \
1003 if (r != 0) { \
1004 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST); \
1005 return r; \
1006 } \
1007 struct timespec *pts = NULL; \
1008 if (has_deadline) { \
1009 if (!pubsub_remaining_time(&deadline, &remaining)) { \
1010 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST); \
1011 return 0; \
1012 } \
1013 pts = &remaining; \
1014 } \
1015 long rc = syscall(SYS_futex, &hdr->sub_futex, FUTEX_WAIT, \
1016 fseq, pts, NULL, 0); \
1017 int wait_errno = errno; \
1018 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST); \
1019 if (PUBSUB_WAIT_INTERRUPTED()) { errno = EINTR; return -1; } \
1020 r = pubsub_##PFX##_poll(sub, value); \
1021 if (r != 0) return r; \
1022 if (rc == -1 && wait_errno == ETIMEDOUT) return 0; \
1023 } \
1024 }
1025  
1026 /* Instantiate for Int (64-bit seq + 64-bit value = 16 bytes/slot). The 16-byte
1027 * slot uses a lock-free CAS where available, else the header-mutex fallback. */
1028 2617 ▶DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT)
Branch: 23 branches
BranchTrueFalseTotal
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 5 6 11
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 6 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 6 0 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 6 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 6 0 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 6 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 6 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 4 2 6
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 2 0 2
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 2 0 2
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 32 1193 1225
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 2 1191 1193
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 1191 1191
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 0 0
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 0 0
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 0 0
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 1191 1191
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 1225 0 1225
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 213 5 218
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 685 685
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 0 0
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 0 0 0
DEFINE_INT_PUBSUB(int, PubSubIntSlot, PubSubIntWord, int64_t, uint64_t, int64_t, PUBSUB_COMMIT_INT) 685 0 685
1029  
1030 /* Instantiate for Int32 (32-bit seq + 32-bit value = 8 bytes/slot) */
1031 167 ▶DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8)
Branch: 23 branches
BranchTrueFalseTotal
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 1 2
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 8 36 44
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 35 36
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 35 35
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 35 35
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 44 0 44
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 8 2 10
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 59 59
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int32, PubSubInt32Slot, uint64_t, int32_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 59 0 59
1032  
1033 /* Instantiate for Int16 (32-bit seq + 16-bit value = 8 bytes/slot) */
1034 165 ▶DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8)
Branch: 23 branches
BranchTrueFalseTotal
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 1 2
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 1 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 0 1
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 8 36 44
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 1 35 36
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 35 35
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 35 35
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 44 0 44
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 8 2 10
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 58 58
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 0 0 0
DEFINE_INT_PUBSUB(int16, PubSubInt16Slot, uint64_t, int16_t, uint32_t, int32_t, PUBSUB_COMMIT_INT8) 58 0 58
1035  
1036 /* ================================================================
1037 * Str: mutex-protected publish, lock-free subscribe
1038 *
1039 * Variable-length messages: each slot owns a fixed dedicated arena region.
1040 * The seqlock (sequence double-check) guarantees readers see consistent data.
1041 * ================================================================ */
1042  
1043 /* Publish one Str message while mutex is already held (no lock/wake). */
1044 415 static inline int pubsub_str_publish_locked(PubSubHandle *h, const char *str,
1045 uint32_t len, bool utf8) {
1046 415 ▶ if (len > PUBSUB_STR_LEN_MASK) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (len > PUBSUB_STR_LEN_MASK) return -1; 0 415 415
1047 415 ▶ if (len > h->msg_size) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (len > h->msg_size) return -1; 2 413 415
1048  
1049 413 PubSubHeader *hdr = h->hdr;
1050 413 PubSubStrSlot *slots = (PubSubStrSlot *)h->slots;
1051  
1052 413 uint64_t pos = __atomic_load_n(&hdr->write_pos, __ATOMIC_RELAXED);
1053 413 uint32_t idx = pos & h->cap_mask;
1054 413 PubSubStrSlot *slot = &slots[idx];
1055  
1056 413 __atomic_store_n(&slot->sequence, 0, __ATOMIC_RELAXED);
1057 413 __atomic_thread_fence(__ATOMIC_RELEASE);
1058  
1059 413 uint32_t alloc = (len + 7) & ~7u;
1060 413 ▶ if (alloc == 0) alloc = 8;
Branch: 1 branch
BranchTrueFalseTotal
if (alloc == 0) alloc = 8; 3 410 413
1061 413 ▶ if (alloc > h->arena_cap) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (alloc > h->arena_cap) return -1; 0 413 413
1062  
1063 /* Each slot owns a fixed, dedicated arena region
1064 * [idx*stride, idx*stride + stride), with
1065 * stride = arena_cap/capacity == msg_size+8 > round_up(len).
1066 * A publish therefore writes only within its own slot's region and can
1067 * never touch another slot's still-live bytes, so the per-slot seqlock
1068 * fully guards every message. (The previous circular byte arena could, at
1069 * small capacity with variable-length messages, wrap its write frontier
1070 * onto a still-current slot's region WITHOUT bumping that slot's sequence,
1071 * so a lagging subscriber read corrupted bytes the seqlock never caught.) */
1072 413 uint32_t stride = (uint32_t)(h->arena_cap / h->capacity);
1073 413 uint32_t apos = idx * stride;
1074  
1075 /* Bound the arena write position against the cached (open-time-validated)
1076 * region size, using cached capacity/arena_cap (not live hdr->) for the
1077 * stride: a peer that corrupted the shared header must not be able to make
1078 * this publish memcpy past the mapped arena. Never taken for a valid
1079 * layout (apos+alloc < arena_cap always). */
1080 413 ▶ if ((uint64_t)apos + alloc > h->arena_cap) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)apos + alloc > h->arena_cap) return -1; 0 413 413
1081  
1082 413 memcpy(h->data + apos, str, len);
1083  
1084 413 slot->arena_off = apos;
1085 413 ▶ slot->packed_len = len | (utf8 ? PUBSUB_STR_UTF8_FLAG : 0);
Branch: 1 branch
BranchTrueFalseTotal
slot->packed_len = len | (utf8 ? PUBSUB_STR_UTF8_FLAG : 0); 6 407 413
1086  
1087 413 __atomic_store_n(&slot->sequence, pos + 1, __ATOMIC_RELEASE);
1088 413 __atomic_store_n(&hdr->write_pos, pos + 1, __ATOMIC_RELEASE);
1089 413 __atomic_add_fetch(&hdr->stat_publish_ok, 1, __ATOMIC_RELAXED);
1090  
1091 413 return 1;
1092 }
1093  
1094 static inline int pubsub_str_publish(PubSubHandle *h, const char *str,
1095 uint32_t len, bool utf8) {
1096 if (len > h->msg_size) return -1;
1097 pubsub_mutex_lock(h->hdr);
1098 int r = pubsub_str_publish_locked(h, str, len, utf8);
1099 pubsub_mutex_unlock(h->hdr);
1100 if (r == 1) pubsub_wake_subscribers_fenced(h->hdr);
1101 return r;
1102 }
1103  
1104 /* Returns: 1 = success, 0 = empty/not-ready */
1105 988 static inline int pubsub_str_poll(PubSubSub *sub, const char **out_str,
1106 uint32_t *out_len, bool *out_utf8) {
1107 988 PubSubHeader *hdr = sub->hdr;
1108 988 PubSubStrSlot *slots = (PubSubStrSlot *)sub->slots;
1109  
1110 990 ▶ for (int attempt = 0; attempt < PUBSUB_POLL_RETRIES; attempt++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int attempt = 0; attempt < PUBSUB_POLL_RETRIES; attempt++) { 990 0 990
1111 990 uint64_t cursor = sub->cursor;
1112 990 uint64_t wp = __atomic_load_n(&hdr->write_pos, __ATOMIC_ACQUIRE);
1113  
1114 990 ▶ if (cursor >= wp) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (cursor >= wp) return 0; 22 968 990
1115  
1116 968 ▶ if (wp - cursor > sub->capacity) {
Branch: 1 branch
BranchTrueFalseTotal
if (wp - cursor > sub->capacity) { 2 966 968
1117 2 sub->overflow_count += wp - cursor - sub->capacity;
1118 2 sub->cursor = wp - sub->capacity;
1119 2 continue;
1120 }
1121  
1122 966 uint32_t idx = cursor & sub->cap_mask;
1123 966 PubSubStrSlot *slot = &slots[idx];
1124  
1125 966 uint64_t seq1 = __atomic_load_n(&slot->sequence, __ATOMIC_ACQUIRE);
1126 966 ▶ if (__builtin_expect(seq1 != cursor + 1, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (__builtin_expect(seq1 != cursor + 1, 0)) { 0 966 966
1127 0 ▶ if (seq1 > cursor + 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (seq1 > cursor + 1) { 0 0 0
1128 0 wp = __atomic_load_n(&hdr->write_pos, __ATOMIC_ACQUIRE);
1129 0 ▶ uint64_t new_cursor = wp > sub->capacity ? wp - sub->capacity : 0;
Branch: 1 branch
BranchTrueFalseTotal
uint64_t new_cursor = wp > sub->capacity ? wp - sub->capacity : 0; 0 0 0
1130 0 ▶ if (new_cursor > cursor) {
Branch: 1 branch
BranchTrueFalseTotal
if (new_cursor > cursor) { 0 0 0
1131 0 sub->overflow_count += new_cursor - cursor;
1132 0 sub->cursor = new_cursor;
1133 }
1134 0 continue;
1135 }
1136 0 return 0;
1137 }
1138  
1139 966 uint32_t plen = slot->packed_len;
1140 966 uint32_t aoff = slot->arena_off;
1141 966 uint32_t len = plen & PUBSUB_STR_LEN_MASK;
1142 966 bool utf8 = (plen & PUBSUB_STR_UTF8_FLAG) != 0;
1143  
1144 /* Safety: bound the file-stored length and arena offset against the
1145 * subscriber's cached (open-time-validated) msg_size / arena_cap
1146 * before dereferencing, so a peer that corrupted the shared header
1147 * or slot metadata cannot drive this memcpy past the mapped arena.
1148 * Cached (not live hdr->) values: a concurrent header corruption
1149 * must not be able to widen the bound. Never taken for valid data. */
1150 966 ▶ if (len > sub->msg_size) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (len > sub->msg_size) continue; 0 966 966
1151 966 ▶ if ((uint64_t)aoff + len > sub->arena_cap) continue;
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)aoff + len > sub->arena_cap) continue; 0 966 966
1152  
1153 966 ▶ if (!pubsub_ensure_copy_buf(sub, len + 1)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_ensure_copy_buf(sub, len + 1)) return 0; 0 966 966
1154  
1155 966 ▶ if (len > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (len > 0) 963 3 966
1156 963 memcpy(sub->copy_buf, sub->data + aoff, len);
1157 966 sub->copy_buf[len] = '\0';
1158  
1159 966 __atomic_thread_fence(__ATOMIC_ACQUIRE);
1160 966 uint64_t seq2 = __atomic_load_n(&slot->sequence, __ATOMIC_RELAXED);
1161 966 ▶ if (seq2 != seq1) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (seq2 != seq1) continue; 0 966 966
1162  
1163 966 *out_str = sub->copy_buf;
1164 966 *out_len = len;
1165 966 *out_utf8 = utf8;
1166 966 sub->cursor = cursor + 1;
1167 966 return 1;
1168 }
1169 0 return 0;
1170 }
1171  
1172 55 static int pubsub_str_poll_wait(PubSubSub *sub, const char **out_str,
1173 uint32_t *out_len, bool *out_utf8,
1174 double timeout) {
1175 55 int r = pubsub_str_poll(sub, out_str, out_len, out_utf8);
1176 55 ▶ if (r != 0) return r;
Branch: 1 branch
BranchTrueFalseTotal
if (r != 0) return r; 50 5 55
1177 5 ▶ if (timeout == 0.0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (timeout == 0.0) return 0; 0 5 5
1178  
1179 5 PubSubHeader *hdr = sub->hdr;
1180 struct timespec deadline, remaining;
1181 5 int has_deadline = (timeout > 0);
1182 5 ▶ if (has_deadline) pubsub_make_deadline(timeout, &deadline);
Branch: 1 branch
BranchTrueFalseTotal
if (has_deadline) pubsub_make_deadline(timeout, &deadline); 5 0 5
1183  
1184 0 for (;;) {
1185 /* See pubsub_int_poll_wait above for the SEQ_CST ordering rationale. */
1186 5 __atomic_add_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST);
1187 5 uint32_t fseq = __atomic_load_n(&hdr->sub_futex, __ATOMIC_ACQUIRE);
1188 5 r = pubsub_str_poll(sub, out_str, out_len, out_utf8);
1189 5 ▶ if (r != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (r != 0) { 1 4 5
1190 1 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST);
1191 1 return r;
1192 }
1193  
1194 4 struct timespec *pts = NULL;
1195 4 ▶ if (has_deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (has_deadline) { 4 0 4
1196 4 ▶ if (!pubsub_remaining_time(&deadline, &remaining)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pubsub_remaining_time(&deadline, &remaining)) { 0 4 4
1197 0 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST);
1198 0 return 0;
1199 }
1200 4 pts = &remaining;
1201 }
1202 4 long rc = syscall(SYS_futex, &hdr->sub_futex, FUTEX_WAIT,
1203 fseq, pts, NULL, 0);
1204 4 int wait_errno = errno;
1205 4 __atomic_sub_fetch(&hdr->sub_waiters, 1, __ATOMIC_SEQ_CST);
1206 4 ▶ if (PUBSUB_WAIT_INTERRUPTED()) { errno = EINTR; return -1; }
Branch: 1 branch
BranchTrueFalseTotal
if (PUBSUB_WAIT_INTERRUPTED()) { errno = EINTR; return -1; } 0 4 4
1207  
1208 4 r = pubsub_str_poll(sub, out_str, out_len, out_utf8);
1209 4 ▶ if (r != 0) return r;
Branch: 1 branch
BranchTrueFalseTotal
if (r != 0) return r; 3 1 4
1210 1 ▶ if (rc == -1 && wait_errno == ETIMEDOUT) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (rc == -1 && wait_errno == ETIMEDOUT) return 0; 1 0 1
if (rc == -1 && wait_errno == ETIMEDOUT) return 0; 1 0 1
1211 }
1212 }
1213  
1214 /* ================================================================
1215 * Common operations
1216 * ================================================================ */
1217  
1218 8 static void pubsub_clear_locked(PubSubHandle *h) {
1219 8 PubSubHeader *hdr = h->hdr;
1220 /* Zero all slot sequences */
1221 8 uint32_t cap = h->capacity;
1222 8 ▶ if (h->mode == PUBSUB_MODE_INT) {
Branch: 1 branch
BranchTrueFalseTotal
if (h->mode == PUBSUB_MODE_INT) { 4 4 8
1223 4 PubSubIntSlot *s = (PubSubIntSlot *)h->slots;
1224 260 ▶ for (uint32_t i = 0; i < cap; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < cap; i++) 256 4 260
1225 256 __atomic_store_n(&s[i].sequence, 0, __ATOMIC_RELAXED);
1226 4 ▶ } else if (h->mode == PUBSUB_MODE_INT32) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->mode == PUBSUB_MODE_INT32) { 1 3 4
1227 1 PubSubInt32Slot *s = (PubSubInt32Slot *)h->slots;
1228 65 ▶ for (uint32_t i = 0; i < cap; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < cap; i++) 64 1 65
1229 64 __atomic_store_n(&s[i].sequence, 0, __ATOMIC_RELAXED);
1230 3 ▶ } else if (h->mode == PUBSUB_MODE_INT16) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (h->mode == PUBSUB_MODE_INT16) { 1 2 3
1231 1 PubSubInt16Slot *s = (PubSubInt16Slot *)h->slots;
1232 65 ▶ for (uint32_t i = 0; i < cap; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < cap; i++) 64 1 65
1233 64 __atomic_store_n(&s[i].sequence, 0, __ATOMIC_RELAXED);
1234 } else {
1235 2 PubSubStrSlot *s = (PubSubStrSlot *)h->slots;
1236 82 ▶ for (uint32_t i = 0; i < cap; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (uint32_t i = 0; i < cap; i++) 80 2 82
1237 80 __atomic_store_n(&s[i].sequence, 0, __ATOMIC_RELAXED);
1238 }
1239  
1240 /* Rewind only once no slot holds a later lap: stale sequences past a rewound
1241 * write_pos make every new int publish into them a silent drop. */
1242 8 __atomic_thread_fence(__ATOMIC_RELEASE);
1243 8 __atomic_store_n(&hdr->write_pos, 0, __ATOMIC_RELAXED);
1244 8 __atomic_store_n(&hdr->stat_publish_ok, 0, __ATOMIC_RELAXED);
1245 8 ▶ if (h->mode == PUBSUB_MODE_STR)
Branch: 1 branch
BranchTrueFalseTotal
if (h->mode == PUBSUB_MODE_STR) 2 6 8
1246 2 __atomic_store_n(&hdr->arena_wpos, 0, __ATOMIC_RELAXED);
1247  
1248 8 pubsub_wake_subscribers(hdr);
1249 8 }
1250  
1251 6 static void pubsub_clear(PubSubHandle *h) {
1252 6 ▶ if (h->mode == PUBSUB_MODE_STR) pubsub_mutex_lock(h->hdr);
Branch: 1 branch
BranchTrueFalseTotal
if (h->mode == PUBSUB_MODE_STR) pubsub_mutex_lock(h->hdr); 0 6 6
1253 6 pubsub_clear_locked(h);
1254 6 ▶ if (h->mode == PUBSUB_MODE_STR) pubsub_mutex_unlock(h->hdr);
Branch: 1 branch
BranchTrueFalseTotal
if (h->mode == PUBSUB_MODE_STR) pubsub_mutex_unlock(h->hdr); 0 6 6
1255 6 }
1256  
1257  
1258 7 static inline int pubsub_sync(PubSubHandle *h) {
1259 7 return msync(h->hdr, h->mmap_size, MS_SYNC);
1260 }
1261  
1262 21 static inline int pubsub_eventfd_create(PubSubHandle *h) {
1263 21 ▶ if (h->notify_fd >= 0) return h->notify_fd;
Branch: 1 branch
BranchTrueFalseTotal
if (h->notify_fd >= 0) return h->notify_fd; 0 21 21
1264 21 h->notify_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
1265 21 return h->notify_fd;
1266 }
1267  
1268 21 static inline int pubsub_eventfd_set(PubSubHandle *h, int fd) {
1269 21 ▶ if (h->notify_fd == fd) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (h->notify_fd == fd) return 0; 5 16 21
1270 16 ▶ int myfd = fd < 0 ? -1 : fcntl(fd, F_DUPFD_CLOEXEC, 0);
Branch: 1 branch
BranchTrueFalseTotal
int myfd = fd < 0 ? -1 : fcntl(fd, F_DUPFD_CLOEXEC, 0); 12 4 16
1271 16 ▶ if (fd >= 0 && myfd < 0) return -1;
Branch: 2 branches
BranchTrueFalseTotal
if (fd >= 0 && myfd < 0) return -1; 12 4 16
if (fd >= 0 && myfd < 0) return -1; 4 8 12
1272 12 ▶ if (h->notify_fd >= 0) close(h->notify_fd);
Branch: 1 branch
BranchTrueFalseTotal
if (h->notify_fd >= 0) close(h->notify_fd); 4 8 12
1273 12 h->notify_fd = myfd;
1274 12 return 0;
1275 }
1276  
1277 26 static inline void pubsub_notify_fd(int fd) {
1278 26 ▶ if (fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fd >= 0) { 25 1 26
1279 25 uint64_t one = 1;
1280 25 ssize_t __attribute__((unused)) rc = write(fd, &one, sizeof(one));
1281 }
1282 26 }
1283  
1284 21 static inline void pubsub_notify(PubSubHandle *h) {
1285 21 pubsub_notify_fd(h->notify_fd);
1286 21 }
1287  
1288 22 static inline int64_t pubsub_eventfd_consume(PubSubHandle *h) {
1289 22 ▶ if (h->notify_fd < 0) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (h->notify_fd < 0) return -1; 0 22 22
1290 22 uint64_t val = 0;
1291 22 ▶ if (read(h->notify_fd, &val, sizeof(val)) != sizeof(val)) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (read(h->notify_fd, &val, sizeof(val)) != sizeof(val)) return -1; 4 18 22
1292 18 return (int64_t)val;
1293 }
1294  
1295 12 static inline void pubsub_sub_eventfd_consume(PubSubSub *sub) {
1296 12 ▶ if (sub->notify_fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (sub->notify_fd >= 0) { 12 0 12
1297 uint64_t val;
1298 12 ssize_t __attribute__((unused)) rc = read(sub->notify_fd, &val, sizeof(val));
1299 }
1300 12 }
1301  
1302 #endif /* PUBSUB_H */
« Shared.xs ↑ Summary blib/lib/Data/PubSub/Shared/Int.pm »