summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHenry Gressmann <mail@henrygressmann.de>2026-08-08 15:43:26 +0200
committerGitHub <noreply@github.com>2026-08-08 15:43:26 +0200
commitd0c74255f9d6c57a243cf34037af0e8f371504b3 (patch)
treeeb962ddcdcafdb8ca53aaaaf93fd79b94f7e29f4
parent87f1da2b7bfbbd0f499743871a04c84d6f1bf958 (diff)
feat: initial support for the webassembly gc proposal (#50)
Signed-off-by: Henry <mail@henrygressmann.de>
-rw-r--r--CHANGELOG.md3
-rw-r--r--Cargo.lock32
-rw-r--r--Cargo.toml2
-rw-r--r--README.md48
-rw-r--r--crates/cli/src/wast_runner.rs55
-rw-r--r--crates/parser/src/conversion.rs142
-rw-r--r--crates/parser/src/lib.rs1
-rw-r--r--crates/parser/src/macros.rs32
-rw-r--r--crates/parser/src/module.rs43
-rw-r--r--crates/parser/src/optimize.rs1
-rw-r--r--crates/parser/src/visit.rs184
-rw-r--r--crates/tinywasm/Cargo.toml2
-rw-r--r--crates/tinywasm/src/engine.rs10
-rw-r--r--crates/tinywasm/src/error.rs25
-rw-r--r--crates/tinywasm/src/func.rs64
-rw-r--r--crates/tinywasm/src/imports.rs35
-rw-r--r--crates/tinywasm/src/instance.rs6
-rw-r--r--crates/tinywasm/src/interpreter/executor.rs332
-rw-r--r--crates/tinywasm/src/interpreter/stack/value_stack.rs28
-rw-r--r--crates/tinywasm/src/interpreter/values.rs54
-rw-r--r--crates/tinywasm/src/reference.rs50
-rw-r--r--crates/tinywasm/src/store/element.rs6
-rw-r--r--crates/tinywasm/src/store/function.rs8
-rw-r--r--crates/tinywasm/src/store/gc/arena.rs263
-rw-r--r--crates/tinywasm/src/store/gc/mod.rs92
-rw-r--r--crates/tinywasm/src/store/gc/object.rs218
-rw-r--r--crates/tinywasm/src/store/mod.rs470
-rw-r--r--crates/tinywasm/src/store/state.rs385
-rw-r--r--crates/tinywasm/src/store/table.rs104
-rw-r--r--crates/tinywasm/src/store/types.rs204
-rw-r--r--crates/tinywasm/tests/gc_refs.rs120
-rw-r--r--crates/tinywasm/tests/generated/wasm-2.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-3.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-extended-const.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-function-references.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-gc.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-latest.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-threads.csv1
-rw-r--r--crates/tinywasm/tests/internal_refs.rs9
-rw-r--r--crates/types/src/archive.rs2
-rw-r--r--crates/types/src/instructions.rs37
-rw-r--r--crates/types/src/lib.rs96
-rw-r--r--crates/types/src/reference.rs109
-rw-r--r--crates/types/src/types.rs158
-rw-r--r--crates/types/src/value.rs34
45 files changed, 2770 insertions, 705 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b58768f..38d4dd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,12 +10,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added support for the WebAssembly function-references proposal
+- Added support for the WebAssembly garbage-collection proposal
- Added `WasmValue::ty` and `WasmValue::matches_type`
- Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules.
### Changed
-- Function types are now stored separately and resolved through `Function::ty(&Store)`.
+- Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`.
### Fixed
diff --git a/Cargo.lock b/Cargo.lock
index 680b8fb..df0e601 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4,9 +4,9 @@ version = 4
[[package]]
name = "aho-corasick"
-version = "1.1.4"
+version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
@@ -171,9 +171,9 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.6.5"
+version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf"
+checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
dependencies = [
"clap_builder",
"clap_derive",
@@ -181,9 +181,9 @@ dependencies = [
[[package]]
name = "clap_builder"
-version = "4.6.5"
+version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078"
+checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
dependencies = [
"anstream",
"anstyle",
@@ -193,9 +193,9 @@ dependencies = [
[[package]]
name = "clap_complete"
-version = "4.6.8"
+version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1f84a88507dbd05c695f2cb5e8558e747179134005e9893882dec964190ed89"
+checksum = "3be2ad0423bdbbb0e25bc89add796f3559706d4a95e1bc98e4d9662a957b6a19"
dependencies = [
"clap",
]
@@ -690,9 +690,9 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.4.16"
+version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
@@ -982,9 +982,9 @@ dependencies = [
[[package]]
name = "wasm-testsuite"
-version = "0.7.4"
+version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6fd62746cfcc437a1bdadbe75bf29df08d5a3ae67336e4ac6cea37e0194fce47"
+checksum = "9d451d78ea8b19bbed461065802e8797edf21cfb6aa2e9cbeea0aede114f8fb4"
dependencies = [
"include_dir",
"wast",
@@ -1071,18 +1071,18 @@ dependencies = [
[[package]]
name = "zerocopy"
-version = "0.8.55"
+version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
+checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.55"
+version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
+checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index e57b6ea..ca80b66 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,12 +21,10 @@ categories = ["compilers", "embedded", "no-std", "virtualization", "wasm"]
[workspace.dependencies]
tinywasm = { path = "crates/tinywasm", version = "0.11.0-pre.0", default-features = false }
-tinywasm-cli = { path = "crates/cli", version = "0.11.0-pre.0", default-features = false }
tinywasm-parser = { path = "crates/parser", version = "0.11.0-pre.0", default-features = false }
tinywasm-types = { path = "crates/types", version = "0.11.0-pre.0", default-features = false }
eyre = "0.6"
-indexmap = "2.14"
log = "0.4"
owo-colors = { version = "4.3" }
pretty_env_logger = "0.5"
diff --git a/README.md b/README.md
index 77aaf93..484dbaf 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin
With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments.
-Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, or trap-on-OOM behavior.
+Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, the GC collection threshold, or trap-on-OOM behavior.
[^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`.
@@ -75,27 +75,31 @@ The internal `twasm` bytecode format is not currently validated as an untrusted
## Supported Proposals
-| Proposal | Status | `tinywasm` Version |
-| --------------------------------------------------------------------------------------------------------------------------------------- | ------ | ------------------ |
-| [**Multi-value**](https://github.com/WebAssembly/spec/blob/master/proposals/multi-value/Overview.md) | 🟢 | 0.2.0 |
-| [**Mutable Globals**](https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global/Overview.md) | 🟢 | 0.2.0 |
-| [**Non-trapping float-to-int Conversion**](https://github.com/WebAssembly/nontrapping-float-to-int-conversions) | 🟢 | 0.2.0 |
-| [**Sign-extension operators**](https://github.com/WebAssembly/sign-extension-ops) | 🟢 | 0.2.0 |
-| [**Bulk Memory Operations**](https://github.com/WebAssembly/spec/blob/master/proposals/bulk-memory-operations/Overview.md) | 🟢 | 0.4.0 |
-| [**Reference Types**](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) | 🟢 | 0.7.0 |
-| [**Multi-memory**](https://github.com/WebAssembly/multi-memory/blob/master/proposals/multi-memory/Overview.md) | 🟢 | 0.8.0 |
-| [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes/blob/main/proposals/custom-page-sizes/Overview.md) | 🟢 | 0.9.0 |
-| [**Extended Const**](https://github.com/WebAssembly/extended-const/blob/main/proposals/extended-const/Overview.md) | 🟢 | 0.9.0 |
-| [**Fixed-Width SIMD**](https://github.com/WebAssembly/simd/blob/main/proposals/simd/Overview.md) | 🟢 | 0.9.0 |
-| [**Memory64**](https://github.com/WebAssembly/memory64/blob/master/proposals/memory64/Overview.md) | 🟢 | 0.9.0 |
-| [**Tail Call**](https://github.com/WebAssembly/tail-call/blob/main/proposals/tail-call/Overview.md) | 🟢 | 0.9.0 |
-| [**Relaxed SIMD**](https://github.com/WebAssembly/relaxed-simd/blob/main/proposals/relaxed-simd/Overview.md) | 🟢 | 0.9.0 |
-| [**Wide Arithmetic**](https://github.com/WebAssembly/wide-arithmetic/blob/main/proposals/wide-arithmetic/Overview.md) | 🟢 | 0.9.0 |
-| [**Typed Function References**](https://github.com/WebAssembly/function-references/blob/main/proposals/function-references/Overview.md) | 🚧 | `next` |
-| [**Exception Handling**](https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/Exceptions.md) | 🌑 | - |
-| [**Garbage Collection**](https://github.com/WebAssembly/gc/blob/main/proposals/gc/Overview.md) | 🌑 | - |
-| [**Stack Switching**](https://github.com/WebAssembly/stack-switching/blob/main/proposals/stack-switching/Explainer.md) | 🌑 | - |
-| [**Threads**](https://github.com/WebAssembly/threads/blob/main-legacy/proposals/threads/Overview.md) | 🌑 | - |
+TinyWasm targets non-JavaScript core proposals through [phase 3](https://github.com/WebAssembly/proposals). JavaScript integrations and optional embedding or tooling APIs are not included here.
+
+| Proposal | Status | `tinywasm` Version |
+| ---------------------------------------------------------------------------------------------------------------- | ------ | ------------------ |
+| [**Import/Export of Mutable Globals**](https://github.com/WebAssembly/mutable-global) | 🟢 | 0.2.0 |
+| [**Multi-value**](https://github.com/WebAssembly/multi-value) | 🟢 | 0.2.0 |
+| [**Non-trapping Float-to-int Conversions**](https://github.com/WebAssembly/nontrapping-float-to-int-conversions) | 🟢 | 0.2.0 |
+| [**Sign-extension Operators**](https://github.com/WebAssembly/sign-extension-ops) | 🟢 | 0.2.0 |
+| [**Bulk Memory Operations**](https://github.com/WebAssembly/bulk-memory-operations) | 🟢 | 0.4.0 |
+| [**Reference Types**](https://github.com/WebAssembly/reference-types) | 🟢 | 0.7.0 |
+| [**Fixed-width SIMD**](https://github.com/WebAssembly/simd) | 🟢 | 0.9.0 |
+| [**Tail Calls**](https://github.com/WebAssembly/tail-call) | 🟢 | 0.9.0 |
+| [**Extended Constant Expressions**](https://github.com/WebAssembly/extended-const) | 🟢 | 0.9.0 |
+| [**Multiple Memories**](https://github.com/WebAssembly/multi-memory) | 🟢 | 0.8.0 |
+| [**Relaxed SIMD**](https://github.com/WebAssembly/relaxed-simd) | 🟢 | 0.9.0 |
+| [**Custom Annotation Syntax**](https://github.com/WebAssembly/annotations) | 🟢 | 0.8.0 |
+| [**Memory64**](https://github.com/WebAssembly/memory64) | 🟢 | 0.9.0 |
+| [**Wide Arithmetic**](https://github.com/WebAssembly/wide-arithmetic) | 🟢 | 0.9.0 |
+| [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes) | 🟢 | 0.9.0 |
+| [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` |
+| [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` |
+| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🌑 | - |
+| [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - |
+| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - |
+| [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - |
**Legend**\
🌑 -- not available\
diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs
index c773663..ad1742e 100644
--- a/crates/cli/src/wast_runner.rs
+++ b/crates/cli/src/wast_runner.rs
@@ -7,7 +7,10 @@ use std::time::Duration;
use eyre::{Context, Result, bail, eyre};
use log::{debug, error};
-use tinywasm::types::{ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, WasmType, WasmValue};
+use tinywasm::types::{
+ AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType,
+ WasmType, WasmValue,
+};
use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table};
use wast::{QuoteWat, core::AbstractHeapType};
@@ -459,7 +462,7 @@ impl WastRunner {
let expected = expected_alternatives
.iter()
.filter_map(|alts| alts.first())
- .find(|exp| exp.matches(&module_global));
+ .find(|exp| exp.matches(&module_global, &store));
if expected.is_none() {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
@@ -508,7 +511,10 @@ impl WastRunner {
}
if expected_alternatives.iter().any(|expected| {
expected.len() == outcomes.len()
- && outcomes.iter().zip(expected.iter()).all(|(outcome, exp)| exp.matches(outcome))
+ && outcomes
+ .iter()
+ .zip(expected.iter())
+ .all(|(outcome, exp)| exp.matches(outcome, &store))
}) {
Ok(())
} else {
@@ -755,16 +761,18 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result<WasmValue> {
I32(i) => WasmValue::I32(i),
I64(i) => WasmValue::I64(i),
V128(i) => WasmValue::V128(i.to_le_bytes()),
- RefExtern(v) => ExternRef::new(v).into(),
+ RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(),
RefNull(t) => match t {
wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(),
- wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern } => RefValue::Null.into(),
+ wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => {
+ RefValue::Null.into()
+ }
_ => {
bail!("unsupported arg type: refnull: {:?}", t);
}
},
- RefHost(_) => {
- bail!("unsupported arg type: RefHost");
+ RefHost(value) => {
+ RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into()
}
})
}
@@ -791,15 +799,29 @@ enum ExpectedValue {
RefNull,
RefFunc,
RefExtern,
+ RefAny,
+ RefEq,
+ RefI31,
+ RefStruct,
+ RefArray,
}
impl ExpectedValue {
- fn matches(&self, value: &WasmValue) -> bool {
+ fn matches(&self, value: &WasmValue, store: &Store) -> bool {
match self {
Self::Exact(expected) => value.eq_loose(expected),
Self::RefNull => matches!(value, WasmValue::Ref(RefValue::Null)),
Self::RefFunc => matches!(value, WasmValue::Ref(RefValue::Func(_))),
Self::RefExtern => matches!(value, WasmValue::Ref(RefValue::Extern(_))),
+ Self::RefAny => matches!(value, WasmValue::Ref(RefValue::Any(_))),
+ Self::RefEq => {
+ store.value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Eq)))
+ }
+ Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()),
+ Self::RefStruct => store
+ .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Struct))),
+ Self::RefArray => store
+ .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Array))),
}
}
}
@@ -817,7 +839,10 @@ fn wastret2tinywasmvalues(ret: wast::WastRet) -> Result<Vec<ExpectedValue>> {
}
fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result<ExpectedValue> {
- use wast::core::WastRetCore::{F32, F64, I32, I64, RefExtern, RefFunc, RefNull, V128};
+ use wast::core::WastRetCore::{
+ F32, F64, I32, I64, RefAny, RefArray, RefEq, RefExtern, RefFunc, RefHost, RefI31, RefI31Shared, RefNull,
+ RefStruct, V128,
+ };
Ok(match ret {
F32(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?),
F64(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?),
@@ -825,13 +850,23 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result<ExpectedVal
I64(i) => ExpectedValue::Exact(WasmValue::I64(i)),
V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))),
RefNull(_) => ExpectedValue::RefNull,
- RefExtern(Some(v)) => ExpectedValue::Exact(ExternRef::new(v).into()),
+ RefExtern(Some(v)) => ExpectedValue::Exact(
+ ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(),
+ ),
RefExtern(None) => ExpectedValue::RefExtern,
RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()),
RefFunc(None) => ExpectedValue::RefFunc,
RefFunc(v) => {
bail!("unsupported arg type: reffunc: {:?}", v);
}
+ RefAny => ExpectedValue::RefAny,
+ RefEq => ExpectedValue::RefEq,
+ RefI31 | RefI31Shared => ExpectedValue::RefI31,
+ RefStruct => ExpectedValue::RefStruct,
+ RefArray => ExpectedValue::RefArray,
+ RefHost(value) => ExpectedValue::Exact(
+ RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into(),
+ ),
a => {
bail!("unsupported arg type {:?}", a);
}
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index 600976a..8bc7df1 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -2,9 +2,9 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResour
#[cfg(feature = "validate")]
use crate::visit::process_operators_and_validate;
use crate::{Result, module::FunctionCode, visit::process_operators};
-use alloc::{boxed::Box, format, string::ToString, vec::Vec};
+use alloc::{boxed::Box, format, vec::Vec};
use tinywasm_types::*;
-use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations};
+use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex};
pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
let kind = match element.kind {
@@ -208,25 +208,77 @@ pub(crate) fn convert_module_code(
))
}
-pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> {
- let mut types = ty.types();
- // TODO(wasm3): Preserve recursive groups and non-function composite types instead of flattening singleton funcs.
- if types.len() != 1 {
- return Err(crate::ParseError::UnsupportedOperator(
- "Expected exactly one type in the type section".to_string(),
- ));
+pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<SubType>) -> Result<u32> {
+ let group_len = u32::try_from(ty.types().len())
+ .map_err(|_| crate::ParseError::Other("recursive type group is too large".into()))?;
+ types.reserve(group_len as usize);
+ for ty in ty.into_types() {
+ let composite = &ty.composite_type;
+ if composite.shared {
+ return Err(crate::ParseError::UnsupportedOperator("shared composite types are unsupported".into()));
+ }
+ if composite.descriptor_idx.is_some() || composite.describes_idx.is_some() {
+ return Err(crate::ParseError::UnsupportedOperator("descriptor types are unsupported".into()));
+ }
+
+ let supertype =
+ ty.supertype_idx.map(|idx| convert_type_index(idx.unpack(), group_start, group_len)).transpose()?;
+ let composite = match &composite.inner {
+ CompositeInnerType::Func(ty) => {
+ let params = ty
+ .params()
+ .iter()
+ .map(|ty| convert_valtype_in_group(ty, group_start, group_len))
+ .collect::<Result<Vec<_>>>()?;
+ let results = ty
+ .results()
+ .iter()
+ .map(|ty| convert_valtype_in_group(ty, group_start, group_len))
+ .collect::<Result<Vec<_>>>()?;
+ CompositeType::Func(FuncType::new(&params, &results))
+ }
+ CompositeInnerType::Struct(ty) => CompositeType::Struct(StructType {
+ fields: ty
+ .fields
+ .iter()
+ .map(|field| convert_field_type(field, group_start, group_len))
+ .collect::<Result<_>>()?,
+ }),
+ CompositeInnerType::Array(ty) => {
+ CompositeType::Array(ArrayType { field: convert_field_type(&ty.0, group_start, group_len)? })
+ }
+ CompositeInnerType::Cont(_) => {
+ return Err(crate::ParseError::UnsupportedOperator("continuation types are unsupported".into()));
+ }
+ };
+ types.push(SubType { is_final: ty.is_final, supertype, composite });
+ }
+ Ok(group_len)
+}
+
+fn convert_type_index(index: UnpackedIndex, group_start: u32, group_len: u32) -> Result<TypeAddr> {
+ match index {
+ UnpackedIndex::Module(index) => Ok(index),
+ UnpackedIndex::RecGroup(index) if index < group_len => {
+ group_start.checked_add(index).ok_or_else(|| crate::ParseError::Other("type index is too large".into()))
+ }
+ UnpackedIndex::RecGroup(index) => {
+ Err(crate::ParseError::Other(format!("recursive group type index out of bounds: {index}")))
+ }
+ #[cfg(feature = "validate")]
+ UnpackedIndex::Id(_) => {
+ Err(crate::ParseError::UnsupportedOperator(format!("unsupported canonical type index: {index}")))
+ }
}
+}
- let ty = types.next().unwrap();
- let CompositeInnerType::Func(ty) = &ty.composite_type.inner else {
- return Err(crate::ParseError::UnsupportedOperator(format!(
- "Unsupported non-function type in type section: {}",
- ty.composite_type
- )));
+fn convert_field_type(field: &wasmparser::FieldType, group_start: u32, group_len: u32) -> Result<FieldType> {
+ let storage = match &field.element_type {
+ wasmparser::StorageType::I8 => StorageType::I8,
+ wasmparser::StorageType::I16 => StorageType::I16,
+ wasmparser::StorageType::Val(ty) => StorageType::Value(convert_valtype_in_group(ty, group_start, group_len)?),
};
- let params = ty.params().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?;
- let results = ty.results().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?;
- Ok(FuncType::new(&params, &results))
+ Ok(FieldType { storage, mutable: field.mutable })
}
pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> {
@@ -234,13 +286,23 @@ pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> {
}
pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> {
+ convert_valtype_with_group(valtype, None)
+}
+
+fn convert_valtype_in_group(valtype: &wasmparser::ValType, group_start: u32, group_len: u32) -> Result<WasmType> {
+ convert_valtype_with_group(valtype, Some((group_start, group_len)))
+}
+
+fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, u32)>) -> Result<WasmType> {
match valtype {
wasmparser::ValType::I32 => Ok(WasmType::I32),
wasmparser::ValType::I64 => Ok(WasmType::I64),
wasmparser::ValType::F32 => Ok(WasmType::F32),
wasmparser::ValType::F64 => Ok(WasmType::F64),
wasmparser::ValType::V128 => Ok(WasmType::V128),
- wasmparser::ValType::Ref(r) => Ok(WasmType::Ref(convert_ref_type(*r)?)),
+ wasmparser::ValType::Ref(r) => {
+ Ok(WasmType::Ref(convert_heap_type_with_group(r.heap_type(), r.is_nullable(), group)?))
+ }
}
}
@@ -265,6 +327,20 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
wasmparser::Operator::RefFunc { function_index } => {
ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index)))
}
+ wasmparser::Operator::RefI31 => ConstInstruction::RefI31,
+ wasmparser::Operator::AnyConvertExtern => ConstInstruction::AnyConvertExtern,
+ wasmparser::Operator::ExternConvertAny => ConstInstruction::ExternConvertAny,
+ wasmparser::Operator::StructNew { struct_type_index } => ConstInstruction::StructNew(struct_type_index),
+ wasmparser::Operator::StructNewDefault { struct_type_index } => {
+ ConstInstruction::StructNewDefault(struct_type_index)
+ }
+ wasmparser::Operator::ArrayNew { array_type_index } => ConstInstruction::ArrayNew(array_type_index),
+ wasmparser::Operator::ArrayNewDefault { array_type_index } => {
+ ConstInstruction::ArrayNewDefault(array_type_index)
+ }
+ wasmparser::Operator::ArrayNewFixed { array_type_index, array_size } => {
+ ConstInstruction::ArrayNewFixed(array_type_index, array_size)
+ }
wasmparser::Operator::I32Const { value } => ConstInstruction::I32Const(value),
wasmparser::Operator::I64Const { value } => ConstInstruction::I64Const(value),
wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())),
@@ -294,6 +370,14 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
}
pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> Result<RefType> {
+ convert_heap_type_with_group(heap, nullable, None)
+}
+
+fn convert_heap_type_with_group(
+ heap: wasmparser::HeapType,
+ nullable: bool,
+ group: Option<(u32, u32)>,
+) -> Result<RefType> {
match heap {
wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract(
nullable,
@@ -316,9 +400,23 @@ pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> R
},
)),
wasmparser::HeapType::Concrete(index) => {
- let index = index.as_module_index().ok_or_else(|| {
- crate::ParseError::UnsupportedOperator(format!("Unsupported non-module heap type index: {index:?}"))
- })?;
+ let index = match index {
+ UnpackedIndex::Module(index) => index,
+ index @ UnpackedIndex::RecGroup(_) => {
+ let (group_start, group_len) = group.ok_or_else(|| {
+ crate::ParseError::UnsupportedOperator(format!(
+ "recursive-group heap type outside a type group: {index}"
+ ))
+ })?;
+ convert_type_index(index, group_start, group_len)?
+ }
+ #[cfg(feature = "validate")]
+ index @ UnpackedIndex::Id(_) => {
+ return Err(crate::ParseError::UnsupportedOperator(format!(
+ "unsupported canonical heap type index: {index}"
+ )));
+ }
+ };
RefType::new_concrete(nullable, index)
.ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}")))
}
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index 6efc112..5439558 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -174,6 +174,7 @@ impl Parser {
| WasmFeatures::BULK_MEMORY_OPT
| WasmFeatures::RELAXED_SIMD
| WasmFeatures::GC_TYPES
+ | WasmFeatures::GC
| WasmFeatures::REFERENCE_TYPES
| WasmFeatures::MUTABLE_GLOBAL
| WasmFeatures::MULTI_VALUE
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 4ce23bb..553f439 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -37,6 +37,27 @@ pub(crate) mod visit {
$(lowering_ops!(@effect $inputs => $outputs $visit);)*
lowering_ops!($($rest)*);
};
+ (unsupported $args:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => {
+ $(lowering_ops!(@unsupported $args $visit);)*
+ lowering_ops!($($rest)*);
+ };
+ (heap $nullable:literal $inputs:tt => $outputs:tt {
+ $($visit:ident => $instr:ident),* $(,)?
+ } $($rest:tt)*) => {
+ $(
+ fn $visit(&mut self, heap_type: wasmparser::HeapType) -> Self::Output {
+ let ty = convert_heap_type(heap_type, $nullable)?;
+ lowering_ops!(@emit self fixed $inputs => $outputs Instruction::$instr(ty))
+ }
+ )*
+ lowering_ops!($($rest)*);
+ };
+
+ (@unsupported [$($argty:ty),*] $visit:ident) => {
+ fn $visit(&mut self $(, _: $argty)*) -> Self::Output {
+ Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string()))
+ }
+ };
(@fixed [$($input:ident),*] => [$($output:ident),*]
$visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident
@@ -64,6 +85,15 @@ pub(crate) mod visit {
(@table $inputs:tt => $outputs:tt $($operator:tt)*) => {
lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*);
};
+ (@array_field [$($input:ident),*] => [$($output:ident),*]
+ $visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident
+ ) => {
+ fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output {
+ let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage);
+ lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*]
+ Instruction::$instr($type_index $(, $arg)*).into())
+ }
+ };
(@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*]
$visit:ident($index:ident: $ty:ty) => $instr:ident
) => {
@@ -110,6 +140,7 @@ pub(crate) mod visit {
};
(@size Addr, $address:ident) => { $address };
+ (@size Field, $address:ident) => { $address };
(@size $size:ident $(, $address:ident)?) => { OperandSize::$size };
}
@@ -128,6 +159,7 @@ pub(crate) mod visit {
(@@relaxed_simd $($rest:tt)* ) => {};
(@@tail_call $($rest:tt)* ) => {};
(@@function_references $($rest:tt)* ) => {};
+ (@@gc $($rest:tt)* ) => {};
(@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => {
fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output {
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index a269141..237478c 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -44,11 +44,12 @@ pub(crate) struct ModuleReader<'a> {
translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
has_code_section: bool,
+ has_type_section: bool,
marker: PhantomData<&'a [u8]>,
pub(crate) version: Option<u16>,
pub(crate) start_func: Option<u32>,
- pub(crate) func_types: Box<[FuncType]>,
+ pub(crate) types: TypeSection,
pub(crate) code_type_addrs: Box<[u32]>,
code_results: Box<[ValueCounts]>,
pub(crate) exports: Arc<[Export]>,
@@ -71,7 +72,7 @@ impl<'a> ModuleReader<'a> {
fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata {
if self.translation_metadata.is_none() {
self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new(
- &self.func_types,
+ &self.types,
&self.code_type_addrs,
&self.imports,
&self.globals,
@@ -119,12 +120,25 @@ impl<'a> ModuleReader<'a> {
self.start_func = Some(func);
}
Payload::TypeSection(reader) => {
- check_section("type", !self.func_types.is_empty())?;
+ check_section("type", self.has_type_section)?;
+ self.has_type_section = true;
#[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.type_section(&reader)?;
}
- self.func_types = reader.into_iter().map(|t| convert_module_type(t?)).collect::<Result<_>>()?;
+ let mut types = Vec::with_capacity(reader.count() as usize);
+ let mut rec_group_lengths = Vec::with_capacity(reader.count() as usize);
+ for group in reader {
+ let group = group?;
+ let group_start = u32::try_from(types.len())
+ .map_err(|_| ParseError::Other("type section is too large".into()))?;
+ let group_len = convert_rec_group(group, group_start, &mut types)?;
+ rec_group_lengths.push(group_len);
+ }
+ self.types = TypeSection {
+ types: types.into_boxed_slice(),
+ rec_group_lengths: rec_group_lengths.into_boxed_slice(),
+ };
}
Payload::GlobalSection(reader) => {
check_section("global", !self.globals.is_empty())?;
@@ -207,10 +221,9 @@ impl<'a> ModuleReader<'a> {
let mut results = Vec::with_capacity(reader.count() as usize);
for ty_idx in reader {
let ty_idx = ty_idx?;
- let ty = self
- .func_types
- .get(ty_idx as usize)
- .ok_or_else(|| ParseError::Other(format!("function type index out of bounds: {ty_idx}")))?;
+ let ty = self.types.get(ty_idx).and_then(SubType::as_func).ok_or_else(|| {
+ ParseError::Other(format!("function type index does not reference a function: {ty_idx}"))
+ })?;
type_addrs.push(ty_idx);
results.push(ValueCounts::from_iter(ty.results()));
}
@@ -227,7 +240,14 @@ impl<'a> ModuleReader<'a> {
for import in reader.into_imports() {
let import = convert_module_import(import?)?;
match import.kind {
- ImportKind::Function(_) => self.imported_func_count += 1,
+ ImportKind::Function(type_idx) => {
+ if self.types.get(type_idx).and_then(SubType::as_func).is_none() {
+ return Err(ParseError::Other(format!(
+ "function import type index does not reference a function: {type_idx}"
+ )));
+ }
+ self.imported_func_count += 1;
+ }
ImportKind::Memory(_) => self.imported_memory_count += 1,
_ => {}
}
@@ -504,7 +524,8 @@ impl<'a> ModuleReader<'a> {
.zip(self.code_type_addrs)
.zip(self.code_results)
.map(|((code, ty_idx), results)| {
- let ty = self.func_types.get(ty_idx as usize).expect("function type was checked while parsing").clone();
+ let ty =
+ self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing");
let params = ValueCounts::from_iter(ty.params());
if code.uses_local_memory {
local_memory_allocation = LocalMemoryAllocation::Eager;
@@ -522,7 +543,7 @@ impl<'a> ModuleReader<'a> {
Ok(ModuleInner {
funcs,
- func_types: self.func_types,
+ types: self.types,
func_type_idxs,
globals: self.globals,
tables: self.tables,
diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs
index dcb7568..5c2d7d5 100644
--- a/crates/parser/src/optimize.rs
+++ b/crates/parser/src/optimize.rs
@@ -858,6 +858,7 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> {
| Instruction::JumpIfNonZero64(ip)
| Instruction::JumpIfRefNull(ip)
| Instruction::JumpIfRefNonNull(ip)
+ | Instruction::BrOnCast(ip, _, _)
| Instruction::JumpCmpStackConst32 { target_ip: ip, .. }
| Instruction::JumpCmpStackConst64 { target_ip: ip, .. }
| Instruction::JumpIfLocalZero32 { target_ip: ip, .. }
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index 67651f9..4437242 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -2,8 +2,8 @@ use crate::{Result, conversion::convert_heap_type, macros::visit::*};
use alloc::string::ToString;
use alloc::vec::Vec;
use tinywasm_types::{
- FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableDefinition, ValueCounts,
- WasmFunctionData, WasmType,
+ Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition,
+ TypeSection, ValueCounts, WasmFunctionData, WasmType,
};
use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator};
@@ -85,11 +85,12 @@ pub(crate) struct Signature {
}
pub(crate) struct ModuleMetadata {
- signatures: Vec<Signature>,
+ signatures: Vec<Option<Signature>>,
functions: Vec<u32>,
globals: Vec<OperandSize>,
memories: Vec<OperandSize>,
tables: Vec<OperandSize>,
+ types: Vec<SubType>,
}
#[derive(Default)]
@@ -140,6 +141,16 @@ impl<'a> FunctionBuilder<'a> {
lane_counts: ValueCounts::default(),
}
}
+
+ fn visit_struct_get_impl(
+ &mut self,
+ type_index: u32,
+ field_index: u32,
+ instruction: fn(u32, u32) -> Instruction,
+ ) -> Result<()> {
+ let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage);
+ self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index))
+ }
}
#[cfg(feature = "validate")]
@@ -151,7 +162,7 @@ struct ValidateThenVisit<'a, 'm> {
impl ModuleMetadata {
pub(crate) fn new(
- types: &[FuncType],
+ types: &TypeSection,
code_type_addrs: &[u32],
imports: &[Import],
globals: &[Global],
@@ -178,19 +189,30 @@ impl ModuleMetadata {
table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch())));
let signatures = types
+ .types
.iter()
- .map(|ty| Signature {
- params: ty.params().iter().map(OperandSize::from).collect(),
- results: ty.results().iter().map(OperandSize::from).collect(),
+ .map(|ty| {
+ ty.as_func().map(|ty| Signature {
+ params: ty.params().iter().map(OperandSize::from).collect(),
+ results: ty.results().iter().map(OperandSize::from).collect(),
+ })
})
.collect();
- Self { signatures, functions, globals: global_sizes, memories: memory_sizes, tables: table_sizes }
+ Self {
+ signatures,
+ functions,
+ globals: global_sizes,
+ memories: memory_sizes,
+ tables: table_sizes,
+ types: types.types.to_vec(),
+ }
}
pub(crate) fn signature(&self, idx: u32) -> Result<&Signature> {
self.signatures
.get(idx as usize)
- .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index out of bounds: {idx}")))
+ .and_then(Option::as_ref)
+ .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a function type: {idx}")))
}
fn function_signature(&self, idx: u32) -> Result<&Signature> {
@@ -219,6 +241,36 @@ impl ModuleMetadata {
.copied()
.ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}")))
}
+
+ fn storage_size(storage: StorageType) -> OperandSize {
+ match storage {
+ StorageType::I8 | StorageType::I16 => OperandSize::S32,
+ StorageType::Value(ref ty) => OperandSize::from(ty),
+ }
+ }
+
+ fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> {
+ self.types
+ .get(idx as usize)
+ .and_then(SubType::as_struct)
+ .map(|ty| ty.fields.as_ref())
+ .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}")))
+ }
+
+ fn struct_field(&self, type_index: u32, field_index: u32) -> Result<tinywasm_types::FieldType> {
+ self.struct_fields(type_index)?
+ .get(field_index as usize)
+ .copied()
+ .ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into()))
+ }
+
+ fn array_field(&self, idx: u32) -> Result<tinywasm_types::FieldType> {
+ self.types
+ .get(idx as usize)
+ .and_then(SubType::as_array)
+ .map(|ty| ty.field)
+ .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}")))
+ }
}
#[cfg(feature = "validate")]
@@ -339,8 +391,17 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop }
fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc }
fixed [] => [S64] { visit_i64_const(value: i64) => Const64 }
+ heap false [] => [S32] { visit_ref_null => RefNull }
+ heap false [S32] => [S32] {
+ visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast,
+ }
+ heap true [S32] => [S32] {
+ visit_ref_test_nullable => RefTest, visit_ref_cast_nullable => RefCast,
+ }
fixed [S32] => [S32] {
- visit_i32_eqz => I32Eqz, visit_ref_is_null => RefIsNull, visit_i32_clz => I32Clz,
+ visit_ref_is_null => RefIsNull, visit_ref_as_non_null => RefAsNonNull, visit_ref_i31 => RefI31,
+ visit_i31_get_s => I31GetS, visit_i31_get_u => I31GetU,
+ visit_i32_eqz => I32Eqz, visit_i32_clz => I32Clz,
visit_i32_ctz => I32Ctz, visit_i32_popcnt => I32Popcnt, visit_i32_extend8_s => I32Extend8S,
visit_i32_extend16_s => I32Extend16S, visit_i32_trunc_f32_s => I32TruncF32S,
visit_i32_trunc_f32_u => I32TruncF32U, visit_f32_convert_i32_s => F32ConvertI32S,
@@ -349,6 +410,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
visit_f32_ceil => F32Ceil, visit_f32_floor => F32Floor, visit_f32_trunc => F32Trunc,
visit_f32_nearest => F32Nearest, visit_f32_sqrt => F32Sqrt,
}
+ effect [S32] => [S32] { visit_any_convert_extern, visit_extern_convert_any }
fixed [S64] => [S64] {
visit_i64_clz => I64Clz, visit_i64_ctz => I64Ctz, visit_i64_popcnt => I64Popcnt,
visit_i64_extend8_s => I64Extend8S, visit_i64_extend16_s => I64Extend16S,
@@ -373,7 +435,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
visit_i64_trunc_sat_f32_u => I64TruncSatF32U,
}
fixed [S32, S32] => [S32] {
- visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU,
+ visit_ref_eq => RefEq, visit_i32_eq => I32Eq, visit_i32_ne => I32Ne,
+ visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU,
visit_i32_gt_s => I32GtS, visit_i32_gt_u => I32GtU, visit_i32_le_s => I32LeS,
visit_i32_le_u => I32LeU, visit_i32_ge_s => I32GeS, visit_i32_ge_u => I32GeU,
visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt,
@@ -420,6 +483,65 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow }
table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill }
table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit }
+ fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault }
+ fixed [S32] => [S32] {
+ visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen,
+ }
+ fixed [S32, S32] => [S32] {
+ visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData,
+ visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem,
+ }
+ fixed [S32, S32, S32, S32] => [] {
+ visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData,
+ visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem,
+ }
+ fixed [S32, S32, S32, S32, S32] => [] {
+ visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy,
+ }
+ array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew }
+ array_field [S32, S32] => [Field] {
+ visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS,
+ visit_array_get_u(type_index: u32) => ArrayGetU,
+ }
+ array_field [S32, S32, Field] => [] { visit_array_set(type_index: u32) => ArraySet }
+ array_field [S32, S32, Field, S32] => [] { visit_array_fill(type_index: u32) => ArrayFill }
+ }
+
+ fn visit_struct_new(&mut self, type_index: u32) -> Self::Output {
+ let inputs = self
+ .metadata
+ .struct_fields(type_index)?
+ .iter()
+ .map(|field| ModuleMetadata::storage_size(field.storage))
+ .collect::<Vec<_>>();
+ self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index))
+ }
+
+ fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGet)
+ }
+
+ fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Self::Output {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetS)
+ }
+
+ fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Self::Output {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetU)
+ }
+
+ fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output {
+ let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage);
+ self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index))
+ }
+
+ fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output {
+ let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage);
+ for _ in 0..array_size {
+ self.pop_expect(size)?;
+ }
+ self.push_sizes(&[OperandSize::S32])?;
+ self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size));
+ Ok(())
}
fn visit_call(&mut self, function_index: u32) -> Self::Output {
@@ -718,14 +840,22 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem })
}
- // Reference Types
- fn visit_ref_null(&mut self, ty: wasmparser::HeapType) -> Self::Output {
- let instruction = Instruction::RefNull(convert_heap_type(ty, false)?);
- self.emit(&[], &[OperandSize::S32], instruction)
+ fn visit_br_on_cast(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Self::Output {
+ self.emit_cast_branch(relative_depth, to_ref_type, false)
}
- fn visit_ref_as_non_null(&mut self) -> Self::Output {
- self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull)
+ fn visit_br_on_cast_fail(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Self::Output {
+ self.emit_cast_branch(relative_depth, to_ref_type, true)
}
fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output {
@@ -971,6 +1101,23 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
}
impl FunctionBuilder<'_> {
+ fn emit_cast_branch(
+ &mut self,
+ relative_depth: u32,
+ target: wasmparser::RefType,
+ branch_on_fail: bool,
+ ) -> Result<()> {
+ self.pop_expect(OperandSize::S32)?;
+ let target = convert_heap_type(target.heap_type(), target.is_nullable())?;
+ let conditional_ip = self.instructions.len();
+ self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail));
+ self.push_sizes(&[OperandSize::S32])?;
+ self.emit_dropkeep_to_label(relative_depth)?;
+ self.emit_branch_jump_or_return(relative_depth)?;
+ self.patch_jump(conditional_ip, self.instructions.len());
+ Ok(())
+ }
+
fn is_unreachable(&self) -> bool {
self.control_stack.last().is_none_or(|frame| frame.unreachable)
}
@@ -1108,7 +1255,8 @@ impl FunctionBuilder<'_> {
| Instruction::JumpIfZero32(ip)
| Instruction::JumpIfNonZero32(ip)
| Instruction::JumpIfRefNull(ip)
- | Instruction::JumpIfRefNonNull(ip) => {
+ | Instruction::JumpIfRefNonNull(ip)
+ | Instruction::BrOnCast(ip, _, _) => {
*ip = target as u32;
}
_ => {}
diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml
index d1c387b..6cf9b17 100644
--- a/crates/tinywasm/Cargo.toml
+++ b/crates/tinywasm/Cargo.toml
@@ -70,7 +70,6 @@ name = "test-wasm-custom-page-sizes"
[[test]]
harness = false
name = "test-wasm-function-references"
-test = false
[[test]]
harness = false
@@ -79,7 +78,6 @@ name = "test-wasm-custom"
[[test]]
harness = false
name = "test-wasm-gc"
-test = false
[[test]]
harness = false
diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs
index 521eb80..64ef6be 100644
--- a/crates/tinywasm/src/engine.rs
+++ b/crates/tinywasm/src/engine.rs
@@ -123,6 +123,9 @@ pub struct Config {
/// Whether memory and stack allocation failures should trap instead of degrading into normal operation failure modes.
/// Defaults to `false`.
pub trap_on_oom: bool,
+ /// Initial number of GC heap bytes that triggers collection.
+ /// Defaults to 1 MiB.
+ pub gc_collection_threshold: usize,
}
impl Config {
@@ -181,6 +184,12 @@ impl Config {
self
}
+ /// Set the initial GC heap collection threshold in bytes.
+ pub fn with_gc_collection_threshold(mut self, threshold: usize) -> Self {
+ self.gc_collection_threshold = threshold;
+ self
+ }
+
/// Get the current fuel policy
pub fn fuel_policy(&self) -> FuelPolicy {
self.fuel_policy
@@ -206,6 +215,7 @@ impl Default for Config {
fuel_policy: FuelPolicy::default(),
memory_backend: MemoryBackend::default(),
trap_on_oom: false,
+ gc_collection_threshold: 1024 * 1024,
}
}
}
diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs
index b5885ca..ebd0470 100644
--- a/crates/tinywasm/src/error.rs
+++ b/crates/tinywasm/src/error.rs
@@ -133,6 +133,9 @@ pub enum Trap {
max: usize,
},
+ /// An out-of-bounds GC array access occurred.
+ ArrayOutOfBounds,
+
/// A division by zero occurred
DivisionByZero,
@@ -169,9 +172,21 @@ pub enum Trap {
/// A null reference was used where a non-null reference was required.
NullReference,
+ /// A null struct reference was dereferenced.
+ NullStructReference,
+
+ /// A null array reference was dereferenced.
+ NullArrayReference,
+
/// A null function reference was called.
NullFunctionReference,
+ /// A null i31 reference was unwrapped.
+ NullI31Reference,
+
+ /// A reference cast failed.
+ CastFailure,
+
/// Indirect call type mismatch
IndirectCallTypeMismatch {
/// The expected type
@@ -191,6 +206,7 @@ impl Trap {
Self::Unreachable => "unreachable",
Self::MemoryOutOfBounds { .. } => "out of bounds memory access",
Self::TableOutOfBounds { .. } => "out of bounds table access",
+ Self::ArrayOutOfBounds => "out of bounds array access",
Self::DivisionByZero => "integer divide by zero",
Self::InvalidConversionToInt => "invalid conversion to integer",
Self::IntegerOverflow => "integer overflow",
@@ -200,7 +216,11 @@ impl Trap {
Self::UndefinedElement { .. } => "undefined element",
Self::UninitializedElement { .. } => "uninitialized element",
Self::NullReference => "null reference",
+ Self::NullStructReference => "null structure reference",
+ Self::NullArrayReference => "null array reference",
Self::NullFunctionReference => "null function reference",
+ Self::NullI31Reference => "null i31 reference",
+ Self::CastFailure => "cast failure",
Self::IndirectCallTypeMismatch { .. } => "indirect call type mismatch",
Self::HostFunction(_) => "host function trap",
Self::InvalidStore => "invalid store",
@@ -291,6 +311,7 @@ impl Display for Trap {
Self::TableOutOfBounds { offset, len, max } => {
write!(f, "out of bounds table access: offset={offset}, len={len}, max={max}")
}
+ Self::ArrayOutOfBounds => write!(f, "out of bounds array access"),
Self::DivisionByZero => write!(f, "integer divide by zero"),
Self::InvalidConversionToInt => write!(f, "invalid conversion to integer"),
Self::IntegerOverflow => write!(f, "integer overflow"),
@@ -302,7 +323,11 @@ impl Display for Trap {
write!(f, "uninitialized element: index={index}")
}
Self::NullReference => write!(f, "null reference"),
+ Self::NullStructReference => write!(f, "null structure reference"),
+ Self::NullArrayReference => write!(f, "null array reference"),
Self::NullFunctionReference => write!(f, "null function reference"),
+ Self::NullI31Reference => write!(f, "null i31 reference"),
+ Self::CastFailure => write!(f, "cast failure"),
Self::InvalidStore => write!(f, "invalid store"),
#[cfg(feature = "debug")]
Self::IndirectCallTypeMismatch { expected, actual } => {
diff --git a/crates/tinywasm/src/func.rs b/crates/tinywasm/src/func.rs
index b6b7b14..732cafc 100644
--- a/crates/tinywasm/src/func.rs
+++ b/crates/tinywasm/src/func.rs
@@ -44,16 +44,25 @@ impl Function {
// Execute until completion and then collect result values from the stack.
InterpreterRuntime::exec(store, callframe, 0)?;
- collect_call_results(&mut store.value_stack, store.state.get_type(func_instance.type_addr))
+ collect_call_results(
+ &mut store.value_stack,
+ &store.state,
+ store.state.get_canonical_func_type(func_instance.type_addr),
+ )
}
self.item.validate_store(store)?;
validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?;
+ let results_may_gc = store.state.get_func(self.addr()).gc.results;
store.enter_execution()?;
let result = call_inner(self, store, params);
store.exit_execution();
+ if results_may_gc && let Ok(values) = &result {
+ store.state.pin_host_values(values);
+ }
+
result
}
@@ -97,12 +106,17 @@ impl Function {
self.item.validate_store(store)?;
validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?;
+ let results_may_gc = store.state.get_func(self.addr()).gc.results;
store.enter_execution()?;
let result = call_resumable_inner(self, store, params);
store.exit_execution();
- Ok(FuncExecution { store, state: result? })
+ let state = result?;
+ if results_may_gc && let FuncExecutionState::Completed { result: Some(values) } = &state {
+ store.state.pin_host_values(values);
+ }
+ Ok(FuncExecution { store, state })
}
}
@@ -188,6 +202,7 @@ impl HostFunction {
let type_addr = store.register_host_type(ty);
let addr = store.add_func(FunctionInstance {
type_addr,
+ gc: store.state.func_gc_metadata(type_addr),
kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(func) })),
});
Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
@@ -231,6 +246,7 @@ impl HostFunction {
let type_addr = store.register_host_type(&ty);
let addr = store.add_func(FunctionInstance {
type_addr,
+ gc: store.state.func_gc_metadata(type_addr),
kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(inner_func) })),
});
Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
@@ -328,7 +344,7 @@ impl FuncContext<'_> {
validate_call_params(&self.store.state, self.store.state.get_func_type(func.addr()), args)?;
let func_instance = self.store.state.get_func(func.addr()).clone();
- match func_instance.kind {
+ let result = match func_instance.kind {
crate::store::FunctionKind::Host(host_func) => {
let result =
host_func.call(FuncContext { store: &mut *self.store, module_id: func.module_id }, args)?;
@@ -354,9 +370,19 @@ impl FuncContext<'_> {
self.store.value_stack.truncate_to_base(value_stack_base);
})?;
- collect_call_results(&mut self.store.value_stack, self.store.state.get_type(func_instance.type_addr))
+ collect_call_results(
+ &mut self.store.value_stack,
+ &self.store.state,
+ self.store.state.get_canonical_func_type(func_instance.type_addr),
+ )
}
+ };
+ if func_instance.gc.results
+ && let Ok(values) = &result
+ {
+ self.store.state.pin_host_values(values);
}
+ result
}
/// Call a typed function from within the current host-function invocation.
@@ -441,12 +467,19 @@ impl<'store> FuncExecution<'store> {
match result? {
crate::interpreter::ExecState::Completed => {
- let result_ty = self.store.state.get_func(root_func_addr).type_addr;
+ let func = self.store.state.get_func(root_func_addr);
+ let result_ty = func.type_addr;
+ let results_may_gc = func.gc.results;
self.state = FuncExecutionState::Completed { result: None };
- Ok(ExecProgress::Completed(collect_call_results(
+ let values = collect_call_results(
&mut self.store.value_stack,
- self.store.state.get_type(result_ty),
- )?))
+ &self.store.state,
+ self.store.state.get_canonical_func_type(result_ty),
+ )?;
+ if results_may_gc {
+ self.store.state.pin_host_values(&values);
+ }
+ Ok(ExecProgress::Completed(values))
}
crate::interpreter::ExecState::Suspended(callframe) => {
let FuncExecutionState::Running { exec_state, .. } = &mut self.state else {
@@ -517,7 +550,7 @@ pub(crate) fn validate_host_results(
type_addr: TypeAddr,
result: Vec<WasmValue>,
) -> Result<Vec<WasmValue>> {
- let expected = store.state.get_type(type_addr);
+ let expected = store.state.get_canonical_func_type(type_addr);
if result.len() == expected.results().len()
&& result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty))
{
@@ -527,9 +560,18 @@ pub(crate) fn validate_host_results(
Err(Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result })
}
-fn collect_call_results(value_stack: &mut ValueStack, func_ty: &FuncType) -> Result<Vec<WasmValue>> {
+fn collect_call_results(
+ value_stack: &mut ValueStack,
+ state: &crate::store::State,
+ func_ty: &FuncType,
+) -> Result<Vec<WasmValue>> {
debug_assert!(value_stack.len() >= func_ty.results().len()); // m values are on the top of the stack (Ensured by validation)
- let mut res: Vec<_> = value_stack.pop_types(func_ty.results().iter().rev()).collect(); // pop in reverse order since the stack is LIFO
+ let mut res: Vec<_> = func_ty
+ .results()
+ .iter()
+ .rev()
+ .map(|&ty| state.attach_value(value_stack.pop_tinyvalue(ty), ty).expect("validated function result"))
+ .collect();
res.reverse(); // reverse to get the original order
Ok(res)
}
diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs
index 887d107..3a7c06d 100644
--- a/crates/tinywasm/src/imports.rs
+++ b/crates/tinywasm/src/imports.rs
@@ -157,35 +157,9 @@ impl Imports {
Ok(())
}
- fn ref_subtype(actual: RefType, expected: RefType) -> bool {
- if actual.is_nullable() && !expected.is_nullable() {
- return false;
- }
- match (actual.type_index(), expected.type_index()) {
- (Some(actual), Some(expected)) => actual == expected,
- (Some(_), None) => matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func)),
- (None, Some(_)) => matches!(actual.abstract_heap_type(), Some(AbstractHeapType::NoFunc)),
- (None, None) => {
- actual.abstract_heap_type() == expected.abstract_heap_type()
- || actual.is_func() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func))
- || actual.is_extern() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Extern))
- || actual.is_exn() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Exn))
- }
- }
- }
-
- fn value_subtype(actual: WasmType, expected: WasmType) -> bool {
- match (actual, expected) {
- (WasmType::Ref(actual), WasmType::Ref(expected)) => Self::ref_subtype(actual, expected),
- _ => actual == expected,
- }
- }
-
fn compare_table_types(import: &Import, actual: &TableType, expected: &TableType) -> Result<()> {
Self::compare_types(import, &actual.arch(), &expected.arch())?;
- if !Self::ref_subtype(actual.element_type, expected.element_type)
- || !Self::ref_subtype(expected.element_type, actual.element_type)
- {
+ if actual.element_type != expected.element_type {
return Err(LinkingError::incompatible_import_type(import).into());
}
if actual.size_initial < expected.size_initial {
@@ -275,8 +249,8 @@ impl Imports {
let global = store.state.get_global(global_addr);
let expected = ty.with_ty(crate::store::canonicalize_value_type(ty.ty, type_addrs));
let compatible = global.ty.mutable == ty.mutable
- && Self::value_subtype(global.ty.ty, expected.ty)
- && (!ty.mutable || Self::value_subtype(expected.ty, global.ty.ty));
+ && store.state.value_type_is_subtype(global.ty.ty, expected.ty)
+ && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global.ty.ty));
if !compatible {
cold_path();
return Err(LinkingError::incompatible_import_type(import).into());
@@ -306,7 +280,8 @@ impl Imports {
if let Some(func) = &func_handle {
func.item.validate_store(store)?;
}
- if store.state.get_func(func_addr).type_addr != *expected_type_addr {
+ if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr)
+ {
cold_path();
return Err(LinkingError::incompatible_import_type(import).into());
}
diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs
index ecfbacb..be38419 100644
--- a/crates/tinywasm/src/instance.rs
+++ b/crates/tinywasm/src/instance.rs
@@ -151,7 +151,7 @@ impl ModuleInstance {
///
/// See <https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation>
pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<Imports>) -> Result<Self> {
- let type_addrs = store.register_module_types(&module.func_types);
+ let type_addrs = store.register_module_types(&module.types);
let id = store.next_module_instance_id();
let mut addrs = imports.unwrap_or_default().link(store, module, &type_addrs)?;
let local_type_addrs = module.func_type_idxs[addrs.funcs.len()..]
@@ -175,9 +175,9 @@ 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)?;
+ 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)?;
+ store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?;
let instance = ModuleInstanceInner {
store_id: store.id(),
diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs
index 5e78dae..fb8fdec 100644
--- a/crates/tinywasm/src/interpreter/executor.rs
+++ b/crates/tinywasm/src/interpreter/executor.rs
@@ -237,6 +237,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
JumpIfNonZero64(ip) => if self.exec_jump_non_zero_64(*ip) { return Ok(None) },
JumpIfRefNull(ip) => if self.exec_jump_ref_null(*ip) { return Ok(None) },
JumpIfRefNonNull(ip) => if self.exec_jump_ref_non_null(*ip) { return Ok(None) },
+ BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); },
JumpIfLocalZero32 { target_ip, local } => if self.exec_jump_local_zero_32(*target_ip, *local) { return Ok(None) },
JumpIfLocalNonZero32 { target_ip, local } => if self.exec_jump_local_non_zero_32(*target_ip, *local) { return Ok(None) },
JumpIfLocalZero64 { target_ip, local } => if self.exec_jump_local_zero_64(*target_ip, *local) { return Ok(None) },
@@ -444,10 +445,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
I64Popcnt => stack_op!(unary i64, |v| i64::from(v.count_ones())),
// Reference types
- RefFunc(func_idx) => self.exec_const(ValueRef::from_addr(Some(self.module.resolve_func_addr(*func_idx))))?,
+ RefFunc(func_idx) => self.exec_const(ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?,
RefNull(_) => self.exec_const(ValueRef::NULL)?,
RefIsNull => self.exec_ref_is_null()?,
RefAsNonNull => self.exec_ref_as_non_null()?,
+ RefI31 => stack_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)),
+ I31GetS => self.exec_i31_get(true)?,
+ I31GetU => self.exec_i31_get(false)?,
+ RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)),
+ RefTest(ty) => {
+ let value = ValueRef::stack_pop(&mut self.store.value_stack);
+ let ty = self.canonical_ref_type(*ty);
+ self.store.value_stack.push(i32::from(self.store.state.value_ref_matches(value, ty)))?;
+ }
+ RefCast(ty) => {
+ if !self.exec_ref_matches(*ty) {
+ cold_path();
+ return Err(Trap::CastFailure);
+ }
+ }
+ // GC objects
+ StructNew(ty) => self.exec_struct_new(*ty, false)?,
+ StructNewDefault(ty) => self.exec_struct_new(*ty, true)?,
+ StructGet(ty, field) => self.exec_struct_get(*ty, *field, None)?,
+ StructGetS(ty, field) => self.exec_struct_get(*ty, *field, Some(true))?,
+ StructGetU(ty, field) => self.exec_struct_get(*ty, *field, Some(false))?,
+ StructSet(ty, field) => self.exec_struct_set(*ty, *field)?,
+ ArrayNew(ty) => self.exec_array_new(*ty, false)?,
+ ArrayNewDefault(ty) => self.exec_array_new(*ty, true)?,
+ ArrayNewFixed(ty, len) => self.exec_array_new_fixed(*ty, *len)?,
+ ArrayNewData(ty, data) => self.exec_array_new_data(*ty, *data)?,
+ ArrayNewElem(ty, elem) => self.exec_array_new_elem(*ty, *elem)?,
+ ArrayGet(ty) => self.exec_array_get(*ty, None)?,
+ ArrayGetS(ty) => self.exec_array_get(*ty, Some(true))?,
+ ArrayGetU(ty) => self.exec_array_get(*ty, Some(false))?,
+ ArraySet(ty) => self.exec_array_set(*ty)?,
+ ArrayLen => self.exec_array_len()?,
+ ArrayFill(ty) => self.exec_array_fill(*ty)?,
+ ArrayCopy(dst, src) => self.exec_array_copy(*dst, *src)?,
+ ArrayInitData(ty, data) => self.exec_array_init_data(*ty, *data)?,
+ ArrayInitElem(ty, elem) => self.exec_array_init_elem(*ty, *elem)?,
MemorySize(addr) => self.exec_memory_size(*addr)?,
MemoryGrow(addr) => self.exec_memory_grow(*addr)?,
@@ -987,10 +1024,19 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
&mut self,
host_func: Rc<HostFunction>,
type_addr: TypeAddr,
+ params_may_gc: bool,
) -> Result<bool, Trap> {
- let ty = self.store.state.get_type(type_addr);
- let mut params = self.store.value_stack.pop_types(ty.params().iter().rev()).collect::<Vec<_>>();
+ let param_types = self.store.state.get_canonical_func_type(type_addr).params();
+ let mut params = Vec::new();
+ params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?;
+ for &ty in param_types.iter().rev() {
+ let value = self.store.value_stack.pop_tinyvalue(ty);
+ params.push(self.store.state.attach_value(value, ty).expect("validated host argument"));
+ }
params.reverse();
+ if params_may_gc {
+ self.store.state.pin_host_values(&params);
+ }
let result = host_func.call(FuncContext { store: self.store, module_id: self.module.id() }, &params);
let res = match result.and_then(|result| crate::func::validate_host_results(self.store, type_addr, result)) {
Ok(res) => res,
@@ -1016,7 +1062,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
match func.kind {
crate::store::FunctionKind::Wasm(wasm_func) => self.exec_call(wasm_func, addr),
crate::store::FunctionKind::Host(host_func) => {
- self.exec_call_host::<false>(host_func, func.type_addr)?;
+ self.exec_call_host::<false>(host_func, func.type_addr, func.gc.params)?;
Ok(())
}
}
@@ -1031,7 +1077,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.exec_return_call(wasm_func, addr)?;
Ok(false)
}
- crate::store::FunctionKind::Host(host_func) => self.exec_call_host::<true>(host_func, func.type_addr),
+ crate::store::FunctionKind::Host(host_func) => {
+ self.exec_call_host::<true>(host_func, func.type_addr, func.gc.params)
+ }
}
}
@@ -1071,7 +1119,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let table_addr = self.module.resolve_table_addr(table_addr);
let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?;
let table = self.store.state.get_table(table_addr);
- debug_assert!(table.kind.element_type.is_func(), "table is not of type funcref");
let Ok(table) = table.get(table_idx) else {
cold_path();
@@ -1092,11 +1139,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
expected_type_addr: TypeAddr,
) -> Result<bool, Trap> {
let func = self.store.state.get_func(func_addr).clone();
- if func.type_addr != expected_type_addr {
+ if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) {
cold_path();
return Err(Trap::IndirectCallTypeMismatch {
- actual: Box::new(self.store.state.get_type(func.type_addr).clone()),
- expected: Box::new(self.store.state.get_type(expected_type_addr).clone()),
+ actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()),
+ expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()),
});
}
match func.kind {
@@ -1105,7 +1152,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
false => self.exec_call(wasm_func, func_addr),
},
crate::store::FunctionKind::Host(host_func) => {
- return self.exec_call_host::<IS_RETURN_CALL>(host_func, func.type_addr);
+ return self.exec_call_host::<IS_RETURN_CALL>(host_func, func.type_addr, func.gc.params);
}
}?;
Ok(false)
@@ -1327,6 +1374,261 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
+ fn canonical_ref_type(&self, ty: RefType) -> RefType {
+ let Some(type_index) = ty.type_index() else { return ty };
+ RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index))
+ .expect("canonical type address fits in a reference")
+ }
+
+ fn exec_ref_matches(&self, ty: RefType) -> bool {
+ let value = ValueRef::stack_peek(&self.store.value_stack);
+ self.store.state.value_ref_matches(value, self.canonical_ref_type(ty))
+ }
+
+ fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> {
+ let value = ValueRef::stack_pop(&mut self.store.value_stack);
+ if value.is_null() {
+ cold_path();
+ return Err(Trap::NullI31Reference);
+ }
+ let value = if signed {
+ value.i31_s().expect("validated i31.get operand")
+ } else {
+ value.i31_u().expect("validated i31.get operand") as i32
+ };
+ self.store.value_stack.push(value)
+ }
+
+ fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let fields = &self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields;
+ let mut values = Vec::new();
+ values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?;
+ if default {
+ values.extend(fields.iter().map(|field| default_value(field.storage)));
+ } else {
+ for field in fields.iter().rev() {
+ values.push(pop_value(&mut self.store.value_stack, field.storage));
+ }
+ values.reverse();
+ }
+ let value = self.store.state.alloc_gc_object(
+ type_addr,
+ values,
+ (&self.store.value_stack.stack_32).into_iter().copied(),
+ )?;
+ self.store.value_stack.push(value)
+ }
+
+ fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option<bool>) -> Result<(), Trap> {
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields
+ [field_index as usize]
+ .storage;
+ let object = self.store.state.gc_object(reference, type_addr)?;
+ let value = *object.values.get(field_index as usize).expect("validated struct field index");
+ push_value(&mut self.store.value_stack, value, storage, signed)
+ }
+
+ fn exec_struct_set(&mut self, type_index: TypeAddr, field_index: u32) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields
+ [field_index as usize]
+ .storage;
+ let value = pop_value(&mut self.store.value_stack, storage);
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ self.store.state.gc_object(reference, type_addr)?;
+ self.store.state.gc.set(reference, field_index as usize, value).expect("live struct field");
+ Ok(())
+ }
+
+ fn exec_array_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage;
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) };
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ values.resize(len, value);
+ let reference = self.store.state.alloc_gc_object(
+ type_addr,
+ values,
+ (&self.store.value_stack.stack_32).into_iter().copied(),
+ )?;
+ self.store.value_stack.push(reference)
+ }
+
+ fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage =
+ self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage;
+ let len = len as usize;
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ for _ in 0..len {
+ values.push(pop_value(&mut self.store.value_stack, storage));
+ }
+ values.reverse();
+ let reference = self.store.state.alloc_gc_object(
+ type_addr,
+ values,
+ (&self.store.value_stack.stack_32).into_iter().copied(),
+ )?;
+ self.store.value_stack.push(reference)
+ }
+
+ fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option<bool>) -> Result<(), Trap> {
+ let index = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage;
+ let object = self.store.state.gc_object(reference, type_addr)?;
+ let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?;
+ push_value(&mut self.store.value_stack, value, storage, signed)
+ }
+
+ fn exec_array_set(&mut self, type_index: TypeAddr) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.set type").field.storage;
+ let value = pop_value(&mut self.store.value_stack, storage);
+ let index = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let object = self.store.state.gc_object(reference, type_addr)?;
+ if index >= object.values.len() {
+ return Err(Trap::ArrayOutOfBounds);
+ }
+ self.store.state.gc.set(reference, index, value).expect("live array element");
+ Ok(())
+ }
+
+ fn exec_array_len(&mut self) -> Result<(), Trap> {
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ if reference.is_null() {
+ return Err(Trap::NullArrayReference);
+ }
+ let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?;
+ if self.store.state.get_type(object.type_addr).as_array().is_none() {
+ return Err(Trap::Other("GC reference is not an array"));
+ }
+ self.store.value_stack.push(object.values.len() as i32)
+ }
+
+ fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.fill type").field.storage;
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let value = pop_value(&mut self.store.value_stack, storage);
+ let index = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let object = self.store.state.gc_object(reference, type_addr)?;
+ let end = index.checked_add(len).filter(|end| *end <= object.values.len()).ok_or(Trap::ArrayOutOfBounds)?;
+ self.store.state.gc.fill(reference, index..end, value).expect("live array range");
+ Ok(())
+ }
+
+ fn exec_array_copy(&mut self, dst_type: TypeAddr, src_type: TypeAddr) -> Result<(), Trap> {
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src_index = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src = ValueRef::stack_pop(&mut self.store.value_stack);
+ let dst_index = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let dst = ValueRef::stack_pop(&mut self.store.value_stack);
+ let dst_type = self.module.resolve_type_addr(dst_type);
+ let src_type = self.module.resolve_type_addr(src_type);
+ let dst_len = self.store.state.gc_object(dst, dst_type)?.values.len();
+ let src_object = self.store.state.gc_object(src, src_type)?;
+ let src_end =
+ src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?;
+ dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?;
+ if src == dst {
+ self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range");
+ return Ok(());
+ }
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ values.extend_from_slice(&src_object.values[src_index..src_end]);
+ self.store.state.gc.set_slice(dst, dst_index, &values).expect("live array range");
+ Ok(())
+ }
+
+ fn exec_array_new_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> {
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage;
+ let data_addr = self.module.resolve_data_addr(data_index);
+ let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]);
+ let values = decode_data(storage, data, src, len)?;
+ let reference = self.store.state.alloc_gc_object(
+ type_addr,
+ values,
+ (&self.store.value_stack.stack_32).into_iter().copied(),
+ )?;
+ self.store.value_stack.push(reference)
+ }
+
+ fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> {
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let elem_addr = self.module.resolve_elem_addr(elem_index);
+ let items = self.store.state.elements[elem_addr as usize].items.as_deref().unwrap_or(&[]);
+ let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds {
+ offset: src,
+ len,
+ max: items.len(),
+ })?;
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef));
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let reference = self.store.state.alloc_gc_object(
+ type_addr,
+ values,
+ (&self.store.value_stack.stack_32).into_iter().copied(),
+ )?;
+ self.store.value_stack.push(reference)
+ }
+
+ fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> {
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let dst = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage;
+ let object_len = self.store.state.gc_object(reference, type_addr)?.values.len();
+ dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?;
+ let data =
+ self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]);
+ let values = decode_data(storage, data, src, len)?;
+ self.store.state.gc.set_slice(reference, dst, &values).expect("live array range");
+ Ok(())
+ }
+
+ fn exec_array_init_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> {
+ let len = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let src = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let dst = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let reference = ValueRef::stack_pop(&mut self.store.value_stack);
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let object_len = self.store.state.gc_object(reference, type_addr)?.values.len();
+ dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?;
+ let items = self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize]
+ .items
+ .as_deref()
+ .unwrap_or(&[]);
+ let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds {
+ offset: src,
+ len,
+ max: items.len(),
+ })?;
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef));
+ self.store.state.gc.set_slice(reference, dst, &values).expect("live array range");
+ Ok(())
+ }
+
fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> {
let mem = self.store.state.get_mem(self.module.resolve_mem_addr(addr));
match mem.is_64bit() {
@@ -1531,8 +1833,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> {
let table_addr = self.module.resolve_table_addr(table_index);
let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?;
- let v = self.store.state.get_table(table_addr).get_wasm_val(idx)?;
- self.store.value_stack.push_dyn(v.into())
+ let value = *self.store.state.get_table(table_addr).get(idx)?;
+ self.store.value_stack.push(value)
}
fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> {
@@ -1540,7 +1842,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let table_addr = self.module.resolve_table_addr(table_index);
let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?;
let table = self.store.state.get_table_mut(table_addr);
- table.set(idx, val.addr().into())
+ table.set(idx, val)
}
fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> {
@@ -1580,7 +1882,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
let table = self.store.state.get_table_mut(table_addr);
let sz = table.size();
- let result = table.grow(n, val.addr().into());
+ let result = table.grow(n, val);
match (arch, result) {
(MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32),
(MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32),
@@ -1595,7 +1897,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let n = self.pop_table_operand(arch)?;
let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
let i = self.pop_table_operand(arch)?;
- self.store.state.get_table_mut(table_addr).fill(i, n, val.addr().into())
+ self.store.state.get_table_mut(table_addr).fill(i, n, val)
}
fn pop_table_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> {
diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs
index 853c5e4..378dc7f 100644
--- a/crates/tinywasm/src/interpreter/stack/value_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs
@@ -165,6 +165,15 @@ impl<T: Copy + Default> Stack<T> {
self.data.truncate(len - count);
}
}
+
+impl<'a, T: Copy + Default> IntoIterator for &'a Stack<T> {
+ type Item = &'a T;
+ type IntoIter = core::slice::Iter<'a, T>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.data.iter()
+ }
+}
impl ValueStack {
pub(crate) fn new(config: &Config) -> Self {
Self {
@@ -207,13 +216,6 @@ impl ValueStack {
self.stack_128.select_many(counts.c128 as usize, condition);
}
- pub(crate) fn pop_types<'a>(
- &'a mut self,
- val_types: impl IntoIterator<Item = &'a WasmType>,
- ) -> impl core::iter::Iterator<Item = WasmValue> {
- val_types.into_iter().map(|val_type| self.pop_wasmvalue(*val_type))
- }
-
#[inline(always)]
pub(crate) fn enter_locals(&mut self, params: &ValueCounts, locals: &ValueCounts) -> Result<StackBase, Trap> {
let locals_base32 = self.stack_32.enter_locals(params.c32 as usize, locals.c32 as usize)?;
@@ -246,14 +248,12 @@ impl ValueStack {
Ok(())
}
- pub(crate) fn pop_wasmvalue(&mut self, val_type: WasmType) -> WasmValue {
+ pub(crate) fn pop_tinyvalue(&mut self, val_type: WasmType) -> TinyWasmValue {
match val_type {
- WasmType::I32 => WasmValue::I32(i32::stack_pop(self)),
- WasmType::I64 => WasmValue::I64(i64::stack_pop(self)),
- WasmType::F32 => WasmValue::F32(f32::stack_pop(self)),
- WasmType::F64 => WasmValue::F64(f64::stack_pop(self)),
- WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(self)).attach_type(val_type).unwrap(),
- WasmType::V128 => WasmValue::V128(Value128::stack_pop(self).0),
+ WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(Value32::stack_pop(self)),
+ WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(Value64::stack_pop(self)),
+ WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(self)),
+ WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(self)),
}
}
diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs
index be2e0a1..f034906 100644
--- a/crates/tinywasm/src/interpreter/values.rs
+++ b/crates/tinywasm/src/interpreter/values.rs
@@ -8,8 +8,6 @@ pub(crate) type Value64 = u64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ValueRef(u32);
-// TODO(wasm3): GC references need a tagged representation; this raw address is only sufficient for current refs.
-
impl Default for ValueRef {
fn default() -> Self {
Self::NULL
@@ -17,7 +15,8 @@ impl Default for ValueRef {
}
impl ValueRef {
- pub(crate) const NULL: Self = Self(u32::MAX);
+ const HOST_ANY_TAG: u32 = 1 << 30;
+ pub(crate) const NULL: Self = Self(0);
#[inline]
pub(crate) const fn from_raw(raw: u32) -> Self {
@@ -25,16 +24,24 @@ impl ValueRef {
}
#[inline]
- pub(crate) const fn from_addr(addr: Option<u32>) -> Self {
- match addr {
- Some(addr) => Self(addr),
- None => Self::NULL,
- }
+ pub(crate) const fn from_category_addr(addr: u32) -> Self {
+ let Some(raw) = addr.checked_add(1) else { panic!("reference address does not fit in the runtime encoding") };
+ let Some(raw) = raw.checked_mul(2) else { panic!("reference address does not fit in the runtime encoding") };
+ Self(raw)
+ }
+
+ #[inline]
+ pub(crate) const fn from_i31(value: i32) -> Self {
+ Self(((value as u32) << 1) | 1)
+ }
+
+ pub(crate) const fn is_host_any(self) -> bool {
+ matches!(self.addr(), Some(addr) if addr & Self::HOST_ANY_TAG != 0)
}
#[inline]
pub(crate) const fn addr(self) -> Option<u32> {
- if self.is_null() { None } else { Some(self.0) }
+ if self.is_null() || self.is_i31() { None } else { Some(self.0 / 2 - 1) }
}
#[inline]
@@ -43,6 +50,21 @@ impl ValueRef {
}
#[inline]
+ pub(crate) const fn is_i31(self) -> bool {
+ self.0 & 1 != 0
+ }
+
+ #[inline]
+ pub(crate) const fn i31_s(self) -> Option<i32> {
+ if self.is_i31() { Some((self.0 as i32) >> 1) } else { None }
+ }
+
+ #[inline]
+ pub(crate) const fn i31_u(self) -> Option<u32> {
+ if self.is_i31() { Some(self.0 >> 1) } else { None }
+ }
+
+ #[inline]
pub(crate) const fn raw(self) -> u32 {
self.0
}
@@ -96,7 +118,7 @@ impl TinyWasmValue {
}
}
- /// Attaches a type to the value (panics if the size of the value is not the same as the type)
+ /// Converts this internal value to the requested public WebAssembly type.
pub fn attach_type(self, ty: WasmType) -> Option<WasmValue> {
match (self, ty) {
(Self::Value32(v), WasmType::I32) => Some(WasmValue::I32(v as i32)),
@@ -105,13 +127,13 @@ impl TinyWasmValue {
(Self::Value64(v), WasmType::F64) => Some(WasmValue::F64(f64::from_bits(v))),
(Self::ValueRef(v), WasmType::Ref(_)) if v.is_null() => Some(RefValue::Null.into()),
(Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_func() => {
- Some(WasmValue::Ref(RefValue::Func(FuncRef::new(v.raw()))))
+ Some(WasmValue::Ref(RefValue::Func(FuncRef::new(v.addr()?))))
}
(Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_extern() => {
- Some(WasmValue::Ref(RefValue::Extern(ExternRef::new(v.raw()))))
+ Some(WasmValue::Ref(RefValue::Extern(ExternRef::from_raw(v.raw()))))
}
(Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_exn() => {
- Some(WasmValue::Ref(RefValue::Exn(ExnRef::new(v.raw()))))
+ Some(WasmValue::Ref(RefValue::Exn(ExnRef::new(v.addr()?))))
}
(Self::ValueRef(v), WasmType::Ref(_)) => Some(WasmValue::Ref(RefValue::Any(AnyRef::from_raw(v.raw())))),
(Self::Value128(v), WasmType::V128) => Some(WasmValue::V128(v.0)),
@@ -130,7 +152,11 @@ impl From<&WasmValue> for TinyWasmValue {
WasmValue::I64(v) => Self::Value64(*v as u64),
WasmValue::F32(v) => Self::Value32(v.to_bits()),
WasmValue::F64(v) => Self::Value64(v.to_bits()),
- WasmValue::Ref(value) => Self::ValueRef(ValueRef::from_addr(value.raw())),
+ WasmValue::Ref(RefValue::Null) => Self::ValueRef(ValueRef::NULL),
+ WasmValue::Ref(RefValue::Func(value)) => Self::ValueRef(ValueRef::from_category_addr(value.addr())),
+ WasmValue::Ref(RefValue::Extern(value)) => Self::ValueRef(ValueRef::from_raw(value.raw())),
+ WasmValue::Ref(RefValue::Exn(value)) => Self::ValueRef(ValueRef::from_category_addr(value.addr())),
+ WasmValue::Ref(RefValue::Any(value)) => Self::ValueRef(ValueRef::from_raw(value.raw())),
WasmValue::V128(v) => Self::Value128((*v).into()),
}
}
diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs
index dc54736..d8f9669 100644
--- a/crates/tinywasm/src/reference.rs
+++ b/crates/tinywasm/src/reference.rs
@@ -5,7 +5,8 @@ use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
-use crate::store::{GlobalInstance, TableElement, TableInstance};
+use crate::interpreter::TinyWasmValue;
+use crate::store::{GlobalInstance, TableInstance};
use crate::{Error, MemoryInstance, Result, Store, Trap};
use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue};
@@ -346,12 +347,13 @@ fn table_value_to_element(
state: &crate::store::State,
element_type: tinywasm_types::RefType,
value: WasmValue,
-) -> Result<TableElement, Trap> {
+) -> Result<crate::interpreter::ValueRef, Trap> {
if !state.value_matches_type(value, WasmType::Ref(element_type)) {
return Err(Trap::Other("invalid table value type"));
}
let WasmValue::Ref(value) = value else { unreachable!() };
- Ok(TableElement::from(value.raw()))
+ let TinyWasmValue::ValueRef(value) = TinyWasmValue::from(WasmValue::Ref(value)) else { unreachable!() };
+ Ok(value)
}
impl Table {
@@ -390,20 +392,37 @@ impl Table {
/// Get a table element as a wasm reference value.
pub fn get(&self, store: &Store, index: TableAddr) -> Result<WasmValue> {
- Ok(self.instance(store)?.get_wasm_val(index as usize)?)
+ let table = self.instance(store)?;
+ let value = store
+ .state
+ .attach_value(TinyWasmValue::ValueRef(*table.get(index as usize)?), WasmType::Ref(table.kind.element_type))
+ .expect("table value matches its element type");
+ if let WasmValue::Ref(value) = value {
+ store.state.pin_host_ref(value);
+ }
+ Ok(value)
}
/// Load a range of table elements and iterate over wasm reference values.
- pub fn load(&self, store: &Store, offset: usize, len: usize) -> Result<alloc::vec::IntoIter<WasmValue>> {
+ pub fn load<'a>(
+ &self,
+ store: &'a Store,
+ offset: usize,
+ len: usize,
+ ) -> Result<impl Iterator<Item = WasmValue> + 'a> {
let table = self.instance(store)?;
let element_type = table.kind.element_type;
let elements = table.load(offset, len)?;
- Ok(elements
- .iter()
- .copied()
- .map(move |element| element.to_wasm_value(element_type))
- .collect::<alloc::vec::Vec<_>>()
- .into_iter())
+ let may_contain_gc = store.state.type_may_contain_gc(WasmType::Ref(element_type));
+ Ok(elements.iter().copied().map(move |value| {
+ if may_contain_gc {
+ store.state.gc.pin(value);
+ }
+ store
+ .state
+ .attach_value(TinyWasmValue::ValueRef(value), WasmType::Ref(element_type))
+ .expect("table value matches its element type")
+ }))
}
/// Set a table element.
@@ -460,8 +479,13 @@ impl Global {
/// Get the current value of the global.
pub fn get(&self, store: &Store) -> Result<WasmValue> {
let global = self.instance(store)?;
- let value = global.value.attach_type(global.ty.ty);
- Ok(value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")))
+ let value = store.state.attach_value(global.value, global.ty.ty);
+ let value =
+ value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug"));
+ if let WasmValue::Ref(value) = value {
+ store.state.pin_host_ref(value);
+ }
+ Ok(value)
}
/// Set the current value of the global.
diff --git a/crates/tinywasm/src/store/element.rs b/crates/tinywasm/src/store/element.rs
index f3a8602..4437bd4 100644
--- a/crates/tinywasm/src/store/element.rs
+++ b/crates/tinywasm/src/store/element.rs
@@ -1,12 +1,14 @@
-use crate::TableElement;
+use crate::interpreter::ValueRef;
use alloc::vec::Vec;
+use tinywasm_types::RefType;
/// A WebAssembly Element Instance
///
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#element-instances>
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct ElementInstance {
- pub(crate) items: Option<Vec<TableElement>>, // none is the element was dropped
+ pub(crate) items: Option<Vec<ValueRef>>, // none is the element was dropped
+ pub(crate) ty: RefType,
}
impl ElementInstance {
diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs
index f0e3ed9..367fadb 100644
--- a/crates/tinywasm/src/store/function.rs
+++ b/crates/tinywasm/src/store/function.rs
@@ -10,9 +10,17 @@ use crate::func::HostFunction;
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct FunctionInstance {
pub(crate) type_addr: TypeAddr,
+ pub(crate) gc: FunctionGcMetadata,
pub(crate) kind: FunctionKind,
}
+#[derive(Clone, Copy)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub(crate) struct FunctionGcMetadata {
+ pub(crate) params: bool,
+ pub(crate) results: bool,
+}
+
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) enum FunctionKind {
diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs
new file mode 100644
index 0000000..b8f5961
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/arena.rs
@@ -0,0 +1,263 @@
+//! Mark-and-sweep storage with stable handles for WebAssembly GC objects.
+
+use alloc::vec::Vec;
+use core::cell::Cell;
+use core::mem::size_of;
+use core::num::NonZeroU32;
+
+/// A stable reference to an arena slot.
+///
+/// Reclaimed slots increment their generation so stale handles cannot access a
+/// new object allocated in the same slot.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub(crate) struct Handle {
+ index: u32,
+ generation: NonZeroU32,
+}
+
+/// Adds the handles referenced by an arena object to the mark worklist.
+pub(crate) trait Trace {
+ /// Calls `mark` for every arena object referenced by this object.
+ fn trace(&self, mark: &mut impl FnMut(Handle));
+}
+
+/// An arena allocation or capacity error.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct AllocError;
+
+impl core::fmt::Display for AllocError {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str("GC arena capacity exhausted")
+ }
+}
+
+impl core::error::Error for AllocError {}
+
+#[inline]
+fn mark<T>(slots: &[Slot<T>], worklist: &mut Vec<u32>, handle: Handle) {
+ let Some(slot) = slots.get(handle.index as usize) else {
+ return;
+ };
+ if slot.generation != handle.generation || !matches!(slot.state, SlotState::Occupied { .. }) || slot.marked.get() {
+ return;
+ }
+ slot.marked.set(true);
+ worklist.push(handle.index);
+}
+
+struct Slot<T> {
+ generation: NonZeroU32,
+ marked: Cell<bool>,
+ state: SlotState<T>,
+}
+
+enum SlotState<T> {
+ Occupied { value: T, bytes: usize },
+ Free { next: Option<u32> },
+ Retired,
+}
+
+/// A mark-and-sweep arena with stable generational handles.
+pub(crate) struct Arena<T> {
+ slots: Vec<Slot<T>>,
+ free_head: Option<u32>,
+ worklist: Vec<u32>,
+ len: usize,
+ allocated_bytes: usize,
+ collection_threshold: usize,
+ next_collection: usize,
+}
+
+impl<T> Arena<T> {
+ /// Creates an empty arena with the given initial collection threshold.
+ pub(crate) const fn new(collection_threshold: usize) -> Self {
+ Self {
+ slots: Vec::new(),
+ free_head: None,
+ worklist: Vec::new(),
+ len: 0,
+ allocated_bytes: 0,
+ collection_threshold,
+ next_collection: collection_threshold,
+ }
+ }
+
+ /// Allocates a value with `out_of_line_bytes` of storage owned outside its slot.
+ ///
+ /// The byte count must remain valid while the value is in the arena.
+ pub(crate) fn alloc(&mut self, value: T, out_of_line_bytes: usize) -> Result<Handle, AllocError> {
+ let bytes = size_of::<Slot<T>>().checked_add(out_of_line_bytes).ok_or(AllocError)?;
+ let allocated_bytes = self.allocated_bytes.checked_add(bytes).ok_or(AllocError)?;
+
+ let handle = if let Some(index) = self.free_head {
+ let slot = &mut self.slots[index as usize];
+ let SlotState::Free { next } = slot.state else { unreachable!("free list points to an occupied slot") };
+ self.free_head = next;
+ slot.marked.set(false);
+ slot.state = SlotState::Occupied { value, bytes };
+ Handle { index, generation: slot.generation }
+ } else {
+ if self.slots.len() >= u32::MAX as usize {
+ return Err(AllocError);
+ }
+ let index = self.slots.len() as u32;
+ self.slots.try_reserve(1).map_err(|_| AllocError)?;
+ self.slots.push(Slot {
+ generation: NonZeroU32::MIN,
+ marked: Cell::new(false),
+ state: SlotState::Occupied { value, bytes },
+ });
+ Handle { index, generation: NonZeroU32::MIN }
+ };
+
+ self.len += 1;
+ self.allocated_bytes = allocated_bytes;
+ Ok(handle)
+ }
+
+ /// Returns a shared reference if the handle is live and current.
+ pub(crate) fn get(&self, handle: Handle) -> Option<&T> {
+ let slot = self.slots.get(handle.index as usize)?;
+ if slot.generation != handle.generation {
+ return None;
+ }
+ match &slot.state {
+ SlotState::Occupied { value, .. } => Some(value),
+ SlotState::Free { .. } | SlotState::Retired => None,
+ }
+ }
+
+ /// Returns an exclusive reference if the handle is live and current.
+ pub(crate) fn get_mut(&mut self, handle: Handle) -> Option<&mut T> {
+ let slot = self.slots.get_mut(handle.index as usize)?;
+ if slot.generation != handle.generation {
+ return None;
+ }
+ match &mut slot.state {
+ SlotState::Occupied { value, .. } => Some(value),
+ SlotState::Free { .. } | SlotState::Retired => None,
+ }
+ }
+
+ /// Returns whether an allocation of this size should trigger collection.
+ pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool {
+ size_of::<Slot<T>>()
+ .checked_add(out_of_line_bytes)
+ .and_then(|bytes| self.allocated_bytes.checked_add(bytes))
+ .is_none_or(|bytes| bytes >= self.next_collection)
+ }
+}
+
+impl<T: Trace> Arena<T> {
+ /// Collects objects that cannot be reached from `roots`.
+ pub(crate) fn collect(&mut self, roots: impl IntoIterator<Item = Handle>) -> Result<(), AllocError> {
+ self.worklist.clear();
+ self.worklist.try_reserve(self.len).map_err(|_| AllocError)?;
+
+ for root in roots {
+ mark(&self.slots, &mut self.worklist, root);
+ }
+
+ while let Some(index) = self.worklist.pop() {
+ let slots = &self.slots;
+ let worklist = &mut self.worklist;
+ let SlotState::Occupied { value, .. } = &slots[index as usize].state else {
+ unreachable!("marked slots are occupied")
+ };
+ value.trace(&mut |handle| mark(slots, worklist, handle));
+ }
+
+ let mut live_objects = 0;
+ let mut live_bytes = 0;
+ for (index, slot) in self.slots.iter_mut().enumerate() {
+ let SlotState::Occupied { bytes, .. } = &slot.state else {
+ continue;
+ };
+ if slot.marked.replace(false) {
+ live_objects += 1;
+ live_bytes += bytes;
+ continue;
+ }
+
+ if let Some(generation) = slot.generation.checked_add(1) {
+ slot.generation = generation;
+ slot.state = SlotState::Free { next: self.free_head };
+ self.free_head = Some(index as u32);
+ } else {
+ slot.state = SlotState::Retired;
+ }
+ }
+
+ self.len = live_objects;
+ self.allocated_bytes = live_bytes;
+ self.next_collection = live_bytes.saturating_mul(2).max(self.collection_threshold);
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use alloc::vec;
+
+ struct Object(Vec<Handle>);
+
+ impl Trace for Object {
+ fn trace(&self, mark: &mut impl FnMut(Handle)) {
+ for &handle in &self.0 {
+ mark(handle);
+ }
+ }
+ }
+
+ #[test]
+ fn reuses_slots_and_rejects_stale_handles() {
+ let mut arena = Arena::new(1024);
+ let stale = arena.alloc(Object(vec![]), 0).unwrap();
+
+ arena.collect([]).unwrap();
+ let current = arena.alloc(Object(vec![]), 0).unwrap();
+
+ assert_eq!(stale.index, current.index);
+ assert_ne!(stale.generation, current.generation);
+ assert!(arena.get(stale).is_none());
+ assert!(arena.get(current).is_some());
+ }
+
+ #[test]
+ fn keeps_reachable_cycles() {
+ let mut arena = Arena::new(1024);
+ let first = arena.alloc(Object(Vec::with_capacity(1)), size_of::<Handle>()).unwrap();
+ let second = arena.alloc(Object(vec![first]), size_of::<Handle>()).unwrap();
+ arena.get_mut(first).unwrap().0.push(second);
+
+ arena.collect([first]).unwrap();
+
+ assert_eq!(arena.len, 2);
+ assert_eq!(arena.allocated_bytes, size_of::<Slot<Object>>() * 2 + size_of::<Handle>() * 2);
+ assert_eq!(arena.get(second).unwrap().0, [first]);
+ }
+
+ #[test]
+ fn reclaims_unreachable_cycles() {
+ let mut arena = Arena::new(1024);
+ let first = arena.alloc(Object(Vec::with_capacity(1)), size_of::<Handle>()).unwrap();
+ let second = arena.alloc(Object(vec![first]), size_of::<Handle>()).unwrap();
+ arena.get_mut(first).unwrap().0.push(second);
+
+ arena.collect([]).unwrap();
+
+ assert_eq!(arena.len, 0);
+ assert_eq!(arena.allocated_bytes, 0);
+ }
+
+ #[test]
+ fn accounts_for_object_storage() {
+ let mut arena = Arena::new(1024);
+ let root = arena.alloc(Object(vec![]), 24).unwrap();
+
+ arena.collect([root]).unwrap();
+
+ assert_eq!(arena.allocated_bytes, size_of::<Slot<Object>>() + 24);
+ }
+}
diff --git a/crates/tinywasm/src/store/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs
new file mode 100644
index 0000000..2a87a5f
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/mod.rs
@@ -0,0 +1,92 @@
+mod arena;
+mod object;
+
+use alloc::vec::Vec;
+use tinywasm_types::{StorageType, WasmType};
+
+use crate::Trap;
+use crate::interpreter::stack::ValueStack;
+use crate::interpreter::{InternalValue, TinyWasmValue, Value128, ValueRef};
+
+pub(crate) use arena::{AllocError, Arena, Handle, Trace};
+pub(crate) use object::{GcHeap, GcObject};
+
+/// Returns the zero value for a GC field or array element.
+pub(crate) fn default_value(storage: StorageType) -> TinyWasmValue {
+ match storage {
+ StorageType::I8 | StorageType::I16 | StorageType::Value(WasmType::I32 | WasmType::F32) => {
+ TinyWasmValue::Value32(0)
+ }
+ StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(0),
+ StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::from([0; 16])),
+ StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::NULL),
+ }
+}
+
+/// Pops and packs a GC field or array element from the operand stack.
+pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> TinyWasmValue {
+ match storage {
+ StorageType::I8 => TinyWasmValue::Value32(i32::stack_pop(stack) as u8 as u32),
+ StorageType::I16 => TinyWasmValue::Value32(i32::stack_pop(stack) as u16 as u32),
+ StorageType::Value(WasmType::I32 | WasmType::F32) => TinyWasmValue::Value32(u32::stack_pop(stack)),
+ StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(u64::stack_pop(stack)),
+ StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::stack_pop(stack)),
+ StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::stack_pop(stack)),
+ }
+}
+
+/// Extends a packed value and pushes it onto the operand stack.
+pub(crate) fn push_value(
+ stack: &mut ValueStack,
+ value: TinyWasmValue,
+ storage: StorageType,
+ signed: Option<bool>,
+) -> Result<(), Trap> {
+ let value = match (value, storage, signed) {
+ (TinyWasmValue::Value32(value), StorageType::I8, Some(true)) => {
+ TinyWasmValue::Value32(value as i8 as i32 as u32)
+ }
+ (TinyWasmValue::Value32(value), StorageType::I16, Some(true)) => {
+ TinyWasmValue::Value32(value as i16 as i32 as u32)
+ }
+ (TinyWasmValue::Value32(value), StorageType::I8, Some(false)) => TinyWasmValue::Value32(value & u8::MAX as u32),
+ (TinyWasmValue::Value32(value), StorageType::I16, Some(false)) => {
+ TinyWasmValue::Value32(value & u16::MAX as u32)
+ }
+ (value, _, None) => value,
+ _ => unreachable!("validated packed field access"),
+ };
+ stack.push_dyn(value)
+}
+
+/// Decodes numeric array elements from a data segment.
+pub(crate) fn decode_data(
+ storage: StorageType,
+ data: &[u8],
+ src: usize,
+ len: usize,
+) -> Result<Vec<TinyWasmValue>, Trap> {
+ let width = match storage {
+ StorageType::I8 => 1,
+ StorageType::I16 => 2,
+ StorageType::Value(WasmType::I32 | WasmType::F32) => 4,
+ StorageType::Value(WasmType::I64 | WasmType::F64) => 8,
+ StorageType::Value(WasmType::V128) => 16,
+ StorageType::Value(WasmType::Ref(_)) => unreachable!("array.new_data reference element"),
+ };
+ let Some(end) = len.checked_mul(width).and_then(|bytes| src.checked_add(bytes)).filter(|&end| end <= data.len())
+ else {
+ return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() });
+ };
+ let mut values = Vec::new();
+ values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(data[src..end].chunks_exact(width).map(|bytes| match width {
+ 1 => TinyWasmValue::Value32(u32::from(bytes[0])),
+ 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))),
+ 4 => TinyWasmValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())),
+ 8 => TinyWasmValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())),
+ 16 => TinyWasmValue::Value128(Value128::from(<[u8; 16]>::try_from(bytes).unwrap())),
+ _ => unreachable!(),
+ }));
+ Ok(values)
+}
diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs
new file mode 100644
index 0000000..a3c5440
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/object.rs
@@ -0,0 +1,218 @@
+use alloc::{boxed::Box, vec::Vec};
+use core::cell::RefCell;
+use core::mem::size_of;
+use core::sync::atomic::{AtomicU32, Ordering};
+
+use tinywasm_types::TypeAddr;
+
+use crate::interpreter::{TinyWasmValue, ValueRef};
+
+use super::{AllocError, Arena, Handle, Trace};
+
+static NEXT_GC_REF: AtomicU32 = AtomicU32::new(0);
+
+pub(crate) struct GcObject {
+ pub(crate) type_addr: TypeAddr,
+ pub(crate) values: Box<[TinyWasmValue]>,
+ references: Option<Box<[Option<Handle>]>>,
+}
+
+impl Trace for GcObject {
+ fn trace(&self, mark: &mut impl FnMut(Handle)) {
+ if let Some(references) = &self.references {
+ references.iter().flatten().copied().for_each(mark);
+ }
+ }
+}
+
+pub(crate) struct GcHeap {
+ objects: Arena<GcObject>,
+ directory: Vec<(u32, Handle)>,
+ pinned: RefCell<Vec<Handle>>,
+}
+
+impl Default for GcHeap {
+ fn default() -> Self {
+ Self::new(1024 * 1024)
+ }
+}
+
+impl GcHeap {
+ /// Creates a heap with the configured allocation threshold.
+ pub(crate) const fn new(collection_threshold: usize) -> Self {
+ Self { objects: Arena::new(collection_threshold), directory: Vec::new(), pinned: RefCell::new(Vec::new()) }
+ }
+
+ #[inline]
+ /// Resolves a compact reference to its generation-checked arena handle.
+ pub(crate) fn handle(&self, value: ValueRef) -> Option<Handle> {
+ let key = value.addr()?;
+ let index = self.directory.binary_search_by_key(&key, |entry| entry.0).ok()?;
+ Some(self.directory[index].1)
+ }
+
+ #[inline]
+ pub(crate) fn get(&self, value: ValueRef) -> Option<&GcObject> {
+ self.objects.get(self.handle(value)?)
+ }
+
+ #[inline]
+ pub(crate) fn get_mut(&mut self, value: ValueRef) -> Option<&mut GcObject> {
+ self.objects.get_mut(self.handle(value)?)
+ }
+
+ /// Allocates an object and returns its compact runtime reference.
+ pub(crate) fn alloc(
+ &mut self,
+ type_addr: TypeAddr,
+ values: Vec<TinyWasmValue>,
+ trace_references: bool,
+ ) -> Result<ValueRef, AllocError> {
+ let key =
+ NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1));
+ let Ok(key) = key else {
+ return Err(AllocError);
+ };
+ let references = if trace_references {
+ let mut references = Vec::new();
+ references.try_reserve_exact(values.len()).map_err(|_| AllocError)?;
+ references.extend(values.iter().map(|value| match value {
+ TinyWasmValue::ValueRef(value) => self.handle(*value),
+ _ => None,
+ }));
+ Some(references.into_boxed_slice())
+ } else {
+ None
+ };
+ let element_size = size_of::<TinyWasmValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
+ let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(AllocError)?;
+ let object = GcObject { type_addr, values: values.into_boxed_slice(), references };
+ self.directory.try_reserve(1).map_err(|_| AllocError)?;
+ let handle = self.objects.alloc(object, out_of_line_bytes)?;
+ self.directory.push((key, handle));
+ Ok(ValueRef::from_category_addr(key))
+ }
+
+ pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> {
+ let reference = value.as_ref().and_then(|value| self.handle(value));
+ let object = self.get_mut(object)?;
+ *object.values.get_mut(index)? = value;
+ if let Some(references) = &mut object.references {
+ references[index] = reference;
+ }
+ Some(())
+ }
+
+ /// Replaces a contiguous range and updates its traced references.
+ pub(crate) fn set_slice(&mut self, object: ValueRef, index: usize, values: &[TinyWasmValue]) -> Option<()> {
+ let object_handle = self.handle(object)?;
+ let end = index.checked_add(values.len())?;
+ let directory = &self.directory;
+ let object = self.objects.get_mut(object_handle)?;
+ object.values.get_mut(index..end)?.copy_from_slice(values);
+ if let Some(references) = &mut object.references {
+ for (reference, value) in references[index..end].iter_mut().zip(values) {
+ *reference = value.as_ref().and_then(|value| {
+ let key = value.addr()?;
+ let index = directory.binary_search_by_key(&key, |entry| entry.0).ok()?;
+ Some(directory[index].1)
+ });
+ }
+ }
+ Some(())
+ }
+
+ /// Fills a contiguous range and updates its traced references.
+ pub(crate) fn fill(
+ &mut self,
+ object: ValueRef,
+ range: core::ops::Range<usize>,
+ value: TinyWasmValue,
+ ) -> Option<()> {
+ let reference = value.as_ref().and_then(|value| self.handle(value));
+ let object = self.get_mut(object)?;
+ object.values.get_mut(range.clone())?.fill(value);
+ if let Some(references) = &mut object.references {
+ references[range].fill(reference);
+ }
+ Some(())
+ }
+
+ pub(crate) fn should_collect(&self, value_count: usize, trace_references: bool) -> bool {
+ let element_size = size_of::<TinyWasmValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
+ let bytes = value_count.saturating_mul(element_size);
+ self.objects.should_collect(bytes)
+ }
+
+ /// Reclaims objects unreachable from runtime and permanent host roots.
+ pub(crate) fn collect(&mut self, roots: impl IntoIterator<Item = ValueRef>) -> Result<(), AllocError> {
+ let pinned = self.pinned.borrow();
+ let directory = &self.directory;
+ let root_handles = roots.into_iter().filter_map(|value| {
+ let key = value.addr()?;
+ Some(directory.get(directory.binary_search_by_key(&key, |entry| entry.0).ok()?)?.1)
+ });
+ self.objects.collect(pinned.iter().copied().chain(root_handles))?;
+ drop(pinned);
+ self.directory.retain(|(_, handle)| self.objects.get(*handle).is_some());
+ Ok(())
+ }
+
+ /// Permanently roots a managed reference exposed through the copyable host API.
+ pub(crate) fn pin(&self, value: ValueRef) {
+ if let Some(handle) = self.handle(value) {
+ let mut pinned = self.pinned.borrow_mut();
+ if let Err(index) = pinned.binary_search(&handle) {
+ pinned.insert(index, handle);
+ }
+ }
+ }
+
+ pub(crate) fn copy_within(&mut self, object: ValueRef, src: core::ops::Range<usize>, dst: usize) -> Option<()> {
+ let object = self.get_mut(object)?;
+ object.values.copy_within(src.clone(), dst);
+ if let Some(references) = &mut object.references {
+ references.copy_within(src, dst);
+ }
+ Some(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn compact_keys_are_not_reused_after_collection() {
+ let mut heap = GcHeap::default();
+ let stale = heap.alloc(0, Vec::new(), false).unwrap();
+ heap.collect([]).unwrap();
+ let current = heap.alloc(0, Vec::new(), false).unwrap();
+
+ assert_ne!(stale, current);
+ assert!(heap.get(stale).is_none());
+ assert!(heap.get(current).is_some());
+ }
+
+ #[test]
+ fn compact_keys_do_not_resolve_in_another_heap() {
+ let mut first = GcHeap::default();
+ let second = GcHeap::default();
+ let value = first.alloc(0, Vec::new(), false).unwrap();
+
+ assert!(second.get(value).is_none());
+ }
+
+ #[test]
+ fn collection_reclaims_object_cycles() {
+ let mut heap = GcHeap::default();
+ let first = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(ValueRef::NULL)], true).unwrap();
+ let second = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(first)], true).unwrap();
+ heap.set(first, 0, TinyWasmValue::ValueRef(second)).unwrap();
+
+ heap.collect([]).unwrap();
+
+ assert!(heap.get(first).is_none());
+ assert!(heap.get(second).is_none());
+ }
+}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index 517a561..84c4033 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -1,4 +1,3 @@
-use alloc::sync::Arc;
use alloc::{boxed::Box, format, vec::Vec};
use core::hint::cold_path;
use core::sync::atomic::{AtomicUsize, Ordering};
@@ -11,36 +10,29 @@ use crate::{Engine, Error, ModuleInstance, Result, Trap};
mod data;
mod element;
mod function;
+mod gc;
mod global;
mod memory;
+mod state;
mod table;
+mod types;
+pub(crate) use gc::{decode_data, default_value, pop_value, push_value};
pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory};
pub(crate) use memory::{MemValue, MemoryInstance};
+pub(crate) use state::State;
+pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type};
pub(crate) use {data::*, element::*, function::*, global::*, table::*};
// global store id counter
static STORE_ID: AtomicUsize = AtomicUsize::new(0);
-pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType {
- let Some(type_addr) = ty.type_index() else { return ty };
- let canonical =
- *type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}"));
- RefType::new_concrete(ty.is_nullable(), canonical).unwrap()
-}
-
-pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType {
- match ty {
- WasmType::Ref(ty) => WasmType::Ref(canonicalize_ref_type(ty, type_addrs)),
- ty => ty,
- }
-}
-
/// Global state that can be manipulated by WebAssembly programs
///
-/// Note that the state doesn't do any garbage collection - so it will grow
-/// indefinitely if you keep adding modules to it. When calling temporary
-/// functions, you should create a new store and then drop it when you're done (e.g. in a request handler).
+/// Managed WebAssembly GC objects are collected automatically. Other Store
+/// instances, such as modules, functions, memories, and tables, live until the
+/// Store is dropped. GC references exposed through the copyable host value API
+/// are retained for the Store's lifetime.
///
/// ## Example
/// ```rust
@@ -80,10 +72,11 @@ impl Store {
/// Create a new store
pub fn new(engine: Engine) -> Self {
let id = STORE_ID.fetch_add(1, Ordering::Relaxed);
+ let state = State { gc: gc::GcHeap::new(engine.config().gc_collection_threshold), ..State::default() };
Self {
id,
module_instances: Vec::new(),
- state: State::default(),
+ state,
call_stack: CallStack::new(engine.config()),
value_stack: ValueStack::new(engine.config()),
engine,
@@ -130,140 +123,6 @@ impl Default for Store {
}
}
-#[derive(Default)]
-/// Global state that can be manipulated by WebAssembly programs
-///
-/// Data should only be addressable by the module that owns it
-/// See <https://webassembly.github.io/spec/core/exec/runtime.html#store>
-pub(crate) struct State {
- // Concrete type indexes in store instances address this canonical type space.
- canonical_types: Vec<FuncType>,
- pub(crate) funcs: Vec<FunctionInstance>,
- pub(crate) tables: Vec<TableInstance>,
- pub(crate) memories: Vec<MemoryInstance>,
- pub(crate) globals: Vec<GlobalInstance>,
- pub(crate) elements: Vec<ElementInstance>,
- pub(crate) data: Vec<DataInstance>,
-}
-
-impl State {
- pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool {
- match (value, expected) {
- (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(),
- (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => {
- self.funcs.get(func.addr() as usize).is_some_and(|func| match expected.type_index() {
- Some(expected) => func.type_addr == expected,
- None => matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func)),
- })
- }
- (_, WasmType::Ref(expected)) if expected.is_concrete() => false,
- _ => value.matches_type(expected),
- }
- }
-
- #[inline]
- pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType {
- let type_addr = self.get_func(addr).type_addr;
- Self::get(&self.canonical_types, type_addr, "canonical type")
- }
-
- #[inline]
- pub(crate) fn get_type(&self, addr: TypeAddr) -> &FuncType {
- Self::get(&self.canonical_types, addr, "canonical type")
- }
- fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T {
- items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
- }
-
- fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T {
- items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
- }
-
- fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) {
- let [item_a, item_b] = items
- .get_disjoint_mut([addr as usize, addr2 as usize])
- .unwrap_or_else(|_| unreachable!("invalid {kind} addresses: {addr}, {addr2}"));
- (item_a, item_b)
- }
-
- /// Get the function at the actual index in the store
- pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance {
- Self::get(&self.funcs, addr, "function")
- }
-
- /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator)
- pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance {
- match self.funcs.get(addr as usize).map(|func| &func.kind) {
- Some(FunctionKind::Wasm(wasm_func)) => wasm_func,
- _ => unreachable!("invalid wasm function address: {addr}"),
- }
- }
-
- /// Get the memory at the actual index in the store
- pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance {
- Self::get(&self.memories, addr, "memory")
- }
-
- /// Get the memory at the actual index in the store
- pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance {
- Self::get_mut(&mut self.memories, addr, "memory")
- }
-
- /// Get the memory at the actual index in the store
- pub(crate) fn get_mems_mut(&mut self, addr: MemAddr, addr2: MemAddr) -> (&mut MemoryInstance, &mut MemoryInstance) {
- Self::get_disjoint_mut(&mut self.memories, addr, addr2, "memory")
- }
-
- /// Get the table at the actual index in the store
- pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance {
- Self::get(&self.tables, addr, "table")
- }
-
- /// Get the table at the actual index in the store
- pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance {
- Self::get_mut(&mut self.tables, addr, "table")
- }
-
- /// Get two mutable tables at the actual index in the store
- pub(crate) fn get_tables_mut(
- &mut self,
- addr: TableAddr,
- addr2: TableAddr,
- ) -> (&mut TableInstance, &mut TableInstance) {
- Self::get_disjoint_mut(&mut self.tables, addr, addr2, "table")
- }
-
- /// Get the data at the actual index in the store
- pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance {
- Self::get_mut(&mut self.data, addr, "data")
- }
-
- /// Get the element at the actual index in the store
- pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance {
- Self::get_mut(&mut self.elements, addr, "element")
- }
-
- /// Get the global at the actual index in the store
- pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance {
- Self::get(&self.globals, addr, "global")
- }
-
- /// Get the global at the actual index in the store
- pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance {
- Self::get_mut(&mut self.globals, addr, "global")
- }
-
- /// Get the global at the actual index in the store
- pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue {
- self.get_global(addr).value
- }
-
- /// Set the global at the actual index in the store
- pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
- self.get_global_mut(addr).value = value;
- }
-}
-
impl Store {
/// Get the store's ID (unique per process)
pub fn id(&self) -> usize {
@@ -290,71 +149,31 @@ impl Store {
pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
self.state.set_global_val(addr, value);
}
-}
-
-// Linking related functions
-impl Store {
- pub(crate) fn register_module_types(&mut self, types: &[FuncType]) -> Box<[TypeAddr]> {
- let mut type_addrs = Vec::with_capacity(types.len());
- for (local_addr, ty) in types.iter().enumerate() {
- if let Some(addr) = self
- .state
- .canonical_types
- .iter()
- .position(|registered| ty.equivalent(types, registered, &self.state.canonical_types))
- {
- type_addrs.push(addr as TypeAddr);
- continue;
- }
- let addr = self.state.canonical_types.len();
- assert!(addr <= ((1 << 30) - 1), "too many canonical function types");
- type_addrs.push(addr as TypeAddr);
- let canonicalize = |ty: WasmType| match ty {
- WasmType::Ref(ty) if ty.is_concrete() => {
- let module_ref = ty.type_index().unwrap() as usize;
- // A singleton recursive group can refer to the type currently being registered.
- let canonical = if module_ref == local_addr {
- addr as TypeAddr
- } else {
- *type_addrs
- .get(module_ref)
- .unwrap_or_else(|| unreachable!("invalid forward type reference: {module_ref}"))
- };
- WasmType::Ref(RefType::new_concrete(ty.is_nullable(), canonical).unwrap())
- }
- ty => ty,
- };
- let params = ty.params().iter().copied().map(canonicalize).collect::<Vec<_>>();
- let results = ty.results().iter().copied().map(canonicalize).collect::<Vec<_>>();
- self.state.canonical_types.push(FuncType::new(&params, &results));
- }
- type_addrs.into_boxed_slice()
- }
-
- pub(crate) fn register_host_type(&mut self, ty: &FuncType) -> TypeAddr {
- if let Some(addr) = self.state.canonical_types.iter().position(|registered| ty == registered) {
- return addr as TypeAddr;
- }
- let addr = self.state.canonical_types.len();
- assert!(addr <= ((1 << 30) - 1), "too many canonical function types");
- self.state.canonical_types.push(ty.clone());
- addr as TypeAddr
+ /// Returns whether a public value has the requested runtime type.
+ #[doc(hidden)]
+ pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool {
+ self.state.value_matches_type(value, ty)
}
+}
+impl Store {
/// Add functions to the store, returning their addresses in the store
pub(crate) fn init_funcs(
&mut self,
- funcs: &[Arc<WasmFunction>],
+ funcs: &[alloc::sync::Arc<WasmFunction>],
owner: ModuleInstanceId,
type_addrs: &[TypeAddr],
) -> impl ExactSizeIterator<Item = FuncAddr> {
let start = self.state.funcs.len() as FuncAddr;
debug_assert_eq!(funcs.len(), type_addrs.len());
- self.state.funcs.extend(funcs.iter().zip(type_addrs).map(|(func, &type_addr)| FunctionInstance {
- type_addr,
- kind: FunctionKind::Wasm(WasmFunctionInstance { func: func.clone(), owner }),
- }));
+ for (func, &type_addr) in funcs.iter().zip(type_addrs) {
+ self.state.funcs.push(FunctionInstance {
+ type_addr,
+ gc: self.state.func_gc_metadata(type_addr),
+ kind: FunctionKind::Wasm(WasmFunctionInstance { func: func.clone(), owner }),
+ });
+ }
start..start + funcs.len() as FuncAddr
}
@@ -370,11 +189,11 @@ impl Store {
self.state.tables.reserve_exact(tables.len());
for table in tables {
let init = match &table.init {
- Some(expr) => match self.eval_const(expr, global_addrs, func_addrs)? {
- TinyWasmValue::ValueRef(value) => TableElement::from(value.addr()),
+ Some(expr) => match self.eval_const(expr, global_addrs, func_addrs, type_addrs)? {
+ TinyWasmValue::ValueRef(value) => value,
_ => return Err(Error::other("table initializer is not a reference value")),
},
- None => TableElement::Uninitialized,
+ None => ValueRef::NULL,
};
let element_type = canonicalize_ref_type(table.ty.element_type, type_addrs);
let ty = match table.ty.arch() {
@@ -417,7 +236,7 @@ impl Store {
out.extend(start..start + globals.len() as Addr);
for global in globals {
- let value = match self.eval_const(&global.init, out, func_addrs) {
+ let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) {
Ok(val) => val,
Err(e) => {
cold_path();
@@ -431,17 +250,23 @@ impl Store {
Ok(())
}
- fn elem_addr(&self, item: &ElementItem, globals: &[Addr], funcs: &[FuncAddr]) -> Result<Option<u32>> {
+ fn elem_value(
+ &mut self,
+ item: &ElementItem,
+ globals: &[Addr],
+ funcs: &[FuncAddr],
+ type_addrs: &[TypeAddr],
+ ) -> Result<ValueRef> {
match item {
- ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs)? {
- TinyWasmValue::ValueRef(v) => Ok(v.addr()),
+ ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs, type_addrs)? {
+ TinyWasmValue::ValueRef(value) => Ok(value),
other => {
cold_path();
Err(Error::Other(format!("expected ref type, got {other:?}")))
}
},
ElementItem::Func(addr) => match funcs.get(*addr as usize) {
- Some(func_addr) => Ok(Some(*func_addr)),
+ Some(func_addr) => Ok(ValueRef::from_category_addr(*func_addr)),
None => {
cold_path();
Err(Error::Other(format!(
@@ -460,26 +285,31 @@ impl Store {
func_addrs: &[FuncAddr],
global_addrs: &[Addr],
elements: &[Element],
+ type_addrs: &[TypeAddr],
) -> Result<(Box<[Addr]>, Option<Trap>)> {
let elem_count = self.state.elements.len();
- let mut elem_addrs = Vec::with_capacity(elem_count);
+ let mut elem_addrs = Vec::with_capacity(elements.len());
for (i, element) in elements.iter().enumerate() {
- let init = element
- .items
- .iter()
- .map(|item| Ok(TableElement::from(self.elem_addr(item, global_addrs, func_addrs)?)))
- .collect::<Result<Vec<_>>>()?;
+ let elem_addr = self.state.elements.len();
+ self.state.elements.push(ElementInstance {
+ items: Some(Vec::with_capacity(element.items.len())),
+ ty: canonicalize_ref_type(element.ty, type_addrs),
+ });
+ for item in &element.items {
+ let value = self.elem_value(item, global_addrs, func_addrs, type_addrs)?;
+ self.state.elements[elem_addr].items.as_mut().unwrap().push(value);
+ }
- let items = match &element.kind {
+ match &element.kind {
// doesn't need to be initialized, can be initialized lazily using the `table.init` instruction
- ElementKind::Passive => Some(init),
+ ElementKind::Passive => {}
// this one is not available to the runtime but needs to be initialized to declare references
- ElementKind::Declared => None, // a. Execute the instruction elm.drop i
+ ElementKind::Declared => self.state.elements[elem_addr].drop(),
// this one is active, so we need to initialize it (essentially a `table.init` instruction)
ElementKind::Active { offset, table } => {
- let offset = self.eval_size_const(offset, global_addrs, func_addrs)?;
+ let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?;
let table_addr = table_addrs
.get(*table as usize)
.copied()
@@ -497,20 +327,26 @@ impl Store {
let Ok(offset) = usize::try_from(offset) else {
return Ok((
elem_addrs.into_boxed_slice(),
- Some(Trap::TableOutOfBounds { offset: usize::MAX, len: init.len(), max: table.size() }),
+ Some(Trap::TableOutOfBounds {
+ offset: usize::MAX,
+ len: self.state.elements[elem_addr].items.as_ref().unwrap().len(),
+ max: table.size(),
+ }),
));
};
- if let Err(trap) = table.init(offset, &init) {
+ 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)));
}
// f. Execute the instruction elm.drop i
- None
+ elements[elem_addr].drop();
}
- };
+ }
- self.state.elements.push(ElementInstance { items });
elem_addrs.push((i + elem_count) as Addr);
}
@@ -525,6 +361,7 @@ impl Store {
global_addrs: &[Addr],
func_addrs: &[FuncAddr],
data: &[Data],
+ type_addrs: &[TypeAddr],
) -> Result<(Box<[Addr]>, Option<Trap>)> {
let data_count = self.state.data.len();
let mut data_addrs = Vec::with_capacity(data_count);
@@ -535,7 +372,7 @@ impl Store {
return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}")));
};
- let offset = self.eval_size_const(offset, global_addrs, func_addrs)?;
+ let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?;
let Some(mem) = self.state.memories.get_mut(*mem_addr as usize) else {
return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}")));
};
@@ -573,12 +410,13 @@ impl Store {
/// Evaluate a constant expression that's either a i32 or a i64 as a global or a const instruction
fn eval_size_const(
- &self,
+ &mut self,
const_instrs: &[tinywasm_types::ConstInstruction],
module_global_addrs: &[Addr],
module_func_addrs: &[FuncAddr],
+ module_type_addrs: &[TypeAddr],
) -> Result<u64> {
- let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs)?;
+ let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs, module_type_addrs)?;
match value {
TinyWasmValue::Value32(i) => Ok(u64::from(i)),
TinyWasmValue::Value64(i) => Ok(i),
@@ -589,61 +427,56 @@ impl Store {
/// Evaluate a constant expression
#[inline]
fn eval_const(
- &self,
+ &mut self,
const_instrs: &[tinywasm_types::ConstInstruction],
module_global_addrs: &[Addr],
module_func_addrs: &[FuncAddr],
+ module_type_addrs: &[TypeAddr],
) -> Result<TinyWasmValue> {
use tinywasm_types::ConstInstruction::*;
- let resolve_global = |idx: u32| -> Result<TinyWasmValue> {
- let Some(addr) = module_global_addrs.get(idx as usize) else {
- cold_path();
- return Err(Error::Other(format!(
- "global {idx} not found. This should have been caught by the validator"
- )));
- };
-
- let Some(global) = self.state.globals.get(*addr as usize) else {
- cold_path();
- return Err(Error::Other(format!("global {addr} not found")));
- };
-
- Ok(global.value)
+ let global_value = |state: &State, index: u32| -> Result<TinyWasmValue> {
+ let addr = *module_global_addrs
+ .get(index as usize)
+ .ok_or_else(|| Error::Other(format!("global {index} not found")))?;
+ Ok(state.globals.get(addr as usize).ok_or_else(|| Error::Other(format!("global {addr} not found")))?.value)
};
-
- let resolve_func = |idx: u32| -> Result<u32> {
- match module_func_addrs.get(idx as usize) {
- Some(func_addr) => Ok(*func_addr),
- None => {
- cold_path();
- Err(Error::Other(format!(
- "function {idx} not found. This should have been caught by the validator"
- )))
- }
+ let func_ref = |index: u32| -> Result<ValueRef> {
+ let addr = *module_func_addrs
+ .get(index as usize)
+ .ok_or_else(|| Error::Other(format!("function {index} not found")))?;
+ Ok(ValueRef::from_category_addr(addr))
+ };
+ let type_addr = |index: TypeAddr| -> Result<TypeAddr> {
+ module_type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found"))
+ };
+ let pop_value = |stack: &mut Vec<TinyWasmValue>, storage: StorageType| -> Result<TinyWasmValue> {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ match (storage, value) {
+ (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)),
+ (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)),
+ (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_))
+ | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_))
+ | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_))
+ | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value),
+ _ => Err(Error::other("type mismatch in GC constant")),
}
};
- if const_instrs.len() == 1 {
- let val = match &const_instrs[0] {
- F32Const(f) => (*f).into(),
- F64Const(f) => (*f).into(),
- I32Const(i) => (*i).into(),
- I64Const(i) => (*i).into(),
- V128Const(i) => (*i).into(),
- GlobalGet(addr) => resolve_global(*addr)?,
- Ref(tinywasm_types::RefValue::Null) => TinyWasmValue::ValueRef(ValueRef::NULL),
+ if let [instr] = const_instrs {
+ match instr {
+ I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)),
+ I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)),
+ F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())),
+ F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())),
+ V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())),
+ GlobalGet(index) => return global_value(&self.state, *index),
+ Ref(tinywasm_types::RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)),
Ref(tinywasm_types::RefValue::Func(func)) => {
- TinyWasmValue::ValueRef(ValueRef::from_raw(resolve_func(func.addr())?))
- }
- Ref(_) => return Err(Error::other("unsupported reference constant")),
- _ => {
- cold_path();
- return Err(Error::other("unsupported const instruction"));
+ return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?));
}
- };
-
- return Ok(val);
+ _ => {}
+ }
}
let mut stack = Vec::new();
@@ -654,15 +487,96 @@ impl Store {
F32Const(f) => stack.push(TinyWasmValue::Value32(f.to_bits())),
F64Const(f) => stack.push(TinyWasmValue::Value64(f.to_bits())),
V128Const(i) => stack.push(TinyWasmValue::Value128((*i).into())),
- GlobalGet(addr) => stack.push(resolve_global(*addr)?),
+ GlobalGet(index) => stack.push(global_value(&self.state, *index)?),
Ref(tinywasm_types::RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)),
Ref(tinywasm_types::RefValue::Func(func)) => {
- stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(resolve_func(func.addr())?)))
+ stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?))
}
Ref(_) => {
cold_path();
return Err(Error::other("unsupported reference constant"));
}
+ RefI31 => {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ let TinyWasmValue::Value32(value) = value else {
+ return Err(Error::other("type mismatch in const ref.i31"));
+ };
+ stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32)));
+ }
+ AnyConvertExtern | ExternConvertAny => {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ if !matches!(value, TinyWasmValue::ValueRef(_)) {
+ return Err(Error::other("type mismatch in const reference conversion"));
+ }
+ stack.push(value);
+ }
+ StructNew(type_index) | StructNewDefault(type_index) => {
+ let type_addr = type_addr(*type_index)?;
+ let fields = self
+ .state
+ .get_type(type_addr)
+ .as_struct()
+ .ok_or_else(|| Error::other("GC constant type is not a struct"))?
+ .fields
+ .clone();
+ let default = matches!(instr, StructNewDefault(_));
+ let mut values = Vec::new();
+ values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?;
+ if default {
+ values.extend(fields.iter().map(|field| default_value(field.storage)));
+ } else {
+ for field in fields.iter().rev() {
+ values.push(pop_value(&mut stack, field.storage)?);
+ }
+ values.reverse();
+ }
+ let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
+ let reference = self.state.alloc_gc_object(type_addr, values, roots)?;
+ stack.push(TinyWasmValue::ValueRef(reference));
+ }
+ ArrayNew(type_index) | ArrayNewDefault(type_index) => {
+ let type_addr = type_addr(*type_index)?;
+ let storage = self
+ .state
+ .get_type(type_addr)
+ .as_array()
+ .ok_or_else(|| Error::other("GC constant type is not an array"))?
+ .field
+ .storage;
+ let Some(TinyWasmValue::Value32(len)) = stack.pop() else {
+ return Err(Error::other("type mismatch in const array length"));
+ };
+ let value = if matches!(instr, ArrayNewDefault(_)) {
+ default_value(storage)
+ } else {
+ pop_value(&mut stack, storage)?
+ };
+ let mut values = Vec::new();
+ values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?;
+ values.resize(len as usize, value);
+ let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
+ let reference = self.state.alloc_gc_object(type_addr, values, roots)?;
+ stack.push(TinyWasmValue::ValueRef(reference));
+ }
+ ArrayNewFixed(type_index, len) => {
+ let type_addr = type_addr(*type_index)?;
+ let storage = self
+ .state
+ .get_type(type_addr)
+ .as_array()
+ .ok_or_else(|| Error::other("GC constant type is not an array"))?
+ .field
+ .storage;
+ let mut values = Vec::new();
+ values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?;
+ for _ in 0..*len {
+ values.push(pop_value(&mut stack, storage)?);
+ }
+ values.reverse();
+ let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw);
+ let reference = self.state.alloc_gc_object(type_addr, values, roots)?;
+ stack.push(TinyWasmValue::ValueRef(reference));
+ }
I32Add | I32Sub | I32Mul => {
let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
new file mode 100644
index 0000000..125cc30
--- /dev/null
+++ b/crates/tinywasm/src/store/state.rs
@@ -0,0 +1,385 @@
+use alloc::vec::Vec;
+
+use super::*;
+
+#[derive(Default)]
+/// Global state that can be manipulated by WebAssembly programs
+///
+/// Data should only be addressable by the module that owns it
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#store>
+pub(crate) struct State {
+ // Concrete type indexes in store instances address this canonical type space.
+ pub(crate) canonical_types: Vec<SubType>,
+ pub(crate) canonical_rec_group_lengths: Vec<u32>,
+ pub(crate) funcs: Vec<FunctionInstance>,
+ pub(crate) tables: Vec<TableInstance>,
+ pub(crate) memories: Vec<MemoryInstance>,
+ pub(crate) globals: Vec<GlobalInstance>,
+ pub(crate) elements: Vec<ElementInstance>,
+ pub(crate) data: Vec<DataInstance>,
+ pub(crate) gc: gc::GcHeap,
+}
+
+impl State {
+ /// Returns whether values of this type can contain a managed GC object.
+ pub(crate) fn type_may_contain_gc(&self, ty: WasmType) -> bool {
+ Self::type_may_contain_gc_in(&self.canonical_types, ty)
+ }
+
+ fn type_may_contain_gc_in(types: &[SubType], ty: WasmType) -> bool {
+ let WasmType::Ref(ty) = ty else { return false };
+ if let Some(type_addr) = ty.type_index() {
+ return matches!(types[type_addr as usize].composite, CompositeType::Struct(_) | CompositeType::Array(_));
+ }
+ matches!(
+ ty.abstract_heap_type(),
+ Some(
+ AbstractHeapType::Any
+ | AbstractHeapType::Eq
+ | AbstractHeapType::Struct
+ | AbstractHeapType::Array
+ | AbstractHeapType::Extern
+ )
+ )
+ }
+
+ /// Precomputes whether a canonical function signature can carry GC objects.
+ pub(crate) fn func_gc_metadata(&self, type_addr: TypeAddr) -> FunctionGcMetadata {
+ let ty = self.get_canonical_func_type(type_addr);
+ FunctionGcMetadata {
+ params: ty.params().iter().copied().any(|ty| self.type_may_contain_gc(ty)),
+ results: ty.results().iter().copied().any(|ty| self.type_may_contain_gc(ty)),
+ }
+ }
+
+ /// Allocates an object, collecting from all runtime roots when needed.
+ pub(crate) fn alloc_gc_object(
+ &mut self,
+ type_addr: TypeAddr,
+ values: Vec<TinyWasmValue>,
+ stack_32: impl IntoIterator<Item = u32>,
+ ) -> Result<ValueRef, Trap> {
+ let trace_references = match &self.get_type(type_addr).composite {
+ CompositeType::Struct(ty) => {
+ ty.fields.iter().any(|field| matches!(field.storage, StorageType::Value(WasmType::Ref(_))))
+ }
+ CompositeType::Array(ty) => matches!(ty.field.storage, StorageType::Value(WasmType::Ref(_))),
+ CompositeType::Func(_) => unreachable!("GC object type is not a function"),
+ };
+ if self.gc.should_collect(values.len(), trace_references) {
+ let canonical_types = &self.canonical_types;
+ let roots = stack_32
+ .into_iter()
+ .map(ValueRef::from_raw)
+ .chain(
+ self.globals
+ .iter()
+ .filter(|global| Self::type_may_contain_gc_in(canonical_types, global.ty.ty))
+ .filter_map(|global| global.value.as_ref()),
+ )
+ .chain(
+ self.tables
+ .iter()
+ .filter(|table| {
+ Self::type_may_contain_gc_in(canonical_types, WasmType::Ref(table.kind.element_type))
+ })
+ .flat_map(|table| table.elements.iter().copied()),
+ )
+ .chain(
+ self.elements
+ .iter()
+ .filter(|element| Self::type_may_contain_gc_in(canonical_types, WasmType::Ref(element.ty)))
+ .flat_map(|element| element.items.iter().flatten().copied()),
+ )
+ .chain(values.iter().filter_map(|value| value.as_ref()));
+ self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?;
+ }
+ self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory)
+ }
+
+ /// Pins a host-visible reference when it resolves to a managed GC object.
+ pub(crate) fn pin_host_ref(&self, value: RefValue) {
+ let raw = match value {
+ RefValue::Any(value) => value.raw(),
+ RefValue::Extern(value) => value.raw(),
+ RefValue::Null | RefValue::Func(_) | RefValue::Exn(_) => return,
+ };
+ self.gc.pin(ValueRef::from_raw(raw));
+ }
+
+ /// Pins GC references that have crossed into host-visible values.
+ pub(crate) fn pin_host_values(&self, values: &[WasmValue]) {
+ for &value in values {
+ if let WasmValue::Ref(value) = value {
+ self.pin_host_ref(value);
+ }
+ }
+ }
+
+ /// Resolves a non-null object of the expected canonical type.
+ pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result<&gc::GcObject, Trap> {
+ if reference.is_null() {
+ return Err(if self.get_type(expected_type).as_array().is_some() {
+ Trap::NullArrayReference
+ } else {
+ Trap::NullStructReference
+ });
+ }
+ let object = self.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?;
+ if !self.type_addr_is_subtype(object.type_addr, expected_type) {
+ return Err(Trap::Other("GC reference type mismatch"));
+ }
+ Ok(object)
+ }
+
+ /// Converts an internal value using canonical reference type information.
+ pub(crate) fn attach_value(&self, value: TinyWasmValue, ty: WasmType) -> Option<WasmValue> {
+ if let (TinyWasmValue::ValueRef(value), WasmType::Ref(reference_type)) = (value, ty)
+ && let Some(type_addr) = reference_type.type_index()
+ {
+ if value.is_null() {
+ return Some(RefValue::Null.into());
+ }
+ return match &self.get_type(type_addr).composite {
+ CompositeType::Func(_) => Some(RefValue::Func(FuncRef::new(value.addr()?)).into()),
+ CompositeType::Struct(_) | CompositeType::Array(_) => {
+ Some(RefValue::Any(AnyRef::from_raw(value.raw())).into())
+ }
+ };
+ }
+ value.attach_type(ty)
+ }
+
+ /// Returns whether one canonical type is a subtype of another.
+ pub(crate) fn type_addr_is_subtype(&self, mut actual: TypeAddr, expected: TypeAddr) -> bool {
+ loop {
+ if actual == expected {
+ return true;
+ }
+ let Some(supertype) = self.get_type(actual).supertype else { return false };
+ actual = supertype;
+ }
+ }
+
+ /// Returns whether one reference type is a subtype of another.
+ pub(crate) fn ref_type_is_subtype(&self, actual: RefType, expected: RefType) -> bool {
+ if actual.is_nullable() && !expected.is_nullable() {
+ return false;
+ }
+ self.heap_type_is_subtype(actual, expected)
+ }
+
+ /// Returns whether one value type is a subtype of another.
+ pub(crate) fn value_type_is_subtype(&self, actual: WasmType, expected: WasmType) -> bool {
+ match (actual, expected) {
+ (WasmType::Ref(actual), WasmType::Ref(expected)) => self.ref_type_is_subtype(actual, expected),
+ _ => actual == expected,
+ }
+ }
+
+ fn heap_type_is_subtype(&self, actual: RefType, expected: RefType) -> bool {
+ if let Some(expected_addr) = expected.type_index() {
+ let Some(actual_addr) = actual.type_index() else {
+ return matches!(
+ (actual.abstract_heap_type(), &self.get_type(expected_addr).composite),
+ (Some(AbstractHeapType::NoFunc), CompositeType::Func(_))
+ | (Some(AbstractHeapType::None), CompositeType::Struct(_) | CompositeType::Array(_))
+ );
+ };
+ return self.type_addr_is_subtype(actual_addr, expected_addr);
+ }
+
+ let expected = expected.abstract_heap_type().expect("abstract reference type");
+ if let Some(actual_addr) = actual.type_index() {
+ return match &self.get_type(actual_addr).composite {
+ CompositeType::Func(_) => expected == AbstractHeapType::Func,
+ CompositeType::Struct(_) => {
+ matches!(expected, AbstractHeapType::Struct | AbstractHeapType::Eq | AbstractHeapType::Any)
+ }
+ CompositeType::Array(_) => {
+ matches!(expected, AbstractHeapType::Array | AbstractHeapType::Eq | AbstractHeapType::Any)
+ }
+ };
+ }
+
+ let actual = actual.abstract_heap_type().expect("abstract reference type");
+ actual == expected
+ || match actual {
+ AbstractHeapType::None => matches!(
+ expected,
+ AbstractHeapType::I31
+ | AbstractHeapType::Struct
+ | AbstractHeapType::Array
+ | AbstractHeapType::Eq
+ | AbstractHeapType::Any
+ ),
+ AbstractHeapType::I31 | AbstractHeapType::Struct | AbstractHeapType::Array => {
+ matches!(expected, AbstractHeapType::Eq | AbstractHeapType::Any)
+ }
+ AbstractHeapType::Eq => expected == AbstractHeapType::Any,
+ AbstractHeapType::NoFunc => expected == AbstractHeapType::Func,
+ AbstractHeapType::NoExtern => expected == AbstractHeapType::Extern,
+ AbstractHeapType::NoExn => expected == AbstractHeapType::Exn,
+ _ => false,
+ }
+ }
+
+ /// Returns whether a runtime reference has the expected type.
+ pub(crate) fn value_ref_matches(&self, value: ValueRef, expected: RefType) -> bool {
+ if value.is_null() {
+ return expected.is_nullable();
+ }
+ if expected.abstract_heap_type() == Some(AbstractHeapType::Extern) {
+ return true;
+ }
+ let expected_func = expected.type_index().is_some_and(|addr| self.get_type(addr).as_func().is_some())
+ || expected.abstract_heap_type() == Some(AbstractHeapType::Func);
+ if expected_func {
+ let Some(func_addr) = value.addr() else { return false };
+ let Some(func) = self.funcs.get(func_addr as usize) else { return false };
+ let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits");
+ return self.ref_type_is_subtype(actual, expected);
+ }
+ if value.is_i31() {
+ let actual = RefType::new_abstract(false, AbstractHeapType::I31);
+ return self.ref_type_is_subtype(actual, expected);
+ }
+ if value.is_host_any() {
+ let actual = RefType::new_abstract(false, AbstractHeapType::Any);
+ return self.ref_type_is_subtype(actual, expected);
+ }
+
+ let Some(object) = self.gc.get(value) else { return false };
+ let actual = RefType::new_concrete(false, object.type_addr).expect("canonical type fits");
+ self.ref_type_is_subtype(actual, expected)
+ }
+
+ #[inline]
+ pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType {
+ self.get_canonical_func_type(self.get_func(addr).type_addr)
+ }
+
+ #[inline]
+ pub(crate) fn get_type(&self, addr: TypeAddr) -> &SubType {
+ Self::get(&self.canonical_types, addr, "canonical type")
+ }
+
+ #[inline]
+ pub(crate) fn get_canonical_func_type(&self, addr: TypeAddr) -> &FuncType {
+ self.get_type(addr).as_func().expect("validated function address references a function type")
+ }
+
+ pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool {
+ match (value, expected) {
+ (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(),
+ (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => {
+ self.funcs.get(func.addr() as usize).is_some_and(|func| {
+ let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits");
+ self.ref_type_is_subtype(actual, expected)
+ })
+ }
+ (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected))
+ if expected.is_func() || expected.is_extern() || expected.is_exn() =>
+ {
+ false
+ }
+ (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => {
+ self.value_ref_matches(ValueRef::from_raw(value.raw()), expected)
+ }
+ (_, WasmType::Ref(expected)) if expected.is_concrete() => false,
+ _ => value.matches_type(expected),
+ }
+ }
+
+ pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T {
+ items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
+ }
+
+ fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T {
+ items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
+ }
+
+ fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) {
+ let [item_a, item_b] = items
+ .get_disjoint_mut([addr as usize, addr2 as usize])
+ .unwrap_or_else(|_| unreachable!("invalid {kind} addresses: {addr}, {addr2}"));
+ (item_a, item_b)
+ }
+
+ /// Get the function at the actual index in the store
+ pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance {
+ Self::get(&self.funcs, addr, "function")
+ }
+
+ /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator)
+ pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance {
+ match self.funcs.get(addr as usize).map(|func| &func.kind) {
+ Some(FunctionKind::Wasm(wasm_func)) => wasm_func,
+ _ => unreachable!("invalid wasm function address: {addr}"),
+ }
+ }
+
+ /// Get the memory at the actual index in the store
+ pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance {
+ Self::get(&self.memories, addr, "memory")
+ }
+
+ /// Get the memory at the actual index in the store
+ pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance {
+ Self::get_mut(&mut self.memories, addr, "memory")
+ }
+
+ /// Get the memory at the actual index in the store
+ pub(crate) fn get_mems_mut(&mut self, addr: MemAddr, addr2: MemAddr) -> (&mut MemoryInstance, &mut MemoryInstance) {
+ Self::get_disjoint_mut(&mut self.memories, addr, addr2, "memory")
+ }
+
+ /// Get the table at the actual index in the store
+ pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance {
+ Self::get(&self.tables, addr, "table")
+ }
+
+ /// Get the table at the actual index in the store
+ pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance {
+ Self::get_mut(&mut self.tables, addr, "table")
+ }
+
+ /// Get two mutable tables at the actual index in the store
+ pub(crate) fn get_tables_mut(
+ &mut self,
+ addr: TableAddr,
+ addr2: TableAddr,
+ ) -> (&mut TableInstance, &mut TableInstance) {
+ Self::get_disjoint_mut(&mut self.tables, addr, addr2, "table")
+ }
+
+ /// Get the data at the actual index in the store
+ pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance {
+ Self::get_mut(&mut self.data, addr, "data")
+ }
+
+ /// Get the element at the actual index in the store
+ pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance {
+ Self::get_mut(&mut self.elements, addr, "element")
+ }
+
+ /// Get the global at the actual index in the store
+ pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance {
+ Self::get(&self.globals, addr, "global")
+ }
+
+ /// Get the global at the actual index in the store
+ pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance {
+ Self::get_mut(&mut self.globals, addr, "global")
+ }
+
+ /// Get the global at the actual index in the store
+ pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue {
+ self.get_global(addr).value
+ }
+
+ /// Set the global at the actual index in the store
+ pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
+ self.get_global_mut(addr).value = value;
+ }
+}
diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs
index 68ed99f..ece0001 100644
--- a/crates/tinywasm/src/store/table.rs
+++ b/crates/tinywasm/src/store/table.rs
@@ -1,4 +1,4 @@
-use crate::{Result, Trap};
+use crate::{Result, Trap, interpreter::ValueRef};
use alloc::vec::Vec;
use core::ops::Range;
use tinywasm_types::*;
@@ -10,17 +10,17 @@ const MAX_TABLE_SIZE: usize = 10_000_000;
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#table-instances>
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct TableInstance {
- pub(crate) elements: Vec<TableElement>,
+ pub(crate) elements: Vec<ValueRef>,
pub(crate) kind: TableType,
}
impl TableInstance {
#[cfg(test)]
pub(crate) fn new(kind: TableType) -> Result<Self> {
- Self::new_with_init(kind, TableElement::Uninitialized)
+ Self::new_with_init(kind, ValueRef::NULL)
}
- pub(crate) fn new_with_init(kind: TableType, init: TableElement) -> Result<Self> {
+ pub(crate) fn new_with_init(kind: TableType, init: ValueRef) -> Result<Self> {
let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?;
if size > MAX_TABLE_SIZE {
return Err(Trap::OutOfMemory.into());
@@ -45,27 +45,23 @@ impl TableInstance {
Ok(addr..end)
}
- pub(crate) fn get_wasm_val(&self, addr: usize) -> Result<WasmValue, Trap> {
- Ok(self.get(addr)?.to_wasm_value(self.kind.element_type))
- }
-
- pub(crate) fn fill(&mut self, addr: usize, len: usize, val: TableElement) -> Result<(), Trap> {
+ pub(crate) fn fill(&mut self, addr: usize, len: usize, val: ValueRef) -> Result<(), Trap> {
let range = self.checked_range(addr, len)?;
self.elements[range].fill(val);
Ok(())
}
- pub(crate) fn get(&self, addr: usize) -> Result<&TableElement, Trap> {
+ pub(crate) fn get(&self, addr: usize) -> Result<&ValueRef, Trap> {
self.elements.get(addr).ok_or_else(|| self.trap_oob(addr, 1))
}
- pub(crate) fn copy_from_slice(&mut self, dst: usize, src: &[TableElement]) -> Result<(), Trap> {
+ pub(crate) fn copy_from_slice(&mut self, dst: usize, src: &[ValueRef]) -> Result<(), Trap> {
let range = self.checked_range(dst, src.len())?;
self.elements[range].copy_from_slice(src);
Ok(())
}
- pub(crate) fn load(&self, addr: usize, len: usize) -> Result<&[TableElement], Trap> {
+ pub(crate) fn load(&self, addr: usize, len: usize) -> Result<&[ValueRef], Trap> {
Ok(&self.elements[self.checked_range(addr, len)?])
}
@@ -76,13 +72,13 @@ impl TableInstance {
Ok(())
}
- pub(crate) fn set(&mut self, table_idx: usize, value: TableElement) -> Result<(), Trap> {
+ pub(crate) fn set(&mut self, table_idx: usize, value: ValueRef) -> Result<(), Trap> {
let range = self.checked_range(table_idx, 1)?;
self.elements[range.start] = value;
Ok(())
}
- pub(crate) fn grow(&mut self, n: usize, init: TableElement) -> Result<(), Trap> {
+ pub(crate) fn grow(&mut self, n: usize, init: ValueRef) -> Result<(), Trap> {
let len = n.checked_add(self.elements.len()).ok_or(Trap::OutOfMemory)?;
let declared_max = self.kind.size_max.and_then(|max| usize::try_from(max).ok()).unwrap_or(usize::MAX);
let max = declared_max.min(MAX_TABLE_SIZE);
@@ -99,52 +95,13 @@ impl TableInstance {
self.elements.len()
}
- pub(crate) fn init(&mut self, offset: usize, init: &[TableElement]) -> Result<(), Trap> {
+ pub(crate) fn init(&mut self, offset: usize, init: &[ValueRef]) -> Result<(), Trap> {
let range = self.checked_range(offset, init.len())?;
self.elements[range].copy_from_slice(init);
Ok(())
}
}
-#[derive(Clone, Copy)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) enum TableElement {
- Uninitialized,
- Initialized(TableAddr),
-}
-
-impl From<Option<Addr>> for TableElement {
- fn from(addr: Option<Addr>) -> Self {
- match addr {
- None => Self::Uninitialized,
- Some(addr) => Self::Initialized(addr),
- }
- }
-}
-
-impl TableElement {
- pub(crate) fn addr(&self) -> Option<Addr> {
- match self {
- Self::Uninitialized => None,
- Self::Initialized(addr) => Some(*addr),
- }
- }
-
- pub(crate) fn to_wasm_value(self, ty: RefType) -> WasmValue {
- let Some(addr) = self.addr() else { return RefValue::Null.into() };
- let value = if ty.is_func() {
- RefValue::Func(FuncRef::new(addr))
- } else if ty.is_extern() {
- RefValue::Extern(ExternRef::new(addr))
- } else if ty.is_exn() {
- RefValue::Exn(ExnRef::new(addr))
- } else {
- RefValue::Any(AnyRef::from_raw(addr))
- };
- value.into()
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -163,42 +120,16 @@ mod tests {
}
#[test]
- fn test_get_wasm_val() {
- let kind = dummy_table_type();
- let mut table_instance = TableInstance::new(kind).unwrap();
-
- table_instance.set(0, TableElement::Initialized(0)).expect("Setting table element failed");
- table_instance.set(1, TableElement::Uninitialized).expect("Setting table element failed");
-
- match table_instance.get_wasm_val(0) {
- Ok(WasmValue::Ref(RefValue::Func(_))) => {}
- _ => panic!("get_wasm_val failed to return the correct WasmValue"),
- }
-
- match table_instance.get_wasm_val(1) {
- Ok(WasmValue::Ref(RefValue::Null)) => {}
- _ => panic!("get_wasm_val failed to return the correct WasmValue"),
- }
-
- match table_instance.get_wasm_val(999) {
- Err(Trap::TableOutOfBounds { .. }) => {}
- _ => panic!("get_wasm_val failed to handle undefined element correctly"),
- }
- }
-
- #[test]
fn test_set_and_get() {
let kind = dummy_table_type();
let mut table_instance = TableInstance::new(kind).unwrap();
- let result = table_instance.set(0, TableElement::Initialized(1));
+ let value = ValueRef::from_raw(2);
+ let result = table_instance.set(0, value);
assert!(result.is_ok(), "Setting table element failed");
let elem = table_instance.get(0);
- assert!(
- elem.is_ok() && matches!(elem.unwrap(), &TableElement::Initialized(1)),
- "Getting table element failed or returned incorrect value"
- );
+ assert!(elem.is_ok() && elem.unwrap() == &value, "Getting table element failed or returned incorrect value");
}
#[test]
@@ -206,17 +137,14 @@ mod tests {
let kind = dummy_table_type();
let mut table_instance = TableInstance::new(kind).unwrap();
- let init_elements = vec![TableElement::Initialized(0); 5];
+ let init_elements = vec![ValueRef::from_raw(2); 5];
let result = table_instance.init(0, &init_elements);
assert!(result.is_ok(), "Initializing table with elements failed");
for i in 0..5 {
let elem = table_instance.get(i);
- assert!(
- elem.is_ok() && matches!(elem.unwrap(), &TableElement::Initialized(_)),
- "Element not initialized correctly at index {i}"
- );
+ assert!(elem.is_ok() && !elem.unwrap().is_null(), "Element not initialized correctly at index {i}");
}
}
}
diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs
new file mode 100644
index 0000000..7cee56b
--- /dev/null
+++ b/crates/tinywasm/src/store/types.rs
@@ -0,0 +1,204 @@
+use alloc::{boxed::Box, vec::Vec};
+use tinywasm_types::*;
+
+use super::Store;
+
+pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType {
+ let Some(type_addr) = ty.type_index() else { return ty };
+ let canonical = *type_addrs.get(type_addr as usize).expect("validated type address should exist");
+ RefType::new_concrete(ty.is_nullable(), canonical).expect("canonical type addresses fit in references")
+}
+
+pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType {
+ match ty {
+ WasmType::Ref(ty) => WasmType::Ref(canonicalize_ref_type(ty, type_addrs)),
+ ty => ty,
+ }
+}
+
+fn map_value_type(ty: WasmType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> WasmType {
+ match ty {
+ WasmType::Ref(ty) if ty.is_concrete() => {
+ let addr = resolve(ty.type_index().expect("concrete reference has a type index"));
+ WasmType::Ref(
+ RefType::new_concrete(ty.is_nullable(), addr).expect("canonical type addresses fit in references"),
+ )
+ }
+ ty => ty,
+ }
+}
+
+fn map_field_type(field: FieldType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> FieldType {
+ let storage = match field.storage {
+ StorageType::Value(ty) => StorageType::Value(map_value_type(ty, resolve)),
+ storage => storage,
+ };
+ FieldType { storage, mutable: field.mutable }
+}
+
+fn map_subtype(ty: &SubType, mut resolve: impl FnMut(TypeAddr) -> TypeAddr) -> SubType {
+ let supertype = ty.supertype.map(&mut resolve);
+ let composite = match &ty.composite {
+ CompositeType::Func(ty) => {
+ let params = ty.params().iter().copied().map(|ty| map_value_type(ty, &mut resolve)).collect::<Vec<_>>();
+ let results = ty.results().iter().copied().map(|ty| map_value_type(ty, &mut resolve)).collect::<Vec<_>>();
+ CompositeType::Func(FuncType::new(&params, &results))
+ }
+ CompositeType::Struct(ty) => CompositeType::Struct(StructType {
+ fields: ty.fields.iter().copied().map(|field| map_field_type(field, &mut resolve)).collect(),
+ }),
+ CompositeType::Array(ty) => CompositeType::Array(ArrayType { field: map_field_type(ty.field, &mut resolve) }),
+ };
+ SubType { is_final: ty.is_final, supertype, composite }
+}
+
+fn subtypes_equal(
+ ty: &SubType,
+ registered: &SubType,
+ module_group: core::ops::Range<usize>,
+ canonical_group: core::ops::Range<usize>,
+ resolve: impl Fn(TypeAddr) -> TypeAddr + Copy,
+) -> bool {
+ let type_addrs_equal = |ty: TypeAddr, registered: TypeAddr| {
+ module_group.contains(&(ty as usize)) == canonical_group.contains(&(registered as usize))
+ && resolve(ty) == registered
+ };
+ let values_equal = |ty: WasmType, registered: WasmType| match (ty, registered) {
+ (WasmType::Ref(ty), WasmType::Ref(registered)) if ty.is_concrete() => {
+ let ty_addr = ty.type_index().expect("concrete reference");
+ let Some(registered_addr) = registered.type_index() else { return false };
+ ty.is_nullable() == registered.is_nullable() && type_addrs_equal(ty_addr, registered_addr)
+ }
+ _ => ty == registered,
+ };
+ let fields_equal = |ty: FieldType, registered: FieldType| {
+ ty.mutable == registered.mutable
+ && match (ty.storage, registered.storage) {
+ (StorageType::Value(ty), StorageType::Value(registered)) => values_equal(ty, registered),
+ (ty, registered) => ty == registered,
+ }
+ };
+
+ let supertypes_equal = match (ty.supertype, registered.supertype) {
+ (Some(ty), Some(registered)) => type_addrs_equal(ty, registered),
+ (None, None) => true,
+ _ => false,
+ };
+ ty.is_final == registered.is_final
+ && supertypes_equal
+ && match (&ty.composite, &registered.composite) {
+ (CompositeType::Func(ty), CompositeType::Func(registered)) => {
+ ty.params().len() == registered.params().len()
+ && ty.results().len() == registered.results().len()
+ && ty
+ .params()
+ .iter()
+ .chain(ty.results())
+ .copied()
+ .zip(registered.params().iter().chain(registered.results()).copied())
+ .all(|(ty, registered)| values_equal(ty, registered))
+ }
+ (CompositeType::Struct(ty), CompositeType::Struct(registered)) => {
+ ty.fields.len() == registered.fields.len()
+ && ty
+ .fields
+ .iter()
+ .copied()
+ .zip(registered.fields.iter().copied())
+ .all(|(ty, registered)| fields_equal(ty, registered))
+ }
+ (CompositeType::Array(ty), CompositeType::Array(registered)) => fields_equal(ty.field, registered.field),
+ _ => false,
+ }
+}
+
+impl Store {
+ pub(crate) fn register_module_types(&mut self, section: &TypeSection) -> Box<[TypeAddr]> {
+ let mut type_addrs = Vec::with_capacity(section.types.len());
+ let mut module_group_start = 0usize;
+
+ for &group_len in &section.rec_group_lengths {
+ let group_len = group_len as usize;
+ let module_group_end = module_group_start.checked_add(group_len).expect("type group is too large");
+ let group = section
+ .types
+ .get(module_group_start..module_group_end)
+ .expect("validated recursive group length fits the type section");
+
+ let resolve = |module_addr: TypeAddr, canonical_group_start: usize| {
+ let module_addr = module_addr as usize;
+ if (module_group_start..module_group_end).contains(&module_addr) {
+ (canonical_group_start + module_addr - module_group_start) as TypeAddr
+ } else {
+ *type_addrs
+ .get(module_addr)
+ .expect("validated type reference targets the current or a prior recursive group")
+ }
+ };
+
+ let mut canonical_group_start = 0;
+ let mut matching_group = None;
+ for &canonical_group_len in &self.state.canonical_rec_group_lengths {
+ let canonical_group_len = canonical_group_len as usize;
+ if canonical_group_len == group_len
+ && group.iter().zip(&self.state.canonical_types[canonical_group_start..]).all(|(ty, registered)| {
+ subtypes_equal(
+ ty,
+ registered,
+ module_group_start..module_group_end,
+ canonical_group_start..canonical_group_start + canonical_group_len,
+ |addr| resolve(addr, canonical_group_start),
+ )
+ })
+ {
+ matching_group = Some(canonical_group_start);
+ break;
+ }
+ canonical_group_start += canonical_group_len;
+ }
+
+ let canonical_group_start = match matching_group {
+ Some(start) => start,
+ None => {
+ let start = self.state.canonical_types.len();
+ assert!(
+ start.checked_add(group_len).is_some_and(|end| end <= (1 << 30)),
+ "too many canonical types"
+ );
+ self.state
+ .canonical_types
+ .extend(group.iter().map(|ty| map_subtype(ty, |addr| resolve(addr, start))));
+ self.state.canonical_rec_group_lengths.push(group_len as u32);
+ start
+ }
+ };
+ type_addrs.extend((canonical_group_start..canonical_group_start + group_len).map(|addr| addr as TypeAddr));
+ module_group_start = module_group_end;
+ }
+ debug_assert_eq!(module_group_start, section.types.len());
+ type_addrs.into_boxed_slice()
+ }
+
+ pub(crate) fn register_host_type(&mut self, ty: &FuncType) -> TypeAddr {
+ let mut group_start = 0usize;
+ for &group_len in &self.state.canonical_rec_group_lengths {
+ if group_len == 1
+ && self.state.canonical_types[group_start].is_final
+ && self.state.canonical_types[group_start].supertype.is_none()
+ && self.state.canonical_types[group_start].as_func() == Some(ty)
+ {
+ return group_start as TypeAddr;
+ }
+ group_start += group_len as usize;
+ }
+ let addr = self.state.canonical_types.len();
+ assert!(addr < (1 << 30), "too many canonical types");
+ self.state.canonical_types.push(SubType {
+ is_final: true,
+ supertype: None,
+ composite: CompositeType::Func(ty.clone()),
+ });
+ self.state.canonical_rec_group_lengths.push(1);
+ addr as TypeAddr
+ }
+}
diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs
new file mode 100644
index 0000000..d3f2994
--- /dev/null
+++ b/crates/tinywasm/tests/gc_refs.rs
@@ -0,0 +1,120 @@
+use tinywasm::types::{ExternRef, RefValue, WasmValue};
+use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config};
+
+const MODULE: &str = r#"
+ (module
+ (type $node (struct (field i32)))
+ (type $bytes (array (mut i8)))
+ (func (export "new") (result anyref)
+ (struct.new $node (i32.const 42)))
+ (func (export "new-extern") (result externref)
+ (extern.convert_any (struct.new $node (i32.const 42))))
+ (func (export "read") (param anyref) (result i32)
+ (struct.get $node 0 (ref.cast (ref $node) (local.get 0))))
+ (func (export "read-extern") (param externref) (result i32)
+ (struct.get $node 0
+ (ref.cast (ref $node) (any.convert_extern (local.get 0)))))
+ (func (export "churn")
+ (local $i i32)
+ (loop $loop
+ (drop (array.new_default $bytes (i32.const 16)))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $loop (i32.lt_u (local.get $i) (i32.const 100)))))
+ )
+"#;
+
+fn store() -> Store {
+ Store::new(Engine::new(Config::new().with_gc_collection_threshold(1)))
+}
+
+#[test]
+fn host_result_is_pinned_and_rejected_by_another_store() {
+ let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap();
+ let mut first_store = store();
+ let first = ModuleInstance::instantiate(&mut first_store, &module, None).unwrap();
+ let new = first.func_untyped(&first_store, "new").unwrap();
+ let read = first.func_untyped(&first_store, "read").unwrap();
+ let churn = first.func_untyped(&first_store, "churn").unwrap();
+
+ let value = new.call(&mut first_store, &[]).unwrap().pop().unwrap();
+ assert!(matches!(value, WasmValue::Ref(RefValue::Any(_))));
+ churn.call(&mut first_store, &[]).unwrap();
+ assert_eq!(read.call(&mut first_store, &[value]).unwrap(), [WasmValue::I32(42)]);
+
+ let mut second_store = store();
+ let second = ModuleInstance::instantiate(&mut second_store, &module, None).unwrap();
+ let other_read = second.func_untyped(&second_store, "read").unwrap();
+ assert!(other_read.call(&mut second_store, &[value]).is_err());
+}
+
+#[test]
+fn externalized_gc_result_is_pinned() {
+ let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap();
+ let mut store = store();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap();
+ let new = instance.func_untyped(&store, "new-extern").unwrap();
+ let read = instance.func_untyped(&store, "read-extern").unwrap();
+ let churn = instance.func_untyped(&store, "churn").unwrap();
+
+ let value = new.call(&mut store, &[]).unwrap().pop().unwrap();
+ assert!(matches!(value, WasmValue::Ref(RefValue::Extern(_))));
+ churn.call(&mut store, &[]).unwrap();
+ assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]);
+}
+
+#[test]
+fn host_externref_does_not_alias_a_gc_object() {
+ let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap();
+ let mut store = store();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap();
+ let new = instance.func_untyped(&store, "new").unwrap();
+ let read = instance.func_untyped(&store, "read-extern").unwrap();
+
+ new.call(&mut store, &[]).unwrap();
+ let host_ref = WasmValue::Ref(RefValue::Extern(ExternRef::new(0)));
+ assert!(read.call(&mut store, &[host_ref]).is_err());
+}
+
+#[test]
+fn resumable_gc_result_is_pinned() {
+ let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap();
+ let mut store = store();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap();
+ let new = instance.func_untyped(&store, "new").unwrap();
+ let read = instance.func_untyped(&store, "read").unwrap();
+ let churn = instance.func_untyped(&store, "churn").unwrap();
+
+ let mut execution = new.call_resumable(&mut store, &[]).unwrap();
+ let value = match execution.resume_with_fuel(1000).unwrap() {
+ ExecProgress::Completed(mut values) => values.pop().unwrap(),
+ ExecProgress::Suspended => panic!("constructor unexpectedly suspended"),
+ };
+ drop(execution);
+
+ churn.call(&mut store, &[]).unwrap();
+ assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]);
+}
+
+#[test]
+fn element_initializers_root_previous_gc_values() {
+ let module = tinywasm::parse_bytes(
+ &wat::parse_str(
+ r#"
+ (module
+ (type $node (struct (field i32)))
+ (table 2 (ref null $node))
+ (elem (i32.const 0) (ref $node)
+ (struct.new $node (i32.const 1))
+ (struct.new $node (i32.const 2)))
+ (func (export "first") (result i32)
+ (struct.get $node 0 (table.get 0 (i32.const 0)))))
+ "#,
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let mut store = store();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap();
+
+ assert_eq!(instance.func_untyped(&store, "first").unwrap().call(&mut store, &[]).unwrap(), [WasmValue::I32(1)]);
+}
diff --git a/crates/tinywasm/tests/generated/wasm-2.csv b/crates/tinywasm/tests/generated/wasm-2.csv
index c2472a7..645f0d5 100644
--- a/crates/tinywasm/tests/generated/wasm-2.csv
+++ b/crates/tinywasm/tests/generated/wasm-2.csv
@@ -13,4 +13,4 @@
0.9.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
0.9.1,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
0.10.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
-0.11.0-pre.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
+0.11.0-pre.0,28002,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":96,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-3.csv b/crates/tinywasm/tests/generated/wasm-3.csv
index 9403d27..7d3961c 100644
--- a/crates/tinywasm/tests/generated/wasm-3.csv
+++ b/crates/tinywasm/tests/generated/wasm-3.csv
@@ -1,3 +1,3 @@
0.9.0,20776,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
0.10.0,20778,450,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
-0.11.0-pre.0,21107,121,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":19,"failed":13},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
+0.11.0-pre.0,21151,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-extended-const.csv b/crates/tinywasm/tests/generated/wasm-extended-const.csv
index 8677772..1e4e851 100644
--- a/crates/tinywasm/tests/generated/wasm-extended-const.csv
+++ b/crates/tinywasm/tests/generated/wasm-extended-const.csv
@@ -2,4 +2,4 @@
0.9.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
0.9.1,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
0.10.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
-0.11.0-pre.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}]
+0.11.0-pre.0,284,0,[{"name":"data.wast","passed":63,"failed":0},{"name":"elem.wast","passed":109,"failed":0},{"name":"global.wast","passed":112,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-function-references.csv b/crates/tinywasm/tests/generated/wasm-function-references.csv
index 3e59535..9d6dd64 100644
--- a/crates/tinywasm/tests/generated/wasm-function-references.csv
+++ b/crates/tinywasm/tests/generated/wasm-function-references.csv
@@ -1,3 +1,3 @@
0.9.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}]
0.10.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}]
-0.11.0-pre.0,1867,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":14,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}]
+0.11.0-pre.0,1866,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":13,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-gc.csv b/crates/tinywasm/tests/generated/wasm-gc.csv
index 5b2995f..ea39c56 100644
--- a/crates/tinywasm/tests/generated/wasm-gc.csv
+++ b/crates/tinywasm/tests/generated/wasm-gc.csv
@@ -1,2 +1,3 @@
0.9.0,80,703,[{"name":"array.wast","passed":6,"failed":48},{"name":"array_copy.wast","passed":4,"failed":31},{"name":"array_fill.wast","passed":3,"failed":27},{"name":"array_init_data.wast","passed":2,"failed":44},{"name":"array_init_elem.wast","passed":3,"failed":33},{"name":"array_new_data.wast","passed":0,"failed":28},{"name":"array_new_elem.wast","passed":0,"failed":24},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":6,"failed":31},{"name":"br_on_cast_fail.wast","passed":6,"failed":31},{"name":"extern.wast","passed":0,"failed":18},{"name":"i31.wast","passed":2,"failed":71},{"name":"ref_cast.wast","passed":0,"failed":45},{"name":"ref_eq.wast","passed":6,"failed":83},{"name":"ref_test.wast","passed":0,"failed":71},{"name":"struct.wast","passed":5,"failed":25},{"name":"type-subtyping.wast","passed":36,"failed":93}]
0.10.0,80,704,[{"name":"array.wast","passed":6,"failed":48},{"name":"array_copy.wast","passed":4,"failed":31},{"name":"array_fill.wast","passed":3,"failed":27},{"name":"array_init_data.wast","passed":2,"failed":44},{"name":"array_init_elem.wast","passed":3,"failed":33},{"name":"array_new_data.wast","passed":0,"failed":28},{"name":"array_new_elem.wast","passed":0,"failed":24},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":6,"failed":31},{"name":"br_on_cast_fail.wast","passed":6,"failed":31},{"name":"extern.wast","passed":0,"failed":18},{"name":"i31.wast","passed":2,"failed":71},{"name":"ref_cast.wast","passed":0,"failed":45},{"name":"ref_eq.wast","passed":6,"failed":83},{"name":"ref_test.wast","passed":0,"failed":71},{"name":"struct.wast","passed":5,"failed":25},{"name":"type-subtyping.wast","passed":36,"failed":94}]
+0.11.0-pre.0,784,0,[{"name":"array.wast","passed":54,"failed":0},{"name":"array_copy.wast","passed":35,"failed":0},{"name":"array_fill.wast","passed":30,"failed":0},{"name":"array_init_data.wast","passed":46,"failed":0},{"name":"array_init_elem.wast","passed":36,"failed":0},{"name":"array_new_data.wast","passed":28,"failed":0},{"name":"array_new_elem.wast","passed":24,"failed":0},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":37,"failed":0},{"name":"br_on_cast_fail.wast","passed":37,"failed":0},{"name":"extern.wast","passed":18,"failed":0},{"name":"i31.wast","passed":73,"failed":0},{"name":"ref_cast.wast","passed":45,"failed":0},{"name":"ref_eq.wast","passed":89,"failed":0},{"name":"ref_test.wast","passed":71,"failed":0},{"name":"struct.wast","passed":30,"failed":0},{"name":"type-subtyping.wast","passed":130,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-latest.csv b/crates/tinywasm/tests/generated/wasm-latest.csv
index ef7e1a2..94a8b58 100644
--- a/crates/tinywasm/tests/generated/wasm-latest.csv
+++ b/crates/tinywasm/tests/generated/wasm-latest.csv
@@ -1,2 +1,3 @@
0.9.0,20777,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
0.10.0,20697,536,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":14,"failed":35},{"name":"return_call_indirect.wast","passed":30,"failed":51},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
+0.11.0-pre.0,21156,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-threads.csv b/crates/tinywasm/tests/generated/wasm-threads.csv
index f588c66..25d09b7 100644
--- a/crates/tinywasm/tests/generated/wasm-threads.csv
+++ b/crates/tinywasm/tests/generated/wasm-threads.csv
@@ -1,2 +1,3 @@
0.9.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}]
0.10.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}]
+0.11.0-pre.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}]
diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs
index 7a68f01..04279cc 100644
--- a/crates/tinywasm/tests/internal_refs.rs
+++ b/crates/tinywasm/tests/internal_refs.rs
@@ -149,8 +149,13 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<()
let module = tinywasm::parse_bytes(&wasm)?;
let export = module.exports.iter().find(|export| export.name.as_ref() == "f").expect("export f not found");
- let old_lookup_ty = module.func_types.get(export.index as usize).expect("old lookup type missing");
- let func_ty = &module.func_types[module.func_type_idxs[export.index as usize] as usize];
+ let old_lookup_ty = module.types.get(export.index).and_then(|ty| ty.as_func()).expect("old lookup type missing");
+ let func_ty = module
+ .types
+ .get(module.func_type_idxs[export.index as usize])
+ .expect("export function type index should exist")
+ .as_func()
+ .expect("export function should reference a function type");
assert_eq!(old_lookup_ty.params(), &[tinywasm::types::WasmType::I64]);
assert_eq!(func_ty.params(), &[]);
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index 99238ab..9904a7d 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -7,7 +7,7 @@ use crate::Module;
#[rustfmt::skip]
const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS";
-const TWASM_VERSION: &[u8; 2] = b"04";
+const TWASM_VERSION: &[u8; 2] = b"05";
fn validate_magic(wasm: &[u8]) -> Result<usize, TwasmError> {
if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX {
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index a53576e..1160fa5 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -54,6 +54,14 @@ pub enum ConstInstruction {
V128Const([u8; 16]),
GlobalGet(GlobalAddr),
Ref(RefValue),
+ RefI31,
+ AnyConvertExtern,
+ ExternConvertAny,
+ StructNew(TypeAddr),
+ StructNewDefault(TypeAddr),
+ ArrayNew(TypeAddr),
+ ArrayNewDefault(TypeAddr),
+ ArrayNewFixed(TypeAddr, u32),
I32Add,
I32Sub,
I32Mul,
@@ -272,6 +280,35 @@ pub enum Instruction {
RefFunc(FuncAddr),
RefIsNull,
RefAsNonNull,
+ RefI31,
+ I31GetS,
+ I31GetU,
+ RefEq,
+ RefTest(RefType),
+ RefCast(RefType),
+ BrOnCast(u32, RefType, bool),
+
+ // > GC Objects
+ StructNew(TypeAddr),
+ StructNewDefault(TypeAddr),
+ StructGet(TypeAddr, u32),
+ StructGetS(TypeAddr, u32),
+ StructGetU(TypeAddr, u32),
+ StructSet(TypeAddr, u32),
+ ArrayNew(TypeAddr),
+ ArrayNewDefault(TypeAddr),
+ ArrayNewFixed(TypeAddr, u32),
+ ArrayNewData(TypeAddr, DataAddr),
+ ArrayNewElem(TypeAddr, ElemAddr),
+ ArrayGet(TypeAddr),
+ ArrayGetS(TypeAddr),
+ ArrayGetU(TypeAddr),
+ ArraySet(TypeAddr),
+ ArrayLen,
+ ArrayFill(TypeAddr),
+ ArrayCopy(TypeAddr, TypeAddr),
+ ArrayInitData(TypeAddr, DataAddr),
+ ArrayInitElem(TypeAddr, ElemAddr),
// > Numeric Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions>
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index 0b15927..c461296 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -22,9 +22,11 @@ const fn max_page_count(page_size: u64) -> u64 {
mod instructions;
mod reference;
+mod types;
mod value;
pub use instructions::*;
pub use reference::*;
+pub use types::*;
pub use value::*;
#[cfg(feature = "archive")]
@@ -81,10 +83,10 @@ pub struct ModuleInner {
/// Contains data from to the `code`, `func`, and `type` sections of the original WebAssembly module.
pub funcs: Box<[Arc<WasmFunction>]>,
- /// A vector of type definitions, indexed by `TypeAddr`
+ /// The dense type definitions, indexed by `TypeAddr`.
///
/// Corresponds to the `type` section of the original WebAssembly module.
- pub func_types: Box<[FuncType]>,
+ pub types: TypeSection,
/// Function index to type index mapping in module index space, including imports.
pub func_type_idxs: Box<[TypeAddr]>,
@@ -135,7 +137,7 @@ impl Module {
pub fn imports(&self) -> impl Iterator<Item = ModuleImport<'_>> {
self.0.imports.iter().filter_map(|import| {
let ty = match &import.kind {
- ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.func_types.get(*type_idx as usize)?)),
+ ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.types.get(*type_idx)?.as_func()?)),
ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)),
ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)),
ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)),
@@ -178,7 +180,7 @@ impl Module {
let import = imports.nth(index)?;
match &import.kind {
- ImportKind::Function(type_idx) => Some(ExportType::Func(module.func_types.get(*type_idx as usize)?)),
+ ImportKind::Function(type_idx) => Some(ExportType::Func(module.types.get(*type_idx)?.as_func()?)),
ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)),
ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)),
ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)),
@@ -194,7 +196,7 @@ impl Module {
imported_type(&self.0, ExternalKind::Func, idx)?
} else {
let type_idx = *self.0.func_type_idxs.get(idx)?;
- ExportType::Func(self.0.func_types.get(type_idx as usize)?)
+ ExportType::Func(self.0.types.get(type_idx)?.as_func()?)
}
}
ExternalKind::Table => {
@@ -360,90 +362,6 @@ impl ExternVal {
}
}
-/// The type of a WebAssembly Function.
-///
-/// See <https://webassembly.github.io/spec/core/syntax/types.html#function-types>
-#[derive(Clone, PartialEq, Eq, Default)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct FuncType {
- data: Box<[WasmType]>,
- param_count: u16,
-}
-
-impl FuncType {
- /// Create a new function type.
- pub fn new(params: &[WasmType], results: &[WasmType]) -> Self {
- let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect();
- Self { data, param_count: params.len() as u16 }
- }
-
- /// Get the parameter types of this function type.
- pub fn params(&self) -> &[WasmType] {
- &self.data[..self.param_count as usize]
- }
-
- /// Get the result types of this function type.
- pub fn results(&self) -> &[WasmType] {
- &self.data[self.param_count as usize..]
- }
-
- /// Compare function types while resolving concrete references in their respective type spaces.
- pub fn equivalent(&self, types: &[FuncType], other: &Self, other_types: &[FuncType]) -> bool {
- fn refs_equal(
- left_types: &[FuncType],
- left: RefType,
- right_types: &[FuncType],
- right: RefType,
- visited: &mut alloc::vec::Vec<(u32, u32)>,
- ) -> bool {
- if left.is_nullable() != right.is_nullable() {
- return false;
- }
- match (left.type_index(), right.type_index()) {
- (Some(left_idx), Some(right_idx)) => {
- if visited.contains(&(left_idx, right_idx)) {
- return true;
- }
- let (Some(left), Some(right)) =
- (left_types.get(left_idx as usize), right_types.get(right_idx as usize))
- else {
- return false;
- };
- visited.push((left_idx, right_idx));
- funcs_equal(left, left_types, right, right_types, visited)
- }
- (None, None) => left.abstract_heap_type() == right.abstract_heap_type(),
- _ => false,
- }
- }
-
- fn funcs_equal(
- left: &FuncType,
- left_types: &[FuncType],
- right: &FuncType,
- right_types: &[FuncType],
- visited: &mut alloc::vec::Vec<(u32, u32)>,
- ) -> bool {
- left.params().len() == right.params().len()
- && left.results().len() == right.results().len()
- && left.params().iter().chain(left.results()).zip(right.params().iter().chain(right.results())).all(
- |(&left, &right)| match (left, right) {
- (WasmType::Ref(left), WasmType::Ref(right)) => {
- refs_equal(left_types, left, right_types, right, visited)
- }
- _ => left == right,
- },
- )
- }
-
- if core::ptr::eq(types, other_types) && self == other {
- return true;
- }
- funcs_equal(self, types, other, other_types, &mut alloc::vec::Vec::new())
- }
-}
-
#[derive(Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
index ee66965..884d330 100644
--- a/crates/types/src/reference.rs
+++ b/crates/types/src/reference.rs
@@ -1,3 +1,12 @@
+const HOST_REF_TAG: u32 = 1 << 30;
+
+const fn encode_host_ref(addr: u32) -> Option<u32> {
+ if addr >= HOST_REF_TAG - 1 {
+ return None;
+ }
+ Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2))
+}
+
/// An abstract WebAssembly heap type.
///
/// This contains exactly the abstract heap types in core Wasm 3.0.
@@ -31,7 +40,8 @@ pub enum AbstractHeapType {
/// [nullable:1 concrete:1 payload:30]
/// ```
///
-/// For concrete types, `payload` is a module type index.
+/// For concrete types, `payload` is a module type index before instantiation
+/// and a canonical store type address at runtime.
/// Otherwise, it is an [`AbstractHeapType`].
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -116,9 +126,7 @@ impl RefType {
#[inline]
pub const fn is_func(self) -> bool {
- // TODO(wasm3): Classify concrete refs from the module type definition once GC types are represented.
- self.is_concrete()
- || matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc))
+ matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc))
}
#[inline]
@@ -132,6 +140,7 @@ impl RefType {
}
}
+/// A host-facing WebAssembly reference value.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -143,19 +152,9 @@ pub enum RefValue {
Exn(ExnRef),
}
-impl RefValue {
- /// Return the reference's raw representation, or `None` for null.
- pub const fn raw(self) -> Option<u32> {
- match self {
- Self::Null => None,
- Self::Func(value) => Some(value.addr()),
- Self::Extern(value) => Some(value.addr()),
- Self::Any(value) => Some(value.raw()),
- Self::Exn(value) => Some(value.addr()),
- }
- }
-}
-
+/// A reference to a function in a store.
+///
+/// The payload is the function's store-local address.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -173,6 +172,11 @@ impl FuncRef {
}
}
+/// An opaque external reference.
+///
+/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload
+/// category, Store-managed objects use the lower category, and odd values
+/// contain an externalized i31.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -181,15 +185,35 @@ pub struct ExternRef(u32);
impl ExternRef {
#[inline]
pub const fn new(addr: u32) -> Self {
- Self(addr)
+ let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") };
+ value
}
+ /// Creates an external reference when `addr` fits the runtime encoding.
#[inline]
- pub const fn addr(self) -> u32 {
+ pub const fn try_new(addr: u32) -> Option<Self> {
+ match encode_host_ref(addr) {
+ Some(raw) => Some(Self(raw)),
+ None => None,
+ }
+ }
+
+ #[doc(hidden)]
+ #[inline]
+ pub const fn from_raw(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ #[doc(hidden)]
+ #[inline]
+ pub const fn raw(self) -> u32 {
self.0
}
}
+/// A reference to an exception in a store.
+///
+/// The payload is the exception's store-local address.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -207,14 +231,30 @@ impl ExnRef {
}
}
+/// A WebAssembly `anyref` value.
+///
+/// Packed as:
+///
+/// ```text
+/// [payload:31 i31:1]
+/// ```
+///
+/// Odd values contain an inline signed i31. Non-zero even values are reserved
+/// for store-managed references, and zero is reserved for null by the runtime.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct AnyRef(u32);
impl AnyRef {
- // Odd values are inline i31s.
- // Even values are GC object handles.
+ /// Creates a host reference when `addr` fits the runtime encoding.
+ #[inline]
+ pub const fn from_host(addr: u32) -> Option<Self> {
+ match encode_host_ref(addr) {
+ Some(raw) => Some(Self(raw)),
+ None => None,
+ }
+ }
#[doc(hidden)]
#[inline]
@@ -234,22 +274,21 @@ impl AnyRef {
if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None }
}
- pub const fn from_gc_addr(addr: u32) -> Option<Self> {
- match addr.checked_add(1) {
- Some(raw) => match raw.checked_mul(2) {
- Some(raw) => Some(Self(raw)),
- None => None,
- },
- None => None,
- }
- }
-
- pub const fn gc_addr(self) -> Option<u32> {
- if self.0 != 0 && self.0 & 1 == 0 { Some(self.0 / 2 - 1) } else { None }
- }
-
#[inline]
pub const fn raw(self) -> u32 {
self.0
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn host_reference_encoding_is_checked_and_unique() {
+ assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1));
+ assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some());
+ assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none());
+ assert!(ExternRef::try_new(u32::MAX).is_none());
+ }
+}
diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs
new file mode 100644
index 0000000..214ada6
--- /dev/null
+++ b/crates/types/src/types.rs
@@ -0,0 +1,158 @@
+use alloc::boxed::Box;
+
+use crate::{TypeAddr, WasmType};
+
+/// The dense type index space of a WebAssembly module.
+#[derive(Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct TypeSection {
+ /// Types in module index order.
+ pub types: Box<[SubType]>,
+ /// Number of types in each recursive group, in section order.
+ pub rec_group_lengths: Box<[u32]>,
+}
+
+impl TypeSection {
+ #[inline]
+ pub fn get(&self, index: TypeAddr) -> Option<&SubType> {
+ self.types.get(index as usize)
+ }
+
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.types.len()
+ }
+
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.types.is_empty()
+ }
+}
+
+/// A type with optional declared subtyping.
+#[derive(Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct SubType {
+ pub is_final: bool,
+ pub supertype: Option<TypeAddr>,
+ pub composite: CompositeType,
+}
+
+impl SubType {
+ #[inline]
+ pub const fn as_func(&self) -> Option<&FuncType> {
+ self.composite.as_func()
+ }
+
+ #[inline]
+ pub const fn as_struct(&self) -> Option<&StructType> {
+ self.composite.as_struct()
+ }
+
+ #[inline]
+ pub const fn as_array(&self) -> Option<&ArrayType> {
+ self.composite.as_array()
+ }
+}
+
+/// A function, struct, or array type.
+#[derive(Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub enum CompositeType {
+ Func(FuncType),
+ Struct(StructType),
+ Array(ArrayType),
+}
+
+impl CompositeType {
+ #[inline]
+ pub const fn as_func(&self) -> Option<&FuncType> {
+ match self {
+ Self::Func(ty) => Some(ty),
+ _ => None,
+ }
+ }
+
+ #[inline]
+ pub const fn as_struct(&self) -> Option<&StructType> {
+ match self {
+ Self::Struct(ty) => Some(ty),
+ _ => None,
+ }
+ }
+
+ #[inline]
+ pub const fn as_array(&self) -> Option<&ArrayType> {
+ match self {
+ Self::Array(ty) => Some(ty),
+ _ => None,
+ }
+ }
+}
+
+/// The type of a WebAssembly function.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#function-types>
+#[derive(Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct FuncType {
+ data: Box<[WasmType]>,
+ param_count: u16,
+}
+
+impl FuncType {
+ /// Create a new function type.
+ pub fn new(params: &[WasmType], results: &[WasmType]) -> Self {
+ let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect();
+ Self { data, param_count: params.len() as u16 }
+ }
+
+ /// Get the parameter types of this function type.
+ pub fn params(&self) -> &[WasmType] {
+ &self.data[..self.param_count as usize]
+ }
+
+ /// Get the result types of this function type.
+ pub fn results(&self) -> &[WasmType] {
+ &self.data[self.param_count as usize..]
+ }
+}
+
+/// A WebAssembly struct type.
+#[derive(Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct StructType {
+ pub fields: Box<[FieldType]>,
+}
+
+/// A WebAssembly array type.
+#[derive(Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct ArrayType {
+ pub field: FieldType,
+}
+
+/// A struct field or array element type.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct FieldType {
+ pub storage: StorageType,
+ pub mutable: bool,
+}
+
+/// A field's packed or unpacked storage type.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub enum StorageType {
+ I8,
+ I16,
+ Value(WasmType),
+}
diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs
index 92c660b..f0a576b 100644
--- a/crates/types/src/value.rs
+++ b/crates/types/src/value.rs
@@ -54,7 +54,7 @@ impl WasmValue {
| (Self::V128(_), WasmType::V128) => true,
(Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(),
(Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => {
- ty.is_concrete() || matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func))
+ matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func))
}
(Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => {
matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern))
@@ -62,12 +62,42 @@ impl WasmValue {
(Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => {
matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn))
}
- (Self::Ref(RefValue::Any(_)), WasmType::Ref(ty)) => !ty.is_func() && !ty.is_extern() && !ty.is_exn(),
+ (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => matches!(
+ (value.as_i31(), ty.abstract_heap_type()),
+ (
+ Some(_),
+ Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any)
+ ) | (None, Some(crate::AbstractHeapType::Any))
+ ),
_ => false,
}
}
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{AbstractHeapType, AnyRef, FuncRef, RefType};
+
+ #[test]
+ fn concrete_references_require_store_type_information() {
+ let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap());
+
+ assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete));
+ assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete));
+ }
+
+ #[test]
+ fn i31_only_matches_its_store_independent_supertypes() {
+ let value = WasmValue::from(AnyRef::from_i31(0).unwrap());
+
+ for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] {
+ assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty))));
+ }
+ assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct))));
+ }
+}
+
impl Debug for WasmValue {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {