oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
# oscall: design

oscall is the layer between a program and the operating system: one API for
files, memory, networking, time, threads and processes that behaves the same
on Linux, macOS and Windows, that works in a
[fullrust](https://github.com/KarpelesLab/fullrust) binary, where there is no
libc at all, and that compiles to WebAssembly, where it offers what WASI has.

[internals.md](internals.md) describes how the crate is put together.

It sits below `std`: no buffering, no hidden allocation, no global state. Every
call maps onto one OS operation, or onto the few that are needed to give the
same result everywhere.

## Design rules

1. **No dependencies.** Not `libc`, not `windows-sys`, not `rustix`. Every
   system call number, structure layout and import is declared in this crate.
   That is what lets one source tree build for fullrust, where `libc` cannot
   link, and it keeps the crate usable at the very bottom of a dependency graph.
2. **`no_std` first.** The core needs neither `std` nor an allocator. `alloc`
   adds the calls that must allocate (long paths, directory listings); `std`
   (default) adds conversions only: `std::io::Error`, `OwnedFd`/`OwnedHandle`,
   `Path`.
3. **Two layers.**
   - `sys`: the raw platform layer, one backend per system. The module is
     private, and what a direct call to the system needs is public as
     `oscall::raw`, one sub-module per system and `unsafe` where the system
     is: the system call itself, its numbers and the error numbers on Linux;
     `errno`, `GetLastError`, `NTSTATUS` and path conversions elsewhere,
     where the functions are the system libraries' own. Handles convert to
     and from the system's raw handles, so anything oscall lacks can be done
     next to it, on the same handles and with the same errors.
   - Everything else: portable and safe wherever the operation allows it,
     built only on `sys`.
4. **Portable by default, platform-specific by name.** A portable function
   behaves the same on every OS. What only one OS offers lives in an extension
   module named after it (`oscall::mem::linux::remap`), never as a portable
   function that fails elsewhere. WebAssembly is the one exception: it lacks
   whole subsystems (memory mapping, sockets, processes), and there the
   portable functions fail with `ErrorKind::Unsupported`.
5. **Errors are the OS's own.** `Error` holds the raw code (`errno`, or
   `GetLastError`/`WSAGetLastError`/`NTSTATUS`) and maps it to a portable
   `ErrorKind` on request. Nothing is lost in translation and no thread-local
   `errno` is involved on Linux.

## Backends

### Linux and fullrust: raw system calls

One backend serves both, selected with
`any(target_os = "linux", target_os = "fullrust")`. fullrust is not
`cfg(unix)`, so nothing in the crate may be gated on `cfg(unix)`.

- System calls are made with inline assembly (`syscall`, `int 0x80`, `svc 0`,
  `ecall`): one small module per architecture, `syscall0`..`syscall6`. Stable
  inline assembly covers all six architectures on Rust 1.95.
- The system call numbers and kernel structures are per architecture. The
  tables are generated from the kernel headers by a script kept in the
  repository, and committed.
- 32-bit targets use the 64-bit time and offset calls (`clock_gettime64`,
  `statx`, `_llseek`/`pread64`, ...) so that the API is identical to 64-bit.
- Known hazards to design around:
  - `arm` in Thumb mode and `x86` with PIC reserve `r7`/`ebx`, which the
    system call convention needs: the assembly must save and restore them.
  - `clock_gettime` is only fast through the vDSO, and with no libc there is
    no dynamic linker to find it: oscall reads `AT_SYSINFO_EHDR` from
    `/proc/self/auxv`, checks that the image is readable before reading it,
    parses it with bounds-checked code and calls its `clock_gettime`,
    falling back to the system call whenever any of that fails or the
    function does not answer. riscv32 has no clock in its vDSO.
  - When a libc is present in the process (plain Linux targets), oscall
    bypasses it. That is fine for most calls, but not for what libc keeps
    state about: thread creation and the program break are left alone;
    children are created with `clone(CLONE_VM | CLONE_VFORK)` and run nothing
    but system calls until `execve` (without `CLONE_VM` when the child
    changes its user or group, which the kernel records on the memory;
    `process::unix::fork` exists, is `unsafe`, and leaves its child the
    same rule); signal handlers are installed with
    oscall's own restorer, only record the signal, and the previous
    disposition is put back when the subscription ends.

### macOS: libSystem

The kernel's system call interface is private and changes between releases;
`libSystem` is the supported boundary, and every Rust binary already links it.
oscall declares the functions it uses in its own `extern "C"` blocks, with the
structure layouts for x86_64 and aarch64. The backend is gated on
`target_os = "macos"`; iOS and the other Apple systems can share it later.

### Windows: kernel32, ntdll, ws2_32

Imports are declared with `#[link(kind = "raw-dylib")]`, so no import library
and no `windows-sys` is needed, on MSVC and GNU toolchains alike. Paths are
UTF-8 in the API and converted to UTF-16 at the call (on the stack when short,
on the heap with `alloc`). Sockets are a separate handle type from files, as
they are in the OS.

### WebAssembly: WASI preview 1, or nothing

On `wasm32-wasip1` (and `wasm32-wasip2`, through its preview 1 adapter) oscall
declares the `wasi_snapshot_preview1` imports itself. Files, clocks, random
numbers and polling work; the rest fails with `Unsupported`.

On `wasm32-unknown-unknown` there is no system interface: the crate compiles,
and everything that needs a system fails with `Unsupported`.

## Non-goals

- **Creating threads.** A thread made behind the back of the runtime (libc's,
  or fullrust's `std`) has no thread-local storage that runtime knows about,
  and Rust code cannot run on it soundly. `std::thread` owns thread creation;
  oscall covers what the current thread can do (identity, yielding,
  affinity) and the wait/wake primitive locks are built from.
- **Environment and arguments.** They belong to the runtime that received
  them at startup; `std::env` is the interface.

## Targets

| | x86_64 | x86 | aarch64 | arm | riscv64 | riscv32 |
|---|---|---|---|---|---|---|
| Linux | tested | tested | tested | tested (qemu) | tested (qemu) | tested (qemu)¹ |
| fullrust | tested | tested | tested (qemu) | tested (qemu) | —² | — |
| macOS | tested | — | tested | — | — | — |
| Windows | tested | tested | tested | best effort³ | — | — |

1. Rust has no `std` build for riscv32 Linux (tier 3), so it is tested with
   a nightly toolchain that builds one (`-Zbuild-std`), outside the stable
   path: a CI job that reports without blocking lints the target, runs a
   program with no libc at all (`tests/freestanding`) and runs the whole
   test-suite as static musl binaries, all under qemu-user
   (`scripts/riscv32.sh`; musl 1.2.6 or later, qemu 10). Its
   vDSO has no clock: reading one is a system call there.
2. fullrust has no RISC-V target yet. Since the Linux backend is the same,
   supporting it will only need the CI entry.
3. 32-bit ARM Windows is tier 3 in Rust and no longer shipped by Microsoft.
   Nothing in the crate excludes it; nothing tests it.

"—" means the OS does not exist on that architecture.

WebAssembly: `wasm32-wasip1` is tested (wasmtime); `wasm32-wasip2` and
`wasm32-unknown-unknown` are type-checked.

## What exists

Every module below is implemented on every backend, with integration tests
that run on every tested target.

| Module | Contents |
|---|---|
| `oscall` | `Error`, `ErrorKind`, `Result`; `OwnedHandle`, `BorrowedHandle`, `AsHandle`; `AsPath` |
| `oscall::mem` | page size; anonymous and file mappings, anywhere, at a free address or inside a placeholder (`MapOptions`); shared memory with a handle; protect, reserve/commit/decommit, advise, flush, lock; executable memory and the instruction cache; an owning `Mapping` |
| `oscall::io` | read/write, positional and vectored I/O, seek, pipes (blocking or not), duplicate, standard handles, inheritance |
| `oscall::fs` | open, metadata, permissions, times, locks, links, rename, copy, space, preallocation, directory listing, and the same operations relative to a directory handle |
| `oscall::time` | wall clock, monotonic, boot-time and CPU clocks (through the vDSO on Linux), sleep |
| `oscall::rand` | the system random generator |
| `oscall::sync` | wait/wake on an address (futex, `os_sync_wait_on_address`, `WaitOnAddress`) |
| `oscall::thread` | the current thread: id, yield, parallelism, name |
| `oscall::net` | sockets (IPv4, IPv6, Unix-domain), addresses, options, vectored I/O, interfaces |
| `oscall::event` | stateless `poll`, and a `Poller` (epoll, kqueue, I/O completion port with AFD) that waits for sockets, timers (one-shot and periodic), signals, child processes that exit, and wake-ups from other threads |
| `oscall::process` | ids, exit, spawning children, wait, kill, resource usage, termination requests (signals, console events); setting a child up and containing it is per system, in the extensions |
| `oscall::raw` | the escape hatch, per system: `raw::linux` (`syscall0`..`syscall6`, `syscall!`, `check`, the system call numbers `nr`, `errno`), `raw::apple` (`errno`, `last_error`, `cvt`), `raw::windows` (`last_error`, `cvt`, `nt_error`, `with_wide`, `wide_to_wtf8`, `dll!`), `raw::wasi` (`errno`, `cvt`), and `raw::with_cstr` |

What only one family of systems has is in extension modules named after it:
`mem::linux` (remap, huge pages, populating, more advice, locking
everything), `mem::macos` (`MAP_JIT`, regions), `mem::windows` (regions),
`mem::unix` (access patterns), `fs::unix` (owners, FIFOs), `net::unix`
(socket pairs, handle passing, peer credentials), `net::linux`,
`net::windows`, `event::unix` (polling any handle), `event::windows` (waiting
for any waitable handle), `thread::linux` and
`thread::windows` (affinity), `process::unix` (signals, groups and sessions,
limits of the process and of a child, the user, groups and file creation
mask of a child, `fork`), `process::linux` (namespaces and the maps of a
user namespace, process descriptors, starting a child in new namespaces or
in a cgroup, `prctl` attributes, a signal for the child whose parent goes
away), `process::windows` (console groups and events, job objects: limits
on memory, processor time and the number of processes, accounting,
terminating a whole tree, also when the parent ends).

## Not there yet

- **Completion-based I/O** (io_uring, overlapped I/O) as an interface of its
  own. `event` reports readiness; pipes are event sources where the system
  has readiness for them, which Windows has not.
- **Name resolution.** Not an operating system service on Linux; out of scope.
- **Mapping over an arbitrary mapping** (`MAP_FIXED` proper) and **address
  hints**: Windows has neither. `MapOptions::at` fails when the address is
  taken, and `MapOptions::in_placeholder` replaces part of a placeholder,
  which is what every system can do.
- **Asking what is mapped at an address on Linux**, which has no system
  call for it short of reading `/proc/self/maps`: `mem::windows::query` and
  `mem::macos::query` are extensions for that reason.
- **Large pages on Windows**: they need a privilege
  (`SeLockMemoryPrivilege`) no test can be given.
- **A child that ends with its parent, on macOS.** Linux has the parent
  death signal and Windows a job that is closed with its last handle; macOS
  has nothing the parent can set on a child, which has to watch for its
  parent itself. There is therefore no portable form either.
- **Containing a child's resources portably.** Limits are `RLIMIT_*` values
  on Linux and macOS and job limits on Windows, which do not count the
  same things; a tree of processes is only held together by a Windows job
  (and by Linux cgroups).
- **Opening a file for execution on Windows.** Mapping a file as code needs
  a handle opened with `FILE_EXECUTE`, which `fs::OpenOptions` cannot ask
  for: such a handle has to come from elsewhere for now.

- **The rest of a container on Linux.** `process::linux` creates
  namespaces and puts a child in a cgroup, which is what the kernel offers
  to contain a process and to limit the memory of a tree of them. Not there:
  mounting (`mount`, `umount2`, `pivot_root`, `chroot`, the new mount API),
  capabilities (`capset`), `seccomp` filters, the offsets of a time
  namespace, and anything that manages cgroups (they are files: `fs` reads
  and writes them). `raw::linux` makes those calls meanwhile.

0.1.0 is the first release with every module on every backend. The API may
still change between 0.x releases, as what uses it shows what is missing.

## Testing

- Every portable function has tests that run on all tested targets: natively
  on the Linux, macOS and Windows runners (x86_64 and aarch64 each), as static
  musl binaries under qemu-user for arm and riscv64, and with the fullrust
  action for its four targets. riscv32 runs the same tests with a nightly
  toolchain, in a job that does not block.
- `tests/freestanding` is a program with no libc and no `std` (its own entry
  point, `core` and oscall only) that calls a little of every module: the
  proof that the Linux backend needs nothing else, on the host and on
  riscv32.
- Where `std` offers the same operation, tests compare oscall's result with
  `std`'s (same file contents, same metadata, same error kind).
- What depends on the environment (user namespaces, a writable cgroup
  hierarchy, a system call an emulator or a container's filter lacks) is
  tested where the environment has it, and elsewhere the test says what it
  skipped and why. `tests/process_linux_single.rs` has no test harness: it
  must be a process with a single thread.
- The MSRV (1.95) is checked on every push.