Skip to content

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

Remove need for explicit `Config::async_support` knob (#12371)

Alex Crichtoncc8d04f45d9b
diff --git a/benches/call.rs b/benches/call.rs
index 1f302b0847..59863d4763 100644
--- a/benches/call.rs
+++ b/benches/call.rs
@@ -67,10 +67,7 @@ fn engines() -> Vec<(Engine, IsAsync)> {
.unwrap(),
IsAsync::NoPooling,
),
- (
- Engine::new(config.async_support(true)).unwrap(),
- IsAsync::Yes,
- ),
+ (Engine::new(&config).unwrap(), IsAsync::Yes),
(
Engine::new(config.allocation_strategy(InstanceAllocationStrategy::Pooling(pool)))
.unwrap(),
diff --git a/crates/c-api/include/wasmtime/async.h b/crates/c-api/include/wasmtime/async.h
index 06327ca022..9ac7588888 100644
--- a/crates/c-api/include/wasmtime/async.h
+++ b/crates/c-api/include/wasmtime/async.h
@@ -4,7 +4,7 @@
* \brief Wasmtime async functionality
*
* Async functionality in Wasmtime is well documented here:
- * https://docs.wasmtime.dev/api/wasmtime/struct.Config.html#method.async_support
+ * https://docs.wasmtime.dev/api/wasmtime/#async
*
* All WebAssembly executes synchronously, but an async support enables the Wasm
* code be executed on a separate stack, so it can be paused and resumed. There
@@ -47,20 +47,6 @@
extern "C" {
#endif
-/**
- * \brief Whether or not to enable support for asynchronous functions in
- * Wasmtime.
- *
- * When enabled, the config can optionally define host functions with async.
- * Instances created and functions called with this Config must be called
- * through their asynchronous APIs, however. For example using
- * wasmtime_func_call will panic when used with this config.
- *
- * For more information see the Rust documentation at
- * https://docs.wasmtime.dev/api/wasmtime/struct.Config.html#method.async_support
- */
-WASMTIME_CONFIG_PROP(void, async_support, bool)
-
/**
* \brief Configures the size of the stacks used for asynchronous execution.
*
diff --git a/crates/c-api/include/wasmtime/store.h b/crates/c-api/include/wasmtime/store.h
index 65613041c9..aefe31c959 100644
--- a/crates/c-api/include/wasmtime/store.h
+++ b/crates/c-api/include/wasmtime/store.h
@@ -144,7 +144,8 @@ WASM_API_EXTERN void wasmtime_context_set_data(wasmtime_context_t *context,
*
* The `context` argument must not be NULL.
*/
-WASM_API_EXTERN void wasmtime_context_gc(wasmtime_context_t *context);
+WASM_API_EXTERN wasmtime_error_t *
+wasmtime_context_gc(wasmtime_context_t *context);
/**
* \brief Set fuel to this context's store for wasm to consume while executing.
diff --git a/crates/c-api/include/wasmtime/store.hh b/crates/c-api/include/wasmtime/store.hh
index ec56126196..766cd8fdeb 100644
--- a/crates/c-api/include/wasmtime/store.hh
+++ b/crates/c-api/include/wasmtime/store.hh
@@ -91,7 +91,13 @@ public:
/// Runs a garbage collection pass in the referenced store to collect loose
/// `externref` values, if any are available.
- void gc() { wasmtime_context_gc(ptr); }
+ Result<std::monostate> gc() {
+ auto *error = wasmtime_context_gc(ptr);
+ if (error != nullptr) {
+ return Error(error);
+ }
+ return std::monostate();
+ }
/// Injects fuel to be consumed within this store.
///
diff --git a/crates/c-api/src/async.rs b/crates/c-api/src/async.rs
index 61e44b3ba6..22f83106c7 100644
--- a/crates/c-api/src/async.rs
+++ b/crates/c-api/src/async.rs
@@ -18,11 +18,6 @@ use crate::{
wasmtime_val_t, wasmtime_val_union,
};
-#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_config_async_support_set(c: &mut wasm_config_t, enable: bool) {
- c.config.async_support(enable);
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn wasmtime_config_async_stack_size_set(c: &mut wasm_config_t, size: usize) {
c.config.async_stack_size(size);
diff --git a/crates/c-api/src/store.rs b/crates/c-api/src/store.rs
index 32531eb157..6e5d2d8e74 100644
--- a/crates/c-api/src/store.rs
+++ b/crates/c-api/src/store.rs
@@ -225,8 +225,10 @@ pub extern "C" fn wasmtime_context_set_wasi(
}
#[unsafe(no_mangle)]
-pub extern "C" fn wasmtime_context_gc(mut context: WasmtimeStoreContextMut<'_>) {
- context.gc(None);
+pub extern "C" fn wasmtime_context_gc(
+ mut context: WasmtimeStoreContextMut<'_>,
+) -> Option<Box<wasmtime_error_t>> {
+ crate::handle_result(context.gc(None), |()| {})
}
#[unsafe(no_mangle)]
diff --git a/crates/debugger/src/lib.rs b/crates/debugger/src/lib.rs
index fccf4b3faa..f37bcd4b71 100644
--- a/crates/debugger/src/lib.rs
+++ b/crates/debugger/src/lib.rs
@@ -466,7 +466,6 @@ mod test {
let mut config = Config::new();
config.guest_debug(true);
- config.async_support(true);
let engine = Engine::new(&config)?;
let module = Module::new(
&engine,
@@ -605,7 +604,6 @@ mod test {
let mut config = Config::new();
config.guest_debug(true);
- config.async_support(true);
let engine = Engine::new(&config)?;
let module = Module::new(
&engine,
@@ -644,7 +642,6 @@ mod test {
let mut config = Config::new();
config.guest_debug(true);
- config.async_support(true);
let engine = Engine::new(&config)?;
let module = Module::new(
&engine,
diff --git a/crates/fuzzing/src/generators/async_config.rs b/crates/fuzzing/src/generators/async_config.rs
index 5e229b4100..dfd2173daa 100644
--- a/crates/fuzzing/src/generators/async_config.rs
+++ b/crates/fuzzing/src/generators/async_config.rs
@@ -28,10 +28,10 @@ impl AsyncConfig {
match self {
AsyncConfig::Disabled => {}
AsyncConfig::YieldWithFuel(_) => {
- config.async_support(true).consume_fuel(true);
+ config.consume_fuel(true);
}
AsyncConfig::YieldWithEpochs { .. } => {
- config.async_support(true).epoch_interruption(true);
+ config.epoch_interruption(true);
}
}
}
diff --git a/crates/fuzzing/src/oracles.rs b/crates/fuzzing/src/oracles.rs
index 4ad56c80cb..5b3024421f 100644
--- a/crates/fuzzing/src/oracles.rs
+++ b/crates/fuzzing/src/oracles.rs
@@ -822,7 +822,7 @@ pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usi
move |mut caller: Caller<'_, StoreLimits>, _params, results| {
log::info!("gc_ops: GC");
if num_gcs.fetch_add(1, SeqCst) < MAX_GCS {
- caller.gc(None);
+ caller.gc(None)?;
}
let a = ExternRef::new(
@@ -1000,7 +1000,7 @@ pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usi
}
// Do a final GC after running the Wasm.
- store.gc(None);
+ store.gc(None)?;
}
assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst));
diff --git a/crates/fuzzing/src/oracles/component_async.rs b/crates/fuzzing/src/oracles/component_async.rs
index 196d34080c..5603958577 100644
--- a/crates/fuzzing/src/oracles/component_async.rs
+++ b/crates/fuzzing/src/oracles/component_async.rs
@@ -41,7 +41,6 @@ pub fn init() {
STATE.get_or_init(|| {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = Engine::new(&config).unwrap();
let component = compile(&engine);
let mut linker = Linker::new(&engine);
diff --git a/crates/misc/component-async-tests/tests/scenario/util.rs b/crates/misc/component-async-tests/tests/scenario/util.rs
index ac4221adf4..49af3a0fe7 100644
--- a/crates/misc/component-async-tests/tests/scenario/util.rs
+++ b/crates/misc/component-async-tests/tests/scenario/util.rs
@@ -38,7 +38,6 @@ pub fn config() -> Config {
config.wasm_component_model_async_stackful(true);
config.wasm_component_model_threading(true);
config.wasm_component_model_error_context(true);
- config.async_support(true);
config
}
diff --git a/crates/test-util/src/component.rs b/crates/test-util/src/component.rs
index 06ea28f4bc..c711ce908e 100644
--- a/crates/test-util/src/component.rs
+++ b/crates/test-util/src/component.rs
@@ -70,9 +70,7 @@ pub fn engine() -> Engine {
}
pub fn async_engine() -> Engine {
- let mut config = config();
- config.async_support(true);
- Engine::new(&config).unwrap()
+ Engine::default()
}
/// Newtype wrapper for `f32` whose `PartialEq` impl considers NaNs equal to each other.
diff --git a/crates/wasi-common/src/lib.rs b/crates/wasi-common/src/lib.rs
index 98caebc4e9..cf1c0b980e 100644
--- a/crates/wasi-common/src/lib.rs
+++ b/crates/wasi-common/src/lib.rs
@@ -43,8 +43,8 @@
//! virtual filesystem.
//!
//! Implementations of the `WasiFile` and `WasiDir` traits are provided
-//! for synchronous embeddings (i.e. Config::async_support(false)) in
-//! `wasi_common::sync` and for Tokio embeddings in `wasi_common::tokio`.
+//! for synchronous embeddings in `wasi_common::sync` and for Tokio embeddings
+//! in `wasi_common::tokio`.
//!
//! ## Traits for the rest of WASI's features
//!
diff --git a/crates/wasi-common/tests/all/async_.rs b/crates/wasi-common/tests/all/async_.rs
index 34372e3c68..5d2d4ec244 100644
--- a/crates/wasi-common/tests/all/async_.rs
+++ b/crates/wasi-common/tests/all/async_.rs
@@ -18,9 +18,7 @@ async fn run(path: &str, inherit_stdio: bool) -> Result<()> {
let stdout = WritePipe::new_in_memory();
let stderr = WritePipe::new_in_memory();
let r = {
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut linker = Linker::<WasiCtx>::new(&engine);
add_to_linker(&mut linker, |cx| cx)?;
diff --git a/crates/wasi-config/src/lib.rs b/crates/wasi-config/src/lib.rs
index 5f7443cb6c..8d38f84a0e 100644
--- a/crates/wasi-config/src/lib.rs
+++ b/crates/wasi-config/src/lib.rs
@@ -15,16 +15,14 @@
//! ```
//! use wasmtime::{
//! component::{Linker, ResourceTable},
-//! Config, Engine, Result, Store,
+//! Engine, Result, Store,
//! };
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
//! use wasmtime_wasi_config::{WasiConfig, WasiConfigVariables};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
-//! let mut config = Config::new();
-//! config.async_support(true);
-//! let engine = Engine::new(&config)?;
+//! let engine = Engine::default();
//!
//! let mut store = Store::new(&engine, Ctx {
//! table: ResourceTable::new(),
diff --git a/crates/wasi-config/tests/main.rs b/crates/wasi-config/tests/main.rs
index 38b29e1d87..70b3f6aec1 100644
--- a/crates/wasi-config/tests/main.rs
+++ b/crates/wasi-config/tests/main.rs
@@ -24,9 +24,7 @@ impl WasiView for Ctx {
}
async fn run_wasi(path: &str, ctx: Ctx) -> Result<()> {
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut store = Store::new(&engine, ctx);
let component = Component::from_file(&engine, path)?;
diff --git a/crates/wasi-http/src/lib.rs b/crates/wasi-http/src/lib.rs
index bcda1fe960..2b52f8317c 100644
--- a/crates/wasi-http/src/lib.rs
+++ b/crates/wasi-http/src/lib.rs
@@ -70,7 +70,7 @@
//! use std::sync::Arc;
//! use tokio::net::TcpListener;
//! use wasmtime::component::{Component, Linker, ResourceTable};
-//! use wasmtime::{Config, Engine, Result, Store};
+//! use wasmtime::{Engine, Result, Store};
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
//! use wasmtime_wasi_http::bindings::ProxyPre;
//! use wasmtime_wasi_http::bindings::http::types::Scheme;
@@ -83,9 +83,7 @@
//! let component = std::env::args().nth(1).unwrap();
//!
//! // Prepare the `Engine` for Wasmtime
-//! let mut config = Config::new();
-//! config.async_support(true);
-//! let engine = Engine::new(&config)?;
+//! let engine = Engine::default();
//!
//! // Compile the component on the command line to machine code
//! let component = Component::from_file(&engine, &component)?;
@@ -249,24 +247,19 @@ use wasmtime::component::{HasData, Linker};
/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
///
/// This function will add the `async` variant of all interfaces into the
-/// `Linker` provided. By `async` this means that this function is only
-/// compatible with [`Config::async_support(true)`][async]. For embeddings with
-/// async support disabled see [`add_to_linker_sync`] instead.
-///
-/// [async]: wasmtime::Config::async_support
+/// `Linker` provided. For embeddings with async support disabled see
+/// [`add_to_linker_sync`] instead.
///
/// # Example
///
/// ```
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi_http::add_to_linker_async(&mut linker)?;
diff --git a/crates/wasi-http/src/p3/mod.rs b/crates/wasi-http/src/p3/mod.rs
index f931da78f7..d8af50b685 100644
--- a/crates/wasi-http/src/p3/mod.rs
+++ b/crates/wasi-http/src/p3/mod.rs
@@ -188,7 +188,6 @@ pub trait WasiHttpView: Send {
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi-http/tests/all/p2.rs b/crates/wasi-http/tests/all/p2.rs
index 6c7dbf4dd6..a420855830 100644
--- a/crates/wasi-http/tests/all/p2.rs
+++ b/crates/wasi-http/tests/all/p2.rs
@@ -132,7 +132,6 @@ async fn run_wasi_http(
let mut config = Config::new();
config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
config.wasm_component_model(true);
- config.async_support(true);
let engine = Engine::new(&config)?;
let component = Component::from_file(&engine, component_filename)?;
diff --git a/crates/wasi-http/tests/all/p2/async_.rs b/crates/wasi-http/tests/all/p2/async_.rs
index 87caa9b3b7..f5a8674255 100644
--- a/crates/wasi-http/tests/all/p2/async_.rs
+++ b/crates/wasi-http/tests/all/p2/async_.rs
@@ -7,7 +7,6 @@ foreach_p2_http!(assert_test_exists);
async fn run(path: &str, server: &Server) -> Result<()> {
let engine = test_programs_artifacts::engine(|config| {
config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
- config.async_support(true);
});
let component = Component::from_file(&engine, path)?;
let mut store = store(&engine, server);
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index f014a318a8..f78d9b5455 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -117,7 +117,6 @@ impl WasiHttpView for Ctx {
async fn run_cli(path: &str, server: &Server) -> wasmtime::Result<()> {
let engine = test_programs_artifacts::engine(|config| {
config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
- config.async_support(true);
config.wasm_component_model_async(true);
});
let component = Component::from_file(&engine, path)?;
@@ -153,7 +152,6 @@ async fn run_http<E: Into<ErrorCode> + 'static>(
) -> wasmtime::Result<Result<http::Response<Collected<Bytes>>, Option<ErrorCode>>> {
let engine = test_programs_artifacts::engine(|config| {
config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
- config.async_support(true);
config.wasm_component_model_async(true);
});
let component = Component::from_file(&engine, component_filename)?;
diff --git a/crates/wasi-io/src/lib.rs b/crates/wasi-io/src/lib.rs
index 7d589ab3b5..118a5fc6fe 100644
--- a/crates/wasi-io/src/lib.rs
+++ b/crates/wasi-io/src/lib.rs
@@ -50,7 +50,7 @@ use wasmtime::component::{HasData, ResourceTable};
/// # Example
///
/// ```
-/// use wasmtime::{Config, Engine};
+/// use wasmtime::Engine;
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi_io::{IoView, add_to_linker_async};
///
@@ -61,9 +61,7 @@ use wasmtime::component::{HasData, ResourceTable};
/// impl IoView for MyState {
/// fn table(&mut self) -> &mut ResourceTable { &mut self.table }
/// }
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config).unwrap();
+/// let engine = Engine::default();
/// let mut linker: Linker<MyState> = Linker::new(&engine);
/// add_to_linker_async(&mut linker).unwrap();
/// ```
@@ -95,17 +93,15 @@ impl<T: ?Sized + IoView> IoView for Box<T> {
/// provided.
///
/// This function will add the `async` variant of all interfaces into the
-/// [`Linker`] provided. By `async` this means that this function is only
-/// compatible with [`Config::async_support(true)`][async]. For embeddings
-/// with async support disabled, you'll need to use other crates, such as the
-/// [`wasmtime-wasi`] crate, which provides an [`add_to_linker_sync`] that
-/// includes an appropriate wasi-io implementation based on this crate's.
+/// [`Linker`] provided. For embeddings which don't want to use async, you'll
+/// need to use other crates, such as the [`wasmtime-wasi`] crate, which
+/// provides an [`add_to_linker_sync`] that includes an appropriate wasi-io
+/// implementation based on this crate's.
///
/// This function will add all interfaces implemented by this crate to the
/// [`Linker`], which corresponds to the `wasi:io/imports` world supported by
/// this crate.
///
-/// [async]: wasmtime::Config::async_support
/// [`Linker`]: wasmtime::component::Linker
/// [`wasmtime-wasi`]: https://crates.io/crates/wasmtime-wasi
/// [`add_to_linker_sync`]: https://docs.rs/wasmtime-wasi/latest/wasmtime_wasi/p2/fn.add_to_linker_sync.html
@@ -114,14 +110,12 @@ impl<T: ?Sized + IoView> IoView for Box<T> {
/// # Example
///
/// ```
-/// use wasmtime::{Engine, Result, Store, Config};
+/// use wasmtime::{Engine, Result, Store};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi_io::IoView;
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi_io::add_to_linker_async(&mut linker)?;
diff --git a/crates/wasi-keyvalue/src/lib.rs b/crates/wasi-keyvalue/src/lib.rs
index 764287e2d6..a4036e20bf 100644
--- a/crates/wasi-keyvalue/src/lib.rs
+++ b/crates/wasi-keyvalue/src/lib.rs
@@ -18,16 +18,14 @@
//! ```
//! use wasmtime::{
//! component::{Linker, ResourceTable},
-//! Config, Engine, Result, Store,
+//! Engine, Result, Store,
//! };
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
//! use wasmtime_wasi_keyvalue::{WasiKeyValue, WasiKeyValueCtx, WasiKeyValueCtxBuilder};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
-//! let mut config = Config::new();
-//! config.async_support(true);
-//! let engine = Engine::new(&config)?;
+//! let engine = Engine::default();
//!
//! let mut store = Store::new(&engine, Ctx {
//! table: ResourceTable::new(),
diff --git a/crates/wasi-keyvalue/tests/main.rs b/crates/wasi-keyvalue/tests/main.rs
index 21d7ad4d63..b196fbecc2 100644
--- a/crates/wasi-keyvalue/tests/main.rs
+++ b/crates/wasi-keyvalue/tests/main.rs
@@ -23,9 +23,7 @@ impl WasiView for Ctx {
}
async fn run_wasi(path: &str, ctx: Ctx) -> Result<()> {
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut store = Store::new(&engine, ctx);
let component = Component::from_file(&engine, path)?;
diff --git a/crates/wasi-threads/src/lib.rs b/crates/wasi-threads/src/lib.rs
index ffaa8ab2e1..6edb59a1a0 100644
--- a/crates/wasi-threads/src/lib.rs
+++ b/crates/wasi-threads/src/lib.rs
@@ -17,13 +17,18 @@ const WASI_ENTRY_POINT: &str = "wasi_thread_start";
pub struct WasiThreadsCtx<T> {
instance_pre: Arc<InstancePre<T>>,
tid: AtomicI32,
+ use_async: bool,
}
impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
- pub fn new(module: Module, linker: Arc<Linker<T>>) -> Result<Self> {
+ pub fn new(module: Module, linker: Arc<Linker<T>>, use_async: bool) -> Result<Self> {
let instance_pre = Arc::new(linker.instantiate_pre(&module)?);
let tid = AtomicI32::new(0);
- Ok(Self { instance_pre, tid })
+ Ok(Self {
+ instance_pre,
+ tid,
+ use_async,
+ })
}
pub fn spawn(&self, host: T, thread_start_arg: i32) -> Result<i32> {
@@ -60,6 +65,7 @@ impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
// Start a Rust thread running a new instance of the current module.
let builder = thread::Builder::new().name(format!("wasi-thread-{wasi_thread_id}"));
+ let use_async = self.use_async;
builder.spawn(move || {
// Catch any panic failures in host code; e.g., if a WASI module
// were to crash, we want all threads to exit, not just this one.
@@ -67,7 +73,7 @@ impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
// Each new instance is created in its own store.
let mut store = Store::new(&instance_pre.module().engine(), host);
- let instance = if instance_pre.module().engine().is_async() {
+ let instance = if use_async {
wasmtime_wasi::runtime::in_tokio(instance_pre.instantiate_async(&mut store))
} else {
instance_pre.instantiate(&mut store)
@@ -86,7 +92,7 @@ impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
log::trace!(
"spawned thread id = {wasi_thread_id}; calling start function `{WASI_ENTRY_POINT}` with: {thread_start_arg}"
);
- let res = if instance_pre.module().engine().is_async() {
+ let res = if use_async {
wasmtime_wasi::runtime::in_tokio(
thread_entry_point
.call_async(&mut store, (wasi_thread_id, thread_start_arg)),
diff --git a/crates/wasi-tls-nativetls/tests/main.rs b/crates/wasi-tls-nativetls/tests/main.rs
index 5854ed58e9..0aa344a815 100644
--- a/crates/wasi-tls-nativetls/tests/main.rs
+++ b/crates/wasi-tls-nativetls/tests/main.rs
@@ -33,9 +33,7 @@ async fn run_test(path: &str) -> Result<()> {
wasi_tls_ctx: WasiTlsCtxBuilder::new().provider(provider).build(),
};
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut store = Store::new(&engine, ctx);
let component = Component::from_file(&engine, path)?;
diff --git a/crates/wasi-tls-openssl/tests/main.rs b/crates/wasi-tls-openssl/tests/main.rs
index e54e14e6e3..d09c0939aa 100644
--- a/crates/wasi-tls-openssl/tests/main.rs
+++ b/crates/wasi-tls-openssl/tests/main.rs
@@ -33,9 +33,7 @@ async fn run_test(path: &str) -> Result<()> {
wasi_tls_ctx: WasiTlsCtxBuilder::new().provider(provider).build(),
};
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut store = Store::new(&engine, ctx);
let component = Component::from_file(&engine, path)?;
diff --git a/crates/wasi-tls/src/lib.rs b/crates/wasi-tls/src/lib.rs
index 183f0ab030..0f011f0bde 100644
--- a/crates/wasi-tls/src/lib.rs
+++ b/crates/wasi-tls/src/lib.rs
@@ -11,7 +11,7 @@
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
//! use wasmtime::{
//! component::{Linker, ResourceTable},
-//! Store, Engine, Result, Config
+//! Store, Engine, Result,
//! };
//! use wasmtime_wasi_tls::{LinkOptions, WasiTls, WasiTlsCtx, WasiTlsCtxBuilder};
//!
@@ -42,9 +42,7 @@
//! .build(),
//! };
//!
-//! let mut config = Config::new();
-//! config.async_support(true);
-//! let engine = Engine::new(&config)?;
+//! let engine = Engine::default();
//!
//! // Set up wasi-cli
//! let mut store = Store::new(&engine, ctx);
diff --git a/crates/wasi-tls/tests/main.rs b/crates/wasi-tls/tests/main.rs
index eb96d759a0..86ddee7f88 100644
--- a/crates/wasi-tls/tests/main.rs
+++ b/crates/wasi-tls/tests/main.rs
@@ -33,9 +33,7 @@ async fn run_test(path: &str) -> Result<()> {
wasi_tls_ctx: WasiTlsCtxBuilder::new().build(),
};
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut store = Store::new(&engine, ctx);
let component = Component::from_file(&engine, path)?;
diff --git a/crates/wasi/src/cli.rs b/crates/wasi/src/cli.rs
index 018e068d60..97db6acb11 100644
--- a/crates/wasi/src/cli.rs
+++ b/crates/wasi/src/cli.rs
@@ -34,7 +34,7 @@ pub use tokio::io::{Stderr, Stdin, Stdout, stderr, stdin, stdout};
///
/// ```
/// use wasmtime::component::{Linker, ResourceTable};
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime_wasi::cli::*;
///
/// struct MyStoreState {
@@ -43,9 +43,7 @@ pub use tokio::io::{Stderr, Stdin, Stdout, stderr, stdin, stdout};
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
/// let mut linker = Linker::new(&engine);
///
/// wasmtime_wasi::p2::bindings::cli::environment::add_to_linker::<MyStoreState, WasiCli>(
diff --git a/crates/wasi/src/clocks.rs b/crates/wasi/src/clocks.rs
index 27d729dc08..1ebc77ae81 100644
--- a/crates/wasi/src/clocks.rs
+++ b/crates/wasi/src/clocks.rs
@@ -19,7 +19,7 @@ use wasmtime::component::{HasData, ResourceTable};
///
/// ```
/// use wasmtime::component::{Linker, ResourceTable};
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime_wasi::clocks::*;
///
/// struct MyStoreState {
@@ -28,9 +28,7 @@ use wasmtime::component::{HasData, ResourceTable};
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
/// let mut linker = Linker::new(&engine);
///
/// wasmtime_wasi::p2::bindings::clocks::monotonic_clock::add_to_linker::<MyStoreState, WasiClocks>(
diff --git a/crates/wasi/src/ctx.rs b/crates/wasi/src/ctx.rs
index 3fa8d3c836..568e72f96e 100644
--- a/crates/wasi/src/ctx.rs
+++ b/crates/wasi/src/ctx.rs
@@ -147,12 +147,11 @@ impl WasiCtxBuilder {
/// on the host. This is currently done with Tokio's
/// [`spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html).
///
- /// When WebAssembly is used in a synchronous context, for example when
- /// [`Config::async_support`] is disabled, then this asynchronous operation
- /// is quickly turned back into a synchronous operation with a `block_on` in
- /// Rust. This switching back-and-forth between a blocking a non-blocking
- /// context can have overhead, and this option exists to help alleviate this
- /// overhead.
+ /// When WebAssembly is used in a synchronous context then this asynchronous
+ /// operation is quickly turned back into a synchronous operation with a
+ /// `block_on` in Rust. This switching back-and-forth between a blocking a
+ /// non-blocking context can have overhead, and this option exists to help
+ /// alleviate this overhead.
///
/// This option indicates that for WASI functions that are blocking from the
/// perspective of WebAssembly it's ok to block the native thread as well.
@@ -160,8 +159,6 @@ impl WasiCtxBuilder {
/// and instead blocking operations are performed on-thread (such as opening
/// a file). This can improve the performance of WASI operations when async
/// support is disabled.
- ///
- /// [`Config::async_support`]: https://docs.rs/wasmtime/latest/wasmtime/struct.Config.html#method.async_support
pub fn allow_blocking_current_thread(&mut self, enable: bool) -> &mut Self {
self.filesystem.allow_blocking_current_thread = enable;
self
diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rs
index 8b55b2cae6..c45abf5647 100644
--- a/crates/wasi/src/filesystem.rs
+++ b/crates/wasi/src/filesystem.rs
@@ -22,7 +22,7 @@ use wasmtime::error::Context as _;
///
/// ```
/// use wasmtime::component::{Linker, ResourceTable};
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime_wasi::filesystem::*;
///
/// struct MyStoreState {
@@ -31,9 +31,7 @@ use wasmtime::error::Context as _;
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
/// let mut linker = Linker::new(&engine);
///
/// wasmtime_wasi::p2::bindings::filesystem::types::add_to_linker::<MyStoreState, WasiFilesystem>(
diff --git a/crates/wasi/src/p1.rs b/crates/wasi/src/p1.rs
index cda806f4af..689947f497 100644
--- a/crates/wasi/src/p1.rs
+++ b/crates/wasi/src/p1.rs
@@ -12,8 +12,7 @@
//!
//! First a [`WasiCtxBuilder`] will be used and finalized with the [`build_p1`]
//! method to create a [`WasiCtx`]. Next a [`wasmtime::Linker`] is configured
-//! with WASI imports by using the `add_to_linker_*` desired (sync or async
-//! depending on [`Config::async_support`]).
+//! with WASI imports by using the `add_to_linker_*` desired (sync or async).
//!
//! Note that WASIp1 is not as extensible or configurable as WASIp2 so the
//! support in this module is enough to run wasm modules but any customization
@@ -21,7 +20,6 @@
//!
//! [`WasiCtxBuilder`]: crate::p2::WasiCtxBuilder
//! [`build_p1`]: crate::p2::WasiCtxBuilder::build_p1
-//! [`Config::async_support`]: wasmtime::Config::async_support
//!
//! # Components vs Modules
//!
@@ -662,11 +660,7 @@ enum FdWrite {
/// arg.field`) or something otherwise "small" as it will be executed every time
/// a WASI call is made.
///
-/// Note that this function is intended for use with
-/// [`Config::async_support(true)`]. If you're looking for a synchronous version
-/// see [`add_to_linker_sync`].
-///
-/// [`Config::async_support(true)`]: wasmtime::Config::async_support
+/// If you're looking for a synchronous version see [`add_to_linker_sync`].
///
/// # Examples
///
@@ -677,9 +671,7 @@ enum FdWrite {
/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
/// p1::add_to_linker_async(&mut linker, |cx| cx)?;
@@ -703,9 +695,7 @@ enum FdWrite {
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker: Linker<MyState> = Linker::new(&engine);
/// p1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
@@ -736,24 +726,18 @@ pub fn add_to_linker_async<T: Send + 'static>(
/// arg.field`) or something otherwise "small" as it will be executed every time
/// a WASI call is made.
///
-/// Note that this function is intended for use with
-/// [`Config::async_support(false)`]. If you're looking for a synchronous version
-/// see [`add_to_linker_async`].
-///
-/// [`Config::async_support(false)`]: wasmtime::Config::async_support
+/// If you're looking for a synchronous version see [`add_to_linker_async`].
///
/// # Examples
///
/// If the `T` in `Linker<T>` is just `WasiP1Ctx`:
///
/// ```no_run
-/// use wasmtime::{Result, Linker, Engine, Config};
+/// use wasmtime::{Result, Linker, Engine};
/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
/// p1::add_to_linker_async(&mut linker, |cx| cx)?;
@@ -767,7 +751,7 @@ pub fn add_to_linker_async<T: Send + 'static>(
/// If the `T` in `Linker<T>` is custom state:
///
/// ```no_run
-/// use wasmtime::{Result, Linker, Engine, Config};
+/// use wasmtime::{Result, Linker, Engine};
/// use wasmtime_wasi::p1::{self, WasiP1Ctx};
///
/// struct MyState {
@@ -777,9 +761,7 @@ pub fn add_to_linker_async<T: Send + 'static>(
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker: Linker<MyState> = Linker::new(&engine);
/// p1::add_to_linker_async(&mut linker, |cx| &mut cx.wasi)?;
diff --git a/crates/wasi/src/p2/bindings.rs b/crates/wasi/src/p2/bindings.rs
index e60c7818f1..db60468b28 100644
--- a/crates/wasi/src/p2/bindings.rs
+++ b/crates/wasi/src/p2/bindings.rs
@@ -16,7 +16,7 @@
//!
//! ```rust
//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
-//! use wasmtime::{Result, Engine, Config};
+//! use wasmtime::{Result, Engine};
//! use wasmtime::component::{Linker, ResourceTable, HasSelf};
//!
//! wasmtime::component::bindgen!({
@@ -60,9 +60,7 @@
//! }
//!
//! fn main() -> Result<()> {
-//! let mut config = Config::default();
-//! config.async_support(true);
-//! let engine = Engine::new(&config)?;
+//! let engine = Engine::default();
//! let mut linker: Linker<MyState> = Linker::new(&engine);
//! wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
//! example::wasi::custom_host::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)?;
@@ -192,15 +190,13 @@ pub mod sync {
/// Synchronous bindings to execute and run a `wasi:cli/command`.
///
- /// This structure is automatically generated by `bindgen!` and is intended
- /// to be used with [`Config::async_support(false)`][async]. For the
+ /// This structure is automatically generated by `bindgen!`. For the
/// asynchronous version see [`bindings::Command`](super::Command).
///
/// This can be used for a more "typed" view of executing a command
/// component through the [`Command::wasi_cli_run`] method plus
/// [`Guest::call_run`](exports::wasi::cli::run::Guest::call_run).
///
- /// [async]: wasmtime::Config::async_support
/// [`wasmtime_wasi::p2::add_to_linker_sync`]: crate::p2::add_to_linker_sync
///
/// # Examples
@@ -412,15 +408,13 @@ pub use self::async_io::wasi::*;
/// Asynchronous bindings to execute and run a `wasi:cli/command`.
///
-/// This structure is automatically generated by `bindgen!` and is intended to
-/// be used with [`Config::async_support(true)`][async]. For the synchronous
+/// This structure is automatically generated by `bindgen!`. For the synchronous
/// version see [`bindings::sync::Command`](sync::Command).
///
/// This can be used for a more "typed" view of executing a command component
/// through the [`Command::wasi_cli_run`] method plus
/// [`Guest::call_run`](exports::wasi::cli::run::Guest::call_run).
///
-/// [async]: wasmtime::Config::async_support
/// [`wasmtime_wasi::p2::add_to_linker_async`]: crate::p2::add_to_linker_async
///
/// # Examples
@@ -438,9 +432,7 @@ pub use self::async_io::wasi::*;
/// let args = std::env::args().skip(1).collect::<Vec<_>>();
///
/// // Configure and create `Engine`
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// // Configure a `Linker` with WASI, compile a component based on
/// // command line arguments, and then pre-instantiate it.
@@ -493,7 +485,7 @@ pub use self::async_io::Command;
/// # Examples
///
/// ```no_run
-/// use wasmtime::{Engine, Result, Store, Config};
+/// use wasmtime::{Engine, Result, Store};
/// use wasmtime::component::{ResourceTable, Linker, Component};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
/// use wasmtime_wasi::p2::bindings::CommandPre;
@@ -505,9 +497,7 @@ pub use self::async_io::Command;
/// let args = std::env::args().skip(1).collect::<Vec<_>>();
///
/// // Configure and create `Engine`
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// // Configure a `Linker` with WASI, compile a component based on
/// // command line arguments, and then pre-instantiate it.
diff --git a/crates/wasi/src/p2/mod.rs b/crates/wasi/src/p2/mod.rs
index a11b3c8304..5685054a26 100644
--- a/crates/wasi/src/p2/mod.rs
+++ b/crates/wasi/src/p2/mod.rs
@@ -113,21 +113,19 @@
//!
//! # Async and Sync
//!
-//! As of WASI0.2, WASI functions are not blocking from WebAssembly's point of
-//! view: a WebAssembly call into these functions returns when they are
-//! complete.
+//! All WASIp2 functions are blocking from WebAssembly's point of view: a
+//! WebAssembly call into these functions returns only when they are complete.
//!
-//! This module provides an implementation of those functions in the host,
-//! where for some functions, it is appropriate to implement them using
-//! async Rust and the Tokio executor, so that the host implementation can be
-//! nonblocking when Wasmtime's [`Config::async_support`][async] is set.
-//! Synchronous wrappers are provided for all async implementations, which
-//! creates a private Tokio executor.
+//! This module provides an implementation of those functions in the host, where
+//! for some functions, it is appropriate to implement them using async Rust and
+//! the Tokio executor. The host implementation still blocks WebAssembly, but it
+//! does not block the host's thread. Synchronous wrappers are also provided for
+//! all async implementations, which create a private Tokio executor.
//!
//! Users can choose between these modes of implementation using variants
//! of the add_to_linker functions:
//!
-//! * For non-async users (the default of `Config`), use [`add_to_linker_sync`].
+//! * For non-async users, use [`add_to_linker_sync`].
//! * For async users, use [`add_to_linker_async`].
//!
//! Note that bindings are generated once for async and once for sync. Most
@@ -218,7 +216,6 @@
//! [`wasi:sockets/tcp`]: bindings::sockets::tcp::Host
//! [`wasi:sockets/udp-create-socket`]: bindings::sockets::udp_create_socket::Host
//! [`wasi:sockets/udp`]: bindings::sockets::udp::Host
-//! [async]: https://docs.rs/wasmtime/latest/wasmtime/struct.Config.html#method.async_support
//! [`ResourceTable`]: wasmtime::component::ResourceTable
use crate::WasiView;
@@ -257,16 +254,13 @@ pub use wasmtime_wasi_io::streams::{
/// Add all WASI interfaces from this crate into the `linker` provided.
///
/// This function will add the `async` variant of all interfaces into the
-/// [`Linker`] provided. By `async` this means that this function is only
-/// compatible with [`Config::async_support(true)`][async]. For embeddings with
-/// async support disabled see [`add_to_linker_sync`] instead.
+/// [`Linker`] provided. For embeddings with async support disabled see
+/// [`add_to_linker_sync`] instead.
///
/// This function will add all interfaces implemented by this crate to the
/// [`Linker`], which corresponds to the `wasi:cli/imports` world supported by
/// this crate.
///
-/// [async]: wasmtime::Config::async_support
-///
/// # Example
///
/// ```
@@ -275,9 +269,7 @@ pub use wasmtime_wasi_io::streams::{
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
@@ -402,16 +394,13 @@ fn add_proxy_interfaces_nonblocking<T: WasiView>(linker: &mut Linker<T>) -> wasm
/// Add all WASI interfaces from this crate into the `linker` provided.
///
/// This function will add the synchronous variant of all interfaces into the
-/// [`Linker`] provided. By synchronous this means that this function is only
-/// compatible with [`Config::async_support(false)`][async]. For embeddings
-/// with async support enabled see [`add_to_linker_async`] instead.
+/// [`Linker`] provided. For embeddings with async support enabled see
+/// [`add_to_linker_async`] instead.
///
/// This function will add all interfaces implemented by this crate to the
/// [`Linker`], which corresponds to the `wasi:cli/imports` world supported by
/// this crate.
///
-/// [async]: wasmtime::Config::async_support
-///
/// # Example
///
/// ```
diff --git a/crates/wasi/src/p3/bindings.rs b/crates/wasi/src/p3/bindings.rs
index 2e23917377..f847af9fda 100644
--- a/crates/wasi/src/p3/bindings.rs
+++ b/crates/wasi/src/p3/bindings.rs
@@ -61,7 +61,6 @@
//!
//! fn main() -> Result<()> {
//! let mut config = Config::default();
-//! config.async_support(true);
//! config.wasm_component_model_async(true);
//! let engine = Engine::new(&config)?;
//! let mut linker: Linker<MyState> = Linker::new(&engine);
@@ -132,7 +131,6 @@ pub use self::generated::wasi::*;
///
/// // Configure and create `Engine`
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
@@ -205,7 +203,6 @@ pub use self::generated::Command;
///
/// // Configure and create `Engine`
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/p3/cli/mod.rs b/crates/wasi/src/p3/cli/mod.rs
index fb8230d364..5e96b919dd 100644
--- a/crates/wasi/src/p3/cli/mod.rs
+++ b/crates/wasi/src/p3/cli/mod.rs
@@ -26,7 +26,6 @@ use wasmtime::component::Linker;
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/p3/clocks/mod.rs b/crates/wasi/src/p3/clocks/mod.rs
index 4cde6e9f71..5a0298fd78 100644
--- a/crates/wasi/src/p3/clocks/mod.rs
+++ b/crates/wasi/src/p3/clocks/mod.rs
@@ -23,7 +23,6 @@ use wasmtime::component::Linker;
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/p3/filesystem/mod.rs b/crates/wasi/src/p3/filesystem/mod.rs
index 0908e5727d..9977d67704 100644
--- a/crates/wasi/src/p3/filesystem/mod.rs
+++ b/crates/wasi/src/p3/filesystem/mod.rs
@@ -27,7 +27,6 @@ pub type FilesystemError = TrappableError<types::ErrorCode>;
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/p3/mod.rs b/crates/wasi/src/p3/mod.rs
index 5e5fac2d65..ecbb31a6e0 100644
--- a/crates/wasi/src/p3/mod.rs
+++ b/crates/wasi/src/p3/mod.rs
@@ -135,7 +135,6 @@ impl<I, E> Drop for FallibleIteratorProducer<I, E> {
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/p3/random/mod.rs b/crates/wasi/src/p3/random/mod.rs
index fe9dbb8153..2ac7338422 100644
--- a/crates/wasi/src/p3/random/mod.rs
+++ b/crates/wasi/src/p3/random/mod.rs
@@ -18,14 +18,12 @@ use wasmtime::component::Linker;
/// # Example
///
/// ```
-/// use wasmtime::{Engine, Result, Store, Config};
+/// use wasmtime::{Engine, Result, Store};
/// use wasmtime::component::Linker;
/// use wasmtime_wasi::random::{WasiRandomView, WasiRandomCtx};
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
///
/// let mut linker = Linker::<MyState>::new(&engine);
/// wasmtime_wasi::p3::random::add_to_linker(&mut linker)?;
diff --git a/crates/wasi/src/p3/sockets/mod.rs b/crates/wasi/src/p3/sockets/mod.rs
index 3577e29c97..d490ec2dec 100644
--- a/crates/wasi/src/p3/sockets/mod.rs
+++ b/crates/wasi/src/p3/sockets/mod.rs
@@ -28,7 +28,6 @@ pub type SocketError = TrappableError<types::ErrorCode>;
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
-/// config.async_support(true);
/// config.wasm_component_model_async(true);
/// let engine = Engine::new(&config)?;
///
diff --git a/crates/wasi/src/random.rs b/crates/wasi/src/random.rs
index 16292352dc..0e6337a9c3 100644
--- a/crates/wasi/src/random.rs
+++ b/crates/wasi/src/random.rs
@@ -15,7 +15,7 @@ use wasmtime::component::HasData;
///
/// ```
/// use wasmtime::component::Linker;
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime_wasi::random::*;
///
/// struct MyStoreState {
@@ -23,9 +23,7 @@ use wasmtime::component::HasData;
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
/// let mut linker = Linker::new(&engine);
///
/// wasmtime_wasi::p2::bindings::random::random::add_to_linker::<MyStoreState, WasiRandom>(
diff --git a/crates/wasi/src/sockets/mod.rs b/crates/wasi/src/sockets/mod.rs
index f7e0686647..55572c2acd 100644
--- a/crates/wasi/src/sockets/mod.rs
+++ b/crates/wasi/src/sockets/mod.rs
@@ -28,7 +28,7 @@ pub use udp::UdpSocket;
///
/// ```
/// use wasmtime::component::{Linker, ResourceTable};
-/// use wasmtime::{Engine, Result, Config};
+/// use wasmtime::{Engine, Result};
/// use wasmtime_wasi::sockets::*;
///
/// struct MyStoreState {
@@ -37,9 +37,7 @@ pub use udp::UdpSocket;
/// }
///
/// fn main() -> Result<()> {
-/// let mut config = Config::new();
-/// config.async_support(true);
-/// let engine = Engine::new(&config)?;
+/// let engine = Engine::default();
/// let mut linker = Linker::new(&engine);
///
/// wasmtime_wasi::p2::bindings::sockets::tcp::add_to_linker::<MyStoreState, WasiSockets>(
diff --git a/crates/wasi/tests/all/p1.rs b/crates/wasi/tests/all/p1.rs
index 04cf2a3bc7..ccf4c5a76f 100644
--- a/crates/wasi/tests/all/p1.rs
+++ b/crates/wasi/tests/all/p1.rs
@@ -8,9 +8,7 @@ use wasmtime_wasi::p1::{WasiP1Ctx, add_to_linker_async};
async fn run(path: &str, inherit_stdio: bool) -> Result<()> {
let path = Path::new(path);
let name = path.file_stem().unwrap().to_str().unwrap();
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut linker = Linker::<Ctx<WasiP1Ctx>>::new(&engine);
add_to_linker_async(&mut linker, |t| &mut t.wasi)?;
diff --git a/crates/wasi/tests/all/p2/api.rs b/crates/wasi/tests/all/p2/api.rs
index cf3da0fabb..415ce250d6 100644
--- a/crates/wasi/tests/all/p2/api.rs
+++ b/crates/wasi/tests/all/p2/api.rs
@@ -30,9 +30,7 @@ use test_programs_artifacts::*;
foreach_p2_api!(assert_test_exists);
async fn instantiate(path: &str, ctx: CommandCtx) -> Result<(Store<CommandCtx>, Command)> {
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut linker = Linker::new(&engine);
add_to_linker_async(&mut linker)?;
@@ -145,9 +143,7 @@ wasmtime::component::bindgen!({
async fn p2_api_reactor() -> Result<()> {
let table = ResourceTable::new();
let wasi = WasiCtxBuilder::new().env("GOOD_DOG", "gussie").build();
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut linker = Linker::new(&engine);
add_to_linker_async(&mut linker)?;
diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rs
index 0e1ec3833f..c24ab17517 100644
--- a/crates/wasi/tests/all/p2/async_.rs
+++ b/crates/wasi/tests/all/p2/async_.rs
@@ -9,9 +9,7 @@ use wasmtime_wasi::p2::bindings::Command;
async fn run(path: &str, inherit_stdio: bool) -> Result<()> {
let path = Path::new(path);
let name = path.file_stem().unwrap().to_str().unwrap();
- let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
- });
+ let engine = test_programs_artifacts::engine(|_config| {});
let mut linker = Linker::new(&engine);
add_to_linker_async(&mut linker)?;
diff --git a/crates/wasi/tests/all/p3/mod.rs b/crates/wasi/tests/all/p3/mod.rs
index b6cd01e7a5..37bef7869f 100644
--- a/crates/wasi/tests/all/p3/mod.rs
+++ b/crates/wasi/tests/all/p3/mod.rs
@@ -16,7 +16,6 @@ async fn run_allow_blocking_current_thread(
let path = Path::new(path);
let name = path.file_stem().unwrap().to_str().unwrap();
let engine = test_programs_artifacts::engine(|config| {
- config.async_support(true);
config.wasm_component_model_async(true);
});
let mut linker = Linker::new(&engine);
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index 435c4333ba..8998bac2b3 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -153,7 +153,6 @@ pub struct Config {
pub(crate) async_stack_zeroing: bool,
#[cfg(feature = "async")]
pub(crate) stack_creator: Option<Arc<dyn RuntimeFiberStackCreator>>,
- pub(crate) async_support: bool,
pub(crate) module_version: ModuleVersionStrategy,
pub(crate) parallel_compilation: bool,
pub(crate) memory_guaranteed_dense_image_size: u64,
@@ -260,7 +259,6 @@ impl Config {
async_stack_zeroing: false,
#[cfg(feature = "async")]
stack_creator: None,
- async_support: false,
module_version: ModuleVersionStrategy::default(),
parallel_compilation: !cfg!(miri),
memory_guaranteed_dense_image_size: 16 << 20,
@@ -382,100 +380,10 @@ impl Config {
Ok(self)
}
- /// Whether or not to enable support for asynchronous functions in Wasmtime.
- ///
- /// When enabled, the config can optionally define host functions with `async`.
- /// Instances created and functions called with this `Config` *must* be called
- /// through their asynchronous APIs, however. For example using
- /// [`Func::call`](crate::Func::call) will panic when used with this config.
- ///
- /// # Asynchronous Wasm
- ///
- /// WebAssembly does not currently have a way to specify at the bytecode
- /// level what is and isn't async. Host-defined functions, however, may be
- /// defined as `async`. WebAssembly imports always appear synchronous, which
- /// gives rise to a bit of an impedance mismatch here. To solve this
- /// Wasmtime supports "asynchronous configs" which enables calling these
- /// asynchronous functions in a way that looks synchronous to the executing
- /// WebAssembly code.
- ///
- /// An asynchronous config must always invoke wasm code asynchronously,
- /// meaning we'll always represent its computation as a
- /// [`Future`](std::future::Future). The `poll` method of the futures
- /// returned by Wasmtime will perform the actual work of calling the
- /// WebAssembly. Wasmtime won't manage its own thread pools or similar,
- /// that's left up to the embedder.
- ///
- /// To implement futures in a way that WebAssembly sees asynchronous host
- /// functions as synchronous, all async Wasmtime futures will execute on a
- /// separately allocated native stack from the thread otherwise executing
- /// Wasmtime. This separate native stack can then be switched to and from.
- /// Using this whenever an `async` host function returns a future that
- /// resolves to `Pending` we switch away from the temporary stack back to
- /// the main stack and propagate the `Pending` status.
- ///
- /// In general it's encouraged that the integration with `async` and
- /// wasmtime is designed early on in your embedding of Wasmtime to ensure
- /// that it's planned that WebAssembly executes in the right context of your
- /// application.
- ///
- /// # Execution in `poll`
- ///
- /// The [`Future::poll`](std::future::Future::poll) method is the main
- /// driving force behind Rust's futures. That method's own documentation
- /// states "an implementation of `poll` should strive to return quickly, and
- /// should not block". This, however, can be at odds with executing
- /// WebAssembly code as part of the `poll` method itself. If your
- /// WebAssembly is untrusted then this could allow the `poll` method to take
- /// arbitrarily long in the worst case, likely blocking all other
- /// asynchronous tasks.
- ///
- /// To remedy this situation you have a few possible ways to solve this:
- ///
- /// * The most efficient solution is to enable
- /// [`Config::epoch_interruption`] in conjunction with
- /// [`crate::Store::epoch_deadline_async_yield_and_update`]. Coupled with
- /// periodic calls to [`crate::Engine::increment_epoch`] this will cause
- /// executing WebAssembly to periodically yield back according to the
- /// epoch configuration settings. This enables `Future::poll` to take at
- /// most a certain amount of time according to epoch configuration
- /// settings and when increments happen. The benefit of this approach is
- /// that the instrumentation in compiled code is quite lightweight, but a
- /// downside can be that the scheduling is somewhat nondeterministic since
- /// increments are usually timer-based which are not always deterministic.
- ///
- /// Note that to prevent infinite execution of wasm it's recommended to
- /// place a timeout on the entire future representing executing wasm code
- /// and the periodic yields with epochs should ensure that when the
- /// timeout is reached it's appropriately recognized.
- ///
- /// * Alternatively you can enable the
- /// [`Config::consume_fuel`](crate::Config::consume_fuel) method as well
- /// as [`crate::Store::fuel_async_yield_interval`] When doing so this will
- /// configure Wasmtime futures to yield periodically while they're
- /// executing WebAssembly code. After consuming the specified amount of
- /// fuel wasm futures will return `Poll::Pending` from their `poll`
- /// method, and will get automatically re-polled later. This enables the
- /// `Future::poll` method to take roughly a fixed amount of time since
- /// fuel is guaranteed to get consumed while wasm is executing. Unlike
- /// epoch-based preemption this is deterministic since wasm always
- /// consumes a fixed amount of fuel per-operation. The downside of this
- /// approach, however, is that the compiled code instrumentation is
- /// significantly more expensive than epoch checks.
- ///
- /// Note that to prevent infinite execution of wasm it's recommended to
- /// place a timeout on the entire future representing executing wasm code
- /// and the periodic yields with epochs should ensure that when the
- /// timeout is reached it's appropriately recognized.
- ///
- /// In all cases special care needs to be taken when integrating
- /// asynchronous wasm into your application. You should carefully plan where
- /// WebAssembly will execute and what compute resources will be allotted to
- /// it. If Wasmtime doesn't support exactly what you'd like just yet, please
- /// feel free to open an issue!
+ #[doc(hidden)]
+ #[deprecated(note = "no longer has any effect")]
#[cfg(feature = "async")]
- pub fn async_support(&mut self, enable: bool) -> &mut Self {
- self.async_support = enable;
+ pub fn async_support(&mut self, _enable: bool) -> &mut Self {
self
}
@@ -543,11 +451,12 @@ impl Config {
/// suitable in concurrent environments since one thread capturing a
/// backtrace won't block other threads.
///
- /// Collected backtraces are attached via [`wasmtime::Error::context`] to
- /// errors returned from host functions. The [`WasmBacktrace`] type can be
- /// acquired via [`wasmtime::Error::downcast_ref`] to inspect the backtrace.
- /// When this option is disabled then this context is never applied to
- /// errors coming out of wasm.
+ /// Collected backtraces are attached via
+ /// [`Error::context`](crate::Error::context) to errors returned from host
+ /// functions. The [`WasmBacktrace`] type can be acquired via
+ /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the
+ /// backtrace. When this option is disabled then this context is never
+ /// applied to errors coming out of wasm.
///
/// This option is `true` by default.
///
@@ -715,13 +624,12 @@ impl Config {
/// itself and it's left to the embedder to determine how best to wake up
/// indefinitely blocking code in the host.
///
- /// The typical solution for this, however, is to use
- /// [`Config::async_support(true)`](Config::async_support) and the `async`
- /// variant of WASI host functions. This models computation as a Rust
- /// `Future` which means that when blocking happens the future is only
- /// suspended and control yields back to the main event loop. This gives the
- /// embedder the opportunity to use `tokio::time::timeout` for example on a
- /// wasm computation and have the desired effect of cancelling a blocking
+ /// The typical solution for this, however, is to use the `async` variant of
+ /// WASI host functions. This models computation as a Rust `Future` which
+ /// means that when blocking happens the future is only suspended and
+ /// control yields back to the main event loop. This gives the embedder the
+ /// opportunity to use `tokio::time::timeout` for example on a wasm
+ /// computation and have the desired effect of cancelling a blocking
/// operation when a timeout expires.
///
/// ## When to use fuel vs. epochs
@@ -831,8 +739,7 @@ impl Config {
/// Configures whether or not stacks used for async futures are zeroed
/// before (re)use.
///
- /// When the [`async_support`](Config::async_support) method is enabled for
- /// Wasmtime and the [`call_async`] variant of calling WebAssembly is used
+ /// When the [`call_async`] variant of calling WebAssembly is used
/// then Wasmtime will create a separate runtime execution stack for each
/// future produced by [`call_async`]. By default upon allocation, depending
/// on the platform, these stacks might be filled with uninitialized
@@ -871,8 +778,9 @@ impl Config {
/// supports.
///
/// Feature validation is deferred until an engine is being built, thus by
- /// enabling features here a caller may cause [`Engine::new`] to fail later,
- /// if the feature configuration isn't supported.
+ /// enabling features here a caller may cause
+ /// [`Engine::new`](crate::Engine::new) to fail later, if the feature
+ /// configuration isn't supported.
pub fn wasm_features(&mut self, flag: WasmFeatures, enable: bool) -> &mut Self {
self.enabled_features.set(flag, enable);
self.disabled_features.set(flag, !enable);
@@ -2137,7 +2045,7 @@ impl Config {
}
/// Configures whether or not a coredump should be generated and attached to
- /// the [`wasmtime::Error`] when a trap is raised.
+ /// the [`Error`](crate::Error) when a trap is raised.
///
/// This option is disabled by default.
#[cfg(feature = "coredump")]
@@ -2430,7 +2338,7 @@ impl Config {
}
#[cfg(any(feature = "async", feature = "stack-switching"))]
- if self.async_support && self.max_wasm_stack > self.async_stack_size {
+ if self.max_wasm_stack > self.async_stack_size {
bail!("max_wasm_stack size cannot exceed the async_stack_size");
}
if self.max_wasm_stack == 0 {
@@ -3085,7 +2993,7 @@ pub enum Strategy {
/// A low-latency baseline compiler for WebAssembly.
/// For more details regarding ISA support and Wasm proposals support
- /// see https://docs.wasmtime.dev/stability-tiers.html#current-tier-status
+ /// see <https://docs.wasmtime.dev/stability-tiers.html#current-tier-status>
Winch,
}
diff --git a/crates/wasmtime/src/engine.rs b/crates/wasmtime/src/engine.rs
index b2b1ef42f3..8b155791cf 100644
--- a/crates/wasmtime/src/engine.rs
+++ b/crates/wasmtime/src/engine.rs
@@ -251,13 +251,6 @@ impl Engine {
Arc::ptr_eq(&a.inner, &b.inner)
}
- /// Returns whether the engine is configured to support async functions.
- #[cfg(feature = "async")]
- #[inline]
- pub fn is_async(&self) -> bool {
- self.config().async_support
- }
-
/// Detects whether the bytes provided are a precompiled object produced by
/// Wasmtime.
///
diff --git a/crates/wasmtime/src/lib.rs b/crates/wasmtime/src/lib.rs
index 20dea9a1f6..3eaa8fddaf 100644
--- a/crates/wasmtime/src/lib.rs
+++ b/crates/wasmtime/src/lib.rs
@@ -176,6 +176,106 @@
//!
//! [`wasmtime-wasi`]: https://crates.io/crates/wasmtime-wasi
//!
+//! ## Async
+//!
+//! Wasmtime supports executing WebAssembly guests through Rust-level `async`
+//! functions. This enables Wasmtime to block the guest without blocking the
+//! host, interrupt infinite loops or long-running CPU-bound guests, and
+//! integrate with Rust host functions that are themselves `async`.
+//!
+//! Many functions in the embedding API have a sync variant and an async
+//! variant, for example [`Func::call`] and [`Func::call_async`]. Embedders
+//! may decide which is most appropriate for their use case, but if certain
+//! features of Wasmtime are configured then `*_async` variants of functions are
+//! required. If any of these features are used, for example, then `*_async`
+//! must be used:
+//!
+//! * Async core wasm host functions, for example via [`Linker::func_wrap_async`]
+//! * Async component host functions, for example via [`component::LinkerInstance::func_wrap_async`]
+//! * Async resource limiters, via [`Store::limiter_async`]
+//! * Async yields with fuel via [`Store::fuel_async_yield_interval`]
+//! * Async yields via epochs via [`Store::epoch_deadline_async_yield_and_update`]
+//!
+//! This is not an exhaustive list, but if any of these configurations/APIs are
+//! used then all `*_async` APIs must be used in Wasmtime. If synchronous APIs
+//! are used instead they will return an error.
+//!
+//! #### Asynchronous Wasm
+//!
+//! Core WebAssembly and synchronous WIT functions (e.g. WASIp2-and-prior)
+//! require that all imported functions appear synchronous from the perspective
+//! of the guest. Host functions which perform I/O and block, however, are often
+//! defined with `async` in Rust. Wasmtime's async support bridges this gap with
+//! asynchronous wasm execution.
+//!
+//! When using `*_async` APIs to execute WebAssembly Wasmtime will always
+//! represent its computation as a [`Future`]. The `poll` method of the futures
+//! returned by Wasmtime will perform the actual work of calling the
+//! WebAssembly. Wasmtime won't manage its own thread pools or similar, that's
+//! left up to the embedder.
+//!
+//! To implement futures in a way that WebAssembly sees asynchronous host
+//! functions as synchronous, all async Wasmtime futures will execute on a
+//! separately allocated native stack from the thread otherwise executing
+//! Wasmtime. This separate native stack can then be switched to and from.
+//! Using this whenever an `async` host function returns a future that
+//! resolves to `Pending` we switch away from the temporary stack back to
+//! the main stack and propagate the `Pending` status.
+//!
+//! #### Execution in `poll`
+//!
+//! The [`Future::poll`] method is the main driving force behind Rust's futures.
+//! That method's own documentation states "an implementation of `poll` should
+//! strive to return quickly, and should not block". This, however, can be at
+//! odds with executing WebAssembly code as part of the `poll` method itself. If
+//! your WebAssembly is untrusted then this could allow the `poll` method to
+//! take arbitrarily long in the worst case, likely blocking all other
+//! asynchronous tasks.
+//!
+//! To remedy this situation you have a few possible ways to solve this:
+//!
+//! * The most efficient solution is to enable
+//! [`Config::epoch_interruption`] in conjunction with
+//! [`crate::Store::epoch_deadline_async_yield_and_update`]. Coupled with
+//! periodic calls to [`crate::Engine::increment_epoch`] this will cause
+//! executing WebAssembly to periodically yield back according to the
+//! epoch configuration settings. This enables [`Future::poll`] to take at
+//! most a certain amount of time according to epoch configuration
+//! settings and when increments happen. The benefit of this approach is
+//! that the instrumentation in compiled code is quite lightweight, but a
+//! downside can be that the scheduling is somewhat nondeterministic since
+//! increments are usually timer-based which are not always deterministic.
+//!
+//! Note that to prevent infinite execution of wasm it's recommended to
+//! place a timeout on the entire future representing executing wasm code
+//! and the periodic yields with epochs should ensure that when the
+//! timeout is reached it's appropriately recognized.
+//!
+//! * Alternatively you can enable the
+//! [`Config::consume_fuel`](crate::Config::consume_fuel) method as well
+//! as [`crate::Store::fuel_async_yield_interval`] When doing so this will
+//! configure Wasmtime futures to yield periodically while they're
+//! executing WebAssembly code. After consuming the specified amount of
+//! fuel wasm futures will return `Poll::Pending` from their `poll`
+//! method, and will get automatically re-polled later. This enables the
+//! `Future::poll` method to take roughly a fixed amount of time since
+//! fuel is guaranteed to get consumed while wasm is executing. Unlike
+//! epoch-based preemption this is deterministic since wasm always
+//! consumes a fixed amount of fuel per-operation. The downside of this
+//! approach, however, is that the compiled code instrumentation is
+//! significantly more expensive than epoch checks.
+//!
+//! Note that to prevent infinite execution of wasm it's recommended to
+//! place a timeout on the entire future representing executing wasm code
+//! and the periodic yields with epochs should ensure that when the
+//! timeout is reached it's appropriately recognized.
+//!
+//! In all cases special care needs to be taken when integrating
+//! asynchronous wasm into your application. You should carefully plan where
+//! WebAssembly will execute and what compute resources will be allotted to
+//! it. If Wasmtime doesn't support exactly what you'd like just yet, please
+//! feel free to open an issue!
+//!
//! ## Crate Features
//!
//! The `wasmtime` crate comes with a number of compile-time features that can
@@ -208,7 +308,7 @@
//!
//! * `async` - Enabled by default, this feature enables APIs and runtime
//! support for defining asynchronous host functions and calling WebAssembly
-//! asynchronously. For more information see [`Config::async_support`].
+//! asynchronously. For more information see [async documentation](#async)
//!
//! * `profiling` - Enabled by default, this feature compiles in support for
//! profiling guest code via a number of possible strategies. See
diff --git a/crates/wasmtime/src/runtime/component/func.rs b/crates/wasmtime/src/runtime/component/func.rs
index 817c18686c..eca12988d9 100644
--- a/crates/wasmtime/src/runtime/component/func.rs
+++ b/crates/wasmtime/src/runtime/component/func.rs
@@ -220,15 +220,15 @@ impl Func {
/// * `results` is not the right size
/// * A trap occurs while executing the function
/// * The function calls a host function which returns an error
+ /// * The `store` used requires the use of [`Func::call_async`] instead. See
+ /// [store documentation](crate#async) for more information.
///
/// See [`TypedFunc::call`] for more information in addition to
/// [`wasmtime::Func::call`](crate::Func::call).
///
/// # Panics
///
- /// Panics if this is called on a function in an asynchronous store. This
- /// only works with functions defined within a synchronous store. Also
- /// panics if `store` does not own this function.
+ /// Panics if `store` does not own this function.
pub fn call(
&self,
mut store: impl AsContextMut,
@@ -236,10 +236,7 @@ impl Func {
results: &mut [Val],
) -> Result<()> {
let mut store = store.as_context_mut();
- assert!(
- !store.0.async_support(),
- "must use `call_async` when async support is enabled on the config"
- );
+ store.0.validate_sync_call()?;
self.call_impl(&mut store.as_context_mut(), params, results)
}
@@ -250,9 +247,7 @@ impl Func {
///
/// # Panics
///
- /// Panics if this is called on a function in a synchronous store. This
- /// only works with functions defined within an asynchronous store. Also
- /// panics if `store` does not own this function.
+ /// Panics if `store` does not own this function.
#[cfg(feature = "async")]
pub async fn call_async(
&self,
@@ -273,10 +268,6 @@ impl Func {
.await?;
}
- assert!(
- store.0.async_support(),
- "cannot use `call_async` without enabling async support in the config"
- );
let mut store = store;
store
.on_fiber(|store| self.call_impl(store, params, results))
@@ -422,10 +413,6 @@ impl Func {
call_post_return_automatically: bool,
) -> Result<TaskExit> {
let result = accessor.as_accessor().with(|mut store| {
- assert!(
- store.as_context_mut().0.async_support(),
- "cannot use `call_concurrent` when async support is not enabled on the config"
- );
self.check_params_results(store.as_context_mut(), params, results)?;
let prepared = self.prepare_call_dynamic(
store.as_context_mut(),
@@ -728,32 +715,18 @@ impl Func {
/// called, then it will panic. If a different [`Func`] for the same
/// component instance was invoked then this function will also panic
/// because the `post-return` needs to happen for the other function.
- ///
- /// Panics if this is called on a function in an asynchronous store.
- /// This only works with functions defined within a synchronous store.
#[inline]
pub fn post_return(&self, mut store: impl AsContextMut) -> Result<()> {
let store = store.as_context_mut();
- assert!(
- !store.0.async_support(),
- "must use `post_return_async` when async support is enabled on the config"
- );
+ store.0.validate_sync_call()?;
self.post_return_impl(store)
}
- /// Exactly like [`Self::post_return`] except for use on async stores.
- ///
- /// # Panics
- ///
- /// Panics if this is called on a function in a synchronous store. This
- /// only works with functions defined within an asynchronous store.
+ /// Exactly like [`Self::post_return`] except for invoke WebAssembly
+ /// [asynchronously](crate::#async).
#[cfg(feature = "async")]
pub async fn post_return_async(&self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
let mut store = store.as_context_mut();
- assert!(
- store.0.async_support(),
- "cannot use `post_return_async` without enabling async support in the config"
- );
// Future optimization opportunity: conditionally use a fiber here since
// some func's post_return will not need the async context (i.e. end up
// calling async host functionality)
diff --git a/crates/wasmtime/src/runtime/component/func/host.rs b/crates/wasmtime/src/runtime/component/func/host.rs
index 29de061653..8a05da3705 100644
--- a/crates/wasmtime/src/runtime/component/func/host.rs
+++ b/crates/wasmtime/src/runtime/component/func/host.rs
@@ -16,11 +16,12 @@ use crate::runtime::vm::component::{
ComponentInstance, VMComponentContext, VMLowering, VMLoweringCallee,
};
use crate::runtime::vm::{VMOpaqueContext, VMStore};
+use crate::store::Asyncness;
use crate::{AsContextMut, CallHook, StoreContextMut, ValRaw};
use alloc::sync::Arc;
use core::any::Any;
use core::mem::{self, MaybeUninit};
-#[cfg(feature = "component-model-async")]
+#[cfg(feature = "async")]
use core::pin::Pin;
use core::ptr::NonNull;
use wasmtime_environ::component::{
@@ -50,6 +51,10 @@ pub struct HostFunc {
/// type is a zero-sized-type. Host functions are allowed, though, to close
/// over the environment as well.
func: Box<dyn Any + Send + Sync>,
+
+ /// Whether or not this host function was defined in such a way that async
+ /// stack switching is required when calling it.
+ asyncness: Asyncness,
}
impl core::fmt::Debug for HostFunc {
@@ -65,7 +70,15 @@ enum HostResult<T> {
}
impl HostFunc {
- fn new<T, F, P, R>(func: F) -> Arc<HostFunc>
+ /// Creates a new host function based on the implementation of `func`.
+ ///
+ /// The `asyncness` parameter indicates whether the `func` requires
+ /// wasm to be on a fiber. This is used to propagate to the `Store` during
+ /// instantiation to ensure that this guarantee is met.
+ ///
+ /// Note that if `asyncness` is mistaken then that'll result in panics
+ /// in Wasmtime, but not memory unsafety.
+ fn new<T, F, P, R>(asyncness: Asyncness, func: F) -> Arc<HostFunc>
where
T: 'static,
R: Send + Sync + 'static,
@@ -75,27 +88,53 @@ impl HostFunc {
entrypoint: F::cabi_entrypoint,
typecheck: F::typecheck,
func: Box::new(func),
+ asyncness,
})
}
- /// Creates a new, statically typed, synchronous, host function from the
- /// `func` provided.
- pub(crate) fn from_closure<T, F, P, R>(func: F) -> Arc<HostFunc>
+ /// Equivalent for `Linker::func_wrap`
+ pub(crate) fn func_wrap<T, F, P, R>(func: F) -> Arc<HostFunc>
where
T: 'static,
F: Fn(StoreContextMut<T>, P) -> Result<R> + Send + Sync + 'static,
P: ComponentNamedList + Lift + 'static,
R: ComponentNamedList + Lower + 'static,
{
- Self::new(StaticHostFn::<_, false>::new(move |store, params| {
- HostResult::Done(func(store, params))
- }))
+ Self::new(
+ Asyncness::No,
+ StaticHostFn::<_, false>::new(move |store, params| {
+ HostResult::Done(func(store, params))
+ }),
+ )
}
- /// Creates a new, statically typed, asynchronous, host function from the
- /// `func` provided.
+ /// Equivalent for `Linker::func_wrap_async`
+ #[cfg(feature = "async")]
+ pub(crate) fn func_wrap_async<T, F, P, R>(func: F) -> Arc<HostFunc>
+ where
+ T: 'static,
+ F: Fn(StoreContextMut<'_, T>, P) -> Box<dyn Future<Output = Result<R>> + Send + '_>
+ + Send
+ + Sync
+ + 'static,
+ P: ComponentNamedList + Lift + 'static,
+ R: ComponentNamedList + Lower + 'static,
+ {
+ Self::new(
+ Asyncness::Yes,
+ StaticHostFn::<_, false>::new(move |store, params| {
+ HostResult::Done(
+ store
+ .block_on(|store| Pin::from(func(store, params)))
+ .and_then(|r| r),
+ )
+ }),
+ )
+ }
+
+ /// Equivalent for `Linker::func_wrap_concurrent`
#[cfg(feature = "component-model-async")]
- pub(crate) fn from_concurrent<T, F, P, R>(func: F) -> Arc<HostFunc>
+ pub(crate) fn func_wrap_concurrent<T, F, P, R>(func: F) -> Arc<HostFunc>
where
T: 'static,
F: Fn(&Accessor<T>, P) -> Pin<Box<dyn Future<Output = Result<R>> + Send + '_>>
@@ -106,36 +145,73 @@ impl HostFunc {
R: ComponentNamedList + Lower + 'static,
{
let func = Arc::new(func);
- Self::new(StaticHostFn::<_, true>::new(move |store, params| {
- let func = func.clone();
- HostResult::Future(Box::pin(
- store.wrap_call(move |accessor| func(accessor, params)),
- ))
- }))
+ Self::new(
+ Asyncness::Yes,
+ StaticHostFn::<_, true>::new(move |store, params| {
+ let func = func.clone();
+ HostResult::Future(Box::pin(
+ store.wrap_call(move |accessor| func(accessor, params)),
+ ))
+ }),
+ )
}
- /// Creates a new, dynamically typed, synchronous, host function from the
- /// `func` provided.
- pub(crate) fn new_dynamic<T: 'static, F>(func: F) -> Arc<HostFunc>
+ /// Equivalent of `Linker::func_new`
+ pub(crate) fn func_new<T, F>(func: F) -> Arc<HostFunc>
where
+ T: 'static,
F: Fn(StoreContextMut<'_, T>, ComponentFunc, &[Val], &mut [Val]) -> Result<()>
+ Send
+ Sync
+ 'static,
{
- Self::new(DynamicHostFn::<_, false>::new(
- move |store, ty, mut params_and_results, result_start| {
- let (params, results) = params_and_results.split_at_mut(result_start);
- let result = func(store, ty, params, results).map(move |()| params_and_results);
- HostResult::Done(result)
- },
- ))
+ Self::new(
+ Asyncness::No,
+ DynamicHostFn::<_, false>::new(
+ move |store, ty, mut params_and_results, result_start| {
+ let (params, results) = params_and_results.split_at_mut(result_start);
+ let result = func(store, ty, params, results).map(move |()| params_and_results);
+ HostResult::Done(result)
+ },
+ ),
+ )
+ }
+
+ /// Equivalent of `Linker::func_new_async`
+ #[cfg(feature = "async")]
+ pub(crate) fn func_new_async<T, F>(func: F) -> Arc<HostFunc>
+ where
+ T: 'static,
+ F: for<'a> Fn(
+ StoreContextMut<'a, T>,
+ ComponentFunc,
+ &'a [Val],
+ &'a mut [Val],
+ ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
+ + Send
+ + Sync
+ + 'static,
+ {
+ Self::new(
+ Asyncness::Yes,
+ DynamicHostFn::<_, false>::new(
+ move |store, ty, mut params_and_results, result_start| {
+ let (params, results) = params_and_results.split_at_mut(result_start);
+ let result = store
+ .with_blocking(|store, cx| {
+ cx.block_on(Pin::from(func(store, ty, params, results)))
+ })
+ .and_then(|r| r);
+ let result = result.map(move |()| params_and_results);
+ HostResult::Done(result)
+ },
+ ),
+ )
}
- /// Creates a new, dynamically typed, asynchronous, host function from the
- /// `func` provided.
+ /// Equivalent of `Linker::func_new_concurrent`
#[cfg(feature = "component-model-async")]
- pub(crate) fn new_dynamic_concurrent<T, F>(func: F) -> Arc<HostFunc>
+ pub(crate) fn func_new_concurrent<T, F>(func: F) -> Arc<HostFunc>
where
T: 'static,
F: for<'a> Fn(
@@ -149,18 +225,21 @@ impl HostFunc {
+ 'static,
{
let func = Arc::new(func);
- Self::new(DynamicHostFn::<_, true>::new(
- move |store, ty, mut params_and_results, result_start| {
- let func = func.clone();
- HostResult::Future(Box::pin(store.wrap_call(move |accessor| {
- Box::pin(async move {
- let (params, results) = params_and_results.split_at_mut(result_start);
- func(accessor, ty, params, results).await?;
- Ok(params_and_results)
- })
- })))
- },
- ))
+ Self::new(
+ Asyncness::Yes,
+ DynamicHostFn::<_, true>::new(
+ move |store, ty, mut params_and_results, result_start| {
+ let func = func.clone();
+ HostResult::Future(Box::pin(store.wrap_call(move |accessor| {
+ Box::pin(async move {
+ let (params, results) = params_and_results.split_at_mut(result_start);
+ func(accessor, ty, params, results).await?;
+ Ok(params_and_results)
+ })
+ })))
+ },
+ ),
+ )
}
pub fn typecheck(&self, ty: TypeFuncIndex, types: &InstanceType<'_>) -> Result<()> {
@@ -174,6 +253,10 @@ impl HostFunc {
data: data.into(),
}
}
+
+ pub fn asyncness(&self) -> Asyncness {
+ self.asyncness
+ }
}
/// Argument to [`HostFn::lift_params`]
diff --git a/crates/wasmtime/src/runtime/component/func/options.rs b/crates/wasmtime/src/runtime/component/func/options.rs
index 7a1948346b..aefa1471e8 100644
--- a/crates/wasmtime/src/runtime/component/func/options.rs
+++ b/crates/wasmtime/src/runtime/component/func/options.rs
@@ -57,11 +57,11 @@ impl<'a, T: 'static> LowerContext<'a, T> {
options: OptionsIndex,
instance: Instance,
) -> LowerContext<'a, T> {
- #[cfg(all(debug_assertions, feature = "component-model-async"))]
- if store.engine().config().async_support {
- // Assert that we're running on a fiber, which is necessary in
- // case we call the guest's realloc function.
- store.0.with_blocking(|_, _| {});
+ // Debug-assert that if we can't block that blocking is indeed allowed.
+ // This'll catch when this is accidentally created outside of a fiber
+ // when we need to be on a fiber.
+ if cfg!(debug_assertions) && !store.0.can_block() {
+ store.0.validate_sync_call().unwrap();
}
let (component, store) = instance.component_and_store_mut(store.0);
LowerContext {
diff --git a/crates/wasmtime/src/runtime/component/func/typed.rs b/crates/wasmtime/src/runtime/component/func/typed.rs
index ee25c3737d..ed9b8a703a 100644
--- a/crates/wasmtime/src/runtime/component/func/typed.rs
+++ b/crates/wasmtime/src/runtime/component/func/typed.rs
@@ -140,6 +140,8 @@ where
/// instance is currently calling a host function.
/// * If a previous function call occurred and the corresponding
/// `post_return` hasn't been invoked yet.
+ /// * If `store` requires using [`Self::call_async`] instead, see
+ /// [crate documentation](crate#async) for more info.
///
/// In general there are many ways that things could go wrong when copying
/// types in and out of a wasm module with the canonical ABI, and certain
@@ -154,24 +156,19 @@ where
///
/// # Panics
///
- /// Panics if this is called on a function in an asynchronous store. This
- /// only works with functions defined within a synchronous store. Also
- /// panics if `store` does not own this function.
- pub fn call(&self, store: impl AsContextMut, params: Params) -> Result<Return> {
- assert!(
- !store.as_context().async_support(),
- "must use `call_async` when async support is enabled on the config"
- );
+ /// Panics if `store` does not own this function.
+ pub fn call(&self, mut store: impl AsContextMut, params: Params) -> Result<Return> {
+ let store = store.as_context_mut();
+ store.0.validate_sync_call()?;
self.call_impl(store, params)
}
- /// Exactly like [`Self::call`], except for use on asynchronous stores.
+ /// Exactly like [`Self::call`], except for invoking WebAssembly
+ /// [asynchronously](crate#async).
///
/// # Panics
///
- /// Panics if this is called on a function in a synchronous store. This
- /// only works with functions defined within an asynchronous store. Also
- /// panics if `store` does not own this function.
+ /// Panics if `store` does not own this function.
#[cfg(feature = "async")]
pub async fn call_async(
&self,
@@ -182,10 +179,6 @@ where
Return: 'static,
{
let mut store = store.as_context_mut();
- assert!(
- store.0.async_support(),
- "cannot use `call_async` when async support is not enabled on the config"
- );
#[cfg(feature = "component-model-async")]
if store.0.cm_concurrency_enabled() {
@@ -321,10 +314,6 @@ where
let result = accessor.as_accessor().with(|mut store| {
let mut store = store.as_context_mut();
assert!(store.0.cm_concurrency_enabled());
- assert!(
- store.0.async_support(),
- "cannot use `call_concurrent` when async support is not enabled on the config"
- );
let prepared =
self.prepare_call(store.as_context_mut(), false, true, move |cx, ty, dst| {
diff --git a/crates/wasmtime/src/runtime/component/instance.rs b/crates/wasmtime/src/runtime/component/instance.rs
index 22934f84db..c00870e155 100644
--- a/crates/wasmtime/src/runtime/component/instance.rs
+++ b/crates/wasmtime/src/runtime/component/instance.rs
@@ -12,7 +12,7 @@ use crate::runtime::vm::component::{
CallContexts, ComponentInstance, ResourceTables, TypedResource, TypedResourceIndex,
};
use crate::runtime::vm::{self, VMFuncRef};
-use crate::store::{AsStoreOpaque, StoreOpaque};
+use crate::store::{AsStoreOpaque, Asyncness, StoreOpaque};
use crate::{AsContext, AsContextMut, Engine, Module, StoreContextMut};
use alloc::sync::Arc;
use core::marker;
@@ -729,7 +729,7 @@ pub(crate) enum RuntimeImport {
// function being used across multiple instances simultaneously. Or
// otherwise this makes `InstancePre::instantiate` possible to create
// separate instances all sharing the same host function.
- _dtor: Arc<crate::func::HostFunc>,
+ dtor: Arc<crate::func::HostFunc>,
// A raw function which is filled out (including `wasm_call`) which
// points to the internals of the `_dtor` field. This is read and
@@ -768,7 +768,11 @@ impl<'a> Instantiator<'a> {
})
}
- async fn run<T>(&mut self, store: &mut StoreContextMut<'_, T>) -> Result<()> {
+ async fn run<T>(
+ &mut self,
+ store: &mut StoreContextMut<'_, T>,
+ asyncness: Asyncness,
+ ) -> Result<()> {
let env_component = self.component.env_component();
// Before all initializers are processed configure all destructors for
@@ -873,7 +877,8 @@ impl<'a> Instantiator<'a> {
// if required.
let i = unsafe {
- crate::Instance::new_started(store, module, imports.as_ref()).await?
+ crate::Instance::new_started(store, module, imports.as_ref(), asyncness)
+ .await?
};
self.instance_mut(store.0).push_instance_id(i.id());
}
@@ -1086,6 +1091,7 @@ pub struct InstancePre<T: 'static> {
component: Component,
imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>,
+ asyncness: Asyncness,
_marker: marker::PhantomData<fn() -> T>,
}
@@ -1096,6 +1102,7 @@ impl<T: 'static> Clone for InstancePre<T> {
component: self.component.clone(),
imports: self.imports.clone(),
resource_types: self.resource_types.clone(),
+ asyncness: self.asyncness,
_marker: self._marker,
}
}
@@ -1113,10 +1120,20 @@ impl<T: 'static> InstancePre<T> {
imports: Arc<PrimaryMap<RuntimeImportIndex, RuntimeImport>>,
resource_types: Arc<PrimaryMap<ResourceIndex, ResourceType>>,
) -> InstancePre<T> {
+ let mut asyncness = Asyncness::No;
+ for (_, import) in imports.iter() {
+ asyncness = asyncness
+ | match import {
+ RuntimeImport::Func(f) => f.asyncness(),
+ RuntimeImport::Module(_) => Asyncness::No,
+ RuntimeImport::Resource { dtor, .. } => dtor.asyncness(),
+ };
+ }
InstancePre {
component,
imports,
resource_types,
+ asyncness,
_marker: marker::PhantomData,
}
}
@@ -1145,12 +1162,16 @@ impl<T: 'static> InstancePre<T> {
/// Performs the instantiation process into the store specified.
//
// TODO: needs more docs
- pub fn instantiate(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> {
- assert!(
- !store.as_context().async_support(),
- "must use async instantiation when async support is enabled"
- );
- vm::assert_ready(self._instantiate(store))
+ pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
+ let store = store.as_context_mut();
+
+ // If this instance requires an async host, set that flag in the store,
+ // and then afterwards assert nothing else in the store, nor this
+ // instance, required async.
+ store.0.set_async_required(self.asyncness);
+ store.0.validate_sync_call()?;
+
+ vm::assert_ready(self._instantiate(store, Asyncness::No))
}
/// Performs the instantiation process into the store specified.
///
@@ -1159,17 +1180,22 @@ impl<T: 'static> InstancePre<T> {
// TODO: needs more docs
#[cfg(feature = "async")]
pub async fn instantiate_async(&self, store: impl AsContextMut<Data = T>) -> Result<Instance> {
- self._instantiate(store).await
+ self._instantiate(store, Asyncness::Yes).await
}
- async fn _instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
+ async fn _instantiate(
+ &self,
+ mut store: impl AsContextMut<Data = T>,
+ asyncness: Asyncness,
+ ) -> Result<Instance> {
let mut store = store.as_context_mut();
+ store.0.set_async_required(self.asyncness);
store
.engine()
.allocator()
.increment_component_instance_count()?;
let mut instantiator = Instantiator::new(&self.component, store.0, &self.imports)?;
- instantiator.run(&mut store).await.map_err(|e| {
+ instantiator.run(&mut store, asyncness).await.map_err(|e| {
store
.engine()
.allocator()
diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rs
index 74852452f7..5ef3820d71 100644
--- a/crates/wasmtime/src/runtime/component/linker.rs
+++ b/crates/wasmtime/src/runtime/component/linker.rs
@@ -12,8 +12,8 @@ use crate::prelude::*;
use crate::{AsContextMut, Engine, Module, StoreContextMut};
use alloc::sync::Arc;
use core::marker;
-#[cfg(feature = "async")]
-use core::{future::Future, pin::Pin};
+#[cfg(feature = "component-model-async")]
+use core::pin::Pin;
use wasmtime_environ::PrimaryMap;
use wasmtime_environ::component::{NameMap, NameMapIntern};
@@ -243,7 +243,7 @@ impl<T: 'static> Linker<T> {
Definition::Func(f) => RuntimeImport::Func(f.clone()),
Definition::Resource(t, dtor) => RuntimeImport::Resource {
ty: *t,
- _dtor: dtor.clone(),
+ dtor: dtor.clone(),
dtor_funcref: component.resource_drop_func_ref(dtor),
},
@@ -273,19 +273,18 @@ impl<T: 'static> Linker<T> {
/// a runtime trap or a runtime limit being exceeded.
pub fn instantiate(
&self,
- store: impl AsContextMut<Data = T>,
+ mut store: impl AsContextMut<Data = T>,
component: &Component,
) -> Result<Instance> {
- assert!(
- !store.as_context().async_support(),
- "must use async instantiation when async support is enabled"
- );
+ let store = store.as_context_mut();
+ store.0.validate_sync_call()?;
self.instantiate_pre(component)?.instantiate(store)
}
/// Instantiates the [`Component`] provided into the `store` specified.
///
- /// This is exactly like [`Linker::instantiate`] except for async stores.
+ /// This is exactly like [`Linker::instantiate`] except for [asynchronous
+ /// execution](crate#async).
///
/// # Errors
///
@@ -302,10 +301,6 @@ impl<T: 'static> Linker<T> {
where
T: Send,
{
- assert!(
- store.as_context().async_support(),
- "must use sync instantiation when async support is disabled"
- );
self.instantiate_pre(component)?
.instantiate_async(store)
.await
@@ -412,14 +407,12 @@ impl<T: 'static> LinkerInstance<'_, T> {
/// # Blocking / Async Behavior
///
/// The host function `func` provided here is a blocking function from the
- /// perspective of WebAssembly, regardless of how [`Config::async_support`]
- /// is defined. This function can be used both with sync and async stores
- /// and will always define a blocking function.
+ /// perspective of WebAssembly. WebAssembly, and Rust, will be blocked until
+ /// `func` completes.
///
/// To define a function which is async on the host, but blocking to the
/// guest, see the [`func_wrap_async`] method.
///
- /// [`Config::async_support`]: crate::Config::async_support
/// [`func_wrap_async`]: LinkerInstance::func_wrap_async
//
// TODO: needs more words and examples
@@ -429,7 +422,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
Params: ComponentNamedList + Lift + 'static,
Return: ComponentNamedList + Lower + 'static,
{
- self.insert(name, Definition::Func(HostFunc::from_closure(func)))?;
+ self.insert(name, Definition::Func(HostFunc::func_wrap(func)))?;
Ok(())
}
@@ -449,24 +442,19 @@ impl<T: 'static> LinkerInstance<'_, T> {
///
/// # Blocking / Async Behavior
///
- /// This function can only be called when [`Config::async_support`] is
- /// enabled. The function defined which WebAssembly calls will still appear
- /// as blocking from the perspective of WebAssembly itself. The host,
- /// however, can perform asynchronous operations without blocking the thread
+ /// The function defined which WebAssembly calls will still appear as
+ /// blocking from the perspective of WebAssembly itself. The host, however,
+ /// can perform asynchronous operations without blocking the thread
/// performing a call.
///
- /// When [`Config::async_support`] is enabled then all WebAssembly is
- /// invoked on a separate stack within a Wasmtime-managed fiber. This means
- /// that if the future returned by `F` is not immediately ready then the
- /// fiber will be suspended to block WebAssembly but not the host. When the
- /// future becomes ready again the fiber will be resumed to continue
- /// execution within WebAssembly.
- ///
- /// # Panics
+ /// When defining host functions with this function, WebAssembly is invoked
+ /// on a separate stack within a Wasmtime-managed fiber (through the
+ /// `call_async`-style of invocation). This means that if the future
+ /// returned by `F` is not immediately ready then the fiber will be
+ /// suspended to block WebAssembly but not the host. When the future
+ /// becomes ready again the fiber will be resumed to continue execution
+ /// within WebAssembly.
///
- /// This function panics if [`Config::async_support`] is set to `false`.
- ///
- /// [`Config::async_support`]: crate::Config::async_support
/// [`func_wrap_async`]: LinkerInstance::func_wrap_async
#[cfg(feature = "async")]
pub fn func_wrap_async<Params, Return, F>(&mut self, name: &str, f: F) -> Result<()>
@@ -481,14 +469,8 @@ impl<T: 'static> LinkerInstance<'_, T> {
Params: ComponentNamedList + Lift + 'static,
Return: ComponentNamedList + Lower + 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_wrap_async` without enabling async support in the config"
- );
- let ff = move |store: StoreContextMut<'_, T>, params: Params| -> Result<Return> {
- store.block_on(|store| f(store, params).into())?
- };
- self.func_wrap(name, ff)
+ self.insert(name, Definition::Func(HostFunc::func_wrap_async(f)))?;
+ Ok(())
}
/// Defines a new host-provided async function into this [`LinkerInstance`].
@@ -521,14 +503,13 @@ impl<T: 'static> LinkerInstance<'_, T> {
///
/// # Blocking / Async Behavior
///
- /// This function can only be called when [`Config::async_support`] is
- /// enabled. Unlike [`Self::func_wrap`] and [`Self::func_wrap_async`] this
- /// function is asynchronous even from the perspective of guest WebAssembly.
- /// This means that if `f` is not immediately resolved then the call from
+ /// Unlike [`Self::func_wrap`] and [`Self::func_wrap_async`] this function
+ /// is asynchronous even from the perspective of guest WebAssembly. This
+ /// means that if `f` is not immediately resolved then the call from
/// WebAssembly will still return immediately (assuming it was lowered with
- /// `async`). The closure `f` should not block the current thread and should
- /// only perform blocking via `async` meaning that `f` won't block either
- /// WebAssembly nor the host.
+ /// `async`). The closure `f` should not block the current thread and
+ /// should only perform blocking via `async` meaning that `f` won't block
+ /// either WebAssembly nor the host.
///
/// Note that WebAssembly components can lower host functions both with and
/// without `async`. That means that even if a host function is defined in
@@ -537,11 +518,6 @@ impl<T: 'static> LinkerInstance<'_, T> {
/// `f` provided here completes. If a guest lowers this function with
/// `async`, though, then no blocking will happen.
///
- /// # Panics
- ///
- /// This function panics if [`Config::async_support`] is set to `false`.
- ///
- /// [`Config::async_support`]: crate::Config::async_support
/// [`Config::wasm_component_model_async`]: crate::Config::wasm_component_model_async
/// [`func_wrap_async`]: LinkerInstance::func_wrap_async
#[cfg(feature = "component-model-async")]
@@ -555,11 +531,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
Params: ComponentNamedList + Lift + 'static,
Return: ComponentNamedList + Lower + 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_wrap_concurrent` without enabling async support in the config"
- );
- self.insert(name, Definition::Func(HostFunc::from_concurrent(f)))?;
+ self.insert(name, Definition::Func(HostFunc::func_wrap_concurrent(f)))?;
Ok(())
}
@@ -670,7 +642,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
+ Sync
+ 'static,
) -> Result<()> {
- self.insert(name, Definition::Func(HostFunc::new_dynamic(func)))?;
+ self.insert(name, Definition::Func(HostFunc::func_new(func)))?;
Ok(())
}
@@ -681,7 +653,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
///
/// For documentation on blocking behavior see [`Self::func_wrap_async`].
#[cfg(feature = "async")]
- pub fn func_new_async<F>(&mut self, name: &str, f: F) -> Result<()>
+ pub fn func_new_async<F>(&mut self, name: &str, func: F) -> Result<()>
where
F: for<'a> Fn(
StoreContextMut<'a, T>,
@@ -693,15 +665,8 @@ impl<T: 'static> LinkerInstance<'_, T> {
+ Sync
+ 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_new_async` without enabling async support in the config"
- );
- let ff = move |store: StoreContextMut<'_, T>, ty, params: &[Val], results: &mut [Val]| {
- store
- .with_blocking(|store, cx| cx.block_on(Pin::from(f(store, ty, params, results)))?)
- };
- return self.func_new(name, ff);
+ self.insert(name, Definition::Func(HostFunc::func_new_async(func)))?;
+ Ok(())
}
/// Define a new host-provided async function using dynamic types.
@@ -725,11 +690,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
+ Sync
+ 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_wrap_concurrent` without enabling async support in the config"
- );
- self.insert(name, Definition::Func(HostFunc::new_dynamic_concurrent(f)))?;
+ self.insert(name, Definition::Func(HostFunc::func_new_concurrent(f)))?;
Ok(())
}
@@ -789,10 +750,6 @@ impl<T: 'static> LinkerInstance<'_, T> {
+ Sync
+ 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `resource_async` without enabling async support in the config"
- );
let dtor = Arc::new(crate::func::HostFunc::wrap_async(
&self.engine,
move |cx: crate::Caller<'_, T>, (param,): (u32,)| dtor(cx.into(), param),
@@ -811,10 +768,6 @@ impl<T: 'static> LinkerInstance<'_, T> {
+ Sync
+ 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `resource_concurrent` without enabling async support in the config"
- );
// TODO: This isn't really concurrent -- it requires exclusive access to
// the store for the duration of the call, preventing guest code from
// running until it completes. We should make it concurrent and clean
diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs
index 7273cf6a3c..b06907125b 100644
--- a/crates/wasmtime/src/runtime/component/mod.rs
+++ b/crates/wasmtime/src/runtime/component/mod.rs
@@ -287,8 +287,7 @@ pub(crate) use self::store::ComponentStoreData;
/// // The `async` flag is used to indicate that a Rust-level `async`
/// // function is used on the host. This means that the host is allowed
/// // to do async I/O. Note though that to WebAssembly itself the
-/// // function will still be blocking. This requires
-/// // `Config::async_support` to be `true` as well.
+/// // function will still be blocking.
/// "wasi:io/poll.poll": async,
///
/// // The `store` flag means that the host function will have access
diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rs
index 052c6ae5b4..642a60295e 100644
--- a/crates/wasmtime/src/runtime/component/resources/any.rs
+++ b/crates/wasmtime/src/runtime/component/resources/any.rs
@@ -148,22 +148,15 @@ impl ResourceAny {
/// if one was specified).
pub fn resource_drop(self, mut store: impl AsContextMut) -> Result<()> {
let mut store = store.as_context_mut();
- assert!(
- !store.0.async_support(),
- "must use `resource_drop_async` when async support is enabled on the config"
- );
- self.resource_drop_impl(&mut store.as_context_mut())
+ store.0.validate_sync_call()?;
+ self.resource_drop_impl(&mut store)
}
/// Same as [`ResourceAny::resource_drop`] except for use with async stores
- /// to execute the destructor asynchronously.
+ /// to execute the destructor [asynchronously](crate#async).
#[cfg(feature = "async")]
pub async fn resource_drop_async(self, mut store: impl AsContextMut<Data: Send>) -> Result<()> {
let mut store = store.as_context_mut();
- assert!(
- store.0.async_support(),
- "cannot use `resource_drop_async` without enabling async support in the config"
- );
store
.on_fiber(|store| self.resource_drop_impl(store))
.await?
diff --git a/crates/wasmtime/src/runtime/coredump.rs b/crates/wasmtime/src/runtime/coredump.rs
index 38bf793f14..c8c8fe366e 100644
--- a/crates/wasmtime/src/runtime/coredump.rs
+++ b/crates/wasmtime/src/runtime/coredump.rs
@@ -9,12 +9,12 @@ use std::fmt;
/// Representation of a core dump of a WebAssembly module
///
/// When the Config::coredump_on_trap option is enabled this structure is
-/// attached to the [`wasmtime::Error`] returned from many Wasmtime functions
+/// attached to the [`Error`](crate::Error) returned from many Wasmtime functions
/// that execute WebAssembly such as [`Instance::new`] or [`Func::call`]. This
-/// can be acquired with the [`wasmtime::Error::downcast`] family of methods to
-/// programmatically inspect the coredump. Otherwise since it's part of the
-/// error returned this will get printed along with the rest of the error when
-/// the error is logged.
+/// can be acquired with the [`Error::downcast`](crate::Error::downcast) family
+/// of methods to programmatically inspect the coredump. Otherwise since it's
+/// part of the error returned this will get printed along with the rest of the
+/// error when the error is logged.
///
/// Note that some state, such as Wasm locals or values on the operand stack,
/// may be optimized away by the compiler or otherwise not recovered in the
diff --git a/crates/wasmtime/src/runtime/externals/table.rs b/crates/wasmtime/src/runtime/externals/table.rs
index bca5c3200d..9e22df7f4c 100644
--- a/crates/wasmtime/src/runtime/externals/table.rs
+++ b/crates/wasmtime/src/runtime/externals/table.rs
@@ -59,13 +59,11 @@ impl Table {
/// Returns an error if `init` does not match the element type of the table,
/// or if `init` does not belong to the `store` provided.
///
- /// # Panics
- ///
- /// This function will panic when used with a [`Store`](`crate::Store`)
- /// which has a [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`)
- /// (see also: [`Store::limiter_async`](`crate::Store::limiter_async`).
- /// When using an async resource limiter, use [`Table::new_async`]
- /// instead.
+ /// This function will also return an error when used with a
+ /// [`Store`](`crate::Store`) which has a
+ /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
+ /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an
+ /// async resource limiter, use [`Table::new_async`] instead.
///
/// # Examples
///
@@ -94,19 +92,17 @@ impl Table {
/// # }
/// ```
pub fn new(mut store: impl AsContextMut, ty: TableType, init: Ref) -> Result<Table> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- vm::one_poll(Table::_new(store, limiter.as_mut(), ty, init))
- .expect("must use `new_async` when async resource limiters are in use")
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(Table::_new(store, limiter.as_mut(), ty, init))
}
- /// Async variant of [`Table::new`]. You must use this variant with
- /// [`Store`](`crate::Store`)s which have a
- /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
- ///
- /// # Panics
+ /// Async variant of [`Table::new`].
///
- /// This function will panic when used with a non-async
- /// [`Store`](`crate::Store`)
+ /// You must use this variant with [`Store`](`crate::Store`)s which have a
+ /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
#[cfg(feature = "async")]
pub async fn new_async(
mut store: impl AsContextMut,
@@ -275,18 +271,19 @@ impl Table {
/// error if `init` is not of the right type or if `init` does not belong to
/// `store`.
///
+ /// This function also returns an error when used with a
+ /// [`Store`](`crate::Store`) which has a
+ /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
+ /// [`Store::limiter_async`](`crate::Store::limiter_async`)). When using an
+ /// async resource limiter, use [`Table::grow_async`] instead.
+ ///
/// # Panics
///
/// Panics if `store` does not own this table.
- ///
- /// This function will panic when used with a [`Store`](`crate::Store`)
- /// which has a [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`)
- /// (see also: [`Store::limiter_async`](`crate::Store::limiter_async`)).
- /// When using an async resource limiter, use [`Table::grow_async`]
- /// instead.
pub fn grow(&self, mut store: impl AsContextMut, delta: u64, init: Ref) -> Result<u64> {
- vm::one_poll(self._grow(store.as_context_mut(), delta, init))
- .expect("must use `grow_async` when async resource limiters are in use")
+ let store = store.as_context_mut();
+ store.0.validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(self._grow(store, delta, init))
}
async fn _grow<T>(&self, store: StoreContextMut<'_, T>, delta: u64, init: Ref) -> Result<u64> {
@@ -342,13 +339,14 @@ impl Table {
}
}
- /// Async variant of [`Table::grow`]. Required when using a
+ /// Async variant of [`Table::grow`].
+ ///
+ /// Required when using a
/// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
///
/// # Panics
///
- /// This function will panic when used with a non-async
- /// [`Store`](`crate::Store`).
+ /// This function will panic when if the store doens't own the table.
#[cfg(feature = "async")]
pub async fn grow_async(
&self,
diff --git a/crates/wasmtime/src/runtime/fiber.rs b/crates/wasmtime/src/runtime/fiber.rs
index 5faa4dd5c8..2d5da669a6 100644
--- a/crates/wasmtime/src/runtime/fiber.rs
+++ b/crates/wasmtime/src/runtime/fiber.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use crate::store::{AsStoreOpaque, Executor, StoreId, StoreOpaque};
+use crate::store::{AsStoreOpaque, Asyncness, Executor, StoreId, StoreOpaque};
use crate::vm::mpk::{self, ProtectionMask};
use crate::vm::{AlwaysMut, AsyncWasmCallState};
use crate::{Engine, StoreContextMut};
@@ -84,6 +84,12 @@ pub(crate) struct AsyncState {
// be multiple concurrent fibers in play; consider caching more than one
// stack at a time and making the number tunable via `Config`.
last_fiber_stack: Option<wasmtime_fiber::FiberStack>,
+
+ /// Whether or not this store has async host functions defined somewhere
+ /// within it or some other store-related configuration (e.g. epochs
+ /// yielding) which requires that wasm is executed on a fiber, thus async
+ /// entrypoints are required.
+ pub(crate) async_required: bool,
}
// SAFETY: it's known that `std::task::Context` is neither `Send` nor `Sync`,
@@ -102,6 +108,7 @@ impl Default for AsyncState {
current_suspend: None,
current_future_cx: None,
last_fiber_stack: None,
+ async_required: false,
}
}
}
@@ -110,6 +117,12 @@ impl AsyncState {
pub(crate) fn last_fiber_stack(&mut self) -> &mut Option<wasmtime_fiber::FiberStack> {
&mut self.last_fiber_stack
}
+
+ /// Returns whether `block_on` will succeed or panic.
+ #[inline]
+ pub(crate) fn can_block(&mut self) -> bool {
+ self.current_future_cx.is_some()
+ }
}
/// A helper structure used to block a fiber.
@@ -357,10 +370,24 @@ impl StoreOpaque {
BlockingContext::with(self, |store, cx| f(store, cx))
}
- /// Returns whether `block_on` will succeed or panic.
- #[cfg(any(feature = "call-hook", feature = "debug"))]
- pub(crate) fn can_block(&mut self) -> bool {
- self.fiber_async_state_mut().current_future_cx.is_some()
+ /// Used when any configuration option that affects a store, as a side
+ /// effect, disallows further use of sync APIs in Wasmtime.
+ ///
+ /// For example enabling async yielding epochs, async yielding fuel, or
+ /// async resource limiters all require that wasm is invoked on fibers.
+ /// These options, when enabled, will all set this flag.
+ ///
+ /// Note that this specifically only models the transition from "some
+ /// previous state" to "async is now required". There's no reasonable way to
+ /// iterate through a store and recompute this if epoch settings, for
+ /// example, are dynamically changed.
+ pub(crate) fn set_async_required(&mut self, asyncness: Asyncness) {
+ match asyncness {
+ Asyncness::Yes => {
+ self.fiber_async_state_mut().async_required = true;
+ }
+ Asyncness::No => {}
+ }
}
}
@@ -855,7 +882,6 @@ where
{
let opaque = store.as_store_opaque();
let config = opaque.engine().config();
- debug_assert!(opaque.async_support());
debug_assert!(config.async_stack_size > 0);
let mut result = None;
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index 5f29f1c7a9..1445fc1b64 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -4,7 +4,7 @@ use crate::runtime::vm::{
VMCommonStackInformation, VMContext, VMFuncRef, VMFunctionImport, VMOpaqueContext,
VMStoreContext,
};
-use crate::store::{AutoAssertNoGc, InstanceId, StoreId, StoreOpaque};
+use crate::store::{Asyncness, AutoAssertNoGc, InstanceId, StoreId, StoreOpaque};
use crate::type_registry::RegisteredType;
use crate::{
AsContext, AsContextMut, CallHook, Engine, Extern, FuncType, Instance, ModuleExport, Ref,
@@ -120,7 +120,7 @@ impl NoFunc {
/// might have an `async` function in Rust, however, which you'd like to make
/// available from WebAssembly. Wasmtime supports asynchronously calling
/// WebAssembly through native stack switching. You can get some more
-/// information about [asynchronous configs](crate::Config::async_support), but
+/// information about [asynchronous configs](crate#async), but
/// from the perspective of `Func` it's important to know that whether or not
/// your [`Store`](crate::Store) is asynchronous will dictate whether you call
/// functions through [`Func::call`] or [`Func::call_async`] (or the typed
@@ -444,9 +444,6 @@ impl Func {
///
/// # Panics
///
- /// This function will panic if `store` is not associated with an [async
- /// config](crate::Config::async_support).
- ///
/// Panics if the given function type is not associated with this store's
/// engine.
///
@@ -479,7 +476,7 @@ impl Func {
///
/// // Using `new_async` we can hook up into calling our async
/// // `get_row_count` function.
- /// let engine = Engine::new(Config::new().async_support(true))?;
+ /// let engine = Engine::default();
/// let mut store = Store::new(&engine, MyDatabase {
/// // ...
/// });
@@ -513,10 +510,7 @@ impl Func {
T: Send + 'static,
{
let store = store.as_context_mut().0;
- assert!(
- store.async_support(),
- "cannot use `new_async` without enabling async support in the config"
- );
+
let host = HostFunc::new_async(store.engine(), ty, func);
// SAFETY: the `T` used by `func` matches the `T` of the store we're
@@ -806,10 +800,6 @@ impl Func {
/// Same as [`Func::wrap`], except the closure asynchronously produces the
/// result and the arguments are passed within a tuple. For more information
/// see the [`Func`] documentation.
- ///
- /// # Panics
- ///
- /// This function will panic if called with a non-asynchronous store.
#[cfg(feature = "async")]
pub fn wrap_async<T, F, P, R>(mut store: impl AsContextMut<Data = T>, func: F) -> Func
where
@@ -822,10 +812,6 @@ impl Func {
T: Send + 'static,
{
let store = store.as_context_mut().0;
- assert!(
- store.async_support(),
- concat!("cannot use `wrap_async` without enabling async support on the config")
- );
let host = HostFunc::wrap_async(store.engine(), func);
// SAFETY: The `T` the closure takes is the same as the `T` of the store
@@ -910,6 +896,8 @@ impl Func {
/// `params`.
/// * Any host-originating error originally returned from a function defined
/// via [`Func::new`], for example.
+ /// * The `store` provided is configured to require `call_async` to be used
+ /// instead, such as with epochs or fuel.
///
/// Errors typically indicate that execution of WebAssembly was halted
/// mid-way and did not complete after the error condition happened.
@@ -918,9 +906,7 @@ impl Func {
///
/// # Panics
///
- /// This function will panic if called on a function belonging to an async
- /// store. Asynchronous stores must always use `call_async`. Also panics if
- /// `store` does not own this function.
+ /// Panics if `store` does not own this function.
///
/// [`WasmBacktrace`]: crate::WasmBacktrace
pub fn call(
@@ -929,11 +915,8 @@ impl Func {
params: &[Val],
results: &mut [Val],
) -> Result<()> {
- assert!(
- !store.as_context().async_support(),
- "must use `call_async` when async support is enabled on the config",
- );
let mut store = store.as_context_mut();
+ store.0.validate_sync_call()?;
self.call_impl_check_args(&mut store, params, results)?;
@@ -1048,8 +1031,7 @@ impl Func {
/// asynchronously.
///
/// This function is the same as [`Func::call`] except that it is
- /// asynchronous. This is only compatible with stores associated with an
- /// [asynchronous config](crate::Config::async_support).
+ /// asynchronous.
///
/// It's important to note that the execution of WebAssembly will happen
/// synchronously in the `poll` method of the future returned from this
@@ -1059,7 +1041,7 @@ impl Func {
/// in a "blocking context".
///
/// For more information see the documentation on [asynchronous
- /// configs](crate::Config::async_support).
+ /// configs](crate#async).
///
/// # Errors
///
@@ -1078,10 +1060,6 @@ impl Func {
results: &mut [Val],
) -> Result<()> {
let mut store = store.as_context_mut();
- assert!(
- store.0.async_support(),
- "cannot use `call_async` without enabling async support in the config",
- );
self.call_impl_check_args(&mut store, params, results)?;
@@ -1499,7 +1477,7 @@ impl EntryStoreContext {
// stack. This means that the previous stack limit is no longer relevant
// because we're on a separate stack.
if unsafe { *store.0.vm_store_context().stack_limit.get() } != usize::MAX
- && !store.0.async_support()
+ && !store.0.can_block()
{
stack_limit = None;
}
@@ -2090,8 +2068,8 @@ impl<T> Caller<'_, T> {
///
/// Same as [`Store::gc`](crate::Store::gc).
#[cfg(feature = "gc")]
- pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) {
- self.store.gc(why);
+ pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
+ self.store.gc(why)
}
/// Perform garbage collection asynchronously.
@@ -2123,6 +2101,7 @@ impl<T> Caller<'_, T> {
///
/// For more information see
/// [`Store::fuel_async_yield_interval`](crate::Store::fuel_async_yield_interval)
+ #[cfg(feature = "async")]
pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
self.store.fuel_async_yield_interval(interval)
}
@@ -2171,6 +2150,14 @@ impl<'a, T: 'static> From<Caller<'a, T>> for StoreContextMut<'a, T> {
pub struct HostFunc {
ctx: StoreBox<VMArrayCallHostFuncContext>,
+ /// Whether or not this function was defined with an `async` host function,
+ /// meaning that it is only invokable when wasm is itself on a fiber to
+ /// support suspension on `Poll::Pending`.
+ ///
+ /// This is used to propagate to an `InstancePre` and then eventually into a
+ /// `Store` as to whether the store requires async entrypoints.
+ asyncness: Asyncness,
+
// Stored to unregister this function's signature with the engine when this
// is dropped.
engine: Engine,
@@ -2198,10 +2185,15 @@ impl HostFunc {
///
/// This is an internal private constructor for this type intended to only
/// be used by other constructors of this type below.
- fn new_raw(engine: &Engine, ctx: StoreBox<VMArrayCallHostFuncContext>) -> Self {
+ fn new_raw(
+ engine: &Engine,
+ ctx: StoreBox<VMArrayCallHostFuncContext>,
+ asyncness: Asyncness,
+ ) -> Self {
HostFunc {
ctx,
engine: engine.clone(),
+ asyncness,
}
}
@@ -2382,7 +2374,7 @@ impl HostFunc {
where
T: 'static,
{
- HostFunc::new_raw(engine, Self::vmctx_sync(engine, ty, func))
+ HostFunc::new_raw(engine, Self::vmctx_sync(engine, ty, func), Asyncness::No)
}
/// Analog of [`Func::new`]
@@ -2411,6 +2403,7 @@ impl HostFunc {
func(caller.sub_caller(), params, results)?;
Self::store_untyped_results(caller.store, &ty, vec, values)
}),
+ Asyncness::No,
)
}
@@ -2453,6 +2446,7 @@ impl HostFunc {
})
},
),
+ Asyncness::Yes,
)
}
@@ -2529,7 +2523,7 @@ impl HostFunc {
// wasmtime's ambient correctness.
unsafe { Self::store_typed_results(caller.store.0, ret, args) }
});
- HostFunc::new_raw(engine, ctx)
+ HostFunc::new_raw(engine, ctx, Asyncness::No)
}
/// Analog of [`Func::wrap_async`]
@@ -2559,7 +2553,7 @@ impl HostFunc {
unsafe { Self::store_typed_results(caller.store.0, ret.into_fallible(), args) }
})
});
- HostFunc::new_raw(engine, ctx)
+ HostFunc::new_raw(engine, ctx, Asyncness::Yes)
}
/// Loads the typed parameters from `params`
@@ -2681,6 +2675,11 @@ impl HostFunc {
/// Same as [`HostFunc::to_func`], different ownership.
unsafe fn into_func(self, store: &mut StoreOpaque) -> Func {
self.validate_store(store);
+
+ // This function could be called by a guest at any time, and it requires
+ // fibers, so the store now required async entrypoints.
+ store.set_async_required(self.asyncness);
+
let (funcrefs, modules) = store.func_refs_and_modules();
let funcref = funcrefs.push_box_host(Box::new(self), modules);
// SAFETY: this funcref was just pushed within `store`, so it's safe to
@@ -2706,6 +2705,10 @@ impl HostFunc {
pub(crate) fn func_ref(&self) -> &VMFuncRef {
unsafe { self.ctx.get().as_ref().func_ref() }
}
+
+ pub(crate) fn asyncness(&self) -> Asyncness {
+ self.asyncness
+ }
}
#[cfg(test)]
diff --git a/crates/wasmtime/src/runtime/func/typed.rs b/crates/wasmtime/src/runtime/func/typed.rs
index 7ea40f9826..fa0d4b10bd 100644
--- a/crates/wasmtime/src/runtime/func/typed.rs
+++ b/crates/wasmtime/src/runtime/func/typed.rs
@@ -89,18 +89,13 @@ where
///
/// # Panics
///
- /// This function will panic if it is called when the underlying [`Func`] is
- /// connected to an asynchronous store.
+ /// Panics if `store` does not contain this function.
///
/// [`Trap`]: crate::Trap
#[inline]
pub fn call(&self, mut store: impl AsContextMut, params: Params) -> Result<Results> {
let mut store = store.as_context_mut();
- assert!(
- !store.0.async_support(),
- "must use `call_async` with async stores"
- );
-
+ store.0.validate_sync_call()?;
let func = self.func.vm_func_ref(store.0);
unsafe { Self::call_raw(&mut store, &self.ty, func, params) }
}
@@ -133,10 +128,6 @@ where
Results: Sync,
{
let mut store = store.as_context_mut();
- assert!(
- store.0.async_support(),
- "must use `call` with non-async stores"
- );
store
.on_fiber(|store| {
diff --git a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
index 78db88eaef..b9468c5e1c 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs
@@ -1,7 +1,9 @@
//! Working with GC `array` objects.
-use crate::runtime::vm::{VMGcRef, VMStore};
-use crate::store::{StoreId, StoreResourceLimiter};
+use crate::runtime::vm::VMGcRef;
+use crate::store::{Asyncness, StoreId, StoreResourceLimiter};
+#[cfg(feature = "async")]
+use crate::vm::VMStore;
use crate::vm::{self, VMArrayRef, VMGcHeader};
use crate::{AnyRef, FieldType};
use crate::{
@@ -148,7 +150,7 @@ impl ArrayRefPre {
/// Ok(oom) => {
/// // Do a GC! Note: in an async context, you'd want to do
/// // `scope.as_context_mut().gc_async().await`.
-/// scope.as_context_mut().gc(Some(&oom));
+/// scope.as_context_mut().gc(Some(&oom))?;
///
/// // Try again. If the GC heap is still out of memory, then we
/// // weren't able to free up resources for this allocation, so
@@ -283,11 +285,11 @@ impl ArrayRef {
/// error is returned. The allocation might succeed on a second attempt if
/// you drop some rooted GC references and try again.
///
- /// # Panics
+ /// If `store` is configured with a
+ /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error will
+ /// be returned because [`ArrayRef::new_async`] should be used instead.
///
- /// Panics if the `store` is configured for async; use
- /// [`ArrayRef::new_async`][crate::ArrayRef::new_async] to perform
- /// asynchronous allocation instead.
+ /// # Panics
///
/// Panics if either the allocator or the `elem` value is not associated
/// with the given store.
@@ -297,14 +299,17 @@ impl ArrayRef {
elem: &Val,
len: u32,
) -> Result<Rooted<ArrayRef>> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- assert!(!store.async_support());
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
vm::assert_ready(Self::_new_async(
store,
limiter.as_mut(),
allocator,
elem,
len,
+ Asyncness::No,
))
}
@@ -348,7 +353,15 @@ impl ArrayRef {
len: u32,
) -> Result<Rooted<ArrayRef>> {
let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- Self::_new_async(store, limiter.as_mut(), allocator, elem, len).await
+ Self::_new_async(
+ store,
+ limiter.as_mut(),
+ allocator,
+ elem,
+ len,
+ Asyncness::Yes,
+ )
+ .await
}
pub(crate) async fn _new_async(
@@ -357,9 +370,10 @@ impl ArrayRef {
allocator: &ArrayRefPre,
elem: &Val,
len: u32,
+ asyncness: Asyncness,
) -> Result<Rooted<ArrayRef>> {
store
- .retry_after_gc_async(limiter, (), |store, ()| {
+ .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
Self::new_from_iter(store, allocator, RepeatN(elem, len))
})
.await
@@ -440,11 +454,12 @@ impl ArrayRef {
/// error is returned. The allocation might succeed on a second attempt if
/// you drop some rooted GC references and try again.
///
- /// # Panics
+ /// If `store` is configured with a
+ /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error
+ /// will be returned because [`ArrayRef::new_fixed_async`] should be used
+ /// instead.
///
- /// Panics if the `store` is configured for async; use
- /// [`ArrayRef::new_fixed_async`][crate::ArrayRef::new_fixed_async] to
- /// perform asynchronous allocation instead.
+ /// # Panics
///
/// Panics if the allocator or any of the `elems` values are not associated
/// with the given store.
@@ -453,13 +468,16 @@ impl ArrayRef {
allocator: &ArrayRefPre,
elems: &[Val],
) -> Result<Rooted<ArrayRef>> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- assert!(!store.async_support());
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
vm::assert_ready(Self::_new_fixed_async(
store,
limiter.as_mut(),
allocator,
elems,
+ Asyncness::No,
))
}
@@ -505,7 +523,7 @@ impl ArrayRef {
elems: &[Val],
) -> Result<Rooted<ArrayRef>> {
let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- Self::_new_fixed_async(store, limiter.as_mut(), allocator, elems).await
+ Self::_new_fixed_async(store, limiter.as_mut(), allocator, elems, Asyncness::Yes).await
}
pub(crate) async fn _new_fixed_async(
@@ -513,9 +531,10 @@ impl ArrayRef {
limiter: Option<&mut StoreResourceLimiter<'_>>,
allocator: &ArrayRefPre,
elems: &[Val],
+ asyncness: Asyncness,
) -> Result<Rooted<ArrayRef>> {
store
- .retry_after_gc_async(limiter, (), |store, ()| {
+ .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
Self::new_from_iter(store, allocator, elems.iter())
})
.await
diff --git a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs b/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
index 5ada1f06d2..91ac8ad54b 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/exnref.rs
@@ -1,7 +1,9 @@
//! Implementation of `exnref` in Wasmtime.
-use crate::runtime::vm::{VMGcRef, VMStore};
-use crate::store::{StoreId, StoreResourceLimiter};
+use crate::runtime::vm::VMGcRef;
+use crate::store::{Asyncness, StoreId, StoreResourceLimiter};
+#[cfg(feature = "async")]
+use crate::vm::VMStore;
use crate::vm::{self, VMExnRef, VMGcHeader};
use crate::{
AsContext, AsContextMut, GcRefImpl, GcRootIndex, HeapType, OwnedRooted, RefType, Result,
@@ -191,11 +193,11 @@ impl ExnRef {
/// error is returned. The allocation might succeed on a second attempt if
/// you drop some rooted GC references and try again.
///
- /// # Panics
+ /// If `store` is configured with a
+ /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error
+ /// will be returned because [`ExnRef::new_async`] should be used instead.
///
- /// Panics if your engine is configured for async; use
- /// [`ExnRef::new_async`][crate::ExnRef::new_async] to perform
- /// synchronous allocation instead.
+ /// # Panics
///
/// Panics if the allocator, or any of the field values, is not associated
/// with the given store.
@@ -205,14 +207,17 @@ impl ExnRef {
tag: &Tag,
fields: &[Val],
) -> Result<Rooted<ExnRef>> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- assert!(!store.async_support());
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
vm::assert_ready(Self::_new_async(
store,
limiter.as_mut(),
allocator,
tag,
fields,
+ Asyncness::No,
))
}
@@ -238,10 +243,6 @@ impl ExnRef {
///
/// # Panics
///
- /// Panics if your engine is not configured for async; use
- /// [`ExnRef::new`][crate::ExnRef::new] to perform synchronous
- /// allocation instead.
- ///
/// Panics if the allocator, or any of the field values, is not associated
/// with the given store.
#[cfg(feature = "async")]
@@ -252,7 +253,15 @@ impl ExnRef {
fields: &[Val],
) -> Result<Rooted<ExnRef>> {
let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- Self::_new_async(store, limiter.as_mut(), allocator, tag, fields).await
+ Self::_new_async(
+ store,
+ limiter.as_mut(),
+ allocator,
+ tag,
+ fields,
+ Asyncness::Yes,
+ )
+ .await
}
pub(crate) async fn _new_async(
@@ -261,10 +270,11 @@ impl ExnRef {
allocator: &ExnRefPre,
tag: &Tag,
fields: &[Val],
+ asyncness: Asyncness,
) -> Result<Rooted<ExnRef>> {
Self::type_check_tag_and_fields(store, allocator, tag, fields)?;
store
- .retry_after_gc_async(limiter, (), |store, ()| {
+ .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
Self::new_unchecked(store, allocator, tag, fields)
})
.await
diff --git a/crates/wasmtime/src/runtime/gc/enabled/externref.rs b/crates/wasmtime/src/runtime/gc/enabled/externref.rs
index 1d2195de48..17788ca4e2 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/externref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/externref.rs
@@ -2,7 +2,10 @@
use super::{AnyRef, RootedGcRefImpl};
use crate::prelude::*;
-use crate::runtime::vm::{self, VMGcRef, VMStore};
+use crate::runtime::vm::{self, VMGcRef};
+use crate::store::Asyncness;
+#[cfg(feature = "async")]
+use crate::vm::VMStore;
use crate::{
AsContextMut, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType, OwnedRooted, RefType,
Result, Rooted, StoreContext, StoreContextMut, ValRaw, ValType, WasmTy,
@@ -149,7 +152,9 @@ impl ExternRef {
///
/// If the GC heap is at capacity, and there isn't room for allocating a new
/// `externref`, this method will automatically trigger a synchronous
- /// collection in an attempt to free up space in the GC heap.
+ /// collection in an attempt to free up space in the GC heap. Note that
+ /// [`ExternRef::new_async`] will perform an async GC if a synchronous GC is
+ /// not desired.
///
/// # Errors
///
@@ -164,6 +169,10 @@ impl ExternRef {
/// `externref` again after dropping rooted GC references and then
/// performing a collection or otherwise do with it whatever you see fit.
///
+ /// If `store` is configured with a
+ /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error will
+ /// be returned because [`ExternRef::new_async`] should be used instead.
+ ///
/// # Example
///
/// ```
@@ -204,19 +213,20 @@ impl ExternRef {
/// # Ok(())
/// # }
/// ```
- ///
- /// # Panics
- ///
- /// Panics if the `context` is configured for async; use
- /// [`ExternRef::new_async`][crate::ExternRef::new_async] to perform
- /// asynchronous allocation instead.
pub fn new<T>(mut store: impl AsContextMut, value: T) -> Result<Rooted<ExternRef>>
where
T: 'static + Any + Send + Sync,
{
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- assert!(!store.async_support());
- vm::assert_ready(Self::_new_async(store, limiter.as_mut(), value))
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(Self::_new_async(
+ store,
+ limiter.as_mut(),
+ value,
+ Asyncness::No,
+ ))
}
/// Asynchronously allocates a new `ExternRef` wrapping the given value.
@@ -300,13 +310,14 @@ impl ExternRef {
T: 'static + Any + Send + Sync,
{
let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- Self::_new_async(store, limiter.as_mut(), value).await
+ Self::_new_async(store, limiter.as_mut(), value, Asyncness::Yes).await
}
pub(crate) async fn _new_async<T>(
store: &mut StoreOpaque,
limiter: Option<&mut StoreResourceLimiter<'_>>,
value: T,
+ asyncness: Asyncness,
) -> Result<Rooted<ExternRef>>
where
T: 'static + Any + Send + Sync,
@@ -316,7 +327,7 @@ impl ExternRef {
let value: Box<dyn Any + Send + Sync> = Box::new(value);
let gc_ref = store
- .retry_after_gc_async(limiter, value, |store, value| {
+ .retry_after_gc_async(limiter, value, asyncness, |store, value| {
store
.require_gc_store_mut()?
.alloc_externref(value)
diff --git a/crates/wasmtime/src/runtime/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/gc/enabled/structref.rs
index b348338e61..144fd31355 100644
--- a/crates/wasmtime/src/runtime/gc/enabled/structref.rs
+++ b/crates/wasmtime/src/runtime/gc/enabled/structref.rs
@@ -1,8 +1,10 @@
//! Working with GC `struct` objects.
use crate::runtime::vm::VMGcRef;
-use crate::store::StoreId;
-use crate::vm::{self, VMGcHeader, VMStore, VMStructRef};
+use crate::store::{Asyncness, StoreId};
+#[cfg(feature = "async")]
+use crate::vm::VMStore;
+use crate::vm::{self, VMGcHeader, VMStructRef};
use crate::{AnyRef, FieldType};
use crate::{
AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType,
@@ -218,11 +220,12 @@ impl StructRef {
/// error is returned. The allocation might succeed on a second attempt if
/// you drop some rooted GC references and try again.
///
- /// # Panics
+ /// If `store` is configured with a
+ /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error
+ /// will be returned because [`StructRef::new_async`] should be used
+ /// instead.
///
- /// Panics if your engine is configured for async; use
- /// [`StructRef::new_async`][crate::StructRef::new_async] to perform
- /// synchronous allocation instead.
+ /// # Panics
///
/// Panics if the allocator, or any of the field values, is not associated
/// with the given store.
@@ -231,9 +234,17 @@ impl StructRef {
allocator: &StructRefPre,
fields: &[Val],
) -> Result<Rooted<StructRef>> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- assert!(!store.async_support());
- vm::assert_ready(Self::_new_async(store, limiter.as_mut(), allocator, fields))
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(Self::_new_async(
+ store,
+ limiter.as_mut(),
+ allocator,
+ fields,
+ Asyncness::No,
+ ))
}
/// Asynchronously allocate a new `struct` and get a reference to it.
@@ -265,7 +276,7 @@ impl StructRef {
fields: &[Val],
) -> Result<Rooted<StructRef>> {
let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- Self::_new_async(store, limiter.as_mut(), allocator, fields).await
+ Self::_new_async(store, limiter.as_mut(), allocator, fields, Asyncness::Yes).await
}
pub(crate) async fn _new_async(
@@ -273,10 +284,11 @@ impl StructRef {
limiter: Option<&mut StoreResourceLimiter<'_>>,
allocator: &StructRefPre,
fields: &[Val],
+ asyncness: Asyncness,
) -> Result<Rooted<StructRef>> {
Self::type_check_fields(store, allocator, fields)?;
store
- .retry_after_gc_async(limiter, (), |store, ()| {
+ .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
Self::new_unchecked(store, allocator, fields)
})
.await
diff --git a/crates/wasmtime/src/runtime/instance.rs b/crates/wasmtime/src/runtime/instance.rs
index 50b1073c64..2a55d96234 100644
--- a/crates/wasmtime/src/runtime/instance.rs
+++ b/crates/wasmtime/src/runtime/instance.rs
@@ -5,7 +5,7 @@ use crate::runtime::vm::{
VMStore, VMTableImport, VMTagImport,
};
use crate::store::{
- AllocateInstanceKind, InstanceId, StoreInstanceId, StoreOpaque, StoreResourceLimiter,
+ AllocateInstanceKind, Asyncness, InstanceId, StoreInstanceId, StoreOpaque, StoreResourceLimiter,
};
use crate::types::matching;
use crate::{
@@ -93,6 +93,8 @@ impl Instance {
/// [`ExternType`] entry that it maps to.
/// * The `start` function in the instance, if present, traps.
/// * Module/instance resource limits are exceeded.
+ /// * The `store` provided requires the use of [`Instance::new_async`]
+ /// instead, such as if epochs or fuel are configured.
///
/// When instantiation fails it's recommended to inspect the return value to
/// see why it failed, or bubble it upwards. If you'd like to specifically
@@ -103,9 +105,8 @@ impl Instance {
///
/// # Panics
///
- /// This function will panic if called with a store associated with a
- /// [`asynchronous config`](crate::Config::async_support). This function
- /// will also panic if any [`Extern`] supplied is not owned by `store`.
+ /// This function will panic if any [`Extern`] supplied is not owned by
+ /// `store`.
///
/// [inst]: https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation
/// [`ExternType`]: crate::ExternType
@@ -115,12 +116,14 @@ impl Instance {
imports: &[Extern],
) -> Result<Instance> {
let mut store = store.as_context_mut();
+ store.0.validate_sync_call()?;
let imports = Instance::typecheck_externs(store.0, module, imports)?;
// Note that the unsafety here should be satisfied by the call to
// `typecheck_externs` above which satisfies the condition that all
// the imports are valid for this module.
- assert!(!store.0.async_support());
- vm::assert_ready(unsafe { Instance::new_started(&mut store, module, imports.as_ref()) })
+ vm::assert_ready(unsafe {
+ Instance::new_started(&mut store, module, imports.as_ref(), Asyncness::No)
+ })
}
/// Same as [`Instance::new`], except for usage in [asynchronous stores].
@@ -133,12 +136,7 @@ impl Instance {
///
/// # Panics
///
- /// This function will panic if called with a store associated with a
- /// [`synchronous config`](crate::Config::new). This is only compatible with
- /// stores associated with an [`asynchronous
- /// config`](crate::Config::async_support).
- ///
- /// This function will also panic, like [`Instance::new`], if any [`Extern`]
+ /// This function will panic, like [`Instance::new`], if any [`Extern`]
/// specified does not belong to `store`.
///
/// # Examples
@@ -146,13 +144,11 @@ impl Instance {
/// An example of using this function:
///
/// ```
- /// use wasmtime::{Result, Store, Engine, Config, Module, Instance};
+ /// use wasmtime::{Result, Store, Engine, Module, Instance};
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
- /// let mut config = Config::new();
- /// config.async_support(true);
- /// let engine = Engine::new(&config)?;
+ /// let engine = Engine::default();
///
/// // For this example, a module with no imports is being used hence
/// // the empty array to `Instance::new_async`.
@@ -171,14 +167,12 @@ impl Instance {
/// compile for example:
///
/// ```compile_fail
- /// use wasmtime::{Result, Store, Engine, Config, Module, Instance};
+ /// use wasmtime::{Result, Store, Engine, Module, Instance};
/// use std::rc::Rc;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
- /// let mut config = Config::new();
- /// config.async_support(true);
- /// let engine = Engine::new(&config)?;
+ /// let engine = Engine::default();
///
/// let module = Module::new(&engine, "(module)")?;
///
@@ -203,7 +197,7 @@ impl Instance {
let mut store = store.as_context_mut();
let imports = Instance::typecheck_externs(store.0, module, imports)?;
// See `new` for notes on this unsafety
- unsafe { Instance::new_started(&mut store, module, imports.as_ref()).await }
+ unsafe { Instance::new_started(&mut store, module, imports.as_ref(), Asyncness::Yes).await }
}
fn typecheck_externs(
@@ -249,15 +243,18 @@ impl Instance {
store: &mut StoreContextMut<'_, T>,
module: &Module,
imports: Imports<'_>,
+ asyncness: Asyncness,
) -> Result<Instance> {
let (instance, start) = {
let (mut limiter, store) = store.0.resource_limiter_and_store_opaque();
// SAFETY: the safety contract of `new_raw` is the same as this
// function.
- unsafe { Instance::new_raw(store, limiter.as_mut(), module, imports).await? }
+ unsafe { Instance::new_raw(store, limiter.as_mut(), module, imports, asyncness).await? }
};
if let Some(start) = start {
- if store.0.async_support() {
+ if asyncness == Asyncness::No {
+ instance.start_raw(store, start)?;
+ } else {
#[cfg(feature = "async")]
{
store
@@ -266,8 +263,6 @@ impl Instance {
}
#[cfg(not(feature = "async"))]
unreachable!();
- } else {
- instance.start_raw(store, start)?;
}
}
Ok(instance)
@@ -293,6 +288,7 @@ impl Instance {
mut limiter: Option<&mut StoreResourceLimiter<'_>>,
module: &Module,
imports: Imports<'_>,
+ asyncness: Asyncness,
) -> Result<(Instance, Option<FuncIndex>)> {
if !Engine::same(store.engine(), module.engine()) {
bail!("cross-`Engine` instantiation is not currently supported");
@@ -356,7 +352,15 @@ impl Instance {
.features()
.contains(WasmFeatures::BULK_MEMORY);
- vm::initialize_instance(store, limiter, id, compiled_module.module(), bulk_memory).await?;
+ vm::initialize_instance(
+ store,
+ limiter,
+ id,
+ compiled_module.module(),
+ bulk_memory,
+ asyncness,
+ )
+ .await?;
Ok((instance, compiled_module.module().start_func))
}
@@ -784,6 +788,12 @@ pub struct InstancePre<T> {
/// This is an `Arc<[T]>` for the same reason as `items`.
func_refs: Arc<[VMFuncRef]>,
+ /// Whether or not any import in `items` is flagged as needing async.
+ ///
+ /// This is used to update stores during instantiation as to whether they
+ /// require async entrypoints.
+ asyncness: Asyncness,
+
_marker: core::marker::PhantomData<fn() -> T>,
}
@@ -795,6 +805,7 @@ impl<T> Clone for InstancePre<T> {
items: self.items.clone(),
host_funcs: self.host_funcs,
func_refs: self.func_refs.clone(),
+ asyncness: self.asyncness,
_marker: self._marker,
}
}
@@ -814,6 +825,7 @@ impl<T: 'static> InstancePre<T> {
let mut func_refs = vec![];
let mut host_funcs = 0;
+ let mut asyncness = Asyncness::No;
for item in &items {
match item {
Definition::Extern(_, _) => {}
@@ -827,6 +839,7 @@ impl<T: 'static> InstancePre<T> {
..*f.func_ref()
});
}
+ asyncness = asyncness | f.asyncness();
}
}
}
@@ -836,6 +849,7 @@ impl<T: 'static> InstancePre<T> {
items: items.into(),
host_funcs,
func_refs: func_refs.into(),
+ asyncness,
_marker: core::marker::PhantomData,
})
}
@@ -869,14 +883,20 @@ impl<T: 'static> InstancePre<T> {
&self.items,
self.host_funcs,
&self.func_refs,
+ self.asyncness,
)?;
+ // Note that this is specifically done after `pre_instantiate_raw` to
+ // handle the case that if any imports in this `InstancePre` require
+ // async that it's flagged in the store by that point which will reject
+ // this instantiation to say "use `instantiate_async` instead".
+ store.0.validate_sync_call()?;
+
// This unsafety should be handled by the type-checking performed by the
// constructor of `InstancePre` to assert that all the imports we're passing
// in match the module we're instantiating.
- assert!(!store.0.async_support());
vm::assert_ready(unsafe {
- Instance::new_started(&mut store, &self.module, imports.as_ref())
+ Instance::new_started(&mut store, &self.module, imports.as_ref(), Asyncness::No)
})
}
@@ -902,12 +922,15 @@ impl<T: 'static> InstancePre<T> {
&self.items,
self.host_funcs,
&self.func_refs,
+ self.asyncness,
)?;
// This unsafety should be handled by the type-checking performed by the
// constructor of `InstancePre` to assert that all the imports we're passing
// in match the module we're instantiating.
- unsafe { Instance::new_started(&mut store, &self.module, imports.as_ref()).await }
+ unsafe {
+ Instance::new_started(&mut store, &self.module, imports.as_ref(), Asyncness::Yes).await
+ }
}
}
@@ -923,6 +946,7 @@ fn pre_instantiate_raw(
items: &Arc<[Definition]>,
host_funcs: usize,
func_refs: &Arc<[VMFuncRef]>,
+ asyncness: Asyncness,
) -> Result<OwnedImports> {
// Register this module and use it to fill out any funcref wasm_call holes
// we can. For more comments on this see `typecheck_externs`.
@@ -945,6 +969,8 @@ fn pre_instantiate_raw(
funcrefs.push_instance_pre_func_refs(func_refs.clone());
}
+ store.set_async_required(asyncness);
+
let mut func_refs = func_refs.iter().map(|f| NonNull::from(f));
let mut imports = OwnedImports::new(module);
for import in items.iter() {
diff --git a/crates/wasmtime/src/runtime/limits.rs b/crates/wasmtime/src/runtime/limits.rs
index 657f7f96ad..41a40b6529 100644
--- a/crates/wasmtime/src/runtime/limits.rs
+++ b/crates/wasmtime/src/runtime/limits.rs
@@ -157,9 +157,7 @@ pub trait ResourceLimiter: Send {
/// asynchronously if necessary.
///
/// This trait is identical to [`ResourceLimiter`], except that the
-/// `memory_growing` and `table_growing` functions are `async`. Must be used
-/// with an async [`Store`](`crate::Store`) configured via
-/// [`Config::async_support`](crate::Config::async_support).
+/// `memory_growing` and `table_growing` functions are `async`.
///
/// This trait is used with
/// [`Store::limiter_async`](`crate::Store::limiter_async`)`: see those docs
diff --git a/crates/wasmtime/src/runtime/linker.rs b/crates/wasmtime/src/runtime/linker.rs
index 692dfc29ab..1376b83b44 100644
--- a/crates/wasmtime/src/runtime/linker.rs
+++ b/crates/wasmtime/src/runtime/linker.rs
@@ -447,9 +447,6 @@ impl<T> Linker<T> {
///
/// This method panics in the following situations:
///
- /// * This linker is not associated with an [async
- /// config](crate::Config::async_support).
- ///
/// * If the given function type is not associated with the same engine as
/// this linker.
#[cfg(feature = "async")]
@@ -471,10 +468,6 @@ impl<T> Linker<T> {
+ 'static,
T: Send + 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_new_async` without enabling async support in the config"
- );
self.func_insert(module, name, HostFunc::new_async(&self.engine, ty, func))
}
@@ -561,10 +554,6 @@ impl<T> Linker<T> {
+ 'static,
T: Send + 'static,
{
- assert!(
- self.engine.config().async_support,
- "cannot use `func_wrap_async` without enabling async support on the config",
- );
self.func_insert(module, name, HostFunc::wrap_async(&self.engine, func))
}
diff --git a/crates/wasmtime/src/runtime/memory.rs b/crates/wasmtime/src/runtime/memory.rs
index 64f4897a00..1a93a583b6 100644
--- a/crates/wasmtime/src/runtime/memory.rs
+++ b/crates/wasmtime/src/runtime/memory.rs
@@ -1,8 +1,10 @@
use crate::Trap;
use crate::prelude::*;
-use crate::runtime::vm::{self, ExportMemory, VMStore};
+use crate::runtime::vm::{self, ExportMemory};
use crate::store::{StoreInstanceId, StoreOpaque, StoreResourceLimiter};
use crate::trampoline::generate_memory_export;
+#[cfg(feature = "async")]
+use crate::vm::VMStore;
use crate::{AsContext, AsContextMut, Engine, MemoryType, StoreContext, StoreContextMut};
use core::cell::UnsafeCell;
use core::fmt;
@@ -259,9 +261,11 @@ impl Memory {
/// # }
/// ```
pub fn new(mut store: impl AsContextMut, ty: MemoryType) -> Result<Memory> {
- let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
- vm::one_poll(Self::_new(store, limiter.as_mut(), ty))
- .expect("must use `new_async` when async resource limiters are in use")
+ let (mut limiter, store) = store
+ .as_context_mut()
+ .0
+ .validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(Self::_new(store, limiter.as_mut(), ty))
}
/// Async variant of [`Memory::new`]. You must use this variant with
@@ -573,15 +577,15 @@ impl Memory {
/// [`ResourceLimiter`](crate::ResourceLimiter) is another example of
/// preventing a memory to grow.
///
+ /// This function will return an error if the [`Store`](`crate::Store`) has
+ /// a [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
+ /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an
+ /// async resource limiter, use [`Memory::grow_async`] instead.
+ ///
/// # Panics
///
/// Panics if this memory doesn't belong to `store`.
///
- /// This function will panic if the [`Store`](`crate::Store`) has a
- /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
- /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an
- /// async resource limiter, use [`Memory::grow_async`] instead.
- ///
/// # Examples
///
/// ```
@@ -604,9 +608,8 @@ impl Memory {
/// ```
pub fn grow(&self, mut store: impl AsContextMut, delta: u64) -> Result<u64> {
let store = store.as_context_mut().0;
- let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- vm::one_poll(self._grow(store, limiter.as_mut(), delta))
- .expect("must use `grow_async` if an async resource limiter is used")
+ let (mut limiter, store) = store.validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(self._grow(store, limiter.as_mut(), delta))
}
/// Async variant of [`Memory::grow`]. Required when using a
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index 1be1b73ea2..4671bc8f7b 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -400,13 +400,19 @@ pub enum UpdateDeadline {
/// Extend the deadline by the specified number of ticks.
Continue(u64),
/// Extend the deadline by the specified number of ticks after yielding to
- /// the async executor loop. This can only be used with an async [`Store`]
- /// configured via [`Config::async_support`](crate::Config::async_support).
+ /// the async executor loop.
+ ///
+ /// This can only be used when WebAssembly is invoked with `*_async`
+ /// methods. If WebAssembly was invoked with a synchronous method then
+ /// returning this variant will raise a trap.
#[cfg(feature = "async")]
Yield(u64),
/// Extend the deadline by the specified number of ticks after yielding to
- /// the async executor loop. This can only be used with an async [`Store`]
- /// configured via [`Config::async_support`](crate::Config::async_support).
+ /// the async executor loop.
+ ///
+ /// This can only be used when WebAssembly is invoked with `*_async`
+ /// methods. If WebAssembly was invoked with a synchronous method then
+ /// returning this variant will raise a trap.
///
/// The yield will be performed by the future provided; when using `tokio`
/// it is recommended to provide [`tokio::task::yield_now`](https://docs.rs/tokio/latest/tokio/task/fn.yield_now.html)
@@ -1011,9 +1017,13 @@ impl<T> Store<T> {
/// GC heap for that allocation, so that it will succeed on the next
/// attempt.
///
- /// This method is only available when the `gc` Cargo feature is enabled.
+ /// # Errors
+ ///
+ /// This method will fail if an [async limiter is
+ /// configured](Store::limiter_async) in which case [`Store::gc_async`] must
+ /// be used instead.
#[cfg(feature = "gc")]
- pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) {
+ pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
StoreContextMut(&mut self.inner).gc(why)
}
@@ -1056,10 +1066,10 @@ impl<T> Store<T> {
///
/// When a [`Store`] is configured to consume fuel with
/// [`Config::consume_fuel`](crate::Config::consume_fuel) this method will
- /// configure WebAssembly to be suspended and control will be yielded back to the
- /// caller every `interval` units of fuel consumed. This is only suitable with use of
- /// a store associated with an [async config](crate::Config::async_support) because
- /// only then are futures used and yields are possible.
+ /// configure WebAssembly to be suspended and control will be yielded back
+ /// to the caller every `interval` units of fuel consumed. When using this
+ /// method it requires further invocations of WebAssembly to use `*_async`
+ /// entrypoints.
///
/// The purpose of this behavior is to ensure that futures which represent
/// execution of WebAssembly do not execute too long inside their
@@ -1077,8 +1087,9 @@ impl<T> Store<T> {
///
/// # Error
///
- /// This method will error if it is not called on a store associated with an [async
- /// config](crate::Config::async_support).
+ /// This method will error if fuel is not enabled or `interval` is
+ /// `Some(0)`.
+ #[cfg(feature = "async")]
pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
self.inner.fuel_async_yield_interval(interval)
}
@@ -1293,8 +1304,6 @@ impl<T> Store<T> {
///
/// # Panics
///
- /// - Will panic if this store is not configured for async
- /// support.
/// - Will panic if guest-debug support was not enabled via
/// [`crate::Config::guest_debug`].
#[cfg(feature = "debug")]
@@ -1313,10 +1322,9 @@ impl<T> Store<T> {
// be a `Store<T> where T: Send`.
T: Send,
{
- assert!(
- self.inner.async_support(),
- "debug hooks rely on async support"
- );
+ // Debug hooks rely on async support, so async entrypoints are required.
+ self.inner.set_async_required(Asyncness::Yes);
+
assert!(
self.engine().tunables().debug_guest,
"debug hooks require guest debugging to be enabled"
@@ -1333,10 +1341,6 @@ impl<T> Store<T> {
}
impl<'a, T> StoreContext<'a, T> {
- pub(crate) fn async_support(&self) -> bool {
- self.0.async_support()
- }
-
/// Returns the underlying [`Engine`] this store is connected to.
pub fn engine(&self) -> &Engine {
self.0.engine()
@@ -1380,13 +1384,16 @@ impl<'a, T> StoreContextMut<'a, T> {
/// Perform garbage collection of `ExternRef`s.
///
/// Same as [`Store::gc`].
- ///
- /// This method is only available when the `gc` Cargo feature is enabled.
#[cfg(feature = "gc")]
- pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) {
- assert!(!self.0.async_support());
- let (mut limiter, store) = self.0.resource_limiter_and_store_opaque();
- vm::assert_ready(store.gc(limiter.as_mut(), None, why.map(|e| e.bytes_needed())));
+ pub fn gc(&mut self, why: Option<&crate::GcHeapOutOfMemory<()>>) -> Result<()> {
+ let (mut limiter, store) = self.0.validate_sync_resource_limiter_and_store_opaque()?;
+ vm::assert_ready(store.gc(
+ limiter.as_mut(),
+ None,
+ why.map(|e| e.bytes_needed()),
+ Asyncness::No,
+ ));
+ Ok(())
}
/// Returns remaining fuel in this store.
@@ -1406,6 +1413,7 @@ impl<'a, T> StoreContextMut<'a, T> {
/// Configures this `Store` to periodically yield while executing futures.
///
/// For more information see [`Store::fuel_async_yield_interval`]
+ #[cfg(feature = "async")]
pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
self.0.fuel_async_yield_interval(interval)
}
@@ -1559,6 +1567,24 @@ impl<T> StoreInner<T> {
fn flush_fiber_stack(&mut self) {
// noop shim so code can assume this always exists.
}
+
+ /// Splits this `StoreInner<T>` into a `limiter`/`StoerOpaque` borrow while
+ /// validating that an async limiter is not configured.
+ ///
+ /// This is used for sync entrypoints which need to fail if an async limiter
+ /// is configured as otherwise the async entrypoint must be used instead.
+ pub(crate) fn validate_sync_resource_limiter_and_store_opaque(
+ &mut self,
+ ) -> Result<(Option<StoreResourceLimiter<'_>>, &mut StoreOpaque)> {
+ let (limiter, store) = self.resource_limiter_and_store_opaque();
+ if !matches!(limiter, None | Some(StoreResourceLimiter::Sync(_))) {
+ bail!(
+ "when using an async resource limiter `*_async` functions must \
+ be used instead"
+ );
+ }
+ Ok((limiter, store))
+ }
}
fn get_fuel(injected_fuel: i64, fuel_reserve: u64) -> u64 {
@@ -1632,11 +1658,6 @@ impl StoreOpaque {
Ok(())
}
- #[inline]
- pub fn async_support(&self) -> bool {
- cfg!(feature = "async") && self.engine().config().async_support
- }
-
#[inline]
pub fn engine(&self) -> &Engine {
&self.engine
@@ -2051,7 +2072,7 @@ impl StoreOpaque {
}
#[cfg(feature = "gc")]
- async fn do_gc(&mut self) {
+ async fn do_gc(&mut self, asyncness: Asyncness) {
// If the GC heap hasn't been initialized, there is nothing to collect.
if self.gc_store.is_none() {
return;
@@ -2063,10 +2084,9 @@ impl StoreOpaque {
// call mutable methods on `self`.
let mut roots = core::mem::take(&mut self.gc_roots_list);
- self.trace_roots(&mut roots).await;
- let async_yield = self.async_support();
+ self.trace_roots(&mut roots, asyncness).await;
self.unwrap_gc_store_mut()
- .gc(async_yield, unsafe { roots.iter() })
+ .gc(asyncness, unsafe { roots.iter() })
.await;
// Restore the GC roots for the next GC.
@@ -2077,28 +2097,25 @@ impl StoreOpaque {
}
#[cfg(feature = "gc")]
- async fn trace_roots(&mut self, gc_roots_list: &mut GcRootsList) {
+ async fn trace_roots(&mut self, gc_roots_list: &mut GcRootsList, asyncness: Asyncness) {
log::trace!("Begin trace GC roots");
// We shouldn't have any leftover, stale GC roots.
assert!(gc_roots_list.is_empty());
self.trace_wasm_stack_roots(gc_roots_list);
- #[cfg(feature = "async")]
- if self.async_support() {
+ if asyncness != Asyncness::No {
vm::Yield::new().await;
}
#[cfg(feature = "stack-switching")]
{
self.trace_wasm_continuation_roots(gc_roots_list);
- #[cfg(feature = "async")]
- if self.async_support() {
+ if asyncness != Asyncness::No {
vm::Yield::new().await;
}
}
self.trace_vmctx_roots(gc_roots_list);
- #[cfg(feature = "async")]
- if self.async_support() {
+ if asyncness != Asyncness::No {
vm::Yield::new().await;
}
self.trace_user_roots(gc_roots_list);
@@ -2326,19 +2343,21 @@ impl StoreOpaque {
Ok(())
}
+ #[cfg(feature = "async")]
pub fn fuel_async_yield_interval(&mut self, interval: Option<u64>) -> Result<()> {
crate::ensure!(
self.engine().tunables().consume_fuel,
"fuel is not configured in this store"
);
- crate::ensure!(
- self.engine().config().async_support,
- "async support is not configured in this store"
- );
crate::ensure!(
interval != Some(0),
"fuel_async_yield_interval must not be 0"
);
+
+ // All future entrypoints must be async to handle the case that fuel
+ // runs out and an async yield is needed.
+ self.set_async_required(Asyncness::Yes);
+
self.fuel_yield_interval = interval.and_then(|i| NonZeroU64::new(i));
// Reset the fuel active + reserve states by resetting the amount.
self.set_fuel(self.get_fuel()?)
@@ -2777,6 +2796,33 @@ at https://bytecodealliance.org/security.
pub(crate) fn get_epoch_deadline(&mut self) -> u64 {
*self.vm_store_context.epoch_deadline.get_mut()
}
+
+ #[inline]
+ pub(crate) fn validate_sync_call(&self) -> Result<()> {
+ #[cfg(feature = "async")]
+ if self.async_state.async_required {
+ bail!("store configuration requires that `*_async` functions are used instead");
+ }
+ Ok(())
+ }
+
+ /// Returns whether this store is presently on a fiber and is allowed to
+ /// block via `block_on` with fibers.
+ pub(crate) fn can_block(&mut self) -> bool {
+ #[cfg(feature = "async")]
+ if true {
+ return self.fiber_async_state_mut().can_block();
+ }
+
+ false
+ }
+
+ #[cfg(not(feature = "async"))]
+ pub(crate) fn set_async_required(&mut self, asyncness: Asyncness) {
+ match asyncness {
+ Asyncness::No => {}
+ }
+ }
}
/// Helper parameter to [`StoreOpaque::allocate_instance`].
@@ -2986,6 +3032,46 @@ impl<T: AsStoreOpaque + ?Sized> AsStoreOpaque for &mut T {
}
}
+/// Helper enum to indicate, in some function contexts, whether `async` should
+/// be taken advantage of or not.
+///
+/// This is used throughout Wasmtime where internal functions are all `async`
+/// but external functions might be either sync or `async`. If the external
+/// function is sync, then internally Wasmtime shouldn't yield as it won't do
+/// anything. If the external function is `async`, however, yields are fine.
+///
+/// An example of this is GC. Right now GC will cooperatively yield after phases
+/// of GC have passed, but this cooperative yielding is only enabled with
+/// `Asyncness::Yes`.
+///
+/// This enum is additionally conditionally defined such that `Yes` is only
+/// present in `async`-enabled builds. That ensures that this compiles down to a
+/// zero-sized type in `async`-disabled builds in case that interests embedders.
+#[derive(PartialEq, Eq, Copy, Clone)]
+pub enum Asyncness {
+ /// Don't do async things, don't yield, etc. It's ok to execute an `async`
+ /// function, but it should be validated ahead of time that when doing so a
+ /// yield isn't possible (e.g. `validate_sync_*` methods on Store.
+ No,
+
+ /// Async things is OK. This should only be used when the API entrypoint is
+ /// itself `async`.
+ #[cfg(feature = "async")]
+ Yes,
+}
+
+impl core::ops::BitOr for Asyncness {
+ type Output = Self;
+
+ fn bitor(self, rhs: Self) -> Self::Output {
+ match (self, rhs) {
+ (Asyncness::No, Asyncness::No) => Asyncness::No,
+ #[cfg(feature = "async")]
+ (Asyncness::Yes, _) | (_, Asyncness::Yes) => Asyncness::Yes,
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/wasmtime/src/runtime/store/async_.rs b/crates/wasmtime/src/runtime/store/async_.rs
index 93e3617501..c3e149f4ee 100644
--- a/crates/wasmtime/src/runtime/store/async_.rs
+++ b/crates/wasmtime/src/runtime/store/async_.rs
@@ -4,7 +4,7 @@ use crate::fiber::{self};
use crate::prelude::*;
#[cfg(feature = "gc")]
use crate::runtime::vm::VMStore;
-use crate::store::{ResourceLimiterInner, StoreInner, StoreOpaque};
+use crate::store::{Asyncness, ResourceLimiterInner, StoreInner, StoreOpaque};
use crate::{Store, StoreContextMut, UpdateDeadline};
/// An object that can take callbacks when the runtime enters or exits hostcalls.
@@ -37,9 +37,12 @@ impl<T> Store<T> {
///
/// Note that this limiter is only used to limit the creation/growth of
/// resources in the future, this does not retroactively attempt to apply
- /// limits to the [`Store`]. Additionally this must be used with an async
- /// [`Store`] configured via
- /// [`Config::async_support`](crate::Config::async_support).
+ /// limits to the [`Store`].
+ ///
+ /// After configuring this method it's required that synchronous APIs in
+ /// Wasmtime are no longer used, such as [`Func::call`](crate::Func::call).
+ /// Instead APIs such as [`Func::call_async`](crate::Func::call_async) must
+ /// be used instead.
pub fn limiter_async(
&mut self,
mut limiter: impl (FnMut(&mut T) -> &mut dyn crate::ResourceLimiterAsync)
@@ -47,7 +50,6 @@ impl<T> Store<T> {
+ Sync
+ 'static,
) {
- debug_assert!(self.inner.async_support());
// Apply the limits on instances, tables, and memory given by the limiter:
let inner = &mut self.inner;
let (instance_limit, table_limit, memory_limit) = {
@@ -61,6 +63,7 @@ impl<T> Store<T> {
// Save the limiter accessor function:
inner.limiter = Some(ResourceLimiterInner::Async(Box::new(limiter)));
+ inner.set_async_required(Asyncness::Yes);
}
/// Configures an async function that runs on calls and returns between
@@ -81,6 +84,7 @@ impl<T> Store<T> {
#[cfg(feature = "call-hook")]
pub fn call_hook_async(&mut self, hook: impl CallHookHandler<T> + Send + Sync + 'static) {
self.inner.call_hook = Some(crate::store::CallHookInner::Async(Box::new(hook)));
+ self.inner.set_async_required(Asyncness::Yes);
}
/// Perform garbage collection asynchronously.
@@ -140,7 +144,12 @@ impl<'a, T> StoreContextMut<'a, T> {
{
let (mut limiter, store) = self.0.resource_limiter_and_store_opaque();
store
- .gc(limiter.as_mut(), None, why.map(|e| e.bytes_needed()))
+ .gc(
+ limiter.as_mut(),
+ None,
+ why.map(|e| e.bytes_needed()),
+ crate::store::Asyncness::Yes,
+ )
.await;
}
@@ -158,10 +167,10 @@ impl<'a, T> StoreContextMut<'a, T> {
impl<T> StoreInner<T> {
#[cfg(target_has_atomic = "64")]
fn epoch_deadline_async_yield_and_update(&mut self, delta: u64) {
- assert!(
- self.async_support(),
- "cannot use `epoch_deadline_async_yield_and_update` without enabling async support in the config"
- );
+ // All future entrypoints must be async to handle the case that an epoch
+ // changes and a yield is required.
+ self.set_async_required(Asyncness::Yes);
+
self.epoch_deadline_behavior =
Some(Box::new(move |_store| Ok(UpdateDeadline::Yield(delta))));
}
diff --git a/crates/wasmtime/src/runtime/store/gc.rs b/crates/wasmtime/src/runtime/store/gc.rs
index 6232030bd1..10e1805d08 100644
--- a/crates/wasmtime/src/runtime/store/gc.rs
+++ b/crates/wasmtime/src/runtime/store/gc.rs
@@ -20,13 +20,16 @@ impl StoreOpaque {
limiter: Option<&mut StoreResourceLimiter<'_>>,
root: Option<VMGcRef>,
bytes_needed: Option<u64>,
+ asyncness: Asyncness,
) -> Option<VMGcRef> {
let mut scope = crate::OpaqueRootScope::new(self);
scope.trim_gc_liveness_flags(true);
let store_id = scope.id();
let root = root.map(|r| scope.gc_roots_mut().push_lifo_root(store_id, r));
- scope.grow_or_collect_gc_heap(limiter, bytes_needed).await;
+ scope
+ .grow_or_collect_gc_heap(limiter, bytes_needed, asyncness)
+ .await;
root.map(|r| {
let r = r
@@ -51,13 +54,14 @@ impl StoreOpaque {
&mut self,
limiter: Option<&mut StoreResourceLimiter<'_>>,
bytes_needed: Option<u64>,
+ asyncness: Asyncness,
) {
if let Some(n) = bytes_needed {
if self.grow_gc_heap(limiter, n).await.is_ok() {
return;
}
}
- self.do_gc().await;
+ self.do_gc(asyncness).await;
}
/// Attempt to grow the GC heap by `bytes_needed` bytes.
@@ -167,6 +171,7 @@ impl StoreOpaque {
&mut self,
mut limiter: Option<&mut StoreResourceLimiter<'_>>,
value: T,
+ asyncness: Asyncness,
alloc_func: impl Fn(&mut Self, T) -> Result<U>,
) -> Result<U>
where
@@ -178,7 +183,8 @@ impl StoreOpaque {
Err(e) => match e.downcast::<crate::GcHeapOutOfMemory<T>>() {
Ok(oom) => {
let (value, oom) = oom.take_inner();
- self.gc(limiter, None, Some(oom.bytes_needed())).await;
+ self.gc(limiter, None, Some(oom.bytes_needed()), asyncness)
+ .await;
alloc_func(self, value)
}
Err(e) => Err(e),
diff --git a/crates/wasmtime/src/runtime/vm.rs b/crates/wasmtime/src/runtime/vm.rs
index cbdfa25876..fd9ff41e58 100644
--- a/crates/wasmtime/src/runtime/vm.rs
+++ b/crates/wasmtime/src/runtime/vm.rs
@@ -150,9 +150,9 @@ mod cow_disabled;
#[cfg(has_virtual_memory)]
mod mmap;
-#[cfg(feature = "async")]
+#[cfg(any(feature = "async", feature = "gc"))]
mod async_yield;
-#[cfg(feature = "async")]
+#[cfg(any(feature = "async", feature = "gc"))]
pub use crate::runtime::vm::async_yield::*;
#[cfg(feature = "gc-null")]
@@ -459,12 +459,18 @@ impl fmt::Display for WasmFault {
/// Asserts that the future `f` is ready and returns its output.
///
-/// This function is intended to be used when `async_support` is verified as
-/// disabled. Internals of Wasmtime are generally `async` when they optionally
-/// can be, meaning that synchronous entrypoints will invoke this function
-/// after invoking the asynchronous internals. Due to `async_support` being
-/// disabled there should be no way to introduce a yield point meaning that all
-/// futures built from internal functions should always be ready.
+/// This function is intended to be used with `Store::validate_sync_call`.
+/// Internals of Wasmtime are generally `async` when they optionally can be,
+/// meaning that synchronous entrypoints will invoke this function after
+/// invoking the asynchronous internals. The `validate_sync_call` method
+/// ensures that during this `async` function call there won't actually be any
+/// yield points. If a yield point could possibly happen, then
+/// `validate_sync_call` will fail.
+///
+/// If `validate_sync_call` passes, then this function is an extra assert that
+/// yes, indeed, we coded everything correctly in Wasmtime and there shouldn't
+/// be any yield points in the future provided, so its result should be ready
+/// immediately.
///
/// # Panics
///
@@ -484,7 +490,7 @@ pub fn assert_ready<F: Future>(f: F) -> F::Output {
/// is available. If it isn't then `None` is returned and an appropriate panic
/// message should be generated recommending to use an async function (e.g.
/// `grow_async` instead of `grow`).
-pub fn one_poll<F: Future>(f: F) -> Option<F::Output> {
+fn one_poll<F: Future>(f: F) -> Option<F::Output> {
let mut context = Context::from_waker(&Waker::noop());
match pin!(f).poll(&mut context) {
Poll::Ready(output) => Some(output),
diff --git a/crates/wasmtime/src/runtime/vm/const_expr.rs b/crates/wasmtime/src/runtime/vm/const_expr.rs
index 006ed4d22b..f6eaa34589 100644
--- a/crates/wasmtime/src/runtime/vm/const_expr.rs
+++ b/crates/wasmtime/src/runtime/vm/const_expr.rs
@@ -2,7 +2,7 @@
use crate::prelude::*;
use crate::runtime::vm;
-use crate::store::{AutoAssertNoGc, InstanceId, StoreOpaque, StoreResourceLimiter};
+use crate::store::{Asyncness, AutoAssertNoGc, InstanceId, StoreOpaque, StoreResourceLimiter};
#[cfg(feature = "gc")]
use crate::{
AnyRef, ArrayRef, ArrayRefPre, ArrayType, ExternRef, I31, StructRef, StructRefPre, StructType,
@@ -33,12 +33,16 @@ impl Default for ConstExprEvaluator {
/// The context within which a particular const expression is evaluated.
pub struct ConstEvalContext {
pub(crate) instance: InstanceId,
+ pub(crate) asyncness: Asyncness,
}
impl ConstEvalContext {
/// Create a new context.
- pub fn new(instance: InstanceId) -> Self {
- Self { instance }
+ pub fn new(instance: InstanceId, asyncness: Asyncness) -> Self {
+ Self {
+ instance,
+ asyncness,
+ }
}
fn global_get(&mut self, store: &mut StoreOpaque, index: GlobalIndex) -> Result<Val> {
@@ -75,7 +79,8 @@ impl ConstEvalContext {
) -> Result<Val> {
let struct_ty = StructType::from_shared_type_index(store.engine(), shared_ty);
let allocator = StructRefPre::_new(store, struct_ty);
- let struct_ref = StructRef::_new_async(store, limiter, &allocator, &fields).await?;
+ let struct_ref =
+ StructRef::_new_async(store, limiter, &allocator, &fields, self.asyncness).await?;
Ok(Val::AnyRef(Some(struct_ref.into())))
}
@@ -202,9 +207,6 @@ impl ConstExprEvaluator {
fn return_one(&mut self, val: Val) -> &Val {
self.simple = val;
&self.simple
- // self.stack.clear();
- // self.stack.push(val);
- // &self.stack[0]
}
#[cold]
@@ -338,9 +340,15 @@ impl ConstExprEvaluator {
let elem = self.pop()?;
let pre = ArrayRefPre::_new(store, ty);
- let array =
- ArrayRef::_new_async(store, limiter.as_deref_mut(), &pre, &elem, len)
- .await?;
+ let array = ArrayRef::_new_async(
+ store,
+ limiter.as_deref_mut(),
+ &pre,
+ &elem,
+ len,
+ context.asyncness,
+ )
+ .await?;
self.stack.push(Val::AnyRef(Some(array.into())));
}
@@ -357,9 +365,15 @@ impl ConstExprEvaluator {
.expect("type should have a default value");
let pre = ArrayRefPre::_new(store, ty);
- let array =
- ArrayRef::_new_async(store, limiter.as_deref_mut(), &pre, &elem, len)
- .await?;
+ let array = ArrayRef::_new_async(
+ store,
+ limiter.as_deref_mut(),
+ &pre,
+ &elem,
+ len,
+ context.asyncness,
+ )
+ .await?;
self.stack.push(Val::AnyRef(Some(array.into())));
}
@@ -389,9 +403,14 @@ impl ConstExprEvaluator {
.collect::<smallvec::SmallVec<[_; 8]>>();
let pre = ArrayRefPre::_new(store, ty);
- let array =
- ArrayRef::_new_fixed_async(store, limiter.as_deref_mut(), &pre, &elems)
- .await?;
+ let array = ArrayRef::_new_fixed_async(
+ store,
+ limiter.as_deref_mut(),
+ &pre,
+ &elems,
+ context.asyncness,
+ )
+ .await?;
self.stack.push(Val::AnyRef(Some(array.into())));
}
diff --git a/crates/wasmtime/src/runtime/vm/gc.rs b/crates/wasmtime/src/runtime/vm/gc.rs
index dd21291735..6067b565d5 100644
--- a/crates/wasmtime/src/runtime/vm/gc.rs
+++ b/crates/wasmtime/src/runtime/vm/gc.rs
@@ -22,6 +22,7 @@ pub use i31::*;
use crate::prelude::*;
use crate::runtime::vm::{GcHeapAllocationIndex, VMMemoryDefinition};
+use crate::store::Asyncness;
use core::any::Any;
use core::mem::MaybeUninit;
use core::{alloc::Layout, num::NonZeroU32};
@@ -68,9 +69,9 @@ impl GcStore {
}
/// Asynchronously perform garbage collection within this heap.
- pub async fn gc(&mut self, async_yield: bool, roots: GcRootsIter<'_>) {
+ pub async fn gc(&mut self, asyncness: Asyncness, roots: GcRootsIter<'_>) {
let collection = self.gc_heap.gc(roots, &mut self.host_data_table);
- collect_async(collection, async_yield).await;
+ collect_async(collection, asyncness).await;
}
/// Get the kind of the given GC reference.
diff --git a/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs b/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
index 8147add1b6..2808b46fc8 100644
--- a/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
+++ b/crates/wasmtime/src/runtime/vm/gc/gc_runtime.rs
@@ -5,6 +5,7 @@ use crate::runtime::vm::{
ExternRefHostDataId, ExternRefHostDataTable, GcHeapObject, SendSyncPtr, TypedGcRef, VMArrayRef,
VMExternRef, VMGcHeader, VMGcObjectData, VMGcRef,
};
+use crate::store::Asyncness;
use crate::vm::VMMemoryDefinition;
use core::ptr::NonNull;
use core::slice;
@@ -747,12 +748,12 @@ pub enum GcProgress {
/// cooperatively yielding back to the event loop after each increment of work.
pub async fn collect_async<'a>(
mut collection: Box<dyn GarbageCollection<'a> + 'a>,
- async_yield: bool,
+ asyncness: Asyncness,
) {
loop {
match collection.collect_increment() {
GcProgress::Continue => {
- if async_yield {
+ if asyncness != Asyncness::No {
#[cfg(feature = "async")]
crate::runtime::vm::Yield::new().await
}
@@ -771,7 +772,7 @@ mod collect_async_tests {
fn _assert_send_sync<T: Send + Sync>(_: T) {}
fn _foo<'a>(collection: Box<dyn GarbageCollection<'a>>) {
- _assert_send_sync(collect_async(collection, true));
+ _assert_send_sync(collect_async(collection, Asyncness::Yes));
}
}
}
diff --git a/crates/wasmtime/src/runtime/vm/instance.rs b/crates/wasmtime/src/runtime/vm/instance.rs
index 73905b2879..ebf0982ce5 100644
--- a/crates/wasmtime/src/runtime/vm/instance.rs
+++ b/crates/wasmtime/src/runtime/vm/instance.rs
@@ -19,7 +19,9 @@ use crate::runtime::vm::{
GcStore, HostResult, Imports, ModuleRuntimeInfo, SendSyncPtr, VMGlobalKind, VMStore,
VMStoreRawPtr, VmPtr, VmSafe, WasmFault, catch_unwind_and_record_trap,
};
-use crate::store::{InstanceId, StoreId, StoreInstanceId, StoreOpaque, StoreResourceLimiter};
+use crate::store::{
+ Asyncness, InstanceId, StoreId, StoreInstanceId, StoreOpaque, StoreResourceLimiter,
+};
use crate::vm::VMWasmCallFunction;
use alloc::sync::Arc;
use core::alloc::Layout;
@@ -947,6 +949,7 @@ impl Instance {
pub(crate) async fn table_init(
store: &mut StoreOpaque,
limiter: Option<&mut StoreResourceLimiter<'_>>,
+ asyncness: Asyncness,
instance: InstanceId,
table_index: TableIndex,
elem_index: ElemIndex,
@@ -962,6 +965,7 @@ impl Instance {
Self::table_init_segment(
store,
limiter,
+ asyncness,
instance,
&mut const_evaluator,
table_index,
@@ -976,6 +980,7 @@ impl Instance {
pub(crate) async fn table_init_segment(
store: &mut StoreOpaque,
mut limiter: Option<&mut StoreResourceLimiter<'_>>,
+ asyncness: Asyncness,
elements_instance_id: InstanceId,
const_evaluator: &mut ConstExprEvaluator,
table_index: TableIndex,
@@ -1026,7 +1031,7 @@ impl Instance {
.get(src..)
.and_then(|s| s.get(..len))
.ok_or(Trap::TableOutOfBounds)?;
- let mut context = ConstEvalContext::new(elements_instance_id);
+ let mut context = ConstEvalContext::new(elements_instance_id, asyncness);
for (i, expr) in positions.zip(exprs) {
let element = const_evaluator
.eval(&mut store, limiter.as_deref_mut(), &mut context, expr)
diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator.rs b/crates/wasmtime/src/runtime/vm/instance/allocator.rs
index 24f616aeaf..3e420cf096 100644
--- a/crates/wasmtime/src/runtime/vm/instance/allocator.rs
+++ b/crates/wasmtime/src/runtime/vm/instance/allocator.rs
@@ -6,7 +6,7 @@ use crate::runtime::vm::memory::Memory;
use crate::runtime::vm::mpk::ProtectionKey;
use crate::runtime::vm::table::Table;
use crate::runtime::vm::{CompiledModuleId, ModuleRuntimeInfo};
-use crate::store::{InstanceId, StoreOpaque, StoreResourceLimiter};
+use crate::store::{Asyncness, InstanceId, StoreOpaque, StoreResourceLimiter};
use crate::{OpaqueRootScope, Val};
use core::{mem, ptr};
use wasmtime_environ::{
@@ -493,14 +493,14 @@ fn check_table_init_bounds(
store: &mut StoreOpaque,
instance: InstanceId,
module: &Module,
+ context: &mut ConstEvalContext,
+ const_evaluator: &mut ConstExprEvaluator,
) -> Result<()> {
- let mut const_evaluator = ConstExprEvaluator::default();
let mut store = OpaqueRootScope::new(store);
for segment in module.table_initialization.segments.iter() {
- let mut context = ConstEvalContext::new(instance);
let start = const_evaluator
- .eval_int(&mut store, &mut context, &segment.offset)
+ .eval_int(&mut store, context, &segment.offset)
.expect("const expression should be valid");
let start = usize::try_from(start.unwrap_i32().cast_unsigned()).unwrap();
let end = start.checked_add(usize::try_from(segment.elements.len()).unwrap());
@@ -565,6 +565,7 @@ async fn initialize_tables(
Instance::table_init_segment(
&mut store,
limiter.as_deref_mut(),
+ context.asyncness,
context.instance,
const_evaluator,
segment.table_index,
@@ -590,12 +591,12 @@ fn get_memory_init_start(
store: &mut StoreOpaque,
init: &MemoryInitializer,
instance: InstanceId,
+ context: &mut ConstEvalContext,
+ const_evaluator: &mut ConstExprEvaluator,
) -> Result<u64> {
- let mut context = ConstEvalContext::new(instance);
- let mut const_evaluator = ConstExprEvaluator::default();
let mut store = OpaqueRootScope::new(store);
const_evaluator
- .eval_int(&mut store, &mut context, &init.offset)
+ .eval_int(&mut store, context, &init.offset)
.map(|v| {
get_index(
v,
@@ -608,10 +609,12 @@ fn check_memory_init_bounds(
store: &mut StoreOpaque,
instance: InstanceId,
initializers: &[MemoryInitializer],
+ context: &mut ConstEvalContext,
+ const_evaluator: &mut ConstExprEvaluator,
) -> Result<()> {
for init in initializers {
let memory = store.instance_mut(instance).get_memory(init.memory_index);
- let start = get_memory_init_start(store, init, instance)?;
+ let start = get_memory_init_start(store, init, instance, context, const_evaluator)?;
let end = usize::try_from(start)
.ok()
.and_then(|start| start.checked_add(init.data.len()));
@@ -729,12 +732,18 @@ fn initialize_memories(
Ok(())
}
-fn check_init_bounds(store: &mut StoreOpaque, instance: InstanceId, module: &Module) -> Result<()> {
- check_table_init_bounds(store, instance, module)?;
+fn check_init_bounds(
+ store: &mut StoreOpaque,
+ instance: InstanceId,
+ context: &mut ConstEvalContext,
+ const_evaluator: &mut ConstExprEvaluator,
+ module: &Module,
+) -> Result<()> {
+ check_table_init_bounds(store, instance, module, context, const_evaluator)?;
match &module.memory_initialization {
MemoryInitialization::Segmented(initializers) => {
- check_memory_init_bounds(store, instance, initializers)?;
+ check_memory_init_bounds(store, instance, initializers, context, const_evaluator)?;
}
// Statically validated already to have everything in-bounds.
MemoryInitialization::Static { .. } => {}
@@ -805,18 +814,19 @@ pub async fn initialize_instance(
instance: InstanceId,
module: &Module,
is_bulk_memory: bool,
+ asyncness: Asyncness,
) -> Result<()> {
+ let mut context = ConstEvalContext::new(instance, asyncness);
+ let mut const_evaluator = ConstExprEvaluator::default();
+
// If bulk memory is not enabled, bounds check the data and element segments before
// making any changes. With bulk memory enabled, initializers are processed
// in-order and side effects are observed up to the point of an out-of-bounds
// initializer, so the early checking is not desired.
if !is_bulk_memory {
- check_init_bounds(store, instance, module)?;
+ check_init_bounds(store, instance, &mut context, &mut const_evaluator, module)?;
}
- let mut context = ConstEvalContext::new(instance);
- let mut const_evaluator = ConstExprEvaluator::default();
-
initialize_globals(
store,
limiter.as_deref_mut(),
diff --git a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/metrics.rs b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/metrics.rs
index 74525fb673..4cd26be24b 100644
--- a/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/metrics.rs
+++ b/crates/wasmtime/src/runtime/vm/instance/allocator/pooling/metrics.rs
@@ -334,7 +334,6 @@ mod tests {
let pool = small_pool_config();
let mut config = Config::new();
config.allocation_strategy(pool);
- config.async_support(true);
let engine = Engine::new(&config)?;
let metrics = engine.pooling_allocator_metrics().unwrap();
diff --git a/crates/wasmtime/src/runtime/vm/libcalls.rs b/crates/wasmtime/src/runtime/vm/libcalls.rs
index 9e2f74e8b0..ac3a6be0a1 100644
--- a/crates/wasmtime/src/runtime/vm/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/libcalls.rs
@@ -57,7 +57,7 @@
#[cfg(feature = "stack-switching")]
use super::stack_switching::VMContObj;
use crate::prelude::*;
-use crate::runtime::store::{InstanceId, StoreInstanceId, StoreOpaque};
+use crate::runtime::store::{Asyncness, InstanceId, StoreInstanceId, StoreOpaque};
#[cfg(feature = "gc")]
use crate::runtime::vm::VMGcRef;
use crate::runtime::vm::table::TableElementType;
@@ -170,7 +170,7 @@ pub mod raw {
///
/// This will internally multiplex on `$store.with_blocking(...)` vs simply
/// asserting the closure is ready depending on whether a store's
-/// `async_support` flag is set or not.
+/// `can_block` flag is set or not.
///
/// FIXME: ideally this would be a function, not a macro. If this is a function
/// though it would require placing a bound on the async closure $f where the
@@ -186,27 +186,60 @@ macro_rules! block_on {
($store:expr, $f:expr) => {{
let store: &mut StoreOpaque = $store;
let closure = assert_async_fn_closure($f);
- if store.async_support() {
+
+ if store.can_block() {
+ // If the store can block then that means it's on a fiber. We can
+ // forward to `block_on` and everything should be fine and dandy.
#[cfg(feature = "async")]
{
- store.with_blocking(|store, cx| cx.block_on(closure(store)))
+ store.with_blocking(|store, cx| cx.block_on(closure(store, Asyncness::Yes)))
}
#[cfg(not(feature = "async"))]
{
unreachable!()
}
} else {
- // Note that if `async_support` is disabled then it should not be
- // possible to introduce await points so the provided future should
- // always be ready.
- crate::error::Ok(vm::assert_ready(closure(store)))
+ // If the store cannot block it's not on a fiber. That means that we get
+ // at most one poll of `closure(store)` here. In the typical case
+ // what this means is that nothing async is configured in the store
+ // and one poll should be all we need. There are niche cases where
+ // one poll is not sufficient though, for example:
+ //
+ // * Store is created.
+ // * Wasm is called.
+ // * Wasm calls host.
+ // * Host configures an async resource limiter, returns back to
+ // wasm.
+ // * Wasm grows memory.
+ // * Limiter wants to block asynchronously.
+ //
+ // Technically there's nothing wrong with this, but it means that
+ // we're in wasm and one poll is not enough here. Given the niche
+ // nature of this scenario and how it's not really expected to work
+ // this translates failures in `closure` to a trap. This trap is
+ // only expected to show up in niche-ish scenarios, not for actual
+ // blocking work, as that would otherwise be too surprising.
+ vm::one_poll(closure(store, Asyncness::No)).ok_or_else(|| {
+ crate::format_err!(
+ "
+
+A synchronously called wasm function invoked an async-defined libcall which
+failed to complete synchronously and is thus raising a trap. It's expected
+that this indicates that the store was configured to do async things after the
+original synchronous entrypoint to wasm was called. That's generally not
+supported in Wasmtime and async entrypoint should be used instead. If you're
+seeing this message in error please file an issue on Wasmtime.
+
+"
+ )
+ })
}
}};
}
fn assert_async_fn_closure<F, R>(f: F) -> F
where
- F: AsyncFnOnce(&mut StoreOpaque) -> R,
+ F: AsyncFnOnce(&mut StoreOpaque, Asyncness) -> R,
{
f
}
@@ -220,7 +253,7 @@ fn memory_grow(
let memory_index = DefinedMemoryIndex::from_u32(memory_index);
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
let limiter = limiter.as_mut();
- block_on!(store, async |store| {
+ block_on!(store, async |store, _| {
let instance = store.instance_mut(instance);
let module = instance.env_module();
let page_size_log2 = module.memories[module.memory_index(memory_index)].page_size_log2;
@@ -283,7 +316,7 @@ unsafe fn table_grow_func_ref(
let element = NonNull::new(init_value.cast::<VMFuncRef>()).map(SendSyncPtr::new);
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
let limiter = limiter.as_mut();
- block_on!(store, async |store| {
+ block_on!(store, async |store, _| {
let mut instance = store.instance_mut(instance);
let table_index = instance.env_module().table_index(defined_table_index);
debug_assert!(matches!(
@@ -313,7 +346,7 @@ fn table_grow_gc_ref(
let element = VMGcRef::from_raw_u32(init_value);
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
let limiter = limiter.as_mut();
- block_on!(store, async |store| {
+ block_on!(store, async |store, _| {
let (gc_store, mut instance) = store.optional_gc_store_and_instance_mut(instance);
let table_index = instance.env_module().table_index(defined_table_index);
debug_assert!(matches!(
@@ -348,7 +381,7 @@ unsafe fn table_grow_cont_obj(
let element = unsafe { VMContObj::from_raw_parts(init_value_contref, init_value_revision) };
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
let limiter = limiter.as_mut();
- block_on!(store, async |store| {
+ block_on!(store, async |store, _| {
let mut instance = store.instance_mut(instance);
let table_index = instance.env_module().table_index(defined_table_index);
debug_assert!(matches!(
@@ -489,10 +522,11 @@ fn table_init(
let elem_index = ElemIndex::from_u32(elem_index);
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
+ block_on!(store, async |store, asyncness| {
vm::Instance::table_init(
store,
limiter.as_mut(),
+ asyncness,
instance,
table_index,
elem_index,
@@ -620,8 +654,10 @@ fn grow_gc_heap(store: &mut dyn VMStore, _instance: InstanceId, bytes_needed: u6
.unwrap();
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
- store.gc(limiter.as_mut(), None, Some(bytes_needed)).await;
+ block_on!(store, async |store, asyncness| {
+ store
+ .gc(limiter.as_mut(), None, Some(bytes_needed), asyncness)
+ .await;
})?;
// JIT code relies on the memory having grown by `bytes_needed` bytes if
@@ -686,9 +722,9 @@ fn gc_alloc_raw(
})?;
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
+ block_on!(store, async |store, asyncness| {
let gc_ref = store
- .retry_after_gc_async(limiter.as_mut(), (), |store, ()| {
+ .retry_after_gc_async(limiter.as_mut(), (), asyncness, |store, ()| {
store
.unwrap_gc_store_mut()
.alloc_raw(header, layout)?
@@ -780,7 +816,7 @@ fn array_new_data(
use wasmtime_environ::ModuleInternedTypeIndex;
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
+ block_on!(store, async |store, asyncness| {
let array_type_index = ModuleInternedTypeIndex::from_u32(array_type_index);
let data_index = DataIndex::from_u32(data_index);
let instance = store.instance(instance_id);
@@ -815,7 +851,7 @@ fn array_new_data(
.expect("array types have GC layouts");
let array_layout = gc_layout.unwrap_array();
let array_ref = store
- .retry_after_gc_async(limiter.as_mut(), (), |store, ()| {
+ .retry_after_gc_async(limiter.as_mut(), (), asyncness, |store, ()| {
store
.unwrap_gc_store_mut()
.alloc_uninit_array(shared_ty, len, &array_layout)?
@@ -955,7 +991,7 @@ fn array_new_elem(
let pre = ArrayRefPre::_new(store, array_ty);
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
+ block_on!(store, async |store, asyncness| {
let mut store = OpaqueRootScope::new(store);
// Turn the elements into `Val`s.
let mut vals = Vec::with_capacity(usize::try_from(elements.len()).unwrap());
@@ -983,7 +1019,7 @@ fn array_new_elem(
.and_then(|s| s.get(..len))
.ok_or_else(|| Trap::TableOutOfBounds)?;
- let mut const_context = ConstEvalContext::new(instance_id);
+ let mut const_context = ConstEvalContext::new(instance_id, asyncness);
let mut const_evaluator = ConstExprEvaluator::default();
for x in xs.iter() {
@@ -995,7 +1031,9 @@ fn array_new_elem(
}
}
- let array = ArrayRef::_new_fixed_async(&mut store, limiter.as_mut(), &pre, &vals).await?;
+ let array =
+ ArrayRef::_new_fixed_async(&mut store, limiter.as_mut(), &pre, &vals, asyncness)
+ .await?;
let mut store = AutoAssertNoGc::new(&mut store);
let gc_ref = array.try_clone_gc_ref(&mut store)?;
@@ -1023,7 +1061,7 @@ fn array_init_elem(
use wasmtime_environ::{ModuleInternedTypeIndex, TableSegmentElements};
let (mut limiter, store) = store.resource_limiter_and_store_opaque();
- block_on!(store, async |store| {
+ block_on!(store, async |store, asyncness| {
let mut store = OpaqueRootScope::new(store);
// Convert the indices into their typed forms.
@@ -1073,7 +1111,7 @@ fn array_init_elem(
})
.collect::<Vec<_>>(),
TableSegmentElements::Expressions(xs) => {
- let mut const_context = ConstEvalContext::new(instance.id());
+ let mut const_context = ConstEvalContext::new(instance.id(), asyncness);
let mut const_evaluator = ConstExprEvaluator::default();
let mut vals = Vec::new();
@@ -1239,7 +1277,7 @@ fn memory_atomic_wait64(
// Hook for when an instance runs out of fuel.
fn out_of_gas(store: &mut dyn VMStore, _instance: InstanceId) -> Result<()> {
- block_on!(store, async |store| {
+ block_on!(store, async |store, _| {
if !store.refuel() {
return Err(Trap::OutOfFuel.into());
}
@@ -1262,33 +1300,36 @@ fn new_epoch(store: &mut dyn VMStore, _instance: InstanceId) -> Result<NextEpoch
}
let update_deadline = store.new_epoch_updated_deadline()?;
- block_on!(store, async move |store| {
+ block_on!(store, async move |store, asyncness| {
+ #[cfg(not(feature = "async"))]
+ let _ = asyncness;
+
let delta = match update_deadline {
UpdateDeadline::Interrupt => return Err(Trap::Interrupt.into()),
UpdateDeadline::Continue(delta) => delta,
- // Note that custom assertions for `async_support` are needed below
- // as otherwise if these are used in an
- // `async_support`-disabled-build it'll trip the `assert_ready` part
- // of `block_on!` above. The assertion here provides a more direct
- // error message as to what's going on.
+ // Note that custom errors are used here to avoid tripping up on the
+ // `block_on!` message that otherwise assumes
+ // async-configuration-after-the-fact.
#[cfg(feature = "async")]
UpdateDeadline::Yield(delta) => {
- assert!(
- store.async_support(),
- "cannot use `UpdateDeadline::Yield` without enabling \
- async support in the config"
- );
+ if asyncness != Asyncness::Yes {
+ bail!(
+ "cannot use `UpdateDeadline::Yield` without using \
+ an async wasm entrypoint",
+ );
+ }
crate::runtime::vm::Yield::new().await;
delta
}
#[cfg(feature = "async")]
UpdateDeadline::YieldCustom(delta, future) => {
- assert!(
- store.async_support(),
- "cannot use `UpdateDeadline::YieldCustom` without enabling \
- async support in the config"
- );
+ if asyncness != Asyncness::Yes {
+ bail!(
+ "cannot use `UpdateDeadline::YieldCustom` without using \
+ an async wasm entrypoint",
+ );
+ }
future.await;
delta
}
diff --git a/crates/wasmtime/tests/host_segfault.rs b/crates/wasmtime/tests/host_segfault.rs
index a6061c3153..d08f0b0136 100644
--- a/crates/wasmtime/tests/host_segfault.rs
+++ b/crates/wasmtime/tests/host_segfault.rs
@@ -155,9 +155,7 @@ fn main() {
(
"hit async stack guard page",
|| {
- let mut config = Config::default();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let mut store = Store::new(&engine, ());
let f = Func::wrap_async(&mut store, |_, _: ()| {
Box::new(async {
@@ -189,7 +187,6 @@ fn main() {
"hit async stack guard page with pooling allocator",
|| {
let mut config = Config::default();
- config.async_support(true);
let mut cfg = PoolingAllocationConfig::default();
cfg.total_memories(1);
cfg.max_memory_size(1 << 16);
diff --git a/crates/wiggle/tests/wasmtime_async.rs b/crates/wiggle/tests/wasmtime_async.rs
index 93badb82fa..c5a90fc6f4 100644
--- a/crates/wiggle/tests/wasmtime_async.rs
+++ b/crates/wiggle/tests/wasmtime_async.rs
@@ -1,4 +1,4 @@
-use wasmtime::{Config, Engine, Linker, Module, Store, Val};
+use wasmtime::{Engine, Linker, Module, Store, Val};
use wiggle::GuestMemory;
wiggle::from_witx!({
@@ -106,10 +106,7 @@ async fn test_async_host_func() {
}
fn async_store() -> Store<Ctx> {
- Store::new(
- &Engine::new(Config::new().async_support(true)).unwrap(),
- Ctx,
- )
+ Store::new(&Engine::default(), Ctx)
}
// Wiggle expects the caller to have an exported memory. Wasmtime can only
diff --git a/crates/wizer/tests/all/component.rs b/crates/wizer/tests/all/component.rs
index e665739566..4c41c83bfc 100644
--- a/crates/wizer/tests/all/component.rs
+++ b/crates/wizer/tests/all/component.rs
@@ -1,5 +1,5 @@
use wasmtime::component::{Component, Instance, Linker, Val};
-use wasmtime::{Config, Engine, Result, Store, ToWasmtimeResult as _, bail, error::Context as _};
+use wasmtime::{Engine, Result, Store, ToWasmtimeResult as _, bail, error::Context as _};
use wasmtime_wizer::Wizer;
fn fail_wizening(msg: &str, wasm: &[u8]) -> Result<()> {
@@ -120,9 +120,7 @@ fn unsupported_constructs() -> Result<()> {
}
fn store() -> Result<Store<()>> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
Ok(Store::new(&engine, ()))
}
diff --git a/crates/wizer/tests/all/make_linker.rs b/crates/wizer/tests/all/make_linker.rs
index 65c5cc3ce0..c28ea95500 100644
--- a/crates/wizer/tests/all/make_linker.rs
+++ b/crates/wizer/tests/all/make_linker.rs
@@ -7,7 +7,6 @@ async fn run_wasm(args: &[wasmtime::Val], expected: i32, wasm: &[u8]) -> Result<
let _ = env_logger::try_init();
let mut config = wasmtime::Config::new();
- config.async_support(true);
wasmtime::Cache::from_file(None)
.map(|cache| config.cache(Some(cache)))
.unwrap();
diff --git a/crates/wizer/tests/all/preloads.rs b/crates/wizer/tests/all/preloads.rs
index 6e4a67a145..f08fcb650b 100644
--- a/crates/wizer/tests/all/preloads.rs
+++ b/crates/wizer/tests/all/preloads.rs
@@ -21,9 +21,7 @@ const PRELOAD2: &'static str = r#"
async fn run_with_preloads(args: &[wasmtime::Val], wat: &str) -> Result<wasmtime::Val> {
let wasm = wat_to_wasm(wat)?;
- let mut config = wasmtime::Config::new();
- config.async_support(true);
- let engine = wasmtime::Engine::new(&config)?;
+ let engine = wasmtime::Engine::default();
let mut store = wasmtime::Store::new(&engine, ());
let mod1 = Module::new(store.engine(), PRELOAD1)?;
let mod2 = Module::new(store.engine(), PRELOAD2)?;
diff --git a/crates/wizer/tests/all/tests.rs b/crates/wizer/tests/all/tests.rs
index ff8f351f4e..a0fe6d9715 100644
--- a/crates/wizer/tests/all/tests.rs
+++ b/crates/wizer/tests/all/tests.rs
@@ -21,7 +21,6 @@ fn get_wizer() -> Wizer {
fn store() -> Result<Store<p1::WasiP1Ctx>> {
let mut wasi = WasiCtxBuilder::new();
let mut config = Config::new();
- config.async_support(true);
config.relaxed_simd_deterministic(true);
let engine = Engine::new(&config)?;
Ok(Store::new(&engine, wasi.build_p1()))
diff --git a/docs/examples-wasip2.md b/docs/examples-wasip2.md
index be67ff069a..0e9b2bca61 100644
--- a/docs/examples-wasip2.md
+++ b/docs/examples-wasip2.md
@@ -45,7 +45,9 @@ This example shows adding and configuring the WASI imports to invoke the above W
This [async example code][code2] shows how to use the [wasmtime-wasi][`wasmtime-wasi`] crate to
execute the same WASIp2 component from the example above. This example requires the `wasmtime` crate `async` feature to be enabled.
-This does not require any change to the WASIp2 component, it's just the WASIp2 API host functions which are implemented to be async. See [wasmtime async support](https://docs.wasmtime.dev/api/wasmtime/struct.Config.html#method.async_support).
+This does not require any change to the WASIp2 component, it's just the WASIp2
+API host functions which are implemented to be async. See [wasmtime async
+support](https://docs.wasmtime.dev/api/wasmtime/#async).
[code2]: https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip2-async/main.rs
[`wasmtime-wasi`]: https://docs.rs/wasmtime-wasi/*/wasmtime_wasi/preview2/index.html
diff --git a/examples/anyref.rs b/examples/anyref.rs
index 6cd010a94e..b28d765d06 100644
--- a/examples/anyref.rs
+++ b/examples/anyref.rs
@@ -54,7 +54,7 @@ fn main() -> Result<()> {
assert_eq!(ret.unwrap().unwrap_i31(&store)?, I31::wrapping_u32(42));
println!("GCing within the store...");
- store.gc(None);
+ store.gc(None)?;
println!("Done.");
Ok(())
diff --git a/examples/async.cc b/examples/async.cc
index cff6d6ad00..0c11000553 100644
--- a/examples/async.cc
+++ b/examples/async.cc
@@ -61,7 +61,6 @@ void exit_with_error(std::string msg, wasmtime_error_t *err,
handle<wasm_engine_t, wasm_engine_delete> create_engine() {
wasm_config_t *config = wasm_config_new();
assert(config != nullptr);
- wasmtime_config_async_support_set(config, true);
wasmtime_config_consume_fuel_set(config, true);
handle<wasm_engine_t, wasm_engine_delete> engine;
// this takes ownership of config
diff --git a/examples/externref.rs b/examples/externref.rs
index 0a53c8c17e..4d0ad6816b 100644
--- a/examples/externref.rs
+++ b/examples/externref.rs
@@ -23,7 +23,7 @@ fn main() -> Result<()> {
Err(e) => match e.downcast::<GcHeapOutOfMemory<&str>>() {
Ok(oom) => {
let (inner, oom) = oom.take_inner();
- store.gc(Some(&oom));
+ store.gc(Some(&oom))?;
ExternRef::new(&mut store, inner)?
}
Err(e) => return Err(e),
@@ -70,7 +70,7 @@ fn main() -> Result<()> {
assert!(Rooted::ref_eq(&store, &ret.unwrap(), &externref)?);
println!("GCing within the store...");
- store.gc(None);
+ store.gc(None)?;
println!("Done.");
Ok(())
diff --git a/examples/min-platform/embedding/src/wasi.rs b/examples/min-platform/embedding/src/wasi.rs
index 6a9885b6bf..b7a36b0b79 100644
--- a/examples/min-platform/embedding/src/wasi.rs
+++ b/examples/min-platform/embedding/src/wasi.rs
@@ -73,12 +73,7 @@ pub unsafe extern "C" fn run_wasi(
}
fn run(wasi_component: &[u8]) -> Result<String> {
- // wasmtime-wasi-io requires an async store, because the wasi:io/poll
- // interface will poll as Pending while execution is suspended and it is
- // waiting for a Pollable to become Ready. This example provides a very
- // small async executor which is entered below with `block_on`.
- let mut config = super::config();
- config.async_support(true);
+ let config = super::config();
// For future: we could consider turning on fuel in the Config to meter
// how long a wasm guest could execute for.
let engine = Engine::new(&config)?;
diff --git a/examples/resource-component/main.rs b/examples/resource-component/main.rs
index d37208cf30..efe0802671 100644
--- a/examples/resource-component/main.rs
+++ b/examples/resource-component/main.rs
@@ -11,7 +11,7 @@ use std::collections::HashMap;
use wasmtime::component::bindgen;
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::component::{HasSelf, Resource};
-use wasmtime::{Config, Engine, Result, Store};
+use wasmtime::{Engine, Result, Store};
use wasmtime_wasi::p2::add_to_linker_async;
use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
@@ -121,10 +121,7 @@ impl example::kv_store::kvdb::HostConnection for ComponentRunStates {
#[tokio::main]
async fn main() -> Result<()> {
- // Construct the wasm engine with async support enabled.
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut linker = Linker::new(&engine);
let state = ComponentRunStates::new();
let mut store = Store::new(&engine, state);
diff --git a/examples/tokio/main.rs b/examples/tokio/main.rs
index 91866d3afa..9feca556e1 100644
--- a/examples/tokio/main.rs
+++ b/examples/tokio/main.rs
@@ -45,9 +45,8 @@ struct Environment {
impl Environment {
pub fn new() -> Result<Self, Error> {
let mut config = Config::new();
- // We need this engine's `Store`s to be async, and consume fuel, so
- // that they can co-operatively yield during execution.
- config.async_support(true);
+ // Consume fuel for guests so that they can co-operatively yield during
+ // execution.
config.consume_fuel(true);
let engine = Engine::new(&config)?;
diff --git a/examples/wasip1-async/main.rs b/examples/wasip1-async/main.rs
index 516379f6e4..3474305eb4 100644
--- a/examples/wasip1-async/main.rs
+++ b/examples/wasip1-async/main.rs
@@ -8,16 +8,13 @@ You can execute this example with:
*/
use wasmtime::Result;
-use wasmtime::{Config, Engine, Linker, Module, Store};
+use wasmtime::{Engine, Linker, Module, Store};
use wasmtime_wasi::WasiCtx;
use wasmtime_wasi::p1::{self, WasiP1Ctx};
#[tokio::main]
async fn main() -> Result<()> {
- // Construct the wasm engine with async support enabled.
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
// Add the WASIp1 APIs to the linker
let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
diff --git a/examples/wasip2-async/main.rs b/examples/wasip2-async/main.rs
index db44473d55..8dec512efb 100644
--- a/examples/wasip2-async/main.rs
+++ b/examples/wasip2-async/main.rs
@@ -32,10 +32,7 @@ impl WasiView for ComponentRunStates {
#[tokio::main]
async fn main() -> Result<()> {
- // Construct the wasm engine with async support enabled.
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut linker = Linker::new(&engine);
wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
diff --git a/src/commands/run.rs b/src/commands/run.rs
index 8db019d54e..edcca310ff 100644
--- a/src/commands/run.rs
+++ b/src/commands/run.rs
@@ -130,7 +130,6 @@ impl RunCommand {
/// Creates a new `Engine` with the configuration for this command.
pub fn new_engine(&mut self) -> Result<Engine> {
let mut config = self.run.common.config(None)?;
- config.async_support(true);
if self.run.common.wasm.timeout.is_some() {
config.epoch_interruption(true);
@@ -1042,6 +1041,7 @@ impl RunCommand {
store.data_mut().wasi_threads = Some(Arc::new(WasiThreadsCtx::new(
module.clone(),
Arc::new(linker.clone()),
+ true,
)?));
}
}
diff --git a/src/commands/serve.rs b/src/commands/serve.rs
index 56b7856a4e..4d7ca7ff59 100644
--- a/src/commands/serve.rs
+++ b/src/commands/serve.rs
@@ -404,7 +404,6 @@ impl ServeCommand {
.config(use_pooling_allocator_by_default().unwrap_or(None))?;
config.wasm_component_model(true);
config.wasm_component_model_async(true);
- config.async_support(true);
if self.run.common.wasm.timeout.is_some() {
config.epoch_interruption(true);
diff --git a/src/commands/wast.rs b/src/commands/wast.rs
index 4f60a47eab..8f7a318b3c 100644
--- a/src/commands/wast.rs
+++ b/src/commands/wast.rs
@@ -46,7 +46,6 @@ impl WastCommand {
let async_ = optional_flag_with_default(self.async_, true);
let mut config = self.common.config(None)?;
- config.async_support(async_);
config.shared_memory(true);
let engine = Engine::new(&config)?;
let mut wast_context = WastContext::new(
diff --git a/tests/all/async_functions.rs b/tests/all/async_functions.rs
index 9f5c836a19..fe5d284a15 100644
--- a/tests/all/async_functions.rs
+++ b/tests/all/async_functions.rs
@@ -5,7 +5,7 @@ use std::task::{Context, Poll, Waker};
use wasmtime::*;
fn async_store() -> Store<()> {
- Store::new(&Engine::new(Config::new().async_support(true)).unwrap(), ())
+ Store::new(&Engine::default(), ())
}
async fn run_smoke_test(store: &mut Store<()>, func: Func) {
@@ -247,7 +247,7 @@ async fn suspend_while_suspending() {
#[tokio::test]
async fn cancel_during_run() {
- let mut store = Store::new(&Engine::new(Config::new().async_support(true)).unwrap(), 0);
+ let mut store = Store::new(&Engine::default(), 0);
let func_ty = FuncType::new(store.engine(), None, None);
let async_thunk = Func::new_async(&mut store, func_ty, move |mut caller, _params, _results| {
@@ -292,7 +292,7 @@ async fn cancel_during_run() {
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn iloop_with_fuel() {
- let engine = Engine::new(Config::new().async_support(true).consume_fuel(true)).unwrap();
+ let engine = Engine::new(Config::new().consume_fuel(true)).unwrap();
let mut store = Store::new(&engine, ());
store.set_fuel(10_000).unwrap();
store.fuel_async_yield_interval(Some(100)).unwrap();
@@ -316,7 +316,7 @@ async fn iloop_with_fuel() {
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn fuel_eventually_finishes() {
- let engine = Engine::new(Config::new().async_support(true).consume_fuel(true)).unwrap();
+ let engine = Engine::new(Config::new().consume_fuel(true)).unwrap();
let mut store = Store::new(&engine, ());
store.set_fuel(u64::MAX).unwrap();
store.fuel_async_yield_interval(Some(10)).unwrap();
@@ -351,7 +351,6 @@ async fn async_with_pooling_stacks() {
.max_memory_size(1 << 16)
.table_elements(0);
let mut config = Config::new();
- config.async_support(true);
config.allocation_strategy(InstanceAllocationStrategy::Pooling(pool));
config.memory_guard_size(0);
config.memory_reservation(1 << 16);
@@ -375,7 +374,6 @@ async fn async_host_func_with_pooling_stacks() -> Result<()> {
.max_memory_size(1 << 16)
.table_elements(0);
let mut config = Config::new();
- config.async_support(true);
config.allocation_strategy(InstanceAllocationStrategy::Pooling(pooling));
config.memory_guard_size(0);
config.memory_reservation(1 << 16);
@@ -409,7 +407,6 @@ async fn async_mpk_protection() -> Result<()> {
.max_memory_size(1 << 16)
.table_elements(0);
let mut config = Config::new();
- config.async_support(true);
config.allocation_strategy(InstanceAllocationStrategy::Pooling(pooling));
config.memory_reservation(1 << 26);
config.epoch_interruption(true);
@@ -791,9 +788,7 @@ where
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn non_stacky_async_activations() -> Result<()> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store1: Store<Option<Pin<Box<dyn Future<Output = Result<()>> + Send>>>> =
Store::new(&engine, None);
let mut linker1 = Linker::new(&engine);
@@ -932,9 +927,7 @@ async fn non_stacky_async_activations() -> Result<()> {
async fn gc_preserves_externref_on_historical_async_stacks() -> Result<()> {
let _ = env_logger::try_init();
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let module = Module::new(
&engine,
@@ -1007,7 +1000,6 @@ async fn async_gc_with_func_new_and_func_wrap() -> Result<()> {
let _ = env_logger::try_init();
let mut config = Config::new();
- config.async_support(true);
config.wasm_gc(true);
let engine = Engine::new(&config)?;
diff --git a/tests/all/call_hook.rs b/tests/all/call_hook.rs
index 0e7741331b..532ba73420 100644
--- a/tests/all/call_hook.rs
+++ b/tests/all/call_hook.rs
@@ -116,9 +116,7 @@ fn call_wrapped_func() -> Result<(), Error> {
// Create an async Func, call it directly:
#[tokio::test]
async fn call_wrapped_async_func() -> Result<(), Error> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, State::default());
store.call_hook(sync_call_hook);
let f = Func::wrap_async(
@@ -239,9 +237,7 @@ fn call_linked_func() -> Result<(), Error> {
// Use the Linker to define an async func, call it through WebAssembly:
#[tokio::test]
async fn call_linked_func_async() -> Result<(), Error> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, State::default());
store.call_hook(sync_call_hook);
@@ -330,9 +326,7 @@ fn instantiate() -> Result<(), Error> {
#[tokio::test]
async fn instantiate_async() -> Result<(), Error> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, State::default());
store.call_hook(sync_call_hook);
@@ -564,9 +558,7 @@ async fn basic_async_hook() -> Result<(), Error> {
sync_call_hook(ctx, ch)
}
}
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, State::default());
store.call_hook_async(HandlerR {});
@@ -655,9 +647,7 @@ async fn timeout_async_hook() -> Result<(), Error> {
}
}
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, State::default());
store.call_hook_async(HandlerR {});
@@ -733,9 +723,7 @@ async fn drop_suspended_async_hook() -> Result<(), Error> {
}
}
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let mut store = Store::new(&engine, 0);
store.call_hook_async(Handler);
diff --git a/tests/all/component_model.rs b/tests/all/component_model.rs
index 4761f50c19..daa5d55348 100644
--- a/tests/all/component_model.rs
+++ b/tests/all/component_model.rs
@@ -16,6 +16,7 @@ mod import;
mod instance;
mod linker;
mod macros;
+mod missing_async;
mod nested;
mod post_return;
mod resources;
diff --git a/tests/all/component_model/async.rs b/tests/all/component_model/async.rs
index 766038b840..da6cde8b4c 100644
--- a/tests/all/component_model/async.rs
+++ b/tests/all/component_model/async.rs
@@ -108,7 +108,6 @@ async fn smoke_func_wrap() -> Result<()> {
#[cfg_attr(miri, ignore)]
async fn resume_separate_thread() -> Result<()> {
let mut config = wasmtime_test_util::component::config();
- config.async_support(true);
config.consume_fuel(true);
let engine = Engine::new(&config)?;
let component = format!(
@@ -185,7 +184,6 @@ async fn resume_separate_thread() -> Result<()> {
#[cfg_attr(miri, ignore)]
async fn poll_through_wasm_activation() -> Result<()> {
let mut config = wasmtime_test_util::component::config();
- config.async_support(true);
config.consume_fuel(true);
let engine = Engine::new(&config)?;
let component = format!(
@@ -325,7 +323,6 @@ async fn drop_resource_async() -> Result<()> {
#[cfg_attr(miri, ignore)]
async fn task_deletion() -> Result<()> {
let mut config = Config::new();
- config.async_support(true);
config.wasm_component_model_async(true);
config.wasm_component_model_threading(true);
config.wasm_component_model_async_stackful(true);
@@ -677,7 +674,6 @@ async fn task_deletion() -> Result<()> {
#[cfg_attr(miri, ignore)]
async fn cancel_host_future() -> Result<()> {
let mut config = Config::new();
- config.async_support(true);
config.wasm_component_model_async(true);
let engine = Engine::new(&config)?;
@@ -774,7 +770,6 @@ async fn run_wasm_in_call_async() -> Result<()> {
_ = env_logger::try_init();
let mut config = Config::new();
- config.async_support(true);
config.wasm_component_model_async(true);
let engine = Engine::new(&config)?;
diff --git a/tests/all/component_model/bindgen.rs b/tests/all/component_model/bindgen.rs
index 83ddaa8ed0..22adebfb79 100644
--- a/tests/all/component_model/bindgen.rs
+++ b/tests/all/component_model/bindgen.rs
@@ -89,7 +89,6 @@ mod no_imports_concurrent {
async fn run() -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(
@@ -221,7 +220,6 @@ mod one_import_concurrent {
async fn run() -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(
diff --git a/tests/all/component_model/call_hook.rs b/tests/all/component_model/call_hook.rs
index d71fe42159..72602d2220 100644
--- a/tests/all/component_model/call_hook.rs
+++ b/tests/all/component_model/call_hook.rs
@@ -6,7 +6,7 @@ use std::future::Future;
use std::pin::Pin;
use std::task::{self, Poll};
use wasmtime::component::*;
-use wasmtime::{CallHook, CallHookHandler, Config, Engine, Result, Store, StoreContextMut, bail};
+use wasmtime::{CallHook, CallHookHandler, Engine, Result, Store, StoreContextMut, bail};
// Crate a synchronous Func, call it directly:
#[test]
@@ -222,9 +222,7 @@ async fn call_wrapped_async_func() -> Result<()> {
)
"#;
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let component = Component::new(&engine, wat)?;
@@ -469,9 +467,7 @@ async fn timeout_async_hook() -> Result<()> {
)
"#;
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let component = Component::new(&engine, wat)?;
@@ -557,9 +553,7 @@ async fn drop_suspended_async_hook() -> Result<()> {
)
"#;
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config)?;
+ let engine = Engine::default();
let component = Component::new(&engine, wat)?;
diff --git a/tests/all/component_model/func.rs b/tests/all/component_model/func.rs
index f35a8a1e26..331a623c6d 100644
--- a/tests/all/component_model/func.rs
+++ b/tests/all/component_model/func.rs
@@ -927,7 +927,6 @@ async fn async_reentrance() -> Result<()> {
config.wasm_component_model_async(true);
config.wasm_component_model_async_stackful(true);
config.wasm_component_model_threading(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(&engine, component)?;
let mut store = Store::new(&engine, ());
@@ -1140,7 +1139,6 @@ async fn task_return_trap(component: &str, substring: &str) -> Result<()> {
config.wasm_component_model_async(true);
config.wasm_component_model_async_stackful(true);
config.wasm_component_model_threading(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(&engine, component)?;
let mut store = Store::new(&engine, ());
@@ -1297,7 +1295,6 @@ async fn test_many_parameters(dynamic: bool, concurrent: bool) -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(&engine, component)?;
let mut store = Store::new(&engine, ());
@@ -1753,7 +1750,6 @@ async fn test_many_results(dynamic: bool, concurrent: bool) -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(&engine, component)?;
let mut store = Store::new(&engine, ());
diff --git a/tests/all/component_model/import.rs b/tests/all/component_model/import.rs
index b83e0cd95d..b30b82668d 100644
--- a/tests/all/component_model/import.rs
+++ b/tests/all/component_model/import.rs
@@ -729,7 +729,6 @@ async fn test_stack_and_heap_args_and_rets(concurrent: bool) -> Result<()> {
let mut config = Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &Engine::new(&config)?;
let component = Component::new(&engine, component)?;
let mut store = Store::new(&engine, ());
diff --git a/tests/all/component_model/missing_async.rs b/tests/all/component_model/missing_async.rs
new file mode 100644
index 0000000000..56851aa4cb
--- /dev/null
+++ b/tests/all/component_model/missing_async.rs
@@ -0,0 +1,209 @@
+#![cfg(not(miri))] // not testing unsafe code
+
+use wasmtime::component::{Component, Func, Linker, ResourceAny};
+use wasmtime::{Config, Engine, Result, Store};
+
+fn async_store() -> Store<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ wasmtime::Func::wrap_async(&mut store, |_, ()| Box::new(async {}));
+ return store;
+}
+
+async fn func_in_store(store: &mut Store<()>) -> Result<Func> {
+ let component = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (core module $a
+ (func (export "hi") )
+ )
+ (core instance $i (instantiate $a))
+ (func (export "hi") (canon lift (core func $i "hi")))
+ )
+ "#,
+ )?;
+ let instance = Linker::new(store.engine())
+ .instantiate_async(&mut *store, &component)
+ .await?;
+ let func = instance.get_func(&mut *store, "hi").unwrap();
+ Ok(func)
+}
+
+fn assert_requires_async<T>(store: &mut Store<T>) {
+ let module = wasmtime::Module::new(store.engine(), "(module)").unwrap();
+ assert!(wasmtime::Instance::new(&mut *store, &module, &[]).is_err());
+}
+
+#[tokio::test]
+async fn async_disallows_func_call() -> Result<()> {
+ let mut store = async_store();
+ let func = func_in_store(&mut store).await?;
+ assert!(func.call(&mut store, &[], &mut []).is_err());
+ func.call_async(&mut store, &[], &mut []).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_func_post_return() -> Result<()> {
+ let mut store = async_store();
+ let func = func_in_store(&mut store).await?;
+ func.call_async(&mut store, &[], &mut []).await?;
+
+ assert!(func.post_return(&mut store).is_err());
+ func.post_return_async(&mut store).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_typed_func_call() -> Result<()> {
+ let mut store = async_store();
+ let func = func_in_store(&mut store).await?;
+ let func = func.typed::<(), ()>(&store)?;
+ assert!(func.call(&mut store, ()).is_err());
+ func.call_async(&mut store, ()).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_typed_func_post_return() -> Result<()> {
+ let mut store = async_store();
+ let func = func_in_store(&mut store).await?;
+ let func = func.typed::<(), ()>(&store)?;
+ func.call_async(&mut store, ()).await?;
+ assert!(func.post_return(&mut store).is_err());
+ func.post_return_async(&mut store).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_instantiate() -> Result<()> {
+ let mut store = async_store();
+ let component = Component::new(store.engine(), "(component)")?;
+ let linker = Linker::new(store.engine());
+ assert!(linker.instantiate(&mut store, &component).is_err());
+ linker.instantiate_async(&mut store, &component).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_wrap_async() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker
+ .root()
+ .func_wrap_async("hi", |_, ()| Box::new(async { Ok(()) }))?;
+ let module = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (import "hi" (func))
+ (core func (canon lower (func 0)))
+ )
+ "#,
+ )?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_wrap_concurrent() -> Result<()> {
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker
+ .root()
+ .func_wrap_concurrent("hi", |_, ()| Box::pin(async { Ok(()) }))?;
+ let module = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (import "hi" (func async))
+ (core func (canon lower (func 0)))
+ )
+ "#,
+ )?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_new_async() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker
+ .root()
+ .func_new_async("hi", |_, _, _, _| Box::new(async { Ok(()) }))?;
+ let module = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (import "hi" (func))
+ (core func (canon lower (func 0)))
+ )
+ "#,
+ )?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_new_concurrent() -> Result<()> {
+ let mut config = Config::new();
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker
+ .root()
+ .func_new_concurrent("hi", |_, _, _, _| Box::pin(async { Ok(()) }))?;
+ let module = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (import "hi" (func async))
+ (core func (canon lower (func 0)))
+ )
+ "#,
+ )?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_resource_any_drop() -> Result<()> {
+ let mut store = async_store();
+ let component = Component::new(
+ store.engine(),
+ r#"
+ (component
+ (type $t' (resource (rep i32)))
+ (export $t "t" (type $t'))
+
+ (core func $new (canon resource.new $t))
+ (func (export "mk") (param "r" u32) (result (own $t))
+ (canon lift (core func $new))
+ )
+ )
+ "#,
+ )?;
+ let instance = Linker::new(store.engine())
+ .instantiate_async(&mut store, &component)
+ .await?;
+ let func = instance.get_typed_func::<(u32,), (ResourceAny,)>(&mut store, "mk")?;
+ let (resource,) = func.call_async(&mut store, (42,)).await?;
+ func.post_return_async(&mut store).await?;
+
+ assert!(resource.resource_drop(&mut store).is_err());
+ resource.resource_drop_async(&mut store).await?;
+
+ Ok(())
+}
diff --git a/tests/all/component_model/resources.rs b/tests/all/component_model/resources.rs
index 410a35e144..821553fca4 100644
--- a/tests/all/component_model/resources.rs
+++ b/tests/all/component_model/resources.rs
@@ -1315,7 +1315,6 @@ fn pass_host_borrow_to_guest() -> Result<()> {
async fn drop_on_owned_resource() -> Result<()> {
let mut config = wasmtime::Config::new();
config.wasm_component_model_async(true);
- config.async_support(true);
let engine = &wasmtime::Engine::new(&config)?;
let c = Component::new(
&engine,
diff --git a/tests/all/debug.rs b/tests/all/debug.rs
index 8dbeab7f21..87e75784fe 100644
--- a/tests/all/debug.rs
+++ b/tests/all/debug.rs
@@ -192,7 +192,7 @@ fn gc_access_during_call() -> wasmtime::Result<()> {
let mut stack = caller.debug_frames().unwrap();
// Do a GC while we hold the stack cursor.
- stack.as_context_mut().gc(None);
+ stack.as_context_mut().gc(None).unwrap();
assert!(!stack.done());
assert_eq!(stack.num_stacks(), 0);
@@ -502,7 +502,6 @@ async fn uncaught_exception_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
},
r#"
@@ -554,7 +553,6 @@ async fn caught_exception_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
},
r#"
@@ -609,7 +607,6 @@ async fn hostcall_trap_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
},
r#"
@@ -649,7 +646,6 @@ async fn hostcall_error_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
},
r#"
@@ -694,7 +690,6 @@ async fn breakpoint_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
},
r#"
@@ -836,7 +831,6 @@ async fn breakpoints_in_inlined_code() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.wasm_exceptions(true);
config.compiler_inlining(true);
unsafe {
@@ -849,7 +843,7 @@ async fn breakpoints_in_inlined_code() -> wasmtime::Result<()> {
local.get 0
local.get 1
i32.add)
-
+
(func (export "main") (param i32 i32) (result i32)
local.get 0
local.get 1
@@ -903,7 +897,6 @@ async fn epoch_events() -> wasmtime::Result<()> {
let (module, mut store) = get_module_and_store(
|config| {
- config.async_support(true);
config.epoch_interruption(true);
},
r#"
diff --git a/tests/all/epoch_interruption.rs b/tests/all/epoch_interruption.rs
index b861e252aa..ec1dbb0d6b 100644
--- a/tests/all/epoch_interruption.rs
+++ b/tests/all/epoch_interruption.rs
@@ -8,7 +8,6 @@ use wasmtime::*;
use wasmtime_test_macros::wasmtime_test;
fn build_engine(config: &mut Config) -> Result<Arc<Engine>> {
- config.async_support(true);
config.epoch_interruption(true);
Ok(Arc::new(Engine::new(&config)?))
}
diff --git a/tests/all/exceptions.rs b/tests/all/exceptions.rs
index 97358e6a2d..987011c4f4 100644
--- a/tests/all/exceptions.rs
+++ b/tests/all/exceptions.rs
@@ -238,7 +238,7 @@ fn gc_with_exnref_global(config: &mut Config) -> Result<()> {
let global = instance.get_global(&mut store, "g").unwrap();
global.set(&mut store, Val::ExnRef(Some(exn)))?;
- store.gc(None);
+ store.gc(None)?;
Ok(())
}
diff --git a/tests/all/gc.rs b/tests/all/gc.rs
index 7892c7663e..55b6e9e8b5 100644
--- a/tests/all/gc.rs
+++ b/tests/all/gc.rs
@@ -49,7 +49,7 @@ fn smoke_test_gc_impl(use_epochs: bool) -> Result<()> {
let do_gc = Func::wrap(&mut store, |mut caller: Caller<'_, _>| {
// Do a GC with `externref`s on the stack in Wasm frames.
- caller.gc(None);
+ caller.gc(None)
});
let instance = Instance::new(&mut store, &module, &[do_gc.into()])?;
let func = instance.get_func(&mut store, "func").unwrap();
@@ -67,7 +67,7 @@ fn smoke_test_gc_impl(use_epochs: bool) -> Result<()> {
// Doing a GC should see that there aren't any `externref`s on the stack in
// Wasm frames anymore.
- scope.as_context_mut().gc(None);
+ scope.as_context_mut().gc(None)?;
// But the scope should still be rooting `r`.
assert!(!inner_dropped.load(SeqCst));
@@ -115,7 +115,7 @@ fn wasm_dropping_refs() -> Result<()> {
}
// After doing a GC, all the refs should have been dropped.
- store.gc(None);
+ store.gc(None)?;
assert_eq!(num_refs_dropped.load(SeqCst), 4096);
return Ok(());
@@ -192,7 +192,7 @@ fn many_live_refs() -> Result<()> {
many_live_refs.call(&mut store, &[], &mut [])?;
- store.as_context_mut().gc(None);
+ store.as_context_mut().gc(None)?;
assert_eq!(live_refs.load(SeqCst), 0);
return Ok(());
@@ -248,7 +248,7 @@ fn drop_externref_via_table_set() -> Result<()> {
table_set.call(&mut scope, &args, &mut [])?;
}
- scope.as_context_mut().gc(None);
+ scope.as_context_mut().gc(None)?;
assert!(!foo_is_dropped.load(SeqCst));
assert!(!bar_is_dropped.load(SeqCst));
@@ -258,7 +258,7 @@ fn drop_externref_via_table_set() -> Result<()> {
}
}
- store.gc(None);
+ store.gc(None)?;
assert!(foo_is_dropped.load(SeqCst));
assert!(!bar_is_dropped.load(SeqCst));
@@ -636,9 +636,7 @@ fn gc_and_tail_calls_and_stack_arguments() -> Result<()> {
);
},
)?;
- linker.func_wrap("", "gc", |mut caller: Caller<()>| {
- caller.gc(None);
- })?;
+ linker.func_wrap("", "gc", |mut caller: Caller<()>| caller.gc(None))?;
let instance = linker.instantiate(&mut store, &module)?;
let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
@@ -736,11 +734,11 @@ fn rooted_gets_collected_after_scope_exit() -> Result<()> {
let mut scope = RootScope::new(&mut store);
let _externref = ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?;
- scope.as_context_mut().gc(None);
+ scope.as_context_mut().gc(None)?;
assert!(!flag.load(SeqCst), "not dropped when still rooted");
}
- store.as_context_mut().gc(None);
+ store.as_context_mut().gc(None)?;
assert!(flag.load(SeqCst), "dropped after being unrooted");
Ok(())
@@ -756,11 +754,11 @@ fn owned_rooted_gets_collected_after_unrooting() -> Result<()> {
ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?.to_owned_rooted(&mut scope)?
};
- store.gc(None);
+ store.gc(None)?;
assert!(!flag.load(SeqCst), "not dropped when still rooted");
drop(externref);
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst), "dropped after being unrooted");
Ok(())
@@ -799,8 +797,8 @@ fn round_trip_gc_ref_through_func_wrap() -> Result<()> {
let f = Func::wrap(
&mut store,
|mut caller: Caller<'_, _>, x: Rooted<ExternRef>| {
- caller.gc(None);
- x
+ caller.gc(None)?;
+ Ok(x)
},
);
let f = f.typed::<Rooted<ExternRef>, Rooted<ExternRef>>(&store)?;
@@ -822,7 +820,7 @@ fn to_raw_from_raw_doesnt_leak() -> Result<()> {
let _x = ExternRef::from_raw(&mut scope, raw);
}
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst));
Ok(())
}
@@ -845,7 +843,7 @@ fn table_fill_doesnt_leak() -> Result<()> {
table.fill(&mut scope, 0, Ref::Extern(None), 10)?;
}
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst));
Ok(())
}
@@ -872,7 +870,7 @@ fn table_copy_doesnt_leak() -> Result<()> {
Table::copy(&mut scope, &table, 0, &table, 5, 5)?;
}
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst));
Ok(())
}
@@ -899,7 +897,7 @@ fn table_set_doesnt_leak() -> Result<()> {
table.set(&mut scope, 2, Ref::Extern(None))?;
}
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst));
Ok(())
}
@@ -924,7 +922,7 @@ fn table_grow_doesnt_leak() -> Result<()> {
table.grow(&mut scope, 0, x.into())?;
}
- store.gc(None);
+ store.gc(None)?;
assert!(flag.load(SeqCst));
Ok(())
}
@@ -1206,7 +1204,7 @@ fn drc_transitive_drop_cons_list() -> Result<()> {
// Not holding the cons list alive anymore; should transitively drop
// everything we created.
- store.gc(None);
+ store.gc(None)?;
assert_eq!(num_refs_dropped.load(SeqCst), len);
Ok(())
@@ -1266,7 +1264,7 @@ fn drc_transitive_drop_nested_arrays_tree() -> Result<()> {
// Not holding the tree alive anymore; should transitively drop everything
// we created.
- store.gc(None);
+ store.gc(None)?;
assert_eq!(num_refs_dropped.load(SeqCst), expected);
Ok(())
@@ -1308,7 +1306,7 @@ fn drc_traces_the_correct_number_of_gc_refs_in_arrays() -> Result<()> {
}
// Make sure the poison array is collected.
- store.gc(None);
+ store.gc(None)?;
// Allocate and then collect an array of GC refs from Wasm. This should not
// trick the collector into tracing any poison and panicking.
@@ -1325,7 +1323,7 @@ fn drc_traces_the_correct_number_of_gc_refs_in_arrays() -> Result<()> {
"#,
)?;
let _instance = Instance::new(&mut store, &module, &[])?;
- store.gc(None);
+ store.gc(None)?;
Ok(())
}
@@ -1485,7 +1483,7 @@ fn drc_gc_inbetween_host_calls() -> Result<()> {
}
assert!(!inner_dropped.load(SeqCst));
- store.gc(None);
+ store.gc(None)?;
assert!(inner_dropped.load(SeqCst));
wasmtime::error::Ok(())
};
@@ -1515,16 +1513,16 @@ fn owned_rooted() -> Result<()> {
r.to_owned_rooted(&mut scope)?
};
assert!(!inner_dropped.load(SeqCst));
- store.gc(None);
+ store.gc(None)?;
assert!(!inner_dropped.load(SeqCst));
let r2 = r.clone();
- store.gc(None);
+ store.gc(None)?;
assert!(!inner_dropped.load(SeqCst));
drop(r);
- store.gc(None);
+ store.gc(None)?;
assert!(!inner_dropped.load(SeqCst));
drop(r2);
- store.gc(None);
+ store.gc(None)?;
assert!(inner_dropped.load(SeqCst));
Ok(())
@@ -1548,7 +1546,7 @@ fn owned_rooted_lots_of_root_creation() -> Result<()> {
r.to_owned_rooted(&mut scope)?
};
assert!(!inner_dropped.load(SeqCst));
- store.gc(None);
+ store.gc(None)?;
for _ in 0..100_000 {
let mut scope = RootScope::new(&mut store);
@@ -1559,11 +1557,11 @@ fn owned_rooted_lots_of_root_creation() -> Result<()> {
drop(r3);
}
- store.gc(None);
+ store.gc(None)?;
assert!(!inner_dropped.load(SeqCst));
drop(r);
- store.gc(None);
+ store.gc(None)?;
assert!(inner_dropped.load(SeqCst));
Ok(())
diff --git a/tests/all/host_funcs.rs b/tests/all/host_funcs.rs
index 627138d1a7..fbfdeb2cdc 100644
--- a/tests/all/host_funcs.rs
+++ b/tests/all/host_funcs.rs
@@ -2,19 +2,6 @@ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use wasmtime::bail;
use wasmtime::*;
-#[test]
-#[should_panic = "cannot use `func_new_async` without enabling async support"]
-fn async_required() {
- let engine = Engine::default();
- let mut linker = Linker::<()>::new(&engine);
- drop(linker.func_new_async(
- "",
- "",
- FuncType::new(&engine, None, None),
- move |_caller, _params, _results| Box::new(async { Ok(()) }),
- ));
-}
-
#[test]
fn wrap_func() -> Result<()> {
let engine = Engine::default();
diff --git a/tests/all/limits.rs b/tests/all/limits.rs
index 01f7bda589..1e75a38d12 100644
--- a/tests/all/limits.rs
+++ b/tests/all/limits.rs
@@ -93,9 +93,7 @@ fn test_limits() -> Result<()> {
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_limits_async() -> Result<()> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let module = Module::new(
&engine,
r#"(module (memory (export "m") 0) (table (export "t") 0 funcref))"#,
@@ -544,9 +542,7 @@ impl ResourceLimiterAsync for MemoryContext {
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn test_custom_memory_limiter_async() -> Result<()> {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let mut linker = Linker::new(&engine);
// This approximates a function that would "allocate" resources that the host tracks.
@@ -865,7 +861,6 @@ async fn custom_limiter_async_detect_grow_failure() -> Result<()> {
let mut pool = crate::small_pool_config();
pool.max_memory_size(10 << 16).table_elements(10);
let mut config = Config::new();
- config.async_support(true);
config.allocation_strategy(InstanceAllocationStrategy::Pooling(pool));
let engine = Engine::new(&config).unwrap();
let linker = Linker::<FailureDetector>::new(&engine);
@@ -1046,9 +1041,7 @@ fn panic_in_table_limiter() {
#[should_panic(expected = "async resource limiter memory growing")]
#[cfg_attr(miri, ignore)]
async fn panic_in_async_memory_limiter() {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let linker = Linker::<Panic>::new(&engine);
let module = Module::new(&engine, r#"(module (memory (export "m") 0))"#).unwrap();
@@ -1068,9 +1061,7 @@ async fn panic_in_async_memory_limiter() {
async fn panic_in_async_memory_limiter_wasm_stack() {
// Like the test above, except the memory.grow happens in
// wasm code instead of a host function call.
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let linker = Linker::<Panic>::new(&engine);
let module = Module::new(
@@ -1098,9 +1089,7 @@ async fn panic_in_async_memory_limiter_wasm_stack() {
#[should_panic(expected = "async resource limiter table growing")]
#[cfg_attr(miri, ignore)]
async fn panic_in_async_table_limiter() {
- let mut config = Config::new();
- config.async_support(true);
- let engine = Engine::new(&config).unwrap();
+ let engine = Engine::default();
let linker = Linker::<Panic>::new(&engine);
let module = Module::new(&engine, r#"(module (table (export "t") 0 funcref))"#).unwrap();
diff --git a/tests/all/main.rs b/tests/all/main.rs
index 3a365ba16a..e7c33138e6 100644
--- a/tests/all/main.rs
+++ b/tests/all/main.rs
@@ -36,6 +36,7 @@ mod limits;
mod linker;
mod memory;
mod memory_creator;
+mod missing_async;
mod module;
mod module_serialize;
mod name;
diff --git a/tests/all/missing_async.rs b/tests/all/missing_async.rs
new file mode 100644
index 0000000000..722ed13fac
--- /dev/null
+++ b/tests/all/missing_async.rs
@@ -0,0 +1,368 @@
+#![cfg(not(miri))] // not testing unsafe code
+
+use wasmtime::*;
+
+fn async_store() -> Store<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ Func::wrap_async(&mut store, |_, ()| Box::new(async {}));
+ return store;
+}
+
+struct MyAsyncLimiter;
+
+#[async_trait::async_trait]
+impl ResourceLimiterAsync for MyAsyncLimiter {
+ async fn memory_growing(
+ &mut self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> Result<bool> {
+ Ok(true)
+ }
+
+ async fn table_growing(
+ &mut self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> Result<bool> {
+ Ok(true)
+ }
+}
+
+fn async_limiter_store() -> Store<MyAsyncLimiter> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, MyAsyncLimiter);
+ store.limiter_async(|x| x);
+ return store;
+}
+
+fn assert_requires_async<T>(store: &mut Store<T>) {
+ let module = Module::new(store.engine(), "(module)").unwrap();
+ assert!(Instance::new(&mut *store, &module, &[]).is_err());
+}
+
+#[test]
+fn require_async_after_func_wrap() {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ Func::wrap_async(&mut store, |_, ()| Box::new(async {}));
+ assert_requires_async(&mut store);
+}
+
+#[test]
+fn require_async_after_func_new() {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let ty = FuncType::new(store.engine(), [], []);
+ Func::new_async(&mut store, ty, |_, _, _| Box::new(async { Ok(()) }));
+ assert_requires_async(&mut store);
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_wrap() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker.func_wrap_async("", "", |_, ()| Box::new(async {}))?;
+ let module = Module::new(store.engine(), r#"(module (import "" "" (func)))"#)?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_after_linker_with_func_new() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ let ty = FuncType::new(store.engine(), [], []);
+ linker.func_new_async("", "", ty, |_, _, _| Box::new(async { Ok(()) }))?;
+ let module = Module::new(store.engine(), r#"(module (import "" "" (func)))"#)?;
+ linker.instantiate_async(&mut store, &module).await?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[test]
+fn require_async_after_epochs() -> Result<()> {
+ let mut config = Config::new();
+ config.epoch_interruption(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+ store.epoch_deadline_async_yield_and_update(1);
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[test]
+fn require_async_after_fuel() -> Result<()> {
+ let mut config = Config::new();
+ config.consume_fuel(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+ store.fuel_async_yield_interval(Some(1))?;
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[test]
+fn require_async_after_async_limiter() -> Result<()> {
+ let mut store = async_limiter_store();
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn require_async_with_linker_func_wrap() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let mut linker = Linker::new(store.engine());
+ linker.func_wrap_async("", "", |_, ()| Box::new(async {}))?;
+ let module = Module::new(store.engine(), r#"(module (import "" "" (func)))"#)?;
+ assert!(linker.instantiate(&mut store, &module).is_err());
+ linker.instantiate_async(&mut store, &module).await?;
+ Ok(())
+}
+
+#[test]
+fn require_async_with_debug_handler() -> Result<()> {
+ let mut config = Config::new();
+ config.guest_debug(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+ store.set_debug_handler(MyDebugHandler);
+ assert_requires_async(&mut store);
+ return Ok(());
+
+ #[derive(Clone)]
+ struct MyDebugHandler;
+
+ impl DebugHandler for MyDebugHandler {
+ type Data = ();
+
+ async fn handle(&self, _: StoreContextMut<'_, ()>, _: DebugEvent<'_>) {}
+ }
+}
+
+struct MyAsyncCallHook;
+
+#[async_trait::async_trait]
+impl CallHookHandler<()> for MyAsyncCallHook {
+ async fn handle_call_event(&self, _: StoreContextMut<'_, ()>, _: CallHook) -> Result<()> {
+ Ok(())
+ }
+}
+
+#[test]
+fn require_async_with_async_call_hook() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ store.call_hook_async(MyAsyncCallHook);
+ assert_requires_async(&mut store);
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_instance_new() -> Result<()> {
+ let mut store = async_store();
+ let module = Module::new(store.engine(), "(module)")?;
+ assert!(Instance::new(&mut store, &module, &[]).is_err());
+ Instance::new_async(&mut store, &module, &[]).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_linker_instantiate() -> Result<()> {
+ let mut store = async_store();
+ let module = Module::new(store.engine(), "(module)")?;
+ let linker = Linker::new(store.engine());
+ assert!(linker.instantiate(&mut store, &module).is_err());
+ linker.instantiate_async(&mut store, &module).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_func_call() -> Result<()> {
+ let mut store = async_store();
+ let func = Func::wrap(&mut store, || {});
+ assert!(func.call(&mut store, &[], &mut []).is_err());
+ func.call_async(&mut store, &[], &mut []).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_typed_func_call() -> Result<()> {
+ let mut store = async_store();
+ let func = Func::wrap(&mut store, || {});
+ let func = func.typed::<(), ()>(&mut store)?;
+ assert!(func.call(&mut store, ()).is_err());
+ func.call_async(&mut store, ()).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_gc() -> Result<()> {
+ let mut store = async_limiter_store();
+ assert!(store.gc(None).is_err());
+ store.gc_async(None).await;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_array_ref_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = ArrayType::new(
+ store.engine(),
+ FieldType::new(Mutability::Var, StorageType::I8),
+ );
+ let pre = ArrayRefPre::new(&mut store, ty);
+ assert!(ArrayRef::new(&mut store, &pre, &Val::I32(0), 10).is_err());
+ ArrayRef::new_async(&mut store, &pre, &Val::I32(0), 10).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_array_ref_new_fixed() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = ArrayType::new(
+ store.engine(),
+ FieldType::new(Mutability::Var, StorageType::I8),
+ );
+ let pre = ArrayRefPre::new(&mut store, ty);
+ assert!(ArrayRef::new_fixed(&mut store, &pre, &[Val::I32(0)]).is_err());
+ ArrayRef::new_fixed_async(&mut store, &pre, &[Val::I32(0)]).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_exnref_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = ExnType::new(store.engine(), [])?;
+ let pre = ExnRefPre::new(&mut store, ty);
+ let fty = FuncType::new(store.engine(), [], []);
+ let tag = Tag::new(&mut store, &TagType::new(fty))?;
+ assert!(ExnRef::new(&mut store, &pre, &tag, &[]).is_err());
+ ExnRef::new_async(&mut store, &pre, &tag, &[]).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_externref_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ assert!(ExternRef::new(&mut store, 1).is_err());
+ ExternRef::new_async(&mut store, 1).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_disallows_structref_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = StructType::new(
+ store.engine(),
+ [FieldType::new(Mutability::Var, StorageType::I8)],
+ )?;
+ let pre = StructRefPre::new(&mut store, ty);
+ assert!(StructRef::new(&mut store, &pre, &[Val::I32(0)]).is_err());
+ StructRef::new_async(&mut store, &pre, &[Val::I32(0)]).await?;
+ Ok(())
+}
+
+#[test]
+fn epoch_yield_disallowed_without_async() -> Result<()> {
+ let mut config = Config::new();
+ config.epoch_interruption(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, ());
+
+ let module = Module::new(&engine, r#"(module (func (export "") (loop br 0)))"#)?;
+ let instance = Instance::new(&mut store, &module, &[])?;
+ let func = instance.get_typed_func::<(), ()>(&mut store, "")?;
+
+ store.epoch_deadline_callback(|_store| Ok(UpdateDeadline::Yield(1)));
+ assert!(func.call(&mut store, ()).is_err());
+
+ store.epoch_deadline_callback(|_store| Ok(UpdateDeadline::YieldCustom(1, Box::pin(async {}))));
+ assert!(func.call(&mut store, ()).is_err());
+
+ store.epoch_deadline_trap();
+ let err = func.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;
+ assert_eq!(err, Trap::Interrupt);
+ Ok(())
+}
+
+#[test]
+fn start_sync_then_configure_async_then_do_async() -> Result<()> {
+ let mut config = Config::new();
+ config.consume_fuel(true);
+ let engine = Engine::new(&config)?;
+ let mut store = Store::new(&engine, MyAsyncLimiter);
+
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "" (func $host))
+ (memory 1)
+ (func (export "")
+ call $host
+ (loop br 0)
+ )
+ )
+ "#,
+ )?;
+
+ let mut linker = Linker::new(&engine);
+ linker.func_wrap("", "", |mut store: Caller<'_, MyAsyncLimiter>| {
+ store.as_context_mut().fuel_async_yield_interval(Some(1))
+ })?;
+ store.set_fuel(100)?;
+ let instance = linker.instantiate(&mut store, &module)?;
+ let func = instance.get_typed_func::<(), ()>(&mut store, "")?;
+ let err = func.call(&mut store, ()).unwrap_err();
+ assert!(
+ format!("{err:?}").contains("configured to do async things"),
+ "bad error {err:?}",
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_limiter_disallows_table_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = TableType::new(RefType::FUNCREF, 1, None);
+ assert!(Table::new(&mut store, ty.clone(), Ref::Func(None)).is_err());
+ Table::new_async(&mut store, ty, Ref::Func(None)).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_limiter_disallows_table_grow() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = TableType::new(RefType::FUNCREF, 1, None);
+ let table = Table::new_async(&mut store, ty, Ref::Func(None)).await?;
+ assert!(table.grow(&mut store, 1, Ref::Func(None)).is_err());
+ table.grow_async(&mut store, 1, Ref::Func(None)).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_limiter_disallows_memory_new() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = MemoryType::new(1, None);
+ assert!(Memory::new(&mut store, ty.clone()).is_err());
+ Memory::new_async(&mut store, ty).await?;
+ Ok(())
+}
+
+#[tokio::test]
+async fn async_limiter_disallows_memory_grow() -> Result<()> {
+ let mut store = async_limiter_store();
+ let ty = MemoryType::new(1, None);
+ let mem = Memory::new_async(&mut store, ty).await?;
+ assert!(mem.grow(&mut store, 1).is_err());
+ mem.grow_async(&mut store, 1).await?;
+ Ok(())
+}
diff --git a/tests/all/pooling_allocator.rs b/tests/all/pooling_allocator.rs
index 1ba7fc805e..a02e4b0d28 100644
--- a/tests/all/pooling_allocator.rs
+++ b/tests/all/pooling_allocator.rs
@@ -912,7 +912,6 @@ async fn total_stacks_limit() -> Result<()> {
pool.total_stacks(TOTAL_STACKS)
.total_core_instances(TOTAL_STACKS + 1);
let mut config = Config::new();
- config.async_support(true);
config.allocation_strategy(pool);
let engine = Engine::new(&config)?;
diff --git a/tests/all/pulley.rs b/tests/all/pulley.rs
index 4e2127583d..50f4ffc533 100644
--- a/tests/all/pulley.rs
+++ b/tests/all/pulley.rs
@@ -430,8 +430,7 @@ async fn sleep(duration: std::time::Duration) {
#[tokio::test]
#[cfg_attr(miri, ignore)]
async fn pulley_provenance_test_async_components() -> Result<()> {
- let mut config = provenance_test_config();
- config.async_support(true);
+ let config = provenance_test_config();
let engine = Engine::new(&config)?;
let component = if cfg!(miri) {
unsafe {
diff --git a/tests/all/stack_creator.rs b/tests/all/stack_creator.rs
index 10fe25e8b8..480161b11b 100644
--- a/tests/all/stack_creator.rs
+++ b/tests/all/stack_creator.rs
@@ -117,7 +117,6 @@ fn config() -> (Store<()>, Arc<CustomStackCreator>) {
let stack_creator = Arc::new(CustomStackCreator::new().unwrap());
let mut config = Config::new();
config
- .async_support(true)
.max_wasm_stack(stack_creator.size / 2)
.async_stack_size(stack_creator.size)
.with_host_stack(stack_creator.clone());
diff --git a/tests/all/traps.rs b/tests/all/traps.rs
index fa7752afd4..3b578b49d9 100644
--- a/tests/all/traps.rs
+++ b/tests/all/traps.rs
@@ -994,7 +994,7 @@ async fn async_then_sync_trap() -> Result<()> {
}
let mut async_store = Store::new(
- &Engine::new(Config::new().async_support(true)).unwrap(),
+ &Engine::default(),
AsyncCtx {
sync_instance,
sync_store,
@@ -1057,7 +1057,7 @@ async fn sync_then_async_trap() -> Result<()> {
)
"#;
- let mut async_store = Store::new(&Engine::new(Config::new().async_support(true)).unwrap(), ());
+ let mut async_store = Store::new(&Engine::default(), ());
let async_module = Module::new(async_store.engine(), wat)?;
@@ -1648,16 +1648,6 @@ fn same_module_multiple_stores() -> Result<()> {
Ok(())
}
-#[test]
-fn async_stack_size_ignored_if_disabled() -> Result<()> {
- let mut config = Config::new();
- config.async_support(false);
- config.max_wasm_stack(8 << 20);
- Engine::new(&config)?;
-
- Ok(())
-}
-
#[wasmtime_test(wasm_features(tail_call))]
fn tail_call_to_imported_function(config: &mut Config) -> Result<()> {
let engine = Engine::new(config)?;
diff --git a/tests/wast.rs b/tests/wast.rs
index 4dc7a28184..c203867ff6 100644
--- a/tests/wast.rs
+++ b/tests/wast.rs
@@ -142,7 +142,6 @@ fn run_wast(test: &WastTest, config: WastConfig) -> wasmtime::Result<()> {
};
let mut cfg = Config::new();
- cfg.async_support(true);
cfg.shared_memory(true);
wasmtime_test_util::wasmtime_wast::apply_test_config(&mut cfg, &test_config);
wasmtime_test_util::wasmtime_wast::apply_wast_config(&mut cfg, &config);