Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -173,16 +173,6 @@ jobs:
env:
CARGO_PROFILE_DEV_DEBUG_ASSERTIONS: false

# Check whether `crates/wasi-common` cross-compiles to the following targets:
# * wasm32-unknown-emscripten
# * armv7-unknown-linux-gnueabihf
- run: |
rustup target add wasm32-unknown-emscripten
rustup target add armv7-unknown-linux-gnueabihf
sudo apt-get update && sudo apt-get install -y gcc-arm-linux-gnueabihf
- run: cargo check --target wasm32-unknown-emscripten -p wasi-common
- run: cargo check --target armv7-unknown-linux-gnueabihf -p wasi-common

# Check whether `wasmtime` cross-compiles to aarch64-pc-windows-msvc
# We don't build nor test it because it lacks trap handling.
# Tracking issue: https://github.com/bytecodealliance/wasmtime/issues/4992
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/wasi-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ links = "wasi-common-19"
[dependencies]
anyhow = { workspace = true }
thiserror = "1.0"
wiggle = { workspace = true, default-features = false }
wiggle = { workspace = true }
wasmtime = { workspace = true }
tracing = "0.1.19"
cap-std = { workspace = true }
cap-rand = "0.26.0"
Expand Down
6 changes: 3 additions & 3 deletions crates/wasi-common/src/snapshots/preview_0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ impl wiggle::GuestErrorType for types::Errno {
}

impl types::UserErrorConversion for WasiCtx {
fn errno_from_error(&mut self, e: Error) -> Result<types::Errno, wiggle::Trap> {
fn errno_from_error(&mut self, e: Error) -> Result<types::Errno, wasmtime::Trap> {
debug!("Error: {:?}", e);
e.try_into()
.map_err(|e| wiggle::Trap::String(format!("{:?}", e)))
.map_err(|e| wasmtime::Trap::new(format!("{:?}", e)))
}
}

Expand Down Expand Up @@ -932,7 +932,7 @@ impl wasi_unstable::WasiUnstable for WasiCtx {
Ok(num_results.try_into().expect("results fit into memory"))
}

async fn proc_exit(&mut self, status: types::Exitcode) -> wiggle::Trap {
async fn proc_exit(&mut self, status: types::Exitcode) -> wasmtime::Trap {
Snapshot1::proc_exit(self, status).await
}

Expand Down
10 changes: 5 additions & 5 deletions crates/wasi-common/src/snapshots/preview_1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ impl wiggle::GuestErrorType for types::Errno {
}

impl types::UserErrorConversion for WasiCtx {
fn errno_from_error(&mut self, e: Error) -> Result<types::Errno, wiggle::Trap> {
fn errno_from_error(&mut self, e: Error) -> Result<types::Errno, wasmtime::Trap> {
debug!("Error: {:?}", e);
e.try_into()
.map_err(|e| wiggle::Trap::String(format!("{:?}", e)))
.map_err(|e| wasmtime::Trap::new(format!("{:?}", e)))
}
}

Expand Down Expand Up @@ -1214,12 +1214,12 @@ impl wasi_snapshot_preview1::WasiSnapshotPreview1 for WasiCtx {
Ok(num_results.try_into().expect("results fit into memory"))
}

async fn proc_exit(&mut self, status: types::Exitcode) -> wiggle::Trap {
async fn proc_exit(&mut self, status: types::Exitcode) -> wasmtime::Trap {
// Check that the status is within WASI's range.
if status < 126 {
wiggle::Trap::I32Exit(status as i32)
wasmtime::Trap::i32_exit(status as i32)
} else {
wiggle::Trap::String("exit with invalid exit status outside of [0..126)".to_owned())
wasmtime::Trap::new("exit with invalid exit status outside of [0..126)")
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/wasi-common/tokio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ include = ["src/**/*", "LICENSE" ]
[dependencies]
wasi-common = { workspace = true }
wasi-cap-std-sync = { workspace = true }
wiggle = { workspace = true, features = ['wasmtime_integration'] }
wiggle = { workspace = true }
tokio = { version = "1.8.0", features = [ "rt", "fs", "time", "io-util", "net", "io-std", "rt-multi-thread"] }
cap-std = { workspace = true }
anyhow = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion crates/wasi-crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ edition.workspace = true
anyhow = { workspace = true }
wasi-crypto = { path = "spec/implementations/hostcalls/rust", version = "0.1.5" }
wasmtime = { workspace = true }
wiggle = { workspace = true, default-features = true, features = ['wasmtime_integration'] }
wiggle = { workspace = true }

[badges]
maintenance = { status = "experimental" }
5 changes: 4 additions & 1 deletion crates/wasi-nn/src/witx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ wiggle::from_witx!({
use types::NnErrno;

impl<'a> types::UserErrorConversion for WasiNnCtx {
fn nn_errno_from_wasi_nn_error(&mut self, e: WasiNnError) -> Result<NnErrno, wiggle::Trap> {
fn nn_errno_from_wasi_nn_error(
&mut self,
e: WasiNnError,
) -> Result<NnErrno, wiggle::wasmtime_crate::Trap> {
eprintln!("Host error: {:?}", e);
match e {
WasiNnError::BackendError(_) => unimplemented!(),
Expand Down
2 changes: 1 addition & 1 deletion crates/wasi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ build = "build.rs"
wasi-common = { workspace = true }
wasi-cap-std-sync = { workspace = true, optional = true }
wasi-tokio = { workspace = true, optional = true }
wiggle = { workspace = true, default-features = false, features = ["wasmtime_integration"] }
wiggle = { workspace = true }
wasmtime = { workspace = true }
anyhow = { workspace = true }

Expand Down
12 changes: 5 additions & 7 deletions crates/wiggle/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ wiggle-macro = { workspace = true }
tracing = "0.1.26"
bitflags = "1.2"
async-trait = "0.1.42"
wasmtime = { workspace = true, optional = true }
wasmtime = { workspace = true }
anyhow = { workspace = true }

[badges]
Expand All @@ -41,12 +41,12 @@ required-features = ["wasmtime_async", "wasmtime/wat"]
[[test]]
name = "wasmtime_sync"
path = "tests/wasmtime_sync.rs"
required-features = ["wasmtime_integration", "wasmtime/wat"]
required-features = ["wasmtime/wat"]

[[test]]
name = "wasmtime_integration"
path = "tests/wasmtime_integration.rs"
required-features = ["wasmtime_integration", "wasmtime/wat"]
required-features = ["wasmtime/wat"]


[features]
Expand All @@ -62,9 +62,7 @@ wiggle_metadata = ['witx', "wiggle-macro/wiggle_metadata"]
# the logs out of wiggle-generated libraries.
tracing_log = [ "tracing/log" ]

# Generate adapters for wasmtime, and expose the wasmtime_integration macro.
wasmtime_integration = [ "wasmtime", "wiggle-macro/wasmtime" ]
# Support for async in the wasmtime crates.
wasmtime_async = [ "wasmtime_integration", "wasmtime/async" ]
wasmtime_async = [ "wasmtime/async" ]

default = ["wiggle_metadata", "wasmtime_integration" ]
default = ["wiggle_metadata", "wasmtime_async" ]
4 changes: 2 additions & 2 deletions crates/wiggle/generate/src/funcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ fn _define_func(
ctx: &mut (impl #(#bounds)+*),
memory: &dyn #rt::GuestMemory,
#(#abi_params),*
) -> Result<#abi_ret, #rt::Trap> {
) -> Result<#abi_ret, #rt::wasmtime_crate::Trap> {
use std::convert::TryFrom as _;
#mk_span
_span.in_scope(|| {
Expand All @@ -109,7 +109,7 @@ fn _define_func(
ctx: &'a mut (impl #(#bounds)+*),
memory: &'a dyn #rt::GuestMemory,
#(#abi_params),*
) -> impl std::future::Future<Output = Result<#abi_ret, #rt::Trap>> + 'a {
) -> impl std::future::Future<Output = Result<#abi_ret, #rt::wasmtime_crate::Trap>> + 'a {
use std::convert::TryFrom as _;
use #rt::tracing::Instrument as _;
#mk_span
Expand Down
2 changes: 1 addition & 1 deletion crates/wiggle/generate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn generate(doc: &witx::Document, names: &Names, settings: &CodegenSettings)
let abi_typename = names.type_ref(&errtype.abi_type(), anon_lifetime());
let user_typename = errtype.typename();
let methodname = names.user_error_conversion_method(&errtype);
quote!(fn #methodname(&mut self, e: super::#user_typename) -> Result<#abi_typename, #rt::Trap>;)
quote!(fn #methodname(&mut self, e: super::#user_typename) -> Result<#abi_typename, #rt::wasmtime_crate::Trap>;)
});
let user_error_conversion = quote! {
pub trait UserErrorConversion {
Expand Down
2 changes: 1 addition & 1 deletion crates/wiggle/generate/src/module_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub fn define_module_trait(names: &Names, m: &Module, settings: &CodegenSettings
});

let result = match f.results.len() {
0 if f.noreturn => quote!(#rt::Trap),
0 if f.noreturn => quote!(#rt::wasmtime_crate::Trap),
0 => quote!(()),
1 => {
let (ok, err) = match &**f.results[0].tref.type_() {
Expand Down
6 changes: 1 addition & 5 deletions crates/wiggle/generate/src/wasmtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,7 @@ fn generate_func(
let (mem , ctx) = mem.data_and_store_mut(&mut caller);
let ctx = get_cx(ctx);
let mem = #rt::wasmtime::WasmtimeGuestMemory::new(mem);
match #abi_func(ctx, &mem #(, #arg_names)*) #await_ {
Ok(r) => Ok(<#ret_ty>::from(r)),
Err(#rt::Trap::String(err)) => Err(#rt::wasmtime_crate::Trap::new(err)),
Err(#rt::Trap::I32Exit(err)) => Err(#rt::wasmtime_crate::Trap::i32_exit(err)),
}
Ok(<#ret_ty>::from(#abi_func(ctx, &mem #(, #arg_names)*) #await_ ?))
};

match asyncness {
Expand Down
1 change: 0 additions & 1 deletion crates/wiggle/macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,4 @@ proc-macro2 = "1.0"
wiggle = { path = ".." }

[features]
wasmtime = []
wiggle_metadata = []
17 changes: 6 additions & 11 deletions crates/wiggle/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,14 @@ use syn::parse_macro_input;
///
/// impl types::UserErrorConversion for YourCtxType {
/// fn errno_from_your_rich_error(&mut self, e: YourRichError)
/// -> Result<types::Errno, wiggle::Trap>
/// -> Result<types::Errno, wiggle::wasmtime_crate::Trap>
/// {
/// println!("Rich error: {:?}", e);
/// match e {
/// YourRichError::InvalidArg{..} => Ok(types::Errno::InvalidArg),
/// YourRichError::Io{..} => Ok(types::Errno::Io),
/// YourRichError::Overflow => Ok(types::Errno::Overflow),
/// YourRichError::Trap(s) => Err(wiggle::Trap::String(s)),
/// YourRichError::Trap(s) => Err(wiggle::wasmtime_crate::Trap::new(s)),
/// }
/// }
/// }
Expand All @@ -152,7 +152,7 @@ pub fn from_witx(args: TokenStream) -> TokenStream {
&config.errors,
&config.async_,
&doc,
cfg!(feature = "wasmtime") && config.wasmtime,
config.wasmtime,
)
.expect("validating codegen settings");

Expand All @@ -176,7 +176,6 @@ pub fn async_trait(attr: TokenStream, item: TokenStream) -> TokenStream {
})
}

#[cfg(feature = "wasmtime")]
/// Define the structs required to integrate a Wiggle implementation with Wasmtime.
///
/// ## Arguments
Expand All @@ -190,13 +189,9 @@ pub fn wasmtime_integration(args: TokenStream) -> TokenStream {
let doc = config.c.load_document();
let names = wiggle_generate::Names::new(quote!(wiggle));

let settings = wiggle_generate::CodegenSettings::new(
&config.c.errors,
&config.c.async_,
&doc,
cfg!(feature = "wasmtime"),
)
.expect("validating codegen settings");
let settings =
wiggle_generate::CodegenSettings::new(&config.c.errors, &config.c.async_, &doc, true)
.expect("validating codegen settings");

let modules = doc.modules().map(|module| {
wiggle_generate::wasmtime::link_module(&module, &names, Some(&config.target), &settings)
Expand Down
27 changes: 5 additions & 22 deletions crates/wiggle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use std::sync::Arc;

pub use wiggle_macro::{async_trait, from_witx};

#[cfg(feature = "wasmtime")]
pub use anyhow;
#[cfg(feature = "wasmtime")]
pub use wiggle_macro::wasmtime_integration;

pub use bitflags;
Expand All @@ -30,10 +28,7 @@ pub mod async_trait_crate {
pub use async_trait::*;
}

#[cfg(feature = "wasmtime")]
pub mod wasmtime;

#[cfg(feature = "wasmtime")]
pub mod wasmtime_crate {
pub use wasmtime::*;
}
Expand Down Expand Up @@ -914,26 +909,14 @@ impl Pointee for str {
}
}

/// A runtime-independent way for Wiggle to terminate WebAssembly execution.
/// Functions that are marked `(@witx noreturn)` will always return a Trap.
/// Other functions that want to Trap can do so via their `UserErrorConversion`
/// trait, which transforms the user's own error type into a `Result<abierror, Trap>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Trap {
/// A Trap which indicates an i32 (posix-style) exit code. Runtimes may have a
/// special way of dealing with this for WASI embeddings and otherwise.
I32Exit(i32),
/// Any other Trap is just an unstructured String, for reporting and debugging.
String(String),
}

impl From<GuestError> for Trap {
fn from(err: GuestError) -> Trap {
Trap::String(err.to_string())
impl From<GuestError> for wasmtime_crate::Trap {
fn from(err: GuestError) -> wasmtime_crate::Trap {
wasmtime_crate::Trap::from(
Box::new(err) as Box<dyn std::error::Error + Send + Sync + 'static>
)
}
}

#[cfg(feature = "wasmtime")]
pub fn run_in_dummy_executor<F: std::future::Future>(
future: F,
) -> Result<F::Output, wasmtime_crate::Trap> {
Expand Down
17 changes: 10 additions & 7 deletions crates/wiggle/test-helpers/examples/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ impl_errno!(types::Errno);
/// When the `errors` mapping in witx is non-empty, we need to impl the
/// types::UserErrorConversion trait that wiggle generates from that mapping.
impl<'a> types::UserErrorConversion for WasiCtx<'a> {
fn errno_from_rich_error(&mut self, e: RichError) -> Result<types::Errno, wiggle::Trap> {
fn errno_from_rich_error(
&mut self,
e: RichError,
) -> Result<types::Errno, wiggle::wasmtime_crate::Trap> {
wiggle::tracing::debug!(
rich_error = wiggle::tracing::field::debug(&e),
"error conversion"
Expand Down Expand Up @@ -83,19 +86,19 @@ fn main() {

// Exercise each of the branches in `foo`.
// Start with the success case:
let r0 = one_error_conversion::foo(&mut ctx, &host_memory, 0, 0, 8);
let r0 = one_error_conversion::foo(&mut ctx, &host_memory, 0, 0, 8).unwrap();
assert_eq!(
r0,
Ok(types::Errno::Ok as i32),
types::Errno::Ok as i32,
"Expected return value for strike=0"
);
assert!(ctx.log.borrow().is_empty(), "No error log for strike=0");

// First error case:
let r1 = one_error_conversion::foo(&mut ctx, &host_memory, 1, 0, 8);
let r1 = one_error_conversion::foo(&mut ctx, &host_memory, 1, 0, 8).unwrap();
assert_eq!(
r1,
Ok(types::Errno::PicketLine as i32),
types::Errno::PicketLine as i32,
"Expected return value for strike=1"
);
assert_eq!(
Expand All @@ -105,10 +108,10 @@ fn main() {
);

// Second error case:
let r2 = one_error_conversion::foo(&mut ctx, &host_memory, 2, 0, 8);
let r2 = one_error_conversion::foo(&mut ctx, &host_memory, 2, 0, 8).unwrap();
assert_eq!(
r2,
Ok(types::Errno::InvalidArg as i32),
types::Errno::InvalidArg as i32,
"Expected return value for strike=2"
);
assert_eq!(
Expand Down
10 changes: 6 additions & 4 deletions crates/wiggle/tests/atoms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ impl IntFloatExercise {
let mut ctx = WasiCtx::new();
let host_memory = HostMemory::new();

let e = atoms::int_float_args(&mut ctx, &host_memory, self.an_int as i32, self.an_float);
let e = atoms::int_float_args(&mut ctx, &host_memory, self.an_int as i32, self.an_float)
.unwrap();

assert_eq!(e, Ok(types::Errno::Ok as i32), "int_float_args error");
assert_eq!(e, types::Errno::Ok as i32, "int_float_args error");
}

pub fn strat() -> BoxedStrategy<Self> {
Expand Down Expand Up @@ -68,13 +69,14 @@ impl DoubleIntExercise {
&host_memory,
self.input as i32,
self.return_loc.ptr as i32,
);
)
.unwrap();

let return_val = host_memory
.ptr::<types::AliasToFloat>(self.return_loc.ptr)
.read()
.expect("failed to read return");
assert_eq!(e, Ok(types::Errno::Ok as i32), "errno");
assert_eq!(e, types::Errno::Ok as i32, "errno");
assert_eq!(return_val, (self.input as f32) * 2.0, "return val");
}

Expand Down
Loading