# oscall internals: how the crate is put together
Read this before adding to the crate. [plan.md](plan.md) has the goals; this
is the mechanics.
## Layout
```
src/lib.rs module declarations and re-exports
src/error.rs Error, ErrorKind, Result
src/handle.rs OwnedHandle, BorrowedHandle, AsHandle, RawHandle
src/path.rs AsPath; with_cstr / with_wide path conversion
src/macros.rs flags!
src/raw.rs the public raw layer: thin wrappers over `sys`
src/<module>.rs the portable, public API of a module (mem, fs, io, ...)
src/sys/mod.rs selects the backend and re-exports it as `crate::sys`
src/sys/<backend>/mod.rs the backend's core
src/sys/<backend>/<module>.rs the module's implementation on that backend
tests/<module>.rs integration tests of the module, run on every platform
tests/common/mod.rs test helpers (tmp_dir, skip)
tests/freestanding/ a package of its own: oscall with no libc and no std
tests/vm_init.rs not a test: process 1 of the machines of scripts/vm.sh
```
Backends: `linux` (Linux and fullrust), `apple` (macOS), `windows`, `wasi`
(WASI preview 1) and `unsupported` (`wasm32-unknown-unknown`).
A portable module is a thin, documented layer: types, argument checking that
is the same everywhere, and calls into `crate::sys::<module>`. Each backend
file exposes the same `pub(crate)` items, so `src/<module>.rs` contains no
`cfg` on the operating system, apart from platform extension modules.
## Rules
- **No dependencies**, and no `build.rs`.
- **`no_std`.** `core` only by default. Use `alloc` only behind
`#[cfg(feature = "alloc")]`, and offer an allocation-free form of the same
operation (caller-provided buffer) whenever one makes sense. `std` is for
conversions with `std` types only.
- **Safe wherever possible.** A function is `unsafe` only when memory safety
depends on the caller (mapping memory, raw pointers). Every `unsafe` block
has a `// SAFETY:` comment; every `unsafe fn` a `# Safety` section.
- **One call, one operation.** No retry loops hidden from the caller: an
interrupted call returns `ErrorKind::Interrupted` (closing a handle is the
exception). No global state, apart from lazily initialised facts that
cannot change (page size, `WSAStartup`).
- **Never panic on an operating system result.** Unexpected values become
errors.
- **Portable by default.** A function in a portable module does the same
thing everywhere. What one system alone offers goes in an extension module
named after it (`oscall::mem::linux`), gated on that system. The only
portable function that may fail for lack of a platform feature is one on
WebAssembly, which fails with `ErrorKind::Unsupported`; say so in its doc.
- **Portable values.** Flags and enumerations exposed in the API have oscall's
own values (`flags!`), translated by each backend. Never expose a system
constant's value in a portable type.
- **Paths** are taken as `&P where P: AsPath + ?Sized` and converted with
`path::with_cstr` (Linux, macOS), `path::with_wide` (Windows), or passed
as pointer and length (WASI).
- **Errors.** Return the system's own code: `Error::from_raw_os_error`. For a
condition oscall detects itself, `ErrorKind::X.into()`. If a new
`ErrorKind` is really needed, add it to `error.rs` and to every backend's
`ERRORS` table.
- **What a release published stays.** `cargo semver-checks --baseline-rev
v0.1.0 --all-features`, for a Linux target, `--target
x86_64-pc-windows-gnu` and `--target aarch64-apple-darwin`, must ask for
no more than a minor version. New variants go at the end of an enum;
new public enums and structures that may grow are `#[non_exhaustive]`;
and **an extension trait is sealed from its first release** (a private
supertrait, as in `process::linux`), because a method added to a trait
anyone may implement breaks whoever did. `process::linux::CommandExt`
was published open in 0.1.0 and has the methods it had then: what came
later is in `process::linux::ConfineExt`.
- **Documentation.** Every public item is documented (`missing_docs` is
denied in CI): what it does, which system call it maps to on each platform
when that is not obvious, and any difference in behaviour that could not be
hidden.
- **Tests.** Every public function has an integration test in
`tests/<module>.rs` that runs on all platforms, comparing with `std` where
`std` offers the same operation. Files go under `common::tmp_dir(name)`.
A test that cannot hold on a platform is `cfg`'d out for that platform
alone, with a comment saying why.
## Linux and fullrust
`syscall!(NAME, args...)` makes a raw system call and returns
`Result<usize>`; it must be used in an `unsafe` block. `crate::sys::nr` has
the numbers of the target architecture, `crate::sys::errno` the error
numbers.
- The code must be identical for Linux and fullrust: never use libc, never
gate on `cfg(unix)` or on `target_os = "linux"` alone.
- **Use the modern system call of each family, everywhere**: aarch64 and
riscv do not have the legacy ones. `openat` not `open`, `statx` not
`stat`, `pipe2`, `dup3`, `ppoll`, `epoll_pwait`, `renameat2`, `mkdirat`,
`unlinkat`, `clone` not `fork`...
- **32-bit targets** (x86, arm, riscv32): use the 64-bit time and offset
variants (`clock_gettime64`, `futex_time64`, `ppoll_time64`, `mmap2`,
`_llseek` or `llseek`, `statx`, `fcntl64`...) with the 64-bit
`__kernel_timespec`. riscv32 has no 32-bit time calls at all. Check which
name exists in `nr` for each architecture and `cfg` on
`target_pointer_width` or `target_arch` accordingly.
- **64-bit arguments on 32-bit targets** are passed in two registers, and arm
wants the pair aligned to an even register (a padding argument), while x86
does not. Prefer calls that take the halves as separate arguments
(`preadv`/`pwritev` take `pos_l, pos_h`) to those that need per-architecture
argument lists (`pread64`, `ftruncate64`, `fallocate`, `fadvise64_64`).
- **Constants differ between architectures**, notably the `O_*` open flags
(arm and aarch64 swap `O_DIRECTORY`/`O_NOFOLLOW`/`O_DIRECT`/`O_LARGEFILE`
compared to x86 and riscv) and some `struct` layouts (`epoll_event` is
packed on x86_64 only; `sigaction`, `stat`, `flock`). Take every constant
and layout from the kernel sources (`/usr/src/linux/arch/*/include/uapi`,
`/usr/src/linux/include/uapi`), not from memory.
- The oldest kernel supported is 5.10.
- **The auxiliary vector** is read from `/proc/self/auxv` (`sys::auxv`):
nothing in a process without libc has a pointer to it. `/proc` may be
missing, so every user has a fallback.
- **The vDSO** (`sys::vdso`) is used for `clock_gettime` only. The image is
checked to be readable before it is read (the kernel is asked to read it
into a pipe), then parsed as a byte slice by safe code; any failure means
the system call is made instead. Symbol names and versions differ per
architecture: take them from the kernel's `vdso.lds.S`.
- **Creating a child** (`sys/linux/process.rs`): `clone(CLONE_VM |
CLONE_VFORK)` on a stack of its own, then system calls only until
`execve`. Four things change that, three of them in `process::linux`:
- A child that changes its user or group (`process::unix`) is created
*without* `CLONE_VM`. `commit_creds` sets the dumpable flag of the *mm*
to `fs.suid_dumpable` when the effective or filesystem ids change, and
with `CLONE_VM` the mm is the parent's (measured: after such a spawn
the parent's `PR_GET_DUMPABLE` was 0: no core dump, no ptrace,
`/proc/self` owned by root). Restoring the flag afterwards would race
with other threads that spawn. The child runs the same code, on a copy.
Anything added to the child that changes its identity, or that could
add to its permitted capabilities, needs the same. Giving capabilities
up does not: the kernel also sets the flag when the new permitted set
is not within the old one, and `capset`, `PR_CAPBSET_DROP` and the
ambient set never make it so (measured: the parent of a child that
drops its bounding set while sharing memory stays dumpable; a test
checks it).
- A child whose user namespace maps the parent writes is created *without*
`CLONE_VFORK`: the parent must run while the child waits (on a pipe).
The two then share memory and run at once; the stack and what the child
reads are kept until the error pipe says the child has called `execve`
or reported, and a child that could not be released is killed and
waited for before they are freed.
- `clone3` is used when `clone` cannot say it: a cgroup
(`CLONE_INTO_CGROUP`) or a time namespace (whose flag is one of the
bits `clone` keeps for the exit signal). The default system call
filter of Docker answers `ENOSYS` to `clone3`, and qemu-user has none:
for a cgroup the child is then created with `clone` and writes itself
to `cgroup.procs`.
- qemu-user turns `clone(CLONE_VM | CLONE_VFORK)` into a `fork`, and
refuses the `CLONE_NEW*` flags with `EINVAL`: nothing creates a child
in a namespace there. It also interrupts waits the kernel would not:
a `Poller::wait` of a test whose process has no signal handler came
back `Interrupted` in 10 runs of 240 (qemu 10.0.13, two processors,
the tests of `process_linux` in parallel; why was not established).
- **A failed `clone` leaves a pidfd number behind.** With `CLONE_PIDFD` the
kernel writes the descriptor's number to the caller's memory as soon as it
has reserved it, and frees the descriptor if the call fails later (a
cgroup that refuses the process, a dead process namespace) without
touching the number. Never take the value for a descriptor unless the
call succeeded: closing it closes what another thread opened since.
- **Namespaces belong to threads.** `unshare` and `setns` move the calling
thread, and threads created by it afterwards; a user namespace is refused
(`EINVAL`) to a process with more than one thread, which every test run
by the harness is. Such a test goes in `tests/process_linux_single.rs`
(`harness = false`), or is done by a child created in the namespace.
After `unshare(CLONE_NEWUSER)` a process has its capabilities in the new
namespace only: it writes its own maps by the rules of a process without
privilege, root included.
- **What the test environments allow of namespaces**, as measured. A
developer machine: everything but a writable cgroup. GitHub's Ubuntu
runners (AppArmor's `unprivileged_userns` profile, enforced): a child is
created in new namespaces, user, PID and time included, and its maps of
one identifier are written, as are the offsets of its time namespace
(the parent's doing, which the profile does not confine), but it may
not *use* a capability there (`sethostname`, a later `unshare`,
`/proc/self/setgroups`, writing `security.capability` all fail with
`EPERM`). Docker's default filter (the fullrust jobs): `EPERM` for
`unshare`, `setns`, `mount` and `clone` with a namespace flag, `ENOSYS`
for `clone3`, and a read-only cgroup hierarchy; `seccomp` itself is
allowed, and the process already has a filter (strict mode is then
refused, `EINVAL`). qemu-user: see above; it has no `seccomp` either
(`ENOSYS`, and `EINVAL` for `PR_GET_SECCOMP`), and the emulator is
itself a process with several threads. On GitHub's runners AppArmor
also denies mounting to the root of a user namespace. A cgroup can only
be written by root in a privileged container
(`docker run --privileged --cgroupns private`): `scripts/privileged.sh`
runs the tests there, and `scripts/vm.sh` in virtual machines, with
`OSCALL_REQUIRE_PRIVILEGED=1`.
- **Skipping.** A test that the environment keeps from testing says so
with `common::skip` (`skip!`), which fails when
`OSCALL_REQUIRE_PRIVILEGED` is set: in the runs that exist to cover such
things, a skip is a failure. What is not a matter of privilege (root may
write any map, the kernel of this architecture has no time namespaces)
is said with `note!` and passes everywhere. A program run as process 1
of a container has no parent and takes no signal it does not handle:
`scripts/privileged.sh` runs the tests under `docker run --init`.
- **`capget` is filtered by security modules, `/proc` is not.** Under
AppArmor's `unprivileged_userns` profile (GitHub's runners), the root
of a user namespace has every capability in `/proc/<pid>/status` and
none according to `capget` (measured), and the kernel's own checks
disagree: `PR_CAPBSET_DROP` asks the module and is refused, while
`PR_SET_SECUREBITS` looks at the credentials and succeeds. A test that
expects a refusal from the sets `capget` returned must first check that
they are what `/proc` says.
- **Credentials and filters belong to threads too.** `capset`, `prctl`
(the bounding and ambient sets, the secure bits, `PR_SET_NO_NEW_PRIVS`),
`setresuid`, `setresgid`, `setgroups` and `seccomp` change the calling
thread, and the threads it creates afterwards. libc's `setuid` family
interrupts every thread to make it a process-wide change; oscall does
not, says so in each function, and tests it (a thread that existed
before keeps what it had). A test that changes any of it does so in a
helper process, never in the harness: a filter or a dropped capability
cannot be taken back.
- **A filter built for one architecture ends programs of another.** The
programs `seccomp::build` writes start by checking the architecture of
the call and end the process when it is not the one they were built
for, as the numbers would mean other calls. A 32-bit process that
installs one and then runs a 64-bit program (measured: the i686 tests
running the x86_64 `/bin/sh` of a container) gets that program killed
at its first system call. A filter that must hold across architectures
is written by hand, as the test of the cgroup fallback does for
`clone3`, whose number is the same everywhere.
- **`pivot_root` cannot leave the initial file system of the kernel**
(rootfs, what an initramfs is unpacked into): `EINVAL`. `tests/vm_init.rs`
first moves to a tmpfs mounted over `/` (`MS_MOVE`, `chroot`), as
`switch_root` does. Mounting `proc` from a user namespace needs a process
namespace owned by it and a `/proc` of which nothing is hidden: in a
container that masks parts of `/proc` it is `EPERM`.
- **32-bit kernels of arm and riscv have no time namespaces** (Linux
6.18: `CONFIG_TIME_NS` needs a vDSO with clocks, which they lack); a
32-bit program on a 64-bit kernel has them. And musl on arm makes the
32-bit time system calls first for values that fit: a kernel built
without `CONFIG_COMPAT_32BIT_TIME` answers `ENOSYS` to `nanosleep`.
- **The offsets of a time namespace are written while it is empty**
(`EACCES` afterwards), and when a child enters the one it was created
for depends on its memory: a child that shares the memory of its parent
(`CLONE_VM`) enters when it runs its program, and one that has a copy
enters at once, in `clone` itself (as `kernel/nsproxy.c` of Linux 6.18
reads; the first is measured, the second is not). So the parent writes `/proc/<pid>/timens_offsets` of a
waiting child of the first kind, and a child of the second kind (one
that changes its identity, or has a filter) is created *outside* the
namespace, calls `unshare(CLONE_NEWTIME)` itself, tells the parent on a
pipe, waits for the offsets and enters with its program too. The file
of a process is about the time namespace of its *children*, and
`unshare` moves one thread: `set_time_offsets` writes
`/proc/<tid>/timens_offsets`, which exists for a thread that is not the
first although no listing shows it. An offset that would make a clock
negative is `ERANGE`, which reads as `BufferTooSmall`.
- **`/proc/<pid>` means the process `<pid>` of the process namespace
`/proc` was mounted in**, not of the caller's. A process that is the
first of a new process namespace and still has the old `/proc` cannot
write the maps of a child it spawns: the identifier `spawn` got names
someone else there. The helper of `tests/fs_linux.rs` that spawns a
child in a user namespace is therefore not given a process namespace.
- **The mount calls on handles** (`fs::linux`), as measured on Linux 6.18:
- `fspick` wants the root of a mount: a directory under one is
`EINVAL`.
- A mount `fsmount` made and a tree `open_tree` opened are handles of a
path alone (`O_PATH`): `fsconfig` on one is `EBADF`, where a file is
`EINVAL`. While one is open its mount is in use, and `umount` says
`EBUSY`.
- After `FSCONFIG_CMD_CREATE` another option, or a second creation, is
`EBUSY`; `fsmount` before it is `EINVAL`, and a second `fsmount`
`EBUSY`. What a filesystem says of an option it refused is read from
the handle (`e tmpfs: Unknown parameter '...'`), and reading when it
said nothing is `ENODATA`.
- `mount_setattr` wants the three bits of the access time setting
cleared whenever one of its values is set (`EINVAL` otherwise), and
"relative" is the value 0: the backend clears them for any mention of
the setting, in what is set or in what is cleared.
- Through a mount that maps identifiers, a file whose owner the map
does not have belongs to nobody, *and so does not answer to
`CAP_DAC_OVERRIDE`*: root of the namespace that mounted the
filesystem is refused (`EACCES`) by a directory of mode 750 it
created itself. Creating a file as a user the map does not have is
`EOVERFLOW`. The user namespace a map is taken from may not be the
one of the filesystem (`EINVAL`), and need not outlive the call.
- **What is mounted** (`fs::linux`: `statmount`, `listmount`), as
measured on Linux 6.18:
- The unique identifiers start above 2³¹, to be no short identifier of
`/proc/self/mountinfo`: one of those, given as a mount, a parent or a
place to go on from, is `EINVAL`, and a unique identifier that names
nothing `ENOENT`. `LSMT_ROOT` lists every mount of the namespace, the
one at its root included, in ascending order.
- A mount that is attached nowhere has an identifier (`statx` gives
it, on the handle) and is in no namespace: `statmount` says `ENOENT`.
- The file joins a type and its kind (`fuse.sshfs`), which `statmount`
gives apart. A buffer too small for the answer is `EOVERFLOW`, which
reads as `BufferTooSmall`.
- Docker's default filter (29) lets both calls through, and qemu-user
has neither (`ENOSYS`). The list of a machine that runs containers
changes while it is read: a test compares what stayed.
- The options of `fsconfig` that are paths (`FSCONFIG_SET_PATH`,
`FSCONFIG_SET_PATH_EMPTY`) are commands the kernel takes, for options
no filesystem at hand has: `tmpfs`, `proc`, `cgroup2` and `ext4`
answer `EINVAL` for theirs, `source` included ("Non-string source").
`FSCONFIG_CMD_CREATE_EXCL` creates a `tmpfs`, and is `EBUSY` for
`cgroup2`, of which there is one; after that refusal the
configuration takes nothing more (`EBUSY` for a plain creation too).
- `open_tree_attr` without `OPEN_TREE_CLONE` changes the mount that is
at the path, as `mount_setattr` would, and returns a handle of the
place.
- **Landlock** (`process::linux::landlock`), as measured (version 7):
- A restriction is the calling thread's, and of what it creates: a
thread that existed before goes on writing where the thread that
restricted itself no longer may. A seventeenth layer is `E2BIG`.
- A thread that may open nothing for writing cannot give a child the
null device: `spawn` with `Stdio::Null` opens `/dev/null` for
reading and writing, and fails with `EACCES`.
- A handle that is no ruleset is `EBADFD` (77), which is not `EBADF`;
a ruleset or a rule about nothing is `ENOMSG`.
- The child of `spawn` restricts itself first among the last things it
does: before `capset`, which may take away the capability that
stands in for "no new privileges", and before the filter. The
ruleset must survive the closing of every other descriptor, like the
error pipe: `ChildSecurity::kept`.
- Docker's default filter lets the calls through; qemu-user has none
(`ENOSYS`). The kernels of `scripts/vm.sh` are built with it.
- **Tracing** (`process::linux::ptrace`), as measured:
- *A tracer is a thread, and so is a tracee.* A request by another
thread of the tracer's process is `ESRCH`. The child of `spawn` that
traces itself is traced by its first thread alone; the threads it
creates are not, unless asked for (`PTRACE_O_TRACECLONE`). The test
harness runs a test on a thread of its own, with `--test-threads=1`
too (measured: Rust 1.100): a helper started by it would have its
code on a thread no one traces, and a signal sent to the process
goes to the first thread, which sits in a wait that a single step
only restarts. `tests/process_linux_trace.rs` has no harness for
that reason.
- *The status of a stop is whole in `waitid`*: `si_status` is the
signal, or `event << 8 | signal`, or `SIGTRAP | 0x80`, as `wait4`
has it above the low byte. riscv32 has no `wait4`.
- A wait for a child to stop, when the child has ended, is `ECHILD`,
with `WNOHANG` or without: it does not wait for nothing.
- `PTRACE_SINGLESTEP` is `EIO` on riscv64, riscv32 and 32-bit ARM
kernels (the three virtual machines), and steps on x86_64 and
aarch64 kernels, for their 32-bit programs too (i686, and armv7 on
the arm64 runners): the kernel counts, not the program. The test
says which it met.
- `PTRACE_GETSIGINFO` in a group-stop: a tracee that was seized
answers, with the status of the stop as `si_code`; one that was
attached says `EINVAL`, and its group-stop reports as the stop
signal coming a second time. Such a tracee is told nothing of a
`SIGCONT` until it is restarted.
- *A filter's `SECCOMP_RET_TRACE` is about the thread that makes the
call*: without a tracer of that thread that asked
(`PTRACE_O_TRACESECCOMP`), `ENOSYS`.
- Docker's default filter lets `ptrace`, `process_vm_readv` and
`process_vm_writev` through and refuses `pidfd_getfd` (`EPERM`);
qemu-user has no `ptrace` (`ENOSYS`: a child that is to trace itself
is not spawned). `process_vm_readv` needs a kernel built with
`CONFIG_CROSS_MEMORY_ATTACH`, which those of `scripts/vm.sh` are.
- **What is mapped** (`mem::linux`): `/proc/self/maps` is read through
a buffer of the structure, and answers `PROCMAP_QUERY` since Linux
6.11. Under qemu-user the file is the emulator's own account of the
program's memory and has no `ioctl`: `query` reads the text there,
which is also what a unit test does everywhere, to compare the two.
The name the `ioctl` gives has no escapes, and its size counts the
byte that ends it; the text writes a line feed as `\012`.
- **File capabilities** (`process::linux`), as measured: removing them
without `CAP_SETFCAP` is `EPERM` also when there are none, the kernel
asking before it looks; root of a user namespace writes revision 2 and
a reader above it finds revision 3 with the writer's root (the kernel
converts, both ways); a directory takes the attribute (xfs); `/proc`
has no extended attributes (`EOPNOTSUPP`). They do nothing on a
filesystem mounted `nosuid`, which is how docker mounts a `--tmpfs`:
`scripts/privileged.sh` asks for `suid`.
- **The listener of a child's filter** (`CommandExt::seccomp_listener`).
The descriptor exists once the filter is installed, is close-on-exec,
and from that moment the child may make no system call the filter could
refuse or hand to a supervisor that does not hold the listener yet:
it cannot send it, clear the flag, or wait. So the child, before the
filter, creates a process that shares its memory and its descriptor
table (`CLONE_VM | CLONE_FILES`), which has no filter. That process
waits on a futex for the kernel to clear the address the child gave
`set_tid_address`, which the kernel does, with a wake-up, when a
process whose memory is shared runs a program or ends; it then reads
the number the child stored (a write to memory, not a call) and sends
the descriptor to the parent over a socket (`SCM_RIGHTS`). It still has
the descriptor: `execve` gave the child a table of its own before it
closed anything. To leave the program no child it does not know, that
process is created by another that exits at once and is waited for
(`__WALL`: it has no exit signal): it is an orphan. It also holds the
write end of the pipe `spawn` learns of failures by, so `spawn` returns
when it has sent and gone. A listener's `SECCOMP_IOCTL_NOTIF_SET_FLAGS`
takes its flags as the argument itself, whatever its number says of a
pointer; and the `pid` of a notification is a *thread*. of a small process can read 0** (`ru_maxrss`:
the pages are counted per processor and added up in batches that grow
with the number of processors). Measured for a libc-free test program
started by a small parent on a machine with 192 processors; when the
parent is large it does not show, because the value survives `execve`.
- **io_uring** (`io::linux`; the system calls and the layouts are in
`sys/linux/uring.rs`).
- The structures shared with the kernel (`io_uring_sqe`, `io_uring_cqe`,
`io_uring_params`) have one layout on the six architectures: each
64-bit member is at a multiple of eight, so that the alignment of
`u64` (four on 32-bit x86) changes nothing. Their sizes are asserted.
Pointers go in 64-bit members, zero-extended. On 32-bit targets the
queues are mapped with `mmap2`, whose offset is in units of 4096
bytes: the kernel's three offsets are multiples of it.
- The queues: the program writes an entry and then the tail of the
submission queue (`Release`), the kernel the head; the kernel writes a
completion and then the tail of the completion queue, which the
program loads (`Acquire`) before it reads the entry, and the program
the head (`Release`). Without `SQPOLL` the kernel reads the submission
queue during `io_uring_enter` only, which is why `push` publishes the
tail at once and `submit` keeps no state: what there is to submit is
the tail less the head. The array of indexes the kernel reads entries
through is written once, as the identity.
- `Setup` has no option that changes who owns the memory of the
queues or how they are indexed (`NO_SQARRAY`, `NO_MMAP`). The sizes of
the entries can be doubled (`SQE128`, `CQE32`): the ring keeps a shift
for each queue, maps and bounds the arrays by it, and every index goes
through it; an ordinary `push` zeroes the second half of a wide entry.
- **A thread of the kernel that submits** (`SQPOLL`) reads the tail at
any time, which `push` already allowed for (the entry, then the tail
with `Release`). What it adds is the wake-up: the thread sets
`IORING_SQ_NEED_WAKEUP` and then looks at the tail once more, the
program stores the tail and then looks at the flag, and one of the two
must see the other: a full barrier (`fence(SeqCst)`) between the
program's store and its load, as liburing has. Measured on Linux 6.18:
`io_uring_enter` returns the count it was given, not what the thread
took; and the thread of a new ring is asleep at once on the 64-bit
kernels (x86_64, riscv64) and awake on the 32-bit ones (arm, riscv32)
for as long as the test waited, a minute. (The thread compares the
clock with a deadline that starts at 0, and the kernel's clock starts
five minutes before its 32 bits wrap: `sqpoll.c`, `INITIAL_JIFFIES`.
The cause is read from the sources, not measured.) Nothing may count
on either.
- **What is in flight is counted from the queue**: entries pushed, less
those the kernel has not taken (tail less head), less final
completions. Not from what `io_uring_enter` returns, which a thread
that submits never says, and which by the sources of Linux 5.10 leaves
out an entry that failed to start (not measured: no such kernel at
hand).
- **The ring asks what the kernel has when it is made**
(`IORING_REGISTER_PROBE`, one more system call in `Ring::new`), and
`push` refuses the entry of an operation that is not there. For a
registration the kernel says `EINVAL` whether it does not know it or
finds it wrong; `or_unsupported` makes that `Unsupported` when an
operation that came with the same release is missing (`MSG_RING` for
registered ring descriptors, 5.18; `SOCKET` for rings of buffers and
sparse tables, 5.19; `MKDIRAT` for the limit on workers, 5.15). The
affinity of workers came with 5.14, which brought no operation: the
witness is the feature `RSRC_TAGS` (5.13), one release early. None of
this could be run on an old kernel: every machine at hand, and CI,
has 6.x.
- **`Sqe::flags` drops `FIXED_FILE` and `BUFFER_SELECT`.** With the
second, the kernel writes to the memory of a group, which only an
`unsafe` constructor may ask for (`Sqe::buffer_select`): were the
flag settable in safe code, dropping a `BufRing` could free memory
under an operation that no `unsafe` block ever vouched for.
- **A ring of buffers** (`BufRing`): the tail the program writes is the
last two bytes of the *first entry* of the ring (`struct
io_uring_buf_ring` is a union), so an entry is written member by
member, never whole. One mapping holds the ring, a byte of state for
each buffer, and the buffers. `Drop` asks the kernel to forget the
group, through a duplicate of the ring's descriptor (the `Ring` may be
gone, and its number reused), and unmaps only if the kernel did, or
says there is no such group (`ENOENT`): a ring of one thread refuses
another thread's registrations (`EEXIST`), a restricted ring refuses
them all (`EACCES`), and the kernel would go on writing to the
buffers. The memory is then leaked.
- **Several completions.** As measured on Linux 6.18 (x86_64, and the
virtual machines): a multishot receive that finds no buffer ends with
`ENOBUFS` and no `IORING_CQE_F_MORE`; a multishot timeout of a count
ends with the flag cleared on its last expiry, with no completion
after it; cancelling by handle with nothing in flight completes with
0, not `ENOENT`, because all are asked for
(`IORING_ASYNC_CANCEL_ALL`). A zero-copy send to a socket that is not
connected fails with `EPIPE` *and* `IORING_CQE_F_MORE`, and its
notification follows: the kernel had started on it. Over the loopback
interface the kernel copies what a zero-copy send was given
(`IORING_NOTIF_USAGE_ZC_COPIED`), and still posts both completions.
- **The limit on unbounded workers reads as 0 when there is none**:
it starts as `RLIMIT_NPROC`, which the kernel keeps in an `int`
(measured: 0 for root in the privileged container, where the limit
is infinite, and a number everywhere else; the cause is read from
`io-wq.c`).
- **Completions deferred to the thread** (`DEFER_TASKRUN`): measured,
the completion of a read of a pipe was not in the queue 50 ms after
the pipe was written to, and was after `io_uring_enter` with
`GETEVENTS` and a count of 0. `Ring::ready` is no way to wait on such
a ring.
- **A registered ring descriptor is the thread's.** Entered from
another thread, the index names nothing there (measured: `EINVAL`
from a thread that never used io_uring; `EBADF`, by the sources, from
one that did), or the ring *that* thread registered. Nothing in oscall
can tell threads apart without a system call, so `register_ring_fd`
documents it and `Drop` does not unregister (it may run elsewhere, and
would end another ring's registration).
- **32-bit programs on a 64-bit kernel** (the i686 tests on x86_64):
the kernel reads `struct msghdr`, `siginfo_t` and the mask of
processors in their 32-bit layouts for a ring such a program made
(`ctx->compat`), which the tests of `sendmsg`, `recvmsg`, `waitid` and
the affinity of workers pass by.
- `io_uring_enter` returns the count of entries it submitted rather
than the error of the wait, when it submitted any: a timeout
(`ETIME`) or a signal only shows when nothing was submitted.
- Closing the ring does not end its operations before `close` returns:
the kernel cancels them from a work queue (as its sources read; not
measured). Hence the contract of the constructors that take a
pointer: valid until the completion is taken, not until the ring is
dropped.
- **Where there is none**, as measured: Docker's default system call
filter answers `EPERM` to `io_uring_setup` (the fullrust jobs of CI
and of `scripts/check.sh`), and the qemu-user of the fullrust image
`ENOSYS`. The tests then skip, and say so; `OSCALL_REQUIRE_IO_URING=1`
makes a skip a failure, which CI sets for the Linux runners
themselves (x86_64 and aarch64, and the static musl builds that run
natively, 32-bit x86 included). To run them under fullrust, by hand:
`docker run --security-opt seccomp=unconfined ...` with the command of
`scripts/check.sh` (x86_64 and x86 then pass; aarch64 and armv7 are
emulated, and skip). `scripts/privileged.sh` runs them, required, in
its container, which has no filter: that is where they execute for
the fullrust targets of x86_64 and x86. `scripts/vm.sh` runs them,
required, on kernels of riscv64, riscv32 and arm (Linux 6.18 built
with `CONFIG_IO_URING`), where qemu-user has nothing; `tests/vm_init.rs`
brings the loopback interface up for them.
- **The kernel's older asynchronous I/O is no substitute** (`io_setup`,
`io_submit`, `io_getevents`; nothing in oscall uses it). Docker's
filter allows it and qemu-user answers `ENOSYS` to `io_setup`. And
`io_submit` does a buffered operation before it returns: that of a
read of an empty pipe returned when the pipe was written to, 300 ms
later, and that of a read of 1 MB of a file with its completion
already there to collect (measured on x86_64, natively and under
Docker's filter).
- **The arguments and the environment** (`sys/linux/env.rs`) are read
from `/proc/self/cmdline` and `/proc/self/environ`, for the reason the
auxiliary vector is read from `/proc`: they sit above the initial stack,
and nothing in a process without libc has a pointer to them. (The `std`
of fullrust keeps them in private statics and exports no symbol; a C
library has `environ`, which oscall does not link.) What that means, as
measured:
- They are the values the process was *started* with. `setenv` and
`std::env::set_var` change a copy the runtime keeps, and fullrust's a
private map: neither shows.
- A process that made itself not dumpable (`PR_SET_DUMPABLE` 0) and is
not root still reads `cmdline`, and is refused `environ` and `auxv`
(`EACCES`: the files then belong to root, and those two are mode 400).
- qemu-user answers `/proc/self/cmdline` with the arguments of the
program it runs, not its own, and `environ` is the emulator's, which
is the program's (the tests compare both with `std` there).
- Both are read whole into the caller's buffer, with one read more to
tell a buffer that is exactly full from one that is too small.
- **A thread made with `clone`** (`thread::linux::spawn_raw`,
`sys/linux/thread/spawn.rs`).
- *What it is not.* It has the thread pointer of its creator (no
`CLONE_SETTLS`): what reads thread-local storage reads the creator's,
while the creator does. Under fullrust that includes the allocator,
which finds the heap of the thread through that block on every call
(read in fullrust's `std`: `tls::heap()`, in the patch of
`sys/pal/fullrust`); fullrust builds the block in its own wrapper of
`clone`, a hidden symbol, and exports nothing to build one with. So
the code of such a thread runs `core` and oscall, and the tests of it
do not even assert: they store what they saw in statics.
- *The flags* are exactly `CLONE_VM | CLONE_FS | CLONE_FILES |
CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | CLONE_CHILD_CLEARTID`.
They are the flags a C library gives, and qemu-user, which answers
`clone` itself, makes a thread of them (measured on aarch64, arm,
riscv64 and riscv32 under qemu 10; what it does with another set was
not tried).
- *Joining* waits on the word the kernel clears and wakes when the
thread is gone. That wake-up is not a private one (`FUTEX_WAKE`
without `FUTEX_PRIVATE_FLAG`, as `kernel/fork.c` reads), and a
private wait is on another queue: `sync::wait` cannot be used for
it. The wait in `spawn.rs` is the plain `FUTEX_WAIT`.
- *A detached thread unmaps its own stack*, which it is standing on:
`munmap` and `exit` are made from registers by one block of assembly
with nothing between them. Before that the thread calls
`set_tid_address(0)`: the word the kernel clears when a thread ends
is in that mapping, and between the `munmap` and the end of the
thread another thread can map something at the same address, into
which the kernel (or qemu-user, which does the clearing itself)
writes a zero. Measured, as armv7 fullrust binaries under the
qemu-user of the fullrust image, the tests of `thread` run in a
loop: without the call 16 runs of 12 000 ended with `SIGSEGV` (13 of
6000 as a user, 3 of 6000 as root; so did one on master's CI), none
of 6000 when the test that detaches threads was left out, and with
the call none of 12 000. It was not seen on another target (300
runs of the armv7 musl binary under qemu 10 without the call), which
says how narrow the window is there, not that there is none: the
kernel writes that zero too (`mm_release` in `kernel/fork.c`). musl
does the same before it unmaps the stack of a detached thread. A
joined thread has no such window: its stack is unmapped by whoever
joins, after the zero is written. Who unmaps is
settled by one atomic, swapped by the thread when its function
returns and by the handle when it is dropped.
- *Signals* are all blocked in the thread (the mask is set around
`clone` and inherited): a handler of the program's would otherwise
run on a thread its runtime does not know.
- *The assembly* is one naked function per architecture, after
`clone_vfork` of `process.rs`, with the address of the word as the
fifth argument of `clone` everywhere but on x86_64, where it is the
fourth (`CONFIG_CLONE_BACKWARDS`, which 32-bit x86, arm, aarch64 and
riscv select). The stack is aligned
to 16 bytes at the call of the thread's function on every
architecture (8 on arm, which wants no more).
- **Name resolution** (`net::resolve`, `sys/linux/resolve.rs`): the kernel
has none, and the C library's is out of reach, so the Linux backend is
`/etc/hosts`, then `net::dns` with the servers of `/etc/resolv.conf`.
Both files are read a line at a time through a buffer on the stack. The
addresses are then ordered by connecting a datagram socket to each,
which sends nothing and fails when the machine has no route (how a
machine without IPv6 gets `127.0.0.1` before `::1`); it is only done
when there are addresses of both kinds.
- A libc may be present in the process (plain Linux targets) and knows nothing
of what oscall does. Do not touch what libc keeps state about: the program
break, thread creation, `fork` without an immediate `exec`, signal
dispositions libc reserves. (`thread::linux::spawn_raw` creates a thread
libc does not know of, and its contract is that the thread stays out of
libc's way: see above.)
- **What a child sets about itself** (`process::unix`) is prepared by the
parent as plain data (`process/setup.rs`) and applied by the child with
system calls, in this order, which matters: the limits
before the identity (raising a hard limit needs the privilege about to be
given up), groups before group before user, and `PR_SET_PDEATHSIG` after
them all, because the kernel clears it whenever the effective user or
group changes. Capabilities and the system call filter
(`process/cred.rs`) go around that: `PR_SET_KEEPCAPS` and the bounding
set *before* the identity (dropping from the bounding set takes
`CAP_SETPCAP`, which a change of user gives up, and the permitted set
must survive that change for what follows), then, last before `execve`,
`capset`, the ambient set and the filter: under a filter nothing but
`execve`, and `write` and `exit_group` if it fails, may be assumed
allowed. The identity calls are the kernel's, which act on one
thread (libc's versions tell every thread; the child has one), and on x86
and arm they are the `32` variants: the plain ones take 16-bit ids.
- **The parent death signal is about a thread**: it is sent when the thread
that created the child ends, not the process (measured: a child spawned
from a thread that returns dies at once, the process going on).
- **A forked child holds every descriptor of the process**, those other
threads opened included, for as long as it lives: a pipe another test
has closed its end of stays open, and its writer gets no `SIGPIPE`, its
reader no end of stream. Tests of `fork` run in a helper process for
that reason, never in the harness process. The child of a `spawn` is
such a process too, until it runs its program: a test that writes a
program and runs it finds it "busy" (`ETXTBSY`, measured once on a CI
runner) when another test created a child while the file was open for
writing, and has to try again.
## macOS
Declare `libSystem` functions in `unsafe extern "C"` blocks. `sys::cvt`,
`sys::cvt_long` and `sys::last_error` turn the `-1`/`errno` convention into
a `Result`.
- **Variadic functions must be declared variadic** (`fn open(path: *const
c_char, flags: c_int, ...) -> c_int;`, likewise `fcntl`, `ioctl`,
`openat`): on aarch64 macOS variadic arguments are passed on the stack, and
a non-variadic declaration silently passes garbage.
- On x86_64, functions that use `struct stat`, `dirent` or `statfs` need the
`$INODE64` symbol suffix (see `sys/apple/mod.rs`); `$NOCANCEL` and
`$DARWIN_EXTSN` variants exist for some others. Check what the `libc` crate
or Apple's headers do for each function.
- **Extended attributes** (`fs::unix`, `sys/apple/fs/xattr.rs`), as
measured on the CI runners of both architectures: the functions take a
position, which is 0 for anything but the resource fork, and options,
where `XATTR_NOFOLLOW` replaces Linux's `l` functions. A length is
asked for with a *null* buffer: a buffer of size 0 that is not null is
one that is too short (`ERANGE`), which is what an empty Rust slice
would be. A missing attribute is `ENOATTR` (93), where Linux says
`ENODATA` (61, a number macOS has for something else). A symbolic link
has attributes of its own, and a name needs no prefix: on Linux a link
has no `user.` attribute (`EPERM` to set or remove one) and a name
without a class is `EOPNOTSUPP`.
- The oldest macOS supported is 11. Do not use functions newer than that
without a fallback: look them up with `dlsym(RTLD_DEFAULT, ..)` when
first needed, as `sys/apple/sync.rs` does, never by declaring them.
- Structure layouts are the same on x86_64 and aarch64, but verify each one
against Apple's headers (the `libc` crate's `src/unix/bsd/apple` is a good
transcription).
- **`posix_spawn` cannot set limits, a user, groups or a file creation
mask.** A command that asks for one is spawned by `fork`; the child calls
async-signal-safe functions only (`setsid`, `setpgid`, `dup2`, `open`,
`umask`, `setrlimit`, `setgroups`, `setgid`, `setuid`, `chdir`) and then
replaces itself with the program by `posix_spawn` with
`POSIX_SPAWN_SETEXEC`, which still does what only it can: close every
other descriptor (`POSIX_SPAWN_CLOEXEC_DEFAULT`) and reset the signals.
The standard descriptors are installed by the child itself, with the
file actions only marking them as inherited: with `POSIX_SPAWN_SETEXEC`
a `dup2` action whose source is close-on-exec, as every descriptor of
oscall is, fails with `EBADF` (measured on the CI runners of both
architectures), where the same action works when a process is spawned.
Everything else keeps the plain `posix_spawn`.
- **The first place of a process's list of groups is its own group's.**
`setgid` writes the group there, over what `setgroups` put (measured: a
child given the group 4242 and the groups 7 and 8 had 4242 and 8). The
list given to `setgroups` is therefore the group the child is to have,
then the others: 16 places in all. And `id` does not show the list of a
process whose user it knows, root included: it asks the directory, which
has more groups (23 for root on the CI runners). A test reads the list
from a child whose user no one knows, or with `getgroups`. None of this
runs in CI, where the tests are not root: `sudo` the test binary on a
`wip/` branch to check a change.
- **POSIX asynchronous I/O** (`io::macos`, `sys/apple/aio.rs`), as measured
on the CI runners: macOS 15.7 on x86_64 and macOS 26.7 on aarch64. They
differ in several places, by the version of the system rather than by
the processor as far as can be told.
- *The layouts.* `struct aiocb` is 80 bytes and `struct sigevent` 32 on
both (a C program compiled on each runner printed the sizes, the
offsets and the constants); they are asserted in the file.
- *What it takes.* Files, and what is a file to the kernel: a FIFO, a
character device (`/dev/null`, `/dev/zero`), a directory, whose read
completes with `EISDIR`. A pipe or a socket is refused when the
operation is submitted (`ESPIPE`). The offset is ignored on a FIFO,
and a write to a file open for appending appends whatever the offset.
More than `INT_MAX` bytes is `EINVAL`, as is a negative offset.
- *Every refusal is `EAGAIN` on macOS 15*: a closed descriptor, one open
the wrong way, a pipe, a negative offset, a notice the kernel does not
know, and too many operations. macOS 26 answers `EBADF`, `ESPIPE`,
`EINVAL` and keeps `EAGAIN` for the last. A test of a refusal accepts
`WouldBlock` in the place of any other kind.
- *The limits* are `kern.aioprocmax` (16) for a process and
`kern.aiomax` (90) for the system. An operation holds its place from
`aio_read` until `aio_return`, not until it is over: 16 reads that
were complete and not returned made the seventeenth fail. Hence
`sys::aio::take`, which returns as soon as `aio_error` says the
operation is over, and `Drop`, which does too.
- *`aio_error`, `aio_return` and `aio_suspend` know a block by its
address* and only while it holds its place: all three answer `EINVAL`
for a block that was returned, or never submitted, and `aio_suspend`
also for a list of nothing but null pointers. (It does not wait on
what it does not know.) `aio_return` on an operation that runs is
`EINPROGRESS`. The result of a cancelled operation is -1, with an
`errno` that `aio_return` does not set on macOS 15: the error is
`aio_error`'s (`ECANCELED`), which is why `take` asks it first.
- *`aio_suspend`* waits for the operations listed and no other: one that
completes and is not in the list does not end it. Its timeout is kept
(20 ms took 20.4 to 21.4 ms, zero 40 to 90 µs) and reported as
`EAGAIN`.
- *The threads.* macOS 15 runs the operations of every process on four
threads of the kernel (`kern.aiothreads`): of 16 reads of a FIFO
nobody writes to, 4 ran and 12 stayed queued, and a read of a file
submitted then was not started in 2 s, by that process or by another
one: four reads that wait stop the asynchronous I/O of the machine.
macOS 26 has the same value
and does not keep to it: the 16 all ran, and a read of a file by
another process meanwhile took 5 ms. So the number that can be
cancelled depends on the system: `aio_cancel` gives up what is queued
(`AIO_CANCELED`, and the operation is over at once with `ECANCELED`)
and nothing that runs (`AIO_NOTCANCELED`); a block the kernel does
not know is `AIO_ALLDONE`.
- *An operation that runs holds its descriptor, and on macOS 15 its
process.* `close` on a descriptor with a read of a FIFO in flight
did not return in 3 s, and returned when the FIFO was written to (both
systems); with a read still queued it returned at once and the read
was cancelled. A process that called `exit` with such a read in flight
was still there 4 s later on macOS 15, and ended at once on macOS 26.
The tests that hold operations in flight give each of them its byte
before they end.
- *The notices.* `SIGEV_SIGNAL` delivers its signal; `SIGEV_THREAD` and
anything else is refused (`EINVAL`). `kevent` refuses `EVFILT_AIO`:
`ENOTSUP` on macOS 15, `EPERM` on macOS 26.
- *Flushing.* `aio_fsync` takes `O_SYNC`, `O_DSYNC` and 0, and wants a
descriptor open for writing (`EBADF` on one open for reading; on a
FIFO it completes with 0). It is `fsync` and not `F_FULLFSYNC`, by
the kernel's sources; nothing here can measure the difference.
- *What a test can hold in flight* is a read of a FIFO opened for
reading and writing, which waits until a byte is written: a file is
read at once (64 MB of a sparse file in 40 to 180 ms). And the tests
of `tests/io_macos.rs` take a lock each: the 16 places are the
process's, and the harness runs the tests of a file in one process.
- *A null buffer is refused whatever the length* (`EINVAL`, or the
`EAGAIN` of macOS 15): a read of nothing wants an address all the
same, which a `Vec` that holds nothing has.
- *`lio_listio`* takes 16 blocks (`AIO_LISTIO_MAX`), reads and writes
only. **It looks at every block before it queues any**: with one
block the kernel refuses (a write on a descriptor open for reading)
between two it would take, none was queued, whether the call was to
wait or not, and the call returned that refusal (`EBADF`; `EAGAIN` on
macOS 15). **Short of places it queues what fits**: of four blocks
with two places left in the process, the first two were queued and
the call returned `EAGAIN`. Which of the two happened is told by
`aio_error` on each block, which knows a block the kernel has and
answers `EINVAL` for one it has not: `Batch` asks it. An operation
that fails by itself (a read of a directory) is no failure of the
call, which with `LIO_WAIT` returned 0 once both were over.
- *The notice by signal.* The signal comes when the outcome is there:
`aio_error` was never `EINPROGRESS` once the signal was told. Signals
merge: 8 writes of a file that ask for one each were told by 1 to 3
deliveries. The notice of `lio_listio` is sent once, when the last
operation of the list is over: with 2 of 3 over nothing came in
150 ms, and one signal came with the third. (`Batch` clears the
notice of each block before it submits: whether the kernel would
send those as well was not measured.) A number that is no signal (0,
-1, 1000) and `SIGKILL` are refused when the operation is submitted;
`SIGSTOP` was not tried. An operation whose notice is `SIGIO`, ended
with no handler for it, left the process alone: the system discards
that signal by default, which is why it is the one `io::macos`
names.
- *The rest of what the system has.* `preadv` and `pwritev` are in
`libSystem`; `F_NOCACHE` is accepted and asks no alignment of a
read.
- *libdispatch* (`dispatch_io_create`, `dispatch_io_read`,
`dispatch_read`...) is the other asynchronous I/O of the system, and
oscall makes nothing of it. What its headers declare takes blocks.
`libSystem` also exports a variant of each that takes a function and
a context (`dispatch_read_f`, `dispatch_write_f`,
`dispatch_io_create_f`, `dispatch_io_read_f`, `dispatch_io_write_f`,
`dispatch_io_barrier_f`, `dispatch_data_create_f`: `dlsym` finds
them all on macOS 15 and 26), which the sources of libdispatch
declare in a private header (`io_private.h`; the SDK of the runners
was not searched for them): no interface to build on. A
block can be had without a compiler that knows them, as a structure
whose layout the block ABI fixes: one made by hand in a test, with
nothing captured (`_NSConcreteGlobalBlock`), was called by
`dispatch_read` with the 4096 bytes asked for, on a thread of
libdispatch's pool (not the caller's; the one `dispatch_async_f` had
just run its work on, or another).
That thread is the point: the outcome is handed to code that runs
there, as an object of the library's that has to be copied out of
and released. For oscall to hand it on in its own shape it would
need a queue of its own and something for a poller to wait on, kept
by the process for good: a runtime, where every other module is a
call. And what libdispatch does on those threads is `read` and
`pread`: a program that wants that has threads of its own, and `io`.
- **The arguments, the environment, threads and names.** `_NSGetArgv` and
`_NSGetEnviron` give what the C runtime has, the second being the
environment as it is *now*; reading it is what `getenv` does, with no
lock (see `process::vars`). A function declared in two files must have
the same signature in both, to the mutability of the pointers
(`clashing_extern_declarations`). `pthread_create` wants a stack of
whole pages and of 16 KiB at least, or answers `EINVAL`: the backend
rounds. `getaddrinfo` and `getnameinfo` return numbers of their own
(`EAI_*`), which mean other things as `errno` values: the backend turns
each into the system error that says the same, so that an `Error` stays
a system error. `struct addrinfo` has its members in another order than
on Linux (`ai_canonname` before `ai_addr`).
## The DNS client
`net::dns` is portable code on the sockets of the crate, not a backend:
the same on every system, and the whole resolver of Linux.
- **The reader of messages** (`net/dns/message.rs`) takes bytes from the
network. It never indexes with a number the message gave (`get`
everywhere), every loop is bounded by something the message cannot
change (the length of a name, a count of jumps, a count of aliases, the
message's own length), and a message that lies is `None`, which its
callers treat as a server that failed. Add a unit test with the
malformed case for anything it learns to read; `noise` there runs
20 000 generated messages through it.
- **What makes an answer the answer**: the datagram socket is connected,
so the kernel drops what comes from elsewhere; the identifier is random
and the port the system's choice; and the question in the response
must be the one asked. Anything else on the socket is skipped, not an
error.
- **Nothing is allocated**, and a `Config` is plain data of a fixed size.
The one place memory can be wanted is a response over TCP longer than
4 KiB.
- **Tests run a name server of their own** (`tests/dns.rs`: UDP and TCP
on one loopback port, answering by the name asked) and never ask for a
name outside the machine: a test that needs the Internet fails where
there is none, and is slow where a resolver times out.
## Windows
`dll!("kernel32.dll" { fn Name(args) -> ret; })` imports functions.
`sys::cvt` and `sys::last_error` turn `BOOL` results into a `Result`.
- Use the wide (`W`) functions only. The oldest Windows supported is 10.
- Mind the 32-bit layouts: `usize`/pointer-sized fields, `OVERLAPPED`,
`WSADATA` (its field order differs between 32 and 64 bits).
- Winsock functions report errors through `WSAGetLastError`, and need
`WSAStartup` once per process.
- `NTSTATUS` results are converted with `RtlNtStatusToDosError`
(`sys::nt_error`).
- **A handle may be open for overlapped operation** when oscall did not open
it (a `std` file opened with `FILE_FLAG_OVERLAPPED`, the pipe of a child
process, an inherited handle). On such a handle `ReadFile`, `WriteFile`,
`LockFileEx`, `DeviceIoControl` and the `Nt` calls that start an operation
(`NtReadFile`, `NtQueryDirectoryFile`, `NtFsControlFile`...) return while
the operation is pending, and the system writes the buffers and the status
block when it completes: a function that returned by then is unsound.
Give the operation a status block that says `STATUS_PENDING` and do not
return before it says otherwise: `sys::io::completed` and
`sys::io::wait_completion`. Calls that query or set information
(`NtQueryInformationFile`, `NtSetInformationFile`, `FlushFileBuffers`) are
waited for by the system itself. A handle oscall opened is synchronous.
- **Overlapped operations and completion ports** (`io::windows`,
`sys/windows/overlapped.rs`), as measured on the three architectures:
- *When the status block is written depends on the event.* An operation
given an event (`OVERLAPPED.hEvent`, the `Event` of `NtReadFile`) has
its status written when it completes, while its packet is still in
the port, and the structure is not touched when the packet is taken.
One given no event, on a handle that
has a port, has its status written when its packet is *taken from the
port*, by the thread that takes it: two seconds after the operation
completed, the status still said pending. So the memory of an
operation without an event must outlive its packet, and nothing can
tell that such an operation is over without taking the packet. An
`Operation` gives every operation an event for that reason; it is
what lets `Drop` cancel and wait.
- *The price of the event is the thread.* An operation with an event is
cancelled when the thread that started it ends, on a handle with a
port too (`ERROR_OPERATION_ABORTED`); one without an event survives
its thread if the handle has a port, and is cancelled if it has none.
- *What starts nothing.* A call that returns an error status (the two
top bits set) started nothing: no status is written, no event set, no
packet queued. Success, a warning and "pending" all mean a completion
will come, also when the operation was over before the call returned.
- *A file is read and written in the call that starts the operation.*
On a file opened by `io::windows::open`, which goes through the
system's cache as every file of oscall does, `NtWriteFile` of 256 MB
took 0.7 to 1 s and returned with the operation complete, extending
the file or not, and a read of as much 70 ms. No operation on a file
was ever seen pending (x86_64 and aarch64): what an `Operation` on a
file saves its caller is nothing, unless the file is opened without
the cache, which oscall does not do.
- A read at the end of an overlapped file is started and *completes*
with `ERROR_HANDLE_EOF`; a read of a pipe whose write end is closed
fails at once with `ERROR_BROKEN_PIPE`. Closing the read end under a
read in flight completes it with `ERROR_BROKEN_PIPE`.
- A port refuses (`ERROR_INVALID_PARAMETER`) a handle that is not
overlapped, and one that has a port already.
- The synchronous functions (`sys::io`, which give an operation neither
an event nor a context for the port) work on a handle that has a port,
also when the operation has to wait: the status is written, and no
packet is queued.
- The read end of `io::windows::pipe` cannot be made non-blocking:
`SetNamedPipeHandleState` answers `ERROR_ACCESS_DENIED`. (Presumably
for want of `FILE_WRITE_ATTRIBUTES`, which `CreateNamedPipeW` does not
ask for the inbound end of a pipe and `CreatePipe` does; the cause was
not measured.) The write end can.
- *A cached read of what the cache does not hold is pending.* The
measurements above were of data the test had just written. Of 32 MiB
written without the cache and read through it, the start took 2 to
4 ms and the read was complete after 15 to 340 ms; read again, the
start took 3.6 to 5.6 ms and the read was complete when it returned,
*and the call had said pending all the same*: what `NtReadFile`
returns for a file does not tell whether the work is done.
- *Without the cache* (`FILE_FLAG_NO_BUFFERING`,
`io::windows::open_unbuffered`) operations go to the storage and the
call that starts one returns first. 32 MiB on the runners, whose
disks are virtual and differ from one run to the next (two runs of
each of the three targets): a write over what the file has started
in 0.3 to 0.8 ms and was complete after 5 to 120 ms, a read in 2.6 to
5.9 ms and 8 to 528 ms. **A write that extends the file is done
before the call returns** (7.6 to 119 ms to start, and no more in
all, six times of six), and is reported as pending all the same,
with its completion queued. An address, a length or an offset that is no multiple of a
sector (512 bytes there) is `ERROR_INVALID_PARAMETER` at the start,
each of the three; so is `NtReadFileScatter` on a file that goes
through the cache. A file that ends within a sector is read short.
- *What completes at once with a warning is reported as pending.*
`NtReadFile` of a message of a pipe longer than the buffer, and
`WSARecvFrom` of a datagram longer than the buffer, both with the
data there before the call: the call says pending, the status of the
operation is `STATUS_BUFFER_OVERFLOW` (`0x80000005`) with the count
of what fitted, and a packet is queued, also on a handle that has
`FILE_SKIP_COMPLETION_PORT_ON_SUCCESS`. Winsock was never seen to
return `WSAEMSGSIZE` from an overlapped call; should it, the status
block tells whether an operation stands behind it
(`started_receive`). A watch of a directory with changes waiting is
reported as pending as well.
- *`NtReadFile` on a file open for overlapped operation answers
"pending"*, for 4096 bytes through the cache as for 32 MiB without
it, and so does `NtWriteFile` without the cache. A write of 4096
bytes through the cache answered success on x86_64 (and in the
32-bit build there) and "pending" on aarch64. So
`FILE_SKIP_COMPLETION_PORT_ON_SUCCESS` saves next to nothing on a
file, nearly every operation of which queues its packet.
- *`FILE_SKIP_COMPLETION_PORT_ON_SUCCESS`* does what it says for a call
that returns success: no packet (waited for 150 ms), the status and
the count written before the call returns, the event of the
operation set. Hence `Operation::completed_at_start`, which is what
the call returned and not what the operation is later: a pending
operation that is over an instant after has its packet. The modes
cannot be cleared (setting none succeeds and changes nothing), and a
handle that is not overlapped is `ERROR_INVALID_PARAMETER`.
- *`FILE_SKIP_SET_EVENT_ON_HANDLE`* takes away the signal
`sys::io::completed` waits on for the synchronous calls, which then
find their operation complete by looking (`wait_completion` polls
when the signal does not help): a read that waited 100 ms for its
data returned 0.2 to 27 ms after it.
- *A named pipe instance*: new, it takes a client before
`ConnectNamedPipe` is called, which then answers
`ERROR_PIPE_CONNECTED` (as it does for an instance that has its
client); once its client has gone, `ERROR_NO_DATA` until
`DisconnectNamedPipe`; disconnected, it takes no client
(`ERROR_PIPE_BUSY` to `CreateFileW`) until `ConnectNamedPipe` is
called again. A write to a pipe the server disconnected is
`ERROR_PIPE_NOT_CONNECTED`. One more instance than the pipe was
created to have is `ERROR_PIPE_BUSY`, a second "first" instance
`ERROR_ACCESS_DENIED`, a client that asks to read a pipe the server
reads `ERROR_ACCESS_DENIED`, and message mode on a pipe of bytes
`ERROR_INVALID_PARAMETER` (from `SetNamedPipeHandleState`, once the
client is connected: the instance has then had its client).
- *`WaitNamedPipeW` gives up before its timeout*: asked for 60 ms with
no instance to wait for, it once returned `ERROR_SEM_TIMEOUT` before
50 ms had passed (aarch64; by how much was not recorded), where the
other runs took the 60. `wait_pipe` keeps a deadline on the unbiased
interrupt time and calls again for what is left, as the wait of a
completion port does; 60 runs of the tests on each of the three
targets then never saw less than the 60 ms.
- *`TransmitFile`* reads from the offset of the `OVERLAPPED`, and moves
the position of a file handle that has one to the end of what it
sent, on most machines: read right after the packet was taken, the
position was the new one in every run on every runner but one, where
it was still 0 in 60 runs of 60 (the 32-bit build on an x86_64
runner; the same build had the new one in 60 of 60 on another runner
an hour before. What differs between the two was not found). **It
reads through the handle for as long as it runs**: with
the file handle closed as soon as the call had returned, the
operation completed with `ERROR_INVALID_HANDLE` (and a test that
waited for the bytes waited for ever), and on x86_64, 64 and 32 bits,
the next `TransmitFile` on that connection was started and completed
with the code 22 (`ERROR_BAD_COMMAND`), where on aarch64 it stayed
in flight like one on a connection nothing had failed on. A file
handle open for
overlapped operation is taken as well as one that is not. On a
socket that is not connected it fails at the start (`WSAENOTCONN`),
as it does for a file handle that is none (`ERROR_INVALID_HANDLE`);
from the end of the file it sends nothing and completes with 0.
- *`WSARecvFrom` writes the address and its length when the operation
completes*, not when the call returns: both are in the `Operation`'s
allocation (`RawAddr`, whose length is at `LEN_OFFSET`), as is the
array of pages of a scattered read. The array of `WSABUF`s and the
flags are read by the call.
- *`ReadDirectoryChangesW`* is `NtNotifyChangeDirectoryFile`, which is
called directly: the Win32 function returns success for a pending
operation and for a complete one alike. The buffer must be aligned as
a `DWORD` (the `Operation` allocates `u32`s). More changes than the
buffer holds complete the watch with success and a count of 0
(`STATUS_NOTIFY_ENUM_DIR`). A file, and an empty filter, are
`ERROR_INVALID_PARAMETER`.
- A completion port is not a target for a wait completion packet
(`ERROR_INVALID_PARAMETER`): it cannot be an event source of the
poller.
- `ConnectEx` is not exported: it is asked of the socket's provider
(`SIO_GET_EXTENSION_FUNCTION_POINTER`), wants a bound socket, and like
`AcceptEx` leaves a socket that is only like the others after
`SO_UPDATE_CONNECT_CONTEXT` or `SO_UPDATE_ACCEPT_CONTEXT`.
- **The command line is split by oscall** (`process/env.rs`), by the
rules of Microsoft's C runtime since 2008, which `std` applies too: the
inverse of what `Command` quotes. The splitter is portable code with
unit tests that run everywhere; it writes WTF-8 as it goes, a leading
surrogate waiting for the unit after it.
- **`GetAddrInfoW` and `GetNameInfoW` return their error**, a Winsock code
(`WSAHOST_NOT_FOUND`...), and need `WSAStartup` like any Winsock call
(`sys::net::startup`). The codes are in `ERRORS`, after every entry that
is the first of its kind.
- **Privileges and large pages** (`process::windows`, `mem::windows`), as
measured on the runners of GitHub (x86_64 and aarch64), whose account
is the built-in administrator, elevated:
- The token of the tests holds `SeDebugPrivilege` enabled, and
`SeBackupPrivilege`, `SeRestorePrivilege`, `SeShutdownPrivilege`,
`SeCreateSymbolicLinkPrivilege` and `SeIncreaseWorkingSetPrivilege`
disabled; `SeChangeNotifyPrivilege` enabled, as every token has it;
and no `SeLockMemoryPrivilege`. What oscall reads is what
`whoami /priv` prints, before and after each switch.
- `AdjustTokenPrivileges` succeeds for a privilege the token does not
hold, enabling or disabling, and leaves `ERROR_NOT_ALL_ASSIGNED` in
the last error: `set_privilege` returns that. Names are looked up in
any case of letters.
- `VirtualAlloc` with `MEM_LARGE_PAGES` and no privilege is
`ERROR_PRIVILEGE_NOT_HELD`; with a length that is no multiple of
`GetLargePageMinimum` (2 MiB on both architectures) it is
`ERROR_INVALID_PARAMETER`, which comes first.
- *The privilege is a matter of logons.* `LsaAddAccountRights` gave the
account the right (it succeeds for an administrator), and the token
of the process that asked still had none of it, nor had a process it
then created. A scheduled task of the same account, logged on anew
by the system without a password (`schtasks /RU <account> /NP`), had
the privilege, disabled; enabled, it mapped two large pages, wrote
to them and released them. A task of the system's own account
(`/RU SYSTEM`) has the privilege enabled from the start, and mapped
them too. `tests/mem_windows.rs` does both where it is allowed to
change the machine (`GITHUB_ACTIONS`, or
`OSCALL_TEST_GRANT_PRIVILEGES`), by running a part of itself as such
a task; it reports what it found and fails only if a process that
has the privilege enabled is refused large pages for another reason
than the want of memory in one piece (`ERROR_NO_SYSTEM_RESOURCES`,
which was not met).
- **A file is mapped as code only if it was opened with `FILE_EXECUTE`**
(`fs::windows::OpenOptionsExt::execute`): `CreateFileMappingW` with an
executable protection is `ERROR_ACCESS_DENIED` on a handle opened for
reading alone. The right is asked for by `CreateFileW` and by
`NtCreateFile` (the calls relative to a directory) alike.
- **A child is put in a job at creation** with
`PROC_THREAD_ATTRIBUTE_JOB_LIST` (Windows 10), in the same attribute list
as the handles to inherit; a list is initialised for the number of
attributes it will really hold. Jobs nest since Windows 8, so this works
from a process that is itself in a job, as CI runners are.
## WebAssembly
- `wasi`: declare `wasi_snapshot_preview1` imports (see `sys/wasi/mod.rs`);
`sys::cvt` turns the returned `errno` into a `Result`. Paths are relative
to preopened directories. `sys/wasi/mod.rs` has the table of every call
of preview 1 and what uses it: keep it when a call gains a user.
`args_get` and `environ_get` write an array of pointers besides the
strings, which oscall has no use for: it goes in the caller's buffer
after the strings, which is why that buffer needs four bytes more per
string there.
- `unsupported`: same items as the other backends, failing with
`ErrorKind::Unsupported`, except what needs no system.
## The public raw layer
`oscall::raw` (`src/raw.rs`) is what `sys` offers to everyone: a documented
wrapper or re-export per item, in a sub-module per system. `sys` itself stays
private and is free to change; what `raw` exposes is API. The system call
numbers and the error numbers are the backends' own tables, whose constants
are `pub` and documented for that reason (`scripts/gen-syscalls.py` writes
the former). The two public macros (`raw::linux::syscall!`,
`raw::windows::dll!`) are `#[macro_export]`ed under hidden names and
re-exported in their module; they name `$crate::raw` paths only, since a
macro expanded in another crate cannot reach `sys`.
## Checking
`scripts/check.sh` formats, lints every target with both feature sets, and
runs the tests natively, as 32-bit x86, on WASI (under Node), and under
fullrust for its four targets (docker). `scripts/check.sh lint` and
`scripts/check.sh test [cargo test args]` run one half.
riscv32 Linux has no prebuilt `std`. With a nightly toolchain that has
`rust-src`, `scripts/check.sh` also lints it and builds
`tests/freestanding` for it (and runs it if there is a `qemu-riscv32`);
`scripts/riscv32.sh` runs the whole test-suite for it, building musl first
(docker). CI does both in a job that does not block, on every branch.
`tests/freestanding` is not a test target of the crate but a separate
package (`#![no_std]`, `#![no_main]`, its own `_start`): add to it when a
module gains something whose system calls differ on 32-bit targets.
`scripts/privileged.sh` runs the tests of what a container is made of
(`process`, `process_linux*`, `fs_linux`) and those of io_uring
(`io_linux`) as root in a privileged container, for the targets the
machine runs natively; `scripts/check.sh`
calls it when there is docker. `scripts/vm.sh` runs the ones that need no
other program (all but `process`), and `mem_linux`, on riscv64, riscv32 and arm kernels in
virtual machines (qemu-system, in a docker image it builds, with a kernel it
builds from kernel.org's sources): it is not part of `scripts/check.sh`.
Both set `OSCALL_REQUIRE_PRIVILEGED=1`. A test of `process::linux` or
`fs::linux` must not run a shell or any program but the test binary itself
(a helper mode): the virtual machines have nothing else.
macOS and Windows only run in CI. CI runs on `master`, on pull requests and
on branches named `wip/**`: push work in progress to `wip/<topic>` to have
it tested on macOS, Windows and wasmtime (the jobs `scripts/check.sh` covers
locally are skipped on those branches; the privileged container, which also
runs on arm64, and the virtual machines are not) (`gh run list --branch
wip/<topic>`, `gh run view <id> --log-failed`).
## Handles are private to the process
Every handle and socket oscall creates is close-on-exec (`O_CLOEXEC`,
`SOCK_CLOEXEC`) or non-inheritable (Windows), atomically at creation where
the system allows it. Passing one to a child process is an explicit request.
Likewise, writing to a closed pipe or socket returns `BrokenPipe`; oscall
never lets `SIGPIPE` be raised for a socket (`MSG_NOSIGNAL`, `SO_NOSIGPIPE`).
## Landing a change
1. `scripts/check.sh` passes (set nothing: it uses `./target`). When
running `cargo` by hand in one of several checkouts, give it the same
`CARGO_TARGET_DIR=$PWD/target`: a target directory shared between
checkouts (a `target-dir` in `~/.cargo/config.toml`) can link a test
with the library of another checkout.
2. Commit, then `git push -f origin HEAD:refs/heads/wip/<topic>`: CI runs the
jobs that cannot run locally (macOS, Windows, wasmtime). Read results per
job, without waiting for the whole run:
`gh run list -R KarpelesLab/oscall --branch wip/<topic> --limit 1`,
`gh run view <id> -R KarpelesLab/oscall --json jobs -q '.jobs[] | "\(.databaseId) \(.name) \(.status) \(.conclusion)"'`,
`gh run view -R KarpelesLab/oscall --job <jobId> --log-failed`.
Every job must be green; a `Test & lint (macos-latest)` job that is still
queued for want of a runner does not block (a failed one does), but must
be checked once it has run.
3. `git fetch origin && git rebase origin/master`, check again if master
changed code the change uses, then `git push origin HEAD:master`. Never
force-push master; if the push is rejected, fetch, rebase, push again.
4. Look at master's full CI run (it adds riscv64 and armv7 musl under qemu,
armv7 natively on arm64, fullrust and the MSRV) and fix what it finds
before starting anything else. The `Virtual machine` and `riscv32` jobs
do not block, and must be read all the same.
Never `git add` anything under `.claude/`. A Windows function imported with
`dll!` in two files must have the same signature and the same structure types
in both. Do not weaken a test on a guess: establish the cause, keep the
strongest assertion that holds, and document the difference.