oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
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
//! `event` on WASI preview 1: `poll_oneoff`, with one subscription for each
//! direction of each entry and one on the monotonic clock for the timeout.

use core::time::Duration;

use crate::event::{Interest, Readiness};
use crate::sys::{RawHandle, cvt, errno};
use crate::time::Clock;
use crate::{Error, ErrorKind, Result};

/// `clockid::monotonic`.
const CLOCK_MONOTONIC: u32 = 1;
/// `eventtype`, the tag of a subscription and of its event.
const EVENTTYPE_CLOCK: u8 = 0;
const EVENTTYPE_FD_READ: u8 = 1;
const EVENTTYPE_FD_WRITE: u8 = 2;
/// `eventrwflags::fd_readwrite_hangup`.
const EVENT_HANGUP: u16 = 1;

/// The `userdata` of the subscription on the clock; the others have the
/// index of their entry.
const TIMEOUT: u64 = u64::MAX;
/// The longest timeout of one `poll_oneoff`, in nanoseconds: 136 years.
const MAX_WAIT: u64 = (u32::MAX as u64) * 1_000_000_000;
/// How many subscriptions fit on the stack.
const INLINE: usize = 64;

/// `subscription`. The union that follows the tag is laid out as its
/// largest variant, `clock`; the `fd_read` and `fd_write` variants are a
/// descriptor, where the clock has its identifier.
#[repr(C)]
#[derive(Clone, Copy)]
struct Subscription {
    userdata: u64,
    tag: u8,
    /// The union starts at its own alignment, 8.
    padding: [u8; 7],
    /// The clock, or the descriptor.
    id: u32,
    timeout: u64,
    precision: u64,
    flags: u16,
}

/// `event`.
#[repr(C)]
#[derive(Clone, Copy)]
struct Event {
    userdata: u64,
    error: u16,
    kind: u8,
    nbytes: u64,
    flags: u16,
}

// The layouts of the witx definition.
const _: () = {
    assert!(size_of::<Subscription>() == 48);
    assert!(core::mem::offset_of!(Subscription, id) == 16);
    assert!(core::mem::offset_of!(Subscription, timeout) == 24);
    assert!(size_of::<Event>() == 32);
    assert!(core::mem::offset_of!(Event, kind) == 10);
    assert!(core::mem::offset_of!(Event, flags) == 24);
};

impl Subscription {
    const EMPTY: Self = Self {
        userdata: 0,
        tag: 0,
        padding: [0; 7],
        id: 0,
        timeout: 0,
        precision: 0,
        flags: 0,
    };
}

impl Event {
    const EMPTY: Self = Self {
        userdata: 0,
        error: 0,
        kind: 0,
        nbytes: 0,
        flags: 0,
    };
}

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn poll_oneoff(
        subscriptions: *const Subscription,
        events: *mut Event,
        count: usize,
        stored: *mut usize,
    ) -> i32;
}

/// The entry of a poll: WASI has no `pollfd`.
#[derive(Clone, Copy)]
pub(crate) struct PollFd {
    fd: RawHandle,
    interest: Interest,
    readiness: Readiness,
}

impl PollFd {
    pub(crate) fn new(fd: RawHandle, interest: Interest) -> Self {
        Self {
            fd,
            interest,
            readiness: Readiness::empty(),
        }
    }

    pub(crate) fn raw(&self) -> RawHandle {
        self.fd
    }

    pub(crate) fn interest(&self) -> Interest {
        self.interest
    }

    pub(crate) fn readiness(&self) -> Readiness {
        self.readiness
    }

    pub(crate) fn clear(&mut self) {
        self.readiness = Readiness::empty();
    }
}

fn monotonic() -> Result<u64> {
    let now = crate::sys::time::clock(Clock::Monotonic)?;
    Ok(u64::try_from(now.as_nanos()).unwrap_or(u64::MAX))
}

pub(crate) fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> Result<usize> {
    let needed = fds
        .iter()
        .map(|fd| fd.interest.bits().count_ones() as usize)
        .sum::<usize>()
        + usize::from(timeout.is_some());
    if needed <= INLINE {
        let mut subscriptions = [Subscription::EMPTY; INLINE];
        let mut events = [Event::EMPTY; INLINE];
        return poll_with(
            fds,
            timeout,
            &mut subscriptions[..needed],
            &mut events[..needed],
        );
    }
    #[cfg(feature = "alloc")]
    {
        let mut subscriptions = alloc::vec![Subscription::EMPTY; needed];
        let mut events = alloc::vec![Event::EMPTY; needed];
        poll_with(fds, timeout, &mut subscriptions, &mut events)
    }
    #[cfg(not(feature = "alloc"))]
    Err(ErrorKind::Unsupported.into())
}

/// Polls with the buffers given, which have room for every subscription.
///
/// This loops, checking the clock: hosts are free to round the timeout of
/// `poll_oneoff`, and some round it down (Node, to a millisecond).
fn poll_with(
    fds: &mut [PollFd],
    timeout: Option<Duration>,
    subscriptions: &mut [Subscription],
    events: &mut [Event],
) -> Result<usize> {
    let deadline = match timeout {
        Some(timeout) => {
            let nanos = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
            Some(monotonic()?.saturating_add(nanos))
        }
        None => None,
    };
    loop {
        let mut count = 0;
        for (index, fd) in fds.iter_mut().enumerate() {
            fd.clear();
            for (interest, tag) in [
                (Interest::READABLE, EVENTTYPE_FD_READ),
                (Interest::WRITABLE, EVENTTYPE_FD_WRITE),
            ] {
                if fd.interest.contains(interest) {
                    subscriptions[count] = Subscription {
                        userdata: index as u64,
                        tag,
                        id: fd.fd as u32,
                        ..Subscription::EMPTY
                    };
                    count += 1;
                }
            }
        }
        if let Some(deadline) = deadline {
            // A relative timeout: `flags` has no `abstime`.
            subscriptions[count] = Subscription {
                userdata: TIMEOUT,
                tag: EVENTTYPE_CLOCK,
                id: CLOCK_MONOTONIC,
                // In pieces if it is very long: the loop goes on until the
                // deadline, and no host is asked to add centuries to its
                // clock.
                timeout: deadline.saturating_sub(monotonic()?).min(MAX_WAIT),
                ..Subscription::EMPTY
            };
            count += 1;
        }
        if count == 0 {
            // Nothing to wait for and no timeout: only entries with no
            // interest, which the portable layer refuses.
            return Err(ErrorKind::InvalidInput.into());
        }
        let mut stored = 0;
        // SAFETY: the host reads `count` subscriptions and writes at most
        // as many events, and the count of events stored.
        cvt(unsafe {
            poll_oneoff(
                subscriptions.as_ptr(),
                events.as_mut_ptr(),
                count,
                &raw mut stored,
            )
        })?;
        for event in &events[..stored.min(count)] {
            if event.userdata == TIMEOUT {
                if event.error != 0 {
                    return Err(Error::from_raw_os_error(event.error.into()));
                }
                continue;
            }
            let Some(fd) = fds.get_mut(event.userdata as usize) else {
                continue;
            };
            if event.error != 0 {
                fd.readiness |= if i32::from(event.error) == errno::EBADF {
                    Readiness::INVALID
                } else {
                    Readiness::ERROR
                };
                continue;
            }
            match event.kind {
                EVENTTYPE_FD_READ => fd.readiness |= Readiness::READABLE,
                EVENTTYPE_FD_WRITE => fd.readiness |= Readiness::WRITABLE,
                _ => {}
            }
            if event.flags & EVENT_HANGUP != 0 {
                fd.readiness |= Readiness::HANGUP;
            }
        }
        let ready = fds.iter().filter(|fd| !fd.readiness.is_empty()).count();
        if ready > 0 {
            return Ok(ready);
        }
        if let Some(deadline) = deadline
            && monotonic()? >= deadline
        {
            return Ok(0);
        }
    }
}

// ---------------------------------------------------------------------------
// The poller: a table of registrations, polled by each wait
// ---------------------------------------------------------------------------

#[cfg(feature = "alloc")]
pub(crate) use poller::{Poller, RawEvent};

#[cfg(feature = "alloc")]
mod poller {
    use alloc::vec::Vec;
    use core::time::Duration;

    use super::PollFd;
    use crate::event::lock::Lock;
    use crate::event::timers::{Op, Timers};
    use crate::event::{Interest, ModeKind, Readiness};
    use crate::sys::RawHandle;
    use crate::{ErrorKind, Result};

    /// The event of a poller: WASI has no structure for it.
    #[derive(Clone, Copy)]
    pub(crate) struct RawEvent {
        token: usize,
        readiness: Readiness,
        wake: bool,
        /// For a timer, how many times it expired; 0 for another event.
        expirations: u64,
    }

    impl RawEvent {
        pub(crate) const EMPTY: Self = Self {
            token: 0,
            readiness: Readiness::empty(),
            wake: false,
            expirations: 0,
        };

        pub(crate) fn is_timer(&self) -> bool {
            self.expirations != 0
        }

        pub(crate) fn expirations(&self) -> u64 {
            self.expirations
        }

        pub(crate) fn token(&self) -> usize {
            self.token
        }

        pub(crate) fn is_wake(&self) -> bool {
            self.wake
        }

        pub(crate) fn readiness(&self) -> Readiness {
            self.readiness
        }
    }

    struct Registration {
        fd: RawHandle,
        token: usize,
        interest: Interest,
        oneshot: bool,
        /// Cleared when a one-shot registration has fired.
        armed: bool,
    }

    struct State {
        registrations: Vec<Registration>,
        /// A wake-up to report.
        woken: bool,
        /// The timers: no timer of the system is behind them, the wait
        /// lasts no longer than the earliest of them.
        timers: Timers,
        /// Where the last wait stopped reporting: the next one starts
        /// there, so that a small buffer does not starve the last
        /// registrations.
        next: usize,
    }

    pub(crate) struct Poller(Lock<State>);

    impl Poller {
        pub(crate) fn new() -> Result<Self> {
            Ok(Self(Lock::new(State {
                registrations: Vec::new(),
                woken: false,
                timers: Timers::new(),
                next: 0,
            })))
        }

        pub(crate) fn register(
            &self,
            fd: RawHandle,
            token: usize,
            interest: Interest,
            mode: ModeKind,
        ) -> Result<()> {
            let mut state = self.0.lock();
            if state.registrations.iter().any(|r| r.fd == fd) {
                return Err(ErrorKind::AlreadyExists.into());
            }
            state
                .registrations
                .try_reserve(1)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            state.registrations.push(Registration {
                fd,
                token,
                interest,
                oneshot: matches!(mode, ModeKind::OneShot),
                armed: true,
            });
            Ok(())
        }

        pub(crate) fn modify(
            &self,
            fd: RawHandle,
            token: usize,
            interest: Interest,
            mode: ModeKind,
        ) -> Result<()> {
            let mut state = self.0.lock();
            let Some(registration) = state.registrations.iter_mut().find(|r| r.fd == fd) else {
                return Err(ErrorKind::NotFound.into());
            };
            registration.token = token;
            registration.interest = interest;
            registration.oneshot = matches!(mode, ModeKind::OneShot);
            registration.armed = true;
            Ok(())
        }

        pub(crate) fn deregister(&self, fd: RawHandle) -> Result<()> {
            let mut state = self.0.lock();
            let Some(index) = state.registrations.iter().position(|r| r.fd == fd) else {
                return Err(ErrorKind::NotFound.into());
            };
            // In order: `next` keeps its meaning.
            state.registrations.remove(index);
            Ok(())
        }

        pub(crate) fn register_signals(
            &self,
            signals: &crate::sys::process::signal::Signals,
            _token: usize,
        ) -> Result<()> {
            match *signals {}
        }

        pub(crate) fn deregister_signals(
            &self,
            signals: &crate::sys::process::signal::Signals,
        ) -> Result<()> {
            match *signals {}
        }

        pub(crate) fn register_child(
            &self,
            child: &crate::sys::process::Child,
            _collected: bool,
            _token: usize,
        ) -> Result<()> {
            match *child {}
        }

        pub(crate) fn deregister_child(&self, child: &crate::sys::process::Child) -> Result<()> {
            match *child {}
        }

        pub(crate) fn timer(&self, token: usize, op: Op) -> Result<()> {
            let mut state = self.0.lock();
            let now = super::monotonic()?;
            // Nothing to arm: the next wait looks at the queue.
            state.timers.apply(token, op, now, |_| Ok(()))
        }

        pub(crate) fn wait(
            &self,
            events: &mut [RawEvent],
            timeout: Option<Duration>,
        ) -> Result<usize> {
            // There is one thread: nobody waits for the lock meanwhile.
            let mut state = self.0.lock();
            let deadline = match timeout {
                Some(timeout) => {
                    let nanos = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX);
                    Some(super::monotonic()?.saturating_add(nanos))
                }
                None => None,
            };
            loop {
                let count = self.wait_once(&mut state, events, deadline)?;
                if count > 0 {
                    return Ok(count);
                }
                // Nothing: the time is up, or the host ended the wait
                // before a timer was due.
                if let Some(deadline) = deadline
                    && super::monotonic()? >= deadline
                {
                    return Ok(0);
                }
            }
        }

        /// One `poll_oneoff`, until `deadline` or the earliest timer.
        fn wait_once(
            &self,
            state: &mut State,
            events: &mut [RawEvent],
            deadline: Option<u64>,
        ) -> Result<usize> {
            let mut count = 0;
            if state.woken {
                state.woken = false;
                events[0] = RawEvent {
                    wake: true,
                    ..RawEvent::EMPTY
                };
                count = 1;
            }
            let total = state.registrations.len();
            let start = if state.next < total { state.next } else { 0 };
            // The armed registrations, from `start` round.
            let order = (start..total).chain(0..start);
            let armed: Vec<usize> = order
                .filter(|&index| state.registrations[index].armed)
                .collect();
            let mut fds: Vec<PollFd> = armed
                .iter()
                .map(|&index| {
                    let registration = &state.registrations[index];
                    PollFd::new(registration.fd, registration.interest)
                })
                .collect();
            // Until the deadline or the earliest timer, whichever is first.
            let until = match (deadline, state.timers.next()) {
                (Some(deadline), Some(timer)) => Some(deadline.min(timer)),
                (deadline, timer) => deadline.or(timer),
            };
            let timeout = if count > 0 {
                // Only collect what is ready besides the wake-up.
                Some(Duration::ZERO)
            } else {
                match until {
                    Some(until) => Some(Duration::from_nanos(
                        until.saturating_sub(super::monotonic()?),
                    )),
                    None => None,
                }
            };
            if fds.is_empty() && timeout.is_none() {
                // Nothing can happen, and nobody can wake.
                return Err(ErrorKind::Deadlock.into());
            }
            if count == events.len() {
                return Ok(count);
            }
            match super::poll(&mut fds, timeout) {
                Ok(_) => {}
                // The wake-up is not lost to an error.
                Err(_) if count > 0 => return Ok(count),
                Err(err) => return Err(err),
            }
            for (fd, &index) in fds.iter().zip(&armed) {
                let mut readiness = fd.readiness();
                if readiness.is_empty() {
                    continue;
                }
                if count == events.len() {
                    // The rest is for the next wait, starting here.
                    state.next = index;
                    break;
                }
                if readiness.contains(Readiness::INVALID) {
                    // A poller does not say `INVALID`: the descriptor was
                    // closed while registered.
                    readiness = (readiness - Readiness::INVALID) | Readiness::ERROR;
                }
                let registration = &mut state.registrations[index];
                events[count] = RawEvent {
                    token: registration.token,
                    readiness,
                    wake: false,
                    expirations: 0,
                };
                count += 1;
                if registration.oneshot {
                    registration.armed = false;
                }
            }
            // The timers that are due, in what room is left: the others
            // are still due at the next wait.
            if state.timers.next().is_some() && count < events.len() {
                let now = match super::monotonic() {
                    Ok(now) => now,
                    // What was collected is not lost to an error.
                    Err(_) if count > 0 => return Ok(count),
                    Err(err) => return Err(err),
                };
                let room = &mut events[count..];
                count += state
                    .timers
                    .expire(now, room.len(), |index, token, expirations| {
                        room[index] = RawEvent {
                            token,
                            expirations,
                            ..RawEvent::EMPTY
                        };
                    });
            }
            Ok(count)
        }

        pub(crate) fn wake(&self) -> Result<()> {
            self.0.lock().woken = true;
            Ok(())
        }
    }
}