//! Open files (`std/file/stream`, ADR 0087): the kernel both back ends //! share. The native runtime wraps a [`Handle`] in a resource and calls it //! on the blocking `io` pool (`louise_rt/src/fs.rs`); the interpreter //! calls it inline (`louise_interp`, `externs.rs`). //! //! - **One owner.** A handle belongs to the actor that opened it (its //! resource is pinned), so its calls never overlap; the lock only makes //! the handle `Sync` for the pool's threads. //! - **Closing** empties the handle: later calls fail with [`CLOSED`], //! never touch a stale descriptor. Dropping it closes the file too. //! - **Reads fill** up to `max` bytes: fewer only at the end of the file, //! none past it. //! - **New files** are created with mode [`NEW_FILE_MODE`] (`0600`, //! subject to the umask); an existing file keeps its mode. Descriptors //! are close-on-exec (Rust's default), so `std/command` children never //! inherit them. //! //! Errors are the OS's message, or one of this module's for an argument //! the OS never sees. use std::fs::{File, OpenOptions}; use std::io::{ErrorKind, Read, Seek, SeekFrom, Write}; use std::os::unix::fs::{FileExt, OpenOptionsExt}; use std::sync::{Mutex, PoisonError}; /// The mode a new file requests: private to its owner. pub const NEW_FILE_MODE: u32 = 0o600; /// The error of every call on a closed handle. pub const CLOSED: &str = "the file is closed"; /// Linux's `EISDIR`: `open_read` refuses a directory, which `open(2)` /// would accept for reading. const IS_A_DIRECTORY: i32 = 21; /// The first buffer a read allocates, at most: a read of a large `max` /// grows it (doubling) only while the file has more. const FIRST_BUFFER: usize = 1 << 20; /// How `open_write` treats the file at its path (`std/file/stream`'s /// `Mode`, by its constructor's index). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { /// Create it, or empty it if it exists. Truncate, /// Create it; an existing file is an error and is left untouched. CreateNew, /// Create it if missing; every write goes to its end. Append, } impl Mode { /// The mode of constructor index `code` (0, 1, 2), if any. pub fn from_index(code: i64) -> Option { match code { 0 => Some(Mode::Truncate), 1 => Some(Mode::CreateNew), 2 => Some(Mode::Append), _ => None, } } } /// An open file, until [`Handle::close`]. #[derive(Debug)] pub struct Handle { file: Mutex>, } impl Handle { fn new(file: File) -> Handle { Handle { file: Mutex::new(Some(file)), } } /// The file at `path`, open for reading from its start. A directory /// is an error. pub fn open_read(path: &str) -> Result { let file = File::open(path).map_err(message)?; if file.metadata().map_err(message)?.is_dir() { return Err(message(std::io::Error::from_raw_os_error(IS_A_DIRECTORY))); } Ok(Handle::new(file)) } /// The file at `path`, open for writing as `mode` says. No directory /// is created. pub fn open_write(path: &str, mode: Mode) -> Result { let mut options = OpenOptions::new(); options.mode(NEW_FILE_MODE); match mode { Mode::Truncate => options.write(true).create(true).truncate(true), Mode::CreateNew => options.write(true).create_new(true), Mode::Append => options.append(true).create(true), }; options.open(path).map(Handle::new).map_err(message) } fn with(&self, f: impl FnOnce(&mut File) -> std::io::Result) -> Result { let mut file = self.file.lock().unwrap_or_else(PoisonError::into_inner); match file.as_mut() { Some(file) => f(file).map_err(message), None => Err(CLOSED.to_owned()), } } /// Up to `max` bytes from the current position, which moves past /// them: fewer only at the end of the file, none past it. pub fn read(&self, max: i64) -> Result, String> { let max = positive(max)?; self.with(|file| fill(max, |buf| file.read(buf))) } /// Up to `max` bytes from `offset`, without moving the position (as /// `read`, fewer only at the end of the file). pub fn read_at(&self, offset: i64, max: i64) -> Result, String> { let mut at = not_negative(offset)?; let max = positive(max)?; self.with(|file| { fill(max, |buf| { let n = file.read_at(buf, at)?; at += n as u64; Ok(n) }) }) } /// All of `data`, at the current position (at the end in `Append` /// mode). pub fn write(&self, data: &[u8]) -> Result<(), String> { self.with(|file| file.write_all(data)) } /// Move the position to `offset` bytes from the start (past the end is /// allowed: a write there leaves a hole of zeros). pub fn seek(&self, offset: i64) -> Result<(), String> { let offset = not_negative(offset)?; self.with(|file| file.seek(SeekFrom::Start(offset)).map(drop)) } /// The file's size in bytes, now. pub fn size(&self) -> Result { self.with(|file| Ok(i64::try_from(file.metadata()?.len()).unwrap_or(i64::MAX))) } /// Flush the file's data and metadata to the device (`fsync`). pub fn sync(&self) -> Result<(), String> { self.with(|file| file.sync_all()) } /// Close the file; nothing if it is closed. An error of `close(2)` /// itself is not reported, as Rust's `File` does not: `sync` first to /// know the data reached the device. pub fn close(&self) { let file = self .file .lock() .unwrap_or_else(PoisonError::into_inner) .take(); drop(file); } } /// Flush the directory at `path` to the device (`fsync` on the /// directory), so a file created or renamed in it survives a crash. pub fn sync_dir(path: &str) -> Result<(), String> { File::open(path) .and_then(|dir| dir.sync_all()) .map_err(message) } fn message(e: std::io::Error) -> String { e.to_string() } fn positive(max: i64) -> Result { match usize::try_from(max) { Ok(n) if n > 0 => Ok(n), _ => Err(format!("max must be positive, got {max}")), } } fn not_negative(offset: i64) -> Result { u64::try_from(offset).map_err(|_| format!("offset must not be negative, got {offset}")) } /// Up to `max` bytes from `read`, called until it has them or returns 0. fn fill( max: usize, mut read: impl FnMut(&mut [u8]) -> std::io::Result, ) -> std::io::Result> { let mut buf = Vec::new(); let mut filled = 0; while filled < max { if filled == buf.len() { let grown = (buf.len() * 2).clamp(FIRST_BUFFER.min(max), max); buf.resize(grown, 0); } match read(&mut buf[filled..]) { Ok(0) => break, Ok(n) => filled += n, Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), } } buf.truncate(filled); Ok(buf) } #[cfg(test)] mod tests { use super::*; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!( "louise_rt_prims_file_{name}_{}", std::process::id() )); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir } fn path(p: &std::path::Path) -> &str { p.to_str().unwrap() } #[test] fn writes_then_reads_back_in_chunks_to_the_end() { let dir = scratch("chunks"); let file = dir.join("f"); let w = Handle::open_write(path(&file), Mode::Truncate).unwrap(); w.write(b"hello ").unwrap(); w.write(b"world").unwrap(); w.close(); let r = Handle::open_read(path(&file)).unwrap(); assert_eq!(r.read(4).unwrap(), b"hell"); assert_eq!(r.read(4).unwrap(), b"o wo"); assert_eq!(r.read(100).unwrap(), b"rld"); assert_eq!(r.read(4).unwrap(), b""); assert_eq!(r.size().unwrap(), 11); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn a_read_larger_than_the_first_buffer_fills_it() { let dir = scratch("large"); let file = dir.join("f"); let data: Vec = (0..3 * FIRST_BUFFER + 7).map(|i| i as u8).collect(); std::fs::write(&file, &data).unwrap(); let r = Handle::open_read(path(&file)).unwrap(); let max = i64::try_from(2 * FIRST_BUFFER + 1).unwrap(); assert_eq!(r.read(max).unwrap(), &data[..2 * FIRST_BUFFER + 1]); assert_eq!(r.read(i64::MAX).unwrap(), &data[2 * FIRST_BUFFER + 1..]); assert_eq!(r.read_at(5, i64::MAX).unwrap(), &data[5..]); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn read_at_leaves_the_position_and_seek_moves_it() { let dir = scratch("read_at"); let file = dir.join("f"); std::fs::write(&file, b"0123456789").unwrap(); let r = Handle::open_read(path(&file)).unwrap(); assert_eq!(r.read(2).unwrap(), b"01"); assert_eq!(r.read_at(5, 3).unwrap(), b"567"); assert_eq!(r.read_at(8, 10).unwrap(), b"89"); assert_eq!(r.read_at(50, 10).unwrap(), b""); assert_eq!(r.read(2).unwrap(), b"23"); r.seek(7).unwrap(); assert_eq!(r.read(10).unwrap(), b"789"); assert!(r.seek(-1).unwrap_err().contains("negative")); assert!(r.read_at(-1, 1).unwrap_err().contains("negative")); assert!(r.read(0).unwrap_err().contains("positive")); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn modes_truncate_refuse_an_existing_file_or_append() { let dir = scratch("modes"); let file = dir.join("f"); std::fs::write(&file, b"old content").unwrap(); let e = Handle::open_write(path(&file), Mode::CreateNew).unwrap_err(); assert!(e.contains("File exists"), "{e}"); assert_eq!(std::fs::read(&file).unwrap(), b"old content"); Handle::open_write(path(&file), Mode::Truncate) .unwrap() .write(b"new") .unwrap(); assert_eq!(std::fs::read(&file).unwrap(), b"new"); let a = Handle::open_write(path(&file), Mode::Append).unwrap(); a.seek(0).unwrap(); a.write(b"!").unwrap(); assert_eq!(std::fs::read(&file).unwrap(), b"new!"); let fresh = dir.join("fresh"); Handle::open_write(path(&fresh), Mode::CreateNew) .unwrap() .sync() .unwrap(); assert!(fresh.is_file()); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn new_files_are_private() { let dir = scratch("private"); for (name, mode) in [ ("t", Mode::Truncate), ("c", Mode::CreateNew), ("a", Mode::Append), ] { let file = dir.join(name); Handle::open_write(path(&file), mode).unwrap(); let bits = std::fs::metadata(&file).unwrap().permissions().mode(); assert_eq!(bits & 0o077, 0, "{name}: {bits:o}"); } std::fs::remove_dir_all(dir).unwrap(); } #[test] fn a_closed_handle_refuses_every_call() { let dir = scratch("closed"); let file = dir.join("f"); let h = Handle::open_write(path(&file), Mode::Truncate).unwrap(); h.close(); h.close(); assert_eq!(h.write(b"x").unwrap_err(), CLOSED); assert_eq!(h.read(1).unwrap_err(), CLOSED); assert_eq!(h.read_at(0, 1).unwrap_err(), CLOSED); assert_eq!(h.seek(0).unwrap_err(), CLOSED); assert_eq!(h.size().unwrap_err(), CLOSED); assert_eq!(h.sync().unwrap_err(), CLOSED); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn errors_are_the_os_messages() { let dir = scratch("errors"); let e = Handle::open_read(path(&dir.join("missing"))).unwrap_err(); assert_eq!(e, "No such file or directory (os error 2)"); let e = Handle::open_read(path(&dir)).unwrap_err(); assert_eq!(e, "Is a directory (os error 21)"); let file = dir.join("f"); std::fs::write(&file, b"x").unwrap(); let r = Handle::open_read(path(&file)).unwrap(); assert_eq!( r.write(b"y").unwrap_err(), "Bad file descriptor (os error 9)" ); assert!(sync_dir(path(&dir)).is_ok()); assert!(sync_dir(path(&dir.join("missing"))).is_err()); std::fs::remove_dir_all(dir).unwrap(); } }