wasi_common/lib.rs
1//! # wasi-common
2//!
3//! This is Wasmtime's legacy implementation of WASI 0.1 (Preview 1). The
4//! Wasmtime maintainers suggest all users upgrade to the implementation
5//! of WASI 0.1 and 0.2 provided by the `wasmtime-wasi` crate. This
6//! implementation remains in the wasmtime tree because it is required to use
7//! the `wasmtime-wasi-threads` crate, an implementation of the `wasi-threads`
8//! proposal which is not compatible with WASI 0.2.
9//!
10//! In addition to integration with Wasmtime, this implementation may be used
11//! by other runtimes by disabling the `wasmtime` feature on this crate.
12//!
13//! ## The `WasiFile` and `WasiDir` traits
14//!
15//! The WASI specification only defines one `handle` type, `fd`, on which all
16//! operations on both files and directories (aka dirfds) are defined. We
17//! believe this is a design mistake, and are architecting wasi-common to make
18//! this straightforward to correct in future snapshots of WASI. Wasi-common
19//! internally treats files and directories as two distinct resource types in
20//! the table - `Box<dyn WasiFile>` and `Box<dyn WasiDir>`. The snapshot 0 and
21//! 1 interfaces via `fd` will attempt to downcast a table element to one or
22//! both of these interfaces depending on what is appropriate - e.g.
23//! `fd_close` operates on both files and directories, `fd_read` only operates
24//! on files, and `fd_readdir` only operates on directories.
25
26//! The `WasiFile` and `WasiDir` traits are defined by `wasi-common` in terms
27//! of types defined directly in the crate's source code (I decided it should
28//! NOT those generated by the `wiggle` proc macros, see snapshot architecture
29//! below), as well as the `cap_std::time` family of types. And, importantly,
30//! `wasi-common` itself provides no implementation of `WasiDir`, and only two
31//! trivial implementations of `WasiFile` on the `crate::pipe::{ReadPipe,
32//! WritePipe}` types, which in turn just delegate to `std::io::{Read,
33//! Write}`. In order for `wasi-common` to access the local filesystem at all,
34//! you need to provide `WasiFile` and `WasiDir` impls through either the new
35//! `wasi-cap-std-sync` crate found at `crates/wasi-common/cap-std-sync` - see
36//! the section on that crate below - or by providing your own implementation
37//! from elsewhere.
38//!
39//! This design makes it possible for `wasi-common` embedders to statically
40//! reason about access to the local filesystem by examining what impls are
41//! linked into an application. We found that this separation of concerns also
42//! makes it pretty enjoyable to write alternative implementations, e.g. a
43//! virtual filesystem.
44//!
45//! Implementations of the `WasiFile` and `WasiDir` traits are provided
46//! for synchronous embeddings in `wasi_common::sync` and for Tokio embeddings
47//! in `wasi_common::tokio`.
48//!
49//! ## Traits for the rest of WASI's features
50//!
51//! Other aspects of a WASI implementation are not yet considered resources
52//! and accessed by `handle`. We plan to correct this design deficiency in
53//! WASI in the future, but for now we have designed the following traits to
54//! provide embedders with the same sort of implementation flexibility they
55//! get with WasiFile/WasiDir:
56//!
57//! * Timekeeping: `WasiSystemClock` and `WasiMonotonicClock` provide the two
58//! interfaces for a clock. `WasiSystemClock` represents time as a
59//! `cap_std::time::SystemTime`, and `WasiMonotonicClock` represents time as
60//! `cap_std::time::Instant`. * Randomness: we re-use the `cap_rand::RngCore`
61//! trait to represent a randomness source. A trivial `Deterministic` impl is
62//! provided. * Scheduling: The `WasiSched` trait abstracts over the
63//! `sched_yield` and `poll_oneoff` functions.
64//!
65//! Users can provide implementations of each of these interfaces to the
66//! `WasiCtx::builder(...)` function. The
67//! `wasi_cap_std_sync::WasiCtxBuilder::new()` function uses this public
68//! interface to plug in its own implementations of each of these resources.
69
70#![warn(clippy::cast_sign_loss)]
71#![cfg_attr(docsrs, feature(doc_cfg))]
72
73pub mod clocks;
74mod ctx;
75pub mod dir;
76mod error;
77pub mod file;
78pub mod pipe;
79pub mod random;
80pub mod sched;
81pub mod snapshots;
82mod string_array;
83#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
84#[cfg(feature = "sync")]
85pub mod sync;
86pub mod table;
87#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
88#[cfg(feature = "tokio")]
89pub mod tokio;
90
91pub use cap_rand::RngCore;
92pub use clocks::{SystemTimeSpec, WasiClocks, WasiMonotonicClock, WasiSystemClock};
93pub use ctx::WasiCtx;
94pub use dir::WasiDir;
95pub use error::{Error, ErrorExt, I32Exit};
96pub use file::WasiFile;
97pub use sched::{Poll, WasiSched};
98pub use string_array::{StringArray, StringArrayError};
99pub use table::Table;
100
101pub(crate) use wasmtime_environ::error::Error as EnvError;
102
103// The only difference between these definitions for sync vs async is whether
104// the wasmtime::Funcs generated are async (& therefore need an async Store and an executor to run)
105// or whether they have an internal "dummy executor" that expects the implementation of all
106// the async funcs to poll to Ready immediately.
107#[cfg(feature = "wasmtime")]
108#[doc(hidden)]
109#[macro_export]
110macro_rules! define_wasi {
111 ($async_mode:tt $($bounds:tt)*) => {
112
113 use wasmtime::Linker;
114 use wasmtime_environ::error::Result as EnvResult;
115
116 pub fn add_to_linker<T, U>(
117 linker: &mut Linker<T>,
118 get_cx: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
119 ) -> EnvResult<()>
120 where U: Send
121 + crate::snapshots::preview_0::wasi_unstable::WasiUnstable
122 + crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1,
123 T: 'static,
124 $($bounds)*
125 {
126 snapshots::preview_1::add_wasi_snapshot_preview1_to_linker(linker, get_cx)?;
127 snapshots::preview_0::add_wasi_unstable_to_linker(linker, get_cx)?;
128 Ok(())
129 }
130
131 pub mod snapshots {
132 pub mod preview_1 {
133 wiggle::wasmtime_integration!({
134 // The wiggle code to integrate with lives here:
135 target: crate::snapshots::preview_1,
136 witx: ["witx/preview1/wasi_snapshot_preview1.witx"],
137 errors: { errno => trappable Error },
138 $async_mode: *
139 });
140 }
141 pub mod preview_0 {
142 wiggle::wasmtime_integration!({
143 // The wiggle code to integrate with lives here:
144 target: crate::snapshots::preview_0,
145 witx: ["witx/preview0/wasi_unstable.witx"],
146 errors: { errno => trappable Error },
147 $async_mode: *
148 });
149 }
150 }
151}}
152
153/// Exit the process with a conventional OS error code as long as Wasmtime
154/// understands the error. If the error is not an `I32Exit` or `Trap`, return
155/// the error back to the caller for it to decide what to do.
156///
157/// Note: this function is designed for usage where it is acceptable for
158/// Wasmtime failures to terminate the parent process, such as in the Wasmtime
159/// CLI; this would not be suitable for use in multi-tenant embeddings.
160#[cfg_attr(docsrs, doc(cfg(feature = "exit")))]
161#[cfg(feature = "exit")]
162pub fn maybe_exit_on_error(e: EnvError) -> EnvError {
163 use std::process;
164 use wasmtime::Trap;
165
166 // If a specific WASI error code was requested then that's
167 // forwarded through to the process here without printing any
168 // extra error information.
169 if let Some(exit) = e.downcast_ref::<crate::I32Exit>() {
170 process::exit(exit.0);
171 }
172
173 // If the program exited because of a trap, return an error code
174 // to the outside environment indicating a more severe problem
175 // than a simple failure.
176 if e.is::<Trap>() {
177 eprintln!("Error: {e:?}");
178
179 if cfg!(unix) {
180 // On Unix, return the error code of an abort.
181 process::exit(128 + libc::SIGABRT);
182 } else if cfg!(windows) {
183 // On Windows, return 3.
184 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/abort?view=vs-2019
185 process::exit(3);
186 }
187 }
188
189 e
190}