Skip to main content

wasmtime_wasi/
p1.rs

1//! Bindings for WASIp1 aka Preview 1 aka `wasi_snapshot_preview1`.
2//!
3//! This module contains runtime support for configuring and executing
4//! WASIp1-using core WebAssembly modules. Support for WASIp1 is built on top of
5//! support for WASIp2 available at [the crate root](crate), but that's just an
6//! internal implementation detail.
7//!
8//! Unlike the crate root, support for WASIp1 centers around two APIs:
9//!
10//! * [`WasiP1Ctx`]
11//! * [`add_to_linker_sync`] (or [`add_to_linker_async`])
12//!
13//! First a [`WasiCtxBuilder`] will be used and finalized with the [`build_p1`]
14//! method to create a [`WasiCtx`]. Next a [`wasmtime::Linker`] is configured
15//! with WASI imports by using the `add_to_linker_*` desired (sync or async).
16//!
17//! Note that WASIp1 is not as extensible or configurable as WASIp2 so the
18//! support in this module is enough to run wasm modules but any customization
19//! beyond that [`WasiCtxBuilder`] already supports is not possible yet.
20//!
21//! [`WasiCtxBuilder`]: crate::WasiCtxBuilder
22//! [`build_p1`]: crate::WasiCtxBuilder::build_p1
23//!
24//! # Components vs Modules
25//!
26//! Note that WASIp1 does not work for components at this time, only core wasm
27//! modules. That means this module is only for users of [`wasmtime::Module`]
28//! and [`wasmtime::Linker`], for example. If you're using
29//! [`wasmtime::component::Component`] or [`wasmtime::component::Linker`] you'll
30//! want the WASIp2 [support this crate has](crate) instead.
31//!
32//! # Examples
33//!
34//! ```no_run
35//! use wasmtime::{Result, Engine, Linker, Module, Store};
36//! use wasmtime_wasi::p1::{self, WasiP1Ctx};
37//! use wasmtime_wasi::WasiCtxBuilder;
38//!
39//! // An example of executing a WASIp1 "command"
40//! fn main() -> Result<()> {
41//!     let args = std::env::args().skip(1).collect::<Vec<_>>();
42//!     let engine = Engine::default();
43//!     let module = Module::from_file(&engine, &args[0])?;
44//!
45//!     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
46//!     p1::add_to_linker_async(&mut linker, |t| t)?;
47//!     let pre = linker.instantiate_pre(&module)?;
48//!
49//!     let wasi_ctx = WasiCtxBuilder::new()
50//!         .inherit_stdio()
51//!         .inherit_env()
52//!         .args(&args)
53//!         .build_p1();
54//!
55//!     let mut store = Store::new(&engine, wasi_ctx);
56//!     let instance = pre.instantiate(&mut store)?;
57//!     let func = instance.get_typed_func::<(), ()>(&mut store, "_start")?;
58//!     func.call(&mut store, ())?;
59//!
60//!     Ok(())
61//! }
62//! ```
63
64use crate::cli::WasiCliView as _;
65use crate::clocks::WasiClocksView as _;
66use crate::filesystem::WasiFilesystemView as _;
67use crate::filesystem::primitives;
68use crate::p2::bindings::{
69    cli::{
70        stderr::Host as _, stdin::Host as _, stdout::Host as _, terminal_input, terminal_output,
71        terminal_stderr::Host as _, terminal_stdin::Host as _, terminal_stdout::Host as _,
72    },
73    clocks::{monotonic_clock, wall_clock},
74    filesystem::types as filesystem,
75};
76use crate::p2::{FsError, IsATTY};
77use crate::{ResourceTable, WasiCtx, WasiCtxView, WasiView};
78use std::collections::{BTreeMap, BTreeSet, HashSet, btree_map};
79use std::mem::{self, size_of};
80use std::sync::Arc;
81use std::sync::atomic::{AtomicU64, Ordering};
82use wasmtime::component::Resource;
83use wasmtime::{bail, error::Context as _};
84use wasmtime_wasi_io::{
85    bindings::wasi::io::streams,
86    streams::{StreamError, StreamResult},
87};
88use wiggle::tracing::instrument;
89use wiggle::{GuestError, GuestMemory, GuestPtr, GuestType};
90
91// Bring all WASI traits in scope that this implementation builds on.
92use crate::p2::bindings::cli::environment::Host as _;
93use crate::p2::bindings::filesystem::types::HostDescriptor as _;
94use crate::p2::bindings::random::random::Host as _;
95use wasmtime_wasi_io::bindings::wasi::io::poll::Host as _;
96
97/// Structure containing state for WASIp1.
98///
99/// This structure is created through [`WasiCtxBuilder::build_p1`] and is
100/// configured through the various methods of [`WasiCtxBuilder`]. This structure
101/// itself implements generated traits for WASIp1 as well as [`WasiView`] to
102/// have access to WASIp2.
103///
104/// Instances of [`WasiP1Ctx`] are typically stored within the `T` of
105/// [`Store<T>`](wasmtime::Store).
106///
107/// [`WasiCtxBuilder::build_p1`]: crate::WasiCtxBuilder::build_p1
108/// [`WasiCtxBuilder`]: crate::WasiCtxBuilder
109///
110/// # Examples
111///
112/// ```no_run
113/// use wasmtime::{Result, Linker};
114/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
115/// use wasmtime_wasi::WasiCtxBuilder;
116///
117/// struct MyState {
118///     // ... custom state as necessary ...
119///
120///     wasi: WasiP1Ctx,
121/// }
122///
123/// impl MyState {
124///     fn new() -> MyState {
125///         MyState {
126///             // .. initialize custom state if needed ..
127///
128///             wasi: WasiCtxBuilder::new()
129///                 .arg("./foo.wasm")
130///                 // .. more customization if necessary ..
131///                 .build_p1(),
132///         }
133///     }
134/// }
135///
136/// fn add_to_linker(linker: &mut Linker<MyState>) -> Result<()> {
137///     p1::add_to_linker_sync(linker, |my_state| &mut my_state.wasi)?;
138///     Ok(())
139/// }
140/// ```
141pub struct WasiP1Ctx {
142    table: ResourceTable,
143    wasi: WasiCtx,
144    adapter: WasiP1Adapter,
145    hostcall_fuel: usize,
146}
147
148impl WasiP1Ctx {
149    pub(crate) fn new(wasi: WasiCtx) -> Self {
150        Self {
151            table: ResourceTable::new(),
152            wasi,
153            adapter: WasiP1Adapter::new(),
154            hostcall_fuel: 0,
155        }
156    }
157
158    fn consume_fuel(&mut self, fuel: usize) -> Result<()> {
159        if fuel > self.hostcall_fuel {
160            return Err(types::Errno::Nomem.into());
161        }
162        self.hostcall_fuel -= fuel;
163        Ok(())
164    }
165
166    /// Assumes the host is going to copy all of `array` in which case a
167    /// corresponding amount of fuel is consumed to ensure it's not too large.
168    pub(crate) fn consume_fuel_for_array<T>(&mut self, array: wiggle::GuestPtr<[T]>) -> Result<()> {
169        let byte_size = usize::try_from(array.len())?
170            .checked_mul(size_of::<T>())
171            .ok_or(types::Errno::Overflow)?;
172        self.consume_fuel(byte_size)
173    }
174
175    /// Returns the first non-empty buffer in `ciovs` or a single empty buffer
176    /// if they're all empty.
177    ///
178    /// Additionally consumes a corresponding amount of fuel appropriate to the
179    /// size of `ciovs` and the first non-empty array.
180    fn first_non_empty_ciovec(
181        &mut self,
182        memory: &GuestMemory<'_>,
183        ciovs: types::CiovecArray,
184    ) -> Result<GuestPtr<[u8]>> {
185        self.consume_fuel_for_array(ciovs)?;
186        for iov in ciovs.iter() {
187            let iov = memory.read(iov?)?;
188            if iov.buf_len == 0 {
189                continue;
190            }
191            let ret = iov.buf.as_array(iov.buf_len);
192            self.consume_fuel_for_array(ret)?;
193            return Ok(ret);
194        }
195        Ok(GuestPtr::new((0, 0)))
196    }
197
198    /// Returns the first non-empty buffer in `iovs` or a single empty buffer if
199    /// they're all empty.
200    ///
201    /// Additionally consumes a corresponding amount of fuel appropriate to the
202    /// size of `ciovs` and the first non-empty array.
203    fn first_non_empty_iovec(
204        &mut self,
205        memory: &GuestMemory<'_>,
206        iovs: types::IovecArray,
207    ) -> Result<GuestPtr<[u8]>> {
208        self.consume_fuel_for_array(iovs)?;
209        for iov in iovs.iter() {
210            let iov = memory.read(iov?)?;
211            if iov.buf_len == 0 {
212                continue;
213            }
214            let ret = iov.buf.as_array(iov.buf_len);
215            self.consume_fuel_for_array(ret)?;
216            return Ok(ret);
217        }
218        Ok(GuestPtr::new((0, 0)))
219    }
220
221    /// Copies the guest string `ptr` into the host.
222    ///
223    /// Consumes a corresponding amount of fuel for the byte size of `ptr` and
224    /// fails if it's too large.
225    fn read_string(&mut self, memory: &GuestMemory<'_>, ptr: GuestPtr<str>) -> Result<String> {
226        self.consume_fuel(usize::try_from(ptr.len())?)?;
227        Ok(memory.as_cow_str(ptr)?.into_owned())
228    }
229}
230
231impl WasiView for WasiP1Ctx {
232    fn ctx(&mut self) -> WasiCtxView<'_> {
233        WasiCtxView {
234            ctx: &mut self.wasi,
235            table: &mut self.table,
236        }
237    }
238}
239
240#[derive(Debug)]
241struct File {
242    /// The handle to the preview2 descriptor of type [`crate::filesystem::Descriptor::File`].
243    fd: Resource<filesystem::Descriptor>,
244
245    /// The current-position pointer.
246    position: Arc<AtomicU64>,
247
248    /// In append mode, all writes append to the file.
249    append: bool,
250
251    /// When blocking, read and write calls dispatch to blocking_read and
252    /// blocking_check_write on the underlying streams. When false, read and write
253    /// dispatch to stream's plain read and check_write.
254    blocking_mode: BlockingMode,
255}
256
257/// NB: p1 files always use blocking writes regardless of what
258/// they're configured to use since OSes don't have nonblocking
259/// reads/writes anyway. This behavior originated in the first
260/// implementation of WASIp1 where flags were propagated to the
261/// OS and the OS ignored the nonblocking flag for files
262/// generally.
263#[derive(Clone, Copy, Debug)]
264enum BlockingMode {
265    Blocking,
266    NonBlocking,
267}
268impl BlockingMode {
269    fn from_fdflags(flags: &types::Fdflags) -> Self {
270        if flags.contains(types::Fdflags::NONBLOCK) {
271            BlockingMode::NonBlocking
272        } else {
273            BlockingMode::Blocking
274        }
275    }
276    async fn read(
277        &self,
278        host: &mut impl streams::HostInputStream,
279        input_stream: Resource<streams::InputStream>,
280        max_size: usize,
281    ) -> Result<Vec<u8>, types::Error> {
282        // For zero-length reads, the `read` man page says that it may or may
283        // not check for errors, and `pread` apparently just immediately returns
284        // zero while maybe validating things like an offset. Just return 0 here
285        // for now. Note that this doesn't naturally fall out of falling-through
286        // due to the `Intr`-return below.
287        if max_size == 0 {
288            return Ok(Vec::new());
289        }
290        let max_size = max_size.try_into().unwrap_or(u64::MAX);
291        match streams::HostInputStream::blocking_read(host, input_stream, max_size).await {
292            Ok(r) if r.is_empty() => Err(types::Errno::Intr.into()),
293            Ok(r) => Ok(r),
294            Err(StreamError::Closed) => Ok(Vec::new()),
295            Err(e) => Err(e.into()),
296        }
297    }
298    async fn write(
299        &self,
300        memory: &mut GuestMemory<'_>,
301        host: &mut impl streams::HostOutputStream,
302        output_stream: Resource<streams::OutputStream>,
303        bytes: GuestPtr<[u8]>,
304    ) -> StreamResult<usize> {
305        use streams::HostOutputStream as Streams;
306
307        let bytes = memory
308            .as_cow(bytes)
309            .map_err(|e| StreamError::Trap(e.into()))?;
310        let mut bytes = &bytes[..];
311
312        let total = bytes.len();
313        while !bytes.is_empty() {
314            // NOTE: blocking_write_and_flush takes at most one 4k buffer.
315            let len = bytes.len().min(4096);
316            let (chunk, rest) = bytes.split_at(len);
317            bytes = rest;
318
319            Streams::blocking_write_and_flush(host, output_stream.borrowed(), Vec::from(chunk))
320                .await?
321        }
322
323        Ok(total)
324    }
325}
326
327#[derive(Debug)]
328enum Descriptor {
329    Stdin {
330        stream: Resource<streams::InputStream>,
331        isatty: IsATTY,
332    },
333    Stdout {
334        stream: Resource<streams::OutputStream>,
335        isatty: IsATTY,
336    },
337    Stderr {
338        stream: Resource<streams::OutputStream>,
339        isatty: IsATTY,
340    },
341    /// A fd of type [`crate::filesystem::Descriptor::Dir`]
342    Directory {
343        fd: Resource<filesystem::Descriptor>,
344        /// The path this directory was preopened as.
345        /// `None` means this directory was opened using `open-at`.
346        preopen_path: Option<String>,
347    },
348    /// A fd of type [`crate::filesystem::Descriptor::File`]
349    File(File),
350}
351
352#[derive(Debug, Default)]
353struct WasiP1Adapter {
354    descriptors: Option<Descriptors>,
355}
356
357#[derive(Debug, Default)]
358struct Descriptors {
359    used: BTreeMap<u32, Descriptor>,
360    free: BTreeSet<u32>,
361}
362
363impl Descriptors {
364    /// Initializes [Self] using `preopens`
365    fn new(host: &mut WasiP1Ctx) -> Result<Self, types::Error> {
366        let mut descriptors = Self::default();
367        descriptors.push(Descriptor::Stdin {
368            stream: host
369                .cli()
370                .get_stdin()
371                .context("failed to call `get-stdin`")
372                .map_err(types::Error::trap)?,
373            isatty: if let Some(term_in) = host
374                .cli()
375                .get_terminal_stdin()
376                .context("failed to call `get-terminal-stdin`")
377                .map_err(types::Error::trap)?
378            {
379                terminal_input::HostTerminalInput::drop(&mut host.cli(), term_in)
380                    .context("failed to call `drop-terminal-input`")
381                    .map_err(types::Error::trap)?;
382                IsATTY::Yes
383            } else {
384                IsATTY::No
385            },
386        })?;
387        descriptors.push(Descriptor::Stdout {
388            stream: host
389                .cli()
390                .get_stdout()
391                .context("failed to call `get-stdout`")
392                .map_err(types::Error::trap)?,
393            isatty: if let Some(term_out) = host
394                .cli()
395                .get_terminal_stdout()
396                .context("failed to call `get-terminal-stdout`")
397                .map_err(types::Error::trap)?
398            {
399                terminal_output::HostTerminalOutput::drop(&mut host.cli(), term_out)
400                    .context("failed to call `drop-terminal-output`")
401                    .map_err(types::Error::trap)?;
402                IsATTY::Yes
403            } else {
404                IsATTY::No
405            },
406        })?;
407        descriptors.push(Descriptor::Stderr {
408            stream: host
409                .cli()
410                .get_stderr()
411                .context("failed to call `get-stderr`")
412                .map_err(types::Error::trap)?,
413            isatty: if let Some(term_out) = host
414                .cli()
415                .get_terminal_stderr()
416                .context("failed to call `get-terminal-stderr`")
417                .map_err(types::Error::trap)?
418            {
419                terminal_output::HostTerminalOutput::drop(&mut host.cli(), term_out)
420                    .context("failed to call `drop-terminal-output`")
421                    .map_err(types::Error::trap)?;
422                IsATTY::Yes
423            } else {
424                IsATTY::No
425            },
426        })?;
427
428        for dir in host
429            .filesystem()
430            .get_directories()
431            .context("failed to call `get-directories`")
432            .map_err(types::Error::trap)?
433        {
434            descriptors.push(Descriptor::Directory {
435                fd: dir.0,
436                preopen_path: Some(dir.1),
437            })?;
438        }
439        Ok(descriptors)
440    }
441
442    /// Returns next descriptor number, which was never assigned
443    fn unused(&self) -> Result<u32> {
444        match self.used.last_key_value() {
445            Some((fd, _)) => {
446                if let Some(fd) = fd.checked_add(1) {
447                    return Ok(fd);
448                }
449                if self.used.len() == u32::MAX as usize {
450                    return Err(types::Errno::Loop.into());
451                }
452                // TODO: Optimize
453                Ok((0..u32::MAX)
454                    .rev()
455                    .find(|fd| !self.used.contains_key(fd))
456                    .expect("failed to find an unused file descriptor"))
457            }
458            None => Ok(0),
459        }
460    }
461
462    /// Pushes the [Descriptor] returning corresponding number.
463    /// This operation will try to reuse numbers previously removed via [`Self::remove`]
464    /// and rely on [`Self::unused`] if no free numbers are recorded
465    fn push(&mut self, desc: Descriptor) -> Result<u32> {
466        let fd = if let Some(fd) = self.free.pop_last() {
467            fd
468        } else {
469            self.unused()?
470        };
471        assert!(self.used.insert(fd, desc).is_none());
472        Ok(fd)
473    }
474}
475
476impl WasiP1Adapter {
477    fn new() -> Self {
478        Self::default()
479    }
480}
481
482/// A mutably-borrowed `WasiP1Ctx`, which provides access to the stored
483/// state. It can be thought of as an in-flight [`WasiP1Adapter`] transaction, all
484/// changes will be recorded in the underlying [`WasiP1Adapter`] returned by
485/// [`WasiPreview1View::adapter_mut`] on [`Drop`] of this struct.
486// NOTE: This exists for the most part just due to the fact that `bindgen` generates methods with
487// `&mut self` receivers and so this struct lets us extend the lifetime of the `&mut self` borrow
488// of the [`WasiPreview1View`] to provide means to return mutably and immutably borrowed [`Descriptors`]
489// without having to rely on something like `Arc<Mutex<Descriptors>>`, while also being able to
490// call methods like [`Descriptor::is_file`] and hiding complexity from p1 method implementations.
491struct Transaction<'a> {
492    view: &'a mut WasiP1Ctx,
493    descriptors: Descriptors,
494}
495
496impl Drop for Transaction<'_> {
497    /// Record changes in the [`WasiP1Adapter`] .
498    fn drop(&mut self) {
499        let descriptors = mem::take(&mut self.descriptors);
500        self.view.adapter.descriptors = Some(descriptors);
501    }
502}
503
504impl Transaction<'_> {
505    /// Borrows [`Descriptor`] corresponding to `fd`.
506    ///
507    /// # Errors
508    ///
509    /// Returns [`types::Errno::Badf`] if no [`Descriptor`] is found
510    fn get_descriptor(&self, fd: types::Fd) -> Result<&Descriptor> {
511        let fd = fd.into();
512        let desc = self.descriptors.used.get(&fd).ok_or(types::Errno::Badf)?;
513        Ok(desc)
514    }
515
516    /// Borrows [`File`] corresponding to `fd`
517    /// if it describes a [`Descriptor::File`]
518    fn get_file(&self, fd: types::Fd) -> Result<&File> {
519        let fd = fd.into();
520        match self.descriptors.used.get(&fd) {
521            Some(Descriptor::File(file)) => Ok(file),
522            _ => Err(types::Errno::Badf.into()),
523        }
524    }
525
526    /// Mutably borrows [`File`] corresponding to `fd`
527    /// if it describes a [`Descriptor::File`]
528    fn get_file_mut(&mut self, fd: types::Fd) -> Result<&mut File> {
529        let fd = fd.into();
530        match self.descriptors.used.get_mut(&fd) {
531            Some(Descriptor::File(file)) => Ok(file),
532            _ => Err(types::Errno::Badf.into()),
533        }
534    }
535
536    /// Borrows [`File`] corresponding to `fd`
537    /// if it describes a [`Descriptor::File`]
538    ///
539    /// # Errors
540    ///
541    /// Returns [`types::Errno::Spipe`] if the descriptor corresponds to stdio
542    fn get_seekable(&self, fd: types::Fd) -> Result<&File> {
543        let fd = fd.into();
544        match self.descriptors.used.get(&fd) {
545            Some(Descriptor::File(file)) => Ok(file),
546            Some(
547                Descriptor::Stdin { .. } | Descriptor::Stdout { .. } | Descriptor::Stderr { .. },
548            ) => {
549                // NOTE: legacy implementation returns SPIPE here
550                Err(types::Errno::Spipe.into())
551            }
552            _ => Err(types::Errno::Badf.into()),
553        }
554    }
555
556    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
557    fn get_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
558        match self.get_descriptor(fd)? {
559            Descriptor::File(File { fd, .. }) => Ok(fd.borrowed()),
560            Descriptor::Directory { fd, .. } => Ok(fd.borrowed()),
561            Descriptor::Stdin { .. } | Descriptor::Stdout { .. } | Descriptor::Stderr { .. } => {
562                Err(types::Errno::Badf.into())
563            }
564        }
565    }
566
567    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
568    /// if it describes a [`Descriptor::File`]
569    fn get_file_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
570        self.get_file(fd).map(|File { fd, .. }| fd.borrowed())
571    }
572
573    /// Returns [`filesystem::Descriptor`] corresponding to `fd`
574    /// if it describes a [`Descriptor::Directory`]
575    fn get_dir_fd(&self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>> {
576        let fd = fd.into();
577        match self.descriptors.used.get(&fd) {
578            Some(Descriptor::Directory { fd, .. }) => Ok(fd.borrowed()),
579            _ => Err(types::Errno::Badf.into()),
580        }
581    }
582}
583
584impl WasiP1Ctx {
585    /// Lazily initializes [`WasiP1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
586    /// and returns [`Transaction`] on success
587    fn transact(&mut self) -> Result<Transaction<'_>, types::Error> {
588        let descriptors = if let Some(descriptors) = self.adapter.descriptors.take() {
589            descriptors
590        } else {
591            Descriptors::new(self)?
592        };
593        Ok(Transaction {
594            view: self,
595            descriptors,
596        })
597    }
598
599    /// Lazily initializes [`WasiP1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
600    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
601    fn get_fd(&mut self, fd: types::Fd) -> Result<Resource<filesystem::Descriptor>, types::Error> {
602        let st = self.transact()?;
603        let fd = st.get_fd(fd)?;
604        Ok(fd)
605    }
606
607    /// Lazily initializes [`WasiP1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
608    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
609    /// if it describes a [`Descriptor::File`] of [`crate::p2::filesystem::File`] type
610    fn get_file_fd(
611        &mut self,
612        fd: types::Fd,
613    ) -> Result<Resource<filesystem::Descriptor>, types::Error> {
614        let st = self.transact()?;
615        let fd = st.get_file_fd(fd)?;
616        Ok(fd)
617    }
618
619    /// Lazily initializes [`WasiP1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
620    /// and returns [`filesystem::Descriptor`] corresponding to `fd`
621    /// if it describes a [`Descriptor::File`] or [`Descriptor::PreopenDirectory`]
622    /// of [`crate::p2::filesystem::Dir`] type
623    fn get_dir_fd(
624        &mut self,
625        fd: types::Fd,
626    ) -> Result<Resource<filesystem::Descriptor>, types::Error> {
627        let st = self.transact()?;
628        let fd = st.get_dir_fd(fd)?;
629        Ok(fd)
630    }
631
632    /// Shared implementation of `fd_write` and `fd_pwrite`.
633    async fn fd_write_impl(
634        &mut self,
635        memory: &mut GuestMemory<'_>,
636        fd: types::Fd,
637        ciovs: types::CiovecArray,
638        write: FdWrite,
639    ) -> Result<types::Size, types::Error> {
640        let buf = self.first_non_empty_ciovec(memory, ciovs)?;
641        let t = self.transact()?;
642        let desc = t.get_descriptor(fd)?;
643        match desc {
644            Descriptor::File(File {
645                fd,
646                append,
647                position,
648                // NB: files always use blocking writes regardless of what
649                // they're configured to use since OSes don't have nonblocking
650                // reads/writes anyway. This behavior originated in the first
651                // implementation of WASIp1 where flags were propagated to the
652                // OS and the OS ignored the nonblocking flag for files
653                // generally.
654                blocking_mode: _,
655            }) => {
656                let fd = fd.borrowed();
657                let position = position.clone();
658                let pos = position.load(Ordering::Relaxed);
659                let append = *append;
660                drop(t);
661                let f = self.table.get(&fd)?.file()?;
662
663                let do_write = move |f: &std::fs::File, buf: &[u8]| match (append, write) {
664                    // Note that this is implementing Linux semantics of
665                    // `pwrite` where the offset is ignored if the file was
666                    // opened in append mode.
667                    (true, _) => primitives::append_cursor_unspecified(f, &buf),
668                    (false, FdWrite::At(pos)) => {
669                        primitives::write_at_cursor_unspecified(f, &buf, pos)
670                    }
671                    (false, FdWrite::AtCur) => {
672                        primitives::write_at_cursor_unspecified(f, &buf, pos)
673                    }
674                };
675
676                let nwritten = match f.as_blocking_file() {
677                    // If we can block then skip the copy out of wasm memory and
678                    // write directly to `f`.
679                    Some(f) => do_write(f, &memory.as_cow(buf)?),
680                    // ... otherwise copy out of wasm memory and use
681                    // `spawn_blocking` to do this write in a thread that can
682                    // block.
683                    None => {
684                        let buf = memory.to_vec(buf)?;
685                        f.run_blocking(move |f| do_write(f, &buf)).await
686                    }
687                };
688
689                let nwritten = nwritten.map_err(|e| StreamError::LastOperationFailed(e.into()))?;
690
691                // If this was a write at the current position then update the
692                // current position with the result, otherwise the current
693                // position is left unmodified.
694                if let FdWrite::AtCur = write {
695                    if append {
696                        let len = self.filesystem().stat(fd).await?;
697                        position.store(len.size, Ordering::Relaxed);
698                    } else {
699                        let pos = pos
700                            .checked_add(nwritten as u64)
701                            .ok_or(types::Errno::Overflow)?;
702                        position.store(pos, Ordering::Relaxed);
703                    }
704                }
705                Ok(nwritten.try_into()?)
706            }
707            Descriptor::Stdout { stream, .. } | Descriptor::Stderr { stream, .. } => {
708                match write {
709                    // Reject calls to `fd_pwrite` on stdio descriptors...
710                    FdWrite::At(_) => return Err(types::Errno::Spipe.into()),
711                    // ... but allow calls to `fd_write`
712                    FdWrite::AtCur => {}
713                }
714                let stream = stream.borrowed();
715                drop(t);
716                let n = BlockingMode::Blocking
717                    .write(memory, &mut self.table, stream, buf)
718                    .await?
719                    .try_into()?;
720                Ok(n)
721            }
722            _ => Err(types::Errno::Badf.into()),
723        }
724    }
725}
726
727#[derive(Copy, Clone)]
728enum FdWrite {
729    At(u64),
730    AtCur,
731}
732
733/// Adds asynchronous versions of all WASIp1 functions to the
734/// [`wasmtime::Linker`] provided.
735///
736/// This method will add WASIp1 functions to `linker`. Access to [`WasiP1Ctx`]
737/// is provided with `f` by projecting from the store-local state of `T` to
738/// [`WasiP1Ctx`]. The closure `f` is invoked every time a WASIp1 function is
739/// called to get access to [`WasiP1Ctx`] from `T`. The returned [`WasiP1Ctx`] is
740/// used to implement I/O and controls what each function will return.
741///
742/// It's recommended that [`WasiP1Ctx`] is stored as a field in `T` or that `T =
743/// WasiP1Ctx` itself. The closure `f` should be a small projection (e.g. `&mut
744/// arg.field`) or something otherwise "small" as it will be executed every time
745/// a WASI call is made.
746///
747/// If you're looking for a synchronous version see [`add_to_linker_sync`].
748///
749/// # Examples
750///
751/// If the `T` in `Linker<T>` is just `WasiP1Ctx`:
752///
753/// ```no_run
754/// use wasmtime::{Result, Linker, Engine, Config};
755/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
756///
757/// fn main() -> Result<()> {
758///     let engine = Engine::default();
759///
760///     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
761///     p1::add_to_linker_async(&mut linker, |cx| cx)?;
762///
763///     // ... continue to add more to `linker` as necessary and use it ...
764///
765///     Ok(())
766/// }
767/// ```
768///
769/// If the `T` in `Linker<T>` is custom state:
770///
771/// ```no_run
772/// use wasmtime::{Result, Linker, Engine, Config};
773/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
774///
775/// struct MyState {
776///     // .. other custom state here ..
777///
778///     wasi: WasiP1Ctx,
779/// }
780///
781/// fn main() -> Result<()> {
782///     let engine = Engine::default();
783///
784///     let mut linker: Linker<MyState> = Linker::new(&engine);
785///     p1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
786///
787///     // ... continue to add more to `linker` as necessary and use it ...
788///
789///     Ok(())
790/// }
791/// ```
792pub fn add_to_linker_async<T: Send + 'static>(
793    linker: &mut wasmtime::Linker<T>,
794    f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static,
795) -> wasmtime::Result<()> {
796    crate::p1::wasi_snapshot_preview1::add_to_linker(linker, f)
797}
798
799/// Adds synchronous versions of all WASIp1 functions to the
800/// [`wasmtime::Linker`] provided.
801///
802/// This method will add WASIp1 functions to `linker`. Access to [`WasiP1Ctx`]
803/// is provided with `f` by projecting from the store-local state of `T` to
804/// [`WasiP1Ctx`]. The closure `f` is invoked every time a WASIp1 function is
805/// called to get access to [`WasiP1Ctx`] from `T`. The returned [`WasiP1Ctx`] is
806/// used to implement I/O and controls what each function will return.
807///
808/// It's recommended that [`WasiP1Ctx`] is stored as a field in `T` or that `T =
809/// WasiP1Ctx` itself. The closure `f` should be a small projection (e.g. `&mut
810/// arg.field`) or something otherwise "small" as it will be executed every time
811/// a WASI call is made.
812///
813/// If you're looking for a synchronous version see [`add_to_linker_async`].
814///
815/// # Examples
816///
817/// If the `T` in `Linker<T>` is just `WasiP1Ctx`:
818///
819/// ```no_run
820/// use wasmtime::{Result, Linker, Engine};
821/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
822///
823/// fn main() -> Result<()> {
824///     let engine = Engine::default();
825///
826///     let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
827///     p1::add_to_linker_async(&mut linker, |cx| cx)?;
828///
829///     // ... continue to add more to `linker` as necessary and use it ...
830///
831///     Ok(())
832/// }
833/// ```
834///
835/// If the `T` in `Linker<T>` is custom state:
836///
837/// ```no_run
838/// use wasmtime::{Result, Linker, Engine};
839/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
840///
841/// struct MyState {
842///     // .. other custom state here ..
843///
844///     wasi: WasiP1Ctx,
845/// }
846///
847/// fn main() -> Result<()> {
848///     let engine = Engine::default();
849///
850///     let mut linker: Linker<MyState> = Linker::new(&engine);
851///     p1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
852///
853///     // ... continue to add more to `linker` as necessary and use it ...
854///
855///     Ok(())
856/// }
857/// ```
858pub fn add_to_linker_sync<T: Send + 'static>(
859    linker: &mut wasmtime::Linker<T>,
860    f: impl Fn(&mut T) -> &mut WasiP1Ctx + Copy + Send + Sync + 'static,
861) -> wasmtime::Result<()> {
862    sync::add_wasi_snapshot_preview1_to_linker(linker, f)
863}
864
865// Generate the wasi_snapshot_preview1::WasiSnapshotPreview1 trait,
866// and the module types.
867// None of the generated modules, traits, or types should be used externally
868// to this module.
869wiggle::from_witx!({
870    witx: ["witx/p1/wasi_snapshot_preview1.witx"],
871    async: {
872        wasi_snapshot_preview1::{
873            fd_advise, fd_close, fd_datasync, fd_fdstat_get, fd_filestat_get, fd_filestat_set_size,
874            fd_filestat_set_times, fd_read, fd_pread, fd_seek, fd_sync, fd_readdir, fd_write,
875            fd_pwrite, poll_oneoff, path_create_directory, path_filestat_get,
876            path_filestat_set_times, path_link, path_open, path_readlink, path_remove_directory,
877            path_rename, path_symlink, path_unlink_file, fd_renumber
878        }
879    },
880    errors: { errno => trappable Error },
881});
882
883pub(crate) mod sync {
884    use std::future::Future;
885    use wasmtime::Result;
886
887    wiggle::wasmtime_integration!({
888        witx: ["witx/p1/wasi_snapshot_preview1.witx"],
889        target: super,
890        block_on[in_tokio]: {
891            wasi_snapshot_preview1::{
892                fd_advise, fd_close, fd_datasync, fd_fdstat_get, fd_filestat_get, fd_filestat_set_size,
893                fd_filestat_set_times, fd_read, fd_pread, fd_seek, fd_sync, fd_readdir, fd_write,
894                fd_pwrite, poll_oneoff, path_create_directory, path_filestat_get,
895                path_filestat_set_times, path_link, path_open, path_readlink, path_remove_directory,
896                path_rename, path_symlink, path_unlink_file, fd_renumber
897            }
898        },
899        errors: { errno => trappable Error },
900    });
901
902    // Small wrapper around `in_tokio` to add a `Result` layer which is always
903    // `Ok`
904    fn in_tokio<F: Future>(future: F) -> Result<F::Output> {
905        Ok(crate::runtime::in_tokio(future))
906    }
907}
908
909impl wiggle::GuestErrorType for types::Errno {
910    fn success() -> Self {
911        Self::Success
912    }
913}
914
915impl From<StreamError> for types::Error {
916    fn from(err: StreamError) -> Self {
917        match err {
918            StreamError::Closed => types::Errno::Io.into(),
919            StreamError::LastOperationFailed(e) => match e.downcast::<std::io::Error>() {
920                Ok(err) => filesystem::ErrorCode::from(err).into(),
921                Err(e) => {
922                    tracing::debug!("dropping error {e:?}");
923                    types::Errno::Io.into()
924                }
925            },
926            StreamError::Trap(e) => types::Error::trap(e),
927        }
928    }
929}
930
931impl From<FsError> for types::Error {
932    fn from(err: FsError) -> Self {
933        match err.downcast() {
934            Ok(code) => code.into(),
935            Err(e) => types::Error::trap(e),
936        }
937    }
938}
939
940fn systimespec(set: bool, ts: types::Timestamp, now: bool) -> Result<filesystem::NewTimestamp> {
941    if set && now {
942        Err(types::Errno::Inval.into())
943    } else if set {
944        Ok(filesystem::NewTimestamp::Timestamp(filesystem::Datetime {
945            seconds: ts / 1_000_000_000,
946            nanoseconds: (ts % 1_000_000_000) as _,
947        }))
948    } else if now {
949        Ok(filesystem::NewTimestamp::Now)
950    } else {
951        Ok(filesystem::NewTimestamp::NoChange)
952    }
953}
954
955impl TryFrom<wall_clock::Datetime> for types::Timestamp {
956    type Error = types::Errno;
957
958    fn try_from(
959        wall_clock::Datetime {
960            seconds,
961            nanoseconds,
962        }: wall_clock::Datetime,
963    ) -> Result<Self, Self::Error> {
964        types::Timestamp::from(seconds)
965            .checked_mul(1_000_000_000)
966            .and_then(|ns| ns.checked_add(nanoseconds.into()))
967            .ok_or(types::Errno::Overflow)
968    }
969}
970
971impl From<types::Lookupflags> for filesystem::PathFlags {
972    fn from(flags: types::Lookupflags) -> Self {
973        if flags.contains(types::Lookupflags::SYMLINK_FOLLOW) {
974            filesystem::PathFlags::SYMLINK_FOLLOW
975        } else {
976            filesystem::PathFlags::empty()
977        }
978    }
979}
980
981impl From<types::Oflags> for filesystem::OpenFlags {
982    fn from(flags: types::Oflags) -> Self {
983        let mut out = filesystem::OpenFlags::empty();
984        if flags.contains(types::Oflags::CREAT) {
985            out |= filesystem::OpenFlags::CREATE;
986        }
987        if flags.contains(types::Oflags::DIRECTORY) {
988            out |= filesystem::OpenFlags::DIRECTORY;
989        }
990        if flags.contains(types::Oflags::EXCL) {
991            out |= filesystem::OpenFlags::EXCLUSIVE;
992        }
993        if flags.contains(types::Oflags::TRUNC) {
994            out |= filesystem::OpenFlags::TRUNCATE;
995        }
996        out
997    }
998}
999
1000impl From<types::Advice> for filesystem::Advice {
1001    fn from(advice: types::Advice) -> Self {
1002        match advice {
1003            types::Advice::Normal => filesystem::Advice::Normal,
1004            types::Advice::Sequential => filesystem::Advice::Sequential,
1005            types::Advice::Random => filesystem::Advice::Random,
1006            types::Advice::Willneed => filesystem::Advice::WillNeed,
1007            types::Advice::Dontneed => filesystem::Advice::DontNeed,
1008            types::Advice::Noreuse => filesystem::Advice::NoReuse,
1009        }
1010    }
1011}
1012
1013impl TryFrom<filesystem::DescriptorType> for types::Filetype {
1014    type Error = wasmtime::Error;
1015
1016    fn try_from(ty: filesystem::DescriptorType) -> Result<Self, Self::Error> {
1017        match ty {
1018            filesystem::DescriptorType::RegularFile => Ok(types::Filetype::RegularFile),
1019            filesystem::DescriptorType::Directory => Ok(types::Filetype::Directory),
1020            filesystem::DescriptorType::BlockDevice => Ok(types::Filetype::BlockDevice),
1021            filesystem::DescriptorType::CharacterDevice => Ok(types::Filetype::CharacterDevice),
1022            // p1 never had a FIFO code.
1023            filesystem::DescriptorType::Fifo => Ok(types::Filetype::Unknown),
1024            // TODO: Add a way to disginguish between FILETYPE_SOCKET_STREAM and
1025            // FILETYPE_SOCKET_DGRAM.
1026            filesystem::DescriptorType::Socket => {
1027                bail!("sockets are not currently supported")
1028            }
1029            filesystem::DescriptorType::SymbolicLink => Ok(types::Filetype::SymbolicLink),
1030            filesystem::DescriptorType::Unknown => Ok(types::Filetype::Unknown),
1031        }
1032    }
1033}
1034
1035impl From<IsATTY> for types::Filetype {
1036    fn from(isatty: IsATTY) -> Self {
1037        match isatty {
1038            IsATTY::Yes => types::Filetype::CharacterDevice,
1039            IsATTY::No => types::Filetype::Unknown,
1040        }
1041    }
1042}
1043
1044impl From<crate::filesystem::ErrorCode> for types::Errno {
1045    fn from(code: crate::filesystem::ErrorCode) -> Self {
1046        match code {
1047            crate::filesystem::ErrorCode::Access => types::Errno::Acces,
1048            crate::filesystem::ErrorCode::Already => types::Errno::Already,
1049            crate::filesystem::ErrorCode::BadDescriptor => types::Errno::Badf,
1050            crate::filesystem::ErrorCode::Busy => types::Errno::Busy,
1051            crate::filesystem::ErrorCode::Exist => types::Errno::Exist,
1052            crate::filesystem::ErrorCode::FileTooLarge => types::Errno::Fbig,
1053            crate::filesystem::ErrorCode::IllegalByteSequence => types::Errno::Ilseq,
1054            crate::filesystem::ErrorCode::InProgress => types::Errno::Inprogress,
1055            crate::filesystem::ErrorCode::Interrupted => types::Errno::Intr,
1056            crate::filesystem::ErrorCode::Invalid => types::Errno::Inval,
1057            crate::filesystem::ErrorCode::Io => types::Errno::Io,
1058            crate::filesystem::ErrorCode::IsDirectory => types::Errno::Isdir,
1059            crate::filesystem::ErrorCode::Loop => types::Errno::Loop,
1060            crate::filesystem::ErrorCode::TooManyLinks => types::Errno::Mlink,
1061            crate::filesystem::ErrorCode::NameTooLong => types::Errno::Nametoolong,
1062            crate::filesystem::ErrorCode::NoEntry => types::Errno::Noent,
1063            crate::filesystem::ErrorCode::InsufficientMemory => types::Errno::Nomem,
1064            crate::filesystem::ErrorCode::InsufficientSpace => types::Errno::Nospc,
1065            crate::filesystem::ErrorCode::Unsupported => types::Errno::Notsup,
1066            crate::filesystem::ErrorCode::NotDirectory => types::Errno::Notdir,
1067            crate::filesystem::ErrorCode::NotEmpty => types::Errno::Notempty,
1068            crate::filesystem::ErrorCode::Overflow => types::Errno::Overflow,
1069            crate::filesystem::ErrorCode::NotPermitted => types::Errno::Perm,
1070            crate::filesystem::ErrorCode::Pipe => types::Errno::Pipe,
1071            crate::filesystem::ErrorCode::InvalidSeek => types::Errno::Spipe,
1072        }
1073    }
1074}
1075
1076impl From<filesystem::ErrorCode> for types::Errno {
1077    fn from(code: filesystem::ErrorCode) -> Self {
1078        match code {
1079            filesystem::ErrorCode::Access => types::Errno::Acces,
1080            filesystem::ErrorCode::WouldBlock => types::Errno::Again,
1081            filesystem::ErrorCode::Already => types::Errno::Already,
1082            filesystem::ErrorCode::BadDescriptor => types::Errno::Badf,
1083            filesystem::ErrorCode::Busy => types::Errno::Busy,
1084            filesystem::ErrorCode::Deadlock => types::Errno::Deadlk,
1085            filesystem::ErrorCode::Quota => types::Errno::Dquot,
1086            filesystem::ErrorCode::Exist => types::Errno::Exist,
1087            filesystem::ErrorCode::FileTooLarge => types::Errno::Fbig,
1088            filesystem::ErrorCode::IllegalByteSequence => types::Errno::Ilseq,
1089            filesystem::ErrorCode::InProgress => types::Errno::Inprogress,
1090            filesystem::ErrorCode::Interrupted => types::Errno::Intr,
1091            filesystem::ErrorCode::Invalid => types::Errno::Inval,
1092            filesystem::ErrorCode::Io => types::Errno::Io,
1093            filesystem::ErrorCode::IsDirectory => types::Errno::Isdir,
1094            filesystem::ErrorCode::Loop => types::Errno::Loop,
1095            filesystem::ErrorCode::TooManyLinks => types::Errno::Mlink,
1096            filesystem::ErrorCode::MessageSize => types::Errno::Msgsize,
1097            filesystem::ErrorCode::NameTooLong => types::Errno::Nametoolong,
1098            filesystem::ErrorCode::NoDevice => types::Errno::Nodev,
1099            filesystem::ErrorCode::NoEntry => types::Errno::Noent,
1100            filesystem::ErrorCode::NoLock => types::Errno::Nolck,
1101            filesystem::ErrorCode::InsufficientMemory => types::Errno::Nomem,
1102            filesystem::ErrorCode::InsufficientSpace => types::Errno::Nospc,
1103            filesystem::ErrorCode::Unsupported => types::Errno::Notsup,
1104            filesystem::ErrorCode::NotDirectory => types::Errno::Notdir,
1105            filesystem::ErrorCode::NotEmpty => types::Errno::Notempty,
1106            filesystem::ErrorCode::NotRecoverable => types::Errno::Notrecoverable,
1107            filesystem::ErrorCode::NoTty => types::Errno::Notty,
1108            filesystem::ErrorCode::NoSuchDevice => types::Errno::Nxio,
1109            filesystem::ErrorCode::Overflow => types::Errno::Overflow,
1110            filesystem::ErrorCode::NotPermitted => types::Errno::Perm,
1111            filesystem::ErrorCode::Pipe => types::Errno::Pipe,
1112            filesystem::ErrorCode::ReadOnly => types::Errno::Rofs,
1113            filesystem::ErrorCode::InvalidSeek => types::Errno::Spipe,
1114            filesystem::ErrorCode::TextFileBusy => types::Errno::Txtbsy,
1115            filesystem::ErrorCode::CrossDevice => types::Errno::Xdev,
1116        }
1117    }
1118}
1119
1120impl From<std::num::TryFromIntError> for types::Error {
1121    fn from(_: std::num::TryFromIntError) -> Self {
1122        types::Errno::Overflow.into()
1123    }
1124}
1125
1126impl From<GuestError> for types::Error {
1127    fn from(err: GuestError) -> Self {
1128        use wiggle::GuestError::*;
1129        match err {
1130            InvalidFlagValue { .. } => types::Errno::Inval.into(),
1131            InvalidEnumValue { .. } => types::Errno::Inval.into(),
1132            // As per
1133            // https://github.com/WebAssembly/wasi/blob/main/legacy/tools/witx-docs.md#pointers
1134            //
1135            // > If a misaligned pointer is passed to a function, the function
1136            // > shall trap.
1137            // >
1138            // > If an out-of-bounds pointer is passed to a function and the
1139            // > function needs to dereference it, the function shall trap.
1140            //
1141            // so this turns OOB and misalignment errors into traps.
1142            PtrOverflow { .. } | PtrOutOfBounds { .. } | PtrNotAligned { .. } => {
1143                types::Error::trap(err.into())
1144            }
1145            InvalidUtf8 { .. } => types::Errno::Ilseq.into(),
1146            TryFromIntError { .. } => types::Errno::Overflow.into(),
1147            SliceLengthsDiffer { .. } => types::Errno::Fault.into(),
1148            InFunc { err, .. } => types::Error::from(*err),
1149        }
1150    }
1151}
1152
1153impl From<filesystem::ErrorCode> for types::Error {
1154    fn from(code: filesystem::ErrorCode) -> Self {
1155        types::Errno::from(code).into()
1156    }
1157}
1158
1159impl From<crate::filesystem::ErrorCode> for types::Error {
1160    fn from(code: crate::filesystem::ErrorCode) -> Self {
1161        types::Errno::from(code).into()
1162    }
1163}
1164
1165impl From<wasmtime::component::ResourceTableError> for types::Error {
1166    fn from(err: wasmtime::component::ResourceTableError) -> Self {
1167        types::Error::trap(err.into())
1168    }
1169}
1170
1171type Result<T, E = types::Error> = std::result::Result<T, E>;
1172
1173fn write_bytes(
1174    memory: &mut GuestMemory<'_>,
1175    ptr: GuestPtr<u8>,
1176    buf: &[u8],
1177) -> Result<GuestPtr<u8>, types::Error> {
1178    // NOTE: legacy implementation always returns Inval errno
1179
1180    let len = u32::try_from(buf.len())?;
1181
1182    memory.copy_from_slice(buf, ptr.as_array(len))?;
1183    let next = ptr.add(len)?;
1184    Ok(next)
1185}
1186
1187fn write_byte(memory: &mut GuestMemory<'_>, ptr: GuestPtr<u8>, byte: u8) -> Result<GuestPtr<u8>> {
1188    memory.write(ptr, byte)?;
1189    let next = ptr.add(1)?;
1190    Ok(next)
1191}
1192
1193// Implement the WasiSnapshotPreview1 trait using only the traits that are
1194// required for T, i.e., in terms of the preview 2 wit interface, and state
1195// stored in the WasiP1Adapter struct.
1196impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiP1Ctx {
1197    fn set_hostcall_fuel(&mut self, fuel: usize) {
1198        self.hostcall_fuel = fuel;
1199    }
1200
1201    #[instrument(skip(self, memory))]
1202    fn args_get(
1203        &mut self,
1204        memory: &mut GuestMemory<'_>,
1205        argv: GuestPtr<GuestPtr<u8>>,
1206        argv_buf: GuestPtr<u8>,
1207    ) -> Result<(), types::Error> {
1208        self.cli()
1209            .get_arguments()
1210            .context("failed to call `get-arguments`")
1211            .map_err(types::Error::trap)?
1212            .into_iter()
1213            .try_fold((argv, argv_buf), |(argv, argv_buf), arg| -> Result<_> {
1214                memory.write(argv, argv_buf)?;
1215                let argv = argv.add(1)?;
1216
1217                let argv_buf = write_bytes(memory, argv_buf, arg.as_bytes())?;
1218                let argv_buf = write_byte(memory, argv_buf, 0)?;
1219
1220                Ok((argv, argv_buf))
1221            })?;
1222        Ok(())
1223    }
1224
1225    #[instrument(skip(self, _memory))]
1226    fn args_sizes_get(
1227        &mut self,
1228        _memory: &mut GuestMemory<'_>,
1229    ) -> Result<(types::Size, types::Size), types::Error> {
1230        let args = self
1231            .cli()
1232            .get_arguments()
1233            .context("failed to call `get-arguments`")
1234            .map_err(types::Error::trap)?;
1235        let num = args.len().try_into().map_err(|_| types::Errno::Overflow)?;
1236        let len = args
1237            .iter()
1238            .map(|buf| buf.len() + 1) // Each argument is expected to be `\0` terminated.
1239            .sum::<usize>()
1240            .try_into()
1241            .map_err(|_| types::Errno::Overflow)?;
1242        Ok((num, len))
1243    }
1244
1245    #[instrument(skip(self, memory))]
1246    fn environ_get(
1247        &mut self,
1248        memory: &mut GuestMemory<'_>,
1249        environ: GuestPtr<GuestPtr<u8>>,
1250        environ_buf: GuestPtr<u8>,
1251    ) -> Result<(), types::Error> {
1252        self.cli()
1253            .get_environment()
1254            .context("failed to call `get-environment`")
1255            .map_err(types::Error::trap)?
1256            .into_iter()
1257            .try_fold(
1258                (environ, environ_buf),
1259                |(environ, environ_buf), (k, v)| -> Result<_, types::Error> {
1260                    memory.write(environ, environ_buf)?;
1261                    let environ = environ.add(1)?;
1262
1263                    let environ_buf = write_bytes(memory, environ_buf, k.as_bytes())?;
1264                    let environ_buf = write_byte(memory, environ_buf, b'=')?;
1265                    let environ_buf = write_bytes(memory, environ_buf, v.as_bytes())?;
1266                    let environ_buf = write_byte(memory, environ_buf, 0)?;
1267
1268                    Ok((environ, environ_buf))
1269                },
1270            )?;
1271        Ok(())
1272    }
1273
1274    #[instrument(skip(self, _memory))]
1275    fn environ_sizes_get(
1276        &mut self,
1277        _memory: &mut GuestMemory<'_>,
1278    ) -> Result<(types::Size, types::Size), types::Error> {
1279        let environ = self
1280            .cli()
1281            .get_environment()
1282            .context("failed to call `get-environment`")
1283            .map_err(types::Error::trap)?;
1284        let num = environ.len().try_into()?;
1285        let len = environ
1286            .iter()
1287            .map(|(k, v)| k.len() + 1 + v.len() + 1) // Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
1288            .sum::<usize>()
1289            .try_into()?;
1290        Ok((num, len))
1291    }
1292
1293    #[instrument(skip(self, _memory))]
1294    fn clock_res_get(
1295        &mut self,
1296        _memory: &mut GuestMemory<'_>,
1297        id: types::Clockid,
1298    ) -> Result<types::Timestamp, types::Error> {
1299        let res = match id {
1300            types::Clockid::Realtime => wall_clock::Host::resolution(&mut self.clocks())
1301                .context("failed to call `wall_clock::resolution`")
1302                .map_err(types::Error::trap)?
1303                .try_into()?,
1304            types::Clockid::Monotonic => monotonic_clock::Host::resolution(&mut self.clocks())
1305                .context("failed to call `monotonic_clock::resolution`")
1306                .map_err(types::Error::trap)?,
1307            types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
1308                return Err(types::Errno::Badf.into());
1309            }
1310        };
1311        Ok(res)
1312    }
1313
1314    #[instrument(skip(self, _memory))]
1315    fn clock_time_get(
1316        &mut self,
1317        _memory: &mut GuestMemory<'_>,
1318        id: types::Clockid,
1319        _precision: types::Timestamp,
1320    ) -> Result<types::Timestamp, types::Error> {
1321        let now = match id {
1322            types::Clockid::Realtime => wall_clock::Host::now(&mut self.clocks())
1323                .context("failed to call `wall_clock::now`")
1324                .map_err(types::Error::trap)?
1325                .try_into()?,
1326            types::Clockid::Monotonic => monotonic_clock::Host::now(&mut self.clocks())
1327                .context("failed to call `monotonic_clock::now`")
1328                .map_err(types::Error::trap)?,
1329            types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
1330                return Err(types::Errno::Badf.into());
1331            }
1332        };
1333        Ok(now)
1334    }
1335
1336    #[instrument(skip(self, _memory))]
1337    async fn fd_advise(
1338        &mut self,
1339        _memory: &mut GuestMemory<'_>,
1340        fd: types::Fd,
1341        offset: types::Filesize,
1342        len: types::Filesize,
1343        advice: types::Advice,
1344    ) -> Result<(), types::Error> {
1345        let fd = self.get_file_fd(fd)?;
1346        self.filesystem()
1347            .advise(fd, offset, len, advice.into())
1348            .await?;
1349        Ok(())
1350    }
1351
1352    /// Force the allocation of space in a file.
1353    /// NOTE: This is similar to `posix_fallocate` in POSIX.
1354    #[instrument(skip(self, _memory))]
1355    fn fd_allocate(
1356        &mut self,
1357        _memory: &mut GuestMemory<'_>,
1358        fd: types::Fd,
1359        _offset: types::Filesize,
1360        _len: types::Filesize,
1361    ) -> Result<(), types::Error> {
1362        self.get_file_fd(fd)?;
1363        Err(types::Errno::Notsup.into())
1364    }
1365
1366    /// Close a file descriptor.
1367    /// NOTE: This is similar to `close` in POSIX.
1368    #[instrument(skip(self, _memory))]
1369    async fn fd_close(
1370        &mut self,
1371        _memory: &mut GuestMemory<'_>,
1372        fd: types::Fd,
1373    ) -> Result<(), types::Error> {
1374        let desc = {
1375            let fd = fd.into();
1376            let mut st = self.transact()?;
1377            let desc = st.descriptors.used.remove(&fd).ok_or(types::Errno::Badf)?;
1378            st.descriptors.free.insert(fd);
1379            desc
1380        };
1381        match desc {
1382            Descriptor::Stdin { stream, .. } => {
1383                streams::HostInputStream::drop(&mut self.table, stream)
1384                    .await
1385                    .context("failed to call `drop` on `input-stream`")
1386            }
1387            Descriptor::Stdout { stream, .. } | Descriptor::Stderr { stream, .. } => {
1388                streams::HostOutputStream::drop(&mut self.table, stream)
1389                    .await
1390                    .context("failed to call `drop` on `output-stream`")
1391            }
1392            Descriptor::File(File { fd, .. }) | Descriptor::Directory { fd, .. } => {
1393                filesystem::HostDescriptor::drop(&mut self.filesystem(), fd)
1394                    .context("failed to call `drop`")
1395            }
1396        }
1397        .map_err(types::Error::trap)
1398    }
1399
1400    /// Synchronize the data of a file to disk.
1401    /// NOTE: This is similar to `fdatasync` in POSIX.
1402    #[instrument(skip(self, _memory))]
1403    async fn fd_datasync(
1404        &mut self,
1405        _memory: &mut GuestMemory<'_>,
1406        fd: types::Fd,
1407    ) -> Result<(), types::Error> {
1408        let fd = self.get_file_fd(fd)?;
1409        self.filesystem().sync_data(fd).await?;
1410        Ok(())
1411    }
1412
1413    /// Get the attributes of a file descriptor.
1414    /// NOTE: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields.
1415    #[instrument(skip(self, _memory))]
1416    async fn fd_fdstat_get(
1417        &mut self,
1418        _memory: &mut GuestMemory<'_>,
1419        fd: types::Fd,
1420    ) -> Result<types::Fdstat, types::Error> {
1421        let (fd, blocking, append) = match self.transact()?.get_descriptor(fd)? {
1422            Descriptor::Stdin { isatty, .. } => {
1423                let fs_rights_base = types::Rights::FD_READ;
1424                return Ok(types::Fdstat {
1425                    fs_filetype: (*isatty).into(),
1426                    fs_flags: types::Fdflags::empty(),
1427                    fs_rights_base,
1428                    fs_rights_inheriting: fs_rights_base,
1429                });
1430            }
1431            Descriptor::Stdout { isatty, .. } | Descriptor::Stderr { isatty, .. } => {
1432                let fs_rights_base = types::Rights::FD_WRITE;
1433                return Ok(types::Fdstat {
1434                    fs_filetype: (*isatty).into(),
1435                    fs_flags: types::Fdflags::empty(),
1436                    fs_rights_base,
1437                    fs_rights_inheriting: fs_rights_base,
1438                });
1439            }
1440            Descriptor::Directory {
1441                preopen_path: Some(_),
1442                ..
1443            } => {
1444                // Hard-coded set or rights expected by many userlands:
1445                let fs_rights_base = types::Rights::PATH_CREATE_DIRECTORY
1446                    | types::Rights::PATH_CREATE_FILE
1447                    | types::Rights::PATH_LINK_SOURCE
1448                    | types::Rights::PATH_LINK_TARGET
1449                    | types::Rights::PATH_OPEN
1450                    | types::Rights::FD_READDIR
1451                    | types::Rights::PATH_READLINK
1452                    | types::Rights::PATH_RENAME_SOURCE
1453                    | types::Rights::PATH_RENAME_TARGET
1454                    | types::Rights::PATH_SYMLINK
1455                    | types::Rights::PATH_REMOVE_DIRECTORY
1456                    | types::Rights::PATH_UNLINK_FILE
1457                    | types::Rights::PATH_FILESTAT_GET
1458                    | types::Rights::PATH_FILESTAT_SET_TIMES
1459                    | types::Rights::FD_FILESTAT_GET
1460                    | types::Rights::FD_FILESTAT_SET_TIMES;
1461
1462                let fs_rights_inheriting = fs_rights_base
1463                    | types::Rights::FD_DATASYNC
1464                    | types::Rights::FD_READ
1465                    | types::Rights::FD_SEEK
1466                    | types::Rights::FD_FDSTAT_SET_FLAGS
1467                    | types::Rights::FD_SYNC
1468                    | types::Rights::FD_TELL
1469                    | types::Rights::FD_WRITE
1470                    | types::Rights::FD_ADVISE
1471                    | types::Rights::FD_ALLOCATE
1472                    | types::Rights::FD_FILESTAT_GET
1473                    | types::Rights::FD_FILESTAT_SET_SIZE
1474                    | types::Rights::FD_FILESTAT_SET_TIMES
1475                    | types::Rights::POLL_FD_READWRITE;
1476
1477                return Ok(types::Fdstat {
1478                    fs_filetype: types::Filetype::Directory,
1479                    fs_flags: types::Fdflags::empty(),
1480                    fs_rights_base,
1481                    fs_rights_inheriting,
1482                });
1483            }
1484            Descriptor::Directory { fd, .. } => (fd.borrowed(), BlockingMode::Blocking, false),
1485            Descriptor::File(File {
1486                fd,
1487                blocking_mode,
1488                append,
1489                ..
1490            }) => (fd.borrowed(), *blocking_mode, *append),
1491        };
1492        let flags = self.filesystem().get_flags(fd.borrowed()).await?;
1493        let fs_filetype = self
1494            .filesystem()
1495            .get_type(fd.borrowed())
1496            .await?
1497            .try_into()
1498            .map_err(types::Error::trap)?;
1499        let mut fs_flags = types::Fdflags::empty();
1500        let mut fs_rights_base = types::Rights::all();
1501        if let types::Filetype::Directory = fs_filetype {
1502            fs_rights_base &= !types::Rights::FD_SEEK;
1503            fs_rights_base &= !types::Rights::FD_FILESTAT_SET_SIZE;
1504            fs_rights_base &= !types::Rights::PATH_FILESTAT_SET_SIZE;
1505        }
1506        if !flags.contains(filesystem::DescriptorFlags::READ) {
1507            fs_rights_base &= !types::Rights::FD_READ;
1508            fs_rights_base &= !types::Rights::FD_READDIR;
1509        }
1510        if !flags.contains(filesystem::DescriptorFlags::WRITE) {
1511            fs_rights_base &= !types::Rights::FD_WRITE;
1512        }
1513        if flags.contains(filesystem::DescriptorFlags::DATA_INTEGRITY_SYNC) {
1514            fs_flags |= types::Fdflags::DSYNC;
1515        }
1516        if flags.contains(filesystem::DescriptorFlags::REQUESTED_WRITE_SYNC) {
1517            fs_flags |= types::Fdflags::RSYNC;
1518        }
1519        if flags.contains(filesystem::DescriptorFlags::FILE_INTEGRITY_SYNC) {
1520            fs_flags |= types::Fdflags::SYNC;
1521        }
1522        if append {
1523            fs_flags |= types::Fdflags::APPEND;
1524        }
1525        if matches!(blocking, BlockingMode::NonBlocking) {
1526            fs_flags |= types::Fdflags::NONBLOCK;
1527        }
1528        Ok(types::Fdstat {
1529            fs_filetype,
1530            fs_flags,
1531            fs_rights_base,
1532            fs_rights_inheriting: fs_rights_base,
1533        })
1534    }
1535
1536    /// Adjust the flags associated with a file descriptor.
1537    /// NOTE: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX.
1538    #[instrument(skip(self, _memory))]
1539    fn fd_fdstat_set_flags(
1540        &mut self,
1541        _memory: &mut GuestMemory<'_>,
1542        fd: types::Fd,
1543        flags: types::Fdflags,
1544    ) -> Result<(), types::Error> {
1545        let mut st = self.transact()?;
1546        let File {
1547            append,
1548            blocking_mode,
1549            ..
1550        } = st.get_file_mut(fd)?;
1551
1552        // Only support changing the NONBLOCK or APPEND flags.
1553        if flags.contains(types::Fdflags::DSYNC)
1554            || flags.contains(types::Fdflags::SYNC)
1555            || flags.contains(types::Fdflags::RSYNC)
1556        {
1557            return Err(types::Errno::Inval.into());
1558        }
1559        *append = flags.contains(types::Fdflags::APPEND);
1560        *blocking_mode = BlockingMode::from_fdflags(&flags);
1561        Ok(())
1562    }
1563
1564    /// Does not do anything if `fd` corresponds to a valid descriptor and returns `[types::Errno::Badf]` error otherwise.
1565    #[instrument(skip(self, _memory))]
1566    fn fd_fdstat_set_rights(
1567        &mut self,
1568        _memory: &mut GuestMemory<'_>,
1569        fd: types::Fd,
1570        _fs_rights_base: types::Rights,
1571        _fs_rights_inheriting: types::Rights,
1572    ) -> Result<(), types::Error> {
1573        self.get_fd(fd)?;
1574        Err(types::Errno::Notsup.into())
1575    }
1576
1577    /// Return the attributes of an open file.
1578    #[instrument(skip(self, _memory))]
1579    async fn fd_filestat_get(
1580        &mut self,
1581        _memory: &mut GuestMemory<'_>,
1582        fd: types::Fd,
1583    ) -> Result<types::Filestat, types::Error> {
1584        let t = self.transact()?;
1585        let desc = t.get_descriptor(fd)?;
1586        match desc {
1587            Descriptor::Stdin { isatty, .. }
1588            | Descriptor::Stdout { isatty, .. }
1589            | Descriptor::Stderr { isatty, .. } => Ok(types::Filestat {
1590                dev: 0,
1591                ino: 0,
1592                filetype: (*isatty).into(),
1593                nlink: 0,
1594                size: 0,
1595                atim: 0,
1596                mtim: 0,
1597                ctim: 0,
1598            }),
1599            Descriptor::Directory { fd, .. } | Descriptor::File(File { fd, .. }) => {
1600                let fd = fd.borrowed();
1601                drop(t);
1602                let filesystem::DescriptorStat {
1603                    type_,
1604                    link_count: nlink,
1605                    size,
1606                    data_access_timestamp,
1607                    data_modification_timestamp,
1608                    status_change_timestamp,
1609                } = self.filesystem().stat(fd.borrowed()).await?;
1610                let metadata_hash = self.filesystem().metadata_hash(fd).await?;
1611                let filetype = type_.try_into().map_err(types::Error::trap)?;
1612                let zero = wall_clock::Datetime {
1613                    seconds: 0,
1614                    nanoseconds: 0,
1615                };
1616                let atim = data_access_timestamp.unwrap_or(zero).try_into()?;
1617                let mtim = data_modification_timestamp.unwrap_or(zero).try_into()?;
1618                let ctim = status_change_timestamp.unwrap_or(zero).try_into()?;
1619                Ok(types::Filestat {
1620                    dev: 1,
1621                    ino: metadata_hash.lower,
1622                    filetype,
1623                    nlink,
1624                    size,
1625                    atim,
1626                    mtim,
1627                    ctim,
1628                })
1629            }
1630        }
1631    }
1632
1633    /// Adjust the size of an open file. If this increases the file's size, the extra bytes are filled with zeros.
1634    /// NOTE: This is similar to `ftruncate` in POSIX.
1635    #[instrument(skip(self, _memory))]
1636    async fn fd_filestat_set_size(
1637        &mut self,
1638        _memory: &mut GuestMemory<'_>,
1639        fd: types::Fd,
1640        size: types::Filesize,
1641    ) -> Result<(), types::Error> {
1642        let fd = self.get_file_fd(fd)?;
1643        self.filesystem().set_size(fd, size).await?;
1644        Ok(())
1645    }
1646
1647    /// Adjust the timestamps of an open file or directory.
1648    /// NOTE: This is similar to `futimens` in POSIX.
1649    #[instrument(skip(self, _memory))]
1650    async fn fd_filestat_set_times(
1651        &mut self,
1652        _memory: &mut GuestMemory<'_>,
1653        fd: types::Fd,
1654        atim: types::Timestamp,
1655        mtim: types::Timestamp,
1656        fst_flags: types::Fstflags,
1657    ) -> Result<(), types::Error> {
1658        let atim = systimespec(
1659            fst_flags.contains(types::Fstflags::ATIM),
1660            atim,
1661            fst_flags.contains(types::Fstflags::ATIM_NOW),
1662        )?;
1663        let mtim = systimespec(
1664            fst_flags.contains(types::Fstflags::MTIM),
1665            mtim,
1666            fst_flags.contains(types::Fstflags::MTIM_NOW),
1667        )?;
1668
1669        let fd = self.get_fd(fd)?;
1670        self.filesystem().set_times(fd, atim, mtim).await?;
1671        Ok(())
1672    }
1673
1674    /// Read from a file descriptor.
1675    /// NOTE: This is similar to `readv` in POSIX.
1676    #[instrument(skip(self, memory))]
1677    async fn fd_read(
1678        &mut self,
1679        memory: &mut GuestMemory<'_>,
1680        fd: types::Fd,
1681        iovs: types::IovecArray,
1682    ) -> Result<types::Size, types::Error> {
1683        let iov = self.first_non_empty_iovec(memory, iovs)?;
1684        let t = self.transact()?;
1685        let desc = t.get_descriptor(fd)?;
1686        match desc {
1687            Descriptor::File(File {
1688                fd,
1689                position,
1690                // NB: the nonblocking flag is intentionally ignored here and
1691                // blocking reads/writes are always performed.
1692                blocking_mode: _,
1693                ..
1694            }) => {
1695                let fd = fd.borrowed();
1696                let position = position.clone();
1697                drop(t);
1698                let pos = position.load(Ordering::Relaxed);
1699                let file = self.table.get(&fd)?.file()?;
1700                let bytes_read = match (file.as_blocking_file(), memory.as_slice_mut(iov)?) {
1701                    // Try to read directly into wasm memory where possible
1702                    // when the current thread can block and additionally wasm
1703                    // memory isn't shared.
1704                    (Some(file), Some(mut buf)) => {
1705                        primitives::read_at_cursor_unspecified(file, &mut buf, pos)
1706                            .map_err(|e| StreamError::LastOperationFailed(e.into()))?
1707                    }
1708                    // ... otherwise fall back to performing the read on a
1709                    // blocking thread and which copies the data back into wasm
1710                    // memory.
1711                    (_, buf) => {
1712                        drop(buf);
1713                        let mut buf = vec![0; iov.len() as usize];
1714                        let buf = file
1715                            .run_blocking(move |file| -> Result<_, types::Error> {
1716                                let bytes_read =
1717                                    primitives::read_at_cursor_unspecified(file, &mut buf, pos)
1718                                        .map_err(|e| StreamError::LastOperationFailed(e.into()))?;
1719                                buf.truncate(bytes_read);
1720                                Ok(buf)
1721                            })
1722                            .await?;
1723                        let iov = iov.get_range(0..u32::try_from(buf.len())?).unwrap();
1724                        memory.copy_from_slice(&buf, iov)?;
1725                        buf.len()
1726                    }
1727                };
1728
1729                let pos = pos
1730                    .checked_add(bytes_read.try_into()?)
1731                    .ok_or(types::Errno::Overflow)?;
1732                position.store(pos, Ordering::Relaxed);
1733
1734                Ok(bytes_read.try_into()?)
1735            }
1736            Descriptor::Stdin { stream, .. } => {
1737                let stream = stream.borrowed();
1738                drop(t);
1739                let read = BlockingMode::Blocking
1740                    .read(&mut self.table, stream, iov.len().try_into()?)
1741                    .await?;
1742                if read.len() > iov.len().try_into()? {
1743                    return Err(types::Errno::Range.into());
1744                }
1745                let iov = iov.get_range(0..u32::try_from(read.len())?).unwrap();
1746                memory.copy_from_slice(&read, iov)?;
1747                let n = read.len().try_into()?;
1748                Ok(n)
1749            }
1750            _ => return Err(types::Errno::Badf.into()),
1751        }
1752    }
1753
1754    /// Read from a file descriptor, without using and updating the file descriptor's offset.
1755    /// NOTE: This is similar to `preadv` in POSIX.
1756    #[instrument(skip(self, memory))]
1757    async fn fd_pread(
1758        &mut self,
1759        memory: &mut GuestMemory<'_>,
1760        fd: types::Fd,
1761        iovs: types::IovecArray,
1762        offset: types::Filesize,
1763    ) -> Result<types::Size, types::Error> {
1764        let buf = self.first_non_empty_iovec(memory, iovs)?;
1765        let t = self.transact()?;
1766        let desc = t.get_descriptor(fd)?;
1767        let (buf, read) = match desc {
1768            Descriptor::File(File {
1769                fd, blocking_mode, ..
1770            }) => {
1771                let fd = fd.borrowed();
1772                let blocking_mode = *blocking_mode;
1773                drop(t);
1774
1775                let stream = self.filesystem().read_via_stream(fd, offset)?;
1776                let read = blocking_mode
1777                    .read(&mut self.table, stream.borrowed(), buf.len().try_into()?)
1778                    .await;
1779                streams::HostInputStream::drop(&mut self.table, stream)
1780                    .await
1781                    .map_err(|e| types::Error::trap(e))?;
1782                (buf, read?)
1783            }
1784            Descriptor::Stdin { .. } => {
1785                // NOTE: legacy implementation returns SPIPE here
1786                return Err(types::Errno::Spipe.into());
1787            }
1788            _ => return Err(types::Errno::Badf.into()),
1789        };
1790        if read.len() > buf.len().try_into()? {
1791            return Err(types::Errno::Range.into());
1792        }
1793        let buf = buf.get_range(0..u32::try_from(read.len())?).unwrap();
1794        memory.copy_from_slice(&read, buf)?;
1795        let n = read.len().try_into()?;
1796        Ok(n)
1797    }
1798
1799    /// Write to a file descriptor.
1800    /// NOTE: This is similar to `writev` in POSIX.
1801    #[instrument(skip(self, memory))]
1802    async fn fd_write(
1803        &mut self,
1804        memory: &mut GuestMemory<'_>,
1805        fd: types::Fd,
1806        ciovs: types::CiovecArray,
1807    ) -> Result<types::Size, types::Error> {
1808        self.fd_write_impl(memory, fd, ciovs, FdWrite::AtCur).await
1809    }
1810
1811    /// Write to a file descriptor, without using and updating the file descriptor's offset.
1812    /// NOTE: This is similar to `pwritev` in POSIX.
1813    #[instrument(skip(self, memory))]
1814    async fn fd_pwrite(
1815        &mut self,
1816        memory: &mut GuestMemory<'_>,
1817        fd: types::Fd,
1818        ciovs: types::CiovecArray,
1819        offset: types::Filesize,
1820    ) -> Result<types::Size, types::Error> {
1821        self.fd_write_impl(memory, fd, ciovs, FdWrite::At(offset))
1822            .await
1823    }
1824
1825    /// Return a description of the given preopened file descriptor.
1826    #[instrument(skip(self, _memory))]
1827    fn fd_prestat_get(
1828        &mut self,
1829        _memory: &mut GuestMemory<'_>,
1830        fd: types::Fd,
1831    ) -> Result<types::Prestat, types::Error> {
1832        if let Descriptor::Directory {
1833            preopen_path: Some(p),
1834            ..
1835        } = self.transact()?.get_descriptor(fd)?
1836        {
1837            let pr_name_len = p.len().try_into()?;
1838            return Ok(types::Prestat::Dir(types::PrestatDir { pr_name_len }));
1839        }
1840        Err(types::Errno::Badf.into()) // NOTE: legacy implementation returns BADF here
1841    }
1842
1843    /// Return a description of the given preopened file descriptor.
1844    #[instrument(skip(self, memory))]
1845    fn fd_prestat_dir_name(
1846        &mut self,
1847        memory: &mut GuestMemory<'_>,
1848        fd: types::Fd,
1849        path: GuestPtr<u8>,
1850        path_max_len: types::Size,
1851    ) -> Result<(), types::Error> {
1852        let path_max_len = path_max_len.try_into()?;
1853        if let Descriptor::Directory {
1854            preopen_path: Some(p),
1855            ..
1856        } = self.transact()?.get_descriptor(fd)?
1857        {
1858            if p.len() > path_max_len {
1859                return Err(types::Errno::Nametoolong.into());
1860            }
1861            write_bytes(memory, path, p.as_bytes())?;
1862            return Ok(());
1863        }
1864        Err(types::Errno::Notdir.into()) // NOTE: legacy implementation returns NOTDIR here
1865    }
1866
1867    /// Atomically replace a file descriptor by renumbering another file descriptor.
1868    #[instrument(skip(self, memory))]
1869    async fn fd_renumber(
1870        &mut self,
1871        memory: &mut GuestMemory<'_>,
1872        from_fd: types::Fd,
1873        to_fd: types::Fd,
1874    ) -> Result<(), types::Error> {
1875        let from = from_fd.into();
1876        let to = to_fd.into();
1877        {
1878            let st = self.transact()?;
1879            if !st.descriptors.used.contains_key(&to) || !st.descriptors.used.contains_key(&from) {
1880                return Err(types::Errno::Badf.into());
1881            }
1882            if from == to {
1883                return Ok(());
1884            }
1885        }
1886        self.fd_close(memory, to_fd).await?;
1887        let mut st = self.transact()?;
1888        let btree_map::Entry::Occupied(desc) = st.descriptors.used.entry(from) else {
1889            return Err(types::Errno::Badf.into());
1890        };
1891        let desc = desc.remove();
1892        st.descriptors.free.insert(from);
1893        st.descriptors.free.remove(&to);
1894        st.descriptors.used.insert(to, desc);
1895        Ok(())
1896    }
1897
1898    /// Move the offset of a file descriptor.
1899    /// NOTE: This is similar to `lseek` in POSIX.
1900    #[instrument(skip(self, _memory))]
1901    async fn fd_seek(
1902        &mut self,
1903        _memory: &mut GuestMemory<'_>,
1904        fd: types::Fd,
1905        offset: types::Filedelta,
1906        whence: types::Whence,
1907    ) -> Result<types::Filesize, types::Error> {
1908        let t = self.transact()?;
1909        let File { fd, position, .. } = t.get_seekable(fd)?;
1910        let fd = fd.borrowed();
1911        let position = position.clone();
1912        drop(t);
1913        let pos = match whence {
1914            types::Whence::Set if offset >= 0 => {
1915                offset.try_into().map_err(|_| types::Errno::Inval)?
1916            }
1917            types::Whence::Cur => position
1918                .load(Ordering::Relaxed)
1919                .checked_add_signed(offset)
1920                .ok_or(types::Errno::Inval)?,
1921            types::Whence::End => {
1922                let filesystem::DescriptorStat { size, .. } = self.filesystem().stat(fd).await?;
1923                size.checked_add_signed(offset).ok_or(types::Errno::Inval)?
1924            }
1925            _ => return Err(types::Errno::Inval.into()),
1926        };
1927        position.store(pos, Ordering::Relaxed);
1928        Ok(pos)
1929    }
1930
1931    /// Synchronize the data and metadata of a file to disk.
1932    /// NOTE: This is similar to `fsync` in POSIX.
1933    #[instrument(skip(self, _memory))]
1934    async fn fd_sync(
1935        &mut self,
1936        _memory: &mut GuestMemory<'_>,
1937        fd: types::Fd,
1938    ) -> Result<(), types::Error> {
1939        let fd = self.get_file_fd(fd)?;
1940        self.filesystem().sync(fd).await?;
1941        Ok(())
1942    }
1943
1944    /// Return the current offset of a file descriptor.
1945    /// NOTE: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX.
1946    #[instrument(skip(self, _memory))]
1947    fn fd_tell(
1948        &mut self,
1949        _memory: &mut GuestMemory<'_>,
1950        fd: types::Fd,
1951    ) -> Result<types::Filesize, types::Error> {
1952        let pos = self
1953            .transact()?
1954            .get_seekable(fd)
1955            .map(|File { position, .. }| position.load(Ordering::Relaxed))?;
1956        Ok(pos)
1957    }
1958
1959    #[instrument(skip(self, memory))]
1960    async fn fd_readdir(
1961        &mut self,
1962        memory: &mut GuestMemory<'_>,
1963        fd: types::Fd,
1964        buf: GuestPtr<u8>,
1965        buf_len: types::Size,
1966        cookie: types::Dircookie,
1967    ) -> Result<types::Size, types::Error> {
1968        let fd = self.get_dir_fd(fd)?;
1969        let stream = self.filesystem().read_directory(fd.borrowed()).await?;
1970        let dir_metadata_hash = self.filesystem().metadata_hash(fd.borrowed()).await?;
1971        let cookie = cookie.try_into().map_err(|_| types::Errno::Overflow)?;
1972
1973        let head = [
1974            (
1975                types::Dirent {
1976                    d_next: 1u64,
1977                    d_ino: dir_metadata_hash.lower,
1978                    d_type: types::Filetype::Directory,
1979                    d_namlen: 1u32,
1980                },
1981                ".".into(),
1982            ),
1983            (
1984                types::Dirent {
1985                    d_next: 2u64,
1986                    d_ino: dir_metadata_hash.lower, // NOTE: incorrect, but legacy implementation returns `fd` inode here
1987                    d_type: types::Filetype::Directory,
1988                    d_namlen: 2u32,
1989                },
1990                "..".into(),
1991            ),
1992        ];
1993
1994        let mut dir = Vec::new();
1995        for (entry, d_next) in self
1996            .table
1997            // remove iterator from table and use it directly:
1998            .delete(stream)?
1999            .into_iter()
2000            .zip(3u64..)
2001        {
2002            let filesystem::DirectoryEntry { type_, name } = entry?;
2003            let metadata_hash = self
2004                .filesystem()
2005                .metadata_hash_at(fd.borrowed(), filesystem::PathFlags::empty(), name.clone())
2006                .await?;
2007            let d_type = type_.try_into().map_err(types::Error::trap)?;
2008            let d_namlen: u32 = name.len().try_into().map_err(|_| types::Errno::Overflow)?;
2009            dir.push((
2010                types::Dirent {
2011                    d_next,
2012                    d_ino: metadata_hash.lower,
2013                    d_type,
2014                    d_namlen,
2015                },
2016                name,
2017            ))
2018        }
2019
2020        let mut buf = buf;
2021        let mut cap = buf_len;
2022        let mut dirent = vec![0; types::Dirent::guest_size() as usize];
2023        for (ref entry, path) in head.into_iter().chain(dir.into_iter()).skip(cookie) {
2024            let mut path = path.into_bytes();
2025            dirent[0..8].copy_from_slice(entry.d_next.to_le_bytes().as_slice());
2026            dirent[8..16].copy_from_slice(entry.d_ino.to_le_bytes().as_slice());
2027            dirent[16..20].copy_from_slice(entry.d_namlen.to_le_bytes().as_slice());
2028            dirent[20..21].copy_from_slice((entry.d_type as u8).to_le_bytes().as_slice());
2029            let entry_len = cap.min(types::Dirent::guest_size());
2030            cap = cap.checked_sub(entry_len).unwrap();
2031            buf = write_bytes(memory, buf, &dirent[..entry_len as usize])?;
2032            if cap == 0 {
2033                return Ok(buf_len);
2034            }
2035
2036            if let Ok(cap) = cap.try_into() {
2037                // `path` cannot be longer than `usize`, only truncate if `cap` fits in `usize`
2038                path.truncate(cap);
2039            }
2040            cap = cap.checked_sub(path.len() as _).unwrap();
2041            buf = write_bytes(memory, buf, &path)?;
2042            if cap == 0 {
2043                return Ok(buf_len);
2044            }
2045        }
2046        Ok(buf_len.checked_sub(cap).unwrap())
2047    }
2048
2049    #[instrument(skip(self, memory))]
2050    async fn path_create_directory(
2051        &mut self,
2052        memory: &mut GuestMemory<'_>,
2053        dirfd: types::Fd,
2054        path: GuestPtr<str>,
2055    ) -> Result<(), types::Error> {
2056        let dirfd = self.get_dir_fd(dirfd)?;
2057        let path = self.read_string(memory, path)?;
2058        self.filesystem()
2059            .create_directory_at(dirfd.borrowed(), path)
2060            .await?;
2061        Ok(())
2062    }
2063
2064    /// Return the attributes of a file or directory.
2065    /// NOTE: This is similar to `stat` in POSIX.
2066    #[instrument(skip(self, memory))]
2067    async fn path_filestat_get(
2068        &mut self,
2069        memory: &mut GuestMemory<'_>,
2070        dirfd: types::Fd,
2071        flags: types::Lookupflags,
2072        path: GuestPtr<str>,
2073    ) -> Result<types::Filestat, types::Error> {
2074        let dirfd = self.get_dir_fd(dirfd)?;
2075        let path = self.read_string(memory, path)?;
2076        let filesystem::DescriptorStat {
2077            type_,
2078            link_count: nlink,
2079            size,
2080            data_access_timestamp,
2081            data_modification_timestamp,
2082            status_change_timestamp,
2083        } = self
2084            .filesystem()
2085            .stat_at(dirfd.borrowed(), flags.into(), path.clone())
2086            .await?;
2087        let metadata_hash = self
2088            .filesystem()
2089            .metadata_hash_at(dirfd, flags.into(), path)
2090            .await?;
2091        let filetype = type_.try_into().map_err(types::Error::trap)?;
2092        let zero = wall_clock::Datetime {
2093            seconds: 0,
2094            nanoseconds: 0,
2095        };
2096        let atim = data_access_timestamp.unwrap_or(zero).try_into()?;
2097        let mtim = data_modification_timestamp.unwrap_or(zero).try_into()?;
2098        let ctim = status_change_timestamp.unwrap_or(zero).try_into()?;
2099        Ok(types::Filestat {
2100            dev: 1,
2101            ino: metadata_hash.lower,
2102            filetype,
2103            nlink,
2104            size,
2105            atim,
2106            mtim,
2107            ctim,
2108        })
2109    }
2110
2111    /// Adjust the timestamps of a file or directory.
2112    /// NOTE: This is similar to `utimensat` in POSIX.
2113    #[instrument(skip(self, memory))]
2114    async fn path_filestat_set_times(
2115        &mut self,
2116        memory: &mut GuestMemory<'_>,
2117        dirfd: types::Fd,
2118        flags: types::Lookupflags,
2119        path: GuestPtr<str>,
2120        atim: types::Timestamp,
2121        mtim: types::Timestamp,
2122        fst_flags: types::Fstflags,
2123    ) -> Result<(), types::Error> {
2124        let atim = systimespec(
2125            fst_flags.contains(types::Fstflags::ATIM),
2126            atim,
2127            fst_flags.contains(types::Fstflags::ATIM_NOW),
2128        )?;
2129        let mtim = systimespec(
2130            fst_flags.contains(types::Fstflags::MTIM),
2131            mtim,
2132            fst_flags.contains(types::Fstflags::MTIM_NOW),
2133        )?;
2134
2135        let dirfd = self.get_dir_fd(dirfd)?;
2136        let path = self.read_string(memory, path)?;
2137        self.filesystem()
2138            .set_times_at(dirfd, flags.into(), path, atim, mtim)
2139            .await?;
2140        Ok(())
2141    }
2142
2143    /// Create a hard link.
2144    /// NOTE: This is similar to `linkat` in POSIX.
2145    #[instrument(skip(self, memory))]
2146    async fn path_link(
2147        &mut self,
2148        memory: &mut GuestMemory<'_>,
2149        src_fd: types::Fd,
2150        src_flags: types::Lookupflags,
2151        src_path: GuestPtr<str>,
2152        target_fd: types::Fd,
2153        target_path: GuestPtr<str>,
2154    ) -> Result<(), types::Error> {
2155        let src_fd = self.get_dir_fd(src_fd)?;
2156        let target_fd = self.get_dir_fd(target_fd)?;
2157        let src_path = self.read_string(memory, src_path)?;
2158        let target_path = self.read_string(memory, target_path)?;
2159        self.filesystem()
2160            .link_at(src_fd, src_flags.into(), src_path, target_fd, target_path)
2161            .await?;
2162        Ok(())
2163    }
2164
2165    /// Open a file or directory.
2166    /// NOTE: This is similar to `openat` in POSIX.
2167    #[instrument(skip(self, memory))]
2168    async fn path_open(
2169        &mut self,
2170        memory: &mut GuestMemory<'_>,
2171        dirfd: types::Fd,
2172        dirflags: types::Lookupflags,
2173        path: GuestPtr<str>,
2174        oflags: types::Oflags,
2175        fs_rights_base: types::Rights,
2176        _fs_rights_inheriting: types::Rights,
2177        fdflags: types::Fdflags,
2178    ) -> Result<types::Fd, types::Error> {
2179        let path = self.read_string(memory, path)?;
2180
2181        let mut flags = filesystem::DescriptorFlags::empty();
2182        if fs_rights_base.contains(types::Rights::FD_READ) {
2183            flags |= filesystem::DescriptorFlags::READ;
2184        }
2185        if fs_rights_base.contains(types::Rights::FD_WRITE) {
2186            flags |= filesystem::DescriptorFlags::WRITE;
2187        }
2188        if fdflags.contains(types::Fdflags::SYNC) {
2189            flags |= filesystem::DescriptorFlags::FILE_INTEGRITY_SYNC;
2190        }
2191        if fdflags.contains(types::Fdflags::DSYNC) {
2192            flags |= filesystem::DescriptorFlags::DATA_INTEGRITY_SYNC;
2193        }
2194        if fdflags.contains(types::Fdflags::RSYNC) {
2195            flags |= filesystem::DescriptorFlags::REQUESTED_WRITE_SYNC;
2196        }
2197
2198        let t = self.transact()?;
2199        let dirfd = match t.get_descriptor(dirfd)? {
2200            Descriptor::Directory { fd, .. } => fd.borrowed(),
2201            Descriptor::File(_) => return Err(types::Errno::Notdir.into()),
2202            _ => return Err(types::Errno::Badf.into()),
2203        };
2204        drop(t);
2205        let fd = self
2206            .filesystem()
2207            .open_at(dirfd, dirflags.into(), path, oflags.into(), flags)
2208            .await?;
2209        let mut t = self.transact()?;
2210        let desc = match t.view.table.get(&fd)? {
2211            crate::filesystem::Descriptor::Dir(_) => Descriptor::Directory {
2212                fd,
2213                preopen_path: None,
2214            },
2215            crate::filesystem::Descriptor::File(_) => Descriptor::File(File {
2216                fd,
2217                position: Default::default(),
2218                append: fdflags.contains(types::Fdflags::APPEND),
2219                blocking_mode: BlockingMode::from_fdflags(&fdflags),
2220            }),
2221        };
2222        let fd = t.descriptors.push(desc)?;
2223        Ok(fd.into())
2224    }
2225
2226    /// Read the contents of a symbolic link.
2227    /// NOTE: This is similar to `readlinkat` in POSIX.
2228    #[instrument(skip(self, memory))]
2229    async fn path_readlink(
2230        &mut self,
2231        memory: &mut GuestMemory<'_>,
2232        dirfd: types::Fd,
2233        path: GuestPtr<str>,
2234        buf: GuestPtr<u8>,
2235        buf_len: types::Size,
2236    ) -> Result<types::Size, types::Error> {
2237        let dirfd = self.get_dir_fd(dirfd)?;
2238        let path = self.read_string(memory, path)?;
2239        let mut path = self
2240            .filesystem()
2241            .readlink_at(dirfd, path)
2242            .await?
2243            .into_bytes();
2244        if let Ok(buf_len) = buf_len.try_into() {
2245            // `path` cannot be longer than `usize`, only truncate if `buf_len` fits in `usize`
2246            path.truncate(buf_len);
2247        }
2248        let n = path.len().try_into().map_err(|_| types::Errno::Overflow)?;
2249        write_bytes(memory, buf, &path)?;
2250        Ok(n)
2251    }
2252
2253    #[instrument(skip(self, memory))]
2254    async fn path_remove_directory(
2255        &mut self,
2256        memory: &mut GuestMemory<'_>,
2257        dirfd: types::Fd,
2258        path: GuestPtr<str>,
2259    ) -> Result<(), types::Error> {
2260        let dirfd = self.get_dir_fd(dirfd)?;
2261        let path = self.read_string(memory, path)?;
2262        self.filesystem().remove_directory_at(dirfd, path).await?;
2263        Ok(())
2264    }
2265
2266    /// Rename a file or directory.
2267    /// NOTE: This is similar to `renameat` in POSIX.
2268    #[instrument(skip(self, memory))]
2269    async fn path_rename(
2270        &mut self,
2271        memory: &mut GuestMemory<'_>,
2272        src_fd: types::Fd,
2273        src_path: GuestPtr<str>,
2274        dest_fd: types::Fd,
2275        dest_path: GuestPtr<str>,
2276    ) -> Result<(), types::Error> {
2277        let src_fd = self.get_dir_fd(src_fd)?;
2278        let dest_fd = self.get_dir_fd(dest_fd)?;
2279        let src_path = self.read_string(memory, src_path)?;
2280        let dest_path = self.read_string(memory, dest_path)?;
2281        self.filesystem()
2282            .rename_at(src_fd, src_path, dest_fd, dest_path)
2283            .await?;
2284        Ok(())
2285    }
2286
2287    #[instrument(skip(self, memory))]
2288    async fn path_symlink(
2289        &mut self,
2290        memory: &mut GuestMemory<'_>,
2291        src_path: GuestPtr<str>,
2292        dirfd: types::Fd,
2293        dest_path: GuestPtr<str>,
2294    ) -> Result<(), types::Error> {
2295        let dirfd = self.get_dir_fd(dirfd)?;
2296        let src_path = self.read_string(memory, src_path)?;
2297        let dest_path = self.read_string(memory, dest_path)?;
2298        self.filesystem()
2299            .symlink_at(dirfd.borrowed(), src_path, dest_path)
2300            .await?;
2301        Ok(())
2302    }
2303
2304    #[instrument(skip(self, memory))]
2305    async fn path_unlink_file(
2306        &mut self,
2307        memory: &mut GuestMemory<'_>,
2308        dirfd: types::Fd,
2309        path: GuestPtr<str>,
2310    ) -> Result<(), types::Error> {
2311        let dirfd = self.get_dir_fd(dirfd)?;
2312        let path = self.read_string(memory, path)?;
2313        self.filesystem()
2314            .unlink_file_at(dirfd.borrowed(), path)
2315            .await?;
2316        Ok(())
2317    }
2318
2319    #[instrument(skip(self, memory))]
2320    async fn poll_oneoff(
2321        &mut self,
2322        memory: &mut GuestMemory<'_>,
2323        subs: GuestPtr<types::Subscription>,
2324        events: GuestPtr<types::Event>,
2325        nsubscriptions: types::Size,
2326    ) -> Result<types::Size, types::Error> {
2327        if nsubscriptions == 0 {
2328            // Indefinite sleeping is not supported in p1.
2329            return Err(types::Errno::Inval.into());
2330        }
2331
2332        // This is a special case where `poll_oneoff` is just sleeping
2333        // on a single relative timer event. This special case was added
2334        // after experimental observations showed that std::thread::sleep
2335        // results in more consistent sleep times. This design ensures that
2336        // wasmtime can handle real-time requirements more accurately.
2337        if nsubscriptions == 1 {
2338            let sub = memory.read(subs)?;
2339            if let types::SubscriptionU::Clock(clocksub) = sub.u {
2340                if !clocksub
2341                    .flags
2342                    .contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME)
2343                    && self.wasi.filesystem.allow_blocking_current_thread
2344                {
2345                    std::thread::sleep(std::time::Duration::from_nanos(clocksub.timeout));
2346                    memory.write(
2347                        events,
2348                        types::Event {
2349                            userdata: sub.userdata,
2350                            error: types::Errno::Success,
2351                            type_: types::Eventtype::Clock,
2352                            fd_readwrite: types::EventFdReadwrite {
2353                                flags: types::Eventrwflags::empty(),
2354                                nbytes: 1,
2355                            },
2356                        },
2357                    )?;
2358                    return Ok(1);
2359                }
2360            }
2361        }
2362
2363        let subs = subs.as_array(nsubscriptions);
2364        let events = events.as_array(nsubscriptions);
2365        let n = usize::try_from(nsubscriptions).unwrap_or(usize::MAX);
2366
2367        self.consume_fuel_for_array(subs)?;
2368        self.consume_fuel_for_array(events)?;
2369
2370        let mut temp = TempResources {
2371            ctx: self,
2372            pollables: Vec::with_capacity(n),
2373            inputs: Vec::new(),
2374            outputs: Vec::new(),
2375        };
2376        let mut borrowed_pollables = Vec::with_capacity(n);
2377        for sub in subs.iter() {
2378            let sub = memory.read(sub?)?;
2379            let p = match sub.u {
2380                types::SubscriptionU::Clock(types::SubscriptionClock {
2381                    id,
2382                    timeout,
2383                    flags,
2384                    ..
2385                }) => {
2386                    let absolute = flags.contains(types::Subclockflags::SUBSCRIPTION_CLOCK_ABSTIME);
2387                    let (timeout, absolute) = match id {
2388                        types::Clockid::Monotonic => (timeout, absolute),
2389                        types::Clockid::Realtime if !absolute => (timeout, false),
2390                        types::Clockid::Realtime => {
2391                            let now = wall_clock::Host::now(&mut temp.ctx.clocks())
2392                                .context("failed to call `wall_clock::now`")
2393                                .map_err(types::Error::trap)?;
2394                            let now = now.seconds * 1_000_000_000 + u64::from(now.nanoseconds);
2395                            (timeout.saturating_sub(now), false)
2396                        }
2397                        _ => return Err(types::Errno::Inval.into()),
2398                    };
2399                    if absolute {
2400                        monotonic_clock::Host::subscribe_instant(&mut temp.ctx.clocks(), timeout)
2401                            .context("failed to call `monotonic_clock::subscribe_instant`")
2402                            .map_err(types::Error::trap)?
2403                    } else {
2404                        monotonic_clock::Host::subscribe_duration(&mut temp.ctx.clocks(), timeout)
2405                            .context("failed to call `monotonic_clock::subscribe_duration`")
2406                            .map_err(types::Error::trap)?
2407                    }
2408                }
2409                types::SubscriptionU::FdRead(types::SubscriptionFdReadwrite {
2410                    file_descriptor,
2411                }) => {
2412                    let stream = {
2413                        let t = temp.ctx.transact()?;
2414                        let desc = t.get_descriptor(file_descriptor)?;
2415                        match desc {
2416                            Descriptor::Stdin { stream, .. } => stream.borrowed(),
2417                            Descriptor::File(File { fd, position, .. }) => {
2418                                let pos = position.load(Ordering::Relaxed);
2419                                let fd = fd.borrowed();
2420                                drop(t);
2421                                let r = temp.ctx.filesystem().read_via_stream(fd, pos)?;
2422                                let ret = r.borrowed();
2423                                temp.inputs.push(r);
2424                                ret
2425                            }
2426                            // TODO: Support sockets
2427                            _ => return Err(types::Errno::Badf.into()),
2428                        }
2429                    };
2430                    streams::HostInputStream::subscribe(&mut temp.ctx.table, stream)
2431                        .context("failed to call `subscribe` on `input-stream`")
2432                        .map_err(types::Error::trap)?
2433                }
2434                types::SubscriptionU::FdWrite(types::SubscriptionFdReadwrite {
2435                    file_descriptor,
2436                }) => {
2437                    let stream = {
2438                        let t = temp.ctx.transact()?;
2439                        let desc = t.get_descriptor(file_descriptor)?;
2440                        match desc {
2441                            Descriptor::Stdout { stream, .. }
2442                            | Descriptor::Stderr { stream, .. } => stream.borrowed(),
2443                            Descriptor::File(File {
2444                                fd,
2445                                position,
2446                                append,
2447                                ..
2448                            }) => {
2449                                let fd = fd.borrowed();
2450                                let position = position.clone();
2451                                let append = *append;
2452                                drop(t);
2453                                let r = if append {
2454                                    temp.ctx.filesystem().append_via_stream(fd)?
2455                                } else {
2456                                    let pos = position.load(Ordering::Relaxed);
2457                                    temp.ctx.filesystem().write_via_stream(fd, pos)?
2458                                };
2459                                let ret = r.borrowed();
2460                                temp.outputs.push(r);
2461                                ret
2462                            }
2463                            // TODO: Support sockets
2464                            _ => return Err(types::Errno::Badf.into()),
2465                        }
2466                    };
2467                    streams::HostOutputStream::subscribe(&mut temp.ctx.table, stream)
2468                        .context("failed to call `subscribe` on `output-stream`")
2469                        .map_err(types::Error::trap)?
2470                }
2471            };
2472            borrowed_pollables.push(p.borrowed());
2473            temp.pollables.push(p);
2474        }
2475        let ready: HashSet<_> = temp
2476            .ctx
2477            .table
2478            .poll(borrowed_pollables)
2479            .await
2480            .context("failed to call `poll-oneoff`")
2481            .map_err(types::Error::trap)?
2482            .into_iter()
2483            .collect();
2484
2485        // While `Drop` below does a version of this, this executes in the
2486        // normal case to be able to call the `async drop` methods on these
2487        // resources in case any synchronization is needed there.
2488        while let Some(p) = temp.pollables.pop() {
2489            use wasmtime_wasi_io::bindings::wasi::io::poll::HostPollable;
2490            temp.ctx.table.drop(p).map_err(types::Error::trap)?;
2491        }
2492        while let Some(s) = temp.inputs.pop() {
2493            streams::HostInputStream::drop(&mut temp.ctx.table, s)
2494                .await
2495                .map_err(types::Error::trap)?;
2496        }
2497        while let Some(s) = temp.outputs.pop() {
2498            streams::HostOutputStream::drop(&mut temp.ctx.table, s)
2499                .await
2500                .map_err(types::Error::trap)?;
2501        }
2502        drop(temp);
2503
2504        let mut count: types::Size = 0;
2505        for (sub, event) in (0..)
2506            .zip(subs.iter())
2507            .filter_map(|(idx, sub)| ready.contains(&idx).then_some(sub))
2508            .zip(events.iter())
2509        {
2510            let sub = memory.read(sub?)?;
2511            let event = event?;
2512            let e = match sub.u {
2513                types::SubscriptionU::Clock(..) => types::Event {
2514                    userdata: sub.userdata,
2515                    error: types::Errno::Success,
2516                    type_: types::Eventtype::Clock,
2517                    fd_readwrite: types::EventFdReadwrite {
2518                        flags: types::Eventrwflags::empty(),
2519                        nbytes: 0,
2520                    },
2521                },
2522                types::SubscriptionU::FdRead(types::SubscriptionFdReadwrite {
2523                    file_descriptor,
2524                }) => {
2525                    let t = self.transact()?;
2526                    let desc = t.get_descriptor(file_descriptor)?;
2527                    match desc {
2528                        Descriptor::Stdin { .. } => types::Event {
2529                            userdata: sub.userdata,
2530                            error: types::Errno::Success,
2531                            type_: types::Eventtype::FdRead,
2532                            fd_readwrite: types::EventFdReadwrite {
2533                                flags: types::Eventrwflags::empty(),
2534                                nbytes: 1,
2535                            },
2536                        },
2537                        Descriptor::File(File { fd, position, .. }) => {
2538                            let fd = fd.borrowed();
2539                            let position = position.clone();
2540                            drop(t);
2541                            match self.filesystem().stat(fd).await? {
2542                                filesystem::DescriptorStat { size, .. } => {
2543                                    let pos = position.load(Ordering::Relaxed);
2544                                    let nbytes = size.saturating_sub(pos);
2545                                    types::Event {
2546                                        userdata: sub.userdata,
2547                                        error: types::Errno::Success,
2548                                        type_: types::Eventtype::FdRead,
2549                                        fd_readwrite: types::EventFdReadwrite {
2550                                            flags: if nbytes == 0 {
2551                                                types::Eventrwflags::FD_READWRITE_HANGUP
2552                                            } else {
2553                                                types::Eventrwflags::empty()
2554                                            },
2555                                            nbytes: 1,
2556                                        },
2557                                    }
2558                                }
2559                            }
2560                        }
2561                        // TODO: Support sockets
2562                        _ => return Err(types::Errno::Badf.into()),
2563                    }
2564                }
2565                types::SubscriptionU::FdWrite(types::SubscriptionFdReadwrite {
2566                    file_descriptor,
2567                }) => {
2568                    let t = self.transact()?;
2569                    let desc = t.get_descriptor(file_descriptor)?;
2570                    match desc {
2571                        Descriptor::Stdout { .. } | Descriptor::Stderr { .. } => types::Event {
2572                            userdata: sub.userdata,
2573                            error: types::Errno::Success,
2574                            type_: types::Eventtype::FdWrite,
2575                            fd_readwrite: types::EventFdReadwrite {
2576                                flags: types::Eventrwflags::empty(),
2577                                nbytes: 1,
2578                            },
2579                        },
2580                        Descriptor::File(_) => types::Event {
2581                            userdata: sub.userdata,
2582                            error: types::Errno::Success,
2583                            type_: types::Eventtype::FdWrite,
2584                            fd_readwrite: types::EventFdReadwrite {
2585                                flags: types::Eventrwflags::empty(),
2586                                nbytes: 1,
2587                            },
2588                        },
2589                        // TODO: Support sockets
2590                        _ => return Err(types::Errno::Badf.into()),
2591                    }
2592                }
2593            };
2594            memory.write(event, e)?;
2595            count = count
2596                .checked_add(1)
2597                .ok_or_else(|| types::Error::from(types::Errno::Overflow))?
2598        }
2599        return Ok(count);
2600
2601        struct TempResources<'a> {
2602            ctx: &'a mut WasiP1Ctx,
2603            pollables: Vec<Resource<crate::p2::bindings::io::streams::Pollable>>,
2604            inputs: Vec<Resource<crate::p2::bindings::io::streams::InputStream>>,
2605            outputs: Vec<Resource<crate::p2::bindings::io::streams::OutputStream>>,
2606        }
2607
2608        impl Drop for TempResources<'_> {
2609            fn drop(&mut self) {
2610                for p in self.pollables.drain(..) {
2611                    use wasmtime_wasi_io::bindings::wasi::io::poll::HostPollable;
2612                    self.ctx.table.drop(p).unwrap();
2613                }
2614                for p in self.inputs.drain(..) {
2615                    assert!(p.owned());
2616                    self.ctx.table.delete(p).unwrap();
2617                }
2618                for p in self.outputs.drain(..) {
2619                    assert!(p.owned());
2620                    self.ctx.table.delete(p).unwrap();
2621                }
2622            }
2623        }
2624    }
2625
2626    #[instrument(skip(self, _memory))]
2627    fn proc_exit(
2628        &mut self,
2629        _memory: &mut GuestMemory<'_>,
2630        status: types::Exitcode,
2631    ) -> wasmtime::Error {
2632        // Check that the status is within WASI's range.
2633        if status >= 126 {
2634            return wasmtime::Error::msg("exit with invalid exit status outside of [0..126)");
2635        }
2636        crate::I32Exit(status as i32).into()
2637    }
2638
2639    #[instrument(skip(self, _memory))]
2640    fn proc_raise(
2641        &mut self,
2642        _memory: &mut GuestMemory<'_>,
2643        _sig: types::Signal,
2644    ) -> Result<(), types::Error> {
2645        Err(types::Errno::Notsup.into())
2646    }
2647
2648    #[instrument(skip(self, _memory))]
2649    fn sched_yield(&mut self, _memory: &mut GuestMemory<'_>) -> Result<(), types::Error> {
2650        // No such thing in preview 2. Intentionally left empty.
2651        Ok(())
2652    }
2653
2654    #[instrument(skip(self, memory))]
2655    fn random_get(
2656        &mut self,
2657        memory: &mut GuestMemory<'_>,
2658        buf: GuestPtr<u8>,
2659        buf_len: types::Size,
2660    ) -> Result<(), types::Error> {
2661        let rand = self
2662            .wasi
2663            .random
2664            .get_random_bytes(buf_len.into())
2665            .context("failed to call `get-random-bytes`")
2666            .map_err(types::Error::trap)?;
2667        write_bytes(memory, buf, &rand)?;
2668        Ok(())
2669    }
2670
2671    #[instrument(skip(self, _memory))]
2672    fn sock_accept(
2673        &mut self,
2674        _memory: &mut GuestMemory<'_>,
2675        fd: types::Fd,
2676        flags: types::Fdflags,
2677    ) -> Result<types::Fd, types::Error> {
2678        tracing::warn!("p1 sock_accept is not implemented");
2679        self.transact()?.get_descriptor(fd)?;
2680        Err(types::Errno::Notsock.into())
2681    }
2682
2683    #[instrument(skip(self, _memory))]
2684    fn sock_recv(
2685        &mut self,
2686        _memory: &mut GuestMemory<'_>,
2687        fd: types::Fd,
2688        ri_data: types::IovecArray,
2689        ri_flags: types::Riflags,
2690    ) -> Result<(types::Size, types::Roflags), types::Error> {
2691        tracing::warn!("p1 sock_recv is not implemented");
2692        self.transact()?.get_descriptor(fd)?;
2693        Err(types::Errno::Notsock.into())
2694    }
2695
2696    #[instrument(skip(self, _memory))]
2697    fn sock_send(
2698        &mut self,
2699        _memory: &mut GuestMemory<'_>,
2700        fd: types::Fd,
2701        si_data: types::CiovecArray,
2702        _si_flags: types::Siflags,
2703    ) -> Result<types::Size, types::Error> {
2704        tracing::warn!("p1 sock_send is not implemented");
2705        self.transact()?.get_descriptor(fd)?;
2706        Err(types::Errno::Notsock.into())
2707    }
2708
2709    #[instrument(skip(self, _memory))]
2710    fn sock_shutdown(
2711        &mut self,
2712        _memory: &mut GuestMemory<'_>,
2713        fd: types::Fd,
2714        how: types::Sdflags,
2715    ) -> Result<(), types::Error> {
2716        tracing::warn!("p1 sock_shutdown is not implemented");
2717        self.transact()?.get_descriptor(fd)?;
2718        Err(types::Errno::Notsock.into())
2719    }
2720}
2721
2722trait ResourceExt<T> {
2723    fn borrowed(&self) -> Resource<T>;
2724}
2725
2726impl<T: 'static> ResourceExt<T> for Resource<T> {
2727    fn borrowed(&self) -> Resource<T> {
2728        Resource::new_borrow(self.rep())
2729    }
2730}