//! Whole-file operations for `std/file.fs` (ADR 0084). //! //! The public effect reaches the immortal root capability below. Its owned //! and borrowed clause entries adapt to the retained `tl_file_*` C ABI: //! those kernels still borrow exactly their original arguments. Every call //! goes through the I/O blocking pool while its actor is parked; a kill is //! deferred until the borrowed arguments' blocking call has returned (see //! `blocking.rs`). Results are allocated by the cross-thread-safe value //! builders, and every OS failure is an `Error`, not a panic. use std::sync::OnceLock; use crate::abi::{Ctx, UNIT, Value, int}; use crate::blocking::{IO, Thunk, tl_call_blocking}; use crate::heap::drop_value; use crate::prims::boolean; use crate::process::Code; use crate::values::{ bytes_from, bytes_of, error, list, ok, string, text, tl_borrowed1, tl_borrowed2, }; /// The clauses of `std/file.fs`, in `louise_rt_prims::FS_OPS` order. const FS_CLAUSES: [(Code, Code); louise_rt_prims::FS_OPS.len()] = [ (op_read_bytes, tl_borrowed1), (op_write_bytes, tl_borrowed2), (op_exists, tl_borrowed1), (op_size, tl_borrowed1), (op_list_dir, tl_borrowed1), ]; /// The immortal root capability for `fs`: five stateless clauses, shared by /// every actor, outside the counted heap (ADR 0084). pub(crate) fn fs_cap() -> Value { static CAP: OnceLock = OnceLock::new(); *CAP.get_or_init(|| crate::clock::immortal_cap(&FS_CLAUSES)) } /// `read_bytes(path)`: the file's contents, or `Error` with the OS's /// message. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. The /// result is built with the allocation functions of `louise_rt.h`, which /// work on any thread, as a blocking extern requires. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_read(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. match std::fs::read(unsafe { text(path) }) { Ok(bytes) => { let b = bytes_from(ctx, &bytes); ok(ctx, b) } Err(e) => error(ctx, &e.to_string()), } } /// `write(path, content)`: the file created or truncated, or `Error` with /// the OS's message. /// /// # Safety /// `path` must be a live string and `content` live `Bytes`; `ctx` the /// calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_write(ctx: *mut Ctx, path: Value, content: Value) -> Value { // SAFETY: caller guarantees a live string and live Bytes. let (path, content) = unsafe { (text(path), bytes_of(content)) }; match std::fs::write(path, content) { Ok(()) => ok(ctx, UNIT), Err(e) => error(ctx, &e.to_string()), } } /// Whether a file (not a directory) exists at `path`. /// /// # Safety /// `path` must be a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_exists(_ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. boolean(std::path::Path::is_file(std::path::Path::new(unsafe { text(path) }))) } /// The file's size in bytes, or `Error` with the OS's message. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_size(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. match std::fs::metadata(unsafe { text(path) }) { Ok(meta) => ok(ctx, int(i64::try_from(meta.len()).unwrap_or(i64::MAX))), Err(e) => error(ctx, &e.to_string()), } } /// The names of the directory's entries (not full paths, never `.` or /// `..`, in the OS's order), or `Error` with the OS's message. A name /// that is not valid UTF-8 is lossy-decoded. /// /// # Safety /// `path` must be a live string; `ctx` the calling actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_file_list_dir(ctx: *mut Ctx, path: Value) -> Value { // SAFETY: caller guarantees a live string. let entries = match std::fs::read_dir(unsafe { text(path) }) { Ok(entries) => entries, Err(e) => return error(ctx, &e.to_string()), }; let mut names = Vec::new(); for entry in entries { match entry { Ok(e) => names.push(string(ctx, &e.file_name().to_string_lossy())), Err(e) => return error(ctx, &e.to_string()), } } ok(ctx, list(ctx, names.into_iter())) } // The fixed-arity thunks below are the only bridge to the borrowed C // kernels. In particular, no capability argument is prepended to a // `tl_file_*` call: the capability is the handler block, not an operation // parameter (ADR 0084). #[cfg(test)] fn note_io_thread() { note_io_threads().lock().expect("fs test threads").push( std::thread::current() .name() .unwrap_or("unnamed") .to_owned(), ); } #[cfg(test)] fn io_threads() -> Vec { let mut threads = Vec::new(); // The two fixed test programs drain this after eight and two calls; // the vector never holds a user-controlled or unbounded capture. std::mem::swap( &mut threads, &mut *note_io_threads().lock().expect("fs test threads"), ); threads } #[cfg(test)] fn note_io_threads() -> &'static std::sync::Mutex> { use std::sync::Mutex; static THREADS: Mutex> = Mutex::new(Vec::new()); &THREADS } unsafe extern "C" fn read_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes one live, borrowed path. unsafe { tl_file_read(ctx, args.read()) } } unsafe extern "C" fn write_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes a live, borrowed path and Bytes value. unsafe { tl_file_write(ctx, args.read(), args.add(1).read()) } } unsafe extern "C" fn exists_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes one live, borrowed path. unsafe { tl_file_exists(ctx, args.read()) } } unsafe extern "C" fn size_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes one live, borrowed path. unsafe { tl_file_size(ctx, args.read()) } } unsafe extern "C" fn list_dir_thunk(ctx: *mut Ctx, args: *const Value) -> Value { #[cfg(test)] note_io_thread(); // SAFETY: the I/O pool passes one live, borrowed path. unsafe { tl_file_list_dir(ctx, args.read()) } } /// Run a one-argument root clause. The owned entry holds `this_` and `arg`; /// the pool's kernel only borrows `arg`, so the adapter drops it exactly once /// after every normal, error or actor-kill return from `tl_call_blocking`. unsafe fn blocking1(ctx: *mut Ctx, this_: Value, arg: Value, thunk: Thunk) -> Value { // SAFETY: the caller is the running actor and owns both values. unsafe { drop_value(ctx, this_); let out = tl_call_blocking(ctx, IO, thunk, 1, &arg); drop_value(ctx, arg); out } } /// The two-argument counterpart of [`blocking1`]. unsafe fn blocking2( ctx: *mut Ctx, this_: Value, first: Value, second: Value, thunk: Thunk, ) -> Value { // SAFETY: as `blocking1`; the array outlives argument borrowing by the // pool because this actor remains parked until the kernel returns. unsafe { drop_value(ctx, this_); let args = [first, second]; let out = tl_call_blocking(ctx, IO, thunk, args.len(), args.as_ptr()); drop_value(ctx, first); drop_value(ctx, second); out } } /// Test-only entry into the exact owned adapters above, with unit standing /// in for the immortal clause. The scheduler tests supply a bounded thunk; /// these symbols are absent from production and add no native capability. #[cfg(test)] pub(crate) unsafe fn test_blocking1(ctx: *mut Ctx, arg: Value, thunk: Thunk) -> Value { // SAFETY: the test follows the running-actor/owned-value contract. unsafe { blocking1(ctx, UNIT, arg, thunk) } } #[cfg(test)] pub(crate) unsafe fn test_blocking2( ctx: *mut Ctx, first: Value, second: Value, thunk: Thunk, ) -> Value { // SAFETY: as `test_blocking1`. unsafe { blocking2(ctx, UNIT, first, second, thunk) } } /// Consume the owned arguments of a denied fs op without inspecting its path. unsafe fn deny_result(ctx: *mut Ctx, this_: Value, args: &[Value]) -> Value { // SAFETY: the root invocation owns `this_` and `args`. unsafe { drop_value(ctx, this_); for &arg in args { drop_value(ctx, arg); } } error(ctx, louise_rt_prims::FS_REMOTE_DENIED) } unsafe extern "C" fn op_read_bytes( ctx: *mut Ctx, this_: Value, path: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_fs_denied(ctx) { return deny_result(ctx, this_, &[path]); } blocking1(ctx, this_, path, read_thunk) } } unsafe extern "C" fn op_write_bytes( ctx: *mut Ctx, this_: Value, path: Value, content: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_fs_denied(ctx) { return deny_result(ctx, this_, &[path, content]); } blocking2(ctx, this_, path, content, write_thunk) } } unsafe extern "C" fn op_exists( ctx: *mut Ctx, this_: Value, path: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_fs_denied(ctx) { drop_value(ctx, this_); drop_value(ctx, path); return boolean(false); } blocking1(ctx, this_, path, exists_thunk) } } unsafe extern "C" fn op_size( ctx: *mut Ctx, this_: Value, path: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_fs_denied(ctx) { return deny_result(ctx, this_, &[path]); } blocking1(ctx, this_, path, size_thunk) } } unsafe extern "C" fn op_list_dir( ctx: *mut Ctx, this_: Value, path: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: an owned root-clause invocation on the running actor. unsafe { if crate::sched::remote_fs_denied(ctx) { return deny_result(ctx, this_, &[path]); } blocking1(ctx, this_, path, list_dir_thunk) } } #[cfg(test)] mod tests { use super::*; use crate::abi::{Block, int_get}; use crate::heap::{drop_value, dup_value}; use crate::values::{closure_code_borrowed, list_items, string, string_bytes, text}; #[test] fn the_fs_capability_is_immortal_and_built_once() { let cap = fs_cap(); assert_eq!(cap, fs_cap()); // SAFETY: the capability and its clauses are never freed. unsafe { let b = cap as *mut Block; assert_eq!((*b).header.rc, 0); let n = (*b).header.scan_fsize as usize; assert_eq!(n, louise_rt_prims::FS_OPS.len() + 1); let fields = Block::fields_ptr(b); assert_eq!(fields.add(n - 1).read(), int(0), "the marker"); for i in 0..n - 1 { let clause = fields.add(i).read() as *mut Block; assert_eq!((*clause).header.rc, 0); } } } /// Perform an `fs` operation through its root clause, with either the /// owned entry or the borrowed adapter generated closures also use. /// At most two arguments: no register/xargs reinterpretation is hidden. unsafe fn perform(ctx: *mut Ctx, op: &str, args: &[Value], owned: bool) -> Value { // SAFETY: the caller runs on an actor and supplies live values. unsafe { assert!(args.len() <= 2); let i = louise_rt_prims::FS_OPS .iter() .position(|name| *name == op) .expect("an fs operation"); let cap = crate::process::root_cap(crate::process::RootCap::Fs); let clause = Block::fields_ptr(cap as *mut Block).add(i).read(); if owned { let clause = dup_value(clause); drop_value(ctx, cap); return crate::prims::call_closure(ctx, clause, args); } let mut regs = [UNIT; 5]; regs[..args.len()].copy_from_slice(args); let code: Code = std::mem::transmute(closure_code_borrowed(clause)); let out = code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4]); drop_value(ctx, cap); out } } fn assert_used_io_pool(n: usize) { let threads = io_threads(); assert_eq!(threads.len(), n, "one record per operation: {threads:?}"); assert!( threads .iter() .all(|name| name.starts_with("louise-blocking-io-")), "filesystem roots must not run on a scheduler: {threads:?}" ); } /// (tag, first field) of a constructor value (`Ok` is tag 0). unsafe fn ctor(v: Value) -> (u16, Value) { // SAFETY: a live constructor cell. unsafe { let b = v as *mut Block; ((*b).header.tag, Block::fields_ptr(b).read()) } } extern "C" fn roundtrip(ctx: *mut Ctx) -> Value { // SAFETY: the test follows generated code's owned and borrowed // clause conventions. Paths and payloads are smaller than 128 bytes. unsafe { let path = std::env::temp_dir().join("louise_rt_fs_test.bin"); let path = path.to_str().unwrap(); let p = string(ctx, path); std::fs::remove_file(path).ok(); let before_exists = perform(ctx, "exists", &[dup_value(p)], true); assert_eq!(before_exists, int(0)); drop_value(ctx, before_exists); let content = bytes_from(ctx, b"hello"); let wrote = perform( ctx, "write_bytes", &[dup_value(p), dup_value(content)], true, ); assert_eq!(ctor(wrote).0, 0, "Ok expected"); // The borrowed two-argument adapter leaves both inputs alone. let wrote_borrowed = perform(ctx, "write_bytes", &[p, content], false); assert_eq!(ctor(wrote_borrowed).0, 0, "Ok expected"); let exists = perform(ctx, "exists", &[p], false); assert_eq!(exists, int(1)); drop_value(ctx, exists); let size = perform(ctx, "size", &[p], false); let (tag, n) = ctor(size); assert_eq!(tag, 0, "Ok expected"); assert_eq!(int_get(n), 5); let read = perform(ctx, "read_bytes", &[dup_value(p)], true); let (tag, bytes) = ctor(read); assert_eq!(tag, 0, "Ok expected"); assert_eq!(string_bytes(bytes), b"hello"); // A missing file is an `Error`, not a panic. The borrowed // one-argument adapter still leaves `p` alive. std::fs::remove_file(path).unwrap(); let missing = perform(ctx, "read_bytes", &[p], false); assert_eq!(ctor(missing).0, 1, "Error expected"); // The two-argument adapter releases its duplicates on Error too. let no_dir = string(ctx, &format!("{path}/child")); let write_error = perform( ctx, "write_bytes", &[dup_value(no_dir), dup_value(content)], true, ); assert_eq!(ctor(write_error).0, 1, "Error expected"); for v in [ wrote, wrote_borrowed, size, read, missing, write_error, content, p, no_dir, ] { drop_value(ctx, v); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); assert_used_io_pool(8); UNIT } } #[test] fn write_read_exists_size_and_errors() { // SAFETY: the test actor follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(roundtrip) }, 0); } extern "C" fn lists_dir(ctx: *mut Ctx) -> Value { // SAFETY: the test follows the generated-code clause conventions. unsafe { let p = string(ctx, "."); let listed = perform(ctx, "list_dir", &[p], false); let (tag, entries) = ctor(listed); assert_eq!(tag, 0, "Ok expected"); let names: Vec<&str> = list_items(entries).map(|e| text(e)).collect(); assert!(names.contains(&"Cargo.toml"), "{names:?}"); assert!(!names.contains(&"."), "{names:?}"); // A missing directory is an `Error`, not a panic. let np = string(ctx, "/definitely/not/here"); let missing = perform(ctx, "list_dir", &[dup_value(np)], true); assert_eq!(ctor(missing).0, 1, "Error expected"); for v in [listed, missing, p, np] { drop_value(ctx, v); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); assert_used_io_pool(2); UNIT } } #[test] fn list_dir_lists_and_errors() { // SAFETY: the test actor follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(lists_dir) }, 0); } }