oscall 0.1.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
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
//! A thread made with `clone`, on a stack of its own, that no runtime
//! knows of.
//!
//! The mapping of a thread, from the bottom: a page nothing may touch (a
//! stack that overflows faults there), the stack, and at the very top a
//! [`Control`], which is how the thread and its handle talk. The kernel
//! clears the `tid` word of it when the thread is gone
//! (`CLONE_CHILD_CLEARTID`), and wakes who waits on it.
//!
//! Who unmaps: whoever joins, once the kernel has cleared the word; or the
//! thread itself when it was detached, with two system calls in a row and
//! no stack between them ([`exit_unmapping`]). `state` settles which.

use core::ffi::c_void;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicU32, Ordering};

use crate::mem::{MapOptions, Protection};
use crate::sys::{errno, mem, nr, syscall};
use crate::{ErrorKind, Result};

// include/uapi/linux/sched.h
const CLONE_VM: usize = 0x0000_0100;
const CLONE_FS: usize = 0x0000_0200;
const CLONE_FILES: usize = 0x0000_0400;
const CLONE_SIGHAND: usize = 0x0000_0800;
const CLONE_THREAD: usize = 0x0001_0000;
const CLONE_SYSVSEM: usize = 0x0004_0000;
const CLONE_CHILD_CLEARTID: usize = 0x0020_0000;

const FLAGS: usize = CLONE_VM
    | CLONE_FS
    | CLONE_FILES
    | CLONE_SIGHAND
    | CLONE_THREAD
    | CLONE_SYSVSEM
    | CLONE_CHILD_CLEARTID;

/// Not private: the kernel's wake-up of the `tid` word is not, and a
/// private wait is another queue.
const FUTEX_WAIT: usize = 0;

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

/// `state`: the thread runs and someone holds its handle.
const JOINABLE: u32 = 0;
/// The handle is gone: the thread unmaps its own stack.
const DETACHED: u32 = 1;
/// The thread is past its function: whoever has the handle unmaps.
const EXITING: u32 = 2;

/// What `tid` holds until the kernel clears it.
const ALIVE: u32 = u32::MAX;

#[repr(C, align(16))]
struct Control {
    tid: AtomicU32,
    state: AtomicU32,
    base: *mut u8,
    len: usize,
    f: fn(usize),
    arg: usize,
}

pub(crate) struct RawThread {
    control: NonNull<Control>,
    tid: u32,
}

// SAFETY: the handle is a pointer to a mapping it shares with one thread,
// which the two only reach through atomics.
unsafe impl Send for RawThread {}
// SAFETY: as above; `&self` only loads an atomic.
unsafe impl Sync for RawThread {}

/// Calls `clone` for a thread that shares everything with the caller, and
/// in it `f(arg)` on the stack that ends at `stack`; the kernel clears
/// `*ctid` when that thread is gone. Returns the thread's identifier, or
/// a negative error number.
///
/// The function and its argument travel on the new stack. `f` does not
/// return: there is nothing to return to.
///
/// # Safety
///
/// `stack` is the end of a writable region large enough for `f`, and
/// `ctid` is writable for as long as the thread lives or until the region
/// it is in is unmapped.
#[cfg(target_arch = "x86_64")]
#[unsafe(naked)]
unsafe extern "C" fn clone_thread(
    flags: usize,
    stack: *mut u8,
    ctid: *mut u32,
    f: unsafe extern "C" fn(*mut c_void) -> !,
    arg: *mut c_void,
) -> isize {
    // rdi = flags, rsi = stack, rdx = ctid, rcx = f, r8 = arg.
    // clone(rdi = flags, rsi = stack, rdx = ptid, r10 = ctid, r8 = tls).
    core::arch::naked_asm!(
        "and rsi, -16",
        "sub rsi, 16",
        "mov [rsi], rcx",
        "mov [rsi + 8], r8",
        "mov r10, rdx",
        "xor edx, edx",
        "xor r8d, r8d",
        "mov eax, {clone}",
        "syscall",
        "test rax, rax",
        "jz 2f",
        "ret",
        // The thread: rsp is the new stack, 16-byte aligned once the two
        // words are popped, as the ABI wants before a call.
        "2:",
        "xor ebp, ebp",
        "pop rax",
        "pop rdi",
        "call rax",
        "ud2",
        clone = const nr::CLONE,
    )
}

/// See the x86_64 version.
#[cfg(target_arch = "x86")]
#[unsafe(naked)]
unsafe extern "C" fn clone_thread(
    flags: usize,
    stack: *mut u8,
    ctid: *mut u32,
    f: unsafe extern "C" fn(*mut c_void) -> !,
    arg: *mut c_void,
) -> isize {
    // After the pushes: [esp + 12] = flags, + 16 = stack, + 20 = ctid,
    // + 24 = f, + 28 = arg.
    // clone(ebx = flags, ecx = stack, edx = ptid, esi = tls, edi = ctid);
    // the kernel does not read `tls` without CLONE_SETTLS.
    core::arch::naked_asm!(
        "push ebx",
        "push edi",
        "mov ecx, [esp + 16]",
        "and ecx, -16",
        "sub ecx, 16",
        "mov eax, [esp + 28]",
        "mov [ecx], eax",
        "mov eax, [esp + 24]",
        "mov [ecx + 4], eax",
        "mov ebx, [esp + 12]",
        "mov edi, [esp + 20]",
        "xor edx, edx",
        "mov eax, {clone}",
        "int 0x80",
        "test eax, eax",
        "jz 2f",
        "pop edi",
        "pop ebx",
        "ret",
        // The thread: esp is 16-byte aligned and points to the argument,
        // as the ABI wants at a call.
        "2:",
        "xor ebp, ebp",
        "mov eax, [esp + 4]",
        "call eax",
        "ud2",
        clone = const nr::CLONE,
    )
}

/// See the x86_64 version.
#[cfg(target_arch = "aarch64")]
#[unsafe(naked)]
unsafe extern "C" fn clone_thread(
    flags: usize,
    stack: *mut u8,
    ctid: *mut u32,
    f: unsafe extern "C" fn(*mut c_void) -> !,
    arg: *mut c_void,
) -> isize {
    // x0 = flags, x1 = stack, x2 = ctid, x3 = f, x4 = arg.
    // clone(x0 = flags, x1 = stack, x2 = ptid, x3 = tls, x4 = ctid).
    core::arch::naked_asm!(
        // `bti c`, a no-op where branch target identification is off.
        "hint #34",
        "and x1, x1, #-16",
        "stp x3, x4, [x1, #-16]!",
        "mov x4, x2",
        "mov x2, #0",
        "mov x3, #0",
        "mov x8, {clone}",
        "svc #0",
        "cbz x0, 2f",
        "ret",
        // The thread: sp is the new stack, 16-byte aligned.
        "2:",
        "mov x29, #0",
        "mov x30, #0",
        "ldp x1, x0, [sp]",
        "blr x1",
        "brk #1",
        clone = const nr::CLONE,
    )
}

/// See the x86_64 version.
#[cfg(target_arch = "arm")]
#[unsafe(naked)]
unsafe extern "C" fn clone_thread(
    flags: usize,
    stack: *mut u8,
    ctid: *mut u32,
    f: unsafe extern "C" fn(*mut c_void) -> !,
    arg: *mut c_void,
) -> isize {
    // r0 = flags, r1 = stack, r2 = ctid, r3 = f, [sp] = arg.
    // clone(r0 = flags, r1 = stack, r2 = ptid, r3 = tls, r4 = ctid), with
    // the number in r7. Every instruction exists in both the ARM and the
    // Thumb-2 instruction sets.
    core::arch::naked_asm!(
        "push {{r4, r7}}",
        "ldr r4, [sp, #8]",
        "bic r1, r1, #15",
        "str r4, [r1, #-4]!",
        "str r3, [r1, #-4]!",
        "mov r4, r2",
        "mov r2, #0",
        "mov r7, #{clone}",
        "svc 0",
        "cmp r0, #0",
        "beq 2f",
        "pop {{r4, r7}}",
        "bx lr",
        // The thread: sp is the new stack, 8-byte aligned.
        "2:",
        "mov r11, #0",
        "mov lr, #0",
        "ldr r1, [sp]",
        "ldr r0, [sp, #4]",
        "blx r1",
        "udf #0",
        clone = const nr::CLONE,
    )
}

/// See the x86_64 version.
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
#[unsafe(naked)]
unsafe extern "C" fn clone_thread(
    flags: usize,
    stack: *mut u8,
    ctid: *mut u32,
    f: unsafe extern "C" fn(*mut c_void) -> !,
    arg: *mut c_void,
) -> isize {
    // a0 = flags, a1 = stack, a2 = ctid, a3 = f, a4 = arg.
    // clone(a0 = flags, a1 = stack, a2 = ptid, a3 = tls, a4 = ctid), with
    // the number in a7.
    #[cfg(target_arch = "riscv64")]
    core::arch::naked_asm!(
        "andi a1, a1, -16",
        "addi a1, a1, -16",
        "sd a3, 0(a1)",
        "sd a4, 8(a1)",
        "mv a4, a2",
        "mv a2, zero",
        "li a7, {clone}",
        "ecall",
        "beqz a0, 2f",
        "ret",
        // The thread: sp is the new stack, 16-byte aligned.
        "2:",
        "mv s0, zero",
        "mv ra, zero",
        "ld a1, 0(sp)",
        "ld a0, 8(sp)",
        "jalr a1",
        "unimp",
        clone = const nr::CLONE,
    );
    #[cfg(target_arch = "riscv32")]
    core::arch::naked_asm!(
        "andi a1, a1, -16",
        "addi a1, a1, -16",
        "sw a3, 0(a1)",
        "sw a4, 4(a1)",
        "mv a4, a2",
        "mv a2, zero",
        "li a7, {clone}",
        "ecall",
        "beqz a0, 2f",
        "ret",
        "2:",
        "mv s0, zero",
        "mv ra, zero",
        "lw a1, 0(sp)",
        "lw a0, 4(sp)",
        "jalr a1",
        "unimp",
        clone = const nr::CLONE,
    );
}

/// Unmaps `len` bytes at `base` and ends the calling thread, which may be
/// running on them: nothing touches the stack between the two system
/// calls.
///
/// # Safety
///
/// The range is a mapping nothing but the calling thread uses.
unsafe fn exit_unmapping(base: *mut u8, len: usize) -> ! {
    // SAFETY: the caller's contract. Each block makes `munmap(base, len)`
    // and then `exit(0)` from registers alone, and does not return.
    unsafe {
        #[cfg(target_arch = "x86_64")]
        core::arch::asm!(
            "syscall",
            "xor edi, edi",
            "mov eax, {exit}",
            "syscall",
            "ud2",
            in("rax") nr::MUNMAP,
            in("rdi") base,
            in("rsi") len,
            exit = const nr::EXIT,
            options(noreturn, nostack),
        );
        #[cfg(target_arch = "x86")]
        core::arch::asm!(
            "mov ebx, {base}",
            "int 0x80",
            "xor ebx, ebx",
            "mov eax, {exit}",
            "int 0x80",
            "ud2",
            base = in(reg) base,
            in("eax") nr::MUNMAP,
            in("ecx") len,
            exit = const nr::EXIT,
            options(noreturn, nostack),
        );
        #[cfg(target_arch = "aarch64")]
        core::arch::asm!(
            "svc #0",
            "mov x0, #0",
            "mov x8, {exit}",
            "svc #0",
            "brk #1",
            in("x8") nr::MUNMAP,
            in("x0") base,
            in("x1") len,
            exit = const nr::EXIT,
            options(noreturn, nostack),
        );
        #[cfg(target_arch = "arm")]
        core::arch::asm!(
            "mov r7, #{munmap}",
            "svc 0",
            "mov r0, #0",
            "mov r7, #{exit}",
            "svc 0",
            "udf #0",
            in("r0") base,
            in("r1") len,
            munmap = const nr::MUNMAP,
            exit = const nr::EXIT,
            options(noreturn, nostack),
        );
        #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
        core::arch::asm!(
            "ecall",
            "li a0, 0",
            "li a7, {exit}",
            "ecall",
            "unimp",
            in("a7") nr::MUNMAP,
            in("a0") base,
            in("a1") len,
            exit = const nr::EXIT,
            options(noreturn, nostack),
        );
    }
}

/// What the thread runs.
///
/// # Safety
///
/// `control` points to the [`Control`] at the top of the stack the thread
/// runs on.
unsafe extern "C" fn start(control: *mut c_void) -> ! {
    let control = control.cast::<Control>().cast_const();
    // SAFETY: the caller's contract; the function and its argument were
    // written before the thread existed, and nothing writes them again.
    let (f, arg, base, len) = unsafe {
        (
            (*control).f,
            (*control).arg,
            (*control).base,
            (*control).len,
        )
    };
    f(arg);
    // SAFETY: the control block is mapped for as long as the state says
    // the thread has not left.
    if unsafe { &(*control).state }.swap(EXITING, Ordering::AcqRel) == DETACHED {
        // Nobody will join: the mapping is this thread's to remove.
        // First the kernel is told to clear no word when the thread ends:
        // the word is in the mapping, and between `munmap` and the end
        // of the thread another thread may have mapped something there,
        // into which the kernel would write a zero. (A C library does the
        // same before it unmaps the stack of a detached thread.)
        // SAFETY: `set_tid_address` only records an address, here none;
        // the handle gave the mapping up when it detached.
        unsafe {
            let _ = syscall!(SET_TID_ADDRESS, 0);
            exit_unmapping(base, len)
        }
    }
    loop {
        // SAFETY: ends the calling thread; whoever joins it unmaps the
        // stack once the kernel has cleared `tid`.
        let _ = unsafe { syscall!(EXIT, 0) };
    }
}

/// # Safety
///
/// What `thread::linux::spawn_raw` says of `f`.
pub(crate) unsafe fn spawn_raw(stack_size: usize, f: fn(usize), arg: usize) -> Result<RawThread> {
    let page = mem::page_size();
    // Room for the frames of `start` and of the exit besides what the
    // caller asked for.
    let len = stack_size
        .checked_add(size_of::<Control>() + page - 1)
        .map(|len| len & !(page - 1))
        .and_then(|len| len.checked_add(2 * page))
        .ok_or(ErrorKind::InvalidInput)?;
    let base = mem::map_anonymous(len, &MapOptions::new())?;
    // SAFETY: the mapping was just made and is at least three pages; its
    // first page is the guard, and its top holds the control block, which
    // is aligned since the mapping ends on a page.
    let control = unsafe {
        if let Err(error) = mem::protect(base, page, Protection::NONE) {
            let _ = mem::unmap(base, len);
            return Err(error);
        }
        let control = base.add(len - size_of::<Control>()).cast::<Control>();
        control.write(Control {
            tid: AtomicU32::new(ALIVE),
            state: AtomicU32::new(JOINABLE),
            base,
            len,
            f,
            arg,
        });
        control
    };

    // The thread starts with every signal blocked: a handler of the
    // program's would run on it otherwise, and handlers are code that
    // expects a thread of the runtime. The mask is inherited.
    let all = u64::MAX;
    let mut old = 0u64;
    // SAFETY: the kernel reads and writes one signal set each, of the size
    // given; `clone_thread` gets the end of a writable region, the control
    // block is at the top of it, and `start` is given that block.
    let tid = unsafe {
        syscall!(
            RT_SIGPROCMASK,
            SIG_SETMASK,
            &raw const all,
            &raw mut old,
            SIGSET_SIZE
        )?;
        let tid = clone_thread(
            FLAGS,
            control.cast(),
            (&raw mut (*control).tid).cast(),
            start,
            control.cast(),
        );
        let _ = syscall!(RT_SIGPROCMASK, SIG_SETMASK, &raw const old, 0, SIGSET_SIZE);
        tid
    };
    if tid < 0 {
        // SAFETY: no thread was created: the mapping is still ours alone.
        let _ = unsafe { mem::unmap(base, len) };
        return Err(crate::Error::from_raw_os_error(-tid as i32));
    }
    Ok(RawThread {
        // SAFETY: a pointer into a mapping is not null.
        control: unsafe { NonNull::new_unchecked(control) },
        tid: tid as u32,
    })
}

impl RawThread {
    fn control(&self) -> &Control {
        // SAFETY: the mapping lives until this handle joins or detaches,
        // both of which consume it.
        unsafe { self.control.as_ref() }
    }

    pub(crate) fn id(&self) -> u32 {
        self.tid
    }

    pub(crate) fn is_finished(&self) -> bool {
        self.control().tid.load(Ordering::Acquire) == 0
    }

    /// Waits until the kernel has cleared `tid`, which it does when the
    /// thread no longer runs on its stack, and unmaps.
    fn reap(&self) -> Result<()> {
        let control = self.control();
        loop {
            let tid = control.tid.load(Ordering::Acquire);
            if tid == 0 {
                break;
            }
            let null = core::ptr::null::<u8>();
            // SAFETY: the kernel reads the atomic, and no timeout.
            #[cfg(target_pointer_width = "32")]
            let result =
                unsafe { syscall!(FUTEX_TIME64, control.tid.as_ptr(), FUTEX_WAIT, tid, null) };
            // SAFETY: as above.
            #[cfg(target_pointer_width = "64")]
            let result = unsafe { syscall!(FUTEX, control.tid.as_ptr(), FUTEX_WAIT, tid, null) };
            match result {
                Ok(_) => {}
                Err(error) => match error.raw_os_error() {
                    // The value changed first, or a signal handler ran.
                    errno::EAGAIN | errno::EINTR => {}
                    _ => return Err(error),
                },
            }
        }
        let (base, len) = (control.base, control.len);
        // SAFETY: the thread is gone, and this handle was the only other
        // user of the mapping.
        unsafe { mem::unmap(base, len) }
    }

    pub(crate) fn join(self) -> Result<()> {
        let result = self.reap();
        core::mem::forget(self);
        result
    }
}

impl Drop for RawThread {
    /// Detaches: the thread frees its stack itself, unless it is already
    /// past the point of asking, and then it is as good as gone.
    fn drop(&mut self) {
        let detached = self.control().state.compare_exchange(
            JOINABLE,
            DETACHED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        if detached.is_err() {
            let _ = self.reap();
        }
    }
}