runite 0.1.0

An event-loop-per-thread async runtime built on io_uring (Linux), kqueue (macOS), and IOCP (Windows)
Documentation
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
//! Public runtime driver primitives for macOS.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use crate::op::completion::CompletionHandle;
use crate::platform::runtime_shared::{DriverBackend, Notifier};

pub use crate::platform::runtime_shared::ReadyEvents;

type FdCompletion = CompletionHandle<io::Result<()>>;

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub(crate) struct FdReadinessToken(u64);

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub(crate) enum FdInterest {
    Readable,
    Writable,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
struct FdKey {
    fd: RawFd,
    interest: FdInterest,
}

struct FdWaiter {
    token: FdReadinessToken,
    completion: FdCompletion,
}

#[derive(Clone)]
struct NotifierInner {
    /// A **dup** of the wake pipe's write end, owned by the notifier (shared via
    /// `Arc` so the notifier stays cloneable).
    ///
    /// Holding an [`OwnedFd`] rather than a bare `RawFd` closes a TOCTOU hazard:
    /// after the target [`Driver`] drops and closes its own write-end fd, the
    /// raw number could be recycled for an unrelated resource, and an in-flight
    /// `notify` that already passed the `closed` check would then `write` a
    /// stray wake byte into it — corrupting whatever now owns that fd. The dup
    /// keeps the number reserved for as long as any notifier exists, so a racing
    /// `notify` can only ever write to the original pipe. `F_SETNOSIGPIPE` on
    /// the dup turns a write to a fully-closed pipe into `EPIPE` instead of a
    /// `SIGPIPE`.
    write_fd: Arc<OwnedFd>,
    closed: Arc<AtomicBool>,
}

impl NotifierInner {
    fn notify(&self) -> io::Result<()> {
        if self.closed.load(Ordering::Acquire) {
            return Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "target runtime driver is closed",
            ));
        }

        let byte = 1u8;
        let written = unsafe {
            libc::write(
                self.write_fd.as_raw_fd(),
                &byte as *const u8 as *const libc::c_void,
                std::mem::size_of::<u8>(),
            )
        };
        if written < 0 {
            let error = io::Error::last_os_error();
            if error.kind() == io::ErrorKind::WouldBlock {
                return Ok(());
            }
            return Err(error);
        }

        Ok(())
    }
}

#[derive(Clone)]
/// Cross-thread notifier for a runtime thread's driver.
pub struct ThreadNotifier {
    inner: NotifierInner,
}

impl Notifier for ThreadNotifier {
    fn notify(&self) -> io::Result<()> {
        self.inner.notify()
    }
}

/// Low-level macOS runtime driver backed by `kqueue` and a wake pipe.
pub struct Driver {
    kqueue_fd: RawFd,
    wake_read_fd: RawFd,
    wake_write_fd: RawFd,
    closed: Arc<AtomicBool>,
    timer_deadline: Cell<Option<Duration>>,
    pending_wakes: Cell<u64>,
    pending_timers: Cell<u64>,
    next_fd_token: Cell<u64>,
    fd_waiters: RefCell<HashMap<FdKey, FdWaiter>>,
}

/// Creates a new driver and its paired [`ThreadNotifier`].
pub fn create_driver() -> io::Result<(Driver, ThreadNotifier)> {
    let kqueue_fd = cvt(unsafe { libc::kqueue() })?;

    let mut pipe_fds = [0; 2];
    cvt(unsafe { libc::pipe(pipe_fds.as_mut_ptr()) })?;
    let wake_read_fd = pipe_fds[0];
    let wake_write_fd = pipe_fds[1];

    set_nonblocking(wake_read_fd)?;
    set_nonblocking(wake_write_fd)?;

    let event = libc::kevent {
        ident: wake_read_fd as usize,
        filter: libc::EVFILT_READ,
        flags: libc::EV_ADD | libc::EV_ENABLE,
        fflags: 0,
        data: 0,
        udata: std::ptr::null_mut(),
    };

    let submitted = unsafe {
        libc::kevent(
            kqueue_fd,
            &event,
            1,
            std::ptr::null_mut(),
            0,
            std::ptr::null(),
        )
    };
    if submitted < 0 {
        let error = io::Error::last_os_error();
        unsafe {
            libc::close(wake_read_fd);
            libc::close(wake_write_fd);
            libc::close(kqueue_fd);
        }
        return Err(error);
    }

    let closed = Arc::new(AtomicBool::new(false));
    let driver = Driver {
        kqueue_fd,
        wake_read_fd,
        wake_write_fd,
        closed: Arc::clone(&closed),
        timer_deadline: Cell::new(None),
        pending_wakes: Cell::new(0),
        pending_timers: Cell::new(0),
        next_fd_token: Cell::new(1),
        fd_waiters: RefCell::new(HashMap::new()),
    };

    // The notifier holds its own dup of the write end so a cross-thread wake can
    // never target a recycled fd after this driver drops (see `NotifierInner`).
    let notifier_write_fd = match dup_nosigpipe_cloexec(wake_write_fd) {
        Ok(fd) => fd,
        Err(error) => {
            // `driver` owns wake_read_fd/wake_write_fd/kqueue_fd and will close
            // them when it drops here.
            drop(driver);
            return Err(error);
        }
    };
    let notifier = ThreadNotifier {
        inner: NotifierInner {
            write_fd: Arc::new(notifier_write_fd),
            closed,
        },
    };

    Ok((driver, notifier))
}

/// Duplicates `fd` with close-on-exec set, then disables `SIGPIPE` on the copy
/// (`F_SETNOSIGPIPE`) so a write to a fully-closed pipe returns `EPIPE` rather
/// than raising a signal.
fn dup_nosigpipe_cloexec(fd: RawFd) -> io::Result<OwnedFd> {
    // `F_SETNOSIGPIPE` is Darwin `fcntl` command 73 (XNU `bsd/sys/fcntl.h`);
    // the pinned `libc` does not re-export it, so define it locally. A wrong
    // command number here fails every macOS driver creation at runtime while
    // passing compile-only cross-target checks, so treat this constant as
    // verified only by the macOS test job.
    const F_SETNOSIGPIPE: libc::c_int = 73;

    let duplicated = cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) })?;
    // SAFETY: `duplicated` is a fresh, exclusively-owned fd from
    // `fcntl(F_DUPFD_CLOEXEC)`; ownership transfers to the `OwnedFd`, which
    // closes it on drop even if the `F_SETNOSIGPIPE` call below fails.
    let owned = unsafe { OwnedFd::from_raw_fd(duplicated) };
    cvt(unsafe { libc::fcntl(owned.as_raw_fd(), F_SETNOSIGPIPE, 1) })?;
    Ok(owned)
}

impl Driver {
    pub(crate) fn bind_current_thread(&self) {}

    pub(crate) fn unbind_current_thread(&self) {}

    /// Polls the driver without blocking.
    pub fn poll(&self) -> io::Result<Option<ReadyEvents>> {
        let mut pending = ReadyEvents::default();
        if self.pending_wakes.get() > 0 {
            pending.wake = true;
        }
        if self.pending_timers.get() > 0 {
            pending.timer = true;
        }
        if pending.wake || pending.timer {
            return Ok(Some(pending));
        }
        self.process(Some(Duration::ZERO))
    }

    /// Blocks until at least one event is available.
    pub fn wait(&self) -> io::Result<()> {
        let now = monotonic_now()?;
        let timeout = self
            .timer_deadline
            .get()
            .map(|deadline| deadline.saturating_sub(now));
        let _ = self.process(timeout)?;
        Ok(())
    }

    /// Updates the currently armed timer deadline.
    pub fn rearm_timer(&self, deadline: Option<Duration>) -> io::Result<()> {
        self.timer_deadline.set(deadline);
        Ok(())
    }

    /// Drains the accumulated wake notification count.
    ///
    /// Returns `Some(count)` with the number of wake notifications collected
    /// since the previous call, or `None` if no wake events were pending.
    pub fn drain_wake(&self) -> Option<u64> {
        let wakes = self.pending_wakes.replace(0);
        if wakes == 0 { None } else { Some(wakes) }
    }

    /// Drains the accumulated timer-expiration count.
    ///
    /// Returns `Some(count)` with the number of timer expirations collected
    /// since the previous call, or `None` if no timer events were pending.
    pub fn drain_timer(&self) -> Option<u64> {
        let timers = self.pending_timers.replace(0);
        if timers == 0 { None } else { Some(timers) }
    }

    pub(crate) fn register_fd_readiness(
        &self,
        fd: RawFd,
        interest: FdInterest,
        completion: FdCompletion,
    ) -> io::Result<FdReadinessToken> {
        let key = FdKey { fd, interest };
        let removed_stale_waiter = {
            let mut waiters = self.fd_waiters.borrow_mut();
            match waiters.get(&key) {
                Some(waiter) if !waiter.completion.is_interested() => {
                    waiters.remove(&key);
                    true
                }
                Some(_) => {
                    return Err(io::Error::new(
                        io::ErrorKind::AlreadyExists,
                        "fd readiness already has a waiter for this interest",
                    ));
                }
                None => false,
            }
        };
        if removed_stale_waiter {
            let _ = self.update_fd_interest(key, libc::EV_DELETE);
        }

        let token = self.allocate_fd_token();
        self.update_fd_interest(key, libc::EV_ADD | libc::EV_ENABLE | libc::EV_ONESHOT)?;
        self.fd_waiters
            .borrow_mut()
            .insert(key, FdWaiter { token, completion });
        Ok(token)
    }

    pub(crate) fn cancel_fd_readiness(&self, token: FdReadinessToken) {
        let mut empty_key = None;
        {
            let mut waiters = self.fd_waiters.borrow_mut();
            for (key, entry) in waiters.iter() {
                if entry.token == token {
                    empty_key = Some(*key);
                    break;
                }
            }

            if let Some(key) = empty_key {
                waiters.remove(&key);
            }
        }

        if let Some(key) = empty_key {
            let _ = self.update_fd_interest(key, libc::EV_DELETE);
        }
    }

    fn process(&self, timeout: Option<Duration>) -> io::Result<Option<ReadyEvents>> {
        let mut ready = ReadyEvents::default();

        let mut events = [unsafe { std::mem::zeroed::<libc::kevent>() }; 16];
        let timeout_spec = timeout_to_timespec(timeout);
        let timeout_ptr = timeout_spec
            .as_ref()
            .map_or(std::ptr::null(), |value| value as *const libc::timespec);

        let result = unsafe {
            libc::kevent(
                self.kqueue_fd,
                std::ptr::null(),
                0,
                events.as_mut_ptr(),
                events.len() as i32,
                timeout_ptr,
            )
        };
        if result < 0 {
            let error = io::Error::last_os_error();
            if error.kind() != io::ErrorKind::Interrupted {
                return Err(error);
            }
        }

        let mut saw_any = false;
        let count = result.max(0) as usize;
        if count > 0 {
            saw_any = true;
            for event in events.iter().take(count) {
                if event.ident as RawFd == self.wake_read_fd {
                    ready.wake = true;
                    let wakes = drain_wake_pipe(self.wake_read_fd)?;
                    self.pending_wakes
                        .set(self.pending_wakes.get().saturating_add(wakes));
                } else if let Some(interest) = interest_from_filter(event.filter) {
                    self.complete_fd_waiters(event.ident as RawFd, interest, event);
                }
            }
        }

        if let Some(deadline) = self.timer_deadline.get()
            && monotonic_now()? >= deadline
        {
            ready.timer = true;
            saw_any = true;
            self.timer_deadline.set(None);
            self.pending_timers
                .set(self.pending_timers.get().saturating_add(1));
        }

        if saw_any { Ok(Some(ready)) } else { Ok(None) }
    }

    fn allocate_fd_token(&self) -> FdReadinessToken {
        let token = self.next_fd_token.get();
        self.next_fd_token.set(
            token
                .checked_add(1)
                .expect("fd readiness token space exhausted"),
        );
        FdReadinessToken(token)
    }

    fn update_fd_interest(&self, key: FdKey, flags: u16) -> io::Result<()> {
        let event = libc::kevent {
            ident: key.fd as usize,
            filter: filter_for_interest(key.interest),
            flags,
            fflags: 0,
            data: 0,
            udata: std::ptr::null_mut(),
        };
        let submitted = unsafe {
            libc::kevent(
                self.kqueue_fd,
                &event,
                1,
                std::ptr::null_mut(),
                0,
                std::ptr::null(),
            )
        };
        if submitted < 0 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }

    fn complete_fd_waiters(&self, fd: RawFd, interest: FdInterest, event: &libc::kevent) {
        let key = FdKey { fd, interest };
        let waiter = self.fd_waiters.borrow_mut().remove(&key);
        let Some(waiter) = waiter else {
            return;
        };

        let result = fd_event_result(event, interest);
        waiter.completion.complete(result);
    }
}

impl Drop for Driver {
    fn drop(&mut self) {
        self.closed.store(true, Ordering::Release);
        unsafe {
            libc::close(self.wake_read_fd);
            libc::close(self.wake_write_fd);
            libc::close(self.kqueue_fd);
        }
    }
}

impl DriverBackend for Driver {
    fn poll(&self) -> io::Result<Option<ReadyEvents>> {
        Driver::poll(self)
    }

    fn wait(&self) -> io::Result<()> {
        Driver::wait(self)
    }

    fn rearm_timer(&self, deadline: Option<Duration>) -> io::Result<()> {
        Driver::rearm_timer(self, deadline)
    }

    fn drain_wake(&self) -> Option<u64> {
        Driver::drain_wake(self)
    }

    fn drain_timer(&self) -> Option<u64> {
        Driver::drain_timer(self)
    }

    fn bind_current_thread(&self) {
        Driver::bind_current_thread(self)
    }

    fn unbind_current_thread(&self) {
        Driver::unbind_current_thread(self)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Returns the current monotonic clock reading.
pub fn monotonic_now() -> io::Result<Duration> {
    let mut now = std::mem::MaybeUninit::<libc::timespec>::uninit();
    let result = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, now.as_mut_ptr()) };
    if result < 0 {
        return Err(io::Error::last_os_error());
    }

    let now = unsafe { now.assume_init() };
    Ok(Duration::new(now.tv_sec as u64, now.tv_nsec as u32))
}

fn cvt(value: libc::c_int) -> io::Result<libc::c_int> {
    if value < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(value)
    }
}

fn filter_for_interest(interest: FdInterest) -> i16 {
    match interest {
        FdInterest::Readable => libc::EVFILT_READ,
        FdInterest::Writable => libc::EVFILT_WRITE,
    }
}

fn interest_from_filter(filter: i16) -> Option<FdInterest> {
    if filter == libc::EVFILT_READ {
        Some(FdInterest::Readable)
    } else if filter == libc::EVFILT_WRITE {
        Some(FdInterest::Writable)
    } else {
        None
    }
}

fn fd_event_result(event: &libc::kevent, interest: FdInterest) -> io::Result<()> {
    if event.flags & libc::EV_ERROR != 0 && event.data != 0 {
        Err(io::Error::from_raw_os_error(event.data as i32))
    } else if event.flags & libc::EV_EOF != 0 && interest == FdInterest::Writable {
        Err(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "fd write side reached EOF",
        ))
    } else {
        Ok(())
    }
}

fn set_nonblocking(fd: RawFd) -> io::Result<()> {
    let flags = cvt(unsafe { libc::fcntl(fd, libc::F_GETFL) })?;
    cvt(unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) })?;
    Ok(())
}

fn timeout_to_timespec(timeout: Option<Duration>) -> Option<libc::timespec> {
    timeout.map(|value| libc::timespec {
        tv_sec: value.as_secs() as libc::time_t,
        tv_nsec: value.subsec_nanos() as libc::c_long,
    })
}

fn drain_wake_pipe(fd: RawFd) -> io::Result<u64> {
    let mut wakes = 0u64;
    let mut buf = [0u8; 256];

    loop {
        let read = unsafe {
            libc::read(
                fd,
                buf.as_mut_ptr() as *mut libc::c_void,
                buf.len() as libc::size_t,
            )
        };

        if read > 0 {
            wakes = wakes.saturating_add(read as u64);
            continue;
        }

        if read == 0 {
            break;
        }

        let error = io::Error::last_os_error();
        if error.kind() == io::ErrorKind::WouldBlock {
            break;
        }
        if error.kind() == io::ErrorKind::Interrupted {
            continue;
        }

        return Err(error);
    }

    Ok(wakes.max(1))
}