Skip to content

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

Handle OOM in `Linker::func_wrap` (#12537)

Nick Fitzgeraldc211295917b2
diff --git a/crates/core/src/alloc/vec.rs b/crates/core/src/alloc/vec.rs
index 835bdaaa06..235b125e8e 100644
--- a/crates/core/src/alloc/vec.rs
+++ b/crates/core/src/alloc/vec.rs
@@ -44,8 +44,10 @@ where
impl<T> Vec<T> {
/// Same as [`std::vec::Vec::new`].
- pub fn new() -> Self {
- Default::default()
+ pub const fn new() -> Self {
+ Self {
+ inner: StdVec::new(),
+ }
}
/// Same as [`std::vec::Vec::with_capacity`] but returns an error on
diff --git a/crates/fuzzing/tests/oom.rs b/crates/fuzzing/tests/oom.rs
index 8f25dcd7b8..05aa31583b 100644
--- a/crates/fuzzing/tests/oom.rs
+++ b/crates/fuzzing/tests/oom.rs
@@ -427,6 +427,19 @@ fn linker_new() -> Result<()> {
})
}
+#[test]
+#[cfg(arc_try_new)]
+fn linker_func_wrap() -> Result<()> {
+ OomTest::new().test(|| {
+ let mut config = Config::new();
+ config.enable_compiler(false);
+ let engine = Engine::new(&config)?;
+ let mut linker = Linker::<()>::new(&engine);
+ linker.func_wrap("module", "func", |x: i32| x * 2)?;
+ Ok(())
+ })
+}
+
#[test]
#[cfg(arc_try_new)]
fn store_try_new() -> Result<()> {
diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rs
index 9e3cf42c2f..faf1e21f9a 100644
--- a/crates/wasmtime/src/runtime/component/linker.rs
+++ b/crates/wasmtime/src/runtime/component/linker.rs
@@ -741,7 +741,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
let dtor = Arc::new(crate::func::HostFunc::wrap(
&self.engine,
move |mut cx: crate::Caller<'_, T>, (param,): (u32,)| dtor(cx.as_context_mut(), param),
- ));
+ )?);
self.insert(name, Definition::Resource(ty, dtor))?;
Ok(())
}
@@ -759,7 +759,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
let dtor = Arc::new(crate::func::HostFunc::wrap_async(
&self.engine,
move |cx: crate::Caller<'_, T>, (param,): (u32,)| dtor(cx.into(), param),
- ));
+ )?);
self.insert(name, Definition::Resource(ty, dtor))?;
Ok(())
}
@@ -798,7 +798,7 @@ impl<T: 'static> LinkerInstance<'_, T> {
.await
})
},
- ));
+ )?);
self.insert(name, Definition::Resource(ty, dtor))?;
Ok(())
}
diff --git a/crates/wasmtime/src/runtime/fiber.rs b/crates/wasmtime/src/runtime/fiber.rs
index 2d5da669a6..bf9282fcfb 100644
--- a/crates/wasmtime/src/runtime/fiber.rs
+++ b/crates/wasmtime/src/runtime/fiber.rs
@@ -783,7 +783,7 @@ where
{
let opaque = store.as_store_opaque();
let engine = opaque.engine().clone();
- let executor = Executor::new(&engine);
+ let executor = Executor::new(&engine)?;
let id = opaque.id();
let stack = opaque.allocate_fiber_stack()?;
let track_pkey_context_switch = opaque.has_pkey();
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index d8ce50167f..7a5a11c14c 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -1,3 +1,4 @@
+use crate::error::OutOfMemory;
use crate::prelude::*;
use crate::runtime::vm::{
self, InterpreterRef, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext,
@@ -17,7 +18,7 @@ use core::ffi::c_void;
use core::future::Future;
use core::mem::{self, MaybeUninit};
use core::ptr::NonNull;
-use wasmtime_environ::VMSharedTypeIndex;
+use wasmtime_environ::{PanicOnOom as _, VMSharedTypeIndex};
/// A reference to the abstract `nofunc` heap value.
///
@@ -376,7 +377,7 @@ impl Func {
func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
) -> Self {
let store = store.as_context_mut().0;
- let host = HostFunc::new(store.engine(), ty, func);
+ let host = HostFunc::new(store.engine(), ty, func).panic_on_oom();
// SAFETY: the `T` used by `func` matches the `T` of the store we're
// inserting into via this function's type signature.
@@ -420,7 +421,7 @@ impl Func {
// SAFETY: the contract required by `new_unchecked` is the same as the
// contract required by this function itself.
- let host = unsafe { HostFunc::new_unchecked(store.engine(), ty, func) };
+ let host = unsafe { HostFunc::new_unchecked(store.engine(), ty, func).panic_on_oom() };
// SAFETY: the `T` used by `func` matches the `T` of the store we're
// inserting into via this function's type signature.
@@ -511,7 +512,7 @@ impl Func {
{
let store = store.as_context_mut().0;
- let host = HostFunc::new_async(store.engine(), ty, func);
+ let host = HostFunc::new_async(store.engine(), ty, func).panic_on_oom();
// SAFETY: the `T` used by `func` matches the `T` of the store we're
// inserting into via this function's type signature.
@@ -790,7 +791,7 @@ impl Func {
{
let store = store.as_context_mut().0;
let engine = store.engine();
- let host = func.into_func(engine);
+ let host = func.into_func(engine).panic_on_oom();
// SAFETY: The `T` the closure takes is the same as the `T` of the store
// we're inserting into via the type signature above.
@@ -812,7 +813,7 @@ impl Func {
T: Send + 'static,
{
let store = store.as_context_mut().0;
- let host = HostFunc::wrap_async(store.engine(), func);
+ let host = HostFunc::wrap_async(store.engine(), func).panic_on_oom();
// SAFETY: The `T` the closure takes is the same as the `T` of the store
// we're inserting into via the type signature above.
@@ -1610,7 +1611,10 @@ pub unsafe trait WasmRet {
) -> Result<()>;
#[doc(hidden)]
- fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType;
+ fn func_type(
+ engine: &Engine,
+ params: impl Iterator<Item = ValType>,
+ ) -> Result<FuncType, OutOfMemory>;
#[doc(hidden)]
fn may_gc() -> bool;
@@ -1650,8 +1654,11 @@ where
T::may_gc()
}
- fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType {
- FuncType::new(engine, params, Some(<Self as WasmTy>::valtype()))
+ fn func_type(
+ engine: &Engine,
+ params: impl Iterator<Item = ValType>,
+ ) -> Result<FuncType, OutOfMemory> {
+ FuncType::try_new(engine, params, Some(<Self as WasmTy>::valtype()))
}
fn into_fallible(self) -> Result<T> {
@@ -1690,7 +1697,10 @@ where
T::may_gc()
}
- fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType {
+ fn func_type(
+ engine: &Engine,
+ params: impl Iterator<Item = ValType>,
+ ) -> Result<FuncType, OutOfMemory> {
T::func_type(engine, params)
}
@@ -1745,8 +1755,11 @@ macro_rules! impl_wasm_host_results {
$( $t::may_gc() || )* false
}
- fn func_type(engine: &Engine, params: impl Iterator<Item = ValType>) -> FuncType {
- FuncType::new(
+ fn func_type(
+ engine: &Engine,
+ params: impl Iterator<Item = ValType>,
+ ) -> Result<FuncType, OutOfMemory> {
+ FuncType::try_new(
engine,
params,
IntoIterator::into_iter([$($t::valtype(),)*]),
@@ -1777,7 +1790,7 @@ pub trait IntoFunc<T, Params, Results>: Send + Sync + 'static {
/// Convert this function into a `VM{Array,Native}CallHostFuncContext` and
/// internal `VMFuncRef`.
#[doc(hidden)]
- fn into_func(self, engine: &Engine) -> HostFunc;
+ fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory>;
}
macro_rules! impl_into_func {
@@ -1793,7 +1806,7 @@ macro_rules! impl_into_func {
R: WasmRet,
T: 'static,
{
- fn into_func(self, engine: &Engine) -> HostFunc {
+ fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
let f = move |_: Caller<'_, T>, $arg: $arg| {
self($arg)
};
@@ -1810,7 +1823,7 @@ macro_rules! impl_into_func {
R: WasmRet,
T: 'static,
{
- fn into_func(self, engine: &Engine) -> HostFunc {
+ fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
HostFunc::wrap(engine, move |caller: Caller<'_, T>, ($arg,)| {
self(caller, $arg)
})
@@ -1829,7 +1842,7 @@ macro_rules! impl_into_func {
R: WasmRet,
T: 'static,
{
- fn into_func(self, engine: &Engine) -> HostFunc {
+ fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
let f = move |_: Caller<'_, T>, $($args:$args),*| {
self($($args),*)
};
@@ -1846,7 +1859,7 @@ macro_rules! impl_into_func {
R: WasmRet,
T: 'static,
{
- fn into_func(self, engine: &Engine) -> HostFunc {
+ fn into_func(self, engine: &Engine) -> Result<HostFunc, OutOfMemory> {
HostFunc::wrap(engine, move |caller: Caller<'_, T>, ( $( $args ),* )| {
self(caller, $( $args ),* )
})
@@ -2212,7 +2225,7 @@ impl HostFunc {
engine: &Engine,
ty: FuncType,
func: F,
- ) -> StoreBox<VMArrayCallHostFuncContext>
+ ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
where
F: Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
T: 'static,
@@ -2223,10 +2236,10 @@ impl HostFunc {
VMArrayCallHostFuncContext::new(
Self::array_call_trampoline::<T, F>,
ty.type_index(),
- Box::new(HostFuncState {
+ try_new::<Box<_>>(HostFuncState {
func,
_ty: ty.into_registered_type(),
- }),
+ })?,
)
}
}
@@ -2247,7 +2260,7 @@ impl HostFunc {
ty: FuncType,
ctx: U,
func: F,
- ) -> StoreBox<VMArrayCallHostFuncContext>
+ ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory>
where
F: for<'a> Fn(
Caller<'a, T>,
@@ -2377,11 +2390,15 @@ impl HostFunc {
engine: &Engine,
ty: FuncType,
func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
- ) -> Self
+ ) -> Result<Self, OutOfMemory>
where
T: 'static,
{
- HostFunc::new_raw(engine, Self::vmctx_sync(engine, ty, func), Asyncness::No)
+ Ok(HostFunc::new_raw(
+ engine,
+ Self::vmctx_sync(engine, ty, func)?,
+ Asyncness::No,
+ ))
}
/// Analog of [`Func::new`]
@@ -2394,13 +2411,13 @@ impl HostFunc {
engine: &Engine,
ty: FuncType,
func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
- ) -> Self
+ ) -> Result<Self, OutOfMemory>
where
T: 'static,
{
// NB: this is "duplicated" below in `new_async`, so try to keep the
// two in sync.
- HostFunc::new_raw(
+ Ok(HostFunc::new_raw(
engine,
Self::vmctx_sync(engine, ty.clone(), move |mut caller, values| {
// SAFETY: Wasmtime in general provides the guarantee that
@@ -2409,9 +2426,9 @@ impl HostFunc {
let (params, results) = vec.split_at_mut(ty.params().len());
func(caller.sub_caller(), params, results)?;
Self::store_untyped_results(caller.store, &ty, vec, values)
- }),
+ })?,
Asyncness::No,
- )
+ ))
}
/// Analog of [`Func::new_async`]
@@ -2421,7 +2438,7 @@ impl HostFunc {
/// Panics if the given function type is not associated with the given
/// engine.
#[cfg(feature = "async")]
- pub fn new_async<T, F>(engine: &Engine, ty: FuncType, func: F) -> Self
+ pub fn new_async<T, F>(engine: &Engine, ty: FuncType, func: F) -> Result<Self, OutOfMemory>
where
F: for<'a> Fn(
Caller<'a, T>,
@@ -2435,7 +2452,7 @@ impl HostFunc {
{
// NB: this is "duplicated" above in `new`, so try to keep the two in
// sync.
- HostFunc::new_raw(
+ Ok(HostFunc::new_raw(
engine,
Self::vmctx_async(
engine,
@@ -2452,9 +2469,9 @@ impl HostFunc {
Self::store_untyped_results(caller.store, &ty, vec, values)
})
},
- ),
+ )?,
Asyncness::Yes,
- )
+ ))
}
/// Loads the the parameters of `ty` from `params` into a vector.
@@ -2510,7 +2527,7 @@ impl HostFunc {
}
/// Analog of [`Func::wrap`]
- pub fn wrap<T, F, P, R>(engine: &Engine, func: F) -> Self
+ pub fn wrap<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
where
F: Fn(Caller<'_, T>, P) -> R + Send + Sync + 'static,
P: WasmTyList,
@@ -2519,7 +2536,7 @@ impl HostFunc {
{
// NB: this entire function is "duplicated" below in `wrap_async`, so
// try to keep the two in sync.
- let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()));
+ let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
let ctx = Self::vmctx_sync(engine, ty, move |mut caller, args| {
// SAFETY: `args` matching `ty` is provided by `HostFunc` and
@@ -2529,13 +2546,13 @@ impl HostFunc {
// SAFETY: `args` matching `ty` is provided by `HostFunc` and
// wasmtime's ambient correctness.
unsafe { Self::store_typed_results(caller.store.0, ret, args) }
- });
- HostFunc::new_raw(engine, ctx, Asyncness::No)
+ })?;
+ Ok(HostFunc::new_raw(engine, ctx, Asyncness::No))
}
/// Analog of [`Func::wrap_async`]
#[cfg(feature = "async")]
- pub fn wrap_async<T, F, P, R>(engine: &Engine, func: F) -> Self
+ pub fn wrap_async<T, F, P, R>(engine: &Engine, func: F) -> Result<Self, OutOfMemory>
where
F: for<'a> Fn(Caller<'a, T>, P) -> Box<dyn Future<Output = R> + Send + 'a>
+ Send
@@ -2547,7 +2564,7 @@ impl HostFunc {
{
// NB: this entire function is "duplicated" above in `wrap`, so try to
// keep the two in sync.
- let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()));
+ let ty = R::func_type(engine, None::<ValType>.into_iter().chain(P::valtypes()))?;
let ctx = Self::vmctx_async(engine, ty, func, move |mut caller, args, func| {
Box::new(async move {
@@ -2559,8 +2576,8 @@ impl HostFunc {
// wasmtime's ambient correctness.
unsafe { Self::store_typed_results(caller.store.0, ret.into_fallible(), args) }
})
- });
- HostFunc::new_raw(engine, ctx, Asyncness::Yes)
+ })?;
+ Ok(HostFunc::new_raw(engine, ctx, Asyncness::Yes))
}
/// Loads the typed parameters from `params`
diff --git a/crates/wasmtime/src/runtime/linker.rs b/crates/wasmtime/src/runtime/linker.rs
index 1376b83b44..5ba1859e51 100644
--- a/crates/wasmtime/src/runtime/linker.rs
+++ b/crates/wasmtime/src/runtime/linker.rs
@@ -1,12 +1,12 @@
+use crate::error::OutOfMemory;
use crate::func::HostFunc;
-use crate::hash_map::{Entry, HashMap};
use crate::instance::InstancePre;
+use crate::runtime::string_pool::{Atom, StringPool};
use crate::store::StoreOpaque;
use crate::{
AsContext, AsContextMut, Caller, Engine, Extern, ExternType, Func, FuncType, ImportType,
- Instance, Module, Result, StoreContextMut, Val, ValRaw,
+ Instance, IntoFunc, Module, Result, StoreContextMut, Val, ValRaw, prelude::*,
};
-use crate::{IntoFunc, prelude::*};
use alloc::sync::Arc;
use core::fmt::{self, Debug};
#[cfg(feature = "async")]
@@ -14,6 +14,10 @@ use core::future::Future;
use core::marker;
use core::mem::MaybeUninit;
use log::warn;
+use wasmtime_environ::{
+ PanicOnOom as _,
+ collections::{HashMap, TryClone},
+};
/// Structure used to link wasm modules/instances together.
///
@@ -83,8 +87,7 @@ use log::warn;
/// [`Global`]: crate::Global
pub struct Linker<T> {
engine: Engine,
- string2idx: HashMap<Arc<str>, usize>,
- strings: Vec<Arc<str>>,
+ pool: StringPool,
map: HashMap<ImportKey, Definition>,
allow_shadowing: bool,
allow_unknown_exports: bool,
@@ -101,9 +104,8 @@ impl<T> Clone for Linker<T> {
fn clone(&self) -> Linker<T> {
Linker {
engine: self.engine.clone(),
- string2idx: self.string2idx.clone(),
- strings: self.strings.clone(),
- map: self.map.clone(),
+ pool: self.pool.try_clone().panic_on_oom(),
+ map: self.map.try_clone().panic_on_oom(),
allow_shadowing: self.allow_shadowing,
allow_unknown_exports: self.allow_unknown_exports,
_marker: self._marker,
@@ -113,8 +115,15 @@ impl<T> Clone for Linker<T> {
#[derive(Copy, Clone, Hash, PartialEq, Eq)]
struct ImportKey {
- name: usize,
- module: usize,
+ module: Atom,
+ name: Option<Atom>,
+}
+
+impl TryClone for ImportKey {
+ #[inline]
+ fn try_clone(&self) -> Result<Self, OutOfMemory> {
+ Ok(*self)
+ }
}
#[derive(Clone)]
@@ -123,10 +132,16 @@ pub(crate) enum Definition {
HostFunc(Arc<HostFunc>),
}
+impl TryClone for Definition {
+ fn try_clone(&self) -> core::result::Result<Self, OutOfMemory> {
+ Ok(self.clone())
+ }
+}
+
/// This is a sort of slimmed down `ExternType` which notably doesn't have a
/// `FuncType`, which is an allocation, and additionally retains the current
/// size of the table/memory.
-#[derive(Clone, Debug)]
+#[derive(Clone, Copy, Debug)]
pub(crate) enum DefinitionType {
Func(wasmtime_environ::VMSharedTypeIndex),
Global(wasmtime_environ::Global),
@@ -150,8 +165,7 @@ impl<T> Linker<T> {
Linker {
engine: engine.clone(),
map: HashMap::new(),
- string2idx: HashMap::new(),
- strings: Vec::new(),
+ pool: StringPool::new(),
allow_shadowing: false,
allow_unknown_exports: false,
_marker: marker::PhantomData,
@@ -356,7 +370,7 @@ impl<T> Linker<T> {
T: 'static,
{
let store = store.as_context();
- let key = self.import_key(module, Some(name));
+ let key = self.import_key(module, Some(name))?;
self.insert(key, Definition::new(store.0, item.into()))?;
Ok(self)
}
@@ -377,7 +391,7 @@ impl<T> Linker<T> {
T: 'static,
{
let store = store.as_context();
- let key = self.import_key(name, None);
+ let key = self.import_key(name, None)?;
self.insert(key, Definition::new(store.0, item.into()))?;
Ok(self)
}
@@ -386,8 +400,8 @@ impl<T> Linker<T> {
where
T: 'static,
{
- let key = self.import_key(module, Some(name));
- self.insert(key, Definition::HostFunc(Arc::new(func)))?;
+ let key = self.import_key(module, Some(name))?;
+ self.insert(key, Definition::HostFunc(try_new(func)?))?;
Ok(self)
}
@@ -409,7 +423,7 @@ impl<T> Linker<T> {
where
T: 'static,
{
- self.func_insert(module, name, HostFunc::new(&self.engine, ty, func))
+ self.func_insert(module, name, HostFunc::new(&self.engine, ty, func)?)
}
/// Creates a [`Func::new_unchecked`]-style function named in this linker.
@@ -435,7 +449,7 @@ impl<T> Linker<T> {
T: 'static,
{
// SAFETY: the contract of this function is the same as `new_unchecked`.
- let func = unsafe { HostFunc::new_unchecked(&self.engine, ty, func) };
+ let func = unsafe { HostFunc::new_unchecked(&self.engine, ty, func)? };
self.func_insert(module, name, func)
}
@@ -468,7 +482,7 @@ impl<T> Linker<T> {
+ 'static,
T: Send + 'static,
{
- self.func_insert(module, name, HostFunc::new_async(&self.engine, ty, func))
+ self.func_insert(module, name, HostFunc::new_async(&self.engine, ty, func)?)
}
/// Define a host function within this linker.
@@ -536,7 +550,7 @@ impl<T> Linker<T> {
where
T: 'static,
{
- self.func_insert(module, name, func.into_func(&self.engine))
+ self.func_insert(module, name, func.into_func(&self.engine)?)
}
/// Asynchronous analog of [`Linker::func_wrap`].
@@ -554,7 +568,7 @@ impl<T> Linker<T> {
+ 'static,
T: Send + 'static,
{
- self.func_insert(module, name, HostFunc::wrap_async(&self.engine, func))
+ self.func_insert(module, name, HostFunc::wrap_async(&self.engine, func)?)
}
/// Convenience wrapper to define an entire [`Instance`] in this linker.
@@ -626,12 +640,12 @@ impl<T> Linker<T> {
let exports = instance
.exports(&mut store)
.map(|e| {
- (
- self.import_key(module_name, Some(e.name())),
+ Ok((
+ self.import_key(module_name, Some(e.name()))?,
e.into_extern(),
- )
+ ))
})
- .collect::<Vec<_>>();
+ .collect::<Result<Vec<_>>>()?;
for (key, export) in exports {
self.insert(key, Definition::new(store.0, export))?;
}
@@ -903,7 +917,7 @@ impl<T> Linker<T> {
let instance_pre = self.instantiate_pre(module)?;
let export_name = export.name().to_owned();
let func = mk_func(&mut store, func_ty, export_name, instance_pre);
- let key = self.import_key(module_name, Some(export.name()));
+ let key = self.import_key(module_name, Some(export.name()))?;
self.insert(key, Definition::new(store.0, func.into()))?;
} else if export.name() == "memory" && export.ty().memory().is_some() {
// Allow an exported "memory" memory for now.
@@ -957,8 +971,8 @@ impl<T> Linker<T> {
as_module: &str,
as_name: &str,
) -> Result<&mut Self> {
- let src = self.import_key(module, Some(name));
- let dst = self.import_key(as_module, Some(as_name));
+ let src = self.import_key(module, Some(name))?;
+ let dst = self.import_key(as_module, Some(as_name))?;
match self.map.get(&src).cloned() {
Some(item) => self.insert(dst, item)?,
None => bail!("no item named `{module}::{name}` defined"),
@@ -976,8 +990,8 @@ impl<T> Linker<T> {
/// Returns an error if any shadowing violations happen while defining new
/// items.
pub fn alias_module(&mut self, module: &str, as_module: &str) -> Result<()> {
- let module = self.intern_str(module);
- let as_module = self.intern_str(as_module);
+ let module = self.pool.insert(module)?;
+ let as_module = self.pool.insert(as_module)?;
let items = self
.map
.iter()
@@ -997,43 +1011,23 @@ impl<T> Linker<T> {
}
fn insert(&mut self, key: ImportKey, item: Definition) -> Result<()> {
- match self.map.entry(key) {
- Entry::Occupied(_) if !self.allow_shadowing => {
- let module = &self.strings[key.module];
- let desc = match self.strings.get(key.name) {
- Some(name) => format!("{module}::{name}"),
- None => module.to_string(),
- };
- bail!("import of `{desc}` defined twice")
- }
- Entry::Occupied(mut o) => {
- o.insert(item);
- }
- Entry::Vacant(v) => {
- v.insert(item);
+ if !self.allow_shadowing && self.map.contains_key(&key) {
+ let module = &self.pool[key.module];
+ match key.name.and_then(|n| self.pool.get(n)) {
+ Some(name) => bail!("import of `{module}::{name}` defined twice"),
+ None => bail!("import of `{module}` defined twice"),
}
}
- Ok(())
- }
- fn import_key(&mut self, module: &str, name: Option<&str>) -> ImportKey {
- ImportKey {
- module: self.intern_str(module),
- name: name
- .map(|name| self.intern_str(name))
- .unwrap_or(usize::max_value()),
- }
+ self.map.insert(key, item)?;
+ Ok(())
}
- fn intern_str(&mut self, string: &str) -> usize {
- if let Some(idx) = self.string2idx.get(string) {
- return *idx;
- }
- let string: Arc<str> = string.into();
- let idx = self.strings.len();
- self.strings.push(string.clone());
- self.string2idx.insert(string, idx);
- idx
+ fn import_key(&mut self, module: &str, name: Option<&str>) -> Result<ImportKey, OutOfMemory> {
+ Ok(ImportKey {
+ module: self.pool.insert(module)?,
+ name: name.map(|name| self.pool.insert(name)).transpose()?,
+ })
}
/// Attempts to instantiate the `module` provided.
@@ -1223,8 +1217,8 @@ impl<T> Linker<T> {
self.map.iter().map(move |(key, item)| {
let store = store.as_context_mut();
(
- &*self.strings[key.module],
- &*self.strings[key.name],
+ &self.pool[key.module],
+ &self.pool[key.name.unwrap()],
// Should be safe since `T` is connecting the linker and store
unsafe { item.to_extern(store.0) },
)
@@ -1257,8 +1251,8 @@ impl<T> Linker<T> {
fn _get(&self, module: &str, name: &str) -> Option<&Definition> {
let key = ImportKey {
- module: *self.string2idx.get(module)?,
- name: *self.string2idx.get(name)?,
+ module: self.pool.get_atom(module)?,
+ name: Some(self.pool.get_atom(name)?),
};
self.map.get(&key)
}
@@ -1340,7 +1334,7 @@ impl Definition {
pub(crate) fn ty(&self) -> DefinitionType {
match self {
- Definition::Extern(_, ty) => ty.clone(),
+ Definition::Extern(_, ty) => *ty,
Definition::HostFunc(func) => DefinitionType::Func(func.sig_index()),
}
}
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index f214fff565..699afef3b2 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -598,17 +598,17 @@ pub(crate) enum Executor {
}
impl Executor {
- pub(crate) fn new(engine: &Engine) -> Self {
+ pub(crate) fn new(engine: &Engine) -> Result<Self, OutOfMemory> {
#[cfg(has_host_compiler_backend)]
if cfg!(feature = "pulley") && engine.target().is_pulley() {
- Executor::Interpreter(Interpreter::new(engine))
+ Ok(Executor::Interpreter(Interpreter::new(engine)?))
} else {
- Executor::Native
+ Ok(Executor::Native)
}
#[cfg(not(has_host_compiler_backend))]
{
debug_assert!(engine.target().is_pulley());
- Executor::Interpreter(Interpreter::new(engine))
+ Ok(Executor::Interpreter(Interpreter::new(engine)?))
}
}
}
@@ -783,7 +783,7 @@ impl<T> Store<T> {
component_calls: Default::default(),
#[cfg(feature = "component-model")]
host_resource_data: Default::default(),
- executor: Executor::new(engine),
+ executor: Executor::new(engine)?,
#[cfg(feature = "component-model")]
concurrent_state: if engine.tunables().concurrency_support {
#[cfg(feature = "component-model-async")]
diff --git a/crates/wasmtime/src/runtime/string_pool.rs b/crates/wasmtime/src/runtime/string_pool.rs
index 30db692127..3c01d42e62 100644
--- a/crates/wasmtime/src/runtime/string_pool.rs
+++ b/crates/wasmtime/src/runtime/string_pool.rs
@@ -1,7 +1,5 @@
//! Simple string interning.
-#![allow(unused, reason = "used in follow up commits")]
-
use crate::{error::OutOfMemory, prelude::*};
use core::{fmt, mem, num::NonZeroU32};
use wasmtime_core::alloc::TryClone;
diff --git a/crates/wasmtime/src/runtime/trampoline/global.rs b/crates/wasmtime/src/runtime/trampoline/global.rs
index 6c3099d59a..58e22dd3a9 100644
--- a/crates/wasmtime/src/runtime/trampoline/global.rs
+++ b/crates/wasmtime/src/runtime/trampoline/global.rs
@@ -29,7 +29,7 @@ pub fn generate_global_export(
ty: global,
global: VMGlobalDefinition::new(),
_registered_type: ty.into_registered_type(),
- });
+ })?;
let mut store = AutoAssertNoGc::new(store);
// SAFETY: the global that this is pointing to is rooted in `ctx` above and
diff --git a/crates/wasmtime/src/runtime/vm/interpreter.rs b/crates/wasmtime/src/runtime/vm/interpreter.rs
index f67e088d10..5c015c2524 100644
--- a/crates/wasmtime/src/runtime/vm/interpreter.rs
+++ b/crates/wasmtime/src/runtime/vm/interpreter.rs
@@ -1,3 +1,4 @@
+use crate::error::OutOfMemory;
use crate::runtime::vm::vmcontext::VMArrayCallNative;
use crate::runtime::vm::{
StoreBox, TrapRegisters, TrapTest, VMContext, VMOpaqueContext, f32x4, f64x2, i8x16, tls,
@@ -57,15 +58,15 @@ struct VmState {
impl Interpreter {
/// Creates a new interpreter ready to interpret code.
- pub fn new(engine: &Engine) -> Interpreter {
+ pub fn new(engine: &Engine) -> Result<Interpreter, OutOfMemory> {
let ret = Interpreter {
pulley: StoreBox::new(VmState {
vm: Vm::with_stack(engine.config().max_wasm_stack),
resume_at_pc: None,
- }),
+ })?,
};
engine.profiler().register_interpreter(&ret);
- ret
+ Ok(ret)
}
/// Returns the `InterpreterRef` structure which can be used to actually
diff --git a/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs b/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs
index fd8a0829ab..e7bd948759 100644
--- a/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs
+++ b/crates/wasmtime/src/runtime/vm/interpreter_disabled.rs
@@ -5,7 +5,7 @@
//! having these structures plumbed around.
use crate::runtime::vm::{VMContext, VMOpaqueContext};
-use crate::{Engine, ValRaw};
+use crate::{Engine, ValRaw, error::OutOfMemory};
use core::convert::Infallible;
use core::marker;
use core::mem;
@@ -20,7 +20,7 @@ const _: () = assert!(mem::size_of::<Interpreter>() == 0);
const _: () = assert!(mem::size_of::<Option<Interpreter>>() == 0);
impl Interpreter {
- pub fn new(_engine: &Engine) -> Interpreter {
+ pub fn new(_engine: &Engine) -> Result<Interpreter, OutOfMemory> {
unreachable!()
}
diff --git a/crates/wasmtime/src/runtime/vm/store_box.rs b/crates/wasmtime/src/runtime/vm/store_box.rs
index 0327eba28f..8eaf8197f3 100644
--- a/crates/wasmtime/src/runtime/vm/store_box.rs
+++ b/crates/wasmtime/src/runtime/vm/store_box.rs
@@ -1,3 +1,4 @@
+use crate::error::OutOfMemory;
use crate::prelude::*;
use crate::runtime::vm::SendSyncPtr;
use core::ptr::NonNull;
@@ -15,9 +16,9 @@ pub struct StoreBox<T: ?Sized>(SendSyncPtr<T>);
impl<T> StoreBox<T> {
/// Allocates space on the heap to store `val` and returns a pointer to it
/// living on the heap.
- pub fn new(val: T) -> StoreBox<T> {
- let ptr = Box::into_raw(Box::new(val));
- StoreBox(SendSyncPtr::from(NonNull::new(ptr).unwrap()))
+ pub fn new(val: T) -> Result<StoreBox<T>, OutOfMemory> {
+ let ptr = Box::into_raw(try_new(val)?);
+ Ok(StoreBox(SendSyncPtr::from(NonNull::new(ptr).unwrap())))
}
}
diff --git a/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs b/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs
index 47ea2abf2a..36ccf47e1f 100644
--- a/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs
+++ b/crates/wasmtime/src/runtime/vm/vmcontext/vm_host_func_context.rs
@@ -3,6 +3,7 @@
//! Keep in sync with `wasmtime_environ::VMHostFuncOffsets`.
use super::{VMArrayCallNative, VMOpaqueContext};
+use crate::error::OutOfMemory;
use crate::prelude::*;
use crate::runtime::vm::{StoreBox, VMFuncRef};
use core::any::Any;
@@ -34,7 +35,7 @@ impl VMArrayCallHostFuncContext {
host_func: VMArrayCallNative,
type_index: VMSharedTypeIndex,
host_state: Box<dyn Any + Send + Sync>,
- ) -> StoreBox<VMArrayCallHostFuncContext> {
+ ) -> Result<StoreBox<VMArrayCallHostFuncContext>, OutOfMemory> {
let ctx = StoreBox::new(VMArrayCallHostFuncContext {
magic: wasmtime_environ::VM_ARRAY_CALL_HOST_FUNC_MAGIC,
func_ref: VMFuncRef {
@@ -44,12 +45,12 @@ impl VMArrayCallHostFuncContext {
vmctx: NonNull::dangling().into(),
},
host_state,
- });
+ })?;
let vmctx = VMOpaqueContext::from_vm_array_call_host_func_context(ctx.get());
unsafe {
ctx.get().as_mut().func_ref.vmctx = vmctx.into();
}
- ctx
+ Ok(ctx)
}
/// Get the host state for this host function context.