tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

527 lignes · 18037 octetsBrut · Historique
1//! Whole-file operations for `std/file.fs` (ADR 0084).
2//!
3//! The public effect reaches the immortal root capability below. Its owned
4//! and borrowed clause entries adapt to the retained `tl_file_*` C ABI:
5//! those kernels still borrow exactly their original arguments. Every call
6//! goes through the I/O blocking pool while its actor is parked; a kill is
7//! deferred until the borrowed arguments' blocking call has returned (see
8//! `blocking.rs`). Results are allocated by the cross-thread-safe value
9//! builders, and every OS failure is an `Error`, not a panic.
10
11use std::sync::OnceLock;
12
13use crate::abi::{Ctx, UNIT, Value, int};
14use crate::blocking::{IO, Thunk, tl_call_blocking};
15use crate::heap::drop_value;
16use crate::prims::boolean;
17use crate::process::Code;
18use crate::values::{
19 bytes_from, bytes_of, error, list, ok, string, text, tl_borrowed1, tl_borrowed2,
20};
21
22/// The clauses of `std/file.fs`, in `louise_rt_prims::FS_OPS` order.
23const FS_CLAUSES: [(Code, Code); louise_rt_prims::FS_OPS.len()] = [
24 (op_read_bytes, tl_borrowed1),
25 (op_write_bytes, tl_borrowed2),
26 (op_exists, tl_borrowed1),
27 (op_size, tl_borrowed1),
28 (op_list_dir, tl_borrowed1),
29];
30
31/// The immortal root capability for `fs`: five stateless clauses, shared by
32/// every actor, outside the counted heap (ADR 0084).
33pub(crate) fn fs_cap() -> Value {
34 static CAP: OnceLock<Value> = OnceLock::new();
35 *CAP.get_or_init(|| crate::clock::immortal_cap(&FS_CLAUSES))
36}
37
38/// `read_bytes(path)`: the file's contents, or `Error` with the OS's
39/// message.
40///
41/// # Safety
42/// `path` must be a live string; `ctx` the calling actor's context. The
43/// result is built with the allocation functions of `louise_rt.h`, which
44/// work on any thread, as a blocking extern requires.
45#[unsafe(no_mangle)]
46pub unsafe extern "C" fn tl_file_read(ctx: *mut Ctx, path: Value) -> Value {
47 // SAFETY: caller guarantees a live string.
48 match std::fs::read(unsafe { text(path) }) {
49 Ok(bytes) => {
50 let b = bytes_from(ctx, &bytes);
51 ok(ctx, b)
52 }
53 Err(e) => error(ctx, &e.to_string()),
54 }
55}
56
57/// `write(path, content)`: the file created or truncated, or `Error` with
58/// the OS's message.
59///
60/// # Safety
61/// `path` must be a live string and `content` live `Bytes`; `ctx` the
62/// calling actor's context.
63#[unsafe(no_mangle)]
64pub unsafe extern "C" fn tl_file_write(ctx: *mut Ctx, path: Value, content: Value) -> Value {
65 // SAFETY: caller guarantees a live string and live Bytes.
66 let (path, content) = unsafe { (text(path), bytes_of(content)) };
67 match std::fs::write(path, content) {
68 Ok(()) => ok(ctx, UNIT),
69 Err(e) => error(ctx, &e.to_string()),
70 }
71}
72
73/// Whether a file (not a directory) exists at `path`.
74///
75/// # Safety
76/// `path` must be a live string.
77#[unsafe(no_mangle)]
78pub unsafe extern "C" fn tl_file_exists(_ctx: *mut Ctx, path: Value) -> Value {
79 // SAFETY: caller guarantees a live string.
80 boolean(std::path::Path::is_file(std::path::Path::new(unsafe {
81 text(path)
82 })))
83}
84
85/// The file's size in bytes, or `Error` with the OS's message.
86///
87/// # Safety
88/// `path` must be a live string; `ctx` the calling actor's context.
89#[unsafe(no_mangle)]
90pub unsafe extern "C" fn tl_file_size(ctx: *mut Ctx, path: Value) -> Value {
91 // SAFETY: caller guarantees a live string.
92 match std::fs::metadata(unsafe { text(path) }) {
93 Ok(meta) => ok(ctx, int(i64::try_from(meta.len()).unwrap_or(i64::MAX))),
94 Err(e) => error(ctx, &e.to_string()),
95 }
96}
97
98/// The names of the directory's entries (not full paths, never `.` or
99/// `..`, in the OS's order), or `Error` with the OS's message. A name
100/// that is not valid UTF-8 is lossy-decoded.
101///
102/// # Safety
103/// `path` must be a live string; `ctx` the calling actor's context.
104#[unsafe(no_mangle)]
105pub unsafe extern "C" fn tl_file_list_dir(ctx: *mut Ctx, path: Value) -> Value {
106 // SAFETY: caller guarantees a live string.
107 let entries = match std::fs::read_dir(unsafe { text(path) }) {
108 Ok(entries) => entries,
109 Err(e) => return error(ctx, &e.to_string()),
110 };
111 let mut names = Vec::new();
112 for entry in entries {
113 match entry {
114 Ok(e) => names.push(string(ctx, &e.file_name().to_string_lossy())),
115 Err(e) => return error(ctx, &e.to_string()),
116 }
117 }
118 ok(ctx, list(ctx, names.into_iter()))
119}
120
121// The fixed-arity thunks below are the only bridge to the borrowed C
122// kernels. In particular, no capability argument is prepended to a
123// `tl_file_*` call: the capability is the handler block, not an operation
124// parameter (ADR 0084).
125
126#[cfg(test)]
127fn note_io_thread() {
128 note_io_threads().lock().expect("fs test threads").push(
129 std::thread::current()
130 .name()
131 .unwrap_or("unnamed")
132 .to_owned(),
133 );
134}
135
136#[cfg(test)]
137fn io_threads() -> Vec<String> {
138 let mut threads = Vec::new();
139 // The two fixed test programs drain this after eight and two calls;
140 // the vector never holds a user-controlled or unbounded capture.
141 std::mem::swap(
142 &mut threads,
143 &mut *note_io_threads().lock().expect("fs test threads"),
144 );
145 threads
146}
147
148#[cfg(test)]
149fn note_io_threads() -> &'static std::sync::Mutex<Vec<String>> {
150 use std::sync::Mutex;
151 static THREADS: Mutex<Vec<String>> = Mutex::new(Vec::new());
152 &THREADS
153}
154
155unsafe extern "C" fn read_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
156 #[cfg(test)]
157 note_io_thread();
158 // SAFETY: the I/O pool passes one live, borrowed path.
159 unsafe { tl_file_read(ctx, args.read()) }
160}
161
162unsafe extern "C" fn write_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
163 #[cfg(test)]
164 note_io_thread();
165 // SAFETY: the I/O pool passes a live, borrowed path and Bytes value.
166 unsafe { tl_file_write(ctx, args.read(), args.add(1).read()) }
167}
168
169unsafe extern "C" fn exists_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
170 #[cfg(test)]
171 note_io_thread();
172 // SAFETY: the I/O pool passes one live, borrowed path.
173 unsafe { tl_file_exists(ctx, args.read()) }
174}
175
176unsafe extern "C" fn size_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
177 #[cfg(test)]
178 note_io_thread();
179 // SAFETY: the I/O pool passes one live, borrowed path.
180 unsafe { tl_file_size(ctx, args.read()) }
181}
182
183unsafe extern "C" fn list_dir_thunk(ctx: *mut Ctx, args: *const Value) -> Value {
184 #[cfg(test)]
185 note_io_thread();
186 // SAFETY: the I/O pool passes one live, borrowed path.
187 unsafe { tl_file_list_dir(ctx, args.read()) }
188}
189
190/// Run a one-argument root clause. The owned entry holds `this_` and `arg`;
191/// the pool's kernel only borrows `arg`, so the adapter drops it exactly once
192/// after every normal, error or actor-kill return from `tl_call_blocking`.
193unsafe fn blocking1(ctx: *mut Ctx, this_: Value, arg: Value, thunk: Thunk) -> Value {
194 // SAFETY: the caller is the running actor and owns both values.
195 unsafe {
196 drop_value(ctx, this_);
197 let out = tl_call_blocking(ctx, IO, thunk, 1, &arg);
198 drop_value(ctx, arg);
199 out
200 }
201}
202
203/// The two-argument counterpart of [`blocking1`].
204unsafe fn blocking2(
205 ctx: *mut Ctx,
206 this_: Value,
207 first: Value,
208 second: Value,
209 thunk: Thunk,
210) -> Value {
211 // SAFETY: as `blocking1`; the array outlives argument borrowing by the
212 // pool because this actor remains parked until the kernel returns.
213 unsafe {
214 drop_value(ctx, this_);
215 let args = [first, second];
216 let out = tl_call_blocking(ctx, IO, thunk, args.len(), args.as_ptr());
217 drop_value(ctx, first);
218 drop_value(ctx, second);
219 out
220 }
221}
222
223/// Test-only entry into the exact owned adapters above, with unit standing
224/// in for the immortal clause. The scheduler tests supply a bounded thunk;
225/// these symbols are absent from production and add no native capability.
226#[cfg(test)]
227pub(crate) unsafe fn test_blocking1(ctx: *mut Ctx, arg: Value, thunk: Thunk) -> Value {
228 // SAFETY: the test follows the running-actor/owned-value contract.
229 unsafe { blocking1(ctx, UNIT, arg, thunk) }
230}
231
232#[cfg(test)]
233pub(crate) unsafe fn test_blocking2(
234 ctx: *mut Ctx,
235 first: Value,
236 second: Value,
237 thunk: Thunk,
238) -> Value {
239 // SAFETY: as `test_blocking1`.
240 unsafe { blocking2(ctx, UNIT, first, second, thunk) }
241}
242
243/// Consume the owned arguments of a denied fs op without inspecting its path.
244unsafe fn deny_result(ctx: *mut Ctx, this_: Value, args: &[Value]) -> Value {
245 // SAFETY: the root invocation owns `this_` and `args`.
246 unsafe {
247 drop_value(ctx, this_);
248 for &arg in args {
249 drop_value(ctx, arg);
250 }
251 }
252 error(ctx, louise_rt_prims::FS_REMOTE_DENIED)
253}
254
255unsafe extern "C" fn op_read_bytes(
256 ctx: *mut Ctx,
257 this_: Value,
258 path: Value,
259 _: Value,
260 _: Value,
261 _: Value,
262 _: Value,
263) -> Value {
264 // SAFETY: an owned root-clause invocation on the running actor.
265 unsafe {
266 if crate::sched::remote_fs_denied(ctx) {
267 return deny_result(ctx, this_, &[path]);
268 }
269 blocking1(ctx, this_, path, read_thunk)
270 }
271}
272
273unsafe extern "C" fn op_write_bytes(
274 ctx: *mut Ctx,
275 this_: Value,
276 path: Value,
277 content: Value,
278 _: Value,
279 _: Value,
280 _: Value,
281) -> Value {
282 // SAFETY: an owned root-clause invocation on the running actor.
283 unsafe {
284 if crate::sched::remote_fs_denied(ctx) {
285 return deny_result(ctx, this_, &[path, content]);
286 }
287 blocking2(ctx, this_, path, content, write_thunk)
288 }
289}
290
291unsafe extern "C" fn op_exists(
292 ctx: *mut Ctx,
293 this_: Value,
294 path: Value,
295 _: Value,
296 _: Value,
297 _: Value,
298 _: Value,
299) -> Value {
300 // SAFETY: an owned root-clause invocation on the running actor.
301 unsafe {
302 if crate::sched::remote_fs_denied(ctx) {
303 drop_value(ctx, this_);
304 drop_value(ctx, path);
305 return boolean(false);
306 }
307 blocking1(ctx, this_, path, exists_thunk)
308 }
309}
310
311unsafe extern "C" fn op_size(
312 ctx: *mut Ctx,
313 this_: Value,
314 path: Value,
315 _: Value,
316 _: Value,
317 _: Value,
318 _: Value,
319) -> Value {
320 // SAFETY: an owned root-clause invocation on the running actor.
321 unsafe {
322 if crate::sched::remote_fs_denied(ctx) {
323 return deny_result(ctx, this_, &[path]);
324 }
325 blocking1(ctx, this_, path, size_thunk)
326 }
327}
328
329unsafe extern "C" fn op_list_dir(
330 ctx: *mut Ctx,
331 this_: Value,
332 path: Value,
333 _: Value,
334 _: Value,
335 _: Value,
336 _: Value,
337) -> Value {
338 // SAFETY: an owned root-clause invocation on the running actor.
339 unsafe {
340 if crate::sched::remote_fs_denied(ctx) {
341 return deny_result(ctx, this_, &[path]);
342 }
343 blocking1(ctx, this_, path, list_dir_thunk)
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350 use crate::abi::{Block, int_get};
351 use crate::heap::{drop_value, dup_value};
352 use crate::values::{closure_code_borrowed, list_items, string, string_bytes, text};
353
354 #[test]
355 fn the_fs_capability_is_immortal_and_built_once() {
356 let cap = fs_cap();
357 assert_eq!(cap, fs_cap());
358 // SAFETY: the capability and its clauses are never freed.
359 unsafe {
360 let b = cap as *mut Block;
361 assert_eq!((*b).header.rc, 0);
362 let n = (*b).header.scan_fsize as usize;
363 assert_eq!(n, louise_rt_prims::FS_OPS.len() + 1);
364 let fields = Block::fields_ptr(b);
365 assert_eq!(fields.add(n - 1).read(), int(0), "the marker");
366 for i in 0..n - 1 {
367 let clause = fields.add(i).read() as *mut Block;
368 assert_eq!((*clause).header.rc, 0);
369 }
370 }
371 }
372
373 /// Perform an `fs` operation through its root clause, with either the
374 /// owned entry or the borrowed adapter generated closures also use.
375 /// At most two arguments: no register/xargs reinterpretation is hidden.
376 unsafe fn perform(ctx: *mut Ctx, op: &str, args: &[Value], owned: bool) -> Value {
377 // SAFETY: the caller runs on an actor and supplies live values.
378 unsafe {
379 assert!(args.len() <= 2);
380 let i = louise_rt_prims::FS_OPS
381 .iter()
382 .position(|name| *name == op)
383 .expect("an fs operation");
384 let cap = crate::process::root_cap(crate::process::RootCap::Fs);
385 let clause = Block::fields_ptr(cap as *mut Block).add(i).read();
386 if owned {
387 let clause = dup_value(clause);
388 drop_value(ctx, cap);
389 return crate::prims::call_closure(ctx, clause, args);
390 }
391 let mut regs = [UNIT; 5];
392 regs[..args.len()].copy_from_slice(args);
393 let code: Code = std::mem::transmute(closure_code_borrowed(clause));
394 let out = code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4]);
395 drop_value(ctx, cap);
396 out
397 }
398 }
399
400 fn assert_used_io_pool(n: usize) {
401 let threads = io_threads();
402 assert_eq!(threads.len(), n, "one record per operation: {threads:?}");
403 assert!(
404 threads
405 .iter()
406 .all(|name| name.starts_with("louise-blocking-io-")),
407 "filesystem roots must not run on a scheduler: {threads:?}"
408 );
409 }
410
411 /// (tag, first field) of a constructor value (`Ok` is tag 0).
412 unsafe fn ctor(v: Value) -> (u16, Value) {
413 // SAFETY: a live constructor cell.
414 unsafe {
415 let b = v as *mut Block;
416 ((*b).header.tag, Block::fields_ptr(b).read())
417 }
418 }
419
420 extern "C" fn roundtrip(ctx: *mut Ctx) -> Value {
421 // SAFETY: the test follows generated code's owned and borrowed
422 // clause conventions. Paths and payloads are smaller than 128 bytes.
423 unsafe {
424 let path = std::env::temp_dir().join("louise_rt_fs_test.bin");
425 let path = path.to_str().unwrap();
426 let p = string(ctx, path);
427 std::fs::remove_file(path).ok();
428 let before_exists = perform(ctx, "exists", &[dup_value(p)], true);
429 assert_eq!(before_exists, int(0));
430 drop_value(ctx, before_exists);
431
432 let content = bytes_from(ctx, b"hello");
433 let wrote = perform(
434 ctx,
435 "write_bytes",
436 &[dup_value(p), dup_value(content)],
437 true,
438 );
439 assert_eq!(ctor(wrote).0, 0, "Ok expected");
440 // The borrowed two-argument adapter leaves both inputs alone.
441 let wrote_borrowed = perform(ctx, "write_bytes", &[p, content], false);
442 assert_eq!(ctor(wrote_borrowed).0, 0, "Ok expected");
443 let exists = perform(ctx, "exists", &[p], false);
444 assert_eq!(exists, int(1));
445 drop_value(ctx, exists);
446
447 let size = perform(ctx, "size", &[p], false);
448 let (tag, n) = ctor(size);
449 assert_eq!(tag, 0, "Ok expected");
450 assert_eq!(int_get(n), 5);
451
452 let read = perform(ctx, "read_bytes", &[dup_value(p)], true);
453 let (tag, bytes) = ctor(read);
454 assert_eq!(tag, 0, "Ok expected");
455 assert_eq!(string_bytes(bytes), b"hello");
456
457 // A missing file is an `Error`, not a panic. The borrowed
458 // one-argument adapter still leaves `p` alive.
459 std::fs::remove_file(path).unwrap();
460 let missing = perform(ctx, "read_bytes", &[p], false);
461 assert_eq!(ctor(missing).0, 1, "Error expected");
462 // The two-argument adapter releases its duplicates on Error too.
463 let no_dir = string(ctx, &format!("{path}/child"));
464 let write_error = perform(
465 ctx,
466 "write_bytes",
467 &[dup_value(no_dir), dup_value(content)],
468 true,
469 );
470 assert_eq!(ctor(write_error).0, 1, "Error expected");
471
472 for v in [
473 wrote,
474 wrote_borrowed,
475 size,
476 read,
477 missing,
478 write_error,
479 content,
480 p,
481 no_dir,
482 ] {
483 drop_value(ctx, v);
484 }
485 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
486 assert_used_io_pool(8);
487 UNIT
488 }
489 }
490
491 #[test]
492 fn write_read_exists_size_and_errors() {
493 // SAFETY: the test actor follows the generated-code convention.
494 assert_eq!(unsafe { crate::sched::run_test_actor(roundtrip) }, 0);
495 }
496
497 extern "C" fn lists_dir(ctx: *mut Ctx) -> Value {
498 // SAFETY: the test follows the generated-code clause conventions.
499 unsafe {
500 let p = string(ctx, ".");
501 let listed = perform(ctx, "list_dir", &[p], false);
502 let (tag, entries) = ctor(listed);
503 assert_eq!(tag, 0, "Ok expected");
504 let names: Vec<&str> = list_items(entries).map(|e| text(e)).collect();
505 assert!(names.contains(&"Cargo.toml"), "{names:?}");
506 assert!(!names.contains(&"."), "{names:?}");
507
508 // A missing directory is an `Error`, not a panic.
509 let np = string(ctx, "/definitely/not/here");
510 let missing = perform(ctx, "list_dir", &[dup_value(np)], true);
511 assert_eq!(ctor(missing).0, 1, "Error expected");
512
513 for v in [listed, missing, p, np] {
514 drop_value(ctx, v);
515 }
516 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
517 assert_used_io_pool(2);
518 UNIT
519 }
520 }
521
522 #[test]
523 fn list_dir_lists_and_errors() {
524 // SAFETY: the test actor follows the generated-code convention.
525 assert_eq!(unsafe { crate::sched::run_test_actor(lists_dir) }, 0);
526 }
527}