A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
component: centralize `may_enter` check (#15069)
Adam Bratschi-Kaye5c6eb7fef1f1
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rsindex 8b9d582b7f..560389d31e 100644--- a/crates/wasmtime/src/runtime/component/concurrent.rs+++ b/crates/wasmtime/src/runtime/component/concurrent.rs@@ -1433,7 +1433,7 @@ impl<T> StoreContextMut<'_, T> {// unwound. Note that this is checked after polling `future`// above so that it can observe the original error, e.g. a// trap delivered over a oneshot channel by a work item.- if reset.store.0.trapped() {+ if reset.store.0.component_trapped() {return Poll::Ready(Err(Trap::CannotEnterComponent.into()));}@@ -6813,6 +6813,9 @@ pub(crate) fn prepare_call<T, R>(+ Sync+ 'static,) -> Result<PreparedCall<R>> {+ // This check should be redundant, but leave it here so that there is a+ // clear error when trying to execute wasm in a poisoned store instead of+ // possibly hitting some other `bail_bug!` because of inconsistent state.if !store.0.may_enter() {bail!(Trap::CannotEnterComponent);}diff --git a/crates/wasmtime/src/runtime/component/func.rs b/crates/wasmtime/src/runtime/component/func.rsindex 8d4e9cdb80..749f9618db 100644--- a/crates/wasmtime/src/runtime/component/func.rs+++ b/crates/wasmtime/src/runtime/component/func.rs@@ -466,10 +466,6 @@ impl Func {let instance = self.instance.runtime_instance(raw_options.instance);let async_ = raw_options.async_;- if !store.0.may_enter() {- bail!(crate::Trap::CannotEnterComponent);- }-store.0.enter_guest_sync_call(async_, instance)?;#[repr(C)]diff --git a/crates/wasmtime/src/runtime/component/func/host.rs b/crates/wasmtime/src/runtime/component/func/host.rsindex d639eb23bb..7856067c90 100644--- a/crates/wasmtime/src/runtime/component/func/host.rs+++ b/crates/wasmtime/src/runtime/component/func/host.rs@@ -456,7 +456,7 @@ where// If the store was poisoned while the host function ran, e.g. because// it made a nested call back into the guest which failed but then// returned normally, then don't let the guest continue running.- if store.0.trapped() {+ if store.0.component_trapped() {bail!(crate::Trap::CannotEnterComponent);}diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rsindex f299a57fd9..c4c99683f4 100644--- a/crates/wasmtime/src/runtime/component/resources/any.rs+++ b/crates/wasmtime/src/runtime/component/resources/any.rs@@ -16,7 +16,7 @@ use crate::component::resources::{HostResourceIndex, HostResourceTables};use crate::component::{ComponentType, Lift, Lower, Resource, ResourceDynamic, ResourceType};use crate::prelude::*;use crate::runtime::vm::{UncaughtException, ValRaw};-use crate::{AsContextMut, StoreContextMut, Trap};+use crate::{AsContextMut, StoreContextMut};use core::mem::MaybeUninit;use core::ptr::NonNull;use wasmtime_environ::component::{CanonicalAbiInfo, InterfaceType};@@ -378,10 +378,6 @@ impl ResourceAny {_ => unreachable!(),};- if slot.instance.is_some() && !store.0.may_enter() {- bail!(Trap::CannotEnterComponent);- }-let dtor = match slot.dtor {Some(dtor) => dtor.as_non_null(),None => return Ok(()),diff --git a/crates/wasmtime/src/runtime/component/store.rs b/crates/wasmtime/src/runtime/component/store.rsindex 1da49249ed..7de6329eb4 100644--- a/crates/wasmtime/src/runtime/component/store.rs+++ b/crates/wasmtime/src/runtime/component/store.rs@@ -39,8 +39,16 @@ pub struct ComponentStoreData {/// are managed.instances: TryPrimaryMap<ComponentInstanceId, Option<OwnedComponentInstance>>,- /// Whether an instance belonging to this store has trapped.- trapped: bool,+ /// Whether an component instance belonging to this store has trapped. This+ /// can be used to determine if the `Store` is poisoned.+ ///+ /// This is only set if a trap occurs while `has_components` is also set.+ /// Pure core Wasm instances are required to continue running after traps+ /// so `Store`s with only core modules are never considered poisoned.+ component_trapped: bool,++ /// Whether a component instance has ever been created in this store.+ has_components: bool,/// Total number of component instances in this store, used to track/// resources in the instance allocator.@@ -95,7 +103,8 @@ impl ComponentStoreData {pub fn new(engine: &Engine) -> ComponentStoreData {ComponentStoreData {instances: Default::default(),- trapped: false,+ component_trapped: false,+ has_components: false,num_component_instances: 0,component_host_table: Default::default(),handle_counter: HandleCounter::new(DEFAULT_MAX_COMPONENT_HANDLES),@@ -294,6 +303,7 @@ impl StoreData {let expected = data.get().id();let ret = self.components.instances.push(Some(data))?;assert_eq!(expected, ret);+ self.components.has_components = true;Ok(ret)}@@ -322,19 +332,24 @@ impl StoreData {}impl StoreOpaque {- pub(crate) fn trapped(&self) -> bool {- self.store_data().components.trapped+ #[inline]+ pub(crate) fn component_trapped(&self) -> bool {+ self.store_data().components.component_trapped}pub(crate) fn set_trapped(&mut self) {- self.store_data_mut().components.trapped = true;+ let component_data = &mut self.store_data_mut().components;+ if component_data.has_components {+ component_data.component_trapped = true;+ }}/// Determine whether an instance may be entered from the host.////// We return `false` here only `self` has been poisoned due to a trap.+ #[inline]pub(crate) fn may_enter(&mut self) -> bool {- !self.trapped()+ !self.component_trapped()}pub(crate) fn component_data(&self) -> &ComponentStoreData {diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rsindex d7de03f1fb..d4b42fd6c2 100644--- a/crates/wasmtime/src/runtime/func.rs+++ b/crates/wasmtime/src/runtime/func.rs@@ -1469,6 +1469,13 @@ pub(crate) fn invoke_wasm_and_catch_traps<T>(uncaught_exception: crate::runtime::vm::UncaughtException,closure: impl FnMut(NonNull<VMContext>, Option<InterpreterRef<'_>>) -> bool,) -> Result<()> {+ // A store containing components is poisoned once anything in it traps, and+ // no wasm may run in it afterwards.+ #[cfg(feature = "component-model")]+ if !store.0.may_enter() {+ return Err(crate::Trap::CannotEnterComponent.into());+ }+// The `enter_wasm` call below will reset the store context's// `stack_chain` to a new `InitialStack`, pointing to the// stack-allocated `initial_stack_csi`.diff --git a/tests/all/component_model/instance.rs b/tests/all/component_model/instance.rsindex e7ad1c3c6c..c4912203ff 100644--- a/tests/all/component_model/instance.rs+++ b/tests/all/component_model/instance.rs@@ -1,6 +1,6 @@use wasmtime::Result;use wasmtime::component::*;-use wasmtime::{Module, Store};+use wasmtime::{Module, Store, StoreContextMut, Trap};#[test]#[cfg_attr(miri, ignore)]@@ -228,3 +228,66 @@ fn export_type_ascription_hides_exports() -> Result<()> {Ok(())}++#[test]+#[cfg_attr(miri, ignore)]+fn start_function_not_run_in_poisoned_store() -> Result<()> {+ let engine = super::engine();++ let trapper = Component::new(+ &engine,+ r#"+(component+ (core module $m (func (export "trap") unreachable))+ (core instance $m (instantiate $m))+ (func (export "trap") (canon lift (core func $m "trap")))+)+ "#,+ )?;++ // The start function calls a host import so we can observe whether it+ // ran.+ let starter = Component::new(+ &engine,+ r#"+ (component+ (import "ran" (func $ran))+ (core func $ran_lower (canon lower (func $ran)))+ (core module $m+ (import "host" "ran" (func $ran))+ (func $start call $ran)+ (start $start)+ )+ (core instance (instantiate $m+ (with "host" (instance (export "ran" (func $ran_lower))))+ ))+ )+ "#,+ )?;++ let mut store = Store::new(&engine, false);+ let mut linker = Linker::new(&engine);+ linker+ .root()+ .func_wrap("ran", |mut store: StoreContextMut<'_, bool>, _: ()| {+ *store.data_mut() = true;+ Ok(())+ })?;++ // Poison the store with a trap.+ let instance = linker.instantiate(&mut store, &trapper)?;+ let trap = instance.get_typed_func::<(), ()>(&mut store, "trap")?;+ assert!(trap.call(&mut store, ()).is_err());++ // Instantiating into the poisoned store must fail without running the+ // start function.+ let err = linker.instantiate(&mut store, &starter).unwrap_err();+ assert_eq!(+ err.downcast_ref::<Trap>(),+ Some(&Trap::CannotEnterComponent),+ "{err:?}"+ );+ assert!(!*store.data(), "start function ran in a poisoned store");++ Ok(())+}