Files
ww/lib/os/os.ww
Hojun-Cho 87c088359d lib/os+test: export alloc + free via rt_alloc/rt_free
Add os.alloc(n: u64) *void and os.free(p: *void, n: u64) void as
`export fn` via @symbol("rt_alloc") / @symbol("rt_free"). Signatures
mirror lib/memio's existing internal bindings byte-for-byte — only
the name and `export` keyword change. lib/memio + lib/shlex + lib/
getopt drop their own copies in a follow-up commit.

Doc comment spells out the actual failure ABI: rt_alloc wraps the
raw mmap syscall (no libc), so OOM yields a negative-errno cast to
`*void` (e.g. (void*)-12 for ENOMEM). Neither `== nil` nor the libc
MAP_FAILED `(void*)-1` value catches it; deref faults. A typed
fallible variant is future work (alongside #16 fmt.asprintf).

Test (ostest test_alloc_free_roundtrip, signalled=5): alloc 4096B,
write 0x5a at head + 0xa5 at tail, read-back asserts both, free.
The head+tail write/read prevents DCE (failure path calls os.exit)
and proves a real page is backing the returned pointer.
2026-05-16 01:54:20 +09:00

368 lines
13 KiB
Plaintext

// os — process and filesystem facade. The body of each call lands
// either in libwwrt.a (rt_syscall trampoline) or libc bindings,
// depending on how the program was linked.
@symbol("rt_syscall") fn syscall0(num: nr) i64;
@symbol("rt_syscall") fn syscall1(num: nr, a: i64) i64;
@symbol("rt_syscall") fn syscall2(num: nr, a: i64, b: i64) i64;
@symbol("rt_syscall") fn syscall3(num: nr, a: i64, b: i64, c: i64) i64;
@symbol("rt_syscall") fn syscall4(num: nr, a: i64, b: i64, c: i64, d: i64) i64;
// alloc / free — runtime mmap-backed page allocator. Untyped:
// `alloc(n)` returns a `*void` and `free(p, n)` requires the byte
// count back because rt_free is munmap-based and doesn't track
// mapping sizes (the kernel needs the length to release the
// reservation).
//
// Diverges from Hare. Hare exposes `alloc` / `free` as typed
// language builtins (`alloc(value, cap)?` / `free(ptr)`) that the
// compiler lowers to rt::malloc/rt::free; ww has no such builtins,
// so the rt-symbol surface is exposed directly. Stdlib callers
// that need a typed allocation pattern wrap this with a cast plus
// a stored capacity (see [[strings.dup]], [[memio.dynamic]]).
//
// OOM: rt_alloc is a bare mmap(MAP_ANON|MAP_PRIVATE) wrapper with
// no error path. The raw Linux mmap syscall returns a negative
// errno cast to `*void` on failure (e.g. `(void*)-12` for ENOMEM);
// the `MAP_FAILED` (`(void*)-1`) value is a libc-wrapper convention
// that rt_alloc doesn't apply. Neither `== nil` nor `== (void*)-1`
// catches it; any deref of such a return faults. Today the stdlib
// does not check; OOM faults on first dereference. A typed
// fallible variant is a future task.
@symbol("rt_alloc") export fn alloc(n: u64) *void;
@symbol("rt_free") export fn free(p: *void, n: u64) void;
@symbol("rt_abort") fn abort(msg: str) void;
// Hare-style runtime check. Caller passes a message that's printed
// to stderr before exit(1).
export fn assert(cond: bool, msg: str) void = {
if (!cond) { abort(msg); };
};
// Linux amd64 syscall numbers. Internal to this module — passed as
// the first arg of syscall0..4 via libwwrt's rt_syscall trampoline.
// `nr` is the type so the call sites can't accidentally pass an
// arbitrary i64 (`syscall1(0i64, ...)` no longer typechecks).
type nr = enum i64 {
READ = 0,
WRITE = 1,
OPEN = 2,
CLOSE = 3,
LSEEK = 8,
ACCESS = 21,
DUP2 = 33,
GETPID = 39,
FORK = 57,
EXECVE = 59,
EXIT = 60,
WAIT4 = 61,
MKDIR = 83,
RMDIR = 84,
UNLINK = 87,
GETCWD = 79,
GETDENTS64 = 217,
};
// open(2) flags. Linux values, matching <fcntl.h>. Hare names them
// `fs::flag::RDONLY` etc; we use the same leaf names so callers say
// `os.flag.RDONLY` and `os.flag.WRONLY | os.flag.CREATE`.
export type flag = enum i32 {
RDONLY = 0,
WRONLY = 1,
RDWR = 2,
CREATE = 64, // 0x40
EXCL = 128, // 0x80 — pair with CREATE to fail on existing path
TRUNC = 512, // 0x200
};
// lseek(2) whence. Hare names it `io::whence`.
export type whence = enum i32 {
SET = 0,
CUR = 1,
END = 2,
};
export fn exit(code: i32) void = {
syscall1(nr.EXIT, code: i64);
};
// Raw, non-fallible primitives. These return Linux's int conventions
// (negative = -errno, non-negative = bytes/fd/etc). Callers wanting a
// Hare-style fallible API use the wrappers below.
export fn write(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.WRITE, fd: i64, buf: i64, n: i64);
};
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.READ, fd: i64, buf: i64, n: i64);
};
export fn close(fd: i32) i32 = {
return syscall1(nr.CLOSE, fd: i64): i32;
};
// dup2(2): make `newfd` refer to the same description as `oldfd`,
// closing `newfd` first if open. Returns `newfd` on success or a
// negative errno. Used by w6c_ww to redirect stdout into an output
// file without changing the cgen emit path.
export fn dup2(oldfd: i32, newfd: i32) i32 = {
return syscall2(nr.DUP2, oldfd: i64, newfd: i64): i32;
};
// Fallible wrappers. The error variant is `oserror` (an i64 carrying
// -errno). The sum type makes success/failure explicit and lets
// callers `?` the result up the stack.
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let r: i64 = read(fd, buf, n);
if (r < 0) { return r: oserror; };
return r;
};
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let r: i64 = write(fd, buf, n);
if (r < 0) { return r: oserror; };
return r;
};
// open — Linux open(2). Path must be NUL-terminated; callers using ww
// `str` must ensure the bytes are followed by a 0 byte (literals are,
// arena-copied paths usually are by construction). Returns -errno on
// failure, fd otherwise. Higher-level callers prefer `tryopen`.
export fn open(path: *u8, flags: flag, mode: i32) i32 = {
return syscall3(nr.OPEN, path: i64, (flags as i32): i64, mode: i64): i32;
};
export fn tryopen(path: *u8, flags: flag, mode: i32) (i32 | oserror) = {
let fd: i32 = open(path, flags, mode);
if (fd < 0) { return fd: i64: oserror; };
return fd;
};
// lseek — set/inspect the fd's position. Returns the new offset or
// a negative errno. We use this for fstat-free file-size discovery
// (open ⇒ lseek to end ⇒ lseek back).
export fn lseek(fd: i32, off: i64, w: whence) i64 = {
return syscall3(nr.LSEEK, fd: i64, off, (w as i32): i64);
};
// oserror — the underlying errno from a failed syscall, as a
// negative i64 (Linux's int convention; e.g. -2 = ENOENT). The
// `!`-flagged alias makes ?-propagation pick this variant as the
// error half of any (T | oserror) shape. Hare's analogue is
// errors::errno carried inside io::error.
export type oserror = !i64;
// filesize — byte length of an open fd via lseek-to-end-and-back.
export fn filesize(fd: i32) (i64 | oserror) = {
let end: i64 = lseek(fd, 0i64, whence.END);
if (end < 0) { return end: oserror; };
let r: i64 = lseek(fd, 0i64, whence.SET);
if (r < 0) { return r: oserror; };
return end;
};
// readall — keep reading until `n` bytes have arrived or the fd
// closes early. Hare name (io::readall); the buffer is caller-
// supplied, matching the Plan 9 subset convention.
export fn readall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let got: u64 = 0u64;
for (got < n) {
let r: i64 = read(fd, buf + got, n - got);
if (r < 0) { return r: oserror; };
if (r == 0) { return got: i64; }; // short read: caller decides
got += r: u64;
};
return got: i64;
};
// writeall — keep writing until `n` bytes have been accepted or the
// fd refuses progress. Hare name (io::writeall).
export fn writeall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let sent: u64 = 0u64;
for (sent < n) {
let r: i64 = write(fd, buf + sent, n - sent);
if (r < 0) { return r: oserror; };
if (r == 0) { return sent: i64; };
sent += r: u64;
};
return sent: i64;
};
// ---- process and filesystem helpers used by the `ww` driver ----------
// access(2): returns 0 if the file is reachable, negative errno
// otherwise. mode is the bitset described in <unistd.h> (F_OK=0).
export fn access(path: *u8, mode: i32) i32 = {
return syscall2(nr.ACCESS, path: i64, mode: i64): i32;
};
// remove — unlink(2). Hare name; the underlying syscall is unlink(2).
export fn remove(path: *u8) i32 = {
return syscall1(nr.UNLINK, path: i64): i32;
};
// mkdir — mkdir(2). Path must be NUL-terminated. Mode is the unix
// permission bitset (e.g. 0o700). Returns 0 on success, negative
// errno otherwise. Hare name (os::mkdir).
export fn mkdir(path: *u8, mode: i32) i32 = {
return syscall2(nr.MKDIR, path: i64, mode: i64): i32;
};
// rmdir — rmdir(2). Path must be NUL-terminated. Returns 0 on
// success, negative errno otherwise. Hare name (os::rmdir).
export fn rmdir(path: *u8) i32 = {
return syscall1(nr.RMDIR, path: i64): i32;
};
// mkdirs — recursive mkdir. Creates `path` and any non-existent
// parent directories with the given mode. EEXIST is silently
// accepted (matches Hare's `errors::exists` skip in os::mkdirs);
// any other syscall failure surfaces as `oserror`.
//
// `path` must be NUL-terminated AND its bytes must be writable —
// mkdirs temporarily replaces '/' separators with NUL while
// invoking [[mkdir]] on each prefix, then restores them. Pointing
// `path` at a string literal will segfault. Callers hold the bytes
// in a writable buffer (rt_alloc'd, a static `[N]u8`, etc.) — same
// precedent as [[temp.named]]'s pathbuf.
//
// Mirrors Hare's os::mkdirs (recursive variant of os::mkdir).
export fn mkdirs(path: *u8, mode: i32) (void | oserror) = {
// Find the path length (excluding trailing NUL).
let n: i32 = 0;
for (path[n] != 0u8) { n += 1; };
if (n == 0) { return; };
// Walk forward; at each '/' boundary, NUL-terminate the prefix,
// mkdir it, restore the slash, continue. Skip index 0 so a
// leading '/' on absolute paths doesn't trigger an empty mkdir.
let i: i32 = 1;
for (i < n) {
if (path[i] == 47u8) { // '/'
path[i] = 0u8;
let r: i32 = mkdir(path, mode);
path[i] = 47u8;
if (r < 0) {
if (r != -17) { return r: i64: oserror; };
};
};
i += 1;
};
// mkdir the full path.
let r: i32 = mkdir(path, mode);
if (r < 0) {
if (r != -17) { return r: i64: oserror; };
};
return;
};
// getpid(2). Used by the driver to mint unique scratch paths.
export fn getpid() i32 = {
return syscall0(nr.GETPID): i32;
};
// fork(2): 0 in the child, child pid in the parent, negative errno
// on failure.
export fn fork() i32 = {
return syscall0(nr.FORK): i32;
};
// execve(2): on success, does not return.
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
return syscall3(nr.EXECVE, path: i64, argv: i64, envp: i64): i32;
};
// wait4(2): wait for `pid` (or any child if -1), store status in
// `*status`, return the pid that ended (or negative errno).
export fn wait4(pid: i32, status: *i32, options: i32, rusage: *void) i32 = {
return syscall4(nr.WAIT4, pid: i64, status: i64,
options: i64, rusage: i64): i32;
};
// getcwd(2) — Linux flavour. Writes the NUL-terminated cwd into `buf`
// and returns the number of bytes written (including the NUL), or a
// negative errno. The driver uses it to expand `.` to the cwd's
// basename for `ww build` / `ww test`.
export fn getcwd(buf: *u8, n: u64) i64 = {
return syscall2(nr.GETCWD, buf: i64, n: i64);
};
// getdents64(2) — Linux directory enumeration. The fd must be opened
// with O_RDONLY on a directory. `buf` receives a packed sequence of
// linux_dirent64 records:
//
// struct linux_dirent64 {
// u64 d_ino; // 0..7
// i64 d_off; // 8..15
// u16 d_reclen; // 16..17 — total bytes for this record
// u8 d_type; // 18 — DT_REG/DT_DIR/...
// u8 d_name[]; // 19.. — NUL-terminated name + padding
// };
//
// Returns bytes written into `buf` (advance by d_reclen to walk),
// 0 at end-of-directory, or a negative errno.
export fn getdents64(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.GETDENTS64, fd: i64, buf: i64, n: i64);
};
// ---- environment ------------------------------------------------------
// rt_envp — runtime-side getter. rt/start.s captures envp into a DATAW
// slot before calling main; this binding lifts the captured pointer
// into ww. Same FFI shape as rt_syscall / rt_alloc / rt_abort: a TEXT
// symbol the linker resolves. The returned `**u8` is a NUL-terminated
// table of `*u8` entries, each pointing at a NUL-terminated
// "NAME=VALUE" byte sequence.
//
// We don't expose `rtenvp` directly; [[getenv]] is the only consumer.
@symbol("rt_envp") fn rtenvp() **u8;
// getenv — POSIX getenv. Returns a borrowed `str` view over the value
// bytes of the named environment variable, or void if the name is not
// present. The view is valid for the process lifetime — the bytes
// live in the kernel-supplied envp table at process entry. A future
// `setenv` (separate task) that grows the table behind the scenes
// would invalidate prior views; v1 has no setenv, so callers can
// hold the view indefinitely.
//
// Mirrors Hare's os::tryenv shape (returns void rather than panicking
// on missing). Hare also ships os::getenv (`(str | void)`) and
// os::mustenv (panic-on-missing); ww collapses to the single
// `(str | void)` form for now — consumers wanting "must" semantics
// abort at the call site.
//
// Algorithm: walk the NUL-pointer-terminated `environ` table doing a
// "name=" prefix match against each entry, byte-wise. NUL inside
// `name` would never match a real env var (env var names cannot
// contain '\0'), so we don't filter — POSIX puts that responsibility
// on the caller.
export fn getenv(name: str) (str | void) = {
let envp: **u8 = rtenvp();
let i: i32 = 0;
for (true) {
let entry: *u8 = envp[i];
if (entry == nil: *u8) { return; };
let j: i32 = 0;
let matched: bool = true;
for (j < name.len) {
if (entry[j] == 0u8) { matched = false; break; };
if (entry[j] != name[j]) { matched = false; break; };
j += 1;
};
if (matched) {
if (entry[name.len] == 61u8) { // '='
let val: *u8 = entry + ((name.len + 1): u64);
let n: i32 = 0;
for (val[n] != 0u8) { n += 1; };
let r: str;
r.ptr = val;
r.len = n;
return r;
};
};
i += 1;
};
return;
};