tobogganSe connecter

louise

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

339 lignes · 12653 octetsBrut · Historique
1//! Filesystem operations for `std/file`: blocking externs, run on the
2//! blocking pool while their actor is parked (see `blocking.rs`).
3//!
4//! Every failure is an `Error` value with the OS's message: a blocking
5//! extern must not panic.
6
7use crate::abi::{Ctx, UNIT, Value, int};
8use crate::prims::boolean;
9use crate::values::{bytes_from, bytes_of, error, list, ok, string, text};
10
11fn create_dir(path: &str, recursive: bool) -> std::io::Result<()> {
12 let mut builder = std::fs::DirBuilder::new();
13 builder.recursive(recursive);
14 #[cfg(unix)]
15 {
16 use std::os::unix::fs::DirBuilderExt;
17 builder.mode(0o700);
18 }
19 builder.create(path)
20}
21
22fn remove_path(path: &str, recursive: bool) -> std::io::Result<()> {
23 let file_type = std::fs::symlink_metadata(path)?.file_type();
24 if file_type.is_dir() {
25 if recursive {
26 std::fs::remove_dir_all(path)
27 } else {
28 std::fs::remove_dir(path)
29 }
30 } else {
31 std::fs::remove_file(path)
32 }
33}
34
35fn unit_result(ctx: *mut Ctx, result: std::io::Result<()>) -> Value {
36 match result {
37 Ok(()) => ok(ctx, UNIT),
38 Err(e) => error(ctx, &e.to_string()),
39 }
40}
41
42/// `read_bytes(path)`: the file's contents, or `Error` with the OS's
43/// message.
44///
45/// # Safety
46/// `path` must be a live string; `ctx` the calling actor's context. The
47/// result is built with the allocation functions of `louise_rt.h`, which
48/// work on any thread, as a blocking extern requires.
49#[unsafe(no_mangle)]
50pub unsafe extern "C" fn tl_file_read(ctx: *mut Ctx, path: Value) -> Value {
51 // SAFETY: caller guarantees a live string.
52 match std::fs::read(unsafe { text(path) }) {
53 Ok(bytes) => {
54 let b = bytes_from(ctx, &bytes);
55 ok(ctx, b)
56 }
57 Err(e) => error(ctx, &e.to_string()),
58 }
59}
60
61/// `write(path, content)`: the file created or truncated, or `Error` with
62/// the OS's message.
63///
64/// # Safety
65/// `path` must be a live string and `content` live `Bytes`; `ctx` the
66/// calling actor's context.
67#[unsafe(no_mangle)]
68pub unsafe extern "C" fn tl_file_write(ctx: *mut Ctx, path: Value, content: Value) -> Value {
69 // SAFETY: caller guarantees a live string and live Bytes.
70 let (path, content) = unsafe { (text(path), bytes_of(content)) };
71 match std::fs::write(path, content) {
72 Ok(()) => ok(ctx, UNIT),
73 Err(e) => error(ctx, &e.to_string()),
74 }
75}
76
77/// Whether a file (not a directory) exists at `path`.
78///
79/// # Safety
80/// `path` must be a live string.
81#[unsafe(no_mangle)]
82pub unsafe extern "C" fn tl_file_exists(_ctx: *mut Ctx, path: Value) -> Value {
83 // SAFETY: caller guarantees a live string.
84 boolean(std::path::Path::is_file(std::path::Path::new(unsafe {
85 text(path)
86 })))
87}
88
89/// The file's size in bytes, or `Error` with the OS's message.
90///
91/// # Safety
92/// `path` must be a live string; `ctx` the calling actor's context.
93#[unsafe(no_mangle)]
94pub unsafe extern "C" fn tl_file_size(ctx: *mut Ctx, path: Value) -> Value {
95 // SAFETY: caller guarantees a live string.
96 match std::fs::metadata(unsafe { text(path) }) {
97 Ok(meta) => ok(ctx, int(i64::try_from(meta.len()).unwrap_or(i64::MAX))),
98 Err(e) => error(ctx, &e.to_string()),
99 }
100}
101
102/// The names of the directory's entries (not full paths, never `.` or
103/// `..`, in the OS's order), or `Error` with the OS's message. A name
104/// that is not valid UTF-8 is lossy-decoded.
105///
106/// # Safety
107/// `path` must be a live string; `ctx` the calling actor's context.
108#[unsafe(no_mangle)]
109pub unsafe extern "C" fn tl_file_list_dir(ctx: *mut Ctx, path: Value) -> Value {
110 // SAFETY: caller guarantees a live string.
111 let entries = match std::fs::read_dir(unsafe { text(path) }) {
112 Ok(entries) => entries,
113 Err(e) => return error(ctx, &e.to_string()),
114 };
115 let mut names = Vec::new();
116 for entry in entries {
117 match entry {
118 Ok(e) => names.push(string(ctx, &e.file_name().to_string_lossy())),
119 Err(e) => return error(ctx, &e.to_string()),
120 }
121 }
122 ok(ctx, list(ctx, names.into_iter()))
123}
124
125/// `make_dir(path)`: a private directory, without creating its parents.
126///
127/// # Safety
128/// `path` must be a live string; `ctx` the calling actor's context.
129#[unsafe(no_mangle)]
130pub unsafe extern "C" fn tl_file_make_dir(ctx: *mut Ctx, path: Value) -> Value {
131 // SAFETY: caller guarantees a live string.
132 unit_result(ctx, create_dir(unsafe { text(path) }, false))
133}
134
135/// `make_dirs(path)`: a private directory and any missing parents.
136///
137/// # Safety
138/// `path` must be a live string; `ctx` the calling actor's context.
139#[unsafe(no_mangle)]
140pub unsafe extern "C" fn tl_file_make_dirs(ctx: *mut Ctx, path: Value) -> Value {
141 // SAFETY: caller guarantees a live string.
142 unit_result(ctx, create_dir(unsafe { text(path) }, true))
143}
144
145/// `remove(path)`: a file, symbolic link, or empty directory removed.
146///
147/// # Safety
148/// `path` must be a live string; `ctx` the calling actor's context.
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn tl_file_remove(ctx: *mut Ctx, path: Value) -> Value {
151 // SAFETY: caller guarantees a live string.
152 unit_result(ctx, remove_path(unsafe { text(path) }, false))
153}
154
155/// `remove_all(path)`: a file, symbolic link, or directory tree removed,
156/// without following symbolic links.
157///
158/// # Safety
159/// `path` must be a live string; `ctx` the calling actor's context.
160#[unsafe(no_mangle)]
161pub unsafe extern "C" fn tl_file_remove_all(ctx: *mut Ctx, path: Value) -> Value {
162 // SAFETY: caller guarantees a live string.
163 unit_result(ctx, remove_path(unsafe { text(path) }, true))
164}
165
166/// `rename(from, to)`: `from` atomically renamed over `to` within one
167/// filesystem.
168///
169/// # Safety
170/// `from` and `to` must be live strings; `ctx` the calling actor's context.
171#[unsafe(no_mangle)]
172pub unsafe extern "C" fn tl_file_rename(ctx: *mut Ctx, from: Value, to: Value) -> Value {
173 // SAFETY: caller guarantees live strings.
174 let (from, to) = unsafe { (text(from), text(to)) };
175 unit_result(ctx, std::fs::rename(from, to))
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use crate::abi::{Block, int_get};
182 use crate::heap::drop_value;
183 use crate::values::{list_items, string, string_bytes, text};
184
185 /// (tag, first field) of a constructor value (`Ok` is tag 0).
186 unsafe fn ctor(v: Value) -> (u16, Value) {
187 // SAFETY: a live constructor cell.
188 unsafe {
189 let b = v as *mut Block;
190 ((*b).header.tag, Block::fields_ptr(b).read())
191 }
192 }
193
194 extern "C" fn roundtrip(ctx: *mut Ctx) -> Value {
195 // SAFETY: the test follows the generated-code convention: fresh
196 // values are dropped once, arguments of the externs are borrowed.
197 unsafe {
198 let path = std::env::temp_dir().join("louise_rt_fs_test.bin");
199 let path = path.to_str().unwrap();
200 let p = string(ctx, path);
201 std::fs::remove_file(path).ok();
202 assert_eq!(tl_file_exists(ctx, p), int(0));
203
204 let content = bytes_from(ctx, b"hello");
205 let wrote = tl_file_write(ctx, p, content);
206 assert_eq!(ctor(wrote).0, 0, "Ok expected");
207 assert_eq!(tl_file_exists(ctx, p), int(1));
208
209 let size = tl_file_size(ctx, p);
210 let (tag, n) = ctor(size);
211 assert_eq!(tag, 0, "Ok expected");
212 assert_eq!(int_get(n), 5);
213
214 let read = tl_file_read(ctx, p);
215 let (tag, bytes) = ctor(read);
216 assert_eq!(tag, 0, "Ok expected");
217 assert_eq!(string_bytes(bytes), b"hello");
218
219 // A missing file is an `Error`, not a panic.
220 std::fs::remove_file(path).unwrap();
221 let missing = tl_file_read(ctx, p);
222 assert_eq!(ctor(missing).0, 1, "Error expected");
223
224 for v in [wrote, size, read, missing, content, p] {
225 drop_value(ctx, v);
226 }
227 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
228 UNIT
229 }
230 }
231
232 #[test]
233 fn write_read_exists_size_and_errors() {
234 // SAFETY: the test actor follows the generated-code convention.
235 assert_eq!(unsafe { crate::sched::run_test_actor(roundtrip) }, 0);
236 }
237
238 extern "C" fn lists_dir(ctx: *mut Ctx) -> Value {
239 // SAFETY: the test follows the generated-code convention: fresh
240 // values are dropped once, arguments of the externs are borrowed.
241 unsafe {
242 let p = string(ctx, ".");
243 let listed = tl_file_list_dir(ctx, p);
244 let (tag, entries) = ctor(listed);
245 assert_eq!(tag, 0, "Ok expected");
246 let names: Vec<&str> = list_items(entries).map(|e| text(e)).collect();
247 assert!(names.contains(&"Cargo.toml"), "{names:?}");
248 assert!(!names.contains(&"."), "{names:?}");
249
250 // A missing directory is an `Error`, not a panic.
251 let np = string(ctx, "/definitely/not/here");
252 let missing = tl_file_list_dir(ctx, np);
253 assert_eq!(ctor(missing).0, 1, "Error expected");
254
255 for v in [listed, missing, p, np] {
256 drop_value(ctx, v);
257 }
258 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
259 UNIT
260 }
261 }
262
263 #[test]
264 fn list_dir_lists_and_errors() {
265 // SAFETY: the test actor follows the generated-code convention.
266 assert_eq!(unsafe { crate::sched::run_test_actor(lists_dir) }, 0);
267 }
268
269 #[cfg(unix)]
270 #[test]
271 fn new_directories_are_private() {
272 use std::os::unix::fs::PermissionsExt;
273
274 let base =
275 std::env::temp_dir().join(format!("louise_rt_fs_private_dirs_{}", std::process::id()));
276 let _ = std::fs::remove_dir_all(&base);
277 std::fs::create_dir(&base).unwrap();
278 let (single, nested) = (base.join("single"), base.join("parent/child"));
279 create_dir(single.to_str().unwrap(), false).unwrap();
280 create_dir(nested.to_str().unwrap(), true).unwrap();
281 create_dir(nested.to_str().unwrap(), true).unwrap();
282 assert!(create_dir(single.to_str().unwrap(), false).is_err());
283 for path in [single.as_path(), nested.as_path(), nested.parent().unwrap()] {
284 let mode = std::fs::metadata(path).unwrap().permissions().mode();
285 assert_eq!(
286 mode & 0o077,
287 0,
288 "{} is group/other accessible",
289 path.display()
290 );
291 }
292 std::fs::remove_dir_all(base).unwrap();
293 }
294
295 #[cfg(unix)]
296 extern "C" fn removes_without_following_symlinks(ctx: *mut Ctx) -> Value {
297 // SAFETY: the test follows the generated-code convention: fresh
298 // values are dropped once, arguments of the externs are borrowed.
299 unsafe {
300 let base = std::env::temp_dir()
301 .join(format!("louise_rt_fs_symlink_test_{}", std::process::id()));
302 let _ = std::fs::remove_dir_all(&base);
303 let (tree, outside) = (base.join("tree"), base.join("outside"));
304 std::fs::create_dir_all(tree.join("nested")).unwrap();
305 std::fs::create_dir(&outside).unwrap();
306 let sentinel = outside.join("keep.txt");
307 std::fs::write(&sentinel, "untouched").unwrap();
308 std::os::unix::fs::symlink(&outside, tree.join("link")).unwrap();
309
310 let p = string(ctx, tree.to_str().unwrap());
311 let removed = tl_file_remove_all(ctx, p);
312 assert_eq!(ctor(removed).0, 0, "Ok expected");
313 assert!(!tree.exists());
314 assert!(sentinel.is_file());
315
316 // A symlink at the root is removed itself, just like a nested one.
317 std::os::unix::fs::symlink(&outside, &tree).unwrap();
318 let removed_link = tl_file_remove_all(ctx, p);
319 assert_eq!(ctor(removed_link).0, 0, "Ok expected");
320 assert!(std::fs::symlink_metadata(&tree).is_err());
321 assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "untouched");
322
323 for v in [removed, removed_link, p] {
324 drop_value(ctx, v);
325 }
326 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
327 std::fs::remove_dir_all(base).unwrap();
328 UNIT
329 }
330 }
331
332 #[cfg(unix)]
333 #[test]
334 fn remove_all_does_not_follow_symlinks() {
335 // SAFETY: the test actor follows the generated-code convention.
336 let result = unsafe { crate::sched::run_test_actor(removes_without_following_symlinks) };
337 assert_eq!(result, 0);
338 }
339}