A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix some API unsoundness with invalid cross-`Engine` usage (#14044)
Alex Crichton0437a8232422
diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rsindex 028ec394ef..7ab6722853 100644--- a/crates/wasmtime/src/runtime/component/linker.rs+++ b/crates/wasmtime/src/runtime/component/linker.rs@@ -227,10 +227,17 @@ impl<T: 'static> Linker<T> {/// `component` imports or if a name defined doesn't match the type of the/// item imported by the `component` provided.///+ /// Returns an error if `component` was not compiled by the same+ /// [`Engine`](crate::Engine) as this linker.+ ////// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.pub fn instantiate_pre(&self, component: &Component) -> Result<InstancePre<T>> {+ ensure!(+ Engine::same(&self.engine, component.engine()),+ "cross-`Engine` instantiation is not currently supported"+ );let cx = self.typecheck(&component)?;// A successful typecheck resolves all of the imported resources used bydiff --git a/crates/wasmtime/src/runtime/debug.rs b/crates/wasmtime/src/runtime/debug.rsindex c9d27abe76..c5a8fbd7cf 100644--- a/crates/wasmtime/src/runtime/debug.rs+++ b/crates/wasmtime/src/runtime/debug.rs@@ -6,7 +6,7 @@ use crate::module::RegisterBreakpointState;use crate::store::StoreId;use crate::vm::{Activation, Backtrace};use crate::{- AnyRef, AsContextMut, CodeMemory, ExnRef, Extern, ExternRef, Func, Instance, Module,+ AnyRef, AsContextMut, CodeMemory, Engine, ExnRef, Extern, ExternRef, Func, Instance, Module,OwnedRooted, StoreContext, StoreContextMut, Val,code::StoreCodePC,module::ModuleRegistry,@@ -153,8 +153,8 @@ impl StoreOpaque {return None;}- let (breakpoints, registry) = self.breakpoints_and_registry_mut();- Some(breakpoints.edit(registry))+ let (breakpoints, registry, engine) = self.breakpoints_and_registry_and_engine_mut();+ Some(breakpoints.edit(registry, engine))}fn debug_all_instances(&mut self) -> Vec<Instance> {@@ -999,6 +999,8 @@ impl BreakpointKey {pub struct BreakpointEdit<'a> {state: &'a mut BreakpointState,registry: &'a mut ModuleRegistry,+ /// The engine that owns everything in `registry`.+ engine: &'a Engine,/// Modules that have been edited.////// Invariant: each of these modules' CodeMemory objects is@@ -1007,10 +1009,15 @@ pub struct BreakpointEdit<'a> {}impl BreakpointState {- pub(crate) fn edit<'a>(&'a mut self, registry: &'a mut ModuleRegistry) -> BreakpointEdit<'a> {+ pub(crate) fn edit<'a>(+ &'a mut self,+ registry: &'a mut ModuleRegistry,+ engine: &'a Engine,+ ) -> BreakpointEdit<'a> {BreakpointEdit {state: self,registry,+ engine,dirty_modules: BTreeSet::new(),}}@@ -1045,6 +1052,21 @@ impl BreakpointState {}impl<'a> BreakpointEdit<'a> {+ /// Errors if `module` does not belong to the same engine as the store+ /// being edited.+ ///+ /// The module registry rejects foreign modules on its own, but breakpoint+ /// bookkeeping is updated before a module reaches the registry, and+ /// removing a breakpoint that was never added does not touch the registry+ /// at all. So this editing session checks up front as well.+ fn check_engine(&self, module: &Module) -> Result<()> {+ crate::ensure!(+ crate::Engine::same(self.engine, module.engine()),+ "cross-`Engine` breakpoint editing is not supported"+ );+ Ok(())+ }+fn get_code_memory<'b>(breakpoints: &BreakpointState,registry: &'b mut ModuleRegistry,@@ -1089,7 +1111,13 @@ impl<'a> BreakpointEdit<'a> {/// available opcode PC.////// No effect if the breakpoint is already set.+ ///+ /// # Errors+ ///+ /// Returns an error if `module` was not compiled by the same engine as+ /// the store being edited.pub fn add_breakpoint(&mut self, module: &Module, pc: ModulePC) -> Result<()> {+ self.check_engine(module)?;let frame_table = module.frame_table().expect("Frame table must be present when guest-debug is enabled");@@ -1120,7 +1148,13 @@ impl<'a> BreakpointEdit<'a> {/// that module.////// No effect if the breakpoint was not set.+ ///+ /// # Errors+ ///+ /// Returns an error if `module` was not compiled by the same engine as+ /// the store being edited.pub fn remove_breakpoint(&mut self, module: &Module, pc: ModulePC) -> Result<()> {+ self.check_engine(module)?;let requested_key = BreakpointKey::from_raw(module, pc);let actual_key = self.statediff --git a/crates/wasmtime/src/runtime/externals/global.rs b/crates/wasmtime/src/runtime/externals/global.rsindex 6b4a486510..ede512da35 100644--- a/crates/wasmtime/src/runtime/externals/global.rs+++ b/crates/wasmtime/src/runtime/externals/global.rs@@ -59,6 +59,9 @@ impl Global {/// Returns an error if the `ty` provided does not match the type of the/// value `val`, or if `val` comes from a different store than `store`.///+ /// Returns an error if the content type of `ty` was not created with the+ /// same [`Engine`](crate::Engine) as `store`.+ ////// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.diff --git a/crates/wasmtime/src/runtime/externals/table.rs b/crates/wasmtime/src/runtime/externals/table.rsindex 9c557e450a..b17a9bb65d 100644--- a/crates/wasmtime/src/runtime/externals/table.rs+++ b/crates/wasmtime/src/runtime/externals/table.rs@@ -56,6 +56,9 @@ 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.///+ /// Returns an error if the element type of `ty` was not created with the+ /// same [`Engine`](crate::Engine) as `store`.+ ////// This function will also return an error when used with a/// [`Store`](`crate::Store`) which has a/// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:@@ -107,6 +110,9 @@ impl Table {////// # Errors///+ /// Returns an error if the element type of `ty` was not created with the+ /// same [`Engine`](crate::Engine) as `store`.+ ////// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.diff --git a/crates/wasmtime/src/runtime/externals/tag.rs b/crates/wasmtime/src/runtime/externals/tag.rsindex 0c6d8814df..3704ea30d8 100644--- a/crates/wasmtime/src/runtime/externals/tag.rs+++ b/crates/wasmtime/src/runtime/externals/tag.rs@@ -27,6 +27,9 @@ impl Tag {////// # Errors///+ /// Returns an error if `ty` was not created with the same+ /// [`Engine`](crate::Engine) as `store`.+ ////// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when/// memory allocation fails. See the `OutOfMemory` type's documentation for/// details on Wasmtime's out-of-memory handling.diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rsindex 2b91241e41..d847800388 100644--- a/crates/wasmtime/src/runtime/func.rs+++ b/crates/wasmtime/src/runtime/func.rs@@ -2771,6 +2771,10 @@ impl HostFunc {);}+ pub(crate) fn engine(&self) -> &Engine {+ &self.engine+ }+pub(crate) fn sig_index(&self) -> VMSharedTypeIndex {self.func_ref().type_index}diff --git a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rsindex b4bac74f25..ce21b748fc 100644--- a/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs+++ b/crates/wasmtime/src/runtime/gc/enabled/arrayref.rs@@ -70,6 +70,11 @@ pub struct ArrayRefPre {impl ArrayRefPre {/// Create a new `ArrayRefPre` that is associated with the given store/// and type.+ ///+ /// # Panics+ ///+ /// Panics if `ty` was not created with the same+ /// [`Engine`](crate::Engine) as `store`.pub fn new(mut store: impl AsContextMut, ty: ArrayType) -> Self {Self::_new(store.as_context_mut().0, ty)}diff --git a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs b/crates/wasmtime/src/runtime/gc/enabled/exnref.rsindex 5973308df9..a50c3416ba 100644--- a/crates/wasmtime/src/runtime/gc/enabled/exnref.rs+++ b/crates/wasmtime/src/runtime/gc/enabled/exnref.rs@@ -73,6 +73,11 @@ pub struct ExnRefPre {impl ExnRefPre {/// Create a new `ExnRefPre` that is associated with the given store/// and type.+ ///+ /// # Panics+ ///+ /// Panics if `ty` was not created with the same+ /// [`Engine`](crate::Engine) as `store`.pub fn new(mut store: impl AsContextMut, ty: ExnType) -> Self {Self::_new(store.as_context_mut().0, ty)}diff --git a/crates/wasmtime/src/runtime/gc/enabled/structref.rs b/crates/wasmtime/src/runtime/gc/enabled/structref.rsindex 379c57165a..dfa09134de 100644--- a/crates/wasmtime/src/runtime/gc/enabled/structref.rs+++ b/crates/wasmtime/src/runtime/gc/enabled/structref.rs@@ -70,6 +70,11 @@ pub struct StructRefPre {impl StructRefPre {/// Create a new `StructRefPre` that is associated with the given store/// and type.+ ///+ /// # Panics+ ///+ /// Panics if `ty` was not created with the same+ /// [`Engine`](crate::Engine) as `store`.pub fn new(mut store: impl AsContextMut, ty: StructType) -> Self {Self::_new(store.as_context_mut().0, ty)}diff --git a/crates/wasmtime/src/runtime/instance.rs b/crates/wasmtime/src/runtime/instance.rsindex 47856b5cc7..53fd54faed 100644--- a/crates/wasmtime/src/runtime/instance.rs+++ b/crates/wasmtime/src/runtime/instance.rs@@ -219,7 +219,7 @@ impl Instance {}}- typecheck(module, imports, |cx, ty, item| {+ typecheck(store.engine(), module, imports, |cx, ty, item| {let item = DefinitionType::from(store, item);cx.definition(ty, &item)})?;@@ -815,20 +815,32 @@ impl<T: 'static> InstancePre<T> {/// Creates a new `InstancePre` which type-checks the `items` provided and/// on success is ready to instantiate a new instance.///+ /// `engine` is the engine that `items` belong to, and this returns an error+ /// if that is not also `module`'s engine. This also returns an error if an+ /// individual item within `items` reports an engine of its own that is not+ /// `engine`, which happens when that item was taken from a store belonging+ /// to a different engine than the linker it was defined in.+ ////// # Unsafety////// This method is unsafe as the `T` of the `InstancePre<T>` is not/// guaranteed to be the same as the `T` within the `Store`, the caller must/// verify that.- pub(crate) unsafe fn new(module: &Module, items: TryVec<Definition>) -> Result<InstancePre<T>> {- typecheck(module, &items, |cx, ty, item| cx.definition(ty, &item.ty()))?;+ pub(crate) unsafe fn new(+ engine: &Engine,+ module: &Module,+ items: TryVec<Definition>,+ ) -> Result<InstancePre<T>> {+ typecheck(engine, module, &items, |cx, ty, item| {+ cx.definition(ty, &item.ty())+ })?;let mut func_refs = TryVec::with_capacity(items.len())?;let mut host_funcs = 0;let mut asyncness = Asyncness::No;for item in &items {match item {- Definition::Extern(_, _) => {}+ Definition::Extern { .. } => {}Definition::HostFunc(f) => {host_funcs += 1;if f.func_ref().wasm_call.is_none() {@@ -995,7 +1007,7 @@ fn pre_instantiate_raw(// `T` of the store. Additionally the rooting necessary has happened// above.let item = match import {- Definition::Extern(e, _) => e.clone(),+ Definition::Extern { item, .. } => item.clone(),Definition::HostFunc(func) => unsafe {func.to_func_store_rooted(store,@@ -1014,11 +1026,62 @@ fn pre_instantiate_raw(Ok(imports)}+/// An item that can be supplied as an import argument during instantiation.+///+/// # Safety+///+/// Implementations must return an associated engine if they own a handle to+/// one. Failure to do so may allow cross-`Engine` type confusion.+///+/// (Items that are just identifiers indexing into a store, for example+/// `Extern::Global(wasmtime::Global)`, do not have their own handle to an+/// engine. Their engine is the engine of the store they belong to, and it is+/// the store, not them, that holds an owning handle to the engine.)+unsafe trait ImportArg {+ fn engine(&self) -> Option<&Engine>;+}++// SAFETY: `Extern::SharedMemory` is the only variant with an `Engine` handle.+unsafe impl ImportArg for Extern {+ fn engine(&self) -> Option<&Engine> {+ match self {+ Extern::SharedMemory(m) => Some(m.engine()),+ Extern::Func(_)+ | Extern::Global(_)+ | Extern::Table(_)+ | Extern::Memory(_)+ | Extern::Tag(_) => None,+ }+ }+}++// SAFETY: `Definition::engine` is complete.+unsafe impl ImportArg for Definition {+ fn engine(&self) -> Option<&Engine> {+ Some(Definition::engine(self))+ }+}++/// Type check the `import_args` against the imports that `module` declares.+///+/// `engine` is the engine that the `import_args` belong to. It must be the same+/// engine as `module`'s: entity types are compared by `VMSharedTypeIndex`, which+/// only means anything within the engine that assigned it, so checking one+/// engine's items against another engine's module would compare unrelated types+/// and consider them equal.fn typecheck<I>(+ engine: &Engine,module: &Module,import_args: &[I],check: impl Fn(&matching::MatchCx<'_>, &EntityType, &I) -> Result<()>,-) -> Result<()> {+) -> Result<()>+where+ I: ImportArg,+{+ ensure!(+ Engine::same(engine, module.engine()),+ "cross-`Engine` instantiation is not currently supported"+ );let env_module = module.compiled_module().module();let expected_len = env_module.imports().count();let actual_len = import_args.len();@@ -1028,6 +1091,14 @@ fn typecheck<I>(let cx = matching::MatchCx::new(module.engine());for ((name, field, expected_ty), actual) in env_module.imports().zip(import_args) {debug_assert!(expected_ty.is_canonicalized_for_runtime_usage());+ if let Some(actual_engine) = actual.engine() {+ ensure!(+ Engine::same(actual_engine, engine),+ "cross-`Engine` instantiation is not currently supported: \+ the item provided for `{name}::{field}` belongs to a \+ different engine than the module being instantiated"+ );+ }check(&cx, &expected_ty, actual).with_context(|| format!("incompatible import type for `{name}::{field}`"))?;}diff --git a/crates/wasmtime/src/runtime/linker.rs b/crates/wasmtime/src/runtime/linker.rsindex 11a0448dc8..2c8fed9842 100644--- a/crates/wasmtime/src/runtime/linker.rs+++ b/crates/wasmtime/src/runtime/linker.rs@@ -75,9 +75,10 @@ use wasmtime_environ::{Atom, PanicOnOom, StringPool};/// The [`Linker`] type is not compatible with usage between multiple [`Engine`]/// values. An [`Engine`] is provided when a [`Linker`] is created and only/// stores and items which originate from that [`Engine`] can be used with this-/// [`Linker`]. If more than one [`Engine`] is used with a [`Linker`] then that-/// may cause a panic at runtime, similar to how if a [`Func`] is used with the-/// wrong [`Store`] that can also panic at runtime.+/// [`Linker`]. Instantiating a [`Module`] from another [`Engine`] returns an+/// error, and mixing engines in other ways may cause a panic at runtime,+/// similar to how if a [`Func`] is used with the wrong [`Store`] that can also+/// panic at runtime.////// [`Store`]: crate::Store/// [`Global`]: crate::Global@@ -124,7 +125,13 @@ impl TryClone for ImportKey {#[derive(Clone)]pub(crate) enum Definition {- Extern(Extern, DefinitionType),+ Extern {+ item: Extern,+ ty: DefinitionType,+ /// The engine of the store that `item` was taken from, which is the+ /// engine that assigned any type indices within `ty`.+ engine: Engine,+ },HostFunc(Arc<HostFunc>),}@@ -1191,6 +1198,10 @@ impl<T> Linker<T> {whereT: 'static,{+ ensure!(+ Engine::same(&self.engine, module.engine()),+ "cross-`Engine` instantiation is not currently supported"+ );let mut imports: TryVec<_> = module.imports().map(|import| Ok(self._get_by_import(&import)?))@@ -1200,7 +1211,7 @@ impl<T> Linker<T> {import.update_size(store);}}- unsafe { InstancePre::new(module, imports) }+ unsafe { InstancePre::new(&self.engine, module, imports) }}/// Returns an iterator over all items defined in this `Linker`, in@@ -1393,16 +1404,29 @@ impl<T: 'static> Default for Linker<T> {impl Definition {fn new(store: &StoreOpaque, item: Extern) -> Definition {let ty = DefinitionType::from(store, &item);- Definition::Extern(item, ty)+ Definition::Extern {+ item,+ ty,+ engine: store.engine().clone(),+ }}pub(crate) fn ty(&self) -> DefinitionType {match self {- Definition::Extern(_, ty) => *ty,+ Definition::Extern { ty, .. } => *ty,Definition::HostFunc(func) => DefinitionType::Func(func.sig_index()),}}+ /// The engine that assigned the type indices within this definition's+ /// [`Definition::ty`].+ pub(crate) fn engine(&self) -> &Engine {+ match self {+ Definition::Extern { engine, .. } => engine,+ Definition::HostFunc(func) => func.engine(),+ }+ }+/// Inserts this definition into the `store` provided.////// # Safety@@ -1412,7 +1436,7 @@ impl Definition {/// `HostFunc` matches the `T` on the store.pub(crate) unsafe fn to_extern(&self, store: &mut StoreOpaque) -> Result<Extern, OutOfMemory> {match self {- Definition::Extern(e, _) => Ok(e.clone()),+ Definition::Extern { item, .. } => Ok(item.clone()),// SAFETY: the contract of this function is the same as what's// required of `to_func`, that `T` of the store matches the `T` of// this original definition.@@ -1422,20 +1446,32 @@ impl Definition {pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {match self {- Definition::Extern(e, _) => e.comes_from_same_store(store),+ Definition::Extern { item, .. } => item.comes_from_same_store(store),Definition::HostFunc(_func) => true,}}fn update_size(&mut self, store: &StoreOpaque) {match self {- Definition::Extern(Extern::Memory(m), DefinitionType::Memory(_, size)) => {+ Definition::Extern {+ item: Extern::Memory(m),+ ty: DefinitionType::Memory(_, size),+ ..+ } => {*size = m.internal_size(store);}- Definition::Extern(Extern::SharedMemory(m), DefinitionType::Memory(_, size)) => {+ Definition::Extern {+ item: Extern::SharedMemory(m),+ ty: DefinitionType::Memory(_, size),+ ..+ } => {*size = m.size();}- Definition::Extern(Extern::Table(m), DefinitionType::Table(_, size)) => {+ Definition::Extern {+ item: Extern::Table(m),+ ty: DefinitionType::Table(_, size),+ ..+ } => {*size = m.size_(store);}_ => {}diff --git a/crates/wasmtime/src/runtime/module/registry.rs b/crates/wasmtime/src/runtime/module/registry.rsindex 97c2e43e23..f056a8d1de 100644--- a/crates/wasmtime/src/runtime/module/registry.rs+++ b/crates/wasmtime/src/runtime/module/registry.rs@@ -139,6 +139,16 @@ enum ModuleOrComponent<'a> {Component(&'a Component),}+impl<'a> ModuleOrComponent<'a> {+ fn engine(&self) -> &'a Engine {+ match self {+ ModuleOrComponent::Module(module) => module.engine(),+ #[cfg(feature = "component-model")]+ ModuleOrComponent::Component(component) => component.engine(),+ }+ }+}+impl ModuleRegistry {/// Get a previously-registered module by id.pub fn module_by_id(&self, id: RegisteredModuleId) -> Option<&Module> {@@ -216,6 +226,8 @@ impl ModuleRegistry {}/// Registers a new module with the registry.+ ///+ /// Returns an error if `module` was not compiled by `engine`.pub fn register_module(&mut self,module: &Module,@@ -226,6 +238,9 @@ impl ModuleRegistry {.map(|id| id.unwrap())}+ /// Registers a new component with the registry.+ ///+ /// Returns an error if `component` was not compiled by `engine`.#[cfg(feature = "component-model")]pub fn register_component(&mut self,@@ -242,12 +257,24 @@ impl ModuleRegistry {}/// Registers a new module with the registry.+ ///+ /// Returns an error if `module_or_component` was not compiled by `engine`.+ /// All code and metadata enters a store through here, so callers+ /// registering on a store's behalf pass that store's engine to keep foreign+ /// code out of it.fn register(&mut self,module_or_component: ModuleOrComponent<'_>,engine: &Engine,breakpoint_state: RegisterBreakpointState,) -> Result<Option<RegisteredModuleId>> {+ // Nothing below here may run for a foreign module or component: the+ // type indices it carries mean something else entirely in this+ // engine.+ ensure!(+ Engine::same(engine, module_or_component.engine()),+ "cross-`Engine` usage is not supported"+ );let compiled_id = match module_or_component {ModuleOrComponent::Module(module) => module.id(),#[cfg(feature = "component-model")]diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rsindex 4959c741d9..9cc49ea836 100644--- a/crates/wasmtime/src/runtime/store.rs+++ b/crates/wasmtime/src/runtime/store.rs@@ -1225,6 +1225,11 @@ impl<T> Store<T> {/// instantiated. This is useful for guest-debug workflows where/// the debugger needs to see modules to set breakpoints before/// the first Wasm instruction executes.+ ///+ /// # Errors+ ///+ /// Returns an error if `module` was not compiled by this store's+ /// [`Engine`].#[cfg(feature = "debug")]pub fn debug_register_module(&mut self, module: &crate::Module) -> crate::Result<()> {let (modules, engine, breakpoints) = self.inner.modules_and_engine_and_breakpoints_mut();@@ -1235,11 +1240,18 @@ impl<T> Store<T> {/// Register all inner modules of a [`Component`](crate::component::Component)/// with this store's module registry for debugging, without instantiating/// the component.+ ///+ /// # Errors+ ///+ /// Returns an error if `component` was not compiled by this store's+ /// [`Engine`].#[cfg(all(feature = "debug", feature = "component-model"))]pub fn debug_register_component(&mut self,component: &crate::component::Component,) -> crate::Result<()> {+ let (modules, engine, breakpoints) = self.inner.modules_and_engine_and_breakpoints_mut();+ modules.register_component(component, engine, breakpoints)?;for module in component.static_modules() {self.debug_register_module(module)?;}@@ -1550,10 +1562,10 @@ impl StoreOpaque {}#[cfg(feature = "debug")]- pub(crate) fn breakpoints_and_registry_mut(+ pub(crate) fn breakpoints_and_registry_and_engine_mut(&mut self,- ) -> (&mut BreakpointState, &mut ModuleRegistry) {- (&mut self.breakpoints, &mut self.modules)+ ) -> (&mut BreakpointState, &mut ModuleRegistry, &Engine) {+ (&mut self.breakpoints, &mut self.modules, &self.engine)}#[cfg(feature = "debug")]diff --git a/crates/wasmtime/src/runtime/store/gc.rs b/crates/wasmtime/src/runtime/store/gc.rsindex e5754301ed..364249346c 100644--- a/crates/wasmtime/src/runtime/store/gc.rs+++ b/crates/wasmtime/src/runtime/store/gc.rs@@ -13,7 +13,8 @@ use crate::vm::{SendSyncPtr, StoreGcHostAllocTypes, TraceInfo, VMGcRef,};use crate::{- ExnRef, GcHeapOutOfMemory, Result, Rooted, Store, StoreContextMut, ThrownException, bail,+ Engine, ExnRef, GcHeapOutOfMemory, Result, Rooted, Store, StoreContextMut, ThrownException,+ bail,};use core::fmt;use core::mem::ManuallyDrop;@@ -876,7 +877,17 @@ impl StoreOpaque {/// type in this store, and we don't have to worry about the type being/// reclaimed (since it is possible that none of the Wasm modules in this/// store are holding it alive).+ ///+ /// # Panics+ ///+ /// Panics if `ty` was not registered with this store's engine. The types+ /// here are keyed by their `VMSharedTypeIndex`, which only means anything+ /// within the engine that assigned it.pub(crate) fn insert_gc_host_alloc_type(&mut self, ty: RegisteredType) {+ assert!(+ Engine::same(self.engine(), ty.engine()),+ "type used with wrong engine"+ );let trace_info = ty.layout().map(TraceInfo::new);self.gc_data.gc_host_alloc_typesdiff --git a/crates/wasmtime/src/runtime/trampoline/table.rs b/crates/wasmtime/src/runtime/trampoline/table.rsindex fc1ddd6f05..952e368c1e 100644--- a/crates/wasmtime/src/runtime/trampoline/table.rs+++ b/crates/wasmtime/src/runtime/trampoline/table.rs@@ -30,20 +30,22 @@ pub async fn create_table(let imports = Imports::default();+ let runtime_info = ModuleRuntimeInfo::bare_with_registered_types(+ try_new::<Arc<_>>(module)?,+ store.engine(),+ table.element().clone().into_registered_type(),+ )?;+unsafe {let allocator =OnDemandInstanceAllocator::new(store.engine().config().mem_creator.clone(), 0, false);- let module = try_new::<Arc<_>>(module)?;store.allocate_instance(limiter,AllocateInstanceKind::Dummy {allocator: &allocator,},- &ModuleRuntimeInfo::bare_with_registered_types(- module,- table.element().clone().into_registered_type(),- )?,+ &runtime_info,imports,).awaitdiff --git a/crates/wasmtime/src/runtime/trampoline/tag.rs b/crates/wasmtime/src/runtime/trampoline/tag.rsindex 46e2028b6e..eac420caa1 100644--- a/crates/wasmtime/src/runtime/trampoline/tag.rs+++ b/crates/wasmtime/src/runtime/trampoline/tag.rs@@ -33,28 +33,31 @@ pub fn create_tag(store: &mut StoreOpaque, ty: &TagType) -> Result<InstanceId> {let imports = Imports::default();+ // Both the tag's signature type and its exception type are referred to by+ // engine-level type index from the dummy module's `Tag`, so both+ // `RegisteredType`s must be handed to the instance's runtime info to keep+ // those indices rooted in the engine's type registry for as long as the+ // instance (and thus the store) is alive.+ let runtime_info = ModuleRuntimeInfo::bare_with_registered_types(+ try_new::<Arc<_>>(module)?,+ store.engine(),+ [func_ty, exn_ty],+ )?;+unsafe {let allocator =OnDemandInstanceAllocator::new(store.engine().config().mem_creator.clone(), 0, false);- let module = try_new::<Arc<_>>(module)?;// Note that `assert_ready` should be valid here because this module// doesn't allocate tables or memories meaning it shouldn't need a// resource limiter so `None` is passed. As a result no `await` points// should ever be hit.- //- // Both the tag's signature type and its exception type are- // referred to by engine-level type index from the dummy- // module's `Tag`, so both `RegisteredType`s must be handed to- // the instance's runtime info to keep those indices rooted in- // the engine's type registry for as long as the instance (and- // thus the store) is alive.vm::assert_ready(store.allocate_instance(None,AllocateInstanceKind::Dummy {allocator: &allocator,},- &ModuleRuntimeInfo::bare_with_registered_types(module, [func_ty, exn_ty])?,+ &runtime_info,imports,))}diff --git a/crates/wasmtime/src/runtime/vm.rs b/crates/wasmtime/src/runtime/vm.rsindex d57e18cceb..2f503d1606 100644--- a/crates/wasmtime/src/runtime/vm.rs+++ b/crates/wasmtime/src/runtime/vm.rs@@ -305,17 +305,40 @@ pub struct BareModuleInfo {impl ModuleRuntimeInfo {pub(crate) fn bare(module: Arc<wasmtime_environ::Module>) -> Result<Self, OutOfMemory> {- ModuleRuntimeInfo::bare_with_registered_types(module, None)+ ModuleRuntimeInfo::new_bare(module, TryVec::new())}+ /// Same as [`ModuleRuntimeInfo::bare`], but additionally keeps+ /// `registered_types` alive for as long as the resulting instance.+ ///+ /// This is the choke point at which a host-allocated table or tag holds+ /// `VMSharedTypeIndex`es alive on behalf of a store, so it is where we+ /// check that those types belong to that store's engine. Returns an error+ /// if any of `registered_types` was not registered with `engine`.pub(crate) fn bare_with_registered_types(module: Arc<wasmtime_environ::Module>,+ engine: &crate::Engine,registered_types: impl IntoIterator<Item = RegisteredType>,+ ) -> Result<Self> {+ let mut types = TryVec::new();+ for ty in registered_types {+ crate::ensure!(+ crate::Engine::same(engine, ty.engine()),+ "type used with wrong engine"+ );+ types.push(ty)?;+ }+ Ok(ModuleRuntimeInfo::new_bare(module, types)?)+ }++ fn new_bare(+ module: Arc<wasmtime_environ::Module>,+ registered_types: TryVec<RegisteredType>,) -> Result<Self, OutOfMemory> {let info = try_new(BareModuleInfo {offsets: VMOffsets::new(HostPtr, &module),module,- _registered_types: registered_types.into_iter().try_collect()?,+ _registered_types: registered_types,})?;Ok(ModuleRuntimeInfo::Bare(info))}diff --git a/tests/all/arrays.rs b/tests/all/arrays.rsindex b42a38855d..4d37a0d0e0 100644--- a/tests/all/arrays.rs+++ b/tests/all/arrays.rs@@ -1,6 +1,6 @@use crate::ErrorExt;-use super::gc_store;+use super::{gc_engine, gc_store};use wasmtime::*;#[test]@@ -72,11 +72,12 @@ fn array_new_cross_store_initial_elem() {#[test]#[should_panic = "wrong store"]fn array_new_cross_store_pre() {- let mut store1 = gc_store().unwrap();- let mut store2 = gc_store().unwrap();+ let engine = gc_engine().unwrap();+ let mut store1 = Store::new(&engine, ());+ let mut store2 = Store::new(&engine, ());let array_ty = ArrayType::new(- store1.engine(),+ &engine,FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)),);let pre = ArrayRefPre::new(&mut store2, array_ty);@@ -157,11 +158,12 @@ fn array_new_fixed_cross_store_initial_elem() {#[test]#[should_panic = "wrong store"]fn array_new_fixed_cross_store_pre() {- let mut store1 = gc_store().unwrap();- let mut store2 = gc_store().unwrap();+ let engine = gc_engine().unwrap();+ let mut store1 = Store::new(&engine, ());+ let mut store2 = Store::new(&engine, ());let array_ty = ArrayType::new(- store1.engine(),+ &engine,FieldType::new(Mutability::Var, StorageType::ValType(ValType::ANYREF)),);let pre = ArrayRefPre::new(&mut store2, array_ty);diff --git a/tests/all/cross_engine.rs b/tests/all/cross_engine.rsnew file mode 100644index 0000000000..f216865fb8--- /dev/null+++ b/tests/all/cross_engine.rs@@ -0,0 +1,427 @@+//! Tests that objects belonging to one `Engine` cannot be admitted into a+//! `Store` that belongs to a different `Engine`.+//!+//! Type indices (`VMSharedTypeIndex`) are unique only within a single+//! `Engine`. Two engines will happily hand out the same index for two+//! completely unrelated types. When an object from one engine reaches a store+//! from another, those numerically-equal-but-semantically-different indices+//! collide:+//!+//! * A host function's `wasm_call` field gets patched with a Wasm-to-array+//! trampoline compiled for a different signature, so the trampoline reads+//! and writes the wrong number of `ValRaw` slots in a stack buffer.+//!+//! * The garbage collector traces a Wasm object using a foreign type's+//! layout.+//!+//! Every API that lets an object into a store must therefore check that the+//! object comes from the store's engine.++use crate::ErrorExt;+use std::sync::{Arc, Mutex};+use wasmtime::component::{Component, Linker as ComponentLinker};+use wasmtime::*;++/// The value that [`observe_i64_in_host`] sends from Wasm to the host.+const SENTINEL: i64 = 0x1122334455667788;++/// A module whose only function type is `(func (param f64))`.+///+/// In a freshly created engine that type gets the same `VMSharedTypeIndex` as+/// the `(func (param i64))` type used by [`observe_i64_in_host`], so if this+/// module is registered with a store belonging to a different engine then its+/// trampoline is what the host function ends up calling.+const COLLIDING_MODULE: &str = r#"(module (func (export "f") (param f64)))"#;++/// [`COLLIDING_MODULE`] wrapped up in a component.+///+/// The core module is deliberately left uninstantiated so that instantiating+/// this component does not itself instantiate any core module.+const COLLIDING_COMPONENT: &str = r#"+ (component+ (core module (func (export "f") (param f64)))+ )+"#;++/// Two separate engines that assign the same type indices to different types.+fn engine_pair() -> (Engine, Engine) {+ (Engine::default(), Engine::default())+}++/// Same as [`engine_pair`], but with a customized configuration.+fn engine_pair_with(f: impl Fn(&mut Config)) -> Result<(Engine, Engine)> {+ let mut config = Config::new();+ f(&mut config);+ Ok((Engine::new(&config)?, Engine::new(&config)?))+}++/// Calls a host function that takes an `i64` and returns the value that the+/// host actually observed, which should always be [`SENTINEL`].+///+/// This is the canary for cross-engine corruption: if a foreign module has+/// been registered with `store`, then filling in this host function's+/// `VMFuncRef::wasm_call` finds the foreign engine's `(param f64)` trampoline+/// and the host sees a garbage value instead.+fn observe_i64_in_host(store: &mut Store<()>) -> Result<i64> {+ let observed = Arc::new(Mutex::new(0));+ let host = Func::wrap(&mut *store, {+ let observed = Arc::clone(&observed);+ move |x: i64| *observed.lock().unwrap() = x+ });+ let engine = store.engine().clone();+ let module = Module::new(+ &engine,+ r#"+ (module+ (import "" "" (func $host (param i64)))+ (func (export "go")+ i64.const 0x1122334455667788+ call $host))+ "#,+ )?;+ let instance = Instance::new(&mut *store, &module, &[host.into()])?;+ instance+ .get_typed_func::<(), ()>(&mut *store, "go")?+ .call(&mut *store, ())?;+ let observed = *observed.lock().unwrap();+ Ok(observed)+}++/// Asserts that `store` is still usable and that nothing in it confuses one+/// engine's type indices for another's.+fn assert_store_is_uncorrupted(store: &mut Store<()>) -> Result<()> {+ assert_eq!(observe_i64_in_host(store)?, SENTINEL);+ Ok(())+}++#[test]+#[cfg_attr(miri, ignore)]+fn instance_new_rejects_foreign_module() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign = Module::new(&b, COLLIDING_MODULE)?;++ Instance::new(&mut store, &foreign, &[])+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++/// A foreign module's imports must be rejected as cross-engine rather than+/// type checked, since type checking would compare this engine's indices+/// against the foreign engine's.+#[test]+#[cfg_attr(miri, ignore)]+fn instance_new_rejects_foreign_module_with_imports() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());++ // Register an unrelated type first so that the host function below does not+ // land on the same index in `a` that the module's imported type lands on in+ // `b`.+ let _ = Func::wrap(&mut store, |_: i32| {});+ let host = Func::wrap(&mut store, |_: i64| {});++ let foreign = Module::new(&b, r#"(module (import "" "" (func (param i64))))"#)?;++ Instance::new(&mut store, &foreign, &[host.into()])+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++/// A linker and the module it instantiates can belong to the same engine while+/// an individual item defined in that linker came from a store belonging to a+/// different one, so each item has to be checked on its own.+#[test]+#[cfg_attr(miri, ignore)]+fn instantiate_pre_rejects_foreign_definition() -> Result<()> {+ let (a, b) = engine_pair();++ // Register an unrelated type first so that the function below does not land+ // on the same index in `b` that the module's imported type lands on in `a`.+ let mut foreign_store = Store::new(&b, ());+ let _ = Func::wrap(&mut foreign_store, |_: i32| {});+ let foreign = Func::wrap(&mut foreign_store, |_: f64| {});++ let mut linker = Linker::<()>::new(&a);+ linker.define(&foreign_store, "", "", foreign)?;++ let module = Module::new(&a, r#"(module (import "" "" (func (param i64))))"#)?;++ linker+ .instantiate_pre(&module)+ .err()+ .expect("should reject an item defined from a different engine's store")+ .assert_contains("cross-`Engine`");++ let mut store = Store::new(&a, ());+ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn instance_pre_instantiate_rejects_foreign_store() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign = Module::new(&b, COLLIDING_MODULE)?;+ let pre = Linker::<()>::new(&b).instantiate_pre(&foreign)?;++ pre.instantiate(&mut store)+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn linker_instantiate_pre_rejects_foreign_module() -> Result<()> {+ let (a, b) = engine_pair();+ let foreign = Module::new(&b, COLLIDING_MODULE)?;++ Linker::<()>::new(&a)+ .instantiate_pre(&foreign)+ .err()+ .expect("should reject a module from a different engine")+ .assert_contains("cross-`Engine`");++ Ok(())+}++#[test]+#[cfg_attr(miri, ignore)]+fn debug_register_module_rejects_foreign_module() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign = Module::new(&b, COLLIDING_MODULE)?;++ store+ .debug_register_module(&foreign)+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn debug_register_component_rejects_foreign_component() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign = Component::new(&b, COLLIDING_COMPONENT)?;++ store+ .debug_register_component(&foreign)+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn add_breakpoint_rejects_foreign_module() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.guest_debug(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign = Module::new(&b, r#"(module (func (export "f") (param f64)))"#)?;++ store+ .edit_breakpoints()+ .unwrap()+ .add_breakpoint(&foreign, ModulePC::new(0))+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn remove_breakpoint_rejects_foreign_module() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.guest_debug(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign = Module::new(&b, r#"(module (func (export "f") (param f64)))"#)?;++ store+ .edit_breakpoints()+ .unwrap()+ .remove_breakpoint(&foreign, ModulePC::new(0))+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn component_linker_instantiate_pre_rejects_foreign_component() -> Result<()> {+ let (a, b) = engine_pair();+ let foreign = Component::new(&b, COLLIDING_COMPONENT)?;++ ComponentLinker::<()>::new(&a)+ .instantiate_pre(&foreign)+ .err()+ .expect("should reject a component from a different engine")+ .assert_contains("cross-`Engine`");++ Ok(())+}++#[test]+#[cfg_attr(miri, ignore)]+fn component_instance_pre_instantiate_rejects_foreign_store() -> Result<()> {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign = Component::new(&b, COLLIDING_COMPONENT)?;+ let pre = ComponentLinker::<()>::new(&b).instantiate_pre(&foreign)?;++ pre.instantiate(&mut store)+ .unwrap_err()+ .assert_contains("cross-`Engine`");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn tag_new_rejects_foreign_type() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.wasm_exceptions(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign_ty = TagType::new(FuncType::new(&b, [ValType::I32], []));++ Tag::new(&mut store, &foreign_ty)+ .unwrap_err()+ .assert_contains("wrong engine");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn table_new_rejects_foreign_type() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.wasm_gc(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign_struct = StructType::new(+ &b,+ [FieldType::new(+ Mutability::Const,+ StorageType::ValType(ValType::I32),+ )],+ )?;+ let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);+ let foreign_ty = TableType::new(RefType::new(true, foreign_heap_ty.clone()), 0, None);++ Table::new(&mut store, foreign_ty, Ref::null(&foreign_heap_ty))+ .unwrap_err()+ .assert_contains("wrong engine");++ assert_store_is_uncorrupted(&mut store)+}++/// Same as [`table_new_rejects_foreign_type`], but for the async variant, which+/// reaches the same check by a different path.+#[tokio::test]+#[cfg_attr(miri, ignore)]+async fn table_new_async_rejects_foreign_type() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.wasm_gc(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign_struct = StructType::new(+ &b,+ [FieldType::new(+ Mutability::Const,+ StorageType::ValType(ValType::I32),+ )],+ )?;+ let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);+ let foreign_ty = TableType::new(RefType::new(true, foreign_heap_ty.clone()), 0, None);++ Table::new_async(&mut store, foreign_ty, Ref::null(&foreign_heap_ty))+ .await+ .unwrap_err()+ .assert_contains("wrong engine");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[cfg_attr(miri, ignore)]+fn global_new_rejects_foreign_type() -> Result<()> {+ let (a, b) = engine_pair_with(|config| {+ config.wasm_gc(true);+ })?;+ let mut store = Store::new(&a, ());+ let foreign_struct = StructType::new(+ &b,+ [FieldType::new(+ Mutability::Const,+ StorageType::ValType(ValType::I32),+ )],+ )?;+ let foreign_heap_ty = HeapType::ConcreteStruct(foreign_struct);+ let foreign_ty = GlobalType::new(+ ValType::Ref(RefType::new(true, foreign_heap_ty.clone())),+ Mutability::Const,+ );++ Global::new(&mut store, foreign_ty, Ref::null(&foreign_heap_ty).into())+ .unwrap_err()+ .assert_contains("wrong engine");++ assert_store_is_uncorrupted(&mut store)+}++#[test]+#[should_panic = "wrong engine"]+fn struct_ref_pre_rejects_foreign_type() {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign_ty = StructType::new(+ &b,+ [FieldType::new(+ Mutability::Const,+ StorageType::ValType(ValType::I32),+ )],+ )+ .unwrap();++ let _ = StructRefPre::new(&mut store, foreign_ty);+}++#[test]+#[should_panic = "wrong engine"]+fn array_ref_pre_rejects_foreign_type() {+ let (a, b) = engine_pair();+ let mut store = Store::new(&a, ());+ let foreign_ty = ArrayType::new(+ &b,+ FieldType::new(Mutability::Const, StorageType::ValType(ValType::I32)),+ );++ let _ = ArrayRefPre::new(&mut store, foreign_ty);+}++#[test]+#[should_panic = "wrong engine"]+fn exn_ref_pre_rejects_foreign_type() {+ let (a, b) = engine_pair_with(|config| {+ config.wasm_exceptions(true);+ })+ .unwrap();+ let mut store = Store::new(&a, ());+ let foreign_ty = ExnType::new(&b, [ValType::I32]).unwrap();++ let _ = ExnRefPre::new(&mut store, foreign_ty);+}diff --git a/tests/all/main.rs b/tests/all/main.rsindex c6d29c7ad5..e5d7000422 100644--- a/tests/all/main.rs+++ b/tests/all/main.rs@@ -9,6 +9,7 @@ mod cli_tests;mod compile_time_builtins;mod component_model;mod coredump;+mod cross_engine;mod custom_code_memory;mod debug;mod debug_component;@@ -131,14 +132,18 @@ pub(crate) fn small_pool_config() -> wasmtime::PoolingAllocationConfig {}pub(crate) fn gc_store() -> Result<wasmtime::Store<()>> {+ Ok(wasmtime::Store::new(&gc_engine()?, ()))+}++/// A helper to create an engine with GC enabled.+pub(crate) fn gc_engine() -> Result<wasmtime::Engine> {let _ = env_logger::try_init();let mut config = wasmtime::Config::new();config.wasm_function_references(true);config.wasm_gc(true);- let engine = wasmtime::Engine::new(&config)?;- Ok(wasmtime::Store::new(&engine, ()))+ wasmtime::Engine::new(&config)}trait ErrorExt {diff --git a/tests/all/structs.rs b/tests/all/structs.rsindex 652f028f31..e5d3b1edfb 100644--- a/tests/all/structs.rs+++ b/tests/all/structs.rs@@ -1,4 +1,4 @@-use super::gc_store;+use super::{gc_engine, gc_store};use wasmtime::*;use wasmtime_test_macros::wasmtime_test;@@ -77,10 +77,11 @@ fn struct_new_cross_store_field() {#[test]#[should_panic = "wrong store"]fn struct_new_cross_store_pre() {- let mut store = gc_store().unwrap();- let struct_ty = StructType::new(store.engine(), []).unwrap();+ let engine = gc_engine().unwrap();+ let mut store = Store::new(&engine, ());+ let struct_ty = StructType::new(&engine, []).unwrap();- let mut other_store = gc_store().unwrap();+ let mut other_store = Store::new(&engine, ());let pre = StructRefPre::new(&mut other_store, struct_ty);// This should panic.