oscall 0.0.1

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
//! Receiving signals on macOS: `sigaction`, and a handler that only
//! records the signal and writes a byte to a pipe.

use core::cell::UnsafeCell;
use core::ffi::{c_int, c_void};
use core::mem::ManuallyDrop;
use core::sync::atomic::Ordering::SeqCst;
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU8, AtomicU32};
use core::time::Duration;

use crate::process::Wake;
use crate::sys::{cvt, errno, last_error};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};

// <sys/signal.h>
pub(crate) const HANGUP: i32 = 1;
pub(crate) const INTERRUPT: i32 = 2;
pub(crate) const TERMINATE: i32 = 15;
const SIGILL: i32 = 4;
const SIGTRAP: i32 = 5;
const SIGFPE: i32 = 8;
const SIGKILL: i32 = 9;
const SIGBUS: i32 = 10;
const SIGSEGV: i32 = 11;
const SIGSYS: i32 = 12;
const SIGURG: i32 = 16;
const SIGSTOP: i32 = 17;
const SIGCONT: i32 = 19;
const SIGCHLD: i32 = 20;
const SIGIO: i32 = 23;
const SIGWINCH: i32 = 28;
const SIGINFO: i32 = 29;
/// The highest signal number (`NSIG - 1`).
const SIGNALS: usize = 31;

const SIG_DFL: usize = 0;
const SIG_IGN: usize = 1;

const SA_ONSTACK: c_int = 0x0001;
const SA_RESTART: c_int = 0x0002;

/// `struct sigaction`: the handler (a union of two function pointers), a
/// `sigset_t` of 32 bits, the flags.
#[repr(C)]
#[derive(Clone, Copy)]
struct Action {
    handler: usize,
    mask: u32,
    flags: c_int,
}

impl Action {
    const fn new(handler: usize, flags: c_int) -> Self {
        Self {
            handler,
            mask: 0,
            flags,
        }
    }
}

/// `struct pollfd`.
#[repr(C)]
struct PollFd {
    fd: c_int,
    events: i16,
    revents: i16,
}

const POLLIN: i16 = 1;

unsafe extern "C" {
    #[link_name = "sigaction"]
    fn c_sigaction(signal: c_int, new: *const Action, old: *mut Action) -> c_int;
    fn __error() -> *mut c_int;
    fn write(fd: c_int, buf: *const c_void, len: usize) -> isize;
    fn read(fd: c_int, buf: *mut c_void, len: usize) -> isize;
    fn poll(fds: *mut PollFd, count: u32, timeout: c_int) -> c_int;
    fn sched_yield() -> c_int;
    fn raise(signal: c_int) -> c_int;
}

fn sigaction(signal: i32, new: Option<&Action>, old: Option<&mut Action>) -> Result<()> {
    let new = new.map_or(core::ptr::null(), core::ptr::from_ref);
    let old = old.map_or(core::ptr::null_mut(), core::ptr::from_mut);
    // SAFETY: each pointer is null or to a `struct sigaction`, writable
    // for `old`.
    cvt(unsafe { c_sigaction(signal, new, old) }).map(drop)
}

/// What the process knows about one signal.
struct Slot {
    /// Who has the signal for itself: nobody ([`FREE`]), a `Signals` or a
    /// call that changes the disposition ([`OWNED`]), or for an instant
    /// the handler, when it finds itself installed with nobody listening
    /// ([`HANDLER`]).
    state: AtomicU8,
    /// The write end of the pipe of the `Signals` that listens, or -1.
    wake: AtomicI32,
    /// Whether the signal was delivered since it was last asked about.
    pending: AtomicBool,
    /// The number of handlers between setting `pending` and having woken
    /// the descriptor.
    waking: AtomicU32,
    /// The action the signal has when nobody listens: the one in place
    /// before the handler was first installed, or set since by
    /// [`set_disposition`]. It is never the handler itself. Only the one
    /// that holds `state` touches it.
    previous: UnsafeCell<Action>,
}

const FREE: u8 = 0;
const OWNED: u8 = 1;
const HANDLER: u8 = 2;

// SAFETY: `previous` is only accessed by the one that holds `state`.
unsafe impl Sync for Slot {}

/// Whether `action` cannot be put in the place of a handler, for
/// `signal`.
///
/// The system decides that a signal is caught and reads its action again
/// to deliver it, without checking it a second time (`issignal_locked`,
/// then `postsig_locked`, in xnu's `kern_sig.c`). If the action became
/// "ignore" in between, the process jumps to `SIG_IGN`, the address 1; if
/// it became "default", the process is terminated, which is wrong for the
/// signals whose default is to do nothing. So an action that amounts to
/// ignoring the signal never replaces a handler: oscall's handler stays,
/// or is installed, and discards the signal, which is the same to the
/// process.
fn discards(signal: i32, action: &Action) -> bool {
    action.handler == SIG_IGN
        || (action.handler == SIG_DFL
            && matches!(
                signal,
                SIGURG | SIGCONT | SIGCHLD | SIGIO | SIGWINCH | SIGINFO
            ))
}

static SLOTS: [Slot; SIGNALS + 1] = [const {
    Slot {
        state: AtomicU8::new(FREE),
        wake: AtomicI32::new(-1),
        pending: AtomicBool::new(false),
        waking: AtomicU32::new(0),
        previous: UnsafeCell::new(Action::new(SIG_DFL, 0)),
    }
}; SIGNALS + 1];

/// The number of threads inside [`handler`].
static ACTIVE: AtomicU32 = AtomicU32::new(0);

/// The signal handler. It runs on whichever thread the system chose, in
/// the middle of whatever that thread was doing: it touches atomics and
/// calls `write`, which is async-signal-safe, and nothing else. `errno` is
/// the interrupted code's, and is put back.
unsafe extern "C" fn handler(signal: c_int) {
    // Announced before the descriptor is read: whoever wants to close it
    // takes it away first, then waits for this count to drop to zero.
    ACTIVE.fetch_add(1, SeqCst);
    if let Some(slot) = SLOTS.get(signal as usize) {
        let fd = slot.wake.load(SeqCst);
        if fd >= 0 {
            slot.waking.fetch_add(1, SeqCst);
            slot.pending.store(true, SeqCst);
            let byte = 0u8;
            // SAFETY: `__error` returns the address of the thread's
            // `errno`. One readable byte, for a descriptor that stays open
            // while `ACTIVE` counts this thread; the pipe does not block,
            // and when it is full it is readable, which is all that is
            // wanted.
            unsafe {
                let errno = __error();
                let saved = *errno;
                let _ = write(fd, (&raw const byte).cast(), 1);
                *errno = saved;
            }
            slot.waking.fetch_sub(1, SeqCst);
        } else if slot
            .state
            .compare_exchange(FREE, HANDLER, SeqCst, SeqCst)
            .is_ok()
        {
            // Nobody listens and nobody is changing that. Either the
            // signal is one to discard, and this is how it is discarded
            // (see `discards`); or the handler is an orphan: the
            // subscription ended while other code had put an action of
            // its own in place, and that code has since put back what it
            // had found, this handler. Then do now what the end of the
            // subscription could not: give the signal the action it has
            // without us, and send it again for that action to take it.
            // It is blocked until this handler returns.
            // SAFETY: `state` is held: nothing else accesses `previous`.
            // `sigaction` and `raise` are async-signal-safe; `errno` is
            // put back.
            unsafe {
                let previous = &*slot.previous.get();
                if !discards(signal, previous) {
                    let errno = __error();
                    let saved = *errno;
                    let mut current = Action::new(SIG_DFL, 0);
                    if c_sigaction(signal, core::ptr::null(), &raw mut current) == 0
                        && current.handler == handler as *const () as usize
                        && c_sigaction(signal, previous, core::ptr::null_mut()) == 0
                    {
                        let _ = raise(signal);
                    }
                    *errno = saved;
                }
            }
            slot.state.store(FREE, SeqCst);
        }
        // Otherwise the delivery raced with the end of a subscription, or
        // with the start of one, and is dropped like those that came just
        // before.
    }
    ACTIVE.fetch_sub(1, SeqCst);
}

/// Whether no thread is inside the handler, waiting a little for it: a
/// handler runs for microseconds, unless its thread is not scheduled.
fn handlers_done() -> bool {
    for round in 0..2000 {
        if ACTIVE.load(SeqCst) == 0 {
            return true;
        }
        if round < 1000 {
            // SAFETY: no argument.
            unsafe { sched_yield() };
        } else {
            let _ = crate::sys::time::sleep(Duration::from_micros(100));
        }
    }
    false
}

/// Takes the slot of `signal` for the caller, who must release it.
fn claim(signal: i32) -> Result<&'static Slot> {
    if signal < 1 {
        return Err(ErrorKind::InvalidInput.into());
    }
    let slot = SLOTS.get(signal as usize).ok_or(ErrorKind::InvalidInput)?;
    loop {
        match slot.state.compare_exchange(FREE, OWNED, SeqCst, SeqCst) {
            Ok(_) => return Ok(slot),
            // The handler has it for the time of a few system calls.
            Err(HANDLER) => core::hint::spin_loop(),
            Err(_) => return Err(ErrorKind::ResourceBusy.into()),
        }
    }
}

/// The action that makes [`handler`] run.
fn handler_action() -> Action {
    // SA_RESTART: a system call the signal interrupts in code that knows
    // nothing of it is restarted, where the system can. SA_ONSTACK: on the
    // thread's alternate stack if it has one, as runtimes with small
    // stacks ask of every handler in the process.
    let mut action = Action::new(handler as *const () as usize, SA_RESTART | SA_ONSTACK);
    // Every signal is blocked while the handler runs: handlers do not pile
    // up on one stack, each with the frame the system saves the thread's
    // state in.
    action.mask = u32::MAX;
    action
}

/// Sets the disposition of `signal` to "ignore" or to its default.
pub(crate) fn set_disposition(signal: i32, ignore: bool) -> Result<()> {
    if matches!(signal, SIGKILL | SIGSTOP) {
        return Err(ErrorKind::InvalidInput.into());
    }
    let slot = claim(signal)?;
    let action = Action::new(if ignore { SIG_IGN } else { SIG_DFL }, 0);
    let result = (|| {
        let mut current = Action::new(SIG_DFL, 0);
        sigaction(signal, None, Some(&mut current))?;
        let caught = current.handler != SIG_DFL && current.handler != SIG_IGN;
        if caught && discards(signal, &action) {
            // Not in the place of a handler: ours discards the signal.
            // (One handler replaces another safely.)
            sigaction(signal, Some(&handler_action()), None)
        } else {
            sigaction(signal, Some(&action), None)
        }
    })();
    if result.is_ok() {
        // What the signal does from now on when nobody listens.
        // SAFETY: the slot is ours; nothing else accesses `previous`.
        unsafe { *slot.previous.get() = action };
    }
    slot.state.store(FREE, SeqCst);
    result
}

pub(crate) struct Signals {
    /// The pipe the handler writes to: readable when a signal of the set
    /// may be pending. Both ends are left open for ever in the unlikely
    /// case where a handler could still be about to write to it.
    read: ManuallyDrop<OwnedHandle>,
    write: ManuallyDrop<OwnedHandle>,
    /// Bit `n - 1` for signal `n`.
    set: u32,
}

impl Signals {
    pub(crate) fn new(signals: &[i32]) -> Result<Self> {
        let (read, write) = crate::sys::io::pipe()?;
        // The handler must never wait for room in the pipe, nor the
        // program for a byte.
        crate::sys::io::set_nonblocking(read.as_handle(), true)?;
        crate::sys::io::set_nonblocking(write.as_handle(), true)?;
        let fd = write.as_raw();
        // Dropped on failure, which undoes what was done.
        let mut this = Self {
            read: ManuallyDrop::new(read),
            write: ManuallyDrop::new(write),
            set: 0,
        };
        let action = handler_action();
        for &signal in signals {
            // What cannot be caught; and the faults of the thread itself,
            // which make no sense as notifications: returning from the
            // handler would run the faulting instruction again.
            if matches!(
                signal,
                SIGKILL | SIGSTOP | SIGILL | SIGTRAP | SIGBUS | SIGFPE | SIGSEGV | SIGSYS
            ) {
                return Err(ErrorKind::InvalidInput.into());
            }
            if this.contains(signal) {
                continue;
            }
            let slot = claim(signal)?;
            slot.pending.store(false, SeqCst);
            slot.wake.store(fd, SeqCst);
            this.set |= 1 << (signal - 1);
            let mut old = Action::new(SIG_DFL, 0);
            sigaction(signal, Some(&action), Some(&mut old))?;
            // The handler found in place is not what to go back to: it
            // was left there with no subscription (see the handler), and
            // the slot still has the action from before.
            if old.handler != action.handler {
                // SAFETY: the slot is ours; nothing else accesses
                // `previous`.
                unsafe { *slot.previous.get() = old };
            }
        }
        Ok(this)
    }

    fn contains(&self, signal: i32) -> bool {
        (1..=SIGNALS as i32).contains(&signal) && self.set & 1 << (signal - 1) != 0
    }

    /// The signals of the set, with their slots.
    fn slots(&self) -> impl Iterator<Item = (i32, &'static Slot)> {
        let set = self.set;
        (1..=SIGNALS as i32)
            .filter(move |signal| set & 1 << (signal - 1) != 0)
            .map(|signal| (signal, &SLOTS[signal as usize]))
    }

    /// A signal that is pending, which no longer is.
    fn take(&self) -> Option<i32> {
        self.slots()
            .find(|(_, slot)| slot.pending.swap(false, SeqCst))
            .map(|(signal, _)| signal)
    }

    /// Waits for the handlers that have set a flag of this set to have
    /// woken the descriptor too: an instant, unless the thread of one is
    /// not running, and then not for long.
    fn settle(&self) {
        for _ in 0..1000 {
            if self.slots().all(|(_, slot)| slot.waking.load(SeqCst) == 0) {
                return;
            }
            // SAFETY: no argument.
            unsafe { sched_yield() };
        }
    }

    pub(crate) fn try_next(&self) -> Option<i32> {
        if let Some(signal) = self.take() {
            return Some(signal);
        }
        // Nothing is pending: the descriptor must not stay readable. A
        // handler sets its flag, then wakes the descriptor. One that is
        // between the two had its flag taken by an earlier call, and its
        // wake-up is for nothing: it is waited for, so that the wake-up is
        // cleared with the others. One that starts after this wait sets
        // its flag after it too, and the last look below either finds the
        // flag, or leaves it set with its wake-up to come: in no case is
        // the descriptor left readable with nothing to take, nor a flag
        // set with nothing to wake for it.
        self.settle();
        let mut buf = [0u8; 64];
        loop {
            // SAFETY: the buffer is writable for its length; the
            // descriptor does not block.
            let n = unsafe { read(self.read.as_raw(), buf.as_mut_ptr().cast(), buf.len()) };
            if n < buf.len() as isize {
                break;
            }
        }
        self.take()
    }

    pub(crate) fn wait_once(&self, timeout: Option<Duration>) -> Result<Wake> {
        let mut fd = PollFd {
            fd: self.read.as_raw(),
            events: POLLIN,
            revents: 0,
        };
        // Milliseconds, rounded up; what does not fit is waited for in
        // several times by the caller.
        let timeout = match timeout {
            None => -1,
            Some(timeout) => {
                let millis = timeout.as_nanos().div_ceil(1_000_000);
                c_int::try_from(millis).unwrap_or(c_int::MAX)
            }
        };
        // SAFETY: one `pollfd`, which the system writes to.
        match unsafe { poll(&raw mut fd, 1, timeout) } {
            0 => Ok(Wake::TimedOut),
            -1 => {
                let error = last_error();
                if error.raw_os_error() == errno::EINTR {
                    Ok(Wake::Interrupted)
                } else {
                    Err(error)
                }
            }
            _ => Ok(Wake::Ready),
        }
    }

    pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
        self.read.as_handle()
    }
}

impl Drop for Signals {
    fn drop(&mut self) {
        let ours = handler as *const () as usize;
        for (signal, slot) in self.slots() {
            // The action that was there, unless other code has installed
            // its own since: that one is not ours to remove.
            let mut current = Action::new(SIG_DFL, 0);
            // SAFETY: the slot is ours; nothing else accesses `previous`,
            // which was written when the handler was installed.
            let previous = unsafe { &*slot.previous.get() };
            // An action that amounts to ignoring the signal is not put
            // back: the handler stays, and discards the signal now that
            // nobody listens (see `discards`; the jump to `SIG_IGN` was
            // seen under load on x86_64 and arm64).
            if !discards(signal, previous)
                && sigaction(signal, None, Some(&mut current)).is_ok()
                && current.handler == ours
            {
                let _ = sigaction(signal, Some(previous), None);
            }
            slot.wake.store(-1, SeqCst);
        }
        // A handler that read the descriptor before it was taken away is
        // counted in `ACTIVE`, and one that starts now does not see it:
        // once the count is zero nobody writes to it any more.
        if handlers_done() {
            // SAFETY: not used afterwards.
            unsafe {
                ManuallyDrop::drop(&mut self.read);
                ManuallyDrop::drop(&mut self.write);
            }
        }
        for (_, slot) in self.slots() {
            slot.pending.store(false, SeqCst);
            slot.state.store(FREE, SeqCst);
        }
    }
}

impl core::fmt::Debug for Signals {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Signals")
            .field("read", &*self.read)
            .field("write", &*self.write)
            .field("set", &format_args!("{:#x}", self.set))
            .finish()
    }
}