oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
# 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)
tests/freestanding/   a package of its own: oscall with no libc and no std
```

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.
- **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`.
- 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.

## 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.
- 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).

## 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.

## 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.
- `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.

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) (`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`).
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,
   fullrust and the MSRV) and fix what it finds before starting anything else.

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.