tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

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

357 lignes · 12857 octetsBrut · Historique
1//! Open files (`std/file/stream`, ADR 0087): the kernel both back ends
2//! share. The native runtime wraps a [`Handle`] in a resource and calls it
3//! on the blocking `io` pool (`louise_rt/src/fs.rs`); the interpreter
4//! calls it inline (`louise_interp`, `externs.rs`).
5//!
6//! - **One owner.** A handle belongs to the actor that opened it (its
7//! resource is pinned), so its calls never overlap; the lock only makes
8//! the handle `Sync` for the pool's threads.
9//! - **Closing** empties the handle: later calls fail with [`CLOSED`],
10//! never touch a stale descriptor. Dropping it closes the file too.
11//! - **Reads fill** up to `max` bytes: fewer only at the end of the file,
12//! none past it.
13//! - **New files** are created with mode [`NEW_FILE_MODE`] (`0600`,
14//! subject to the umask); an existing file keeps its mode. Descriptors
15//! are close-on-exec (Rust's default), so `std/command` children never
16//! inherit them.
17//!
18//! Errors are the OS's message, or one of this module's for an argument
19//! the OS never sees.
20
21use std::fs::{File, OpenOptions};
22use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
23use std::os::unix::fs::{FileExt, OpenOptionsExt};
24use std::sync::{Mutex, PoisonError};
25
26/// The mode a new file requests: private to its owner.
27pub const NEW_FILE_MODE: u32 = 0o600;
28
29/// The error of every call on a closed handle.
30pub const CLOSED: &str = "the file is closed";
31
32/// Linux's `EISDIR`: `open_read` refuses a directory, which `open(2)`
33/// would accept for reading.
34const IS_A_DIRECTORY: i32 = 21;
35
36/// The first buffer a read allocates, at most: a read of a large `max`
37/// grows it (doubling) only while the file has more.
38const FIRST_BUFFER: usize = 1 << 20;
39
40/// How `open_write` treats the file at its path (`std/file/stream`'s
41/// `Mode`, by its constructor's index).
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum Mode {
44 /// Create it, or empty it if it exists.
45 Truncate,
46 /// Create it; an existing file is an error and is left untouched.
47 CreateNew,
48 /// Create it if missing; every write goes to its end.
49 Append,
50}
51
52impl Mode {
53 /// The mode of constructor index `code` (0, 1, 2), if any.
54 pub fn from_index(code: i64) -> Option<Mode> {
55 match code {
56 0 => Some(Mode::Truncate),
57 1 => Some(Mode::CreateNew),
58 2 => Some(Mode::Append),
59 _ => None,
60 }
61 }
62}
63
64/// An open file, until [`Handle::close`].
65#[derive(Debug)]
66pub struct Handle {
67 file: Mutex<Option<File>>,
68}
69
70impl Handle {
71 fn new(file: File) -> Handle {
72 Handle {
73 file: Mutex::new(Some(file)),
74 }
75 }
76
77 /// The file at `path`, open for reading from its start. A directory
78 /// is an error.
79 pub fn open_read(path: &str) -> Result<Handle, String> {
80 let file = File::open(path).map_err(message)?;
81 if file.metadata().map_err(message)?.is_dir() {
82 return Err(message(std::io::Error::from_raw_os_error(IS_A_DIRECTORY)));
83 }
84 Ok(Handle::new(file))
85 }
86
87 /// The file at `path`, open for writing as `mode` says. No directory
88 /// is created.
89 pub fn open_write(path: &str, mode: Mode) -> Result<Handle, String> {
90 let mut options = OpenOptions::new();
91 options.mode(NEW_FILE_MODE);
92 match mode {
93 Mode::Truncate => options.write(true).create(true).truncate(true),
94 Mode::CreateNew => options.write(true).create_new(true),
95 Mode::Append => options.append(true).create(true),
96 };
97 options.open(path).map(Handle::new).map_err(message)
98 }
99
100 fn with<T>(&self, f: impl FnOnce(&mut File) -> std::io::Result<T>) -> Result<T, String> {
101 let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner);
102 match file.as_mut() {
103 Some(file) => f(file).map_err(message),
104 None => Err(CLOSED.to_owned()),
105 }
106 }
107
108 /// Up to `max` bytes from the current position, which moves past
109 /// them: fewer only at the end of the file, none past it.
110 pub fn read(&self, max: i64) -> Result<Vec<u8>, String> {
111 let max = positive(max)?;
112 self.with(|file| fill(max, |buf| file.read(buf)))
113 }
114
115 /// Up to `max` bytes from `offset`, without moving the position (as
116 /// `read`, fewer only at the end of the file).
117 pub fn read_at(&self, offset: i64, max: i64) -> Result<Vec<u8>, String> {
118 let mut at = not_negative(offset)?;
119 let max = positive(max)?;
120 self.with(|file| {
121 fill(max, |buf| {
122 let n = file.read_at(buf, at)?;
123 at += n as u64;
124 Ok(n)
125 })
126 })
127 }
128
129 /// All of `data`, at the current position (at the end in `Append`
130 /// mode).
131 pub fn write(&self, data: &[u8]) -> Result<(), String> {
132 self.with(|file| file.write_all(data))
133 }
134
135 /// Move the position to `offset` bytes from the start (past the end is
136 /// allowed: a write there leaves a hole of zeros).
137 pub fn seek(&self, offset: i64) -> Result<(), String> {
138 let offset = not_negative(offset)?;
139 self.with(|file| file.seek(SeekFrom::Start(offset)).map(drop))
140 }
141
142 /// The file's size in bytes, now.
143 pub fn size(&self) -> Result<i64, String> {
144 self.with(|file| Ok(i64::try_from(file.metadata()?.len()).unwrap_or(i64::MAX)))
145 }
146
147 /// Flush the file's data and metadata to the device (`fsync`).
148 pub fn sync(&self) -> Result<(), String> {
149 self.with(|file| file.sync_all())
150 }
151
152 /// Close the file; nothing if it is closed. An error of `close(2)`
153 /// itself is not reported, as Rust's `File` does not: `sync` first to
154 /// know the data reached the device.
155 pub fn close(&self) {
156 let file = self
157 .file
158 .lock()
159 .unwrap_or_else(PoisonError::into_inner)
160 .take();
161 drop(file);
162 }
163}
164
165/// Flush the directory at `path` to the device (`fsync` on the
166/// directory), so a file created or renamed in it survives a crash.
167pub fn sync_dir(path: &str) -> Result<(), String> {
168 File::open(path)
169 .and_then(|dir| dir.sync_all())
170 .map_err(message)
171}
172
173fn message(e: std::io::Error) -> String {
174 e.to_string()
175}
176
177fn positive(max: i64) -> Result<usize, String> {
178 match usize::try_from(max) {
179 Ok(n) if n > 0 => Ok(n),
180 _ => Err(format!("max must be positive, got {max}")),
181 }
182}
183
184fn not_negative(offset: i64) -> Result<u64, String> {
185 u64::try_from(offset).map_err(|_| format!("offset must not be negative, got {offset}"))
186}
187
188/// Up to `max` bytes from `read`, called until it has them or returns 0.
189fn fill(
190 max: usize,
191 mut read: impl FnMut(&mut [u8]) -> std::io::Result<usize>,
192) -> std::io::Result<Vec<u8>> {
193 let mut buf = Vec::new();
194 let mut filled = 0;
195 while filled < max {
196 if filled == buf.len() {
197 let grown = (buf.len() * 2).clamp(FIRST_BUFFER.min(max), max);
198 buf.resize(grown, 0);
199 }
200 match read(&mut buf[filled..]) {
201 Ok(0) => break,
202 Ok(n) => filled += n,
203 Err(e) if e.kind() == ErrorKind::Interrupted => {}
204 Err(e) => return Err(e),
205 }
206 }
207 buf.truncate(filled);
208 Ok(buf)
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use std::os::unix::fs::PermissionsExt;
215 use std::path::PathBuf;
216
217 fn scratch(name: &str) -> PathBuf {
218 let dir = std::env::temp_dir().join(format!(
219 "louise_rt_prims_file_{name}_{}",
220 std::process::id()
221 ));
222 let _ = std::fs::remove_dir_all(&dir);
223 std::fs::create_dir_all(&dir).unwrap();
224 dir
225 }
226
227 fn path(p: &std::path::Path) -> &str {
228 p.to_str().unwrap()
229 }
230
231 #[test]
232 fn writes_then_reads_back_in_chunks_to_the_end() {
233 let dir = scratch("chunks");
234 let file = dir.join("f");
235 let w = Handle::open_write(path(&file), Mode::Truncate).unwrap();
236 w.write(b"hello ").unwrap();
237 w.write(b"world").unwrap();
238 w.close();
239 let r = Handle::open_read(path(&file)).unwrap();
240 assert_eq!(r.read(4).unwrap(), b"hell");
241 assert_eq!(r.read(4).unwrap(), b"o wo");
242 assert_eq!(r.read(100).unwrap(), b"rld");
243 assert_eq!(r.read(4).unwrap(), b"");
244 assert_eq!(r.size().unwrap(), 11);
245 std::fs::remove_dir_all(dir).unwrap();
246 }
247
248 #[test]
249 fn a_read_larger_than_the_first_buffer_fills_it() {
250 let dir = scratch("large");
251 let file = dir.join("f");
252 let data: Vec<u8> = (0..3 * FIRST_BUFFER + 7).map(|i| i as u8).collect();
253 std::fs::write(&file, &data).unwrap();
254 let r = Handle::open_read(path(&file)).unwrap();
255 let max = i64::try_from(2 * FIRST_BUFFER + 1).unwrap();
256 assert_eq!(r.read(max).unwrap(), &data[..2 * FIRST_BUFFER + 1]);
257 assert_eq!(r.read(i64::MAX).unwrap(), &data[2 * FIRST_BUFFER + 1..]);
258 assert_eq!(r.read_at(5, i64::MAX).unwrap(), &data[5..]);
259 std::fs::remove_dir_all(dir).unwrap();
260 }
261
262 #[test]
263 fn read_at_leaves_the_position_and_seek_moves_it() {
264 let dir = scratch("read_at");
265 let file = dir.join("f");
266 std::fs::write(&file, b"0123456789").unwrap();
267 let r = Handle::open_read(path(&file)).unwrap();
268 assert_eq!(r.read(2).unwrap(), b"01");
269 assert_eq!(r.read_at(5, 3).unwrap(), b"567");
270 assert_eq!(r.read_at(8, 10).unwrap(), b"89");
271 assert_eq!(r.read_at(50, 10).unwrap(), b"");
272 assert_eq!(r.read(2).unwrap(), b"23");
273 r.seek(7).unwrap();
274 assert_eq!(r.read(10).unwrap(), b"789");
275 assert!(r.seek(-1).unwrap_err().contains("negative"));
276 assert!(r.read_at(-1, 1).unwrap_err().contains("negative"));
277 assert!(r.read(0).unwrap_err().contains("positive"));
278 std::fs::remove_dir_all(dir).unwrap();
279 }
280
281 #[test]
282 fn modes_truncate_refuse_an_existing_file_or_append() {
283 let dir = scratch("modes");
284 let file = dir.join("f");
285 std::fs::write(&file, b"old content").unwrap();
286 let e = Handle::open_write(path(&file), Mode::CreateNew).unwrap_err();
287 assert!(e.contains("File exists"), "{e}");
288 assert_eq!(std::fs::read(&file).unwrap(), b"old content");
289 Handle::open_write(path(&file), Mode::Truncate)
290 .unwrap()
291 .write(b"new")
292 .unwrap();
293 assert_eq!(std::fs::read(&file).unwrap(), b"new");
294 let a = Handle::open_write(path(&file), Mode::Append).unwrap();
295 a.seek(0).unwrap();
296 a.write(b"!").unwrap();
297 assert_eq!(std::fs::read(&file).unwrap(), b"new!");
298 let fresh = dir.join("fresh");
299 Handle::open_write(path(&fresh), Mode::CreateNew)
300 .unwrap()
301 .sync()
302 .unwrap();
303 assert!(fresh.is_file());
304 std::fs::remove_dir_all(dir).unwrap();
305 }
306
307 #[test]
308 fn new_files_are_private() {
309 let dir = scratch("private");
310 for (name, mode) in [
311 ("t", Mode::Truncate),
312 ("c", Mode::CreateNew),
313 ("a", Mode::Append),
314 ] {
315 let file = dir.join(name);
316 Handle::open_write(path(&file), mode).unwrap();
317 let bits = std::fs::metadata(&file).unwrap().permissions().mode();
318 assert_eq!(bits & 0o077, 0, "{name}: {bits:o}");
319 }
320 std::fs::remove_dir_all(dir).unwrap();
321 }
322
323 #[test]
324 fn a_closed_handle_refuses_every_call() {
325 let dir = scratch("closed");
326 let file = dir.join("f");
327 let h = Handle::open_write(path(&file), Mode::Truncate).unwrap();
328 h.close();
329 h.close();
330 assert_eq!(h.write(b"x").unwrap_err(), CLOSED);
331 assert_eq!(h.read(1).unwrap_err(), CLOSED);
332 assert_eq!(h.read_at(0, 1).unwrap_err(), CLOSED);
333 assert_eq!(h.seek(0).unwrap_err(), CLOSED);
334 assert_eq!(h.size().unwrap_err(), CLOSED);
335 assert_eq!(h.sync().unwrap_err(), CLOSED);
336 std::fs::remove_dir_all(dir).unwrap();
337 }
338
339 #[test]
340 fn errors_are_the_os_messages() {
341 let dir = scratch("errors");
342 let e = Handle::open_read(path(&dir.join("missing"))).unwrap_err();
343 assert_eq!(e, "No such file or directory (os error 2)");
344 let e = Handle::open_read(path(&dir)).unwrap_err();
345 assert_eq!(e, "Is a directory (os error 21)");
346 let file = dir.join("f");
347 std::fs::write(&file, b"x").unwrap();
348 let r = Handle::open_read(path(&file)).unwrap();
349 assert_eq!(
350 r.write(b"y").unwrap_err(),
351 "Bad file descriptor (os error 9)"
352 );
353 assert!(sync_dir(path(&dir)).is_ok());
354 assert!(sync_dir(path(&dir.join("missing"))).is_err());
355 std::fs::remove_dir_all(dir).unwrap();
356 }
357}