summaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/parser/src/lib.rs22
-rw-r--r--crates/tinywasm/src/engine.rs7
-rw-r--r--crates/tinywasm/src/func/context.rs22
-rw-r--r--crates/tinywasm/src/instance.rs26
-rw-r--r--crates/tinywasm/src/interpreter/stack/call_stack.rs2
-rw-r--r--crates/tinywasm/src/interpreter/stack/value_stack.rs3
-rw-r--r--crates/tinywasm/src/lib.rs7
-rw-r--r--crates/tinywasm/src/store/memory/instance.rs9
-rw-r--r--crates/tinywasm/src/store/memory/vec.rs17
-rw-r--r--crates/tinywasm/src/store/mod.rs92
-rw-r--r--crates/tinywasm/tests/host_reentrancy.rs109
-rw-r--r--crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast104
12 files changed, 344 insertions, 76 deletions
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index 2752d8b..019e027 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -190,10 +190,24 @@ impl Parser {
#[cfg(feature = "std")]
fn read_more(stream: &mut impl std::io::Read, buffer: &mut alloc::vec::Vec<u8>, hint: usize) -> Result<usize> {
let len = buffer.len();
- buffer.resize(len + hint, 0);
- let read_bytes = stream
- .read(&mut buffer[len..])
- .map_err(|e| ParseError::Other(alloc::format!("Error reading from stream: {e}")))?;
+ // Size hints can come from untrusted section lengths.
+ let increment = hint.clamp(1, 64 * 1024);
+ let new_len =
+ len.checked_add(increment).ok_or_else(|| ParseError::Other("stream buffer is too large".into()))?;
+ buffer
+ .try_reserve(increment)
+ .map_err(|e| ParseError::Other(alloc::format!("Error reserving stream buffer: {e}")))?;
+ buffer.resize(new_len, 0);
+ let read_bytes = loop {
+ match stream.read(&mut buffer[len..]) {
+ Ok(read_bytes) => break read_bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => {
+ buffer.truncate(len);
+ return Err(ParseError::Other(alloc::format!("Error reading from stream: {e}")));
+ }
+ }
+ };
buffer.truncate(len + read_bytes);
Ok(read_bytes)
}
diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs
index b4ad0b8..76acc19 100644
--- a/crates/tinywasm/src/engine.rs
+++ b/crates/tinywasm/src/engine.rs
@@ -68,7 +68,8 @@ const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames
pub struct StackConfig {
/// Initial reserved capacity for the stack.
pub initial_size: usize,
- /// Maximum number of elements the stack may contain.
+ /// Growth threshold, checked only when the stack reaches its allocated capacity.
+ /// Dynamic stacks may exceed this threshold up to their allocated capacity.
pub max_size: usize,
/// Whether the stack may grow past its initial capacity.
pub dynamic: bool,
@@ -80,7 +81,9 @@ impl StackConfig {
Self { initial_size: size, max_size: size, dynamic: false }
}
- /// Creates a dynamically growing stack with the given initial and maximum sizes.
+ /// Creates a dynamically growing stack with the given initial size and growth threshold.
+ ///
+ /// The threshold is not a strict element limit, see [`Self::max_size`].
pub const fn dynamic(initial_size: usize, max_size: usize) -> Self {
assert!(initial_size <= max_size, "initial_size must be less than or equal to max_size");
Self { initial_size, max_size, dynamic: true }
diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs
index 9a05f8b..e5c183c 100644
--- a/crates/tinywasm/src/func/context.rs
+++ b/crates/tinywasm/src/func/context.rs
@@ -89,7 +89,9 @@ impl FuncContext<'_> {
let call_stack_base = self.store.call_stack.len();
let value_stack_base = self.store.value_stack.base();
- func.call_untyped(self.store, type_addr, args, results, call_stack_base, value_stack_base)
+ self.with_reentrant_call(|store| {
+ func.call_untyped(store, type_addr, args, results, call_stack_base, value_stack_base)
+ })
}
/// Calls a Store-aware function reference in the current module context.
@@ -117,7 +119,23 @@ impl FuncContext<'_> {
func.func.item.validate_store(self.store)?;
let call_stack_base = self.store.call_stack.len();
let value_stack_base = self.store.value_stack.base();
- func.func.call_typed(self.store, params.into_wasm_values(), call_stack_base, value_stack_base)
+ self.with_reentrant_call(|store| {
+ func.func.call_typed(store, params.into_wasm_values(), call_stack_base, value_stack_base)
+ })
+ }
+
+ fn with_reentrant_call<R>(&mut self, call: impl FnOnce(&mut crate::Store) -> Result<R>) -> Result<R> {
+ // Each nested executor keeps its current frame on the native stack,
+ // outside CallStack, even when the Wasm function has no params or locals.
+ let config = self.store.engine.config().call_stack;
+ let limit = if config.dynamic { config.max_size } else { config.initial_size };
+ if self.store.reentrant_call_depth >= limit {
+ return Err(crate::Trap::CallStackOverflow.into());
+ }
+ self.store.reentrant_call_depth += 1;
+ let result = call(self.store);
+ self.store.reentrant_call_depth -= 1;
+ result
}
}
diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs
index 581eb9e..31bb733 100644
--- a/crates/tinywasm/src/instance.rs
+++ b/crates/tinywasm/src/instance.rs
@@ -189,10 +189,8 @@ impl ModuleInstance {
store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?;
addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?);
- let (elem_addrs, elem_trapped) =
- store.init_elements(&addrs.tables, &addrs.funcs, &addrs.globals, &module.elements, &type_addrs)?;
- let (data_addrs, data_trapped) =
- store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?;
+ let elem_addrs = store.alloc_elements(&addrs.funcs, &addrs.globals, &module.elements, &type_addrs)?;
+ let data_addrs = store.alloc_data(&module.data);
let instance = ModuleInstanceInner {
store_id: store.id(),
@@ -210,11 +208,25 @@ impl ModuleInstance {
};
let instance = ModuleInstance(StoreShared::new(instance));
+ // Earlier table writes can expose functions even if a later segment traps.
store.add_instance(instance.clone());
- if let Some(trap) = elem_trapped.or(data_trapped) {
- return cold!(Err(trap.into()));
- }
+ store.init_elements(
+ &instance.0.table_addrs,
+ &instance.0.func_addrs,
+ &instance.0.global_addrs,
+ &module.elements,
+ &instance.0.type_addrs,
+ &instance.0.elem_addrs,
+ )?;
+ store.init_data(
+ &instance.0.mem_addrs,
+ &instance.0.global_addrs,
+ &instance.0.func_addrs,
+ &module.data,
+ &instance.0.type_addrs,
+ &instance.0.data_addrs,
+ )?;
Ok(instance)
}
diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs
index d2c515a..411f327 100644
--- a/crates/tinywasm/src/interpreter/stack/call_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/call_stack.rs
@@ -37,6 +37,8 @@ impl CallStack {
#[inline(always)]
pub(crate) fn push(&mut self, mut call_frame: CallFrame, instr_ptr: usize) -> Result<(), Trap> {
+ // Check the limit only at capacity to avoid an extra hot-path check. Vec growth may
+ // intentionally overshoot max_size. Revisit when Vec::push_within_capacity is stable.
if self.stack.len() == self.stack.capacity() && (!self.dynamic || self.stack.len() >= self.max_size) {
return cold!(Err(Trap::CallStackOverflow));
}
diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs
index 2bed835..814195a 100644
--- a/crates/tinywasm/src/interpreter/stack/value_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs
@@ -46,6 +46,8 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> {
+ // Check the limit only at capacity to avoid an extra hot-path check. Vec growth may
+ // intentionally overshoot max_size. Revisit when Vec::push_within_capacity is stable.
if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) {
return cold!(Err(Trap::ValueStackOverflow));
}
@@ -55,6 +57,7 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> {
+ // Keep the same capacity-based limit check as push, including intentional overshoot.
if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) {
return cold!(Err(Trap::ValueStackOverflow));
}
diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs
index b2b7eae..47da470 100644
--- a/crates/tinywasm/src/lib.rs
+++ b/crates/tinywasm/src/lib.rs
@@ -65,16 +65,17 @@
//!
//! ## Cargo features
//!
-//! - **`full`:** Enables `archive`, `parallel-parser`, `parser`, and `validate`. Enabled by default.
+//! - **`full`:** Enables `archive`, `debug`, `parallel-parser`, `parser`, `state`, and `validate`. Enabled by default.
//! - **`std`:** Enables `std` and parsing from files and streams. Enabled by default.
//! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default.
//! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`.
//! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
//! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default.
-//! - **`log`:** Enables integration with the `log` crate. Enabled by default.
+//! - **`log`:** Enables integration with the `log` crate.
//! - **`send`:** Makes stores and store-local handles movable across threads.
+//! - **`state`:** Adds store-owned host state for access from host callbacks. Enabled by default.
//! - **`portable-atomic`:** Supports targets without native atomic compare-and-swap.
-//! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default.
+//! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results.
//! - **`debug`:** Derives `Debug` for runtime types. Enabled by default.
//! - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
//! - **`nightly-tail-calls`:** Uses Rust's unstable explicit tail calls for interpreter dispatch. Requires nightly Rust (recommended for maximum performance).
diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs
index b947916..9da327b 100644
--- a/crates/tinywasm/src/store/memory/instance.rs
+++ b/crates/tinywasm/src/store/memory/instance.rs
@@ -101,14 +101,7 @@ impl MemoryInstance {
src: usize,
len: usize,
) -> Result<(), Trap> {
- cold_err!(src_mem.inner.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_mem.inner.len())))?;
- cold_err!(self.inner.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))?;
- cold_err!(self.inner.copy_from(dst, &src_mem.inner, src, len).ok_or_else(|| memory_oob(
- dst,
- len,
- self.inner.len()
- )))?;
- Ok(())
+ self.inner.copy_from(dst, &src_mem.inner, src, len)
}
pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result<(), Trap> {
diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs
index c2daa16..e8586c0 100644
--- a/crates/tinywasm/src/store/memory/vec.rs
+++ b/crates/tinywasm/src/store/memory/vec.rs
@@ -124,12 +124,19 @@ impl VecMemory {
Some(())
}
- /// Copies a valid range from another memory.
+ /// Copies from another memory, checking both ranges before mutation and reporting source errors first.
#[inline(always)]
- pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) -> Option<()> {
- let src_range = src_memory.checked_range(src, len)?;
- let dst_range = self.checked_range(dst, len)?;
+ pub(super) fn copy_from(
+ &mut self,
+ dst: usize,
+ src_memory: &Self,
+ src: usize,
+ len: usize,
+ ) -> Result<(), crate::Trap> {
+ let src_range =
+ cold_err!(src_memory.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_memory.len())))?;
+ let dst_range = cold_err!(self.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.len())))?;
self.data[dst_range].copy_from_slice(&src_memory.data[src_range]);
- Some(())
+ Ok(())
}
}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index ed9b4f0..b065f2a 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -152,6 +152,7 @@ pub struct Store {
pub(crate) engine: Engine,
pub(crate) execution_fuel: u32,
pub(crate) execution_active: bool,
+ pub(crate) reentrant_call_depth: usize,
pub(crate) state: State,
pub(crate) call_stack: CallStack,
pub(crate) value_stack: ValueStack,
@@ -263,6 +264,7 @@ impl Store {
engine,
execution_fuel: 0,
execution_active: false,
+ reentrant_call_depth: 0,
#[cfg(feature = "state")]
host_state: BTreeMap::new(),
}
@@ -677,16 +679,14 @@ impl Store {
}
}
- /// Add elements to the store, returning their addresses in the store
- /// Should be called after the tables have been added
- pub(crate) fn init_elements(
+ /// Allocates all element segments before applying initialization effects.
+ pub(crate) fn alloc_elements(
&mut self,
- table_addrs: &[TableAddr],
func_addrs: &[FuncAddr],
global_addrs: &[Addr],
elements: &[Element],
type_addrs: &[TypeAddr],
- ) -> Result<(Box<[ElemAddr]>, Option<Trap>)> {
+ ) -> Result<Box<[ElemAddr]>> {
let elem_count = self.state.elements.len();
let mut elem_addrs = Vec::with_capacity(elements.len());
self.state.elements.reserve_exact(elements.len());
@@ -700,7 +700,23 @@ impl Store {
let value = self.elem_value(item, global_addrs, func_addrs, type_addrs)?;
self.state.elements[elem_addr].items.as_mut().unwrap().push(value);
}
+ elem_addrs.push((i + elem_count) as ElemAddr);
+ }
+ Ok(elem_addrs.into_boxed_slice())
+ }
+ /// Applies element initialization effects in segment order.
+ pub(crate) fn init_elements(
+ &mut self,
+ table_addrs: &[TableAddr],
+ func_addrs: &[FuncAddr],
+ global_addrs: &[Addr],
+ elements: &[Element],
+ type_addrs: &[TypeAddr],
+ elem_addrs: &[ElemAddr],
+ ) -> Result<()> {
+ for (i, element) in elements.iter().enumerate() {
+ let elem_addr = elem_addrs[i] as usize;
match &element.kind {
// doesn't need to be initialized, can be initialized lazily using the `table.init` instruction
ElementKind::Passive => {}
@@ -724,41 +740,38 @@ impl Store {
return Err(Error::Other(format!("table {table} not found for element {i}")));
};
- // In wasm 2.0, it's possible to call a function that hasn't been instantiated yet,
- // when using a partially initialized active element segments.
- // This isn't mentioned in the spec, but the "unofficial" testsuite has a test for it:
- // https://github.com/WebAssembly/testsuite/blob/5a1a590603d81f40ef471abba70a90a9ae5f4627/linking.wast#L264-L276
- // I have NO IDEA why this is allowed, but it is.
let Ok(offset) = usize::try_from(offset) else {
- return Ok((
- elem_addrs.into_boxed_slice(),
- Some(Trap::TableOutOfBounds {
- offset: usize::MAX,
- len: self.state.elements[elem_addr].items.as_ref().unwrap().len(),
- max: table.size(),
- }),
- ));
+ return Err(Trap::TableOutOfBounds {
+ offset: usize::MAX,
+ len: self.state.elements[elem_addr].items.as_ref().unwrap().len(),
+ max: table.size(),
+ }
+ .into());
};
let State { elements, tables, .. } = &mut self.state;
let init = elements[elem_addr].items.as_deref().unwrap();
let table = &mut tables[table_addr as usize];
- if let Err(trap) = table.init(offset, init) {
- return Ok((elem_addrs.into_boxed_slice(), Some(trap)));
- }
+ table.init(offset, init)?;
// f. Execute the instruction elm.drop i
elements[elem_addr].drop();
}
}
- elem_addrs.push((i + elem_count) as ElemAddr);
}
- // this should be optimized out by the compiler
- Ok((elem_addrs.into_boxed_slice(), None))
+ Ok(())
+ }
+
+ /// Allocates all data segments before applying initialization effects.
+ pub(crate) fn alloc_data(&mut self, data: &[Data]) -> Box<[DataAddr]> {
+ let start = self.state.data.len() as DataAddr;
+ self.state.data.reserve_exact(data.len());
+ self.state.data.extend(data.iter().map(|data| DataInstance { data: Some(data.data.clone()) }));
+ (start..start + data.len() as DataAddr).collect()
}
- /// Add data to the store, returning their addresses in the store
+ /// Applies data initialization effects in segment order.
pub(crate) fn init_data(
&mut self,
mem_addrs: &[MemAddr],
@@ -766,12 +779,10 @@ impl Store {
func_addrs: &[FuncAddr],
data: &[Data],
type_addrs: &[TypeAddr],
- ) -> Result<(Box<[DataAddr]>, Option<Trap>)> {
- let data_count = self.state.data.len();
- let mut data_addrs = Vec::with_capacity(data.len());
- self.state.data.reserve_exact(data.len());
+ data_addrs: &[DataAddr],
+ ) -> Result<()> {
for (i, data) in data.iter().enumerate() {
- let data_val = match &data.kind {
+ match &data.kind {
tinywasm_types::DataKind::Active { mem: mem_addr, offset } => {
let Some(mem_addr) = mem_addrs.get(*mem_addr as usize) else {
return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}")));
@@ -788,28 +799,19 @@ impl Store {
let offset = usize::try_from(offset).unwrap_or(usize::MAX);
match mem.inner.write_all(offset, &data.data) {
- Some(()) => None,
+ Some(()) => self.state.data[data_addrs[i] as usize].drop(),
None => {
- return Ok((
- data_addrs.into_boxed_slice(),
- Some(crate::Trap::MemoryOutOfBounds {
- offset,
- len: data.data.len(),
- max: mem.inner.len(),
- }),
- ));
+ return Err(
+ Trap::MemoryOutOfBounds { offset, len: data.data.len(), max: mem.inner.len() }.into()
+ );
}
}
}
- tinywasm_types::DataKind::Passive => Some(data.data.clone()),
+ tinywasm_types::DataKind::Passive => {}
};
-
- self.state.data.push(DataInstance { data: data_val });
- data_addrs.push((i + data_count) as DataAddr);
}
- // this should be optimized out by the compiler
- Ok((data_addrs.into_boxed_slice(), None))
+ Ok(())
}
/// Adds a function and returns its store address.
diff --git a/crates/tinywasm/tests/host_reentrancy.rs b/crates/tinywasm/tests/host_reentrancy.rs
new file mode 100644
index 0000000..60724a5
--- /dev/null
+++ b/crates/tinywasm/tests/host_reentrancy.rs
@@ -0,0 +1,109 @@
+#![cfg(feature = "state")]
+
+use tinywasm::engine::{Config, StackConfig};
+use tinywasm::{Engine, Error, ExecProgress, HostFunction, Imports, ModuleInstance, Result, Store, Trap};
+
+#[derive(Default)]
+struct Recursion {
+ remaining: usize,
+ visits: usize,
+ catch_overflow: bool,
+ caught: usize,
+}
+
+fn assert_call_stack_overflow(result: &Result<()>) {
+ let mut error = result.as_ref().unwrap_err();
+ while let Error::Trap(Trap::HostFunction(inner)) = error {
+ error = inner.downcast_ref::<Error>().expect("nested TinyWasm error");
+ }
+ assert!(matches!(error, Error::Trap(Trap::CallStackOverflow)), "{error:?}");
+}
+
+#[test]
+fn host_reentrancy_obeys_call_stack_policy() -> Result<()> {
+ let wasm = wat::parse_str(
+ r#"(module
+ (import "env" "recurse" (func $host))
+ (export "host" (func $host))
+ (func (export "wasm") call $host)
+ (func (export "leaf")))"#,
+ )
+ .unwrap();
+ let module = tinywasm::parse_bytes(&wasm)?;
+
+ for policy in [StackConfig::fixed(3), StackConfig::dynamic(0, 3), StackConfig::fixed(0)] {
+ for path in 0..3 {
+ for target in ["wasm", "host"] {
+ let mut imports = Imports::new();
+ imports.define(
+ "env",
+ "recurse",
+ HostFunction::from(move |mut ctx, (): ()| -> Result<()> {
+ let state = ctx.state_mut::<Recursion>().unwrap();
+ state.visits += 1;
+ state.remaining -= 1;
+ if state.remaining == 0 {
+ return Ok(());
+ }
+ let function = ctx.module().func_untyped(&ctx, target)?;
+ let result = match path {
+ 0 => {
+ let typed = ctx.module().func::<(), ()>(&ctx, target)?;
+ ctx.call(&typed, ())
+ }
+ 1 => ctx.call_untyped(&function, &[], &mut []),
+ _ => ctx.call_ref(function.as_func_ref(&ctx)?, &[], &mut []),
+ };
+ if ctx.state::<Recursion>().unwrap().catch_overflow && result.is_err() {
+ assert_call_stack_overflow(&result);
+ ctx.state_mut::<Recursion>().unwrap().caught += 1;
+ // The failed nested call must release its depth before
+ // another call is attempted in the same invocation.
+ let leaf = ctx.module().func::<(), ()>(&ctx, "leaf")?;
+ ctx.call(&leaf, ())?;
+ ctx.call(&leaf, ())?;
+ return Ok(());
+ }
+ result
+ }),
+ );
+ let mut store =
+ Store::new(Engine::new(Config::new().with_call_stack(policy))).with_state(Recursion::default());
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ let function = instance.func::<(), ()>(&store, "wasm")?;
+
+ // Finite recursion would succeed without reentrancy accounting.
+ // Run twice to check cleanup after an error, including resumable entry.
+ for resumable in [false, true] {
+ *store.state_mut::<Recursion>().unwrap() = Recursion { remaining: 16, ..Default::default() };
+ let result = if resumable {
+ function.call_resumable(&mut store, ())?.resume_with_fuel(100).map(|_| ())
+ } else {
+ function.call(&mut store, ())
+ };
+ assert_call_stack_overflow(&result);
+ assert_eq!(store.state::<Recursion>().unwrap().visits, policy.max_size + 1);
+
+ *store.state_mut::<Recursion>().unwrap() =
+ Recursion { remaining: policy.max_size + 1, ..Default::default() };
+ function.call(&mut store, ())?;
+ assert_eq!(store.state::<Recursion>().unwrap().remaining, 0);
+ }
+
+ if policy.max_size > 0 {
+ *store.state_mut::<Recursion>().unwrap() =
+ Recursion { remaining: 16, catch_overflow: true, ..Default::default() };
+ function.call(&mut store, ())?;
+ assert!(store.state::<Recursion>().unwrap().caught > 0);
+ }
+
+ *store.state_mut::<Recursion>().unwrap() = Recursion { remaining: 1, ..Default::default() };
+ assert!(matches!(
+ function.call_resumable(&mut store, ())?.resume_with_fuel(100)?,
+ ExecProgress::Completed(())
+ ));
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast b/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast
new file mode 100644
index 0000000..975b89a
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast
@@ -0,0 +1,104 @@
+;; A function exposed before data initialization traps can still drop that data.
+(module $host
+ (table (export "table") 1 funcref)
+ (func (export "run")
+ i32.const 0
+ call_indirect))
+(register "host" $host)
+(assert_trap
+ (module
+ (import "host" "table" (table 1 funcref))
+ (memory 0)
+ (func $f data.drop 0)
+ (elem (i32.const 0) $f)
+ (data (i32.const 0) "x"))
+ "out of bounds memory access")
+(assert_return (invoke $host "run"))
+(assert_return (invoke $host "run"))
+
+(module $shared
+ (table (export "table") 8 funcref)
+ (memory (export "memory") 1)
+ (func (export "run") (param i32)
+ (call_indirect (local.get 0)))
+ (func (export "load") (param i32) (result i32)
+ (i32.load8_u (local.get 0))))
+(register "shared" $shared)
+
+;; Earlier data writes persist, but the failing and later segments are not dropped.
+(assert_trap
+ (module
+ (import "shared" "table" (table 8 funcref))
+ (import "shared" "memory" (memory 1))
+ (func $earlier
+ (memory.init $earlier (i32.const 10) (i32.const 0) (i32.const 1)))
+ (func $remaining
+ (memory.init $failed (i32.const 10) (i32.const 0) (i32.const 1))
+ (memory.init $later (i32.const 11) (i32.const 0) (i32.const 1))
+ (memory.init $passive (i32.const 12) (i32.const 0) (i32.const 1)))
+ (func $drop
+ data.drop $earlier
+ data.drop $failed
+ data.drop $later
+ data.drop $passive)
+ (elem (i32.const 0) $earlier $remaining $drop)
+ (data $earlier (i32.const 0) "a")
+ (data $failed (i32.const 65535) "bc")
+ (data $later (i32.const 1) "d")
+ (data $passive "e"))
+ "out of bounds memory access")
+(assert_return (invoke $shared "load" (i32.const 0)) (i32.const 97))
+(assert_return (invoke $shared "load" (i32.const 1)) (i32.const 0))
+(assert_return (invoke $shared "load" (i32.const 65535)) (i32.const 0))
+(assert_trap (invoke $shared "run" (i32.const 0)) "out of bounds memory access")
+(assert_return (invoke $shared "run" (i32.const 1)))
+(assert_return (invoke $shared "load" (i32.const 10)) (i32.const 98))
+(assert_return (invoke $shared "load" (i32.const 11)) (i32.const 100))
+(assert_return (invoke $shared "load" (i32.const 12)) (i32.const 101))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_trap (invoke $shared "run" (i32.const 1)) "out of bounds memory access")
+
+;; An element trap stops all later effects, including declarative drops and data writes.
+(assert_trap
+ (module
+ (import "shared" "table" (table 8 funcref))
+ (import "shared" "memory" (memory 1))
+ (func $earlier
+ (table.init $earlier (i32.const 6) (i32.const 0) (i32.const 1)))
+ (func $remaining
+ (table.init $failed (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $later (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $passive (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $declared (i32.const 6) (i32.const 0) (i32.const 1))
+ (memory.init $active (i32.const 20) (i32.const 0) (i32.const 1))
+ (memory.init $data (i32.const 21) (i32.const 0) (i32.const 1)))
+ (func $drop
+ elem.drop $earlier
+ elem.drop $failed
+ elem.drop $later
+ elem.drop $passive
+ elem.drop $declared
+ data.drop $active
+ data.drop $data)
+ (func $marker
+ (i32.store8 (i32.const 22) (i32.const 42)))
+ (elem $earlier (i32.const 0) $earlier $remaining $drop)
+ (elem $failed (i32.const 7) $marker $marker)
+ (elem $later (i32.const 7) $marker)
+ (elem $passive func $marker)
+ (elem $declared declare func $marker)
+ (data $active (i32.const 0) "x")
+ (data $data "y"))
+ "out of bounds table access")
+(assert_return (invoke $shared "load" (i32.const 0)) (i32.const 97))
+(assert_trap (invoke $shared "run" (i32.const 7)) "uninitialized element")
+(assert_trap (invoke $shared "run" (i32.const 0)) "out of bounds table access")
+(assert_return (invoke $shared "run" (i32.const 1)))
+(assert_return (invoke $shared "load" (i32.const 20)) (i32.const 120))
+(assert_return (invoke $shared "load" (i32.const 21)) (i32.const 121))
+(assert_return (invoke $shared "run" (i32.const 6)))
+(assert_return (invoke $shared "load" (i32.const 22)) (i32.const 42))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_trap (invoke $shared "run" (i32.const 1)) "out of bounds table access")