Skip to content

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

Expose the `LinearMemory` instance from the store. (#15144)

Mat Gienieczko546c33f17127
diff --git a/crates/wasmtime/src/runtime/memory.rs b/crates/wasmtime/src/runtime/memory.rs
index ed7255359e..c07c8dc0a7 100644
--- a/crates/wasmtime/src/runtime/memory.rs
+++ b/crates/wasmtime/src/runtime/memory.rs
@@ -400,6 +400,33 @@ impl Memory {
Ok(())
}
+ /// Returns the [`LinearMemory`] backing this memory if it is of the concrete type `M`.
+ ///
+ /// This is intended for embedders that create memories with a custom
+ /// [`MemoryCreator`] (see [`Config::with_host_memory`](crate::Config::with_host_memory))
+ /// and need to inspect the created [`LinearMemory`] object after instantiation.
+ ///
+ /// Returns `None` if the memory is not of type `M`.
+ /// Keeping the concrete `M` returned by a [`MemoryCreator`] private
+ /// ensures that no other code with access to the store can obtain it.
+ ///
+ /// Note that this method will consider the entire store context provided as
+ /// borrowed for the duration of the lifetime of the returned reference.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this memory doesn't belong to `store`.
+ pub fn linear_memory<'a, M: LinearMemory, T: 'static>(
+ &self,
+ store: impl Into<StoreContext<'a, T>>,
+ ) -> Option<&'a M> {
+ let store: &'a StoreOpaque = store.into().0;
+ let memory: &'a dyn Any = store[self.instance]
+ .get_defined_memory(self.index)
+ .as_linear_memory()?;
+ memory.downcast_ref()
+ }
+
/// Returns this memory as a native Rust slice.
///
/// Note that this method will consider the entire store context provided as
@@ -779,6 +806,11 @@ impl Memory {
/// `as_ptr() + max(reserved_size_in_bytes, byte_size()) + guard_size_in_bytes` must be
/// inaccessible, so that any access to it faults. This must hold at all times, including after growth.
///
+/// - **Shared access.** Embedders can obtain `&Self` through [`Memory::linear_memory`] whenever
+/// the owning store is not in use. Methods taking `&self` must therefore be safe to call at any
+/// such time, from any thread, and must not hand out mutable access to state that Wasmtime or
+/// WebAssembly code also mutates, such as the memory's contents.
+///
/// Additionally, observe the safety requirements when the memory is accessed, as explained in [`Memory`].
///
/// # Correctness
diff --git a/crates/wasmtime/src/runtime/vm/memory.rs b/crates/wasmtime/src/runtime/vm/memory.rs
index 981fe43b21..617d137ec2 100644
--- a/crates/wasmtime/src/runtime/vm/memory.rs
+++ b/crates/wasmtime/src/runtime/vm/memory.rs
@@ -374,6 +374,14 @@ impl Memory {
Memory::Shared(_) => panic!("expected a local memory"),
}
}
+ /// Returns the [`LinearMemory`] allocation backing this memory, or `None`
+ /// for shared memories.
+ pub fn as_linear_memory(&self) -> Option<&dyn LinearMemory> {
+ match self {
+ Memory::Local(mem) => Some(&*mem.alloc),
+ Memory::Shared(_) => None,
+ }
+ }
/// Is this a shared memory?
pub fn is_shared_memory(&self) -> bool {
diff --git a/tests/all/memory_creator.rs b/tests/all/memory_creator.rs
index 2d07344370..4cc9466e24 100644
--- a/tests/all/memory_creator.rs
+++ b/tests/all/memory_creator.rs
@@ -489,6 +489,31 @@ fn growth_limited_to_capacity_when_memory_may_not_move() -> Result<()> {
Ok(())
}
+// The `LinearMemory` returned by a custom creator can be recovered from an
+// instance's exported memory.
+#[test]
+fn linear_memory_downcasts_to_creator_type() -> Result<()> {
+ let (mut store, counters) = store(CustomMemoryCreator::new(ImageMode::ReturnFalse), |_| {});
+ let module = Module::new(store.engine(), DATA_MODULE)?;
+ let instance = Instance::new(&mut store, &module, &[])?;
+ let memory = instance.get_memory(&mut store, "memory").unwrap();
+
+ let custom = memory.linear_memory::<CustomMemory, _>(&store).unwrap();
+ // Check that this is the same instance that we expect it to be.
+ assert!(Arc::ptr_eq(&custom.counters, &counters));
+ assert_eq!(custom.byte_size(), WASM_PAGE);
+ assert_eq!(custom.base(), memory.data_ptr(&store));
+
+ // Make sure grow works and is reflected in the returned reference.
+ let grow = instance.get_typed_func::<i32, i32>(&mut store, "grow")?;
+ assert_eq!(grow.call(&mut store, 1)?, 1);
+ let custom = memory.linear_memory::<CustomMemory, _>(&store).unwrap();
+ assert_eq!(custom.byte_size(), 2 * WASM_PAGE);
+ assert_eq!(custom.base(), memory.data_ptr(&store));
+
+ Ok(())
+}
+
// A memory that moves while growing within its capacity violates the `LinearMemory` contract.
// Wasmtime does not guarantee that this is detected, but it is an easy check that prevents
// potentially catastrophic errors, so we make sure it leads to a panic.