Skip to main content

hermit/fs/
mod.rs

1pub(crate) mod dev_directory;
2pub(crate) mod mem;
3#[cfg(feature = "uhyve")]
4pub(crate) mod uhyve;
5#[cfg(feature = "virtio-fs")]
6pub(crate) mod virtio_fs;
7
8use alloc::borrow::ToOwned;
9use alloc::boxed::Box;
10use alloc::string::String;
11use alloc::sync::Arc;
12use alloc::vec::Vec;
13use core::fmt;
14use core::mem::MaybeUninit;
15use core::ops::BitAnd;
16
17use embedded_io::{Read, Write};
18use hermit_sync::{InterruptSpinMutex, OnceCell};
19use mem::MemDirectory;
20use num_enum::{IntoPrimitive, TryFromPrimitive};
21
22use crate::errno::Errno;
23use crate::executor::block_on;
24use crate::fd::{AccessPermission, Fd, ObjectInterface, OpenOption, insert_object, remove_object};
25use crate::io;
26use crate::time::{SystemTime, timespec};
27
28static FILESYSTEM: OnceCell<Filesystem> = OnceCell::new();
29
30static WORKING_DIRECTORY: InterruptSpinMutex<Option<String>> = InterruptSpinMutex::new(None);
31
32static UMASK: InterruptSpinMutex<AccessPermission> =
33	InterruptSpinMutex::new(AccessPermission::from_bits_retain(0o777));
34
35#[derive(Debug, Clone)]
36pub struct DirectoryEntry {
37	pub name: String,
38}
39
40impl DirectoryEntry {
41	pub fn new(name: String) -> Self {
42		Self { name }
43	}
44}
45
46/// Type of the VNode
47#[derive(Copy, Clone, Debug, PartialEq, Eq)]
48pub(crate) enum NodeKind {
49	/// Node represent a file
50	File,
51	/// Node represent a directory
52	Directory,
53}
54
55/// VfsNode represents an internal node of the ramdisk.
56pub(crate) trait VfsNode: Send + Sync + fmt::Debug {
57	/// Determines the current node type
58	fn get_kind(&self) -> NodeKind;
59
60	/// Determines the current file attribute
61	fn get_file_attributes(&self) -> io::Result<FileAttr> {
62		Err(Errno::Nosys)
63	}
64
65	/// Determines the syscall interface
66	fn get_object(&self) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
67		Err(Errno::Nosys)
68	}
69
70	/// Creates a new directory node
71	fn traverse_mkdir(&self, _path: &str, _mode: AccessPermission) -> io::Result<()> {
72		Err(Errno::Nosys)
73	}
74
75	/// Deletes a directory node
76	fn traverse_rmdir(&self, _path: &str) -> io::Result<()> {
77		Err(Errno::Nosys)
78	}
79
80	/// Removes the specified file
81	fn traverse_unlink(&self, _path: &str) -> io::Result<()> {
82		Err(Errno::Nosys)
83	}
84
85	/// Opens a directory
86	fn traverse_readdir(&self, _path: &str) -> io::Result<Vec<DirectoryEntry>> {
87		Err(Errno::Nosys)
88	}
89
90	/// Gets file status
91	fn traverse_lstat(&self, _path: &str) -> io::Result<FileAttr> {
92		Err(Errno::Nosys)
93	}
94
95	/// Gets file status
96	fn traverse_stat(&self, _path: &str) -> io::Result<FileAttr> {
97		Err(Errno::Nosys)
98	}
99
100	/// Mounts a file system
101	fn traverse_mount(&self, _path: &str, _obj: Box<dyn VfsNode>) -> io::Result<()> {
102		Err(Errno::Nosys)
103	}
104
105	/// Opens a file
106	fn traverse_open(
107		&self,
108		_path: &str,
109		_option: OpenOption,
110		_mode: AccessPermission,
111	) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
112		Err(Errno::Nosys)
113	}
114
115	/// Creates a read-only file
116	fn traverse_create_file(
117		&self,
118		_path: &str,
119		_data: &'static [u8],
120		_mode: AccessPermission,
121	) -> io::Result<()> {
122		Err(Errno::Nosys)
123	}
124}
125
126#[derive(Clone)]
127pub(crate) struct DirectoryReader(Vec<DirectoryEntry>);
128
129impl DirectoryReader {
130	pub fn new(data: Vec<DirectoryEntry>) -> Self {
131		Self(data)
132	}
133}
134
135impl ObjectInterface for DirectoryReader {
136	async fn getdents(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
137		let _buf = buf;
138		let _ = &self.0; // Dummy statement to avoid warning for the moment
139		unimplemented!()
140	}
141}
142
143#[derive(Debug)]
144pub(crate) struct Filesystem {
145	root: MemDirectory,
146}
147
148impl Filesystem {
149	pub fn new() -> Self {
150		Self {
151			root: MemDirectory::new(AccessPermission::from_bits(0o777).unwrap()),
152		}
153	}
154
155	/// Tries to open file at given path.
156	pub fn open(
157		&self,
158		path: &str,
159		opt: OpenOption,
160		mode: AccessPermission,
161	) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
162		debug!("Open file {path} with {opt:?}");
163
164		let path = path.strip_prefix('/').unwrap_or(path);
165
166		self.root.traverse_open(path, opt, mode)
167	}
168
169	/// Unlinks a file given by path
170	pub fn unlink(&self, path: &str) -> io::Result<()> {
171		debug!("Unlinking file {path}");
172
173		let path = path.strip_prefix('/').unwrap_or(path);
174
175		self.root.traverse_unlink(path)
176	}
177
178	/// Remove directory given by path
179	pub fn rmdir(&self, path: &str) -> io::Result<()> {
180		debug!("Removing directory {path}");
181
182		let path = path.strip_prefix('/').unwrap_or(path);
183
184		self.root.traverse_rmdir(path)
185	}
186
187	/// Create directory given by path
188	pub fn mkdir(&self, path: &str, mode: AccessPermission) -> io::Result<()> {
189		debug!("Create directory {path}");
190
191		let path = path.strip_prefix('/').unwrap_or(path);
192
193		self.root.traverse_mkdir(path, mode)
194	}
195
196	pub fn opendir(&self, path: &str) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
197		debug!("Open directory {path}");
198		Ok(Arc::new(async_lock::RwLock::new(
199			DirectoryReader::new(self.readdir(path)?).into(),
200		)))
201	}
202
203	/// List given directory
204	pub fn readdir(&self, path: &str) -> io::Result<Vec<DirectoryEntry>> {
205		debug!("Readdir {path}");
206
207		let path = path.strip_prefix('/').unwrap_or(path);
208
209		self.root.traverse_readdir(path)
210	}
211
212	/// stat
213	pub fn stat(&self, path: &str) -> io::Result<FileAttr> {
214		debug!("Getting stats {path}");
215
216		let path = path.strip_prefix('/').unwrap_or(path);
217
218		self.root.traverse_stat(path)
219	}
220
221	/// lstat
222	pub fn lstat(&self, path: &str) -> io::Result<FileAttr> {
223		debug!("Getting lstats {path}");
224
225		let path = path.strip_prefix('/').unwrap_or(path);
226
227		self.root.traverse_lstat(path)
228	}
229
230	/// Create new backing-fs at mountpoint mntpath
231	pub fn mount(&self, path: &str, obj: Box<dyn VfsNode>) -> io::Result<()> {
232		debug!("Mounting {path}");
233
234		let path = path.strip_prefix('/').unwrap_or(path);
235
236		self.root.traverse_mount(path, obj)
237	}
238
239	/// Create read-only file
240	pub fn create_file(
241		&self,
242		path: &str,
243		data: &'static [u8],
244		mode: AccessPermission,
245	) -> io::Result<()> {
246		debug!("Create read-only file {path}");
247
248		let path = path.strip_prefix('/').unwrap_or(path);
249
250		self.root.traverse_create_file(path, data, mode)
251	}
252}
253
254#[repr(C)]
255#[derive(Debug, Default, Copy, Clone)]
256pub struct FileAttr {
257	pub st_dev: u64,
258	pub st_ino: u64,
259	pub st_nlink: u64,
260	/// Access permissions
261	pub st_mode: AccessPermission,
262	/// User id
263	pub st_uid: u32,
264	/// Group id
265	pub st_gid: u32,
266	/// Device id
267	pub st_rdev: u64,
268	/// Size in bytes
269	pub st_size: i64,
270	/// Block size
271	pub st_blksize: i64,
272	/// Size in blocks
273	pub st_blocks: i64,
274	/// Time of last access
275	pub st_atim: timespec,
276	/// Time of last modification
277	pub st_mtim: timespec,
278	/// Time of last status change
279	pub st_ctim: timespec,
280}
281
282#[derive(TryFromPrimitive, IntoPrimitive, PartialEq, Eq, Clone, Copy, Debug)]
283#[repr(u8)]
284pub enum FileType {
285	Unknown = 0,         // DT_UNKNOWN
286	Fifo = 1,            // DT_FIFO
287	CharacterDevice = 2, // DT_CHR
288	Directory = 4,       // DT_DIR
289	BlockDevice = 6,     // DT_BLK
290	RegularFile = 8,     // DT_REG
291	SymbolicLink = 10,   // DT_LNK
292	Socket = 12,         // DT_SOCK
293	Whiteout = 14,       // DT_WHT
294}
295
296#[derive(TryFromPrimitive, IntoPrimitive, PartialEq, Eq, Clone, Copy, Debug)]
297#[repr(u8)]
298pub enum SeekWhence {
299	Set = 0,
300	Cur = 1,
301	End = 2,
302	Data = 3,
303	Hole = 4,
304}
305
306pub(crate) fn init() {
307	const VERSION: &str = env!("CARGO_PKG_VERSION");
308	const UTC_BUILT_TIME: &str = build_time::build_time_utc!();
309
310	let root_filesystem = Filesystem::new();
311
312	root_filesystem
313		.mkdir("/tmp", AccessPermission::from_bits(0o777).unwrap())
314		.expect("Unable to create /tmp");
315	root_filesystem
316		.mkdir("/proc", AccessPermission::from_bits(0o777).unwrap())
317		.expect("Unable to create /proc");
318
319	FILESYSTEM.set(root_filesystem).unwrap();
320
321	if let Ok(mut file) = File::create("/proc/version") {
322		if write!(file, "Hermit version {VERSION} # UTC {UTC_BUILT_TIME}").is_err() {
323			error!("Unable to write in /proc/version");
324		}
325	} else {
326		error!("Unable to create /proc/version");
327	}
328
329	*WORKING_DIRECTORY.lock() = Some("/tmp".to_owned());
330
331	#[cfg(feature = "virtio-fs")]
332	virtio_fs::init();
333
334	#[cfg(feature = "uhyve")]
335	use crate::env::UhyveStartInfo;
336
337	#[cfg(feature = "uhyve")]
338	if crate::env::start_info().is_uhyve() {
339		uhyve::init();
340	}
341
342	dev_directory::init();
343}
344
345pub fn create_file(name: &str, data: &'static [u8], mode: AccessPermission) -> io::Result<()> {
346	with_relative_filename(name, |name| {
347		FILESYSTEM
348			.get()
349			.ok_or(Errno::Inval)?
350			.create_file(name, data, mode)
351	})
352}
353
354/// Removes an empty directory.
355pub fn remove_dir(path: &str) -> io::Result<()> {
356	with_relative_filename(path, |path| {
357		FILESYSTEM.get().ok_or(Errno::Inval)?.rmdir(path)
358	})
359}
360
361pub fn unlink(path: &str) -> io::Result<()> {
362	with_relative_filename(path, |path| {
363		FILESYSTEM.get().ok_or(Errno::Inval)?.unlink(path)
364	})
365}
366
367/// Creates a new, empty directory at the provided path
368pub fn create_dir(path: &str, mode: AccessPermission) -> io::Result<()> {
369	let mask = *UMASK.lock();
370
371	with_relative_filename(path, |path| {
372		FILESYSTEM
373			.get()
374			.ok_or(Errno::Inval)?
375			.mkdir(path, mode.bitand(mask))
376	})
377}
378
379/// Returns an vector with all the entries within a directory.
380pub fn readdir(name: &str) -> io::Result<Vec<DirectoryEntry>> {
381	debug!("Read directory {name}");
382
383	with_relative_filename(name, |name| {
384		FILESYSTEM.get().ok_or(Errno::Inval)?.readdir(name)
385	})
386}
387
388pub fn read_stat(name: &str) -> io::Result<FileAttr> {
389	with_relative_filename(name, |name| {
390		FILESYSTEM.get().ok_or(Errno::Inval)?.stat(name)
391	})
392}
393
394pub fn read_lstat(name: &str) -> io::Result<FileAttr> {
395	with_relative_filename(name, |name| {
396		FILESYSTEM.get().ok_or(Errno::Inval)?.lstat(name)
397	})
398}
399
400fn with_relative_filename<F, T>(name: &str, callback: F) -> io::Result<T>
401where
402	F: FnOnce(&str) -> io::Result<T>,
403{
404	if name.starts_with("/") {
405		return callback(name);
406	}
407
408	let cwd = WORKING_DIRECTORY.lock();
409
410	let Some(cwd) = cwd.as_ref() else {
411		// Relative path with no CWD, this is weird/impossible
412		return Err(Errno::Badf);
413	};
414
415	let mut path = String::with_capacity(cwd.len() + name.len() + 1);
416	path.push_str(cwd);
417	path.push('/');
418	path.push_str(name);
419
420	callback(&path)
421}
422
423pub fn truncate(name: &str, size: usize) -> io::Result<()> {
424	with_relative_filename(name, |name| {
425		let fs = FILESYSTEM.get().ok_or(Errno::Inval)?;
426		let file = fs
427			.open(name, OpenOption::O_TRUNC, AccessPermission::empty())
428			.map_err(|_| Errno::Badf)?;
429
430		block_on(async { file.read().await.truncate(size).await }, None)
431	})
432}
433
434pub fn open(name: &str, flags: OpenOption, mode: AccessPermission) -> io::Result<RawFd> {
435	// mode is 0x777 (0b0111_0111_0111), when flags | O_CREAT, else 0
436	// flags is bitmask of O_DEC_* defined above.
437	// (taken from rust stdlib/sys hermit target )
438	let mask = *UMASK.lock();
439
440	with_relative_filename(name, |name| {
441		debug!("Open {name}, {flags:?}, {mode:?}");
442
443		let fs = FILESYSTEM.get().ok_or(Errno::Inval)?;
444		let file = fs.open(name, flags, mode.bitand(mask))?;
445		let fd = insert_object(file)?;
446		Ok(fd)
447	})
448}
449
450pub fn get_cwd() -> io::Result<String> {
451	let cwd = WORKING_DIRECTORY.lock();
452	let cwd = cwd.as_ref().ok_or(Errno::Noent)?;
453	Ok(cwd.clone())
454}
455
456pub fn set_cwd(cwd: &str) -> io::Result<()> {
457	// TODO: check that the directory exists and that permission flags are correct
458
459	let mut working_dir = WORKING_DIRECTORY.lock();
460	if cwd.starts_with("/") {
461		*working_dir = Some(cwd.to_owned());
462	} else {
463		let working_dir = working_dir.as_mut().ok_or(Errno::Badf)?;
464		working_dir.push('/');
465		working_dir.push_str(cwd);
466	}
467
468	Ok(())
469}
470
471pub fn umask(new_mask: AccessPermission) -> AccessPermission {
472	let mut lock = UMASK.lock();
473	let old = *lock;
474	*lock = new_mask;
475	old
476}
477
478/// Open a directory to read the directory entries
479pub(crate) fn opendir(name: &str) -> io::Result<RawFd> {
480	let obj = FILESYSTEM.get().ok_or(Errno::Inval)?.opendir(name)?;
481	insert_object(obj)
482}
483
484use crate::fd::{self, RawFd};
485
486pub fn file_attributes(path: &str) -> io::Result<FileAttr> {
487	FILESYSTEM.get().ok_or(Errno::Inval)?.lstat(path)
488}
489
490#[allow(clippy::len_without_is_empty)]
491#[derive(Debug, Copy, Clone)]
492pub struct Metadata(FileAttr);
493
494impl Metadata {
495	/// Returns the size of the file, in bytes
496	pub fn len(&self) -> usize {
497		self.0.st_size.try_into().unwrap()
498	}
499
500	/// Returns true if this metadata is for a file.
501	pub fn is_file(&self) -> bool {
502		self.0.st_mode.contains(AccessPermission::S_IFREG)
503	}
504
505	/// Returns true if this metadata is for a directory.
506	pub fn is_dir(&self) -> bool {
507		self.0.st_mode.contains(AccessPermission::S_IFDIR)
508	}
509
510	/// Returns the last modification time listed in this metadata.
511	pub fn modified(&self) -> io::Result<SystemTime> {
512		Ok(SystemTime::from(self.0.st_mtim))
513	}
514
515	/// Returns the last modification time listed in this metadata.
516	pub fn accessed(&self) -> io::Result<SystemTime> {
517		Ok(SystemTime::from(self.0.st_atim))
518	}
519}
520
521/// Given a path, query the file system to get information about a file, directory, etc.
522pub fn metadata(path: &str) -> io::Result<Metadata> {
523	Ok(Metadata(file_attributes(path)?))
524}
525
526#[derive(Debug)]
527pub struct File {
528	fd: RawFd,
529	path: String,
530}
531
532impl File {
533	/// Opens a file in write-only mode.
534	///
535	/// This function will create a file if it does not exist, and will truncate it if it does.
536	fn create(path: &str) -> io::Result<File> {
537		let fd = open(
538			path,
539			OpenOption::O_CREAT | OpenOption::O_TRUNC | OpenOption::O_WRONLY,
540			AccessPermission::from_bits(0o666).unwrap(),
541		)?;
542
543		Ok(File {
544			fd,
545			path: path.to_owned(),
546		})
547	}
548
549	/// Creates a new file in read-write mode; error if the file exists.
550	///
551	/// This function will create a file if it does not exist, or return
552	/// an error if it does. This way, if the call succeeds, the file
553	/// returned is guaranteed to be new.
554	pub fn create_new(path: &str) -> io::Result<Self> {
555		let fd = open(
556			path,
557			OpenOption::O_CREAT | OpenOption::O_EXCL | OpenOption::O_RDWR,
558			AccessPermission::from_bits(0o666).unwrap(),
559		)?;
560
561		Ok(File {
562			fd,
563			path: path.to_owned(),
564		})
565	}
566
567	/// Attempts to open a file in read-write mode.
568	pub fn open(path: &str) -> io::Result<Self> {
569		let fd = open(
570			path,
571			OpenOption::O_RDWR,
572			AccessPermission::from_bits(0o666).unwrap(),
573		)?;
574
575		Ok(File {
576			fd,
577			path: path.to_owned(),
578		})
579	}
580
581	pub fn metadata(&self) -> io::Result<Metadata> {
582		metadata(&self.path)
583	}
584}
585
586impl embedded_io::ErrorType for File {
587	type Error = Errno;
588}
589
590impl Read for File {
591	fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
592		fd::read(self.fd, buf)
593	}
594}
595
596impl Write for File {
597	fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
598		fd::write(self.fd, buf)
599	}
600
601	fn flush(&mut self) -> Result<(), Self::Error> {
602		Ok(())
603	}
604}
605
606impl Drop for File {
607	fn drop(&mut self) {
608		if let Err(err) = remove_object(self.fd) {
609			error!("File::drop failed: {err}");
610		}
611	}
612}