wasmer_wasix/fs/
mod.rs

1// TODO: currently, hard links are broken in the presence or renames.
2// It is impossible to fix them with the current setup, since a hard
3// link must point to the actual file rather than its path, but the
4// only way we can get to a file on a FileSystem instance is by going
5// through its repective FileOpener and giving it a path as input.
6// TODO: refactor away the InodeVal type
7
8mod fd;
9mod fd_list;
10mod inode_guard;
11mod notification;
12pub(crate) mod relative_path_hack;
13
14use std::{
15    borrow::{Borrow, Cow},
16    collections::{HashMap, HashSet, VecDeque},
17    ops::{Deref, DerefMut},
18    path::{Component, Path, PathBuf},
19    pin::Pin,
20    sync::{
21        Arc, Mutex, RwLock, Weak,
22        atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering},
23    },
24    task::{Context, Poll},
25};
26
27use self::fd_list::FdList;
28use crate::{
29    net::socket::InodeSocketKind,
30    state::{Stderr, Stdin, Stdout},
31};
32use futures::{Future, TryStreamExt, future::BoxFuture};
33#[cfg(feature = "enable-serde")]
34use serde_derive::{Deserialize, Serialize};
35use tokio::io::AsyncWriteExt;
36use tracing::{debug, trace};
37use virtual_fs::{
38    FileSystem, FsError, OpenOptions, UnionFileSystem, VirtualFile, copy_reference,
39    tmp_fs::TmpFileSystem,
40};
41use wasmer_config::package::PackageId;
42use wasmer_wasix_types::{
43    types::{__WASI_STDERR_FILENO, __WASI_STDIN_FILENO, __WASI_STDOUT_FILENO},
44    wasi::{
45        Errno, Fd as WasiFd, Fdflags, Fdflagsext, Fdstat, Filesize, Filestat, Filetype,
46        Preopentype, Prestat, PrestatEnum, Rights, Socktype,
47    },
48};
49
50pub use self::fd::{EpollFd, EpollInterest, EpollJoinGuard, Fd, FdInner, InodeVal, Kind};
51pub(crate) use self::inode_guard::{
52    InodeValFilePollGuard, InodeValFilePollGuardJoin, InodeValFilePollGuardMode,
53    InodeValFileReadGuard, InodeValFileWriteGuard, POLL_GUARD_MAX_RET, WasiStateFileGuard,
54};
55pub use self::notification::NotificationInner;
56use self::relative_path_hack::RelativeOrAbsolutePathHack;
57use crate::syscalls::map_io_err;
58use crate::{ALL_RIGHTS, bin_factory::BinaryPackage, state::PreopenedDir};
59
60/// the fd value of the virtual root
61///
62/// Used for interacting with the file system when it has no
63/// pre-opened file descriptors at the root level. Normally
64/// a WASM process will do this in the libc initialization stage
65/// however that does not happen when the WASM process has never
66/// been run. Further that logic could change at any time in libc
67/// which would then break functionality. Instead we use this fixed
68/// file descriptor
69///
70/// This is especially important for fuse mounting journals which
71/// use the same syscalls as a normal WASI application but do not
72/// run the libc initialization logic
73pub const VIRTUAL_ROOT_FD: WasiFd = 3;
74
75/// The root inode and stdio inodes are the first inodes in the
76/// file system tree
77pub const FS_STDIN_INO: Inode = Inode(10);
78pub const FS_STDOUT_INO: Inode = Inode(11);
79pub const FS_STDERR_INO: Inode = Inode(12);
80pub const FS_ROOT_INO: Inode = Inode(13);
81
82const STDIN_DEFAULT_RIGHTS: Rights = {
83    // This might seem a bit overenineered, but it's the only way I
84    // discovered for getting the values in a const environment
85    Rights::from_bits_truncate(
86        Rights::FD_DATASYNC.bits()
87            | Rights::FD_READ.bits()
88            | Rights::FD_SYNC.bits()
89            | Rights::FD_ADVISE.bits()
90            | Rights::FD_FILESTAT_GET.bits()
91            | Rights::FD_FDSTAT_SET_FLAGS.bits()
92            | Rights::POLL_FD_READWRITE.bits(),
93    )
94};
95const STDOUT_DEFAULT_RIGHTS: Rights = {
96    // This might seem a bit overenineered, but it's the only way I
97    // discovered for getting the values in a const environment
98    Rights::from_bits_truncate(
99        Rights::FD_DATASYNC.bits()
100            | Rights::FD_SYNC.bits()
101            | Rights::FD_WRITE.bits()
102            | Rights::FD_ADVISE.bits()
103            | Rights::FD_FILESTAT_GET.bits()
104            | Rights::FD_FDSTAT_SET_FLAGS.bits()
105            | Rights::POLL_FD_READWRITE.bits(),
106    )
107};
108const STDERR_DEFAULT_RIGHTS: Rights = STDOUT_DEFAULT_RIGHTS;
109
110/// A completely aribtrary "big enough" number used as the upper limit for
111/// the number of symlinks that can be traversed when resolving a path
112pub const MAX_SYMLINKS: u32 = 128;
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
115#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
116pub struct Inode(u64);
117
118impl Inode {
119    pub fn as_u64(&self) -> u64 {
120        self.0
121    }
122
123    pub fn from_path(str: &str) -> Self {
124        Inode(xxhash_rust::xxh64::xxh64(str.as_bytes(), 0))
125    }
126}
127
128#[derive(Debug, Clone)]
129pub struct InodeGuard {
130    ino: Inode,
131    inner: Arc<InodeVal>,
132
133    // This exists because self.inner doesn't really represent the
134    // number of FDs referencing this InodeGuard. We need that number
135    // so we can know when to drop the file handle, which should result
136    // in the backing file (which may be a host file) getting closed.
137    open_handles: Arc<AtomicI32>,
138}
139impl InodeGuard {
140    pub fn ino(&self) -> Inode {
141        self.ino
142    }
143
144    pub fn downgrade(&self) -> InodeWeakGuard {
145        InodeWeakGuard {
146            ino: self.ino,
147            open_handles: self.open_handles.clone(),
148            inner: Arc::downgrade(&self.inner),
149        }
150    }
151
152    pub fn ref_cnt(&self) -> usize {
153        Arc::strong_count(&self.inner)
154    }
155
156    pub fn handle_count(&self) -> u32 {
157        self.open_handles.load(Ordering::SeqCst) as u32
158    }
159
160    pub fn acquire_handle(&self) {
161        let prev_handles = self.open_handles.fetch_add(1, Ordering::SeqCst);
162        trace!(ino = %self.ino.0, new_count = %(prev_handles + 1), "acquiring handle for InodeGuard");
163    }
164
165    pub fn drop_one_handle(&self) {
166        let prev_handles = self.open_handles.fetch_sub(1, Ordering::SeqCst);
167
168        trace!(ino = %self.ino.0, %prev_handles, "dropping handle for InodeGuard");
169
170        // If this wasn't the last handle, nothing else to do...
171        if prev_handles > 1 {
172            return;
173        }
174
175        // ... otherwise, drop the VirtualFile reference
176        let mut guard = self.inner.write();
177
178        // Must have at least one open handle before we can drop.
179        // This check happens after `inner` is locked so we can
180        // poison the lock and keep people from using this (possibly
181        // corrupt) InodeGuard.
182        if prev_handles != 1 {
183            panic!("InodeGuard handle dropped too many times");
184        }
185
186        // Re-check the open handles to account for race conditions
187        if self.open_handles.load(Ordering::SeqCst) != 0 {
188            return;
189        }
190
191        let ino = self.ino.0;
192        trace!(%ino, "InodeGuard has no more open handles");
193
194        match guard.deref_mut() {
195            Kind::File { handle, .. } if handle.is_some() => {
196                let file_ref_count = Arc::strong_count(handle.as_ref().unwrap());
197                trace!(%file_ref_count, %ino, "dropping file handle");
198                drop(handle.take().unwrap());
199            }
200            Kind::PipeRx { rx } => {
201                trace!(%ino, "closing pipe rx");
202                rx.close();
203            }
204            Kind::PipeTx { tx } => {
205                trace!(%ino, "closing pipe tx");
206                tx.close();
207            }
208            _ => (),
209        }
210    }
211}
212impl std::ops::Deref for InodeGuard {
213    type Target = InodeVal;
214    fn deref(&self) -> &Self::Target {
215        self.inner.deref()
216    }
217}
218
219#[derive(Debug, Clone)]
220pub struct InodeWeakGuard {
221    ino: Inode,
222    // Needed for when we want to upgrade back. We don't exactly
223    // care too much when the AtomicI32 is dropped, so this is
224    // a strong reference to keep things simple.
225    open_handles: Arc<AtomicI32>,
226    inner: Weak<InodeVal>,
227}
228impl InodeWeakGuard {
229    pub fn ino(&self) -> Inode {
230        self.ino
231    }
232    pub fn upgrade(&self) -> Option<InodeGuard> {
233        Weak::upgrade(&self.inner).map(|inner| InodeGuard {
234            ino: self.ino,
235            open_handles: self.open_handles.clone(),
236            inner,
237        })
238    }
239}
240
241#[derive(Debug)]
242#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
243struct EphemeralSymlinkEntry {
244    base_po_dir: WasiFd,
245    path_to_symlink: PathBuf,
246    relative_path: PathBuf,
247}
248
249#[derive(Debug)]
250#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
251struct WasiInodesProtected {
252    lookup: HashMap<Inode, Weak<InodeVal>>,
253}
254
255#[derive(Clone, Debug)]
256#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
257pub struct WasiInodes {
258    protected: Arc<RwLock<WasiInodesProtected>>,
259}
260
261fn normalize_virtual_symlink_key(path: &Path) -> PathBuf {
262    let mut normalized = PathBuf::new();
263    for component in path.components() {
264        match component {
265            Component::RootDir => normalized.push("/"),
266            Component::CurDir => {}
267            Component::ParentDir => {
268                if !normalized.as_os_str().is_empty() && normalized.as_os_str() != "/" {
269                    normalized.pop();
270                }
271            }
272            Component::Normal(seg) => normalized.push(seg),
273            Component::Prefix(_) => {}
274        }
275    }
276    if normalized.as_os_str().is_empty() {
277        PathBuf::from("/")
278    } else {
279        normalized
280    }
281}
282
283impl WasiInodes {
284    pub fn new() -> Self {
285        Self {
286            protected: Arc::new(RwLock::new(WasiInodesProtected {
287                lookup: Default::default(),
288            })),
289        }
290    }
291
292    /// adds another value to the inodes
293    pub fn add_inode_val(&self, val: InodeVal) -> InodeGuard {
294        let val = Arc::new(val);
295        let st_ino = {
296            let guard = val.stat.read().unwrap();
297            guard.st_ino
298        };
299
300        let mut guard = self.protected.write().unwrap();
301        let ino = Inode(st_ino);
302        guard.lookup.insert(ino, Arc::downgrade(&val));
303
304        // every 100 calls we clear out dead weaks
305        if guard.lookup.len() % 100 == 1 {
306            guard.lookup.retain(|_, v| Weak::strong_count(v) > 0);
307        }
308
309        let open_handles = Arc::new(AtomicI32::new(0));
310
311        InodeGuard {
312            ino,
313            open_handles,
314            inner: val,
315        }
316    }
317
318    /// Get the `VirtualFile` object at stdout
319    pub(crate) fn stdout(fd_map: &RwLock<FdList>) -> Result<InodeValFileReadGuard, FsError> {
320        Self::std_dev_get(fd_map, __WASI_STDOUT_FILENO)
321    }
322    /// Get the `VirtualFile` object at stdout mutably
323    pub(crate) fn stdout_mut(fd_map: &RwLock<FdList>) -> Result<InodeValFileWriteGuard, FsError> {
324        Self::std_dev_get_mut(fd_map, __WASI_STDOUT_FILENO)
325    }
326
327    /// Get the `VirtualFile` object at stderr
328    pub(crate) fn stderr(fd_map: &RwLock<FdList>) -> Result<InodeValFileReadGuard, FsError> {
329        Self::std_dev_get(fd_map, __WASI_STDERR_FILENO)
330    }
331    /// Get the `VirtualFile` object at stderr mutably
332    pub(crate) fn stderr_mut(fd_map: &RwLock<FdList>) -> Result<InodeValFileWriteGuard, FsError> {
333        Self::std_dev_get_mut(fd_map, __WASI_STDERR_FILENO)
334    }
335
336    /// Get the `VirtualFile` object at stdin
337    /// TODO: Review why this is dead
338    #[allow(dead_code)]
339    pub(crate) fn stdin(fd_map: &RwLock<FdList>) -> Result<InodeValFileReadGuard, FsError> {
340        Self::std_dev_get(fd_map, __WASI_STDIN_FILENO)
341    }
342    /// Get the `VirtualFile` object at stdin mutably
343    pub(crate) fn stdin_mut(fd_map: &RwLock<FdList>) -> Result<InodeValFileWriteGuard, FsError> {
344        Self::std_dev_get_mut(fd_map, __WASI_STDIN_FILENO)
345    }
346
347    /// Internal helper function to get a standard device handle.
348    /// Expects one of `__WASI_STDIN_FILENO`, `__WASI_STDOUT_FILENO`, `__WASI_STDERR_FILENO`.
349    fn std_dev_get(fd_map: &RwLock<FdList>, fd: WasiFd) -> Result<InodeValFileReadGuard, FsError> {
350        if let Some(fd) = fd_map.read().unwrap().get(fd) {
351            let guard = fd.inode.read();
352            if let Kind::File {
353                handle: Some(handle),
354                ..
355            } = guard.deref()
356            {
357                Ok(InodeValFileReadGuard::new(handle))
358            } else {
359                // Our public API should ensure that this is not possible
360                Err(FsError::NotAFile)
361            }
362        } else {
363            // this should only trigger if we made a mistake in this crate
364            Err(FsError::NoDevice)
365        }
366    }
367    /// Internal helper function to mutably get a standard device handle.
368    /// Expects one of `__WASI_STDIN_FILENO`, `__WASI_STDOUT_FILENO`, `__WASI_STDERR_FILENO`.
369    fn std_dev_get_mut(
370        fd_map: &RwLock<FdList>,
371        fd: WasiFd,
372    ) -> Result<InodeValFileWriteGuard, FsError> {
373        if let Some(fd) = fd_map.read().unwrap().get(fd) {
374            let guard = fd.inode.read();
375            if let Kind::File {
376                handle: Some(handle),
377                ..
378            } = guard.deref()
379            {
380                Ok(InodeValFileWriteGuard::new(handle))
381            } else {
382                // Our public API should ensure that this is not possible
383                Err(FsError::NotAFile)
384            }
385        } else {
386            // this should only trigger if we made a mistake in this crate
387            Err(FsError::NoDevice)
388        }
389    }
390}
391
392impl Default for WasiInodes {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398#[derive(Debug, Clone)]
399pub enum WasiFsRoot {
400    Sandbox(TmpFileSystem),
401    /// Dedicated canonical overlay representation.
402    ///
403    /// Overlays are the common form of the file system for WASIX packages.
404    /// Dependencies are all added to the overlay, with the regular file system
405    /// as the foundation.
406    ///
407    /// This dedicated variant is necessary to norm the behaviour and prevent
408    /// redundant recursive merging of filesystems when additional dependencies
409    /// are added.
410    Overlay(
411        Arc<
412            virtual_fs::OverlayFileSystem<
413                TmpFileSystem,
414                [RelativeOrAbsolutePathHack<UnionFileSystem>; 1],
415            >,
416        >,
417    ),
418    Backing(Arc<dyn FileSystem + Send + Sync>),
419}
420
421impl FileSystem for WasiFsRoot {
422    fn readlink(&self, path: &Path) -> virtual_fs::Result<PathBuf> {
423        match self {
424            Self::Sandbox(fs) => fs.readlink(path),
425            Self::Overlay(overlay) => overlay.readlink(path),
426            Self::Backing(fs) => fs.readlink(path),
427        }
428    }
429
430    fn read_dir(&self, path: &Path) -> virtual_fs::Result<virtual_fs::ReadDir> {
431        match self {
432            Self::Sandbox(fs) => fs.read_dir(path),
433            Self::Overlay(overlay) => overlay.read_dir(path),
434            Self::Backing(fs) => fs.read_dir(path),
435        }
436    }
437
438    fn create_dir(&self, path: &Path) -> virtual_fs::Result<()> {
439        match self {
440            Self::Sandbox(fs) => fs.create_dir(path),
441            Self::Overlay(overlay) => overlay.create_dir(path),
442            Self::Backing(fs) => fs.create_dir(path),
443        }
444    }
445
446    fn remove_dir(&self, path: &Path) -> virtual_fs::Result<()> {
447        match self {
448            Self::Sandbox(fs) => fs.remove_dir(path),
449            Self::Overlay(overlay) => overlay.remove_dir(path),
450            Self::Backing(fs) => fs.remove_dir(path),
451        }
452    }
453
454    fn rename<'a>(&'a self, from: &Path, to: &Path) -> BoxFuture<'a, virtual_fs::Result<()>> {
455        let from = from.to_owned();
456        let to = to.to_owned();
457        let this = self.clone();
458        Box::pin(async move {
459            match this {
460                Self::Sandbox(fs) => fs.rename(&from, &to).await,
461                Self::Overlay(overlay) => overlay.rename(&from, &to).await,
462                Self::Backing(fs) => fs.rename(&from, &to).await,
463            }
464        })
465    }
466
467    fn metadata(&self, path: &Path) -> virtual_fs::Result<virtual_fs::Metadata> {
468        match self {
469            Self::Sandbox(fs) => fs.metadata(path),
470            Self::Overlay(overlay) => overlay.metadata(path),
471            Self::Backing(fs) => fs.metadata(path),
472        }
473    }
474
475    fn symlink_metadata(&self, path: &Path) -> virtual_fs::Result<virtual_fs::Metadata> {
476        match self {
477            Self::Sandbox(fs) => fs.symlink_metadata(path),
478            Self::Overlay(overlay) => overlay.symlink_metadata(path),
479            Self::Backing(fs) => fs.symlink_metadata(path),
480        }
481    }
482
483    fn remove_file(&self, path: &Path) -> virtual_fs::Result<()> {
484        match self {
485            Self::Sandbox(fs) => fs.remove_file(path),
486            Self::Overlay(overlay) => overlay.remove_file(path),
487            Self::Backing(fs) => fs.remove_file(path),
488        }
489    }
490
491    fn new_open_options(&self) -> OpenOptions<'_> {
492        match self {
493            Self::Sandbox(fs) => fs.new_open_options(),
494            Self::Overlay(overlay) => overlay.new_open_options(),
495            Self::Backing(fs) => fs.new_open_options(),
496        }
497    }
498
499    fn mount(
500        &self,
501        name: String,
502        path: &Path,
503        fs: Box<dyn FileSystem + Send + Sync>,
504    ) -> virtual_fs::Result<()> {
505        match self {
506            Self::Sandbox(root) => FileSystem::mount(root, name, path, fs),
507            Self::Overlay(overlay) => FileSystem::mount(overlay.primary(), name, path, fs),
508            Self::Backing(f) => f.mount(name, path, fs),
509        }
510    }
511}
512
513/// Merge the contents of one filesystem into another.
514///
515/// NOTE: merging is a very expensive operation, since it requires copying
516/// many files in memory, even if the underlying files are immutable and
517/// mapped through mmap or similar mechanisms.
518/// Merging should be avoided when possible.
519#[tracing::instrument(level = "trace", skip_all)]
520async fn merge_filesystems(
521    source: &dyn FileSystem,
522    destination: &dyn FileSystem,
523) -> Result<(), virtual_fs::FsError> {
524    tracing::warn!("Falling back to a recursive copy to merge filesystems");
525    let files = futures::stream::FuturesUnordered::new();
526
527    let mut to_check = VecDeque::new();
528    to_check.push_back(PathBuf::from("/"));
529
530    while let Some(path) = to_check.pop_front() {
531        let metadata = match source.metadata(&path) {
532            Ok(m) => m,
533            Err(err) => {
534                tracing::debug!(path=%path.display(), source_fs=?source, ?err, "failed to get metadata for path while merging file systems");
535                return Err(err);
536            }
537        };
538
539        if metadata.is_dir() {
540            create_dir_all(destination, &path)?;
541
542            for entry in source.read_dir(&path)? {
543                let entry = entry?;
544                to_check.push_back(entry.path);
545            }
546        } else if metadata.is_file() {
547            files.push(async move {
548                copy_reference(source, destination, &path)
549                    .await
550                    .map_err(virtual_fs::FsError::from)
551            });
552        } else {
553            tracing::debug!(
554                path=%path.display(),
555                ?metadata,
556                "Skipping unknown file type while merging"
557            );
558        }
559    }
560
561    files.try_collect().await
562}
563
564fn create_dir_all(fs: &dyn FileSystem, path: &Path) -> Result<(), virtual_fs::FsError> {
565    if fs.metadata(path).is_ok() {
566        return Ok(());
567    }
568
569    if let Some(parent) = path.parent() {
570        create_dir_all(fs, parent)?;
571    }
572
573    fs.create_dir(path)?;
574
575    Ok(())
576}
577
578/// Warning, modifying these fields directly may cause invariants to break and
579/// should be considered unsafe.  These fields may be made private in a future release
580#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
581pub struct WasiFs {
582    //pub repo: Repo,
583    pub preopen_fds: RwLock<Vec<u32>>,
584    pub fd_map: RwLock<FdList>,
585    pub current_dir: Mutex<String>,
586    #[cfg_attr(feature = "enable-serde", serde(skip, default))]
587    pub root_fs: WasiFsRoot,
588    pub root_inode: InodeGuard,
589    pub has_unioned: Mutex<HashSet<PackageId>>,
590    ephemeral_symlinks: Arc<RwLock<HashMap<PathBuf, EphemeralSymlinkEntry>>>,
591
592    // TODO: remove
593    // using an atomic is a hack to enable customization after construction,
594    // but it shouldn't be necessary
595    // It should not be necessary at all.
596    is_wasix: AtomicBool,
597
598    // The preopens when this was initialized
599    pub(crate) init_preopens: Vec<PreopenedDir>,
600    // The virtual file system preopens when this was initialized
601    pub(crate) init_vfs_preopens: Vec<String>,
602}
603
604impl WasiFs {
605    pub fn is_wasix(&self) -> bool {
606        // NOTE: this will only be set once very early in the instance lifetime,
607        // so Relaxed should be okay.
608        self.is_wasix.load(Ordering::Relaxed)
609    }
610
611    pub fn set_is_wasix(&self, is_wasix: bool) {
612        self.is_wasix.store(is_wasix, Ordering::SeqCst);
613    }
614
615    pub(crate) fn register_ephemeral_symlink(
616        &self,
617        full_path: PathBuf,
618        base_po_dir: WasiFd,
619        path_to_symlink: PathBuf,
620        relative_path: PathBuf,
621    ) {
622        let mut guard = self.ephemeral_symlinks.write().unwrap();
623        guard.insert(
624            normalize_virtual_symlink_key(&full_path),
625            EphemeralSymlinkEntry {
626                base_po_dir,
627                path_to_symlink: normalize_virtual_symlink_key(&path_to_symlink),
628                relative_path,
629            },
630        );
631    }
632
633    pub(crate) fn ephemeral_symlink_at(
634        &self,
635        full_path: &Path,
636    ) -> Option<(WasiFd, PathBuf, PathBuf)> {
637        let guard = self.ephemeral_symlinks.read().unwrap();
638        let entry = guard.get(&normalize_virtual_symlink_key(full_path))?;
639        Some((
640            entry.base_po_dir,
641            entry.path_to_symlink.clone(),
642            entry.relative_path.clone(),
643        ))
644    }
645
646    pub(crate) fn unregister_ephemeral_symlink(&self, full_path: &Path) {
647        let mut guard = self.ephemeral_symlinks.write().unwrap();
648        guard.remove(&normalize_virtual_symlink_key(full_path));
649    }
650
651    pub(crate) fn move_ephemeral_symlink(
652        &self,
653        old_full_path: &Path,
654        new_full_path: &Path,
655        base_po_dir: WasiFd,
656        path_to_symlink: PathBuf,
657        relative_path: PathBuf,
658    ) {
659        let old_key = normalize_virtual_symlink_key(old_full_path);
660        let new_key = normalize_virtual_symlink_key(new_full_path);
661
662        let mut guard = self.ephemeral_symlinks.write().unwrap();
663        guard.remove(&old_key);
664        guard.insert(
665            new_key,
666            EphemeralSymlinkEntry {
667                base_po_dir,
668                path_to_symlink: normalize_virtual_symlink_key(&path_to_symlink),
669                relative_path,
670            },
671        );
672    }
673
674    /// Forking the WasiState is used when either fork or vfork is called
675    pub fn fork(&self) -> Self {
676        Self {
677            preopen_fds: RwLock::new(self.preopen_fds.read().unwrap().clone()),
678            fd_map: RwLock::new(self.fd_map.read().unwrap().clone()),
679            current_dir: Mutex::new(self.current_dir.lock().unwrap().clone()),
680            is_wasix: AtomicBool::new(self.is_wasix.load(Ordering::Acquire)),
681            root_fs: self.root_fs.clone(),
682            root_inode: self.root_inode.clone(),
683            has_unioned: Mutex::new(self.has_unioned.lock().unwrap().clone()),
684            ephemeral_symlinks: self.ephemeral_symlinks.clone(),
685            init_preopens: self.init_preopens.clone(),
686            init_vfs_preopens: self.init_vfs_preopens.clone(),
687        }
688    }
689
690    /// Closes all the file handles.
691    pub async fn close_cloexec_fds(&self) {
692        let to_close = {
693            if let Ok(map) = self.fd_map.read() {
694                map.iter()
695                    .filter_map(|(k, v)| {
696                        if v.inner.fd_flags.contains(Fdflagsext::CLOEXEC)
697                            && !v.is_stdio
698                            && !v.inode.is_preopened
699                        {
700                            tracing::trace!(fd = %k, "Closing FD due to CLOEXEC flag");
701                            Some(k)
702                        } else {
703                            None
704                        }
705                    })
706                    .collect::<HashSet<_>>()
707            } else {
708                HashSet::new()
709            }
710        };
711
712        let _ = tokio::join!(async {
713            for fd in &to_close {
714                self.flush(*fd).await.ok();
715                self.close_fd(*fd).ok();
716            }
717        });
718
719        if let Ok(mut map) = self.fd_map.write() {
720            for fd in &to_close {
721                map.remove(*fd);
722            }
723        }
724    }
725
726    /// Closes all the file handles.
727    pub async fn close_all(&self) {
728        let mut to_close = {
729            if let Ok(map) = self.fd_map.read() {
730                map.keys().collect::<HashSet<_>>()
731            } else {
732                HashSet::new()
733            }
734        };
735        to_close.insert(__WASI_STDOUT_FILENO);
736        to_close.insert(__WASI_STDERR_FILENO);
737
738        let _ = tokio::join!(async {
739            for fd in to_close {
740                self.flush(fd).await.ok();
741                self.close_fd(fd).ok();
742            }
743        });
744
745        if let Ok(mut map) = self.fd_map.write() {
746            map.clear();
747        }
748    }
749
750    /// Will conditionally union the binary file system with this one
751    /// if it has not already been unioned
752    pub async fn conditional_union(
753        &self,
754        binary: &BinaryPackage,
755    ) -> Result<(), virtual_fs::FsError> {
756        let Some(webc_fs) = &binary.webc_fs else {
757            return Ok(());
758        };
759
760        let needs_to_be_unioned = self.has_unioned.lock().unwrap().insert(binary.id.clone());
761        if !needs_to_be_unioned {
762            return Ok(());
763        }
764
765        match &self.root_fs {
766            WasiFsRoot::Sandbox(fs) => {
767                // TODO: this can be changed to switch to Self::Overlay instead!
768                let fdyn: Arc<dyn FileSystem + Send + Sync> = webc_fs.clone();
769                fs.union(&fdyn);
770                Ok(())
771            }
772            WasiFsRoot::Overlay(overlay) => {
773                let union = &overlay.secondaries()[0];
774                union.0.merge(webc_fs, virtual_fs::UnionMergeMode::Skip)
775            }
776            WasiFsRoot::Backing(backing) => merge_filesystems(webc_fs, backing).await,
777        }
778    }
779
780    /// Created for the builder API. like `new` but with more information
781    pub(crate) fn new_with_preopen(
782        inodes: &WasiInodes,
783        preopens: &[PreopenedDir],
784        vfs_preopens: &[String],
785        fs_backing: WasiFsRoot,
786    ) -> Result<Self, String> {
787        let mut wasi_fs = Self::new_init(fs_backing, inodes, FS_ROOT_INO)?;
788        wasi_fs.init_preopens = preopens.to_vec();
789        wasi_fs.init_vfs_preopens = vfs_preopens.to_vec();
790        wasi_fs.create_preopens(inodes, false)?;
791        Ok(wasi_fs)
792    }
793
794    /// Converts a relative path into an absolute path
795    pub(crate) fn relative_path_to_absolute(&self, path: String) -> String {
796        if path.starts_with('/') {
797            return path;
798        }
799
800        let current_dir = self.current_dir.lock().unwrap();
801        format!("{}/{}", current_dir.trim_end_matches('/'), path)
802    }
803
804    /// Private helper function to init the filesystem, called in `new` and
805    /// `new_with_preopen`
806    fn new_init(
807        fs_backing: WasiFsRoot,
808        inodes: &WasiInodes,
809        st_ino: Inode,
810    ) -> Result<Self, String> {
811        debug!("Initializing WASI filesystem");
812
813        let stat = Filestat {
814            st_filetype: Filetype::Directory,
815            st_ino: st_ino.as_u64(),
816            ..Filestat::default()
817        };
818        let root_kind = Kind::Root {
819            entries: HashMap::new(),
820        };
821        let root_inode = inodes.add_inode_val(InodeVal {
822            stat: RwLock::new(stat),
823            is_preopened: true,
824            name: RwLock::new("/".into()),
825            kind: RwLock::new(root_kind),
826        });
827
828        let wasi_fs = Self {
829            preopen_fds: RwLock::new(vec![]),
830            fd_map: RwLock::new(FdList::new()),
831            current_dir: Mutex::new("/".to_string()),
832            is_wasix: AtomicBool::new(false),
833            root_fs: fs_backing,
834            root_inode,
835            has_unioned: Mutex::new(HashSet::new()),
836            ephemeral_symlinks: Arc::new(RwLock::new(HashMap::new())),
837            init_preopens: Default::default(),
838            init_vfs_preopens: Default::default(),
839        };
840        wasi_fs.create_stdin(inodes);
841        wasi_fs.create_stdout(inodes);
842        wasi_fs.create_stderr(inodes);
843        wasi_fs.create_rootfd()?;
844
845        Ok(wasi_fs)
846    }
847
848    /// This function is like create dir all, but it also opens it.
849    /// Function is unsafe because it may break invariants and hasn't been tested.
850    /// This is an experimental function and may be removed
851    ///
852    /// # Safety
853    /// - Virtual directories created with this function must not conflict with
854    ///   the standard operation of the WASI filesystem.  This is vague and
855    ///   unlikely in pratice.  [Join the discussion](https://github.com/wasmerio/wasmer/issues/1219)
856    ///   for what the newer, safer WASI FS APIs should look like.
857    #[allow(dead_code)]
858    #[allow(clippy::too_many_arguments)]
859    pub unsafe fn open_dir_all(
860        &mut self,
861        inodes: &WasiInodes,
862        base: WasiFd,
863        name: String,
864        rights: Rights,
865        rights_inheriting: Rights,
866        flags: Fdflags,
867        fd_flags: Fdflagsext,
868    ) -> Result<WasiFd, FsError> {
869        // TODO: check permissions here? probably not, but this should be
870        // an explicit choice, so justify it in a comment when we remove this one
871        let mut cur_inode = self.get_fd_inode(base).map_err(fs_error_from_wasi_err)?;
872
873        let path: &Path = Path::new(&name);
874        //let n_components = path.components().count();
875        for c in path.components() {
876            let segment_name = c.as_os_str().to_string_lossy().to_string();
877            let guard = cur_inode.read();
878            match guard.deref() {
879                Kind::Dir { entries, .. } | Kind::Root { entries } => {
880                    if let Some(_entry) = entries.get(&segment_name) {
881                        // TODO: this should be fixed
882                        return Err(FsError::AlreadyExists);
883                    }
884
885                    let kind = Kind::Dir {
886                        parent: cur_inode.downgrade(),
887                        path: PathBuf::from(""),
888                        entries: HashMap::new(),
889                    };
890
891                    drop(guard);
892                    let inode = self.create_inode_with_default_stat(
893                        inodes,
894                        kind,
895                        false,
896                        segment_name.clone().into(),
897                    );
898
899                    // reborrow to insert
900                    {
901                        let mut guard = cur_inode.write();
902                        match guard.deref_mut() {
903                            Kind::Dir { entries, .. } | Kind::Root { entries } => {
904                                entries.insert(segment_name, inode.clone());
905                            }
906                            _ => unreachable!("Dir or Root became not Dir or Root"),
907                        }
908                    }
909                    cur_inode = inode;
910                }
911                _ => return Err(FsError::BaseNotDirectory),
912            }
913        }
914
915        // TODO: review open flags (read, write); they were added without consideration
916        self.create_fd(
917            rights,
918            rights_inheriting,
919            flags,
920            fd_flags,
921            Fd::READ | Fd::WRITE,
922            cur_inode,
923        )
924        .map_err(fs_error_from_wasi_err)
925    }
926
927    /// Opens a user-supplied file in the directory specified with the
928    /// name and flags given
929    // dead code because this is an API for external use
930    // TODO: is this used anywhere? Is it even sound?
931    #[allow(dead_code, clippy::too_many_arguments)]
932    pub fn open_file_at(
933        &mut self,
934        inodes: &WasiInodes,
935        base: WasiFd,
936        file: Box<dyn VirtualFile + Send + Sync + 'static>,
937        open_flags: u16,
938        name: String,
939        rights: Rights,
940        rights_inheriting: Rights,
941        flags: Fdflags,
942        fd_flags: Fdflagsext,
943    ) -> Result<WasiFd, FsError> {
944        // TODO: check permissions here? probably not, but this should be
945        // an explicit choice, so justify it in a comment when we remove this one
946        let base_inode = self.get_fd_inode(base).map_err(fs_error_from_wasi_err)?;
947
948        let guard = base_inode.read();
949        match guard.deref() {
950            Kind::Dir { entries, .. } | Kind::Root { entries } => {
951                if let Some(_entry) = entries.get(&name) {
952                    // TODO: eventually change the logic here to allow overwrites
953                    return Err(FsError::AlreadyExists);
954                }
955
956                let kind = Kind::File {
957                    handle: Some(Arc::new(RwLock::new(file))),
958                    path: PathBuf::from(""),
959                    fd: None,
960                };
961
962                drop(guard);
963                let inode = self
964                    .create_inode(inodes, kind, false, name.clone())
965                    .map_err(|_| FsError::IOError)?;
966
967                {
968                    let mut guard = base_inode.write();
969                    match guard.deref_mut() {
970                        Kind::Dir { entries, .. } | Kind::Root { entries } => {
971                            entries.insert(name, inode.clone());
972                        }
973                        _ => unreachable!("Dir or Root became not Dir or Root"),
974                    }
975                }
976
977                // Here, we clone the inode so we can use it to overwrite the fd field below.
978                let real_fd = self
979                    .create_fd(
980                        rights,
981                        rights_inheriting,
982                        flags,
983                        fd_flags,
984                        open_flags,
985                        inode.clone(),
986                    )
987                    .map_err(fs_error_from_wasi_err)?;
988
989                {
990                    let mut guard = inode.kind.write().unwrap();
991                    match guard.deref_mut() {
992                        Kind::File { fd, .. } => {
993                            *fd = Some(real_fd);
994                        }
995                        _ => unreachable!("We just created a Kind::File"),
996                    }
997                }
998
999                Ok(real_fd)
1000            }
1001            _ => Err(FsError::BaseNotDirectory),
1002        }
1003    }
1004
1005    /// Change the backing of a given file descriptor
1006    /// Returns the old backing
1007    /// TODO: add examples
1008    #[allow(dead_code)]
1009    pub fn swap_file(
1010        &self,
1011        fd: WasiFd,
1012        mut file: Box<dyn VirtualFile + Send + Sync + 'static>,
1013    ) -> Result<Option<Box<dyn VirtualFile + Send + Sync + 'static>>, FsError> {
1014        match fd {
1015            __WASI_STDIN_FILENO => {
1016                let mut target = WasiInodes::stdin_mut(&self.fd_map)?;
1017                Ok(Some(target.swap(file)))
1018            }
1019            __WASI_STDOUT_FILENO => {
1020                let mut target = WasiInodes::stdout_mut(&self.fd_map)?;
1021                Ok(Some(target.swap(file)))
1022            }
1023            __WASI_STDERR_FILENO => {
1024                let mut target = WasiInodes::stderr_mut(&self.fd_map)?;
1025                Ok(Some(target.swap(file)))
1026            }
1027            _ => {
1028                let base_inode = self.get_fd_inode(fd).map_err(fs_error_from_wasi_err)?;
1029                {
1030                    // happy path
1031                    let guard = base_inode.read();
1032                    match guard.deref() {
1033                        Kind::File { handle, .. } => {
1034                            if let Some(handle) = handle {
1035                                let mut handle = handle.write().unwrap();
1036                                std::mem::swap(handle.deref_mut(), &mut file);
1037                                return Ok(Some(file));
1038                            }
1039                        }
1040                        _ => return Err(FsError::NotAFile),
1041                    }
1042                }
1043                // slow path
1044                let mut guard = base_inode.write();
1045                match guard.deref_mut() {
1046                    Kind::File { handle, .. } => {
1047                        if let Some(handle) = handle {
1048                            let mut handle = handle.write().unwrap();
1049                            std::mem::swap(handle.deref_mut(), &mut file);
1050                            Ok(Some(file))
1051                        } else {
1052                            handle.replace(Arc::new(RwLock::new(file)));
1053                            Ok(None)
1054                        }
1055                    }
1056                    _ => Err(FsError::NotAFile),
1057                }
1058            }
1059        }
1060    }
1061
1062    /// refresh size from filesystem
1063    pub fn filestat_resync_size(&self, fd: WasiFd) -> Result<Filesize, Errno> {
1064        let inode = self.get_fd_inode(fd)?;
1065        let mut guard = inode.write();
1066        match guard.deref_mut() {
1067            Kind::File { handle, .. } => {
1068                if let Some(h) = handle {
1069                    let h = h.read().unwrap();
1070                    let new_size = h.size();
1071                    drop(h);
1072                    drop(guard);
1073
1074                    inode.stat.write().unwrap().st_size = new_size;
1075                    Ok(new_size as Filesize)
1076                } else {
1077                    Err(Errno::Badf)
1078                }
1079            }
1080            Kind::Dir { .. } | Kind::Root { .. } => Err(Errno::Isdir),
1081            _ => Err(Errno::Inval),
1082        }
1083    }
1084
1085    /// Changes the current directory
1086    pub fn set_current_dir(&self, path: &str) {
1087        let mut guard = self.current_dir.lock().unwrap();
1088        *guard = path.to_string();
1089    }
1090
1091    /// Gets the current directory
1092    pub fn get_current_dir(
1093        &self,
1094        inodes: &WasiInodes,
1095        base: WasiFd,
1096    ) -> Result<(InodeGuard, String), Errno> {
1097        self.get_current_dir_inner(inodes, base, 0)
1098    }
1099
1100    pub(crate) fn get_current_dir_inner(
1101        &self,
1102        inodes: &WasiInodes,
1103        base: WasiFd,
1104        symlink_count: u32,
1105    ) -> Result<(InodeGuard, String), Errno> {
1106        let current_dir = {
1107            let guard = self.current_dir.lock().unwrap();
1108            guard.clone()
1109        };
1110        let cur_inode = self.get_fd_inode(base)?;
1111        let inode = self.get_inode_at_path_inner(
1112            inodes,
1113            cur_inode,
1114            current_dir.as_str(),
1115            symlink_count,
1116            true,
1117        )?;
1118        Ok((inode, current_dir))
1119    }
1120
1121    /// Internal part of the core path resolution function which implements path
1122    /// traversal logic such as resolving relative path segments (such as
1123    /// `.` and `..`) and resolving symlinks (while preventing infinite
1124    /// loops/stack overflows).
1125    ///
1126    /// TODO: expand upon exactly what the state of the returned value is,
1127    /// explaining lazy-loading from the real file system and synchronizing
1128    /// between them.
1129    ///
1130    /// This is where a lot of the magic happens, be very careful when editing
1131    /// this code.
1132    ///
1133    /// TODO: write more tests for this code
1134    fn get_inode_at_path_inner(
1135        &self,
1136        inodes: &WasiInodes,
1137        mut cur_inode: InodeGuard,
1138        path_str: &str,
1139        mut symlink_count: u32,
1140        follow_symlinks: bool,
1141    ) -> Result<InodeGuard, Errno> {
1142        if symlink_count > MAX_SYMLINKS {
1143            return Err(Errno::Mlink);
1144        }
1145
1146        let path: &Path = Path::new(path_str);
1147        let n_components = path.components().count();
1148
1149        // TODO: rights checks
1150        'path_iter: for (i, component) in path.components().enumerate() {
1151            // Since we're resolving the path against the given inode, we want to
1152            // assume '/a/b' to be the same as `a/b` relative to the inode, so
1153            // we skip over the RootDir component.
1154            if matches!(component, Component::RootDir) {
1155                continue;
1156            }
1157
1158            // used to terminate symlink resolution properly
1159            let last_component = i + 1 == n_components;
1160            // for each component traverse file structure
1161            // loading inodes as necessary
1162            'symlink_resolution: while symlink_count < MAX_SYMLINKS {
1163                let processing_cur_inode = cur_inode.clone();
1164                let mut guard = processing_cur_inode.write();
1165                match guard.deref_mut() {
1166                    Kind::Buffer { .. } => unimplemented!("state::get_inode_at_path for buffers"),
1167                    Kind::Dir {
1168                        entries,
1169                        path,
1170                        parent,
1171                        ..
1172                    } => {
1173                        match component.as_os_str().to_string_lossy().borrow() {
1174                            ".." => {
1175                                if let Some(p) = parent.upgrade() {
1176                                    cur_inode = p;
1177                                    continue 'path_iter;
1178                                } else {
1179                                    return Err(Errno::Access);
1180                                }
1181                            }
1182                            "." => continue 'path_iter,
1183                            _ => (),
1184                        }
1185                        // used for full resolution of symlinks
1186                        let mut loop_for_symlink = false;
1187                        if let Some(entry) =
1188                            entries.get(component.as_os_str().to_string_lossy().as_ref())
1189                        {
1190                            cur_inode = entry.clone();
1191                        } else {
1192                            let file = {
1193                                let mut cd = path.clone();
1194                                cd.push(component);
1195                                cd
1196                            };
1197                            // we want to insert newly opened dirs and files, but not transient symlinks
1198                            // TODO: explain why (think about this deeply when well rested)
1199                            let should_insert;
1200
1201                            let kind = if let Some((base_po_dir, path_to_symlink, relative_path)) =
1202                                self.ephemeral_symlink_at(&file)
1203                            {
1204                                // Ephemeral symlinks are transient records;
1205                                // we resolve them but don't cache them as dir entries.
1206                                should_insert = false;
1207                                loop_for_symlink = true;
1208                                symlink_count += 1;
1209                                Kind::Symlink {
1210                                    base_po_dir,
1211                                    path_to_symlink,
1212                                    relative_path,
1213                                }
1214                            } else {
1215                                let metadata = self
1216                                    .root_fs
1217                                    .symlink_metadata(&file)
1218                                    .ok()
1219                                    .ok_or(Errno::Noent)?;
1220                                let file_type = metadata.file_type();
1221                                if file_type.is_dir() {
1222                                    should_insert = true;
1223                                    // load DIR
1224                                    Kind::Dir {
1225                                        parent: cur_inode.downgrade(),
1226                                        path: file.clone(),
1227                                        entries: Default::default(),
1228                                    }
1229                                } else if file_type.is_file() {
1230                                    should_insert = true;
1231                                    // load file
1232                                    Kind::File {
1233                                        handle: None,
1234                                        path: file.clone(),
1235                                        fd: None,
1236                                    }
1237                                } else if file_type.is_symlink() {
1238                                    should_insert = false;
1239                                    let link_value =
1240                                        self.root_fs.readlink(&file).ok().ok_or(Errno::Noent)?;
1241                                    debug!("attempting to decompose path {:?}", link_value);
1242                                    let (pre_open_dir_fd, path_to_symlink) =
1243                                        self.path_into_pre_open_and_relative_path(&file)?;
1244                                    loop_for_symlink = true;
1245                                    symlink_count += 1;
1246                                    Kind::Symlink {
1247                                        base_po_dir: pre_open_dir_fd,
1248                                        path_to_symlink: path_to_symlink.to_owned(),
1249                                        relative_path: link_value,
1250                                    }
1251                                } else {
1252                                    #[cfg(unix)]
1253                                    {
1254                                        //use std::os::unix::fs::FileTypeExt;
1255                                        let file_type: Filetype = if file_type.is_char_device() {
1256                                            Filetype::CharacterDevice
1257                                        } else if file_type.is_block_device() {
1258                                            Filetype::BlockDevice
1259                                        } else if file_type.is_fifo() {
1260                                            // FIFO doesn't seem to fit any other type, so unknown
1261                                            Filetype::Unknown
1262                                        } else if file_type.is_socket() {
1263                                            // TODO: how do we know if it's a `SocketStream` or
1264                                            // a `SocketDgram`?
1265                                            Filetype::SocketStream
1266                                        } else {
1267                                            unimplemented!(
1268                                                "state::get_inode_at_path unknown file type: not file, directory, symlink, char device, block device, fifo, or socket"
1269                                            );
1270                                        };
1271
1272                                        let kind = Kind::File {
1273                                            handle: None,
1274                                            path: file.clone(),
1275                                            fd: None,
1276                                        };
1277                                        drop(guard);
1278                                        let new_inode = self.create_inode_with_stat(
1279                                            inodes,
1280                                            kind,
1281                                            false,
1282                                            file.to_string_lossy().to_string().into(),
1283                                            Filestat {
1284                                                st_filetype: file_type,
1285                                                st_ino: Inode::from_path(path_str).as_u64(),
1286                                                st_size: metadata.len(),
1287                                                st_ctim: metadata.created(),
1288                                                st_mtim: metadata.modified(),
1289                                                st_atim: metadata.accessed(),
1290                                                ..Filestat::default()
1291                                            },
1292                                        );
1293
1294                                        let mut guard = cur_inode.write();
1295                                        if let Kind::Dir { entries, .. } = guard.deref_mut() {
1296                                            entries.insert(
1297                                                component.as_os_str().to_string_lossy().to_string(),
1298                                                new_inode.clone(),
1299                                            );
1300                                        } else {
1301                                            unreachable!(
1302                                                "Attempted to insert special device into non-directory"
1303                                            );
1304                                        }
1305                                        // perhaps just continue with symlink resolution and return at the end
1306                                        return Ok(new_inode);
1307                                    }
1308                                    #[cfg(not(unix))]
1309                                    unimplemented!(
1310                                        "state::get_inode_at_path unknown file type: not file, directory, or symlink"
1311                                    );
1312                                }
1313                            };
1314                            drop(guard);
1315
1316                            let new_inode = self.create_inode(
1317                                inodes,
1318                                kind,
1319                                false,
1320                                file.to_string_lossy().to_string(),
1321                            )?;
1322                            if should_insert {
1323                                let mut guard = processing_cur_inode.write();
1324                                if let Kind::Dir { entries, .. } = guard.deref_mut() {
1325                                    entries.insert(
1326                                        component.as_os_str().to_string_lossy().to_string(),
1327                                        new_inode.clone(),
1328                                    );
1329                                }
1330                            }
1331                            cur_inode = new_inode;
1332
1333                            if loop_for_symlink && follow_symlinks {
1334                                debug!("Following symlink to {:?}", cur_inode);
1335                                continue 'symlink_resolution;
1336                            }
1337                        }
1338                    }
1339                    Kind::Root { entries } => {
1340                        match component {
1341                            // the root's parent is the root
1342                            Component::ParentDir => continue 'path_iter,
1343                            // the root's current directory is the root
1344                            Component::CurDir => continue 'path_iter,
1345                            _ => {}
1346                        }
1347
1348                        let component = component.as_os_str().to_string_lossy();
1349
1350                        if let Some(entry) = entries.get(component.as_ref()) {
1351                            cur_inode = entry.clone();
1352                        } else if let Some(root) = entries.get(&"/".to_string()) {
1353                            cur_inode = root.clone();
1354                            continue 'symlink_resolution;
1355                        } else {
1356                            // Root is not capable of having something other then preopenned folders
1357                            return Err(Errno::Notcapable);
1358                        }
1359                    }
1360                    Kind::File { .. }
1361                    | Kind::Socket { .. }
1362                    | Kind::PipeRx { .. }
1363                    | Kind::PipeTx { .. }
1364                    | Kind::DuplexPipe { .. }
1365                    | Kind::EventNotifications { .. }
1366                    | Kind::Epoll { .. } => {
1367                        return Err(Errno::Notdir);
1368                    }
1369                    Kind::Symlink {
1370                        base_po_dir,
1371                        path_to_symlink,
1372                        relative_path,
1373                    } => {
1374                        let (new_base_inode, new_path) = if relative_path.is_absolute() {
1375                            // Absolute symlink targets must resolve from the virtual root
1376                            // rather than from the directory containing the symlink.
1377                            (
1378                                self.get_fd_inode(VIRTUAL_ROOT_FD)?,
1379                                relative_path.to_string_lossy().to_string(),
1380                            )
1381                        } else {
1382                            let new_base_dir = *base_po_dir;
1383                            let new_base_inode = self.get_fd_inode(new_base_dir)?;
1384                            // allocate to reborrow mutabily to recur
1385                            let new_path = {
1386                                /*if let Kind::Root { .. } = self.inodes[base_po_dir].kind {
1387                                    assert!(false, "symlinks should never be relative to the root");
1388                                }*/
1389                                let mut base = path_to_symlink.clone();
1390                                // remove the symlink file itself from the path, leaving just the path from the base
1391                                // to the dir containing the symlink
1392                                base.pop();
1393                                base.push(relative_path);
1394                                base.to_string_lossy().to_string()
1395                            };
1396                            (new_base_inode, new_path)
1397                        };
1398                        debug!("Following symlink recursively");
1399                        drop(guard);
1400                        let symlink_inode = self.get_inode_at_path_inner(
1401                            inodes,
1402                            new_base_inode,
1403                            &new_path,
1404                            symlink_count + 1,
1405                            follow_symlinks,
1406                        )?;
1407                        cur_inode = symlink_inode;
1408                        // if we're at the very end and we found a file, then we're done
1409                        // TODO: figure out if this should also happen for directories?
1410                        let guard = cur_inode.read();
1411                        if let Kind::File { .. } = guard.deref() {
1412                            // check if on last step
1413                            if last_component {
1414                                break 'symlink_resolution;
1415                            }
1416                        }
1417                        continue 'symlink_resolution;
1418                    }
1419                }
1420                break 'symlink_resolution;
1421            }
1422        }
1423
1424        Ok(cur_inode)
1425    }
1426
1427    /// Finds the preopened directory that is the "best match" for the given path and
1428    /// returns a path relative to this preopened directory.
1429    ///
1430    /// The "best match" is the preopened directory that has the longest prefix of the
1431    /// given path. For example, given preopened directories [`a`, `a/b`, `a/c`] and
1432    /// the path `a/b/c/file`, we will return the fd corresponding to the preopened
1433    /// directory, `a/b` and the relative path `c/file`.
1434    ///
1435    /// In the case of a tie, the later preopened fd is preferred.
1436    fn path_into_pre_open_and_relative_path<'path>(
1437        &self,
1438        path: &'path Path,
1439    ) -> Result<(WasiFd, &'path Path), Errno> {
1440        enum BaseFdAndRelPath<'a> {
1441            None,
1442            BestMatch {
1443                fd: WasiFd,
1444                rel_path: &'a Path,
1445                max_seen: usize,
1446            },
1447        }
1448
1449        impl BaseFdAndRelPath<'_> {
1450            const fn max_seen(&self) -> usize {
1451                match self {
1452                    Self::None => 0,
1453                    Self::BestMatch { max_seen, .. } => *max_seen,
1454                }
1455            }
1456        }
1457        let mut res = BaseFdAndRelPath::None;
1458        // for each preopened directory
1459        let preopen_fds = self.preopen_fds.read().unwrap();
1460        for po_fd in preopen_fds.deref() {
1461            let po_inode = self
1462                .fd_map
1463                .read()
1464                .unwrap()
1465                .get(*po_fd)
1466                .unwrap()
1467                .inode
1468                .clone();
1469            let guard = po_inode.read();
1470            let po_path = match guard.deref() {
1471                Kind::Dir { path, .. } => &**path,
1472                Kind::Root { .. } => Path::new("/"),
1473                _ => unreachable!("Preopened FD that's not a directory or the root"),
1474            };
1475            // stem path based on it
1476            if let Ok(stripped_path) = path.strip_prefix(po_path) {
1477                // find the max
1478                let new_prefix_len = po_path.as_os_str().len();
1479                // we use >= to favor later preopens because we iterate in order
1480                // whereas WASI libc iterates in reverse to get this behavior.
1481                if new_prefix_len >= res.max_seen() {
1482                    res = BaseFdAndRelPath::BestMatch {
1483                        fd: *po_fd,
1484                        rel_path: stripped_path,
1485                        max_seen: new_prefix_len,
1486                    };
1487                }
1488            }
1489        }
1490        match res {
1491            // this error may not make sense depending on where it's called
1492            BaseFdAndRelPath::None => Err(Errno::Inval),
1493            BaseFdAndRelPath::BestMatch { fd, rel_path, .. } => Ok((fd, rel_path)),
1494        }
1495    }
1496
1497    pub(crate) fn path_into_pre_open_and_relative_path_owned(
1498        &self,
1499        path: &Path,
1500    ) -> Result<(WasiFd, PathBuf), Errno> {
1501        let (fd, rel_path) = self.path_into_pre_open_and_relative_path(path)?;
1502        Ok((fd, rel_path.to_owned()))
1503    }
1504
1505    /// gets a host file from a base directory and a path
1506    /// this function ensures the fs remains sandboxed
1507    // NOTE: follow symlinks is super weird right now
1508    // even if it's false, it still follows symlinks, just not the last
1509    // symlink so
1510    // This will be resolved when we have tests asserting the correct behavior
1511    pub(crate) fn get_inode_at_path(
1512        &self,
1513        inodes: &WasiInodes,
1514        base: WasiFd,
1515        path: &str,
1516        follow_symlinks: bool,
1517    ) -> Result<InodeGuard, Errno> {
1518        let base_inode = self.get_fd_inode(base)?;
1519        self.get_inode_at_path_inner(inodes, base_inode, path, 0, follow_symlinks)
1520    }
1521
1522    /// Returns the parent Dir or Root that the file at a given path is in and the file name
1523    /// stripped off
1524    pub(crate) fn get_parent_inode_at_path(
1525        &self,
1526        inodes: &WasiInodes,
1527        base: WasiFd,
1528        path: &Path,
1529        follow_symlinks: bool,
1530    ) -> Result<(InodeGuard, String), Errno> {
1531        let mut parent_dir = std::path::PathBuf::new();
1532        let mut components = path.components().rev();
1533        let new_entity_name = components
1534            .next()
1535            .ok_or(Errno::Inval)?
1536            .as_os_str()
1537            .to_string_lossy()
1538            .to_string();
1539        for comp in components.rev() {
1540            parent_dir.push(comp);
1541        }
1542        self.get_inode_at_path(inodes, base, &parent_dir.to_string_lossy(), follow_symlinks)
1543            .map(|v| (v, new_entity_name))
1544    }
1545
1546    pub fn get_fd(&self, fd: WasiFd) -> Result<Fd, Errno> {
1547        let ret = self
1548            .fd_map
1549            .read()
1550            .unwrap()
1551            .get(fd)
1552            .ok_or(Errno::Badf)
1553            .cloned();
1554
1555        if ret.is_err() && fd == VIRTUAL_ROOT_FD {
1556            Ok(Fd {
1557                inner: FdInner {
1558                    rights: ALL_RIGHTS,
1559                    rights_inheriting: ALL_RIGHTS,
1560                    flags: Fdflags::empty(),
1561                    offset: Arc::new(AtomicU64::new(0)),
1562                    fd_flags: Fdflagsext::empty(),
1563                },
1564                open_flags: 0,
1565                inode: self.root_inode.clone(),
1566                is_stdio: false,
1567            })
1568        } else {
1569            ret
1570        }
1571    }
1572
1573    pub fn get_fd_inode(&self, fd: WasiFd) -> Result<InodeGuard, Errno> {
1574        // see `VIRTUAL_ROOT_FD` for details as to why this exists
1575        if fd == VIRTUAL_ROOT_FD {
1576            return Ok(self.root_inode.clone());
1577        }
1578        self.fd_map
1579            .read()
1580            .unwrap()
1581            .get(fd)
1582            .ok_or(Errno::Badf)
1583            .map(|a| a.inode.clone())
1584    }
1585
1586    pub fn filestat_fd(&self, fd: WasiFd) -> Result<Filestat, Errno> {
1587        let inode = self.get_fd_inode(fd)?;
1588        let guard = inode.stat.read().unwrap();
1589        Ok(*guard.deref())
1590    }
1591
1592    pub fn fdstat(&self, fd: WasiFd) -> Result<Fdstat, Errno> {
1593        match fd {
1594            __WASI_STDIN_FILENO => {
1595                return Ok(Fdstat {
1596                    fs_filetype: Filetype::CharacterDevice,
1597                    fs_flags: Fdflags::empty(),
1598                    fs_rights_base: STDIN_DEFAULT_RIGHTS,
1599                    fs_rights_inheriting: Rights::empty(),
1600                });
1601            }
1602            __WASI_STDOUT_FILENO => {
1603                return Ok(Fdstat {
1604                    fs_filetype: Filetype::CharacterDevice,
1605                    fs_flags: Fdflags::APPEND,
1606                    fs_rights_base: STDOUT_DEFAULT_RIGHTS,
1607                    fs_rights_inheriting: Rights::empty(),
1608                });
1609            }
1610            __WASI_STDERR_FILENO => {
1611                return Ok(Fdstat {
1612                    fs_filetype: Filetype::CharacterDevice,
1613                    fs_flags: Fdflags::APPEND,
1614                    fs_rights_base: STDERR_DEFAULT_RIGHTS,
1615                    fs_rights_inheriting: Rights::empty(),
1616                });
1617            }
1618            VIRTUAL_ROOT_FD => {
1619                return Ok(Fdstat {
1620                    fs_filetype: Filetype::Directory,
1621                    fs_flags: Fdflags::empty(),
1622                    // TODO: fix this
1623                    fs_rights_base: ALL_RIGHTS,
1624                    fs_rights_inheriting: ALL_RIGHTS,
1625                });
1626            }
1627            _ => (),
1628        }
1629        let fd = self.get_fd(fd)?;
1630
1631        let guard = fd.inode.read();
1632        let deref = guard.deref();
1633        Ok(Fdstat {
1634            fs_filetype: match deref {
1635                Kind::File { .. } => Filetype::RegularFile,
1636                Kind::Dir { .. } => Filetype::Directory,
1637                Kind::Symlink { .. } => Filetype::SymbolicLink,
1638                Kind::Socket { socket } => match &socket.inner.protected.read().unwrap().kind {
1639                    InodeSocketKind::TcpStream { .. } => Filetype::SocketStream,
1640                    InodeSocketKind::Raw { .. } => Filetype::SocketRaw,
1641                    InodeSocketKind::PreSocket { props, .. } => match props.ty {
1642                        Socktype::Stream => Filetype::SocketStream,
1643                        Socktype::Dgram => Filetype::SocketDgram,
1644                        Socktype::Raw => Filetype::SocketRaw,
1645                        Socktype::Seqpacket => Filetype::SocketSeqpacket,
1646                        _ => Filetype::Unknown,
1647                    },
1648                    _ => Filetype::Unknown,
1649                },
1650                _ => Filetype::Unknown,
1651            },
1652            fs_flags: fd.inner.flags,
1653            fs_rights_base: fd.inner.rights,
1654            fs_rights_inheriting: fd.inner.rights_inheriting, // TODO(lachlan): Is this right?
1655        })
1656    }
1657
1658    pub fn prestat_fd(&self, fd: WasiFd) -> Result<Prestat, Errno> {
1659        let inode = self.get_fd_inode(fd)?;
1660        //trace!("in prestat_fd {:?}", self.get_fd(fd)?);
1661
1662        if inode.is_preopened {
1663            Ok(self.prestat_fd_inner(inode.deref()))
1664        } else {
1665            Err(Errno::Badf)
1666        }
1667    }
1668
1669    pub(crate) fn prestat_fd_inner(&self, inode_val: &InodeVal) -> Prestat {
1670        Prestat {
1671            pr_type: Preopentype::Dir,
1672            u: PrestatEnum::Dir {
1673                // WASI spec: pr_name_len is the length of the path string, NOT including null terminator
1674                pr_name_len: inode_val.name.read().unwrap().len() as u32,
1675            }
1676            .untagged(),
1677        }
1678    }
1679
1680    #[allow(clippy::await_holding_lock)]
1681    pub async fn flush(&self, fd: WasiFd) -> Result<(), Errno> {
1682        match fd {
1683            __WASI_STDIN_FILENO => (),
1684            __WASI_STDOUT_FILENO => {
1685                let mut file =
1686                    WasiInodes::stdout_mut(&self.fd_map).map_err(fs_error_into_wasi_err)?;
1687                file.flush().await.map_err(map_io_err)?
1688            }
1689            __WASI_STDERR_FILENO => {
1690                let mut file =
1691                    WasiInodes::stderr_mut(&self.fd_map).map_err(fs_error_into_wasi_err)?;
1692                file.flush().await.map_err(map_io_err)?
1693            }
1694            _ => {
1695                let fd = self.get_fd(fd)?;
1696                if !fd.inner.rights.contains(Rights::FD_DATASYNC) {
1697                    return Err(Errno::Access);
1698                }
1699
1700                let file = {
1701                    let guard = fd.inode.read();
1702                    match guard.deref() {
1703                        Kind::File {
1704                            handle: Some(file), ..
1705                        } => file.clone(),
1706                        // TODO: verify this behavior
1707                        Kind::Dir { .. } => return Err(Errno::Isdir),
1708                        Kind::Buffer { .. } => return Ok(()),
1709                        _ => return Err(Errno::Io),
1710                    }
1711                };
1712                drop(fd);
1713
1714                struct FlushPoller {
1715                    file: Arc<RwLock<Box<dyn VirtualFile + Send + Sync>>>,
1716                }
1717                impl Future for FlushPoller {
1718                    type Output = Result<(), Errno>;
1719                    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1720                        let mut file = self.file.write().unwrap();
1721                        Pin::new(file.as_mut())
1722                            .poll_flush(cx)
1723                            .map_err(|_| Errno::Io)
1724                    }
1725                }
1726                FlushPoller { file }.await?;
1727            }
1728        }
1729        Ok(())
1730    }
1731
1732    /// Creates an inode and inserts it given a Kind and some extra data
1733    pub(crate) fn create_inode(
1734        &self,
1735        inodes: &WasiInodes,
1736        kind: Kind,
1737        is_preopened: bool,
1738        name: String,
1739    ) -> Result<InodeGuard, Errno> {
1740        let stat = self.get_stat_for_kind(&kind)?;
1741        Ok(self.create_inode_with_stat(inodes, kind, is_preopened, name.into(), stat))
1742    }
1743
1744    /// Creates an inode and inserts it given a Kind, does not assume the file exists.
1745    pub(crate) fn create_inode_with_default_stat(
1746        &self,
1747        inodes: &WasiInodes,
1748        kind: Kind,
1749        is_preopened: bool,
1750        name: Cow<'static, str>,
1751    ) -> InodeGuard {
1752        let stat = Filestat::default();
1753        self.create_inode_with_stat(inodes, kind, is_preopened, name, stat)
1754    }
1755
1756    /// Creates an inode with the given filestat and inserts it.
1757    pub(crate) fn create_inode_with_stat(
1758        &self,
1759        inodes: &WasiInodes,
1760        kind: Kind,
1761        is_preopened: bool,
1762        name: Cow<'static, str>,
1763        mut stat: Filestat,
1764    ) -> InodeGuard {
1765        match &kind {
1766            Kind::File {
1767                handle: Some(handle),
1768                ..
1769            } => {
1770                let guard = handle.read().unwrap();
1771                stat.st_size = guard.size();
1772            }
1773            Kind::Buffer { buffer } => {
1774                stat.st_size = buffer.len() as u64;
1775            }
1776            _ => {}
1777        }
1778
1779        let st_ino = Inode::from_path(&name);
1780        stat.st_ino = st_ino.as_u64();
1781
1782        inodes.add_inode_val(InodeVal {
1783            stat: RwLock::new(stat),
1784            is_preopened,
1785            name: RwLock::new(name),
1786            kind: RwLock::new(kind),
1787        })
1788    }
1789
1790    pub fn create_fd(
1791        &self,
1792        rights: Rights,
1793        rights_inheriting: Rights,
1794        fs_flags: Fdflags,
1795        fd_flags: Fdflagsext,
1796        open_flags: u16,
1797        inode: InodeGuard,
1798    ) -> Result<WasiFd, Errno> {
1799        self.create_fd_ext(
1800            rights,
1801            rights_inheriting,
1802            fs_flags,
1803            fd_flags,
1804            open_flags,
1805            inode,
1806            None,
1807            false,
1808        )
1809    }
1810
1811    #[allow(clippy::too_many_arguments)]
1812    pub fn with_fd(
1813        &self,
1814        rights: Rights,
1815        rights_inheriting: Rights,
1816        fs_flags: Fdflags,
1817        fd_flags: Fdflagsext,
1818        open_flags: u16,
1819        inode: InodeGuard,
1820        idx: WasiFd,
1821    ) -> Result<(), Errno> {
1822        self.create_fd_ext(
1823            rights,
1824            rights_inheriting,
1825            fs_flags,
1826            fd_flags,
1827            open_flags,
1828            inode,
1829            Some(idx),
1830            true,
1831        )?;
1832        Ok(())
1833    }
1834
1835    #[allow(clippy::too_many_arguments)]
1836    pub fn create_fd_ext(
1837        &self,
1838        rights: Rights,
1839        rights_inheriting: Rights,
1840        fs_flags: Fdflags,
1841        fd_flags: Fdflagsext,
1842        open_flags: u16,
1843        inode: InodeGuard,
1844        idx: Option<WasiFd>,
1845        exclusive: bool,
1846    ) -> Result<WasiFd, Errno> {
1847        let is_stdio = matches!(
1848            idx,
1849            Some(__WASI_STDIN_FILENO) | Some(__WASI_STDOUT_FILENO) | Some(__WASI_STDERR_FILENO)
1850        );
1851        let fd = Fd {
1852            inner: FdInner {
1853                rights,
1854                rights_inheriting,
1855                flags: fs_flags,
1856                offset: Arc::new(AtomicU64::new(0)),
1857                fd_flags,
1858            },
1859            open_flags,
1860            inode,
1861            is_stdio,
1862        };
1863
1864        let mut guard = self.fd_map.write().unwrap();
1865
1866        match idx {
1867            Some(idx) => {
1868                if guard.insert(exclusive, idx, fd) {
1869                    Ok(idx)
1870                } else {
1871                    Err(Errno::Exist)
1872                }
1873            }
1874            None => Ok(guard.insert_first_free(fd)),
1875        }
1876    }
1877
1878    pub fn clone_fd(&self, fd: WasiFd) -> Result<WasiFd, Errno> {
1879        self.clone_fd_ext(fd, 0, None)
1880    }
1881
1882    pub fn clone_fd_ext(
1883        &self,
1884        fd: WasiFd,
1885        min_result_fd: WasiFd,
1886        cloexec: Option<bool>,
1887    ) -> Result<WasiFd, Errno> {
1888        let fd = self.get_fd(fd)?;
1889        Ok(self.fd_map.write().unwrap().insert_first_free_after(
1890            Fd {
1891                inner: FdInner {
1892                    rights: fd.inner.rights,
1893                    rights_inheriting: fd.inner.rights_inheriting,
1894                    flags: fd.inner.flags,
1895                    offset: fd.inner.offset.clone(),
1896                    fd_flags: match cloexec {
1897                        None => fd.inner.fd_flags,
1898                        Some(cloexec) => {
1899                            let mut f = fd.inner.fd_flags;
1900                            f.set(Fdflagsext::CLOEXEC, cloexec);
1901                            f
1902                        }
1903                    },
1904                },
1905                open_flags: fd.open_flags,
1906                inode: fd.inode,
1907                is_stdio: fd.is_stdio,
1908            },
1909            min_result_fd,
1910        ))
1911    }
1912
1913    /// Low level function to remove an inode, that is it deletes the WASI FS's
1914    /// knowledge of a file.
1915    ///
1916    /// This function returns the inode if it existed and was removed.
1917    ///
1918    /// # Safety
1919    /// - The caller must ensure that all references to the specified inode have
1920    ///   been removed from the filesystem.
1921    pub unsafe fn remove_inode(&self, inodes: &WasiInodes, ino: Inode) -> Option<Arc<InodeVal>> {
1922        let mut guard = inodes.protected.write().unwrap();
1923        guard.lookup.remove(&ino).and_then(|a| Weak::upgrade(&a))
1924    }
1925
1926    pub(crate) fn create_stdout(&self, inodes: &WasiInodes) {
1927        self.create_std_dev_inner(
1928            inodes,
1929            Box::<Stdout>::default(),
1930            "stdout",
1931            __WASI_STDOUT_FILENO,
1932            STDOUT_DEFAULT_RIGHTS,
1933            Fdflags::APPEND,
1934            FS_STDOUT_INO,
1935        );
1936    }
1937
1938    pub(crate) fn create_stdin(&self, inodes: &WasiInodes) {
1939        self.create_std_dev_inner(
1940            inodes,
1941            Box::<Stdin>::default(),
1942            "stdin",
1943            __WASI_STDIN_FILENO,
1944            STDIN_DEFAULT_RIGHTS,
1945            Fdflags::empty(),
1946            FS_STDIN_INO,
1947        );
1948    }
1949
1950    pub(crate) fn create_stderr(&self, inodes: &WasiInodes) {
1951        self.create_std_dev_inner(
1952            inodes,
1953            Box::<Stderr>::default(),
1954            "stderr",
1955            __WASI_STDERR_FILENO,
1956            STDERR_DEFAULT_RIGHTS,
1957            Fdflags::APPEND,
1958            FS_STDERR_INO,
1959        );
1960    }
1961
1962    pub(crate) fn create_rootfd(&self) -> Result<(), String> {
1963        // create virtual root
1964        let all_rights = ALL_RIGHTS;
1965        // TODO: make this a list of positive rigths instead of negative ones
1966        // root gets all right for now
1967        let root_rights = all_rights
1968            /*
1969            & (!Rights::FD_WRITE)
1970            & (!Rights::FD_ALLOCATE)
1971            & (!Rights::PATH_CREATE_DIRECTORY)
1972            & (!Rights::PATH_CREATE_FILE)
1973            & (!Rights::PATH_LINK_SOURCE)
1974            & (!Rights::PATH_RENAME_SOURCE)
1975            & (!Rights::PATH_RENAME_TARGET)
1976            & (!Rights::PATH_FILESTAT_SET_SIZE)
1977            & (!Rights::PATH_FILESTAT_SET_TIMES)
1978            & (!Rights::FD_FILESTAT_SET_SIZE)
1979            & (!Rights::FD_FILESTAT_SET_TIMES)
1980            & (!Rights::PATH_SYMLINK)
1981            & (!Rights::PATH_UNLINK_FILE)
1982            & (!Rights::PATH_REMOVE_DIRECTORY)
1983            */;
1984        let fd = self
1985            .create_fd(
1986                root_rights,
1987                root_rights,
1988                Fdflags::empty(),
1989                Fdflagsext::empty(),
1990                Fd::READ,
1991                self.root_inode.clone(),
1992            )
1993            .map_err(|e| format!("Could not create root fd: {e}"))?;
1994        self.preopen_fds.write().unwrap().push(fd);
1995        Ok(())
1996    }
1997
1998    pub(crate) fn create_preopens(
1999        &self,
2000        inodes: &WasiInodes,
2001        ignore_duplicates: bool,
2002    ) -> Result<(), String> {
2003        for preopen_name in self.init_vfs_preopens.iter() {
2004            let kind = Kind::Dir {
2005                parent: self.root_inode.downgrade(),
2006                path: PathBuf::from(preopen_name),
2007                entries: Default::default(),
2008            };
2009            let rights = Rights::FD_ADVISE
2010                | Rights::FD_TELL
2011                | Rights::FD_SEEK
2012                | Rights::FD_READ
2013                | Rights::PATH_OPEN
2014                | Rights::FD_READDIR
2015                | Rights::PATH_READLINK
2016                | Rights::PATH_FILESTAT_GET
2017                | Rights::FD_FILESTAT_GET
2018                | Rights::PATH_LINK_SOURCE
2019                | Rights::PATH_RENAME_SOURCE
2020                | Rights::POLL_FD_READWRITE
2021                | Rights::SOCK_SHUTDOWN;
2022            let inode = self
2023                .create_inode(inodes, kind, true, preopen_name.clone())
2024                .map_err(|e| {
2025                    format!(
2026                        "Failed to create inode for preopened dir (name `{preopen_name}`): WASI error code: {e}",
2027                    )
2028                })?;
2029            let fd_flags = Fd::READ;
2030            let fd = self
2031                .create_fd(
2032                    rights,
2033                    rights,
2034                    Fdflags::empty(),
2035                    Fdflagsext::empty(),
2036                    fd_flags,
2037                    inode.clone(),
2038                )
2039                .map_err(|e| format!("Could not open fd for file {preopen_name:?}: {e}"))?;
2040            {
2041                let mut guard = self.root_inode.write();
2042                if let Kind::Root { entries } = guard.deref_mut() {
2043                    let existing_entry = entries.insert(preopen_name.clone(), inode);
2044                    if existing_entry.is_some() && !ignore_duplicates {
2045                        return Err(format!("Found duplicate entry for alias `{preopen_name}`"));
2046                    }
2047                }
2048            }
2049            self.preopen_fds.write().unwrap().push(fd);
2050        }
2051
2052        for PreopenedDir {
2053            path,
2054            alias,
2055            read,
2056            write,
2057            create,
2058        } in self.init_preopens.iter()
2059        {
2060            debug!(
2061                "Attempting to preopen {} with alias {:?}",
2062                &path.to_string_lossy(),
2063                &alias
2064            );
2065            let cur_dir_metadata = self
2066                .root_fs
2067                .metadata(path)
2068                .map_err(|e| format!("Could not get metadata for file {path:?}: {e}"))?;
2069
2070            let kind = if cur_dir_metadata.is_dir() {
2071                Kind::Dir {
2072                    parent: self.root_inode.downgrade(),
2073                    path: path.clone(),
2074                    entries: Default::default(),
2075                }
2076            } else {
2077                return Err(format!(
2078                    "WASI only supports pre-opened directories right now; found \"{}\"",
2079                    &path.to_string_lossy()
2080                ));
2081            };
2082
2083            let rights = {
2084                // TODO: review tell' and fd_readwrite
2085                let mut rights = Rights::FD_ADVISE | Rights::FD_TELL | Rights::FD_SEEK;
2086                if *read {
2087                    rights |= Rights::FD_READ
2088                        | Rights::PATH_OPEN
2089                        | Rights::FD_READDIR
2090                        | Rights::PATH_READLINK
2091                        | Rights::PATH_FILESTAT_GET
2092                        | Rights::FD_FILESTAT_GET
2093                        | Rights::PATH_LINK_SOURCE
2094                        | Rights::PATH_RENAME_SOURCE
2095                        | Rights::POLL_FD_READWRITE
2096                        | Rights::SOCK_SHUTDOWN;
2097                }
2098                if *write {
2099                    rights |= Rights::FD_DATASYNC
2100                        | Rights::FD_FDSTAT_SET_FLAGS
2101                        | Rights::FD_WRITE
2102                        | Rights::FD_SYNC
2103                        | Rights::FD_ALLOCATE
2104                        | Rights::PATH_OPEN
2105                        | Rights::PATH_RENAME_TARGET
2106                        | Rights::PATH_FILESTAT_SET_SIZE
2107                        | Rights::PATH_FILESTAT_SET_TIMES
2108                        | Rights::FD_FILESTAT_SET_SIZE
2109                        | Rights::FD_FILESTAT_SET_TIMES
2110                        | Rights::PATH_REMOVE_DIRECTORY
2111                        | Rights::PATH_UNLINK_FILE
2112                        | Rights::POLL_FD_READWRITE
2113                        | Rights::SOCK_SHUTDOWN;
2114                }
2115                if *create {
2116                    rights |= Rights::PATH_CREATE_DIRECTORY
2117                        | Rights::PATH_CREATE_FILE
2118                        | Rights::PATH_LINK_TARGET
2119                        | Rights::PATH_OPEN
2120                        | Rights::PATH_RENAME_TARGET
2121                        | Rights::PATH_SYMLINK;
2122                }
2123
2124                rights
2125            };
2126            let inode = if let Some(alias) = &alias {
2127                self.create_inode(inodes, kind, true, alias.clone())
2128            } else {
2129                self.create_inode(inodes, kind, true, path.to_string_lossy().into_owned())
2130            }
2131            .map_err(|e| {
2132                format!("Failed to create inode for preopened dir: WASI error code: {e}")
2133            })?;
2134            let fd_flags = {
2135                let mut fd_flags = 0;
2136                if *read {
2137                    fd_flags |= Fd::READ;
2138                }
2139                if *write {
2140                    // TODO: introduce API for finer grained control
2141                    fd_flags |= Fd::WRITE | Fd::APPEND | Fd::TRUNCATE;
2142                }
2143                if *create {
2144                    fd_flags |= Fd::CREATE;
2145                }
2146                fd_flags
2147            };
2148            let fd = self
2149                .create_fd(
2150                    rights,
2151                    rights,
2152                    Fdflags::empty(),
2153                    Fdflagsext::empty(),
2154                    fd_flags,
2155                    inode.clone(),
2156                )
2157                .map_err(|e| format!("Could not open fd for file {path:?}: {e}"))?;
2158            {
2159                let mut guard = self.root_inode.write();
2160                if let Kind::Root { entries } = guard.deref_mut() {
2161                    let key = if let Some(alias) = &alias {
2162                        alias.clone()
2163                    } else {
2164                        path.to_string_lossy().into_owned()
2165                    };
2166                    let existing_entry = entries.insert(key.clone(), inode);
2167                    if existing_entry.is_some() && !ignore_duplicates {
2168                        return Err(format!("Found duplicate entry for alias `{key}`"));
2169                    }
2170                }
2171            }
2172            self.preopen_fds.write().unwrap().push(fd);
2173        }
2174
2175        Ok(())
2176    }
2177
2178    #[allow(clippy::too_many_arguments)]
2179    pub(crate) fn create_std_dev_inner(
2180        &self,
2181        inodes: &WasiInodes,
2182        handle: Box<dyn VirtualFile + Send + Sync + 'static>,
2183        name: &'static str,
2184        raw_fd: WasiFd,
2185        rights: Rights,
2186        fd_flags: Fdflags,
2187        st_ino: Inode,
2188    ) {
2189        let inode = {
2190            let stat = Filestat {
2191                st_filetype: Filetype::CharacterDevice,
2192                st_ino: st_ino.as_u64(),
2193                ..Filestat::default()
2194            };
2195            let kind = Kind::File {
2196                fd: Some(raw_fd),
2197                handle: Some(Arc::new(RwLock::new(handle))),
2198                path: "".into(),
2199            };
2200            inodes.add_inode_val(InodeVal {
2201                stat: RwLock::new(stat),
2202                is_preopened: true,
2203                name: RwLock::new(name.to_string().into()),
2204                kind: RwLock::new(kind),
2205            })
2206        };
2207        self.fd_map.write().unwrap().insert(
2208            false,
2209            raw_fd,
2210            Fd {
2211                inner: FdInner {
2212                    rights,
2213                    rights_inheriting: Rights::empty(),
2214                    flags: fd_flags,
2215                    offset: Arc::new(AtomicU64::new(0)),
2216                    fd_flags: Fdflagsext::empty(),
2217                },
2218                // since we're not calling open on this, we don't need open flags
2219                open_flags: 0,
2220                inode,
2221                is_stdio: true,
2222            },
2223        );
2224    }
2225
2226    pub fn get_stat_for_kind(&self, kind: &Kind) -> Result<Filestat, Errno> {
2227        let md = match kind {
2228            Kind::File { handle, path, .. } => match handle {
2229                Some(wf) => {
2230                    let wf = wf.read().unwrap();
2231                    return Ok(Filestat {
2232                        st_filetype: Filetype::RegularFile,
2233                        st_ino: Inode::from_path(path.to_string_lossy().as_ref()).as_u64(),
2234                        st_size: wf.size(),
2235                        st_atim: wf.last_accessed(),
2236                        st_mtim: wf.last_modified(),
2237                        st_ctim: wf.created_time(),
2238
2239                        ..Filestat::default()
2240                    });
2241                }
2242                None => self
2243                    .root_fs
2244                    .metadata(path)
2245                    .map_err(fs_error_into_wasi_err)?,
2246            },
2247            Kind::Dir { path, .. } => self
2248                .root_fs
2249                .metadata(path)
2250                .map_err(fs_error_into_wasi_err)?,
2251            Kind::Symlink {
2252                base_po_dir,
2253                path_to_symlink,
2254                ..
2255            } => {
2256                let guard = self.fd_map.read().unwrap();
2257                let base_po_inode = &guard.get(*base_po_dir).unwrap().inode;
2258                let guard = base_po_inode.read();
2259                match guard.deref() {
2260                    Kind::Root { .. } => self
2261                        .root_fs
2262                        .symlink_metadata(path_to_symlink)
2263                        .map_err(fs_error_into_wasi_err)?,
2264                    Kind::Dir { path, .. } => {
2265                        let mut real_path = path.clone();
2266                        // PHASE 1: ignore all possible symlinks in `relative_path`
2267                        // TODO: walk the segments of `relative_path` via the entries of the Dir
2268                        //       use helper function to avoid duplicating this logic (walking this will require
2269                        //       &self to be &mut sel
2270                        // TODO: adjust size of symlink, too
2271                        //      for all paths adjusted think about this
2272                        real_path.push(path_to_symlink);
2273                        self.root_fs
2274                            .symlink_metadata(&real_path)
2275                            .map_err(fs_error_into_wasi_err)?
2276                    }
2277                    // if this triggers, there's a bug in the symlink code
2278                    _ => unreachable!(
2279                        "Symlink pointing to something that's not a directory as its base preopened directory"
2280                    ),
2281                }
2282            }
2283            _ => return Err(Errno::Io),
2284        };
2285        Ok(Filestat {
2286            st_filetype: virtual_file_type_to_wasi_file_type(md.file_type()),
2287            st_size: md.len(),
2288            st_atim: md.accessed(),
2289            st_mtim: md.modified(),
2290            st_ctim: md.created(),
2291            ..Filestat::default()
2292        })
2293    }
2294
2295    /// Closes an open FD, handling all details such as FD being preopen
2296    pub(crate) fn close_fd(&self, fd: WasiFd) -> Result<(), Errno> {
2297        let mut fd_map = self.fd_map.write().unwrap();
2298
2299        let pfd = fd_map.remove(fd).ok_or(Errno::Badf);
2300        match pfd {
2301            Ok(fd_ref) => {
2302                let inode = fd_ref.inode.ino().as_u64();
2303                let ref_cnt = fd_ref.inode.ref_cnt();
2304                if ref_cnt == 1 {
2305                    trace!(%fd, %inode, %ref_cnt, "closing file descriptor");
2306                } else {
2307                    trace!(%fd, %inode, %ref_cnt, "weakening file descriptor");
2308                }
2309            }
2310            Err(err) => {
2311                trace!(%fd, "closing file descriptor failed - {}", err);
2312            }
2313        }
2314        Ok(())
2315    }
2316}
2317
2318impl std::fmt::Debug for WasiFs {
2319    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2320        if let Ok(guard) = self.current_dir.try_lock() {
2321            write!(f, "current_dir={} ", guard.as_str())?;
2322        } else {
2323            write!(f, "current_dir=(locked) ")?;
2324        }
2325        if let Ok(guard) = self.fd_map.read() {
2326            write!(
2327                f,
2328                "next_fd={} max_fd={:?} ",
2329                guard.next_free_fd(),
2330                guard.last_fd()
2331            )?;
2332        } else {
2333            write!(f, "next_fd=(locked) max_fd=(locked) ")?;
2334        }
2335        write!(f, "{:?}", self.root_fs)
2336    }
2337}
2338
2339/// Returns the default filesystem backing
2340pub fn default_fs_backing() -> Arc<dyn virtual_fs::FileSystem + Send + Sync> {
2341    cfg_if::cfg_if! {
2342        if #[cfg(feature = "host-fs")] {
2343            Arc::new(virtual_fs::host_fs::FileSystem::new(tokio::runtime::Handle::current(), "/").unwrap())
2344        } else if #[cfg(not(feature = "host-fs"))] {
2345            Arc::<virtual_fs::mem_fs::FileSystem>::default()
2346        } else {
2347            Arc::<FallbackFileSystem>::default()
2348        }
2349    }
2350}
2351
2352#[derive(Debug, Default)]
2353pub struct FallbackFileSystem;
2354
2355impl FallbackFileSystem {
2356    fn fail() -> ! {
2357        panic!(
2358            "No filesystem set for wasmer-wasi, please enable either the `host-fs` or `mem-fs` feature or set your custom filesystem with `WasiEnvBuilder::set_fs`"
2359        );
2360    }
2361}
2362
2363impl FileSystem for FallbackFileSystem {
2364    fn readlink(&self, _path: &Path) -> virtual_fs::Result<PathBuf> {
2365        Self::fail()
2366    }
2367    fn read_dir(&self, _path: &Path) -> Result<virtual_fs::ReadDir, FsError> {
2368        Self::fail();
2369    }
2370    fn create_dir(&self, _path: &Path) -> Result<(), FsError> {
2371        Self::fail();
2372    }
2373    fn remove_dir(&self, _path: &Path) -> Result<(), FsError> {
2374        Self::fail();
2375    }
2376    fn rename<'a>(&'a self, _from: &Path, _to: &Path) -> BoxFuture<'a, Result<(), FsError>> {
2377        Self::fail();
2378    }
2379    fn metadata(&self, _path: &Path) -> Result<virtual_fs::Metadata, FsError> {
2380        Self::fail();
2381    }
2382    fn symlink_metadata(&self, _path: &Path) -> Result<virtual_fs::Metadata, FsError> {
2383        Self::fail();
2384    }
2385    fn remove_file(&self, _path: &Path) -> Result<(), FsError> {
2386        Self::fail();
2387    }
2388    fn new_open_options(&self) -> virtual_fs::OpenOptions<'_> {
2389        Self::fail();
2390    }
2391    fn mount(
2392        &self,
2393        _name: String,
2394        _path: &Path,
2395        _fs: Box<dyn FileSystem + Send + Sync>,
2396    ) -> virtual_fs::Result<()> {
2397        Self::fail()
2398    }
2399}
2400
2401pub fn virtual_file_type_to_wasi_file_type(file_type: virtual_fs::FileType) -> Filetype {
2402    // TODO: handle other file types
2403    if file_type.is_dir() {
2404        Filetype::Directory
2405    } else if file_type.is_file() {
2406        Filetype::RegularFile
2407    } else if file_type.is_symlink() {
2408        Filetype::SymbolicLink
2409    } else {
2410        Filetype::Unknown
2411    }
2412}
2413
2414pub fn fs_error_from_wasi_err(err: Errno) -> FsError {
2415    match err {
2416        Errno::Badf => FsError::InvalidFd,
2417        Errno::Exist => FsError::AlreadyExists,
2418        Errno::Io => FsError::IOError,
2419        Errno::Addrinuse => FsError::AddressInUse,
2420        Errno::Addrnotavail => FsError::AddressNotAvailable,
2421        Errno::Pipe => FsError::BrokenPipe,
2422        Errno::Connaborted => FsError::ConnectionAborted,
2423        Errno::Connrefused => FsError::ConnectionRefused,
2424        Errno::Connreset => FsError::ConnectionReset,
2425        Errno::Intr => FsError::Interrupted,
2426        Errno::Inval => FsError::InvalidInput,
2427        Errno::Notconn => FsError::NotConnected,
2428        Errno::Nodev => FsError::NoDevice,
2429        Errno::Noent => FsError::EntryNotFound,
2430        Errno::Perm => FsError::PermissionDenied,
2431        Errno::Timedout => FsError::TimedOut,
2432        Errno::Proto => FsError::UnexpectedEof,
2433        Errno::Again => FsError::WouldBlock,
2434        Errno::Nospc => FsError::WriteZero,
2435        Errno::Notempty => FsError::DirectoryNotEmpty,
2436        _ => FsError::UnknownError,
2437    }
2438}
2439
2440pub fn fs_error_into_wasi_err(fs_error: FsError) -> Errno {
2441    match fs_error {
2442        FsError::AlreadyExists => Errno::Exist,
2443        FsError::AddressInUse => Errno::Addrinuse,
2444        FsError::AddressNotAvailable => Errno::Addrnotavail,
2445        FsError::BaseNotDirectory => Errno::Notdir,
2446        FsError::BrokenPipe => Errno::Pipe,
2447        FsError::ConnectionAborted => Errno::Connaborted,
2448        FsError::ConnectionRefused => Errno::Connrefused,
2449        FsError::ConnectionReset => Errno::Connreset,
2450        FsError::Interrupted => Errno::Intr,
2451        FsError::InvalidData => Errno::Io,
2452        FsError::InvalidFd => Errno::Badf,
2453        FsError::InvalidInput => Errno::Inval,
2454        FsError::IOError => Errno::Io,
2455        FsError::NoDevice => Errno::Nodev,
2456        FsError::NotAFile => Errno::Inval,
2457        FsError::NotConnected => Errno::Notconn,
2458        FsError::EntryNotFound => Errno::Noent,
2459        FsError::PermissionDenied => Errno::Perm,
2460        FsError::TimedOut => Errno::Timedout,
2461        FsError::UnexpectedEof => Errno::Proto,
2462        FsError::WouldBlock => Errno::Again,
2463        FsError::WriteZero => Errno::Nospc,
2464        FsError::DirectoryNotEmpty => Errno::Notempty,
2465        FsError::StorageFull => Errno::Overflow,
2466        FsError::Lock | FsError::UnknownError => Errno::Io,
2467        FsError::Unsupported => Errno::Notsup,
2468    }
2469}
2470
2471#[cfg(test)]
2472mod tests {
2473    use super::*;
2474
2475    #[tokio::test]
2476    async fn test_relative_path_to_absolute() {
2477        let inodes = WasiInodes::new();
2478        let fs_backing = WasiFsRoot::Sandbox(TmpFileSystem::new());
2479        let wasi_fs = WasiFs::new_init(fs_backing, &inodes, FS_ROOT_INO).unwrap();
2480
2481        // Test absolute path (returned as-is, no normalization)
2482        assert_eq!(
2483            wasi_fs.relative_path_to_absolute("/foo/bar".to_string()),
2484            "/foo/bar"
2485        );
2486        assert_eq!(wasi_fs.relative_path_to_absolute("/".to_string()), "/");
2487
2488        // Absolute paths with special components are not normalized
2489        assert_eq!(
2490            wasi_fs.relative_path_to_absolute("//foo//bar//".to_string()),
2491            "//foo//bar//"
2492        );
2493        assert_eq!(
2494            wasi_fs.relative_path_to_absolute("/a/b/./c".to_string()),
2495            "/a/b/./c"
2496        );
2497        assert_eq!(
2498            wasi_fs.relative_path_to_absolute("/a/b/../c".to_string()),
2499            "/a/b/../c"
2500        );
2501
2502        // Test relative path with root as current dir
2503        assert_eq!(
2504            wasi_fs.relative_path_to_absolute("foo/bar".to_string()),
2505            "/foo/bar"
2506        );
2507        assert_eq!(wasi_fs.relative_path_to_absolute("foo".to_string()), "/foo");
2508
2509        // Test with different current directory
2510        wasi_fs.set_current_dir("/home/user");
2511        assert_eq!(
2512            wasi_fs.relative_path_to_absolute("file.txt".to_string()),
2513            "/home/user/file.txt"
2514        );
2515        assert_eq!(
2516            wasi_fs.relative_path_to_absolute("dir/file.txt".to_string()),
2517            "/home/user/dir/file.txt"
2518        );
2519
2520        // Test relative paths with . and .. components
2521        wasi_fs.set_current_dir("/a/b/c");
2522        assert_eq!(
2523            wasi_fs.relative_path_to_absolute("./file.txt".to_string()),
2524            "/a/b/c/./file.txt"
2525        );
2526        assert_eq!(
2527            wasi_fs.relative_path_to_absolute("../file.txt".to_string()),
2528            "/a/b/c/../file.txt"
2529        );
2530        assert_eq!(
2531            wasi_fs.relative_path_to_absolute("../../file.txt".to_string()),
2532            "/a/b/c/../../file.txt"
2533        );
2534
2535        // Test edge cases
2536        assert_eq!(
2537            wasi_fs.relative_path_to_absolute(".".to_string()),
2538            "/a/b/c/."
2539        );
2540        assert_eq!(
2541            wasi_fs.relative_path_to_absolute("..".to_string()),
2542            "/a/b/c/.."
2543        );
2544        assert_eq!(wasi_fs.relative_path_to_absolute("".to_string()), "/a/b/c/");
2545
2546        // Test current directory with trailing slash
2547        wasi_fs.set_current_dir("/home/user/");
2548        assert_eq!(
2549            wasi_fs.relative_path_to_absolute("file.txt".to_string()),
2550            "/home/user/file.txt"
2551        );
2552
2553        // Test current directory without trailing slash
2554        wasi_fs.set_current_dir("/home/user");
2555        assert_eq!(
2556            wasi_fs.relative_path_to_absolute("file.txt".to_string()),
2557            "/home/user/file.txt"
2558        );
2559    }
2560}