Hardware and FFI

What unsafe means

Safe Rasmalai covers applications, servers, simulations, and tooling. The remainder, raw pointers, hardware registers, and C libraries, is spelled unsafe and native. unsafe does not suspend checking; it assigns responsibility through containment: every foreign call and every raw-memory operation must sit inside an unsafe block (or an unsafe fn), and the compiler verifies the whole call graph to a fixpoint. A function that reaches foreign code only through a justified block stays safe itself, so wrappers contain rather than spread unsafe. Bounds, types, and ownership keep working inside unsafe exactly as outside it.

.rnx
unsafe fn Raw(x: Int): Int { return x * 2 }

unsafe { println!(Raw(21)); }

Calling an unsafe fn or a foreign function outside an unsafe block is an E201 error; address-of or Pointer arithmetic outside one is E202. An unsafe block that reaches no foreign or raw-memory authority at all is a W202 warning. As an expression, unsafe { ... } runs the block and yields null, so it slots into statement position without affecting surrounding code.

Deliberately excluded from unsafe: intentional reference cycles (they waste memory at worst; see Cycles and Handles) and data-race-free threading through @std/sync. unsafe is reserved for raw memory, C-ABI calls, and genuine data races.

Native declarations

Foreign functions declare inline with from native "lib": plain signatures using Int, Float, Byte, Bool, Pointer<T>, and : Ret. No headers, no build-script bindings. At rnx build time the linker appends -l<lib> automatically ("c" is already in the default set); at rnx run time the JIT resolves each symbol from the host loader. A missing library or symbol fails the build with the symbol name attached.

.rnx
import {
    fn compressBound(sourceLen: Int): Int
} from native "z"

// Re-export without wrappers: downstream users import straight from your package.
export {
    fn compress(
        dest: Pointer<Byte>,
        destLen: Pointer<Int>,
        src: Pointer<Byte>,
        srcLen: Int
    ): Int
} from native "z"

Only C-ABI types cross the boundary; managed values (String, Array, objects, closures) are rejected with E108 until converted to primitives or raw addresses explicitly.

Calling a foreign function requires containment: the call must sit in an unsafe block (or an unsafe fn), verified across the call graph. A direct call outside one is E201. The safe wrapper pattern keeps the perimeter small:

.rnx
import {
    fn compressBound(sourceLen: Int): Int as rawBound
} from native "z"

fn bound(n: Int): Int {
    let out = 0;
    unsafe {
        out = rawBound(n);
    }
    return out;
}

bound is safe to call anywhere; the single unsafe block justifies the foreign authority, and rnx check lists bound on the containment boundary for audit.

Generating bindings with rnx bindgen

rnx bindgen reads C headers and writes bindgen.rnx plus bindgen.oci.json (the registry annotation set: kind, role, target, generator, upstream digest, title). The header parser is built in, with no clang needed, with fixed per-target preprocessor defines, so the same inputs produce byte-identical output on any machine. Only value-shaped surface emits: scalars, fixed-size POD pointers, strings, and opaque handles as Pointer<Byte>; each emitted function becomes an unsafe fn wrapper over a private native import (unsafe-by-construction, so hand wrappers own containment). Callback, void*, and variadic surface warns instead of emitting.

The output is a build artifact. Keep it under .rnx-cache/ or a target/ directory and do not commit it. Non-source artifacts are OCI images, not repository files and not registry chunks (requirements/15_REGISTRY.md section 19), so publishing stages the generated tree as an image with run.rasmalai.kind=bindings. A wrapper that ships generated bindings declares its artifacts ref and the digest travels in the publish frame.

An opaque C handle must be written as typedef struct x_t* x;. A typedef void* is skipped by the parser, which is easy to miss because the generator warns per function rather than failing the run.

sh
rnx bindgen --header /usr/include/sqlite3.h --native-lib sqlite3 \
    --pkg-name sqlite3 --out ./gen --include /usr/include
rnx bindgen --header ./gen-check.h --native-lib sqlite3 \
    --pkg-name sqlite3 --out ./gen --check

--prefix keeps only matching symbols (empty means everything), --skip drops exact names, and --check fails when the checked-in output drifted from the generator.

--case camel (or pascal) converts the emitted wrapper and parameter names to that style; --rename old=new (repeatable) pins one symbol to an exact name. The default --case keep leaves every name verbatim. Renames never touch the link: the from native line keeps the C name in the left-hand position (fn sqlite3_open(...) as __ffi_sqlite3_open), and the wrapper calls through the __ffi_ alias, so the recorded foreign symbol is always the C name. #define constants still emit verbatim. When two C names map to one wrapper name, the later one (in C-name order) gains a digit suffix (fooBar, fooBar2), so output stays deterministic. The __ffi_ prefix is reserved for declared foreign aliases: like runtime __rnx_* internals, __ffi_* names get no scope auto-resolve, so an undeclared __ffi_* use is a scope error (E303). Undeclared __rnx_* uses are scope errors too; the only legal way to name a runtime internal is a declared import { fn name(params): Ret } from runtime "mod" inside registry-verified @std/*, and user code must call the owning @std/* wrapper instead.

Comments in the header travel with the declaration they precede: a // line or /* ... */ block directly above a function or #define becomes a /** ... */ doc comment on the emitted wrapper or constant, so the API reference shows the upstream prose. Banner stars are stripped, prose ends at the first */, and empty comments never emit. Trailing comments on the same line as code are left behind, and a blank line ends the attachment. The file opens with a //! line naming the generator, the source headers, and the upstream digest. Declared bindgen outputs count as package surface: rnx doc and the publish-time API snapshot include them even when no entry-reachable file imports them.

C documentation idioms convert to plain JSDoc-friendly prose on the way through, so the API page never shows raw header markup. The rule is structure, never truncate: the first line becomes the summary and the full body follows, with shared intros staying whole on their first symbol. CAPI3REF markers convert as follows: a leading CAPI3REF: (or CONSTRUCTOR: / DESTRUCTOR: / METHOD:) keyword becomes the summary title, bare taxonomy lines such as CONSTRUCTOR: sqlite3 drop out, ^ line prefixes and ^(...) span markers disappear, [link] and [display | target] brackets keep their display text, [[symbol]] section anchors route that section to the named function (so one comment block covering sqlite3_backup_init, sqlite3_backup_step, and sqlite3_backup_finish documents each of them instead of piling everything onto the first), <ul> / <ol> wrappers drop out, <li> items become - bullets, and every other tag keeps its inner text (`code` keeps backticks). Doxygen @param / @return / @brief (and \param, \return, \brief, \c word) map to @param / @returns / summary text, and KernelDoc - @name: dash lists become @param entries. Anything unrecognized degrades to plain text, and an inner */ still sanitizes to * / so the emitted block always parses.

sh
rnx bindgen --header /usr/include/sqlite3.h --native-lib sqlite3 \
    --pkg-name sqlite3 --out ./gen --case camel --rename sqlite3_open=openDb

Raw pointers

A Pointer<T> is a raw 64-bit address (Int/Float/Byte/Bool pointees; Byte accesses are exactly one byte wide). Mint one from real memory with Pointer.fromAddress<T>(addr), for example buf.address() on a ByteBuffer, which must outlive the pointer. Inside unsafe, ptr.read() loads T, ptr.write(v) stores it, readVolatile/writeVolatile mark the access volatile (LLVM honors it; Cranelift and the interpreter emit a plain access), and *ptr / *ptr = v sugar works the same. Pointer arithmetic is raw byte addition.

Taking &local yields an opaque token, not a readable address: dereferencing it fails cleanly at runtime, and native backends reject &local at compile time. For real memory, use fromAddress.

unsafe and pointer reference

OperationSpellingOutside unsafe
call an unsafe fnunsafe { Raw(21); }E201 error
take an address&xE202 error
pointer arithmeticptr + n (raw byte addition)E202 error
load / storeptr.read() / ptr.write(v)E202 error
volatile accessreadVolatile / writeVolatileE202 error; LLVM honors volatile, Cranelift and interpreter emit plain access
deref sugar*ptr / *ptr = vE202 error
mint from memoryPointer.fromAddress<T>(addr)E202 error

As an expression, unsafe { ... } runs the block and yields null, so it slots into statement position without affecting surrounding code. Keep unsafe blocks small: address-taking, pointer math, and foreign calls only.

.rnx
import { ByteBuffer } from "@std/bytes";

let buf = ByteBuffer.allocate(8);
buf.writeInt32BE(0, 42);
unsafe {
    let p = Pointer.fromAddress<Byte>(buf.address());
    println!(p.read());
}

buf must outlive the pointer: the address borrows the buffer's memory, and using it after the buffer drops reads freed memory.

Shipping C-compatible libraries

The reverse direction, calling Rasmalai from C, is rnx build --lib. It compiles the manifest's C surface to a static archive plus a <basename>.h header, instead of an executable. Normal builds never provide C symbols.

export means package visibility, not a C symbol. The C surface is exactly the export fn declarations written in the file named by entries.cabi. A package whose public API is classes and structs points cabi at a small wrapper file and exports only C-safe functions there:

.rnx
// Project.config
export default {
    project: { name: "com.example.grid", version: "0.3.0" },
    entries: {
        main: "src/main.rnx",
        cabi: "src/cabi.rnx",
    },
}

rnx check parses that file as a second root even when nothing imports it, so a broken surface fails before a C artifact is built. A declared surface with a non-representable signature fails with E108 naming the function and the type. export struct, export class, and export enum in the cabi file are package API; they never become symbols. Imports are not the surface: a helper declared in another file is not exported, even when it carries export.

Each export fn in the surface must be C-representable: no async, no throws, no unannotated or Void parameters, and nothing outside Int/Float/Byte/Bool/String/Pointer<Byte> (params) and Int/Float/Byte/Bool/Void (returns). Each Pointer<Byte> parameter needs a sibling <name>_len: Int length. Duplicate short names and reserved names fail with E108 before codegen. (pub/public still parse as deprecated aliases with W204.)

Without entries.cabi, rnx build --lib falls back to entries.lib, then to entries.main or the path passed on the command line, and validates every export fn reachable from that entry. The graph-wide rule is unchanged for projects that never declare a surface. Declaring a cabi file is the fail-fast path: it scopes the check to one reviewable file instead of the whole import graph.

Each export becomes a C wrapper with a true C signature (Int to int64_t, Float to double, Bool to bool, Void to void, String params to const char* copied in for the call, Pointer<Byte> to const uint8_t* borrowed for the call only). The header carries RNX_<PACKAGE>_H guards, RNX_ABI_VERSION, rnx_init/rnx_last_error declarations, and any /** */ doc comments from the exports. --lib-prefix <p> renames every export to p_<name>; bare names stay the default.

Ownership: the host owns every buffer it passes in. Borrowed pointers are valid for the call only, so copy what you keep. Nothing heap-owned crosses back: String and Pointer returns are rejected, and throwing exports are rejected at compile time.

Embedding: rnx_init(argc, argv) is available for argv control, but a host that never calls it still works. The first wrapper call runs a thread-safe once-guard that installs guard pages and readies the runtime. Wrappers never unwind or abort into the host: a panic or uncaught throw inside an export returns the sentinel for its type (INT64_MIN, false, quiet NaN, nothing for Void) and stores the message for rnx_last_error(), which is per-thread, cleared on entry, and carries only the message. Check it after any sentinel return.

Auditing the surface

unsafe surface is counted: rnx audit reports unsafe {} sites, raw Pointer/Address uses, and from native imports per package for CI gating. Manifests carry the badge (has_hazard: bool), surfaced by rnx doc and rnx audit alike. rnx audit --licenses reports the license graph instead: per-package SPDX, effective linkage, obligation class, and conflict notes, with --deny-license failing the audit on denied ids.

Files

Filesystem work lives in @std/fs: import fs, { File, Path } from "@std/fs";. File.open(path, mode) returns a buffered OS handle; mode is OpenMode.Read, Write, Append, or ReadWrite. A refused open gives isOpen == false instead of throwing, and every other fallible handle operation answers Result. File.create(path, mode) opens for writing with WriteMode.CreateNew, Create, Overwrite, or Append. Opened files require close(). The text path (readText/writeText) and the binary path (readBytes/writeBytes) share the handle cursor; seek/tell move and read it, len measures the file, flush pushes to the OS while sync forces durable storage, and lockSync/tryLockSync/unlockSync take an advisory lock shared by every handle on the same path. The binary path moves bytes directly between the OS handle and a ByteBuffer with no intermediate copy.

.rnx
import { File, OpenMode } from "@std/fs";
import { ByteBuffer } from "@std/bytes";

let f = File.open("/tmp/rnx-notes.txt", OpenMode.Write);
f.writeText("hello bytes");
f.close();
let g = File.open("/tmp/rnx-notes.txt", OpenMode.Read);
let buf = ByteBuffer.allocate(32);
let n = g.readBytes(buf, 0, 11).unwrapOr(-1);
g.close();
println!(n, buf.readString(0, n));

Reads on a closed handle answer Err, and a refused open reads as isOpen == false. One-shot work lives on the fs namespace, and every fallible call answers Result. Only File.open/File.create keep the isOpen sentinel for a refused open:

CallPurpose
fs.readText / fs.writeTextwhole-file text I/O (WriteMode picks create, overwrite, or append)
fs.readBytes / fs.writeByteswhole-file binary I/O through ByteBuffer
fs.statmetadata snapshot (FileStat: size, kind flags, modified time, mode bits)
fs.exists / fs.isFile / fs.isDirboolean probes that never fail
fs.readDir / fs.globdirectory names / pattern matches, both sorted for deterministic builds
fs.mkdir / fs.mkdirAllone level / recursive directory creation
fs.copy / fs.move / fs.renamecopy with CopyMode, cross-filesystem move, same-filesystem rename
fs.remove / fs.removeAllone file or empty directory / full tree
fs.symlink / fs.readLinkcreate / read symbolic links
fs.chmod / fs.truncate / fs.fsyncpermission bits / resize / flush to durable storage

Path.exists, Path.isFile, Path.isDir, Path.join, Path.dir, Path.base, Path.ext, and Path.isAbs cover path queries without opening handles.

The bare name is sync and blocks the caller; appending Async queues the same work on the process-wide fs pool and returns a Promise. Await it, writing out the Result type, since await erases to Any:

.rnx
import fs from "@std/fs";

fs.writeText("/tmp/rnx-hello.txt", "hello", .Overwrite);
let back: Result<String, String> = await fs.readTextAsync("/tmp/rnx-hello.txt");
println!(back.unwrapOr("missing"));

That prints hello. Every Async twin (readTextAsync, writeBytesAsync, statAsync, readDirAsync, globAsync, copyAsync, moveAsync, renameAsync) settles with the same Result its sync original returns.

fs.mmap(path, mode) maps a whole file into memory and fs.mmapAnon(len) maps zeroed pages; both build an Mmap whose raw start comes from address() for Pointer.fromAddress. Construction and address() both require unsafe, and writes through a .ReadWrite map reach the file after flush():

.rnx
import fs from "@std/fs";

fs.writeText("/tmp/rnx-map.bin", "xxxxxxxx", .Overwrite);
unsafe {
    let m = fs.mmap("/tmp/rnx-map.bin", .ReadWrite).unwrap();
    let p = Pointer.fromAddress<Byte>(m.address());
    p.write(72);
    m.flush();
    m.close();
}
println!(fs.readText("/tmp/rnx-map.bin").unwrapOr("?"));

That prints Hxxxxxxx. The lifetime rule is load-bearing: close() unmaps the region, so every address taken from it must be forgotten first. Using one afterwards reads freed memory. And when another process truncates the file below a mapped page, the next touch faults in a way nothing can catch: the OS delivers SIGBUS on POSIX (an access violation on Windows), which no Result and no catch can cover. Size the file before mapping it and never truncate a mapped file.

Terminal I/O

Terminal work lives in @std/io: import io, { ColorLevel } from "@std/io";. The default import binds the module namespace holding the free functions below; file I/O stays in @std/fs. Streams are stdin() / stdout() / stderr() calls returning File handles, each duplicating its descriptor, so closing the handle never closes descriptors 0, 1, or 2:

.rnx
import io from "@std/io";

let inn = io.stdin();
println!(inn.isOpen);
inn.close();

write prints one value with a trailing newline on stdout; writeError matches it on stderr so error text stays separate when either side is piped; writeRaw writes bytes as-is with no newline and no pretty-printing:

.rnx
import io from "@std/io";
import { ByteBuffer } from "@std/bytes";

io.write("hello");
io.write([1, 2, 3]);
io.writeRaw(ByteBuffer.fromString("AB"));
io.writeError("boom");

One shared renderer formats every value: arrays as [a, b], maps in insertion order as {k: v}, class instances in declaration order as Name{field: value}, results as Ok(v) and Err(e). Nesting deeper than 3 renders as ..., and a value that contains itself renders as <cycle>. Strings print as-is, never quoted and never re-escaped. Colors follow colorProfile() when stdout is a terminal and stay out otherwise. print forwards each of its arguments through this same renderer and joins them with spaces:

.rnx
import io from "@std/io";
import { Map } from "@std/collections";

let m = new Map<String, Int>();
m.set("ore", 7);
io.write(m);
io.write(Result.Ok<Int, String>(42));
io.write(Result.Err<Int, String>("boom"));
println!([1, 2], "x");

That prints {ore: 7}, Ok(42), Err(boom), and [1, 2] x. A Point(1, 2) struct would render as Point{x: 1, y: 2}.

Input answers Result: read reads stdin to EOF, while readLine writes its prompt with no newline first, reads one line, and strips the trailing newline. Pipe input or type a line when running these; readLine reports Err on EOF with no bytes read:

.rnx
import io from "@std/io";

let r = io.read();
println!(r.isOk());
.rnx
import io from "@std/io";

let line = io.readLine("> ");
println!(line.isOk());

Size and color queries adapt to the terminal: isTTY reports whether stdin is a terminal, width and height fall back to 80 by 24 when the size cannot be read, and colorProfile derives the ColorLevel tier from NO_COLOR, COLORTERM, TERM, and the TTY state:

.rnx
import io, { ColorLevel } from "@std/io";

println!(io.isTTY() == true || io.isTTY() == false);
println!(io.width() > 0);
println!(io.height() > 0);
println!(io.colorProfile() == ColorLevel.Ascii || true);

setRawMode toggles character-at-a-time, no-echo input and answers Result rather than throwing. Ok(true) reports success and Err(message) reports stdin that is not a TTY. Callers restore with setRawMode(false); the runtime also restores the saved mode automatically at process exit. clear homes the cursor with TTY-guarding: a no-op returning normally when stdout is not a TTY, never an error:

.rnx
import io from "@std/io";

let r = io.setRawMode(false);
println!(r.isOk() || r.isErr());
io.clear();

print stays in the prelude as a shim over io.write, so existing programs keep working with no import. Color, newline, and pretty-printing decisions belong to @std/io.

Process control

Child-process I/O uses ByteBuffer on both ends. Process.spawn returns a ChildProcess with piped stdin/stdout/stderr; Process.run captures a command to completion into ProcessOutput with exitCode, stdoutText(), and stderrText().

.rnx
import { Process } from "@std/process";

let out = Process.run("echo", ["hello"]);
println!(out.exitCode);
println!(out.stdoutText().contains("hello"));

For interactive children, writeStdin/readStdout move ByteBuffer contents, tryWait polls (null while running, the code after exit), wait reaps and returns the exit code, and kill(signal) defaults to 15 (SIGTERM). Dropping a child detaches it; spawned children require wait().

Handle, path, and process reference

Fallible handle operations answer Result; only File.open/File.create keep the isOpen sentinel for a refused open, and reads on a closed handle answer Err.

CallAnswersNotes
File.open(path, OpenMode.Read/Write/Append/ReadWrite)handle; isOpen == false when refusedbuffered OS handle; opened files require close()
File.create(path, WriteMode.CreateNew/Create/Overwrite/Append)handle; isOpen == false when refusedopens for writing
readText / writeTextResulttext path; shares the handle cursor
readBytes(buf, off, n) / writeBytesResultbinary path; zero-copy between OS handle and ByteBuffer
seek / tell / lenResultmove, read, and measure the cursor
flush / syncResultpush to OS / force durable storage
lockSync / tryLockSync / unlockSyncResultadvisory lock shared by every handle on the path
close()—required; mmap close() unmaps the region
Path queryReturns
Path.exists(p) / Path.isFile(p) / Path.isDir(p)Bool, never fails
Path.join(a, b) / Path.dir(p) / Path.base(p)String
Path.ext(p) / Path.isAbs(p)String / Bool

The bare name is sync and blocks the caller; appending Async queues the same work on the process-wide fs pool and returns a Promise. Await it, writing out the Result type, since await erases to Any. Every Async twin settles with the same Result its sync original returns.

Child callReturns
Process.spawn(cmd, args)ChildProcess with piped stdin/stdout/stderr
Process.run(cmd, args)ProcessOutput: exitCode, stdoutText(), stderrText()
tryWait()null while running, the code after exit
wait()exit code; reaps the child (required)
kill(signal = 15)signals; default is SIGTERM
.rnx
import { Process } from "@std/process";

let out = Process.run("echo", ["hello"]);
assert(out.exitCode == 0, "exit code");
assert(out.stdoutText().contains("hello"), "captured");

Summary

  • unsafe scopes three operations (E201/E202 enforce the boundary); from native "lib" declares foreign functions.
  • rnx build --lib exports C-ABI wrappers plus headers; rnx audit counts the surface.
  • File.open/create with text and zero-copy binary paths plus close; Path for queries; fs one-shots with *Async pool twins; mmap under unsafe with OS-level fault rules.
  • io.write/writeError with pretty-printing plus writeRaw for exact bytes; read/readLine answering Result; isTTY/width/height/colorProfile queries; setRawMode with Result and TTY-guarded clear; print as a prelude shim over io.write.
  • Process.spawn/run with ByteBuffer pipes; wait reaps, kill signals, tryWait polls.