File Coverage

stack.h
Criterion Covered Total %
statement 194 224 86.6
branch 91 206 44.1
condition n/a
subroutine n/a
pod n/a
total 285 430 66.2


line stmt bran cond sub pod time code
1             /*
2             * stack.h -- Fixed-size shared-memory LIFO stack for Linux
3             *
4             * CAS-based lock-free push/pop on atomic top index.
5             * Futex blocking when empty (pop) or full (push).
6             *
7             * Variants: Int (int64_t), Str (length-prefixed)
8             */
9              
10             #ifndef STACK_H
11             #define STACK_H
12              
13             #include
14             #include
15             #include
16             #include
17             #include
18             #include
19             #include
20             #include
21             #include
22             #include
23             #include
24             #include
25             #include
26             #include
27             #include
28              
29             #define STK_MAGIC 0x53544B31U /* "STK1" */
30             #define STK_VERSION 1
31             #define STK_ERR_BUFLEN 256
32              
33             #define STK_VAR_INT 0
34             #define STK_VAR_STR 1
35              
36             /* ================================================================
37             * Header (128 bytes)
38             * ================================================================ */
39              
40             typedef struct {
41             uint32_t magic;
42             uint32_t version;
43             uint32_t elem_size;
44             uint32_t variant_id;
45             uint64_t capacity;
46             uint64_t total_size;
47             uint64_t data_off;
48             uint8_t _pad0[24];
49              
50             uint32_t top; /* 64: next free index (0=empty, capacity=full) */
51             uint32_t waiters_push; /* 68 */
52             uint32_t waiters_pop; /* 72 */
53             uint32_t _pad1; /* 76 */
54             uint64_t stat_pushes; /* 80 */
55             uint64_t stat_pops; /* 88 */
56             uint64_t stat_waits; /* 96 */
57             uint64_t stat_timeouts; /* 104 */
58             uint8_t _pad2[16]; /* 112-127 */
59             } StkHeader;
60              
61             #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
62             _Static_assert(sizeof(StkHeader) == 128, "StkHeader must be 128 bytes");
63             #endif
64              
65             typedef struct {
66             StkHeader *hdr;
67             uint8_t *data;
68             size_t mmap_size;
69             uint32_t elem_size; /* cached from header at open time */
70             char *path;
71             int notify_fd;
72             int backing_fd;
73             } StkHandle;
74              
75             /* ================================================================
76             * Utility
77             * ================================================================ */
78              
79 3           static inline void stk_make_deadline(double timeout, struct timespec *dl) {
80 3           clock_gettime(CLOCK_MONOTONIC, dl);
81 3           dl->tv_sec += (time_t)timeout;
82 3           dl->tv_nsec += (long)((timeout - (double)(time_t)timeout) * 1e9);
83 3 50         if (dl->tv_nsec >= 1000000000L) { dl->tv_sec++; dl->tv_nsec -= 1000000000L; }
84 3           }
85              
86 5           static inline int stk_remaining(const struct timespec *dl, struct timespec *rem) {
87             struct timespec now;
88 5           clock_gettime(CLOCK_MONOTONIC, &now);
89 5           rem->tv_sec = dl->tv_sec - now.tv_sec;
90 5           rem->tv_nsec = dl->tv_nsec - now.tv_nsec;
91 5 100         if (rem->tv_nsec < 0) { rem->tv_sec--; rem->tv_nsec += 1000000000L; }
92 5           return rem->tv_sec >= 0;
93             }
94              
95 63           static inline uint8_t *stk_slot(StkHandle *h, uint32_t idx) {
96 63           return h->data + (uint64_t)idx * h->elem_size;
97             }
98              
99             /* ================================================================
100             * Push (LIFO top++)
101             * ================================================================ */
102              
103 43           static inline int stk_try_push(StkHandle *h, const void *val, uint32_t vlen) {
104 43           StkHeader *hdr = h->hdr;
105 0           for (;;) {
106 43           uint32_t t = __atomic_load_n(&hdr->top, __ATOMIC_RELAXED);
107 83 100         if (t >= (uint32_t)hdr->capacity) return 0;
108 40 50         if (__atomic_compare_exchange_n(&hdr->top, &t, t + 1,
109             1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
110 40           uint32_t sz = h->elem_size;
111 40           uint32_t cp = vlen < sz ? vlen : sz;
112 40           memcpy(stk_slot(h, t), val, cp);
113 40 50         if (cp < sz) memset(stk_slot(h, t) + cp, 0, sz - cp);
114 40           __atomic_thread_fence(__ATOMIC_RELEASE);
115 40           __atomic_add_fetch(&hdr->stat_pushes, 1, __ATOMIC_RELAXED);
116 40 50         if (__atomic_load_n(&hdr->waiters_pop, __ATOMIC_RELAXED) > 0)
117 0           syscall(SYS_futex, &hdr->top, FUTEX_WAKE, 1, NULL, NULL, 0);
118 40           return 1;
119             }
120             }
121             }
122              
123 1           static inline int stk_push(StkHandle *h, const void *val, uint32_t vlen, double timeout) {
124 1 50         if (stk_try_push(h, val, vlen)) return 1;
125 1 50         if (timeout == 0) return 0;
126              
127 1           StkHeader *hdr = h->hdr;
128             struct timespec dl, rem;
129 1           int has_dl = (timeout > 0);
130 1 50         if (has_dl) stk_make_deadline(timeout, &dl);
131 1           __atomic_add_fetch(&hdr->stat_waits, 1, __ATOMIC_RELAXED);
132              
133 0           for (;;) {
134 1           __atomic_add_fetch(&hdr->waiters_push, 1, __ATOMIC_RELEASE);
135 1           uint32_t t = __atomic_load_n(&hdr->top, __ATOMIC_ACQUIRE);
136 1 50         if (t >= (uint32_t)hdr->capacity) {
137 1           struct timespec *pts = NULL;
138 1 50         if (has_dl) {
139 1 50         if (!stk_remaining(&dl, &rem)) {
140 0           __atomic_sub_fetch(&hdr->waiters_push, 1, __ATOMIC_RELAXED);
141 0           __atomic_add_fetch(&hdr->stat_timeouts, 1, __ATOMIC_RELAXED);
142 0           return 0;
143             }
144 1           pts = &rem;
145             }
146 1           syscall(SYS_futex, &hdr->top, FUTEX_WAIT, t, pts, NULL, 0);
147             }
148 1           __atomic_sub_fetch(&hdr->waiters_push, 1, __ATOMIC_RELAXED);
149 1 50         if (stk_try_push(h, val, vlen)) return 1;
150 1 50         if (has_dl && !stk_remaining(&dl, &rem)) {
    50          
151 1           __atomic_add_fetch(&hdr->stat_timeouts, 1, __ATOMIC_RELAXED);
152 1           return 0;
153             }
154             }
155             }
156              
157             /* ================================================================
158             * Pop (LIFO top--) — read slot BEFORE CAS to avoid race with pusher
159             * ================================================================ */
160              
161 27           static inline int stk_try_pop(StkHandle *h, void *out) {
162 27           StkHeader *hdr = h->hdr;
163 0           for (;;) {
164 27           uint32_t t = __atomic_load_n(&hdr->top, __ATOMIC_ACQUIRE);
165 48 100         if (t == 0) return 0;
166 21 50         if (__atomic_compare_exchange_n(&hdr->top, &t, t - 1,
167             1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
168             /* Read-after-CAS avoids ABA (read-before-CAS can return
169             * stale data when the slot is recycled). Under extreme
170             * contention a concurrent push can race on the same slot;
171             * this is a known limitation of lock-free array stacks. */
172 21           memcpy(out, stk_slot(h, t - 1), h->elem_size);
173 21           __atomic_add_fetch(&hdr->stat_pops, 1, __ATOMIC_RELAXED);
174 21 50         if (__atomic_load_n(&hdr->waiters_push, __ATOMIC_RELAXED) > 0)
175 0           syscall(SYS_futex, &hdr->top, FUTEX_WAKE, 1, NULL, NULL, 0);
176 21           return 1;
177             }
178             }
179             }
180              
181 2           static inline int stk_pop(StkHandle *h, void *out, double timeout) {
182 2 50         if (stk_try_pop(h, out)) return 1;
183 2 50         if (timeout == 0) return 0;
184              
185 2           StkHeader *hdr = h->hdr;
186             struct timespec dl, rem;
187 2           int has_dl = (timeout > 0);
188 2 50         if (has_dl) stk_make_deadline(timeout, &dl);
189 2           __atomic_add_fetch(&hdr->stat_waits, 1, __ATOMIC_RELAXED);
190              
191 0           for (;;) {
192 2           __atomic_add_fetch(&hdr->waiters_pop, 1, __ATOMIC_RELEASE);
193 2           uint32_t t = __atomic_load_n(&hdr->top, __ATOMIC_ACQUIRE);
194 2 50         if (t == 0) {
195 2           struct timespec *pts = NULL;
196 2 50         if (has_dl) {
197 2 50         if (!stk_remaining(&dl, &rem)) {
198 0           __atomic_sub_fetch(&hdr->waiters_pop, 1, __ATOMIC_RELAXED);
199 0           __atomic_add_fetch(&hdr->stat_timeouts, 1, __ATOMIC_RELAXED);
200 0           return 0;
201             }
202 2           pts = &rem;
203             }
204 2           syscall(SYS_futex, &hdr->top, FUTEX_WAIT, 0, pts, NULL, 0);
205             }
206 2           __atomic_sub_fetch(&hdr->waiters_pop, 1, __ATOMIC_RELAXED);
207 2 100         if (stk_try_pop(h, out)) return 1;
208 1 50         if (has_dl && !stk_remaining(&dl, &rem)) {
    50          
209 1           __atomic_add_fetch(&hdr->stat_timeouts, 1, __ATOMIC_RELAXED);
210 1           return 0;
211             }
212             }
213             }
214              
215             /* ================================================================
216             * Peek / Status
217             * ================================================================ */
218              
219 2           static inline int stk_peek(StkHandle *h, void *out) {
220 2           uint32_t t = __atomic_load_n(&h->hdr->top, __ATOMIC_ACQUIRE);
221 2 50         if (t == 0) return 0;
222 2           memcpy(out, stk_slot(h, t - 1), h->elem_size);
223 2           return 1;
224             }
225              
226 12           static inline uint32_t stk_size(StkHandle *h) {
227 12           return __atomic_load_n(&h->hdr->top, __ATOMIC_RELAXED);
228             }
229              
230             /* ================================================================
231             * Create / Open / Close
232             * ================================================================ */
233              
234             #define STK_ERR(fmt, ...) do { if (errbuf) snprintf(errbuf, STK_ERR_BUFLEN, fmt, ##__VA_ARGS__); } while(0)
235              
236 8           static inline void stk_init_header(void *base, uint64_t total,
237             uint32_t elem_size, uint32_t variant_id,
238             uint64_t capacity) {
239 8           StkHeader *hdr = (StkHeader *)base;
240 8           memset(base, 0, (size_t)total);
241 8           hdr->magic = STK_MAGIC;
242 8           hdr->version = STK_VERSION;
243 8           hdr->elem_size = elem_size;
244 8           hdr->variant_id = variant_id;
245 8           hdr->capacity = capacity;
246 8           hdr->total_size = total;
247 8           hdr->data_off = sizeof(StkHeader);
248 8           __atomic_thread_fence(__ATOMIC_SEQ_CST);
249 8           }
250              
251 10           static inline StkHandle *stk_setup(void *base, size_t msize,
252             const char *path, int bfd) {
253 10           StkHeader *hdr = (StkHeader *)base;
254 10           StkHandle *h = (StkHandle *)calloc(1, sizeof(StkHandle));
255 10 50         if (!h) { munmap(base, msize); return NULL; }
256 10           h->hdr = hdr;
257 10           h->data = (uint8_t *)base + hdr->data_off;
258 10           h->mmap_size = msize;
259 10           h->elem_size = hdr->elem_size; /* cached — safe from shared-mem tampering */
260 10 100         h->path = path ? strdup(path) : NULL;
261 10           h->notify_fd = -1;
262 10           h->backing_fd = bfd;
263 10           return h;
264             }
265              
266 8           static StkHandle *stk_create(const char *path, uint64_t capacity,
267             uint32_t elem_size, uint32_t variant_id,
268             char *errbuf) {
269 8 50         if (errbuf) errbuf[0] = '\0';
270 8 50         if (capacity == 0) { STK_ERR("capacity must be > 0"); return NULL; }
    0          
271 8 50         if (elem_size == 0) { STK_ERR("elem_size must be > 0"); return NULL; }
    0          
272 8 50         if (elem_size > 0 && capacity > (UINT64_MAX - sizeof(StkHeader)) / elem_size) {
    50          
273 0 0         STK_ERR("capacity * elem_size overflow"); return NULL;
274             }
275              
276 8           uint64_t total = sizeof(StkHeader) + capacity * elem_size;
277 8           int anonymous = (path == NULL);
278 8           int fd = -1;
279             size_t map_size;
280             void *base;
281              
282 8 100         if (anonymous) {
283 5           map_size = (size_t)total;
284 5           base = mmap(NULL, map_size, PROT_READ|PROT_WRITE,
285             MAP_SHARED|MAP_ANONYMOUS, -1, 0);
286 5 50         if (base == MAP_FAILED) { STK_ERR("mmap: %s", strerror(errno)); return NULL; }
    0          
287             } else {
288 3           fd = open(path, O_RDWR|O_CREAT, 0666);
289 4 50         if (fd < 0) { STK_ERR("open(%s): %s", path, strerror(errno)); return NULL; }
    0          
290 3 50         if (flock(fd, LOCK_EX) < 0) { STK_ERR("flock: %s", strerror(errno)); close(fd); return NULL; }
    0          
291              
292             struct stat st;
293 3 50         if (fstat(fd, &st) < 0) {
294 0 0         STK_ERR("fstat: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL;
295             }
296 3           int is_new = (st.st_size == 0);
297              
298 3 100         if (is_new) {
299 2 50         if (ftruncate(fd, (off_t)total) < 0) {
300 0 0         STK_ERR("ftruncate: %s", strerror(errno));
301 0           flock(fd, LOCK_UN); close(fd); return NULL;
302             }
303             }
304 3 100         map_size = is_new ? (size_t)total : (size_t)st.st_size;
305 3           base = mmap(NULL, map_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
306 3 50         if (base == MAP_FAILED) { STK_ERR("mmap: %s", strerror(errno)); flock(fd, LOCK_UN); close(fd); return NULL; }
    0          
307              
308 3 100         if (!is_new) {
309 1           StkHeader *hdr = (StkHeader *)base;
310 1 50         if (hdr->magic != STK_MAGIC || hdr->version != STK_VERSION ||
    50          
311 1 50         hdr->variant_id != variant_id ||
312 1 50         hdr->total_size != (uint64_t)st.st_size) {
313 0 0         STK_ERR("invalid or incompatible stack file");
314 0           munmap(base, map_size); flock(fd, LOCK_UN); close(fd); return NULL;
315             }
316 1           flock(fd, LOCK_UN); close(fd);
317 1           return stk_setup(base, map_size, path, -1);
318             }
319             }
320              
321 7           stk_init_header(base, total, elem_size, variant_id, capacity);
322 7 100         if (fd >= 0) { flock(fd, LOCK_UN); close(fd); }
323 7           return stk_setup(base, map_size, path, -1);
324             }
325              
326 1           static StkHandle *stk_create_memfd(const char *name, uint64_t capacity,
327             uint32_t elem_size, uint32_t variant_id,
328             char *errbuf) {
329 1 50         if (errbuf) errbuf[0] = '\0';
330 1 50         if (capacity == 0) { STK_ERR("capacity must be > 0"); return NULL; }
    0          
331 1 50         if (elem_size == 0) { STK_ERR("elem_size must be > 0"); return NULL; }
    0          
332 1 50         if (elem_size > 0 && capacity > (UINT64_MAX - sizeof(StkHeader)) / elem_size) {
    50          
333 0 0         STK_ERR("capacity * elem_size overflow"); return NULL;
334             }
335              
336 1           uint64_t total = sizeof(StkHeader) + capacity * elem_size;
337 1 50         int fd = memfd_create(name ? name : "stack", MFD_CLOEXEC);
338 1 50         if (fd < 0) { STK_ERR("memfd_create: %s", strerror(errno)); return NULL; }
    0          
339 1 50         if (ftruncate(fd, (off_t)total) < 0) { STK_ERR("ftruncate: %s", strerror(errno)); close(fd); return NULL; }
    0          
340 1           void *base = mmap(NULL, (size_t)total, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
341 1 50         if (base == MAP_FAILED) { STK_ERR("mmap: %s", strerror(errno)); close(fd); return NULL; }
    0          
342 1           stk_init_header(base, total, elem_size, variant_id, capacity);
343 1           return stk_setup(base, (size_t)total, NULL, fd);
344             }
345              
346 1           static StkHandle *stk_open_fd(int fd, uint32_t variant_id, char *errbuf) {
347 1 50         if (errbuf) errbuf[0] = '\0';
348             struct stat st;
349 1 50         if (fstat(fd, &st) < 0) { STK_ERR("fstat: %s", strerror(errno)); return NULL; }
    0          
350 1 50         if ((uint64_t)st.st_size < sizeof(StkHeader)) { STK_ERR("too small"); return NULL; }
    0          
351 1           size_t ms = (size_t)st.st_size;
352 1           void *base = mmap(NULL, ms, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
353 1 50         if (base == MAP_FAILED) { STK_ERR("mmap: %s", strerror(errno)); return NULL; }
    0          
354 1           StkHeader *hdr = (StkHeader *)base;
355 1 50         if (hdr->magic != STK_MAGIC || hdr->version != STK_VERSION ||
    50          
356 1 50         hdr->variant_id != variant_id ||
357 1 50         hdr->total_size != (uint64_t)st.st_size) {
358 0 0         STK_ERR("invalid stack"); munmap(base, ms); return NULL;
359             }
360 1           int myfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
361 1 50         if (myfd < 0) { STK_ERR("fcntl: %s", strerror(errno)); munmap(base, ms); return NULL; }
    0          
362 1           return stk_setup(base, ms, NULL, myfd);
363             }
364              
365 10           static void stk_destroy(StkHandle *h) {
366 10 50         if (!h) return;
367 10 100         if (h->notify_fd >= 0) close(h->notify_fd);
368 10 100         if (h->backing_fd >= 0) close(h->backing_fd);
369 10 50         if (h->hdr) munmap(h->hdr, h->mmap_size);
370 10           free(h->path);
371 10           free(h);
372             }
373              
374             /* NOT concurrency-safe — use drain() for concurrent scenarios */
375 3           static void stk_clear(StkHandle *h) {
376 3           __atomic_store_n(&h->hdr->top, 0, __ATOMIC_RELEASE);
377 3 50         if (__atomic_load_n(&h->hdr->waiters_push, __ATOMIC_RELAXED) > 0 ||
378 3 50         __atomic_load_n(&h->hdr->waiters_pop, __ATOMIC_RELAXED) > 0)
379 0           syscall(SYS_futex, &h->hdr->top, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
380 3           }
381              
382             /* Concurrency-safe drain: CAS top to 0, returns count drained */
383 0           static inline uint32_t stk_drain(StkHandle *h) {
384 0           StkHeader *hdr = h->hdr;
385 0           for (;;) {
386 0           uint32_t t = __atomic_load_n(&hdr->top, __ATOMIC_RELAXED);
387 0 0         if (t == 0) return 0;
388 0 0         if (__atomic_compare_exchange_n(&hdr->top, &t, 0,
389             1, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) {
390 0 0         if (__atomic_load_n(&hdr->waiters_push, __ATOMIC_RELAXED) > 0)
391 0           syscall(SYS_futex, &hdr->top, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
392 0           return t;
393             }
394             }
395             }
396              
397             /* eventfd */
398 1           static int stk_create_eventfd(StkHandle *h) {
399 1 50         if (h->notify_fd >= 0) close(h->notify_fd);
400 1           int efd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
401 1 50         if (efd < 0) return -1;
402 1           h->notify_fd = efd;
403 1           return efd;
404             }
405 2           static int stk_notify(StkHandle *h) {
406 2 50         if (h->notify_fd < 0) return 0;
407 2           uint64_t v = 1;
408 2           return write(h->notify_fd, &v, sizeof(v)) == sizeof(v);
409             }
410 1           static int64_t stk_eventfd_consume(StkHandle *h) {
411 1 50         if (h->notify_fd < 0) return -1;
412 1           uint64_t v = 0;
413 1 50         if (read(h->notify_fd, &v, sizeof(v)) != sizeof(v)) return -1;
414 1           return (int64_t)v;
415             }
416 1           static void stk_msync(StkHandle *h) { msync(h->hdr, h->mmap_size, MS_SYNC); }
417              
418             #endif /* STACK_H */