From 4e97d5930d6ea882cb3a0847725139d2a1c55618 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 16 Nov 2026 17:00:50 +0000 Subject: [PATCH] dtchat: add the poll and timer event loop (T1.2) loop.c: one poll(2) per run, monotonic one-shot timers (sorted, FIFO on equal deadlines), non-blocking wakeup pipe and safe fd dispatch when a callback removes another fd. test_loop covers timer order/cancel, timeout, wakeup, pipe, delete-in-callback, timer-added-timer, monotonicity and invalid arguments. make mcde-host exit=0; test_json, test_frame and test_loop all ok. --- lib/libDtChat/Makefile.am | 9 +- lib/libDtChat/dc_internal.h | 51 ++++- lib/libDtChat/loop.c | 362 ++++++++++++++++++++++++++++++++++++ lib/libDtChat/test_loop.c | 277 +++++++++++++++++++++++++++ 4 files changed, 695 insertions(+), 4 deletions(-) create mode 100644 lib/libDtChat/loop.c create mode 100644 lib/libDtChat/test_loop.c diff --git a/lib/libDtChat/Makefile.am b/lib/libDtChat/Makefile.am index a7879e5e..322bb78a 100644 --- a/lib/libDtChat/Makefile.am +++ b/lib/libDtChat/Makefile.am @@ -10,17 +10,20 @@ libDtChatIpc_la_SOURCES = json.c libDtChatIpc_la_LDFLAGS = -version-info 1:0:0 libDtChat_la_CPPFLAGS = -I$(top_srcdir)/include -libDtChat_la_SOURCES = core.c dc_internal.h +libDtChat_la_SOURCES = core.c loop.c dc_internal.h libDtChat_la_LIBADD = libDtChatIpc.la libDtChat_la_LDFLAGS = -version-info 1:0:0 # Built by make mcde-host as well, so tools/mcde-tests.sh finds them in # build/mcde-host; make check still builds and runs them. -noinst_PROGRAMS = test_json test_frame +noinst_PROGRAMS = test_json test_frame test_loop test_json_SOURCES = test_json.c test_json_CPPFLAGS = -I$(top_srcdir)/include test_json_LDADD = libDtChatIpc.la test_frame_SOURCES = test_frame.c test_frame_CPPFLAGS = -I$(top_srcdir)/include test_frame_LDADD = libDtChatIpc.la -TESTS = test_json test_frame +test_loop_SOURCES = test_loop.c +test_loop_CPPFLAGS = -I$(top_srcdir)/include -I$(srcdir) +test_loop_LDADD = libDtChat.la +TESTS = test_json test_frame test_loop diff --git a/lib/libDtChat/dc_internal.h b/lib/libDtChat/dc_internal.h index 5e751c0d..3202647d 100644 --- a/lib/libDtChat/dc_internal.h +++ b/lib/libDtChat/dc_internal.h @@ -3,7 +3,7 @@ * * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. * - * Nothing here is installed. The public surface is include/DtChat/*.h. + * Nothing here is installed. The public surface is include/DtChat/. */ #ifndef _DtChat_dc_internal_h #define _DtChat_dc_internal_h @@ -11,4 +11,53 @@ #include "DtChat/DtChat.h" #include "DtChat/Ipc.h" +#include + +/* + * The core's event loop: one poll(2) per run, monotonic one-shot timers and + * a wakeup pipe for the UI and for adapter threads. No Xt, no threads + * required. All functions are private to libDtChat. + */ +typedef struct DcLoop DcLoop; + +typedef void (*DcLoopFdFn)(int fd, short revents, void *arg); +typedef void (*DcLoopTimerFn)(void *arg); + +DcLoop *dc_loop_new(void); +void dc_loop_free(DcLoop *loop); + +/* milliseconds from CLOCK_MONOTONIC; never goes backwards */ +long long dc_loop_now_ms(void); + +/* + * Watch FD for EVENTS (POLLIN/POLLOUT). Returns an id for + * dc_loop_del_fd(), or -1. The id is unique among fds and timers. + */ +int dc_loop_add_fd(DcLoop *loop, int fd, short events, DcLoopFdFn fn, + void *arg); +int dc_loop_del_fd(DcLoop *loop, int id); + +/* + * One-shot timer: call FN(ARG) after DELAY_MS. DELAY_MS must be >= 0. + * Returns an id for dc_loop_del_timer(), or -1. Equal deadlines fire in + * the order they were added; a callback may add or delete timers. + */ +int dc_loop_add_timer(DcLoop *loop, long long delay_ms, DcLoopTimerFn fn, + void *arg); +int dc_loop_del_timer(DcLoop *loop, int id); + +/* Wake a blocking dc_loop_run() from another thread/signal handler. */ +int dc_loop_wake(DcLoop *loop); + +/* Read end of the wakeup pipe, for XtAppAddInput() or poll(). */ +int dc_loop_wakeup_fd(const DcLoop *loop); + +/* + * Poll once and dispatch ready fds and due timers. timeout_ms < 0 waits + * until an fd, the wakeup pipe or the next timer; 0 does not wait. + * Returns the number of dispatched events (a wakeup counts as one), 0 on + * timeout, -1 on a poll() error other than EINTR (which returns 0). + */ +int dc_loop_run(DcLoop *loop, int timeout_ms); + #endif /* _DtChat_dc_internal_h */ diff --git a/lib/libDtChat/loop.c b/lib/libDtChat/loop.c new file mode 100644 index 00000000..7dd1f588 --- /dev/null +++ b/lib/libDtChat/loop.c @@ -0,0 +1,362 @@ +/* + * loop.c -- the core's poll(2) event loop + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * One poll(2) per dc_loop_run(), a monotonic one-shot timer list and a + * non-blocking wakeup pipe. The loop never calls into Xt; the UI watches + * dc_loop_wakeup_fd() and calls dc_loop_run() from its own callback. + */ +#include "dc_internal.h" + +#include +#include +#include +#include +#include +#include +#include + +struct DcFdEntry { + int id; + int fd; + short events; + DcLoopFdFn fn; + void *arg; +}; + +struct DcTimerEntry { + int id; + long long when; + DcLoopTimerFn fn; + void *arg; +}; + +struct DcReady { + int id; + short revents; +}; + +struct DcLoop { + int wake_r; + int wake_w; + int next_id; + struct DcFdEntry *fds; + size_t nfds, capfds; + struct DcTimerEntry *timers; + size_t ntimers, captimers; + struct pollfd *pfds; + size_t pcap; + struct DcReady *ready; + size_t rcap; +}; + +static int +set_nonblock_cloexec(int fd) +{ + int fl = fcntl(fd, F_GETFL, 0); + + if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) + return -1; + if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) + return -1; + return 0; +} + +long long +dc_loop_now_ms(void) +{ + struct timespec ts; + + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) + return 0; + return (long long)ts.tv_sec * 1000 + (long long)ts.tv_nsec / 1000000; +} + +DcLoop * +dc_loop_new(void) +{ + DcLoop *loop; + int fds[2]; + + if (pipe(fds) != 0) + return NULL; + if (set_nonblock_cloexec(fds[0]) != 0 || + set_nonblock_cloexec(fds[1]) != 0) { + close(fds[0]); + close(fds[1]); + return NULL; + } + loop = calloc(1, sizeof(*loop)); + if (loop == NULL) { + close(fds[0]); + close(fds[1]); + return NULL; + } + loop->wake_r = fds[0]; + loop->wake_w = fds[1]; + loop->next_id = 1; + return loop; +} + +void +dc_loop_free(DcLoop *loop) +{ + if (loop == NULL) + return; + close(loop->wake_r); + close(loop->wake_w); + free(loop->fds); + free(loop->timers); + free(loop->pfds); + free(loop->ready); + free(loop); +} + +int +dc_loop_wakeup_fd(const DcLoop *loop) +{ + return loop ? loop->wake_r : -1; +} + +int +dc_loop_wake(DcLoop *loop) +{ + if (loop == NULL) + return -1; + for (;;) { + ssize_t n = write(loop->wake_w, "x", 1); + if (n == 1) + return 0; + if (n < 0 && errno == EINTR) + continue; + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) + return 0; + return -1; + } +} + +static int +ensure_array(void **ptr, size_t *cap, size_t need, size_t elem) +{ + size_t ncap; + void *np; + + if (need <= *cap) + return 0; + if (elem != 0 && need > SIZE_MAX / elem) + return -1; + ncap = *cap ? *cap : 8; + while (ncap < need) { + if (ncap > SIZE_MAX / 2) + return -1; + ncap *= 2; + } + np = realloc(*ptr, ncap * elem); + if (np == NULL) + return -1; + *ptr = np; + *cap = ncap; + return 0; +} + +int +dc_loop_add_fd(DcLoop *loop, int fd, short events, DcLoopFdFn fn, void *arg) +{ + struct DcFdEntry *entry; + int id; + + if (loop == NULL || fd < 0 || events == 0 || fn == NULL) + return -1; + if (ensure_array((void **)&loop->fds, &loop->capfds, + loop->nfds + 1, sizeof(*loop->fds)) != 0) + return -1; + id = loop->next_id++; + entry = &loop->fds[loop->nfds++]; + entry->id = id; + entry->fd = fd; + entry->events = events; + entry->fn = fn; + entry->arg = arg; + return id; +} + +static struct DcFdEntry * +find_fd(DcLoop *loop, int id) +{ + size_t i; + + for (i = 0; i < loop->nfds; i++) + if (loop->fds[i].id == id) + return &loop->fds[i]; + return NULL; +} + +int +dc_loop_del_fd(DcLoop *loop, int id) +{ + size_t i; + + if (loop == NULL) + return -1; + for (i = 0; i < loop->nfds; i++) { + if (loop->fds[i].id == id) { + memmove(&loop->fds[i], &loop->fds[i + 1], + (loop->nfds - i - 1) * sizeof(*loop->fds)); + loop->nfds--; + return 0; + } + } + return -1; +} + +int +dc_loop_add_timer(DcLoop *loop, long long delay_ms, DcLoopTimerFn fn, + void *arg) +{ + struct DcTimerEntry *entry; + long long when; + size_t i; + int id; + + if (loop == NULL || delay_ms < 0 || fn == NULL) + return -1; + if (ensure_array((void **)&loop->timers, &loop->captimers, + loop->ntimers + 1, sizeof(*loop->timers)) != 0) + return -1; + when = dc_loop_now_ms() + delay_ms; + /* equal deadlines keep their insertion order */ + i = loop->ntimers; + while (i > 0 && loop->timers[i - 1].when > when) + i--; + memmove(&loop->timers[i + 1], &loop->timers[i], + (loop->ntimers - i) * sizeof(*loop->timers)); + id = loop->next_id++; + entry = &loop->timers[i]; + entry->id = id; + entry->when = when; + entry->fn = fn; + entry->arg = arg; + loop->ntimers++; + return id; +} + +int +dc_loop_del_timer(DcLoop *loop, int id) +{ + size_t i; + + if (loop == NULL) + return -1; + for (i = 0; i < loop->ntimers; i++) { + if (loop->timers[i].id == id) { + memmove(&loop->timers[i], &loop->timers[i + 1], + (loop->ntimers - i - 1) * sizeof(*loop->timers)); + loop->ntimers--; + return 0; + } + } + return -1; +} + +static int +dispatch_timers(DcLoop *loop, long long now) +{ + int n = 0; + + while (loop->ntimers > 0 && loop->timers[0].when <= now) { + struct DcTimerEntry timer = loop->timers[0]; + + memmove(&loop->timers[0], &loop->timers[1], + (loop->ntimers - 1) * sizeof(*loop->timers)); + loop->ntimers--; + timer.fn(timer.arg); + n++; + } + return n; +} + +int +dc_loop_run(DcLoop *loop, int timeout_ms) +{ + long long start, wait_until, now; + int fired = 0; + int poll_ms, rc; + size_t i, nready = 0; + + if (loop == NULL) + return -1; + start = dc_loop_now_ms(); + fired += dispatch_timers(loop, start); + + wait_until = timeout_ms < 0 ? -1 : start + timeout_ms; + if (loop->ntimers > 0) { + long long t = loop->timers[0].when; + + if (wait_until < 0 || t < wait_until) + wait_until = t; + } + if (wait_until < 0) { + poll_ms = -1; + } else { + now = dc_loop_now_ms(); + if (wait_until <= now) { + poll_ms = 0; + } else { + long long d = wait_until - now; + + poll_ms = d > 3600000 ? 3600000 : (int)d; + } + } + + if (ensure_array((void **)&loop->pfds, &loop->pcap, + loop->nfds + 1, sizeof(*loop->pfds)) != 0 || + ensure_array((void **)&loop->ready, &loop->rcap, + loop->nfds, sizeof(*loop->ready)) != 0) + return -1; + + loop->pfds[0].fd = loop->wake_r; + loop->pfds[0].events = POLLIN; + loop->pfds[0].revents = 0; + for (i = 0; i < loop->nfds; i++) { + loop->pfds[i + 1].fd = loop->fds[i].fd; + loop->pfds[i + 1].events = loop->fds[i].events; + loop->pfds[i + 1].revents = 0; + } + rc = poll(loop->pfds, (nfds_t)(loop->nfds + 1), poll_ms); + if (rc < 0) { + if (errno == EINTR) + return fired; + return -1; + } + if (loop->pfds[0].revents & POLLIN) { + char buf[64]; + + while (read(loop->wake_r, buf, sizeof(buf)) > 0) + ; + fired++; + } + + /* + * Snapshot the ready fds before any callback runs: a callback may + * remove another fd or add a new one, and the array then moves. + */ + for (i = 0; i < loop->nfds && nready < loop->nfds; i++) { + if (loop->pfds[i + 1].revents != 0) { + loop->ready[nready].id = loop->fds[i].id; + loop->ready[nready].revents = loop->pfds[i + 1].revents; + nready++; + } + } + for (i = 0; i < nready; i++) { + struct DcFdEntry *entry = find_fd(loop, loop->ready[i].id); + + if (entry != NULL) { + entry->fn(entry->fd, loop->ready[i].revents, entry->arg); + fired++; + } + } + + fired += dispatch_timers(loop, dc_loop_now_ms()); + return fired; +} diff --git a/lib/libDtChat/test_loop.c b/lib/libDtChat/test_loop.c new file mode 100644 index 00000000..f56c0a40 --- /dev/null +++ b/lib/libDtChat/test_loop.c @@ -0,0 +1,277 @@ +/* + * test_loop.c -- unit tests for the core's poll/timer event loop + * + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include "dc_internal.h" + +#include +#include +#include +#include +#include + +static int fails; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + fails++; \ + } \ +} while (0) + +static long long +now_ms(void) +{ + return dc_loop_now_ms(); +} + +struct Order { + int values[8]; + int n; +}; + +struct TimerCtx { + struct Order *order; + int code; + int fired; +}; + +static void +timer_cb(void *arg) +{ + struct TimerCtx *ctx = arg; + + ctx->fired++; + if (ctx->order != NULL && ctx->order->n < 8) + ctx->order->values[ctx->order->n++] = ctx->code; +} + +static void +test_timer_order(DcLoop *loop) +{ + struct Order order = { { 0 }, 0 }; + struct TimerCtx a = { &order, 1, 0 }; + struct TimerCtx b = { &order, 2, 0 }; + struct TimerCtx c = { &order, 3, 0 }; + long long start = now_ms(); + + CHECK(dc_loop_add_timer(loop, 60, timer_cb, &a) > 0); + CHECK(dc_loop_add_timer(loop, 20, timer_cb, &b) > 0); + CHECK(dc_loop_add_timer(loop, 40, timer_cb, &c) > 0); + while (order.n < 3 && now_ms() - start < 500) + (void)dc_loop_run(loop, 10); + + CHECK(order.n == 3); + CHECK(a.fired == 1 && b.fired == 1 && c.fired == 1); + CHECK(order.values[0] == 2); + CHECK(order.values[1] == 3); + CHECK(order.values[2] == 1); +} + +static void +test_timer_cancel(DcLoop *loop) +{ + struct TimerCtx ctx = { NULL, 4, 0 }; + int id = dc_loop_add_timer(loop, 20, timer_cb, &ctx); + + CHECK(id > 0); + CHECK(dc_loop_del_timer(loop, id) == 0); + (void)dc_loop_run(loop, 60); + CHECK(ctx.fired == 0); + CHECK(dc_loop_del_timer(loop, 99999) == -1); +} + +static void +test_timeout(DcLoop *loop) +{ + long long start = now_ms(); + int rc = dc_loop_run(loop, 40); + long long elapsed = now_ms() - start; + + CHECK(rc == 0); + CHECK(elapsed >= 30); + CHECK(elapsed < 500); +} + +static void +test_wakeup(DcLoop *loop) +{ + long long start; + + CHECK(dc_loop_wakeup_fd(loop) >= 0); + CHECK(dc_loop_wake(loop) == 0); + start = now_ms(); + CHECK(dc_loop_run(loop, 1000) >= 1); + CHECK(now_ms() - start < 200); +} + +struct PipeCtx { + int called; + char c; +}; + +static void +pipe_cb(int fd, short revents, void *arg) +{ + struct PipeCtx *ctx = arg; + + if (revents & POLLIN) { + char c; + + if (read(fd, &c, 1) == 1) { + ctx->called++; + ctx->c = c; + } + } +} + +static void +test_fd_pipe(DcLoop *loop) +{ + int fds[2]; + int id; + struct PipeCtx ctx = { 0, 0 }; + + CHECK(pipe(fds) == 0); + id = dc_loop_add_fd(loop, fds[0], POLLIN, pipe_cb, &ctx); + CHECK(id > 0); + CHECK(write(fds[1], "Z", 1) == 1); + CHECK(dc_loop_run(loop, 1000) >= 1); + CHECK(ctx.called == 1); + CHECK(ctx.c == 'Z'); + + CHECK(dc_loop_del_fd(loop, id) == 0); + CHECK(write(fds[1], "Q", 1) == 1); + (void)dc_loop_run(loop, 50); + CHECK(ctx.called == 1); + close(fds[0]); + close(fds[1]); +} + +struct DelCtx { + DcLoop *loop; + int id2; + int called1; + int called2; +}; + +static void +del_cb1(int fd, short revents, void *arg) +{ + struct DelCtx *ctx = arg; + + (void)fd; + (void)revents; + ctx->called1++; + CHECK(dc_loop_del_fd(ctx->loop, ctx->id2) == 0); +} + +static void +del_cb2(int fd, short revents, void *arg) +{ + struct DelCtx *ctx = arg; + + (void)fd; + (void)revents; + ctx->called2++; +} + +static void +test_delete_in_callback(DcLoop *loop) +{ + int p1[2], p2[2], id1; + struct DelCtx ctx; + + memset(&ctx, 0, sizeof(ctx)); + ctx.loop = loop; + CHECK(pipe(p1) == 0); + CHECK(pipe(p2) == 0); + id1 = dc_loop_add_fd(loop, p1[0], POLLIN, del_cb1, &ctx); + CHECK(id1 > 0); + ctx.id2 = dc_loop_add_fd(loop, p2[0], POLLIN, del_cb2, &ctx); + CHECK(ctx.id2 > 0); + CHECK(write(p1[1], "x", 1) == 1); + CHECK(write(p2[1], "y", 1) == 1); + (void)dc_loop_run(loop, 1000); + CHECK(ctx.called1 == 1); + CHECK(ctx.called2 == 0); + CHECK(dc_loop_del_fd(loop, id1) == 0); + close(p1[0]); + close(p1[1]); + close(p2[0]); + close(p2[1]); +} + +struct ChainCtx { + DcLoop *loop; + int fired; +}; + +static void +chain_cb(void *arg) +{ + struct ChainCtx *ctx = arg; + + ctx->fired++; + if (ctx->fired == 1) + CHECK(dc_loop_add_timer(ctx->loop, 10, chain_cb, ctx) > 0); +} + +static void +test_timer_adds_timer(DcLoop *loop) +{ + struct ChainCtx ctx = { loop, 0 }; + long long start = now_ms(); + + CHECK(dc_loop_add_timer(loop, 10, chain_cb, &ctx) > 0); + while (ctx.fired < 2 && now_ms() - start < 500) + (void)dc_loop_run(loop, 10); + CHECK(ctx.fired == 2); +} + +static void +test_monotonic(void) +{ + struct timespec ts = { 0, 20 * 1000 * 1000 }; + long long a = now_ms(); + + (void)nanosleep(&ts, NULL); + CHECK(now_ms() >= a + 10); +} + +static void +test_invalid(DcLoop *loop) +{ + CHECK(dc_loop_add_timer(loop, -1, timer_cb, NULL) == -1); + CHECK(dc_loop_add_fd(loop, -1, POLLIN, pipe_cb, NULL) == -1); + CHECK(dc_loop_add_fd(loop, 0, 0, pipe_cb, NULL) == -1); +} + +int +main(void) +{ + DcLoop *loop = dc_loop_new(); + + if (loop == NULL) { + perror("dc_loop_new"); + return 1; + } + test_timer_order(loop); + test_timer_cancel(loop); + test_timeout(loop); + test_wakeup(loop); + test_fd_pipe(loop); + test_delete_in_callback(loop); + test_timer_adds_timer(loop); + test_monotonic(); + test_invalid(loop); + dc_loop_free(loop); + if (fails != 0) { + fprintf(stderr, "%d test(s) failed\n", fails); + return 1; + } + printf("test_loop: all ok\n"); + return 0; +}