1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
|
#define _GNU_SOURCE
#define _DARWIN_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#include "common/loop.h"
#include "platform/sync.h"
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define YASL_LOOP_INIT_CAP 32
typedef int (*yasl_loop_fd_fn)(int fd, short revents, void *ud);
struct yasl_fd_source {
yasl_loop_fd_fn fn;
void *ud;
int id;
int fd;
short events;
};
struct yasl_timer_source {
yasl_timer_cb fn;
void *ud;
uint64_t interval_ns;
uint64_t deadline_ns;
yasl_timer_id id;
bool deleted;
};
struct yasl_post {
void (*fn)(void *ud);
void *ud;
struct yasl_post *next;
};
/* Signals this loop watches; the previous actions are restored on unwatch. */
struct yasl_signal_watch {
void (*cb)(void *ud, int signo);
void *ud;
int count;
int signals[NSIG];
struct sigaction old[NSIG];
};
struct yasl_loop {
struct yasl_fd_source *fds;
struct pollfd *pollfds;
int count;
int capacity;
int next_id;
bool running;
int wake_rfd;
int wake_wfd;
int wake_watch;
struct yasl_timer_source *timers;
int timer_count;
int timer_capacity;
uint32_t next_timer_id;
int timer_firing_depth;
yasl_mutex post_mutex;
struct yasl_post *post_head;
struct yasl_post *post_tail;
struct yasl_signal_watch *signals;
};
/* Handlers run on any thread, so they only touch lock-free atomics: they mark
* the signal pending and write to the owning loop's wake pipe. The pipe is
* stored as fd + 1 so that the zero initializer means no pipe. */
static atomic_int signal_wake_fd[NSIG];
static atomic_bool signal_pending[NSIG];
static struct yasl_loop *signal_owner[NSIG];
uint64_t yasl_loop_now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
static void run_posts(struct yasl_loop *l)
{
yasl_mutex_lock(&l->post_mutex);
struct yasl_post *p = l->post_head;
l->post_head = l->post_tail = NULL;
yasl_mutex_unlock(&l->post_mutex);
while (p) {
struct yasl_post *next = p->next;
p->fn(p->ud);
free(p);
p = next;
}
}
static void run_signals(struct yasl_loop *l)
{
/* A callback may unwatch, so re-check the watch before each delivery. */
for (int signo = 1; signo < NSIG; signo++) {
struct yasl_signal_watch *w = l->signals;
if (!w) return;
if (signal_owner[signo] != l || !atomic_exchange(&signal_pending[signo], false))
continue;
w->cb(w->ud, signo);
}
}
static int loop_wake_cb(int fd, short revents, void *ud)
{
(void)revents;
char buf[128];
ssize_t n;
while ((n = read(fd, buf, sizeof(buf))) > 0 || (n < 0 && errno == EINTR)) {}
struct yasl_loop *l = ud;
run_posts(l);
run_signals(l);
return 0;
}
struct yasl_loop *yasl_loop_create(void)
{
struct yasl_loop *l = calloc(1, sizeof(*l));
if (!l) return NULL;
l->capacity = YASL_LOOP_INIT_CAP;
l->fds = malloc((size_t)l->capacity * sizeof(*l->fds));
l->pollfds = malloc((size_t)l->capacity * sizeof(*l->pollfds));
if (!l->fds || !l->pollfds) {
free(l->fds);
free(l->pollfds);
free(l);
return NULL;
}
if (yasl_mutex_init(&l->post_mutex) != 0) {
free(l->fds);
free(l->pollfds);
free(l);
return NULL;
}
l->next_id = 1;
l->next_timer_id = 1;
l->wake_rfd = -1;
l->wake_wfd = -1;
int p[2];
#if defined(__linux__) && defined(O_CLOEXEC)
if (pipe2(p, O_CLOEXEC | O_NONBLOCK) == 0) {
l->wake_rfd = p[0];
l->wake_wfd = p[1];
}
#else
if (pipe(p) == 0) {
int f0 = fcntl(p[0], F_GETFL, 0);
int f1 = fcntl(p[1], F_GETFL, 0);
if (f0 >= 0) fcntl(p[0], F_SETFL, f0 | O_NONBLOCK);
if (f1 >= 0) fcntl(p[1], F_SETFL, f1 | O_NONBLOCK);
fcntl(p[0], F_SETFD, FD_CLOEXEC);
fcntl(p[1], F_SETFD, FD_CLOEXEC);
l->wake_rfd = p[0];
l->wake_wfd = p[1];
}
#endif
if (l->wake_rfd >= 0) {
l->wake_watch = yasl_loop_add_fd(l, l->wake_rfd, POLLIN, loop_wake_cb, l);
}
return l;
}
void yasl_loop_destroy(struct yasl_loop *l)
{
if (!l) return;
yasl_loop_unwatch_signals(l);
for (struct yasl_post *p = l->post_head; p;) {
struct yasl_post *next = p->next;
free(p);
p = next;
}
yasl_mutex_destroy(&l->post_mutex);
if (l->wake_watch > 0)
yasl_loop_del_fd(l, l->wake_watch);
if (l->wake_rfd >= 0)
close(l->wake_rfd);
if (l->wake_wfd >= 0)
close(l->wake_wfd);
free(l->fds);
free(l->pollfds);
free(l->timers);
free(l);
}
int yasl_loop_add_fd(struct yasl_loop *l, int fd, short events,
int (*fn)(int fd, short revents, void *ud), void *ud)
{
if (!l || fd < 0)
return -1;
if (l->count >= l->capacity) {
int new_cap = l->capacity ? l->capacity * 2 : YASL_LOOP_INIT_CAP;
struct yasl_fd_source *new_fds = realloc(l->fds, (size_t)new_cap * sizeof(*new_fds));
if (!new_fds) return -1;
l->fds = new_fds;
struct pollfd *new_pollfds = realloc(l->pollfds, (size_t)new_cap * sizeof(*new_pollfds));
if (!new_pollfds) return -1;
l->pollfds = new_pollfds;
l->capacity = new_cap;
}
int id = l->next_id++;
if (l->next_id <= 0) l->next_id = 1;
l->fds[l->count] = (struct yasl_fd_source){
.fn = fn, .ud = ud, .id = id, .fd = fd, .events = events,
};
l->pollfds[l->count] = (struct pollfd){
.fd = fd, .events = events, .revents = 0,
};
l->count++;
return id;
}
int yasl_loop_del_fd(struct yasl_loop *l, int id)
{
if (!l || id <= 0) return -1;
for (int i = 0; i < l->count; i++) {
if (l->fds[i].id == id) {
l->count--;
l->fds[i] = l->fds[l->count];
l->pollfds[i] = l->pollfds[l->count];
return 0;
}
}
return -1;
}
int yasl_loop_set_fd_events(struct yasl_loop *l, int id, short events)
{
if (!l || id <= 0) return -1;
for (int i = 0; i < l->count; i++) {
if (l->fds[i].id == id) {
l->fds[i].events = events;
l->pollfds[i].events = events;
return 0;
}
}
return -1;
}
static void wake_write(int fd)
{
/* A full pipe already wakes the loop, so EAGAIN needs no retry. */
int saved = errno;
char b = 1;
ssize_t n;
do {
n = write(fd, &b, 1);
} while (n < 0 && errno == EINTR);
errno = saved;
}
void yasl_loop_kick(struct yasl_loop *l)
{
if (!l || l->wake_wfd < 0) return;
wake_write(l->wake_wfd);
}
bool yasl_loop_post(struct yasl_loop *l, void (*fn)(void *ud), void *ud)
{
if (!l || !fn || l->wake_wfd < 0) return false;
struct yasl_post *p = malloc(sizeof(*p));
if (!p) return false;
*p = (struct yasl_post){.fn = fn, .ud = ud};
yasl_mutex_lock(&l->post_mutex);
if (l->post_tail)
l->post_tail->next = p;
else
l->post_head = p;
l->post_tail = p;
yasl_mutex_unlock(&l->post_mutex);
wake_write(l->wake_wfd);
return true;
}
static void signal_handler(int signo)
{
atomic_store(&signal_pending[signo], true);
int fd = atomic_load(&signal_wake_fd[signo]) - 1;
if (fd >= 0) wake_write(fd);
}
static bool signal_valid(int signo)
{
return signo > 0 && signo < NSIG && signo != SIGKILL && signo != SIGSTOP;
}
bool yasl_loop_watch_signals(struct yasl_loop *l, const int *signals, int n,
void (*cb)(void *ud, int signo), void *ud)
{
if (!l || !signals || n <= 0 || !cb || l->wake_wfd < 0) {
errno = EINVAL;
return false;
}
bool wanted[NSIG] = {0};
for (int i = 0; i < n; i++) {
if (!signal_valid(signals[i])) {
errno = EINVAL;
return false;
}
if (signal_owner[signals[i]] && signal_owner[signals[i]] != l) {
errno = EBUSY;
return false;
}
wanted[signals[i]] = true;
}
struct yasl_signal_watch *w = calloc(1, sizeof(*w));
if (!w) return false;
w->cb = cb;
w->ud = ud;
/* Keep the old watch's saved actions for signals that stay watched, so
* that unwatch restores what the application had before any watch. */
struct yasl_signal_watch *old = l->signals;
struct sigaction sa = {.sa_handler = signal_handler, .sa_flags = SA_RESTART};
sigemptyset(&sa.sa_mask);
for (int signo = 1; signo < NSIG; signo++) {
if (!wanted[signo]) continue;
int prev = -1;
for (int i = 0; old && i < old->count; i++)
if (old->signals[i] == signo) prev = i;
if (prev >= 0) {
w->old[w->count] = old->old[prev];
} else {
atomic_store(&signal_pending[signo], false);
atomic_store(&signal_wake_fd[signo], l->wake_wfd + 1);
if (sigaction(signo, &sa, &w->old[w->count]) != 0) {
int err = errno;
atomic_store(&signal_wake_fd[signo], 0);
for (int i = 0; i < w->count; i++) {
int done = w->signals[i];
bool kept = false;
for (int j = 0; old && j < old->count; j++)
if (old->signals[j] == done) kept = true;
if (kept) continue;
sigaction(done, &w->old[i], NULL);
atomic_store(&signal_wake_fd[done], 0);
}
free(w);
errno = err;
return false;
}
}
w->signals[w->count++] = signo;
}
/* Restore signals the old watch had that the new one drops. */
for (int i = 0; old && i < old->count; i++) {
int signo = old->signals[i];
if (wanted[signo]) continue;
sigaction(signo, &old->old[i], NULL);
atomic_store(&signal_wake_fd[signo], 0);
atomic_store(&signal_pending[signo], false);
signal_owner[signo] = NULL;
}
for (int i = 0; i < w->count; i++)
signal_owner[w->signals[i]] = l;
free(old);
l->signals = w;
return true;
}
void yasl_loop_unwatch_signals(struct yasl_loop *l)
{
if (!l || !l->signals) return;
struct yasl_signal_watch *w = l->signals;
l->signals = NULL;
for (int i = 0; i < w->count; i++) {
int signo = w->signals[i];
sigaction(signo, &w->old[i], NULL);
atomic_store(&signal_wake_fd[signo], 0);
atomic_store(&signal_pending[signo], false);
signal_owner[signo] = NULL;
}
free(w);
}
static void timer_cleanup_deleted(struct yasl_loop *l)
{
if (!l || l->timer_firing_depth > 0) return;
int dest = 0;
for (int src = 0; src < l->timer_count; src++) {
struct yasl_timer_source t = l->timers[src];
l->timers[dest] = t;
dest += !t.deleted;
}
l->timer_count = dest;
}
bool yasl_loop_timer_armed(const struct yasl_loop *l, yasl_timer_id id)
{
if (!l || id == 0) return false;
for (int i = 0; i < l->timer_count; i++)
if (l->timers[i].id == id)
return !l->timers[i].deleted;
return false;
}
int yasl_loop_poll_set(const struct yasl_loop *l, const struct pollfd **fds)
{
if (!l) {
*fds = NULL;
return 0;
}
*fds = l->pollfds;
return l->count;
}
int yasl_loop_next_timeout_ms(const struct yasl_loop *l)
{
if (!l || l->timer_count <= 0) return -1;
uint64_t now = yasl_loop_now_ns();
uint64_t min_deadline = UINT64_MAX;
bool has_active = false;
for (int i = 0; i < l->timer_count; i++) {
if (!l->timers[i].deleted) {
has_active = true;
if (l->timers[i].deadline_ns < min_deadline)
min_deadline = l->timers[i].deadline_ns;
}
}
if (!has_active) return -1;
if (min_deadline <= now) return 0;
uint64_t diff = min_deadline - now;
uint64_t ms = (diff + 999999ull) / 1000000ull;
return (ms > (uint64_t)INT_MAX) ? INT_MAX : (int)ms;
}
yasl_timer_id yasl_loop_add_timer(struct yasl_loop *l, uint64_t interval_ns,
yasl_timer_cb cb, void *ud)
{
if (!l || !cb || interval_ns == 0) return 0;
if (l->timer_count >= l->timer_capacity) {
int new_cap = l->timer_capacity ? l->timer_capacity * 2 : 16;
struct yasl_timer_source *new_timers = realloc(l->timers, (size_t)new_cap * sizeof(*new_timers));
if (!new_timers) return 0;
l->timers = new_timers;
l->timer_capacity = new_cap;
}
uint32_t id = l->next_timer_id++;
if (l->next_timer_id == 0) l->next_timer_id = 1;
uint64_t now = yasl_loop_now_ns();
l->timers[l->timer_count++] = (struct yasl_timer_source){
.fn = cb,
.ud = ud,
.id = id,
.interval_ns = interval_ns,
.deadline_ns = now + interval_ns,
.deleted = false,
};
yasl_loop_kick(l);
return id;
}
bool yasl_loop_del_timer(struct yasl_loop *l, yasl_timer_id id)
{
if (!l || id == 0) return false;
for (int i = l->timer_count - 1; i >= 0; i--) {
if (l->timers[i].id == id && !l->timers[i].deleted) {
l->timers[i].deleted = true;
if (l->timer_firing_depth == 0) {
if (i == l->timer_count - 1) {
while (l->timer_count > 0 && l->timers[l->timer_count - 1].deleted)
l->timer_count--;
} else {
timer_cleanup_deleted(l);
}
}
return true;
}
}
return false;
}
int yasl_loop_step(struct yasl_loop *l, int timeout_ms)
{
if (!l) return -1;
int timer_to = yasl_loop_next_timeout_ms(l);
int effective_timeout = timeout_ms;
if (timer_to >= 0) {
if (effective_timeout < 0 || timer_to < effective_timeout)
effective_timeout = timer_to;
}
if (l->count <= 0) {
if (effective_timeout > 0) {
struct timespec req = {
.tv_sec = effective_timeout / 1000,
.tv_nsec = (long)(effective_timeout % 1000) * 1000000L,
};
nanosleep(&req, NULL);
}
} else {
int n;
do {
n = poll(l->pollfds, (nfds_t)l->count, effective_timeout);
} while (n < 0 && errno == EINTR);
if (n < 0) return -1;
}
int handled = 0;
if (l->count > 0) {
int count = l->count;
struct yasl_fd_source sstack[32];
struct pollfd pstack[32];
struct yasl_fd_source *scopy = (count <= 32) ? sstack : malloc((size_t)count * sizeof(*scopy));
struct pollfd *pcopy = (count <= 32) ? pstack : malloc((size_t)count * sizeof(*pcopy));
if (!scopy || !pcopy) {
if (scopy && scopy != sstack) free(scopy);
if (pcopy && pcopy != pstack) free(pcopy);
return -1;
}
memcpy(scopy, l->fds, (size_t)count * sizeof(*scopy));
memcpy(pcopy, l->pollfds, (size_t)count * sizeof(*pcopy));
for (int i = 0; i < count; i++) {
if (pcopy[i].revents) {
short revents = pcopy[i].revents;
// Fast-path: check if source is still at index i before linear scan
bool valid = false;
if (i < l->count && l->fds[i].id == scopy[i].id) {
l->pollfds[i].revents = 0;
valid = true;
} else {
for (int j = 0; j < l->count; j++) {
if (l->fds[j].id == scopy[i].id) {
l->pollfds[j].revents = 0;
valid = true;
break;
}
}
}
if (valid && scopy[i].fn) {
scopy[i].fn(scopy[i].fd, revents, scopy[i].ud);
handled++;
}
}
}
if (scopy != sstack) free(scopy);
if (pcopy != pstack) free(pcopy);
}
if (l->timer_count > 0) {
uint64_t now = yasl_loop_now_ns();
l->timer_firing_depth++;
int initial_count = l->timer_count;
for (int i = 0; i < initial_count; i++) {
if (i >= l->timer_count) break;
if (l->timers[i].deleted || l->timers[i].deadline_ns > now)
continue;
yasl_timer_id tid = l->timers[i].id;
uint64_t interval = l->timers[i].interval_ns;
void *ud = l->timers[i].ud;
struct yasl_timer_source timer_src = l->timers[i];
uint64_t next_interval = timer_src.fn(ud, tid, interval);
handled++;
// Fast-path: timer is usually still at index i unless an earlier timer was deleted
if (i < l->timer_count && l->timers[i].id == tid) {
if (next_interval == 0 || l->timers[i].deleted) {
l->timers[i].deleted = true;
} else {
l->timers[i].interval_ns = next_interval;
if (l->timers[i].deadline_ns + next_interval > now)
l->timers[i].deadline_ns += next_interval;
else
l->timers[i].deadline_ns = now + next_interval;
}
} else {
for (int j = 0; j < l->timer_count; j++) {
if (l->timers[j].id == tid) {
if (next_interval == 0 || l->timers[j].deleted) {
l->timers[j].deleted = true;
} else {
l->timers[j].interval_ns = next_interval;
if (l->timers[j].deadline_ns + next_interval > now)
l->timers[j].deadline_ns += next_interval;
else
l->timers[j].deadline_ns = now + next_interval;
}
break;
}
}
}
}
l->timer_firing_depth--;
if (l->timer_firing_depth == 0) {
timer_cleanup_deleted(l);
}
}
return handled;
}
int yasl_loop_run(struct yasl_loop *l)
{
if (!l) return -1;
l->running = true;
while (l->running) {
if (yasl_loop_step(l, -1) < 0)
return -1;
}
return 0;
}
void yasl_loop_quit(struct yasl_loop *l)
{
if (l) l->running = false;
}
|