Skip to content

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

Route more component adapters to the host (#14574)

Alex Crichton65abe37529a6
diff --git a/crates/cranelift/src/compiler/component.rs b/crates/cranelift/src/compiler/component.rs
index 815ca0ef6d..8ec76fe2a4 100644
--- a/crates/cranelift/src/compiler/component.rs
+++ b/crates/cranelift/src/compiler/component.rs
@@ -622,7 +622,10 @@ impl<'a> TrampolineCompiler<'a> {
},
);
}
- Trampoline::SyncStartCall { callback } => {
+ Trampoline::StartCall {
+ callback,
+ post_return,
+ } => {
let pointer_type = self.isa.pointer_type();
let (values_vec_ptr, len) = self.compiler.allocate_stack_array_and_spill_args(
&mut self.alias_regions,
@@ -632,7 +635,7 @@ impl<'a> TrampolineCompiler<'a> {
);
let values_vec_len = self.builder.ins().iconst(pointer_type, i64::from(len));
self.translate_libcall(
- host::sync_start,
+ host::start_call,
HostResult::MultiValue {
ptr: Some(values_vec_ptr),
len: Some(values_vec_len),
@@ -641,28 +644,12 @@ impl<'a> TrampolineCompiler<'a> {
|me, params| {
let vmctx = params[0];
params.push(me.load_callback(vmctx, *callback));
+ params.push(me.load_post_return(vmctx, *post_return));
params.push(values_vec_ptr);
params.push(values_vec_len);
},
);
}
- Trampoline::AsyncStartCall {
- callback,
- post_return,
- } => {
- self.translate_libcall(
- host::async_start,
- TrapSentinel::NegativeOne,
- WasmArgs::InRegisters,
- |me, params| {
- let vmctx = params[0];
- params.extend([
- me.load_callback(vmctx, *callback),
- me.load_post_return(vmctx, *post_return),
- ]);
- },
- );
- }
Trampoline::FutureTransfer => {
self.translate_libcall(
host::future_transfer,
@@ -1423,8 +1410,7 @@ impl<'a> TrampolineCompiler<'a> {
Trampoline::ResourceTransferOwn
| Trampoline::ResourceTransferBorrow
| Trampoline::PrepareCall { .. }
- | Trampoline::SyncStartCall { .. }
- | Trampoline::AsyncStartCall { .. }
+ | Trampoline::StartCall { .. }
| Trampoline::FutureTransfer
| Trampoline::StreamTransfer
| Trampoline::ErrorContextTransfer
diff --git a/crates/environ/src/component.rs b/crates/environ/src/component.rs
index 6d3b93434f..3a75238c9f 100644
--- a/crates/environ/src/component.rs
+++ b/crates/environ/src/component.rs
@@ -46,11 +46,17 @@ pub const PREPARE_ASYNC_WITH_RESULT: u32 = u32::MAX - 1;
/// Bit flag for indicating async-lifted exports
///
-/// This flag may be passed to the `async-start` built-in function (which is
-/// called from both async->async and async->sync adapters) to indicate that the
-/// callee is an async-lifted export.
+/// This flag may be passed to the `start-call` built-in function to indicate
+/// that the callee is an async-lifted export.
pub const START_FLAG_ASYNC_CALLEE: i32 = 1 << 0;
+/// Bit flag for indicating async-lowered imports
+///
+/// This flag may be passed to the `start-call` built-in function to indicate
+/// that the caller is an async-lowered import, in which case the call's status
+/// is returned rather than blocking until the callee produces its results.
+pub const START_FLAG_ASYNC_CALLER: i32 = 1 << 1;
+
mod artifacts;
mod info;
mod intrinsic;
@@ -144,9 +150,7 @@ macro_rules! foreach_builtin_component_function {
storage_len: size
) -> bool;
#[cfg(feature = "component-model-async")]
- sync_start(vmctx: vmctx, callback: ptr_u8, storage: ptr_u8, storage_len: size, callee: ptr_u8, param_count: u32) -> bool;
- #[cfg(feature = "component-model-async")]
- async_start(vmctx: vmctx, callback: ptr_u8, post_return: ptr_u8, callee: ptr_u8, param_count: u32, result_count: u32, flags: u32) -> u64;
+ start_call(vmctx: vmctx, callback: ptr_u8, post_return: ptr_u8, storage: ptr_u8, storage_len: size, callee: ptr_u8, param_count: u32, result_count: u32, flags: u32) -> bool;
#[cfg(feature = "component-model-async")]
future_new(vmctx: vmctx, caller_instance: u32, ty: u32) -> u64;
#[cfg(feature = "component-model-async")]
diff --git a/crates/environ/src/component/dfg.rs b/crates/environ/src/component/dfg.rs
index 3b2aa8a17d..7b26558672 100644
--- a/crates/environ/src/component/dfg.rs
+++ b/crates/environ/src/component/dfg.rs
@@ -463,10 +463,7 @@ pub enum Trampoline {
PrepareCall {
memory: Option<MemoryId>,
},
- SyncStartCall {
- callback: Option<CallbackId>,
- },
- AsyncStartCall {
+ StartCall {
callback: Option<CallbackId>,
post_return: Option<PostReturnId>,
},
@@ -1137,13 +1134,10 @@ impl LinearizeDfg<'_> {
Trampoline::PrepareCall { memory } => info::Trampoline::PrepareCall {
memory: memory.map(|v| self.runtime_memory(v)),
},
- Trampoline::SyncStartCall { callback } => info::Trampoline::SyncStartCall {
- callback: callback.map(|v| self.runtime_callback(v)),
- },
- Trampoline::AsyncStartCall {
+ Trampoline::StartCall {
callback,
post_return,
- } => info::Trampoline::AsyncStartCall {
+ } => info::Trampoline::StartCall {
callback: callback.map(|v| self.runtime_callback(v)),
post_return: post_return.map(|v| self.runtime_post_return(v)),
},
diff --git a/crates/environ/src/component/info.rs b/crates/environ/src/component/info.rs
index 6df332bf41..9d2f623fae 100644
--- a/crates/environ/src/component/info.rs
+++ b/crates/environ/src/component/info.rs
@@ -1044,21 +1044,17 @@ pub enum Trampoline {
memory: Option<RuntimeMemoryIndex>,
},
- /// An intrinsic used by FACT-generated modules to start a call involving a
- /// sync-lowered import and async-lifted export.
- SyncStartCall {
- /// The callee's callback function, if any.
- callback: Option<RuntimeCallbackIndex>,
- },
-
- /// An intrinsic used by FACT-generated modules to start a call involving
- /// an async-lowered import function.
+ /// An intrinsic used by FACT-generated modules to start a call previously
+ /// set up with `PrepareCall`.
+ ///
+ /// This is used for calls where something async is involved, for example an
+ /// async function type, an async lift, or an async lower.
///
- /// Note that `AsyncPrepareCall` and `AsyncStartCall` could theoretically be
- /// combined into a single `AsyncCall` intrinsic, but we separate them to
- /// allow the FACT-generated module to optionally call the callee directly
- /// without an intermediate host stack frame.
- AsyncStartCall {
+ /// Note that `PrepareCall` and `StartCall` could theoretically be combined
+ /// into a single intrinsic, but we separate them to allow the
+ /// FACT-generated module to optionally call the callee directly without an
+ /// intermediate host stack frame.
+ StartCall {
/// The callee's callback, if any.
callback: Option<RuntimeCallbackIndex>,
/// The callee's post-return function, if any.
@@ -1216,8 +1212,7 @@ impl Trampoline {
ResourceTransferOwn => format!("component-resource-transfer-own"),
ResourceTransferBorrow => format!("component-resource-transfer-borrow"),
PrepareCall { .. } => format!("component-prepare-call"),
- SyncStartCall { .. } => format!("component-sync-start-call"),
- AsyncStartCall { .. } => format!("component-async-start-call"),
+ StartCall { .. } => format!("component-start-call"),
FutureTransfer => format!("future-transfer"),
StreamTransfer => format!("stream-transfer"),
ErrorContextTransfer => format!("error-context-transfer"),
diff --git a/crates/environ/src/component/thread_transparency.rs b/crates/environ/src/component/thread_transparency.rs
index 1d3931f5c0..eeeba31322 100644
--- a/crates/environ/src/component/thread_transparency.rs
+++ b/crates/environ/src/component/thread_transparency.rs
@@ -305,8 +305,7 @@ fn trampoline_callable(
| ResourceTransferOwn
| ResourceTransferBorrow
| PrepareCall { .. }
- | SyncStartCall { .. }
- | AsyncStartCall { .. }
+ | StartCall { .. }
| FutureTransfer
| StreamTransfer
| ErrorContextTransfer
diff --git a/crates/environ/src/component/translate/adapt.rs b/crates/environ/src/component/translate/adapt.rs
index a22da96c31..f775e5483c 100644
--- a/crates/environ/src/component/translate/adapt.rs
+++ b/crates/environ/src/component/translate/adapt.rs
@@ -325,15 +325,10 @@ fn fact_import_to_core_def(
fact::Import::PrepareCall { memory } => simple_intrinsic(dfg::Trampoline::PrepareCall {
memory: memory.as_ref().map(|v| dfg.memories.push(unwrap_memory(v))),
}),
- fact::Import::SyncStartCall { callback } => {
- simple_intrinsic(dfg::Trampoline::SyncStartCall {
- callback: callback.clone().map(|v| dfg.callbacks.push(v)),
- })
- }
- fact::Import::AsyncStartCall {
+ fact::Import::StartCall {
callback,
post_return,
- } => simple_intrinsic(dfg::Trampoline::AsyncStartCall {
+ } => simple_intrinsic(dfg::Trampoline::StartCall {
callback: callback.clone().map(|v| dfg.callbacks.push(v)),
post_return: post_return.clone().map(|v| dfg.post_returns.push(v)),
}),
diff --git a/crates/environ/src/fact.rs b/crates/environ/src/fact.rs
index d4645b8cc3..d20674c81c 100644
--- a/crates/environ/src/fact.rs
+++ b/crates/environ/src/fact.rs
@@ -86,7 +86,7 @@ pub struct Module<'a> {
imported_resource_transfer_borrow: Option<FuncIndex>,
// Cached versions of imported trampolines for working with the async ABI.
- imported_async_start_calls: HashMap<(Option<FuncIndex>, Option<FuncIndex>), FuncIndex>,
+ imported_start_calls: HashMap<(Option<FuncIndex>, Option<FuncIndex>, Vec<ValType>), FuncIndex>,
// Cached versions of imported trampolines for working with `stream`s,
// `future`s, and `error-context`s.
@@ -290,7 +290,7 @@ impl<'a> Module<'a> {
helper_worklist: Vec::new(),
imported_resource_transfer_own: None,
imported_resource_transfer_borrow: None,
- imported_async_start_calls: HashMap::new(),
+ imported_start_calls: HashMap::new(),
imported_future_transfer: None,
imported_stream_transfer: None,
imported_error_context_transfer: None,
@@ -594,59 +594,31 @@ impl<'a> Module<'a> {
self.imported_funcs.push(None)
}
- /// Import a host built-in function to start a subtask for a sync-lowered
- /// import call to an async-lifted export.
- ///
- /// This call with block until the subtask has produced result(s) via the
- /// `task.return` intrinsic.
+ /// Import a host built-in function to start a subtask previously set up
+ /// with `prepare-call`.
///
- /// Note that this could potentially be combined with the `sync-prepare`
- /// built-in into a single built-in function that does both jobs. However,
- /// we've kept them separate to allow a future optimization where the caller
- /// calls the callee directly rather than using `sync-start` to have the host
- /// do it.
- fn import_sync_start_call(
- &mut self,
- suffix: &str,
- callback: Option<FuncIndex>,
- results: &[ValType],
- ) -> FuncIndex {
- let ty = self
- .core_types
- .function(&[ValType::FUNCREF, ValType::I32], results);
- self.core_imports.import(
- "sync",
- &format!("[start-call]{suffix}"),
- EntityType::Function(ty),
- );
- let import = Import::SyncStartCall {
- callback: callback
- .map(|callback| self.imported_funcs.get(callback).unwrap().clone().unwrap()),
- };
- self.imports.push(import);
- self.imported_funcs.push(None)
- }
-
- /// Import a host built-in function to start a subtask for an async-lowered
- /// import call to an async- or sync-lifted export.
+ /// For async-lowered imports `results` will be `[i32]`, and for
+ /// sync-lowered imports it'll be the function's normal return type.
///
- /// Note that this could potentially be combined with the `async-prepare`
- /// built-in into a single built-in function that does both jobs. However,
+ /// Note that this could potentially be combined with the `prepare-call`
+ /// built-in into a single built-in function that does both jobs. However,
/// we've kept them separate to allow a future optimization where the caller
- /// calls the callee directly rather than using `async-start` to have the
+ /// calls the callee directly rather than using `start-call` to have the
/// host do it.
- fn import_async_start_call(
+ fn import_start_call(
&mut self,
suffix: &str,
callback: Option<FuncIndex>,
post_return: Option<FuncIndex>,
+ results: &[ValType],
) -> FuncIndex {
+ let key = (callback, post_return, results.to_vec());
self.import_simple_get_and_set(
"async",
&format!("[start-call]{suffix}"),
&[ValType::FUNCREF, ValType::I32, ValType::I32, ValType::I32],
- &[ValType::I32],
- Import::AsyncStartCall {
+ results,
+ Import::StartCall {
callback: callback
.map(|callback| self.imported_funcs.get(callback).unwrap().clone().unwrap()),
post_return: post_return.map(|post_return| {
@@ -657,18 +629,8 @@ impl<'a> Module<'a> {
.unwrap()
}),
},
- |me| {
- me.imported_async_start_calls
- .get(&(callback, post_return))
- .copied()
- },
- |me, v| {
- assert!(
- me.imported_async_start_calls
- .insert((callback, post_return), v)
- .is_none()
- )
- },
+ |me| me.imported_start_calls.get(&key).copied(),
+ |me, v| assert!(me.imported_start_calls.insert(key.clone(), v).is_none()),
)
}
@@ -923,15 +885,9 @@ pub enum Import {
/// specified in the lifted export.
memory: Option<CoreDef>,
},
- /// An intrinsic used by FACT-generated modules to complete a call involving
- /// a sync-lowered import and async-lifted export.
- SyncStartCall {
- /// The callee's callback function, if any.
- callback: Option<CoreDef>,
- },
- /// An intrinsic used by FACT-generated modules to complete a call involving
- /// an async-lowered import function.
- AsyncStartCall {
+ /// An intrinsic used by FACT-generated modules to start a call previously
+ /// set up with `PrepareCall`.
+ StartCall {
/// The callee's callback function, if any.
callback: Option<CoreDef>,
diff --git a/crates/environ/src/fact/trampoline.rs b/crates/environ/src/fact/trampoline.rs
index 04ae907490..09ba83ec14 100644
--- a/crates/environ/src/fact/trampoline.rs
+++ b/crates/environ/src/fact/trampoline.rs
@@ -18,10 +18,11 @@
use crate::component::{
CanonicalAbiInfo, ComponentTypesBuilder, FixedEncoding as FE, FlatType, InterfaceType,
MAX_FLAT_ASYNC_PARAMS, MAX_FLAT_PARAMS, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
- START_FLAG_ASYNC_CALLEE, StringEncoding, Transcode, TypeComponentLocalErrorContextTableIndex,
- TypeEnumIndex, TypeFixedLengthListIndex, TypeFlagsIndex, TypeFutureTableIndex, TypeListIndex,
- TypeMapIndex, TypeOptionIndex, TypeRecordIndex, TypeResourceTableIndex, TypeResultIndex,
- TypeStreamTableIndex, TypeTupleIndex, TypeVariantIndex, VariantInfo,
+ START_FLAG_ASYNC_CALLEE, START_FLAG_ASYNC_CALLER, StringEncoding, Transcode,
+ TypeComponentLocalErrorContextTableIndex, TypeEnumIndex, TypeFixedLengthListIndex,
+ TypeFlagsIndex, TypeFutureTableIndex, TypeListIndex, TypeMapIndex, TypeOptionIndex,
+ TypeRecordIndex, TypeResourceTableIndex, TypeResultIndex, TypeStreamTableIndex, TypeTupleIndex,
+ TypeVariantIndex, VariantInfo,
};
use crate::fact::signature::Signature;
use crate::fact::transcode::Transcoder;
@@ -158,104 +159,44 @@ pub(super) fn compile(module: &mut Module<'_>, adapter: &AdapterData) {
result
};
- match (adapter.lower.options.async_, adapter.lift.options.async_) {
- (false, false) => {
- // We can adapt sync->sync case with only minimal use of intrinsics,
- // e.g. resource enter and exit calls as needed.
- let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
- compiler.compile_sync_to_sync_adapter(adapter, &lower_sig, &lift_sig)
- }
- (true, true) => {
- assert!(module.tunables.concurrency_support);
-
- // In the async->async case, we must compile a couple of helper functions:
- //
- // - `async-start`: copies the parameters from the caller to the callee
- // - `async-return`: copies the result from the callee to the caller
- //
- // Unlike synchronous calls, the above operations are asynchronous
- // and subject to backpressure. If the callee is not yet ready to
- // handle a new call, the `async-start` function will not be called
- // immediately. Instead, control will return to the caller,
- // allowing it to do other work while waiting for this call to make
- // progress. Once the callee indicates it is ready, `async-start`
- // will be called, and sometime later (possibly after various task
- // switch events), when the callee has produced a result, it will
- // call `async-return` via the `task.return` intrinsic, at which
- // point a `STATUS_RETURNED` event will be delivered to the caller.
- let start = async_start_adapter(module);
- let return_ = async_return_adapter(module);
- let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
- compiler.compile_async_to_async_adapter(
- adapter,
- start,
- return_,
- i32::try_from(lift_sig.params.len()).unwrap(),
- &lower_sig,
- );
- }
- (false, true) => {
- assert!(module.tunables.concurrency_support);
+ let lower_async = adapter.lower.options.async_;
+ let lift_async = adapter.lift.options.async_;
+ if !lower_async && !lift_async && !module.types[adapter.lift.ty].async_ {
+ // We can adapt sync->sync case with only minimal use of intrinsics,
+ // e.g. resource enter and exit calls as needed.
+ let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
+ compiler.compile_sync_to_sync_adapter(adapter, &lower_sig, &lift_sig);
+ return;
+ }
- // Like the async->async case above, for the sync->async case we
- // also need `async-start` and `async-return` helper functions to
- // allow the callee to asynchronously "pull" the parameters and
- // "push" the results when it is ready.
- //
- // However, since the caller is using the synchronous ABI, the
- // parameters may have been passed via the stack rather than linear
- // memory. In that case, we pass them to the host to store in a
- // task-local location temporarily in the case of backpressure.
- // Similarly, the host will also temporarily store the results that
- // the callee provides to `async-return` until it is ready to resume
- // the caller.
- let start = async_start_adapter(module);
- let return_ = async_return_adapter(module);
- let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
- compiler.compile_sync_to_async_adapter(
- adapter,
- start,
- return_,
- i32::try_from(lift_sig.params.len()).unwrap(),
- &lower_sig,
- );
- }
- (true, false) => {
- assert!(module.tunables.concurrency_support);
+ assert!(module.tunables.concurrency_support);
- // As with the async->async and sync->async cases above, for the
- // async->sync case we use `async-start` and `async-return` helper
- // functions. Here, those functions allow the host to enforce
- // backpressure in the case where the callee instance already has
- // another synchronous call in progress, in which case we can't
- // start a new one until the current one (and any others already
- // waiting in line behind it) has completed.
- //
- // In the case of backpressure, we'll return control to the caller
- // immediately so it can do other work. Later, once the callee is
- // ready, the host will call the `async-start` function to retrieve
- // the parameters and pass them to the callee. At that point, the
- // callee may block on a host call, at which point the host will
- // suspend the fiber it is running on and allow the caller (or any
- // other ready instance) to run concurrently with the blocked
- // callee. Once the callee finally returns, the host will call the
- // `async-return` function to write the result to the caller's
- // linear memory and deliver a `STATUS_RETURNED` event to the
- // caller.
- let lift_sig = module.types.signature(&adapter.lift);
- let start = async_start_adapter(module);
- let return_ = async_return_adapter(module);
- let (compiler, lower_sig, ..) = compiler(module, adapter);
- compiler.compile_async_to_sync_adapter(
- adapter,
- start,
- return_,
- i32::try_from(lift_sig.params.len()).unwrap(),
- i32::try_from(lift_sig.results.len()).unwrap(),
- &lower_sig,
- );
- }
- }
+ // All other cases are mediated by the host: the caller and/or callee use
+ // the async ABI, or the callee has an async function type (in which case
+ // it's subject to backpressure and exclusive-entry checks even if both
+ // sides are otherwise sync). For these we compile a couple of helper
+ // functions:
+ //
+ // - `async-start`: copies the parameters from the caller to the callee
+ // - `async-return`: copies the result from the callee to the caller
+ //
+ // The host calls `async-start` once the callee is ready to handle a new
+ // call (e.g. it has no backpressure and, if required, its instance isn't
+ // exclusively held by another task), which may not be immediately. It
+ // calls `async-return` once the callee has produced its result, either
+ // via `task.return` (if async-lifted) or by returning (if sync-lifted).
+ //
+ // In the meantime, an async caller gets control back immediately so it can
+ // do other work, and is later notified of the subtask's progress via
+ // events. A sync caller instead blocks until the callee has produced its
+ // result. Since a sync caller may have passed its parameters on the stack
+ // rather than in linear memory, the host stores them in a task-local
+ // location until `async-start` is called, and similarly stores the results
+ // until the caller is resumed.
+ let start = async_start_adapter(module);
+ let return_ = async_return_adapter(module);
+ let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
+ compiler.compile_host_mediated_adapter(adapter, start, return_, &lower_sig, &lift_sig);
}
/// Compiles a helper function as specified by the `Helper` configuration.
@@ -449,28 +390,40 @@ impl<'a, 'b> Compiler<'a, 'b> {
}
}
- /// Compile an adapter function supporting an async-lowered import to an
- /// async-lifted export.
+ /// Compile an adapter function for a call which is mediated by the host,
+ /// i.e. any call other than a sync->sync call to a sync-typed function.
///
- /// This uses a pair of `async-prepare` and `async-start` built-in functions
- /// to set up and start a subtask, respectively. `async-prepare` accepts
+ /// This uses a pair of `prepare-call` and `start-call` built-in functions
+ /// to set up and start a subtask, respectively. `prepare-call` accepts
/// `start` and `return_` functions which copy the parameters and results,
- /// respectively; the host will call the former when the callee has cleared
- /// its backpressure flag and the latter when the callee has called
- /// `task.return`.
- fn compile_async_to_async_adapter(
+ /// respectively; the host will call the former when the callee may be
+ /// entered (e.g. it has no backpressure) and the latter when the callee has
+ /// produced its result.
+ ///
+ /// For an async caller, `start-call` returns the subtask's status. For a
+ /// sync caller, it blocks until the callee has produced its result and
+ /// returns the lowered result, if any.
+ fn compile_host_mediated_adapter(
mut self,
adapter: &AdapterData,
start: FunctionId,
return_: FunctionId,
- param_count: i32,
lower_sig: &Signature,
+ lift_sig: &Signature,
) {
- let start_call =
- self.module
- .import_async_start_call(&adapter.name, adapter.lift.options.callback, None);
+ let async_caller = adapter.lower.options.async_;
+ let start_call = self.module.import_start_call(
+ &adapter.name,
+ adapter.lift.options.callback,
+ adapter.lift.post_return,
+ if async_caller {
+ &[ValType::I32]
+ } else {
+ &lower_sig.results
+ },
+ );
- self.call_prepare(adapter, start, return_, lower_sig, false);
+ self.call_prepare(adapter, start, return_, lower_sig, !async_caller);
// TODO: As an optimization, consider checking the backpressure flag on
// the callee instance and, if it's unset _and_ the callee uses a
@@ -485,13 +438,18 @@ impl<'a, 'b> Compiler<'a, 'b> {
format!("[adapter-callee]{}", adapter.name),
));
+ let mut flags = 0;
+ if async_caller {
+ flags |= START_FLAG_ASYNC_CALLER;
+ }
+ if adapter.lift.options.async_ {
+ flags |= START_FLAG_ASYNC_CALLEE;
+ }
+
self.instruction(RefFunc(adapter.callee.as_u32()));
- self.instruction(I32Const(param_count));
- // The result count for an async callee is either one (if there's a
- // callback) or zero (if there's no callback). We conservatively use
- // one here to ensure the host provides room for the result, if any.
- self.instruction(I32Const(1));
- self.instruction(I32Const(START_FLAG_ASYNC_CALLEE));
+ self.instruction(I32Const(i32::try_from(lift_sig.params.len()).unwrap()));
+ self.instruction(I32Const(i32::try_from(lift_sig.results.len()).unwrap()));
+ self.instruction(I32Const(flags));
self.instruction(Call(start_call.as_u32()));
self.finish()
@@ -588,92 +546,6 @@ impl<'a, 'b> Compiler<'a, 'b> {
self.instruction(Call(prepare.as_u32()));
}
- /// Compile an adapter function supporting a sync-lowered import to an
- /// async-lifted export.
- ///
- /// This uses a pair of `sync-prepare` and `sync-start` built-in functions
- /// to set up and start a subtask, respectively. `sync-prepare` accepts
- /// `start` and `return_` functions which copy the parameters and results,
- /// respectively; the host will call the former when the callee has cleared
- /// its backpressure flag and the latter when the callee has called
- /// `task.return`.
- fn compile_sync_to_async_adapter(
- mut self,
- adapter: &AdapterData,
- start: FunctionId,
- return_: FunctionId,
- lift_param_count: i32,
- lower_sig: &Signature,
- ) {
- let start_call = self.module.import_sync_start_call(
- &adapter.name,
- adapter.lift.options.callback,
- &lower_sig.results,
- );
-
- self.call_prepare(adapter, start, return_, lower_sig, true);
-
- // TODO: As an optimization, consider checking the backpressure flag on
- // the callee instance and, if it's unset _and_ the callee uses a
- // callback, translate the params and call the callee function directly
- // here (and make sure `start_call` knows _not_ to call it in that case).
-
- // We export this function so we can pass a funcref to the host.
- //
- // TODO: Use a declarative element segment instead of exporting this.
- self.module.exports.push((
- adapter.callee.as_u32(),
- format!("[adapter-callee]{}", adapter.name),
- ));
-
- self.instruction(RefFunc(adapter.callee.as_u32()));
- self.instruction(I32Const(lift_param_count));
- self.instruction(Call(start_call.as_u32()));
-
- self.finish()
- }
-
- /// Compile an adapter function supporting an async-lowered import to a
- /// sync-lifted export.
- ///
- /// This uses a pair of `async-prepare` and `async-start` built-in functions
- /// to set up and start a subtask, respectively. `async-prepare` accepts
- /// `start` and `return_` functions which copy the parameters and results,
- /// respectively; the host will call the former when the callee has cleared
- /// its backpressure flag and the latter when the callee has returned its
- /// result(s).
- fn compile_async_to_sync_adapter(
- mut self,
- adapter: &AdapterData,
- start: FunctionId,
- return_: FunctionId,
- param_count: i32,
- result_count: i32,
- lower_sig: &Signature,
- ) {
- let start_call =
- self.module
- .import_async_start_call(&adapter.name, None, adapter.lift.post_return);
-
- self.call_prepare(adapter, start, return_, lower_sig, false);
-
- // We export this function so we can pass a funcref to the host.
- //
- // TODO: Use a declarative element segment instead of exporting this.
- self.module.exports.push((
- adapter.callee.as_u32(),
- format!("[adapter-callee]{}", adapter.name),
- ));
-
- self.instruction(RefFunc(adapter.callee.as_u32()));
- self.instruction(I32Const(param_count));
- self.instruction(I32Const(result_count));
- self.instruction(I32Const(0));
- self.instruction(Call(start_call.as_u32()));
-
- self.finish()
- }
-
/// Compiles a function to be exported to the host which host to lift the
/// parameters from the caller and lower them to the callee.
///
@@ -1050,7 +922,7 @@ impl<'a, 'b> Compiler<'a, 'b> {
let abi = CanonicalAbiInfo::record(src_tys.iter().map(|t| self.types.canonical_abi(t)));
assert_eq!(
result_locals.len(),
- if lower_opts.async_ || lift_opts.async_ {
+ if lower_opts.async_ || lift_opts.async_ || self.types[adapter.lift.ty].async_ {
2
} else {
1
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index 3ec9f9ca09..395b771f12 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -214,10 +214,9 @@ mod callback_code {
pub const WAIT: u32 = 2;
}
-/// A flag indicating that the callee is an async-lowered export.
-///
-/// This may be passed to the `async-start` intrinsic from a fused adapter.
+// Flags passed to the `start-call` intrinsic.
const START_FLAG_ASYNC_CALLEE: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLEE as u32;
+const START_FLAG_ASYNC_CALLER: u32 = wasmtime_environ::component::START_FLAG_ASYNC_CALLER as u32;
/// Provides access to either store data (via the `get` method) or the store
/// itself (via [`AsContext`]/[`AsContextMut`]), as well as the component
@@ -3353,6 +3352,11 @@ impl Instance {
/// `wasmtime_environ::fact::trampoline::Compiler`. The adapter will call
/// this function immediately after calling `Self::prepare_call`.
///
+ /// If `flags` contains `START_FLAG_ASYNC_CALLER` then the caller used an
+ /// async-lowered import and the call's packed status is written to
+ /// `storage[0]`. Otherwise this blocks until the callee has produced its
+ /// result, if any, which is written to `storage[0]`.
+ ///
/// SAFETY: The `*mut VMFuncRef` arguments must be valid pointers to guest
/// functions with the appropriate signatures for the current guest task.
/// If this is a call to an async-lowered import, the actual call may be
@@ -3367,10 +3371,10 @@ impl Instance {
param_count: u32,
result_count: u32,
flags: u32,
- storage: Option<&mut [MaybeUninit<ValRaw>]>,
- ) -> Result<u32> {
+ storage: &mut [MaybeUninit<ValRaw>],
+ ) -> Result<()> {
let token = StoreToken::new(store.as_context_mut());
- let async_caller = storage.is_none();
+ let async_caller = (flags & START_FLAG_ASYNC_CALLER) != 0;
let guest_thread = store.0.current_guest_thread()?;
let state = store.0.concurrent_state_mut()?;
@@ -3533,10 +3537,14 @@ impl Instance {
.state = GuestThreadState::Running;
log::trace!("popped current thread {guest_thread:?}; new thread is {caller:?}");
- if let Some(storage) = storage {
- // The caller used a sync-lowered import to call an async-lifted
- // export, in which case the result, if any, has been stashed in
- // `GuestTask::sync_result`.
+ if async_caller {
+ let Some(slot) = storage.first_mut() else {
+ bail_bug!("no storage for async call status");
+ };
+ *slot = MaybeUninit::new(ValRaw::u32(status.pack(waitable)));
+ } else {
+ // The caller used a sync-lowered import, in which case the result,
+ // if any, has been stashed in `GuestTask::sync_result`.
let state = store.0.concurrent_state_mut()?;
let task = state.get_mut(guest_thread.task)?;
if let Some(result) = task.sync_result.take()? {
@@ -3550,7 +3558,7 @@ impl Instance {
}
}
- Ok(status.pack(waitable))
+ Ok(())
}
/// Poll the specified future once on behalf of a guest->host call using an
@@ -4606,21 +4614,9 @@ pub trait VMComponentAsyncStore {
storage_len: usize,
) -> Result<()>;
- /// A helper function for fused adapter modules involving calls where the
- /// caller is sync-lowered but the callee is async-lifted.
- unsafe fn sync_start(
- &mut self,
- instance: Instance,
- callback: *mut VMFuncRef,
- callee: NonNull<VMFuncRef>,
- param_count: u32,
- storage: *mut MaybeUninit<ValRaw>,
- storage_len: usize,
- ) -> Result<()>;
-
- /// A helper function for fused adapter modules involving calls where the
- /// caller is async-lowered.
- unsafe fn async_start(
+ /// A helper function for fused adapter modules to start a call previously
+ /// set up with `prepare_call`.
+ unsafe fn start_call(
&mut self,
instance: Instance,
callback: *mut VMFuncRef,
@@ -4629,7 +4625,9 @@ pub trait VMComponentAsyncStore {
param_count: u32,
result_count: u32,
flags: u32,
- ) -> Result<u32>;
+ storage: *mut MaybeUninit<ValRaw>,
+ storage_len: usize,
+ ) -> Result<()>;
/// The `future.write` intrinsic.
fn future_write(
@@ -4796,35 +4794,7 @@ impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
}
}
- unsafe fn sync_start(
- &mut self,
- instance: Instance,
- callback: *mut VMFuncRef,
- callee: NonNull<VMFuncRef>,
- param_count: u32,
- storage: *mut MaybeUninit<ValRaw>,
- storage_len: usize,
- ) -> Result<()> {
- unsafe {
- instance
- .start_call(
- StoreContextMut(self),
- callback,
- ptr::null_mut(),
- callee,
- param_count,
- 1,
- START_FLAG_ASYNC_CALLEE,
- // SAFETY: The `wasmtime_cranelift`-generated code that calls
- // this method will have ensured that `storage` is a valid
- // pointer containing at least `storage_len` items.
- Some(core::slice::from_raw_parts_mut(storage, storage_len)),
- )
- .map(drop)
- }
- }
-
- unsafe fn async_start(
+ unsafe fn start_call(
&mut self,
instance: Instance,
callback: *mut VMFuncRef,
@@ -4833,7 +4803,9 @@ impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
param_count: u32,
result_count: u32,
flags: u32,
- ) -> Result<u32> {
+ storage: *mut MaybeUninit<ValRaw>,
+ storage_len: usize,
+ ) -> Result<()> {
unsafe {
instance.start_call(
StoreContextMut(self),
@@ -4843,7 +4815,10 @@ impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
param_count,
result_count,
flags,
- None,
+ // SAFETY: The `wasmtime_cranelift`-generated code that calls
+ // this method will have ensured that `storage` is a valid
+ // pointer containing at least `storage_len` items.
+ core::slice::from_raw_parts_mut(storage, storage_len),
)
}
}
diff --git a/crates/wasmtime/src/runtime/vm/component/libcalls.rs b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
index d41b3e831f..863f2e59b3 100644
--- a/crates/wasmtime/src/runtime/vm/component/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
@@ -862,40 +862,20 @@ unsafe fn prepare_call(
}
#[cfg(feature = "component-model-async")]
-unsafe fn sync_start(
+unsafe fn start_call(
store: &mut dyn VMStore,
instance: Instance,
callback: *mut u8,
+ post_return: *mut u8,
storage: *mut u8,
storage_len: usize,
callee: *mut u8,
param_count: u32,
-) -> Result<()> {
- unsafe {
- store.component_async_store().sync_start(
- instance,
- callback.cast::<crate::vm::VMFuncRef>(),
- NonNull::new(callee).unwrap().cast::<crate::vm::VMFuncRef>(),
- param_count,
- storage.cast::<core::mem::MaybeUninit<crate::ValRaw>>(),
- storage_len,
- )
- }
-}
-
-#[cfg(feature = "component-model-async")]
-unsafe fn async_start(
- store: &mut dyn VMStore,
- instance: Instance,
- callback: *mut u8,
- post_return: *mut u8,
- callee: *mut u8,
- param_count: u32,
result_count: u32,
flags: u32,
-) -> Result<u32> {
+) -> Result<()> {
unsafe {
- store.component_async_store().async_start(
+ store.component_async_store().start_call(
instance,
callback.cast::<crate::vm::VMFuncRef>(),
post_return.cast::<crate::vm::VMFuncRef>(),
@@ -903,6 +883,8 @@ unsafe fn async_start(
param_count,
result_count,
flags,
+ storage.cast::<core::mem::MaybeUninit<crate::ValRaw>>(),
+ storage_len,
)
}
}
diff --git a/tests/misc_testsuite/component-model/async/sync-lower-async-typed-entry-checks.wast b/tests/misc_testsuite/component-model/async/sync-lower-async-typed-entry-checks.wast
new file mode 100644
index 0000000000..bd05b37b5b
--- /dev/null
+++ b/tests/misc_testsuite/component-model/async/sync-lower-async-typed-entry-checks.wast
@@ -0,0 +1,334 @@
+;;! component_model_async = true
+;;! reference_types = true
+;;! bulk_memory = true
+
+;; A sync-lowered call to a sync-lifted export with an `async` function type is
+;; subject to the same backpressure and exclusive-entry checks as any other
+;; call to an `async`-typed function (see `Task.enter_implicit_thread` in the
+;; spec): the callee doesn't start until both allow it, and the sync-lowered
+;; caller blocks in the meantime.
+
+;; Backpressure is set on the callee's instance and never released, so the
+;; callee never starts and the caller blocks forever.
+(component
+ (component $X
+ (core func $backpressure.inc (canon backpressure.inc))
+ (core module $x
+ (import "" "backpressure.inc" (func $backpressure.inc))
+ (func (export "bp-inc") (call $backpressure.inc))
+ (func (export "h") (result i32) unreachable))
+ (core instance $x (instantiate $x
+ (with "" (instance
+ (export "backpressure.inc" (func $backpressure.inc))))))
+ (func (export "bp-inc") (canon lift (core func $x "bp-inc")))
+ (func (export "h") async (result u32) (canon lift (core func $x "h")))
+ )
+ (component $Y
+ (import "x" (instance $x
+ (export "bp-inc" (func))
+ (export "h" (func async (result u32)))))
+ (core func $bp-inc (canon lower (func $x "bp-inc")))
+ (core func $h (canon lower (func $x "h")))
+ (core func $task.return (canon task.return (result u32)))
+ (core module $y
+ (import "" "bp-inc" (func $bp-inc))
+ (import "" "h" (func $h (result i32)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (func (export "run") (result i32)
+ (call $bp-inc)
+ call $h
+ unreachable
+ )
+ (func (export "callback") (param i32 i32 i32) (result i32) unreachable))
+ (core instance $y (instantiate $y (with "" (instance
+ (export "bp-inc" (func $bp-inc))
+ (export "h" (func $h))
+ (export "task.return" (func $task.return))))))
+ (func (export "run") async (result u32)
+ (canon lift (core func $y "run") async
+ (callback (core func $y "callback"))))
+ )
+ (instance $x (instantiate $X))
+ (instance $y (instantiate $Y (with "x" (instance $x))))
+ (export "run" (func $y "run"))
+)
+
+(assert_trap (invoke "run") "deadlock detected")
+
+;; Backpressure is set on the callee's instance and later released by another
+;; task in that instance, at which point the callee starts and the blocked
+;; caller resumes.
+(component
+ (component $X
+ (core func $backpressure.inc (canon backpressure.inc))
+ (core func $backpressure.dec (canon backpressure.dec))
+ (core func $task.return (canon task.return))
+ (core module $x
+ (import "" "backpressure.inc" (func $backpressure.inc))
+ (import "" "backpressure.dec" (func $backpressure.dec))
+ (import "" "task.return" (func $task.return))
+ (global $released (mut i32) (i32.const 0))
+ (func (export "bp-inc") (call $backpressure.inc))
+ (func (export "release") (result i32)
+ i32.const 1 ;; YIELD
+ )
+ (func (export "release-cb") (param i32 i32 i32) (result i32)
+ (global.set $released (i32.const 1))
+ (call $backpressure.dec)
+ (call $task.return)
+ i32.const 0 ;; EXIT
+ )
+ (func (export "h") (result i32)
+ ;; `h` must not start until backpressure has been released.
+ (if (i32.eqz (global.get $released)) (then unreachable))
+ i32.const 42))
+ (core instance $x (instantiate $x (with "" (instance
+ (export "backpressure.inc" (func $backpressure.inc))
+ (export "backpressure.dec" (func $backpressure.dec))
+ (export "task.return" (func $task.return))))))
+ (func (export "bp-inc") (canon lift (core func $x "bp-inc")))
+ (func (export "release") async
+ (canon lift (core func $x "release") async
+ (callback (core func $x "release-cb"))))
+ (func (export "h") async (result u32) (canon lift (core func $x "h")))
+ )
+ (component $Y
+ (import "x" (instance $x
+ (export "bp-inc" (func))
+ (export "release" (func async))
+ (export "h" (func async (result u32)))))
+ (core func $bp-inc (canon lower (func $x "bp-inc")))
+ (core func $release (canon lower (func $x "release") async))
+ (core func $h (canon lower (func $x "h")))
+ (core func $task.return (canon task.return (result u32)))
+ (core module $y
+ (import "" "bp-inc" (func $bp-inc))
+ (import "" "release" (func $release (result i32)))
+ (import "" "h" (func $h (result i32)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (func (export "run") (result i32)
+ ;; Start a task in `x` which will release backpressure once it's
+ ;; resumed after yielding.
+ (drop (call $release))
+ (call $bp-inc)
+ ;; Blocks until `release` has released backpressure.
+ (call $task.return (call $h))
+ i32.const 0 ;; EXIT
+ )
+ (func (export "callback") (param i32 i32 i32) (result i32) unreachable))
+ (core instance $y (instantiate $y (with "" (instance
+ (export "bp-inc" (func $bp-inc))
+ (export "release" (func $release))
+ (export "h" (func $h))
+ (export "task.return" (func $task.return))))))
+ (func (export "run") async (result u32)
+ (canon lift (core func $y "run") async
+ (callback (core func $y "callback"))))
+ )
+ (instance $x (instantiate $X))
+ (instance $y (instantiate $Y (with "x" (instance $x))))
+ (export "run" (func $y "run"))
+)
+
+(assert_return (invoke "run") (u32.const 42))
+
+;; `c`, a callback-lifted export of `$inner`, holds `$inner`'s exclusive lock
+;; while it makes a sync-lowered call which, via an `async`-typed shim in the
+;; outer component, makes a sync-lowered call to `h`, an `async`-typed but
+;; sync-lifted export of `$inner`. `h` needs the exclusive lock which `c` never
+;; releases, so it never starts.
+(component
+ (core module $shim
+ (table (export "funcs") 1 1 funcref)
+ (func (export "export") (result i32)
+ (call_indirect (result i32) (i32.const 0))))
+ (core instance $shim (instantiate $shim))
+ (func $shim-export async (result u32) (canon lift (core func $shim "export")))
+
+ (component $inner
+ (import "import" (func $import async (result u32)))
+ (core func $import (canon lower (func $import)))
+ (core func $task.return (canon task.return (result u32)))
+ (core module $m
+ (import "" "import" (func $import (result i32)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (func (export "c") (result i32)
+ (call $task.return (call $import))
+ i32.const 0 ;; EXIT
+ )
+ (func (export "callback") (param i32 i32 i32) (result i32) unreachable)
+ (func (export "h") (result i32) (i32.const 7)))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "task.return" (func $task.return))
+ (export "import" (func $import))))))
+ (func (export "c") async (result u32)
+ (canon lift (core func $i "c") async
+ (callback (core func $i "callback"))))
+ (func (export "h") async (result u32)
+ (canon lift (core func $i "h"))))
+ (instance $inner (instantiate $inner (with "import" (func $shim-export))))
+
+ (core func $inner-h (canon lower (func $inner "h")))
+ (core module $donut
+ (import "" "funcs" (table 1 1 funcref))
+ (import "" "h" (func $h (result i32)))
+ (func $guest-export (result i32) (call $h))
+ (elem declare func $guest-export)
+ (func $start (table.set (i32.const 0) (ref.func $guest-export)))
+ (start $start))
+ (core instance $donut (instantiate $donut
+ (with "" (instance
+ (export "h" (func $inner-h))
+ (export "funcs" (table $shim "funcs"))))))
+ (export "c" (func $inner "c"))
+)
+
+(assert_trap (invoke "c") "deadlock detected")
+
+;; Same as above, but the shim is sync-typed. A sync-typed task which blocks
+;; with no other thread in its instance to run traps.
+(component
+ (core module $shim
+ (table (export "funcs") 1 1 funcref)
+ (func (export "export") (result i32)
+ (call_indirect (result i32) (i32.const 0))))
+ (core instance $shim (instantiate $shim))
+ (func $shim-export (result u32) (canon lift (core func $shim "export")))
+
+ (component $inner
+ (import "import" (func $import (result u32)))
+ (core func $import (canon lower (func $import)))
+ (core func $task.return (canon task.return (result u32)))
+ (core module $m
+ (import "" "import" (func $import (result i32)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (func (export "c") (result i32)
+ (call $task.return (call $import))
+ i32.const 0 ;; EXIT
+ )
+ (func (export "callback") (param i32 i32 i32) (result i32) unreachable)
+ (func (export "h") (result i32) (i32.const 7)))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "task.return" (func $task.return))
+ (export "import" (func $import))))))
+ (func (export "c") async (result u32)
+ (canon lift (core func $i "c") async
+ (callback (core func $i "callback"))))
+ (func (export "h") async (result u32)
+ (canon lift (core func $i "h"))))
+ (instance $inner (instantiate $inner (with "import" (func $shim-export))))
+
+ (core func $inner-h (canon lower (func $inner "h")))
+ (core module $donut
+ (import "" "funcs" (table 1 1 funcref))
+ (import "" "h" (func $h (result i32)))
+ (func $guest-export (result i32) (call $h))
+ (elem declare func $guest-export)
+ (func $start (table.set (i32.const 0) (ref.func $guest-export)))
+ (start $start))
+ (core instance $donut (instantiate $donut
+ (with "" (instance
+ (export "h" (func $inner-h))
+ (export "funcs" (table $shim "funcs"))))))
+ (export "c" (func $inner "c"))
+)
+
+(assert_trap (invoke "c") "cannot block a synchronous task before returning")
+
+;; `c` makes an async-lowered call to the `async`-typed shim, which in turn
+;; makes a sync-lowered call to `h`. `h` can't start until `c` releases
+;; `$inner`'s exclusive lock by returning `WAIT`, after which `h` runs and `c`
+;; receives the result.
+(component
+ (core module $shim
+ (table (export "funcs") 1 1 funcref)
+ (func (export "export") (result i32)
+ (call_indirect (result i32) (i32.const 0))))
+ (core instance $shim (instantiate $shim))
+ (func $shim-export async (result u32) (canon lift (core func $shim "export")))
+
+ (component $inner
+ (import "import" (func $import async (result u32)))
+ (core module $libc (memory (export "mem") 1))
+ (core instance $libc (instantiate $libc))
+ (core func $import
+ (canon lower (func $import) async (memory (core memory $libc "mem"))))
+ (core func $task.return (canon task.return (result u32)))
+ (core func $waitable-set.new (canon waitable-set.new))
+ (core func $waitable-set.drop (canon waitable-set.drop))
+ (core func $waitable.join (canon waitable.join))
+ (core func $subtask.drop (canon subtask.drop))
+ (core module $m
+ (import "" "mem" (memory 1))
+ (import "" "import" (func $import (param i32) (result i32)))
+ (import "" "task.return" (func $task.return (param i32)))
+ (import "" "waitable-set.new" (func $waitable-set.new (result i32)))
+ (import "" "waitable-set.drop" (func $waitable-set.drop (param i32)))
+ (import "" "waitable.join" (func $waitable.join (param i32 i32)))
+ (import "" "subtask.drop" (func $subtask.drop (param i32)))
+ (global $in-c (mut i32) (i32.const 0))
+ (global $set (mut i32) (i32.const 0))
+ (func (export "c") (result i32)
+ (local $status i32)
+ (global.set $in-c (i32.const 1))
+ (local.set $status (call $import (i32.const 100)))
+ ;; The subtask must not have returned yet since `h` can't start until
+ ;; we return.
+ (if (i32.ne (i32.and (local.get $status) (i32.const 0xf)) (i32.const 1))
+ (then unreachable))
+ (global.set $set (call $waitable-set.new))
+ (call $waitable.join
+ (i32.shr_u (local.get $status) (i32.const 4))
+ (global.get $set))
+ (global.set $in-c (i32.const 0))
+ ;; WAIT on `$set`
+ (i32.or (i32.const 2) (i32.shl (global.get $set) (i32.const 4)))
+ )
+ (func (export "callback")
+ (param $event i32) (param $handle i32) (param $status i32) (result i32)
+ ;; expect EVENT_SUBTASK with STATUS_RETURNED
+ (if (i32.ne (local.get $event) (i32.const 1)) (then unreachable))
+ (if (i32.ne (local.get $status) (i32.const 2)) (then unreachable))
+ (call $subtask.drop (local.get $handle))
+ (call $waitable-set.drop (global.get $set))
+ (call $task.return (i32.load (i32.const 100)))
+ i32.const 0 ;; EXIT
+ )
+ (func (export "h") (result i32)
+ ;; `h` must not run while `c` is running.
+ (if (global.get $in-c) (then unreachable))
+ i32.const 7))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "mem" (memory $libc "mem"))
+ (export "task.return" (func $task.return))
+ (export "import" (func $import))
+ (export "waitable-set.new" (func $waitable-set.new))
+ (export "waitable-set.drop" (func $waitable-set.drop))
+ (export "waitable.join" (func $waitable.join))
+ (export "subtask.drop" (func $subtask.drop))))))
+ (func (export "c") async (result u32)
+ (canon lift (core func $i "c") async
+ (callback (core func $i "callback"))))
+ (func (export "h") async (result u32)
+ (canon lift (core func $i "h"))))
+ (instance $inner (instantiate $inner (with "import" (func $shim-export))))
+
+ (core func $inner-h (canon lower (func $inner "h")))
+ (core module $donut
+ (import "" "funcs" (table 1 1 funcref))
+ (import "" "h" (func $h (result i32)))
+ (func $guest-export (result i32) (call $h))
+ (elem declare func $guest-export)
+ (func $start (table.set (i32.const 0) (ref.func $guest-export)))
+ (start $start))
+ (core instance $donut (instantiate $donut
+ (with "" (instance
+ (export "h" (func $inner-h))
+ (export "funcs" (table $shim "funcs"))))))
+ (export "c" (func $inner "c"))
+)
+
+(assert_return (invoke "c") (u32.const 7))
diff --git a/tests/misc_testsuite/component-model/thread-transparency/reentrancy.wast b/tests/misc_testsuite/component-model/thread-transparency/reentrancy.wast
index 9db5a41bbf..326b84d486 100644
--- a/tests/misc_testsuite/component-model/thread-transparency/reentrancy.wast
+++ b/tests/misc_testsuite/component-model/thread-transparency/reentrancy.wast
@@ -5,19 +5,20 @@
;; Sync-to-sync adapters between sibling instances have no dynamic `may_enter`
;; check, so a guest that cares about reentrance has to guard against it itself.
-;; This exercises the case where it actually happens:
+;; This exercises a case where it could happen:
;;
;; host --async-lift--> $Outer --adapter--> $Mid --async-typed--> $Inner
;;
-;; $Inner blocks on a fresh, empty waitable set. Blocking in a sync-typed call
-;; no longer traps outright: the scheduler first looks for another eligible
-;; thread to run, and $Outer has started a second one. That second thread calls
-;; $Mid.f while the first call's frame is still live, reentrance now being
-;; permitted, so $Mid's own `$inside` guard is what fires.
+;; $Inner blocks on a fresh, empty waitable set, and $Outer has started a second
+;; thread which would call $Mid.f while the first call's frame is still live.
+;; However, since $Inner.g is `async`-typed, blocking in it returns control to
+;; $Mid.f's sync-lowered call, which then blocks waiting for $Inner.g to
+;; return. $Mid.f is sync-typed, so when it blocks the only threads eligible to
+;; run are those in $Mid's own instance (see `canon_lift` in the spec), of
+;; which there are none, so this traps before $Mid.f can be reentered.
;;
-;; This is not an artifact of dropping the `{enter,exit}-sync-call` window: the
-;; $Outer -> $Mid adapter is opaque here anyway, because $Mid lowers an
-;; `async`-typed lift.
+;; Note that the $Outer -> $Mid adapter is opaque here regardless of the
+;; `{enter,exit}-sync-call` elision, because $Mid lowers an `async`-typed lift.
(component definition $Tester
(component $Inner
@@ -111,4 +112,4 @@
)
(component instance $i $Tester)
-(assert_trap (invoke "run") "wasm `unreachable` instruction executed")
+(assert_trap (invoke "run") "cannot block a synchronous task before returning")