Read this before adding to the crate. plan.md has the goals; this is the mechanics.
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.
- No dependencies, and no
build.rs. no_std.coreonly by default. Usealloconly behind#[cfg(feature = "alloc")], and offer an allocation-free form of the same operation (caller-provided buffer) whenever one makes sense.stdis for conversions withstdtypes only.- Safe wherever possible. A function is
unsafeonly when memory safety depends on the caller (mapping memory, raw pointers). Everyunsafeblock has a// SAFETY:comment; everyunsafe fna# Safetysection. - 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 withErrorKind::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 + ?Sizedand converted withpath::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 newErrorKindis really needed, add it toerror.rsand to every backend'sERRORStable. - What a release published stays.
cargo semver-checks --baseline-rev v0.1.0 --all-features, for a Linux target,--target x86_64-pc-windows-gnuand--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 inprocess::linux), because a method added to a trait anyone may implement breaks whoever did.process::linux::CommandExtwas published open in 0.1.0 and has the methods it had then: what came later is inprocess::linux::ConfineExt. - Documentation. Every public item is documented (
missing_docsis 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>.rsthat runs on all platforms, comparing withstdwherestdoffers the same operation. Files go undercommon::tmp_dir(name). A test that cannot hold on a platform iscfg'd out for that platform alone, with a comment saying why.
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 ontarget_os = "linux"alone. -
Use the modern system call of each family, everywhere: aarch64 and riscv do not have the legacy ones.
openatnotopen,statxnotstat,pipe2,dup3,ppoll,epoll_pwait,renameat2,mkdirat,unlinkat,clonenotfork... -
32-bit targets (x86, arm, riscv32): use the 64-bit time and offset variants (
clock_gettime64,futex_time64,ppoll_time64,mmap2,_llseekorllseek,statx,fcntl64...) with the 64-bit__kernel_timespec. riscv32 has no 32-bit time calls at all. Check which name exists innrfor each architecture andcfgontarget_pointer_widthortarget_archaccordingly. -
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/pwritevtakepos_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 swapO_DIRECTORY/O_NOFOLLOW/O_DIRECT/O_LARGEFILEcompared to x86 and riscv) and somestructlayouts (epoll_eventis 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./procmay be missing, so every user has a fallback. -
The vDSO (
sys::vdso) is used forclock_gettimeonly. 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'svdso.lds.S. -
Creating a child (
sys/linux/process.rs):clone(CLONE_VM | CLONE_VFORK)on a stack of its own, then system calls only untilexecve. Four things change that, three of them inprocess::linux:- A child that changes its user or group (
process::unix) is created withoutCLONE_VM.commit_credssets the dumpable flag of the mm tofs.suid_dumpablewhen the effective or filesystem ids change, and withCLONE_VMthe mm is the parent's (measured: after such a spawn the parent'sPR_GET_DUMPABLEwas 0: no core dump, no ptrace,/proc/selfowned 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, andcapset,PR_CAPBSET_DROPand 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 calledexecveor reported, and a child that could not be released is killed and waited for before they are freed. clone3is used whenclonecannot say it: a cgroup (CLONE_INTO_CGROUP) or a time namespace (whose flag is one of the bitsclonekeeps for the exit signal). The default system call filter of Docker answersENOSYStoclone3, and qemu-user has none: for a cgroup the child is then created withcloneand writes itself tocgroup.procs.- qemu-user turns
clone(CLONE_VM | CLONE_VFORK)into afork, and refuses theCLONE_NEW*flags withEINVAL: nothing creates a child in a namespace there. It also interrupts waits the kernel would not: aPoller::waitof a test whose process has no signal handler came backInterruptedin 10 runs of 240 (qemu 10.0.13, two processors, the tests ofprocess_linuxin parallel; why was not established).
- A child that changes its user or group (
-
A failed
cloneleaves a pidfd number behind. WithCLONE_PIDFDthe 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.
unshareandsetnsmove 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 intests/process_linux_single.rs(harness = false), or is done by a child created in the namespace. Afterunshare(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_usernsprofile, 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 laterunshare,/proc/self/setgroups, writingsecurity.capabilityall fail withEPERM). Docker's default filter (the fullrust jobs):EPERMforunshare,setns,mountandclonewith a namespace flag,ENOSYSforclone3, and a read-only cgroup hierarchy;seccompitself is allowed, and the process already has a filter (strict mode is then refused,EINVAL). qemu-user: see above; it has noseccompeither (ENOSYS, andEINVALforPR_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.shruns the tests there, andscripts/vm.shin virtual machines, withOSCALL_REQUIRE_PRIVILEGED=1. -
Skipping. A test that the environment keeps from testing says so with
common::skip(skip!), which fails whenOSCALL_REQUIRE_PRIVILEGEDis 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 withnote!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.shruns the tests underdocker run --init. -
capgetis filtered by security modules,/procis not. Under AppArmor'sunprivileged_usernsprofile (GitHub's runners), the root of a user namespace has every capability in/proc/<pid>/statusand none according tocapget(measured), and the kernel's own checks disagree:PR_CAPBSET_DROPasks the module and is refused, whilePR_SET_SECUREBITSlooks at the credentials and succeeds. A test that expects a refusal from the setscapgetreturned must first check that they are what/procsays. -
Credentials and filters belong to threads too.
capset,prctl(the bounding and ambient sets, the secure bits,PR_SET_NO_NEW_PRIVS),setresuid,setresgid,setgroupsandseccompchange the calling thread, and the threads it creates afterwards. libc'ssetuidfamily 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::buildwrites 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/shof 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 forclone3, whose number is the same everywhere. -
pivot_rootcannot leave the initial file system of the kernel (rootfs, what an initramfs is unpacked into):EINVAL.tests/vm_init.rsfirst moves to a tmpfs mounted over/(MS_MOVE,chroot), asswitch_rootdoes. Mountingprocfrom a user namespace needs a process namespace owned by it and a/procof which nothing is hidden: in a container that masks parts of/procit isEPERM. -
32-bit kernels of arm and riscv have no time namespaces (Linux 6.18:
CONFIG_TIME_NSneeds 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 withoutCONFIG_COMPAT_32BIT_TIMEanswersENOSYStonanosleep. -
The offsets of a time namespace are written while it is empty (
EACCESafterwards), 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, incloneitself (askernel/nsproxy.cof Linux 6.18 reads; the first is measured, the second is not). So the parent writes/proc/<pid>/timens_offsetsof 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, callsunshare(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, andunsharemoves one thread:set_time_offsetswrites/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 isERANGE, which reads asBufferTooSmall. -
/proc/<pid>means the process<pid>of the process namespace/procwas mounted in, not of the caller's. A process that is the first of a new process namespace and still has the old/proccannot write the maps of a child it spawns: the identifierspawngot names someone else there. The helper oftests/fs_linux.rsthat 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:fspickwants the root of a mount: a directory under one isEINVAL.- A mount
fsmountmade and a treeopen_treeopened are handles of a path alone (O_PATH):fsconfigon one isEBADF, where a file isEINVAL. While one is open its mount is in use, andumountsaysEBUSY. - After
FSCONFIG_CMD_CREATEanother option, or a second creation, isEBUSY;fsmountbefore it isEINVAL, and a secondfsmountEBUSY. What a filesystem says of an option it refused is read from the handle (e tmpfs: Unknown parameter '...'), and reading when it said nothing isENODATA. mount_setattrwants the three bits of the access time setting cleared whenever one of its values is set (EINVALotherwise), 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 isEOVERFLOW. 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, isEINVAL, and a unique identifier that names nothingENOENT.LSMT_ROOTlists every mount of the namespace, the one at its root included, in ascending order. - A mount that is attached nowhere has an identifier (
statxgives it, on the handle) and is in no namespace:statmountsaysENOENT. - The file joins a type and its kind (
fuse.sshfs), whichstatmountgives apart. A buffer too small for the answer isEOVERFLOW, which reads asBufferTooSmall. - 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
fsconfigthat are paths (FSCONFIG_SET_PATH,FSCONFIG_SET_PATH_EMPTY) are commands the kernel takes, for options no filesystem at hand has:tmpfs,proc,cgroup2andext4answerEINVALfor theirs,sourceincluded ("Non-string source").FSCONFIG_CMD_CREATE_EXCLcreates atmpfs, and isEBUSYforcgroup2, of which there is one; after that refusal the configuration takes nothing more (EBUSYfor a plain creation too). open_tree_attrwithoutOPEN_TREE_CLONEchanges the mount that is at the path, asmount_setattrwould, and returns a handle of the place.
- The unique identifiers start above 2³¹, to be no short identifier of
-
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:
spawnwithStdio::Nullopens/dev/nullfor reading and writing, and fails withEACCES. - A handle that is no ruleset is
EBADFD(77), which is notEBADF; a ruleset or a rule about nothing isENOMSG. - The child of
spawnrestricts itself first among the last things it does: beforecapset, 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 ofscripts/vm.share built with it.
- 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
-
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 ofspawnthat 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=1too (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.rshas no harness for that reason. - The status of a stop is whole in
waitid:si_statusis the signal, orevent << 8 | signal, orSIGTRAP | 0x80, aswait4has it above the low byte. riscv32 has nowait4. - A wait for a child to stop, when the child has ended, is
ECHILD, withWNOHANGor without: it does not wait for nothing. PTRACE_SINGLESTEPisEIOon 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_GETSIGINFOin a group-stop: a tracee that was seized answers, with the status of the stop assi_code; one that was attached saysEINVAL, and its group-stop reports as the stop signal coming a second time. Such a tracee is told nothing of aSIGCONTuntil it is restarted.- A filter's
SECCOMP_RET_TRACEis 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_readvandprocess_vm_writevthrough and refusespidfd_getfd(EPERM); qemu-user has noptrace(ENOSYS: a child that is to trace itself is not spawned).process_vm_readvneeds a kernel built withCONFIG_CROSS_MEMORY_ATTACH, which those ofscripts/vm.share.
- A tracer is a thread, and so is a tracee. A request by another
thread of the tracer's process is
-
What is mapped (
mem::linux):/proc/self/mapsis read through a buffer of the structure, and answersPROCMAP_QUERYsince Linux 6.11. Under qemu-user the file is the emulator's own account of the program's memory and has noioctl:queryreads the text there, which is also what a unit test does everywhere, to compare the two. The name theioctlgives 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 withoutCAP_SETFCAPisEPERMalso 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);/prochas no extended attributes (EOPNOTSUPP). They do nothing on a filesystem mountednosuid, which is how docker mounts a--tmpfs:scripts/privileged.shasks forsuid. -
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 gaveset_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:execvegave 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 pipespawnlearns of failures by, sospawnreturns when it has sent and gone. A listener'sSECCOMP_IOCTL_NOTIF_SET_FLAGStakes its flags as the argument itself, whatever its number says of a pointer; and thepidof 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 survivesexecve. -
io_uring (
io::linux; the system calls and the layouts are insys/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 ofu64(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 withmmap2, 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). WithoutSQPOLLthe kernel reads the submission queue duringio_uring_enteronly, which is whypushpublishes the tail at once andsubmitkeeps 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. Setuphas 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 ordinarypushzeroes the second half of a wide entry.- A thread of the kernel that submits (
SQPOLL) reads the tail at any time, whichpushalready allowed for (the entry, then the tail withRelease). What it adds is the wake-up: the thread setsIORING_SQ_NEED_WAKEUPand 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_enterreturns 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_enterreturns, 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 inRing::new), andpushrefuses the entry of an operation that is not there. For a registration the kernel saysEINVALwhether it does not know it or finds it wrong;or_unsupportedmakes thatUnsupportedwhen an operation that came with the same release is missing (MSG_RINGfor registered ring descriptors, 5.18;SOCKETfor rings of buffers and sparse tables, 5.19;MKDIRATfor the limit on workers, 5.15). The affinity of workers came with 5.14, which brought no operation: the witness is the featureRSRC_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::flagsdropsFIXED_FILEandBUFFER_SELECT. With the second, the kernel writes to the memory of a group, which only anunsafeconstructor may ask for (Sqe::buffer_select): were the flag settable in safe code, dropping aBufRingcould free memory under an operation that nounsafeblock 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_ringis 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.Dropasks the kernel to forget the group, through a duplicate of the ring's descriptor (theRingmay 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
ENOBUFSand noIORING_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, notENOENT, because all are asked for (IORING_ASYNC_CANCEL_ALL). A zero-copy send to a socket that is not connected fails withEPIPEandIORING_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 anint(measured: 0 for root in the privileged container, where the limit is infinite, and a number everywhere else; the cause is read fromio-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 afterio_uring_enterwithGETEVENTSand a count of 0.Ring::readyis 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:
EINVALfrom 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, soregister_ring_fddocuments it andDropdoes 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_tand the mask of processors in their 32-bit layouts for a ring such a program made (ctx->compat), which the tests ofsendmsg,recvmsg,waitidand the affinity of workers pass by. io_uring_enterreturns 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
closereturns: 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
EPERMtoio_uring_setup(the fullrust jobs of CI and ofscripts/check.sh), and the qemu-user of the fullrust imageENOSYS. The tests then skip, and say so;OSCALL_REQUIRE_IO_URING=1makes 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 ofscripts/check.sh(x86_64 and x86 then pass; aarch64 and armv7 are emulated, and skip).scripts/privileged.shruns 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.shruns them, required, on kernels of riscv64, riscv32 and arm (Linux 6.18 built withCONFIG_IO_URING), where qemu-user has nothing;tests/vm_init.rsbrings 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 answersENOSYStoio_setup. Andio_submitdoes 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 structures shared with the kernel (
-
The arguments and the environment (
sys/linux/env.rs) are read from/proc/self/cmdlineand/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. (Thestdof fullrust keeps them in private statics and exports no symbol; a C library hasenviron, which oscall does not link.) What that means, as measured:- They are the values the process was started with.
setenvandstd::env::set_varchange a copy the runtime keeps, and fullrust's a private map: neither shows. - A process that made itself not dumpable (
PR_SET_DUMPABLE0) and is not root still readscmdline, and is refusedenvironandauxv(EACCES: the files then belong to root, and those two are mode 400). - qemu-user answers
/proc/self/cmdlinewith the arguments of the program it runs, not its own, andenvironis the emulator's, which is the program's (the tests compare both withstdthere). - 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.
- They are the values the process was started with.
-
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'sstd:tls::heap(), in the patch ofsys/pal/fullrust); fullrust builds the block in its own wrapper ofclone, a hidden symbol, and exports nothing to build one with. So the code of such a thread runscoreand 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 answerscloneitself, 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_WAKEwithoutFUTEX_PRIVATE_FLAG, askernel/fork.creads), and a private wait is on another queue:sync::waitcannot be used for it. The wait inspawn.rsis the plainFUTEX_WAIT. - A detached thread unmaps its own stack, which it is standing on:
munmapandexitare made from registers by one block of assembly with nothing between them. Before that the thread callsset_tid_address(0): the word the kernel clears when a thread ends is in that mapping, and between themunmapand 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 ofthreadrun in a loop: without the call 16 runs of 12 000 ended withSIGSEGV(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_releaseinkernel/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
cloneand 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_vforkofprocess.rs, with the address of the word as the fifth argument ofcloneeverywhere 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).
- What it is not. It has the thread pointer of its creator (no
-
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, thennet::dnswith 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 gets127.0.0.1before::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,
forkwithout an immediateexec, signal dispositions libc reserves. (thread::linux::spawn_rawcreates 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, andPR_SET_PDEATHSIGafter 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_KEEPCAPSand the bounding set before the identity (dropping from the bounding set takesCAP_SETPCAP, which a change of user gives up, and the permitted set must survive that change for what follows), then, last beforeexecve,capset, the ambient set and the filter: under a filter nothing butexecve, andwriteandexit_groupif 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 the32variants: 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 offorkrun in a helper process for that reason, never in the harness process. The child of aspawnis 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.
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;, likewisefcntl,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,direntorstatfsneed the$INODE64symbol suffix (seesys/apple/mod.rs);$NOCANCELand$DARWIN_EXTSNvariants exist for some others. Check what thelibccrate 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, whereXATTR_NOFOLLOWreplaces Linux'slfunctions. 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 isENOATTR(93), where Linux saysENODATA(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 nouser.attribute (EPERMto set or remove one) and a name without a class isEOPNOTSUPP. -
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, assys/apple/sync.rsdoes, never by declaring them. -
Structure layouts are the same on x86_64 and aarch64, but verify each one against Apple's headers (the
libccrate'ssrc/unix/bsd/appleis a good transcription). -
posix_spawncannot set limits, a user, groups or a file creation mask. A command that asks for one is spawned byfork; 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 byposix_spawnwithPOSIX_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: withPOSIX_SPAWN_SETEXECadup2action whose source is close-on-exec, as every descriptor of oscall is, fails withEBADF(measured on the CI runners of both architectures), where the same action works when a process is spawned. Everything else keeps the plainposix_spawn. -
The first place of a process's list of groups is its own group's.
setgidwrites the group there, over whatsetgroupsput (measured: a child given the group 4242 and the groups 7 and 8 had 4242 and 8). The list given tosetgroupsis therefore the group the child is to have, then the others: 16 places in all. Andiddoes 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 withgetgroups. None of this runs in CI, where the tests are not root:sudothe test binary on awip/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 aiocbis 80 bytes andstruct sigevent32 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 withEISDIR. 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 thanINT_MAXbytes isEINVAL, as is a negative offset. - Every refusal is
EAGAINon 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 answersEBADF,ESPIPE,EINVALand keepsEAGAINfor the last. A test of a refusal acceptsWouldBlockin the place of any other kind. - The limits are
kern.aioprocmax(16) for a process andkern.aiomax(90) for the system. An operation holds its place fromaio_readuntilaio_return, not until it is over: 16 reads that were complete and not returned made the seventeenth fail. Hencesys::aio::take, which returns as soon asaio_errorsays the operation is over, andDrop, which does too. aio_error,aio_returnandaio_suspendknow a block by its address and only while it holds its place: all three answerEINVALfor a block that was returned, or never submitted, andaio_suspendalso for a list of nothing but null pointers. (It does not wait on what it does not know.)aio_returnon an operation that runs isEINPROGRESS. The result of a cancelled operation is -1, with anerrnothataio_returndoes not set on macOS 15: the error isaio_error's (ECANCELED), which is whytakeasks it first.aio_suspendwaits 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 asEAGAIN.- 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_cancelgives up what is queued (AIO_CANCELED, and the operation is over at once withECANCELED) and nothing that runs (AIO_NOTCANCELED); a block the kernel does not know isAIO_ALLDONE. - An operation that runs holds its descriptor, and on macOS 15 its
process.
closeon 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 calledexitwith 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_SIGNALdelivers its signal;SIGEV_THREADand anything else is refused (EINVAL).keventrefusesEVFILT_AIO:ENOTSUPon macOS 15,EPERMon macOS 26. - Flushing.
aio_fsynctakesO_SYNC,O_DSYNCand 0, and wants a descriptor open for writing (EBADFon one open for reading; on a FIFO it completes with 0). It isfsyncand notF_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.rstake 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 theEAGAINof macOS 15): a read of nothing wants an address all the same, which aVecthat holds nothing has. lio_listiotakes 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;EAGAINon 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 returnedEAGAIN. Which of the two happened is told byaio_erroron each block, which knows a block the kernel has and answersEINVALfor one it has not:Batchasks it. An operation that fails by itself (a read of a directory) is no failure of the call, which withLIO_WAITreturned 0 once both were over.- The notice by signal. The signal comes when the outcome is there:
aio_errorwas neverEINPROGRESSonce 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 oflio_listiois 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. (Batchclears 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) andSIGKILLare refused when the operation is submitted;SIGSTOPwas not tried. An operation whose notice isSIGIO, ended with no handler for it, left the process alone: the system discards that signal by default, which is why it is the oneio::macosnames. - The rest of what the system has.
preadvandpwritevare inlibSystem;F_NOCACHEis 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.libSystemalso 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:dlsymfinds 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 bydispatch_readwith the 4096 bytes asked for, on a thread of libdispatch's pool (not the caller's; the onedispatch_async_fhad 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 isreadandpread: a program that wants that has threads of its own, andio.
- The layouts.
-
The arguments, the environment, threads and names.
_NSGetArgvand_NSGetEnvirongive what the C runtime has, the second being the environment as it is now; reading it is whatgetenvdoes, with no lock (seeprocess::vars). A function declared in two files must have the same signature in both, to the mutability of the pointers (clashing_extern_declarations).pthread_createwants a stack of whole pages and of 16 KiB at least, or answersEINVAL: the backend rounds.getaddrinfoandgetnameinforeturn numbers of their own (EAI_*), which mean other things aserrnovalues: the backend turns each into the system error that says the same, so that anErrorstays a system error.struct addrinfohas its members in another order than on Linux (ai_canonnamebeforeai_addr).
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 (geteverywhere), 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 isNone, which its callers treat as a server that failed. Add a unit test with the malformed case for anything it learns to read;noisethere 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
Configis 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.
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 needWSAStartuponce per process. NTSTATUSresults are converted withRtlNtStatusToDosError(sys::nt_error).- A handle may be open for overlapped operation when oscall did not open
it (a
stdfile opened withFILE_FLAG_OVERLAPPED, the pipe of a child process, an inherited handle). On such a handleReadFile,WriteFile,LockFileEx,DeviceIoControland theNtcalls 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 saysSTATUS_PENDINGand do not return before it says otherwise:sys::io::completedandsys::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, theEventofNtReadFile) 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. AnOperationgives every operation an event for that reason; it is what letsDropcancel 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,NtWriteFileof 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 anOperationon 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 withERROR_BROKEN_PIPE. Closing the read end under a read in flight completes it withERROR_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::pipecannot be made non-blocking:SetNamedPipeHandleStateanswersERROR_ACCESS_DENIED. (Presumably for want ofFILE_WRITE_ATTRIBUTES, whichCreateNamedPipeWdoes not ask for the inbound end of a pipe andCreatePipedoes; 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
NtReadFilereturns 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) isERROR_INVALID_PARAMETERat the start, each of the three; so isNtReadFileScatteron 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.
NtReadFileof a message of a pipe longer than the buffer, andWSARecvFromof a datagram longer than the buffer, both with the data there before the call: the call says pending, the status of the operation isSTATUS_BUFFER_OVERFLOW(0x80000005) with the count of what fitted, and a packet is queued, also on a handle that hasFILE_SKIP_COMPLETION_PORT_ON_SUCCESS. Winsock was never seen to returnWSAEMSGSIZEfrom 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. NtReadFileon a file open for overlapped operation answers "pending", for 4096 bytes through the cache as for 32 MiB without it, and so doesNtWriteFilewithout 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. SoFILE_SKIP_COMPLETION_PORT_ON_SUCCESSsaves next to nothing on a file, nearly every operation of which queues its packet.FILE_SKIP_COMPLETION_PORT_ON_SUCCESSdoes 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. HenceOperation::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 isERROR_INVALID_PARAMETER.FILE_SKIP_SET_EVENT_ON_HANDLEtakes away the signalsys::io::completedwaits on for the synchronous calls, which then find their operation complete by looking (wait_completionpolls 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
ConnectNamedPipeis called, which then answersERROR_PIPE_CONNECTED(as it does for an instance that has its client); once its client has gone,ERROR_NO_DATAuntilDisconnectNamedPipe; disconnected, it takes no client (ERROR_PIPE_BUSYtoCreateFileW) untilConnectNamedPipeis called again. A write to a pipe the server disconnected isERROR_PIPE_NOT_CONNECTED. One more instance than the pipe was created to have isERROR_PIPE_BUSY, a second "first" instanceERROR_ACCESS_DENIED, a client that asks to read a pipe the server readsERROR_ACCESS_DENIED, and message mode on a pipe of bytesERROR_INVALID_PARAMETER(fromSetNamedPipeHandleState, once the client is connected: the instance has then had its client). WaitNamedPipeWgives up before its timeout: asked for 60 ms with no instance to wait for, it once returnedERROR_SEM_TIMEOUTbefore 50 ms had passed (aarch64; by how much was not recorded), where the other runs took the 60.wait_pipekeeps 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.TransmitFilereads from the offset of theOVERLAPPED, 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 withERROR_INVALID_HANDLE(and a test that waited for the bytes waited for ever), and on x86_64, 64 and 32 bits, the nextTransmitFileon 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.WSARecvFromwrites the address and its length when the operation completes, not when the call returns: both are in theOperation's allocation (RawAddr, whose length is atLEN_OFFSET), as is the array of pages of a scattered read. The array ofWSABUFs and the flags are read by the call.ReadDirectoryChangesWisNtNotifyChangeDirectoryFile, 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 aDWORD(theOperationallocatesu32s). 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, areERROR_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. ConnectExis not exported: it is asked of the socket's provider (SIO_GET_EXTENSION_FUNCTION_POINTER), wants a bound socket, and likeAcceptExleaves a socket that is only like the others afterSO_UPDATE_CONNECT_CONTEXTorSO_UPDATE_ACCEPT_CONTEXT.
- When the status block is written depends on the event. An operation
given an event (
- The command line is split by oscall (
process/env.rs), by the rules of Microsoft's C runtime since 2008, whichstdapplies too: the inverse of whatCommandquotes. 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. GetAddrInfoWandGetNameInfoWreturn their error, a Winsock code (WSAHOST_NOT_FOUND...), and needWSAStartuplike any Winsock call (sys::net::startup). The codes are inERRORS, 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
SeDebugPrivilegeenabled, andSeBackupPrivilege,SeRestorePrivilege,SeShutdownPrivilege,SeCreateSymbolicLinkPrivilegeandSeIncreaseWorkingSetPrivilegedisabled;SeChangeNotifyPrivilegeenabled, as every token has it; and noSeLockMemoryPrivilege. What oscall reads is whatwhoami /privprints, before and after each switch. AdjustTokenPrivilegessucceeds for a privilege the token does not hold, enabling or disabling, and leavesERROR_NOT_ALL_ASSIGNEDin the last error:set_privilegereturns that. Names are looked up in any case of letters.VirtualAllocwithMEM_LARGE_PAGESand no privilege isERROR_PRIVILEGE_NOT_HELD; with a length that is no multiple ofGetLargePageMinimum(2 MiB on both architectures) it isERROR_INVALID_PARAMETER, which comes first.- The privilege is a matter of logons.
LsaAddAccountRightsgave 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.rsdoes both where it is allowed to change the machine (GITHUB_ACTIONS, orOSCALL_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).
- The token of the tests holds
- A file is mapped as code only if it was opened with
FILE_EXECUTE(fs::windows::OpenOptionsExt::execute):CreateFileMappingWwith an executable protection isERROR_ACCESS_DENIEDon a handle opened for reading alone. The right is asked for byCreateFileWand byNtCreateFile(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.
wasi: declarewasi_snapshot_preview1imports (seesys/wasi/mod.rs);sys::cvtturns the returnederrnointo aResult. Paths are relative to preopened directories.sys/wasi/mod.rshas the table of every call of preview 1 and what uses it: keep it when a call gains a user.args_getandenviron_getwrite 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 withErrorKind::Unsupported, except what needs no system.
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.
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).
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).
scripts/check.shpasses (set nothing: it uses./target). When runningcargoby hand in one of several checkouts, give it the sameCARGO_TARGET_DIR=$PWD/target: a target directory shared between checkouts (atarget-dirin~/.cargo/config.toml) can link a test with the library of another checkout.- 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; aTest & 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. git fetch origin && git rebase origin/master, check again if master changed code the change uses, thengit push origin HEAD:master. Never force-push master; if the push is rejected, fetch, rebase, push again.- 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 machineandriscv32jobs 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.