Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Migrate wasi-common to `wasmtime::error` (#12293)

Nick Fitzgerald05a041c24be4
diff --git a/Cargo.lock b/Cargo.lock
index 5a47cff797..adbff68e37 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4197,7 +4197,6 @@ dependencies = [
name = "wasi-common"
version = "42.0.0"
dependencies = [
- "anyhow",
"async-trait",
"bitflags 2.9.4",
"cap-fs-ext",
@@ -4220,6 +4219,7 @@ dependencies = [
"tracing-subscriber",
"wasi-common",
"wasmtime",
+ "wasmtime-environ",
"wiggle",
"windows-sys 0.61.2",
]
diff --git a/crates/wasi-common/Cargo.toml b/crates/wasi-common/Cargo.toml
index c0cfd17967..fcde029fad 100644
--- a/crates/wasi-common/Cargo.toml
+++ b/crates/wasi-common/Cargo.toml
@@ -16,7 +16,6 @@ include = ["src/**/*", "tests/**/*", "witx", "README.md", "LICENSE", "build.rs"]
workspace = true
[dependencies]
-anyhow = { workspace = true, features = ['std'] }
thiserror = { workspace = true }
wiggle = { workspace = true }
tracing = { workspace = true }
@@ -25,6 +24,7 @@ cap-rand = { workspace = true }
bitflags = { workspace = true }
log = { workspace = true }
async-trait = { workspace = true }
+wasmtime-environ = { workspace = true }
# Optional, enabled by wasmtime feature:
wasmtime = { workspace = true, optional = true, features = ['runtime'] }
diff --git a/crates/wasi-common/src/error.rs b/crates/wasi-common/src/error.rs
index 11b43ecd49..a4e52a4efa 100644
--- a/crates/wasi-common/src/error.rs
+++ b/crates/wasi-common/src/error.rs
@@ -1,5 +1,5 @@
//! wasi-common uses an [`Error`] type which represents either a preview 1 [`Errno`] enum, on
-//! [`anyhow::Error`] for trapping execution.
+//! [`wasmtime_environ::error::Error`] for trapping execution.
//!
//! The user can construct an [`Error`] out of an [`Errno`] using the `From`/`Into` traits.
//! They may also use [`Error::trap`] to construct an error that traps execution. The contents
diff --git a/crates/wasi-common/src/lib.rs b/crates/wasi-common/src/lib.rs
index d1dd6771ec..98caebc4e9 100644
--- a/crates/wasi-common/src/lib.rs
+++ b/crates/wasi-common/src/lib.rs
@@ -98,6 +98,8 @@ pub use sched::{Poll, WasiSched};
pub use string_array::{StringArray, StringArrayError};
pub use table::Table;
+pub(crate) use wasmtime_environ::error::Error as EnvError;
+
// The only difference between these definitions for sync vs async is whether
// the wasmtime::Funcs generated are async (& therefore need an async Store and an executor to run)
// or whether they have an internal "dummy executor" that expects the implementation of all
@@ -109,11 +111,12 @@ macro_rules! define_wasi {
($async_mode:tt $($bounds:tt)*) => {
use wasmtime::Linker;
+ use wasmtime_environ::error::Result as EnvResult;
pub fn add_to_linker<T, U>(
linker: &mut Linker<T>,
get_cx: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
- ) -> anyhow::Result<()>
+ ) -> EnvResult<()>
where U: Send
+ crate::snapshots::preview_0::wasi_unstable::WasiUnstable
+ crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1,
@@ -156,7 +159,7 @@ macro_rules! define_wasi {
/// CLI; this would not be suitable for use in multi-tenant embeddings.
#[cfg_attr(docsrs, doc(cfg(feature = "exit")))]
#[cfg(feature = "exit")]
-pub fn maybe_exit_on_error(e: anyhow::Error) -> anyhow::Error {
+pub fn maybe_exit_on_error(e: EnvError) -> EnvError {
use std::process;
use wasmtime::Trap;
diff --git a/crates/wasi-common/src/snapshots/preview_0.rs b/crates/wasi-common/src/snapshots/preview_0.rs
index 0eda288325..5320ddc57d 100644
--- a/crates/wasi-common/src/snapshots/preview_0.rs
+++ b/crates/wasi-common/src/snapshots/preview_0.rs
@@ -5,7 +5,7 @@ use crate::sched::{
};
use crate::snapshots::preview_1::types as snapshot1_types;
use crate::snapshots::preview_1::wasi_snapshot_preview1::WasiSnapshotPreview1 as Snapshot1;
-use crate::{ErrorExt, WasiCtx};
+use crate::{EnvError, ErrorExt, WasiCtx};
use cap_std::time::Duration;
use std::collections::HashSet;
use wiggle::{GuestMemory, GuestPtr};
@@ -1004,7 +1004,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
&mut self,
memory: &mut GuestMemory<'_>,
status: types::Exitcode,
- ) -> anyhow::Error {
+ ) -> EnvError {
Snapshot1::proc_exit(self, memory, status).await
}
@@ -1013,7 +1013,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
_memory: &mut GuestMemory<'_>,
_sig: types::Signal,
) -> Result<(), Error> {
- Err(Error::trap(anyhow::Error::msg("proc_raise unsupported")))
+ Err(Error::trap(EnvError::msg("proc_raise unsupported")))
}
async fn sched_yield(&mut self, memory: &mut GuestMemory<'_>) -> Result<(), Error> {
@@ -1038,7 +1038,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
_ri_data: types::IovecArray,
_ri_flags: types::Riflags,
) -> Result<(types::Size, types::Roflags), Error> {
- Err(Error::trap(anyhow::Error::msg("sock_recv unsupported")))
+ Err(Error::trap(EnvError::msg("sock_recv unsupported")))
}
async fn sock_send(
@@ -1048,7 +1048,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
_si_data: types::CiovecArray,
_si_flags: types::Siflags,
) -> Result<types::Size, Error> {
- Err(Error::trap(anyhow::Error::msg("sock_send unsupported")))
+ Err(Error::trap(EnvError::msg("sock_send unsupported")))
}
async fn sock_shutdown(
@@ -1057,7 +1057,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
_fd: types::Fd,
_how: types::Sdflags,
) -> Result<(), Error> {
- Err(Error::trap(anyhow::Error::msg("sock_shutdown unsupported")))
+ Err(Error::trap(EnvError::msg("sock_shutdown unsupported")))
}
}
diff --git a/crates/wasi-common/src/snapshots/preview_1.rs b/crates/wasi-common/src/snapshots/preview_1.rs
index feb87bb5d3..395cf49a9d 100644
--- a/crates/wasi-common/src/snapshots/preview_1.rs
+++ b/crates/wasi-common/src/snapshots/preview_1.rs
@@ -1,5 +1,5 @@
use crate::{
- I32Exit, SystemTimeSpec, WasiCtx,
+ EnvError, I32Exit, SystemTimeSpec, WasiCtx,
dir::{DirEntry, OpenResult, ReaddirCursor, ReaddirEntity, TableDirExt},
file::{
Advice, FdFlags, FdStat, FileAccessMode, FileEntry, FileType, Filestat, OFlags, RiFlags,
@@ -101,9 +101,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
let now = self.clocks.system()?.now(precision).into_std();
let d = now
.duration_since(std::time::SystemTime::UNIX_EPOCH)
- .map_err(|_| {
- Error::trap(anyhow::Error::msg("current time before unix epoch"))
- })?;
+ .map_err(|_| Error::trap(EnvError::msg("current time before unix epoch")))?;
Ok(d.as_nanos().try_into()?)
}
types::Clockid::Monotonic => {
@@ -1135,12 +1133,12 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
&mut self,
_memory: &mut GuestMemory<'_>,
status: types::Exitcode,
- ) -> anyhow::Error {
+ ) -> EnvError {
// Check that the status is within WASI's range.
if status < 126 {
I32Exit(status as i32).into()
} else {
- anyhow::Error::msg("exit with invalid exit status outside of [0..126)")
+ EnvError::msg("exit with invalid exit status outside of [0..126)")
}
}
@@ -1149,7 +1147,7 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
_memory: &mut GuestMemory<'_>,
_sig: types::Signal,
) -> Result<(), Error> {
- Err(Error::trap(anyhow::Error::msg("proc_raise unsupported")))
+ Err(Error::trap(EnvError::msg("proc_raise unsupported")))
}
async fn sched_yield(&mut self, _memory: &mut GuestMemory<'_>) -> Result<(), Error> {
diff --git a/crates/wasi-common/src/snapshots/preview_1/error.rs b/crates/wasi-common/src/snapshots/preview_1/error.rs
index b2164390cd..538f8b91d0 100644
--- a/crates/wasi-common/src/snapshots/preview_1/error.rs
+++ b/crates/wasi-common/src/snapshots/preview_1/error.rs
@@ -1,3 +1,5 @@
+use wasmtime_environ::error::format_err;
+
pub use super::types::{Errno, Error};
pub trait ErrorExt {
@@ -217,7 +219,7 @@ impl From<std::io::Error> for Error {
std::io::ErrorKind::AlreadyExists => Errno::Exist.into(),
std::io::ErrorKind::InvalidInput => Errno::Inval.into(),
std::io::ErrorKind::WouldBlock => Errno::Again.into(),
- _ => Error::trap(anyhow::anyhow!(err).context("Unknown OS error")),
+ _ => Error::trap(format_err!(err).context("Unknown OS error")),
},
}
}
diff --git a/crates/wasi-common/src/sync/sched/windows.rs b/crates/wasi-common/src/sync/sched/windows.rs
index a8e8580c5b..a6f4f1fb4f 100644
--- a/crates/wasi-common/src/sync/sched/windows.rs
+++ b/crates/wasi-common/src/sync/sched/windows.rs
@@ -9,7 +9,7 @@
// taken the time to improve it. See bug #2880.
use crate::sched::subscription::{RwEventFlags, Subscription};
-use crate::{Error, ErrorExt, file::WasiFile, sched::Poll};
+use crate::{EnvError, Error, ErrorExt, file::WasiFile, sched::Poll};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
use std::sync::{LazyLock, Mutex};
use std::thread;
@@ -70,7 +70,7 @@ pub async fn poll_oneoff_<'a>(
if !stdin_read_subs.is_empty() {
let state = STDIN_POLL
.lock()
- .map_err(|_| Error::trap(anyhow::Error::msg("failed to take lock of STDIN_POLL")))?
+ .map_err(|_| Error::trap(EnvError::msg("failed to take lock of STDIN_POLL")))?
.poll(waitmode)?;
for readsub in stdin_read_subs.into_iter() {
match state {
@@ -82,7 +82,7 @@ pub async fn poll_oneoff_<'a>(
PollState::Error(ref e) => {
// Unfortunately, we need to deliver the Error to each of the
// subscriptions, but there is no Clone on std::io::Error. So, we convert it to the
- // kind, and then back to std::io::Error, and finally to anyhow::Error.
+ // kind, and then back to std::io::Error, and finally to EnvError.
// When its time to turn this into an errno elsewhere, the error kind will
// be inspected.
let ekind = e.kind();
@@ -164,7 +164,7 @@ impl StdinPoll {
// Clean up possibly unread result from previous poll.
Ok(_) | Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
- return Err(Error::trap(anyhow::Error::msg(
+ return Err(Error::trap(EnvError::msg(
"StdinPoll notify_rx channel closed",
)));
}
@@ -173,25 +173,25 @@ impl StdinPoll {
// Notify the worker thread to poll stdin
self.request_tx
.send(())
- .map_err(|_| Error::trap(anyhow::Error::msg("request_tx channel closed")))?;
+ .map_err(|_| Error::trap(EnvError::msg("request_tx channel closed")))?;
// Wait for the worker thread to send a readiness notification
match wait_mode {
WaitMode::Timeout(timeout) => match self.notify_rx.recv_timeout(timeout) {
Ok(r) => Ok(r),
Err(RecvTimeoutError::Timeout) => Ok(PollState::TimedOut),
- Err(RecvTimeoutError::Disconnected) => Err(Error::trap(anyhow::Error::msg(
+ Err(RecvTimeoutError::Disconnected) => Err(Error::trap(EnvError::msg(
"StdinPoll notify_rx channel closed",
))),
},
WaitMode::Infinite => self
.notify_rx
.recv()
- .map_err(|_| Error::trap(anyhow::Error::msg("StdinPoll notify_rx channel closed"))),
+ .map_err(|_| Error::trap(EnvError::msg("StdinPoll notify_rx channel closed"))),
WaitMode::Immediate => match self.notify_rx.try_recv() {
Ok(r) => Ok(r),
Err(TryRecvError::Empty) => Ok(PollState::NotReady),
- Err(TryRecvError::Disconnected) => Err(Error::trap(anyhow::Error::msg(
+ Err(TryRecvError::Disconnected) => Err(Error::trap(EnvError::msg(
"StdinPoll notify_rx channel closed",
))),
},
diff --git a/crates/wasi-common/src/table.rs b/crates/wasi-common/src/table.rs
index 4006963678..cd817d38c3 100644
--- a/crates/wasi-common/src/table.rs
+++ b/crates/wasi-common/src/table.rs
@@ -1,4 +1,4 @@
-use crate::{Error, ErrorExt};
+use crate::{EnvError, Error, ErrorExt};
use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
@@ -37,7 +37,7 @@ impl Table {
// NOTE: The performance of this new key calculation could be very bad once keys wrap
// around.
if inner.map.len() == u32::MAX as usize {
- return Err(Error::trap(anyhow::Error::msg("table has no free keys")));
+ return Err(Error::trap(EnvError::msg("table has no free keys")));
}
loop {
let key = inner.next_key;
diff --git a/crates/wasi-common/tests/all/async_.rs b/crates/wasi-common/tests/all/async_.rs
index 115059d021..34372e3c68 100644
--- a/crates/wasi-common/tests/all/async_.rs
+++ b/crates/wasi-common/tests/all/async_.rs
@@ -52,7 +52,7 @@ async fn run(path: &str, inherit_stdio: bool) -> Result<()> {
Ok(())
};
- r.map_err(move |trap: anyhow::Error| {
+ r.map_err(move |trap: EnvError| {
let stdout = stdout
.try_into_inner()
.expect("sole ref to stdout")
diff --git a/crates/wasi-common/tests/all/main.rs b/crates/wasi-common/tests/all/main.rs
index b11d8fcc5c..7b5106855c 100644
--- a/crates/wasi-common/tests/all/main.rs
+++ b/crates/wasi-common/tests/all/main.rs
@@ -1,8 +1,8 @@
-use anyhow::Result;
use std::path::Path;
use tempfile::TempDir;
use wasi_common::pipe::WritePipe;
use wasmtime::{Linker, Module, Store};
+use wasmtime_environ::error::{Error as EnvError, Result};
pub fn prepare_workspace(exe_name: &str) -> Result<TempDir> {
let prefix = format!("wasi_common_{exe_name}_");
diff --git a/crates/wasi-common/tests/all/sync.rs b/crates/wasi-common/tests/all/sync.rs
index 4245cf8d4d..768d1f62ff 100644
--- a/crates/wasi-common/tests/all/sync.rs
+++ b/crates/wasi-common/tests/all/sync.rs
@@ -43,7 +43,7 @@ fn run(path: &str, inherit_stdio: bool) -> Result<()> {
Ok(())
};
- r.map_err(move |trap: anyhow::Error| {
+ r.map_err(move |trap: EnvError| {
let stdout = stdout
.try_into_inner()
.expect("sole ref to stdout")