wasmtime_wasi/filesystem.rs
1use crate::clocks::Datetime;
2use crate::filesystem::primitives::{FollowSymlinks, Metadata, OpenOptions};
3use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking};
4use crate::{NamedId, WasiCtxNamedView};
5use std::collections::hash_map;
6use std::io;
7use std::marker;
8use std::num::NonZeroUsize;
9use std::sync::Arc;
10use std::time::SystemTime;
11use tracing::debug;
12use wasmtime::component::{HasData, Resource, ResourceTable};
13use wasmtime::error::Context as _;
14
15pub(crate) mod primitives;
16
17pub(crate) use primitives::{Advice, DescriptorFlags};
18
19/// A helper struct which implements [`HasData`] for the `wasi:filesystem` APIs.
20///
21/// This can be useful when directly calling `add_to_linker` functions directly,
22/// such as [`wasmtime_wasi::p2::bindings::filesystem::types::add_to_linker`] as
23/// the `D` type parameter. See [`HasData`] for more information about the type
24/// parameter's purpose.
25///
26/// When using this type you can skip the [`WasiFilesystemView`] trait, for
27/// example.
28///
29/// [`wasmtime_wasi::p2::bindings::filesystem::types::add_to_linker`]: crate::p2::bindings::filesystem::types::add_to_linker
30///
31/// # Examples
32///
33/// ```
34/// use wasmtime::component::{Linker, ResourceTable};
35/// use wasmtime::{Engine, Result};
36/// use wasmtime_wasi::filesystem::*;
37///
38/// struct MyStoreState {
39/// table: ResourceTable,
40/// filesystem: WasiFilesystemCtx,
41/// }
42///
43/// fn main() -> Result<()> {
44/// let engine = Engine::default();
45/// let mut linker = Linker::new(&engine);
46///
47/// wasmtime_wasi::p2::bindings::filesystem::types::add_to_linker::<MyStoreState, WasiFilesystem>(
48/// &mut linker,
49/// |state| WasiFilesystemCtxView {
50/// table: &mut state.table,
51/// ctx: &mut state.filesystem,
52/// },
53/// )?;
54/// Ok(())
55/// }
56/// ```
57pub struct WasiFilesystem;
58
59impl HasData for WasiFilesystem {
60 type Data<'a> = WasiFilesystemCtxView<'a>;
61}
62
63#[derive(Clone)]
64pub struct WasiFilesystemCtx {
65 pub(crate) allow_blocking_current_thread: bool,
66 pub(crate) preopens: Vec<(Dir, String)>,
67 pub(crate) max_io_size: NonZeroUsize,
68}
69
70impl Default for WasiFilesystemCtx {
71 fn default() -> Self {
72 Self {
73 allow_blocking_current_thread: false,
74 preopens: Vec::new(),
75 max_io_size: crate::DEFAULT_MAX_IO_SIZE,
76 }
77 }
78}
79
80pub struct WasiFilesystemCtxView<'a> {
81 pub ctx: &'a mut WasiFilesystemCtx,
82 pub table: &'a mut ResourceTable,
83}
84
85pub trait WasiFilesystemView: Send {
86 fn filesystem(&mut self) -> WasiFilesystemCtxView<'_>;
87}
88
89/// Permission bits for operating on filesystem, specified per preopen,
90/// as enforced by wasmtime-wasi.
91///
92/// Filesystems can deny all mutation operations (read-only) or permit
93/// mutations (read-write).
94///
95/// Read-only permissions allow reading the contents
96/// of any file or directory reachable under the preopen, as well as reading
97/// any file metadata. Changing, appending, or truncating files is not
98/// permitted. Creating or deleting files, directories, symbolic links, and
99/// hard links are not permitted.
100///
101/// Read-write permissions include changing the contents of any reachable
102/// file, creating and deleting files, directories, symbolic links, and
103/// creating hard links, as well as mutating any file metadata.
104///
105/// These permissions are enforced by wasmtime-wasi. The host filesystem may
106/// enforce additional restrictions not covered by these.
107#[derive(Copy, Clone, Debug, PartialEq, Eq)]
108pub enum FsPerms {
109 // Only read operations are permitted - no mutation permitted
110 ReadOnly,
111 // All operations are permitted.
112 ReadWrite,
113}
114
115impl FsPerms {
116 /// Tests whether writes are not permitted, returning a boolean. Shorthand
117 /// for matches!(perms, FsPerms::ReadOnly), used frequently in
118 /// if-statements.
119 pub fn write_not_permitted(&self) -> bool {
120 matches!(self, Self::ReadOnly)
121 }
122}
123
124bitflags::bitflags! {
125 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
126 pub struct OpenMode: usize {
127 const READ = 0b1;
128 const WRITE = 0b10;
129 }
130}
131
132bitflags::bitflags! {
133 /// Flags determining the method of how paths are resolved.
134 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
135 pub(crate) struct PathFlags: usize {
136 /// This directory can be read, for example its entries can be iterated
137 /// over and files can be opened.
138 const SYMLINK_FOLLOW = 0b1;
139 }
140}
141
142bitflags::bitflags! {
143 /// Open flags used by `open-at`.
144 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
145 pub(crate) struct OpenFlags: usize {
146 /// Create file if it does not exist, similar to `O_CREAT` in POSIX.
147 const CREATE = 0b1;
148 /// Fail if not a directory, similar to `O_DIRECTORY` in POSIX.
149 const DIRECTORY = 0b10;
150 /// Fail if file already exists, similar to `O_EXCL` in POSIX.
151 const EXCLUSIVE = 0b100;
152 /// Truncate file to size 0, similar to `O_TRUNC` in POSIX.
153 const TRUNCATE = 0b1000;
154 }
155}
156
157/// Error codes returned by functions, similar to `errno` in POSIX.
158/// Not all of these error codes are returned by the functions provided by this
159/// API; some are used in higher-level library layers, and others are provided
160/// merely for alignment with POSIX.
161#[cfg_attr(
162 windows,
163 expect(dead_code, reason = "on Windows, some of these are not used")
164)]
165pub(crate) enum ErrorCode {
166 /// Permission denied, similar to `EACCES` in POSIX.
167 Access,
168 /// Connection already in progress, similar to `EALREADY` in POSIX.
169 Already,
170 /// Bad descriptor, similar to `EBADF` in POSIX.
171 BadDescriptor,
172 /// Device or resource busy, similar to `EBUSY` in POSIX.
173 Busy,
174 /// File exists, similar to `EEXIST` in POSIX.
175 Exist,
176 /// File too large, similar to `EFBIG` in POSIX.
177 FileTooLarge,
178 /// Illegal byte sequence, similar to `EILSEQ` in POSIX.
179 IllegalByteSequence,
180 /// Operation in progress, similar to `EINPROGRESS` in POSIX.
181 InProgress,
182 /// Interrupted function, similar to `EINTR` in POSIX.
183 Interrupted,
184 /// Invalid argument, similar to `EINVAL` in POSIX.
185 Invalid,
186 /// I/O error, similar to `EIO` in POSIX.
187 Io,
188 /// Is a directory, similar to `EISDIR` in POSIX.
189 IsDirectory,
190 /// Too many levels of symbolic links, similar to `ELOOP` in POSIX.
191 Loop,
192 /// Too many links, similar to `EMLINK` in POSIX.
193 TooManyLinks,
194 /// Filename too long, similar to `ENAMETOOLONG` in POSIX.
195 NameTooLong,
196 /// No such file or directory, similar to `ENOENT` in POSIX.
197 NoEntry,
198 /// Not enough space, similar to `ENOMEM` in POSIX.
199 InsufficientMemory,
200 /// No space left on device, similar to `ENOSPC` in POSIX.
201 InsufficientSpace,
202 /// Not a directory or a symbolic link to a directory, similar to `ENOTDIR` in POSIX.
203 NotDirectory,
204 /// Directory not empty, similar to `ENOTEMPTY` in POSIX.
205 NotEmpty,
206 /// Not supported, similar to `ENOTSUP` and `ENOSYS` in POSIX.
207 Unsupported,
208 /// Value too large to be stored in data type, similar to `EOVERFLOW` in POSIX.
209 Overflow,
210 /// Operation not permitted, similar to `EPERM` in POSIX.
211 NotPermitted,
212 /// Broken pipe, similar to `EPIPE` in POSIX.
213 Pipe,
214 /// Invalid seek, similar to `ESPIPE` in POSIX.
215 InvalidSeek,
216}
217
218/// The type of a filesystem object referenced by a descriptor.
219///
220/// Note: This was called `filetype` in earlier versions of WASI.
221pub(crate) enum DescriptorType {
222 /// The type of the descriptor or file is unknown or is different from
223 /// any of the other types specified.
224 Unknown,
225 /// The descriptor refers to a block device inode.
226 BlockDevice,
227 /// The descriptor refers to a character device inode.
228 CharacterDevice,
229 /// The descriptor refers to a directory inode.
230 Directory,
231 /// The file refers to a symbolic link inode.
232 SymbolicLink,
233 /// The descriptor refers to a regular file inode.
234 RegularFile,
235}
236
237impl From<crate::filesystem::primitives::FileType> for DescriptorType {
238 fn from(ft: crate::filesystem::primitives::FileType) -> Self {
239 if ft.is_dir() {
240 DescriptorType::Directory
241 } else if ft.is_symlink() {
242 DescriptorType::SymbolicLink
243 } else if ft.is_file() {
244 DescriptorType::RegularFile
245 } else if ft.is_block_device() {
246 DescriptorType::BlockDevice
247 } else if ft.is_char_device() {
248 DescriptorType::CharacterDevice
249 } else {
250 DescriptorType::Unknown
251 }
252 }
253}
254
255/// File attributes.
256///
257/// Note: This was called `filestat` in earlier versions of WASI.
258pub(crate) struct DescriptorStat {
259 /// File type.
260 pub type_: DescriptorType,
261 /// Number of hard links to the file.
262 pub link_count: u64,
263 /// For regular files, the file size in bytes. For symbolic links, the
264 /// length in bytes of the pathname contained in the symbolic link.
265 pub size: u64,
266 /// Last data access timestamp.
267 ///
268 /// If the `option` is none, the platform doesn't maintain an access
269 /// timestamp for this file.
270 pub data_access_timestamp: Option<Datetime>,
271 /// Last data modification timestamp.
272 ///
273 /// If the `option` is none, the platform doesn't maintain a
274 /// modification timestamp for this file.
275 pub data_modification_timestamp: Option<Datetime>,
276 /// Last file status-change timestamp.
277 ///
278 /// If the `option` is none, the platform doesn't maintain a
279 /// status-change timestamp for this file.
280 pub status_change_timestamp: Option<Datetime>,
281}
282
283impl DescriptorStat {
284 /// Creates a `DescriptorStat` from a `Metadata`.
285 fn from_metadata(meta: &Metadata) -> Self {
286 Self {
287 type_: meta.file_type().into(),
288 link_count: meta.nlink(),
289 size: meta.len(),
290 data_access_timestamp: meta
291 .accessed()
292 .ok()
293 .and_then(|t| Datetime::try_from(t).ok()),
294 data_modification_timestamp: meta
295 .modified()
296 .ok()
297 .and_then(|t| Datetime::try_from(t).ok()),
298 status_change_timestamp: meta.created().ok().and_then(|t| Datetime::try_from(t).ok()),
299 }
300 }
301}
302
303/// A 128-bit hash value, split into parts because wasm doesn't have a
304/// 128-bit integer type.
305pub(crate) struct MetadataHashValue {
306 /// 64 bits of a 128-bit hash value.
307 pub lower: u64,
308 /// Another 64 bits of a 128-bit hash value.
309 pub upper: u64,
310}
311
312impl MetadataHashValue {
313 /// Creates a hash value from a file's unique identity, e.g. a
314 /// device/inode number pair.
315 fn from_metadata(meta: &Metadata) -> Self {
316 // Without incurring any deps, std provides us with a 64 bit hash
317 // function:
318 use std::hash::{Hash as _, Hasher as _};
319 // Note that this means that the metadata hash (which becomes a preview1 ino) may
320 // change when a different rustc release is used to build this host implementation:
321 let mut hasher = hash_map::DefaultHasher::new();
322 meta.identity().hash(&mut hasher);
323 let lower = hasher.finish();
324 // MetadataHashValue has a pair of 64-bit members for representing a
325 // single 128-bit number. However, we only have 64 bits of entropy. To
326 // synthesize the upper 64 bits, lets xor the lower half with an arbitrary
327 // constant, in this case the 64 bit integer corresponding to the IEEE
328 // double representation of (a number as close as possible to) pi.
329 // This seems better than just repeating the same bits in the upper and
330 // lower parts outright, which could make folks wonder if the struct was
331 // mangled in the ABI, or worse yet, lead to consumers of this interface
332 // expecting them to be equal.
333 let upper = lower ^ 4614256656552045848u64;
334 Self { lower, upper }
335 }
336}
337
338/// Returns whether `a` and `b` refer to the same underlying file.
339fn is_same_file(a: &std::fs::File, b: &std::fs::File) -> io::Result<bool> {
340 Ok(Metadata::from_file(a)?.identity() == Metadata::from_file(b)?.identity())
341}
342
343#[cfg(unix)]
344fn from_raw_os_error(err: Option<i32>) -> Option<ErrorCode> {
345 use rustix::io::Errno as RustixErrno;
346 if err.is_none() {
347 return None;
348 }
349 Some(match RustixErrno::from_raw_os_error(err.unwrap()) {
350 RustixErrno::PIPE => ErrorCode::Pipe,
351 RustixErrno::PERM => ErrorCode::NotPermitted,
352 RustixErrno::NOENT => ErrorCode::NoEntry,
353 RustixErrno::NOMEM => ErrorCode::InsufficientMemory,
354 RustixErrno::IO => ErrorCode::Io,
355 RustixErrno::BADF => ErrorCode::BadDescriptor,
356 RustixErrno::BUSY => ErrorCode::Busy,
357 RustixErrno::ACCESS => ErrorCode::Access,
358 RustixErrno::NOTDIR => ErrorCode::NotDirectory,
359 RustixErrno::ISDIR => ErrorCode::IsDirectory,
360 RustixErrno::INVAL => ErrorCode::Invalid,
361 RustixErrno::EXIST => ErrorCode::Exist,
362 RustixErrno::FBIG => ErrorCode::FileTooLarge,
363 RustixErrno::NOSPC => ErrorCode::InsufficientSpace,
364 RustixErrno::SPIPE => ErrorCode::InvalidSeek,
365 RustixErrno::MLINK => ErrorCode::TooManyLinks,
366 RustixErrno::NAMETOOLONG => ErrorCode::NameTooLong,
367 RustixErrno::NOTEMPTY => ErrorCode::NotEmpty,
368 RustixErrno::LOOP => ErrorCode::Loop,
369 RustixErrno::OVERFLOW => ErrorCode::Overflow,
370 RustixErrno::ILSEQ => ErrorCode::IllegalByteSequence,
371 RustixErrno::NOTSUP => ErrorCode::Unsupported,
372 RustixErrno::ALREADY => ErrorCode::Already,
373 RustixErrno::INPROGRESS => ErrorCode::InProgress,
374 RustixErrno::INTR => ErrorCode::Interrupted,
375
376 // On some platforms, these have the same value as other errno values.
377 #[allow(unreachable_patterns, reason = "see comment")]
378 RustixErrno::OPNOTSUPP => ErrorCode::Unsupported,
379
380 _ => return None,
381 })
382}
383
384#[cfg(windows)]
385fn from_raw_os_error(raw_os_error: Option<i32>) -> Option<ErrorCode> {
386 use windows_sys::Win32::Foundation;
387 Some(match raw_os_error.map(|code| code as u32) {
388 Some(Foundation::ERROR_FILE_NOT_FOUND) => ErrorCode::NoEntry,
389 Some(Foundation::ERROR_PATH_NOT_FOUND) => ErrorCode::NoEntry,
390 Some(Foundation::ERROR_ACCESS_DENIED) => ErrorCode::Access,
391 Some(Foundation::ERROR_SHARING_VIOLATION) => ErrorCode::Access,
392 Some(Foundation::ERROR_PRIVILEGE_NOT_HELD) => ErrorCode::NotPermitted,
393 Some(Foundation::ERROR_INVALID_HANDLE) => ErrorCode::BadDescriptor,
394 Some(Foundation::ERROR_INVALID_NAME) => ErrorCode::NoEntry,
395 Some(Foundation::ERROR_NOT_ENOUGH_MEMORY) => ErrorCode::InsufficientMemory,
396 Some(Foundation::ERROR_OUTOFMEMORY) => ErrorCode::InsufficientMemory,
397 Some(Foundation::ERROR_DIR_NOT_EMPTY) => ErrorCode::NotEmpty,
398 Some(Foundation::ERROR_NOT_READY) => ErrorCode::Busy,
399 Some(Foundation::ERROR_BUSY) => ErrorCode::Busy,
400 Some(Foundation::ERROR_NOT_SUPPORTED) => ErrorCode::Unsupported,
401 Some(Foundation::ERROR_FILE_EXISTS) => ErrorCode::Exist,
402 Some(Foundation::ERROR_BROKEN_PIPE) => ErrorCode::Pipe,
403 Some(Foundation::ERROR_BUFFER_OVERFLOW) => ErrorCode::NameTooLong,
404 Some(Foundation::ERROR_NOT_A_REPARSE_POINT) => ErrorCode::Invalid,
405 Some(Foundation::ERROR_NEGATIVE_SEEK) => ErrorCode::Invalid,
406 Some(Foundation::ERROR_DIRECTORY) => ErrorCode::NotDirectory,
407 Some(Foundation::ERROR_ALREADY_EXISTS) => ErrorCode::Exist,
408 Some(Foundation::ERROR_STOPPED_ON_SYMLINK) => ErrorCode::Loop,
409 Some(Foundation::ERROR_DIRECTORY_NOT_SUPPORTED) => ErrorCode::IsDirectory,
410 _ => return None,
411 })
412}
413
414impl<'a> From<&'a std::io::Error> for ErrorCode {
415 fn from(err: &'a std::io::Error) -> ErrorCode {
416 match from_raw_os_error(err.raw_os_error()) {
417 Some(errno) => errno,
418 None => {
419 debug!("unknown raw os error: {err}");
420 match err.kind() {
421 std::io::ErrorKind::NotFound => ErrorCode::NoEntry,
422 std::io::ErrorKind::PermissionDenied => ErrorCode::NotPermitted,
423 std::io::ErrorKind::AlreadyExists => ErrorCode::Exist,
424 std::io::ErrorKind::InvalidInput => ErrorCode::Invalid,
425 _ => ErrorCode::Io,
426 }
427 }
428 }
429 }
430}
431
432impl From<std::io::Error> for ErrorCode {
433 fn from(err: std::io::Error) -> ErrorCode {
434 ErrorCode::from(&err)
435 }
436}
437
438#[derive(Clone)]
439pub enum Descriptor {
440 File(File),
441 Dir(Dir),
442}
443
444impl Descriptor {
445 pub(crate) fn file(&self) -> Result<&File, ErrorCode> {
446 match self {
447 Descriptor::File(f) => Ok(f),
448 // File-only ops such as advise stay bad-descriptor on a dir
449 // (wasi-testsuite filesystem-advise). read-via-stream maps Dir
450 // to is-directory on its own.
451 Descriptor::Dir(_) => Err(ErrorCode::BadDescriptor),
452 }
453 }
454
455 pub(crate) fn dir(&self) -> Result<&Dir, ErrorCode> {
456 match self {
457 Descriptor::Dir(d) => Ok(d),
458 Descriptor::File(_) => Err(ErrorCode::NotDirectory),
459 }
460 }
461
462 pub(crate) async fn sync_data(&self) -> Result<(), ErrorCode> {
463 match self {
464 Self::File(f) => {
465 match f.run_blocking(|f| f.sync_data()).await {
466 Ok(()) => Ok(()),
467 // On windows, `sync_data` uses `FileFlushBuffers` which fails with
468 // `ERROR_ACCESS_DENIED` if the file is not upen for writing. Ignore
469 // this error, for POSIX compatibility.
470 #[cfg(windows)]
471 Err(err)
472 if err.raw_os_error()
473 == Some(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as _) =>
474 {
475 Ok(())
476 }
477 Err(err) => Err(err.into()),
478 }
479 }
480 Self::Dir(d) => {
481 d.run_blocking(|d| {
482 let d = crate::filesystem::primitives::open(
483 d,
484 std::path::Component::CurDir.as_ref(),
485 OpenOptions::new().read(true),
486 )?;
487 d.sync_data()?;
488 Ok(())
489 })
490 .await
491 }
492 }
493 }
494
495 pub(crate) async fn get_flags(&self) -> Result<DescriptorFlags, ErrorCode> {
496 match self {
497 Self::File(f) => {
498 let mut flags = f.run_blocking(|f| primitives::status_flags(f)).await?;
499 if f.open_mode.contains(OpenMode::READ) {
500 flags |= DescriptorFlags::READ;
501 }
502 if f.open_mode.contains(OpenMode::WRITE) {
503 flags |= DescriptorFlags::WRITE;
504 }
505 Ok(flags)
506 }
507 Self::Dir(d) => {
508 let mut flags = d.run_blocking(|d| primitives::status_flags(d)).await?;
509 if d.open_mode.contains(OpenMode::READ) {
510 flags |= DescriptorFlags::READ;
511 }
512 if d.open_mode.contains(OpenMode::WRITE) {
513 flags |= DescriptorFlags::MUTATE_DIRECTORY;
514 }
515 Ok(flags)
516 }
517 }
518 }
519
520 pub(crate) async fn get_type(&self) -> Result<DescriptorType, ErrorCode> {
521 match self {
522 Self::File(f) => {
523 let meta = f.run_blocking(|f| Metadata::from_file(f)).await?;
524 Ok(meta.file_type().into())
525 }
526 Self::Dir(_) => Ok(DescriptorType::Directory),
527 }
528 }
529
530 pub(crate) async fn set_times(
531 &self,
532 atim: Option<SystemTime>,
533 mtim: Option<SystemTime>,
534 ) -> Result<(), ErrorCode> {
535 match self {
536 Self::File(f) => {
537 if f.perms.write_not_permitted() {
538 return Err(ErrorCode::NotPermitted);
539 }
540 f.run_blocking(move |f| {
541 crate::filesystem::primitives::set_times_on_fd(f, atim, mtim)
542 })
543 .await?;
544 Ok(())
545 }
546 Self::Dir(d) => {
547 if d.perms.write_not_permitted() {
548 return Err(ErrorCode::NotPermitted);
549 }
550 d.run_blocking(move |d| {
551 crate::filesystem::primitives::set_times_on_fd(d, atim, mtim)
552 })
553 .await?;
554 Ok(())
555 }
556 }
557 }
558
559 pub(crate) async fn sync(&self) -> Result<(), ErrorCode> {
560 match self {
561 Self::File(f) => {
562 match f.run_blocking(|f| f.sync_all()).await {
563 Ok(()) => Ok(()),
564 // On windows, `sync_data` uses `FileFlushBuffers` which fails with
565 // `ERROR_ACCESS_DENIED` if the file is not upen for writing. Ignore
566 // this error, for POSIX compatibility.
567 #[cfg(windows)]
568 Err(err)
569 if err.raw_os_error()
570 == Some(windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED as _) =>
571 {
572 Ok(())
573 }
574 Err(err) => Err(err.into()),
575 }
576 }
577 Self::Dir(d) => {
578 d.run_blocking(|d| {
579 let d = crate::filesystem::primitives::open(
580 d,
581 std::path::Component::CurDir.as_ref(),
582 OpenOptions::new().read(true),
583 )?;
584 d.sync_all()?;
585 Ok(())
586 })
587 .await
588 }
589 }
590 }
591
592 /// Returns the metadata of the file or directory this descriptor refers
593 /// to.
594 async fn metadata(&self) -> io::Result<Metadata> {
595 match self {
596 Self::File(f) => f.run_blocking(|f| Metadata::from_file(f)).await,
597 Self::Dir(d) => d.run_blocking(|d| Metadata::from_file(d)).await,
598 }
599 }
600
601 pub(crate) async fn stat(&self) -> Result<DescriptorStat, ErrorCode> {
602 Ok(DescriptorStat::from_metadata(&self.metadata().await?))
603 }
604
605 pub(crate) async fn is_same_object(&self, other: &Self) -> wasmtime::Result<bool> {
606 // No permissions check on metadata: if opened, allowed to stat it
607 let other = match other {
608 Self::File(f) => Arc::clone(&f.file),
609 Self::Dir(d) => Arc::clone(&d.dir),
610 };
611 Ok(match self {
612 Self::File(f) => f.run_blocking(move |f| is_same_file(f, &other)).await?,
613 Self::Dir(d) => d.run_blocking(move |d| is_same_file(d, &other)).await?,
614 })
615 }
616
617 pub(crate) async fn metadata_hash(&self) -> Result<MetadataHashValue, ErrorCode> {
618 Ok(MetadataHashValue::from_metadata(&self.metadata().await?))
619 }
620}
621
622#[derive(Clone)]
623pub struct File {
624 /// The operating system File this struct is mediating access to.
625 ///
626 /// Wrapped in an Arc because the same underlying file is used for
627 /// implementing the stream types. A copy is also needed for
628 /// `spawn_blocking`.
629 pub file: Arc<std::fs::File>,
630 /// Permissions to enforce on access to the file. These permissions are
631 /// specified to the parent preopen by a user of the
632 /// `crate::WasiCtxBuilder`, and are enforced prior to any enforced by the
633 /// underlying operating system.
634 pub perms: FsPerms,
635 /// The mode the file was opened under: bits for reading, and writing.
636 /// Required to correctly report the DescriptorFlags, because
637 /// cap-primitives doesn't presently provide a cross-platform equivalent
638 /// of reading the oflags back out using fcntl.
639 pub open_mode: OpenMode,
640
641 allow_blocking_current_thread: bool,
642}
643
644impl File {
645 pub fn new(
646 file: std::fs::File,
647 perms: FsPerms,
648 open_mode: OpenMode,
649 allow_blocking_current_thread: bool,
650 ) -> Self {
651 Self {
652 file: Arc::new(file),
653 perms,
654 open_mode,
655 allow_blocking_current_thread,
656 }
657 }
658
659 /// Execute the blocking `body` function.
660 ///
661 /// Depending on how the WasiCtx was configured, the body may either be:
662 /// - Executed directly on the current thread. In this case the `async`
663 /// signature of this method is effectively a lie and the returned
664 /// Future will always be immediately Ready. Or:
665 /// - Spawned on a background thread using [`tokio::task::spawn_blocking`]
666 /// and immediately awaited.
667 ///
668 /// Intentionally blocking the executor thread might seem unorthodox, but is
669 /// not actually a problem for specific workloads. See:
670 /// - [`crate::WasiCtxBuilder::allow_blocking_current_thread`]
671 /// - [Poor performance of wasmtime file I/O maybe because tokio](https://github.com/bytecodealliance/wasmtime/issues/7973)
672 /// - [Implement opt-in for enabling WASI to block the current thread](https://github.com/bytecodealliance/wasmtime/pull/8190)
673 pub(crate) async fn run_blocking<F, R>(&self, body: F) -> R
674 where
675 F: FnOnce(&std::fs::File) -> R + Send + 'static,
676 R: Send + 'static,
677 {
678 match self.as_blocking_file() {
679 Some(file) => body(file),
680 None => self.spawn_blocking(body).await,
681 }
682 }
683
684 pub(crate) fn spawn_blocking<F, R>(&self, body: F) -> AbortOnDropJoinHandle<R>
685 where
686 F: FnOnce(&std::fs::File) -> R + Send + 'static,
687 R: Send + 'static,
688 {
689 let f = self.file.clone();
690 spawn_blocking(move || body(&f))
691 }
692
693 /// Returns `Some` when the current thread is allowed to block in filesystem
694 /// operations, and otherwise returns `None` to indicate that
695 /// `spawn_blocking` must be used.
696 pub(crate) fn as_blocking_file(&self) -> Option<&std::fs::File> {
697 if self.allow_blocking_current_thread {
698 Some(&self.file)
699 } else {
700 None
701 }
702 }
703
704 /// Returns reference to the underlying [`std::fs::File`]
705 #[cfg(feature = "p3")]
706 pub(crate) fn as_file(&self) -> &Arc<std::fs::File> {
707 &self.file
708 }
709
710 pub(crate) async fn advise(
711 &self,
712 offset: u64,
713 len: u64,
714 advice: Advice,
715 ) -> Result<(), ErrorCode> {
716 self.run_blocking(move |f| primitives::advise(f, offset, len, advice))
717 .await?;
718 Ok(())
719 }
720
721 pub(crate) async fn set_size(&self, size: u64) -> Result<(), ErrorCode> {
722 if self.perms.write_not_permitted() {
723 return Err(ErrorCode::NotPermitted);
724 }
725 self.run_blocking(move |f| f.set_len(size)).await?;
726 Ok(())
727 }
728}
729
730#[derive(Clone)]
731pub struct Dir {
732 /// The operating system file descriptor this struct is mediating access
733 /// to.
734 ///
735 /// This is a handle to a directory, and all paths accessed through this
736 /// struct are sandboxed to be within this directory via `cap-primitives`.
737 ///
738 /// Wrapped in an Arc because a copy is needed for `run_blocking`.
739 pub dir: Arc<std::fs::File>,
740 /// Permissions to enforce on access to the filesystem under this
741 /// directory are specified by a user of the `crate::WasiCtxBuilder`, and
742 /// are enforced prior to any enforced by the underlying operating system.
743 ///
744 /// These permissions are also enforced on any directories opened under
745 /// this directory.
746 pub perms: FsPerms,
747 /// The mode the directory was opened under: bits for reading, and writing.
748 /// Required to correctly report the DescriptorFlags, because
749 /// cap-primitives doesn't presently provide a cross-platform equivalent
750 /// of reading the oflags back out using fcntl.
751 pub open_mode: OpenMode,
752
753 pub(crate) allow_blocking_current_thread: bool,
754}
755
756impl Dir {
757 pub fn new(
758 dir: std::fs::File,
759 perms: FsPerms,
760 open_mode: OpenMode,
761 allow_blocking_current_thread: bool,
762 ) -> Self {
763 Dir {
764 dir: Arc::new(dir),
765 perms,
766 open_mode,
767 allow_blocking_current_thread,
768 }
769 }
770
771 /// Execute the blocking `body` function.
772 ///
773 /// Depending on how the WasiCtx was configured, the body may either be:
774 /// - Executed directly on the current thread. In this case the `async`
775 /// signature of this method is effectively a lie and the returned
776 /// Future will always be immediately Ready. Or:
777 /// - Spawned on a background thread using [`tokio::task::spawn_blocking`]
778 /// and immediately awaited.
779 ///
780 /// Intentionally blocking the executor thread might seem unorthodox, but is
781 /// not actually a problem for specific workloads. See:
782 /// - [`crate::WasiCtxBuilder::allow_blocking_current_thread`]
783 /// - [Poor performance of wasmtime file I/O maybe because tokio](https://github.com/bytecodealliance/wasmtime/issues/7973)
784 /// - [Implement opt-in for enabling WASI to block the current thread](https://github.com/bytecodealliance/wasmtime/pull/8190)
785 pub(crate) async fn run_blocking<F, R>(&self, body: F) -> R
786 where
787 F: FnOnce(&std::fs::File) -> R + Send + 'static,
788 R: Send + 'static,
789 {
790 if self.allow_blocking_current_thread {
791 body(&self.dir)
792 } else {
793 let d = self.dir.clone();
794 spawn_blocking(move || body(&d)).await
795 }
796 }
797
798 /// Returns reference to the underlying directory handle.
799 #[cfg(feature = "p3")]
800 pub(crate) fn as_dir(&self) -> &Arc<std::fs::File> {
801 &self.dir
802 }
803
804 pub(crate) async fn create_directory_at(&self, path: String) -> Result<(), ErrorCode> {
805 if self.perms.write_not_permitted() {
806 return Err(ErrorCode::NotPermitted);
807 }
808 self.run_blocking(move |d| crate::filesystem::primitives::create_dir(d, path.as_ref()))
809 .await?;
810 Ok(())
811 }
812
813 pub(crate) async fn stat_at(
814 &self,
815 path_flags: PathFlags,
816 path: String,
817 ) -> Result<DescriptorStat, ErrorCode> {
818 let follow = if path_flags.contains(PathFlags::SYMLINK_FOLLOW) {
819 FollowSymlinks::Yes
820 } else {
821 FollowSymlinks::No
822 };
823 let meta = self
824 .run_blocking(move |d| primitives::stat(d, path.as_ref(), follow))
825 .await?;
826 Ok(DescriptorStat::from_metadata(&meta))
827 }
828
829 pub(crate) async fn set_times_at(
830 &self,
831 path_flags: PathFlags,
832 path: String,
833 atim: Option<SystemTime>,
834 mtim: Option<SystemTime>,
835 ) -> Result<(), ErrorCode> {
836 if self.perms.write_not_permitted() {
837 return Err(ErrorCode::NotPermitted);
838 }
839 if path_flags.contains(PathFlags::SYMLINK_FOLLOW) {
840 self.run_blocking(move |d| {
841 crate::filesystem::primitives::set_times(d, path.as_ref(), atim, mtim)
842 })
843 .await?;
844 } else {
845 self.run_blocking(move |d| {
846 crate::filesystem::primitives::set_times_nofollow(d, path.as_ref(), atim, mtim)
847 })
848 .await?;
849 }
850 Ok(())
851 }
852
853 pub(crate) async fn link_at(
854 &self,
855 old_path_flags: PathFlags,
856 old_path: String,
857 new_dir: &Self,
858 new_path: String,
859 ) -> Result<(), ErrorCode> {
860 if self.perms.write_not_permitted() {
861 return Err(ErrorCode::NotPermitted);
862 }
863 if new_dir.perms.write_not_permitted() {
864 return Err(ErrorCode::NotPermitted);
865 }
866 if old_path_flags.contains(PathFlags::SYMLINK_FOLLOW) {
867 return Err(ErrorCode::Invalid);
868 }
869 if self.perms != new_dir.perms {
870 return Err(ErrorCode::NotPermitted);
871 }
872 let new_dir_handle = Arc::clone(&new_dir.dir);
873 self.run_blocking(move |d| {
874 crate::filesystem::primitives::hard_link(
875 d,
876 old_path.as_ref(),
877 &new_dir_handle,
878 new_path.as_ref(),
879 )
880 })
881 .await?;
882 Ok(())
883 }
884
885 pub(crate) async fn open_at(
886 &self,
887 path_flags: PathFlags,
888 path: String,
889 oflags: OpenFlags,
890 flags: DescriptorFlags,
891 allow_blocking_current_thread: bool,
892 ) -> Result<Descriptor, ErrorCode> {
893 // Track whether we are creating file, for permission check:
894 let mut create = false;
895 // Track open mode, for permission check and recording in created descriptor:
896 let mut open_mode = OpenMode::empty();
897 // Construct the OpenOptions to give the OS:
898 let mut opts = OpenOptions::new();
899 opts.maybe_dir(true);
900
901 if oflags.contains(OpenFlags::CREATE) {
902 if oflags.contains(OpenFlags::EXCLUSIVE) {
903 opts.create_new(true);
904 } else {
905 opts.create(true);
906 }
907 create = true;
908 opts.write(true);
909 open_mode |= OpenMode::WRITE;
910 }
911
912 if oflags.contains(OpenFlags::TRUNCATE) {
913 opts.truncate(true).write(true);
914 open_mode |= OpenMode::WRITE;
915 }
916 if flags.contains(DescriptorFlags::READ) {
917 opts.read(true);
918 open_mode |= OpenMode::READ;
919 }
920 if flags.contains(DescriptorFlags::WRITE) {
921 opts.write(true);
922 open_mode |= OpenMode::WRITE;
923 } else {
924 // If not opened write, open read. This way the OS lets us open
925 // the file, but we can use perms to reject use of the file later.
926 opts.read(true);
927 open_mode |= OpenMode::READ;
928 }
929
930 if path_flags.contains(PathFlags::SYMLINK_FOLLOW) {
931 opts.follow(FollowSymlinks::Yes);
932 } else {
933 opts.follow(FollowSymlinks::No);
934 }
935
936 // These flags are not yet supported in cap-primitives:
937 if flags.contains(DescriptorFlags::FILE_INTEGRITY_SYNC)
938 || flags.contains(DescriptorFlags::DATA_INTEGRITY_SYNC)
939 || flags.contains(DescriptorFlags::REQUESTED_WRITE_SYNC)
940 {
941 return Err(ErrorCode::Unsupported);
942 }
943
944 if oflags.contains(OpenFlags::DIRECTORY) {
945 if oflags.contains(OpenFlags::CREATE)
946 || oflags.contains(OpenFlags::EXCLUSIVE)
947 || oflags.contains(OpenFlags::TRUNCATE)
948 {
949 return Err(ErrorCode::Invalid);
950 }
951 }
952
953 // Now enforce this WasiCtx's permissions before letting the OS have
954 // its shot:
955 if self.perms.write_not_permitted() {
956 if create || open_mode.contains(OpenMode::WRITE) {
957 return Err(ErrorCode::NotPermitted);
958 }
959 }
960
961 // Represents each possible outcome from the spawn_blocking operation.
962 // This makes sure we don't have to give spawn_blocking any way to
963 // manipulate the table.
964 enum OpenResult {
965 Dir(std::fs::File),
966 File(std::fs::File),
967 NotDir,
968 }
969
970 let opened = self
971 .run_blocking::<_, std::io::Result<OpenResult>>(move |d| {
972 let opened = crate::filesystem::primitives::open(d, path.as_ref(), &opts)?;
973 if Metadata::from_file(&opened)?.is_dir() {
974 Ok(OpenResult::Dir(opened))
975 } else if oflags.contains(OpenFlags::DIRECTORY) {
976 Ok(OpenResult::NotDir)
977 } else {
978 Ok(OpenResult::File(opened))
979 }
980 })
981 .await?;
982
983 match opened {
984 // Paper over a divergence between Windows and POSIX, where
985 // POSIX returns EISDIR if you open a directory with the
986 // WRITE flag: https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html#:~:text=EISDIR
987 #[cfg(windows)]
988 OpenResult::Dir(_) if flags.contains(DescriptorFlags::WRITE) => {
989 Err(ErrorCode::IsDirectory)
990 }
991
992 OpenResult::Dir(dir) => Ok(Descriptor::Dir(Dir::new(
993 dir,
994 self.perms,
995 open_mode,
996 allow_blocking_current_thread,
997 ))),
998
999 OpenResult::File(file) => Ok(Descriptor::File(File::new(
1000 file,
1001 self.perms,
1002 open_mode,
1003 allow_blocking_current_thread,
1004 ))),
1005
1006 OpenResult::NotDir => Err(ErrorCode::NotDirectory),
1007 }
1008 }
1009
1010 pub(crate) async fn readlink_at(&self, path: String) -> Result<String, ErrorCode> {
1011 let link = self
1012 .run_blocking(move |d| crate::filesystem::primitives::read_link(d, path.as_ref()))
1013 .await?;
1014 link.into_os_string()
1015 .into_string()
1016 .or(Err(ErrorCode::IllegalByteSequence))
1017 }
1018
1019 pub(crate) async fn remove_directory_at(&self, path: String) -> Result<(), ErrorCode> {
1020 if self.perms.write_not_permitted() {
1021 return Err(ErrorCode::NotPermitted);
1022 }
1023 self.run_blocking(move |d| crate::filesystem::primitives::remove_dir(d, path.as_ref()))
1024 .await?;
1025 Ok(())
1026 }
1027
1028 pub(crate) async fn rename_at(
1029 &self,
1030 old_path: String,
1031 new_dir: &Self,
1032 new_path: String,
1033 ) -> Result<(), ErrorCode> {
1034 if self.perms.write_not_permitted() {
1035 return Err(ErrorCode::NotPermitted);
1036 }
1037 if new_dir.perms.write_not_permitted() {
1038 return Err(ErrorCode::NotPermitted);
1039 }
1040 if self.perms != new_dir.perms {
1041 return Err(ErrorCode::NotPermitted);
1042 }
1043 let new_dir_handle = Arc::clone(&new_dir.dir);
1044 self.run_blocking(move |d| {
1045 crate::filesystem::primitives::rename(
1046 d,
1047 old_path.as_ref(),
1048 &new_dir_handle,
1049 new_path.as_ref(),
1050 )
1051 })
1052 .await?;
1053 Ok(())
1054 }
1055
1056 pub(crate) async fn symlink_at(
1057 &self,
1058 src_path: String,
1059 dest_path: String,
1060 ) -> Result<(), ErrorCode> {
1061 if self.perms.write_not_permitted() {
1062 return Err(ErrorCode::NotPermitted);
1063 }
1064 self.run_blocking(move |d| primitives::symlink(src_path.as_ref(), d, dest_path.as_ref()))
1065 .await?;
1066 Ok(())
1067 }
1068
1069 pub(crate) async fn unlink_file_at(&self, path: String) -> Result<(), ErrorCode> {
1070 if self.perms.write_not_permitted() {
1071 return Err(ErrorCode::NotPermitted);
1072 }
1073 self.run_blocking(move |d| primitives::remove_file_or_symlink(d, path.as_ref()))
1074 .await?;
1075 Ok(())
1076 }
1077
1078 pub(crate) async fn metadata_hash_at(
1079 &self,
1080 path_flags: PathFlags,
1081 path: String,
1082 ) -> Result<MetadataHashValue, ErrorCode> {
1083 // No permissions check on metadata: if dir opened, allowed to stat it
1084 let follow = if path_flags.contains(PathFlags::SYMLINK_FOLLOW) {
1085 FollowSymlinks::Yes
1086 } else {
1087 FollowSymlinks::No
1088 };
1089 let meta = self
1090 .run_blocking(move |d| primitives::stat(d, path.as_ref(), follow))
1091 .await?;
1092 Ok(MetadataHashValue::from_metadata(&meta))
1093 }
1094}
1095
1096impl WasiFilesystemCtxView<'_> {
1097 pub(crate) fn get_directories(
1098 &mut self,
1099 ) -> wasmtime::Result<Vec<(Resource<Descriptor>, String)>> {
1100 let preopens = self.ctx.preopens.clone();
1101 let mut results = Vec::with_capacity(preopens.len());
1102 for (dir, name) in preopens {
1103 let fd = self
1104 .table
1105 .push(Descriptor::Dir(dir))
1106 .with_context(|| format!("failed to push preopen {name}"))?;
1107 results.push((fd, name));
1108 }
1109 Ok(results)
1110 }
1111}
1112
1113/// A helper struct which implements [`HasData`] for the `wasi:filesystem` APIs
1114/// when used in combination with named imports.
1115///
1116/// This structure is similar in purpose to [`WasiFilesystem`] and is used
1117/// when using the [`named_imports`] module for `wasi:filesystem`. This structure
1118/// serves as the `D` type parameter for `add_to_linker` functions.
1119///
1120/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::filesystem
1121///
1122/// # Meaning of the `T` parameter
1123///
1124/// Here the `T` must be something that implements [`WasiFilesystemNamedView`]. The
1125/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally
1126/// will contain `&mut T`.
1127///
1128/// Effectively you're going to implement [`WasiFilesystemNamedView`] for something in
1129/// your embedding, and that's the `T` you'll fill in here.
1130///
1131/// # Examples
1132///
1133/// ```
1134/// use wasmtime::component::{Linker, Component, ResourceTable};
1135/// use wasmtime::{Engine, Result};
1136/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};
1137/// use wasmtime_wasi::filesystem::*;
1138/// use wasmtime_wasi::p2::bindings::named_imports;
1139/// use std::collections::HashMap;
1140///
1141/// struct MyStoreState {
1142/// table: ResourceTable,
1143/// states: HashMap<NamedId, WasiFilesystemCtx>,
1144/// }
1145///
1146/// fn main() -> Result<()> {
1147/// let engine = Engine::default();
1148/// let mut linker = Linker::new(&engine);
1149/// let component = Component::new(&engine, "(component)")?;
1150/// let mut name_map = HashMap::new();
1151///
1152/// named_imports::wasi::filesystem::preopens::add_to_linker::<MyStoreState, WasiFilesystemNamed<MyStoreState>>(
1153/// &mut linker,
1154/// &component,
1155/// |name| {
1156/// let len = name_map.len();
1157/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))
1158/// },
1159/// |state| WasiCtxNamedView(state),
1160/// )?;
1161/// Ok(())
1162/// }
1163///
1164/// impl WasiFilesystemNamedView for MyStoreState {
1165/// fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_> {
1166/// let ctx = self.states.get_mut(&id).expect("state for id");
1167/// WasiFilesystemCtxView {
1168/// table: &mut self.table,
1169/// ctx,
1170/// }
1171/// }
1172/// }
1173/// ```
1174pub struct WasiFilesystemNamed<T>(marker::PhantomData<fn() -> T>);
1175
1176impl<T> HasData for WasiFilesystemNamed<T>
1177where
1178 T: WasiFilesystemNamedView,
1179{
1180 type Data<'a> = WasiCtxNamedView<'a, T>;
1181}
1182
1183/// A trait used to look up a specific `wasi:filesystem` context for a named
1184/// import.
1185///
1186/// This trait is used in conjunction with the [`named_imports`] bindings
1187/// generated for all WASI interfaces. The purpose of this trait is for
1188/// embedders to define how a [`NamedId`] maps to a particular `wasi:filesystem`
1189/// context, here returned as [`WasiFilesystemCtxView`]. Embedders are responsible
1190/// for assigning meaning to [`NamedId`] values themselves. These IDs are
1191/// assigned when [`add_named_to_linker`] is called, for example, as the
1192/// `lookup` argument to that function.
1193///
1194/// When using [`add_named_to_linker`] it's sufficient to implement this trait
1195/// for the `T` in `Store<T>`. You can also instead implement the
1196/// [`WasiNamedView`] trait for `T` which implies an implementation of this
1197/// trait.
1198///
1199/// When using `add_to_linker` in the generated `bindings::named_imports`
1200/// module then values implementing this live within the `T` of `Store<T>`, and
1201/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll
1202/// hold `WasiCtxNamedView(&mut your_type)`.
1203///
1204/// [`named_imports`]: crate::p3::bindings::named_imports
1205/// [`add_named_to_linker`]: crate::p3::filesystem::add_named_to_linker
1206/// [`WasiNamedView`]: crate::WasiNamedView
1207///
1208/// # Examples
1209///
1210/// ```
1211/// use wasmtime::component::{Linker, Component, ResourceTable};
1212/// use wasmtime::{Engine, Result};
1213/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};
1214/// use wasmtime_wasi::filesystem::*;
1215/// use std::collections::HashMap;
1216///
1217/// struct MyStoreState {
1218/// table: ResourceTable,
1219/// states: HashMap<NamedId, WasiFilesystemCtx>,
1220/// }
1221///
1222/// fn main() -> Result<()> {
1223/// let engine = Engine::default();
1224/// let mut linker = Linker::new(&engine);
1225/// let component = Component::new(&engine, "(component)")?;
1226/// let mut name_map = HashMap::new();
1227///
1228/// wasmtime_wasi::p3::filesystem::add_named_to_linker::<MyStoreState>(
1229/// &mut linker,
1230/// &component,
1231/// |_, name| {
1232/// let len = name_map.len();
1233/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))
1234/// },
1235/// )?;
1236/// Ok(())
1237/// }
1238///
1239/// impl WasiFilesystemNamedView for MyStoreState {
1240/// fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_> {
1241/// let ctx = self.states.get_mut(&id).expect("state for id");
1242/// WasiFilesystemCtxView {
1243/// table: &mut self.table,
1244/// ctx,
1245/// }
1246/// }
1247/// }
1248/// ```
1249pub trait WasiFilesystemNamedView: Send + 'static {
1250 /// Looks up the [`WasiFilesystemCtxView`] for the given [`NamedId`].
1251 ///
1252 /// This method will resolve the `id` specified to a specific filesystem
1253 /// context that is available to be used. Note that this method is
1254 /// specifically infallible meaning that a filesystem context must be returned
1255 /// and this cannot generate a trap or panic or similar.
1256 ///
1257 /// Embedders are responsible for allocating [`NamedId`] and assigning
1258 /// meaning to ids. When a `Linker` is populated embedders will have the
1259 /// ability to generate a `NamedId` for all imports found, and then that
1260 /// embedder-allocated id is then passed back here when the corresponding
1261 /// imported function is invoked.
1262 ///
1263 /// It's strongly recommended, though not always required, that the
1264 /// [`ResourceTable`] in the returned [`WasiFilesystemCtxView`] is the same
1265 /// table that the default context, [`WasiFilesystemView::filesystem`],
1266 /// uses. Resources created through a named import can be used through
1267 /// interfaces bound to the default context (and vice versa), and with
1268 /// separate tables those lookups fail or find another context's resources.
1269 fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_>;
1270}