# oscall: design
oscall is the layer between a program and the operating system: one API for
files, memory, networking, time, threads and processes that behaves the same
on Linux, macOS and Windows, that works in a
[fullrust](https://github.com/KarpelesLab/fullrust) binary, where there is no
libc at all, and that compiles to WebAssembly, where it offers what WASI has.
[internals.md](internals.md) describes how the crate is put together.
It sits below `std`: no buffering, no hidden allocation, no global state. Every
call maps onto one OS operation, or onto the few that are needed to give the
same result everywhere.
## Design rules
1. **No dependencies.** Not `libc`, not `windows-sys`, not `rustix`. Every
system call number, structure layout and import is declared in this crate.
That is what lets one source tree build for fullrust, where `libc` cannot
link, and it keeps the crate usable at the very bottom of a dependency graph.
2. **`no_std` first.** The core needs neither `std` nor an allocator. `alloc`
adds the calls that must allocate (long paths, directory listings); `std`
(default) adds conversions only: `std::io::Error`, `OwnedFd`/`OwnedHandle`,
`Path`.
3. **Two layers.**
- `sys`: the raw platform layer, one backend per system. The module is
private, and what a direct call to the system needs is public as
`oscall::raw`, one sub-module per system and `unsafe` where the system
is: the system call itself, its numbers and the error numbers on Linux;
`errno`, `GetLastError`, `NTSTATUS` and path conversions elsewhere,
where the functions are the system libraries' own. Handles convert to
and from the system's raw handles, so anything oscall lacks can be done
next to it, on the same handles and with the same errors.
- Everything else: portable and safe wherever the operation allows it,
built only on `sys`.
4. **Portable by default, platform-specific by name.** A portable function
behaves the same on every OS. What only one OS offers lives in an extension
module named after it (`oscall::mem::linux::remap`), never as a portable
function that fails elsewhere. WebAssembly is the one exception: it lacks
whole subsystems (memory mapping, sockets, processes), and there the
portable functions fail with `ErrorKind::Unsupported`.
5. **Errors are the OS's own.** `Error` holds the raw code (`errno`, or
`GetLastError`/`WSAGetLastError`/`NTSTATUS`) and maps it to a portable
`ErrorKind` on request. Nothing is lost in translation and no thread-local
`errno` is involved on Linux.
## Backends
### Linux and fullrust: raw system calls
One backend serves both, selected with
`any(target_os = "linux", target_os = "fullrust")`. fullrust is not
`cfg(unix)`, so nothing in the crate may be gated on `cfg(unix)`.
- System calls are made with inline assembly (`syscall`, `int 0x80`, `svc 0`,
`ecall`): one small module per architecture, `syscall0`..`syscall6`. Stable
inline assembly covers all six architectures on Rust 1.95.
- The system call numbers and kernel structures are per architecture. The
tables are generated from the kernel headers by a script kept in the
repository, and committed.
- 32-bit targets use the 64-bit time and offset calls (`clock_gettime64`,
`statx`, `_llseek`/`pread64`, ...) so that the API is identical to 64-bit.
- Known hazards to design around:
- `arm` in Thumb mode and `x86` with PIC reserve `r7`/`ebx`, which the
system call convention needs: the assembly must save and restore them.
- `clock_gettime` is only fast through the vDSO, and with no libc there is
no dynamic linker to find it: oscall reads `AT_SYSINFO_EHDR` from
`/proc/self/auxv`, checks that the image is readable before reading it,
parses it with bounds-checked code and calls its `clock_gettime`,
falling back to the system call whenever any of that fails or the
function does not answer. riscv32 has no clock in its vDSO.
- When a libc is present in the process (plain Linux targets), oscall
bypasses it. That is fine for most calls, but not for what libc keeps
state about: thread creation and the program break are left alone;
children are created with `clone(CLONE_VM | CLONE_VFORK)` and run nothing
but system calls until `execve` (without `CLONE_VM` when the child
changes its user or group, which the kernel records on the memory;
`process::unix::fork` exists, is `unsafe`, and leaves its child the
same rule); signal handlers are installed with
oscall's own restorer, only record the signal, and the previous
disposition is put back when the subscription ends.
### macOS: libSystem
The kernel's system call interface is private and changes between releases;
`libSystem` is the supported boundary, and every Rust binary already links it.
oscall declares the functions it uses in its own `extern "C"` blocks, with the
structure layouts for x86_64 and aarch64. The backend is gated on
`target_os = "macos"`; iOS and the other Apple systems can share it later.
### Windows: kernel32, ntdll, ws2_32
Imports are declared with `#[link(kind = "raw-dylib")]`, so no import library
and no `windows-sys` is needed, on MSVC and GNU toolchains alike. Paths are
UTF-8 in the API and converted to UTF-16 at the call (on the stack when short,
on the heap with `alloc`). Sockets are a separate handle type from files, as
they are in the OS.
### WebAssembly: WASI preview 1, or nothing
On `wasm32-wasip1` (and `wasm32-wasip2`, through its preview 1 adapter) oscall
declares the `wasi_snapshot_preview1` imports itself. Files, clocks, random
numbers, polling, the arguments and the environment work, as do the sockets
the host opened for the module (accepting, sending, receiving, shutting
down). The rest fails with `Unsupported`, because preview 1 has no call for
it: memory mapping, creating, binding or connecting a socket and its
addresses and options, name resolution, processes and signals, threads,
pipes, duplicating a handle, locks, permissions, the space of a filesystem,
a current directory and canonical paths, the boot-time clock. Every call of preview 1 was gone
through: `sys/wasi/mod.rs` lists each with what uses it, and the five that
nothing uses (`fd_advise`, `fd_renumber`, `fd_tell`, `fd_fdstat_set_rights`,
`proc_raise`) with the reason.
On `wasm32-unknown-unknown` there is no system interface: the crate compiles,
and everything that needs a system fails with `Unsupported`.
## Non-goals
- **A portable function that creates a thread.** Threads are created per
system: `thread::macos::spawn` and `thread::windows::spawn` are safe and
their threads are whole, `thread::linux::spawn_raw` is `unsafe` and its
thread may only run code that needs no runtime. The reason is what a
thread is on Linux, as read in the sources of each runtime:
- The kernel's `clone` gives a thread a stack and a value for the
thread-pointer register, and nothing else. What that register points
to (thread-local storage, and what a runtime keeps there) is the
runtime's to build. glibc and musl build it in `pthread_create` and
offer no way to build it for a thread made otherwise. The `std` of
fullrust builds it in its own `clone` wrapper, which is a hidden
symbol: it exports nothing a thread could be created or adopted
with, and its allocator finds the heap of the thread through that
block on every call, so that a thread which has the block of its
creator shares a heap that takes no lock, and one with no block
faults at its first allocation.
- So a thread oscall makes on Linux cannot allocate (fullrust; with
glibc the allocator's per-thread cache is the same hazard), cannot
call `std`, cannot have a `thread_local!`, cannot panic. That is the
contract of `spawn_raw`, which holds on the six architectures and
under fullrust, and which no safe function can ask of its caller.
- Importing `pthread_create` where the target has a C library
(`target_env = "gnu"` or `"musl"`) would make whole threads there. It
was weighed and left out: fullrust has no such function, so the
result would still not be portable; a program that links oscall
without a C library (`tests/freestanding`, which is how riscv32 is
reached) would no longer link; and "no libc on Linux" is the property
the rest of the crate is built on.
- macOS and Windows have no such split: `pthread_create` and
`CreateThread` are the system's, the thread they make has everything,
and `std` adopts a thread it did not create when the thread first
asks it something.
A portable function would have to hold to the weakest of the three
contracts, and be `spawn_raw` under another name. A program that wants
threads everywhere has `std::thread`, the runtime's own way in.
- **Setting an environment variable, or changing the arguments.** Reading
them is there (`process::args`, `process::vars`). The environment a
running program changes is a structure of its runtime: the C library's
`environ`, which `setenv` reallocates under readers that take no lock
(why `std::env::set_var` is `unsafe`), or the private map of fullrust's
`std`. Nothing outside the runtime can change it soundly, and on Linux
oscall cannot even find it: what it reads there is what the kernel
kept, the environment the process was *started* with. A child is given
its environment by `Command::env`.
## Targets
| Linux | tested | tested | tested | tested (qemu) | tested (qemu) | tested (qemu)¹ |
| fullrust | tested | tested | tested (qemu) | tested (qemu) | —² | — |
| macOS | tested | — | tested | — | — | — |
| Windows | tested | tested | tested | best effort³ | — | — |
1. Rust has no `std` build for riscv32 Linux (tier 3), so it is tested with
a nightly toolchain that builds one (`-Zbuild-std`), outside the stable
path: a CI job that reports without blocking lints the target, runs a
program with no libc at all (`tests/freestanding`) and runs the whole
test-suite as static musl binaries, all under qemu-user
(`scripts/riscv32.sh`; musl 1.2.6 or later, qemu 10). Its
vDSO has no clock: reading one is a system call there.
"qemu" is qemu-user, which emulates a program and answers its system calls
itself: it has no `clone3` (checked up to the sources of qemu 11.2), creates
no process in a new namespace and has no `seccomp`. What it cannot run is run
elsewhere, on a kernel of the architecture: arm natively on GitHub's arm64
runners, whose processor and kernel run 32-bit programs, and riscv64,
riscv32 and arm in virtual machines (`scripts/vm.sh`, a CI job that reports
without blocking). See [Testing](#testing).
2. fullrust has no RISC-V target yet. Since the Linux backend is the same,
supporting it will only need the CI entry.
3. 32-bit ARM Windows is tier 3 in Rust and no longer shipped by Microsoft.
Nothing in the crate excludes it; nothing tests it.
"—" means the OS does not exist on that architecture.
WebAssembly: `wasm32-wasip1` is tested (wasmtime); `wasm32-wasip2` and
`wasm32-unknown-unknown` are type-checked.
## What exists
Every module below is implemented on every backend, with integration tests
that run on every tested target.
| `oscall` | `Error`, `ErrorKind`, `Result`; `OwnedHandle`, `BorrowedHandle`, `AsHandle`; `AsPath` |
| `oscall::mem` | page size; anonymous and file mappings, anywhere, at a free address or inside a placeholder (`MapOptions`); shared memory with a handle; protect, reserve/commit/decommit, advise, flush, lock; executable memory and the instruction cache; an owning `Mapping` |
| `oscall::io` | read/write, positional and vectored I/O, seek, pipes (blocking or not), duplicate, standard handles, inheritance |
| `oscall::fs` | open, metadata, permissions, times, locks, links, rename, copy, space, preallocation, directory listing, and the same operations relative to a directory handle |
| `oscall::time` | wall clock, monotonic, boot-time and CPU clocks (through the vDSO on Linux), sleep |
| `oscall::rand` | the system random generator |
| `oscall::sync` | wait/wake on an address (futex, `os_sync_wait_on_address`, `WaitOnAddress`) |
| `oscall::thread` | the current thread: id, yield, parallelism, name; creating threads is per system, in the extensions |
| `oscall::net` | sockets (IPv4, IPv6, Unix-domain), addresses, options, vectored I/O, interfaces; name resolution by the system's resolver (`resolve`, `reverse`), and a DNS client of oscall's own (`net::dns`) |
| `oscall::event` | stateless `poll`, and a `Poller` (epoll, kqueue, I/O completion port with AFD) that waits for sockets, timers (one-shot and periodic), signals, child processes that exit, and wake-ups from other threads |
| `oscall::process` | ids, exit, the arguments and the environment the process was started with, spawning children, wait, kill, resource usage, termination requests (signals, console events); setting a child up and containing it is per system, in the extensions |
| `oscall::raw` | the escape hatch, per system: `raw::linux` (`syscall0`..`syscall6`, `syscall!`, `check`, the system call numbers `nr`, `errno`), `raw::apple` (`errno`, `last_error`, `cvt`), `raw::windows` (`last_error`, `cvt`, `nt_error`, `with_wide`, `wide_to_wtf8`, `dll!`), `raw::wasi` (`errno`, `cvt`), and `raw::with_cstr` |
What only one family of systems has is in extension modules named after it:
`mem::linux` (remap, huge pages, populating, more advice, locking
everything; what is mapped, as a list and at an address, and which pages
are in memory), `mem::macos` (`MAP_JIT`, regions), `mem::windows` (regions,
large pages),
`mem::unix` (access patterns), `io::linux` (io_uring: the ring and its two
queues, also with a kernel thread that submits, with entries of twice the
size, started disabled and restricted; typed entries for reads, writes,
sockets and messages, zero-copy sends, timeouts, cancelling one or many,
polling, files and names, `splice`, futexes, waiting for a child,
messages to another ring and driver commands, with the multishot forms of
accepting, receiving, polling and timing out; groups of buffers the kernel
picks from, provided by entries or in a ring that owns them; the raw entry
for the rest; registered buffers, files, tables of files that are updated,
event descriptors, the workers and the ring's own descriptor),
`io::windows` (handles and pipes
opened for overlapped operation, files opened without the system's cache,
named pipes and their servers, a completion port and what a handle tells
it, and an operation that owns the memory the system writes to, or is
given memory the caller keeps: reads and writes, into one buffer or into
pages, receives and sends with several buffers and with addresses,
accepting and connecting, sending a file on a socket, waiting for the
client of a pipe, and for changes in a directory), `io::macos` (POSIX
asynchronous I/O for files: an operation that owns the memory of a read, a
write or a flush, or is given memory the caller keeps, several started
with one call, waiting for one of several, being told by a signal that a
poller waits for, cancelling, and the limits of the system),
`fs::unix` (owners, FIFOs, extended attributes), `fs::windows` (file
attributes, the right to execute a file that is opened),
`fs::linux` (mounting by type, bind mounts, remounting, propagation, moving
and unmounting, `pivot_root`, `chroot`; and the same on handles: a
filesystem configured in steps and mounted nowhere, a tree opened or
copied, attached and moved, the settings of a whole tree changed at once,
and mounts that map the owners of files; what is mounted, by the calls
that list mounts and describe one), `net::unix`
(socket pairs, handle passing, peer credentials), `net::linux`,
`net::windows`, `event::unix` (polling any handle), `event::windows` (waiting
for any waitable handle), `thread::linux` (affinity, the nice value of a
thread, and `spawn_raw`: a thread made with `clone` on a stack with a
guard page, joined or detached, for code that needs no runtime),
`thread::macos` and `thread::windows` (creating threads, from a closure or
from a function and a number without allocating, with a name and a stack
size, joined or detached; where the stack is; a quality of service class
on macOS, a priority and affinity on Windows), `process::unix` (signals, groups and sessions,
limits of the process and of a child, the user, groups and file creation
mask of a child, `fork`), `process::linux` (namespaces, the maps of a
user namespace and the clock offsets of a time namespace, process
descriptors, starting a child in new namespaces or
in a cgroup, `prctl` attributes, a signal for the child whose parent goes
away; capabilities: the sets of a thread, the bounding and ambient sets,
the secure bits, what a child keeps of them, and those of a program
file; `seccomp`: filters and
strict mode for a thread, a filter for a child, a writer of allow and
deny lists, and a supervisor that answers the calls a filter hands it,
for a thread or for a child; Landlock: rulesets for files, ports and
scopes, for a thread or for a child; `ptrace`: a child traced from its
start, a thread taken while it runs, its stops, registers, memory and
system calls, and the calls a filter hands to a tracer; a wait that
reports stops, for one child or any; the memory and the handles of
another process; the user and groups of the calling thread; `uname`),
`process::windows` (console groups and events, job objects: limits
on memory, processor time and the number of processes, accounting,
terminating a whole tree, also when the parent ends; the privileges of
the process's access token: looking one up, whether it is held, enabling
and disabling it).
## Not there yet
- **A portable interface for completion-based I/O.** Each system's own is
there: io_uring in `io::linux`, overlapped I/O and completion ports in
`io::windows`, POSIX asynchronous I/O in `io::macos`. Nothing portable is
made of them, and the question was asked twice.
The wide one, "submit any operation on any handle with a token, wait for
completions", has no operand the three share. macOS takes what has
positions and refuses pipes and sockets. Windows completes on handles
made for it, and only those: a handle is overlapped from its creation and
belongs to one port for its whole life, and the handles `fs::open` and
`io::pipe` return are refused by a port. And a send on a stream completes
on Windows when everything was taken, on Linux with what fitted.
The narrow one is what all three do have: reading and writing a file at
an offset, and flushing it, on a handle opened for the purpose, each
submitted with a token and collected with a timeout. The outcomes can be
made the same (the end of a file is a count of zero on Linux and macOS
and an error on Windows, which a backend translates; a cancelled
operation is `Canceled` on all three). What cannot is what "submitted"
means. All of this was measured, on the CI runners and under
`scripts/check.sh`, except where it says otherwise:
- **Linux has io_uring only where it is allowed.** Docker's default
system call filter answers `EPERM`, as does
`kernel.io_uring_disabled` by the kernel's documentation; qemu-user
answers `ENOSYS`. A portable function may not fail for want of a
feature, so something would have to stand behind it there, and nothing
that does completes later. The kernel's older interface (`io_setup`,
`io_submit`) passes Docker's filter and is missing from qemu-user
(`ENOSYS`), and it does a buffered operation inside the call that
submits it: `io_submit` of a read of an empty pipe returned when the
pipe was written to, 300 ms later, and that of a file with the read
done. (It is documented to run in the background for files opened
with `O_DIRECT`, which wants aligned buffers and offsets and which not
every file system has; that was not tried.) What is left is to do the
operation in the caller, when it submits or when it waits: then nothing
proceeds between the two, and the timeout of a wait cannot bound a
read, which takes as long as the storage takes. A program could not
tell which of the two it has: its reads would run in the kernel on one
machine and block it in a container on the same machine.
- **Windows does the work in the call that starts it.** On a file opened
for overlapped operation as `fs::open` opens files, a write of 256 MB
took 0.7 to 1 s *to start*, and was complete when the start returned;
so with a write that extends the file and one that does not, with a
read (66 ms) of what the cache held, on x86_64 and on aarch64. A read
of what the cache does not hold is pending, and nothing tells a
program which it will be. Without the cache
(`FILE_FLAG_NO_BUFFERING`, `io::windows::open_unbuffered`) reads and
writes do complete later (32 MiB: 0.3 to 6 ms to start, 5 to 528 ms
to complete), but a write that extends the file is done in the call
all the same (all of its 7.6 to 119 ms), and the offsets, the lengths and the
addresses of the memory must be multiples of a sector, which is
`O_DIRECT` and its alignment again: not a rule a portable function
could hide. And flushing has no overlapped form: `FlushFileBuffers`
waits.
- **macOS runs them in the background, sixteen at a time.** A process
has 16 operations (`kern.aioprocmax`), everything in it that uses
asynchronous I/O together and counting those that are over and were
not collected, and the system 90 (`kern.aiomax`): one more is refused,
where a ring takes thousands. Up to macOS 15 the refusal is `EAGAIN`
whatever its cause, a closed handle included, so that "try again
later" and "never" look the same; and four threads run the operations
of every process of the machine. Nothing queues completions (`kevent`
refuses `EVFILT_AIO`): a wait names the operations it waits for. And
flushing wants a handle open for writing, and is `fsync` (by the
kernel's sources) where `fs::sync_all` is `F_FULLFSYNC`.
One call would thus block for the length of the operation on Windows,
return at once on macOS for sixteen operations and be refused for the
seventeenth, and do one or the other on Linux as the container has it.
That difference is the only thing such an interface is for.
What the three have in common is waiting until a socket is ready and
then doing the operation, which is `event::Poller`. A program that wants
completions takes the extension of its system, and falls back on the
poller where io_uring is refused.
- **libdispatch's I/O on macOS** (`dispatch_io`, `dispatch_read`,
`dispatch_write`): looked at, and left out. What the system declares of
it takes blocks. Variants that take a function and a context are in
`libSystem` too (`dispatch_read_f`, `dispatch_io_read_f` and the others:
found on macOS 15 and 26) and are private to libdispatch (its sources
declare them in a private header; that the SDK has none for them was
not checked on the runners): nothing to build on. A block can be made without a
compiler that knows them (one made by hand in a test was called by
`dispatch_read`, with its data), so the public functions could be
called. What cannot be had is the shape of the rest of this crate: the
outcome goes to code that libdispatch runs on a thread of its pool, as
an object of the library's to copy out of and release. The program's
code would run there, which no module of oscall does to it, or oscall
would keep a queue of outcomes and something for a poller to wait on:
state of the process and threads behind a call. What libdispatch does
on those threads is `read` and `pread`, which a program with threads
does with `io`; what the kernel does itself is `io::macos`.
- **Asynchronous I/O on macOS without allocating**: an `Operation` keeps
its control block on the heap, which is what lets it be moved and
forgotten while the kernel knows the block by its address. A form on a
block the caller pins would be `unsafe` from end to end.
- **More of io_uring.** What `io::linux` leaves to `Sqe::from_raw`, or
out:
- *Direct descriptors* (an accept, an open or a socket whose file goes
straight into the table of registered files and has no number): each
constructor would need a second form, and the multishot accept a
third. The table itself is there (`register_files_sparse`,
`register_files_update`).
- *Bundles and incremental buffer rings* (`IORING_RECVSEND_BUNDLE`,
`IOU_PBUF_RING_INC`, Linux 6.10 and 6.12): a completion then covers
several buffers, or part of one that stays the kernel's. `BufRing`
keeps one state for each buffer, held by the program or not, which is
what makes reading one safe; these need another type, not a flag on
this one. `recvmsg` as a multishot is left out for a like reason: its
buffers start with a header of the kernel's.
- *What a registered ring descriptor cannot be made*: safe against use
from another thread. The registration belongs to the thread, a `Ring`
can be sent, and nothing in a process without thread-local storage
tells one thread from another short of a system call, which is what
the registration is there to save. `register_ring_fd` says so, and
another thread gets an error (measured: `EINVAL`), unless it has
registered a ring of its own at the same index.
- *Options of the ring* that change who owns the memory or the protocol
of the queues: `NO_MMAP`, `NO_SQARRAY`, `IOPOLL`, `REGISTERED_FD_ONLY`,
mixed entry sizes (Linux 6.18 and later), and resizing. Entries of
twice the size *are* there (`Setup::sqe128`, `Setup::cqe32`): the ring
learns the sizes when it is made and indexes by them, `push_wide` and
`pop_wide` carry the other halves, and the ordinary calls work on
such a ring. A second ring type, or a constant parameter, would have
doubled the interface for the sake of one operation (`uring_cmd`).
What could be executed of it: every combination of the two sizes with
no-operations, the second half of a completion with the kernel's
`IORING_NOP_CQE32` (Linux 6.18), and the commands of sockets, which
fit an ordinary entry. No device at hand takes a command of 80 bytes
(NVMe, ublk): that the second half of an *entry* reaches a driver is
by the kernel's sources only.
- *A setup option the kernel lacks is `InvalidInput`*, not
`Unsupported`: there is no ring to ask yet. For everything else the
ring asks once, when it is made (`IORING_REGISTER_PROBE`), and
`Ring::push` refuses an operation the kernel does not have before it
is queued; a registration the kernel answers `EINVAL` to is
`Unsupported` when an operation of the same release is missing too.
What neither covers is a *flag* of an operation the kernel has (the
multishot forms, cancelling by handle): `InvalidInput` in the
completion, as the kernel says.
- The remaining operations (`openat2`, `epoll_ctl` and `epoll_wait`,
extended attributes, `sync_file_range`, `ftruncate`, `bind` and
`listen`, `pipe`, updating a timeout or a poll, installing a
registered file as a descriptor, receiving without a copy) and
registrations (personalities, NAPI, clocks, cloned buffers, memory
regions).
- **More of overlapped I/O**: control data with a datagram (`WSARecvMsg`,
`WSASendMsg`: `net` has no control data on Windows to give them a
meaning); several buffers the caller keeps (the forms on kept memory
take one, or pages); what `TransmitFile` can send before and after the
file, and `TransmitPackets`; registered buffers (`RIO`); the access list
of a named pipe, and acting as its client (the pipes of `pipe_server`
have the default one, and a client lets itself be identified, no more);
the extended records of a watched directory
(`ReadDirectoryChangesExW`); and `Operation`s that do not allocate.
- **More of name resolution.** `net::resolve` asks the system's resolver
on macOS and Windows, and on Linux, where the kernel has none and the C
library's is out of reach, a resolver of oscall's own: `/etc/hosts`,
then the servers of `/etc/resolv.conf` over UDP, and TCP when an answer
is cut. Not there on Linux: `/etc/nsswitch.conf` and the sources it can
name besides files and DNS (multicast DNS, LDAP, `systemd-machined`),
talking to `systemd-resolved` otherwise than as the name server
`resolv.conf` says it is (D-Bus, varlink), a cache, the options of
`resolv.conf` beyond `ndots`, `timeout` and `attempts`, and the sorting
of addresses by RFC 6724 (IPv6 comes first, and what the machine has no
route to last). Not there anywhere: names in other scripts (IDNA: the
caller converts), DNSSEC validation, EDNS, DNS over TLS or HTTPS,
records other than addresses and pointers (`SRV`, `MX`, `TXT`), services
by name, and a lookup that does not block: the system resolvers of macOS
and Windows have asynchronous forms (`GetAddrInfoExW`,
`getaddrinfo_async_start`) that share no shape, and the DNS client
waits on one socket at a time.
- **Where the stack of a thread is, on Linux.** macOS and Windows record
it (`thread::macos::stack_bounds`, `thread::windows::stack_bounds`). The
Linux kernel does not: a C library remembers what it allocated, and for
the first thread reads `/proc/self/maps`. `mem::linux::query` on the
address of a local variable answers the same question the same way: it
gives the mapping the stack is in, which is not the stack when the
kernel has merged it with a neighbour.
- **A portable priority for a thread.** A nice value (Linux, per thread
there), a quality of service class (macOS) and a priority within a
priority class (Windows) are three scales with no meaning in common:
each is in its extension.
- **Mapping over an arbitrary mapping** (`MAP_FIXED` proper) and **address
hints**: Windows has neither. `MapOptions::at` fails when the address is
taken, and `MapOptions::in_placeholder` replaces part of a placeholder,
which is what every system can do.
- **A portable `mem::query`.** Each system now says what is mapped at an
address (`mem::linux::query`, `mem::macos::query`,
`mem::windows::query`), and nothing portable is made of the three,
because what they answer about is not the same thing:
- *What a region is.* Windows answers for the pages from the one asked
about to the end of those that are like it *within one allocation*:
two mappings side by side are two answers, and the start of the
answer is the address asked, not the start of anything. Linux and
macOS answer with an entry of the kernel's map, which starts before
the address, and which the kernel merges with its neighbours when it
can and splits when a part of it changes: two mappings side by side
are one region or two as the kernel had it, and one mapping is
several once part of it is protected. The base and the length of the
same memory differ on the three; only "is this page mapped, and how
may it be accessed" could be the same.
- *What a page is.* Windows tells reserved from committed from free,
and a placeholder is reserved; on Linux and macOS a reservation is a
mapping without access, which nothing tells from memory that was
protected so. Windows reports a page that is copied when written as
writable and a guard page as what it becomes; macOS has two
protections, the current one and the most it can be given.
- *What it costs, and whether it can be asked at all.* One call on
Windows and macOS. Linux has no call: the question is put to
`/proc/self/maps`, by an `ioctl` since Linux 6.11 (open, ask, close)
and before that, as under qemu-user, by reading the file until the
address is passed, which takes the longer the more mappings the
process has. And `/proc` may not be mounted (the
first process of a machine, a `chroot`), or may be refused to a
process that is not dumpable: a portable function may not fail for
want of that.
A program that asks is one that knows which system it is on.
- **A child that ends with its parent, on macOS.** Linux has the parent
death signal and Windows a job that is closed with its last handle; macOS
has nothing the parent can set on a child, which has to watch for its
parent itself. There is therefore no portable form either.
- **Containing a child's resources portably.** Limits are `RLIMIT_*` values
on Linux and macOS and job limits on Windows, which do not count the
same things; a tree of processes is only held together by a Windows job
(and by Linux cgroups).
- **What is left of a container on Linux.** `process::linux` and
`fs::linux` have the namespaces, the cgroup of a child, capabilities,
system call filters with their supervisors and their tracers, Landlock,
`ptrace`, and mounts, by paths and by handles, listed and described,
that a container is made of. Not there: anything that manages cgroups
(they are files: `fs` reads and writes them); the mounts of *another*
mount namespace (`statmount` and `listmount` take one since Linux 6.11)
and being told when mounts change; of `ptrace`, what one architecture
alone has (hardware breakpoints and watchpoints, the register sets
beyond the general ones as structures: they are read as bytes), a
tracer that follows every thread of a process (the requests are there;
the bookkeeping is the program's), changing the call a tracee is about
to make other than through its registers (`PTRACE_SET_SYSCALL_INFO`,
Linux 6.16), and reading the filters of a tracee; Landlock for every
thread of a process at once, which Linux 6.18 has no flag for.
`raw::linux` makes those calls meanwhile.
- **Extended attributes as a portable thing.** Linux and macOS have them
(`fs::unix`), with names that mean different things; Windows has
alternate data streams, which are files within a file, opened and read
like files, and not values: nothing is made of them.
- **A root directory as an option of `Command`.** Building a root is a
sequence of mounts that depends on what is built and can fail half-way,
where the child of `spawn` makes a fixed list of system calls. The way is
a helper program that sets itself up and runs what it contains:
`fs::linux` says how.
- **An identity for the whole process on Linux.** `process::linux` changes
the user, the groups and the capabilities of the calling *thread*, which
is what the kernel does; a C library tells every thread, with a signal
it reserves. oscall cannot do that behind the runtime's back, and offers
what is safe: a child, which has one thread.
0.1.0 is the first release with every module on every backend. The API may
still change between 0.x releases, as what uses it shows what is missing.
## Testing
- Every portable function has tests that run on all tested targets: natively
on the Linux, macOS and Windows runners (x86_64 and aarch64 each), as static
musl binaries under qemu-user for arm and riscv64, and with the fullrust
action for its four targets. riscv32 runs the same tests with a nightly
toolchain, in a job that does not block.
- `tests/freestanding` is a program with no libc and no `std` (its own entry
point, `core` and oscall only) that calls a little of every module: the
proof that the Linux backend needs nothing else, on the host and on
riscv32.
- Where `std` offers the same operation, tests compare oscall's result with
`std`'s (same file contents, same metadata, same error kind).
- What depends on the environment (user namespaces, a writable cgroup
hierarchy, a system call an emulator or a container's filter lacks) is
tested where the environment has it, and elsewhere the test says what it
skipped and why. `tests/process_linux_single.rs` has no test harness: it
must be a process with a single thread. io_uring is such a thing too:
its tests skip where there is none, and CI makes that a failure on the
runners that do have it (`OSCALL_REQUIRE_IO_URING`), so that they cannot
all skip unnoticed. What came after Linux 5.10 is tested where the
kernel has it and skipped, by name, where it is older; a kernel that
should have a thing and refuses it is a failure. The privileged
container and the virtual machines run these tests too: the first is
where they execute for fullrust, the second for riscv64, riscv32 and
arm on kernels of their own.
- Two kinds of runs exist to have that environment, and in them a test that
would skip for want of it fails (`OSCALL_REQUIRE_PRIVILEGED`):
- **A privileged container** (`scripts/privileged.sh`, part of
`scripts/check.sh`, and a CI job on the x86_64 and arm64 runners): root
with every capability, a cgroup hierarchy to write, no system call
filter. x86_64 and i686 as musl and fullrust binaries, aarch64 and
armv7 as musl binaries, all natively.
- **A virtual machine** (`scripts/vm.sh`, a CI job that reports without
blocking): a kernel built for the purpose and nothing in user space
but the tests, for riscv64, riscv32 and arm.
- **Where the `clone3` path of `spawn` has run**, which is assembly per
architecture: x86_64, i686 and aarch64 in the ordinary jobs (a time
namespace) and in the privileged container (a cgroup); arm natively on
the arm64 runners, in both; riscv64 in its virtual machine (a time
namespace and a cgroup); riscv32 and arm in theirs (a cgroup: their
32-bit kernels have no time namespaces). The other way into a cgroup,
for where there is no `clone3`, runs in the same places, in a helper
whose own system call filter takes `clone3` away.
- The tests of `process::linux` and `fs::linux` run no program but
themselves (a helper mode of the test binary): they also run where there
is no shell.
- **Where the rest of a container has run.** The mounts by handles need
the capability to mount: as root of a user namespace on a developer
machine, as root in the privileged container and in the virtual
machines, and nowhere else (GitHub's runners deny it to the root of a
user namespace, Docker's default filter to everyone, and qemu-user has
none of the calls). A mount that maps identifiers to those of other
users, a file capability with a root that is someone else's, and a
program that gets capabilities from its file, take the root of the
system: the privileged container and the virtual machines. The clocks
of a time namespace are moved wherever a child can be created in one,
GitHub's runners included (not on the 32-bit kernels of arm and riscv,
which have none, nor under Docker's default filter, which has no
`clone3`); the child that has to make its time namespace itself, for
having a copy of its parent's memory, is refused that on GitHub's
runners like any other use of a capability, and runs in the other
places. The supervisor of a filter needs nothing but `seccomp`: it runs
in every job that is not emulated, fullrust in a container included,
and the listener of a child comes back by the same path in all of them,
from a child that is the first process of a namespace too.
- **Where tracing, Landlock and the listing of mounts have run.** None
of them needs privilege, and none exists under qemu-user, where their
tests say so and skip.
- `ptrace`, with the registers of the architecture checked against
what the kernel says of a system call: x86_64 and i686 natively and
under Docker's default filter, which lets it through, aarch64
natively on the arm64 runners, arm natively there in the privileged
container and on its own kernel in a virtual machine, riscv64 and
riscv32 in theirs. A single step is taken on the x86_64 and aarch64
kernels, by their 32-bit programs too, and refused by the kernels
of the three virtual machines. `tests/process_linux_trace.rs`
has no harness: a tracer and its tracee are threads, the first of
their processes here.
- The memory of another process in the same places; its handles
(`pidfd_getfd`) where no container's filter stands in the way: the
runners themselves, the privileged container, the virtual machines.
- Landlock wherever the kernel runs it, Docker's default filter
included: files, ports and signals are refused to a helper process
that restricted itself, and to a child restricted by its command.
The kernels of the virtual machines are built with it.
- `statmount` and `listmount` on what is mounted where the tests run
(Linux 6.8), compared with `/proc/self/mountinfo`, and on mounts
made for the purpose wherever the mounts by handles run;
`open_tree_attr` there too, on a kernel that has it (6.15), as
those of the runners, of the developer machine and of the virtual
machines are.
- What is mapped (`mem::linux`) on every Linux target, qemu-user
included, where the file is read as text for want of the `ioctl`;
the `ioctl` on the kernels that have it (6.11), the 32-bit ones of
the virtual machines among them. A unit test asks both ways and
compares.
- **Name resolution never leaves the machine**: the DNS client is tested
against a name server the test runs on a loopback address (UDP and TCP,
answers that are cut, noise, silence, failures, several servers), on
every target that has sockets; the reader of messages is given malformed
and random ones in unit tests; and the system's resolver is asked for
`localhost` and for addresses only.
- **Where `thread::linux::spawn_raw` has run**, which is assembly per
architecture: x86_64 and i686 natively, aarch64, arm and riscv64 under
qemu-user and natively where CI has the processor, the four fullrust
targets, and riscv32 in `tests/freestanding`, a program with no runtime
at all.
- The MSRV (1.95) is checked on every push.