On this page

Foreign function interface

FFI is a trusted-tier boundary for calling C libraries. Keep unsafe details in small native shims and expose safe Tenon wrappers to ordinary packages.

Declarations and package manifest

An FFI package declares private, top-level extern functions without bodies:

extern "tz_crc32" fn crc32(seed: u64, data: bytes) -> u64

The string is the C symbol and must be an ASCII C identifier. extern is not public: expose a safe Tenon wrapper instead. An extern is only permitted in a package with an [ffi] table and ffi in its capability ceiling. The root capability ceiling must also admit ffi when it depends on an FFI package.

The optional manifest table accepts these keys for system libraries:

[ffi]
headers = ["native/tz_zlib.h"] # package-relative shim headers, included in order
system_headers = ["zlib.h"]   # system headers checked by a compiler probe
libs = ["z"]                  # library names, not compiler flags
pkg_config = "zlib"           # optional pkg-config package

Header paths must stay within the package; library names are restricted to [A-Za-z0-9_.+-]+. Free-form compiler flags are not accepted.

For the toolchain's SQLite, use vendored = ["sqlite"] instead of libs or pkg_config. Both native builds and the interpreter's FFI helper link a cached object built from the vendored amalgamation by default, with the matching sqlite3.h supplied by the toolchain. Set TENON_SQLITE=system to use the normal sqlite3 pkg-config and system library path instead.

Types and ownership

Fixed-width integer types map to their <stdint.h> equivalents, bool to bool, and a unit return to void. Records, vectors, results, closures, capabilities and pointers are not FFI-mappable. Shims can encode handles as integers and validate them in a shim-owned table.

str and bytes arguments are borrowed trt_str/trt_bytes pointer-and-length values, not NUL-terminated strings. C must not retain them beyond the call. String and byte returns use trt_ffi_buf {ptr, len} allocated by the shim with malloc; Tenon copies the contents into the caller's arena and frees the buffer. Returned strings must be valid UTF-8 or the call traps with ffi.

The compiler emits a function-pointer assignment against each declared C symbol. This checks the C prototype; a mismatch is reported as E0974, with the C compiler message, rather than as a generic compiler failure.

Finding C dependencies

Discovery uses TENON_FFI_PREFIX first (colon-separated prefixes, each contributing include and lib paths and an rpath), then pkg-config when configured and available, then system defaults. Only -I, -L and -l flags from pkg-config are retained. Within a package, a repeated flag, such as a library that pkg-config and libs both name, is passed once, at its first position; repeats across packages are kept. Each system header is checked with a cc -E probe. Missing headers or libraries produce E0978; its help points to TENON_FFI_PREFIX.

Interpreter and failures

tenon interp runs extern calls through a compiled C ffi-host helper built from the same shims and prototype checks as the C backend. It starts lazily on the first extern call, so programs using FFI need a C compiler even under interp; without one, or if the helper cannot be built, the compiler reports E0979. Helper failure at a call site traps as ffi (exit 101). A crash inside C in the normal C backend is a native process crash instead; this divergence is intentional, and crash cases are not differential tests.

Shims must not write to stdout under interp: it is the helper's frame channel; output corrupts framing and traps ffi. At interpreter teardown an idle FFI helper receives EOF and up to 100 ms to run normal exit cleanup before forced termination and reaping. Cleanup after a native crash, blocked shim or forced termination remains best effort (ADR-0224). The helper defines TRT_INTERP_FFI_HOST; trusted blocking shims may monitor request-pipe EOF for parent loss. SIGPIPE on replies becomes an ordinary write failure so exit cleanup runs. Shims that spawn children restore child SIGPIPE. The helper links the toolchain's vendored SQLite by default, like a native build; set TENON_SQLITE=system to use the system library instead. Native builds with FFI externs and the interpreter's FFI helper can reuse the FFI build cache (ffi-v1 on Linux with GCC and GNU bfd ld, and ffi-cache-macos-v2 on macOS). Entries hash current transitive compile/link inputs (including system headers, libraries and scripts), recheck include resolution with preprocessing, and guard library search directory listings. Compiler identity and ordered resolved flags participate in the key. Time macros, unsupported flags/toolchains/scripts, or incomplete dependency capture bypass caching; capture failures retry the original uncached command. Native builds with vendored SQLite reuse the object instead of the executable. Warnings replay once on hits; linker traces are private. TENON_NO_CACHE=1 disables reuse/publication. See ADR-0210.

The ffi capability and native boundary are trusted-tier features. Keep wrappers narrow, validate native results and handles, and do not expose raw C ownership or pointers to untrusted callers.

Example plugins

plugins/zlib exposes CRC32/Adler32 and bounded compression/decompression; plugins/sqlite exposes generation-checked database handles with bound TEXT parameters. Each DOCS.md covers limits, errors and dependency setup; their plugin-local goldens run identically through C and the interpreter helper.