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