oscall 0.0.2

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
//! Receiving signals on Linux and fullrust: `rt_sigaction` with the
//! kernel's own `struct sigaction`, and a handler that only records the
//! signal and wakes an `eventfd`.
//!
//! There is no libc to install the handler for us, and when there is one in
//! the process it is not told: it keeps no state about the dispositions of
//! the signals this module accepts.

use core::cell::UnsafeCell;
use core::ffi::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::time::Timespec;
use crate::sys::{errno, syscall};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};

// include/uapi/asm-generic/signal.h: the numbers are the same on the six
// architectures supported.
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 SIGBUS: i32 = 7;
const SIGFPE: i32 = 8;
const SIGKILL: i32 = 9;
const SIGSEGV: i32 = 11;
const SIGSTOP: i32 = 19;
const SIGSYS: i32 = 31;
/// The highest signal number (`_NSIG`).
const SIGNALS: usize = 64;

/// The first three real-time signals are not the program's: glibc keeps 32
/// and 33 (thread cancellation, `setuid` across threads), musl 32 to 34.
const LIBC_FIRST: i32 = 32;
const LIBC_LAST: i32 = 34;

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

// include/uapi/asm-generic/signal-defs.h, and the same values in
// arch/{x86,arm,arm64}/include/uapi/asm/signal.h.
const SA_SIGINFO: usize = 0x0000_0004;
#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))]
const SA_RESTORER: usize = 0x0400_0000;
const SA_ONSTACK: usize = 0x0800_0000;
const SA_RESTART: usize = 0x1000_0000;

/// The size of the kernel's `sigset_t`: 64 signals, on every architecture.
const SIGSET_SIZE: usize = 8;

/// The kernel's `struct sigaction` (`include/linux/signal_types.h`), which
/// is not libc's: the handler, the flags as an `unsigned long`, the
/// restorer on the architectures that define `SA_RESTORER` (x86, arm,
/// arm64; not riscv), and last the mask, 64 bits in `unsigned long`s.
#[repr(C)]
#[derive(Clone, Copy)]
struct Action {
    handler: usize,
    flags: usize,
    #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
    restorer: usize,
    mask: [usize; SIGSET_SIZE / size_of::<usize>()],
}

impl Action {
    const fn new(handler: usize, flags: usize) -> Self {
        Self {
            handler,
            flags,
            #[cfg(not(any(target_arch = "riscv32", target_arch = "riscv64")))]
            restorer: 0,
            mask: [0; SIGSET_SIZE / size_of::<usize>()],
        }
    }
}

/// Where the kernel makes a handler return to: a call to `rt_sigreturn`,
/// which restores the context the signal interrupted from the frame the
/// kernel left on the stack. A libc provides it with `sigaction`; x86_64
/// has no other way, and on x86 and arm the kernel's own trampoline needs
/// a vDSO or an executable stack that a process need not have. arm64 and
/// riscv always use the trampoline of the vDSO: no restorer is given there.
///
/// The handler is installed with `SA_SIGINFO`, so that the frame is an
/// `rt` one on x86 and arm, where two kinds exist.
#[cfg(target_arch = "x86_64")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
    core::arch::naked_asm!(
        "mov eax, {rt_sigreturn}",
        "syscall",
        "ud2",
        rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
    )
}

/// See the x86_64 version.
#[cfg(target_arch = "x86")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
    // The handler's `ret` popped the return address: `esp` is where
    // `rt_sigreturn` expects it for an `rt` frame.
    core::arch::naked_asm!(
        "mov eax, {rt_sigreturn}",
        "int 0x80",
        "ud2",
        rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
    )
}

/// See the x86_64 version. The kernel enters it in the instruction set the
/// low bit of its address says, as for the handler.
#[cfg(target_arch = "arm")]
#[unsafe(naked)]
unsafe extern "C" fn restorer() -> ! {
    core::arch::naked_asm!(
        "mov r7, #{rt_sigreturn}",
        "svc 0",
        "udf #0",
        rt_sigreturn = const crate::sys::nr::RT_SIGRETURN,
    )
}

/// 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 kernel 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.
    #[allow(unused_mut)]
    let mut action = Action::new(
        handler as *const () as usize,
        SA_SIGINFO | 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 kernel saves the
    // thread's state in, which an alternate stack of the usual size holds
    // one or two of.
    action.mask = [usize::MAX; SIGSET_SIZE / size_of::<usize>()];
    #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm"))]
    {
        action.flags |= SA_RESTORER;
        action.restorer = restorer as *const () as usize;
    }
    action
}

/// `rt_sigaction`.
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` as the kernel
    // defines it, writable for `old`.
    unsafe { syscall!(RT_SIGACTION, signal, new, old, SIGSET_SIZE) }.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 `eventfd` 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 {}

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 kernel chose, in
/// the middle of whatever that thread was doing, perhaps a thread that the
/// Rust runtime knows nothing about: it touches atomics and makes one
/// system call, and nothing else. No thread-local storage (the raw system
/// call does not set `errno`), no allocation, no lock, no panic.
unsafe extern "C" fn handler(signal: i32, _info: *mut c_void, _context: *mut c_void) {
    // 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 one: u64 = 1;
            // SAFETY: eight readable bytes, for a descriptor that stays
            // open while `ACTIVE` counts this thread. Adding to an
            // `eventfd` does not block; it can only fail when the count is
            // at its maximum, and the descriptor is then readable anyway.
            let _ = unsafe { syscall!(WRITE, fd, &raw const one, size_of::<u64>()) };
            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: 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. 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.
            let mut current = Action::new(SIG_DFL, 0);
            if sigaction(signal, None, Some(&mut current)).is_ok()
                && current.handler == handler as *const () as usize
            {
                // SAFETY: `state` is held: nothing else accesses
                // `previous`. The calls are raw system calls, to this very
                // thread for the second.
                // Sent again only once this handler is out of the way:
                // it would otherwise receive the signal for ever.
                unsafe {
                    if sigaction(signal, Some(&*slot.previous.get()), None).is_ok()
                        && let (Ok(pid), Ok(tid)) = (syscall!(GETPID), syscall!(GETTID))
                    {
                        let _ = syscall!(TGKILL, pid, tid, signal);
                    }
                }
            }
            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.
            let _ = unsafe { syscall!(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 || (LIBC_FIRST..=LIBC_LAST).contains(&signal) {
        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 two system calls.
            Err(HANDLER) => core::hint::spin_loop(),
            Err(_) => return Err(ErrorKind::ResourceBusy.into()),
        }
    }
}

/// Sets the disposition of `signal` to "ignore" or to its default.
pub(crate) fn set_disposition(signal: i32, ignore: bool) -> Result<()> {
    let slot = claim(signal)?;
    let action = Action::new(if ignore { SIG_IGN } else { SIG_DFL }, 0);
    let result = sigaction(signal, Some(&action), None);
    if result.is_ok() {
        // What the signal does from now on when nobody listens, should
        // the handler be put back by code that had saved it.
        // SAFETY: the slot is ours; nothing else accesses `previous`.
        unsafe { *slot.previous.get() = action };
    }
    slot.state.store(FREE, SeqCst);
    result
}

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

const POLLIN: i16 = 1;

// The same on every architecture.
const EFD_CLOEXEC: usize = 0o2000000;
const EFD_NONBLOCK: usize = 0o4000;

pub(crate) struct Signals {
    /// The `eventfd` the handler adds to: readable when a signal of the
    /// set may be pending. Left open for ever in the unlikely case where a
    /// handler could still be about to write to it.
    wake: ManuallyDrop<OwnedHandle>,
    /// Bit `n - 1` for signal `n`.
    set: u64,
}

impl Signals {
    pub(crate) fn new(signals: &[i32]) -> Result<Self> {
        // SAFETY: no memory is involved.
        let fd = unsafe { syscall!(EVENTFD2, 0, EFD_CLOEXEC | EFD_NONBLOCK) }? as i32;
        // SAFETY: the descriptor was just created.
        let wake = ManuallyDrop::new(unsafe { OwnedHandle::from_raw(fd) });
        // Dropped on failure, which undoes what was done.
        let mut this = Self { wake, 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.
            let _ = unsafe { syscall!(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 count: u64 = 0;
        // SAFETY: eight writable bytes; the descriptor does not block.
        let _ = unsafe { syscall!(READ, self.wake.as_raw(), &raw mut count, size_of::<u64>()) };
        self.take()
    }

    pub(crate) fn wait_once(&self, timeout: Option<Duration>) -> Result<Wake> {
        let mut fd = PollFd {
            fd: self.wake.as_raw(),
            events: POLLIN,
            revents: 0,
        };
        let timeout = timeout.map(Timespec::from_duration);
        let timeout = timeout
            .as_ref()
            .map_or(core::ptr::null(), core::ptr::from_ref);
        // SAFETY: one `pollfd` the kernel writes to, a `__kernel_timespec`
        // or null, and no signal mask.
        #[cfg(target_pointer_width = "32")]
        let result = unsafe { syscall!(PPOLL_TIME64, &raw mut fd, 1, timeout, 0, SIGSET_SIZE) };
        // SAFETY: as above; `timespec` has that layout on 64-bit
        // architectures.
        #[cfg(target_pointer_width = "64")]
        let result = unsafe { syscall!(PPOLL, &raw mut fd, 1, timeout, 0, SIGSET_SIZE) };
        match result {
            Ok(0) => Ok(Wake::TimedOut),
            Ok(_) => Ok(Wake::Ready),
            Err(error) if error.raw_os_error() == errno::EINTR => Ok(Wake::Interrupted),
            Err(error) => Err(error),
        }
    }

    pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
        self.wake.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);
            if sigaction(signal, None, Some(&mut current)).is_ok() && current.handler == ours {
                // SAFETY: the slot is ours; nothing else accesses
                // `previous`, which was written when the handler was
                // installed.
                let _ = sigaction(signal, Some(unsafe { &*slot.previous.get() }), 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.wake) };
        }
        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("wake", &*self.wake)
            .field("set", &format_args!("{:#x}", self.set))
            .finish()
    }
}