summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
committerMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
commit264ea48cc8c6dd9c3c9e0fe1a559252863fc9962 (patch)
tree84a4a58de14442f4fcfa06bd0d82480508f82759
parent7877eca4e8be283e7c51168ee3a3b05d9000f39c (diff)
parentb45a98a85c776d956a797773acd2f198c06b40ed (diff)
Merge branch 'main' into bota-tortuise
-rw-r--r--.github/workflows/audit.yaml46
-rw-r--r--.github/workflows/test.yaml15
-rw-r--r--ARCHITECTURE.md62
-rw-r--r--CHANGELOG.md69
-rw-r--r--CODE_OF_CONDUCT.md60
-rw-r--r--CONTRIBUTING.md74
-rw-r--r--Cargo.lock487
-rw-r--r--Cargo.toml65
-rw-r--r--README.md96
-rw-r--r--benches/argon2id.rs (renamed from crates/tinywasm/benches/argon2id.rs)7
-rw-r--r--benches/fibonacci.rs (renamed from crates/tinywasm/benches/fibonacci.rs)9
-rw-r--r--benches/tinywasm.rs (renamed from crates/tinywasm/benches/tinywasm.rs)13
-rw-r--r--benches/tinywasm_modes.rs (renamed from crates/tinywasm/benches/tinywasm_modes.rs)13
-rw-r--r--crates/cli/Cargo.toml18
-rw-r--r--crates/cli/src/bin.rs2
-rw-r--r--crates/cli/src/cmd/compile.rs2
-rw-r--r--crates/cli/src/cmd/completion.rs2
-rw-r--r--crates/cli/src/cmd/dump.rs2
-rw-r--r--crates/cli/src/cmd/inspect.rs2
-rw-r--r--crates/cli/src/cmd/run.rs13
-rw-r--r--crates/cli/src/cmd/wast.rs2
-rw-r--r--crates/cli/src/engine_flags.rs36
-rw-r--r--crates/cli/src/lib.rs4
-rw-r--r--crates/cli/src/load.rs2
-rw-r--r--crates/cli/src/output.rs4
-rw-r--r--crates/cli/src/testsuite.rs (renamed from crates/tinywasm/tests/testsuite/mod.rs)53
-rw-r--r--crates/cli/src/value_parse.rs6
-rw-r--r--crates/cli/src/wast_runner.rs517
-rw-r--r--crates/parser/Cargo.toml21
-rw-r--r--crates/parser/README.md9
-rw-r--r--crates/parser/src/conversion.rs318
-rw-r--r--crates/parser/src/emitter.rs355
-rw-r--r--crates/parser/src/error.rs2
-rw-r--r--crates/parser/src/lib.rs179
-rw-r--r--crates/parser/src/macros.rs304
-rw-r--r--crates/parser/src/module.rs282
-rw-r--r--crates/parser/src/optimize.rs984
-rw-r--r--crates/parser/src/parallel.rs67
-rw-r--r--crates/parser/src/selection.rs314
-rw-r--r--crates/parser/src/selection/encoding.rs293
-rw-r--r--crates/parser/src/validation.rs15
-rw-r--r--crates/parser/src/visit.rs1380
-rw-r--r--crates/tinywasm/Cargo.toml104
-rw-r--r--crates/tinywasm/benches/memory_backends.rs152
-rw-r--r--crates/tinywasm/src/engine.rs90
-rw-r--r--crates/tinywasm/src/error.rs57
-rw-r--r--crates/tinywasm/src/func.rs856
-rw-r--r--crates/tinywasm/src/func/context.rs154
-rw-r--r--crates/tinywasm/src/func/host.rs300
-rw-r--r--crates/tinywasm/src/func/mod.rs256
-rw-r--r--crates/tinywasm/src/func/resume.rs280
-rw-r--r--crates/tinywasm/src/func/values.rs155
-rw-r--r--crates/tinywasm/src/imports.rs288
-rw-r--r--crates/tinywasm/src/instance.rs226
-rw-r--r--crates/tinywasm/src/interpreter/executor.rs1696
-rw-r--r--crates/tinywasm/src/interpreter/executor/dispatch.rs90
-rw-r--r--crates/tinywasm/src/interpreter/executor/dispatch_become.rs191
-rw-r--r--crates/tinywasm/src/interpreter/executor/instructions.rs690
-rw-r--r--crates/tinywasm/src/interpreter/executor/mod.rs1561
-rw-r--r--crates/tinywasm/src/interpreter/mod.rs14
-rw-r--r--crates/tinywasm/src/interpreter/num_helpers.rs39
-rw-r--r--crates/tinywasm/src/interpreter/simd/instructions.rs288
-rw-r--r--crates/tinywasm/src/interpreter/simd/macros.rs37
-rw-r--r--crates/tinywasm/src/interpreter/simd/mod.rs27
-rw-r--r--crates/tinywasm/src/interpreter/simd/tests.rs60
-rw-r--r--crates/tinywasm/src/interpreter/simd/utils.rs2
-rw-r--r--crates/tinywasm/src/interpreter/stack/call_stack.rs34
-rw-r--r--crates/tinywasm/src/interpreter/stack/value_stack.rs165
-rw-r--r--crates/tinywasm/src/interpreter/values.rs424
-rw-r--r--crates/tinywasm/src/lib.rs83
-rw-r--r--crates/tinywasm/src/macros.rs18
-rw-r--r--crates/tinywasm/src/reference.rs482
-rw-r--r--crates/tinywasm/src/reference/managed.rs219
-rw-r--r--crates/tinywasm/src/reference/mod.rs13
-rw-r--r--crates/tinywasm/src/reference/store.rs936
-rw-r--r--crates/tinywasm/src/reference/value.rs232
-rw-r--r--crates/tinywasm/src/shared.rs9
-rw-r--r--crates/tinywasm/src/store/const_expr.rs237
-rw-r--r--crates/tinywasm/src/store/data.rs4
-rw-r--r--crates/tinywasm/src/store/element.rs15
-rw-r--r--crates/tinywasm/src/store/function.rs96
-rw-r--r--crates/tinywasm/src/store/gc/arena.rs281
-rw-r--r--crates/tinywasm/src/store/gc/mod.rs102
-rw-r--r--crates/tinywasm/src/store/gc/object.rs286
-rw-r--r--crates/tinywasm/src/store/gc/roots.rs59
-rw-r--r--crates/tinywasm/src/store/global.rs157
-rw-r--r--crates/tinywasm/src/store/memory/instance.rs198
-rw-r--r--crates/tinywasm/src/store/memory/lazy.rs125
-rw-r--r--crates/tinywasm/src/store/memory/mod.rs255
-rw-r--r--crates/tinywasm/src/store/memory/paged.rs344
-rw-r--r--crates/tinywasm/src/store/memory/vec.rs213
-rw-r--r--crates/tinywasm/src/store/mod.rs1029
-rw-r--r--crates/tinywasm/src/store/state.rs386
-rw-r--r--crates/tinywasm/src/store/table.rs187
-rw-r--r--crates/tinywasm/src/store/tag.rs7
-rw-r--r--crates/tinywasm/src/store/types.rs211
-rw-r--r--crates/tinywasm/tests/branch_target_local_tee.rs77
-rw-r--r--crates/tinywasm/tests/gc_refs.rs135
-rw-r--r--crates/tinywasm/tests/generated/wasm-1.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-2.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-3.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-annotations.csv5
-rw-r--r--crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-extended-const.csv5
-rw-r--r--crates/tinywasm/tests/generated/wasm-function-references.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-gc.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-latest.csv2
-rw-r--r--crates/tinywasm/tests/generated/wasm-memory64.csv3
-rw-r--r--crates/tinywasm/tests/generated/wasm-multi-memory.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-reference-types.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-relaxed-simd.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-simd.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-tail-call.csv4
-rw-r--r--crates/tinywasm/tests/generated/wasm-threads.csv1
-rw-r--r--crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv1
-rw-r--r--crates/tinywasm/tests/host_func_signature_check.rs212
-rw-r--r--crates/tinywasm/tests/host_import_arg_order.rs17
-rw-r--r--crates/tinywasm/tests/host_reentrancy.rs109
-rw-r--r--crates/tinywasm/tests/import_linking.rs11
-rw-r--r--crates/tinywasm/tests/imported_table_init.rs12
-rw-r--r--crates/tinywasm/tests/internal_refs.rs70
-rw-r--r--crates/tinywasm/tests/managed_exceptions.rs141
-rw-r--r--crates/tinywasm/tests/memory.rs202
-rw-r--r--crates/tinywasm/tests/memory_backends.rs262
-rw-r--r--crates/tinywasm/tests/memory_ref_api.rs16
-rw-r--r--crates/tinywasm/tests/module_descriptors.rs8
-rw-r--r--crates/tinywasm/tests/reference_roots.rs104
-rw-r--r--crates/tinywasm/tests/resume_execution.rs21
-rw-r--r--crates/tinywasm/tests/start_function.rs3
-rw-r--r--crates/tinywasm/tests/store_ownership.rs33
-rw-r--r--crates/tinywasm/tests/store_state.rs36
-rw-r--r--crates/tinywasm/tests/test-wasm-1.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-2.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-3.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-annotations.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-custom-page-sizes.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-custom.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-extended-const.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-function-references.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-gc.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-latest.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-memory64.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-multi-memory.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs14
-rw-r--r--crates/tinywasm/tests/test-wasm-reference-types.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-relaxed-simd.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-sign-extension-op.rs13
-rw-r--r--crates/tinywasm/tests/test-wasm-simd.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-tail-call.rs14
-rw-r--r--crates/tinywasm/tests/test-wasm-threads.rs6
-rw-r--r--crates/tinywasm/tests/test-wasm-wide-arithmetic.rs6
-rw-r--r--crates/tinywasm/tests/test-wast.rs23
-rw-r--r--crates/tinywasm/tests/typed_gc_access.rs49
-rw-r--r--crates/tinywasm/tests/typed_globals.rs94
-rw-r--r--crates/tinywasm/tests/typed_lookup.rs5
-rw-r--r--crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast35
-rw-r--r--crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast104
-rw-r--r--crates/tinywasm/tests/wasm-custom/memory64-bulk.wast74
-rw-r--r--crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast59
-rw-r--r--crates/tinywasm/tests/wasm-custom/simd-stack-local.wast53
-rw-r--r--crates/tinywasm/tests/wasm-custom/table-basics.wast32
-rw-r--r--crates/types/Cargo.toml22
-rw-r--r--crates/types/src/archive.rs63
-rw-r--r--crates/types/src/instructions.rs802
-rw-r--r--crates/types/src/lib.rs302
-rw-r--r--crates/types/src/operands.rs342
-rw-r--r--crates/types/src/reference.rs155
-rw-r--r--crates/types/src/types.rs182
-rw-r--r--crates/types/src/value.rs314
-rw-r--r--crates/wasi/Cargo.toml25
-rw-r--r--crates/wasi/README.md10
-rw-r--r--crates/wasi/src/lib.rs4
-rw-r--r--crates/wasi/src/p1/abi.rs300
-rw-r--r--crates/wasi/src/p1/ctx.rs293
-rw-r--r--crates/wasi/src/p1/imports/clock.rs28
-rw-r--r--crates/wasi/src/p1/imports/command.rs72
-rw-r--r--crates/wasi/src/p1/imports/fd.rs423
-rw-r--r--crates/wasi/src/p1/imports/mod.rs101
-rw-r--r--crates/wasi/src/p1/imports/path.rs258
-rw-r--r--crates/wasi/src/p1/imports/poll.rs219
-rw-r--r--crates/wasi/src/p1/imports/process.rs20
-rw-r--r--crates/wasi/src/p1/imports/random.rs25
-rw-r--r--crates/wasi/src/p1/imports/sock.rs124
-rw-r--r--crates/wasi/src/p1/memory.rs115
-rw-r--r--crates/wasi/src/p1/mod.rs22
-rw-r--r--crates/wasi/tests/p1.rs357
-rw-r--r--examples/archive.rs10
-rw-r--r--examples/basic.rs (renamed from examples/simple.rs)8
-rw-r--r--examples/doom/Cargo.toml3
-rw-r--r--examples/doom/src/main.rs10
-rw-r--r--examples/doom/src/runtime.rs346
-rw-r--r--examples/exceptions.rs28
-rw-r--r--examples/funcref_callbacks.rs124
-rw-r--r--examples/gc.rs33
-rw-r--r--examples/linking.rs16
-rw-r--r--examples/reentrance.rs11
-rw-r--r--examples/references.rs34
-rw-r--r--examples/resumable.rs4
-rw-r--r--examples/rust.rs (renamed from examples/wasm-rust.rs)47
-rw-r--r--examples/rust/Cargo.toml16
-rw-r--r--examples/rust/README.md4
-rwxr-xr-xexamples/rust/build.sh11
-rw-r--r--examples/rust/src/hello.rs12
-rw-r--r--examples/rust/src/print.rs4
-rw-r--r--examples/rust/src/print.twasmbin0 -> 155 bytes
-rw-r--r--examples/rust/src/tinywasm.rs4
-rw-r--r--examples/rust/src/tinywasm_no_std.rs10
-rw-r--r--examples/simple2.rs21
-rw-r--r--examples/state.rs51
-rw-r--r--examples/wasi_p1.rs42
212 files changed, 18274 insertions, 9996 deletions
diff --git a/.github/workflows/audit.yaml b/.github/workflows/audit.yaml
new file mode 100644
index 0000000..fa785ca
--- /dev/null
+++ b/.github/workflows/audit.yaml
@@ -0,0 +1,46 @@
+name: Audit dependencies
+
+on:
+ pull_request:
+ paths:
+ - ".github/workflows/audit.yaml"
+ - "**/Cargo.toml"
+ - "Cargo.lock"
+ push:
+ branches: [main, next]
+ paths:
+ - ".github/workflows/audit.yaml"
+ - "**/Cargo.toml"
+ - "Cargo.lock"
+ schedule:
+ # Every Monday at 12:30 UTC
+ - cron: "30 12 * * 1"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ scan-pr:
+ if: github.event_name == 'pull_request'
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+ uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable-pr.yml@a345acffa64b0eaede81a3d9aae6141214d9c8fc # v2.6.0
+ with:
+ runs-on: ubuntu-24.04
+ upload-sarif: false
+ scan-args: --lockfile=./Cargo.lock
+
+ scan:
+ if: github.event_name != 'pull_request'
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+ uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@a345acffa64b0eaede81a3d9aae6141214d9c8fc # v2.6.0
+ with:
+ runs-on: ubuntu-24.04
+ fail-on-vuln: false
+ scan-args: --lockfile=./Cargo.lock
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index e950c47..ed441cd 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -8,6 +8,9 @@ on:
schedule:
- cron: "0 0 * * 0"
+permissions:
+ contents: read
+
jobs:
build-wasm:
name: Build wasm
@@ -18,7 +21,7 @@ jobs:
submodules: true
persist-credentials: false
- name: Install Rust toolchain
- uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1
+ uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0
with:
toolchain: nightly
components: rust-src
@@ -55,6 +58,10 @@ jobs:
rust: nightly
name: "Linux x86 (nightly)"
- os: ubuntu-latest
+ rust: nightly
+ name: "Linux x86 (nightly tail calls)"
+ args: "--features tinywasm/nightly-tail-calls"
+ - os: ubuntu-latest
rust: stable
name: "Linux x86 (stable, no default features)"
args: "--no-default-features"
@@ -62,6 +69,10 @@ jobs:
rust: nightly
name: "Linux x86 (nightly, no default features)"
args: "--no-default-features"
+ - os: ubuntu-latest
+ rust: nightly
+ name: "Linux x86 (nightly tail calls, no default features)"
+ args: "--no-default-features --features tinywasm/nightly-tail-calls"
- os: macos-14
rust: stable
name: "macOS arm64 (Apple M1)"
@@ -84,7 +95,7 @@ jobs:
persist-credentials: false
- name: Install Rust toolchain
- uses: actions-rust-lang/setup-rust-toolchain@46268bd060767258de96ed93c1251119784f2ab6 # v1.16.1
+ uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0
with:
toolchain: ${{ matrix.rust }}
rustflags: ""
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
deleted file mode 100644
index 422dbb5..0000000
--- a/ARCHITECTURE.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# TinyWasm Architecture
-
-TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html), but lowers validated WebAssembly into a compact internal instruction format before execution.
-
-## Runtime Layout
-
-- Values are stored in untyped stacks:
- - `stack_32` for `i32`, `f32`, `funcref`, and `externref`
- - `stack_64` for `i64` and `f64`
- - `stack_128` for `v128`
-- Locals are stored directly in the value stacks. Each `CallFrame` stores a `locals_base`, and local instructions index from that base.
-- Structured control flow (`block`, `loop`, `if`, `br*`) is lowered during parsing to jump-oriented internal instructions such as `Jump`, `JumpIfZero`, `BranchTable*`, `DropKeep*`, and `Return`.
-- Execution is a single iterative interpreter loop over the lowered instruction stream.
-
-## Internal Bytecode
-
-TinyWasm does not interpret WebAssembly instructions directly. During parsing and validation, WebAssembly is translated into TinyWasm's internal bytecode format.
-
-This internal representation is designed to make execution simpler and cheaper:
-
-- structured control flow is resolved ahead of time
-- stack effects are made explicit
-- common instruction sequences can be fused into superinstructions
-- modules can optionally be serialized as `.twasm` for reuse
-
-## Optimizer
-
-During parsing, a peephole optimizer (`optimize.rs`) fuses common instruction sequences into superinstructions. These reduce interpreter dispatch overhead by combining multiple logical operations into one internal instruction.
-
-Examples include:
-
-- **Fused binops**: `BinOpLocalLocal*`, `BinOpLocalConst*`, `BinOpStackGlobal*`
- Combine local/global access, a binary operation, and sometimes a store/tee.
-- **Fused jumps**: `JumpCmpLocalConst*`, `JumpCmpLocalLocal*`, `JumpCmpStackConst*`
- Combine comparison and conditional branch logic.
-
-## Memory Backends
-
-Linear memory is implemented through the `LinearMemory` trait. The backend is selected with `engine::Config::with_memory_backend()`.
-
-Available backends:
-
-- `VecMemory` - contiguous `Vec<u8>` backing; the default backend.
-- `PagedMemory` - chunk-based allocation, useful when growing memory without reallocating one large buffer.
-- `LazyLinearMemory` - wraps another backend and allocates memory on first access.
-- Custom backends through `MemoryBackend::custom()`.
-
-## Future Experiments
-
-TinyWasm's interpreter is intentionally simple today: validated WebAssembly is lowered to internal instructions, optimized with peephole fusion, and executed by an iterative dispatch loop.
-
-Future work may explore additional dispatch and code-generation strategies, including Rust's experimental `loop_match` state-machine work, explicit tail calls, more aggressive superinstruction fusion, top-of-stack register allocation, or even optional JIT compilation.
-
-## Code Map
-
-- [visit.rs](./crates/parser/src/visit.rs) - WebAssembly binary visitor
-- [optimize.rs](./crates/parser/src/optimize.rs) - peephole optimizer and superinstruction fusion
-- [parallel.rs](./crates/parser/src/parallel.rs) - multithreaded function parsing
-- [instructions.rs](./crates/types/src/instructions.rs) - internal instruction set
-- [value_stack.rs](./crates/tinywasm/src/interpreter/stack/value_stack.rs) - typed value stacks
-- [call_stack.rs](./crates/tinywasm/src/interpreter/stack/call_stack.rs) - call frame stack
-- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - memory backend trait and implementations
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79fb6b0..253f5a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,22 +9,73 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- Added support for the WebAssembly function-references proposal
-- Added `WasmValue::ty` and `WasmValue::matches_type`
+- Added new `Memory::data` and `Memory::data_mut` methods for direct access to linear memory.
+- Added several internal methods to support a future c-api crate
+
+## [0.11.0] - 2026-09-19
+
+This release adds garbage collection and typed function reference support, single-pass parsing, and an optional tail-call dispatch backend. The internal instruction representation is now 8 bytes, down from 16, and pluggable memory backends were removed for performance reasons (however, `ResourceLimiter` was added to allow, reject, or trap memory allocation and growth requests).
+
+### Breaking Changes
+
+#### Functions and references
+
+- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`.
+- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores.
+- Module instantiation now borrows `Imports`, allowing the same imports to be reused.
+- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types.
+- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`.
+- Nullable typed references use `Option<T>`, while bare typed references are non-null.
+- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures.
+- `ToWasmTypes` was renamed to `WasmTypes`, and `ToWasmType` was renamed to `WasmValueType`.
+- Conversion traits now include `WasmTypes`, and `FromWasmValues::from_wasm_values` rejects unconsumed values directly.
+
+#### Memory, tables, and stores
+
+- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests.
+- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`.
+- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`.
+- `Table::grow` now returns `Result<Option<usize>>`, matching `Memory::grow`.
+- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`.
+
+#### Parser and archives
+
+- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings.
+- `Parser::with_options` was removed.
+- `ParserOptions::optimize_rewrite` was renamed to `ParserOptions::optimize`.
+- `ParserOptions::parser_threads` was renamed to `ParserOptions::threads`.
+- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions.
+
+### Added
+
+- Optional store-owned host state through `Store::with_state`, `Store::state`, and `Store::state_mut`.
+- Support for the typed function references, garbage collection, exception handling, and compact import section proposals.
+- `ResourceLimiter` callbacks for memory and table allocation or growth.
+- A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation.
+- Optional parse-time operand deduplication to reduce `.twasm` archive size.
+- Optional `send` support for moving stores and store-local handles across threads.
+- Optional portable atomic shared pointers and counters for targets without native compare-and-swap.
+- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch.
### Changed
-- Function types are now stored separately and resolved through `Function::ty(&Store)`.
+- Parsing now uses a single pass.
+- Typed functions now support tuples up to arity 20 and `[u8; 16]` values for `v128`.
+- Module types now use one recursive type space.
+- Linear memory now uses contiguous `Vec`-backed storage.
+- The internal instruction representation was reduced from 16 to 8 bytes.
+- The minimum supported Rust version increased from 1.95 to 1.98.
### Fixed
+- Failed instantiation now preserves complete element and data segment mappings for functions exposed through imported tables, and stops data initialization when element initialization traps.
+- Stream parsing now bounds read increments instead of allocating declared section sizes up front, and retries interrupted reads.
+- Reentrant host calls now enforce a separate depth limit based on the configured call-stack size instead of allowing unbounded native-stack recursion.
+- Instantiation now rejects directly defined imports that contain handles from another `Store`.
- Tail calls to host functions now return directly to the caller frame.
-
-### Breaking Changes
-
-- Renamed `ModuleInstanceAddr` to `ModuleInstanceId` for consistency.
-- Removed `HostFunction::ty` and `WasmFunction::ty`. Use `Function::ty(&Store)` for runtime function types.
-- Changed `TableType::element_type` and `Element::ty` from `WasmType` to `RefType`, and replaced module `table_types` with `TableDefinition { ty, init }`.
+- Memory64 bulk-memory operations and optimized stores now use the correct value-stack lanes.
+- `memory.init` now performs correct bounds checks and operand lowering.
+- Memory64 now uses the correct default limits and host-size conversions, including on 32-bit targets.
## [0.10.0] - 2026-07-24
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..8dd98a5
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,60 @@
+# Contributor Covenant 3.0 Code of Conduct
+
+## Our Pledge
+
+We pledge to make our community welcoming, safe, and equitable for all.
+
+We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
+
+## Encouraged Behaviors
+
+While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
+
+With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
+
+1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
+2. Engaging **kindly and honestly** with others.
+3. Respecting **different viewpoints** and experiences.
+4. **Taking responsibility** for our actions and contributions.
+5. Gracefully giving and accepting **constructive feedback**.
+6. Committing to **repairing harm** when it occurs.
+7. Behaving in other ways that promote and sustain the **well-being of our community**.
+
+## Restricted Behaviors
+
+We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
+
+1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
+2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
+3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
+4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
+5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
+6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
+7. Behaving in other ways that **threaten the well-being** of our community.
+
+### Other Restrictions
+
+1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
+2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
+3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
+4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
+
+## Reporting an Issue
+
+Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
+
+When an incident does occur, it is important to report it promptly. To report a possible violation, **you can send an email to gh@henrygressmann.de.**
+
+Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+
+## Attribution
+
+This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
+
+Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
+
+For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6cb7761..776b132 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,61 +1,63 @@
# Contributing
-Thank you for considering a contribution. For small fixes, feel free to open a pull request directly. For larger changes, please open an issue first so we can discuss the approach. Please target the `next` branch and [allow maintainers to edit your PR branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
+Thank you for contributing to TinyWasm. For small fixes, you can open a pull request directly. For larger changes, including new features and public API changes, open an issue first to discuss the approach.
-## Code of Conduct
+Pull requests should target the `next` branch. If you submit a pull request from a fork, [allow maintainers to edit the branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
-This project follows the [Contributor Covenant 3.0 Code of Conduct](https://www.contributor-covenant.org/version/3/0/code_of_conduct/).
+All contributors must follow the [Code of Conduct](./CODE_OF_CONDUCT.md).
-## Development
-
-This project mostly uses a pretty standard Rust setup. Some common tasks:
-
-```bash
-# Run a specific benchmark (run without arguments to see available benchmarks)
-$ cargo bench --bench {bench_name}
+## AI-assisted contributions
-# Run all tests
-$ cargo test
+You may use AI tools to help develop a contribution, but:
-# Run only the WebAssembly MVP (1.0) test suite
-$ cargo test-wasm-1
+- Write issue and pull request descriptions yourself. Do not submit AI-generated issue or pull request text.
+- Understand and review all code that you submit. You are responsible for its behavior and quality.
+- Keep the change focused on the issue. Do not include unrelated generated changes or refactors.
-# Run only the full WebAssembly 2.0 test suite
-$ cargo test-wasm-2
+## Development
-# Run only the full WebAssembly 3.0 test suite
-$ cargo test-wasm-3
+Common commands:
-# Run a single WAST test file
-$ cargo test-wast ./wasm-testsuite/data/wasm-v1/{file}.wast
+```bash
+cargo fmt --all -- --check
+cargo clippy --workspace
+cargo test --workspace
+cargo run --example basic
+cargo bench --bench tinywasm
+```
-# Run custom wasm tests from crates/tinywasm/tests/wasm-custom
-$ cargo test-wasm-custom
+WebAssembly test commands:
-# Run a specific example (run without arguments to see available examples)
-# The wasm test files required to run the `wasm-rust` examples are not
-# included in the main repository.
-# To build these, you will need to install binaryen and wabt
-# and run `./examples/rust/build.sh`.
-$ cargo run --example {example_name}
+```bash
+cargo test-wasm-1
+cargo test-wasm-2
+cargo test-wasm-3
+cargo test-wasm-custom
+cargo test-wast crates/tinywasm/tests/wasm-custom/table-basics.wast
```
-### Profiling
+Set `RUST_LOG=debug` when running `cargo test-wast` to see executor debug logs.
+
+The `rust` example requires the `wasm32-unknown-unknown` target, the `rust-src` component, [Binaryen](https://github.com/WebAssembly/binaryen), and [WABT](https://github.com/WebAssembly/wabt):
-Use [samply](https://github.com/mstange/samply/) for profiling.
+```bash
+./examples/rust/build.sh
+cargo run --example rust -- hello
+```
-Example usage:
+You can use [samply](https://github.com/mstange/samply/) for profiling:
```bash
cargo install --locked samply
-samply record -- cargo run --release --example wasm-rust -- tinywasm
+samply record -- cargo run --profile samply --example rust -- tinywasm
```
+Keep changes focused and external dependencies to a minimum. Update public documentation, the README, and the unreleased changelog when applicable.
+
## Commits
-This project uses [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for commit messages. For pull requests, the commit messages will be squashed so you don't need to worry about this too much. However, it is still recommended to follow this convention for consistency.
+Use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) when practical. Pull requests are squash-merged, so the pull request title is more important than individual commit messages.
-## Branches
+## Licensing
-- `main`: The main branch. This branch is used for the latest stable release.
-- `next`: The next branch. Development happens here.
+Unless you explicitly state otherwise, contributions are licensed under the repository's [MIT](./LICENSE-MIT) and [Apache-2.0](./LICENSE-APACHE) licenses.
diff --git a/Cargo.lock b/Cargo.lock
index 680b8fb..f49bf9d 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",
]
@@ -21,6 +21,12 @@ dependencies = [
]
[[package]]
+name = "ambient-authority"
+version = "0.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
+
+[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -62,7 +68,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -73,10 +79,16 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
name = "assert_cmd"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -99,15 +111,15 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
-version = "2.13.1"
+version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bstr"
-version = "1.13.0"
+version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
+checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
dependencies = [
"memchr",
"regex-automata",
@@ -121,6 +133,48 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
+name = "cap-fs-ext"
+version = "4.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f"
+dependencies = [
+ "cap-primitives",
+ "cap-std",
+ "io-lifetimes 3.0.1",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "cap-primitives"
+version = "4.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
+dependencies = [
+ "ambient-authority",
+ "fs-set-times",
+ "io-extras",
+ "io-lifetimes 3.0.1",
+ "ipnet",
+ "maybe-owned",
+ "rustix",
+ "rustix-linux-procfs",
+ "windows-sys 0.61.2",
+ "winx",
+]
+
+[[package]]
+name = "cap-std"
+version = "4.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
+dependencies = [
+ "cap-primitives",
+ "io-extras",
+ "io-lifetimes 3.0.1",
+ "rustix",
+]
+
+[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -128,9 +182,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
-version = "1.4.0"
+version = "1.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
+checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -138,9 +192,9 @@ dependencies = [
[[package]]
name = "cfg-if"
-version = "1.0.4"
+version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "ciborium"
@@ -171,9 +225,9 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.6.5"
+version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
@@ -181,9 +235,9 @@ dependencies = [
[[package]]
name = "clap_builder"
-version = "4.6.5"
+version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
@@ -193,30 +247,30 @@ dependencies = [
[[package]]
name = "clap_complete"
-version = "4.6.8"
+version = "4.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1f84a88507dbd05c695f2cb5e8558e747179134005e9893882dec964190ed89"
+checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
-version = "4.6.4"
+version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
- "syn 3.0.3",
+ "syn 3.0.6",
]
[[package]]
name = "clap_lex"
-version = "1.1.0"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "cobs"
@@ -269,9 +323,9 @@ dependencies = [
[[package]]
name = "crossbeam-deque"
-version = "0.8.7"
+version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
@@ -279,18 +333,18 @@ dependencies = [
[[package]]
name = "crossbeam-epoch"
-version = "0.9.20"
+version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
-version = "0.8.22"
+version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crunchy"
@@ -306,9 +360,9 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]
name = "either"
-version = "1.17.0"
+version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "embedded-io"
@@ -348,17 +402,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys",
-]
-
-[[package]]
-name = "eyre"
-version = "0.6.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec"
-dependencies = [
- "indenter",
- "once_cell",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -369,9 +413,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
-version = "0.1.9"
+version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"
[[package]]
name = "float-cmp"
@@ -383,6 +427,17 @@ dependencies = [
]
[[package]]
+name = "fs-set-times"
+version = "0.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
+dependencies = [
+ "io-lifetimes 2.0.4",
+ "rustix",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -418,9 +473,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
-version = "0.5.2"
+version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "humantime"
@@ -448,22 +503,44 @@ dependencies = [
]
[[package]]
-name = "indenter"
-version = "0.3.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"
-
-[[package]]
name = "indexmap"
-version = "2.14.0"
+version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
+name = "io-extras"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
+dependencies = [
+ "io-lifetimes 3.0.1",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "io-lifetimes"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
+
+[[package]]
+name = "io-lifetimes"
+version = "3.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
+[[package]]
name = "is-terminal"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -471,7 +548,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -521,9 +598,15 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
-version = "0.4.33"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "maybe-owned"
+version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "memchr"
@@ -566,9 +649,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "owo-colors"
-version = "4.3.0"
+version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d"
+checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8"
[[package]]
name = "page_size"
@@ -581,6 +664,22 @@ dependencies = [
]
[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+ "serde",
+]
+
+[[package]]
name = "postcard"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -690,9 +789,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",
@@ -707,15 +806,25 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustix"
-version = "1.1.4"
+version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
- "windows-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustix-linux-procfs"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
+dependencies = [
+ "once_cell",
+ "rustix",
]
[[package]]
@@ -760,7 +869,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
- "syn 3.0.3",
+ "syn 3.0.6",
]
[[package]]
@@ -801,9 +910,9 @@ dependencies = [
[[package]]
name = "syn"
-version = "3.0.3"
+version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
@@ -820,7 +929,7 @@ dependencies = [
"getrandom",
"once_cell",
"rustix",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -840,22 +949,22 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"
[[package]]
name = "thiserror"
-version = "2.0.19"
+version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
+checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "2.0.19"
+version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
+checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
dependencies = [
"proc-macro2",
"quote",
- "syn 3.0.3",
+ "syn 3.0.6",
]
[[package]]
@@ -870,15 +979,11 @@ dependencies = [
[[package]]
name = "tinywasm"
-version = "0.11.0-pre.0"
+version = "0.11.0"
dependencies = [
- "criterion",
- "eyre",
"libm",
"log",
- "owo-colors",
- "serde",
- "serde_json",
+ "portable-atomic",
"tinywasm-cli",
"tinywasm-parser",
"tinywasm-types",
@@ -888,26 +993,30 @@ dependencies = [
[[package]]
name = "tinywasm-cli"
-version = "0.11.0-pre.0"
+version = "0.11.0"
dependencies = [
"anstream",
+ "anyhow",
"assert_cmd",
"clap",
"clap_complete",
- "eyre",
"log",
"owo-colors",
"predicates",
"pretty_env_logger",
+ "serde",
+ "serde_json",
"tempfile",
"tinywasm",
+ "tinywasm-wasi",
+ "wasm-testsuite",
"wast",
"wat",
]
[[package]]
name = "tinywasm-parser"
-version = "0.11.0-pre.0"
+version = "0.11.0"
dependencies = [
"log",
"tinywasm-types",
@@ -916,28 +1025,43 @@ dependencies = [
[[package]]
name = "tinywasm-root"
-version = "0.11.0-pre.0"
+version = "0.11.0"
dependencies = [
- "eyre",
+ "anyhow",
+ "criterion",
"pretty_env_logger",
"tinywasm",
+ "tinywasm-parser",
+ "tinywasm-wasi",
"wat",
]
[[package]]
name = "tinywasm-types"
-version = "0.11.0-pre.0"
+version = "0.11.0"
dependencies = [
- "log",
+ "portable-atomic-util",
"postcard",
"serde",
]
[[package]]
+name = "tinywasm-wasi"
+version = "0.11.0"
+dependencies = [
+ "cap-fs-ext",
+ "cap-std",
+ "getrandom",
+ "rustix",
+ "tinywasm",
+ "wat",
+]
+
+[[package]]
name = "unicode-ident"
-version = "1.0.24"
+version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-width"
@@ -972,9 +1096,9 @@ dependencies = [
[[package]]
name = "wasm-encoder"
-version = "0.255.0"
+version = "0.259.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42"
+checksum = "b1d0246511d901aacf25d2dc9111f0054947de5e093fe662099e709ff7530dc3"
dependencies = [
"leb128fmt",
"wasmparser",
@@ -982,9 +1106,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",
@@ -992,9 +1116,9 @@ dependencies = [
[[package]]
name = "wasmparser"
-version = "0.255.0"
+version = "0.259.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b"
+checksum = "0f7c12eac7bb587801590f6a67ff0bc84d0748513864b71108e4b311cc3df694"
dependencies = [
"bitflags",
"indexmap",
@@ -1003,9 +1127,9 @@ dependencies = [
[[package]]
name = "wast"
-version = "255.0.0"
+version = "259.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "55ffec530f199bd3d553ac442c13dd108353cad533cad8514bc41e1f1f0fe686"
+checksum = "c69beba8d9da07af9a0971b559149a2ac4729895b55144de4fddbf5a02660648"
dependencies = [
"bumpalo",
"leb128fmt",
@@ -1016,9 +1140,9 @@ dependencies = [
[[package]]
name = "wat"
-version = "1.255.0"
+version = "1.259.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dda82c82e1486c7eed42a0465e544d80fff37abc3b39482e0d34dbaabe2fe5b1"
+checksum = "c6eec44b0c80391b20fb7ad9ea440c72c5d382385bdf74444bb18321c425017e"
dependencies = [
"wast",
]
@@ -1045,7 +1169,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1062,6 +1186,24 @@ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
@@ -1070,19 +1212,158 @@ dependencies = [
]
[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "winx"
+version = "0.36.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
+dependencies = [
+ "bitflags",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
name = "zerocopy"
-version = "0.8.55"
+version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
+checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.55"
+version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
+checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index e57b6ea..57526e5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,50 +8,75 @@ publish = false
[workspace]
resolver = "3"
members = ["crates/*"]
-default-members = [".", "crates/parser", "crates/tinywasm", "crates/types"]
+default-members = [".", "crates/parser", "crates/tinywasm", "crates/types", "crates/wasi"]
[workspace.package]
-version = "0.11.0-pre.0"
+version = "0.11.0"
edition = "2024"
-rust-version = "1.95"
+rust-version = "1.98"
+homepage = "https://tinywasm.dev"
repository = "https://github.com/explodingcamera/tinywasm"
license = "MIT OR Apache-2.0"
keywords = ["interpreter", "no-std", "tinywasm", "wasm", "webassembly"]
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 }
+tinywasm = { path = "crates/tinywasm", version = "0.11.0", default-features = false }
+tinywasm-parser = { path = "crates/parser", version = "0.11.0", default-features = false }
+tinywasm-types = { path = "crates/types", version = "0.11.0", default-features = false }
+tinywasm-wasi = { path = "crates/wasi", version = "0.11.0" }
-eyre = "0.6"
-indexmap = "2.14"
+anyhow = "1.0"
log = "0.4"
-owo-colors = { version = "4.3" }
+owo-colors = { version = "4.4" }
pretty_env_logger = "0.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
wasm-testsuite = { version = "0.7" }
-wasmparser = { version = "0.255", default-features = false }
-wast = "255"
-wat = "1.255"
+wasmparser = { version = "0.259", default-features = false }
+wast = "259"
+wat = "1.259"
-criterion = { version = "0.8", default-features = false, features = [
- "cargo_bench_support",
- "rayon"
-] }
+criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] }
+
+[workspace.lints.cargo]
+unused_dependencies = "allow" # false-positive on libm
+
+[workspace.lints.rust]
+unexpected_cfgs = { level = "warn", check-cfg = ["cfg(rust_analyzer)"] }
[[example]]
-name = "wasm-rust"
+name = "rust"
test = false
+[[bench]]
+harness = false
+name = "argon2id"
+
+[[bench]]
+harness = false
+name = "fibonacci"
+
+[[bench]]
+harness = false
+name = "tinywasm"
+
+[[bench]]
+harness = false
+name = "tinywasm_modes"
+
[dev-dependencies]
-eyre.workspace = true
+anyhow.workspace = true
+criterion.workspace = true
pretty_env_logger.workspace = true
-tinywasm = { path = "crates/tinywasm" }
+tinywasm = { path = "crates/tinywasm", features = ["state"] }
+tinywasm-parser.workspace = true
+tinywasm-wasi.workspace = true
wat.workspace = true
+[lints]
+workspace = true
+
[profile.bench]
opt-level = 3
debug = true
diff --git a/README.md b/README.md
index 77ade90..6d2ca69 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,22 @@
# <b>`tinywasm`</b>
-[![docs.rs](https://img.shields.io/docsrs/tinywasm?logo=rust&style=flat-square)](https://docs.rs/tinywasm) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE)
+[![Documentation](https://img.shields.io/badge/docs-latest-blue?style=flat-square)](https://docs.rs/tinywasm/latest/tinywasm/) [![Build](https://img.shields.io/github/actions/workflow/status/explodingcamera/tinywasm/test.yaml?branch=next&style=flat-square&label=build)](https://github.com/explodingcamera/tinywasm/actions/workflows/test.yaml?query=branch%3Anext) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE)
## Why `tinywasm`?
-- **Tiny**: Small by design, without significantly compromising performance or functionality.
-- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies, and can itself compile to WebAssembly.
-- **Safe**: Written in safe Rust, with optional `unsafe` limited to the `simd-x86` feature. Its sandbox is designed to prevent untrusted Wasm from accessing host memory or escaping the runtime.
+- **Tiny**: Small by design, while still passing the full WebAssembly 3.0 core test suite.
+- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies[^dependencies], and can itself compile to WebAssembly.
+- **Safe by default**: Written entirely in safe Rust[^unsafe].
+
+[^dependencies]: The two main external components are [`wasmparser`](https://crates.io/crates/wasmparser) for WebAssembly parsing and validation, and [`postcard`](https://crates.io/crates/postcard) for `.twasm` archives.
+
+[^unsafe]: The optional `simd-x86` feature is the only exception. It uses `unsafe` internally for selected x86 SIMD intrinsics.
## Installation
```toml
[dependencies]
-tinywasm = "0.10"
+tinywasm = "0.11.0"
```
## Usage
@@ -41,57 +45,67 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin
## Cargo Features
+- **`full`:** Enables `archive`, `debug`, `parallel-parser`, `parser`, `state`, and `validate`. Enabled by default.
- **`std`:** Enables `std` and parsing from files and streams. Enabled by default.
-- **`log`:** Enables integration with the `log` crate. Enabled by default.
- **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default.
+- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through [`ParserOptions`](https://docs.rs/tinywasm/latest/tinywasm/parser/struct.ParserOptions.html).
+- **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
- **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default.
-- **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default.
+- **`log`:** Enables integration with the `log` crate.
+- **`send`:** Makes stores and store-local handles movable across threads.
+- **`state`:** Adds store-owned host state for access from host callbacks. Enabled by default.
+- **`portable-atomic`:** Supports targets without native atomic compare-and-swap.
+- **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results.
- **`debug`:** Derives `Debug` for runtime types. Enabled by default.
-- **`parallel-parser`:** Parallelizes function parsing and validation when `std` is enabled. Enabled by default.
- **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
+- **`nightly-tail-calls`:** Uses Rust's unstable explicit tail calls for interpreter dispatch. Requires nightly Rust (recommended for maximum performance).
- **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally.
-With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments.
+With default features disabled, `tinywasm` supports `no_std + alloc` and depends only on `libm`.
+
+Use [`Engine`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Engine.html) and [`engine::Config`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Config.html) for non-default fuel accounting, stack sizing, or GC collection thresholds. A configured `ResourceLimiter` can allow, reject, or trap memory and table allocation or growth requests, and GC object allocations.
-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.
+## Precompiled Modules
-[^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`.
+TinyWasm can serialize a parsed module to its version-specific `.twasm` format. Loading an archive skips WebAssembly parsing, validation, and optimization.
-## Current Status
+Applications that only load `.twasm` can remove the parser and validator from their binary by only enabling the `archive` feature. Depending on the target and release profile, this can produce binaries smaller than 300 KB.
-`tinywasm` passes the WebAssembly MVP and WebAssembly 2.0 core testsuites and supports the [Lime1](https://github.com/WebAssembly/tool-conventions/blob/main/Lime.md#lime1) interoperability target. WebAssembly 3.0 support is still in progress, and some newer proposal suites are tracked in-repo as experimental coverage rather than release guarantees; see [Supported Proposals](#supported-proposals) for details.
+## Untrusted Input
-TinyWasm also has its own internal bytecode format, `twasm`. WebAssembly modules can be compiled to `twasm`, which stores TinyWasm's optimized instruction representation for faster loading and reuse.
+WebAssembly [validation](https://webassembly.github.io/spec/core/valid/index.html) is enabled by default through the `validate` feature. Keep this feature enabled and leave `ParserOptions::validation` enabled for modules from untrusted sources. Without validation, parsing can produce modules that violate runtime assumptions and may panic during instantiation or execution.
-## Safety
+Validation does not limit parsing or execution resources. Hosts that run untrusted code should also set input limits, configure stack and `ResourceLimiter` limits, and use fuel- or time-budgeted execution as needed.
-TinyWasm only uses safe Rust by default. The optional `simd-x86` feature enables x86-specific SIMD intrinsics and uses `unsafe` internally. WebAssembly input is validated by default and runs inside a sandbox: untrusted Wasm should not be able to access host memory, escape the sandbox, or cause undefined behavior in the runtime. Validation should only be disabled for trusted input.
+Loading `.twasm` checks the archive header and encoding but does not run WebAssembly validation or verify TinyWasm's runtime invariants. Load archives only from trusted sources. For untrusted input, parse a WebAssembly binary with validation enabled.
-The internal `twasm` bytecode format is not currently validated as an untrusted input format. Malformed `twasm` may panic, but should not compromise memory safety or allow sandbox escape. Only run trusted `twasm` bytecode, or generate it through TinyWasm from Wasm input.
+## WebAssembly Proposal Support
-## Supported Proposals
+TinyWasm generally implements non-JavaScript core proposals at [phase 4](https://github.com/WebAssembly/proposals#phase-4---standardize-the-feature-wg) or later, with some proposals implemented earlier. The table shows current support and known exceptions.
-| 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) | 🌑 | - |
+| 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) | 🟢 | 0.11.0 |
+| [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | 0.11.0 |
+| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🟢 | 0.11.0 |
+| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🟢 | 0.11.0 |
+| [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - |
+| [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - |
**Legend**\
🌑 -- not available\
@@ -100,11 +114,13 @@ The internal `twasm` bytecode format is not currently validated as an untrusted
## See Also
-If you need a more mature, production-tested, or performance-focused WebAssembly runtime today, consider one of these projects:
+If you're looking for a WebAssembly runtime with JIT compilation, better performance or other advanced features, check out these other runtimes:
- [wasmi](https://github.com/wasmi-labs/wasmi) - efficient and versatile WebAssembly interpreter for embedded systems
- [wasm3](https://github.com/wasm3/wasm3) - a fast WebAssembly interpreter written in C
- [wazero](https://wazero.io/) - a zero-dependency WebAssembly interpreter written in Go
+- [wasmer](https://wasmer.io/) - a fast and secure WebAssembly runtime written in Rust
+- [wasmtime](https://wasmtime.dev/) - a fast and secure WebAssembly runtime written in Rust
## License
diff --git a/crates/tinywasm/benches/argon2id.rs b/benches/argon2id.rs
index dbd86e5..3121062 100644
--- a/crates/tinywasm/benches/argon2id.rs
+++ b/benches/argon2id.rs
@@ -1,12 +1,11 @@
use criterion::{Criterion, criterion_group, criterion_main};
-use eyre::Result;
-use tinywasm::{ModuleInstance, Store, types};
+use tinywasm::{ModuleInstance, Result, Store, types};
use types::Module;
-const WASM: &[u8] = include_bytes!("../../../examples/rust/out/argon2id.wasm");
+const WASM: &[u8] = include_bytes!("../examples/rust/out/argon2id.wasm");
fn argon2id_parse() -> Result<Module> {
- let parser = tinywasm_parser::Parser::new();
+ let parser = tinywasm_parser::Parser::default();
let data = parser.parse_module_bytes(WASM)?;
Ok(data)
}
diff --git a/crates/tinywasm/benches/fibonacci.rs b/benches/fibonacci.rs
index e0737da..699dc79 100644
--- a/crates/tinywasm/benches/fibonacci.rs
+++ b/benches/fibonacci.rs
@@ -1,12 +1,11 @@
use criterion::{Criterion, criterion_group, criterion_main};
-use eyre::Result;
-use tinywasm::{ModuleInstance, Store, types};
+use tinywasm::{ModuleInstance, Result, Store, types};
use types::Module;
-const WASM: &[u8] = include_bytes!("../../../examples/rust/out/fibonacci.wasm");
+const WASM: &[u8] = include_bytes!("../examples/rust/out/fibonacci.wasm");
fn fibonacci_parse() -> Result<Module> {
- let parser = tinywasm_parser::Parser::new();
+ let parser = tinywasm_parser::Parser::default();
let data = parser.parse_module_bytes(WASM)?;
Ok(data)
}
@@ -45,7 +44,7 @@ fn criterion_benchmark(c: &mut Criterion) {
group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm)));
group.measurement_time(std::time::Duration::from_secs(10));
- group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60)));
+ group.bench_function("fibonacci_iterative_100", |b| b.iter(|| fibonacci_run(module.clone(), false, 100)));
group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26)));
}
diff --git a/crates/tinywasm/benches/tinywasm.rs b/benches/tinywasm.rs
index 9a4de80..aff8c70 100644
--- a/crates/tinywasm/benches/tinywasm.rs
+++ b/benches/tinywasm.rs
@@ -1,13 +1,12 @@
use criterion::{Criterion, criterion_group, criterion_main};
-use eyre::Result;
use tinywasm::engine::Config;
-use tinywasm::{Engine, FuncContext, HostFunction, Imports, MemoryBackend, ModuleInstance, Store, types};
+use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Result, Store, types};
use types::Module;
-const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm");
+const WASM: &[u8] = include_bytes!("../examples/rust/out/tinywasm.wasm");
fn tinywasm_parse() -> Result<Module> {
- let parser = tinywasm_parser::Parser::new();
+ let parser = tinywasm_parser::Parser::default();
let data = parser.parse_module_bytes(WASM)?;
Ok(data)
}
@@ -23,11 +22,11 @@ fn tinywasm_from_twasm(twasm: &[u8]) -> Result<Module> {
}
fn tinywasm_run(module: &Module) -> Result<()> {
- let engine = Engine::new(Config::default().with_memory_backend(MemoryBackend::paged(64 * 1024)));
+ let engine = Engine::new(Config::default());
let mut store = Store::new(engine);
let mut imports = Imports::default();
- imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _: i32| Ok(())));
- let instance = ModuleInstance::instantiate(&mut store, module, Some(imports)).expect("instantiate");
+ imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(())));
+ let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports)).expect("instantiate");
let hello = instance.func::<(), ()>(&store, "hello").expect("func_typed");
hello.call(&mut store, ()).expect("call");
Ok(())
diff --git a/crates/tinywasm/benches/tinywasm_modes.rs b/benches/tinywasm_modes.rs
index ed89b7b..7d1d993 100644
--- a/crates/tinywasm/benches/tinywasm_modes.rs
+++ b/benches/tinywasm_modes.rs
@@ -1,16 +1,17 @@
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
-use eyre::Result;
use tinywasm::engine::{Config, FuelPolicy};
use tinywasm::types::Module;
-use tinywasm::{Engine, ExecProgress, FuncContext, FunctionTyped, HostFunction, Imports, ModuleInstance, Store};
+use tinywasm::{
+ Engine, ExecProgress, FuncContext, FunctionTyped, HostFunction, Imports, ModuleInstance, Result, Store,
+};
-const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm");
+const WASM: &[u8] = include_bytes!("../examples/rust/out/tinywasm.wasm");
const FUEL_PER_ROUND: u32 = 512;
const TIME_BUDGET_PER_ROUND: core::time::Duration = core::time::Duration::from_micros(50);
const BENCH_MEASUREMENT_TIME: core::time::Duration = core::time::Duration::from_secs(10);
fn tinywasm_parse() -> Result<Module> {
- let parser = tinywasm_parser::Parser::new();
+ let parser = tinywasm_parser::Parser::default();
Ok(parser.parse_module_bytes(WASM)?)
}
@@ -21,9 +22,9 @@ fn setup_typed_func(module: &Module, engine: Option<Engine>) -> Result<(Store, F
};
let mut imports = Imports::default();
- imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _: i32| Ok(())));
+ imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(())));
- let instance = ModuleInstance::instantiate(&mut store, module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?;
let func = instance.func::<(), ()>(&store, "hello")?;
Ok((store, func))
}
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index 7dbd4d2..73b537f 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -4,8 +4,7 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Minimal command-line interface for TinyWasm"
-documentation = "https://docs.rs/tinywasm-cli"
-readme = "README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords = ["cli", "runtime", "tinywasm", "wasm", "webassembly"]
@@ -23,21 +22,24 @@ path = "src/bin.rs"
[dependencies]
anstream = { version = "1.0" }
+anyhow.workspace = true
clap = { version = "4.6", features = ["derive"] }
clap_complete = "4.6"
-eyre.workspace = true
log.workspace = true
owo-colors = { workspace = true }
pretty_env_logger.workspace = true
+serde = { workspace = true, optional = true }
+serde_json = { workspace = true, optional = true }
tinywasm = { workspace = true, features = [
- "archive",
"canonicalize-nans",
"debug",
+ "full",
+ "guest-debug",
"log",
- "parallel-parser",
- "parser",
"std",
] }
+tinywasm-wasi.workspace = true
+wasm-testsuite = { workspace = true, optional = true }
wast = { workspace = true, optional = true }
wat = { workspace = true, optional = true }
@@ -48,5 +50,9 @@ tempfile = "3.27"
[features]
default = ["wast", "wat"]
+tests = ["dep:serde", "dep:serde_json", "dep:wasm-testsuite", "wast"]
wast = ["dep:wast"]
wat = ["dep:wat"]
+
+[lints]
+workspace = true
diff --git a/crates/cli/src/bin.rs b/crates/cli/src/bin.rs
index 592fda7..d630fcf 100644
--- a/crates/cli/src/bin.rs
+++ b/crates/cli/src/bin.rs
@@ -1,5 +1,5 @@
+use anyhow::Result;
use clap::Parser;
-use eyre::Result;
use tinywasm_cli::{Cli, run_cli};
fn main() -> Result<()> {
diff --git a/crates/cli/src/cmd/compile.rs b/crates/cli/src/cmd/compile.rs
index 93e38d5..c7007ee 100644
--- a/crates/cli/src/cmd/compile.rs
+++ b/crates/cli/src/cmd/compile.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use crate::cli::CompileArgs;
use crate::load::{default_twasm_output_path, load_compilable_module, write_output_bytes};
diff --git a/crates/cli/src/cmd/completion.rs b/crates/cli/src/cmd/completion.rs
index 5815f57..b3aec7c 100644
--- a/crates/cli/src/cmd/completion.rs
+++ b/crates/cli/src/cmd/completion.rs
@@ -1,7 +1,7 @@
use std::io;
+use anyhow::Result;
use clap::CommandFactory;
-use eyre::Result;
use crate::cli::{Cli, CompletionArgs};
diff --git a/crates/cli/src/cmd/dump.rs b/crates/cli/src/cmd/dump.rs
index 7a88cc2..da98a0b 100644
--- a/crates/cli/src/cmd/dump.rs
+++ b/crates/cli/src/cmd/dump.rs
@@ -1,5 +1,5 @@
use anstream::println;
-use eyre::Result;
+use anyhow::Result;
use owo_colors::OwoColorize;
use tinywasm::types::{ExternalKind, ImportKind};
diff --git a/crates/cli/src/cmd/inspect.rs b/crates/cli/src/cmd/inspect.rs
index ea2cec7..cf7cb5f 100644
--- a/crates/cli/src/cmd/inspect.rs
+++ b/crates/cli/src/cmd/inspect.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use crate::cli::ModuleInputArgs;
use crate::load::load_module;
diff --git a/crates/cli/src/cmd/run.rs b/crates/cli/src/cmd/run.rs
index 06f29f1..52cd273 100644
--- a/crates/cli/src/cmd/run.rs
+++ b/crates/cli/src/cmd/run.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::types::ExportType;
use tinywasm::{ModuleInstance, Store};
@@ -8,7 +8,7 @@ use crate::output::print_results;
use crate::value_parse::parse_invocation_args;
pub fn run(args: RunArgs) -> Result<()> {
- let module_path = args.module.as_deref().ok_or_else(|| eyre::eyre!("missing module path"))?;
+ let module_path = args.module.as_deref().ok_or_else(|| anyhow::anyhow!("missing module path"))?;
let loaded = load_module(module_path)?;
let mut store = Store::new(args.engine.build_engine()?);
let instance = ModuleInstance::instantiate_no_start(&mut store, &loaded.module, None)?;
@@ -26,10 +26,11 @@ pub fn run(args: RunArgs) -> Result<()> {
(true, ExportType::Func(ty)) => Some(ty),
_ => None,
})
- .ok_or_else(|| eyre::eyre!("export is not a function: {export}"))?;
+ .ok_or_else(|| anyhow::anyhow!("export is not a function: {export}"))?;
let func = instance.func_untyped(&store, export)?;
let params = parse_invocation_args(func_ty, &args.args)?;
- let results = func.call(&mut store, &params)?;
+ let mut results = vec![tinywasm::WasmValue::I32(0); func.ty(&store)?.results().len()];
+ func.call(&mut store, &params, &mut results)?;
print_results(&results);
Ok(())
}
@@ -40,11 +41,11 @@ pub fn run(args: RunArgs) -> Result<()> {
}
let start = instance.func_untyped(&store, "_start").map_err(|_| {
- eyre::eyre!(
+ anyhow::anyhow!(
"module has no start function or `_start` export. Use `tinywasm inspect {module_path}` or `tinywasm run --invoke <export> {module_path}`"
)
})?;
- start.call(&mut store, &[])?;
+ start.call(&mut store, &[], &mut [])?;
Ok(())
}
}
diff --git a/crates/cli/src/cmd/wast.rs b/crates/cli/src/cmd/wast.rs
index ef9c263..c669a0a 100644
--- a/crates/cli/src/cmd/wast.rs
+++ b/crates/cli/src/cmd/wast.rs
@@ -1,6 +1,6 @@
use std::path::PathBuf;
-use eyre::Result;
+use anyhow::Result;
use crate::cli::WastArgs;
use crate::wast_runner::WastRunner;
diff --git a/crates/cli/src/engine_flags.rs b/crates/cli/src/engine_flags.rs
index c8df1fe..edc56aa 100644
--- a/crates/cli/src/engine_flags.rs
+++ b/crates/cli/src/engine_flags.rs
@@ -1,5 +1,5 @@
+use anyhow::Result;
use clap::{Args, ValueEnum};
-use eyre::{Result, bail};
use tinywasm::{Engine, StackConfig, engine::FuelPolicy};
#[derive(Args, Clone, Default)]
@@ -8,18 +8,6 @@ pub struct EngineFlags {
#[arg(long, value_enum)]
pub fuel_policy: Option<FuelPolicyArg>,
- /// Trap immediately on memory or stack allocation failure
- #[arg(long)]
- pub trap_on_oom: bool,
-
- /// Memory backend to use for instantiated memories
- #[arg(long, value_enum)]
- pub memory_backend: Option<MemoryBackendArg>,
-
- /// Chunk size in bytes for the paged memory backend
- #[arg(long, default_value_t = 64 * 1024)]
- pub memory_page_chunk_size: usize,
-
/// Fixed value stack size for all value lanes
#[arg(long, conflicts_with = "value_stack_dynamic")]
pub value_stack_size: Option<usize>,
@@ -43,12 +31,6 @@ pub enum FuelPolicyArg {
Weighted,
}
-#[derive(Clone, Copy, ValueEnum)]
-pub enum MemoryBackendArg {
- Vec,
- Paged,
-}
-
#[derive(Clone)]
pub struct StackSpec {
initial: usize,
@@ -86,18 +68,6 @@ impl EngineFlags {
});
}
- if let Some(memory_backend) = self.memory_backend {
- config = config.with_memory_backend(match memory_backend {
- MemoryBackendArg::Vec => tinywasm::MemoryBackend::vec(),
- MemoryBackendArg::Paged => {
- if self.memory_page_chunk_size == 0 {
- bail!("--memory-page-chunk-size must be greater than zero");
- }
- tinywasm::MemoryBackend::paged(self.memory_page_chunk_size)
- }
- });
- }
-
if let Some(value_stack_size) = self.value_stack_size {
config = config.with_value_stack(StackConfig::fixed(value_stack_size));
}
@@ -114,10 +84,6 @@ impl EngineFlags {
config = config.with_call_stack(call_stack_dynamic.into_stack_config());
}
- if self.trap_on_oom {
- config = config.with_trap_on_oom(true);
- }
-
Ok(Engine::new(config))
}
}
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index bef6b72..877bfe1 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -3,12 +3,14 @@ pub mod cmd;
pub mod engine_flags;
pub mod load;
pub mod output;
+#[cfg(feature = "tests")]
+pub mod testsuite;
pub mod value_parse;
#[cfg(feature = "wast")]
pub mod wast_runner;
+use anyhow::Result;
use clap::CommandFactory;
-use eyre::Result;
pub use cli::{Cli, Commands};
diff --git a/crates/cli/src/load.rs b/crates/cli/src/load.rs
index 9f7c616..12c0e1f 100644
--- a/crates/cli/src/load.rs
+++ b/crates/cli/src/load.rs
@@ -2,7 +2,7 @@ use std::ffi::OsStr;
use std::io::{Read, Write};
use std::path::Path;
-use eyre::{Context, Result, bail};
+use anyhow::{Context, Result, bail};
use tinywasm::Module;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/crates/cli/src/output.rs b/crates/cli/src/output.rs
index 40a271e..75be9f8 100644
--- a/crates/cli/src/output.rs
+++ b/crates/cli/src/output.rs
@@ -48,7 +48,7 @@ pub fn format_memory_type(ty: &MemoryType) -> String {
MemoryArch::I32 => "i32",
MemoryArch::I64 => "i64",
};
- let max = if ty.page_count_max() == ty.page_count_initial() && ty.max_size() == ty.initial_size() {
+ let max = if ty.page_count_max() == ty.page_count_initial() {
ty.page_count_initial().to_string()
} else {
ty.page_count_max().to_string()
@@ -77,6 +77,7 @@ pub fn format_export_type(ty: ExportType<'_>) -> String {
ExportType::Memory(ty) => format_memory_type(ty),
ExportType::Table(ty) => format_table_type(ty),
ExportType::Global(ty) => format_global_type(ty),
+ ExportType::Tag(ty) => format!("tag {}", format_func_type(ty)),
}
}
@@ -86,5 +87,6 @@ pub fn format_import_type(ty: ImportType<'_>) -> String {
ImportType::Memory(ty) => format_memory_type(ty),
ImportType::Table(ty) => format_table_type(ty),
ImportType::Global(ty) => format_global_type(ty),
+ ImportType::Tag(ty) => format!("tag {}", format_func_type(ty)),
}
}
diff --git a/crates/tinywasm/tests/testsuite/mod.rs b/crates/cli/src/testsuite.rs
index ea44c29..b23b2c8 100644
--- a/crates/tinywasm/tests/testsuite/mod.rs
+++ b/crates/cli/src/testsuite.rs
@@ -1,11 +1,27 @@
-#![allow(dead_code)]
-
-use eyre::{Result, eyre};
+use crate::wast_runner::{GroupResult, TestFile as RunnerTestFile, WastRunner};
use owo_colors::OwoColorize;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::io::{BufRead, BufReader, Seek, SeekFrom};
-use tinywasm_cli::wast_runner::{GroupResult, TestFile as RunnerTestFile, WastRunner};
+
+/// Result type used by the WAST test utilities.
+pub type TestResult<T> = core::result::Result<T, Box<dyn core::error::Error>>;
+
+struct TestFailure(String);
+
+impl core::fmt::Debug for TestFailure {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ Display::fmt(self, f)
+ }
+}
+
+impl Display for TestFailure {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl core::error::Error for TestFailure {}
#[derive(Serialize, Deserialize)]
pub struct TestGroupResult {
@@ -27,7 +43,7 @@ impl TestSuite {
Self { runner: WastRunner::new() }
}
- pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> Result<()> {
+ pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> TestResult<()> {
let mut files = Vec::new();
for path in tests {
if path.is_dir() {
@@ -51,38 +67,39 @@ impl TestSuite {
let name = path.to_string_lossy().into_owned();
Ok((name, contents))
})
- .collect::<Result<Vec<_>>>()?;
+ .collect::<TestResult<Vec<_>>>()?;
self.runner.run_files(runner_files.iter().map(|(name, contents)| RunnerTestFile {
name: name.clone(),
parent: name.clone(),
contents,
- }))
+ }))?;
+ Ok(())
}
- pub fn run_files<'a>(&mut self, tests: impl IntoIterator<Item = wasm_testsuite::data::TestFile<'a>>) -> Result<()> {
+ pub fn run_files<'a>(
+ &mut self,
+ tests: impl IntoIterator<Item = wasm_testsuite::data::TestFile<'a>>,
+ ) -> TestResult<()> {
self.runner.run_files(tests.into_iter().map(|file| RunnerTestFile {
name: file.name().to_string(),
parent: file.parent().to_string(),
contents: file.raw(),
- }))
+ }))?;
+ Ok(())
}
pub fn print_errors(&self) {
self.runner.print_errors();
}
- pub fn report_status(&self) -> Result<()> {
- if self.runner.failed() {
- println!();
- Err(eyre!(format!("{}:\n{self}", "failed one or more tests".red().bold())))
- } else {
- println!("{self}");
- Ok(())
- }
+ pub fn report_status(&self) -> TestResult<()> {
+ self.print_errors();
+ println!("{self}");
+ if self.runner.failed() { Err(TestFailure("failed one or more tests".into()).into()) } else { Ok(()) }
}
- pub fn save_csv(&self, path: &str, version: &str) -> Result<()> {
+ pub fn save_csv(&self, path: &str, version: &str) -> TestResult<()> {
use std::fs::OpenOptions;
use std::io::Write;
diff --git a/crates/cli/src/value_parse.rs b/crates/cli/src/value_parse.rs
index eabbdc4..3191eaf 100644
--- a/crates/cli/src/value_parse.rs
+++ b/crates/cli/src/value_parse.rs
@@ -1,4 +1,4 @@
-use eyre::{Result, bail};
+use anyhow::{Result, bail};
use tinywasm::types::{FuncType, WasmType, WasmValue};
use crate::output::format_wasm_type;
@@ -33,8 +33,8 @@ fn parse_arg(index: usize, ty: WasmType, value: &str) -> Result<WasmValue> {
Ok(parsed)
}
-fn format_error(index: usize, ty: WasmType, value: &str, error: impl core::fmt::Display) -> eyre::Report {
- eyre::eyre!("failed to parse argument {} as {} from `{value}`: {error}", index + 1, format_wasm_type(ty))
+fn format_error(index: usize, ty: WasmType, value: &str, error: impl core::fmt::Display) -> anyhow::Error {
+ anyhow::anyhow!("failed to parse argument {} as {} from `{value}`: {error}", index + 1, format_wasm_type(ty))
}
#[cfg(test)]
diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs
index c773663..4ebdc6c 100644
--- a/crates/cli/src/wast_runner.rs
+++ b/crates/cli/src/wast_runner.rs
@@ -5,63 +5,77 @@ use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::time::Duration;
-use eyre::{Context, Result, bail, eyre};
+use anyhow::{Context, Result, anyhow, bail};
use log::{debug, error};
-use tinywasm::types::{ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, WasmType, WasmValue};
+use tinywasm::types::{MemoryType, RefType, RefValue, TableType, WasmType, WasmValue};
use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table};
-use wast::{QuoteWat, core::AbstractHeapType};
+use wast::QuoteWat;
+use wast::core::{AbstractHeapType, NanPattern};
const TEST_TIME_SLICE: Duration = Duration::from_millis(20);
const TEST_MAX_SUSPENSIONS: u32 = 1000;
+// Older suites classify encodings that wasmparser accepts with the latest feature set as malformed.
+const ACCEPTED_MALFORMED_MESSAGES: &[&str] =
+ &["integer representation too long", "zero byte expected", "zero flag expected"];
+const ACCEPTED_INVALID_MESSAGES: &[&str] = &["multiple memories"];
+
+macro_rules! float_value {
+ ($pattern:expr, $float:ty, $variant:ident) => {
+ match $pattern {
+ NanPattern::CanonicalNan | NanPattern::ArithmeticNan => WasmValue::$variant(<$float>::NAN),
+ NanPattern::Value(value) => WasmValue::$variant(<$float>::from_bits(value.bits)),
+ }
+ };
+}
#[derive(Default)]
struct ModuleRegistry {
- modules: HashMap<String, ModuleInstance>,
- named_modules: HashMap<String, ModuleInstance>,
- last_module: Option<ModuleInstance>,
+ definitions: HashMap<String, Module>,
+ instances: HashMap<String, ModuleInstance>,
+ registered: HashMap<String, ModuleInstance>,
+ last_definition: Option<Module>,
+ last_instance: Option<ModuleInstance>,
}
impl ModuleRegistry {
- fn modules(&self) -> &HashMap<String, ModuleInstance> {
- &self.modules
+ fn registered(&self) -> &HashMap<String, ModuleInstance> {
+ &self.registered
}
- fn update_last_module(&mut self, module: ModuleInstance, name: Option<String>) {
- self.last_module = Some(module.clone());
+ fn define(&mut self, module: Module, name: Option<String>) {
+ self.last_definition = Some(module.clone());
if let Some(name) = name {
- self.named_modules.insert(name, module);
+ self.definitions.insert(name, module);
}
}
- fn register(&mut self, name: String, module: ModuleInstance) {
- debug!("registering module: {name}");
- self.modules.insert(name.clone(), module.clone());
- self.last_module = Some(module.clone());
- self.named_modules.insert(name, module);
+ fn definition(&self, id: Option<wast::token::Id<'_>>) -> Option<Module> {
+ let Some(id) = id else { return self.last_definition.clone() };
+ self.definitions.get(id.name()).cloned()
}
- fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> {
- match module_id {
- Some(module) => self
- .modules
- .get(module.name())
- .or_else(|| self.named_modules.get(module.name()))
- .map(ModuleInstance::id),
- None => self.last_module.as_ref().map(ModuleInstance::id),
+ fn update_last_instance(&mut self, instance: ModuleInstance, name: Option<String>) {
+ self.last_instance = Some(instance.clone());
+ if let Some(name) = name {
+ self.instances.insert(name, instance);
}
}
- fn get(&self, module_id: Option<wast::token::Id<'_>>) -> Option<ModuleInstance> {
- match module_id {
- Some(module_id) => {
- self.modules.get(module_id.name()).or_else(|| self.named_modules.get(module_id.name())).cloned()
- }
- None => self.last_module.clone(),
- }
+ fn register(&mut self, name: String, id: Option<wast::token::Id<'_>>) -> bool {
+ let Some(instance) = self.get(id) else { return false };
+ debug!("registering module: {name}");
+ self.registered.insert(name, instance);
+ true
+ }
+
+ fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> {
+ let Some(module_id) = module_id else { return self.last_instance.as_ref().map(ModuleInstance::id) };
+ self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).map(ModuleInstance::id)
}
- fn last(&self) -> Option<ModuleInstance> {
- self.last_module.clone()
+ fn get(&self, module_id: Option<wast::token::Id<'_>>) -> Option<ModuleInstance> {
+ let Some(module_id) = module_id else { return self.last_instance.clone() };
+ self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned()
}
}
@@ -98,7 +112,7 @@ impl WastRunner {
self.print_errors();
if self.failed() {
anstream::println!("{self}");
- Err(eyre!("failed one or more tests"))
+ Err(anyhow!("failed one or more tests"))
} else {
anstream::println!("{self}");
Ok(())
@@ -154,17 +168,18 @@ impl WastRunner {
fn imports(store: &mut Store, modules: &HashMap<String, ModuleInstance>) -> Result<Imports> {
let mut imports = Imports::new();
- let table = Table::new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
- let table64 = Table::new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
- let memory = Memory::new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?;
+ let table = Table::try_new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
+ let table64 = Table::try_new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
+ let memory =
+ Memory::try_new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?;
let global_i32 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?;
let global_i64 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?;
let global_f32 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?;
let global_f64 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?;
imports
.define("spectest", "memory", memory)
@@ -174,20 +189,20 @@ impl WastRunner {
.define("spectest", "global_i64", global_i64)
.define("spectest", "global_f32", global_f32)
.define("spectest", "global_f64", global_f64)
- .define("spectest", "print", HostFunction::from(store, |_ctx: tinywasm::FuncContext, (): ()| Ok(())))
- .define("spectest", "print_i32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i32| Ok(())))
- .define("spectest", "print_i64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i64| Ok(())))
- .define("spectest", "print_f32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f32| Ok(())))
- .define("spectest", "print_f64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f64| Ok(())))
+ .define("spectest", "print", HostFunction::from(|_ctx: tinywasm::FuncContext, (): ()| Ok(())))
+ .define("spectest", "print_i32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i32| Ok(())))
+ .define("spectest", "print_i64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i64| Ok(())))
+ .define("spectest", "print_f32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f32| Ok(())))
+ .define("spectest", "print_f64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f64| Ok(())))
.define(
"spectest",
"print_i32_f32",
- HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())),
+ HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())),
)
.define(
"spectest",
"print_f64_f64",
- HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())),
+ HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())),
);
for (name, module) in modules {
@@ -197,6 +212,11 @@ impl WastRunner {
Ok(imports)
}
+ fn instantiate_module(store: &mut Store, registry: &ModuleRegistry, module: &Module) -> Result<ModuleInstance> {
+ let imports = Self::imports(store, registry.registered())?;
+ Ok(ModuleInstance::instantiate(store, module, Some(&imports))?)
+ }
+
pub fn run_file(&mut self, file: TestFile<'_>) -> Result<()> {
let test_group = self.test_group(file.name(), file.parent());
let wast_raw = file.raw();
@@ -205,56 +225,78 @@ impl WastRunner {
let mut store = Store::default();
let mut module_registry = ModuleRegistry::default();
+ let mut call_results = Vec::new();
println!("running {} tests for group: {}", directives.len(), file.name());
for (i, directive) in directives.into_iter().enumerate() {
let span = directive.span();
use wast::WastDirective::{
- AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, AssertUnlinkable, Invoke,
- Module as Wat, ModuleDefinition, Register,
+ AssertException, AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap,
+ AssertUnlinkable, Invoke, Module as Wat, ModuleDefinition, ModuleInstance as Instance, Register,
};
match directive {
- Register { span, name, .. } => {
- let Some(last) = module_registry.last() else {
+ Register { span, name, module } => {
+ if !module_registry.register(name.to_string(), module) {
test_group.add_result(
&format!("Register({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("no module to register")),
+ Err(anyhow!("module instance to register was not found")),
);
continue;
- };
- module_registry.register(name.to_string(), last);
+ }
test_group.add_result(&format!("Register({i})"), span.linecol_in(wast_raw), Ok(()));
}
Wat(module) => {
let result = catch_unwind_silent(|| {
- let (name, bytes) = encode_quote_wat(module);
- let module = parse_module_bytes(&bytes).expect("failed to parse module bytes");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))
+ let (name, module) = parse_quote_module(module).expect("failed to parse module bytes");
+ let instance = Self::instantiate_module(&mut store, &module_registry, &module)
.expect("failed to instantiate module");
- (name, module_instance)
+ (name, instance)
})
- .map_err(|e| eyre!("failed to parse wat module: {}", try_downcast_panic(e)));
+ .map_err(|e| anyhow!("failed to parse wat module: {}", try_downcast_panic(e)));
match &result {
Err(err) => debug!("failed to parse module: {err:?}"),
- Ok((name, module)) => module_registry.update_last_module(module.clone(), name.clone()),
+ Ok((name, instance)) => module_registry.update_last_instance(instance.clone(), name.clone()),
};
test_group.add_result(&format!("Wat({i})"), span.linecol_in(wast_raw), result.map(|_| ()));
}
ModuleDefinition(module) => {
+ let result =
+ catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition"))
+ .map_err(|err| anyhow!("failed to parse module definition: {}", try_downcast_panic(err)));
+
+ if let Ok((name, module)) = &result {
+ module_registry.define(module.clone(), name.clone());
+ }
+
+ test_group.add_result(
+ &format!("ModuleDefinition({i})"),
+ span.linecol_in(wast_raw),
+ result.map(|_| ()),
+ );
+ }
+ Instance { span, instance, module } => {
+ let name = instance.map(|id| id.name().to_string());
let result = catch_unwind_silent(|| {
- let (_, bytes) = encode_quote_wat(module);
- parse_module_bytes(&bytes)
+ let module = module_registry
+ .definition(module)
+ .ok_or_else(|| anyhow!("module definition was not found"))?;
+ Self::instantiate_module(&mut store, &module_registry, &module)
})
- .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err)))
- .and_then(|result| result)
- .map(|_| ());
+ .map_err(|err| anyhow!("failed to instantiate module definition: {}", try_downcast_panic(err)))
+ .and_then(|result| result);
- test_group.add_result(&format!("ModuleDefinition({i})"), span.linecol_in(wast_raw), result);
+ if let Ok(instance) = &result {
+ module_registry.update_last_instance(instance.clone(), name);
+ }
+ test_group.add_result(
+ &format!("ModuleInstance({i})"),
+ span.linecol_in(wast_raw),
+ result.map(|_| ()),
+ );
}
AssertMalformed { span, mut module, message } => {
let Ok(encoded) = module.encode() else {
@@ -262,52 +304,43 @@ impl WastRunner {
continue;
};
let res = catch_unwind_silent(|| parse_module_bytes(&encoded))
- .map_err(|e| eyre!("failed to parse module (expected): {}", try_downcast_panic(e)))
+ .map_err(|e| anyhow!("failed to parse module (expected): {}", try_downcast_panic(e)))
.and_then(|res| res);
test_group.add_result(
&format!("AssertMalformed({i})"),
span.linecol_in(wast_raw),
match res {
- Ok(_) => {
- if message == "zero byte expected"
- || message == "integer representation too long"
- || message == "zero flag expected"
- {
- continue;
- }
- Err(eyre!("expected module to be malformed: {message}"))
- }
+ Ok(_) if ACCEPTED_MALFORMED_MESSAGES.contains(&message) => Ok(()),
+ Ok(_) => Err(anyhow!("expected module to be malformed: {message}")),
Err(_) => Ok(()),
},
);
}
AssertInvalid { span, mut module, message } => {
- if ["multiple memories", "type mismatch"].contains(&message) {
- test_group.add_result(&format!("AssertInvalid({i})"), span.linecol_in(wast_raw), Ok(()));
- continue;
- }
let res = catch_unwind_silent(move || parse_module_bytes(&module.encode().unwrap()))
- .map_err(|e| eyre!("failed to parse module (invalid): {}", try_downcast_panic(e)))
+ .map_err(|e| anyhow!("failed to parse module (invalid): {}", try_downcast_panic(e)))
.and_then(|res| res);
test_group.add_result(
&format!("AssertInvalid({i})"),
span.linecol_in(wast_raw),
match res {
- Ok(_) => Err(eyre!("expected module to be invalid")),
+ Ok(_) if ACCEPTED_INVALID_MESSAGES.contains(&message) => Ok(()),
+ Ok(_) => Err(anyhow!("expected module to be invalid: {message}")),
Err(_) => Ok(()),
},
);
}
AssertExhaustion { call, message, span } => {
let module = module_registry.get_idx(call.module);
- let args = convert_wastargs(call.args)?;
- let res =
- catch_unwind_silent(|| exec_fn_instance(module, &mut store, call.name, &args).map(|_| ()));
+ let args = convert_wastargs(&mut store, call.args)?;
+ let res = catch_unwind_silent(|| {
+ exec_fn_instance(module, &mut store, call.name, &args, &mut call_results)
+ });
let Ok(Err(tinywasm::Error::Trap(trap))) = res else {
test_group.add_result(
&format!("AssertExhaustion({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap")),
+ Err(anyhow!("expected trap")),
);
continue;
};
@@ -315,7 +348,7 @@ impl WastRunner {
test_group.add_result(
&format!("AssertExhaustion({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap: {}, got: {}", message, trap.message())),
+ Err(anyhow!("expected trap: {}, got: {}", message, trap.message())),
);
continue;
}
@@ -327,30 +360,30 @@ impl WastRunner {
wast::WastExecute::Wat(mut wat) => {
let module = parse_module_bytes(&wat.encode().expect("failed to encode module"))
.expect("failed to parse module");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
return Ok(());
}
wast::WastExecute::Get { .. } => panic!("get not supported"),
wast::WastExecute::Invoke(invoke) => invoke,
};
let module = module_registry.get_idx(invoke.module);
- let args =
- convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ())
+ let args = convert_wastargs(&mut store, invoke.args)
+ .map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results)
});
match res {
Err(err) => test_group.add_result(
&format!("AssertTrap({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("test panicked: {}", try_downcast_panic(err))),
+ Err(anyhow!("test panicked: {}", try_downcast_panic(err))),
),
Ok(Err(tinywasm::Error::Trap(trap))) => {
if !message.starts_with(trap.message()) && !trap.message().starts_with(message) {
test_group.add_result(
&format!("AssertTrap({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap: {}, got: {}", message, trap.message())),
+ Err(anyhow!("expected trap: {}, got: {}", message, trap.message())),
);
continue;
}
@@ -359,27 +392,53 @@ impl WastRunner {
Ok(Err(err)) => test_group.add_result(
&format!("AssertTrap({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap, {}, got: {:?}", message, err)),
+ Err(anyhow!("expected trap, {}, got: {:?}", message, err)),
),
Ok(Ok(())) => test_group.add_result(
&format!("AssertTrap({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap {}, got Ok", message)),
+ Err(anyhow!("expected trap {}, got Ok", message)),
),
}
}
+ AssertException { exec, span } => {
+ let res: Result<tinywasm::Result<()>, _> = catch_unwind_silent(|| {
+ let invoke = match exec {
+ wast::WastExecute::Wat(mut wat) => {
+ let module = parse_module_bytes(&wat.encode().expect("failed to encode module"))
+ .expect("failed to parse module");
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ return Ok(());
+ }
+ wast::WastExecute::Get { .. } => panic!("get not supported"),
+ wast::WastExecute::Invoke(invoke) => invoke,
+ };
+ let module = module_registry.get_idx(invoke.module);
+ let args = convert_wastargs(&mut store, invoke.args)
+ .map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results)
+ });
+ let result = match res {
+ Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))),
+ Ok(Err(tinywasm::Error::Exception(_))) => Ok(()),
+ Ok(Err(err)) => Err(anyhow!("expected exception, got: {err:?}")),
+ Ok(Ok(())) => Err(anyhow!("expected exception, got Ok")),
+ };
+ test_group.add_result(&format!("AssertException({i})"), span.linecol_in(wast_raw), result);
+ }
AssertUnlinkable { mut module, span, message } => {
let res = catch_unwind_silent(|| {
let module = parse_module_bytes(&module.encode().expect("failed to encode module"))
.expect("failed to parse module");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- ModuleInstance::instantiate(&mut store, &module, Some(imports))
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))
});
match res {
Err(err) => test_group.add_result(
&format!("AssertUnlinkable({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("test panicked: {}", try_downcast_panic(err))),
+ Err(anyhow!("test panicked: {}", try_downcast_panic(err))),
),
Ok(Err(tinywasm::Error::Linker(err))) => {
if err.message() != message
@@ -389,7 +448,7 @@ impl WastRunner {
test_group.add_result(
&format!("AssertUnlinkable({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected linker error: {}, got: {}", message, err.message())),
+ Err(anyhow!("expected linker error: {}, got: {}", message, err.message())),
);
continue;
}
@@ -398,27 +457,27 @@ impl WastRunner {
Ok(Err(err)) => test_group.add_result(
&format!("AssertUnlinkable({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected linker error, {}, got: {:?}", message, err)),
+ Err(anyhow!("expected linker error, {}, got: {:?}", message, err)),
),
Ok(Ok(_)) => test_group.add_result(
&format!("AssertUnlinkable({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected linker error {}, got Ok", message)),
+ Err(anyhow!("expected linker error {}, got Ok", message)),
),
}
}
Invoke(invoke) => {
let name = invoke.name;
let res: Result<Result<()>, _> = catch_unwind_silent(|| {
- let args = convert_wastargs(invoke.args)?;
+ let args = convert_wastargs(&mut store, invoke.args)?;
let module = module_registry.get_idx(invoke.module);
- exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| {
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results).map_err(|e| {
error!("failed to execute function: {e:?}");
e
})?;
Ok(())
});
- let res = res.map_err(|e| eyre!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r);
+ let res = res.map_err(|e| anyhow!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r);
test_group.add_result(&format!("Invoke({name}-{i})"), span.linecol_in(wast_raw), res);
}
AssertReturn { span, exec, results } => {
@@ -427,7 +486,7 @@ impl WastRunner {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
span.linecol_in(wast_raw),
- Err(eyre!("failed to convert expected results: {err:?}")),
+ Err(anyhow!("failed to convert expected results: {err:?}")),
);
continue;
}
@@ -435,23 +494,23 @@ impl WastRunner {
};
let invoke = match match exec {
- wast::WastExecute::Wat(_) => Err(eyre!("wat not supported")),
+ wast::WastExecute::Wat(_) => Err(anyhow!("wat not supported")),
wast::WastExecute::Get { module: module_id, global, .. } => {
let Some(module) = module_registry.get(module_id) else {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
span.linecol_in(wast_raw),
- Err(eyre!("no module to get global from")),
+ Err(anyhow!("no module to get global from")),
);
continue;
};
- let module_global = match module.global_get(&store, global) {
+ let module_global = match module.global_get(&mut store, global) {
Ok(value) => value,
Err(err) => {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
span.linecol_in(wast_raw),
- Err(eyre!("failed to get global: {err:?}")),
+ Err(anyhow!("failed to get global: {err:?}")),
);
continue;
}
@@ -459,12 +518,12 @@ 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, &module));
if expected.is_none() {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
span.linecol_in(wast_raw),
- Err(eyre!(
+ Err(anyhow!(
"global value did not match any expected alternative: {:?}",
module_global
)),
@@ -485,7 +544,7 @@ impl WastRunner {
test_group.add_result(
&format!("AssertReturn(unsupported-{i})"),
span.linecol_in(wast_raw),
- Err(eyre!("unsupported directive: {err:?}")),
+ Err(anyhow!("unsupported directive: {err:?}")),
);
continue;
}
@@ -493,36 +552,42 @@ impl WastRunner {
let invoke_name = invoke.name;
let res: Result<Result<()>, _> = catch_unwind_silent(|| {
- let args = convert_wastargs(invoke.args)?;
- let module = module_registry.get_idx(invoke.module);
- let outcomes = exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| {
- error!("failed to execute function: {e:?}");
- e
- })?;
- if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) {
- return Err(eyre!(
+ let args = convert_wastargs(&mut store, invoke.args)?;
+ let module = module_registry
+ .get(invoke.module)
+ .ok_or_else(|| anyhow!("module instance was not found"))?;
+ exec_fn_instance(Some(module.id()), &mut store, invoke.name, &args, &mut call_results)
+ .map_err(|e| {
+ error!("failed to execute function: {e:?}");
+ e
+ })?;
+ if !expected_alternatives.iter().any(|expected| expected.len() == call_results.len()) {
+ return Err(anyhow!(
"expected {} results, got {}",
expected_alternatives.first().map_or(0, |v| v.len()),
- outcomes.len()
+ call_results.len()
));
}
if expected_alternatives.iter().any(|expected| {
- expected.len() == outcomes.len()
- && outcomes.iter().zip(expected.iter()).all(|(outcome, exp)| exp.matches(outcome))
+ expected.len() == call_results.len()
+ && call_results
+ .iter()
+ .zip(expected.iter())
+ .all(|(outcome, exp)| exp.matches(outcome, &store, &module))
}) {
Ok(())
} else {
- Err(eyre!("results did not match any expected alternative"))
+ Err(anyhow!("results did not match any expected alternative"))
}
});
- let res = res.map_err(|e| eyre!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r);
+ let res = res.map_err(|e| anyhow!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r);
test_group.add_result(&format!("AssertReturn({invoke_name}-{i})"), span.linecol_in(wast_raw), res);
}
_ => test_group.add_result(
&format!("Unknown({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("unsupported directive")),
+ Err(anyhow!("unsupported directive")),
),
}
}
@@ -594,17 +659,20 @@ struct TestCase {
fn expand_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
- for path in paths {
+ let mut pending = paths.to_vec();
+ while let Some(path) = pending.pop() {
if path.is_dir() {
- for entry in std::fs::read_dir(path)? {
+ for entry in std::fs::read_dir(&path)? {
let entry = entry?;
let path = entry.path();
- if path.extension().is_some_and(|ext| ext == "wast") {
+ if entry.file_type()?.is_dir() {
+ pending.push(path);
+ } else if path.extension().is_some_and(|ext| ext == "wast") {
files.push(path);
}
}
} else {
- files.push(path.clone());
+ files.push(path);
}
}
files.sort();
@@ -653,12 +721,12 @@ fn exec_with_budget(
func: &tinywasm::Function,
store: &mut Store,
args: &[WasmValue],
-) -> Result<Vec<WasmValue>, tinywasm::Error> {
- let mut exec = func.call_resumable(store, args)?;
+ results: &mut [WasmValue],
+) -> Result<(), tinywasm::Error> {
+ let mut exec = func.call_resumable(store, args, results)?;
for _ in 0..TEST_MAX_SUSPENSIONS {
- match exec.resume_with_time_budget(TEST_TIME_SLICE)? {
- ExecProgress::Completed(values) => return Ok(values),
- ExecProgress::Suspended => {}
+ if let ExecProgress::Completed(()) = exec.resume_with_time_budget(TEST_TIME_SLICE)? {
+ return Ok(());
}
}
Err(tinywasm::Error::Other(format!(
@@ -679,7 +747,8 @@ fn exec_fn_instance(
store: &mut Store,
name: &str,
args: &[WasmValue],
-) -> Result<Vec<WasmValue>, tinywasm::Error> {
+ results: &mut Vec<WasmValue>,
+) -> Result<(), tinywasm::Error> {
let Some(instance) = instance else {
return Err(tinywasm::Error::Other("no instance found".to_string()));
};
@@ -687,7 +756,9 @@ fn exec_fn_instance(
return Err(tinywasm::Error::Other("no instance found".to_string()));
};
let func = instance.func_untyped(store, name)?;
- exec_with_budget(&func, store, args)
+ results.clear();
+ results.resize(func.ty(store)?.results().len(), WasmValue::I32(0));
+ exec_with_budget(&func, store, args, results)
}
fn catch_unwind_silent<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
@@ -723,8 +794,13 @@ fn parse_module_bytes(bytes: &[u8]) -> Result<Module> {
Ok(tinywasm::parse_bytes(bytes)?)
}
-fn convert_wastargs(args: Vec<wast::WastArg>) -> Result<Vec<WasmValue>> {
- args.into_iter().map(wastarg2tinywasmvalue).collect()
+fn parse_quote_module(module: QuoteWat) -> Result<(Option<String>, Module)> {
+ let (name, bytes) = encode_quote_wat(module);
+ Ok((name, parse_module_bytes(&bytes)?))
+}
+
+fn convert_wastargs(store: &mut Store, args: Vec<wast::WastArg>) -> Result<Vec<WasmValue>> {
+ args.into_iter().map(|arg| wastarg2tinywasmvalue(store, arg)).collect()
}
fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<Vec<Vec<ExpectedValue>>> {
@@ -735,7 +811,7 @@ fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<
for prefix in alternatives {
for choice in &choices {
let mut candidate = prefix.clone();
- candidate.push(*choice);
+ candidate.push(choice.clone());
next.push(candidate);
}
}
@@ -744,7 +820,7 @@ fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<
Ok(alternatives)
}
-fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result<WasmValue> {
+fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result<WasmValue> {
let wast::WastArg::Core(arg) = arg else {
bail!("unsupported arg type: Component");
};
@@ -755,27 +831,27 @@ 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) => tinywasm::ExternRef::try_new(store, v)?.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(tinywasm::ExternRef::try_new(store, value)?.to_any()).into(),
})
}
fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] {
let res: Vec<u8> = match i {
wast::core::V128Pattern::F32x4(f) => {
- f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f32().unwrap().to_le_bytes()).collect()
+ f.iter().flat_map(|v| float_value!(*v, f32, F32).as_f32().unwrap().to_le_bytes()).collect()
}
wast::core::V128Pattern::F64x2(f) => {
- f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f64().unwrap().to_le_bytes()).collect()
+ f.iter().flat_map(|v| float_value!(*v, f64, F64).as_f64().unwrap().to_le_bytes()).collect()
}
wast::core::V128Pattern::I16x8(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(),
wast::core::V128Pattern::I32x4(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(),
@@ -785,21 +861,46 @@ fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] {
res.try_into().unwrap()
}
-#[derive(Clone, Copy)]
+#[derive(Clone)]
enum ExpectedValue {
Exact(WasmValue),
RefNull,
RefFunc,
RefExtern,
+ RefAny,
+ RefEq,
+ RefI31,
+ RefStruct,
+ RefArray,
+ RefExternExact(u32),
+ RefFuncExact(u32),
+ RefHostExact(u32),
}
impl ExpectedValue {
- fn matches(&self, value: &WasmValue) -> bool {
+ fn matches(&self, value: &WasmValue, store: &Store, module: &ModuleInstance) -> 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 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_eq().is_some()),
+ Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()),
+ Self::RefStruct => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_struct().is_some()),
+ Self::RefArray => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_array().is_some()),
+ Self::RefExternExact(expected) => match value {
+ WasmValue::Ref(RefValue::Extern(value)) => value.key(store) == Ok(*expected),
+ _ => false,
+ },
+ Self::RefHostExact(expected) => match value {
+ WasmValue::Ref(RefValue::Any(value)) => value.to_extern().key(store) == Ok(*expected),
+ _ => false,
+ },
+ Self::RefFuncExact(expected) => module
+ .func_by_index(store, *expected)
+ .and_then(|function| function.as_func_ref(store))
+ .is_ok_and(|expected| matches!(value, WasmValue::Ref(RefValue::Func(value)) if *value == expected)),
}
}
}
@@ -817,84 +918,36 @@ 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)?),
+ F32(f) => ExpectedValue::Exact(float_value!(f, f32, F32)),
+ F64(f) => ExpectedValue::Exact(float_value!(f, f64, F64)),
I32(i) => ExpectedValue::Exact(WasmValue::I32(i)),
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::RefExternExact(v),
RefExtern(None) => ExpectedValue::RefExtern,
- RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()),
+ RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::RefFuncExact(n),
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::RefHostExact(value),
a => {
bail!("unsupported arg type {:?}", a);
}
})
}
-enum Bits {
- U32(u32),
- U64(u64),
-}
-
-trait FloatToken {
- fn bits(&self) -> Bits;
- fn canonical_nan() -> WasmValue;
- fn arithmetic_nan() -> WasmValue;
- fn value(&self) -> WasmValue {
- match self.bits() {
- Bits::U32(v) => WasmValue::F32(f32::from_bits(v)),
- Bits::U64(v) => WasmValue::F64(f64::from_bits(v)),
- }
- }
-}
-
-impl FloatToken for wast::token::F32 {
- fn bits(&self) -> Bits {
- Bits::U32(self.bits)
- }
-
- fn canonical_nan() -> WasmValue {
- WasmValue::F32(f32::NAN)
- }
-
- fn arithmetic_nan() -> WasmValue {
- WasmValue::F32(f32::NAN)
- }
-}
-
-impl FloatToken for wast::token::F64 {
- fn bits(&self) -> Bits {
- Bits::U64(self.bits)
- }
-
- fn canonical_nan() -> WasmValue {
- WasmValue::F64(f64::NAN)
- }
-
- fn arithmetic_nan() -> WasmValue {
- WasmValue::F64(f64::NAN)
- }
-}
-
-fn nanpattern2tinywasmvalue<T>(arg: wast::core::NanPattern<T>) -> Result<WasmValue>
-where
- T: FloatToken,
-{
- use wast::core::NanPattern::{ArithmeticNan, CanonicalNan, Value};
- Ok(match arg {
- CanonicalNan => T::canonical_nan(),
- ArithmeticNan => T::arithmetic_nan(),
- Value(v) => v.value(),
- })
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -912,4 +965,38 @@ mod tests {
let mut runner = WastRunner::new();
runner.run_paths(&[path]).unwrap();
}
+
+ #[test]
+ fn recursively_runs_wast_files_and_ignores_other_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let nested = dir.path().join("nested");
+ std::fs::create_dir(&nested).unwrap();
+ std::fs::write(dir.path().join("README.md"), "not a wast file").unwrap();
+ std::fs::write(nested.join("simple.wast"), "(module)").unwrap();
+
+ let mut runner = WastRunner::new();
+ runner.run_paths(&[dir.path().to_path_buf()]).unwrap();
+ }
+
+ #[test]
+ fn runs_module_definition_and_instance_directives() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("instance.wast");
+ std::fs::write(
+ &path,
+ r#"
+ (module definition $M (global (export "g") i32 (i32.const 42)))
+ (module instance $I $M)
+ (register "I" $I)
+ (module
+ (import "I" "g" (global $g i32))
+ (func (export "get") (result i32) global.get $g))
+ (assert_return (invoke "get") (i32.const 42))
+ "#,
+ )
+ .unwrap();
+
+ let mut runner = WastRunner::new();
+ runner.run_paths(&[path]).unwrap();
+ }
}
diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml
index 3e71403..afedeed 100644
--- a/crates/parser/Cargo.toml
+++ b/crates/parser/Cargo.toml
@@ -4,7 +4,7 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Parser and lowering pipeline for TinyWasm"
-readme = "README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
@@ -13,10 +13,25 @@ categories.workspace = true
[dependencies]
log = { workspace = true, optional = true }
tinywasm-types = { workspace = true }
-wasmparser = { workspace = true, features = ["features", "simd", "validate"] }
+wasmparser = { workspace = true, features = ["simd"] }
[features]
-default = ["log", "parallel", "std"]
+default = ["log", "parallel", "std", "validate"]
+
+# enable integration with the log crate
log = ["dep:log"]
+
+# parse and validate function bodies in parallel (requires std)
parallel = ["std"]
+
+# support targets without native atomic CAS
+portable-atomic = ["tinywasm-types/portable-atomic"]
+
+# enable standard library support
std = ["tinywasm-types/std", "wasmparser/std"]
+
+# validate WebAssembly while parsing
+validate = ["wasmparser/features", "wasmparser/validate"]
+
+[lints]
+workspace = true
diff --git a/crates/parser/README.md b/crates/parser/README.md
index 91145f1..cf1a6c4 100644
--- a/crates/parser/README.md
+++ b/crates/parser/README.md
@@ -6,7 +6,8 @@ This crate provides the parser and lowering pipeline that converts WebAssembly b
- `std`: Enables the use of `std` and `std::io` for parsing from files and streams.
- `log`: Enables logging of the parsing process using the `log` crate.
-- `parallel`: Enables multithreaded parsing and validation when `std` is available.
+- `parallel`: Enables multithreaded function parsing. Requires `std`.
+- `validate`: Enables `wasmparser` validation. Enabled by default and configurable through `ParserOptions`.
## Usage
@@ -15,10 +16,10 @@ use tinywasm_parser::{Parser, ParserOptions};
let bytes = include_bytes!("./file.wasm");
-let parser = Parser::new();
+let parser = Parser::default();
let module = parser.parse_module_bytes(bytes)?;
-let parser = Parser::with_options(ParserOptions::default().with_rewrite_optimization(false));
+let parser = Parser::new(ParserOptions::default().with_rewrite_optimization(false));
let module = parser.parse_module_bytes(bytes)?;
let module = parser.parse_module_file("path/to/file.wasm")?;
@@ -26,4 +27,4 @@ let mut stream = std::fs::File::open("path/to/file.wasm")?;
let module = parser.parse_module_stream(&mut stream)?;
```
-If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::new()`.
+If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::default()`.
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index db8d2aa..36455ee 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -1,16 +1,38 @@
-use crate::{Result, module::FunctionCode, visit::process_operators_and_validate};
-use alloc::{boxed::Box, format, string::ToString, vec::Vec};
+use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources};
+#[cfg(feature = "validate")]
+use crate::visit::process_operators_and_validate;
+use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators};
+use alloc::{boxed::Box, format, vec::Vec};
use tinywasm_types::*;
-use wasmparser::{
- CompositeInnerType, FuncValidator, FuncValidatorAllocations, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources,
-};
+use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex};
-pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
+/// Function identity and result layout shared by lowering and finalization.
+#[derive(Clone, Copy)]
+pub(crate) struct FunctionLoweringContext {
+ /// Module type index of the function signature.
+ pub(crate) ty_idx: u32,
+ /// Module function index, including imported functions.
+ pub(crate) self_func_addr: u32,
+ /// Result counts in each physical value lane.
+ pub(crate) function_results: ValueCounts,
+}
+
+pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane {
+ match ty {
+ wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32,
+ wasmparser::ValType::I64 | wasmparser::ValType::F64 => ValueLane::S64,
+ wasmparser::ValType::V128 => ValueLane::S128,
+ }
+}
+
+pub(crate) fn convert_module_element(
+ element: wasmparser::Element<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Element> {
let kind = match element.kind {
wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active {
table: table_index.unwrap_or(0),
- offset: process_const_operators(offset_expr.get_operators_reader())?,
+ offset: process_const_operators(offset_expr.get_operators_reader(), global_types)?,
},
wasmparser::ElementKind::Passive => tinywasm_types::ElementKind::Passive,
wasmparser::ElementKind::Declared => tinywasm_types::ElementKind::Declared,
@@ -30,7 +52,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
wasmparser::ElementItems::Expressions(ty, exprs) => {
let items = exprs
.into_iter()
- .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader())?)))
+ .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader(), global_types)?)))
.collect::<Result<Vec<_>>>()?
.into_boxed_slice();
@@ -39,13 +61,16 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
}
}
-pub(crate) fn convert_module_data(data: wasmparser::Data<'_>) -> Result<tinywasm_types::Data> {
+pub(crate) fn convert_module_data(
+ data: wasmparser::Data<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Data> {
Ok(tinywasm_types::Data {
- data: data.data.to_vec().into_boxed_slice(),
+ data: data.data.into(),
range: data.range,
kind: match data.kind {
wasmparser::DataKind::Active { memory_index, offset_expr } => {
- let offset = process_const_operators(offset_expr.get_operators_reader())?;
+ let offset = process_const_operators(offset_expr.get_operators_reader(), global_types)?;
tinywasm_types::DataKind::Active { mem: memory_index, offset }
}
wasmparser::DataKind::Passive => tinywasm_types::DataKind::Passive,
@@ -68,9 +93,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im
wasmparser::TypeRef::Global(ty) => {
ImportKind::Global(GlobalType::new(convert_valtype(&ty.content_type)?, ty.mutable))
}
- wasmparser::TypeRef::Tag(ty) => {
- return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}")));
- }
+ wasmparser::TypeRef::Tag(ty) => ImportKind::Tag(convert_tag_type(ty)),
_ => {
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", import.ty)));
}
@@ -90,16 +113,17 @@ pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> MemoryTyp
pub(crate) fn convert_module_globals(
globals: wasmparser::SectionLimited<'_, wasmparser::Global<'_>>,
+ global_types: &mut Vec<WasmType>,
) -> Result<Box<[Global]>> {
- globals
- .into_iter()
- .map(|global| {
- let global = global?;
- let ty = convert_valtype(&global.ty.content_type)?;
- let ops = global.init_expr.get_operators_reader();
- Ok(Global { init: process_const_operators(ops)?, ty: GlobalType::new(ty, global.ty.mutable) })
- })
- .collect::<Result<Box<_>>>()
+ let mut out = Vec::with_capacity(globals.count() as usize);
+ for global in globals {
+ let global = global?;
+ let ty = convert_valtype(&global.ty.content_type)?;
+ let init = process_const_operators(global.init_expr.get_operators_reader(), global_types)?;
+ global_types.push(ty);
+ out.push(Global { init, ty: GlobalType::new(ty, global.ty.mutable) });
+ }
+ Ok(out.into_boxed_slice())
}
pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Export> {
@@ -108,7 +132,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex
wasmparser::ExternalKind::Table => ExternalKind::Table,
wasmparser::ExternalKind::Memory => ExternalKind::Memory,
wasmparser::ExternalKind::Global => ExternalKind::Global,
- wasmparser::ExternalKind::Tag | wasmparser::ExternalKind::FuncExact => {
+ wasmparser::ExternalKind::Tag => ExternalKind::Tag,
+ wasmparser::ExternalKind::FuncExact => {
return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported export kind: {:?}", export.kind)));
}
};
@@ -116,72 +141,166 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex
Ok(Export { index: export.index, name: Box::from(export.name), kind })
}
+pub(crate) const fn convert_tag_type(ty: wasmparser::TagType) -> TagType {
+ TagType::new(ty.func_type_idx)
+}
+
+fn extend_local_types(local_types: &mut Vec<ValueLane>, count: u32, ty: wasmparser::ValType) -> Result<()> {
+ let size = value_lane(ty);
+ let count =
+ usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?;
+ local_types.reserve(count);
+ local_types.extend(core::iter::repeat_n(size, count));
+ Ok(())
+}
+
pub(crate) fn convert_module_code(
func: wasmparser::FunctionBody<'_>,
- mut validator: Option<FuncValidator<ValidatorResources>>,
+ validator: Option<FuncValidator<ValidatorResources>>,
reader_allocs: OperatorsReaderAllocations,
metadata: &crate::visit::ModuleMetadata,
- ty_idx: u32,
+ context: FunctionLoweringContext,
+ options: &ParserOptions,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
- let locals_reader = func.get_locals_reader()?;
- let pos = locals_reader.original_position();
- let signature = metadata.signature(ty_idx)?.clone();
- let mut local_types = signature.params.clone();
+ let mut locals_reader = func.get_locals_reader()?;
+ let mut local_types = metadata.signature(context.ty_idx)?.params.clone();
- for (i, local) in locals_reader.into_iter().enumerate() {
- let local = local?;
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+
+ for _ in 0..locals_reader.get_count() {
+ #[cfg(feature = "validate")]
+ let position = locals_reader.original_position();
+ let local = locals_reader.read()?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
- validator.define_locals(pos + i, local.0, local.1)?;
+ validator.define_locals(position, local.0, local.1)?;
}
- let size = crate::visit::OperandSize::from(local.1);
- let count = usize::try_from(local.0)
- .map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?;
- local_types.reserve(count);
- local_types.extend(core::iter::repeat_n(size, count));
+ extend_local_types(&mut local_types, local.0, local.1)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
+
// maps a local's address to the index in the type's locals array
let mut local_addr_map = Vec::with_capacity(local_types.len());
let mut local_counts = ValueCounts::default();
for ty in &local_types {
let (count, error) = match ty {
- crate::visit::OperandSize::S32 => (&mut local_counts.c32, "too many 32-bit locals"),
- crate::visit::OperandSize::S64 => (&mut local_counts.c64, "too many 64-bit locals"),
- crate::visit::OperandSize::S128 => (&mut local_counts.c128, "too many 128-bit locals"),
+ ValueLane::S32 => (&mut local_counts.c32, "too many 32-bit locals"),
+ ValueLane::S64 => (&mut local_counts.c64, "too many 64-bit locals"),
+ ValueLane::S128 => (&mut local_counts.c128, "too many 128-bit locals"),
};
local_addr_map.push(*count);
*count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?;
}
- let (body, data, validator_allocs, reader_allocs) =
- process_operators_and_validate(validator, func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?;
+ #[cfg(feature = "validate")]
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = match validator {
+ Some(validator) => {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate(
+ validator,
+ func,
+ (local_types, local_addr_map),
+ metadata,
+ context,
+ reader_allocs,
+ options,
+ )?;
+ (body, data, uses_local_memory, Some(validator_allocs), reader_allocs)
+ }
+ None => {
+ let (body, data, uses_local_memory, reader_allocs) =
+ process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?;
+ (body, data, uses_local_memory, None, reader_allocs)
+ }
+ };
+ #[cfg(not(feature = "validate"))]
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = {
+ let _ = validator;
+ let (body, data, uses_local_memory, reader_allocs) =
+ process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?;
+ (body, data, uses_local_memory, None, reader_allocs)
+ };
Ok((
- FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false },
+ FunctionCode { instructions: body, data: data.finish(), locals: local_counts, uses_local_memory },
validator_allocs,
reader_allocs,
))
}
-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> {
@@ -189,17 +308,30 @@ 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)?))
+ }
}
}
-pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[ConstInstruction]>> {
+pub(crate) fn process_const_operators(
+ ops: OperatorsReader<'_>,
+ global_types: &[WasmType],
+) -> Result<Box<[ConstInstruction]>> {
let mut out = Vec::new();
let mut operator_count = 0;
let mut end_reached = false;
@@ -213,19 +345,36 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
}
let instr = match op {
- wasmparser::Operator::RefNull { hty } => {
- convert_heap_type(hty, false)?;
- ConstInstruction::Ref(RefValue::Null)
- }
+ wasmparser::Operator::RefNull { hty } => ConstInstruction::RefNull(convert_heap_type(hty, true)?),
wasmparser::Operator::RefFunc { function_index } => {
- ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index)))
+ ConstInstruction::RefFunc(ModuleFuncIdx::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())),
wasmparser::Operator::F64Const { value } => ConstInstruction::F64Const(f64::from_bits(value.bits())),
wasmparser::Operator::V128Const { value } => ConstInstruction::V128Const(*value.bytes()),
- wasmparser::Operator::GlobalGet { global_index } => ConstInstruction::GlobalGet(global_index),
+ wasmparser::Operator::GlobalGet { global_index } => match global_types.get(global_index as usize) {
+ Some(WasmType::I32 | WasmType::F32) => ConstInstruction::GlobalGet32(global_index),
+ Some(WasmType::I64 | WasmType::F64) => ConstInstruction::GlobalGet64(global_index),
+ Some(WasmType::V128) => ConstInstruction::GlobalGet128(global_index),
+ Some(WasmType::Ref(_)) => ConstInstruction::GlobalGetRef(global_index),
+ None => return Err(crate::ParseError::Other(format!("global index out of bounds: {global_index}"))),
+ },
wasmparser::Operator::I32Add => ConstInstruction::I32Add,
wasmparser::Operator::I32Sub => ConstInstruction::I32Sub,
wasmparser::Operator::I32Mul => ConstInstruction::I32Mul,
@@ -249,6 +398,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,
@@ -271,11 +428,24 @@ 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:?}"))
- })?;
- RefType::new_concrete(nullable, index)
- .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {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}"
+ )));
+ }
+ };
+ Ok(RefType::new_concrete(nullable, index))
}
wasmparser::HeapType::Abstract { shared: true, .. } | wasmparser::HeapType::Exact(_) => {
Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}")))
diff --git a/crates/parser/src/emitter.rs b/crates/parser/src/emitter.rs
new file mode 100644
index 0000000..d36444a
--- /dev/null
+++ b/crates/parser/src/emitter.rs
@@ -0,0 +1,355 @@
+//! Streaming instruction selection with stable labels and target-only relocation.
+
+use crate::{
+ ParseError, ParserOptions, Result, conversion::FunctionLoweringContext, selection, visit::FunctionDataBuilder,
+};
+use alloc::vec::Vec;
+use tinywasm_types::{BranchTableOperand, ExceptionCatch, ExceptionHandler, Instruction, Operand128, ValueCounts};
+
+const LOOKBEHIND: usize = 3;
+
+/// Restricted vector view, with no readable or mutable access to the committed prefix.
+pub(crate) struct PendingTail<'a> {
+ instructions: &'a mut Vec<Instruction>,
+ start: usize,
+}
+
+impl<'a> PendingTail<'a> {
+ fn new(instructions: &'a mut Vec<Instruction>, start: usize) -> Self {
+ assert!(start < instructions.len() && instructions.len() - start <= LOOKBEHIND + 1);
+ Self { instructions, start }
+ }
+
+ /// Copies at most four pending instructions, including the incoming instruction.
+ pub(crate) fn suffix<const N: usize>(&self) -> Option<[Instruction; N]> {
+ const { assert!(N > 0 && N <= LOOKBEHIND + 1) };
+ let pending = &self.instructions[self.start..];
+ let start = pending.len().checked_sub(N)?;
+ Some(pending[start..].try_into().unwrap())
+ }
+
+ /// Splices a non-growing suffix and truncates immediately, leaving no holes.
+ pub(crate) fn replace<const N: usize, const M: usize>(&mut self, replacements: [Instruction; M]) {
+ const {
+ assert!(N > 0 && N <= LOOKBEHIND + 1);
+ assert!(M <= N);
+ }
+ let pending = &mut self.instructions[self.start..];
+ let start = pending.len().checked_sub(N).expect("replacement exceeds pending tail");
+ pending[start..start + M].copy_from_slice(&replacements);
+ self.instructions.truncate(self.start + start + M);
+ }
+}
+
+/// Identity of a stable instruction boundary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct LabelId(usize);
+
+enum PatchSite {
+ Instruction(usize),
+ TableEntry(usize),
+ ExceptionStart(usize),
+ ExceptionEnd(usize),
+ Catch(usize, usize),
+}
+
+/// Owns one instruction vector with an immutable prefix and at most three pending instructions.
+pub(crate) struct Emitter {
+ instructions: Vec<Instruction>,
+ committed: usize,
+ select: bool,
+ self_func_addr: u32,
+ return_instruction: Instruction,
+ pending_jump: Option<LabelId>,
+ labels: Vec<Option<u32>>,
+ uses: Vec<(PatchSite, LabelId)>,
+}
+
+impl Emitter {
+ /// Creates an emitter with a bounded initial allocation.
+ pub(crate) fn new(body_size: usize, context: FunctionLoweringContext, options: &ParserOptions) -> Self {
+ use Instruction::*;
+ let return_instruction = match (options.optimize(), context.function_results) {
+ (true, ValueCounts { c32: 0, c64: 0, c128: 0 }) => ReturnVoid,
+ (true, ValueCounts { c32: 1, c64: 0, c128: 0 }) => Return32,
+ (true, ValueCounts { c32: 0, c64: 1, c128: 0 }) => Return64,
+ (true, ValueCounts { c32: 0, c64: 0, c128: 1 }) => Return128,
+ _ => Return,
+ };
+ Self {
+ instructions: Vec::with_capacity(body_size.min(1024)),
+ committed: 0,
+ select: options.optimize(),
+ self_func_addr: context.self_func_addr,
+ return_instruction,
+ pending_jump: None,
+ labels: Vec::new(),
+ uses: Vec::new(),
+ }
+ }
+
+ /// Whether lowering may select optimized instruction and target forms.
+ pub(crate) fn optimizations_enabled(&self) -> bool {
+ self.select
+ }
+
+ /// Allocates an unbound structural or executable label.
+ pub(crate) fn new_label(&mut self) -> LabelId {
+ let label = LabelId(self.labels.len());
+ self.labels.push(None);
+ label
+ }
+
+ /// Flushes the pending tail and records a stable boundary.
+ pub(crate) fn bind(&mut self, label: LabelId) -> Result<()> {
+ // Only the uncommitted jump can disappear. Any other binding seals it,
+ // so removing it cannot move a previously bound boundary.
+ if self.pending_jump == Some(label) {
+ debug_assert_eq!(self.instructions.len(), self.committed + 1);
+ debug_assert!(matches!(self.instructions.last(), Some(Instruction::Jump(_))));
+ self.pending_jump = None;
+ self.instructions.pop();
+ }
+ self.seal_jump();
+ self.commit(self.instructions.len());
+ let offset = u32::try_from(self.instructions.len())
+ .map_err(|_| ParseError::Other("function body is too large".into()))?;
+ let binding = self.labels.get_mut(label.0).ok_or_else(|| ParseError::Other("unknown label".into()))?;
+ if binding.is_some() {
+ return Err(ParseError::Other("label bound more than once".into()));
+ }
+ *binding = Some(offset);
+ Ok(())
+ }
+
+ /// Appends an instruction without applying logical stack effects.
+ #[inline]
+ pub(crate) fn emit(&mut self, instruction: Instruction) -> Result<()> {
+ self.push(instruction)?;
+ self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed));
+ Ok(())
+ }
+
+ /// Emits a call or terminator and seals the tail against subsequent fusion.
+ pub(crate) fn emit_boundary(&mut self, instruction: Instruction) -> Result<()> {
+ use Instruction::*;
+ let instruction = match instruction {
+ Call(address) if self.select && address == self.self_func_addr => CallSelf,
+ ReturnCall(address) if self.select && address == self.self_func_addr => ReturnCallSelf,
+ Return => self.return_instruction,
+ _ => instruction,
+ };
+ self.push(instruction)?;
+ self.commit(self.instructions.len());
+ Ok(())
+ }
+
+ fn push(&mut self, instruction: Instruction) -> Result<()> {
+ self.seal_jump();
+ if self.instructions.len() >= u32::MAX as usize {
+ return Err(ParseError::Other("function body is too large".into()));
+ }
+ self.instructions.push(instruction);
+ Ok(())
+ }
+
+ fn seal_jump(&mut self) {
+ if let Some(label) = self.pending_jump.take() {
+ self.uses.push((PatchSite::Instruction(self.instructions.len() - 1), label));
+ self.committed = self.instructions.len();
+ }
+ }
+
+ /// Appends and applies one statically selected family, without redispatching replacements.
+ #[inline]
+ pub(crate) fn emit_with(
+ &mut self,
+ data: &mut FunctionDataBuilder,
+ instruction: Instruction,
+ rules: impl FnOnce(&mut PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>,
+ ) -> Result<()> {
+ self.push(instruction)?;
+ if self.select {
+ rules(&mut PendingTail::new(&mut self.instructions, self.committed), data)?;
+ }
+ self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed));
+ Ok(())
+ }
+
+ /// Selects a conditional branch before sealing and recording its final patch site.
+ pub(crate) fn branch_if(&mut self, data: &mut FunctionDataBuilder, on_zero: bool, label: LabelId) -> Result<()> {
+ let instruction = if on_zero { Instruction::JumpIfZero32(0) } else { Instruction::JumpIfNonZero32(0) };
+ self.emit_with(data, instruction, |tail, data| selection::conditional(tail, data, on_zero, 0))?;
+ // Conditional rules always retain a final target-bearing instruction.
+ assert!(self.instructions.len() > self.committed, "conditional rule removed its branch");
+ let site = self.instructions.len() - 1;
+ self.uses.push((PatchSite::Instruction(site), label));
+ self.commit(self.instructions.len());
+ Ok(())
+ }
+
+ /// Emits a target-bearing instruction and records its symbolic destination.
+ /// Side operands must come from the non-deduplicating target operand allocators
+ /// and belong exclusively to this instruction.
+ pub(crate) fn branch(&mut self, instruction: Instruction, label: LabelId) -> Result<()> {
+ if self.select && matches!(instruction, Instruction::Jump(_)) {
+ self.commit(self.instructions.len());
+ self.push(instruction)?;
+ self.pending_jump = Some(label);
+ return Ok(());
+ }
+ self.emit(instruction)?;
+ let site = self.instructions.len() - 1;
+ self.uses.push((PatchSite::Instruction(site), label));
+ self.commit(self.instructions.len());
+ Ok(())
+ }
+
+ /// Commits table storage and records case and default destinations.
+ pub(crate) fn branch_table(
+ &mut self,
+ data: &mut FunctionDataBuilder,
+ targets: &[LabelId],
+ default: LabelId,
+ ) -> Result<()> {
+ let start = u32::try_from(data.branch_table_targets.len())
+ .map_err(|_| ParseError::Other("branch table pool is too large".into()))?;
+ let count = u32::try_from(targets.len()).map_err(|_| ParseError::Other("branch table is too large".into()))?;
+ start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?;
+ let operand = data.push_target128(Operand128::<BranchTableOperand>::new(0, start, count))?;
+ self.branch(Instruction::BranchTable(operand), default)?;
+ for &label in targets {
+ self.uses.push((PatchSite::TableEntry(data.branch_table_targets.len()), label));
+ data.branch_table_targets.push(0);
+ }
+ Ok(())
+ }
+
+ /// Records exception boundaries and landing pads alongside their metadata.
+ pub(crate) fn exception_handler(
+ &mut self,
+ data: &mut FunctionDataBuilder,
+ start: LabelId,
+ end: LabelId,
+ catches: Vec<(ExceptionCatch, LabelId)>,
+ ) {
+ let index = data.exception_handlers.len();
+ self.uses.push((PatchSite::ExceptionStart(index), start));
+ self.uses.push((PatchSite::ExceptionEnd(index), end));
+ let catches = catches
+ .into_iter()
+ .enumerate()
+ .map(|(catch_index, (catch, label))| {
+ self.uses.push((PatchSite::Catch(index, catch_index), label));
+ catch
+ })
+ .collect();
+ data.exception_handlers.push(ExceptionHandler { start_ip: 0, end_ip: 0, catches });
+ }
+
+ fn commit(&mut self, end: usize) {
+ debug_assert!(self.committed <= end && end <= self.instructions.len());
+ self.committed = end;
+ }
+
+ /// Flushes the tail and resolves recorded targets without moving instructions.
+ pub(crate) fn finish(mut self, data: &mut FunctionDataBuilder) -> Result<Vec<Instruction>> {
+ self.seal_jump();
+ self.commit(self.instructions.len());
+ let invalid_site = || ParseError::Other("invalid label patch site".into());
+ for (site, label) in self.uses {
+ let target = self
+ .labels
+ .get(label.0)
+ .copied()
+ .flatten()
+ .ok_or_else(|| ParseError::Other("referenced label is not bound".into()))?;
+ let boundary = matches!(site, PatchSite::ExceptionEnd(_));
+ if target as usize > self.instructions.len() || (!boundary && target as usize == self.instructions.len()) {
+ return Err(ParseError::Other("label target out of bounds".into()));
+ }
+ match site {
+ PatchSite::Instruction(index) => {
+ let instruction = self.instructions.get_mut(index).ok_or_else(invalid_site)?;
+ Self::patch_target(instruction, data, target)?;
+ if let Instruction::BranchTable(index) = instruction {
+ let operand = data.operand128(*index);
+ let end = operand.start().checked_add(operand.size()).ok_or_else(invalid_site)?;
+ data.branch_table_targets
+ .get(operand.start() as usize..end as usize)
+ .ok_or_else(invalid_site)?;
+ }
+ }
+ PatchSite::TableEntry(index) => {
+ *data.branch_table_targets.get_mut(index).ok_or_else(invalid_site)? = target
+ }
+ PatchSite::ExceptionStart(index) => {
+ data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.start_ip = target
+ }
+ PatchSite::ExceptionEnd(index) => {
+ data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.end_ip = target
+ }
+ PatchSite::Catch(handler, catch) => {
+ let catch = data
+ .exception_handlers
+ .get_mut(handler)
+ .and_then(|handler| handler.catches.get_mut(catch))
+ .ok_or_else(invalid_site)?;
+ match catch {
+ ExceptionCatch::Tag { landing_pad, .. } | ExceptionCatch::All { landing_pad, .. } => {
+ *landing_pad = target
+ }
+ }
+ }
+ }
+ }
+ for handler in &data.exception_handlers {
+ if handler.start_ip > handler.end_ip || handler.end_ip as usize > self.instructions.len() {
+ return Err(ParseError::Other("exception handler range out of bounds".into()));
+ }
+ }
+ Ok(self.instructions)
+ }
+
+ fn patch_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) -> Result<()> {
+ // Target operands are allocated separately from deduplicated immutable
+ // operands. Relocation changes only their target field, not pool layout.
+ macro_rules! patch {
+ ($index:expr, $pool:ident) => {{
+ let operand = data
+ .$pool
+ .get_mut($index.index())
+ .ok_or_else(|| ParseError::Other("target operand out of bounds".into()))?;
+ *operand = operand.with_target(target);
+ }};
+ }
+ use Instruction::*;
+ match instruction {
+ Jump(value)
+ | JumpIfZero32(value)
+ | JumpIfNonZero32(value)
+ | JumpIfZero64(value)
+ | JumpIfNonZero64(value)
+ | JumpIfRefNull(value)
+ | JumpIfRefNonNull(value) => *value = target,
+ JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => {
+ arg.target_ip = target
+ }
+ JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => patch!(packed.index, operands64),
+ BrOnCast(index) | BrOnCastFail(index) => patch!(*index, operands64),
+ JumpCmpStackConst32(packed) => patch!(packed.index, operands64),
+ JumpCmpStackConst64(packed) => patch!(packed.index, operands128),
+ BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => patch!(packed.index, operands128),
+ BinOpLocalConstJumpCmpLocal32(packed) => patch!(packed.index, operands128),
+ BinOpGlobalConstJump32(packed) => patch!(packed.index, operands128),
+ IncLocalJump32(index) | IncStackTeeLocalJump32(index) => patch!(*index, operands128),
+ IncGlobalJump32(index) => patch!(*index, operands128),
+ IncLocalJumpCmpLocal32(packed) => patch!(packed.index, operands128),
+ JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => patch!(packed.index, operands128),
+ JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => patch!(packed.index, operands64),
+ BranchTable(index) => patch!(*index, operands128),
+ _ => return Err(ParseError::Other("unsupported instruction label patch".into())),
+ }
+ Ok(())
+ }
+}
diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs
index e4d8abd..892e27b 100644
--- a/crates/parser/src/error.rs
+++ b/crates/parser/src/error.rs
@@ -20,7 +20,7 @@ pub enum ParseError {
/// The error message
message: String,
/// The offset in the module where the error occurred
- offset: usize,
+ offset: u64,
},
/// An invalid encoding was encountered
InvalidEncoding(Encoding),
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index aa5e0b0..019e027 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -30,10 +30,12 @@ pub(crate) mod log {
}
mod conversion;
+mod emitter;
mod error;
mod macros;
mod module;
-mod optimize;
+mod selection;
+mod validation;
mod visit;
#[cfg(parallel_parser)]
@@ -41,7 +43,10 @@ mod parallel;
pub use error::*;
use module::ModuleReader;
-use wasmparser::{Validator, WasmFeatures};
+use validation::Validator;
+
+#[cfg(feature = "validate")]
+use wasmparser::WasmFeatures;
pub use tinywasm_types::Module;
@@ -49,15 +54,20 @@ pub use tinywasm_types::Module;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ParserOptions {
- /// Whether to validate modules while parsing. Enabled by default.
+ /// Whether to validate modules while parsing. Enabled by default when the
+ /// `validate` feature is enabled.
+ ///
+ /// Requires the `validate` feature to have any effect.
///
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub validation: bool,
- /// Whether to optimize local memory allocation by skipping allocation of unused local memories.
- pub optimize_local_memory_allocation: bool,
- /// Whether to run the peephole rewrite optimizer.
- pub optimize_rewrite: bool,
+
+ /// Whether to enable some of the optimizations during lowering, such as bounded instruction selection.
+ pub optimize: bool,
+
+ /// Whether to deduplicate immutable function operands while parsing.
+ pub deduplicate_operands: bool,
#[cfg(parallel_parser)]
/// Number of threads to use for parallel parsing.
@@ -67,27 +77,35 @@ pub struct ParserOptions {
/// - `None`: auto-detect based on available parallelism
/// - `Some(1)`: force single-threaded
/// - `Some(n)`: use up to `n` workers
- pub parser_threads: Option<usize>,
+ pub threads: Option<usize>,
}
impl Default for ParserOptions {
fn default() -> Self {
Self {
- validation: true,
- optimize_local_memory_allocation: true,
- optimize_rewrite: true,
+ validation: cfg!(feature = "validate"),
+ optimize: true,
+ deduplicate_operands: true,
#[cfg(parallel_parser)]
- parser_threads: None,
+ threads: None,
}
}
}
impl ParserOptions {
+ /// Create parser options with default settings.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
/// Enable or disable WebAssembly validation.
///
+ /// Requires the `validate` feature to have any effect.
+ ///
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub const fn with_validation(mut self, enabled: bool) -> Self {
+ assert!(!enabled || cfg!(feature = "validate"), "validation requires the `validate` feature");
self.validation = enabled;
self
}
@@ -97,41 +115,41 @@ impl ParserOptions {
self.validation
}
- /// Enable or disable the optimization that skips allocating unused local memories.
- pub const fn with_local_memory_allocation_optimization(mut self, enabled: bool) -> Self {
- self.optimize_local_memory_allocation = enabled;
+ /// Enable or disable some of the optimizations during lowering, such as bounded instruction selection.
+ pub const fn with_optimize(mut self, enabled: bool) -> Self {
+ self.optimize = enabled;
self
}
- /// Returns whether unused local memory allocation optimization is enabled.
- pub const fn optimize_local_memory_allocation(&self) -> bool {
- self.optimize_local_memory_allocation
+ /// Returns whether some of the optimizations during lowering, such as bounded instruction selection, are enabled.
+ pub const fn optimize(&self) -> bool {
+ self.optimize
}
- /// Enable or disable the peephole rewrite optimizer.
- pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self {
- self.optimize_rewrite = enabled;
+ /// Enable or disable parse-time deduplication of immutable function operands.
+ pub const fn with_operand_deduplication(mut self, enabled: bool) -> Self {
+ self.deduplicate_operands = enabled;
self
}
- /// Returns whether the peephole rewrite optimizer is enabled.
- pub const fn optimize_rewrite(&self) -> bool {
- self.optimize_rewrite
+ /// Returns whether immutable function operands are deduplicated while parsing.
+ pub const fn deduplicate_operands(&self) -> bool {
+ self.deduplicate_operands
}
#[cfg(parallel_parser)]
/// Set the number of threads for parallel parsing.
///
/// Requires the `parallel` feature to have any effect.
- pub const fn with_parser_threads(mut self, threads: usize) -> Self {
- self.parser_threads = Some(threads);
+ pub const fn with_threads(mut self, threads: usize) -> Self {
+ self.threads = Some(threads);
self
}
#[cfg(parallel_parser)]
/// Returns the configured parser thread count, or `None` for auto-detect.
- pub const fn parser_threads(&self) -> Option<usize> {
- self.parser_threads
+ pub const fn threads(&self) -> Option<usize> {
+ self.threads
}
}
@@ -142,13 +160,8 @@ pub struct Parser {
}
impl Parser {
- /// Create a new parser instance
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Create a new parser with explicit options.
- pub fn with_options(options: ParserOptions) -> Self {
+ /// Create a parser with the given options.
+ pub const fn new(options: ParserOptions) -> Self {
Self { options }
}
@@ -157,36 +170,44 @@ impl Parser {
&self.options
}
- fn create_validator(_options: ParserOptions) -> Validator {
- let features = WasmFeatures::CALL_INDIRECT_OVERLONG
- | WasmFeatures::BULK_MEMORY_OPT
- | WasmFeatures::RELAXED_SIMD
- | WasmFeatures::GC_TYPES
- | WasmFeatures::REFERENCE_TYPES
- | WasmFeatures::MUTABLE_GLOBAL
- | WasmFeatures::MULTI_VALUE
- | WasmFeatures::FLOATS
- | WasmFeatures::BULK_MEMORY
- | WasmFeatures::SATURATING_FLOAT_TO_INT
- | WasmFeatures::SIGN_EXTENSION
- | WasmFeatures::EXTENDED_CONST
- | WasmFeatures::FUNCTION_REFERENCES
- | WasmFeatures::TAIL_CALL
- | WasmFeatures::MULTI_MEMORY
- | WasmFeatures::SIMD
- | WasmFeatures::MEMORY64
- | WasmFeatures::CUSTOM_PAGE_SIZES
- | WasmFeatures::WIDE_ARITHMETIC;
- Validator::new_with_features(features)
+ fn validator(&self) -> Option<Validator> {
+ #[cfg(feature = "validate")]
+ {
+ let features = WasmFeatures::WASM3
+ .difference(WasmFeatures::THREADS)
+ .union(WasmFeatures::CUSTOM_PAGE_SIZES)
+ .union(WasmFeatures::WIDE_ARITHMETIC)
+ .union(WasmFeatures::COMPACT_IMPORTS);
+ self.options.validation().then(|| Validator::new_with_features(features))
+ }
+ #[cfg(not(feature = "validate"))]
+ {
+ assert!(!self.options.validation(), "validation requires the `validate` feature");
+ None
+ }
}
#[cfg(feature = "std")]
fn read_more(stream: &mut impl std::io::Read, buffer: &mut alloc::vec::Vec<u8>, hint: usize) -> Result<usize> {
let len = buffer.len();
- buffer.resize(len + hint, 0);
- let read_bytes = stream
- .read(&mut buffer[len..])
- .map_err(|e| ParseError::Other(alloc::format!("Error reading from stream: {e}")))?;
+ // Size hints can come from untrusted section lengths.
+ let increment = hint.clamp(1, 64 * 1024);
+ let new_len =
+ len.checked_add(increment).ok_or_else(|| ParseError::Other("stream buffer is too large".into()))?;
+ buffer
+ .try_reserve(increment)
+ .map_err(|e| ParseError::Other(alloc::format!("Error reserving stream buffer: {e}")))?;
+ buffer.resize(new_len, 0);
+ let read_bytes = loop {
+ match stream.read(&mut buffer[len..]) {
+ Ok(read_bytes) => break read_bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => {
+ buffer.truncate(len);
+ return Err(ParseError::Other(alloc::format!("Error reading from stream: {e}")));
+ }
+ }
+ };
buffer.truncate(len + read_bytes);
Ok(read_bytes)
}
@@ -194,7 +215,7 @@ impl Parser {
/// Parse a [`Module`] from bytes
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<Module> {
let wasm = wasm.as_ref();
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
for payload in wasmparser::Parser::new(0).parse_all(wasm) {
@@ -214,7 +235,7 @@ impl Parser {
}
reader.process_pending_functions(&self.options)?;
- reader.into_module(&self.options)
+ reader.into_module()
}
#[cfg(feature = "std")]
@@ -228,7 +249,7 @@ impl Parser {
#[cfg(feature = "std")]
/// Parse a [`Module`] from a stream. Requires `std` feature.
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<Module> {
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
let mut buffer = alloc::vec::Vec::new();
let mut parser = wasmparser::Parser::new(0);
@@ -243,7 +264,7 @@ impl Parser {
buffer.truncate(buffer.len() - buffer_offset);
buffer_offset = 0;
}
- let read_bytes = Self::read_more(&mut stream, &mut buffer, hint as usize)?;
+ let read_bytes = Self::read_more(&mut stream, &mut buffer, hint)?;
eof = read_bytes == 0;
}
wasmparser::Chunk::Parsed { consumed, payload } => {
@@ -252,17 +273,12 @@ impl Parser {
match payload {
wasmparser::Payload::CodeSectionStart { count, range, size } => {
- let defer = reader.begin_code_section(
- count,
- range.clone(),
- size,
- validator.as_mut(),
- &self.options,
- )?;
+ let defer =
+ reader.begin_code_section(count, range, size, validator.as_mut(), &self.options)?;
#[cfg(parallel_parser)]
if defer {
- deferred_code_section = Some((count, range.end - size as usize, size as usize));
+ deferred_code_section = Some((count, size as usize));
}
#[cfg(not(parallel_parser))]
@@ -278,21 +294,22 @@ impl Parser {
buffer_offset += consumed;
#[cfg(parallel_parser)]
- if let Some((count, body_offset, section_size)) = deferred_code_section {
+ if let Some((count, section_size)) = deferred_code_section {
while buffer.len() - buffer_offset < section_size {
let remaining = section_size - (buffer.len() - buffer_offset);
let read_bytes = Self::read_more(&mut stream, &mut buffer, remaining)?;
if read_bytes == 0 {
return Err(ParseError::ParseError {
message: "unexpected end-of-file".into(),
- offset: body_offset + buffer.len() - buffer_offset,
+ offset: parser.offset() + (buffer.len() - buffer_offset) as u64,
});
}
}
let section_end = buffer_offset + section_size;
- let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
- reader.queue_owned_code_section(count, body_offset, section_bytes, validator.as_mut())?;
+ let section_bytes =
+ tinywasm_types::Shared::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
+ reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?;
parser.skip_section();
buffer_offset = section_end;
continue;
@@ -315,7 +332,7 @@ impl Parser {
if reader.end_reached || eof {
reader.process_pending_functions(&self.options)?;
- return reader.into_module(&self.options);
+ return reader.into_module();
}
}
};
@@ -327,23 +344,23 @@ impl TryFrom<ModuleReader<'_>> for Module {
type Error = ParseError;
fn try_from(reader: ModuleReader<'_>) -> Result<Self> {
- reader.into_module(&ParserOptions::default())
+ reader.into_module()
}
}
/// Parse a module from bytes
pub fn parse_bytes(wasm: &[u8]) -> Result<Module> {
- Parser::new().parse_module_bytes(wasm)
+ Parser::default().parse_module_bytes(wasm)
}
#[cfg(feature = "std")]
/// Parse a module from a file. Requires the `std` feature.
pub fn parse_file(path: impl AsRef<crate::std::path::Path> + Clone) -> Result<Module> {
- Parser::new().parse_module_file(path)
+ Parser::default().parse_module_file(path)
}
#[cfg(feature = "std")]
/// Parse a module from a stream. Requires the `std` feature.
pub fn parse_stream(stream: impl crate::std::io::Read) -> Result<Module> {
- Parser::new().parse_module_stream(stream)
+ Parser::default().parse_module_stream(stream)
}
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 723f691..fe1364b 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -1,78 +1,144 @@
pub(crate) mod visit {
+ // Rule families are chosen at the call site, not by matching the emitted opcode.
+ // Unary instruction operands are evaluated once and passed after family arguments.
+ macro_rules! emit_selected {
+ ($builder:ident, $inputs:expr, $outputs:expr, $op:ident($value:expr) [$family:ident($($arg:expr),* $(,)?)]) => {{
+ let operand = $value;
+ $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op(operand),
+ |tail, data| crate::selection::$family(tail, data $(, $arg)*, operand))
+ }};
+ ($builder:ident, $inputs:expr, $outputs:expr, $op:ident [$family:ident($($arg:expr),* $(,)?)]) => {
+ $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op,
+ |tail, data| crate::selection::$family(tail, data $(, $arg)*))
+ };
+ ($builder:ident, $inputs:expr, $outputs:expr, $op:ident $(($($value:expr),*))?) => {
+ $builder.emit($inputs, $outputs, tinywasm_types::Instruction::$op $(($($value),*))?)
+ };
+ }
+ #[cfg(feature = "validate")]
macro_rules! validate_then_visit {
($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
)*};
}
+ #[cfg(feature = "validate")]
macro_rules! validate_then_visit_simd {
($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
)*};
}
+ // Optional `[family(args)]` selects rules alongside the visitor's stack effect
+ // and fallback opcode. Instructions without a family use plain emission.
macro_rules! lowering_ops {
() => {};
($kind:ident $inputs:tt => $outputs:tt {
- $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident),* $(,)?
+ $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])?),* $(,)?
} $($rest:tt)*) => {
- $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr);)*
+ $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr $([$family($($rule_arg),*)])?);)*
lowering_ops!($($rest)*);
};
(effect $inputs:tt => $outputs:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => {
$(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 $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
+ $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])?
) => {
fn $visit(&mut self $(, $($arg: $ty),+)?) -> Self::Output {
lowering_ops!(@emit self fixed [$($input),*] => [$($output),*]
- Instruction::$instr $(($($arg),+))?.into())
+ $instr $(($($arg),+))? $([$family($($rule_arg),*)])?)
}
};
(@memory [$($input:ident),*] => [$($output:ident),*]
- $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident
+ $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])?
) => {
fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output {
let address = self.metadata.memory_size(memarg.memory)?;
+ self.mark_memory(memarg.memory);
+ let memory_arg_idx = self.push128(tinywasm_types::Operand128::<
+ tinywasm_types::MemoryOperand,
+ >::new(memarg.offset, memarg.memory))?;
lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
- Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into())
+ $instr(lowering_ops!(@memory_arg memory_arg_idx $(, $lane)?)) $([$family($($rule_arg),*)])?)
}
};
+ (@memory_arg $memory_arg_idx:ident) => {
+ $memory_arg_idx
+ };
+ (@memory_arg $memory_arg_idx:ident, $lane:ident) => {
+ tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }
+ };
(@global $inputs:tt => $outputs:tt $($operator:tt)*) => {
lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*);
};
(@memory_index $inputs:tt => $outputs:tt $($operator:tt)*) => {
- lowering_ops!(@resolved memory_size $inputs => $outputs $($operator)*);
+ lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*);
+ };
+ (@memory_index_impl [$($input:ident),*] => [$($output:ident),*]
+ $visit:ident($index:ident: $ty:ty) => $instr:ident $([$family:ident($($rule_arg:expr),*)])?
+ ) => {
+ fn $visit(&mut self, $index: $ty) -> Self::Output {
+ let address = self.metadata.memory_size($index)?;
+ self.mark_memory($index);
+ lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
+ $instr($index) $([$family($($rule_arg),*)])?)
+ }
};
(@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 = self.metadata.array_field($type_index)?;
+ lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*]
+ $instr($type_index $(, $arg)*))
+ }
+ };
(@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*]
$visit:ident($index:ident: $ty:ty) => $instr:ident
) => {
fn $visit(&mut self, $index: $ty) -> Self::Output {
let address = self.metadata.$resolver($index)?;
lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
- Instruction::$instr($index).into())
+ $instr($index))
}
};
(@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*]
@@ -81,7 +147,7 @@ pub(crate) mod visit {
fn $visit(&mut self, $arg: $arg_ty, $index: $index_ty) -> Self::Output {
let address = self.metadata.$resolver($index)?;
lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
- Instruction::$instr($arg, $index).into())
+ $instr($arg, $index))
}
};
(@effect [$($input:ident),*] => [$($output:ident),*] $visit:ident) => {
@@ -92,27 +158,32 @@ pub(crate) mod visit {
(@terminating [$($input:ident),*] => [$($output:ident),*] $visit:ident => $instr:ident) => {
fn $visit(&mut self) -> Self::Output {
self.mark_unreachable();
- lowering_ops!(@emit self fixed [$($input),*] => [$($output),*] Instruction::$instr)
+ self.emit_boundary(
+ &[$(lowering_ops!(@size $input)),*],
+ &[$(lowering_ops!(@size $output)),*],
+ Instruction::$instr,
+ )
}
};
- (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => {
- $self.emit(
+ (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => {
+ emit_selected!($self,
&[$(lowering_ops!(@size $input)),*],
&[$(lowering_ops!(@size $output)),*],
- $instruction,
+ $($instruction)+
)
};
- (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => {
- $self.emit(
+ (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => {
+ emit_selected!($self,
&[$(lowering_ops!(@size $input, $address)),*],
&[$(lowering_ops!(@size $output, $address)),*],
- $instruction,
+ $($instruction)+
)
};
(@size Addr, $address:ident) => { $address };
- (@size $size:ident $(, $address:ident)?) => { OperandSize::$size };
+ (@size Field, $address:ident) => { $address };
+ (@size $size:ident $(, $address:ident)?) => { ValueLane::$size };
}
macro_rules! impl_visit_operator {
@@ -130,6 +201,8 @@ pub(crate) mod visit {
(@@relaxed_simd $($rest:tt)* ) => {};
(@@tail_call $($rest:tt)* ) => {};
(@@function_references $($rest:tt)* ) => {};
+ (@@gc $($rest:tt)* ) => {};
+ (@@exceptions $($rest:tt)* ) => {};
(@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => {
fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output {
@@ -138,178 +211,7 @@ pub(crate) mod visit {
};
}
- pub(crate) use {impl_visit_operator, lowering_ops, validate_then_visit, validate_then_visit_simd};
-}
-
-pub(crate) mod optimize {
- macro_rules! replace {
- ($instructions:ident, $read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{
- const {
- assert!($consumed >= 1 && $consumed <= 3);
- assert!([$(stringify!($out)),+].len() <= $consumed + 1);
- }
- let replacements = [$($out),+];
- let start = $read - $consumed;
- $instructions[start..start + replacements.len()].copy_from_slice(&replacements);
- $instructions.truncate(start + replacements.len());
- #[allow(unused_assignments)]
- { $read = $instructions.len() - 1; }
- }};
- ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => {
- replace!($instructions, $read, $consumed => [$out]);
- };
- }
-
- macro_rules! rewrite {
- ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => [$($out:expr),+ $(,)?]) => {
- rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => {
- replace!($instructions, $read, [$(stringify!($pattern)),+].len() => [$($out),+]);
- })
- };
- ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{
- const CONSUMED: usize = [$(stringify!($pattern)),+].len();
- if !$instructions.tail_rewritten
- && $read < $instructions.len()
- && $read >= $instructions.block_start + CONSUMED
- {
- let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap();
- if let [$($pattern),+] = previous $(
- && $($guard)+
- )? {
- $instructions.tail_rewritten = true;
- $body
- }
- }
- }};
- ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $out:expr $(,)?) => {
- rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => {
- replace!($instructions, $read, [$(stringify!($pattern)),+].len() => $out);
- })
- };
- }
-
- macro_rules! define_local_source_resolver {
- (
- $name:ident,
- get = $get:ident,
- tee = $tee:ident,
- set = $set:ident,
- binop_local_local_tee = $lltee:ident,
- binop_local_local_set = $llset:ident,
- binop_local_const_tee = $lctee:ident,
- binop_local_const_set = $lcset:ident
- $(, load_local_tee = $loadtee:ident, load_local_set = $loadset:ident)?
- ) => {
- fn $name(instr: Instruction) -> Option<(Option<Instruction>, u16)> {
- Some(match instr {
- Instruction::$get(local) => (None, local),
- Instruction::$tee(local) => (Some(Instruction::$set(local)), local),
- Instruction::$lltee(op, a, b, local) => (Some(Instruction::$llset(op, a, b, local)), local),
- Instruction::$lctee(op, src, c, local) => (Some(Instruction::$lcset(op, src, c, local)), local),
- $(Instruction::$loadtee(memarg, addr, local) => (Some(Instruction::$loadset(memarg, addr, local)), local.into()),)?
- _ => return None,
- })
- }
- };
- }
-
- macro_rules! fold_local_binop {
- (
- $instrs:ident, $read:expr, $dst:expr,
- source = $source:ident,
- op = $op:ident,
- const = $const:ident,
- local_local = $local_local:ident,
- local_const = $local_const:expr
- ) => {{
- if !$instrs.tail_rewritten
- && $read < $instrs.len()
- && $read >= $instrs.block_start + 3
- && let [lhs_src, rhs_src, raw_op] = [$instrs[$read - 3], $instrs[$read - 2], $instrs[$read - 1]]
- && let Some((lhs_instr, lhs)) = $source(lhs_src)
- && let Some(op) = $op(raw_op)
- {
- if let Some((rhs_instr, rhs)) = $source(rhs_src) {
- if rhs_instr.is_none() || rhs != lhs {
- $instrs.tail_rewritten = true;
- $instrs.truncate($read - 3);
- $instrs.extend(lhs_instr);
- $instrs.extend(rhs_instr);
- $instrs.push(Instruction::$local_local(op, lhs, rhs, $dst));
- $read = $instrs.len() - 1;
- }
- } else if let Some(imm) = $const(rhs_src, raw_op) {
- $instrs.tail_rewritten = true;
- $instrs.truncate($read - 3);
- $instrs.extend(lhs_instr);
- $instrs.push($local_const($dst, lhs, op, imm));
- $read = $instrs.len() - 1;
- }
- }
- }};
- }
-
- macro_rules! rewrite_local_set_direct {
- (
- $instrs:ident, $read:ident, $dst:expr,
- get = $get:ident,
- copy = $copy:ident,
- binop_local_local = $ll:ident,
- binop_local_local_set = $llset:ident,
- binop_local_const = $lc:ident,
- binop_local_const_set = $lcset:expr
- $(, const_instr = $const_instr:ident, set_local_const = $set_local_const:ident)?
- ) => {{
- rewrite!($instrs, $read, [$get(src)] if (src != $dst) => Instruction::$copy(src, $dst));
- if !$instrs.tail_rewritten
- && $read < $instrs.len()
- && $read > $instrs.block_start
- && let Instruction::$get(src) = $instrs[$read - 1]
- && src == $dst
- {
- $instrs.tail_rewritten = true;
- $instrs.truncate($read - 1);
- $read = $instrs.len();
- }
- $(rewrite!($instrs, $read, [$const_instr(c)] => Instruction::$set_local_const($dst, c));)?
- rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$llset(op, a, b, $dst));
- rewrite!($instrs, $read, [$lc(op, src, c)] => { replace!($instrs, $read, 1 => $lcset($dst, src, op, c)); });
- }};
- }
-
- macro_rules! rewrite_local_tee_direct {
- (
- $instrs:ident, $read:ident, $dst:expr,
- get = $get:ident,
- binop_local_local = $ll:ident,
- binop_local_local_tee = $lltee:ident,
- binop_local_const = $lc:ident,
- binop_local_const_tee = $lctee:ident
- ) => {{
- rewrite!($instrs, $read, [$get(src)] if (src == $dst) => Instruction::$get(src));
- rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$lltee(op, a, b, $dst));
- rewrite!($instrs, $read, [$lc(op, src, c)] => Instruction::$lctee(op, src, c, $dst));
- }};
- }
-
- macro_rules! rewrite_drop_tee_direct {
- (
- $instrs:ident, $read:ident,
- tee = $tee:ident,
- set = $set:ident,
- binop_local_local_tee = $lltee:ident,
- binop_local_local_set = $llset:ident,
- binop_local_const_tee = $lctee:ident,
- binop_local_const_set = $lcset:ident
- ) => {{
- rewrite!($instrs, $read, [$tee(local)] => Instruction::$set(local));
- rewrite!($instrs, $read, [$lltee(op, a, b, dst)] => Instruction::$llset(op, a, b, dst));
- rewrite!($instrs, $read, [$lctee(op, src, c, dst)] => Instruction::$lcset(op, src, c, dst));
- }};
- }
-
- pub(crate) use {
- define_local_source_resolver, fold_local_binop, replace, rewrite, rewrite_drop_tee_direct,
- rewrite_local_set_direct, rewrite_local_tee_direct,
- };
+ pub(crate) use {emit_selected, impl_visit_operator, lowering_ops};
+ #[cfg(feature = "validate")]
+ pub(crate) use {validate_then_visit, validate_then_visit_simd};
}
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index c2199f3..03c725c 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -1,11 +1,15 @@
use crate::log::debug;
-use crate::{ParseError, ParserOptions, Result, conversion::*, optimize};
-use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec};
+#[cfg(parallel_parser)]
+use crate::validation::{FuncToValidate, ValidatorResources};
+use crate::validation::{FuncValidatorAllocations, Validator};
+use crate::{ParseError, ParserOptions, Result, conversion::*};
+use alloc::{boxed::Box, format, string::ToString, vec::Vec};
use core::marker::PhantomData;
use core::ops::Range;
use tinywasm_types::*;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, Payload, Validator};
+use wasmparser::{OperatorsReaderAllocations, Payload};
+/// Final bytecode and metadata produced by streaming function lowering.
pub(crate) struct FunctionCode {
pub instructions: Vec<Instruction>,
pub data: WasmFunctionData,
@@ -13,52 +17,33 @@ pub(crate) struct FunctionCode {
pub uses_local_memory: bool,
}
-pub(crate) fn optimize_function_code(
- mut code: FunctionCode,
- options: &ParserOptions,
- function_results: ValueCounts,
- self_func_addr: u32,
- imported_memory_count: u32,
-) -> Result<FunctionCode> {
- let optimized = optimize::optimize_instructions(
- code.instructions,
- &mut code.data,
- options,
- function_results,
- self_func_addr,
- imported_memory_count,
- )?;
-
- code.instructions = optimized.instructions;
- code.uses_local_memory = optimized.uses_local_memory;
- Ok(code)
-}
-
#[derive(Default)]
pub(crate) struct ModuleReader<'a> {
func_validator_allocations: Option<FuncValidatorAllocations>,
operators_reader_allocations: Option<OperatorsReaderAllocations>,
- translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
+ translation_metadata: Option<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]>,
+ pub(crate) exports: Shared<[Export]>,
pub(crate) code: Vec<FunctionCode>,
pub(crate) globals: Box<[Global]>,
pub(crate) tables: Box<[TableDefinition]>,
pub(crate) memory_types: Box<[MemoryType]>,
+ pub(crate) tags: Box<[TagType]>,
pub(crate) imports: Box<[Import]>,
pub(crate) data: Box<[Data]>,
pub(crate) elements: Box<[Element]>,
pub(crate) end_reached: bool,
imported_func_count: usize,
- imported_memory_count: u32,
+ global_types: Vec<WasmType>,
#[cfg(parallel_parser)]
pending_functions: Option<Vec<crate::parallel::PendingFunction<'a>>>,
@@ -67,23 +52,24 @@ pub(crate) struct ModuleReader<'a> {
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.translation_metadata = Some(crate::visit::ModuleMetadata::new(
+ &self.types,
&self.code_type_addrs,
&self.imports,
&self.globals,
&self.memory_types,
&self.tables,
- )));
+ &self.tags,
+ ));
}
- self.translation_metadata.as_deref().unwrap()
+ self.translation_metadata.as_ref().unwrap()
}
- pub(crate) fn process_payload(
- &mut self,
- payload: Payload<'_>,
- mut validator: Option<&mut Validator>,
- ) -> Result<()> {
+ pub(crate) fn process_payload(&mut self, payload: Payload<'_>, validator: Option<&mut Validator>) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
fn check_section(section: &str, duplicate: bool) -> Result<()> {
debug!("found {section} section");
if duplicate {
@@ -94,9 +80,12 @@ impl<'a> ModuleReader<'a> {
match payload {
Payload::Version { num, encoding, range } => {
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.version(num, encoding, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
self.version = Some(num);
if let wasmparser::Encoding::Component = encoding {
return Err(ParseError::InvalidEncoding(encoding));
@@ -104,27 +93,46 @@ impl<'a> ModuleReader<'a> {
}
Payload::StartSection { func, range } => {
check_section("start", self.start_func.is_some())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.start_section(func, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
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())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.global_section(&reader)?;
}
- self.globals = convert_module_globals(reader)?;
+ self.globals = convert_module_globals(reader, &mut self.global_types)?;
}
Payload::TableSection(reader) => {
check_section("table", !self.tables.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.table_section(&reader)?;
}
@@ -140,7 +148,7 @@ impl<'a> ModuleReader<'a> {
let init = match table.init {
wasmparser::TableInit::RefNull => None,
wasmparser::TableInit::Expr(expr) => {
- Some(process_const_operators(expr.get_operators_reader())?)
+ Some(process_const_operators(expr.get_operators_reader(), &self.global_types)?)
}
};
tables.push(TableDefinition { ty, init });
@@ -149,38 +157,69 @@ impl<'a> ModuleReader<'a> {
}
Payload::MemorySection(reader) => {
check_section("memory", !self.memory_types.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.memory_section(&reader)?;
}
self.memory_types =
reader.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::<Result<_>>()?;
}
+ Payload::TagSection(reader) => {
+ check_section("tag", !self.tags.is_empty())?;
+ #[cfg(feature = "validate")]
+ if let Some(validator) = validator.as_mut() {
+ validator.tag_section(&reader)?;
+ }
+ let mut tags = Vec::with_capacity(reader.count() as usize);
+ for tag in reader {
+ let tag = convert_tag_type(tag?);
+ let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| {
+ ParseError::Other(format!("tag type index does not reference a function: {}", tag.type_idx))
+ })?;
+ if !ty.results().is_empty() {
+ return Err(ParseError::Other(format!("tag type must not have results: {}", tag.type_idx)));
+ }
+ tags.push(tag);
+ }
+ self.tags = tags.into_boxed_slice();
+ }
Payload::ElementSection(reader) => {
debug!("Found element section");
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.element_section(&reader)?;
}
- self.elements =
- reader.into_iter().map(|element| convert_module_element(element?)).collect::<Result<_>>()?;
+ self.elements = reader
+ .into_iter()
+ .map(|element| convert_module_element(element?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataSection(reader) => {
check_section("data", !self.data.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_section(&reader)?;
}
- self.data = reader.into_iter().map(|data| convert_module_data(data?)).collect::<Result<_>>()?;
+ self.data = reader
+ .into_iter()
+ .map(|data| convert_module_data(data?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataCountSection { count, range } => {
debug!("Found data count section");
if !self.data.is_empty() {
return Err(ParseError::UnsupportedSection("Data count section after data section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_count_section(count, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (count, range);
}
Payload::FunctionSection(reader) => {
check_section("function", !self.code_type_addrs.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.function_section(&reader)?;
}
@@ -188,10 +227,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()));
}
@@ -200,6 +238,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ImportSection(reader) => {
check_section("import", !self.imports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.import_section(&reader)?;
}
@@ -207,8 +246,29 @@ 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::Memory(_) => self.imported_memory_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::Global(ty) => self.global_types.push(ty.ty),
+ ImportKind::Tag(tag) => {
+ let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| {
+ ParseError::Other(format!(
+ "tag import type index does not reference a function: {}",
+ tag.type_idx
+ ))
+ })?;
+ if !ty.results().is_empty() {
+ return Err(ParseError::Other(format!(
+ "tag import type must not have results: {}",
+ tag.type_idx
+ )));
+ }
+ }
_ => {}
}
imports.push(import);
@@ -217,6 +277,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ExportSection(reader) => {
check_section("export", !self.exports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.export_section(&reader)?;
}
@@ -228,9 +289,12 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::DuplicateSection("End section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.end(offset)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = offset;
self.end_reached = true;
}
Payload::CustomSection(_reader) => {
@@ -250,7 +314,7 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn begin_code_section(
&mut self,
count: u32,
- range: Range<usize>,
+ range: Range<u64>,
size: u32,
validator: Option<&mut Validator>,
options: &ParserOptions,
@@ -262,9 +326,12 @@ impl<'a> ModuleReader<'a> {
self.has_code_section = true;
self.code.reserve(count as usize);
+ #[cfg(feature = "validate")]
if let Some(validator) = validator {
validator.code_section_start(&range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (range, validator);
#[cfg(parallel_parser)]
{
@@ -294,28 +361,37 @@ impl<'a> ModuleReader<'a> {
let func_validator_allocs = self.func_validator_allocations.take();
let operators_reader_allocs = self.operators_reader_allocations.take().unwrap_or_default();
+ #[cfg(feature = "validate")]
let func_validator = validator
.map(|validator| validator.code_section_entry(&function))
.transpose()?
.map(|func| func.into_validator(func_validator_allocs.unwrap_or_default()));
+ #[cfg(not(feature = "validate"))]
+ let func_validator = {
+ let _ = (validator, func_validator_allocs);
+ None
+ };
let ordinal = self.code.len();
let ty_idx = *self
.code_type_addrs
.get(ordinal)
.ok_or_else(|| ParseError::Other("code entry has no function signature".into()))?;
+ let context = FunctionLoweringContext {
+ ty_idx,
+ self_func_addr: self
+ .imported_func_count
+ .checked_add(ordinal)
+ .and_then(|idx| u32::try_from(idx).ok())
+ .ok_or_else(|| ParseError::Other("function index is too large".into()))?,
+ function_results: self.code_results[ordinal],
+ };
let metadata = self.translation_metadata();
let (code, func_validator_allocs, operators_reader_allocs) =
- convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx)?;
+ convert_module_code(function, func_validator, operators_reader_allocs, metadata, context, options)?;
- self.code.push(optimize_function_code(
- code,
- options,
- self.code_results[self.code.len()],
- (self.imported_func_count + self.code.len()) as u32,
- self.imported_memory_count,
- )?);
+ self.code.push(code);
self.func_validator_allocations = func_validator_allocs;
self.operators_reader_allocations = Some(operators_reader_allocs);
@@ -332,7 +408,10 @@ impl<'a> ModuleReader<'a> {
#[cfg(parallel_parser)]
if self.pending_functions.is_some() {
+ #[cfg(feature = "validate")]
let func_to_validate = validator.map(|validator| validator.code_section_entry(&function)).transpose()?;
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
return self.queue_function(crate::parallel::FunctionBodyInput::Borrowed(function), func_to_validate);
}
@@ -343,21 +422,31 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn queue_owned_code_section(
&mut self,
count: u32,
- body_offset: usize,
- section_bytes: Arc<[u8]>,
- mut validator: Option<&mut Validator>,
+ body_offset: u64,
+ section_bytes: Shared<[u8]>,
+ validator: Option<&mut Validator>,
) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
let mut reader = wasmparser::BinaryReader::new(&section_bytes, body_offset);
for _ in 0..count {
let body_reader = reader.read_reader()?;
let body_range = body_reader.range();
- let function = wasmparser::FunctionBody::new(body_reader);
- let func_to_validate =
- validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?;
+ let body_start = (body_range.start - body_offset) as usize;
+ let body_end = (body_range.end - body_offset) as usize;
+ #[cfg(feature = "validate")]
+ let func_to_validate = {
+ let function = wasmparser::FunctionBody::new(body_reader);
+ validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?
+ };
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
self.queue_function(
crate::parallel::FunctionBodyInput::Owned(crate::parallel::OwnedFunctionBody {
section_bytes: section_bytes.clone(),
- body_range: (body_range.start - body_offset)..(body_range.end - body_offset),
+ body_range: body_start..body_end,
body_offset: body_range.start,
}),
func_to_validate,
@@ -378,7 +467,7 @@ impl<'a> ModuleReader<'a> {
fn queue_function(
&mut self,
body: crate::parallel::FunctionBodyInput<'a>,
- func_to_validate: Option<wasmparser::FuncToValidate<wasmparser::ValidatorResources>>,
+ func_to_validate: Option<FuncToValidate<ValidatorResources>>,
) -> Result<()> {
let ordinal = self.code.len() + self.pending_functions.as_ref().map_or(0, Vec::len);
let results = *self
@@ -404,10 +493,8 @@ impl<'a> ModuleReader<'a> {
};
let imported_func_count = self.imported_func_count;
- let imported_memory_count = self.imported_memory_count;
let metadata = self.translation_metadata();
- let code =
- crate::parallel::process_pending(pending, metadata, options, imported_func_count, imported_memory_count)?;
+ let code = crate::parallel::process_pending(pending, metadata, options, imported_func_count)?;
self.code.extend(code);
Ok(())
}
@@ -417,7 +504,7 @@ impl<'a> ModuleReader<'a> {
Ok(())
}
- pub(crate) fn into_module(self, options: &ParserOptions) -> Result<Module> {
+ pub(crate) fn into_module(self) -> Result<Module> {
if !self.end_reached {
return Err(ParseError::EndNotReached);
}
@@ -426,24 +513,6 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::Other("Code and code type address count mismatch".to_string()));
}
- let import_mem_count = self.imported_memory_count;
- let has_local_mem_export =
- self.exports.iter().any(|export| export.kind == ExternalKind::Memory && export.index >= import_mem_count);
- let has_active_data_segment_on_local_memory = self.data.iter().any(|data| match &data.kind {
- DataKind::Active { mem, .. } => *mem >= import_mem_count,
- DataKind::Passive => false,
- });
- let optimize_local_memory_allocation = options.optimize_local_memory_allocation();
- let mut local_memory_allocation = if self.memory_types.is_empty() {
- LocalMemoryAllocation::Skip
- } else if !optimize_local_memory_allocation || has_active_data_segment_on_local_memory {
- LocalMemoryAllocation::Eager
- } else if has_local_mem_export {
- LocalMemoryAllocation::Lazy
- } else {
- LocalMemoryAllocation::Skip
- };
-
let func_type_idxs = self
.imports
.iter()
@@ -454,31 +523,43 @@ impl<'a> ModuleReader<'a> {
.chain(self.code_type_addrs.iter().copied())
.collect();
+ let imported_memory_count =
+ self.imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count();
+ let uses_local_memory = self.code.iter().any(|code| code.uses_local_memory);
+ let exports_local_memory = self
+ .exports
+ .iter()
+ .any(|export| export.kind == ExternalKind::Memory && export.index as usize >= imported_memory_count);
+ let initializes_local_memory = self
+ .data
+ .iter()
+ .any(|data| matches!(data.kind, DataKind::Active { mem, .. } if mem as usize >= imported_memory_count));
+ let skip_local_memory_allocation =
+ !self.memory_types.is_empty() && !uses_local_memory && !exports_local_memory && !initializes_local_memory;
+
let funcs = self
.code
.into_iter()
.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();
+ .map(|((code, ty_idx), results)| -> Result<_> {
+ 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;
- }
- Arc::new(WasmFunction {
- instructions: code.instructions.into(),
+ Ok(Shared::new(WasmFunction {
+ instructions: code.instructions.into_boxed_slice(),
data: code.data,
locals: code.locals,
params,
results,
- })
+ }))
})
- .collect();
+ .collect::<Result<_>>()?;
Ok(ModuleInner {
funcs,
- func_types: self.func_types,
+ types: self.types,
func_type_idxs,
globals: self.globals,
tables: self.tables,
@@ -488,7 +569,8 @@ impl<'a> ModuleReader<'a> {
exports: self.exports,
elements: self.elements,
memory_types: self.memory_types,
- local_memory_allocation,
+ skip_local_memory_allocation,
+ tags: self.tags,
}
.into())
}
diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs
deleted file mode 100644
index dcb7568..0000000
--- a/crates/parser/src/optimize.rs
+++ /dev/null
@@ -1,984 +0,0 @@
-use crate::macros::optimize::*;
-use crate::{ParseError, ParserOptions, Result};
-use alloc::vec::Vec;
-use core::ops::{Deref, DerefMut};
-use tinywasm_types::{BinOp, BinOp128, CmpOp, ConstIdx, Instruction, ValueCounts, WasmFunctionData};
-
-pub(crate) struct OptimizeResult {
- pub(crate) instructions: Vec<Instruction>,
- pub(crate) uses_local_memory: bool,
-}
-
-struct CompactOutput {
- instructions: Vec<Instruction>,
- block_start: usize,
- tail_rewritten: bool,
-}
-
-impl Deref for CompactOutput {
- type Target = Vec<Instruction>;
-
- fn deref(&self) -> &Self::Target {
- &self.instructions
- }
-}
-
-impl DerefMut for CompactOutput {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.instructions
- }
-}
-
-pub(crate) fn optimize_instructions(
- instructions: Vec<Instruction>,
- function_data: &mut WasmFunctionData,
- options: &ParserOptions,
- function_results: ValueCounts,
- self_func_addr: u32,
- imported_memory_count: u32,
-) -> Result<OptimizeResult> {
- let (mut instructions, old_to_new) = if options.optimize_rewrite() {
- let boundaries = target_boundaries(&instructions, function_data)?;
- let (instructions, old_to_new) = rewrite(instructions, &boundaries, function_results, self_func_addr);
- (instructions, Some(old_to_new))
- } else {
- (instructions, None)
- };
- let uses_local_memory = finalize(&mut instructions, function_data, old_to_new.as_deref(), imported_memory_count)?;
- Ok(OptimizeResult { instructions, uses_local_memory })
-}
-
-fn rewrite(
- source: Vec<Instruction>,
- boundaries: &[bool],
- function_results: ValueCounts,
- self_func_addr: u32,
-) -> (Vec<Instruction>, Vec<u32>) {
- use Instruction::*;
- let mut instrs =
- CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0, tail_rewritten: false };
- let mut old_to_new = alloc::vec![0; source.len() + 1];
- let mut after_terminator = false;
- let return_instr = match function_results {
- ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid),
- ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32),
- ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64),
- ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128),
- _ => None,
- };
-
- for (old_idx, instr) in source.iter().copied().enumerate() {
- if boundaries[old_idx] || after_terminator {
- instrs.block_start = instrs.len();
- }
- old_to_new[old_idx] = instrs.len() as u32;
- instrs.tail_rewritten = false;
- instrs.push(instr);
- let mut i = instrs.len() - 1;
- match instrs[i] {
- LocalCopy32(a, b) if a == b => {
- instrs.pop();
- }
- LocalCopy64(a, b) if a == b => {
- instrs.pop();
- }
- LocalCopy128(a, b) if a == b => {
- instrs.pop();
- }
- Call(addr) if addr == self_func_addr => instrs[i] = CallSelf,
- ReturnCall(addr) if addr == self_func_addr => instrs[i] = ReturnCallSelf,
- Return if let Some(return_instr) = return_instr => instrs[i] = return_instr,
- instr @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => {
- let Some(op) = int_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b));
- rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c));
- rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c));
- rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global));
- if matches!(op, BinOp::IAdd) {
- rewrite!(instrs, i, [Const32(c)] => AddConst32(c));
- rewrite!(instrs, i, [I32Add] => I32Add3);
- }
- }
- instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => {
- let Some(op) = int_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b));
- rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c));
- rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global));
- if matches!(op, BinOp::IShrS) {
- rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]);
- rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]);
- }
- }
- instr @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => {
- let Some(op) = int_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b));
- rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c));
- rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c));
- rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global));
- if matches!(op, BinOp::IAdd) {
- rewrite!(instrs, i, [Const64(c)] => AddConst64(c));
- rewrite!(instrs, i, [I64Add] => I64Add3);
- }
- }
- instr @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => {
- let Some(op) = int_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b));
- rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c));
- rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global));
- if matches!(op, BinOp::IShrS) {
- rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]);
- rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]);
- rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 32), Const64(32)] => [LocalGet64(local), I64Extend32S]);
- }
- }
- instr @ (F32Add | F32Mul | F32Min | F32Max) => {
- let Some(op) = float_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b));
- rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c));
- rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c));
- }
- instr @ (F32Sub | F32Div | F32Copysign) => {
- let Some(op) = float_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b));
- rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c));
- }
- instr @ (F64Add | F64Mul | F64Min | F64Max) => {
- let Some(op) = float_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b));
- rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c));
- rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c));
- }
- instr @ (F64Sub | F64Div | F64Copysign) => {
- let Some(op) = float_bin_op(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b));
- rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c));
- }
- instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => {
- let Some(op) = bin_op_128(instr) else { unreachable!() };
- rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b));
- rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c));
- rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c));
- }
- V128AndNot => {
- rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b));
- rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c));
- }
- I32Store(memarg) | F32Store(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if
- (load_memarg == memarg && addr == u16::from(load_addr)) =>
- IncMemoryLocal32(memarg, load_addr)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if
- (load_memarg == memarg && addr == u16::from(load_addr)) =>
- IncMemoryLocal32(memarg, load_addr)
- );
- rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg));
- rewrite!(instrs, i,
- [LocalGet32(addr_local), LocalGet32(value_local)] if
- (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) =>
- StoreLocalLocal32(memarg, addr_local, value_local)
- );
- }
- I64Store(memarg) | F64Store(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if
- (load_memarg == memarg && addr == u16::from(load_addr)) =>
- IncMemoryLocal64(memarg, load_addr)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if
- (load_memarg == memarg && addr == u16::from(load_addr)) =>
- IncMemoryLocal64(memarg, load_addr)
- );
- rewrite!(instrs, i, [F64Mul, F64Add] => FMaStoreF64(memarg));
- rewrite!(instrs, i,
- [LocalGet32(addr_local), LocalGet64(value_local)] if
- (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) =>
- StoreLocalLocal64(memarg, addr_local, value_local)
- );
- }
- V128Store(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local), LocalGet128(value_local)] if
- (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) =>
- StoreLocalLocal128(memarg, addr_local, value_local)
- );
- }
- I32Load(memarg) | F32Load(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal32(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal32(memarg, addr_local)
- );
- }
- I64Load(memarg) | F64Load(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal64(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal64(memarg, addr_local)
- );
- }
- I32Load8S(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal8S32(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal8S32(memarg, addr_local)
- );
- }
- I32Load8U(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal8U32(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal8U32(memarg, addr_local)
- );
- }
- I32Load16S(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal16S32(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal16S32(memarg, addr_local)
- );
- }
- I32Load16U(memarg) => {
- rewrite!(instrs, i,
- [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal16U32(memarg, addr_local)
- );
- rewrite!(instrs, i,
- [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) =>
- LoadLocal16U32(memarg, addr_local)
- );
- }
- MemoryFill(mem) => {
- rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size))
- }
- LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)),
- LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)),
- LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)),
- LocalSet32(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_32,
- op = scalar_bin_op,
- const = scalar_const_32,
- local_local = BinOpLocalLocalSet32,
- local_const = |dst, lhs, op, imm| match (dst == lhs, op) {
- (true, BinOp::IAdd) => Instruction::IncLocal32(dst, imm),
- (true, BinOp::ISub) => Instruction::IncLocal32(dst, imm.wrapping_neg()),
- _ => Instruction::BinOpLocalConstSet32(op, lhs, imm, dst),
- }
- );
- rewrite!(instrs, i, [I32Mul, LocalGet32(acc), I32Add] if (acc == dst) => MulAccLocal32(dst));
- rewrite!(instrs, i, [F32Mul, LocalGet32(acc), F32Add] if (acc == dst) => FMulAccLocal32(dst));
- rewrite_local_set_direct!(
- instrs,
- i,
- dst,
- get = LocalGet32,
- copy = LocalCopy32,
- binop_local_local = BinOpLocalLocal32,
- binop_local_local_set = BinOpLocalLocalSet32,
- binop_local_const = BinOpLocalConst32,
- binop_local_const_set = |dst, src, op, c| match (dst == src, op) {
- (true, BinOp::IAdd) => IncLocal32(dst, c),
- (true, BinOp::ISub) => IncLocal32(dst, c.wrapping_neg()),
- _ => BinOpLocalConstSet32(op, src, c, dst),
- },
- const_instr = Const32,
- set_local_const = SetLocalConst32
- );
- rewrite!(instrs, i, [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet32(memarg, addr, dst));
- rewrite!(instrs, i, [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8S32(memarg, addr, dst));
- rewrite!(instrs, i, [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8U32(memarg, addr, dst));
- rewrite!(instrs, i, [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16S32(memarg, addr, dst));
- rewrite!(instrs, i, [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16U32(memarg, addr, dst));
- rewrite!(instrs, i,
- [LocalGet32(addr), I32Load(memarg)] if
- (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) =>
- LoadLocalSet32(memarg, addr, dst)
- );
- }
- LocalSet64(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_64,
- op = scalar_bin_op,
- const = scalar_const_64,
- local_local = BinOpLocalLocalSet64,
- local_const = |dst, lhs, op, imm| match (dst == lhs, op) {
- (true, BinOp::IAdd) => Instruction::IncLocal64(dst, imm),
- (true, BinOp::ISub) => Instruction::IncLocal64(dst, imm.wrapping_neg()),
- _ => Instruction::BinOpLocalConstSet64(op, lhs, imm, dst),
- }
- );
- rewrite!(instrs, i, [I64Mul, LocalGet64(acc), I64Add] if (acc == dst) => MulAccLocal64(dst));
- rewrite!(instrs, i, [F64Mul, LocalGet64(acc), F64Add] if (acc == dst) => FMulAccLocal64(dst));
- rewrite_local_set_direct!(
- instrs,
- i,
- dst,
- get = LocalGet64,
- copy = LocalCopy64,
- binop_local_local = BinOpLocalLocal64,
- binop_local_local_set = BinOpLocalLocalSet64,
- binop_local_const = BinOpLocalConst64,
- binop_local_const_set = |dst, src, op, c| match (dst == src, op) {
- (true, BinOp::IAdd) => IncLocal64(dst, c),
- (true, BinOp::ISub) => IncLocal64(dst, c.wrapping_neg()),
- _ => BinOpLocalConstSet64(op, src, c, dst),
- },
- const_instr = Const64,
- set_local_const = SetLocalConst64
- );
- }
- LocalSet128(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_128,
- op = bin_op_128,
- const = const_128,
- local_local = BinOpLocalLocalSet128,
- local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstSet128(op, lhs, imm, dst)
- );
- rewrite_local_set_direct!(
- instrs,
- i,
- dst,
- get = LocalGet128,
- copy = LocalCopy128,
- binop_local_local = BinOpLocalLocal128,
- binop_local_local_set = BinOpLocalLocalSet128,
- binop_local_const = BinOpLocalConst128,
- binop_local_const_set = |dst, src, op, c| BinOpLocalConstSet128(op, src, c, dst),
- const_instr = Const128,
- set_local_const = SetLocalConst128
- );
- rewrite!(instrs, i,
- [LocalGet32(addr), V128Load(memarg)] if
- (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) =>
- LoadLocalSet128(memarg, addr, dst)
- );
- }
- LocalTee32(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_32,
- op = scalar_bin_op,
- const = scalar_const_32,
- local_local = BinOpLocalLocalTee32,
- local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee32(op, lhs, imm, dst)
- );
- rewrite_local_tee_direct!(
- instrs,
- i,
- dst,
- get = LocalGet32,
- binop_local_local = BinOpLocalLocal32,
- binop_local_local_tee = BinOpLocalLocalTee32,
- binop_local_const = BinOpLocalConst32,
- binop_local_const_tee = BinOpLocalConstTee32
- );
- rewrite!(instrs, i, [Const32(c), I32And] => AndConstTee32(c, dst));
- rewrite!(instrs, i, [Const32(c), I32Sub] => SubConstTee32(c, dst));
- rewrite!(instrs, i,
- [LocalGet32(addr), I32Load(memarg)] if
- (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) =>
- LoadLocalTee32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LocalGet32(addr), F32Load(memarg)] if
- (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) =>
- LoadLocalTee32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) =>
- LoadLocalTee32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) =>
- LoadLocalTee8S32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) =>
- LoadLocalTee8U32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) =>
- LoadLocalTee16S32(memarg, addr, dst)
- );
- rewrite!(instrs, i,
- [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) =>
- LoadLocalTee16U32(memarg, addr, dst)
- );
- }
- LocalTee64(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_64,
- op = scalar_bin_op,
- const = scalar_const_64,
- local_local = BinOpLocalLocalTee64,
- local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee64(op, lhs, imm, dst)
- );
- rewrite_local_tee_direct!(
- instrs,
- i,
- dst,
- get = LocalGet64,
- binop_local_local = BinOpLocalLocal64,
- binop_local_local_tee = BinOpLocalLocalTee64,
- binop_local_const = BinOpLocalConst64,
- binop_local_const_tee = BinOpLocalConstTee64
- );
- rewrite!(instrs, i, [Const64(c), I64And] => AndConstTee64(c, dst));
- rewrite!(instrs, i, [Const64(c), I64Sub] => SubConstTee64(c, dst));
- }
- LocalTee128(dst) => {
- fold_local_binop!(
- instrs, i, dst,
- source = resolve_local_source_128,
- op = bin_op_128,
- const = const_128,
- local_local = BinOpLocalLocalTee128,
- local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee128(op, lhs, imm, dst)
- );
- rewrite_local_tee_direct!(
- instrs,
- i,
- dst,
- get = LocalGet128,
- binop_local_local = BinOpLocalLocal128,
- binop_local_local_tee = BinOpLocalLocalTee128,
- binop_local_const = BinOpLocalConst128,
- binop_local_const_tee = BinOpLocalConstTee128
- );
- rewrite!(instrs, i,
- [LocalGet32(addr), V128Load(memarg)] if
- (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) =>
- LoadLocalTee128(memarg, addr, dst)
- );
- }
- Drop32 => rewrite_drop_tee_direct!(
- instrs,
- i,
- tee = LocalTee32,
- set = LocalSet32,
- binop_local_local_tee = BinOpLocalLocalTee32,
- binop_local_local_set = BinOpLocalLocalSet32,
- binop_local_const_tee = BinOpLocalConstTee32,
- binop_local_const_set = BinOpLocalConstSet32
- ),
- Drop64 => rewrite_drop_tee_direct!(
- instrs,
- i,
- tee = LocalTee64,
- set = LocalSet64,
- binop_local_local_tee = BinOpLocalLocalTee64,
- binop_local_local_set = BinOpLocalLocalSet64,
- binop_local_const_tee = BinOpLocalConstTee64,
- binop_local_const_set = BinOpLocalConstSet64
- ),
- Drop128 => rewrite_drop_tee_direct!(
- instrs,
- i,
- tee = LocalTee128,
- set = LocalSet128,
- binop_local_local_tee = BinOpLocalLocalTee128,
- binop_local_local_set = BinOpLocalLocalSet128,
- binop_local_const_tee = BinOpLocalConstTee128,
- binop_local_const_set = BinOpLocalConstSet128
- ),
- Jump(ip) => {
- let target = resolve_jump_target(&source, ip);
- let exit = old_idx as u32 + 1;
- let body = target + 1;
-
- match source.get(target as usize).copied() {
- Some(JumpCmpLocalLocal32 { target_ip, left, right, op })
- if resolve_jump_target(&source, target_ip) == exit && body > target =>
- {
- instrs[i] = JumpCmpLocalLocal32 { target_ip: body, left, right, op: inverse_cmp_op(op) };
- }
- Some(JumpCmpLocalLocal64 { target_ip, left, right, op })
- if resolve_jump_target(&source, target_ip) == exit && body > target =>
- {
- instrs[i] = JumpCmpLocalLocal64 { target_ip: body, left, right, op: inverse_cmp_op(op) };
- }
- _ => canonicalize_jump_like_with_target(&mut instrs, i, target, exit),
- }
- }
- JumpIfZero32(ip) => {
- let target = resolve_jump_target(&source, ip);
- rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => {
- replace!(instrs, i, 2 => JumpIfLocalNonZero32 { target_ip: target, local });
- continue;
- });
- rewrite!(instrs, i, [I32Eqz] => {
- replace!(instrs, i, 1 => JumpIfNonZero32(target));
- continue;
- });
- rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local });
- rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => {
- replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local });
- continue;
- });
- rewrite!(instrs, i, [I64Eqz] => {
- replace!(instrs, i, 1 => JumpIfNonZero64(target));
- continue;
- });
- rewrite!(instrs, i,
- [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) =>
- match (imm, inverse_cmp_op(op)) {
- (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local },
- (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local },
- (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op },
- }
- );
- rewrite!(instrs, i,
- [LocalGet64(local), Const64(imm), cmp] if
- (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) =>
- match (imm, inverse_cmp_op(op)) {
- (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local },
- (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local },
- (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op },
- }
- );
- rewrite!(instrs, i,
- [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) =>
- JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) }
- );
- rewrite!(instrs, i,
- [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) =>
- JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) }
- );
- rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) {
- (0, CmpOp::Eq) => JumpIfZero32(target),
- (0, CmpOp::Ne) => JumpIfNonZero32(target),
- (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op },
- });
- rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) {
- (0, CmpOp::Eq) => JumpIfZero64(target),
- (0, CmpOp::Ne) => JumpIfNonZero64(target),
- (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op },
- });
- canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1);
- }
- JumpIfNonZero32(ip) => {
- let target = resolve_jump_target(&source, ip);
- rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => {
- replace!(instrs, i, 2 => JumpIfLocalZero32 { target_ip: target, local });
- continue;
- });
- rewrite!(instrs, i, [I32Eqz] => {
- replace!(instrs, i, 1 => JumpIfZero32(target));
- continue;
- });
- rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local });
- rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => {
- replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local });
- continue;
- });
- rewrite!(instrs, i, [I64Eqz] => {
- replace!(instrs, i, 1 => JumpIfZero64(target));
- continue;
- });
- rewrite!(instrs, i,
- [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) =>
- match (imm, op) {
- (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local },
- (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local },
- (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op },
- }
- );
- rewrite!(instrs, i,
- [LocalGet64(local), Const64(imm), cmp] if
- (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) =>
- match (imm, op) {
- (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local },
- (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local },
- (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op },
- }
- );
- rewrite!(instrs, i,
- [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) =>
- JumpCmpLocalLocal32 { target_ip: target, left, right, op }
- );
- rewrite!(instrs, i,
- [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) =>
- JumpCmpLocalLocal64 { target_ip: target, left, right, op }
- );
- rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) {
- (0, CmpOp::Eq) => JumpIfZero32(target),
- (0, CmpOp::Ne) => JumpIfNonZero32(target),
- (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op },
- });
- rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) {
- (0, CmpOp::Eq) => JumpIfZero64(target),
- (0, CmpOp::Ne) => JumpIfNonZero64(target),
- (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op },
- });
- canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1);
- }
- JumpIfZero64(ip) => {
- let target = resolve_jump_target(&source, ip);
- rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local });
- canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1);
- }
- JumpIfNonZero64(ip) => {
- let target = resolve_jump_target(&source, ip);
- rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local });
- canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1);
- }
- JumpCmpStackConst32 { target_ip, imm: 0, op } => {
- match op {
- CmpOp::Eq => instrs[i] = JumpIfZero32(target_ip),
- CmpOp::Ne => instrs[i] = JumpIfNonZero32(target_ip),
- _ => {}
- }
- canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1);
- }
- JumpCmpStackConst64 { target_ip, imm: 0, op } => {
- match op {
- CmpOp::Eq => instrs[i] = JumpIfZero64(target_ip),
- CmpOp::Ne => instrs[i] = JumpIfNonZero64(target_ip),
- _ => {}
- }
- canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1);
- }
- JumpCmpLocalConst32 { target_ip, local, imm: 0, op } => {
- match op {
- CmpOp::Eq => instrs[i] = JumpIfLocalZero32 { target_ip, local },
- CmpOp::Ne => instrs[i] = JumpIfLocalNonZero32 { target_ip, local },
- _ => {}
- }
- canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1);
- }
- JumpCmpLocalConst64 { target_ip, local, imm: 0, op } => {
- match op {
- CmpOp::Eq => instrs[i] = JumpIfLocalZero64 { target_ip, local },
- CmpOp::Ne => instrs[i] = JumpIfLocalNonZero64 { target_ip, local },
- _ => {}
- }
- canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1);
- }
- JumpCmpStackConst32 { .. }
- | JumpCmpStackConst64 { .. }
- | JumpCmpLocalConst32 { .. }
- | JumpCmpLocalConst64 { .. }
- | JumpCmpLocalLocal32 { .. }
- | JumpCmpLocalLocal64 { .. }
- | JumpIfLocalZero32 { .. }
- | JumpIfLocalNonZero32 { .. }
- | JumpIfLocalZero64 { .. }
- | JumpIfLocalNonZero64 { .. } => {
- canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1);
- }
- _ => {}
- }
-
- after_terminator = is_unconditional_terminator(instr);
- }
-
- old_to_new[source.len()] = instrs.len() as u32;
- (instrs.instructions, old_to_new)
-}
-
-fn cmp_op(instr: Instruction) -> Option<CmpOp> {
- Some(match instr {
- Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq,
- Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne,
- Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS,
- Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU,
- Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS,
- Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU,
- Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS,
- Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU,
- Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS,
- Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU,
- _ => return None,
- })
-}
-
-fn int_bin_op(instr: Instruction) -> Option<BinOp> {
- Some(match instr {
- Instruction::I32Add | Instruction::I64Add => BinOp::IAdd,
- Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub,
- Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul,
- Instruction::I32And | Instruction::I64And => BinOp::IAnd,
- Instruction::I32Or | Instruction::I64Or => BinOp::IOr,
- Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor,
- Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl,
- Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS,
- Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU,
- Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl,
- Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr,
- _ => return None,
- })
-}
-
-fn float_bin_op(instr: Instruction) -> Option<BinOp> {
- Some(match instr {
- Instruction::F32Add | Instruction::F64Add => BinOp::FAdd,
- Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub,
- Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul,
- Instruction::F32Div | Instruction::F64Div => BinOp::FDiv,
- Instruction::F32Min | Instruction::F64Min => BinOp::FMin,
- Instruction::F32Max | Instruction::F64Max => BinOp::FMax,
- Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign,
- _ => return None,
- })
-}
-
-fn scalar_bin_op(instr: Instruction) -> Option<BinOp> {
- int_bin_op(instr).or_else(|| float_bin_op(instr))
-}
-
-fn scalar_const_32(instr: Instruction, op_instr: Instruction) -> Option<i32> {
- match instr {
- Instruction::Const32(c) if scalar_bin_op(op_instr).is_some() => Some(c),
- _ => None,
- }
-}
-
-fn scalar_const_64(instr: Instruction, op_instr: Instruction) -> Option<i64> {
- match instr {
- Instruction::Const64(c) if scalar_bin_op(op_instr).is_some() => Some(c),
- _ => None,
- }
-}
-
-fn const_128(instr: Instruction, op_instr: Instruction) -> Option<ConstIdx> {
- match instr {
- Instruction::Const128(c) if bin_op_128(op_instr).is_some() => Some(c),
- _ => None,
- }
-}
-
-define_local_source_resolver!(
- resolve_local_source_32,
- get = LocalGet32,
- tee = LocalTee32,
- set = LocalSet32,
- binop_local_local_tee = BinOpLocalLocalTee32,
- binop_local_local_set = BinOpLocalLocalSet32,
- binop_local_const_tee = BinOpLocalConstTee32,
- binop_local_const_set = BinOpLocalConstSet32,
- load_local_tee = LoadLocalTee32,
- load_local_set = LoadLocalSet32
-);
-
-define_local_source_resolver!(
- resolve_local_source_64,
- get = LocalGet64,
- tee = LocalTee64,
- set = LocalSet64,
- binop_local_local_tee = BinOpLocalLocalTee64,
- binop_local_local_set = BinOpLocalLocalSet64,
- binop_local_const_tee = BinOpLocalConstTee64,
- binop_local_const_set = BinOpLocalConstSet64
-);
-
-define_local_source_resolver!(
- resolve_local_source_128,
- get = LocalGet128,
- tee = LocalTee128,
- set = LocalSet128,
- binop_local_local_tee = BinOpLocalLocalTee128,
- binop_local_local_set = BinOpLocalLocalSet128,
- binop_local_const_tee = BinOpLocalConstTee128,
- binop_local_const_set = BinOpLocalConstSet128,
- load_local_tee = LoadLocalTee128,
- load_local_set = LoadLocalSet128
-);
-
-fn bin_op_128(instr: Instruction) -> Option<BinOp128> {
- Some(match instr {
- Instruction::V128And => BinOp128::And,
- Instruction::V128AndNot => BinOp128::AndNot,
- Instruction::V128Or => BinOp128::Or,
- Instruction::V128Xor => BinOp128::Xor,
- Instruction::I64x2Add => BinOp128::I64x2Add,
- Instruction::I64x2Mul => BinOp128::I64x2Mul,
- _ => return None,
- })
-}
-
-fn inverse_cmp_op(op: CmpOp) -> CmpOp {
- match op {
- CmpOp::Eq => CmpOp::Ne,
- CmpOp::Ne => CmpOp::Eq,
- CmpOp::LtS => CmpOp::GeS,
- CmpOp::LtU => CmpOp::GeU,
- CmpOp::GtS => CmpOp::LeS,
- CmpOp::GtU => CmpOp::LeU,
- CmpOp::LeS => CmpOp::GtS,
- CmpOp::LeU => CmpOp::GtU,
- CmpOp::GeS => CmpOp::LtS,
- CmpOp::GeU => CmpOp::LtU,
- }
-}
-
-fn resolve_jump_target(instrs: &[Instruction], target: u32) -> u32 {
- let mut idx = target as usize;
- let mut steps = 0usize;
-
- while let Some(Instruction::Jump(next)) = instrs.get(idx)
- && steps < instrs.len()
- {
- idx = *next as usize;
- steps += 1;
- }
-
- idx as u32
-}
-
-fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> {
- Some(match instr {
- Instruction::Jump(ip)
- | Instruction::JumpIfZero32(ip)
- | Instruction::JumpIfNonZero32(ip)
- | Instruction::JumpIfZero64(ip)
- | Instruction::JumpIfNonZero64(ip)
- | Instruction::JumpIfRefNull(ip)
- | Instruction::JumpIfRefNonNull(ip)
- | Instruction::JumpCmpStackConst32 { target_ip: ip, .. }
- | Instruction::JumpCmpStackConst64 { target_ip: ip, .. }
- | Instruction::JumpIfLocalZero32 { target_ip: ip, .. }
- | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. }
- | Instruction::JumpIfLocalZero64 { target_ip: ip, .. }
- | Instruction::JumpIfLocalNonZero64 { target_ip: ip, .. }
- | Instruction::JumpCmpLocalConst32 { target_ip: ip, .. }
- | Instruction::JumpCmpLocalConst64 { target_ip: ip, .. }
- | Instruction::JumpCmpLocalLocal32 { target_ip: ip, .. }
- | Instruction::JumpCmpLocalLocal64 { target_ip: ip, .. } => ip,
- Instruction::BranchTable(ip, _, _) => ip,
- _ => return None,
- })
-}
-
-fn instruction_target(instr: &Instruction) -> Option<u32> {
- let mut instr = *instr;
- instruction_target_mut(&mut instr).copied()
-}
-
-fn canonicalize_jump_like(source: &[Instruction], instrs: &mut Vec<Instruction>, idx: usize, fallthrough: u32) {
- let Some(target) = instruction_target(&instrs[idx]) else {
- return;
- };
-
- canonicalize_jump_like_with_target(instrs, idx, resolve_jump_target(source, target), fallthrough);
-}
-
-fn canonicalize_jump_like_with_target(instrs: &mut Vec<Instruction>, idx: usize, target: u32, fallthrough: u32) {
- if matches!(instrs[idx], Instruction::Jump(_)) && target == fallthrough {
- instrs.truncate(idx);
- } else if let Some(ip) = instruction_target_mut(&mut instrs[idx]) {
- *ip = target;
- }
-}
-
-fn is_unconditional_terminator(instr: Instruction) -> bool {
- matches!(
- instr,
- Instruction::Unreachable
- | Instruction::Jump(_)
- | Instruction::BranchTable(..)
- | Instruction::Return
- | Instruction::ReturnVoid
- | Instruction::Return32
- | Instruction::Return64
- | Instruction::Return128
- | Instruction::ReturnCall(_)
- | Instruction::ReturnCallSelf
- | Instruction::ReturnCallIndirect(..)
- | Instruction::ReturnCallRef(_)
- )
-}
-
-fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result<Vec<bool>> {
- let mut boundaries = alloc::vec![false; instructions.len() + 1];
- for instr in instructions {
- if let Some(target) = instruction_target(instr) {
- let boundary = boundaries
- .get_mut(target as usize)
- .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?;
- *boundary = true;
- }
- if let Instruction::BranchTable(_, start, count) = *instr {
- let end =
- start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?;
- let targets = function_data
- .branch_table_targets
- .get(start as usize..end as usize)
- .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?;
- for &target in targets {
- let boundary = boundaries
- .get_mut(target as usize)
- .ok_or_else(|| ParseError::Other(alloc::format!("branch table target out of bounds: {target}")))?;
- *boundary = true;
- }
- }
- }
- Ok(boundaries)
-}
-
-/// Remaps rewritten targets, then validates targets and ranges while detecting local memory use.
-fn finalize(
- instructions: &mut [Instruction],
- function_data: &mut WasmFunctionData,
- old_to_new: Option<&[u32]>,
- imported_memory_count: u32,
-) -> Result<bool> {
- let len = instructions.len() as u32;
- for target in &mut function_data.branch_table_targets {
- if let Some(old_to_new) = old_to_new {
- *target = *old_to_new
- .get(*target as usize)
- .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?;
- }
- if *target >= len {
- return Err(ParseError::Other(alloc::format!("branch table target out of bounds: {target}")));
- }
- }
-
- let mut uses_local_memory = false;
- for instr in instructions {
- if let Some(target) = instruction_target_mut(instr) {
- if let Some(old_to_new) = old_to_new {
- *target = *old_to_new
- .get(*target as usize)
- .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?;
- }
- if *target >= len {
- return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}")));
- }
- }
- if let Instruction::BranchTable(_, start, count) = *instr {
- let end =
- start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?;
- function_data
- .branch_table_targets
- .get(start as usize..end as usize)
- .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?;
- }
- uses_local_memory |= instr.memory_addr().is_some_and(|mem| mem >= imported_memory_count);
- }
- Ok(uses_local_memory)
-}
diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs
index 88d1035..69dbac9 100644
--- a/crates/parser/src/parallel.rs
+++ b/crates/parser/src/parallel.rs
@@ -1,10 +1,10 @@
-use crate::module::{FunctionCode, optimize_function_code};
+use crate::module::FunctionCode;
+use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources};
use crate::{ParseError, ParserOptions, Result, conversion};
-use alloc::sync::Arc;
use alloc::vec::Vec;
use core::ops::Range;
-use tinywasm_types::ValueCounts;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, ValidatorResources};
+use tinywasm_types::{Shared, ValueCounts};
+use wasmparser::OperatorsReaderAllocations;
pub(crate) enum FunctionBodyInput<'a> {
Borrowed(wasmparser::FunctionBody<'a>),
@@ -14,15 +14,15 @@ pub(crate) enum FunctionBodyInput<'a> {
pub(crate) struct OwnedFunctionBody {
// A deferred stream code section is copied once, then shared by all queued
// function jobs from that section.
- pub section_bytes: Arc<[u8]>,
+ pub section_bytes: Shared<[u8]>,
pub body_range: Range<usize>,
- pub body_offset: usize,
+ pub body_offset: u64,
}
pub(crate) struct PendingFunction<'a> {
pub ordinal: usize,
pub results: ValueCounts,
- pub func_to_validate: Option<wasmparser::FuncToValidate<ValidatorResources>>,
+ pub func_to_validate: Option<FuncToValidate<ValidatorResources>>,
pub ty_idx: u32,
pub body: FunctionBodyInput<'a>,
}
@@ -48,10 +48,8 @@ pub(crate) fn should_use_parallel(options: &ParserOptions, num_functions: usize,
}
fn worker_count(options: &ParserOptions, num_functions: usize) -> usize {
- let requested = options
- .parser_threads()
- .unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1))
- .max(1);
+ let requested =
+ options.threads().unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)).max(1);
requested.min(MAX_WORKERS).min(num_functions.div_ceil(MIN_FUNCTIONS_PER_WORKER)).max(1)
}
@@ -60,30 +58,35 @@ fn process_function_job(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
validator_allocs: Option<FuncValidatorAllocations>,
reader_allocs: OperatorsReaderAllocations,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
+ let context = conversion::FunctionLoweringContext {
+ ty_idx: job.ty_idx,
+ self_func_addr: imported_func_count
+ .checked_add(job.ordinal)
+ .and_then(|idx| u32::try_from(idx).ok())
+ .ok_or_else(|| ParseError::Other("function index is too large".into()))?,
+ function_results: job.results,
+ };
+ #[cfg(feature = "validate")]
let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default()));
+ #[cfg(not(feature = "validate"))]
+ let validator = {
+ let _ = (job.func_to_validate, validator_allocs);
+ None
+ };
let (code, validator_allocs, reader_allocs) = match job.body {
FunctionBodyInput::Borrowed(func) => {
- conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)?
+ conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)?
}
FunctionBodyInput::Owned(body) => {
let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset);
let func = wasmparser::FunctionBody::new(reader);
- conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)?
+ conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)?
}
};
- let code = optimize_function_code(
- code,
- options,
- job.results,
- (imported_func_count + job.ordinal) as u32,
- imported_memory_count,
- )?;
-
Ok((code, validator_allocs, reader_allocs))
}
@@ -92,7 +95,6 @@ fn process_chunk<'a>(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<FunctionCode>> {
let mut validator_allocs = None;
let mut reader_allocs = OperatorsReaderAllocations::default();
@@ -100,15 +102,8 @@ fn process_chunk<'a>(
let mut codes = Vec::with_capacity(jobs.size_hint().0);
for job in jobs {
- let (code, next_validator_allocs, next_reader_allocs) = process_function_job(
- job,
- metadata,
- options,
- imported_func_count,
- imported_memory_count,
- validator_allocs,
- reader_allocs,
- )?;
+ let (code, next_validator_allocs, next_reader_allocs) =
+ process_function_job(job, metadata, options, imported_func_count, validator_allocs, reader_allocs)?;
codes.push(code);
validator_allocs = next_validator_allocs;
reader_allocs = next_reader_allocs;
@@ -122,11 +117,10 @@ pub(crate) fn process_pending(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<FunctionCode>> {
let num_workers = worker_count(options, pending.len());
if num_workers == 1 {
- return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count);
+ return process_chunk(pending, metadata, options, imported_func_count);
}
let code_count = pending.len();
let chunk_size = pending.len().div_ceil(num_workers);
@@ -144,10 +138,7 @@ pub(crate) fn process_pending(
bytes += body_len(&job.body);
chunk.push(job);
}
- handles
- .push(scope.spawn(move || {
- process_chunk(chunk, metadata, options, imported_func_count, imported_memory_count)
- }));
+ handles.push(scope.spawn(move || process_chunk(chunk, metadata, options, imported_func_count)));
}
let mut codes = Vec::with_capacity(code_count);
diff --git a/crates/parser/src/selection.rs b/crates/parser/src/selection.rs
new file mode 100644
index 0000000..2d96b66
--- /dev/null
+++ b/crates/parser/src/selection.rs
@@ -0,0 +1,314 @@
+//! Ordered rule families selected by lowering, not by the incoming opcode.
+//! Replacements are contiguous, non-growing suffixes and are not dispatched again.
+//! Small literals stay inline until a selected encoding needs a pooled operand.
+
+mod encoding;
+use crate::{Result, emitter::PendingTail, visit::FunctionDataBuilder};
+use encoding::*;
+use tinywasm_types::{Instruction, Instruction::*, *};
+
+// Patterns include the incoming instruction. First match wins, including identity
+// replacements. Parenthesized guards support expressions and let chains.
+macro_rules! families {
+ ($($name:ident($tail:ident, $data:ident $(, $arg:ident: $ty:ty)*) {
+ $([$($pattern:pat),+ $(,)?] $(if ($($guard:tt)+))? => $replacement:expr),+ $(,)?
+ })*) => {$(
+ #[doc = concat!("Applies the ordered `", stringify!($name), "` rules to the pending suffix.")]
+ #[inline]
+ pub(crate) fn $name($tail: &mut PendingTail<'_>, $data: &mut FunctionDataBuilder $(, $arg: $ty)*) -> Result<()> {
+ let _ = &$data;
+ $(
+ if let Some([$($pattern),+]) = $tail.suffix::<{ [$(stringify!($pattern)),+].len() }>()
+ $( && $($guard)+ )?
+ {
+ $tail.replace::<{ [$(stringify!($pattern)),+].len() }, _>($replacement);
+ return Ok(());
+ }
+ )+
+ Ok(())
+ }
+ )*};
+}
+
+#[rustfmt::skip]
+families! {
+ integer32(tail, data, op: BinOp, commutative: bool) {
+ [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)],
+ [GlobalGet32(global), _] => [BinOpStackGlobal32(op, global)],
+ [LocalGet32(local), _] => [BinOpStackLocal32(op, local)],
+ // Both producers only read locals, and the outer integer operation commutes.
+ [LocalGet32(local), producer, _] if (commutative && local_const32(data, producer).is_some()) => [producer, BinOpStackLocal32(op, local)],
+ [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?],
+ [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))],
+ [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?],
+ [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))],
+ [Const32(value), I32Add] => [AddConst32(value)],
+ [I32Add, I32Add] => [I32Add3],
+ [BinOpStackLocal32(BinOp::IAdd, local), I32Add] => [LocalGet32(local), I32Add3],
+ [left, Const32(right), _] if (op == BinOp::IShrS
+ && let Some((BinOp::IShl, local, shift)) = local_const32(data, left)
+ && shift == right && matches!(shift, 16 | 24)) =>
+ [LocalGet32(local), if shift == 24 { I32Extend8S } else { I32Extend16S }],
+ [Const32(value), _] if (op != BinOp::IAdd) => [stack_const32(op, value)],
+ }
+ integer64(tail, data, op: BinOp, commutative: bool) {
+ [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)],
+ [GlobalGet64(global), _] => [BinOpStackGlobal64(op, global)],
+ [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))],
+ [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))],
+ [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))],
+ [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))],
+ [constant @ (Const64(_) | Const64Imm(_)), I64Add] => [AddConst64(pool64(data, constant)?)],
+ [I64Add, I64Add] => [I64Add3],
+ [left, constant, _] if (op == BinOp::IShrS
+ && let Some((BinOp::IShl, local, shift)) = local_const64(data, left)
+ && Some(shift) == const64(data, constant) && matches!(shift, 56 | 48 | 32)) =>
+ [LocalGet64(local), match shift { 56 => I64Extend8S, 48 => I64Extend16S, _ => I64Extend32S }],
+ [constant @ (Const64(_) | Const64Imm(_)), _] if (op != BinOp::IAdd) => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))],
+ }
+ compare(tail, data, op: CmpOp) {
+ [LocalGet32(a), LocalGet32(b), _] => [CmpLocalLocal32(op, a, b)],
+ [LocalGet64(a), LocalGet64(b), _] => [CmpLocalLocal64(op, a, b)],
+ }
+ extend_i32(tail, data, signed: bool) {
+ [Const32(value), _] => [{
+ let value = if signed { i64::from(value) } else { i64::from(value as u32) };
+ match i32::try_from(value) {
+ Ok(value) => Const64Imm(value),
+ Err(_) => Const64(data.push64(Operand64::<i64>::new(value))?),
+ }
+ }],
+ }
+ float32(tail, data, op: BinOp, commutative: bool) {
+ [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)],
+ [LocalGet32(local), _] => [BinOpStackLocal32(op, local)],
+ [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?],
+ [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))],
+ [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?],
+ [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))],
+ [Const32(value), _] => [stack_const32(op, value)],
+ }
+ float64(tail, data, op: BinOp, commutative: bool) {
+ [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)],
+ [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))],
+ [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))],
+ [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))],
+ [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))],
+ [constant @ (Const64(_) | Const64Imm(_)), _] => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))],
+ }
+ vector(tail, data, op: BinOp128, commutative: bool) {
+ // Stack/local deliberately shadows local/local and reversed local constants.
+ [LocalGet128(local), _] => [BinOpStackLocal128(op, local)],
+ [LocalGet128(a), LocalGet128(b), _] => [BinOpLocalLocal128(op, a, b)],
+ [LocalGet128(local), constant @ (Const128(_) | Const128Imm(_)), _] => [{
+ let value = pool128(data, constant)?;
+ BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?))
+ }],
+ [GlobalGet128(global), constant @ (Const128(_) | Const128Imm(_)), _] => [{
+ let value = pool128(data, constant)?;
+ BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?))
+ }],
+ [constant @ (Const128(_) | Const128Imm(_)), LocalGet128(local), _] if (commutative) => [{
+ let value = pool128(data, constant)?;
+ BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?))
+ }],
+ [constant @ (Const128(_) | Const128Imm(_)), GlobalGet128(global), _] if (commutative) => [{
+ let value = pool128(data, constant)?;
+ BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?))
+ }],
+ }
+ store32(tail, data, index: Operand128Idx<MemoryOperand>) {
+ [Select32, _] => [SelectStore32(index)],
+ [LocalGet32(addr) | LocalGet64(addr), LoadLocal32(arg), AddConst32(1), _]
+ if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from)
+ == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1)) => [IncMemoryLocal32(arg)],
+ [F32Mul, F32Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF32(arg)],
+ [BinOpStackLocal32(BinOp::FMul, local), F32Add, _]
+ if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [LocalGet32(local), FMaStoreF32(arg)],
+ [LocalGet32(addr), LocalGet32(value), _]
+ if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value),
+ CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal32(MemoryLocalArg {
+ memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })],
+ }
+ store64(tail, data, index: Operand128Idx<MemoryOperand>) {
+ [Select64, _] => [SelectStore64(index)],
+ [LocalGet32(addr) | LocalGet64(addr), LoadLocal64(arg), AddConst64(one), _]
+ if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from)
+ == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1)
+ && data.operand64(one).value() == 1) => [IncMemoryLocal64(arg)],
+ [F64Mul, F64Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF64(arg)],
+ [LocalGet32(addr), LocalGet64(value), _]
+ if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value),
+ CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal64(MemoryLocalArg {
+ memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })],
+ }
+ memory_fill(tail, data, memory: u32) {
+ [Const32(value), Const32(size), _] => [MemoryFillConst(data.push128(Operand128::<MemoryFillOperand>::new(memory, value as u8, size))?)],
+ }
+ global_get32(tail, data, dst: u32) { [GlobalSet32(src), _] if (src == dst) => [GlobalTee32(src)] }
+ global_get64(tail, data, dst: u32) { [GlobalSet64(src), _] if (src == dst) => [GlobalTee64(src)] }
+ global_get128(tail, data, dst: u32) { [GlobalSet128(src), _] if (src == dst) => [GlobalTee128(src)] }
+ local_get32(tail, data, dst: u16) { [LocalSet32(src), _] if (src == dst) => [LocalTee32(src)] }
+ local_get64(tail, data, dst: u16) { [LocalSet64(src), _] if (src == dst) => [LocalTee64(src)] }
+ local_get128(tail, data, dst: u16) { [LocalSet128(src), _] if (src == dst) => [LocalTee128(src)] }
+ local_set32(tail, data, dst: u16) {
+ [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc), _] if (acc == dst) => [MulAccLocal32(dst)],
+ [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc), _] if (acc == dst) => [FMulAccLocal32(dst)],
+ [LocalGet32(src), _] if (src == dst) => [],
+ [LocalGet32(src), _] => [LocalCopy32(src, dst)],
+ [Const32(value), _] => [SetLocalConst32(I32LocalArg { value, local: dst })],
+ [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalSet32(LocalTripleArg { left, right, dst })],
+ [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalSet32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) => [{
+ if src == dst && let Some(delta) = op.inc_delta(value) {
+ IncLocal32(I32LocalArg { value: delta, local: dst })
+ } else { local_const_set32(data, op, src, dst, value, false)? }
+ }],
+ [BinOpStackLocal32(op, local), _] => [BinOpStackLocalSet32(op, local, dst)],
+ [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8S32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8U32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16S32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16U32(MemoryLocalArg { local2: dst, ..arg })],
+ }
+ local_set64(tail, data, dst: u16) {
+ [I64Mul, LocalGet64(acc), I64Add, _] if (acc == dst) => [MulAccLocal64(dst)],
+ [F64Mul, LocalGet64(acc), F64Add, _] if (acc == dst) => [FMulAccLocal64(dst)],
+ [LocalGet64(src), _] if (src == dst) => [],
+ [LocalGet64(src), _] => [LocalCopy64(src, dst)],
+ [constant @ (Const64(_) | Const64Imm(_)), _] => [SetLocalConst64(PackedOp::new(dst, pool64(data, constant)?))],
+ [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalSet64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [{
+ if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) {
+ let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() };
+ IncLocal64(PackedOp::new(dst, data.push64(Operand64::<i64>::new(delta))?))
+ } else { local_const_set64(data, op, src, dst, value, false)? }
+ }],
+ }
+ local_set128(tail, data, dst: u16) {
+ [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) =
+ (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) =>
+ [LoadLocalSet128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })],
+ [LocalGet128(src), _] if (src == dst) => [],
+ [LocalGet128(src), _] => [LocalCopy128(src, dst)],
+ [constant @ (Const128(_) | Const128Imm(_)), _] => [SetLocalConst128(PackedOp::new(dst, pool128(data, constant)?))],
+ [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalSet128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) =>
+ [local_const_set128(data, op, src, dst, value, false)?],
+ }
+ local_tee32(tail, data, dst: u16) {
+ [Const32(value), I32And, _] => [AndConstTee32(I32LocalArg { value, local: dst })],
+ [Const32(value), I32Sub, _] => [SubConstTee32(I32LocalArg { value, local: dst })],
+ [AndConst32(value), _] => [AndConstTee32(I32LocalArg { value, local: dst })],
+ [BinOpStackConst32(BinOp::ISub, value), _] => [SubConstTee32(I32LocalArg { value, local: dst })],
+ [LocalGet32(src), _] if (src == dst) => [LocalGet32(src)],
+ [LocalGet32(src), _] => [LocalCopy32(src, dst), LocalGet32(dst)],
+ [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalTee32(LocalTripleArg { left, right, dst })],
+ [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalTee32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) =>
+ [local_const_set32(data, op, src, dst, value, true)?],
+ [BinOpStackLocal32(op, local), _] => [BinOpStackLocalTee32(op, local, dst)],
+ [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8S32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8U32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16S32(MemoryLocalArg { local2: dst, ..arg })],
+ [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16U32(MemoryLocalArg { local2: dst, ..arg })],
+ }
+ local_tee64(tail, data, dst: u16) {
+ [constant @ (Const64(_) | Const64Imm(_)), I64And, _] => [AndConstTee64(PackedOp::new(dst, pool64(data, constant)?))],
+ [constant @ (Const64(_) | Const64Imm(_)), I64Sub, _] => [SubConstTee64(PackedOp::new(dst, pool64(data, constant)?))],
+ [BinOpStackConst64(packed), _] if (packed.op == BinOp::IAnd) => [AndConstTee64(PackedOp::new(dst, packed.index))],
+ [BinOpStackConst64(packed), _] if (packed.op == BinOp::ISub) => [SubConstTee64(PackedOp::new(dst, packed.index))],
+ [LocalGet64(src), _] if (src == dst) => [LocalGet64(src)],
+ [LocalGet64(src), _] => [LocalCopy64(src, dst), LocalGet64(dst)],
+ [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalTee64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [local_const_set64(data, op, src, dst, value, true)?],
+ }
+ local_tee128(tail, data, dst: u16) {
+ [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) =
+ (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) =>
+ [LoadLocalTee128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })],
+ [LocalGet128(src), _] if (src == dst) => [LocalGet128(src)],
+ [LocalGet128(src), _] => [LocalCopy128(src, dst), LocalGet128(dst)],
+ [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalTee128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))],
+ [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) => [local_const_set128(data, op, src, dst, value, true)?],
+ }
+ drop32(tail, data) {
+ [LocalTee32(local), _] => [LocalSet32(local)],
+ [BinOpStackLocalTee32(op, local, dst), _] => [BinOpStackLocalSet32(op, local, dst)],
+ [AddLocalLocalTee32(arg), _] => [AddLocalLocalSet32(arg)],
+ [BinOpLocalLocalTee32(packed), _] => [BinOpLocalLocalSet32(packed)],
+ [BinOpLocalConstTee32(packed), _] => [BinOpLocalConstSet32(packed)],
+ }
+ drop64(tail, data) {
+ [LocalTee64(local), _] => [LocalSet64(local)],
+ [BinOpLocalLocalTee64(packed), _] => [BinOpLocalLocalSet64(packed)],
+ [BinOpLocalConstTee64(packed), _] => [BinOpLocalConstSet64(packed)],
+ }
+ drop128(tail, data) {
+ [LocalTee128(local), _] => [LocalSet128(local)],
+ [BinOpLocalLocalTee128(packed), _] => [BinOpLocalLocalSet128(packed)],
+ [BinOpLocalConstTee128(packed), _] => [BinOpLocalConstSet128(packed)],
+ }
+ load(tail, data, instruction: impl FnOnce(MemoryLocalArg) -> Instruction, index: Operand128Idx<MemoryOperand>) {
+ [LocalGet32(local) | LocalGet64(local), _]
+ if (let Ok(local) = u8::try_from(local)
+ && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) =>
+ [instruction(MemoryLocalArg {
+ memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: 0 })],
+ }
+ store128(tail, data, index: Operand128Idx<MemoryOperand>) {
+ [LocalGet32(addr), LocalGet128(value), _]
+ if (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))
+ && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) =>
+ [StoreLocalLocal128(MemoryLocalArg {
+ memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })],
+ }
+ conditional(tail, data, on_zero: bool, target: u32) {
+ [BinOpLocalConstTee32(packed), _] if (data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{
+ let value = data.operand64(packed.index);
+ update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?
+ }],
+ [BinOpGlobalConst32(packed), GlobalTee32(dst), _] if (data.operand64(packed.index).a() == dst) => [update_jump(data, target, data.operand64(packed.index).b() as i32, dst, packed.op, on_zero, true)?],
+ [AddConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [IncStackTeeLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?)],
+ [XorConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IXor, on_zero)?],
+ [ShrUConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IShrU, on_zero)?],
+ [BinOpStackConst32(op, value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, op, on_zero)?],
+ [AndConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) => [stack_update_jump(data, target, arg.value, arg.local, BinOp::IAnd, on_zero)?],
+ [SubConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) =>
+ [IncStackTeeLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new(
+ target, arg.value.wrapping_neg(), arg.local, on_zero))?)],
+ [BinOpLocalConstTee32(packed), LocalGet32(right), raw_cmp, _]
+ if (let Some(cmp) = cmp_op(raw_cmp)
+ && data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{
+ let value = data.operand64(packed.index);
+ let cmp = if on_zero { cmp.inverse() } else { cmp };
+ if let Some(delta) = packed.op.inc_delta(value.c() as i32) {
+ IncLocalJumpCmpLocal32(PackedOp::new(cmp, data.push_target128(
+ Operand128::<LocalUpdateCmpOperand>::new(target, delta, value.a(), right))?))
+ } else {
+ BinOpLocalConstJumpCmpLocal32(PackedOp::new((packed.op, cmp), data.push_target128(
+ Operand128::<LocalUpdateCmpOperand>::new(target, value.c() as i32, value.a(), right))?))
+ }
+ }],
+ [LocalGet32(local), I32Eqz, _] => [local_jump(target, local, !on_zero, false)],
+ [LocalGet64(local), I64Eqz, _] => [local_jump(target, local, !on_zero, true)],
+ [CmpLocalLocal32(op, left, right), I32Eqz, _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op } else { op.inverse() }, false)?],
+ [I32Eqz, _] => [if on_zero { JumpIfNonZero32(target) } else { JumpIfZero32(target) }],
+ [I64Eqz, _] => [if on_zero { JumpIfNonZero64(target) } else { JumpIfZero64(target) }],
+ [CmpLocalLocal32(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, false)?],
+ [CmpLocalLocal64(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, true)?],
+ [LocalGet32(local), _] => [local_jump(target, local, on_zero, false)],
+ [LocalGet64(local), _] => [local_jump(target, local, on_zero, true)],
+ [LocalGet32(local), Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_const32(data, target, local, value, op)?],
+ [LocalGet64(local), constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)
+ && let Some(value) = const64(data, constant) && let Ok(value) = i32::try_from(value)) =>
+ [jump_cmp_local_const64(data, target, local, value, op)?],
+ [LocalGet32(left), LocalGet32(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, false)?],
+ [LocalGet64(left), LocalGet64(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, true)?],
+ [LocalGet32(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, false)?],
+ [LocalGet64(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, true)?],
+ [Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_const32(data, target, value, op)?],
+ [constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero) && let Some(value) = const64(data, constant)) => [jump_cmp_stack_const64(data, target, value, op)?],
+ }
+}
diff --git a/crates/parser/src/selection/encoding.rs b/crates/parser/src/selection/encoding.rs
new file mode 100644
index 0000000..0b407e5
--- /dev/null
+++ b/crates/parser/src/selection/encoding.rs
@@ -0,0 +1,293 @@
+//! Operand decoding and encoding, without access to the instruction tail.
+use crate::{Result, visit::FunctionDataBuilder};
+use tinywasm_types::{Instruction, Instruction::*, *};
+
+/// Reads a 64-bit literal without requiring a pool entry for immediate values.
+pub(super) fn const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option<i64> {
+ match instruction {
+ Const64(index) => Some(data.operand64(index).value()),
+ Const64Imm(value) => Some(i64::from(value)),
+ _ => None,
+ }
+}
+
+/// Materializes a literal only when the selected encoding requires an operand index.
+pub(super) fn pool64(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result<Operand64Idx<i64>> {
+ match instruction {
+ Const64(index) => Ok(index),
+ Const64Imm(value) => data.push64(Operand64::<i64>::new(i64::from(value))),
+ _ => unreachable!("expected a 64-bit constant"),
+ }
+}
+
+/// Materializes a vector literal only when the selected encoding requires an operand index.
+pub(super) fn pool128(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result<Operand128Idx<[u8; 16]>> {
+ match instruction {
+ Const128(index) => Ok(index),
+ Const128Imm(value) => data.push128(Operand128::<[u8; 16]>::new(u128::from(value).to_le_bytes())),
+ _ => unreachable!("expected a vector constant"),
+ }
+}
+
+/// Decodes specialized and pooled local constants uniformly.
+pub(super) fn local_const32(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i32)> {
+ match instruction {
+ AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)),
+ SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)),
+ MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)),
+ AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)),
+ ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)),
+ BinOpLocalConst32(packed) => {
+ let value = data.operand64(packed.index);
+ Some((packed.op, value.a(), value.b() as i32))
+ }
+ _ => None,
+ }
+}
+
+/// Decodes a pooled 64-bit local constant.
+pub(super) fn local_const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i64)> {
+ let BinOpLocalConst64(packed) = instruction else { return None };
+ let value = data.operand128(packed.index);
+ Some((packed.op, value.a(), value.b() as i64))
+}
+
+/// Decodes a pooled vector local constant.
+pub(super) fn local_const128(
+ data: &FunctionDataBuilder,
+ instruction: Instruction,
+) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> {
+ let BinOpLocalConst128(packed) = instruction else { return None };
+ let value = data.operand64(packed.index);
+ Some((packed.op, value.a(), value.b()))
+}
+
+/// Encodes the dedicated 32-bit local operations before falling back to a pooled operand.
+pub(super) fn encode_local_const32(
+ data: &mut FunctionDataBuilder,
+ op: BinOp,
+ local: u16,
+ value: i32,
+) -> Result<Instruction> {
+ let arg = I32LocalArg { value, local };
+ Ok(match op {
+ BinOp::IAdd => AddLocalConst32(arg),
+ BinOp::ISub => SubLocalConst32(arg),
+ BinOp::IMul => MulLocalConst32(arg),
+ BinOp::IAnd => AndLocalConst32(arg),
+ BinOp::IShrU => ShrULocalConst32(arg),
+ _ => BinOpLocalConst32(PackedOp::new(op, data.push64(Operand64::<(u16, u32)>::new(local, value as u32))?)),
+ })
+}
+
+/// Encodes dedicated stack-immediate operations.
+pub(super) fn stack_const32(op: BinOp, value: i32) -> Instruction {
+ match op {
+ BinOp::IAnd => AndConst32(value),
+ BinOp::IXor => XorConst32(value),
+ BinOp::IShrU => ShrUConst32(value),
+ _ => BinOpStackConst32(op, value),
+ }
+}
+
+macro_rules! local_const_set {
+ ($($name:ident, $op:ty, $value:ty, [$($cast:tt)*], $pool:ident, $operand:ty, $set:ident, $tee:ident;)*) => {$(
+ /// Encodes a local constant operation with a destination local.
+ pub(super) fn $name(data: &mut FunctionDataBuilder, op: $op, src: u16, dst: u16, value: $value, tee: bool) -> Result<Instruction> {
+ let index = data.$pool(<$operand>::new(src, dst, value $($cast)*))?;
+ Ok(if tee { $tee(PackedOp::new(op, index)) } else { $set(PackedOp::new(op, index)) })
+ }
+ )*};
+}
+local_const_set! {
+ local_const_set32, BinOp, i32, [as u32], push64, Operand64<(u16, u16, u32)>, BinOpLocalConstSet32, BinOpLocalConstTee32;
+ local_const_set64, BinOp, i64, [as u64], push128, Operand128<(u16, u16, u64)>, BinOpLocalConstSet64, BinOpLocalConstTee64;
+ local_const_set128, BinOp128, Operand128Idx<[u8; 16]>, [], push64, Operand64<(u16, u16, Operand128Idx<[u8; 16]>)>, BinOpLocalConstSet128, BinOpLocalConstTee128;
+}
+
+/// Decodes a preceding integer comparison, not the incoming instruction.
+pub(super) fn cmp_op(instruction: Instruction) -> Option<CmpOp> {
+ Some(match instruction {
+ I32Eq | I64Eq => CmpOp::Eq,
+ I32Ne | I64Ne => CmpOp::Ne,
+ I32LtS | I64LtS => CmpOp::LtS,
+ I32LtU | I64LtU => CmpOp::LtU,
+ I32GtS | I64GtS => CmpOp::GtS,
+ I32GtU | I64GtU => CmpOp::GtU,
+ I32LeS | I64LeS => CmpOp::LeS,
+ I32LeU | I64LeU => CmpOp::LeU,
+ I32GeS | I64GeS => CmpOp::GeS,
+ I32GeU | I64GeU => CmpOp::GeU,
+ _ => return None,
+ })
+}
+
+/// Applies branch polarity to a preceding integer comparison.
+pub(super) fn branch_cmp(instruction: Instruction, on_zero: bool) -> Option<CmpOp> {
+ cmp_op(instruction).map(|op| if on_zero { op.inverse() } else { op })
+}
+
+/// Encodes a local zero test of the requested width and polarity.
+pub(super) fn local_jump(target: u32, local: u16, on_zero: bool, width64: bool) -> Instruction {
+ let arg = TargetLocalArg { target_ip: target, local };
+ match (on_zero, width64) {
+ (true, false) => JumpIfLocalZero32(arg),
+ (false, false) => JumpIfLocalNonZero32(arg),
+ (true, true) => JumpIfLocalZero64(arg),
+ (false, true) => JumpIfLocalNonZero64(arg),
+ }
+}
+
+/// Allocates a private target operand for a local/local comparison.
+pub(super) fn jump_cmp_local_local(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ left: u16,
+ right: u16,
+ op: CmpOp,
+ width64: bool,
+) -> Result<Instruction> {
+ let index = data.push_target64(Operand64::<(u32, u16, u16)>::new(target, left, right))?;
+ Ok(if width64 {
+ JumpCmpLocalLocal64(PackedOp::new(op, index))
+ } else {
+ JumpCmpLocalLocal32(PackedOp::new(op, index))
+ })
+}
+
+/// Allocates a private target operand for a stack/local comparison.
+pub(super) fn jump_cmp_stack_local(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ local: u16,
+ op: CmpOp,
+ width64: bool,
+) -> Result<Instruction> {
+ let index = data.push_target64(Operand64::<(u32, u16)>::new(target, local))?;
+ Ok(if width64 {
+ JumpCmpStackLocal64(PackedOp::new(op, index))
+ } else {
+ JumpCmpStackLocal32(PackedOp::new(op, index))
+ })
+}
+
+/// Encodes a local/immediate comparison, specializing zero equality tests.
+pub(super) fn jump_cmp_local_const32(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ local: u16,
+ value: i32,
+ op: CmpOp,
+) -> Result<Instruction> {
+ if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) {
+ return Ok(local_jump(target, local, op == CmpOp::Eq, false));
+ }
+ Ok(JumpCmpLocalConst32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?,
+ )))
+}
+
+/// Encodes a 64-bit local comparison with a representable 32-bit immediate.
+pub(super) fn jump_cmp_local_const64(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ local: u16,
+ value: i32,
+ op: CmpOp,
+) -> Result<Instruction> {
+ if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) {
+ return Ok(local_jump(target, local, op == CmpOp::Eq, true));
+ }
+ Ok(JumpCmpLocalConst64(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?,
+ )))
+}
+
+/// Encodes a 32-bit stack/immediate comparison.
+pub(super) fn jump_cmp_stack_const32(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ value: i32,
+ op: CmpOp,
+) -> Result<Instruction> {
+ if value == 0 {
+ match op {
+ CmpOp::Eq => return Ok(JumpIfZero32(target)),
+ CmpOp::Ne => return Ok(JumpIfNonZero32(target)),
+ _ => {}
+ }
+ }
+ Ok(JumpCmpStackConst32(PackedOp::new(op, data.push_target64(Operand64::<(u32, i32)>::new(target, value))?)))
+}
+
+/// Encodes a 64-bit stack/immediate comparison.
+pub(super) fn jump_cmp_stack_const64(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ value: i64,
+ op: CmpOp,
+) -> Result<Instruction> {
+ if value == 0 {
+ match op {
+ CmpOp::Eq => return Ok(JumpIfZero64(target)),
+ CmpOp::Ne => return Ok(JumpIfNonZero64(target)),
+ _ => {}
+ }
+ }
+ Ok(JumpCmpStackConst64(PackedOp::new(op, data.push_target128(Operand128::<(u32, i64)>::new(target, value))?)))
+}
+
+/// Encodes a stack update, tee, and branch using a private target operand.
+pub(super) fn stack_update_jump(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ value: i32,
+ local: u16,
+ op: BinOp,
+ on_zero: bool,
+) -> Result<Instruction> {
+ Ok(BinOpStackConstTeeLocalJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?,
+ )))
+}
+
+/// Encodes local/global updates, specializing increments when possible.
+pub(super) fn update_jump(
+ data: &mut FunctionDataBuilder,
+ target: u32,
+ immediate: i32,
+ address: u32,
+ op: BinOp,
+ on_zero: bool,
+ global: bool,
+) -> Result<Instruction> {
+ if let Some(delta) = op.inc_delta(immediate) {
+ Ok(if global {
+ IncGlobalJump32(
+ data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, delta, address, on_zero))?,
+ )
+ } else {
+ IncLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new(
+ target,
+ delta,
+ address as u16,
+ on_zero,
+ ))?)
+ })
+ } else {
+ Ok(if global {
+ BinOpGlobalConstJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, immediate, address, on_zero))?,
+ ))
+ } else {
+ BinOpLocalConstJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<LocalUpdateOperand>::new(target, immediate, address as u16, on_zero))?,
+ ))
+ })
+ }
+}
diff --git a/crates/parser/src/validation.rs b/crates/parser/src/validation.rs
new file mode 100644
index 0000000..b2bb084
--- /dev/null
+++ b/crates/parser/src/validation.rs
@@ -0,0 +1,15 @@
+#[cfg(all(feature = "validate", parallel_parser))]
+pub(crate) use wasmparser::FuncToValidate;
+#[cfg(feature = "validate")]
+pub(crate) use wasmparser::{FuncValidator, FuncValidatorAllocations, Validator, ValidatorResources};
+
+#[cfg(all(not(feature = "validate"), parallel_parser))]
+pub(crate) type FuncToValidate<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidator<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidatorAllocations = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type Validator = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type ValidatorResources = ();
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index d0e970b..a362f84 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -1,14 +1,24 @@
-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,
+use crate::{
+ ParserOptions, Result,
+ conversion::{FunctionLoweringContext, convert_heap_type, value_lane},
+ emitter::{Emitter, LabelId},
+ macros::visit::*,
+};
+use alloc::{
+ boxed::Box,
+ collections::{BTreeMap, btree_map::Entry},
+ string::ToString,
+ vec::Vec,
};
-use wasmparser::{
- FuncValidator, FuncValidatorAllocations, FunctionBody, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources, VisitOperator, VisitSimdOperator,
+use tinywasm_types::{
+ BinOp, BinOp128, CmpOp, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64,
+ Operand64Idx, Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts,
+ ValueLane, WasmFunctionData,
};
+use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator};
+
+#[cfg(feature = "validate")]
+use wasmparser::{FuncValidator, FuncValidatorAllocations, ValidatorResources, VisitOperator};
#[derive(Debug, Clone, Copy)]
enum BlockKind {
@@ -16,180 +26,319 @@ enum BlockKind {
Block,
Loop,
If,
+ TryTable,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum OperandSize {
- S32,
- S64,
- S128,
+struct ControlFrame<'a> {
+ kind: BlockKind,
+ has_else: bool,
+ loop_start: Option<LabelId>,
+ end: Option<LabelId>,
+ else_entry: Option<LabelId>,
+ height: usize,
+ base: ValueCounts,
+ signature: BlockSignature<'a>,
+ unreachable: bool,
+ entry_unreachable: bool,
+ end_reachable: bool,
+}
+
+/// Module-owned physical lane signature, borrowed by control frames.
+pub(crate) struct Signature {
+ pub params: Vec<ValueLane>,
+ results: Vec<ValueLane>,
+}
+
+#[derive(Clone, Copy)]
+enum BlockSignature<'a> {
+ Empty,
+ Result(ValueLane),
+ Function(&'a Signature),
}
-impl OperandSize {
- fn choose<T>(self, s32: T, s64: T, s128: T) -> T {
+impl BlockSignature<'_> {
+ fn params(&self) -> &[ValueLane] {
match self {
- Self::S32 => s32,
- Self::S64 => s64,
- Self::S128 => s128,
+ Self::Function(signature) => &signature.params,
+ _ => &[],
}
}
-}
-impl From<wasmparser::ValType> for OperandSize {
- fn from(ty: wasmparser::ValType) -> Self {
- match ty {
- wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => Self::S32,
- wasmparser::ValType::I64 | wasmparser::ValType::F64 => Self::S64,
- wasmparser::ValType::V128 => Self::S128,
+ fn results(&self) -> &[ValueLane] {
+ match self {
+ Self::Empty => &[],
+ Self::Result(lane) => core::slice::from_ref(lane),
+ Self::Function(signature) => &signature.results,
}
}
}
-impl From<&WasmType> for OperandSize {
- fn from(ty: &WasmType) -> Self {
- match ty {
- WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32,
- WasmType::I64 | WasmType::F64 => Self::S64,
- WasmType::V128 => Self::S128,
+pub(crate) struct ModuleMetadata {
+ signatures: Vec<Option<Signature>>,
+ functions: Vec<u32>,
+ globals: Vec<ValueLane>,
+ memories: Vec<ValueLane>,
+ tables: Vec<ValueLane>,
+ tags: Vec<u32>,
+ aggregate_fields: Vec<AggregateFields>,
+ imported_memories: u32,
+}
+
+pub(crate) struct FunctionDataBuilder {
+ pub(crate) operands64: Vec<Operand64>,
+ pub(crate) operands128: Vec<Operand128>,
+ pub(crate) branch_table_targets: Vec<u32>,
+ pub(crate) exception_handlers: Vec<ExceptionHandler>,
+ deduplicate64: Option<BTreeMap<Operand64, u32>>,
+ deduplicate128: Option<BTreeMap<Operand128, u32>>,
+}
+
+impl FunctionDataBuilder {
+ pub(crate) fn new(deduplicate_operands: bool) -> Self {
+ Self {
+ operands64: Vec::new(),
+ operands128: Vec::new(),
+ branch_table_targets: Vec::new(),
+ exception_handlers: Vec::new(),
+ deduplicate64: deduplicate_operands.then(BTreeMap::new),
+ deduplicate128: deduplicate_operands.then(BTreeMap::new),
}
}
-}
-impl From<MemoryArch> for OperandSize {
- fn from(arch: MemoryArch) -> Self {
- match arch {
- MemoryArch::I32 => Self::S32,
- MemoryArch::I64 => Self::S64,
+ /// Allocates an immutable 64-bit operand, reusing it when deduplication is enabled.
+ pub(crate) fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ let operand = operand.cast();
+ let entry = match self.deduplicate64.as_mut().map(|map| map.entry(operand)) {
+ Some(Entry::Occupied(entry)) => return Ok(Operand64Idx::new(*entry.get())),
+ Some(Entry::Vacant(entry)) => Some(entry),
+ None => None,
+ };
+ let index = u32::try_from(self.operands64.len())
+ .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?;
+ self.operands64.push(operand);
+ if let Some(entry) = entry {
+ entry.insert(index);
}
+ Ok(Operand64Idx::new(index))
}
-}
-struct ControlFrame {
- kind: BlockKind,
- has_else: bool,
- start_ip: usize,
- branch_jumps: Vec<usize>,
- height: usize,
- base: ValueCounts,
- params: Vec<OperandSize>,
- results: Vec<OperandSize>,
- unreachable: bool,
- entry_unreachable: bool,
- end_reachable: bool,
-}
+ /// Allocates an immutable 128-bit operand, reusing it when deduplication is enabled.
+ pub(crate) fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ let operand = operand.cast();
+ let entry = match self.deduplicate128.as_mut().map(|map| map.entry(operand)) {
+ Some(Entry::Occupied(entry)) => return Ok(Operand128Idx::new(*entry.get())),
+ Some(Entry::Vacant(entry)) => Some(entry),
+ None => None,
+ };
+ let index = u32::try_from(self.operands128.len())
+ .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?;
+ self.operands128.push(operand);
+ if let Some(entry) = entry {
+ entry.insert(index);
+ }
+ Ok(Operand128Idx::new(index))
+ }
-#[derive(Clone)]
-pub(crate) struct Signature {
- pub params: Vec<OperandSize>,
- results: Vec<OperandSize>,
-}
+ /// Allocates a private mutable target operand outside immutable deduplication.
+ pub(crate) fn push_target64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ let index = u32::try_from(self.operands64.len())
+ .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?;
+ self.operands64.push(operand.cast());
+ Ok(Operand64Idx::new(index))
+ }
-pub(crate) struct ModuleMetadata {
- signatures: Vec<Signature>,
- functions: Vec<u32>,
- globals: Vec<OperandSize>,
- memories: Vec<OperandSize>,
- tables: Vec<OperandSize>,
+ /// Allocates a private mutable target operand outside immutable deduplication.
+ pub(crate) fn push_target128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ let index = u32::try_from(self.operands128.len())
+ .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?;
+ self.operands128.push(operand.cast());
+ Ok(Operand128Idx::new(index))
+ }
+
+ pub(crate) fn operand64<T>(&self, index: Operand64Idx<T>) -> Operand64<T> {
+ self.operands64[index.index()].cast()
+ }
+
+ pub(crate) fn operand128<T>(&self, index: Operand128Idx<T>) -> Operand128<T> {
+ self.operands128[index.index()].cast()
+ }
+
+ pub(crate) fn finish(self) -> WasmFunctionData {
+ WasmFunctionData {
+ operands64: self.operands64.into_boxed_slice(),
+ operands128: self.operands128.into_boxed_slice(),
+ branch_table_targets: self.branch_table_targets.into_boxed_slice(),
+ exception_handlers: self.exception_handlers.into_boxed_slice(),
+ }
+ }
}
-#[derive(Default)]
-struct FunctionDataBuilder {
- v128_constants: Vec<[u8; 16]>,
- branch_table_targets: Vec<u32>,
+enum AggregateFields {
+ Other,
+ Struct(Box<[ValueLane]>),
+ Array(ValueLane),
}
pub(crate) struct FunctionBuilder<'a> {
- instructions: Vec<Instruction>,
+ emitter: Emitter,
data: FunctionDataBuilder,
- control_stack: Vec<ControlFrame>,
- operand_stack: Vec<OperandSize>,
+ control_stack: Vec<ControlFrame<'a>>,
+ operand_stack: Vec<ValueLane>,
lane_counts: ValueCounts,
metadata: &'a ModuleMetadata,
- local_types: Vec<OperandSize>,
+ local_types: Vec<ValueLane>,
local_addr_map: Vec<u16>,
+ uses_local_memory: bool,
}
impl<'a> FunctionBuilder<'a> {
+ /// Creates lowering state with a borrowed function signature.
pub(crate) fn new(
metadata: &'a ModuleMetadata,
- signature: Signature,
- local_types: Vec<OperandSize>,
+ signature: &'a Signature,
+ local_types: Vec<ValueLane>,
local_addr_map: Vec<u16>,
body_size: usize,
+ context: FunctionLoweringContext,
+ options: &ParserOptions,
) -> Self {
Self {
local_types,
local_addr_map,
metadata,
- instructions: Vec::with_capacity(body_size.min(1024)),
- data: FunctionDataBuilder::default(),
+ emitter: Emitter::new(body_size, context, options),
+ data: FunctionDataBuilder::new(options.deduplicate_operands()),
control_stack: alloc::vec![ControlFrame {
kind: BlockKind::Function,
has_else: false,
- start_ip: 0,
- branch_jumps: Vec::new(),
+ loop_start: None,
+ end: None,
+ else_entry: None,
height: 0,
base: ValueCounts::default(),
- params: Vec::new(),
- results: signature.results,
+ signature: BlockSignature::Function(signature),
unreachable: false,
entry_unreachable: false,
end_reachable: false,
}],
operand_stack: Vec::new(),
lane_counts: ValueCounts::default(),
+ uses_local_memory: false,
}
}
+
+ fn mark_memory(&mut self, memory: u32) {
+ self.uses_local_memory |= memory >= self.metadata.imported_memories;
+ }
+
+ fn visit_struct_get_impl(
+ &mut self,
+ type_index: u32,
+ field_index: u32,
+ instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction,
+ ) -> Result<()> {
+ let size = self.metadata.struct_field(type_index, field_index)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?;
+ self.emit(&[ValueLane::S32], &[size], instruction(operand))
+ }
+
+ fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ self.data.push64(operand)
+ }
+
+ fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ self.data.push128(operand)
+ }
}
+#[cfg(feature = "validate")]
struct ValidateThenVisit<'a, 'm> {
- validator: Option<&'a mut FuncValidator<ValidatorResources>>,
+ validator: &'a mut FuncValidator<ValidatorResources>,
builder: &'a mut FunctionBuilder<'m>,
- position: usize,
+ position: u64,
}
impl ModuleMetadata {
+ fn address_lane(arch: tinywasm_types::MemoryArch) -> ValueLane {
+ match arch {
+ tinywasm_types::MemoryArch::I32 => ValueLane::S32,
+ tinywasm_types::MemoryArch::I64 => ValueLane::S64,
+ }
+ }
+
pub(crate) fn new(
- types: &[FuncType],
+ types: &TypeSection,
code_type_addrs: &[u32],
imports: &[Import],
globals: &[Global],
memories: &[MemoryType],
tables: &[TableDefinition],
+ tags: &[TagType],
) -> Self {
let mut functions = Vec::with_capacity(imports.len() + code_type_addrs.len());
let mut global_sizes = Vec::with_capacity(imports.len() + globals.len());
let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len());
let mut table_sizes = Vec::with_capacity(imports.len() + tables.len());
+ let mut tag_types = Vec::with_capacity(imports.len() + tags.len());
+ let imported_memories =
+ imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count() as u32;
for import in imports {
match &import.kind {
ImportKind::Function(ty) => functions.push(*ty),
- ImportKind::Global(ty) => global_sizes.push(OperandSize::from(&ty.ty)),
- ImportKind::Memory(ty) => memory_sizes.push(OperandSize::from(ty.arch())),
- ImportKind::Table(ty) => table_sizes.push(OperandSize::from(ty.arch())),
+ ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)),
+ ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())),
+ ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())),
+ ImportKind::Tag(ty) => tag_types.push(ty.type_idx),
}
}
functions.extend_from_slice(code_type_addrs);
- global_sizes.extend(globals.iter().map(|global| OperandSize::from(&global.ty.ty)));
- memory_sizes.extend(memories.iter().map(|ty| OperandSize::from(ty.arch())));
- table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch())));
+ global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty)));
+ memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch())));
+ table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch())));
+ tag_types.extend(tags.iter().map(|tag| tag.type_idx));
let signatures = types
+ .types
+ .iter()
+ .map(|ty| {
+ ty.as_func().map(|ty| Signature {
+ params: ty.params().iter().map(ValueLane::from).collect(),
+ results: ty.results().iter().map(ValueLane::from).collect(),
+ })
+ })
+ .collect();
+ let aggregate_fields = types
+ .types
.iter()
- .map(|ty| Signature {
- params: ty.params().iter().map(OperandSize::from).collect(),
- results: ty.results().iter().map(OperandSize::from).collect(),
+ .map(|ty| {
+ if let Some(ty) = ty.as_struct() {
+ AggregateFields::Struct(ty.fields.iter().map(|field| Self::storage_size(field.storage)).collect())
+ } else if let Some(ty) = ty.as_array() {
+ AggregateFields::Array(Self::storage_size(ty.field.storage))
+ } else {
+ AggregateFields::Other
+ }
})
.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,
+ tags: tag_types,
+ aggregate_fields,
+ imported_memories,
+ }
}
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> {
@@ -200,59 +349,106 @@ impl ModuleMetadata {
self.signature(ty)
}
- fn global_size(&self, idx: u32) -> Result<OperandSize> {
+ fn tag_signature(&self, idx: u32) -> Result<&Signature> {
+ let ty = *self
+ .tags
+ .get(idx as usize)
+ .ok_or_else(|| crate::ParseError::Other(alloc::format!("tag index out of bounds: {idx}")))?;
+ self.signature(ty)
+ }
+
+ fn global_size(&self, idx: u32) -> Result<ValueLane> {
Self::indexed_size(&self.globals, "global", idx)
}
- fn memory_size(&self, idx: u32) -> Result<OperandSize> {
+ fn memory_size(&self, idx: u32) -> Result<ValueLane> {
Self::indexed_size(&self.memories, "memory", idx)
}
- fn table_size(&self, idx: u32) -> Result<OperandSize> {
+ fn table_size(&self, idx: u32) -> Result<ValueLane> {
Self::indexed_size(&self.tables, "table", idx)
}
- fn indexed_size(sizes: &[OperandSize], entity: &str, idx: u32) -> Result<OperandSize> {
+ fn indexed_size(sizes: &[ValueLane], entity: &str, idx: u32) -> Result<ValueLane> {
sizes
.get(idx as usize)
.copied()
.ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}")))
}
+
+ fn storage_size(storage: StorageType) -> ValueLane {
+ match storage {
+ StorageType::I8 | StorageType::I16 => ValueLane::S32,
+ StorageType::Value(ref ty) => ValueLane::from(ty),
+ }
+ }
+
+ fn struct_fields(&self, idx: u32) -> Result<&[ValueLane]> {
+ self.aggregate_fields
+ .get(idx as usize)
+ .and_then(|fields| match fields {
+ AggregateFields::Struct(fields) => Some(fields.as_ref()),
+ AggregateFields::Other | AggregateFields::Array(_) => None,
+ })
+ .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<ValueLane> {
+ 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<ValueLane> {
+ self.aggregate_fields
+ .get(idx as usize)
+ .and_then(|fields| match fields {
+ AggregateFields::Array(field) => Some(*field),
+ AggregateFields::Other | AggregateFields::Struct(_) => None,
+ })
+ .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}")))
+ }
}
+#[cfg(feature = "validate")]
impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> {
type Output = Result<()>;
+ #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded
wasmparser::for_each_visit_operator!(validate_then_visit);
- fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> {
+ fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> {
Some(self)
}
}
+#[cfg(feature = "validate")]
impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> {
+ #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded
wasmparser::for_each_visit_simd_operator!(validate_then_visit_simd);
}
-pub(crate) fn process_operators_and_validate(
- mut validator: Option<FuncValidator<ValidatorResources>>,
+pub(crate) fn process_operators(
body: FunctionBody<'_>,
- local_types: Vec<OperandSize>,
- local_addr_map: Vec<u16>,
+ locals: (Vec<ValueLane>, Vec<u16>),
metadata: &ModuleMetadata,
- ty_idx: u32,
+ context: FunctionLoweringContext,
allocs: OperatorsReaderAllocations,
-) -> Result<(Vec<Instruction>, WasmFunctionData, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
+ options: &ParserOptions,
+) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, OperatorsReaderAllocations)> {
+ let (local_types, local_addr_map) = locals;
let body_size = body.as_bytes().len();
let reader = body.get_binary_reader_for_operators()?;
let mut reader = OperatorsReader::new_with_allocs(reader, allocs);
- let signature = metadata.signature(ty_idx)?.clone();
- let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size);
+ let signature = metadata.signature(context.ty_idx)?;
+ let mut builder =
+ FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options);
while !reader.eof() {
let position = reader.original_position();
let res = reader
- .visit_operator(&mut ValidateThenVisit { validator: validator.as_mut(), builder: &mut builder, position })
+ .visit_operator(&mut builder)
.map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
if let Err(e) = res.flatten() {
@@ -262,19 +458,49 @@ pub(crate) fn process_operators_and_validate(
}
reader.finish()?;
+ let instructions = builder.emitter.finish(&mut builder.data)?;
+ Ok((instructions, builder.data, builder.uses_local_memory, reader.into_allocations()))
+}
- let validator_allocations = validator.map(FuncValidator::into_allocations);
- let data = WasmFunctionData {
- v128_constants: builder.data.v128_constants.into_boxed_slice(),
- branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(),
- };
- Ok((builder.instructions, data, validator_allocations, reader.into_allocations()))
+#[cfg(feature = "validate")]
+pub(crate) fn process_operators_and_validate(
+ mut validator: FuncValidator<ValidatorResources>,
+ body: FunctionBody<'_>,
+ locals: (Vec<ValueLane>, Vec<u16>),
+ metadata: &ModuleMetadata,
+ context: FunctionLoweringContext,
+ allocs: OperatorsReaderAllocations,
+ options: &ParserOptions,
+) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> {
+ let (local_types, local_addr_map) = locals;
+ let body_size = body.as_bytes().len();
+ let reader = body.get_binary_reader_for_operators()?;
+ let mut reader = OperatorsReader::new_with_allocs(reader, allocs);
+ let signature = metadata.signature(context.ty_idx)?;
+ let mut builder =
+ FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options);
+
+ while !reader.eof() {
+ let position = reader.original_position();
+ let res = reader
+ .visit_operator(&mut ValidateThenVisit { validator: &mut validator, builder: &mut builder, position })
+ .map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
+
+ if let Err(e) = res.flatten() {
+ core::hint::cold_path();
+ return Err(e);
+ }
+ }
+
+ reader.finish()?;
+ let instructions = builder.emitter.finish(&mut builder.data)?;
+ Ok((instructions, builder.data, builder.uses_local_memory, validator.into_allocations(), reader.into_allocations()))
}
impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
type Output = Result<()>;
- fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> {
+ fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> {
Some(self)
}
@@ -282,29 +508,41 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
lowering_ops! {
memory [Addr] => [S32] {
- visit_i32_load => I32Load, visit_f32_load => F32Load, visit_i32_load8_s => I32Load8S,
- visit_i32_load8_u => I32Load8U, visit_i32_load16_s => I32Load16S,
- visit_i32_load16_u => I32Load16U,
+ visit_i32_load => I32Load [load(Instruction::LoadLocal32)],
+ visit_f32_load => F32Load [load(Instruction::LoadLocal32)],
+ visit_i32_load8_s => I32Load8S [load(Instruction::LoadLocal8S32)],
+ visit_i32_load8_u => I32Load8U [load(Instruction::LoadLocal8U32)],
+ visit_i32_load16_s => I32Load16S [load(Instruction::LoadLocal16S32)],
+ visit_i32_load16_u => I32Load16U [load(Instruction::LoadLocal16U32)],
}
memory [Addr] => [S64] {
- visit_i64_load => I64Load, visit_f64_load => F64Load, visit_i64_load8_s => I64Load8S,
+ visit_i64_load => I64Load [load(Instruction::LoadLocal64)],
+ visit_f64_load => F64Load [load(Instruction::LoadLocal64)], visit_i64_load8_s => I64Load8S,
visit_i64_load8_u => I64Load8U, visit_i64_load16_s => I64Load16S,
visit_i64_load16_u => I64Load16U, visit_i64_load32_s => I64Load32S,
visit_i64_load32_u => I64Load32U,
}
memory [Addr, S32] => [] {
- visit_f32_store => F32Store, visit_i32_store8 => I32Store8,
- visit_i32_store16 => I32Store16, visit_i32_store => I32Store,
+ visit_f32_store => F32Store [store32()], visit_i32_store8 => I32Store8,
+ visit_i32_store16 => I32Store16, visit_i32_store => I32Store [store32()],
}
memory [Addr, S64] => [] {
- visit_f64_store => F64Store, visit_i64_store8 => I64Store8,
- visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store,
+ visit_f64_store => F64Store [store64()], visit_i64_store8 => I64Store8,
+ visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store [store64()],
}
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,
@@ -313,6 +551,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,
@@ -330,40 +569,83 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
visit_i32_trunc_sat_f64_s => I32TruncSatF64S, visit_i32_trunc_sat_f64_u => I32TruncSatF64U,
}
fixed [S32] => [S64] {
- visit_i64_extend_i32_s => I64ExtendI32S, visit_i64_extend_i32_u => I64ExtendI32U,
+ visit_i64_extend_i32_s => I64ExtendI32S [extend_i32(true)],
+ visit_i64_extend_i32_u => I64ExtendI32U [extend_i32(false)],
visit_i64_trunc_f32_s => I64TruncF32S, visit_i64_trunc_f32_u => I64TruncF32U,
visit_f64_convert_i32_s => F64ConvertI32S, visit_f64_convert_i32_u => F64ConvertI32U,
visit_f64_promote_f32 => F64PromoteF32, visit_i64_trunc_sat_f32_s => I64TruncSatF32S,
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_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_ref_eq => RefEq,
+ visit_i32_eq => I32Eq [compare(CmpOp::Eq)],
+ visit_i32_ne => I32Ne [compare(CmpOp::Ne)],
+ visit_i32_lt_s => I32LtS [compare(CmpOp::LtS)],
+ visit_i32_lt_u => I32LtU [compare(CmpOp::LtU)],
+ visit_i32_gt_s => I32GtS [compare(CmpOp::GtS)],
+ visit_i32_gt_u => I32GtU [compare(CmpOp::GtU)],
+ visit_i32_le_s => I32LeS [compare(CmpOp::LeS)],
+ visit_i32_le_u => I32LeU [compare(CmpOp::LeU)],
+ visit_i32_ge_s => I32GeS [compare(CmpOp::GeS)],
+ visit_i32_ge_u => I32GeU [compare(CmpOp::GeU)],
visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt,
- visit_f32_le => F32Le, visit_f32_ge => F32Ge, visit_i32_add => I32Add, visit_i32_sub => I32Sub,
- visit_i32_mul => I32Mul, visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU,
- visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU, visit_i32_and => I32And,
- visit_i32_or => I32Or, visit_i32_xor => I32Xor, visit_i32_shl => I32Shl, visit_i32_shr_s => I32ShrS,
- visit_i32_shr_u => I32ShrU, visit_i32_rotl => I32Rotl, visit_i32_rotr => I32Rotr,
- visit_f32_add => F32Add, visit_f32_sub => F32Sub, visit_f32_mul => F32Mul, visit_f32_div => F32Div,
- visit_f32_min => F32Min, visit_f32_max => F32Max, visit_f32_copysign => F32Copysign,
+ visit_f32_le => F32Le, visit_f32_ge => F32Ge,
+ visit_i32_add => I32Add [integer32(BinOp::IAdd, true)],
+ visit_i32_sub => I32Sub [integer32(BinOp::ISub, false)],
+ visit_i32_mul => I32Mul [integer32(BinOp::IMul, true)],
+ visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU,
+ visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU,
+ visit_i32_and => I32And [integer32(BinOp::IAnd, true)],
+ visit_i32_or => I32Or [integer32(BinOp::IOr, true)],
+ visit_i32_xor => I32Xor [integer32(BinOp::IXor, true)],
+ visit_i32_shl => I32Shl [integer32(BinOp::IShl, false)],
+ visit_i32_shr_s => I32ShrS [integer32(BinOp::IShrS, false)],
+ visit_i32_shr_u => I32ShrU [integer32(BinOp::IShrU, false)],
+ visit_i32_rotl => I32Rotl [integer32(BinOp::IRotl, false)],
+ visit_i32_rotr => I32Rotr [integer32(BinOp::IRotr, false)],
+ visit_f32_add => F32Add [float32(BinOp::FAdd, true)],
+ visit_f32_sub => F32Sub [float32(BinOp::FSub, false)],
+ visit_f32_mul => F32Mul [float32(BinOp::FMul, true)],
+ visit_f32_div => F32Div [float32(BinOp::FDiv, false)],
+ visit_f32_min => F32Min [float32(BinOp::FMin, true)],
+ visit_f32_max => F32Max [float32(BinOp::FMax, true)],
+ visit_f32_copysign => F32Copysign [float32(BinOp::FCopysign, false)],
}
fixed [S64, S64] => [S32] {
- visit_i64_eq => I64Eq, visit_i64_ne => I64Ne, visit_i64_lt_s => I64LtS, visit_i64_lt_u => I64LtU,
- visit_i64_gt_s => I64GtS, visit_i64_gt_u => I64GtU, visit_i64_le_s => I64LeS,
- visit_i64_le_u => I64LeU, visit_i64_ge_s => I64GeS, visit_i64_ge_u => I64GeU,
+ visit_i64_eq => I64Eq [compare(CmpOp::Eq)],
+ visit_i64_ne => I64Ne [compare(CmpOp::Ne)],
+ visit_i64_lt_s => I64LtS [compare(CmpOp::LtS)],
+ visit_i64_lt_u => I64LtU [compare(CmpOp::LtU)],
+ visit_i64_gt_s => I64GtS [compare(CmpOp::GtS)],
+ visit_i64_gt_u => I64GtU [compare(CmpOp::GtU)],
+ visit_i64_le_s => I64LeS [compare(CmpOp::LeS)],
+ visit_i64_le_u => I64LeU [compare(CmpOp::LeU)],
+ visit_i64_ge_s => I64GeS [compare(CmpOp::GeS)],
+ visit_i64_ge_u => I64GeU [compare(CmpOp::GeU)],
visit_f64_eq => F64Eq, visit_f64_ne => F64Ne, visit_f64_lt => F64Lt, visit_f64_gt => F64Gt,
visit_f64_le => F64Le, visit_f64_ge => F64Ge,
}
fixed [S64, S64] => [S64] {
- visit_i64_add => I64Add, visit_i64_sub => I64Sub, visit_i64_mul => I64Mul,
+ visit_i64_add => I64Add [integer64(BinOp::IAdd, true)],
+ visit_i64_sub => I64Sub [integer64(BinOp::ISub, false)],
+ visit_i64_mul => I64Mul [integer64(BinOp::IMul, true)],
visit_i64_div_s => I64DivS, visit_i64_div_u => I64DivU, visit_i64_rem_s => I64RemS,
- visit_i64_rem_u => I64RemU, visit_i64_and => I64And, visit_i64_or => I64Or, visit_i64_xor => I64Xor,
- visit_i64_shl => I64Shl, visit_i64_shr_s => I64ShrS, visit_i64_shr_u => I64ShrU,
- visit_i64_rotl => I64Rotl, visit_i64_rotr => I64Rotr, visit_f64_add => F64Add,
- visit_f64_sub => F64Sub, visit_f64_mul => F64Mul, visit_f64_div => F64Div,
- visit_f64_min => F64Min, visit_f64_max => F64Max, visit_f64_copysign => F64Copysign,
+ visit_i64_rem_u => I64RemU,
+ visit_i64_and => I64And [integer64(BinOp::IAnd, true)],
+ visit_i64_or => I64Or [integer64(BinOp::IOr, true)],
+ visit_i64_xor => I64Xor [integer64(BinOp::IXor, true)],
+ visit_i64_shl => I64Shl [integer64(BinOp::IShl, false)],
+ visit_i64_shr_s => I64ShrS [integer64(BinOp::IShrS, false)],
+ visit_i64_shr_u => I64ShrU [integer64(BinOp::IShrU, false)],
+ visit_i64_rotl => I64Rotl [integer64(BinOp::IRotl, false)],
+ visit_i64_rotr => I64Rotr [integer64(BinOp::IRotr, false)],
+ visit_f64_add => F64Add [float64(BinOp::FAdd, true)],
+ visit_f64_sub => F64Sub [float64(BinOp::FSub, false)],
+ visit_f64_mul => F64Mul [float64(BinOp::FMul, true)],
+ visit_f64_div => F64Div [float64(BinOp::FDiv, false)],
+ visit_f64_min => F64Min [float64(BinOp::FMin, true)],
+ visit_f64_max => F64Max [float64(BinOp::FMax, true)],
+ visit_f64_copysign => F64Copysign [float64(BinOp::FCopysign, false)],
}
fixed [S64, S64, S64, S64] => [S64, S64] { visit_i64_add128 => I64Add128, visit_i64_sub128 => I64Sub128 }
fixed [S64, S64] => [S64, S64] { visit_i64_mul_wide_s => I64MulWideS, visit_i64_mul_wide_u => I64MulWideU }
@@ -371,71 +653,117 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
effect [S32] => [S32] { visit_f32_reinterpret_i32, visit_i32_reinterpret_f32 }
effect [S64] => [S64] { visit_f64_reinterpret_i64, visit_i64_reinterpret_f64 }
terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return }
- global [] => [Addr] { visit_global_get(global_index: u32) => GlobalGet }
memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize }
memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow }
- memory_index [Addr, S32, Addr] => [] {
- visit_memory_init(data_index: u32, memory: u32) => MemoryInit,
- visit_memory_fill(memory: u32) => MemoryFill,
- }
+ memory_index [Addr, S32, Addr] => [] { visit_memory_fill(memory: u32) => MemoryFill [memory_fill()] }
table [Addr] => [S32] { visit_table_get(table: u32) => TableGet }
table [Addr, S32] => [] { visit_table_set(table: u32) => TableSet }
table [] => [Addr] { visit_table_size(table: u32) => TableSize }
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,
+ }
+ 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_call(&mut self, function_index: u32) -> Self::Output {
- let signature = self.metadata.function_signature(function_index)?.clone();
- self.emit(&signature.params, &signature.results, Instruction::Call(function_index))
+ fn visit_struct_new(&mut self, type_index: u32) -> Result<()> {
+ let field_count = self.metadata.struct_fields(type_index)?.len();
+ for field_index in (0..field_count).rev() {
+ let size = self.metadata.struct_field(type_index, field_index as u32)?;
+ self.pop_expect(size)?;
+ }
+ self.push_sizes(&[ValueLane::S32])?;
+ self.emitter.emit(Instruction::StructNew(type_index))?;
+ Ok(())
+ }
+
+ fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Result<()> {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGet)
}
- fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output {
- let signature = self.metadata.signature(type_index)?.clone();
- let mut inputs = signature.params;
- inputs.push(self.metadata.table_size(table_index)?);
- self.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index))
+ fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Result<()> {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetS)
}
- fn visit_call_ref(&mut self, type_index: u32) -> Self::Output {
- let signature = self.metadata.signature(type_index)?.clone();
- let mut inputs = signature.params;
- inputs.push(OperandSize::S32);
- self.emit(&inputs, &signature.results, Instruction::CallRef(type_index))
+ fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Result<()> {
+ self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetU)
}
- fn visit_return_call(&mut self, function_index: u32) -> Self::Output {
- let signature = self.metadata.function_signature(function_index)?.clone();
+ fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Result<()> {
+ let size = self.metadata.struct_field(type_index, field_index)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?;
+ self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand))
+ }
+
+ fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Result<()> {
+ let size = self.metadata.array_field(type_index)?;
+ for _ in 0..array_size {
+ self.pop_expect(size)?;
+ }
+ self.push_sizes(&[ValueLane::S32])?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, array_size))?;
+ self.emitter.emit(Instruction::ArrayNewFixed(operand))?;
+ Ok(())
+ }
+
+ fn visit_call(&mut self, function_index: u32) -> Result<()> {
+ let signature = self.metadata.function_signature(function_index)?;
+ self.emit_boundary(&signature.params, &signature.results, Instruction::Call(function_index))
+ }
+
+ fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> {
+ let table_size = self.metadata.table_size(table_index)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?;
+ let signature = self.metadata.signature(type_index)?;
+ self.pop_expect(table_size)?;
+ self.emit_boundary(&signature.params, &signature.results, Instruction::CallIndirect(operand))
+ }
+
+ fn visit_call_ref(&mut self, type_index: u32) -> Result<()> {
+ let signature = self.metadata.signature(type_index)?;
+ self.pop_expect(ValueLane::S32)?;
+ self.emit_boundary(&signature.params, &signature.results, Instruction::CallRef(type_index))
+ }
+
+ fn visit_return_call(&mut self, function_index: u32) -> Result<()> {
+ let signature = self.metadata.function_signature(function_index)?;
self.apply_effect(&signature.params, &[])?;
self.mark_unreachable();
- self.instructions.push(Instruction::ReturnCall(function_index));
+ self.emitter.emit_boundary(Instruction::ReturnCall(function_index))?;
Ok(())
}
- fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output {
- let signature = self.metadata.signature(type_index)?.clone();
- let mut inputs = signature.params;
- inputs.push(self.metadata.table_size(table_index)?);
- self.apply_effect(&inputs, &[])?;
+ fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> {
+ let table_size = self.metadata.table_size(table_index)?;
+ let signature = self.metadata.signature(type_index)?;
+ self.pop_expect(table_size)?;
+ self.apply_effect(&signature.params, &[])?;
self.mark_unreachable();
- self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index));
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?;
+ self.emitter.emit_boundary(Instruction::ReturnCallIndirect(operand))?;
Ok(())
}
- fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output {
- let signature = self.metadata.signature(type_index)?.clone();
- let mut inputs = signature.params;
- inputs.push(OperandSize::S32);
- self.apply_effect(&inputs, &[])?;
+ fn visit_return_call_ref(&mut self, type_index: u32) -> Result<()> {
+ let signature = self.metadata.signature(type_index)?;
+ self.pop_expect(ValueLane::S32)?;
+ self.apply_effect(&signature.params, &[])?;
self.mark_unreachable();
- self.instructions.push(Instruction::ReturnCallRef(type_index));
+ self.emitter.emit_boundary(Instruction::ReturnCallRef(type_index))?;
Ok(())
}
- fn visit_global_set(&mut self, global_index: u32) -> Self::Output {
+ fn visit_global_set(&mut self, global_index: u32) -> Result<()> {
let size = self.metadata.global_size(global_index)?;
- let instruction = size.choose(
+ let instruction = size.select(
Instruction::GlobalSet32(global_index),
Instruction::GlobalSet64(global_index),
Instruction::GlobalSet128(global_index),
@@ -443,291 +771,411 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
self.emit(&[size], &[], instruction)
}
- fn visit_drop(&mut self) -> Self::Output {
- let size = self.operand_stack.last().copied().unwrap_or(OperandSize::S32);
- let instruction = size.choose(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128);
- self.emit(&[size], &[], instruction)
+ fn visit_global_get(&mut self, global_index: u32) -> Result<()> {
+ let size = self.metadata.global_size(global_index)?;
+ match size {
+ ValueLane::S32 => emit_selected!(self, &[], &[size], GlobalGet32(global_index)[global_get32()]),
+ ValueLane::S64 => emit_selected!(self, &[], &[size], GlobalGet64(global_index)[global_get64()]),
+ ValueLane::S128 => emit_selected!(self, &[], &[size], GlobalGet128(global_index)[global_get128()]),
+ }
+ }
+
+ fn visit_drop(&mut self) -> Result<()> {
+ let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32);
+ match size {
+ ValueLane::S32 => emit_selected!(self, &[size], &[], Drop32[drop32()]),
+ ValueLane::S64 => emit_selected!(self, &[size], &[], Drop64[drop64()]),
+ ValueLane::S128 => emit_selected!(self, &[size], &[], Drop128[drop128()]),
+ }
}
- fn visit_select(&mut self) -> Self::Output {
- let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(OperandSize::S32);
- let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128);
- self.emit(&[size, size, OperandSize::S32], &[size], instruction)
+ fn visit_select(&mut self) -> Result<()> {
+ let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32);
+ let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128);
+ self.emit(&[size, size, ValueLane::S32], &[size], instruction)
}
- fn visit_local_get(&mut self, idx: u32) -> Self::Output {
+ fn visit_local_get(&mut self, idx: u32) -> Result<()> {
let (size, local_idx) = self.local(idx)?;
- let instruction = size.choose(
- Instruction::LocalGet32(local_idx),
- Instruction::LocalGet64(local_idx),
- Instruction::LocalGet128(local_idx),
- );
- self.emit(&[], &[size], instruction)
+ match size {
+ ValueLane::S32 => emit_selected!(self, &[], &[size], LocalGet32(local_idx)[local_get32()]),
+ ValueLane::S64 => emit_selected!(self, &[], &[size], LocalGet64(local_idx)[local_get64()]),
+ ValueLane::S128 => emit_selected!(self, &[], &[size], LocalGet128(local_idx)[local_get128()]),
+ }
}
- fn visit_local_set(&mut self, idx: u32) -> Self::Output {
+ fn visit_local_set(&mut self, idx: u32) -> Result<()> {
let (size, local_idx) = self.local(idx)?;
- let instruction = size.choose(
- Instruction::LocalSet32(local_idx),
- Instruction::LocalSet64(local_idx),
- Instruction::LocalSet128(local_idx),
- );
- self.emit(&[size], &[], instruction)
+ match size {
+ ValueLane::S32 => emit_selected!(self, &[size], &[], LocalSet32(local_idx)[local_set32()]),
+ ValueLane::S64 => emit_selected!(self, &[size], &[], LocalSet64(local_idx)[local_set64()]),
+ ValueLane::S128 => emit_selected!(self, &[size], &[], LocalSet128(local_idx)[local_set128()]),
+ }
}
- fn visit_local_tee(&mut self, idx: u32) -> Self::Output {
+ fn visit_local_tee(&mut self, idx: u32) -> Result<()> {
let (size, local_idx) = self.local(idx)?;
- self.apply_effect(&[size], &[size])?;
- let src = match (size, self.instructions.last()) {
- (OperandSize::S32, Some(Instruction::LocalGet32(src))) => Some(*src),
- (OperandSize::S64, Some(Instruction::LocalGet64(src))) => Some(*src),
- (OperandSize::S128, Some(Instruction::LocalGet128(src))) => Some(*src),
- _ => None,
- };
- if let Some(src) = src {
- self.instructions.pop();
- let instructions = match size {
- OperandSize::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)],
- OperandSize::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)],
- OperandSize::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)],
- };
- self.instructions.extend(instructions);
- } else {
- self.instructions.push(size.choose(
- Instruction::LocalTee32(local_idx),
- Instruction::LocalTee64(local_idx),
- Instruction::LocalTee128(local_idx),
- ));
+ // Bound labels seal the tail, so these rules cannot fuse across a loop
+ // entry or another branch destination.
+ match size {
+ ValueLane::S32 => emit_selected!(self, &[size], &[size], LocalTee32(local_idx)[local_tee32()]),
+ ValueLane::S64 => emit_selected!(self, &[size], &[size], LocalTee64(local_idx)[local_tee64()]),
+ ValueLane::S128 => emit_selected!(self, &[size], &[size], LocalTee128(local_idx)[local_tee128()]),
}
- Ok(())
}
- fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Self::Output {
+ fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Result<()> {
self.push_control(BlockKind::Block, blockty, None)
}
- fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Self::Output {
+ fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Result<()> {
self.push_control(BlockKind::Loop, ty, None)
}
- fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- self.instructions.push(Instruction::JumpIfZero32(0));
- self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1))
+ fn visit_if(&mut self, ty: wasmparser::BlockType) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let else_entry = self.emitter.new_label();
+ self.emitter.branch_if(&mut self.data, true, else_entry)?;
+ self.push_control(BlockKind::If, ty, Some(else_entry))
+ }
+
+ fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Result<()> {
+ let signature = self.block_signature(try_table.ty)?;
+ for &size in signature.params().iter().rev() {
+ self.pop_expect(size)?;
+ }
+ let height = self.operand_stack.len();
+ let base = self.lane_counts;
+ let entry_unreachable = self.is_unreachable();
+
+ let body_start = self.emitter.new_label();
+ let body_end = self.emitter.new_label();
+ self.emitter.branch(Instruction::Jump(0), body_start)?;
+ let mut catches = Vec::with_capacity(try_table.catches.len());
+ for catch in try_table.catches {
+ let (tag, depth, with_ref) = match catch {
+ wasmparser::Catch::One { tag, label } => (Some(tag), label, false),
+ wasmparser::Catch::OneRef { tag, label } => (Some(tag), label, true),
+ wasmparser::Catch::All { label } => (None, label, false),
+ wasmparser::Catch::AllRef { label } => (None, label, true),
+ };
+ if let Some(tag) = tag {
+ self.metadata.tag_signature(tag)?;
+ }
+ let target_idx = self.get_ctx_idx(depth)?;
+ let target_base = self.control_stack[target_idx].base;
+ let landing_label = self.emitter.new_label();
+ self.emitter.bind(landing_label)?;
+ self.emit_branch_jump_or_return(depth)?;
+ let landing_pad = 0;
+ catches.push((
+ match tag {
+ Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref },
+ None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref },
+ },
+ landing_label,
+ ));
+ }
+
+ self.emitter.bind(body_start)?;
+ self.emitter.exception_handler(&mut self.data, body_start, body_end, catches);
+ self.push_sizes(signature.params())?;
+ self.control_stack.push(ControlFrame {
+ kind: BlockKind::TryTable,
+ has_else: false,
+ loop_start: None,
+ end: Some(body_end),
+ else_entry: None,
+ height,
+ base,
+ signature,
+ unreachable: entry_unreachable,
+ entry_unreachable,
+ end_reachable: false,
+ });
+ Ok(())
+ }
+
+ fn visit_throw(&mut self, tag_index: u32) -> Result<()> {
+ let signature = self.metadata.tag_signature(tag_index)?;
+ self.apply_effect(&signature.params, &[])?;
+ self.emitter.emit_boundary(Instruction::Throw(tag_index))?;
+ self.mark_unreachable();
+ Ok(())
+ }
+
+ fn visit_throw_ref(&mut self) -> Result<()> {
+ self.apply_effect(&[ValueLane::S32], &[])?;
+ self.emitter.emit_boundary(Instruction::ThrowRef)?;
+ self.mark_unreachable();
+ Ok(())
}
- fn visit_else(&mut self) -> Self::Output {
- let (cond_jump_ip, height, base, params, entry_unreachable) = {
+ fn visit_else(&mut self) -> Result<()> {
+ let (else_entry, end, height, base, signature, entry_unreachable) = {
let ctx = self
.control_stack
.last_mut()
- .filter(|ctx| matches!(ctx.kind, BlockKind::If))
+ .filter(|ctx| matches!(ctx.kind, BlockKind::If) && !ctx.has_else)
.ok_or_else(|| crate::ParseError::Other("else without matching if".into()))?;
ctx.end_reachable |= !ctx.unreachable;
ctx.has_else = true;
- (ctx.branch_jumps[0], ctx.height, ctx.base, ctx.params.clone(), ctx.entry_unreachable)
+ let end = *ctx.end.get_or_insert_with(|| self.emitter.new_label());
+ (ctx.else_entry.unwrap(), end, ctx.height, ctx.base, ctx.signature, ctx.entry_unreachable)
};
- let jump_ip = self.instructions.len();
- self.instructions.push(Instruction::Jump(0));
- self.control_stack.last_mut().unwrap().branch_jumps.push(jump_ip);
- self.patch_jump(cond_jump_ip, self.instructions.len());
+ self.emitter.branch(Instruction::Jump(0), end)?;
+ self.emitter.bind(else_entry)?;
self.reset_stack(height, base);
- self.push_sizes(&params)?;
+ self.push_sizes(signature.params())?;
self.control_stack.last_mut().unwrap().unreachable = entry_unreachable;
Ok(())
}
- fn visit_end(&mut self) -> Self::Output {
+ fn visit_end(&mut self) -> Result<()> {
let ctx =
self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?;
+ if let Some(end) = ctx.end {
+ self.emitter.bind(end)?;
+ }
+ if !ctx.has_else
+ && let Some(else_entry) = ctx.else_entry
+ {
+ self.emitter.bind(else_entry)?;
+ }
if matches!(ctx.kind, BlockKind::Function) {
- self.instructions.push(Instruction::Return);
+ self.emitter.emit_boundary(Instruction::Return)?;
} else {
let reachable = !ctx.entry_unreachable
&& (!ctx.unreachable || ctx.end_reachable || matches!(ctx.kind, BlockKind::If) && !ctx.has_else);
self.reset_stack(ctx.height, ctx.base);
- self.push_sizes(&ctx.results)?;
+ self.push_sizes(ctx.signature.results())?;
if let Some(parent) = self.control_stack.last_mut() {
parent.unreachable = !reachable;
}
- self.patch_end_jumps(ctx, self.instructions.len());
}
Ok(())
}
- fn visit_br(&mut self, depth: u32) -> Self::Output {
+ fn visit_br(&mut self, depth: u32) -> Result<()> {
self.emit_dropkeep_to_label(depth)?;
self.emit_branch_jump_or_return(depth)?;
self.mark_unreachable();
Ok(())
}
- fn visit_br_if(&mut self, depth: u32) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- let cond_jump_ip = self.instructions.len();
- self.instructions.push(Instruction::JumpIfZero32(0));
-
- let branch_side_start = self.instructions.len();
- self.emit_dropkeep_to_label(depth)?;
-
- if self.instructions.len() == branch_side_start
- && let Ok(ctx_idx) = self.get_ctx_idx(depth)
- && !matches!(self.control_stack[ctx_idx].kind, BlockKind::Function)
- {
- self.instructions[cond_jump_ip] = Instruction::JumpIfNonZero32(0);
- self.control_stack[ctx_idx].branch_jumps.push(cond_jump_ip);
+ fn visit_br_if(&mut self, depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let ctx_idx = self.get_ctx_idx(depth)?;
+ let frame = &self.control_stack[ctx_idx];
+ let types =
+ if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() };
+ let keep = Self::value_counts(types);
+ let needs_shaping = !self.is_unreachable() && self.needs_dropkeep(frame.base, keep);
+ if !needs_shaping && !matches!(frame.kind, BlockKind::Function) {
+ let target = if let Some(start) = frame.loop_start {
+ start
+ } else {
+ *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label())
+ };
+ self.emitter.branch_if(&mut self.data, false, target)?;
self.control_stack[ctx_idx].end_reachable = true;
return Ok(());
}
-
+ let fallthrough = self.emitter.new_label();
+ self.emitter.branch_if(&mut self.data, true, fallthrough)?;
+ self.emit_dropkeep_to_label(depth)?;
self.emit_branch_jump_or_return(depth)?;
- self.patch_jump(cond_jump_ip, self.instructions.len());
+ self.emitter.bind(fallthrough)?;
Ok(())
}
- fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output {
+ fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Result<()> {
let ts = targets.targets().collect::<Result<Vec<_>, wasmparser::Error>>()?;
- self.pop_expect(OperandSize::S32)?;
+ self.pop_expect(ValueLane::S32)?;
let default_depth = targets.default();
- let len = ts.len() as u32;
let target_depths: Vec<u32> = ts;
-
- let header_ip = self.instructions.len();
- let branch_table_start = self.data.branch_table_targets.len() as u32;
- self.instructions.push(Instruction::BranchTable(0, branch_table_start, len));
-
- struct PadInfo {
- depth: u32,
- pad_start: usize,
- jump_or_ret_ip: usize,
- is_return: bool,
- }
- let mut pads: Vec<PadInfo> = Vec::new();
-
+ let mut pads: Vec<(u32, LabelId)> = Vec::new();
+ let label_count = target_depths
+ .len()
+ .checked_add(1)
+ .ok_or_else(|| crate::ParseError::Other("branch table is too large".into()))?;
+ let mut labels = Vec::with_capacity(label_count);
for &depth in target_depths.iter().chain(core::iter::once(&default_depth)) {
- if pads.iter().any(|pad| pad.depth == depth) {
- continue;
+ if self.emitter.optimizations_enabled() && !self.is_unreachable() {
+ let ctx_idx = self.get_ctx_idx(depth)?;
+ let frame = &self.control_stack[ctx_idx];
+ let is_loop = matches!(frame.kind, BlockKind::Loop);
+ let types = if is_loop { frame.signature.params() } else { frame.signature.results() };
+ if !matches!(frame.kind, BlockKind::Function)
+ && !self.needs_dropkeep(frame.base, Self::value_counts(types))
+ {
+ let target = if let Some(start) = frame.loop_start {
+ start
+ } else {
+ *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label())
+ };
+ labels.push(target);
+ if !is_loop {
+ self.control_stack[ctx_idx].end_reachable = true;
+ }
+ continue;
+ }
}
-
- let pad_start = self.instructions.len();
- let (jump_or_ret_ip, is_return) = if self.is_unreachable() {
- self.instructions.push(Instruction::Return);
- (pad_start, true)
+ let label = if let Some((_, label)) = pads.iter().find(|(pad_depth, _)| *pad_depth == depth) {
+ *label
} else {
- let frame = &self.control_stack[self.get_ctx_idx(depth)?];
- let base = frame.base;
- let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results };
- self.emit_dropkeep(base, Self::value_counts(label_types));
- let jump_ip = self.instructions.len();
- self.instructions.push(Instruction::Jump(0));
- (jump_ip, false)
+ let label = self.emitter.new_label();
+ pads.push((depth, label));
+ label
};
- pads.push(PadInfo { depth, pad_start, jump_or_ret_ip, is_return });
+ labels.push(label);
}
-
- for &depth in &target_depths {
- let pad = pads
- .iter()
- .find(|pad| pad.depth == depth)
- .ok_or_else(|| crate::ParseError::Other("missing branch table target".into()))?;
- self.data.branch_table_targets.push(pad.pad_start as u32);
- }
-
- let default_pad = pads
- .iter()
- .find(|pad| pad.depth == default_depth)
- .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?;
- if let Instruction::BranchTable(default_ip, _, _) = &mut self.instructions[header_ip] {
- *default_ip = default_pad.pad_start as u32;
- }
-
- for pad in &pads {
- if pad.is_return {
- continue;
- }
- let ctx_idx = self.get_ctx_idx(pad.depth)?;
- if matches!(self.control_stack[ctx_idx].kind, BlockKind::Function) {
- self.instructions[pad.jump_or_ret_ip] = Instruction::Return;
- } else if matches!(self.control_stack[ctx_idx].kind, BlockKind::Loop) {
- self.patch_jump(pad.jump_or_ret_ip, self.control_stack[ctx_idx].start_ip);
+ let default = labels.pop().unwrap();
+ self.emitter.branch_table(&mut self.data, &labels, default)?;
+ for (depth, label) in pads {
+ self.emitter.bind(label)?;
+ if self.is_unreachable() {
+ self.emitter.emit_boundary(Instruction::Return)?;
} else {
- self.control_stack[ctx_idx].branch_jumps.push(pad.jump_or_ret_ip);
- self.control_stack[ctx_idx].end_reachable = true;
+ self.emit_dropkeep_to_label(depth)?;
+ self.emit_branch_jump_or_return(depth)?;
}
}
self.mark_unreachable();
Ok(())
}
- fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output {
- self.emit(&[], &[OperandSize::S32], Instruction::Const32(val.bits() as i32))
+ fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Result<()> {
+ self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32))
}
- fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output {
- self.emit(&[], &[OperandSize::S64], Instruction::Const64(val.bits() as i64))
+ #[cfg(not(rust_analyzer))] // rust-analyzer thinks the return type is wrong
+ fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Result<()> {
+ self.visit_i64_const(val.bits() as i64)
}
- fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output {
+ fn visit_i64_const(&mut self, value: i64) -> Result<()> {
+ let instruction = if self.emitter.optimizations_enabled()
+ && let Ok(value) = i32::try_from(value)
+ {
+ Instruction::Const64Imm(value)
+ } else {
+ Instruction::Const64(self.push64(Operand64::<i64>::new(value))?)
+ };
+ self.emit(&[], &[ValueLane::S64], instruction)
+ }
+
+ fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<()> {
let dst = self.metadata.table_size(dst_table)?;
let src = self.metadata.table_size(src_table)?;
- let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 };
- self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table })
+ let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 };
+ let operand = self.push64(Operand64::<(u32, u32)>::new(dst_table, src_table))?;
+ self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand))
}
- fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output {
+ fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<()> {
let dst = self.metadata.memory_size(dst_mem)?;
let src = self.metadata.memory_size(src_mem)?;
- let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 };
- self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem })
+ self.mark_memory(dst_mem);
+ self.mark_memory(src_mem);
+ let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 };
+ let operand = self.push64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?;
+ self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand))
+ }
+
+ fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Result<()> {
+ let dst = self.metadata.memory_size(memory)?;
+ self.mark_memory(memory);
+ let operand = self.push64(Operand64::<(u32, u32)>::new(data_index, memory))?;
+ self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand))
+ }
+
+ fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Result<()> {
+ let address = self.metadata.table_size(table)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(elem_index, table))?;
+ self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand))
}
- // 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_array_new_data(&mut self, type_index: u32, data_index: u32) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?;
+ self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand))
}
- fn visit_ref_as_non_null(&mut self) -> Self::Output {
- self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull)
+ fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?;
+ self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand))
}
- fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- let fallthrough_jump = self.instructions.len();
- self.instructions.push(Instruction::JumpIfRefNonNull(0));
+ fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?;
+ self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand))
+ }
+
+ fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?;
+ self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand))
+ }
+
+ fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?;
+ self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand))
+ }
+
+ fn visit_br_on_cast(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Result<()> {
+ self.emit_cast_branch(relative_depth, to_ref_type, false)
+ }
+
+ fn visit_br_on_cast_fail(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Result<()> {
+ self.emit_cast_branch(relative_depth, to_ref_type, true)
+ }
+
+ fn visit_br_on_null(&mut self, relative_depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let fallthrough = self.emitter.new_label();
+ self.emitter.branch(Instruction::JumpIfRefNonNull(0), fallthrough)?;
self.emit_dropkeep_to_label(relative_depth)?;
self.emit_branch_jump_or_return(relative_depth)?;
- self.patch_jump(fallthrough_jump, self.instructions.len());
- self.push_sizes(&[OperandSize::S32])
+ self.emitter.bind(fallthrough)?;
+ self.push_sizes(&[ValueLane::S32])
}
- fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- let fallthrough_jump = self.instructions.len();
- self.instructions.push(Instruction::JumpIfRefNull(0));
- self.push_sizes(&[OperandSize::S32])?;
+ fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let fallthrough = self.emitter.new_label();
+ self.emitter.branch(Instruction::JumpIfRefNull(0), fallthrough)?;
+ self.push_sizes(&[ValueLane::S32])?;
self.emit_dropkeep_to_label(relative_depth)?;
- self.pop_expect(OperandSize::S32)?;
+ self.pop_expect(ValueLane::S32)?;
self.emit_branch_jump_or_return(relative_depth)?;
- self.patch_jump(fallthrough_jump, self.instructions.len());
+ self.emitter.bind(fallthrough)?;
Ok(())
}
- fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Self::Output {
- let sizes: Vec<_> = tys.into_iter().map(OperandSize::from).collect();
+ fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Result<()> {
+ let sizes: Vec<_> = tys.into_iter().map(value_lane).collect();
let counts = Self::value_counts(&sizes);
self.emit(
- &[sizes.as_slice(), sizes.as_slice(), &[OperandSize::S32]].concat(),
+ &[sizes.as_slice(), sizes.as_slice(), &[ValueLane::S32]].concat(),
&sizes,
Instruction::SelectMulti(counts),
)
}
- fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output {
- let size = OperandSize::from(ty);
- let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128);
- self.emit(&[size, size, OperandSize::S32], &[size], instruction)
+ fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Result<()> {
+ let size = value_lane(ty);
+ let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128);
+ self.emit(&[size, size, ValueLane::S32], &[size], instruction)
}
}
@@ -739,7 +1187,7 @@ macro_rules! impl_visit_simd_operator {
(@@simd $($rest:tt)* ) => {};
(@@relaxed_simd $($rest:tt)* ) => {};
(@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => {
- fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
+ fn $visit(&mut self $($(,$arg: $argty)*)?) -> Result<()> {
Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string()))
}
};
@@ -758,7 +1206,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
visit_v128_load64_splat => V128Load64Splat, visit_v128_load32_zero => V128Load32Zero,
visit_v128_load64_zero => V128Load64Zero,
}
- memory [Addr, S128] => [] { visit_v128_store => V128Store }
+ memory [Addr, S128] => [] { visit_v128_store => V128Store [store128()] }
memory [Addr, S128] => [S128] {
visit_v128_load8_lane(lane: u8) => V128Load8Lane,
visit_v128_load16_lane(lane: u8) => V128Load16Lane,
@@ -847,8 +1295,11 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
visit_i32x4_relaxed_trunc_f64x2_u_zero => I32x4RelaxedTruncF64x2UZero,
}
fixed [S128, S128] => [S128] {
- visit_v128_and => V128And, visit_v128_andnot => V128AndNot, visit_v128_or => V128Or,
- visit_v128_xor => V128Xor, visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq,
+ visit_v128_and => V128And [vector(BinOp128::And, true)],
+ visit_v128_andnot => V128AndNot [vector(BinOp128::AndNot, false)],
+ visit_v128_or => V128Or [vector(BinOp128::Or, true)],
+ visit_v128_xor => V128Xor [vector(BinOp128::Xor, true)],
+ visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq,
visit_i8x16_ne => I8x16Ne, visit_i8x16_lt_s => I8x16LtS, visit_i8x16_lt_u => I8x16LtU,
visit_i8x16_gt_s => I8x16GtS, visit_i8x16_gt_u => I8x16GtU, visit_i8x16_le_s => I8x16LeS,
visit_i8x16_le_u => I8x16LeU, visit_i8x16_ge_s => I8x16GeS, visit_i8x16_ge_u => I8x16GeU,
@@ -879,8 +1330,10 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
visit_i16x8_sub_sat_u => I16x8SubSatU, visit_i16x8_avgr_u => I16x8AvgrU,
visit_i16x8_mul => I16x8Mul, visit_i32x4_add => I32x4Add, visit_i32x4_sub => I32x4Sub,
visit_i32x4_min_s => I32x4MinS, visit_i32x4_min_u => I32x4MinU, visit_i32x4_max_s => I32x4MaxS,
- visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul, visit_i64x2_add => I64x2Add,
- visit_i64x2_sub => I64x2Sub, visit_i64x2_mul => I64x2Mul,
+ visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul,
+ visit_i64x2_add => I64x2Add [vector(BinOp128::I64x2Add, true)],
+ visit_i64x2_sub => I64x2Sub,
+ visit_i64x2_mul => I64x2Mul [vector(BinOp128::I64x2Mul, true)],
visit_i16x8_extmul_low_i8x16_s => I16x8ExtMulLowI8x16S,
visit_i16x8_extmul_low_i8x16_u => I16x8ExtMulLowI8x16U,
visit_i16x8_extmul_high_i8x16_s => I16x8ExtMulHighI8x16S,
@@ -917,24 +1370,45 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
}
}
- fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output {
- self.emit(
- &[OperandSize::S128, OperandSize::S128],
- &[OperandSize::S128],
- Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32),
- )?;
- self.data.v128_constants.push(lanes);
- Ok(())
+ fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Result<()> {
+ let index = self.push128(Operand128::<[u8; 16]>::new(lanes))?;
+ self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index))
}
- fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output {
- self.emit(&[], &[OperandSize::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?;
- self.data.v128_constants.push(*value.bytes());
- Ok(())
+ fn visit_v128_const(&mut self, value: wasmparser::V128) -> Result<()> {
+ let instruction = if self.emitter.optimizations_enabled()
+ && let Ok(value) = u32::try_from(u128::from_le_bytes(*value.bytes()))
+ {
+ Instruction::Const128Imm(value)
+ } else {
+ Instruction::Const128(self.push128(Operand128::<[u8; 16]>::new(*value.bytes()))?)
+ };
+ self.emit(&[], &[ValueLane::S128], instruction)
}
}
-impl FunctionBuilder<'_> {
+impl<'a> FunctionBuilder<'a> {
+ fn emit_cast_branch(
+ &mut self,
+ relative_depth: u32,
+ target: wasmparser::RefType,
+ branch_on_fail: bool,
+ ) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let target = convert_heap_type(target.heap_type(), target.is_nullable())?;
+ let fallthrough = self.emitter.new_label();
+ let operand = self.data.push_target64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?;
+ self.emitter.branch(
+ if branch_on_fail { Instruction::BrOnCastFail(operand) } else { Instruction::BrOnCast(operand) },
+ fallthrough,
+ )?;
+ self.push_sizes(&[ValueLane::S32])?;
+ self.emit_dropkeep_to_label(relative_depth)?;
+ self.emit_branch_jump_or_return(relative_depth)?;
+ self.emitter.bind(fallthrough)?;
+ Ok(())
+ }
+
fn is_unreachable(&self) -> bool {
self.control_stack.last().is_none_or(|frame| frame.unreachable)
}
@@ -946,7 +1420,7 @@ impl FunctionBuilder<'_> {
.ok_or_else(|| crate::ParseError::Other(alloc::format!("branch depth out of bounds: {depth}")))
}
- fn local(&self, idx: u32) -> Result<(OperandSize, u16)> {
+ fn local(&self, idx: u32) -> Result<(ValueLane, u16)> {
let size = *self
.local_types
.get(idx as usize)
@@ -959,12 +1433,12 @@ impl FunctionBuilder<'_> {
}
/// Pushes logical operands while maintaining the lane counts used by `DropKeep`.
- fn push_sizes(&mut self, sizes: &[OperandSize]) -> Result<()> {
+ fn push_sizes(&mut self, sizes: &[ValueLane]) -> Result<()> {
for &size in sizes {
let count = match size {
- OperandSize::S32 => &mut self.lane_counts.c32,
- OperandSize::S64 => &mut self.lane_counts.c64,
- OperandSize::S128 => &mut self.lane_counts.c128,
+ ValueLane::S32 => &mut self.lane_counts.c32,
+ ValueLane::S64 => &mut self.lane_counts.c64,
+ ValueLane::S128 => &mut self.lane_counts.c128,
};
*count = count
.checked_add(1)
@@ -975,7 +1449,7 @@ impl FunctionBuilder<'_> {
}
/// Pops an operand, allowing a polymorphic value at an unreachable frame base.
- fn pop_expect(&mut self, expected: OperandSize) -> Result<()> {
+ fn pop_expect(&mut self, expected: ValueLane) -> Result<()> {
let frame_height = self.control_stack.last().map_or(0, |frame| frame.height);
if self.operand_stack.len() == frame_height && self.is_unreachable() {
return Ok(());
@@ -988,25 +1462,43 @@ impl FunctionBuilder<'_> {
return Err(crate::ParseError::Other("logical operand width mismatch".into()));
}
match actual {
- OperandSize::S32 => self.lane_counts.c32 -= 1,
- OperandSize::S64 => self.lane_counts.c64 -= 1,
- OperandSize::S128 => self.lane_counts.c128 -= 1,
+ ValueLane::S32 => self.lane_counts.c32 -= 1,
+ ValueLane::S64 => self.lane_counts.c64 -= 1,
+ ValueLane::S128 => self.lane_counts.c128 -= 1,
}
Ok(())
}
/// Applies a declared logical stack effect in WebAssembly operand order.
- fn apply_effect(&mut self, inputs: &[OperandSize], outputs: &[OperandSize]) -> Result<()> {
+ fn apply_effect(&mut self, inputs: &[ValueLane], outputs: &[ValueLane]) -> Result<()> {
inputs.iter().rev().try_for_each(|&size| self.pop_expect(size))?;
self.push_sizes(outputs)?;
Ok(())
}
/// Applies an instruction's stack effect before adding it to the bytecode.
- fn emit(&mut self, inputs: &[OperandSize], outputs: &[OperandSize], instruction: Instruction) -> Result<()> {
+ fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> {
self.apply_effect(inputs, outputs)?;
- self.instructions.push(instruction);
- Ok(())
+ self.emitter.emit(instruction)
+ }
+
+ /// Applies stack effects and seals a call or terminator's instruction boundary.
+ fn emit_boundary(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> {
+ self.apply_effect(inputs, outputs)?;
+ self.emitter.emit_boundary(instruction)
+ }
+
+ /// Applies logical stack effects before invoking a statically selected rule family.
+ #[inline]
+ fn emit_with(
+ &mut self,
+ inputs: &[ValueLane],
+ outputs: &[ValueLane],
+ instruction: Instruction,
+ rules: impl FnOnce(&mut crate::emitter::PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>,
+ ) -> Result<()> {
+ self.apply_effect(inputs, outputs)?;
+ self.emitter.emit_with(&mut self.data, instruction, rules)
}
/// Restores both logical operand order and lane counts to a control-frame base.
@@ -1025,31 +1517,42 @@ impl FunctionBuilder<'_> {
}
}
+ fn block_signature(&self, ty: wasmparser::BlockType) -> Result<BlockSignature<'a>> {
+ Ok(match ty {
+ wasmparser::BlockType::Empty => BlockSignature::Empty,
+ wasmparser::BlockType::Type(ty) => BlockSignature::Result(value_lane(ty)),
+ wasmparser::BlockType::FuncType(idx) => BlockSignature::Function(self.metadata.signature(idx)?),
+ })
+ }
+
/// Enters a control frame with its parameters restored above the saved base.
- fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option<usize>) -> Result<()> {
- let signature = match ty {
- wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() },
- wasmparser::BlockType::Type(ty) => {
- Signature { params: Vec::new(), results: alloc::vec![OperandSize::from(ty)] }
- }
- wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(),
- };
- for &size in signature.params.iter().rev() {
+ fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, else_entry: Option<LabelId>) -> Result<()> {
+ let signature = self.block_signature(ty)?;
+ for &size in signature.params().iter().rev() {
self.pop_expect(size)?;
}
let height = self.operand_stack.len();
let base = self.lane_counts;
- self.push_sizes(&signature.params)?;
+ self.push_sizes(signature.params())?;
let entry_unreachable = self.is_unreachable();
+ // Backedges are not known yet, so loop headers always seal the tail.
+ // Other constructs have no entry target and allocate exits on first use.
+ let loop_start = if matches!(kind, BlockKind::Loop) {
+ let start = self.emitter.new_label();
+ self.emitter.bind(start)?;
+ Some(start)
+ } else {
+ None
+ };
self.control_stack.push(ControlFrame {
kind,
has_else: false,
- start_ip: self.instructions.len(),
- branch_jumps: initial_jump.into_iter().collect(),
+ loop_start,
+ end: None,
+ else_entry,
height,
base,
- params: signature.params,
- results: signature.results,
+ signature,
unreachable: entry_unreachable,
entry_unreachable,
end_reachable: false,
@@ -1058,34 +1561,32 @@ impl FunctionBuilder<'_> {
}
/// Emits the stack-shaping instruction required by a branch.
- fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) {
- let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 };
- if self.lane_counts == target {
- return;
+ fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) -> Result<()> {
+ if Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32) {
+ self.emitter.emit(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 })?;
+ }
+ if Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) {
+ self.emitter.emit(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 })?;
}
- self.instructions.push(Instruction::DropKeep((base, keep).into()));
+ if Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128) {
+ self.emitter.emit(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 })?;
+ }
+ Ok(())
}
- fn patch_jump(&mut self, jump_ip: usize, target: usize) {
- match &mut self.instructions[jump_ip] {
- Instruction::Jump(ip)
- | Instruction::JumpIfZero32(ip)
- | Instruction::JumpIfNonZero32(ip)
- | Instruction::JumpIfRefNull(ip)
- | Instruction::JumpIfRefNonNull(ip) => {
- *ip = target as u32;
- }
- _ => {}
- }
+ fn needs_dropkeep(&self, base: ValueCounts, keep: ValueCounts) -> bool {
+ Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32)
+ || Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64)
+ || Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128)
}
- fn value_counts(sizes: &[OperandSize]) -> ValueCounts {
+ fn value_counts(sizes: &[ValueLane]) -> ValueCounts {
let mut counts = ValueCounts::default();
for size in sizes {
match size {
- OperandSize::S32 => counts.c32 += 1,
- OperandSize::S64 => counts.c64 += 1,
- OperandSize::S128 => counts.c128 += 1,
+ ValueLane::S32 => counts.c32 += 1,
+ ValueLane::S64 => counts.c64 += 1,
+ ValueLane::S128 => counts.c128 += 1,
}
}
counts
@@ -1098,39 +1599,24 @@ impl FunctionBuilder<'_> {
}
let frame = &self.control_stack[self.get_ctx_idx(label_depth)?];
let base = frame.base;
- let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results };
- self.emit_dropkeep(base, Self::value_counts(label_types));
- Ok(())
+ let label_types =
+ if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() };
+ self.emit_dropkeep(base, Self::value_counts(label_types))
}
fn emit_branch_jump_or_return(&mut self, depth: u32) -> Result<()> {
let ctx_idx = self.get_ctx_idx(depth)?;
match self.control_stack[ctx_idx].kind {
- BlockKind::Function => self.instructions.push(Instruction::Return),
- BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)),
- BlockKind::Block | BlockKind::If => {
- self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len());
+ BlockKind::Function => self.emitter.emit_boundary(Instruction::Return)?,
+ BlockKind::Loop => {
+ self.emitter.branch(Instruction::Jump(0), self.control_stack[ctx_idx].loop_start.unwrap())?
+ }
+ BlockKind::Block | BlockKind::If | BlockKind::TryTable => {
self.control_stack[ctx_idx].end_reachable = true;
- self.instructions.push(Instruction::Jump(0));
+ let end = *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label());
+ self.emitter.branch(Instruction::Jump(0), end)?;
}
}
Ok(())
}
-
- /// Resolves all jumps owned by a completed control frame.
- fn patch_end_jumps(&mut self, ctx: ControlFrame, end_ip: usize) {
- let target = if matches!(ctx.kind, BlockKind::Loop) { ctx.start_ip } else { end_ip };
- let mut jumps = ctx.branch_jumps.as_slice();
- if matches!(ctx.kind, BlockKind::If)
- && let Some((cond_jump, branch_jumps)) = jumps.split_first()
- {
- if !ctx.has_else {
- self.patch_jump(*cond_jump, end_ip);
- }
- jumps = branch_jumps;
- }
- for &jump in jumps {
- self.patch_jump(jump, target);
- }
- }
}
diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml
index aecebeb..4f35466 100644
--- a/crates/tinywasm/Cargo.toml
+++ b/crates/tinywasm/Cargo.toml
@@ -5,21 +5,14 @@ edition.workspace = true
rust-version.workspace = true
description = "A tiny WebAssembly interpreter"
readme = "../../README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
categories.workspace = true
[package.metadata.docs.rs]
-features = [
- "std",
- "parser",
- "archive",
- "log",
- "canonicalize-nans",
- "debug",
- "guest-debug"
-]
+features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "state", "debug", "guest-debug"]
rustdoc-args = ["--cfg", "docsrs"]
[lib]
@@ -33,7 +26,6 @@ name = "test-wasm-1"
[[test]]
harness = false
name = "test-wasm-3"
-test = false
[[test]]
harness = false
@@ -42,7 +34,6 @@ name = "test-wasm-2"
[[test]]
harness = false
name = "test-wasm-latest"
-test = false
[[test]]
harness = false
@@ -55,10 +46,6 @@ test = false
[[test]]
harness = false
-name = "test-wasm-annotations"
-
-[[test]]
-harness = false
name = "test-wast"
test = false
@@ -68,21 +55,11 @@ name = "test-wasm-custom-page-sizes"
[[test]]
harness = false
-name = "test-wasm-function-references"
-test = false
-
-[[test]]
-harness = false
name = "test-wasm-custom"
[[test]]
harness = false
name = "test-wasm-gc"
-test = false
-
-[[test]]
-harness = false
-name = "test-wasm-tail-call"
[[test]]
harness = false
@@ -90,10 +67,6 @@ name = "test-wasm-memory64"
[[test]]
harness = false
-name = "test-wasm-extended-const"
-
-[[test]]
-harness = false
name = "test-wasm-relaxed-simd"
[[test]]
@@ -104,73 +77,42 @@ name = "test-wasm-simd"
harness = false
name = "test-wasm-wide-arithmetic"
-[[test]]
-harness = false
-name = "test-wasm-sign-extension-op"
-
-[[test]]
-harness = false
-name = "test-wasm-nontrapping-float-to-int-conversions"
-
-[[test]]
-harness = false
-name = "test-wasm-reference-types"
-
-[[bench]]
-harness = false
-name = "argon2id"
-
-[[bench]]
-harness = false
-name = "fibonacci"
-
-[[bench]]
-harness = false
-name = "tinywasm"
-
-[[bench]]
-harness = false
-name = "tinywasm_modes"
-
-[[bench]]
-harness = false
-name = "memory_backends"
-
[dependencies]
libm = { version = "0.2", default-features = false }
log = { workspace = true, optional = true }
+portable-atomic = { version = "1.15.0", default-features = false, optional = true }
tinywasm-parser = { workspace = true, optional = true }
tinywasm-types = { workspace = true }
[dev-dependencies]
-criterion.workspace = true
-eyre.workspace = true
-owo-colors.workspace = true
-serde.workspace = true
-serde_json.workspace = true
-tinywasm-cli = { path = "../cli", features = ["wast", "wat"] }
+tinywasm-cli = { path = "../cli", features = ["tests", "wat"] }
wasm-testsuite.workspace = true
wat.workspace = true
[features]
-default = [
- "archive",
- "canonicalize-nans",
- "debug",
- "log",
- "parallel-parser",
- "parser",
- "std"
-]
+default = ["full", "std"]
+full = ["archive", "debug", "parallel-parser", "parser", "state", "validate"]
-log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"]
+log = ["dep:log", "tinywasm-parser?/log"]
std = ["tinywasm-parser?/std", "tinywasm-types/std"]
+# make stores, instances, references, and host callbacks movable across threads
+send = []
+
+# store host state for access from host callbacks
+state = []
+
# support for parsing WebAssembly
parser = ["dep:tinywasm-parser"]
+# validate WebAssembly while parsing
+validate = ["tinywasm-parser?/validate"]
+
# parallelize function parsing/validation across threads (requires std)
-parallel-parser = ["parser", "tinywasm-parser?/parallel"]
+parallel-parser = ["tinywasm-parser?/parallel"]
+
+# support targets without native atomic CAS
+portable-atomic = ["dep:portable-atomic", "tinywasm-parser?/portable-atomic", "tinywasm-types/portable-atomic"]
# support for "archiving" tinywasm bytecode
archive = ["tinywasm-types/archive"]
@@ -184,7 +126,13 @@ debug = ["tinywasm-types/debug"]
# expose module-internal by-index inspection APIs for non-exported entities (for testing and debugging)
guest-debug = []
+# use explicit tail calls for interpreter dispatch (requires nightly Rust)
+nightly-tail-calls = []
+
# enable x86-specific SIMD intrinsics in Value128 (uses unsafe code)
# note: for x86 backend selection, compile with x86-64-v3 target features
# (for example: `RUSTFLAGS="-C target-cpu=x86-64-v3"`)
simd-x86 = []
+
+[lints]
+workspace = true
diff --git a/crates/tinywasm/benches/memory_backends.rs b/crates/tinywasm/benches/memory_backends.rs
deleted file mode 100644
index 3a59f8c..0000000
--- a/crates/tinywasm/benches/memory_backends.rs
+++ /dev/null
@@ -1,152 +0,0 @@
-use criterion::measurement::WallTime;
-use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main};
-use std::hint::black_box;
-use tinywasm::{LinearMemory, PagedMemory, VecMemory};
-
-const PAGE_SIZE: usize = 64 * 1024;
-const CHUNK_SIZE: usize = 4 * 1024;
-const GROW_STEPS: usize = 32;
-const BENCH_MEASUREMENT_TIME: std::time::Duration = std::time::Duration::from_secs(10);
-
-const MEMORY_LEN: usize = PAGE_SIZE * 4;
-const CONTIGUOUS_OFFSET: usize = 1024;
-const CONTIGUOUS_LEN: usize = 2048;
-const CROSS_CHUNK_OFFSET: usize = CHUNK_SIZE - 512;
-const CROSS_CHUNK_LEN: usize = CHUNK_SIZE * 2;
-
-fn bench_grow<M, F>(group: &mut BenchmarkGroup<'_, WallTime>, backend: &str, make_memory: F)
-where
- M: LinearMemory,
- F: Fn() -> M + Copy,
-{
- group.bench_function(BenchmarkId::new("grow", backend), |b| {
- b.iter_batched(
- make_memory,
- |mut memory| {
- for page_count in 2..=GROW_STEPS + 1 {
- memory.grow_to(page_count * PAGE_SIZE).unwrap();
- }
- black_box(memory.len())
- },
- BatchSize::SmallInput,
- )
- });
-}
-
-fn bench_write_all<M: LinearMemory>(
- group: &mut BenchmarkGroup<'_, WallTime>,
- backend: &str,
- workload: &str,
- mut memory: M,
- offset: usize,
- len: usize,
-) {
- let src = vec![0xA5; len];
- group.bench_function(BenchmarkId::new(format!("write_all/{workload}"), backend), |b| {
- b.iter(|| {
- memory.write_all(offset, black_box(&src)).unwrap();
- black_box(memory.len())
- })
- });
-}
-
-fn bench_read_exact<M: LinearMemory>(
- group: &mut BenchmarkGroup<'_, WallTime>,
- backend: &str,
- workload: &str,
- mut memory: M,
- offset: usize,
- len: usize,
-) {
- let src = vec![0x5A; len];
- memory.write_all(offset, &src).unwrap();
-
- let mut dst = vec![0; len];
- group.bench_function(BenchmarkId::new(format!("read_exact/{workload}"), backend), |b| {
- b.iter(|| {
- memory.read_exact(offset, black_box(&mut dst)).unwrap();
- black_box(&dst);
- })
- });
-}
-
-fn criterion_benchmark(c: &mut Criterion) {
- let mut group = c.benchmark_group("memory_backends");
- group.measurement_time(BENCH_MEASUREMENT_TIME);
-
- bench_grow(&mut group, "vec", || VecMemory::try_new(PAGE_SIZE).expect("bench memory should be constructible"));
- bench_grow(&mut group, "paged", || {
- PagedMemory::try_new(PAGE_SIZE, CHUNK_SIZE).expect("bench memory should be constructible")
- });
-
- bench_write_all(
- &mut group,
- "vec",
- "contiguous",
- VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"),
- CONTIGUOUS_OFFSET,
- CONTIGUOUS_LEN,
- );
- bench_write_all(
- &mut group,
- "paged",
- "contiguous",
- PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"),
- CONTIGUOUS_OFFSET,
- CONTIGUOUS_LEN,
- );
- bench_read_exact(
- &mut group,
- "vec",
- "contiguous",
- VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"),
- CONTIGUOUS_OFFSET,
- CONTIGUOUS_LEN,
- );
- bench_read_exact(
- &mut group,
- "paged",
- "contiguous",
- PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"),
- CONTIGUOUS_OFFSET,
- CONTIGUOUS_LEN,
- );
-
- bench_write_all(
- &mut group,
- "vec",
- "cross_chunk",
- VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"),
- CROSS_CHUNK_OFFSET,
- CROSS_CHUNK_LEN,
- );
- bench_write_all(
- &mut group,
- "paged",
- "cross_chunk",
- PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"),
- CROSS_CHUNK_OFFSET,
- CROSS_CHUNK_LEN,
- );
- bench_read_exact(
- &mut group,
- "vec",
- "cross_chunk",
- VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"),
- CROSS_CHUNK_OFFSET,
- CROSS_CHUNK_LEN,
- );
- bench_read_exact(
- &mut group,
- "paged",
- "cross_chunk",
- PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"),
- CROSS_CHUNK_OFFSET,
- CROSS_CHUNK_LEN,
- );
-
- group.finish();
-}
-
-criterion_group!(benches, criterion_benchmark);
-criterion_main!(benches);
diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs
index 521eb80..76acc19 100644
--- a/crates/tinywasm/src/engine.rs
+++ b/crates/tinywasm/src/engine.rs
@@ -1,9 +1,12 @@
-/// Memory backend types and traits.
-pub use crate::store::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory};
+use alloc::boxed::Box;
+
+use crate::ResourceLimiter;
+use crate::shared::StoreShared;
/// Global configuration for the WebAssembly interpreter
///
-/// Can be cheaply cloned and shared across multiple executions and threads.
+/// Can be cheaply cloned across stores. With the `send` feature, it can also be
+/// moved and shared across threads.
///
/// ## Example
/// ```rust
@@ -48,16 +51,16 @@ pub enum FuelPolicy {
}
/// Default size for the 32-bit value stack (i32, f32, ref values).
-pub const DEFAULT_VALUE_STACK_32_SIZE: usize = 36 * 1024; // 36k slots
+const DEFAULT_VALUE_STACK_32_SIZE: usize = 36 * 1024; // 36k slots
/// Default size for the 64-bit value stack (i64, f64 values).
-pub const DEFAULT_VALUE_STACK_64_SIZE: usize = 32 * 1024; // 32k slots
+const DEFAULT_VALUE_STACK_64_SIZE: usize = 32 * 1024; // 32k slots
/// Default size for the 128-bit value stack (v128 values).
-pub const DEFAULT_VALUE_STACK_128_SIZE: usize = 4 * 1024; // 4k slots
+const DEFAULT_VALUE_STACK_128_SIZE: usize = 4 * 1024; // 4k slots
/// Default maximum size for the call stack (function frames).
-pub const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames
+const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames
/// Stack allocation policy.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -65,7 +68,8 @@ pub const DEFAULT_MAX_CALL_STACK_SIZE: usize = 1024; // 1024 frames
pub struct StackConfig {
/// Initial reserved capacity for the stack.
pub initial_size: usize,
- /// Maximum number of elements the stack may contain.
+ /// Growth threshold, checked only when the stack reaches its allocated capacity.
+ /// Dynamic stacks may exceed this threshold up to their allocated capacity.
pub max_size: usize,
/// Whether the stack may grow past its initial capacity.
pub dynamic: bool,
@@ -77,7 +81,9 @@ impl StackConfig {
Self { initial_size: size, max_size: size, dynamic: false }
}
- /// Creates a dynamically growing stack with the given initial and maximum sizes.
+ /// Creates a dynamically growing stack with the given initial size and growth threshold.
+ ///
+ /// The threshold is not a strict element limit, see [`Self::max_size`].
pub const fn dynamic(initial_size: usize, max_size: usize) -> Self {
assert!(initial_size <= max_size, "initial_size must be less than or equal to max_size");
Self { initial_size, max_size, dynamic: true }
@@ -88,21 +94,18 @@ impl StackConfig {
///
/// ## Example
/// ```rust
-/// use tinywasm::engine::{Config, FuelPolicy, MemoryBackend, StackConfig};
+/// use tinywasm::engine::{Config, FuelPolicy, StackConfig};
///
/// let config = Config::new()
/// .with_fuel_policy(FuelPolicy::Weighted)
/// .with_value_stack_32(StackConfig::dynamic(1024, 36 * 1024))
/// .with_value_stack_64(StackConfig::dynamic(1024, 32 * 1024))
/// .with_value_stack_128(StackConfig::dynamic(256, 4 * 1024))
-/// .with_call_stack(StackConfig::dynamic(64, 1024))
-/// .with_memory_backend(MemoryBackend::paged(64 * 1024))
-/// .with_trap_on_oom(true);
+/// .with_call_stack(StackConfig::dynamic(64, 1024));
///
/// assert!(matches!(config.fuel_policy(), FuelPolicy::Weighted));
/// ```
#[derive(Clone)]
-#[cfg_attr(feature = "debug", derive(Debug))]
#[non_exhaustive]
pub struct Config {
/// Configuration for the 32-bit value stack (i32, f32, ref values).
@@ -118,11 +121,11 @@ pub struct Config {
pub call_stack: StackConfig,
/// Fuel accounting policy used by budgeted execution. Defaults to [`FuelPolicy::PerInstruction`].
pub fuel_policy: FuelPolicy,
- /// Backend used for runtime memories. Defaults to [`MemoryBackend::vec`].
- pub memory_backend: MemoryBackend,
- /// Whether memory and stack allocation failures should trap instead of degrading into normal operation failure modes.
- /// Defaults to `false`.
- pub trap_on_oom: bool,
+ /// Resource limiter shared across all stores created from this engine. Defaults to `None`.
+ pub resource_limiter: Option<StoreShared<dyn ResourceLimiter>>,
+ /// Initial number of GC heap bytes that triggers collection.
+ /// Defaults to 1 MiB.
+ pub gc_collection_threshold: usize,
}
impl Config {
@@ -137,12 +140,6 @@ impl Config {
self
}
- /// Set the backend used for runtime memories.
- pub fn with_memory_backend(mut self, memory_backend: MemoryBackend) -> Self {
- self.memory_backend = memory_backend;
- self
- }
-
/// Set the configuration used for the 32-bit value stack.
pub fn with_value_stack_32(mut self, stack: StackConfig) -> Self {
self.value_stack_32 = stack;
@@ -175,9 +172,18 @@ impl Config {
self
}
- /// Configure whether memory and stack allocation failures trap immediately.
- pub fn with_trap_on_oom(mut self, trap_on_oom: bool) -> Self {
- self.trap_on_oom = trap_on_oom;
+ /// Set the resource limiter shared across all stores created from this engine.
+ ///
+ /// The limiter is converted to TinyWasm's internal shared pointer. Pass the
+ /// limiter value directly rather than wrapping it in `Rc` or `Arc`.
+ pub fn with_resource_limiter(mut self, limiter: impl ResourceLimiter + 'static) -> Self {
+ self.resource_limiter = Some(StoreShared::from(Box::new(limiter) as Box<dyn ResourceLimiter>));
+ 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
}
@@ -185,15 +191,6 @@ impl Config {
pub fn fuel_policy(&self) -> FuelPolicy {
self.fuel_policy
}
-
- /// Get the current memory backend
- pub fn memory_backend(&self) -> &MemoryBackend {
- &self.memory_backend
- }
-
- pub(crate) const fn trap_on_oom(&self) -> bool {
- self.trap_on_oom
- }
}
impl Default for Config {
@@ -204,8 +201,23 @@ impl Default for Config {
value_stack_128: StackConfig::fixed(DEFAULT_VALUE_STACK_128_SIZE),
call_stack: StackConfig::fixed(DEFAULT_MAX_CALL_STACK_SIZE),
fuel_policy: FuelPolicy::default(),
- memory_backend: MemoryBackend::default(),
- trap_on_oom: false,
+ resource_limiter: None,
+ gc_collection_threshold: 1024 * 1024,
}
}
}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for Config {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_struct("Config")
+ .field("value_stack_32", &self.value_stack_32)
+ .field("value_stack_64", &self.value_stack_64)
+ .field("value_stack_128", &self.value_stack_128)
+ .field("call_stack", &self.call_stack)
+ .field("fuel_policy", &self.fuel_policy)
+ .field("resource_limiter", &self.resource_limiter.is_some())
+ .field("gc_collection_threshold", &self.gc_collection_threshold)
+ .finish()
+ }
+}
diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs
index b5885ca..77856af 100644
--- a/crates/tinywasm/src/error.rs
+++ b/crates/tinywasm/src/error.rs
@@ -5,6 +5,8 @@ use core::fmt::{Debug, Display};
use tinywasm_types::FuncType;
use tinywasm_types::archive::TwasmError;
+use crate::{ExnRef, WasmValue};
+
#[cfg(feature = "parser")]
pub use tinywasm_parser::ParseError;
@@ -14,6 +16,9 @@ pub enum Error {
/// A WebAssembly trap occurred
Trap(Trap),
+ /// An uncaught WebAssembly exception occurred.
+ Exception(ExnRef),
+
/// A linking error occurred
Linker(LinkingError),
@@ -28,7 +33,7 @@ pub enum Error {
/// The expected type
expected: Box<FuncType>,
/// The actual value
- actual: Vec<tinywasm_types::WasmValue>,
+ actual: Vec<WasmValue>,
},
/// An invalid label type was encountered
@@ -50,6 +55,7 @@ impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Trap(a), Self::Trap(b)) => a == b,
+ (Self::Exception(a), Self::Exception(b)) => a == b,
(Self::Linker(a), Self::Linker(b)) => a == b,
(Self::UnsupportedFeature(a), Self::UnsupportedFeature(b)) => a == b,
(Self::Other(a), Self::Other(b)) => a == b,
@@ -101,9 +107,11 @@ impl Error {
}
}
-/// A WebAssembly trap
+/// An execution or runtime trap.
+///
+/// This includes WebAssembly traps and TinyWasm runtime failures.
///
-/// See <https://webassembly.github.io/spec/core/intro/overview.html#trap>
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#syntax-trap>
#[non_exhaustive]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum Trap {
@@ -119,7 +127,7 @@ pub enum Trap {
offset: usize,
/// The size of the access
len: usize,
- /// The maximum size of the memory
+ /// The current memory length in bytes.
max: usize,
},
@@ -129,19 +137,25 @@ pub enum Trap {
offset: usize,
/// The size of the access
len: usize,
- /// The maximum size of the memory
+ /// The current table length in elements.
max: usize,
},
+ /// An out-of-bounds GC array access occurred.
+ ArrayOutOfBounds,
+
/// A division by zero occurred
DivisionByZero,
/// Invalid Integer Conversion
InvalidConversionToInt,
- /// The store is not the one that the module instance was instantiated in
+ /// A Store-owned handle or reference was used with a different Store.
InvalidStore,
+ /// A reference does not identify a live value of the expected kind.
+ InvalidReference,
+
/// Integer Overflow
IntegerOverflow,
@@ -151,7 +165,7 @@ pub enum Trap {
/// Value stack overflow
ValueStackOverflow,
- /// The runtime could not allocate memory for a stack or linear memory operation.
+ /// An allocation or requested resource size could not be satisfied.
OutOfMemory,
/// An undefined element was encountered
@@ -169,9 +183,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 +217,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,10 +227,15 @@ 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",
+ Self::InvalidReference => "invalid reference",
Self::Other(message) => message,
}
}
@@ -226,18 +258,21 @@ impl LinkingError {
}
impl From<LinkingError> for Error {
+ #[cold]
fn from(value: LinkingError) -> Self {
Self::Linker(value)
}
}
impl From<TwasmError> for Error {
+ #[cold]
fn from(value: TwasmError) -> Self {
Self::Twasm(value)
}
}
impl From<Trap> for Error {
+ #[cold]
fn from(value: Trap) -> Self {
Self::Trap(value)
}
@@ -254,6 +289,7 @@ impl Display for Error {
Self::Twasm(err) => write!(f, "serialization error: {err}"),
Self::Trap(trap) => write!(f, "trap: {trap}"),
+ Self::Exception(_) => write!(f, "uncaught WebAssembly exception"),
Self::Linker(err) => write!(f, "linking error: {err}"),
Self::InvalidLabelType => write!(f, "invalid label type"),
Self::Other(message) => write!(f, "unknown error: {message}"),
@@ -291,6 +327,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,8 +339,13 @@ 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"),
+ Self::InvalidReference => write!(f, "invalid reference"),
#[cfg(feature = "debug")]
Self::IndirectCallTypeMismatch { expected, actual } => {
write!(f, "indirect call type mismatch: expected={expected:?}, actual={actual:?}")
@@ -334,6 +376,7 @@ impl From<Error> for crate::std::io::Error {
#[cfg(feature = "parser")]
impl From<tinywasm_parser::ParseError> for Error {
+ #[cold]
fn from(value: tinywasm_parser::ParseError) -> Self {
Self::Parser(value)
}
diff --git a/crates/tinywasm/src/func.rs b/crates/tinywasm/src/func.rs
deleted file mode 100644
index adad223..0000000
--- a/crates/tinywasm/src/func.rs
+++ /dev/null
@@ -1,856 +0,0 @@
-use crate::interpreter::stack::{CallFrame, ValueStack};
-use crate::reference::StoreItem;
-use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store, Trap};
-use alloc::{borrow::Cow, boxed::Box, format, sync::Arc, vec, vec::Vec};
-use core::hint::cold_path;
-use tinywasm_types::{ExternRef, FuncAddr, FuncRef, FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue};
-
-impl Function {
- #[inline]
- pub(crate) const fn addr(&self) -> FuncAddr {
- self.item.addr
- }
-
- /// Get this function's canonical type from its store.
- ///
- /// Concrete reference types are only meaningful in this store.
- pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> {
- self.item.validate_store(store)?;
- Ok(store.state.get_func_type(self.addr()))
- }
-
- /// Call a function (Invocation)
- ///
- /// See <https://webassembly.github.io/spec/core/exec/modules.html#invocation>
- #[inline]
- pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> {
- #[inline]
- fn call_inner(func: &Function, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> {
- let func_instance = store.state.get_func(func.addr()).clone();
- let wasm_func = match &func_instance.kind {
- crate::store::FunctionKind::Host(host_func) => {
- let result = host_func.clone().call(FuncContext { store, module_id: func.module_id }, params)?;
- return validate_host_results(store, func_instance.type_addr, result);
- }
- crate::store::FunctionKind::Wasm(wasm_func) => wasm_func,
- };
-
- // Reset stack, push args, allocate locals, create entry frame.
- store.call_stack.clear();
- store.value_stack.clear();
- store.value_stack.extend_from_wasmvalues(params)?;
- let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?;
- let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals);
-
- // 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))
- }
-
- self.item.validate_store(store)?;
- validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?;
-
- store.enter_execution()?;
- let result = call_inner(self, store, params);
- store.exit_execution();
-
- result
- }
-
- /// Call a function and return a resumable execution handle.
- ///
- /// The returned handle keeps a mutable borrow of the [`Store`] until it
- /// completes. Use [`FuncExecution::resume_with_fuel`] (or
- /// `resume_with_time_budget` with `std`) to continue.
- pub fn call_resumable<'store>(
- &self,
- store: &'store mut Store,
- params: &[WasmValue],
- ) -> Result<FuncExecution<'store>> {
- #[inline]
- fn call_resumable_inner(
- func: &Function,
- store: &mut Store,
- params: &[WasmValue],
- ) -> Result<FuncExecutionState> {
- let func_instance = store.state.get_func(func.addr()).clone();
- match &func_instance.kind {
- crate::store::FunctionKind::Host(host_func) => {
- let result = host_func.clone().call(FuncContext { store, module_id: func.module_id }, params)?;
- let result = validate_host_results(store, func_instance.type_addr, result)?;
- Ok(FuncExecutionState::Completed { result: Some(result) })
- }
- crate::store::FunctionKind::Wasm(wasm_func) => {
- store.call_stack.clear();
- store.value_stack.clear();
- store.value_stack.extend_from_wasmvalues(params)?;
- let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?;
- let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals);
-
- Ok(FuncExecutionState::Running {
- exec_state: ExecutionState { callframe },
- root_func_addr: func.addr(),
- })
- }
- }
- }
-
- self.item.validate_store(store)?;
- validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?;
-
- store.enter_execution()?;
- let result = call_resumable_inner(self, store, params);
- store.exit_execution();
-
- Ok(FuncExecution { store, state: result? })
- }
-}
-
-#[derive(Clone, PartialEq, Eq)]
-/// Progress for fuel-limited function execution.
-pub enum ExecProgress<T> {
- /// Execution completed and produced a result.
- Completed(T),
- /// Execution suspended after exhausting fuel or time budget.
- Suspended,
-}
-
-#[derive(Clone)]
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub(crate) struct ExecutionState {
- pub(crate) callframe: CallFrame,
-}
-
-/// A function handle
-#[derive(Clone)]
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub struct Function {
- pub(crate) item: StoreItem,
- pub(crate) module_id: ModuleInstanceId,
-}
-
-/// A typed function handle
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub struct FunctionTyped<P, R> {
- /// The underlying function handle
- pub func: Function,
- pub(crate) marker: core::marker::PhantomData<(P, R)>,
-}
-
-/// A host function
-pub struct HostFunction {
- pub(crate) func: HostFuncInner,
-}
-
-impl HostFunction {
- /// Call the function
- pub fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result<Vec<WasmValue>> {
- (self.func)(ctx, args)
- }
-
- /// Create a new untyped host function import.
- ///
- /// ## Example
- /// ```rust
- /// # fn main() -> tinywasm::Result<()> {
- /// # use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
- /// # use tinywasm::types::{FuncType, WasmType, WasmValue};
- /// # let wasm = wat::parse_str(r#"
- /// # (module
- /// # (import "host" "add_one" (func $add_one (param i32) (result i32)))
- /// # (func (export "call") (param i32) (result i32)
- /// # local.get 0
- /// # call $add_one))
- /// # "#).expect("valid wat");
- /// # let module = tinywasm::parse_bytes(&wasm)?;
- /// let mut store = Store::default();
- /// let ty = FuncType::new(&[WasmType::I32], &[WasmType::I32]);
- /// let add_one = HostFunction::from_untyped(&mut store, &ty, |_ctx: FuncContext<'_>, args| {
- /// let WasmValue::I32(value) = args[0] else {
- /// return Err(tinywasm::Error::Other("expected i32".into()));
- /// };
- /// Ok(vec![WasmValue::I32(value + 1)])
- /// });
- ///
- /// let mut imports = Imports::new();
- /// imports.define("host", "add_one", add_one);
- /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
- /// # let call = instance.func::<i32, i32>(&store, "call")?;
- /// # assert_eq!(call.call(&mut store, 41)?, 42);
- /// # Ok(())
- /// # }
- /// ```
- pub fn from_untyped(
- store: &mut Store,
- ty: &FuncType,
- func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + Sync + Send + 'static,
- ) -> Function {
- let type_addr = store.register_host_type(ty);
- let addr = store.add_func(FunctionInstance {
- type_addr,
- kind: crate::store::FunctionKind::Host(Arc::new(Self { func: Box::new(func) })),
- });
- Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
- }
-
- /// Create a new typed host function import.
- ///
- /// ## Example
- /// ```rust
- /// # fn main() -> tinywasm::Result<()> {
- /// # use tinywasm::{HostFunction, Imports, ModuleInstance, Store};
- /// # let wasm = wat::parse_str(r#"
- /// # (module
- /// # (import "host" "add_one" (func $add_one (param i32) (result i32)))
- /// # (func (export "call") (param i32) (result i32)
- /// # local.get 0
- /// # call $add_one))
- /// # "#).expect("valid wat");
- /// # let module = tinywasm::parse_bytes(&wasm)?;
- /// let mut store = Store::default();
- /// let add_one = HostFunction::from(&mut store, |_ctx, value: i32| Ok(value + 1));
- ///
- /// let mut imports = Imports::new();
- /// imports.define("host", "add_one", add_one);
- /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
- /// # let call = instance.func::<i32, i32>(&store, "call")?;
- /// # assert_eq!(call.call(&mut store, 41)?, 42);
- /// # Ok(())
- /// # }
- /// ```
- pub fn from<P, R>(
- store: &mut Store,
- func: impl Fn(FuncContext<'_>, P) -> Result<R> + Sync + Send + 'static,
- ) -> Function
- where
- P: FromWasmValues + ToWasmTypes,
- R: IntoWasmValues + ToWasmTypes,
- {
- let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result<Vec<WasmValue>> {
- Ok(func(ctx, P::from_wasm_values(args)?)?.into_wasm_values())
- };
-
- let ty = tinywasm_types::FuncType::new(&P::wasm_types(), &R::wasm_types());
- let type_addr = store.register_host_type(&ty);
- let addr = store.add_func(FunctionInstance {
- type_addr,
- kind: crate::store::FunctionKind::Host(Arc::new(Self { func: Box::new(inner_func) })),
- });
- Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
- }
-}
-
-pub(crate) type HostFuncInner = Box<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + Sync + Send>;
-
-/// The context of a host-function call
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub struct FuncContext<'a> {
- pub(crate) store: &'a mut crate::Store,
- pub(crate) module_id: ModuleInstanceId,
-}
-
-impl FuncContext<'_> {
- /// Get the store.
- pub fn store(&self) -> &crate::Store {
- self.store
- }
-
- /// Get mutable access to the store.
- pub fn store_mut(&mut self) -> &mut crate::Store {
- self.store
- }
-
- /// Get the module instance.
- pub fn module(&self) -> crate::ModuleInstance {
- self.store
- .get_module_instance(self.module_id)
- .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id))
- }
-
- /// Get a memory export.
- pub fn memory(&self, name: &str) -> Result<crate::Memory> {
- self.module().memory(name)
- }
-
- /// Get any exported extern value by name.
- pub fn extern_item(&self, name: &str) -> Result<crate::ExternItem> {
- self.module().extern_item(name)
- }
-
- /// Get a table export.
- pub fn table(&self, name: &str) -> Result<crate::Table> {
- self.module().table(name)
- }
-
- /// Get the value of a global export.
- pub fn global_get(&self, name: &str) -> Result<WasmValue> {
- self.module().global_get(self.store, name)
- }
-
- /// Get a global export.
- pub fn global(&self, name: &str) -> Result<crate::Global> {
- self.module().global(name)
- }
-
- /// Set the value of a mutable global export.
- pub fn global_set(&mut self, name: &str, value: WasmValue) -> Result<()> {
- self.module().global_set(self.store, name, value)
- }
-
- /// Charge additional fuel from the currently running resumable invocation.
- ///
- /// This is a no-op when the current invocation is not using fuel-based
- /// resumption.
- pub fn charge_fuel(&mut self, fuel: u32) {
- self.store.execution_fuel = self.store.execution_fuel.saturating_sub(fuel);
- }
-
- /// Get remaining fuel for the current invocation.
- ///
- /// Returns `0` when fuel-based resumption is not active.
- pub fn remaining_fuel(&self) -> u32 {
- self.store.execution_fuel
- }
-
- /// Call a function from within the current host-function invocation.
- ///
- /// This is the safe way for host functions to perform blocking reentrant
- /// calls into Wasm. Unlike [`Function::call`], it preserves the active
- /// invocation's stacks and resumes the host caller after the nested call
- /// completes.
- ///
- /// Nested calls are currently blocking only. If the surrounding invocation
- /// is resumed with fuel or a time budget, this method does not suspend and
- /// later continue the host function in the middle of the nested call.
- pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue]) -> Result<Vec<WasmValue>> {
- if !self.store.execution_active {
- return Err(Error::other("FuncContext::call requires an active host-function invocation"));
- }
-
- func.item.validate_store(self.store)?;
- 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 {
- crate::store::FunctionKind::Host(host_func) => {
- let result =
- host_func.call(FuncContext { store: &mut *self.store, module_id: func.module_id }, args)?;
- validate_host_results(self.store, func_instance.type_addr, result)
- }
- crate::store::FunctionKind::Wasm(wasm_func) => {
- let call_stack_base = self.store.call_stack.len();
- let value_stack_base = self.store.value_stack.base();
-
- self.store.value_stack.extend_from_wasmvalues(args).inspect_err(|_| {
- self.store.value_stack.truncate_to_base(value_stack_base);
- })?;
-
- let locals_base = self
- .store
- .value_stack
- .enter_locals(&wasm_func.func.params, &wasm_func.func.locals)
- .inspect_err(|_| self.store.value_stack.truncate_to_base(value_stack_base))?;
-
- let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals);
- InterpreterRuntime::exec(self.store, callframe, call_stack_base).inspect_err(|_| {
- self.store.call_stack.truncate_to(call_stack_base);
- 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))
- }
- }
- }
-
- /// Call a typed function from within the current host-function invocation.
- ///
- /// See [`Self::call_untyped`] for reentrancy and resumable-execution
- /// limitations.
- pub fn call<P, R>(&mut self, func: &FunctionTyped<P, R>, params: P) -> Result<R>
- where
- P: IntoWasmValues,
- R: FromWasmValues,
- {
- R::from_wasm_values(&self.call_untyped(&func.func, &params.into_wasm_values())?)
- }
-}
-
-impl core::ops::Deref for FuncContext<'_> {
- type Target = crate::Store;
-
- fn deref(&self) -> &Self::Target {
- self.store
- }
-}
-
-impl core::ops::DerefMut for FuncContext<'_> {
- fn deref_mut(&mut self) -> &mut Self::Target {
- self.store
- }
-}
-
-impl<'a> FuncContext<'a> {
- /// Create a new host function context.
- pub const fn new(store: &'a mut crate::Store, module_id: ModuleInstanceId) -> Self {
- Self { store, module_id }
- }
-}
-
-#[cfg(feature = "debug")]
-impl core::fmt::Debug for HostFunction {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- f.debug_struct("HostFunction").field("func", &"...").finish()
- }
-}
-
-/// Resumable execution for an untyped function call.
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub struct FuncExecution<'store> {
- store: &'store mut Store,
- state: FuncExecutionState,
-}
-
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-enum FuncExecutionState {
- Running { exec_state: ExecutionState, root_func_addr: u32 },
- Completed { result: Option<Vec<WasmValue>> },
-}
-
-/// Resumable execution for a typed function call.
-#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
-pub struct FuncExecutionTyped<'store, R> {
- execution: FuncExecution<'store>,
- marker: core::marker::PhantomData<R>,
-}
-
-impl<'store> FuncExecution<'store> {
- fn resume(
- &mut self,
- run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>,
- ) -> Result<ExecProgress<Vec<WasmValue>>> {
- let (callframe, root_func_addr) = match &mut self.state {
- FuncExecutionState::Running { exec_state, root_func_addr } => (exec_state.callframe, *root_func_addr),
- FuncExecutionState::Completed { result } => {
- return match result.take() {
- Some(res) => Ok(ExecProgress::Completed(res)),
- None => Err(Error::other("execution already completed")),
- };
- }
- };
-
- self.store.enter_execution()?;
- let result = run(self.store, callframe);
- self.store.exit_execution();
-
- match result? {
- crate::interpreter::ExecState::Completed => {
- let result_ty = self.store.state.get_func(root_func_addr).type_addr;
- self.state = FuncExecutionState::Completed { result: None };
- Ok(ExecProgress::Completed(collect_call_results(
- &mut self.store.value_stack,
- self.store.state.get_type(result_ty),
- )?))
- }
- crate::interpreter::ExecState::Suspended(callframe) => {
- let FuncExecutionState::Running { exec_state, .. } = &mut self.state else {
- unreachable!("invalid function execution state")
- };
- exec_state.callframe = callframe;
- Ok(ExecProgress::Suspended)
- }
- }
- }
-
- /// Resume execution with up to `fuel` units of fuel.
- ///
- /// Fuel is accounted in chunks, so execution may overshoot the requested
- /// fuel before returning [`ExecProgress::Suspended`] (currently the chunk size is 128 instructions between fuel checks, but this may change in the future).
- ///
- /// Returns [`ExecProgress::Suspended`] when fuel is exhausted, or
- /// [`ExecProgress::Completed`] with the final values once the invocation
- /// returns.
- ///
- /// Reentrant calls made by host functions through [`FuncContext::call`] are
- /// currently blocking. They do not suspend and later resume the host
- /// function in the middle of the nested call.
- pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<Vec<WasmValue>>> {
- self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel))
- }
-
- #[cfg(feature = "std")]
- /// Resume execution for at most `time_budget` wall-clock time.
- ///
- /// Time is checked periodically, so execution may overshoot the requested
- /// time budget before returning [`ExecProgress::Suspended`] (currently time is checked every 128 instructions, but this may change in the future).
- ///
- /// Returns [`ExecProgress::Suspended`] when the budget is exhausted, or
- /// [`ExecProgress::Completed`] with the final values once the invocation
- /// returns.
- ///
- /// Reentrant calls made by host functions through [`FuncContext::call`] are
- /// currently blocking. They do not suspend and later resume the host
- /// function in the middle of the nested call.
- pub fn resume_with_time_budget(
- &mut self,
- time_budget: crate::std::time::Duration,
- ) -> Result<ExecProgress<Vec<WasmValue>>> {
- self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget))
- }
-}
-
-fn validate_call_params(state: &crate::store::State, func_ty: &FuncType, params: &[WasmValue]) -> Result<()> {
- if func_ty.params().len() != params.len() {
- cold_path();
- return Err(Error::Other(format!(
- "param count mismatch: expected {}, got {}",
- func_ty.params().len(),
- params.len()
- )));
- }
-
- if !func_ty.params().iter().zip(params).all(|(ty, param)| state.value_matches_type(*param, *ty)) {
- return Err(Error::other("Type mismatch"));
- }
-
- Ok(())
-}
-
-pub(crate) fn validate_host_results(
- store: &Store,
- type_addr: TypeAddr,
- result: Vec<WasmValue>,
-) -> Result<Vec<WasmValue>> {
- let expected = store.state.get_type(type_addr);
- if result.len() == expected.results().len()
- && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty))
- {
- return Ok(result);
- }
-
- Err(Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result })
-}
-
-fn collect_call_results(value_stack: &mut ValueStack, 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
- res.reverse(); // reverse to get the original order
- Ok(res)
-}
-
-pub trait IntoWasmValues {
- fn into_wasm_values(self) -> Vec<WasmValue>;
-}
-
-pub trait FromWasmValues: Sized {
- fn from_wasm_values(values: &[WasmValue]) -> Result<Self>;
-}
-
-impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> {
- /// Call a typed function
- pub fn call(&self, store: &mut Store, params: P) -> Result<R> {
- // Convert params into Vec<WasmValue>
- let wasm_values = params.into_wasm_values();
-
- // Call the underlying WASM function
- let result = self.func.call(store, &wasm_values)?;
-
- // Convert the Vec<WasmValue> back to R
- R::from_wasm_values(&result)
- }
-
- /// Call a typed function and return a resumable execution handle.
- ///
- /// The handle keeps a mutable borrow of the [`Store`] until completion.
- ///
- /// ## Example
- ///
- /// ```rust
- /// # fn main() -> tinywasm::Result<()> {
- /// use tinywasm::{ExecProgress, ModuleInstance, Store};
- ///
- /// let wasm = include_bytes!("../../../examples/wasm/add.wasm");
- /// let module = tinywasm::parse_bytes(wasm)?;
- /// let mut store = Store::default();
- /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- /// let add = instance.func::<(i32, i32), i32>(&store, "add")?;
- ///
- /// let mut execution = add.call_resumable(&mut store, (20, 22))?;
- /// assert!(matches!(execution.resume_with_fuel(0)?, ExecProgress::Suspended));
- /// assert!(matches!(execution.resume_with_fuel(16)?, ExecProgress::Completed(42)));
- /// # Ok(())
- /// # }
- /// ```
- pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result<FuncExecutionTyped<'store, R>> {
- let wasm_values = params.into_wasm_values();
- let execution = self.func.call_resumable(store, &wasm_values)?;
- Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData })
- }
-}
-
-impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> {
- /// Resume typed execution with up to `fuel` units of fuel.
- ///
- /// Fuel is accounted in chunks, so execution may overshoot the requested
- /// fuel before returning [`ExecProgress::Suspended`].
- pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<R>> {
- match self.execution.resume_with_fuel(fuel)? {
- ExecProgress::Completed(values) => Ok(ExecProgress::Completed(R::from_wasm_values(&values)?)),
- ExecProgress::Suspended => Ok(ExecProgress::Suspended),
- }
- }
-
- #[cfg(feature = "std")]
- /// Resume typed execution for at most `time_budget` wall-clock time.
- ///
- /// Time is checked periodically, so execution may overshoot the requested
- /// time budget before returning [`ExecProgress::Suspended`].
- pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result<ExecProgress<R>> {
- match self.execution.resume_with_time_budget(time_budget)? {
- ExecProgress::Completed(values) => Ok(ExecProgress::Completed(R::from_wasm_values(&values)?)),
- ExecProgress::Suspended => Ok(ExecProgress::Suspended),
- }
- }
-}
-
-/// Describes the WebAssembly value types produced by a Rust value or tuple shape.
-pub trait ToWasmTypes {
- /// Static WebAssembly types for this shape.
- ///
- /// Implementations that require runtime construction may set this to `None`,
- /// but must then override [`Self::wasm_types`].
- const WASM_TYPES: Option<&'static [WasmType]>;
-
- /// Return the flattened WebAssembly value types for this tuple shape.
- fn wasm_types() -> Cow<'static, [WasmType]> {
- Cow::Borrowed(Self::WASM_TYPES.expect("dynamic ToWasmTypes implementation must override wasm_types"))
- }
-}
-
-/// Describes the WebAssembly value types produced by a scalar Rust type.
-pub trait ToWasmType {
- /// The single WebAssembly value type for this scalar type.
- const WASM_TYPE: WasmType;
-}
-
-macro_rules! impl_scalar_wasm_traits {
- ($($T:ty => $val_ty:expr),+ $(,)?) => {
- $(
- impl ToWasmType for $T {
- const WASM_TYPE: WasmType = $val_ty;
- }
-
- impl ToWasmTypes for $T {
- const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$val_ty]);
- }
-
- impl IntoWasmValues for $T {
- #[inline]
- fn into_wasm_values(self) -> Vec<WasmValue> {
- vec![self.into()]
- }
- }
-
- impl FromWasmValues for $T {
- #[inline]
- fn from_wasm_values(values: &[WasmValue]) -> Result<Self> {
- let value = *values.first().ok_or_else(|| {
- core::hint::cold_path();
- Error::other("Not enough elements in &[WasmValue]")
- })?;
-
- <$T>::try_from(value).map_err(|e| {
- core::hint::cold_path();
- Error::Other(format!(
- "FromWasmValues: Could not convert WasmValue to expected type: {e:?}"
- ))
- })
- }
- }
- )+
- };
-}
-
-macro_rules! impl_tuple_traits {
- ($($T:ident),+) => {
- impl<$($T),+> ToWasmTypes for ($($T,)+)
- where
- $($T: ToWasmType,)+
- {
- const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]);
- }
-
- impl<$($T),+> IntoWasmValues for ($($T,)+)
- where
- $($T: Into<WasmValue>,)+
- {
- #[allow(non_snake_case)]
- #[inline]
- fn into_wasm_values(self) -> Vec<WasmValue> {
- let ($($T,)+) = self;
- vec![$($T.into(),)+]
- }
- }
-
- impl<$($T),+> FromWasmValues for ($($T,)+)
- where
- $($T: TryFrom<WasmValue, Error = ()>,)+
- {
- #[inline]
- fn from_wasm_values(values: &[WasmValue]) -> Result<Self> {
- let mut iter = values.iter();
-
- Ok(($(
- $T::try_from(*iter.next().ok_or(Error::other("Not enough values in WasmValue vector"))?)
- .map_err(|e| Error::Other(format!("FromWasmValues: Could not convert WasmValue to expected type: {e:?}")))?,
- )+))
- }
- }
- }
-}
-
-macro_rules! impl_tuple {
- ($macro:ident) => {
- $macro!(T1);
- $macro!(T1, T2);
- $macro!(T1, T2, T3);
- $macro!(T1, T2, T3, T4);
- $macro!(T1, T2, T3, T4, T5);
- $macro!(T1, T2, T3, T4, T5, T6);
- $macro!(T1, T2, T3, T4, T5, T6, T7);
- $macro!(T1, T2, T3, T4, T5, T6, T7, T8);
- $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
- $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
- $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
- $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
- };
-}
-
-impl_scalar_wasm_traits!(
- i32 => WasmType::I32,
- i64 => WasmType::I64,
- u32 => WasmType::I32,
- u64 => WasmType::I64,
- f32 => WasmType::F32,
- f64 => WasmType::F64,
- FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF),
- ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF),
-);
-impl_tuple!(impl_tuple_traits);
-
-/// A helper type for using tuples of arbitrary number of elements as function parameters or results,
-/// by concatenating the Wasm types of each element.
-///
-/// This is useful when a function signature exceeds tuple arity 12. `tinywasm` only implements
-/// direct tuple conversions up to arity 12, but `WasmTupleChain` lets you describe longer
-/// signatures by combining smaller tuples at the type level.
-///
-/// ## Example
-/// ```rust
-/// # fn main() -> tinywasm::Result<()> {
-/// # use tinywasm::{ModuleInstance, Store, WasmTupleChain};
-/// # let wasm = wat::parse_str(r#"
-/// # (module
-/// # (func (export "echo13")
-/// # (param i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32)
-/// # (result i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32)
-/// # local.get 0
-/// # local.get 1
-/// # local.get 2
-/// # local.get 3
-/// # local.get 4
-/// # local.get 5
-/// # local.get 6
-/// # local.get 7
-/// # local.get 8
-/// # local.get 9
-/// # local.get 10
-/// # local.get 11
-/// # local.get 12)
-/// # )
-/// # "#).expect("valid wat");
-/// # let module = tinywasm::parse_bytes(&wasm)?;
-/// # let mut store = Store::default();
-/// # let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
-///
-/// type Params =
-/// WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>;
-/// type Results =
-/// WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>;
-///
-/// let echo13 = instance.func::<Params, Results>(&store, "echo13")?;
-/// let result = echo13.call(&mut store, ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13)).into())?;
-/// assert_eq!(result.into_inner(), ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13)));
-/// # Ok(())
-/// # }
-/// ```
-#[derive(Default)]
-pub struct WasmTupleChain<T1, T2>(T1, T2);
-
-impl<T1, T2> WasmTupleChain<T1, T2> {
- /// Create a new concatenated tuple wrapper.
- pub const fn new(left: T1, right: T2) -> Self {
- Self(left, right)
- }
-
- /// Split the wrapper back into its two component values.
- pub fn into_inner(self) -> (T1, T2) {
- (self.0, self.1)
- }
-}
-
-impl<T1, T2> From<(T1, T2)> for WasmTupleChain<T1, T2> {
- fn from((left, right): (T1, T2)) -> Self {
- Self::new(left, right)
- }
-}
-
-impl<T1: ToWasmTypes, T2: ToWasmTypes> ToWasmTypes for WasmTupleChain<T1, T2> {
- const WASM_TYPES: Option<&'static [WasmType]> = None;
-
- #[inline]
- fn wasm_types() -> Cow<'static, [WasmType]> {
- let mut types = Vec::new();
- types.extend_from_slice(&T1::wasm_types());
- types.extend_from_slice(&T2::wasm_types());
- Cow::Owned(types)
- }
-}
-
-impl<T1: IntoWasmValues, T2: IntoWasmValues> IntoWasmValues for WasmTupleChain<T1, T2> {
- #[inline]
- fn into_wasm_values(self) -> Vec<WasmValue> {
- let (left, right) = self.into_inner();
- let mut values = Vec::new();
- values.extend(left.into_wasm_values());
- values.extend(right.into_wasm_values());
- values
- }
-}
-
-impl<T1: FromWasmValues + ToWasmTypes, T2: FromWasmValues> FromWasmValues for WasmTupleChain<T1, T2> {
- #[inline]
- fn from_wasm_values(values: &[WasmValue]) -> Result<Self> {
- let left_len = T1::wasm_types().len();
- let left = T1::from_wasm_values(&values[..values.len().min(left_len)])?;
- let right = T2::from_wasm_values(values.get(left_len..).unwrap_or(&[]))?;
- Ok(Self::new(left, right))
- }
-}
-
-impl ToWasmTypes for () {
- const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]);
-}
-
-impl IntoWasmValues for () {
- #[inline]
- fn into_wasm_values(self) -> Vec<WasmValue> {
- vec![]
- }
-}
-
-impl FromWasmValues for () {
- #[inline]
- fn from_wasm_values(_values: &[WasmValue]) -> Result<Self> {
- Ok(())
- }
-}
diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs
new file mode 100644
index 0000000..e5c183c
--- /dev/null
+++ b/crates/tinywasm/src/func/context.rs
@@ -0,0 +1,154 @@
+use tinywasm_types::ModuleInstanceId;
+
+use crate::{Error, FromWasmValues, FuncRef, Function, FunctionTyped, IntoWasmValues, Result, WasmValue};
+
+/// The context of a host-function call
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+pub struct FuncContext<'a> {
+ pub(crate) store: &'a mut crate::Store,
+ pub(crate) module_id: ModuleInstanceId,
+}
+
+impl FuncContext<'_> {
+ /// Get the store.
+ pub fn store(&self) -> &crate::Store {
+ self.store
+ }
+
+ /// Get mutable access to the store.
+ pub fn store_mut(&mut self) -> &mut crate::Store {
+ self.store
+ }
+
+ /// Get the module instance.
+ pub fn module(&self) -> &crate::ModuleInstance {
+ self.store.get_module_instance(self.module_id).expect("invalid module instance id in host function context")
+ }
+
+ /// Get a memory export.
+ pub fn memory(&self, name: &str) -> Result<crate::Memory> {
+ self.module().memory(name)
+ }
+
+ /// Get any exported extern value by name.
+ pub fn extern_item(&self, name: &str) -> Result<crate::ExternItem> {
+ self.module().extern_item(name)
+ }
+
+ /// Get a table export.
+ pub fn table(&self, name: &str) -> Result<crate::Table> {
+ self.module().table(name)
+ }
+
+ /// Get the value of a global export.
+ pub fn global_get(&mut self, name: &str) -> Result<WasmValue> {
+ self.module().clone().global_get(self.store, name)
+ }
+
+ /// Get a global export.
+ pub fn global(&self, name: &str) -> Result<crate::Global> {
+ self.module().global(name)
+ }
+
+ /// Set the value of a mutable global export.
+ pub fn global_set(&mut self, name: &str, value: WasmValue) -> Result<()> {
+ self.module().clone().global_set(self.store, name, value)
+ }
+
+ /// Charge additional fuel from the currently running resumable invocation.
+ ///
+ /// This is a no-op when the current invocation is not using fuel-based
+ /// resumption.
+ pub fn charge_fuel(&mut self, fuel: u32) {
+ self.store.execution_fuel = self.store.execution_fuel.saturating_sub(fuel);
+ }
+
+ /// Get remaining fuel for the current invocation.
+ ///
+ /// Returns `0` when fuel-based resumption is not active.
+ pub fn remaining_fuel(&self) -> u32 {
+ self.store.execution_fuel
+ }
+
+ /// Call a function from within the current host-function invocation.
+ ///
+ /// This is the safe way for host functions to perform blocking reentrant
+ /// calls into Wasm. Unlike [`Function::call`], it preserves the active
+ /// invocation's stacks and resumes the host caller after the nested call
+ /// completes.
+ ///
+ /// Nested calls are currently blocking only. If the surrounding invocation
+ /// is resumed with fuel or a time budget, this method does not suspend and
+ /// later continue the host function in the middle of the nested call.
+ pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> {
+ if !self.store.execution_active {
+ return Err(Error::other("FuncContext::call requires an active host-function invocation"));
+ }
+
+ let type_addr = func.validate_call(self.store, args, results.len())?;
+
+ let call_stack_base = self.store.call_stack.len();
+ let value_stack_base = self.store.value_stack.base();
+ self.with_reentrant_call(|store| {
+ func.call_untyped(store, type_addr, args, results, call_stack_base, value_stack_base)
+ })
+ }
+
+ /// Calls a Store-aware function reference in the current module context.
+ pub fn call_ref(&mut self, func: FuncRef, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> {
+ let addr = func.addr(self.store.id()).ok_or(crate::Trap::InvalidStore)?;
+ if !self.store.state.funcs.contains(addr) {
+ return Err(crate::Trap::InvalidReference.into());
+ }
+ let function = Function { item: crate::StoreItem::new(self.store.id(), addr), module_id: self.module_id };
+ self.call_untyped(&function, args, results)
+ }
+
+ /// Call a typed function from within the current host-function invocation.
+ ///
+ /// See [`Self::call_untyped`] for reentrancy and resumable-execution
+ /// limitations.
+ pub fn call<P, R>(&mut self, func: &FunctionTyped<P, R>, params: P) -> Result<R>
+ where
+ P: IntoWasmValues,
+ R: FromWasmValues,
+ {
+ if !self.store.execution_active {
+ return Err(Error::other("FuncContext::call requires an active host-function invocation"));
+ }
+ func.func.item.validate_store(self.store)?;
+ let call_stack_base = self.store.call_stack.len();
+ let value_stack_base = self.store.value_stack.base();
+ self.with_reentrant_call(|store| {
+ func.func.call_typed(store, params.into_wasm_values(), call_stack_base, value_stack_base)
+ })
+ }
+
+ fn with_reentrant_call<R>(&mut self, call: impl FnOnce(&mut crate::Store) -> Result<R>) -> Result<R> {
+ // Each nested executor keeps its current frame on the native stack,
+ // outside CallStack, even when the Wasm function has no params or locals.
+ let config = self.store.engine.config().call_stack;
+ let limit = if config.dynamic { config.max_size } else { config.initial_size };
+ if self.store.reentrant_call_depth >= limit {
+ return Err(crate::Trap::CallStackOverflow.into());
+ }
+ self.store.reentrant_call_depth += 1;
+ let result = call(self.store);
+ self.store.reentrant_call_depth -= 1;
+ result
+ }
+}
+
+impl core::ops::Deref for FuncContext<'_> {
+ type Target = crate::Store;
+
+ fn deref(&self) -> &Self::Target {
+ self.store
+ }
+}
+
+impl core::ops::DerefMut for FuncContext<'_> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.store
+ }
+}
diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs
new file mode 100644
index 0000000..ec81926
--- /dev/null
+++ b/crates/tinywasm/src/func/host.rs
@@ -0,0 +1,300 @@
+use alloc::{boxed::Box, vec::Vec};
+use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType};
+
+use super::{FromWasmValues, FuncContext, IntoWasmValues};
+use crate::shared::StoreShared;
+use crate::store::FuncValueTypes;
+use crate::{Function, Result, Store, WasmValue};
+
+/// Trait bounds required for a host callback in the current build mode.
+#[doc(hidden)]
+#[cfg(not(feature = "send"))]
+pub trait HostFunctionCallback {}
+#[cfg(not(feature = "send"))]
+impl<T: ?Sized> HostFunctionCallback for T {}
+
+/// Trait bounds required for a host callback in the current build mode.
+#[doc(hidden)]
+#[cfg(feature = "send")]
+pub trait HostFunctionCallback: Send + Sync {}
+#[cfg(feature = "send")]
+impl<T: Send + Sync + ?Sized> HostFunctionCallback for T {}
+
+/// A reusable host function definition.
+///
+/// Host functions accept thread-local callback state by default. With the
+/// `send` feature, callbacks must implement `Send + Sync` and host function
+/// definitions can be moved and shared across threads.
+#[derive(Clone)]
+pub struct HostFunction(StoreShared<HostFunctionInner>);
+
+impl HostFunction {
+ /// Instantiates the function with an already registered canonical type.
+ pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function {
+ let addr = store.add_host_func(type_addr, self.clone());
+ Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 }
+ }
+
+ /// Resolves the importing module's types without allocating a function instance.
+ pub(crate) fn resolve_import_type(&self, type_addrs: &[TypeAddr]) -> Result<FuncType> {
+ let mut types = self.0.ty.params().iter().chain(self.0.ty.results());
+ if types.all(|ty| !matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) {
+ return Ok(self.0.ty.clone());
+ }
+ let resolve = |ty: WasmType| -> Result<WasmType> {
+ let WasmType::Ref(ref_ty) = ty else { return Ok(ty) };
+ let Some(module_addr) = ref_ty.type_index() else { return Ok(ty) };
+ let canonical = *type_addrs
+ .get(module_addr as usize)
+ .ok_or_else(|| crate::Error::other("host function signature contains an invalid concrete type"))?;
+ Ok(WasmType::Ref(tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical)))
+ };
+ let params = self.0.ty.params().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?;
+ let results = self.0.ty.results().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?;
+ Ok(FuncType::new(&params, &results))
+ }
+
+ /// Calls the host function through its untyped value interface.
+ pub(crate) fn call_values(
+ &self,
+ store: &mut Store,
+ module_id: ModuleInstanceId,
+ type_addr: TypeAddr,
+ args: &[WasmValue],
+ results: &mut [WasmValue],
+ ) -> Result<()> {
+ {
+ let expected = store.state.get_canonical_func_type(type_addr);
+ if results.len() != expected.results().len() {
+ return Err(crate::Error::other("host result buffer has the wrong length"));
+ }
+ for (result, ty) in results.iter_mut().zip(expected.results()) {
+ *result = match ty {
+ WasmType::I32 => WasmValue::I64(0),
+ _ => WasmValue::I32(0),
+ };
+ }
+ }
+ match &self.0.callback {
+ HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args, results)?,
+ HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args, results)?,
+ }
+ let expected = store.state.get_canonical_func_type(type_addr);
+ if !results.iter().zip(expected.results()).all(|(value, &ty)| store.value_matches_type(value, ty)) {
+ return Err(crate::Error::InvalidHostFnReturn {
+ expected: Box::new(expected.clone()),
+ actual: results.to_vec(),
+ });
+ }
+ Ok(())
+ }
+
+ /// Returns the allocation-free typed callback when one is available.
+ pub(crate) fn typed_callback(&self) -> Option<&dyn TypedHostCallback> {
+ match &self.0.callback {
+ HostCallback::Untyped(_) => None,
+ HostCallback::Typed(func) => Some(&**func),
+ }
+ }
+
+ /// Create a directly callable, store-owned function from this definition.
+ ///
+ /// The returned [`Function`] can only be used with `store`.
+ ///
+ /// Host functions intended as module imports usually do not need to be
+ /// instantiated manually. Pass the reusable definition to
+ /// [`crate::Imports::define`] instead. TinyWasm will then match any GC
+ /// reference types to the module that imports the function.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the signature contains a concrete reference type.
+ /// Define the function through [`crate::Imports`] when concrete types must
+ /// be resolved against an importing module.
+ ///
+ /// ## Example
+ ///
+ /// ```rust
+ /// # fn main() -> tinywasm::Result<()> {
+ /// use tinywasm::types::WasmValue;
+ /// use tinywasm::{HostFunction, Store};
+ ///
+ /// let mut store = Store::default();
+ /// let add_one = HostFunction::from(|_ctx, value: i32| Ok(value + 1));
+ /// let function = add_one.instantiate(&mut store)?;
+ ///
+ /// let mut results = [WasmValue::I32(0)];
+ /// function.call(&mut store, &[WasmValue::I32(41)], &mut results)?;
+ /// assert_eq!(results, [WasmValue::I32(42)]);
+ /// # Ok(())
+ /// # }
+ /// ```
+ pub fn instantiate(&self, store: &mut Store) -> Result<Function> {
+ if self
+ .0
+ .ty
+ .params()
+ .iter()
+ .chain(self.0.ty.results())
+ .any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete()))
+ {
+ return Err(crate::Error::other("standalone host functions cannot use concrete reference types"));
+ }
+ let type_addr = store.register_host_type(&self.0.ty);
+ Ok(self.instantiate_registered(store, type_addr))
+ }
+
+ /// Create a new untyped host function.
+ ///
+ /// To call Wasm from inside the callback, use [`FuncContext::call`] or
+ /// [`FuncContext::call_untyped`].
+ ///
+ /// ## Example
+ /// ```rust
+ /// # fn main() -> tinywasm::Result<()> {
+ /// # use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
+ /// # use tinywasm::types::{FuncType, WasmType, WasmValue};
+ /// # let wasm = wat::parse_str(r#"
+ /// # (module
+ /// # (import "host" "add_one" (func $add_one (param i32) (result i32)))
+ /// # (func (export "call") (param i32) (result i32)
+ /// # local.get 0
+ /// # call $add_one))
+ /// # "#).expect("valid wat");
+ /// # let module = tinywasm::parse_bytes(&wasm)?;
+ /// let mut store = Store::default();
+ /// let ty = FuncType::new(&[WasmType::I32], &[WasmType::I32]);
+ /// let add_one = HostFunction::from_untyped(&ty, |_ctx: FuncContext<'_>, args, results| {
+ /// let WasmValue::I32(value) = args[0] else {
+ /// return Err(tinywasm::Error::Other("expected i32".into()));
+ /// };
+ /// results[0] = WasmValue::I32(value + 1);
+ /// Ok(())
+ /// });
+ ///
+ /// let mut imports = Imports::new();
+ /// imports.define("host", "add_one", add_one);
+ /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ /// # let call = instance.func::<i32, i32>(&store, "call")?;
+ /// # assert_eq!(call.call(&mut store, 41)?, 42);
+ /// # Ok(())
+ /// # }
+ /// ```
+ pub fn from_untyped<F>(ty: &FuncType, func: F) -> Self
+ where
+ F: Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + HostFunctionCallback + 'static,
+ {
+ Self(StoreShared::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) }))
+ }
+
+ /// Create a new typed host function.
+ ///
+ /// To call Wasm from inside the callback, use [`FuncContext::call`] or
+ /// [`FuncContext::call_untyped`].
+ ///
+ /// ## Example
+ /// ```rust
+ /// # fn main() -> tinywasm::Result<()> {
+ /// # use tinywasm::{HostFunction, Imports, ModuleInstance, Store};
+ /// # let wasm = wat::parse_str(r#"
+ /// # (module
+ /// # (import "host" "add_one" (func $add_one (param i32) (result i32)))
+ /// # (func (export "call") (param i32) (result i32)
+ /// # local.get 0
+ /// # call $add_one))
+ /// # "#).expect("valid wat");
+ /// # let module = tinywasm::parse_bytes(&wasm)?;
+ /// let mut store = Store::default();
+ /// let add_one = HostFunction::from(|_ctx, value: i32| Ok(value + 1));
+ ///
+ /// let mut imports = Imports::new();
+ /// imports.define("host", "add_one", add_one);
+ /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ /// # let call = instance.func::<i32, i32>(&store, "call")?;
+ /// # assert_eq!(call.call(&mut store, 41)?, 42);
+ /// # Ok(())
+ /// # }
+ /// ```
+ pub fn from<F, P, R>(func: F) -> Self
+ where
+ F: Fn(FuncContext<'_>, P) -> Result<R> + HostFunctionCallback + 'static,
+ P: FromWasmValues + 'static,
+ R: IntoWasmValues + 'static,
+ {
+ let ty = FuncType::new(P::WASM_TYPES, R::WASM_TYPES);
+ let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData };
+ Self(StoreShared::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) }))
+ }
+}
+
+struct HostFunctionInner {
+ ty: FuncType,
+ callback: HostCallback,
+}
+
+enum HostCallback {
+ Untyped(Box<UntypedHostCallback>),
+ Typed(Box<dyn TypedHostCallback>),
+}
+
+#[cfg(not(feature = "send"))]
+type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()>;
+#[cfg(feature = "send")]
+type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync;
+
+#[cfg(not(feature = "send"))]
+pub(crate) trait TypedHostCallback {
+ fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()>;
+ fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>;
+}
+#[cfg(feature = "send")]
+pub(crate) trait TypedHostCallback: Send + Sync {
+ fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()>;
+ fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>;
+}
+
+struct TypedHostCallbackImpl<F, P, R> {
+ func: F,
+ marker: core::marker::PhantomData<fn(P) -> R>,
+}
+
+impl<F, P, R> TypedHostCallback for TypedHostCallbackImpl<F, P, R>
+where
+ F: Fn(FuncContext<'_>, P) -> Result<R> + HostFunctionCallback,
+ P: FromWasmValues,
+ R: IntoWasmValues,
+{
+ fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> {
+ let mut values = args.iter().cloned();
+ let params = cold_err!(P::from_wasm_values(&mut values))?;
+ let mut values = (self.func)(ctx, params)?.into_wasm_values();
+ for result in results {
+ *result = cold_err!(values.next().ok_or_else(|| crate::Error::other("not enough typed function results")))?;
+ }
+ if values.next().is_some() {
+ return cold!(Err(crate::Error::other("too many typed function results")));
+ }
+ Ok(())
+ }
+
+ fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()> {
+ let base = {
+ let params = store.state.get_canonical_func_type(type_addr).params();
+ store.value_stack.base_before(params.iter().collect())
+ };
+ let params = {
+ let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?;
+ cold_err!(P::from_wasm_values(&mut values))
+ };
+ store.value_stack.truncate_to_base(base);
+ let result = cold_err!((self.func)(FuncContext { store, module_id }, params?))?;
+ store.push_typed_values::<true>(type_addr, result.into_wasm_values(), base)
+ }
+}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for HostFunction {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_struct("HostFunction").field("ty", &self.0.ty).finish_non_exhaustive()
+ }
+}
diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs
new file mode 100644
index 0000000..cf3c855
--- /dev/null
+++ b/crates/tinywasm/src/func/mod.rs
@@ -0,0 +1,256 @@
+use crate::interpreter::stack::{CallFrame, StackBase};
+use crate::reference::StoreItem;
+use crate::{Error, InterpreterRuntime, Result, Store};
+use alloc::format;
+use core::hint::cold_path;
+use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId};
+
+use crate::{FuncRef, WasmValue};
+
+mod context;
+mod host;
+mod resume;
+mod values;
+pub use context::FuncContext;
+pub use host::HostFunction;
+#[doc(hidden)]
+pub use host::HostFunctionCallback;
+pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped};
+pub use values::{FromWasmValues, IntoWasmValues, WasmTypes, WasmValueType};
+
+fn write_typed_params(params: &mut [WasmValue], mut values: impl Iterator<Item = WasmValue>) -> Result<()> {
+ for param in params {
+ *param = values.next().ok_or_else(|| Error::other("not enough typed function parameters"))?;
+ }
+ if values.next().is_some() {
+ return Err(Error::other("too many typed function parameters"));
+ }
+ Ok(())
+}
+
+/// A handle to a function instance in a store.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#function-instances>
+#[derive(Clone)]
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+pub struct Function {
+ pub(crate) item: StoreItem,
+ pub(crate) module_id: ModuleInstanceId,
+}
+
+impl Function {
+ /// Resolves a function reference into a callable handle in its owning store.
+ ///
+ /// Returns an error if the reference belongs to another store or does not
+ /// identify a valid function.
+ pub fn from_func_ref(store: &Store, reference: FuncRef) -> Result<Self> {
+ let addr = reference.addr(store.id()).ok_or(crate::Trap::InvalidStore)?;
+ if !store.state.funcs.contains(addr) {
+ return Err(crate::Trap::InvalidReference.into());
+ }
+ let module_id = if store.state.funcs.is_host(addr) { 0 } else { store.state.funcs.wasm(addr).owner };
+ Ok(Self { item: StoreItem::new(store.id(), addr), module_id })
+ }
+
+ /// Returns this function as a Store-aware WebAssembly function reference.
+ pub fn as_func_ref(&self, store: &Store) -> Result<FuncRef> {
+ self.item.validate_store(store)?;
+ Ok(FuncRef::new(store.id(), self.addr()))
+ }
+
+ #[inline]
+ /// Returns the function's address in its store.
+ pub(crate) const fn addr(&self) -> FuncAddr {
+ self.item.addr
+ }
+
+ /// Get this function's canonical type from its store.
+ ///
+ /// Concrete reference types are only meaningful in this store.
+ pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> {
+ self.item.validate_store(store)?;
+ Ok(store.state.get_func_type(self.addr()))
+ }
+
+ /// Calls the function and writes its results to `results`.
+ ///
+ /// The initial result values are ignored. The result slice length must
+ /// match the function signature.
+ #[inline]
+ pub fn call(&self, store: &mut Store, params: &[WasmValue], results: &mut [WasmValue]) -> Result<()> {
+ let type_addr = self.validate_call(store, params, results.len())?;
+
+ store.enter_execution()?;
+ store.call_stack.clear();
+ store.value_stack.clear();
+ let result = self.call_untyped(store, type_addr, params, results, 0, StackBase::default());
+ store.exit_execution();
+ result
+ }
+
+ fn validate_call(
+ &self,
+ store: &Store,
+ params: &[WasmValue],
+ result_count: usize,
+ ) -> Result<tinywasm_types::TypeAddr> {
+ self.item.validate_store(store)?;
+ let type_addr = store.state.funcs.type_addr(self.addr());
+ self.validate_call_type(store, type_addr, params, result_count)?;
+ Ok(type_addr)
+ }
+
+ fn validate_call_type(
+ &self,
+ store: &Store,
+ type_addr: tinywasm_types::TypeAddr,
+ params: &[WasmValue],
+ result_count: usize,
+ ) -> Result<()> {
+ let func_ty = store.state.get_canonical_func_type(type_addr);
+ if func_ty.params().len() != params.len() {
+ cold_path();
+ return Err(Error::Other(format!(
+ "param count mismatch: expected {}, got {}",
+ func_ty.params().len(),
+ params.len()
+ )));
+ }
+
+ for param in params {
+ if matches!(param, WasmValue::Ref(_)) {
+ param.to_runtime(store)?;
+ }
+ }
+
+ if !func_ty.params().iter().zip(params).all(|(ty, param)| store.value_matches_type(param, *ty)) {
+ cold_path();
+ #[cfg(feature = "debug")]
+ return Err(Error::Other(format!(
+ "param type mismatch: expected {:?}, got {:?}",
+ func_ty.params(),
+ params.iter().map(|v| v.ty()).collect::<alloc::vec::Vec<_>>()
+ )));
+ #[cfg(not(feature = "debug"))]
+ return Err(Error::Other("param type mismatch".into()));
+ }
+ if func_ty.results().len() != result_count {
+ return Err(Error::Other(format!(
+ "result count mismatch: expected {}, got {result_count}",
+ func_ty.results().len()
+ )));
+ }
+ Ok(())
+ }
+
+ #[inline]
+ fn call_untyped(
+ &self,
+ store: &mut Store,
+ type_addr: tinywasm_types::TypeAddr,
+ params: &[WasmValue],
+ results: &mut [WasmValue],
+ call_stack_base: u32,
+ value_stack_base: StackBase,
+ ) -> Result<()> {
+ if store.state.funcs.is_host(self.addr()) {
+ let host = store.state.funcs.host(self.addr()).func.clone();
+ host.call_values(store, self.module_id, type_addr, params, results)
+ } else {
+ let (wasm_params, wasm_locals) = {
+ let wasm = store.state.funcs.wasm(self.addr());
+ let wasm_params = wasm.func.params;
+ let wasm_locals = wasm.func.locals;
+ (wasm_params, wasm_locals)
+ };
+ store.push_wasm_values(params).inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?;
+ let locals_base = store
+ .value_stack
+ .enter_locals(&wasm_params, &wasm_locals)
+ .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?;
+ let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals);
+ InterpreterRuntime::exec(store, callframe, call_stack_base).inspect_err(|_| {
+ store.call_stack.truncate_to(call_stack_base);
+ store.value_stack.truncate_to_base(value_stack_base);
+ })?;
+ store.pop_stack_values(type_addr, results)
+ }
+ }
+
+ #[inline]
+ fn call_typed<R: FromWasmValues>(
+ &self,
+ store: &mut Store,
+ params: impl Iterator<Item = WasmValue>,
+ call_stack_base: u32,
+ value_stack_base: StackBase,
+ ) -> Result<R> {
+ if store.state.funcs.is_host(self.addr()) {
+ let (type_addr, host) = {
+ let host = store.state.funcs.host(self.addr());
+ (host.type_addr, host.func.clone())
+ };
+ return match host.typed_callback() {
+ Some(callback) => {
+ store.push_typed_values::<false>(type_addr, params, value_stack_base)?;
+ callback
+ .call_stack(store, self.module_id, type_addr)
+ .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?;
+ store.take_typed_results(type_addr, value_stack_base)
+ }
+ None => {
+ let ty = store.state.get_canonical_func_type(type_addr);
+ let (param_count, result_count) = (ty.params().len(), ty.results().len());
+ store.with_scratch_values(param_count + result_count, |store, values| {
+ write_typed_params(&mut values[..param_count], params)?;
+ let (params, results) = values.split_at_mut(param_count);
+ self.validate_call_type(store, type_addr, params, results.len())?;
+ host.call_values(store, self.module_id, type_addr, params, results)?;
+ values.drain(..param_count);
+ R::from_wasm_values(&mut values.drain(..))
+ })
+ }
+ };
+ }
+
+ let (type_addr, wasm_params, wasm_locals) = {
+ let wasm = store.state.funcs.wasm(self.addr());
+ (wasm.type_addr, wasm.func.params, wasm.func.locals)
+ };
+ store.push_typed_values::<false>(type_addr, params, value_stack_base)?;
+ let locals_base = store
+ .value_stack
+ .enter_locals(&wasm_params, &wasm_locals)
+ .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?;
+ let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals);
+ InterpreterRuntime::exec(store, callframe, call_stack_base).inspect_err(|_| {
+ store.call_stack.truncate_to(call_stack_base);
+ store.value_stack.truncate_to_base(value_stack_base);
+ })?;
+ store.take_typed_results(type_addr, value_stack_base)
+ }
+}
+
+/// A typed function handle.
+///
+/// Parameter and result tuples are supported up to arity 20. Use
+/// [`crate::ModuleInstance::func_untyped`] for larger signatures.
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+pub struct FunctionTyped<P, R> {
+ /// The underlying function handle
+ pub func: Function,
+ pub(crate) marker: core::marker::PhantomData<(P, R)>,
+}
+
+impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> {
+ /// Call a typed function
+ pub fn call(&self, store: &mut Store, params: P) -> Result<R> {
+ self.func.item.validate_store(store)?;
+ store.enter_execution()?;
+ store.call_stack.clear();
+ store.value_stack.clear();
+ let result = self.func.call_typed(store, params.into_wasm_values(), 0, StackBase::default());
+ store.exit_execution();
+ result
+ }
+}
diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs
new file mode 100644
index 0000000..a035ffc
--- /dev/null
+++ b/crates/tinywasm/src/func/resume.rs
@@ -0,0 +1,280 @@
+use tinywasm_types::{FuncAddr, TypeAddr};
+
+use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues};
+use crate::interpreter::stack::{CallFrame, StackBase};
+use crate::{Error, InterpreterRuntime, Result, Store, WasmValue};
+
+#[derive(Clone, PartialEq, Eq)]
+/// Progress for fuel-limited function execution.
+pub enum ExecProgress<T> {
+ /// Execution completed and produced a result.
+ Completed(T),
+ /// Execution suspended after exhausting fuel or time budget.
+ Suspended,
+}
+
+/// Resumable execution for an untyped function call.
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+pub struct FuncExecution<'store> {
+ execution: ExecutionInner<'store>,
+ results: &'store mut [WasmValue],
+}
+
+/// Resumable execution for a typed function call.
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+pub struct FuncExecutionTyped<'store, R> {
+ execution: ExecutionInner<'store>,
+ result: Option<R>,
+}
+
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+struct ExecutionInner<'store> {
+ store: &'store mut Store,
+ state: ExecState,
+}
+
+impl Drop for ExecutionInner<'_> {
+ fn drop(&mut self) {
+ if matches!(self.state, ExecState::Running { .. }) {
+ self.store.call_stack.clear();
+ self.store.value_stack.clear();
+ }
+ }
+}
+
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+enum ExecState {
+ Running { callframe: CallFrame, root_func_addr: FuncAddr },
+ Completed(Option<CallResult>),
+}
+
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
+enum CallResult {
+ Stack { type_addr: TypeAddr },
+ Written,
+}
+
+impl Function {
+ /// Call a function and return a resumable execution handle.
+ ///
+ /// The returned handle keeps a mutable borrow of the [`Store`] until it
+ /// completes. Use [`FuncExecution::resume_with_fuel`] (or
+ /// `resume_with_time_budget` with `std`) to continue.
+ pub fn call_resumable<'store>(
+ &self,
+ store: &'store mut Store,
+ params: &[WasmValue],
+ results: &'store mut [WasmValue],
+ ) -> Result<FuncExecution<'store>> {
+ let type_addr = self.validate_call(store, params, results.len())?;
+
+ store.enter_execution()?;
+ let result: Result<ExecState> = (|| {
+ if store.state.funcs.is_host(self.addr()) {
+ let func = {
+ let func = store.state.funcs.host(self.addr());
+ func.func.clone()
+ };
+ func.call_values(store, self.module_id, type_addr, params, results)?;
+ return Ok(ExecState::Completed(Some(CallResult::Written)));
+ }
+
+ let (wasm_params, wasm_locals) = {
+ let wasm = store.state.funcs.wasm(self.addr());
+ (wasm.func.params, wasm.func.locals)
+ };
+
+ store.call_stack.clear();
+ store.value_stack.clear();
+ store.push_wasm_values(params)?;
+ let locals_base = store.value_stack.enter_locals(&wasm_params, &wasm_locals)?;
+ let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals);
+
+ Ok(ExecState::Running { callframe, root_func_addr: self.addr() })
+ })();
+ if result.is_err() {
+ store.call_stack.clear();
+ store.value_stack.clear();
+ }
+ store.exit_execution();
+
+ let state = result?;
+ Ok(FuncExecution { execution: ExecutionInner { store, state }, results })
+ }
+}
+
+impl ExecutionInner<'_> {
+ fn resume_raw(
+ &mut self,
+ run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>,
+ ) -> Result<ExecProgress<CallResult>> {
+ let (callframe, root_func_addr) = match &mut self.state {
+ ExecState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr),
+ ExecState::Completed(result) => {
+ return result
+ .take()
+ .map(ExecProgress::Completed)
+ .ok_or_else(|| Error::other("execution already completed"));
+ }
+ };
+
+ self.store.enter_execution()?;
+ let result = run(self.store, callframe);
+ self.store.exit_execution();
+
+ let result = match result {
+ Ok(result) => result,
+ Err(error) => {
+ self.store.call_stack.clear();
+ self.store.value_stack.clear();
+ self.state = ExecState::Completed(None);
+ return Err(error);
+ }
+ };
+
+ match result {
+ crate::interpreter::ExecState::Completed => {
+ let result_ty = self.store.state.funcs.type_addr(root_func_addr);
+ self.state = ExecState::Completed(None);
+ Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty }))
+ }
+ crate::interpreter::ExecState::Suspended(callframe) => {
+ let ExecState::Running { callframe: current, .. } = &mut self.state else {
+ unreachable!("invalid function execution state")
+ };
+ *current = callframe;
+ Ok(ExecProgress::Suspended)
+ }
+ }
+ }
+}
+
+impl FuncExecution<'_> {
+ fn resume(
+ &mut self,
+ run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>,
+ ) -> Result<ExecProgress<()>> {
+ match self.execution.resume_raw(run)? {
+ ExecProgress::Completed(CallResult::Stack { type_addr }) => {
+ self.execution.store.pop_stack_values(type_addr, self.results)?;
+ Ok(ExecProgress::Completed(()))
+ }
+ ExecProgress::Completed(CallResult::Written) => Ok(ExecProgress::Completed(())),
+ ExecProgress::Suspended => Ok(ExecProgress::Suspended),
+ }
+ }
+
+ /// Resume execution with up to `fuel` units of fuel.
+ ///
+ /// Fuel is accounted in chunks, so execution may overshoot the requested
+ /// fuel before returning [`ExecProgress::Suspended`] (currently the chunk size is 128 instructions between fuel checks, but this may change in the future).
+ ///
+ /// Returns [`ExecProgress::Suspended`] when fuel is exhausted, or
+ /// [`ExecProgress::Completed`] after writing the final values to the result
+ /// slice supplied to [`Function::call_resumable`].
+ ///
+ /// Reentrant calls made by host functions through [`crate::FuncContext::call`] are
+ /// currently blocking. They do not suspend and later resume the host
+ /// function in the middle of the nested call.
+ pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<()>> {
+ self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel))
+ }
+
+ #[cfg(feature = "std")]
+ /// Resume execution for at most `time_budget` wall-clock time.
+ ///
+ /// Time is checked periodically, so execution may overshoot the requested
+ /// time budget before returning [`ExecProgress::Suspended`] (currently time
+ /// is checked every 128 instructions, but this may change in the future).
+ ///
+ /// Reentrant calls made by host functions through [`crate::FuncContext::call`]
+ /// are blocking and do not suspend in the middle of the host callback.
+ pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result<ExecProgress<()>> {
+ self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget))
+ }
+}
+
+impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> {
+ /// Call a typed function and return a resumable execution handle.
+ ///
+ /// The handle keeps a mutable borrow of the [`Store`] until completion.
+ ///
+ /// ## Example
+ ///
+ /// ```rust
+ /// # fn main() -> tinywasm::Result<()> {
+ /// use tinywasm::{ExecProgress, ModuleInstance, Store};
+ ///
+ /// let wasm = include_bytes!("../../../../examples/wasm/add.wasm");
+ /// let module = tinywasm::parse_bytes(wasm)?;
+ /// let mut store = Store::default();
+ /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ /// let add = instance.func::<(i32, i32), i32>(&store, "add")?;
+ ///
+ /// let mut execution = add.call_resumable(&mut store, (20, 22))?;
+ /// assert!(matches!(execution.resume_with_fuel(0)?, ExecProgress::Suspended));
+ /// assert!(matches!(execution.resume_with_fuel(16)?, ExecProgress::Completed(42)));
+ /// # Ok(())
+ /// # }
+ /// ```
+ pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result<FuncExecutionTyped<'store, R>> {
+ self.func.item.validate_store(store)?;
+ if store.state.funcs.is_host(self.func.addr()) {
+ let result = self.call(store, params)?;
+ let execution = ExecutionInner { store, state: ExecState::Completed(None) };
+ return Ok(FuncExecutionTyped { execution, result: Some(result) });
+ }
+ let (type_addr, wasm_params, wasm_locals) = {
+ let wasm = store.state.funcs.wasm(self.func.addr());
+ (wasm.type_addr, wasm.func.params, wasm.func.locals)
+ };
+
+ store.enter_execution()?;
+ let result: Result<ExecState> = (|| {
+ store.call_stack.clear();
+ store.value_stack.clear();
+ store.push_typed_values::<false>(type_addr, params.into_wasm_values(), StackBase::default())?;
+ let locals_base = store
+ .value_stack
+ .enter_locals(&wasm_params, &wasm_locals)
+ .inspect_err(|_| store.value_stack.clear())?;
+ let callframe = CallFrame::new(self.func.addr(), locals_base, wasm_locals);
+ Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() })
+ })();
+ store.exit_execution();
+ let execution = ExecutionInner { store, state: result? };
+ Ok(FuncExecutionTyped { execution, result: None })
+ }
+}
+
+impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> {
+ fn resume(
+ &mut self,
+ run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>,
+ ) -> Result<ExecProgress<R>> {
+ if let Some(result) = self.result.take() {
+ return Ok(ExecProgress::Completed(result));
+ }
+ match self.execution.resume_raw(run)? {
+ ExecProgress::Completed(CallResult::Stack { type_addr }) => {
+ Ok(ExecProgress::Completed(self.execution.store.take_typed_results(type_addr, StackBase::default())?))
+ }
+ ExecProgress::Completed(CallResult::Written) => unreachable!("untyped result in typed execution"),
+ ExecProgress::Suspended => Ok(ExecProgress::Suspended),
+ }
+ }
+
+ /// Resume typed execution with up to `fuel` units of fuel.
+ pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<R>> {
+ self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel))
+ }
+
+ #[cfg(feature = "std")]
+ /// Resume typed execution for at most `time_budget` wall-clock time.
+ ///
+ /// Time is checked periodically, so execution may overshoot the requested
+ /// time budget before returning [`ExecProgress::Suspended`].
+ pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result<ExecProgress<R>> {
+ self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget))
+ }
+}
diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs
new file mode 100644
index 0000000..11d3b17
--- /dev/null
+++ b/crates/tinywasm/src/func/values.rs
@@ -0,0 +1,155 @@
+use crate::{Error, Result};
+use tinywasm_types::WasmType;
+
+use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, StructRef, WasmValue};
+
+/// Describes the WebAssembly value types produced by a Rust value or tuple shape.
+pub trait WasmTypes {
+ /// Flattened WebAssembly value types for this shape.
+ const WASM_TYPES: &'static [WasmType];
+}
+
+/// Describes the WebAssembly value types produced by a scalar Rust type.
+pub trait WasmValueType {
+ /// The single WebAssembly value type for this scalar type.
+ const WASM_TYPE: WasmType;
+}
+
+/// Convert a Rust value or tuple into WebAssembly values.
+pub trait IntoWasmValues: WasmTypes {
+ /// Return the flattened WebAssembly values.
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue>;
+}
+
+/// Convert WebAssembly values into a Rust value or tuple.
+pub trait FromWasmValues: WasmTypes + Sized {
+ /// Read this value and reject unconsumed WebAssembly values.
+ fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self>;
+}
+
+fn next_value<T: TryFrom<WasmValue, Error = ()>>(values: &mut impl Iterator<Item = WasmValue>) -> Result<T> {
+ let value = cold_err!(values.next().ok_or_else(|| { Error::other("not enough WebAssembly values") }))?;
+ cold_err!(T::try_from(value).map_err(|_| { Error::other("WebAssembly value does not match the expected type") }))
+}
+
+fn finish_values<T>(result: T, values: &mut impl Iterator<Item = WasmValue>) -> Result<T> {
+ if values.next().is_some() {
+ return cold!(Err(Error::other("typed conversion did not consume all WebAssembly values")));
+ }
+ Ok(result)
+}
+
+macro_rules! impl_scalar_wasm_traits {
+ ($($T:ty => $val_ty:expr),+ $(,)?) => {
+ $(
+ impl WasmValueType for $T {
+ const WASM_TYPE: WasmType = $val_ty;
+ }
+
+ impl WasmTypes for $T {
+ const WASM_TYPES: &'static [WasmType] = &[$val_ty];
+ }
+
+ impl IntoWasmValues for $T {
+ #[inline]
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> {
+ core::iter::once(self.into())
+ }
+ }
+
+ impl FromWasmValues for $T {
+ #[inline]
+ fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> {
+ let result = next_value(values)?;
+ finish_values(result, values)
+ }
+ }
+ )+
+ };
+}
+
+macro_rules! impl_tuple_traits {
+ (@next $head:ident, $($tail:ident),+) => {
+ impl_tuple_traits!($($tail),+);
+ };
+ (@next $head:ident) => {};
+ ($($T:ident),+) => {
+ impl<$($T),+> WasmTypes for ($($T,)+)
+ where
+ $($T: WasmValueType,)+
+ {
+ const WASM_TYPES: &'static [WasmType] = &[$($T::WASM_TYPE,)+];
+ }
+
+ impl<$($T),+> IntoWasmValues for ($($T,)+)
+ where
+ $($T: Into<WasmValue> + WasmValueType,)+
+ {
+ #[allow(non_snake_case)]
+ #[inline]
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> {
+ let ($($T,)+) = self;
+ [$($T.into(),)+].into_iter()
+ }
+ }
+
+ impl<$($T),+> FromWasmValues for ($($T,)+)
+ where
+ $($T: TryFrom<WasmValue, Error = ()> + WasmValueType,)+
+ {
+ #[inline]
+ fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> {
+ let result = ($(next_value::<$T>(values)?,)+);
+ finish_values(result, values)
+ }
+ }
+
+ impl_tuple_traits!(@next $($T),+);
+ }
+}
+
+impl_scalar_wasm_traits!(
+ i32 => WasmType::I32,
+ i64 => WasmType::I64,
+ f32 => WasmType::F32,
+ f64 => WasmType::F64,
+ [u8; 16] => WasmType::V128,
+ FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF.with_nullability(false)),
+ AnyRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Any)),
+ EqRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Eq)),
+ I31Ref => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::I31)),
+ StructRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Struct)),
+ ArrayRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Array)),
+ ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF.with_nullability(false)),
+ ExnRef => WasmType::Ref(tinywasm_types::RefType::EXNREF.with_nullability(false)),
+);
+
+impl_scalar_wasm_traits!(
+ Option<FuncRef> => WasmType::Ref(tinywasm_types::RefType::FUNCREF),
+ Option<AnyRef> => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Any)),
+ Option<EqRef> => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Eq)),
+ Option<I31Ref> => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::I31)),
+ Option<StructRef> => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Struct)),
+ Option<ArrayRef> => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Array)),
+ Option<ExternRef> => WasmType::Ref(tinywasm_types::RefType::EXTERNREF),
+ Option<ExnRef> => WasmType::Ref(tinywasm_types::RefType::EXNREF),
+);
+impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20);
+
+impl WasmTypes for () {
+ const WASM_TYPES: &'static [WasmType] = &[];
+}
+
+impl IntoWasmValues for () {
+ #[inline]
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> {
+ core::iter::empty()
+ }
+}
+
+impl FromWasmValues for () {
+ #[inline]
+ fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> {
+ finish_values((), values)
+ }
+}
diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs
index 887d107..49234e6 100644
--- a/crates/tinywasm/src/imports.rs
+++ b/crates/tinywasm/src/imports.rs
@@ -1,14 +1,12 @@
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
-use core::fmt::Debug;
-use core::hint::cold_path;
-use crate::{Function, Global, LinkingError, Memory, Result, Table};
+use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag};
use tinywasm_types::*;
#[derive(Clone)]
-#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "debug", derive(core::fmt::Debug))]
#[non_exhaustive]
/// An external import value.
pub enum Extern {
@@ -20,43 +18,31 @@ pub enum Extern {
Memory(Memory),
/// A function import.
Function(Function),
+ /// A reusable host function definition.
+ HostFunction(HostFunction),
+ /// A tag instance.
+ Tag(Tag),
}
-impl From<Global> for Extern {
- fn from(value: Global) -> Self {
- Self::Global(value)
- }
-}
-
-impl From<Table> for Extern {
- fn from(value: Table) -> Self {
- Self::Table(value)
- }
-}
-
-impl From<Memory> for Extern {
- fn from(value: Memory) -> Self {
- Self::Memory(value)
- }
-}
-
-impl From<Function> for Extern {
- fn from(value: Function) -> Self {
- Self::Function(value)
- }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
-/// Name of an import
-pub struct ExternName {
- module: String,
- name: String,
+macro_rules! impl_conv {
+ ($($ty:ty => $variant:ident),* $(,)?) => {
+ $(
+ impl From<$ty> for Extern {
+ fn from(value: $ty) -> Self {
+ Self::$variant(value)
+ }
+ }
+ )*
+ };
}
-impl From<&Import> for ExternName {
- fn from(import: &Import) -> Self {
- Self { module: import.module.to_string(), name: import.name.to_string() }
- }
+impl_conv! {
+ Global => Global,
+ Table => Table,
+ Memory => Memory,
+ Function => Function,
+ HostFunction => HostFunction,
+ Tag => Tag,
}
/// Imports for a module instance
@@ -75,22 +61,25 @@ impl From<&Import> for ExternName {
/// # let my_other_instance = ModuleInstance::instantiate(&mut store, &module, None)?;
/// let mut imports = Imports::new();
///
-/// let print_i32 = HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, arg: i32| {
+/// let print_i32 = HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, arg: i32| {
/// log::debug!("print_i32: {}", arg);
/// Ok(())
/// });
///
-/// let table = Table::new(
+/// let table = Table::try_new(
/// &mut store,
/// TableType::new(tinywasm::types::RefType::FUNCREF, 10, Some(20)),
/// tinywasm::types::RefValue::Null.into(),
/// )?;
-/// let memory = Memory::new(
+/// let memory = Memory::try_new(
/// &mut store,
/// MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)),
/// )?;
-/// let global_i32 =
-/// Global::new(&mut store, GlobalType::default().with_ty(WasmType::I32), WasmValue::I32(666))?;
+/// let global_i32 = Global::try_new(
+/// &mut store,
+/// GlobalType::default().with_ty(WasmType::I32),
+/// WasmValue::I32(666),
+/// )?;
///
/// imports
/// .define("my_module", "print_i32", print_i32)
@@ -101,11 +90,13 @@ impl From<&Import> for ExternName {
/// # Ok(())
/// # }
/// ```
-/// Now, the imports object can be passed to [`crate::ModuleInstance::instantiate`].
+/// Host function definitions are store-independent, so the imports object can be borrowed by
+/// [`crate::ModuleInstance::instantiate`] for multiple stores.
+/// TinyWasm also matches GC reference types to each module when it links an imported host function.
#[derive(Default, Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Imports {
- externs: BTreeMap<ExternName, Extern>,
+ externs: BTreeMap<String, BTreeMap<String, Extern>>,
modules: BTreeMap<String, crate::ModuleInstance>,
}
@@ -114,6 +105,7 @@ pub(crate) struct ResolvedImports {
pub(crate) tables: Vec<TableAddr>,
pub(crate) memories: Vec<MemAddr>,
pub(crate) funcs: Vec<FuncAddr>,
+ pub(crate) tags: Vec<TagAddr>,
}
impl Imports {
@@ -124,7 +116,9 @@ impl Imports {
/// Merge two import sets
pub fn merge(mut self, other: Self) -> Self {
- self.externs.extend(other.externs);
+ for (module, externs) in other.externs {
+ self.externs.entry(module).or_default().extend(externs);
+ }
self.modules.extend(other.modules);
self
}
@@ -138,65 +132,90 @@ impl Imports {
}
/// Define an import value.
+ ///
+ /// A [`Function`], [`Global`], [`Table`], [`Memory`], or [`Tag`] handle belongs to
+ /// one store and can only be imported into that store. A [`HostFunction`]
+ /// is a reusable definition and can be imported into multiple stores.
+ ///
+ /// ## Example
+ ///
+ /// ```rust
+ /// # fn main() -> tinywasm::Result<()> {
+ /// use tinywasm::{HostFunction, Imports, ModuleInstance, Store};
+ ///
+ /// let wasm = wat::parse_str(
+ /// r#"
+ /// (module
+ /// (import "host" "answer" (func $answer (result i32)))
+ /// (export "answer" (func $answer)))
+ /// "#,
+ /// )
+ /// .expect("valid wat");
+ /// let module = tinywasm::parse_bytes(&wasm)?;
+ /// let mut imports = Imports::new();
+ /// imports.define("host", "answer", HostFunction::from(|_ctx, ()| Ok(42_i32)));
+ ///
+ /// let mut first_store = Store::default();
+ /// let first = ModuleInstance::instantiate(&mut first_store, &module, Some(&imports))?;
+ /// assert_eq!(first.func::<(), i32>(&first_store, "answer")?.call(&mut first_store, ())?, 42);
+ ///
+ /// let mut second_store = Store::default();
+ /// let second = ModuleInstance::instantiate(&mut second_store, &module, Some(&imports))?;
+ /// assert_eq!(second.func::<(), i32>(&second_store, "answer")?.call(&mut second_store, ())?, 42);
+ /// # Ok(())
+ /// # }
+ /// ```
pub fn define(&mut self, module: &str, name: &str, value: impl Into<Extern>) -> &mut Self {
- let name = ExternName { module: module.to_string(), name: name.to_string() };
- self.externs.insert(name, value.into());
+ self.externs.entry(module.to_string()).or_default().insert(name.to_string(), value.into());
self
}
- pub(crate) fn take_defined(&self, import: &Import) -> Option<Extern> {
- let name = ExternName::from(import);
- self.externs.get(&name).cloned()
+ /// Resolves names in module import order, with explicit definitions taking precedence.
+ pub(crate) fn resolve(&self, module: &Module) -> Result<Vec<Extern>> {
+ module
+ .imports
+ .iter()
+ .map(|import| {
+ if let Some(value) =
+ self.externs.get(import.module.as_ref()).and_then(|items| items.get(import.name.as_ref()))
+ {
+ return Ok(value.clone());
+ }
+ let instance =
+ self.modules.get(import.module.as_ref()).ok_or_else(|| LinkingError::unknown_import(import))?;
+ let item = instance.extern_item(&import.name).map_err(|_| LinkingError::unknown_import(import))?;
+ Ok(match item {
+ crate::ExternItem::Func(value) => Extern::Function(value),
+ crate::ExternItem::Global(value) => Extern::Global(value),
+ crate::ExternItem::Memory(value) => Extern::Memory(value),
+ crate::ExternItem::Table(value) => Extern::Table(value),
+ crate::ExternItem::Tag(value) => Extern::Tag(value),
+ })
+ })
+ .collect()
}
+}
+impl ResolvedImports {
fn compare_types<T: PartialEq>(import: &Import, actual: &T, expected: &T) -> Result<()> {
if expected != actual {
- cold_path();
- return Err(LinkingError::incompatible_import_type(import).into());
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
}
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 {
- cold_path();
- return Err(LinkingError::incompatible_import_type(import).into());
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
}
match expected.size_max {
Some(expected_max) if actual.size_max.is_none_or(|actual_max| actual_max > expected_max) => {
- cold_path();
- Err(LinkingError::incompatible_import_type(import).into())
+ cold!(Err(LinkingError::incompatible_import_type(import).into()))
}
_ => Ok(()),
}
@@ -226,18 +245,23 @@ impl Imports {
Ok(())
}
- pub(crate) fn link(
- &self,
+ /// Validates and binds imports in module import order.
+ pub(crate) fn new(
store: &mut crate::Store,
module: &Module,
type_addrs: &[TypeAddr],
+ externs: &[Extern],
) -> Result<ResolvedImports> {
- let (global_count, table_count, mem_count, func_count) =
- module.imports.iter().fold((0, 0, 0, 0), |(g, t, m, f), import| match import.kind {
- ImportKind::Global(_) => (g + 1, t, m, f),
- ImportKind::Table(_) => (g, t + 1, m, f),
- ImportKind::Memory(_) => (g, t, m + 1, f),
- ImportKind::Function(_) => (g, t, m, f + 1),
+ if externs.len() != module.imports.len() {
+ return Err(crate::Error::other("ordered import count does not match module"));
+ }
+ let (global_count, table_count, mem_count, func_count, tag_count) =
+ module.imports.iter().fold((0, 0, 0, 0, 0), |(g, t, m, f, e), import| match import.kind {
+ ImportKind::Global(_) => (g + 1, t, m, f, e),
+ ImportKind::Table(_) => (g, t + 1, m, f, e),
+ ImportKind::Memory(_) => (g, t, m + 1, f, e),
+ ImportKind::Function(_) => (g, t, m, f + 1, e),
+ ImportKind::Tag(_) => (g, t, m, f, e + 1),
});
let mut imports = ResolvedImports {
@@ -245,41 +269,60 @@ impl Imports {
tables: Vec::with_capacity(table_count + module.tables.len()),
memories: Vec::with_capacity(mem_count + module.memory_types.len()),
funcs: Vec::with_capacity(func_count + module.funcs.len()),
+ tags: Vec::with_capacity(tag_count + module.tags.len()),
};
- for import in &*module.imports {
- let (val, func_handle) = if let Some(defined) = self.take_defined(import) {
- match defined {
- Extern::Global(global) => (ExternVal::Global(global.0.addr), None),
- Extern::Table(table) => (ExternVal::Table(table.0.addr), None),
- Extern::Memory(memory) => (ExternVal::Memory(memory.0.addr), None),
- Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)),
+ for (import, defined) in module.imports.iter().zip(externs) {
+ let val = match defined {
+ Extern::Global(global) => {
+ global.0.validate_store(store)?;
+ ExternVal::Global(global.0.addr)
+ }
+ Extern::Table(table) => {
+ table.0.validate_store(store)?;
+ ExternVal::Table(table.0.addr)
+ }
+ Extern::Memory(memory) => {
+ memory.0.validate_store(store)?;
+ ExternVal::Memory(memory.0.addr)
+ }
+ Extern::Function(func) => {
+ func.item.validate_store(store)?;
+ ExternVal::Func(func.addr())
+ }
+ Extern::HostFunction(func) => {
+ let ImportKind::Function(type_idx) = import.kind else {
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
+ };
+ let expected_type_addr = type_addrs
+ .get(type_idx as usize)
+ .ok_or_else(|| LinkingError::incompatible_import_type(import))?;
+ let actual_ty = func.resolve_import_type(type_addrs)?;
+ let actual_type_addr = store.register_host_type(&actual_ty);
+ if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) {
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
+ }
+ ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr())
+ }
+ Extern::Tag(tag) => {
+ tag.0.validate_store(store)?;
+ ExternVal::Tag(tag.0.addr)
}
- } else {
- let name = ExternName::from(import);
- let Some(instance) = self.modules.get(&name.module) else {
- cold_path();
- return Err(LinkingError::unknown_import(import).into());
- };
- instance.validate_store(store)?;
- (instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))?, None)
};
if val.kind() != (&import.kind).into() {
- cold_path();
- return Err(LinkingError::incompatible_import_type(import).into());
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
}
match (val, &import.kind) {
(ExternVal::Global(global_addr), ImportKind::Global(ty)) => {
- let global = store.state.get_global(global_addr);
+ let global_ty = store.state.globals.ty(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));
+ let compatible = global_ty.mutable == ty.mutable
+ && 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());
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
}
imports.globals.push(global_addr);
}
@@ -303,15 +346,20 @@ impl Imports {
(ExternVal::Func(func_addr), ImportKind::Function(ty)) => {
let expected_type_addr =
type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?;
- if let Some(func) = &func_handle {
- func.item.validate_store(store)?;
- }
- if store.state.get_func(func_addr).type_addr != *expected_type_addr {
- cold_path();
- return Err(LinkingError::incompatible_import_type(import).into());
+ if !store.state.type_addr_is_subtype(store.state.funcs.type_addr(func_addr), *expected_type_addr) {
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
}
imports.funcs.push(func_addr);
}
+ (ExternVal::Tag(tag_addr), ImportKind::Tag(ty)) => {
+ let expected_type_addr = type_addrs
+ .get(ty.type_idx as usize)
+ .ok_or_else(|| LinkingError::incompatible_import_type(import))?;
+ if store.state.get_tag(tag_addr).type_addr != *expected_type_addr {
+ return cold!(Err(LinkingError::incompatible_import_type(import).into()));
+ }
+ imports.tags.push(tag_addr);
+ }
_ => unreachable!("import kind checked above"),
}
}
diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs
index 95c207b..5b71b81 100644
--- a/crates/tinywasm/src/instance.rs
+++ b/crates/tinywasm/src/instance.rs
@@ -1,10 +1,14 @@
-use alloc::{boxed::Box, format, sync::Arc};
+use alloc::{boxed::Box, format, rc::Rc, sync::Arc};
use core::hint::cold_path;
use tinywasm_types::*;
-use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes};
+use crate::func::{FromWasmValues, IntoWasmValues, WasmTypes};
+use crate::reference::StoreId;
+use crate::shared::StoreShared;
use crate::store::MemoryInstance;
-use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Trap};
+use crate::{
+ Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap, WasmValue,
+};
/// A typed view over an exported extern value.
pub enum ExternItem {
@@ -16,6 +20,8 @@ pub enum ExternItem {
Table(Table),
/// Exported global reference.
Global(Global),
+ /// Exported tag reference.
+ Tag(Tag),
}
/// An instantiated WebAssembly module
@@ -36,75 +42,91 @@ pub enum ExternItem {
/// # }
/// ```
///
-/// Backed by an Arc, so cloning is cheap
+/// Cloning an instance handle is cheap.
///
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#module-instances>
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct ModuleInstance(Arc<ModuleInstanceInner>);
+pub struct ModuleInstance(StoreShared<ModuleInstanceInner>);
#[cfg_attr(feature = "debug", derive(Debug))]
struct ModuleInstanceInner {
- store_id: usize,
+ store_id: StoreId,
id: ModuleInstanceId,
type_addrs: Box<[TypeAddr]>,
func_addrs: Box<[FuncAddr]>,
table_addrs: Box<[TableAddr]>,
mem_addrs: Box<[MemAddr]>,
global_addrs: Box<[GlobalAddr]>,
+ tag_addrs: Box<[TagAddr]>,
elem_addrs: Box<[ElemAddr]>,
data_addrs: Box<[DataAddr]>,
func_start: Option<FuncAddr>,
- exports: Arc<[Export]>,
+ exports: Shared<[Export]>,
}
impl ModuleInstance {
#[inline]
pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr {
- *self.0.type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}"))
+ self.0.type_addrs[type_addr as usize]
}
/// resolve a function address to the global store address
#[inline]
pub(crate) fn resolve_func_addr(&self, addr: FuncAddr) -> FuncAddr {
- *self.0.func_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid function address: {addr}"))
+ self.0.func_addrs[addr as usize]
}
/// resolve a table address to the global store address
#[inline]
pub(crate) fn resolve_table_addr(&self, addr: TableAddr) -> TableAddr {
- *self.0.table_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid table address: {addr}"))
+ self.0.table_addrs[addr as usize]
}
/// resolve a memory address to the global store address
#[inline]
pub(crate) fn resolve_mem_addr(&self, addr: MemAddr) -> MemAddr {
- *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}"))
+ self.0.mem_addrs[addr as usize]
+ }
+
+ /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module
+ /// has none.
+ ///
+ /// The sentinel is never used in practice: validation guarantees a memory instruction can only
+ /// reference index 0 when the module declares a memory, so any read of the sentinel would trip
+ /// an out-of-bounds panic in the store lookup and surface a bug.
+ #[inline]
+ pub(crate) fn mem0_addr(&self) -> MemAddr {
+ self.0.mem_addrs.first().copied().unwrap_or(MemAddr::MAX)
}
/// resolve a data address to the global store address
#[inline]
pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr {
- *self.0.data_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid data address: {addr}"))
+ self.0.data_addrs[addr as usize]
}
/// resolve an element address to the global store address
#[inline]
pub(crate) fn resolve_elem_addr(&self, addr: ElemAddr) -> ElemAddr {
- *self.0.elem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid element address: {addr}"))
+ self.0.elem_addrs[addr as usize]
}
/// resolve a global address to the global store address
#[inline]
pub(crate) fn resolve_global_addr(&self, addr: GlobalAddr) -> GlobalAddr {
- *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}"))
+ self.0.global_addrs[addr as usize]
+ }
+
+ #[inline]
+ pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr {
+ self.0.tag_addrs[addr as usize]
}
#[inline]
pub(crate) fn validate_store(&self, store: &Store) -> Result<()> {
if self.0.store_id != store.id() {
- cold_path();
- return Err(Trap::InvalidStore.into());
+ return cold!(Err(Trap::InvalidStore.into()));
}
Ok(())
}
@@ -117,7 +139,7 @@ impl ModuleInstance {
/// Instantiate the module in the given store
///
/// See <https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation>
- pub fn instantiate(store: &mut Store, module: &Module, imports: Option<Imports>) -> Result<Self> {
+ pub fn instantiate(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result<Self> {
let instance = ModuleInstance::instantiate_no_start(store, module, imports)?;
let _ = instance.start(store)?;
Ok(instance)
@@ -142,42 +164,46 @@ impl ModuleInstance {
/// let mut store = Store::default();
/// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;
///
- /// assert_eq!(instance.global_get(&store, "g")?, 0.into());
+ /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into());
/// instance.start(&mut store)?;
- /// assert_eq!(instance.global_get(&store, "g")?, 42.into());
+ /// assert_eq!(instance.global_get(&mut store, "g")?, 42.into());
/// # Ok(())
/// # }
/// ```
///
/// 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);
+ pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result<Self> {
+ let default_imports = Imports::default();
+ let imports = imports.unwrap_or(&default_imports).resolve(module)?;
+ Self::instantiate_inner(store, module, &imports)
+ }
+
+ /// **Unstable**: This method is for internal use only and may change or be removed at any time.
+ #[doc(hidden)]
+ pub fn instantiate_ordered(store: &mut Store, module: &Module, imports: &[crate::Extern]) -> Result<Self> {
+ let instance = Self::instantiate_inner(store, module, imports)?;
+ instance.start(store)?;
+ Ok(instance)
+ }
+
+ fn instantiate_inner(store: &mut Store, module: &Module, imports: &[crate::Extern]) -> Result<Self> {
+ 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()..]
- .iter()
- .map(|&addr| type_addrs[addr as usize])
- .collect::<Box<[_]>>();
- addrs.funcs.extend(store.init_funcs(&module.funcs, id, &local_type_addrs));
- match module.local_memory_allocation {
- LocalMemoryAllocation::Skip => {
- #[cfg(feature = "guest-debug")]
- addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?);
- }
- LocalMemoryAllocation::Lazy => {
- addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?)
- }
- LocalMemoryAllocation::Eager => {
- addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new)?)
- }
+ let mut addrs = crate::imports::ResolvedImports::new(store, module, &type_addrs, imports)?;
+ let imported_funcs = addrs.funcs.len();
+ addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs));
+ addrs.tags.extend(store.init_tags(&module.tags, &type_addrs));
+ let limiter = store.engine.config().resource_limiter.clone();
+ if !module.skip_local_memory_allocation {
+ addrs
+ .memories
+ .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?);
}
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)?;
- let (data_addrs, data_trapped) =
- store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data)?;
+ let elem_addrs = store.alloc_elements(&addrs.funcs, &addrs.globals, &module.elements, &type_addrs)?;
+ let data_addrs = store.alloc_data(&module.data);
let instance = ModuleInstanceInner {
store_id: store.id(),
@@ -187,30 +213,45 @@ impl ModuleInstance {
table_addrs: addrs.tables.into_boxed_slice(),
mem_addrs: addrs.memories.into_boxed_slice(),
global_addrs: addrs.globals.into_boxed_slice(),
+ tag_addrs: addrs.tags.into_boxed_slice(),
elem_addrs,
data_addrs,
func_start: module.start_func,
exports: module.exports.clone(),
};
- let instance = ModuleInstance(Arc::new(instance));
+ let instance = ModuleInstance(StoreShared::new(instance));
+ // Earlier table writes can expose functions even if a later segment traps.
store.add_instance(instance.clone());
- if let Some(trap) = elem_trapped.or(data_trapped) {
- cold_path();
- return Err(trap.into());
- }
+ store.init_elements(
+ &instance.0.table_addrs,
+ &instance.0.func_addrs,
+ &instance.0.global_addrs,
+ &module.elements,
+ &instance.0.type_addrs,
+ &instance.0.elem_addrs,
+ )?;
+ store.init_data(
+ &instance.0.mem_addrs,
+ &instance.0.global_addrs,
+ &instance.0.func_addrs,
+ &module.data,
+ &instance.0.type_addrs,
+ &instance.0.data_addrs,
+ )?;
Ok(instance)
}
/// Get a export by name
- pub fn export_addr(&self, name: &str) -> Option<ExternVal> {
+ pub(crate) fn export_addr(&self, name: &str) -> Option<ExternVal> {
let export = self.0.exports.iter().find(|e| *e.name == *name)?;
let addr = match export.kind {
ExternalKind::Func => self.0.func_addrs.get(export.index as usize)?,
ExternalKind::Table => self.0.table_addrs.get(export.index as usize)?,
ExternalKind::Memory => self.0.mem_addrs.get(export.index as usize)?,
ExternalKind::Global => self.0.global_addrs.get(export.index as usize)?,
+ ExternalKind::Tag => self.0.tag_addrs.get(export.index as usize)?,
};
Some(ExternVal::new(export.kind, *addr))
}
@@ -246,13 +287,10 @@ impl ModuleInstance {
pub fn exports(&self) -> impl Iterator<Item = (&str, ExternItem)> + '_ {
self.0.exports.iter().map(move |export| {
let item = match export.kind {
- ExternalKind::Func => {
- let func_addr = self.resolve_func_addr(export.index);
- ExternItem::Func(Function {
- item: StoreItem::new(self.0.store_id, func_addr),
- module_id: self.id(),
- })
- }
+ ExternalKind::Func => ExternItem::Func(Function {
+ item: StoreItem::new(self.0.store_id, self.resolve_func_addr(export.index)),
+ module_id: self.id(),
+ }),
ExternalKind::Table => {
ExternItem::Table(Table(StoreItem::new(self.0.store_id, self.resolve_table_addr(export.index))))
}
@@ -262,6 +300,9 @@ impl ModuleInstance {
ExternalKind::Global => {
ExternItem::Global(Global(StoreItem::new(self.0.store_id, self.resolve_global_addr(export.index))))
}
+ ExternalKind::Tag => {
+ ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, self.resolve_tag_addr(export.index))))
+ }
};
(export.name.as_ref(), item)
@@ -302,7 +343,7 @@ impl ModuleInstance {
/// let ExternItem::Global(global) = instance.extern_item("answer")? else {
/// panic!("expected global export");
/// };
- /// assert_eq!(global.get(&store)?, 42.into());
+ /// assert_eq!(global.get(&mut store)?, 42.into());
/// # Ok(())
/// # }
/// ```
@@ -314,6 +355,7 @@ impl ModuleInstance {
ExternVal::Memory(addr) => Ok(ExternItem::Memory(Memory(StoreItem::new(self.0.store_id, addr)))),
ExternVal::Table(addr) => Ok(ExternItem::Table(Table(StoreItem::new(self.0.store_id, addr)))),
ExternVal::Global(addr) => Ok(ExternItem::Global(Global(StoreItem::new(self.0.store_id, addr)))),
+ ExternVal::Tag(addr) => Ok(ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, addr)))),
}
}
@@ -335,8 +377,9 @@ impl ModuleInstance {
/// # let mut store = Store::default();
/// let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
/// let add = instance.func_untyped(&store, "add")?;
- /// let result = add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?;
- /// assert_eq!(result, vec![WasmValue::I32(42)]);
+ /// let mut results = [WasmValue::I32(0)];
+ /// add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?;
+ /// assert_eq!(results, [WasmValue::I32(42)]);
/// # Ok(())
/// # }
/// ```
@@ -344,10 +387,8 @@ impl ModuleInstance {
/// For typed access, see [`Self::func`].
pub fn func_untyped(&self, store: &Store, name: &str) -> Result<Function> {
self.validate_store(store)?;
-
let ExternVal::Func(func_addr) = self.require_export(name)? else {
- cold_path();
- return Err(Error::Other(format!("Export is not a function: {name}")));
+ return cold!(Err(Error::Other(format!("Export is not a function: {name}"))));
};
Ok(Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() })
@@ -364,7 +405,6 @@ impl ModuleInstance {
pub fn func_by_index(&self, store: &Store, func_index: FuncAddr) -> Result<Function> {
self.validate_store(store)?;
let func_addr = Self::index_addr(&self.0.func_addrs, func_index, "function")?;
-
Ok(Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() })
}
@@ -392,22 +432,14 @@ impl ModuleInstance {
///
/// For untyped access, see [`Self::func_untyped`] and [`Self::extern_item`].
///
- /// For signatures that exceed tuple arity 12, see [`crate::WasmTupleChain`], which can be used
- /// directly as `instance.func::<crate::WasmTupleChain<_, _>, _>(...)`.
- pub fn func<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>(
- &self,
- store: &Store,
- name: &str,
- ) -> Result<FunctionTyped<P, R>> {
+ /// Tuples are supported up to arity 20. Use [`Self::func_untyped`] for larger signatures.
+ pub fn func<P: IntoWasmValues, R: FromWasmValues>(&self, store: &Store, name: &str) -> Result<FunctionTyped<P, R>> {
self.validate_store(store)?;
-
let ExternVal::Func(func_addr) = self.require_export(name)? else {
- cold_path();
- return Err(Error::Other(format!("Export is not a function: {name}")));
+ return cold!(Err(Error::Other(format!("Export is not a function: {name}"))));
};
let func = Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() };
-
Self::validate_typed_func::<P, R>(store, &func, name)?;
Ok(FunctionTyped { func, marker: core::marker::PhantomData })
}
@@ -415,7 +447,7 @@ impl ModuleInstance {
/// Get a typed function by its module-local index.
#[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))]
#[cfg(feature = "guest-debug")]
- pub fn func_typed_by_index<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>(
+ pub fn func_typed_by_index<P: IntoWasmValues, R: FromWasmValues>(
&self,
store: &Store,
func_index: FuncAddr,
@@ -426,21 +458,17 @@ impl ModuleInstance {
}
#[inline]
- fn validate_typed_func<P: ToWasmTypes, R: ToWasmTypes>(
- store: &Store,
- func: &Function,
- func_name: &str,
- ) -> Result<()> {
- let params = P::wasm_types();
- let results = R::wasm_types();
+ fn validate_typed_func<P: WasmTypes, R: WasmTypes>(store: &Store, func: &Function, func_name: &str) -> Result<()> {
+ let params = P::WASM_TYPES;
+ let results = R::WASM_TYPES;
let ty = store.state.get_func_type(func.addr());
- if ty.params() != params.as_ref() || ty.results() != results.as_ref() {
+ if ty.params() != params || ty.results() != results {
cold_path();
#[cfg(feature = "debug")]
return Err(Error::Other(format!(
"function type mismatch for {func_name}: expected {:?}, actual {:?}",
- FuncType::new(&params, &results),
+ FuncType::new(params, results),
ty
)));
@@ -455,10 +483,7 @@ impl ModuleInstance {
pub fn memory(&self, name: &str) -> Result<Memory> {
match self.require_export(name)? {
ExternVal::Memory(mem_addr) => Ok(Memory(StoreItem::new(self.0.store_id, mem_addr))),
- _ => {
- cold_path();
- Err(Error::Other(format!("Export is not a memory: {name}")))
- }
+ _ => cold!(Err(Error::Other(format!("Export is not a memory: {name}")))),
}
}
@@ -478,7 +503,7 @@ impl ModuleInstance {
pub fn table(&self, name: &str) -> Result<Table> {
match self.require_export(name)? {
ExternVal::Table(table_addr) => Ok(Table(StoreItem::new(self.0.store_id, table_addr))),
- _ => Err(Error::Other(format!("Export is not a table: {name}"))),
+ _ => cold!(Err(Error::Other(format!("Export is not a table: {name}")))),
}
}
@@ -494,8 +519,23 @@ impl ModuleInstance {
Ok(Table(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.table_addrs, table_index, "table")?)))
}
+ /// Get a tag export by name.
+ pub fn tag(&self, name: &str) -> Result<Tag> {
+ match self.require_export(name)? {
+ ExternVal::Tag(tag_addr) => Ok(Tag(StoreItem::new(self.0.store_id, tag_addr))),
+ _ => cold!(Err(Error::Other(format!("Export is not a tag: {name}")))),
+ }
+ }
+
+ /// Get a tag by its module-local index.
+ #[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))]
+ #[cfg(feature = "guest-debug")]
+ pub fn tag_by_index(&self, tag_index: TagAddr) -> Result<Tag> {
+ Ok(Tag(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.tag_addrs, tag_index, "tag")?)))
+ }
+
/// Get the value of a global export by name.
- pub fn global_get(&self, store: &Store, name: &str) -> Result<WasmValue> {
+ pub fn global_get(&self, store: &mut Store, name: &str) -> Result<WasmValue> {
self.global(name)?.get(store)
}
@@ -503,7 +543,7 @@ impl ModuleInstance {
pub fn global(&self, name: &str) -> Result<Global> {
match self.require_export(name)? {
ExternVal::Global(global_addr) => Ok(Global(StoreItem::new(self.0.store_id, global_addr))),
- _ => Err(Error::Other(format!("Export is not a global: {name}"))),
+ _ => cold!(Err(Error::Other(format!("Export is not a global: {name}")))),
}
}
@@ -580,9 +620,9 @@ impl ModuleInstance {
/// let mut store = Store::default();
/// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;
///
- /// assert_eq!(instance.global_get(&store, "g")?, 0.into());
+ /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into());
/// assert_eq!(instance.start(&mut store)?, Some(()));
- /// assert_eq!(instance.global_get(&store, "g")?, 7.into());
+ /// assert_eq!(instance.global_get(&mut store, "g")?, 7.into());
/// # Ok(())
/// # }
/// ```
@@ -590,7 +630,7 @@ impl ModuleInstance {
/// See <https://webassembly.github.io/spec/core/syntax/modules.html#syntax-start>
pub fn start(&self, store: &mut Store) -> Result<Option<()>> {
match self.start_func(store)? {
- Some(func) => func.call(store, &[]).map(|_| Some(())),
+ Some(func) => func.call(store, &[], &mut []).map(|_| Some(())),
None => Ok(None),
}
}
diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs
deleted file mode 100644
index 4a4e5fd..0000000
--- a/crates/tinywasm/src/interpreter/executor.rs
+++ /dev/null
@@ -1,1696 +0,0 @@
-use core::hint::cold_path;
-
-#[cfg(not(feature = "std"))]
-#[allow(unused_imports)]
-use super::no_std_floats::NoStdFloatExt;
-
-use alloc::boxed::Box;
-use alloc::sync::Arc;
-use alloc::vec::Vec;
-
-use interpreter::stack::{CallFrame, ValueStack};
-use tinywasm_types::*;
-
-use super::num_helpers::*;
-use super::values::*;
-use super::ExecState;
-use crate::engine::FuelPolicy;
-use crate::func::{FuncContext, HostFunction};
-use crate::interpreter::Value128;
-use crate::*;
-
-const FUEL_COST_CALL_TOTAL: u32 = 5;
-
-pub(crate) struct Executor<'store, const BUDGETED: bool> {
- cf: CallFrame,
- func: Arc<WasmFunction>,
- module: ModuleInstance,
- store: &'store mut Store,
- call_stack_base: u32,
-}
-
-impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
- #[inline(always)]
- fn pop_memory_addr<const N: usize>(
- stack: &mut ValueStack,
- mem: &MemoryInstance,
- offset: u64,
- ) -> Result<usize, Trap> {
- if mem.is_64bit() {
- mem.effective_addr_64::<N>(<i64>::stack_pop(stack) as u64, offset)
- } else {
- mem.effective_addr_32::<N>(<i32>::stack_pop(stack) as u32, offset)
- }
- }
-
- pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self {
- let wasm_func = store.state.get_wasm_func(cf.func_addr);
- let module = store.get_module_instance_internal(wasm_func.owner);
- Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base }
- }
-
- #[inline(always)]
- fn charge_call_fuel(&mut self, total_fuel_cost: u32) {
- if BUDGETED {
- let extra = match self.store.engine.config().fuel_policy {
- FuelPolicy::PerInstruction => 0,
- FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1),
- };
-
- self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra);
- }
- }
-
- #[inline(always)]
- fn exec(&mut self) -> Result<Option<()>, Trap> {
- macro_rules! stack_op {
- (unary $ty:ty, |$v:ident| $expr:expr) => {
- stack_op!(unary $ty => $ty, |$v| $expr)
- };
- (binary $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {
- stack_op!(binary $ty => $ty, |$lhs, $rhs| $expr)
- };
- (binary try $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$ty>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::stack_push(&mut self.store.value_stack, $expr?)?;
- }};
- (unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{
- let $v = <$from>::stack_pop(&mut self.store.value_stack);
- <$to>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$from>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$from>::stack_pop(&mut self.store.value_stack);
- <$to>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (binary_into2 $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$from>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$from>::stack_pop(&mut self.store.value_stack);
- let out = $expr;
- <$to>::stack_push(&mut self.store.value_stack, out.0)?;
- <$to>::stack_push(&mut self.store.value_stack, out.1)?;
- }};
- (binary $lhs_ty:ty, $rhs_ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {
- stack_op!(binary $lhs_ty, $rhs_ty => $rhs_ty, |$lhs, $rhs| $expr)
- };
- (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack);
- <$res>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (ternary $ty:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{
- let $c = <$ty>::stack_pop(&mut self.store.value_stack);
- let $b = <$ty>::stack_pop(&mut self.store.value_stack);
- let $a = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (quaternary_into2 $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{
- let $d = <$from>::stack_pop(&mut self.store.value_stack);
- let $c = <$from>::stack_pop(&mut self.store.value_stack);
- let $b = <$from>::stack_pop(&mut self.store.value_stack);
- let $a = <$from>::stack_pop(&mut self.store.value_stack);
- let out = $expr;
- <$to>::stack_push(&mut self.store.value_stack, out.0)?;
- <$to>::stack_push(&mut self.store.value_stack, out.1)?;
- }};
- (local_set_pop $ty:ty, $local_index:expr) => {{
- let val = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val);
- }};
- (local_tee $ty:ty, $local_index:expr) => {{
- let val = <$ty>::stack_peek(&self.store.value_stack);
- <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val);
- }};
- }
-
- macro_rules! exec_binop {
- (32, $op:expr, $lhs:expr, $rhs:expr) => {
- exec_binop!(@scalar i32, u32, f32, $op, $lhs, $rhs)
- };
- (64, $op:expr, $lhs:expr, $rhs:expr) => {
- exec_binop!(@scalar i64, u64, f64, $op, $lhs, $rhs)
- };
- (@scalar $signed:ty, $unsigned:ty, $float:ty, $op:expr, $lhs:expr, $rhs:expr) => {{
- match $op {
- BinOp::IAdd => $lhs.wrapping_add($rhs),
- BinOp::ISub => $lhs.wrapping_sub($rhs),
- BinOp::IMul => $lhs.wrapping_mul($rhs),
- BinOp::IAnd => $lhs & $rhs,
- BinOp::IOr => $lhs | $rhs,
- BinOp::IXor => $lhs ^ $rhs,
- BinOp::IShl => (($lhs as $signed).wrapping_shl($rhs as u32)) as $unsigned,
- BinOp::IShrS => (($lhs as $signed).wrapping_shr($rhs as u32)) as $unsigned,
- BinOp::IShrU => $lhs.wrapping_shr($rhs as u32),
- BinOp::IRotl => (($lhs as $signed).rotate_left($rhs as u32)) as $unsigned,
- BinOp::IRotr => (($lhs as $signed).rotate_right($rhs as u32)) as $unsigned,
- BinOp::FAdd => (<$float>::from_bits($lhs) + <$float>::from_bits($rhs)).to_bits(),
- BinOp::FSub => (<$float>::from_bits($lhs) - <$float>::from_bits($rhs)).to_bits(),
- BinOp::FMul => (<$float>::from_bits($lhs) * <$float>::from_bits($rhs)).to_bits(),
- BinOp::FDiv => (<$float>::from_bits($lhs) / <$float>::from_bits($rhs)).to_bits(),
- BinOp::FMin => <$float>::from_bits($lhs).tw_minimum(<$float>::from_bits($rhs)).to_bits(),
- BinOp::FMax => <$float>::from_bits($lhs).tw_maximum(<$float>::from_bits($rhs)).to_bits(),
- BinOp::FCopysign => <$float>::from_bits($lhs).copysign(<$float>::from_bits($rhs)).to_bits(),
- }
- }};
- (128, $op:expr, $lhs:expr, $rhs:expr) => {{
- match $op {
- BinOp128::And => $lhs.v128_and($rhs),
- BinOp128::AndNot => $lhs.v128_andnot($rhs),
- BinOp128::Or => $lhs.v128_or($rhs),
- BinOp128::Xor => $lhs.v128_xor($rhs),
- BinOp128::I64x2Add => $lhs.i64x2_add($rhs),
- BinOp128::I64x2Mul => $lhs.i64x2_mul($rhs),
- }
- }};
- }
-
- macro_rules! binop {
- (local_local $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- self.store.value_stack.push(exec_binop!($width, *$op, lhs, rhs))?;
- }};
- (local_local_set $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- let value = exec_binop!($width, *$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- }};
- (local_local_tee $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- let value = exec_binop!($width, *$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- self.store.value_stack.push(value)?;
- }};
- (local_const $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- self.store.value_stack.push(exec_binop!($width, *$op, lhs, $rhs))?;
- }};
- (local_const_set $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let value = exec_binop!($width, *$op, lhs, $rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- }};
- (local_const_tee $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let value = exec_binop!($width, *$op, lhs, $rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- self.store.value_stack.push(value)?;
- }};
- (stack_global $vt:ident, $width:tt, $op:ident, $global:ident) => {{
- let TinyWasmValue::$vt(global_val) =
- self.store.state.get_global_val(self.module.resolve_global_addr(*$global))
- else {
- unreachable!("expected global to be Value32")
- };
- let stack_val = <$vt>::stack_pop(&mut self.store.value_stack);
- self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?;
- }};
- }
-
- use tinywasm_types::Instruction::*;
- #[rustfmt::skip]
- match &self.func.instructions[self.cf.instr_ptr] {
- Unreachable => { cold_path(); return Err(Trap::Unreachable) },
- Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)},
- Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)},
- Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)},
- Select32 => Value32::stack_select(&mut self.store.value_stack)?,
- Select64 => Value64::stack_select(&mut self.store.value_stack)?,
- Select128 => Value128::stack_select(&mut self.store.value_stack)?,
- SelectMulti(counts) => self.store.value_stack.select_multi(*counts),
- Call(v) => { self.exec_call_direct(*v)?; return Ok(None); }
- CallSelf => { self.exec_call_self()?; return Ok(None); }
- CallIndirect(ty, table) => { self.exec_call_indirect::<false>(*ty, *table)?; return Ok(None); }
- CallRef(ty) => { self.exec_call_ref::<false>(*ty)?; return Ok(None); }
- ReturnCall(v) => { if self.exec_return_call_direct(*v)? { return Ok(Some(())); } return Ok(None); }
- ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); }
- ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::<true>(*ty, *table)? { return Ok(Some(())); } return Ok(None); }
- ReturnCallRef(ty) => { if self.exec_call_ref::<true>(*ty)? { return Ok(Some(())); } return Ok(None); }
- Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); }
- JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) },
- JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) },
- JumpIfZero64(ip) => if self.exec_jump_zero_64(*ip) { return Ok(None) },
- 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) },
- 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) },
- JumpIfLocalNonZero64 { target_ip, local } => if self.exec_jump_local_non_zero_64(*target_ip, *local) { return Ok(None) },
- JumpCmpStackConst32 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_32(*target_ip, *imm, *op) { return Ok(None) },
- JumpCmpStackConst64 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_64(*target_ip, *imm, *op) { return Ok(None) },
- JumpCmpLocalConst32 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_32(*target_ip, *local, *imm, *op) { return Ok(None) },
- JumpCmpLocalConst64 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_64(*target_ip, *local, *imm, *op) { return Ok(None) },
- JumpCmpLocalLocal32 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_32(*target_ip, *left, *right, *op) { return Ok(None) },
- JumpCmpLocalLocal64 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_64(*target_ip, *left, *right, *op) { return Ok(None) },
- DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep),
- BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); }
- Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); }
- ReturnVoid => { if self.exec_return_void() { return Ok(Some(())); } return Ok(None); }
- Return32 => { if self.exec_return_32() { return Ok(Some(())); } return Ok(None); }
- Return64 => { if self.exec_return_64() { return Ok(Some(())); } return Ok(None); }
- Return128 => { if self.exec_return_128() { return Ok(Some(())); } return Ok(None); }
- LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?,
- LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?,
- LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?,
- LocalSet32(local_index) => stack_op!(local_set_pop Value32, local_index),
- LocalSet64(local_index) => stack_op!(local_set_pop Value64, local_index),
- LocalSet128(local_index) => stack_op!(local_set_pop Value128, local_index),
- LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
- LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
- LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
- AddConst32(c) => stack_op!(unary i32, |v| v.wrapping_add(*c)),
- AddConst64(c) => stack_op!(unary i64, |v| v.wrapping_add(*c)),
- IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)),
- IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )),
- I32Add3 => stack_op!(ternary i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
- I64Add3 => stack_op!(ternary i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
- MulAccLocal32(acc) => self.exec_binop_acc_local::<i32, _, _>(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)),
- MulAccLocal64(acc) => self.exec_binop_acc_local::<i64, _, _>(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)),
- FMulAccLocal32(acc) => self.exec_binop_acc_local::<f32, _, _>(*acc, |a, b| a * b, |a, b| a + b),
- FMulAccLocal64(acc) => self.exec_binop_acc_local::<f64, _, _>(*acc, |a, b| a * b, |a, b| a + b),
- BinOpLocalLocal32(op, a, b) => binop!(local_local Value32, 32, op, a, b),
- BinOpLocalLocal64(op, a, b) => binop!(local_local Value64, 64, op, a, b),
- BinOpLocalLocal128(op, a, b) => binop!(local_local Value128, 128, op, a, b),
- BinOpLocalLocalSet32(op, a, b, dst) => binop!(local_local_set Value32, 32, op, a, b, dst),
- BinOpLocalLocalSet64(op, a, b, dst) => binop!(local_local_set Value64, 64, op, a, b, dst),
- BinOpLocalLocalSet128(op, a, b, dst) => binop!(local_local_set Value128, 128, op, a, b, dst),
- BinOpLocalLocalTee32(op, a, b, dst) => binop!(local_local_tee Value32, 32, op, a, b, dst),
- BinOpLocalLocalTee64(op, a, b, dst) => binop!(local_local_tee Value64, 64, op, a, b, dst),
- BinOpLocalLocalTee128(op, a, b, dst) => binop!(local_local_tee Value128, 128, op, a, b, dst),
- BinOpLocalConst32(op, local_index, c) => binop!(local_const Value32, 32, op, local_index, *c as u32),
- BinOpLocalConst64(op, local_index, c) => binop!(local_const Value64, 64, op, local_index, *c as u64),
- BinOpLocalConst128(op, local_index, c) => binop!(local_const Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c))),
- BinOpLocalConstSet32(op, local_index, c, dst) => binop!(local_const_set Value32, 32, op, local_index, *c as u32, dst),
- BinOpLocalConstSet64(op, local_index, c, dst) => binop!(local_const_set Value64, 64, op, local_index, *c as u64, dst),
- BinOpLocalConstSet128(op, local_index, c, dst) => binop!(local_const_set Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst),
- BinOpLocalConstTee32(op, local_index, c, dst) => binop!(local_const_tee Value32, 32, op, local_index, *c as u32, dst),
- BinOpLocalConstTee64(op, local_index, c, dst) => binop!(local_const_tee Value64, 64, op, local_index, *c as u64, dst),
- BinOpLocalConstTee128(op, local_index, c, dst) => binop!(local_const_tee Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst),
- BinOpStackGlobal32(op, global_index) => binop!(stack_global Value32, 32, op, global_index),
- BinOpStackGlobal64(op, global_index) => binop!(stack_global Value64, 64, op, global_index),
- SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c),
- SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c),
- SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))),
- IncMemoryLocal32(m, addr_local) => self.exec_inc_memory_local::<i32, 4>(*m, *addr_local, |v| v.wrapping_add(1))?,
- IncMemoryLocal64(m, addr_local) => self.exec_inc_memory_local::<i64, 8>(*m, *addr_local, |v| v.wrapping_add(1))?,
- StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::<u32, 4>(*m, *addr_local, *value_local)?,
- StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::<i64, 8>(*m, *addr_local, *value_local)?,
- StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::<Value128, 16>(*m, *addr_local, *value_local)?,
- LoadLocal32(m, addr_local) => self.store.value_stack.push(self.exec_load_local_value::<i32, 4>(*m, *addr_local)?)?,
- LoadLocal64(m, addr_local) => self.store.value_stack.push(self.exec_load_local_value::<i64, 8>(*m, *addr_local)?)?,
- LoadLocal8S32(m, addr_local) => {
- let value = self.exec_load_local_value::<i8, 1>(*m, *addr_local)?;
- self.store.value_stack.push(i32::from(value))?;
- }
- LoadLocal8U32(m, addr_local) => {
- let value = self.exec_load_local_value::<u8, 1>(*m, *addr_local)?;
- self.store.value_stack.push(i32::from(value))?;
- }
- LoadLocal16S32(m, addr_local) => {
- let value = self.exec_load_local_value::<i16, 2>(*m, *addr_local)?;
- self.store.value_stack.push(i32::from(value))?;
- }
- LoadLocal16U32(m, addr_local) => {
- let value = self.exec_load_local_value::<u16, 2>(*m, *addr_local)?;
- self.store.value_stack.push(i32::from(value))?;
- }
- LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local_tee::<i32, 4, _>(*m, *addr_local, *dst_local, |v| v)?,
- LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local_set::<i32, 4, _>(*m, *addr_local, *dst_local, |v| v)?,
- LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local_tee::<i8, 1, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local_tee::<u8, 1, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local_tee::<i16, 2, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local_tee::<u16, 2, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local_set::<i8, 1, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local_set::<u8, 1, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local_set::<i16, 2, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::<u16, 2, _>(*m, *addr_local, *dst_local, i32::from)?,
- LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::<Value128, 16, _>(*m, *addr_local, *dst_local, |v| v)?,
- LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::<Value128, 16, _>(*m, *addr_local, *dst_local, |v| v)?,
- AndConstTee32(c, local_index) => { stack_op!(unary i32, |v| v & *c); stack_op!(local_tee i32, local_index); }
- SubConstTee32(c, local_index) => { stack_op!(unary i32, |v| v.wrapping_sub(*c)); stack_op!(local_tee i32, local_index); }
- AndConstTee64(c, local_index) => { stack_op!(unary i64, |v| v & *c); stack_op!(local_tee i64, local_index); }
- SubConstTee64(c, local_index) => { stack_op!(unary i64, |v| v.wrapping_sub(*c)); stack_op!(local_tee i64, local_index); }
- LocalTee32(local_index) => stack_op!(local_tee Value32, local_index),
- LocalTee64(local_index) => stack_op!(local_tee Value64, local_index),
- LocalTee128(local_index) => stack_op!(local_tee Value128, local_index),
- GlobalGet(global_index) => self.exec_global_get(*global_index)?,
- GlobalSet32(global_index) => self.exec_global_set_32(*global_index),
- GlobalSet64(global_index) => self.exec_global_set::<Value64>(*global_index),
- GlobalSet128(global_index) => self.exec_global_set::<Value128>(*global_index),
- Const32(val) => self.exec_const(*val)?,
- Const64(val) => self.exec_const(*val)?,
- I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)),
- I32Eqz => stack_op!(unary i32, |v| i32::from(v == 0)),
- I32Eq => stack_op!(binary i32, |a, b| i32::from(a == b)),
- I64Eq => stack_op!(binary i64 => i32, |a, b| i32::from(a == b)),
- F32Eq => stack_op!(binary f32 => i32, |a, b| i32::from(a == b)),
- F64Eq => stack_op!(binary f64 => i32, |a, b| i32::from(a == b)),
- I32Ne => stack_op!(binary i32, |a, b| i32::from(a != b)),
- I64Ne => stack_op!(binary i64 => i32, |a, b| i32::from(a != b)),
- F32Ne => stack_op!(binary f32 => i32, |a, b| i32::from(a != b)),
- F64Ne => stack_op!(binary f64 => i32, |a, b| i32::from(a != b)),
- I32LtS => stack_op!(binary i32, |a, b| i32::from(a < b)),
- I64LtS => stack_op!(binary i64 => i32, |a, b| i32::from(a < b)),
- I32LtU => stack_op!(binary u32 => i32, |a, b| i32::from(a < b)),
- I64LtU => stack_op!(binary u64 => i32, |a, b| i32::from(a < b)),
- F32Lt => stack_op!(binary f32 => i32, |a, b| i32::from(a < b)),
- F64Lt => stack_op!(binary f64 => i32, |a, b| i32::from(a < b)),
- I32LeS => stack_op!(binary i32, |a, b| i32::from(a <= b)),
- I64LeS => stack_op!(binary i64 => i32, |a, b| i32::from(a <= b)),
- I32LeU => stack_op!(binary u32 => i32, |a, b| i32::from(a <= b)),
- I64LeU => stack_op!(binary u64 => i32, |a, b| i32::from(a <= b)),
- F32Le => stack_op!(binary f32 => i32, |a, b| i32::from(a <= b)),
- F64Le => stack_op!(binary f64 => i32, |a, b| i32::from(a <= b)),
- I32GeS => stack_op!(binary i32, |a, b| i32::from(a >= b)),
- I64GeS => stack_op!(binary i64 => i32, |a, b| i32::from(a >= b)),
- I32GeU => stack_op!(binary u32 => i32, |a, b| i32::from(a >= b)),
- I64GeU => stack_op!(binary u64 => i32, |a, b| i32::from(a >= b)),
- F32Ge => stack_op!(binary f32 => i32, |a, b| i32::from(a >= b)),
- F64Ge => stack_op!(binary f64 => i32, |a, b| i32::from(a >= b)),
- I32GtS => stack_op!(binary i32, |a, b| i32::from(a > b)),
- I64GtS => stack_op!(binary i64 => i32, |a, b| i32::from(a > b)),
- I32GtU => stack_op!(binary u32 => i32, |a, b| i32::from(a > b)),
- I64GtU => stack_op!(binary u64 => i32, |a, b| i32::from(a > b)),
- F32Gt => stack_op!(binary f32 => i32, |a, b| i32::from(a > b)),
- F64Gt => stack_op!(binary f64 => i32, |a, b| i32::from(a > b)),
- I32Add => stack_op!(binary i32, |a, b| a.wrapping_add(b)),
- I64Add => stack_op!(binary i64, |a, b| a.wrapping_add(b)),
- F32Add => stack_op!(binary f32, |a, b| a + b),
- F64Add => stack_op!(binary f64, |a, b| a + b),
- I32Sub => stack_op!(binary i32, |a, b| a.wrapping_sub(b)),
- I64Sub => stack_op!(binary i64, |a, b| a.wrapping_sub(b)),
- F32Sub => stack_op!(binary f32, |a, b| a - b),
- F64Sub => stack_op!(binary f64, |a, b| a - b),
- F32Div => stack_op!(binary f32, |a, b| a / b),
- F64Div => stack_op!(binary f64, |a, b| a / b),
- I32Mul => stack_op!(binary i32, |a, b| a.wrapping_mul(b)),
- I64Mul => stack_op!(binary i64, |a, b| a.wrapping_mul(b)),
- F32Mul => stack_op!(binary f32, |a, b| a * b),
- F64Mul => stack_op!(binary f64, |a, b| a * b),
- I32DivS => stack_op!(binary try i32, |a, b| a.tw_checked_div(b)),
- I64DivS => stack_op!(binary try i64, |a, b| a.tw_checked_div(b)),
- I32DivU => stack_op!(binary try u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)),
- I64DivU => stack_op!(binary try u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)),
- I32RemS => stack_op!(binary try i32, |a, b| a.tw_checked_wrapping_rem(b)),
- I64RemS => stack_op!(binary try i64, |a, b| a.tw_checked_wrapping_rem(b)),
- I32RemU => stack_op!(binary try u32, |a, b| a.tw_checked_wrapping_rem(b)),
- I64RemU => stack_op!(binary try u64, |a, b| a.tw_checked_wrapping_rem(b)),
- I32And => stack_op!(binary i32, |a, b| a & b),
- I64And => stack_op!(binary i64, |a, b| a & b),
- I32Or => stack_op!(binary i32, |a, b| a | b),
- I64Or => stack_op!(binary i64, |a, b| a | b),
- I32Xor => stack_op!(binary i32, |a, b| a ^ b),
- I64Xor => stack_op!(binary i64, |a, b| a ^ b),
- I32Shl => stack_op!(binary i32, |a, b| a.wrapping_shl(b as u32)),
- I64Shl => stack_op!(binary i64, |a, b| a.wrapping_shl(b as u32)),
- I32ShrS => stack_op!(binary i32, |a, b| a.wrapping_shr(b as u32)),
- I64ShrS => stack_op!(binary i64, |a, b| a.wrapping_shr(b as u32)),
- I32ShrU => stack_op!(binary u32, |a, b| a.wrapping_shr(b)),
- I64ShrU => stack_op!(binary u64, |a, b| a.wrapping_shr(b as u32)),
- I32Rotl => stack_op!(binary i32, |a, b| a.rotate_left(b as u32)),
- I64Rotl => stack_op!(binary i64, |a, b| a.rotate_left(b as u32)),
- I32Rotr => stack_op!(binary i32, |a, b| a.rotate_right(b as u32)),
- I64Rotr => stack_op!(binary i64, |a, b| a.rotate_right(b as u32)),
- I64Add128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| {
- let lo = a_lo.wrapping_add(b_lo);
- let carry = u64::from((lo as u64) < (a_lo as u64));
- let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64);
- (lo, hi)
- }),
- I64Sub128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| {
- let lo = a_lo.wrapping_sub(b_lo);
- let borrow = u64::from((a_lo as u64) < (b_lo as u64));
- let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64);
- (lo, hi)
- }),
- I64MulWideS => stack_op!(binary_into2 i64 => i64, |a, b| {
- let product = (a as i128).wrapping_mul(b as i128);
- (product as i64, (product >> 64) as i64)
- }),
- I64MulWideU => stack_op!(binary_into2 i64 => i64, |a, b| {
- let product = (a as u64 as u128).wrapping_mul(b as u64 as u128);
- (product as u64 as i64, (product >> 64) as u64 as i64)
- }),
- I32Clz => stack_op!(unary i32, |v| v.leading_zeros() as i32),
- I64Clz => stack_op!(unary i64, |v| i64::from(v.leading_zeros())),
- I32Ctz => stack_op!(unary i32, |v| v.trailing_zeros() as i32),
- I64Ctz => stack_op!(unary i64, |v| i64::from(v.trailing_zeros())),
- I32Popcnt => stack_op!(unary i32, |v| v.count_ones() as i32),
- 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))))?,
- RefNull(_) => self.exec_const(ValueRef::NULL)?,
- RefIsNull => self.exec_ref_is_null()?,
- RefAsNonNull => self.exec_ref_as_non_null()?,
- MemorySize(addr) => self.exec_memory_size(*addr)?,
- MemoryGrow(addr) => self.exec_memory_grow(*addr)?,
-
- // Bulk memory operations
- MemoryCopy { dst_mem, src_mem } => self.exec_memory_copy(*dst_mem, *src_mem)?,
- MemoryFill(addr) => self.exec_memory_fill(*addr)?,
- MemoryFillImm(addr, val, size) => self.exec_memory_fill_imm(*addr, *val, *size)?,
- MemoryInit(data_idx, mem_idx) => self.exec_memory_init(*data_idx, *mem_idx)?,
- DataDrop(data_index) => self.store.state.get_data_mut(self.module.resolve_data_addr(*data_index)).drop(),
- ElemDrop(elem_index) => self.store.state.get_elem_mut(self.module.resolve_elem_addr(*elem_index)).drop(),
-
- // Table instructions
- TableGet(table_idx) => self.exec_table_get(*table_idx)?,
- TableSet(table_idx) => self.exec_table_set(*table_idx)?,
- TableSize(table_idx) => self.exec_table_size(*table_idx)?,
- TableInit(elem_idx, table_idx) => self.exec_table_init(*elem_idx, *table_idx)?,
- TableGrow(table_idx) => self.exec_table_grow(*table_idx)?,
- TableFill(table_idx) => self.exec_table_fill(*table_idx)?,
- TableCopy { dst_table, src_table } => self.exec_table_copy(*dst_table, *src_table)?,
-
- // Core memory load/store operations
- I32Store(m) => self.exec_mem_store::<i32, i32, 4>(m.mem_addr(), m.offset(), |v| v)?,
- I64Store(m) => self.exec_mem_store::<i64, i64, 8>(m.mem_addr(), m.offset(), |v| v)?,
- F32Store(m) => self.exec_mem_store::<f32, f32, 4>(m.mem_addr(), m.offset(), |v| v)?,
- F64Store(m) => self.exec_mem_store::<f64, f64, 8>(m.mem_addr(), m.offset(), |v| v)?,
- FMaStoreF32(m) => self.exec_fma_store::<f32, 4>(*m)?,
- FMaStoreF64(m) => self.exec_fma_store::<f64, 8>(*m)?,
- I32Store8(m) => self.exec_mem_store::<i32, i8, 1>(m.mem_addr(), m.offset(), |v| v as i8)?,
- I32Store16(m) => self.exec_mem_store::<i32, i16, 2>(m.mem_addr(), m.offset(), |v| v as i16)?,
- I64Store8(m) => self.exec_mem_store::<i64, i8, 1>(m.mem_addr(), m.offset(), |v| v as i8)?,
- I64Store16(m) => self.exec_mem_store::<i64, i16, 2>(m.mem_addr(), m.offset(), |v| v as i16)?,
- I64Store32(m) => self.exec_mem_store::<i64, i32, 4>(m.mem_addr(), m.offset(), |v| v as i32)?,
- I32Load(m) => self.exec_mem_load::<i32, 4, _>(m.mem_addr(), m.offset(), |v| v)?,
- I64Load(m) => self.exec_mem_load::<i64, 8, _>(m.mem_addr(), m.offset(), |v| v)?,
- F32Load(m) => self.exec_mem_load::<f32, 4, _>(m.mem_addr(), m.offset(), |v| v)?,
- F64Load(m) => self.exec_mem_load::<f64, 8, _>(m.mem_addr(), m.offset(), |v| v)?,
- I32Load8S(m) => self.exec_mem_load::<i8, 1, _>(m.mem_addr(), m.offset(), i32::from)?,
- I32Load8U(m) => self.exec_mem_load::<u8, 1, _>(m.mem_addr(), m.offset(), i32::from)?,
- I32Load16S(m) => self.exec_mem_load::<i16, 2, _>(m.mem_addr(), m.offset(), i32::from)?,
- I32Load16U(m) => self.exec_mem_load::<u16, 2, _>(m.mem_addr(), m.offset(), i32::from)?,
- I64Load8S(m) => self.exec_mem_load::<i8, 1, _>(m.mem_addr(), m.offset(), i64::from)?,
- I64Load8U(m) => self.exec_mem_load::<u8, 1, _>(m.mem_addr(), m.offset(), i64::from)?,
- I64Load16S(m) => self.exec_mem_load::<i16, 2, _>(m.mem_addr(), m.offset(), i64::from)?,
- I64Load16U(m) => self.exec_mem_load::<u16, 2, _>(m.mem_addr(), m.offset(), i64::from)?,
- I64Load32S(m) => self.exec_mem_load::<i32, 4, _>(m.mem_addr(), m.offset(), i64::from)?,
- I64Load32U(m) => self.exec_mem_load::<u32, 4, _>(m.mem_addr(), m.offset(), i64::from)?,
-
- // Numeric conversion operations
- F32ConvertI32S => stack_op!(unary i32 => f32, |v| v as f32),
- F32ConvertI64S => stack_op!(unary i64 => f32, |v| v as f32),
- F64ConvertI32S => stack_op!(unary i32 => f64, |v| f64::from(v)),
- F64ConvertI64S => stack_op!(unary i64 => f64, |v| v as f64),
- F32ConvertI32U => stack_op!(unary u32 => f32, |v| v as f32),
- F32ConvertI64U => stack_op!(unary u64 => f32, |v| v as f32),
- F64ConvertI32U => stack_op!(unary u32 => f64, |v| f64::from(v)),
- F64ConvertI64U => stack_op!(unary u64 => f64, |v| v as f64),
-
- // Sign-extension operations
- I32Extend8S => stack_op!(unary i32, |v| i32::from(v as i8)),
- I32Extend16S => stack_op!(unary i32, |v| i32::from(v as i16)),
- I64Extend8S => stack_op!(unary i64, |v| i64::from(v as i8)),
- I64Extend16S => stack_op!(unary i64, |v| i64::from(v as i16)),
- I64Extend32S => stack_op!(unary i64, |v| i64::from(v as i32)),
- I64ExtendI32U => stack_op!(unary u32 => i64, |v| i64::from(v)),
- I64ExtendI32S => stack_op!(unary i32 => i64, |v| i64::from(v)),
- I32WrapI64 => stack_op!(unary i64 => i32, |v| v as i32),
- F32DemoteF64 => stack_op!(unary f64 => f32, |v| v as f32),
- F64PromoteF32 => stack_op!(unary f32 => f64, |v| f64::from(v)),
- F32Abs => stack_op!(unary f32, |v| v.abs()),
- F64Abs => stack_op!(unary f64, |v| v.abs()),
- F32Neg => stack_op!(unary f32, |v| -v),
- F64Neg => stack_op!(unary f64, |v| -v),
- F32Ceil => stack_op!(unary f32, |v| v.ceil()),
- F64Ceil => stack_op!(unary f64, |v| v.ceil()),
- F32Floor => stack_op!(unary f32, |v| v.floor()),
- F64Floor => stack_op!(unary f64, |v| v.floor()),
- F32Trunc => stack_op!(unary f32, |v| v.trunc()),
- F64Trunc => stack_op!(unary f64, |v| v.trunc()),
- F32Nearest => stack_op!(unary f32, |v| v.tw_nearest()),
- F64Nearest => stack_op!(unary f64, |v| v.tw_nearest()),
- F32Sqrt => stack_op!(unary f32, |v| v.sqrt()),
- F64Sqrt => stack_op!(unary f64, |v| v.sqrt()),
- F32Min => stack_op!(binary f32, |a, b| a.tw_minimum(b)),
- F64Min => stack_op!(binary f64, |a, b| a.tw_minimum(b)),
- F32Max => stack_op!(binary f32, |a, b| a.tw_maximum(b)),
- F64Max => stack_op!(binary f64, |a, b| a.tw_maximum(b)),
- F32Copysign => stack_op!(binary f32, |a, b| a.copysign(b)),
- F64Copysign => stack_op!(binary f64, |a, b| a.copysign(b)),
- I32TruncF32S => checked_conv_float!(f32, i32, self),
- I32TruncF64S => checked_conv_float!(f64, i32, self),
- I32TruncF32U => checked_conv_float!(f32, u32, i32, self),
- I32TruncF64U => checked_conv_float!(f64, u32, i32, self),
- I64TruncF32S => checked_conv_float!(f32, i64, self),
- I64TruncF64S => checked_conv_float!(f64, i64, self),
- I64TruncF32U => checked_conv_float!(f32, u64, i64, self),
- I64TruncF64U => checked_conv_float!(f64, u64, i64, self),
-
- // Non-trapping float-to-int conversions
- I32TruncSatF32S => stack_op!(unary f32 => i32, |v| v.trunc() as i32),
- I32TruncSatF32U => stack_op!(unary f32 => u32, |v| v.trunc() as u32),
- I32TruncSatF64S => stack_op!(unary f64 => i32, |v| v.trunc() as i32),
- I32TruncSatF64U => stack_op!(unary f64 => u32, |v| v.trunc() as u32),
- I64TruncSatF32S => stack_op!(unary f32 => i64, |v| v.trunc() as i64),
- I64TruncSatF32U => stack_op!(unary f32 => u64, |v| v.trunc() as u64),
- I64TruncSatF64S => stack_op!(unary f64 => i64, |v| v.trunc() as i64),
- I64TruncSatF64U => stack_op!(unary f64 => u64, |v| v.trunc() as u64),
-
- // SIMD extension
- V128Not => stack_op!(unary Value128, |v| v.v128_not()),
- V128And => stack_op!(binary Value128, |a, b| a.v128_and(b)),
- V128AndNot => stack_op!(binary Value128, |a, b| a.v128_andnot(b)),
- V128Or => stack_op!(binary Value128, |a, b| a.v128_or(b)),
- V128Xor => stack_op!(binary Value128, |a, b| a.v128_xor(b)),
- V128Bitselect => stack_op!(ternary Value128, |a, b, c| Value128::v128_bitselect(a, b, c)),
- V128AnyTrue => stack_op!(unary Value128 => i32, |v| v.v128_any_true() as i32),
- I8x16Swizzle => stack_op!(binary Value128, |a, s| a.i8x16_swizzle(s)),
- I8x16RelaxedSwizzle => stack_op!(binary Value128, |a, s| a.i8x16_relaxed_swizzle(s)),
- V128Load(arg) => self.exec_mem_load::<Value128, 16, _>(arg.mem_addr(), arg.offset(), |v| v)?,
- V128Load8x8S(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?,
- V128Load8x8U(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?,
- V128Load16x4S(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?,
- V128Load16x4U(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?,
- V128Load32x2S(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?,
- V128Load32x2U(arg) => self.exec_mem_load::<u64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?,
- V128Load8Splat(arg) => self.exec_mem_load::<i8, 1, Value128>(arg.mem_addr(), arg.offset(), Value128::splat_i8)?,
- V128Load16Splat(arg) => self.exec_mem_load::<i16, 2, Value128>(arg.mem_addr(), arg.offset(), Value128::splat_i16)?,
- V128Load32Splat(arg) => self.exec_mem_load::<i32, 4, Value128>(arg.mem_addr(), arg.offset(), Value128::splat_i32)?,
- V128Load64Splat(arg) => self.exec_mem_load::<i64, 8, Value128>(arg.mem_addr(), arg.offset(), Value128::splat_i64)?,
- V128Store(arg) => self.exec_mem_store::<Value128, Value128, 16>(arg.mem_addr(), arg.offset(), |v| v)?,
- V128Store8Lane(arg, lane) => self.exec_mem_store_lane::<i8, 1>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Store16Lane(arg, lane) => self.exec_mem_store_lane::<i16, 2>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Store32Lane(arg, lane) => self.exec_mem_store_lane::<i32, 4>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Store64Lane(arg, lane) => self.exec_mem_store_lane::<i64, 8>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Load32Zero(arg) => self.exec_mem_load::<i32, 4, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?,
- V128Load64Zero(arg) => self.exec_mem_load::<i64, 8, Value128>(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?,
- Const128(arg) => self.exec_const(Value128(self.func.data.v128_const(*arg)))?,
- I8x16ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32),
- I8x16ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32),
- I16x8ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32),
- I16x8ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32),
- I32x4ExtractLane(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)),
- I64x2ExtractLane(lane) => stack_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)),
- F32x4ExtractLane(lane) => stack_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)),
- F64x2ExtractLane(lane) => stack_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)),
- V128Load8Lane(arg, lane) => self.exec_mem_load_lane::<i8, 1>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Load16Lane(arg, lane) => self.exec_mem_load_lane::<i16, 2>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Load32Lane(arg, lane) => self.exec_mem_load_lane::<i32, 4>(arg.mem_addr(), arg.offset(), *lane)?,
- V128Load64Lane(arg, lane) => self.exec_mem_load_lane::<i64, 8>(arg.mem_addr(), arg.offset(), *lane)?,
- I8x16ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)),
- I16x8ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)),
- I32x4ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)),
- I64x2ReplaceLane(lane) => stack_op!(binary i64, Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)),
- F32x4ReplaceLane(lane) => stack_op!(binary f32, Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)),
- F64x2ReplaceLane(lane) => stack_op!(binary f64, Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)),
- I8x16Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)),
- I16x8Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)),
- I32x4Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i32(v)),
- I64x2Splat => stack_op!(unary i64 => Value128, |v| Value128::splat_i64(v)),
- F32x4Splat => stack_op!(unary f32 => Value128, |v| Value128::splat_f32(v)),
- F64x2Splat => stack_op!(unary f64 => Value128, |v| Value128::splat_f64(v)),
- I8x16Eq => stack_op!(binary Value128, |a, b| a.i8x16_eq(b)),
- I16x8Eq => stack_op!(binary Value128, |a, b| a.i16x8_eq(b)),
- I32x4Eq => stack_op!(binary Value128, |a, b| a.i32x4_eq(b)),
- I64x2Eq => stack_op!(binary Value128, |a, b| a.i64x2_eq(b)),
- F32x4Eq => stack_op!(binary Value128, |a, b| a.f32x4_eq(b)),
- F64x2Eq => stack_op!(binary Value128, |a, b| a.f64x2_eq(b)),
- I8x16Ne => stack_op!(binary Value128, |a, b| a.i8x16_ne(b)),
- I16x8Ne => stack_op!(binary Value128, |a, b| a.i16x8_ne(b)),
- I32x4Ne => stack_op!(binary Value128, |a, b| a.i32x4_ne(b)),
- I64x2Ne => stack_op!(binary Value128, |a, b| a.i64x2_ne(b)),
- F32x4Ne => stack_op!(binary Value128, |a, b| a.f32x4_ne(b)),
- F64x2Ne => stack_op!(binary Value128, |a, b| a.f64x2_ne(b)),
- I8x16LtS => stack_op!(binary Value128, |a, b| a.i8x16_lt_s(b)),
- I16x8LtS => stack_op!(binary Value128, |a, b| a.i16x8_lt_s(b)),
- I32x4LtS => stack_op!(binary Value128, |a, b| a.i32x4_lt_s(b)),
- I64x2LtS => stack_op!(binary Value128, |a, b| a.i64x2_lt_s(b)),
- I8x16LtU => stack_op!(binary Value128, |a, b| a.i8x16_lt_u(b)),
- I16x8LtU => stack_op!(binary Value128, |a, b| a.i16x8_lt_u(b)),
- I32x4LtU => stack_op!(binary Value128, |a, b| a.i32x4_lt_u(b)),
- F32x4Lt => stack_op!(binary Value128, |a, b| a.f32x4_lt(b)),
- F64x2Lt => stack_op!(binary Value128, |a, b| a.f64x2_lt(b)),
- F32x4Gt => stack_op!(binary Value128, |a, b| a.f32x4_gt(b)),
- F64x2Gt => stack_op!(binary Value128, |a, b| a.f64x2_gt(b)),
- I8x16GtS => stack_op!(binary Value128, |a, b| a.i8x16_gt_s(b)),
- I16x8GtS => stack_op!(binary Value128, |a, b| a.i16x8_gt_s(b)),
- I32x4GtS => stack_op!(binary Value128, |a, b| a.i32x4_gt_s(b)),
- I64x2GtS => stack_op!(binary Value128, |a, b| a.i64x2_gt_s(b)),
- I64x2LeS => stack_op!(binary Value128, |a, b| a.i64x2_le_s(b)),
- F32x4Le => stack_op!(binary Value128, |a, b| a.f32x4_le(b)),
- F64x2Le => stack_op!(binary Value128, |a, b| a.f64x2_le(b)),
- I8x16GtU => stack_op!(binary Value128, |a, b| a.i8x16_gt_u(b)),
- I16x8GtU => stack_op!(binary Value128, |a, b| a.i16x8_gt_u(b)),
- I32x4GtU => stack_op!(binary Value128, |a, b| a.i32x4_gt_u(b)),
- F32x4Ge => stack_op!(binary Value128, |a, b| a.f32x4_ge(b)),
- F64x2Ge => stack_op!(binary Value128, |a, b| a.f64x2_ge(b)),
- I8x16LeS => stack_op!(binary Value128, |a, b| a.i8x16_le_s(b)),
- I16x8LeS => stack_op!(binary Value128, |a, b| a.i16x8_le_s(b)),
- I32x4LeS => stack_op!(binary Value128, |a, b| a.i32x4_le_s(b)),
- I8x16LeU => stack_op!(binary Value128, |a, b| a.i8x16_le_u(b)),
- I16x8LeU => stack_op!(binary Value128, |a, b| a.i16x8_le_u(b)),
- I32x4LeU => stack_op!(binary Value128, |a, b| a.i32x4_le_u(b)),
- I8x16GeS => stack_op!(binary Value128, |a, b| a.i8x16_ge_s(b)),
- I16x8GeS => stack_op!(binary Value128, |a, b| a.i16x8_ge_s(b)),
- I32x4GeS => stack_op!(binary Value128, |a, b| a.i32x4_ge_s(b)),
- I64x2GeS => stack_op!(binary Value128, |a, b| a.i64x2_ge_s(b)),
- I8x16GeU => stack_op!(binary Value128, |a, b| a.i8x16_ge_u(b)),
- I16x8GeU => stack_op!(binary Value128, |a, b| a.i16x8_ge_u(b)),
- I32x4GeU => stack_op!(binary Value128, |a, b| a.i32x4_ge_u(b)),
- I8x16Abs => stack_op!(unary Value128, |a| a.i8x16_abs()),
- I16x8Abs => stack_op!(unary Value128, |a| a.i16x8_abs()),
- I32x4Abs => stack_op!(unary Value128, |a| a.i32x4_abs()),
- I64x2Abs => stack_op!(unary Value128, |a| a.i64x2_abs()),
- I8x16Neg => stack_op!(unary Value128, |a| a.i8x16_neg()),
- I16x8Neg => stack_op!(unary Value128, |a| a.i16x8_neg()),
- I32x4Neg => stack_op!(unary Value128, |a| a.i32x4_neg()),
- I64x2Neg => stack_op!(unary Value128, |a| a.i64x2_neg()),
- I8x16AllTrue => stack_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32),
- I16x8AllTrue => stack_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32),
- I32x4AllTrue => stack_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32),
- I64x2AllTrue => stack_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32),
- I8x16Bitmask => stack_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32),
- I16x8Bitmask => stack_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32),
- I32x4Bitmask => stack_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32),
- I64x2Bitmask => stack_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32),
- I8x16Shl => stack_op!(binary i32, Value128, |a, b| b.i8x16_shl(a as u32)),
- I16x8Shl => stack_op!(binary i32, Value128, |a, b| b.i16x8_shl(a as u32)),
- I32x4Shl => stack_op!(binary i32, Value128, |a, b| b.i32x4_shl(a as u32)),
- I64x2Shl => stack_op!(binary i32, Value128, |a, b| b.i64x2_shl(a as u32)),
- I8x16ShrS => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_s(a as u32)),
- I16x8ShrS => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_s(a as u32)),
- I32x4ShrS => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_s(a as u32)),
- I64x2ShrS => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_s(a as u32)),
- I8x16ShrU => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_u(a as u32)),
- I16x8ShrU => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_u(a as u32)),
- I32x4ShrU => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_u(a as u32)),
- I64x2ShrU => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_u(a as u32)),
- I8x16Add => stack_op!(binary Value128, |a, b| a.i8x16_add(b)),
- I16x8Add => stack_op!(binary Value128, |a, b| a.i16x8_add(b)),
- I32x4Add => stack_op!(binary Value128, |a, b| a.i32x4_add(b)),
- I64x2Add => stack_op!(binary Value128, |a, b| a.i64x2_add(b)),
- I8x16Sub => stack_op!(binary Value128, |a, b| a.i8x16_sub(b)),
- I16x8Sub => stack_op!(binary Value128, |a, b| a.i16x8_sub(b)),
- I32x4Sub => stack_op!(binary Value128, |a, b| a.i32x4_sub(b)),
- I64x2Sub => stack_op!(binary Value128, |a, b| a.i64x2_sub(b)),
- I8x16MinS => stack_op!(binary Value128, |a, b| a.i8x16_min_s(b)),
- I16x8MinS => stack_op!(binary Value128, |a, b| a.i16x8_min_s(b)),
- I32x4MinS => stack_op!(binary Value128, |a, b| a.i32x4_min_s(b)),
- I8x16MinU => stack_op!(binary Value128, |a, b| a.i8x16_min_u(b)),
- I16x8MinU => stack_op!(binary Value128, |a, b| a.i16x8_min_u(b)),
- I32x4MinU => stack_op!(binary Value128, |a, b| a.i32x4_min_u(b)),
- I8x16MaxS => stack_op!(binary Value128, |a, b| a.i8x16_max_s(b)),
- I16x8MaxS => stack_op!(binary Value128, |a, b| a.i16x8_max_s(b)),
- I32x4MaxS => stack_op!(binary Value128, |a, b| a.i32x4_max_s(b)),
- I8x16MaxU => stack_op!(binary Value128, |a, b| a.i8x16_max_u(b)),
- I16x8MaxU => stack_op!(binary Value128, |a, b| a.i16x8_max_u(b)),
- I32x4MaxU => stack_op!(binary Value128, |a, b| a.i32x4_max_u(b)),
- I64x2Mul => stack_op!(binary Value128, |a, b| a.i64x2_mul(b)),
- I16x8Mul => stack_op!(binary Value128, |a, b| a.i16x8_mul(b)),
- I32x4Mul => stack_op!(binary Value128, |a, b| a.i32x4_mul(b)),
- I8x16NarrowI16x8S => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)),
- I8x16NarrowI16x8U => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)),
- I16x8NarrowI32x4S => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)),
- I16x8NarrowI32x4U => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)),
- I8x16AddSatS => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_s(b)),
- I16x8AddSatS => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_s(b)),
- I8x16AddSatU => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_u(b)),
- I16x8AddSatU => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_u(b)),
- I8x16SubSatS => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_s(b)),
- I16x8SubSatS => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_s(b)),
- I8x16SubSatU => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_u(b)),
- I16x8SubSatU => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_u(b)),
- I8x16AvgrU => stack_op!(binary Value128, |a, b| a.i8x16_avgr_u(b)),
- I16x8AvgrU => stack_op!(binary Value128, |a, b| a.i16x8_avgr_u(b)),
- I16x8ExtAddPairwiseI8x16S => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()),
- I16x8ExtAddPairwiseI8x16U => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()),
- I32x4ExtAddPairwiseI16x8S => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()),
- I32x4ExtAddPairwiseI16x8U => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()),
- I16x8ExtMulLowI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)),
- I16x8ExtMulLowI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)),
- I16x8ExtMulHighI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)),
- I16x8ExtMulHighI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)),
- I32x4ExtMulLowI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)),
- I32x4ExtMulLowI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)),
- I32x4ExtMulHighI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)),
- I32x4ExtMulHighI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)),
- I64x2ExtMulLowI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)),
- I64x2ExtMulLowI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)),
- I64x2ExtMulHighI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)),
- I64x2ExtMulHighI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)),
- I16x8ExtendLowI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_s()),
- I16x8ExtendLowI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_u()),
- I16x8ExtendHighI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_s()),
- I16x8ExtendHighI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_u()),
- I32x4ExtendLowI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_s()),
- I32x4ExtendLowI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_u()),
- I32x4ExtendHighI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_s()),
- I32x4ExtendHighI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_u()),
- I64x2ExtendLowI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_s()),
- I64x2ExtendLowI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_u()),
- I64x2ExtendHighI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_s()),
- I64x2ExtendHighI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_u()),
- I8x16Popcnt => stack_op!(unary Value128, |v| v.i8x16_popcnt()),
- I8x16Shuffle(idx) => stack_op!(binary Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))),
- I16x8Q15MulrSatS => stack_op!(binary Value128, |a, b| a.i16x8_q15mulr_sat_s(b)),
- I32x4DotI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_dot_i16x8_s(b)),
- I8x16RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)),
- I16x8RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)),
- I32x4RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)),
- I64x2RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)),
- I16x8RelaxedQ15mulrS => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)),
- I16x8RelaxedDotI8x16I7x16S => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)),
- I32x4RelaxedDotI8x16I7x16AddS => stack_op!(ternary Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)),
- F32x4Ceil => stack_op!(unary Value128, |v| v.f32x4_ceil()),
- F64x2Ceil => stack_op!(unary Value128, |v| v.f64x2_ceil()),
- F32x4Floor => stack_op!(unary Value128, |v| v.f32x4_floor()),
- F64x2Floor => stack_op!(unary Value128, |v| v.f64x2_floor()),
- F32x4Trunc => stack_op!(unary Value128, |v| v.f32x4_trunc()),
- F64x2Trunc => stack_op!(unary Value128, |v| v.f64x2_trunc()),
- F32x4Nearest => stack_op!(unary Value128, |v| v.f32x4_nearest()),
- F64x2Nearest => stack_op!(unary Value128, |v| v.f64x2_nearest()),
- F32x4Abs => stack_op!(unary Value128, |v| v.f32x4_abs()),
- F64x2Abs => stack_op!(unary Value128, |v| v.f64x2_abs()),
- F32x4Neg => stack_op!(unary Value128, |v| v.f32x4_neg()),
- F64x2Neg => stack_op!(unary Value128, |v| v.f64x2_neg()),
- F32x4Sqrt => stack_op!(unary Value128, |v| v.f32x4_sqrt()),
- F64x2Sqrt => stack_op!(unary Value128, |v| v.f64x2_sqrt()),
- F32x4Add => stack_op!(binary Value128, |a, b| a.f32x4_add(b)),
- F64x2Add => stack_op!(binary Value128, |a, b| a.f64x2_add(b)),
- F32x4Sub => stack_op!(binary Value128, |a, b| a.f32x4_sub(b)),
- F64x2Sub => stack_op!(binary Value128, |a, b| a.f64x2_sub(b)),
- F32x4Mul => stack_op!(binary Value128, |a, b| a.f32x4_mul(b)),
- F64x2Mul => stack_op!(binary Value128, |a, b| a.f64x2_mul(b)),
- F32x4Div => stack_op!(binary Value128, |a, b| a.f32x4_div(b)),
- F64x2Div => stack_op!(binary Value128, |a, b| a.f64x2_div(b)),
- F32x4Min => stack_op!(binary Value128, |a, b| a.f32x4_min(b)),
- F64x2Min => stack_op!(binary Value128, |a, b| a.f64x2_min(b)),
- F32x4Max => stack_op!(binary Value128, |a, b| a.f32x4_max(b)),
- F64x2Max => stack_op!(binary Value128, |a, b| a.f64x2_max(b)),
- F32x4PMin => stack_op!(binary Value128, |a, b| a.f32x4_pmin(b)),
- F32x4PMax => stack_op!(binary Value128, |a, b| a.f32x4_pmax(b)),
- F64x2PMin => stack_op!(binary Value128, |a, b| a.f64x2_pmin(b)),
- F64x2PMax => stack_op!(binary Value128, |a, b| a.f64x2_pmax(b)),
- F32x4RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)),
- F32x4RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)),
- F64x2RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)),
- F64x2RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)),
- F32x4RelaxedMin => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_min(b)),
- F32x4RelaxedMax => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_max(b)),
- F64x2RelaxedMin => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_min(b)),
- F64x2RelaxedMax => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_max(b)),
- I32x4TruncSatF32x4S => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_s()),
- I32x4TruncSatF32x4U => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_u()),
- F32x4ConvertI32x4S => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_s()),
- F32x4ConvertI32x4U => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_u()),
- F64x2ConvertLowI32x4S => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_s()),
- F64x2ConvertLowI32x4U => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_u()),
- F32x4DemoteF64x2Zero => stack_op!(unary Value128, |v| v.f32x4_demote_f64x2_zero()),
- F64x2PromoteLowF32x4 => stack_op!(unary Value128, |v| v.f64x2_promote_low_f32x4()),
- I32x4TruncSatF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()),
- I32x4TruncSatF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()),
- I32x4RelaxedTruncF32x4S => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()),
- I32x4RelaxedTruncF32x4U => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()),
- I32x4RelaxedTruncF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()),
- I32x4RelaxedTruncF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()),
- };
-
- self.cf.instr_ptr += 1;
-
- Ok(None)
- }
-
- #[inline(always)]
- fn jump_if(&mut self, condition: bool, ip: u32) -> bool {
- if condition {
- self.cf.instr_ptr = ip as usize;
- }
- condition
- }
-
- #[inline(always)]
- fn exec_jump_zero_32(&mut self, target_ip: u32) -> bool {
- let cond = <i32>::stack_pop(&mut self.store.value_stack) == 0;
- self.jump_if(cond, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_non_zero_32(&mut self, target_ip: u32) -> bool {
- let cond = <i32>::stack_pop(&mut self.store.value_stack) != 0;
- self.jump_if(cond, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_zero_64(&mut self, target_ip: u32) -> bool {
- let cond = <i64>::stack_pop(&mut self.store.value_stack) == 0;
- self.jump_if(cond, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_non_zero_64(&mut self, target_ip: u32) -> bool {
- let cond = <i64>::stack_pop(&mut self.store.value_stack) != 0;
- self.jump_if(cond, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_ref_null(&mut self, target_ip: u32) -> bool {
- let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null();
- if is_null {
- ValueRef::stack_pop(&mut self.store.value_stack);
- }
- self.jump_if(is_null, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_ref_non_null(&mut self, target_ip: u32) -> bool {
- let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null();
- if !is_non_null {
- ValueRef::stack_pop(&mut self.store.value_stack);
- }
- self.jump_if(is_non_null, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_local_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool {
- self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_local_non_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool {
- self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_local_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool {
- self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_local_non_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool {
- self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_stack_const_32(&mut self, target_ip: u32, imm: i32, op: CmpOp) -> bool {
- let condition = cmp_i32(<i32>::stack_pop(&mut self.store.value_stack), imm, op);
- self.jump_if(condition, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_stack_const_64(&mut self, target_ip: u32, imm: i64, op: CmpOp) -> bool {
- let condition = cmp_i64(<i64>::stack_pop(&mut self.store.value_stack), imm, op);
- self.jump_if(condition, target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_local_const_32(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool {
- self.jump_if(cmp_i32(i32::local_get(&self.store.value_stack, &self.cf, local), imm, op), target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_local_const_64(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool {
- self.jump_if(cmp_i64(i64::local_get(&self.store.value_stack, &self.cf, local), i64::from(imm), op), target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_local_local_32(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool {
- let lhs = i32::local_get(&self.store.value_stack, &self.cf, left);
- let rhs = i32::local_get(&self.store.value_stack, &self.cf, right);
- self.jump_if(cmp_i32(lhs, rhs, op), target_ip)
- }
-
- #[inline(always)]
- fn exec_jump_cmp_local_local_64(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool {
- let lhs = i64::local_get(&self.store.value_stack, &self.cf, left);
- let rhs = i64::local_get(&self.store.value_stack, &self.cf, right);
- self.jump_if(cmp_i64(lhs, rhs, op), target_ip)
- }
-
- fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) {
- let idx = <i32>::stack_pop(&mut self.store.value_stack);
- let target_ip = if idx >= 0 && (idx as u32) < len {
- self.func.data.branch_table_targets.get((start + idx as u32) as usize).copied().unwrap_or(default_ip)
- } else {
- default_ip
- };
-
- self.cf.instr_ptr = target_ip as usize;
- }
-
- fn exec_drop_keep(&mut self, drop_keep: DropKeep) {
- let mut base = self.cf.stack_base();
- base.s32 += drop_keep.base.c32 as u32;
- base.s64 += drop_keep.base.c64 as u32;
- base.s128 += drop_keep.base.c128 as u32;
- self.store.value_stack.truncate_keep_counts(base, drop_keep.keep);
- }
-
- fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> {
- if !Arc::ptr_eq(&self.func, &wasm_func.func) {
- self.func = wasm_func.func.clone();
- }
-
- let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)
- else {
- cold_path();
- return Err(Trap::CallStackOverflow);
- };
-
- self.store.call_stack.push(self.cf)?;
- self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals);
- if wasm_func.owner != self.module.id() {
- self.module = self.store.get_module_instance_internal(wasm_func.owner);
- }
-
- Ok(())
- }
-
- fn exec_return_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> {
- if !Arc::ptr_eq(&self.func, &wasm_func.func) {
- self.func = wasm_func.func.clone();
- }
-
- self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.func.params);
- let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)
- else {
- cold_path();
- return Err(Trap::CallStackOverflow);
- };
- self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals);
- if wasm_func.owner != self.module.id() {
- self.module = self.store.get_module_instance_internal(wasm_func.owner);
- }
-
- Ok(())
- }
-
- fn exec_call_host<const TAIL: bool>(
- &mut self,
- host_func: Arc<HostFunction>,
- type_addr: TypeAddr,
- ) -> 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<_>>();
- params.reverse();
- 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,
- Err(err) => {
- cold_path();
- return Err(Trap::HostFunction(Box::new(err)));
- }
- };
-
- self.store.value_stack.extend_from_wasmvalues(&res)?;
- if TAIL {
- Ok(self.exec_return())
- } else {
- self.cf.instr_ptr += 1;
- Ok(false)
- }
- }
-
- fn exec_call_direct(&mut self, v: u32) -> Result<(), Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
- let addr = self.module.resolve_func_addr(v);
- let func = self.store.state.get_func(addr).clone();
- 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)?;
- Ok(())
- }
- }
- }
-
- fn exec_return_call_direct(&mut self, v: u32) -> Result<bool, Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
- let addr = self.module.resolve_func_addr(v);
- let func = self.store.state.get_func(addr).clone();
- match func.kind {
- crate::store::FunctionKind::Wasm(wasm_func) => {
- 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),
- }
- }
-
- fn exec_call_self(&mut self) -> Result<(), Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
-
- self.store.call_stack.push(self.cf)?;
- let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
- cold_path();
- return Err(Trap::CallStackOverflow);
- };
- self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
-
- Ok(())
- }
-
- fn exec_return_call_self(&mut self) -> Result<(), Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
-
- self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params);
- let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
- cold_path();
- return Err(Trap::CallStackOverflow);
- };
- self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
- Ok(())
- }
-
- fn exec_call_indirect<const IS_RETURN_CALL: bool>(
- &mut self,
- type_addr: u32,
- table_addr: u32,
- ) -> Result<bool, Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
-
- // verify that the table is of the right type, this should be validated by the parser already
- 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();
- return Err(Trap::UndefinedElement { index: table_idx });
- };
-
- let Some(func_ref) = table.addr() else {
- cold_path();
- return Err(Trap::UninitializedElement { index: table_idx });
- };
-
- self.exec_typed_call::<IS_RETURN_CALL>(func_ref, self.module.resolve_type_addr(type_addr))
- }
-
- fn exec_typed_call<const IS_RETURN_CALL: bool>(
- &mut self,
- func_addr: FuncAddr,
- expected_type_addr: TypeAddr,
- ) -> Result<bool, Trap> {
- let func = self.store.state.get_func(func_addr).clone();
- if 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()),
- });
- }
- match func.kind {
- crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL {
- true => self.exec_return_call(wasm_func, func_addr),
- 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);
- }
- }?;
- Ok(false)
- }
-
- fn exec_call_ref<const IS_RETURN_CALL: bool>(&mut self, type_addr: u32) -> Result<bool, Trap> {
- self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
- let func_ref = ValueRef::stack_pop(&mut self.store.value_stack);
- let Some(func_addr) = func_ref.addr() else {
- cold_path();
- return Err(Trap::NullFunctionReference);
- };
-
- self.exec_typed_call::<IS_RETURN_CALL>(func_addr, self.module.resolve_type_addr(type_addr))
- }
-
- fn exec_return(&mut self) -> bool {
- self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.results);
- self.finish_return()
- }
-
- #[inline(always)]
- fn finish_return(&mut self) -> bool {
- let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else {
- return true;
- };
- if caller.func_addr == self.cf.func_addr {
- self.cf = caller;
- return false;
- }
- let wasm_func = self.store.state.get_wasm_func(caller.func_addr);
- self.func = wasm_func.func.clone();
- if wasm_func.owner != self.module.id() {
- self.module = self.store.get_module_instance_internal(wasm_func.owner);
- }
- self.cf = caller;
- false
- }
-
- #[inline(always)]
- fn exec_return_void(&mut self) -> bool {
- self.store.value_stack.truncate_to_base(self.cf.locals_base);
- self.finish_return()
- }
-
- #[inline(always)]
- fn exec_return_32(&mut self) -> bool {
- self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize);
- self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
- self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize);
- self.finish_return()
- }
-
- #[inline(always)]
- fn exec_return_64(&mut self) -> bool {
- self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
- self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize);
- self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize);
- self.finish_return()
- }
-
- #[inline(always)]
- fn exec_return_128(&mut self) -> bool {
- self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
- self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
- self.store.value_stack.stack_128.truncate_to_one_tail(self.cf.locals_base.s128 as usize);
- self.finish_return()
- }
-
- fn exec_store_local_local<T: InternalValue + MemValue<N>, const N: usize>(
- &mut self,
- memarg: MemoryArg,
- addr_local: u8,
- value_local: u8,
- ) -> Result<(), Trap> {
- let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local));
- let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(memarg.mem_addr()));
- let addr = mem.effective_addr_32::<N>(base, memarg.offset())?;
- value.store_at(&mut *mem.inner, addr)?;
- Ok(())
- }
-
- #[inline(always)]
- fn exec_inc_memory_local<T: MemValue<N>, const N: usize>(
- &mut self,
- memarg: MemoryArg,
- addr_local: u8,
- increment: impl FnOnce(T) -> T,
- ) -> Result<(), Trap> {
- let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr());
- let mem = self.store.state.get_mem(mem_addr);
- let addr = if mem.is_64bit() {
- let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
- mem.effective_addr_64::<N>(base, memarg.offset())?
- } else {
- let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- mem.effective_addr_32::<N>(base, memarg.offset())?
- };
-
- let mem = self.store.state.get_mem_mut(mem_addr);
- let value = T::load_at(&*mem.inner, addr)?;
- increment(value).store_at(&mut *mem.inner, addr)
- }
-
- #[inline(always)]
- fn exec_fma_store<
- T: InternalValue + MemValue<N> + core::ops::Add<Output = T> + core::ops::Mul<Output = T>,
- const N: usize,
- >(
- &mut self,
- m: MemoryArg,
- ) -> Result<(), Trap> {
- let rhs = T::stack_pop(&mut self.store.value_stack);
- let lhs = T::stack_pop(&mut self.store.value_stack);
- let acc = T::stack_pop(&mut self.store.value_stack);
- let addr = i32::stack_pop(&mut self.store.value_stack);
- let fma = acc + lhs * rhs;
- let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(m.mem_addr()));
- let addr = mem.effective_addr_32::<N>(addr as u32, m.offset())?;
- fma.store_at(&mut *mem.inner, addr)?;
- Ok(())
- }
-
- #[inline(always)]
- fn exec_binop_acc_local<T, M, A>(&mut self, acc: LocalAddr, mul: M, add: A)
- where
- T: InternalValue,
- M: Fn(T, T) -> T,
- A: Fn(T, T) -> T,
- {
- let rhs = T::stack_pop(&mut self.store.value_stack);
- let lhs = T::stack_pop(&mut self.store.value_stack);
- T::local_update(&mut self.store.value_stack, &self.cf, acc, |v| add(mul(lhs, rhs), v));
- }
-
- fn exec_load_local_value<T: MemValue<N>, const N: usize>(
- &self,
- memarg: MemoryArg,
- addr_local: u8,
- ) -> Result<T, Trap> {
- let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr()));
- let addr = if mem.is_64bit() {
- let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
- mem.effective_addr_64::<N>(base, memarg.offset())?
- } else {
- let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- mem.effective_addr_32::<N>(base, memarg.offset())?
- };
- match T::load_at(&*mem.inner, addr) {
- Ok(res) => Ok(res),
- Err(err) => {
- cold_path();
- Err(err)
- }
- }
- }
-
- fn exec_load_local_tee<LOAD: MemValue<N>, const N: usize, TARGET: InternalValue>(
- &mut self,
- memarg: MemoryArg,
- addr_local: u8,
- dst_local: u8,
- cast: impl Fn(LOAD) -> TARGET,
- ) -> Result<(), Trap> {
- let value = cast(self.exec_load_local_value::<LOAD, N>(memarg, addr_local)?);
- TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value);
- self.store.value_stack.push(value)?;
- Ok(())
- }
-
- fn exec_load_local_set<LOAD: MemValue<N>, const N: usize, TARGET: InternalValue>(
- &mut self,
- memarg: MemoryArg,
- addr_local: u8,
- dst_local: u8,
- cast: impl Fn(LOAD) -> TARGET,
- ) -> Result<(), Trap> {
- let value = cast(self.exec_load_local_value::<LOAD, N>(memarg, addr_local)?);
- TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value);
- Ok(())
- }
-
- fn exec_global_get(&mut self, global_index: u32) -> Result<(), Trap> {
- self.store.value_stack.push_dyn(self.store.state.get_global_val(self.module.resolve_global_addr(global_index)))
- }
-
- fn exec_global_set<T: InternalValue>(&mut self, global_index: u32) {
- let global_addr = self.module.resolve_global_addr(global_index);
- let value = <T>::stack_pop(&mut self.store.value_stack).into();
- self.store.state.set_global_val(global_addr, value);
- }
-
- fn exec_global_set_32(&mut self, global_index: u32) {
- let global_addr = self.module.resolve_global_addr(global_index);
- let raw = <Value32>::stack_pop(&mut self.store.value_stack);
- let value = match self.store.state.get_global(global_addr).ty.ty {
- WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(raw),
- WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(raw)),
- WasmType::I64 | WasmType::F64 | WasmType::V128 => unreachable!("invalid global.set.32 target type"),
- };
- self.store.state.set_global_val(global_addr, value);
- }
-
- fn exec_const<T: InternalValue>(&mut self, val: T) -> Result<(), Trap> {
- self.store.value_stack.push(val)
- }
-
- fn exec_ref_is_null(&mut self) -> Result<(), Trap> {
- let is_null = i32::from(<ValueRef>::stack_pop(&mut self.store.value_stack).is_null());
- self.store.value_stack.push::<i32>(is_null)
- }
-
- fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> {
- if ValueRef::stack_peek(&self.store.value_stack).is_null() {
- cold_path();
- return Err(Trap::NullReference);
- }
- 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() {
- true => self.store.value_stack.push::<i64>(mem.page_count as i64),
- false => self.store.value_stack.push::<i32>(mem.page_count as i32),
- }
- }
-
- fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> {
- let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(addr));
- let is_64bit = mem.is_64bit();
- let pages_delta = match is_64bit {
- true => <i64>::stack_pop(&mut self.store.value_stack),
- false => i64::from(<i32>::stack_pop(&mut self.store.value_stack)),
- };
-
- let size = mem.grow(pages_delta, self.store.engine.config().trap_on_oom())?.unwrap_or(-1);
- match is_64bit {
- true => self.store.value_stack.push::<i64>(size)?,
- false => self.store.value_stack.push::<i32>(size as i32)?,
- };
-
- Ok(())
- }
-
- fn exec_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<(), Trap> {
- let size = i32::stack_pop(&mut self.store.value_stack);
- let src = i32::stack_pop(&mut self.store.value_stack);
- let dst = i32::stack_pop(&mut self.store.value_stack);
- let dst_mem_addr = self.module.resolve_mem_addr(dst_mem);
-
- if dst_mem == src_mem {
- // copy within the same memory
- let mem = self.store.state.get_mem_mut(dst_mem_addr);
- mem.copy_within(dst as usize, src as usize, size as usize)?;
- } else {
- // copy between two memories
- let src_mem_addr = self.module.resolve_mem_addr(src_mem);
- let (dst_memory, src_memory) = self.store.state.get_mems_mut(dst_mem_addr, src_mem_addr);
- dst_memory.copy_from_memory(dst as usize, src_memory, src as usize, size as usize)?;
- }
- Ok(())
- }
-
- fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> {
- let size = i32::stack_pop(&mut self.store.value_stack);
- let val = i32::stack_pop(&mut self.store.value_stack);
- let dst = i32::stack_pop(&mut self.store.value_stack);
- self.exec_memory_fill_impl(addr, dst, val as u8, size)
- }
-
- fn exec_memory_fill_imm(&mut self, addr: u32, val: u8, size: i32) -> Result<(), Trap> {
- let dst = i32::stack_pop(&mut self.store.value_stack);
- self.exec_memory_fill_impl(addr, dst, val, size)
- }
-
- fn exec_memory_fill_impl(&mut self, addr: u32, dst: i32, val: u8, size: i32) -> Result<(), Trap> {
- let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(addr));
- if mem.inner.fill(dst as usize, size as usize, val).is_none() {
- cold_path();
- return Err(Trap::MemoryOutOfBounds {
- offset: dst as usize,
- len: size as usize,
- max: self.store.state.get_mem(self.module.resolve_mem_addr(addr)).inner.len(),
- });
- }
- Ok(())
- }
-
- fn exec_memory_init(&mut self, data_index: u32, mem_index: u32) -> Result<(), Trap> {
- let size = i32::stack_pop(&mut self.store.value_stack);
- let offset = i32::stack_pop(&mut self.store.value_stack);
- let dst = i32::stack_pop(&mut self.store.value_stack);
-
- let data = &self.store.state.data[self.module.resolve_data_addr(data_index) as usize];
- let mem = &mut self.store.state.memories[self.module.resolve_mem_addr(mem_index) as usize];
- let data_len = data.data.as_ref().map_or(0, |d| d.len());
- if ((size + offset) as usize > data_len) || ((dst + size) as usize > mem.inner.len()) {
- cold_path();
- return Err(Trap::MemoryOutOfBounds { offset: offset as usize, len: size as usize, max: data_len });
- }
-
- if size == 0 {
- return Ok(());
- }
-
- let Some(data) = &data.data else {
- cold_path();
- return Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 });
- };
-
- if mem.inner.write_all(dst as usize, &data[offset as usize..((offset + size) as usize)]).is_none() {
- cold_path();
- return Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max: mem.inner.len() });
- }
- Ok(())
- }
-
- fn exec_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<(), Trap> {
- let dst_table_addr = self.module.resolve_table_addr(dst_table);
- let src_table_addr = self.module.resolve_table_addr(src_table);
- let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch();
- let src_arch = self.store.state.get_table(src_table_addr).kind.arch();
- let len_arch =
- if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 };
- let size = self.pop_table_operand(len_arch)?;
- let src = self.pop_table_operand(src_arch)?;
- let dst = self.pop_table_operand(dst_arch)?;
-
- if dst_table_addr == src_table_addr {
- // copy within the same table
- self.store.state.get_table_mut(dst_table_addr).copy_within(dst, src, size)
- } else {
- // copy between two tables
- let (dst_table_ref, src_table_ref) = self.store.state.get_tables_mut(dst_table_addr, src_table_addr);
- dst_table_ref.copy_from_slice(dst, src_table_ref.load(src, size)?)
- }
- }
-
- fn exec_mem_load_lane<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize>(
- &mut self,
- mem_addr: tinywasm_types::MemAddr,
- offset: u64,
- lane: u8,
- ) -> Result<(), Trap> {
- let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr));
- let addr = Self::pop_memory_addr::<LOAD_SIZE>(&mut self.store.value_stack, mem, offset)?;
- let val = LOAD::load_at(&*mem.inner, addr)?;
- let offset = lane as usize * LOAD_SIZE;
- let mut imm = <Value128>::stack_pop(&mut self.store.value_stack).to_mem_bytes();
- imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes());
- self.store.value_stack.push(Value128(imm))?;
- Ok(())
- }
-
- #[inline(always)]
- fn exec_mem_load<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize, TARGET: InternalValue>(
- &mut self,
- mem_addr: tinywasm_types::MemAddr,
- offset: u64,
- cast: impl Fn(LOAD) -> TARGET,
- ) -> Result<(), Trap> {
- let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr));
- let addr = Self::pop_memory_addr::<LOAD_SIZE>(&mut self.store.value_stack, mem, offset)?;
-
- match LOAD::load_at(&*mem.inner, addr) {
- Ok(val) => {
- self.store.value_stack.push(cast(val))?;
- Ok(())
- }
- Err(e) => {
- cold_path();
- Err(e)
- }
- }
- }
-
- fn exec_mem_store_lane<U: MemValue<N> + Copy, const N: usize>(
- &mut self,
- mem_addr: tinywasm_types::MemAddr,
- offset: u64,
- lane: u8,
- ) -> Result<(), Trap> {
- let bytes = <Value128>::stack_pop(&mut self.store.value_stack).to_mem_bytes();
- let lane_offset = lane as usize * N;
- let mut val_bytes = [0u8; N];
- val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]);
- let val = U::from_mem_bytes(val_bytes);
- let mem_addr = self.module.resolve_mem_addr(mem_addr);
- let mem = self.store.state.get_mem_mut(mem_addr);
- let addr = Self::pop_memory_addr::<N>(&mut self.store.value_stack, mem, offset)?;
- match val.store_at(&mut *mem.inner, addr) {
- Ok(()) => Ok(()),
- Err(e) => {
- cold_path();
- Err(e)
- }
- }
- }
-
- fn exec_mem_store<T: InternalValue, U: MemValue<N>, const N: usize>(
- &mut self,
- mem_addr: tinywasm_types::MemAddr,
- offset: u64,
- cast: impl Fn(T) -> U,
- ) -> Result<(), Trap> {
- let val = <T>::stack_pop(&mut self.store.value_stack);
- let val = cast(val);
-
- let mem_addr = self.module.resolve_mem_addr(mem_addr);
- let mem = self.store.state.get_mem_mut(mem_addr);
- let addr = Self::pop_memory_addr::<N>(&mut self.store.value_stack, mem, offset)?;
- match val.store_at(&mut *mem.inner, addr) {
- Ok(()) => Ok(()),
- Err(e) => {
- cold_path();
- Err(e)
- }
- }
- }
-
- 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())
- }
-
- fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> {
- let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
- 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())
- }
-
- fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> {
- let table = self.store.state.get_table(self.module.resolve_table_addr(table_index));
- match table.kind.arch() {
- MemoryArch::I32 => self.store.value_stack.push(table.size() as i32),
- MemoryArch::I64 => self.store.value_stack.push(table.size() as i64),
- }
- }
-
- fn exec_table_init(&mut self, elem_index: u32, table_index: u32) -> Result<(), Trap> {
- let size = self.pop_table_operand(MemoryArch::I32)?; // n
- let offset = self.pop_table_operand(MemoryArch::I32)?; // s
- let table_addr = self.module.resolve_table_addr(table_index);
- let dst = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; // d
- let elem_addr = self.module.resolve_elem_addr(elem_index) as usize;
- let elem = self.store.state.elements.get(elem_addr).ok_or_else(|| Trap::Other("element not found"))?;
- let items = elem.items.as_deref().unwrap_or(&[]);
- let Some(end) = offset.checked_add(size) else {
- cold_path();
- return Err(Trap::TableOutOfBounds { offset, len: size, max: items.len() });
- };
- if end > items.len() {
- cold_path();
- return Err(Trap::TableOutOfBounds { offset, len: size, max: items.len() });
- }
-
- let table =
- self.store.state.tables.get_mut(table_addr as usize).ok_or_else(|| Trap::Other("table not found"))?;
- table.init(dst, &items[offset..end])
- }
-
- fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> {
- let table_addr = self.module.resolve_table_addr(table_index);
- let arch = self.store.state.get_table(table_addr).kind.arch();
- let n = self.pop_table_operand(arch)?;
- 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());
- match (arch, result) {
- (MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32),
- (MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32),
- (MemoryArch::I64, Ok(())) => self.store.value_stack.push(sz as i64),
- (MemoryArch::I64, Err(_)) => self.store.value_stack.push(-1_i64),
- }
- }
-
- fn exec_table_fill(&mut self, table_index: u32) -> Result<(), Trap> {
- let table_addr = self.module.resolve_table_addr(table_index);
- let arch = self.store.state.get_table(table_addr).kind.arch();
- 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())
- }
-
- fn pop_table_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> {
- let value = match arch {
- MemoryArch::I32 => <i32>::stack_pop(&mut self.store.value_stack) as u32 as u64,
- MemoryArch::I64 => <i64>::stack_pop(&mut self.store.value_stack) as u64,
- };
- usize::try_from(value).map_err(|_| Trap::TableOutOfBounds { offset: usize::MAX, len: 1, max: usize::MAX })
- }
-}
-
-impl<'store> Executor<'store, false> {
- #[inline(always)]
- pub(crate) fn run_to_completion(&mut self) -> Result<(), Trap> {
- // ideally we use `loop_match` / `become` once thats stabilized
- loop {
- if self.exec()?.is_some() {
- return Ok(());
- }
- }
- }
-
- #[cfg(feature = "std")]
- #[inline(always)]
- pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result<ExecState, Trap> {
- use crate::std::time::Instant;
- let start = Instant::now();
- if time_budget.is_zero() {
- return Ok(ExecState::Suspended(self.cf));
- }
-
- loop {
- for _ in 0..128 {
- if self.exec()?.is_some() {
- return Ok(ExecState::Completed);
- }
- }
-
- if start.elapsed() >= time_budget {
- return Ok(ExecState::Suspended(self.cf));
- }
- }
- }
-}
-
-impl<'store> Executor<'store, true> {
- #[inline(always)]
- pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result<ExecState, Trap> {
- self.store.execution_fuel = fuel;
- if self.store.execution_fuel == 0 {
- return Ok(ExecState::Suspended(self.cf));
- }
-
- loop {
- for _ in 0..128 {
- if self.exec()?.is_some() {
- return Ok(ExecState::Completed);
- }
- }
-
- self.store.execution_fuel = self.store.execution_fuel.saturating_sub(128);
- if self.store.execution_fuel == 0 {
- return Ok(ExecState::Suspended(self.cf));
- }
- }
- }
-}
-
-#[inline(always)]
-fn cmp_i32(lhs: i32, rhs: i32, op: CmpOp) -> bool {
- match op {
- CmpOp::Eq => lhs == rhs,
- CmpOp::Ne => lhs != rhs,
- CmpOp::LtS => lhs < rhs,
- CmpOp::LtU => (lhs as u32) < (rhs as u32),
- CmpOp::GtS => lhs > rhs,
- CmpOp::GtU => (lhs as u32) > (rhs as u32),
- CmpOp::LeS => lhs <= rhs,
- CmpOp::LeU => (lhs as u32) <= (rhs as u32),
- CmpOp::GeS => lhs >= rhs,
- CmpOp::GeU => (lhs as u32) >= (rhs as u32),
- }
-}
-
-#[inline(always)]
-fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool {
- match op {
- CmpOp::Eq => lhs == rhs,
- CmpOp::Ne => lhs != rhs,
- CmpOp::LtS => lhs < rhs,
- CmpOp::LtU => (lhs as u64) < (rhs as u64),
- CmpOp::GtS => lhs > rhs,
- CmpOp::GtU => (lhs as u64) > (rhs as u64),
- CmpOp::LeS => lhs <= rhs,
- CmpOp::LeU => (lhs as u64) <= (rhs as u64),
- CmpOp::GeS => lhs >= rhs,
- CmpOp::GeU => (lhs as u64) >= (rhs as u64),
- }
-}
diff --git a/crates/tinywasm/src/interpreter/executor/dispatch.rs b/crates/tinywasm/src/interpreter/executor/dispatch.rs
new file mode 100644
index 0000000..57efc54
--- /dev/null
+++ b/crates/tinywasm/src/interpreter/executor/dispatch.rs
@@ -0,0 +1,90 @@
+use super::*;
+
+macro_rules! define_stable_dispatch {
+ ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident;
+ $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => {
+ #[inline(always)]
+ fn exec_step($executor: &mut Self, $instr_ptr: usize) -> ExecResult<ExecFlow> {
+ macro_rules! $dispatch_next {
+ ($next_instr_ptr:expr) => {{
+ return Ok(ExecFlow::next($next_instr_ptr));
+ }};
+ }
+ macro_rules! $dispatch_flow {
+ ($flow:expr) => {{
+ return Ok($flow);
+ }};
+ }
+ use tinywasm_types::Instruction::*;
+ match &$executor.func.instructions[$instr_ptr] {
+ $($variant $(($($arg),*))? $({ $($field),* })? => $body,)*
+ }
+ Ok(ExecFlow::next($instr_ptr + 1))
+ }
+ };
+}
+
+impl Executor<'_> {
+ instruction_handlers!(define_stable_dispatch);
+
+ #[inline(always)]
+ pub(crate) fn run_to_completion(mut self) -> Result<()> {
+ let mut instr_ptr = self.cf.instr_ptr;
+ loop {
+ match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() {
+ Some(next_instr_ptr) => instr_ptr = next_instr_ptr,
+ None => return cold!(Ok(())),
+ }
+ }
+ }
+
+ #[cfg(feature = "std")]
+ #[inline(always)]
+ pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result<ExecState> {
+ use crate::std::time::Instant;
+
+ if time_budget.is_zero() {
+ return Ok(ExecState::Suspended(self.cf));
+ }
+ let start = Instant::now();
+ let mut instr_ptr = self.cf.instr_ptr;
+ loop {
+ for _ in 0..CHECKPOINT_INTERVAL {
+ match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() {
+ Some(next_instr_ptr) => instr_ptr = next_instr_ptr,
+ None => return Ok(ExecState::Completed),
+ }
+ }
+
+ if start.elapsed() >= time_budget {
+ self.cf.instr_ptr = instr_ptr;
+ return Ok(ExecState::Suspended(self.cf));
+ }
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result<ExecState> {
+ self.fuel_metered = true;
+ self.store.execution_fuel = fuel;
+ if self.store.execution_fuel == 0 {
+ return Ok(ExecState::Suspended(self.cf));
+ }
+
+ let mut instr_ptr = self.cf.instr_ptr;
+ loop {
+ for _ in 0..CHECKPOINT_INTERVAL {
+ match Self::exec_step(&mut self, instr_ptr)?.next_instr_ptr() {
+ Some(next_instr_ptr) => instr_ptr = next_instr_ptr,
+ None => return Ok(ExecState::Completed),
+ }
+ }
+
+ self.store.execution_fuel = self.store.execution_fuel.saturating_sub(CHECKPOINT_INTERVAL);
+ if self.store.execution_fuel == 0 {
+ self.cf.instr_ptr = instr_ptr;
+ return Ok(ExecState::Suspended(self.cf));
+ }
+ }
+ }
+}
diff --git a/crates/tinywasm/src/interpreter/executor/dispatch_become.rs b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs
new file mode 100644
index 0000000..c24f6ba
--- /dev/null
+++ b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs
@@ -0,0 +1,191 @@
+use super::*;
+
+struct Unbudgeted;
+struct Bounded;
+
+type UnbudgetedHandler = for<'store> fn(&mut Executor<'store>, usize, Instruction) -> ExecResult<()>;
+type BoundedHandler = for<'store> fn(&mut Executor<'store>, usize, Instruction, u32) -> ExecResult<()>;
+
+#[cold]
+#[inline(never)]
+fn instruction_handler_mismatch() -> ! {
+ unreachable!("instruction handler mismatch")
+}
+
+macro_rules! define_unbudgeted_tail_dispatch {
+ ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident;
+ $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => {
+ #[inline(always)]
+ fn handler_for(opcode: InstructionOpcode) -> UnbudgetedHandler {
+ static HANDLERS: [UnbudgetedHandler; InstructionOpcode::COUNT] = {
+ let mut handlers = [Unbudgeted::Unreachable as UnbudgetedHandler; InstructionOpcode::COUNT];
+ $(handlers[InstructionOpcode::$variant as usize] = Unbudgeted::$variant;)*
+ handlers
+ };
+ HANDLERS[opcode as usize]
+ }
+
+ $(
+ #[allow(non_snake_case, unreachable_code, unused_imports, unused_macros, unused_variables)]
+ fn $variant(
+ $executor: &mut Executor<'_>,
+ $instr_ptr: usize,
+ instruction: Instruction,
+ ) -> ExecResult<()> {
+ macro_rules! $dispatch_next {
+ ($next_instr_ptr:expr) => {{
+ let next_instr_ptr = $next_instr_ptr;
+ let instruction = $executor.func.instructions[next_instr_ptr];
+ let handler = Self::handler_for(instruction.opcode());
+ become handler($executor, next_instr_ptr, instruction);
+ }};
+ }
+ macro_rules! $dispatch_flow {
+ ($flow:expr) => {{
+ match $flow.next_instr_ptr() {
+ Some(next_instr_ptr) => $dispatch_next!(next_instr_ptr),
+ None => return cold!(Ok(())),
+ }
+ }};
+ }
+ use tinywasm_types::Instruction::*;
+ $(let $variant($($arg),*) = &instruction else {
+ cold!(instruction_handler_mismatch())
+ };)?
+ $(let $variant { $($field),* } = &instruction else {
+ cold!(instruction_handler_mismatch())
+ };)?
+ $body;
+ $dispatch_next!($instr_ptr + 1)
+ }
+ )*
+ };
+}
+
+macro_rules! define_bounded_tail_dispatch {
+ ($executor:ident, $instr_ptr:ident, $dispatch_next:ident, $dispatch_flow:ident;
+ $($variant:ident $(($($arg:pat),*))? $({ $($field:ident),* })? => $body:expr),* $(,)?) => {
+ #[inline(always)]
+ fn handler_for(opcode: InstructionOpcode) -> BoundedHandler {
+ static HANDLERS: [BoundedHandler; InstructionOpcode::COUNT] = {
+ let mut handlers = [Bounded::Unreachable as BoundedHandler; InstructionOpcode::COUNT];
+ $(handlers[InstructionOpcode::$variant as usize] = Bounded::$variant;)*
+ handlers
+ };
+ HANDLERS[opcode as usize]
+ }
+
+ $(
+ #[allow(non_snake_case, unreachable_code, unused_imports, unused_macros, unused_variables)]
+ fn $variant(
+ $executor: &mut Executor<'_>,
+ $instr_ptr: usize,
+ instruction: Instruction,
+ instructions_until_checkpoint: u32,
+ ) -> ExecResult<()> {
+ macro_rules! $dispatch_next {
+ ($next_instr_ptr:expr) => {{
+ let next_instr_ptr = $next_instr_ptr;
+ if instructions_until_checkpoint == 0 {
+ return cold!({
+ $executor.cf.instr_ptr = next_instr_ptr;
+ Ok(())
+ });
+ }
+
+ let instruction = $executor.func.instructions[next_instr_ptr];
+ let handler = Self::handler_for(instruction.opcode());
+ become handler($executor, next_instr_ptr, instruction, instructions_until_checkpoint - 1);
+ }};
+ }
+ macro_rules! $dispatch_flow {
+ ($flow:expr) => {{
+ match $flow.next_instr_ptr() {
+ Some(next_instr_ptr) => $dispatch_next!(next_instr_ptr),
+ None => return cold!({
+ $executor.completed = true;
+ Ok(())
+ }),
+ }
+ }};
+ }
+ use tinywasm_types::Instruction::*;
+ $(let $variant($($arg),*) = &instruction else {
+ cold!(instruction_handler_mismatch())
+ };)?
+ $(let $variant { $($field),* } = &instruction else {
+ cold!(instruction_handler_mismatch())
+ };)?
+ $body;
+ $dispatch_next!($instr_ptr + 1)
+ }
+ )*
+ };
+}
+
+impl Unbudgeted {
+ instruction_handlers!(define_unbudgeted_tail_dispatch);
+}
+
+impl Bounded {
+ instruction_handlers!(define_bounded_tail_dispatch);
+
+ #[inline(always)]
+ fn run(executor: &mut Executor<'_>) -> ExecResult<()> {
+ let instr_ptr = executor.cf.instr_ptr;
+ let instruction = executor.func.instructions[instr_ptr];
+ let handler = Self::handler_for(instruction.opcode());
+ handler(executor, instr_ptr, instruction, CHECKPOINT_INTERVAL - 1)
+ }
+}
+
+impl<'store> Executor<'store> {
+ #[inline(always)]
+ pub(crate) fn run_to_completion(mut self) -> Result<()> {
+ let instr_ptr = self.cf.instr_ptr;
+ let instruction = self.func.instructions[instr_ptr];
+ let handler = Unbudgeted::handler_for(instruction.opcode());
+ Ok(handler(&mut self, instr_ptr, instruction)?)
+ }
+
+ #[cfg(feature = "std")]
+ #[inline(always)]
+ pub(crate) fn run_with_time_budget(mut self, time_budget: core::time::Duration) -> Result<ExecState> {
+ use crate::std::time::Instant;
+
+ if time_budget.is_zero() {
+ return Ok(ExecState::Suspended(self.cf));
+ }
+ let start = Instant::now();
+
+ loop {
+ Bounded::run(&mut self)?;
+ if self.completed {
+ return cold!(Ok(ExecState::Completed));
+ }
+ if start.elapsed() >= time_budget {
+ return cold!(Ok(ExecState::Suspended(self.cf)));
+ }
+ }
+ }
+
+ #[inline(always)]
+ pub(crate) fn run_with_fuel(mut self, fuel: u32) -> Result<ExecState> {
+ self.fuel_metered = true;
+ self.store.execution_fuel = fuel;
+ if self.store.execution_fuel == 0 {
+ return Ok(ExecState::Suspended(self.cf));
+ }
+
+ loop {
+ Bounded::run(&mut self)?;
+ if self.completed {
+ return cold!(Ok(ExecState::Completed));
+ }
+ self.store.execution_fuel = self.store.execution_fuel.saturating_sub(CHECKPOINT_INTERVAL);
+ if self.store.execution_fuel == 0 {
+ return cold!(Ok(ExecState::Suspended(self.cf)));
+ }
+ }
+ }
+}
diff --git a/crates/tinywasm/src/interpreter/executor/instructions.rs b/crates/tinywasm/src/interpreter/executor/instructions.rs
new file mode 100644
index 0000000..587d776
--- /dev/null
+++ b/crates/tinywasm/src/interpreter/executor/instructions.rs
@@ -0,0 +1,690 @@
+macro_rules! exec_op {
+ ($executor:ident; binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
+ fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $rhs = <$ty>::stack_pop(value_stack);
+ let $lhs = <$ty>::stack_pop(value_stack);
+ <$ty>::stack_push(value_stack, $expr?)
+ }
+ exec_binary_fallible(&mut $executor.store.value_stack)?;
+ }};
+ ($executor:ident; unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{
+ fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $v = <$from>::stack_pop(value_stack);
+ <$to>::stack_push(value_stack, $expr)
+ }
+ exec_unary(&mut $executor.store.value_stack)?;
+ }};
+ ($executor:ident; binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
+ exec_op!($executor; binary $from, $from => $to, |$lhs, $rhs| $expr)
+ }};
+ ($executor:ident; binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
+ fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $rhs = <$rhs_ty>::stack_pop(value_stack);
+ let $lhs = <$lhs_ty>::stack_pop(value_stack);
+ <$res>::stack_push(value_stack, $expr)
+ }
+ exec_binary(&mut $executor.store.value_stack)?;
+ }};
+ ($executor:ident; ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{
+ fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $c = <$from>::stack_pop(value_stack);
+ let $b = <$from>::stack_pop(value_stack);
+ let $a = <$from>::stack_pop(value_stack);
+ <$to>::stack_push(value_stack, $expr)
+ }
+ exec_ternary(&mut $executor.store.value_stack)?;
+ }};
+}
+
+// This list is the single source for stable instruction stepping and nightly tail handlers.
+#[rustfmt::skip]
+macro_rules! instruction_handlers {
+ ($emit:ident) => {
+ $emit! { executor, instr_ptr, dispatch_next, dispatch_flow;
+ Unreachable => { return cold!(Err(Trap::Unreachable.into())); },
+ Drop32 => { _ = Value32::stack_pop(&mut executor.store.value_stack)},
+ Drop64 => { _ = Value64::stack_pop(&mut executor.store.value_stack)},
+ Drop128 => { _ = Value128::stack_pop(&mut executor.store.value_stack)},
+ Select32 => Value32::stack_select(&mut executor.store.value_stack),
+ Select64 => Value64::stack_select(&mut executor.store.value_stack),
+ Select128 => Value128::stack_select(&mut executor.store.value_stack),
+ SelectStore32(idx) => executor.exec_select_store::<Value32, 4>(idx.resolve(&executor.func.data))?,
+ SelectStore64(idx) => executor.exec_select_store::<Value64, 8>(idx.resolve(&executor.func.data))?,
+ SelectMulti(counts) => executor.store.value_stack.select_multi(*counts),
+ Call(v) => dispatch_flow!(executor.exec_call_direct(*v, instr_ptr + 1)?),
+ CallSelf => { executor.exec_call_self(instr_ptr + 1)?; dispatch_next!(0); },
+ CallIndirect(idx) => dispatch_flow!(executor.exec_call_indirect::<false>(*idx, instr_ptr + 1)?),
+ CallRef(ty) => dispatch_flow!(executor.exec_call_ref::<false>(*ty, instr_ptr + 1)?),
+ ReturnCall(v) => dispatch_flow!(executor.exec_return_call_direct(*v)?),
+ ReturnCallSelf => { executor.exec_return_call_self()?; dispatch_next!(0); },
+ ReturnCallIndirect(idx) => dispatch_flow!(executor.exec_call_indirect::<true>(*idx, instr_ptr + 1)?),
+ ReturnCallRef(ty) => dispatch_flow!(executor.exec_call_ref::<true>(*ty, instr_ptr + 1)?),
+ Throw(tag) => dispatch_flow!(executor.exec_throw(*tag, instr_ptr)?),
+ ThrowRef => dispatch_flow!(executor.exec_throw_ref(instr_ptr)?),
+ Jump(ip) => dispatch_next!(*ip as usize),
+ JumpIfZero32(ip) => if i32::stack_pop(&mut executor.store.value_stack) == 0 { dispatch_next!(*ip as usize) },
+ JumpIfNonZero32(ip) => if i32::stack_pop(&mut executor.store.value_stack) != 0 { dispatch_next!(*ip as usize) },
+ JumpIfZero64(ip) => if i64::stack_pop(&mut executor.store.value_stack) == 0 { dispatch_next!(*ip as usize) },
+ JumpIfNonZero64(ip) => if i64::stack_pop(&mut executor.store.value_stack) != 0 { dispatch_next!(*ip as usize) },
+ JumpIfRefNull(ip) => { let ip = *ip; if executor.exec_jump_if_ref::<true>() { dispatch_next!(ip as usize) } },
+ JumpIfRefNonNull(ip) => { let ip = *ip; if executor.exec_jump_if_ref::<false>() { dispatch_next!(ip as usize) } },
+ BrOnCast(idx) => if let Some(ip) = executor.exec_br_on_cast::<false>(*idx) { dispatch_next!(ip) },
+ BrOnCastFail(idx) => if let Some(ip) = executor.exec_br_on_cast::<true>(*idx) { dispatch_next!(ip) },
+ JumpIfLocalZero32(arg) => if executor.exec_jump_if_local::<Value32, true>(arg.local) { dispatch_next!(arg.target_ip as usize) },
+ JumpIfLocalNonZero32(arg) => if executor.exec_jump_if_local::<Value32, false>(arg.local) { dispatch_next!(arg.target_ip as usize) },
+ JumpIfLocalZero64(arg) => if executor.exec_jump_if_local::<Value64, true>(arg.local) { dispatch_next!(arg.target_ip as usize) },
+ JumpIfLocalNonZero64(arg) => if executor.exec_jump_if_local::<Value64, false>(arg.local) { dispatch_next!(arg.target_ip as usize) },
+ JumpCmpStackConst32(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_const32(*packed) { dispatch_next!(ip) },
+ JumpCmpStackConst64(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_const64(*packed) { dispatch_next!(ip) },
+ JumpCmpStackLocal32(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_local32(*packed) { dispatch_next!(ip) },
+ JumpCmpStackLocal64(packed) => if let Some(ip) = executor.exec_jump_cmp_stack_local64(*packed) { dispatch_next!(ip) },
+ BinOpLocalConstJump32(packed) => if let Some(ip) = executor.exec_binop_local_const_jump(*packed) { dispatch_next!(ip) },
+ BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = executor.exec_binop_local_const_jump_cmp_local(*packed) { dispatch_next!(ip) },
+ BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = executor.exec_binop_stack_const_tee_local_jump(*packed)? { dispatch_next!(ip) },
+ BinOpGlobalConstJump32(packed) => if let Some(ip) = executor.exec_binop_global_const_jump(*packed) { dispatch_next!(ip) },
+ IncLocalJump32(idx) => if let Some(ip) = executor.exec_inc_local_jump(*idx) { dispatch_next!(ip) },
+ IncStackTeeLocalJump32(idx) => if let Some(ip) = executor.exec_inc_stack_tee_local_jump(*idx)? { dispatch_next!(ip) },
+ IncGlobalJump32(idx) => if let Some(ip) = executor.exec_inc_global_jump(*idx) { dispatch_next!(ip) },
+ IncLocalJumpCmpLocal32(packed) => if let Some(ip) = executor.exec_inc_local_jump_cmp_local(*packed) { dispatch_next!(ip) },
+ JumpCmpLocalConst32(packed) => if let Some(ip) = executor.exec_jump_cmp_local_const32(*packed) { dispatch_next!(ip) },
+ JumpCmpLocalConst64(packed) => if let Some(ip) = executor.exec_jump_cmp_local_const64(*packed) { dispatch_next!(ip) },
+ JumpCmpLocalLocal32(packed) => if let Some(ip) = executor.exec_jump_cmp_local_local32(*packed) { dispatch_next!(ip) },
+ JumpCmpLocalLocal64(packed) => if let Some(ip) = executor.exec_jump_cmp_local_local64(*packed) { dispatch_next!(ip) },
+ DropKeep32 { base, keep } => executor.store.value_stack.stack_32.truncate_keep((executor.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize),
+ DropKeep64 { base, keep } => executor.store.value_stack.stack_64.truncate_keep((executor.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize),
+ DropKeep128 { base, keep } => executor.store.value_stack.stack_128.truncate_keep((executor.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize),
+ BranchTable(idx) => dispatch_next!(executor.exec_branch_table(*idx)),
+ Return => dispatch_flow!(executor.exec_return()),
+ ReturnVoid => dispatch_flow!(executor.exec_return_void()),
+ Return32 => dispatch_flow!(executor.exec_return_32()),
+ Return64 => dispatch_flow!(executor.exec_return_64()),
+ Return128 => dispatch_flow!(executor.exec_return_128()),
+ LocalGet32(local_index) => Value32::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?,
+ LocalGet64(local_index) => Value64::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?,
+ LocalGet128(local_index) => Value128::local_push(&mut executor.store.value_stack, &executor.cf, *local_index)?,
+ LocalSet32(local_index) => executor.exec_local_set_pop::<Value32>(*local_index),
+ LocalSet64(local_index) => executor.exec_local_set_pop::<Value64>(*local_index),
+ LocalSet128(local_index) => executor.exec_local_set_pop::<Value128>(*local_index),
+ LocalCopy32(from, to) => Value32::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to),
+ LocalCopy64(from, to) => Value64::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to),
+ LocalCopy128(from, to) => Value128::local_copy(&mut executor.store.value_stack, &executor.cf, *from, *to),
+ AddConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value.wrapping_add(*c)); },
+ AndConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value & *c); },
+ XorConst32(c) => { i32::stack_update(&mut executor.store.value_stack, |value| value ^ *c); },
+ ShrUConst32(c) => { u32::stack_update(&mut executor.store.value_stack, |value| value.wrapping_shr(*c as u32)); },
+ AddConst64(idx) => { let rhs = idx.resolve(&executor.func.data).value(); i64::stack_update(&mut executor.store.value_stack, |value| value.wrapping_add(rhs)); },
+ BinOpStackConst32(op, rhs) => { u32::stack_update(&mut executor.store.value_stack, |lhs| op.exec(lhs, *rhs as u32)); },
+ BinOpStackConst64(packed) => { let rhs = packed.index.resolve(&executor.func.data).value() as u64; u64::stack_update(&mut executor.store.value_stack, |lhs| packed.op.exec(lhs, rhs)); },
+ IncLocal32(arg) => { i32::local_update(&mut executor.store.value_stack, &executor.cf, arg.local, |value| value.wrapping_add(arg.value)); },
+ IncLocal64(packed) => { let rhs = packed.index.resolve(&executor.func.data).value(); i64::local_update(&mut executor.store.value_stack, &executor.cf, packed.op, |value| value.wrapping_add(rhs)); },
+ I32Add3 => exec_op!(executor; ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
+ I64Add3 => exec_op!(executor; ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
+ MulAccLocal32(acc) => executor.exec_mul_acc_local::<i32>(*acc, i32::wrapping_mul, i32::wrapping_add),
+ MulAccLocal64(acc) => executor.exec_mul_acc_local::<i64>(*acc, i64::wrapping_mul, i64::wrapping_add),
+ FMulAccLocal32(acc) => executor.exec_mul_acc_local::<f32>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b),
+ FMulAccLocal64(acc) => executor.exec_mul_acc_local::<f64>(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b),
+ BinOpLocalLocal32(op, a, b) => executor.exec_binop_local_local::<Value32, true>(*a, *b, None, *op)?,
+ BinOpLocalLocal64(op, a, b) => executor.exec_binop_local_local::<Value64, true>(*a, *b, None, *op)?,
+ BinOpLocalLocal128(op, a, b) => executor.exec_binop_local_local::<Value128, true>(*a, *b, None, *op)?,
+ CmpLocalLocal32(op, a, b) => executor.exec_cmp_local_local::<i32>(*a, *b, *op)?,
+ CmpLocalLocal64(op, a, b) => executor.exec_cmp_local_local::<i64>(*a, *b, *op)?,
+ AddLocalLocalSet32(arg) => executor.exec_binop_local_local::<Value32, false>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?,
+ AddLocalLocalTee32(arg) => executor.exec_binop_local_local::<Value32, true>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?,
+ BinOpLocalLocalSet32(packed) => executor.exec_binop_local_local_indexed::<Value32, false>(packed.index, packed.op)?,
+ BinOpLocalLocalSet64(packed) => executor.exec_binop_local_local_indexed::<Value64, false>(packed.index, packed.op)?,
+ BinOpLocalLocalSet128(packed) => executor.exec_binop_local_local_indexed::<Value128, false>(packed.index, packed.op)?,
+ BinOpLocalLocalTee32(packed) => executor.exec_binop_local_local_indexed::<Value32, true>(packed.index, packed.op)?,
+ BinOpLocalLocalTee64(packed) => executor.exec_binop_local_local_indexed::<Value64, true>(packed.index, packed.op)?,
+ BinOpLocalLocalTee128(packed) => executor.exec_binop_local_local_indexed::<Value128, true>(packed.index, packed.op)?,
+ AddLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAdd)?,
+ SubLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::ISub)?,
+ MulLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IMul)?,
+ AndLocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAnd)?,
+ ShrULocalConst32(arg) => executor.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IShrU)?,
+ BinOpLocalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, true>(v.a(), v.b(), None, packed.op)?; },
+ BinOpLocalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, true>(v.a(), v.b(), None, packed.op)?; },
+ BinOpLocalConst128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.b().resolve(&executor.func.data).value()); executor.exec_binop_local_const::<Value128, true>(v.a(), rhs, None, packed.op)?; },
+ BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, false>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value32, true>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, false>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_local_const::<Value64, true>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.c().resolve(&executor.func.data).value()); executor.exec_binop_local_const::<Value128, false>(v.a(), rhs, Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.c().resolve(&executor.func.data).value()); executor.exec_binop_local_const::<Value128, true>(v.a(), rhs, Some(v.b()), packed.op)?; },
+ BinOpStackLocal32(op, local) => executor.exec_binop_stack_local::<Value32, true>(*local, None, *op)?,
+ BinOpStackLocalSet32(op, local, dst) => executor.exec_binop_stack_local::<Value32, false>(*local, Some(*dst), *op)?,
+ BinOpStackLocalTee32(op, local, dst) => executor.exec_binop_stack_local::<Value32, true>(*local, Some(*dst), *op)?,
+ BinOpStackLocal128(op, local) => executor.exec_binop_stack_local::<Value128, true>(*local, None, *op)?,
+ BinOpStackGlobal32(op, global_index) => executor.exec_binop_stack_global::<Value32>(*global_index, *op)?,
+ BinOpStackGlobal64(op, global_index) => executor.exec_binop_stack_global::<Value64>(*global_index, *op)?,
+ BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; },
+ BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&executor.func.data); executor.exec_binop_global_const::<Value64>(v.a(), v.b(), packed.op)?; },
+ BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&executor.func.data); let rhs = Value128(v.b().resolve(&executor.func.data).value()); executor.exec_binop_global_const::<Value128>(v.a(), rhs, packed.op)?; },
+ SetLocalConst32(arg) => i32::local_set(&mut executor.store.value_stack, &executor.cf, arg.local, arg.value),
+ SetLocalConst64(packed) => { let v = packed.index.resolve(&executor.func.data).value(); i64::local_set(&mut executor.store.value_stack, &executor.cf, packed.op, v); },
+ SetLocalConst128(packed) => Value128::local_set(&mut executor.store.value_stack, &executor.cf, packed.op, Value128(packed.index.resolve(&executor.func.data).value())),
+ IncMemoryLocal32(arg) => executor.exec_inc_memory_local::<i32, 4>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?,
+ IncMemoryLocal64(arg) => executor.exec_inc_memory_local::<i64, 8>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?,
+ StoreLocalLocal32(arg) => executor.exec_store_local_local::<u32, 4>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ StoreLocalLocal64(arg) => executor.exec_store_local_local::<i64, 8>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ StoreLocalLocal128(arg) => executor.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ LoadLocal32(arg) => executor.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?,
+ LoadLocal64(arg) => executor.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?,
+ LoadLocal8S32(arg) => executor.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal8U32(arg) => executor.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal16S32(arg) => executor.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal16U32(arg) => executor.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocalTee32(arg) => executor.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?,
+ LoadLocalSet32(arg) => executor.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?,
+ LoadLocalTee8S32(arg) => executor.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee8U32(arg) => executor.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee16S32(arg) => executor.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee16U32(arg) => executor.exec_load_local::<u16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet8S32(arg) => executor.exec_load_local::<i8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet8U32(arg) => executor.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet16S32(arg) => executor.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet16U32(arg) => executor.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee128(arg) => executor.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?,
+ LoadLocalSet128(arg) => executor.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?,
+ AndConstTee32(arg) => executor.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::IAnd)?,
+ SubConstTee32(arg) => executor.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::ISub)?,
+ AndConstTee64(packed) => executor.exec_binop_const_tee::<Value64>(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::IAnd)?,
+ SubConstTee64(packed) => executor.exec_binop_const_tee::<Value64>(packed.index.resolve(&executor.func.data).value() as u64, packed.op, BinOp::ISub)?,
+ LocalTee32(local_index) => executor.exec_local_tee::<Value32>(*local_index),
+ LocalTee64(local_index) => executor.exec_local_tee::<Value64>(*local_index),
+ LocalTee128(local_index) => executor.exec_local_tee::<Value128>(*local_index),
+ GlobalGet32(global_index) => executor.exec_global_get::<Value32>(*global_index)?,
+ GlobalGet64(global_index) => executor.exec_global_get::<Value64>(*global_index)?,
+ GlobalGet128(global_index) => executor.exec_global_get::<Value128>(*global_index)?,
+ GlobalSet32(global_index) => executor.exec_global_set::<Value32>(*global_index),
+ GlobalSet64(global_index) => executor.exec_global_set::<Value64>(*global_index),
+ GlobalSet128(global_index) => executor.exec_global_set::<Value128>(*global_index),
+ GlobalTee32(global_index) => executor.exec_global_tee::<Value32>(*global_index),
+ GlobalTee64(global_index) => executor.exec_global_tee::<Value64>(*global_index),
+ GlobalTee128(global_index) => executor.exec_global_tee::<Value128>(*global_index),
+ Const32(val) => i32::stack_push(&mut executor.store.value_stack, *val)?,
+ Const64Imm(val) => i64::stack_push(&mut executor.store.value_stack, i64::from(*val))?,
+ Const64(idx) => i64::stack_push(&mut executor.store.value_stack, idx.resolve(&executor.func.data).value())?,
+ Const128Imm(val) => Value128::stack_push(&mut executor.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?,
+ I64Eqz => exec_op!(executor; unary i64 => i32, |v| i32::from(v == 0)),
+ I32Eqz => exec_op!(executor; unary i32 => i32, |v| i32::from(v == 0)),
+ I32Eq => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a == b)),
+ I64Eq => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a == b)),
+ F32Eq => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a == b)),
+ F64Eq => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a == b)),
+ I32Ne => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a != b)),
+ I64Ne => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a != b)),
+ F32Ne => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a != b)),
+ F64Ne => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a != b)),
+ I32LtS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a < b)),
+ I64LtS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a < b)),
+ I32LtU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a < b)),
+ I64LtU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a < b)),
+ F32Lt => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a < b)),
+ F64Lt => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a < b)),
+ I32LeS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a <= b)),
+ I64LeS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a <= b)),
+ I32LeU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a <= b)),
+ I64LeU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a <= b)),
+ F32Le => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a <= b)),
+ F64Le => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a <= b)),
+ I32GeS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a >= b)),
+ I64GeS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a >= b)),
+ I32GeU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a >= b)),
+ I64GeU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a >= b)),
+ F32Ge => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a >= b)),
+ F64Ge => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a >= b)),
+ I32GtS => exec_op!(executor; binary i32 => i32, |a, b| i32::from(a > b)),
+ I64GtS => exec_op!(executor; binary i64 => i32, |a, b| i32::from(a > b)),
+ I32GtU => exec_op!(executor; binary u32 => i32, |a, b| i32::from(a > b)),
+ I64GtU => exec_op!(executor; binary u64 => i32, |a, b| i32::from(a > b)),
+ F32Gt => exec_op!(executor; binary f32 => i32, |a, b| i32::from(a > b)),
+ F64Gt => exec_op!(executor; binary f64 => i32, |a, b| i32::from(a > b)),
+ I32Add => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_add(b)),
+ I64Add => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_add(b)),
+ F32Add => exec_op!(executor; binary f32 => f32, |a, b| a + b),
+ F64Add => exec_op!(executor; binary f64 => f64, |a, b| a + b),
+ I32Sub => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_sub(b)),
+ I64Sub => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_sub(b)),
+ F32Sub => exec_op!(executor; binary f32 => f32, |a, b| a - b),
+ F64Sub => exec_op!(executor; binary f64 => f64, |a, b| a - b),
+ F32Div => exec_op!(executor; binary f32 => f32, |a, b| a / b),
+ F64Div => exec_op!(executor; binary f64 => f64, |a, b| a / b),
+ I32Mul => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_mul(b)),
+ I64Mul => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_mul(b)),
+ F32Mul => exec_op!(executor; binary f32 => f32, |a, b| a * b),
+ F64Mul => exec_op!(executor; binary f64 => f64, |a, b| a * b),
+ I32DivS => exec_op!(executor; binary_fallible i32, |a, b| a.tw_checked_div(b)),
+ I64DivS => exec_op!(executor; binary_fallible i64, |a, b| a.tw_checked_div(b)),
+ I32DivU => exec_op!(executor; binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)),
+ I64DivU => exec_op!(executor; binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)),
+ I32RemS => exec_op!(executor; binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)),
+ I64RemS => exec_op!(executor; binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)),
+ I32RemU => exec_op!(executor; binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)),
+ I64RemU => exec_op!(executor; binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)),
+ I32And => exec_op!(executor; binary i32 => i32, |a, b| a & b),
+ I64And => exec_op!(executor; binary i64 => i64, |a, b| a & b),
+ I32Or => exec_op!(executor; binary i32 => i32, |a, b| a | b),
+ I64Or => exec_op!(executor; binary i64 => i64, |a, b| a | b),
+ I32Xor => exec_op!(executor; binary i32 => i32, |a, b| a ^ b),
+ I64Xor => exec_op!(executor; binary i64 => i64, |a, b| a ^ b),
+ I32Shl => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_shl(b as u32)),
+ I64Shl => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_shl(b as u32)),
+ I32ShrS => exec_op!(executor; binary i32 => i32, |a, b| a.wrapping_shr(b as u32)),
+ I64ShrS => exec_op!(executor; binary i64 => i64, |a, b| a.wrapping_shr(b as u32)),
+ I32ShrU => exec_op!(executor; binary u32 => u32, |a, b| a.wrapping_shr(b)),
+ I64ShrU => exec_op!(executor; binary u64 => u64, |a, b| a.wrapping_shr(b as u32)),
+ I32Rotl => exec_op!(executor; binary i32 => i32, |a, b| a.rotate_left(b as u32)),
+ I64Rotl => exec_op!(executor; binary i64 => i64, |a, b| a.rotate_left(b as u32)),
+ I32Rotr => exec_op!(executor; binary i32 => i32, |a, b| a.rotate_right(b as u32)),
+ I64Rotr => exec_op!(executor; binary i64 => i64, |a, b| a.rotate_right(b as u32)),
+ I64Add128 => executor.exec_i64_add128()?,
+ I64Sub128 => executor.exec_i64_sub128()?,
+ I64MulWideS => executor.exec_i64_mul_wide_s()?,
+ I64MulWideU => executor.exec_i64_mul_wide_u()?,
+ I32Clz => exec_op!(executor; unary i32 => i32, |v| v.leading_zeros() as i32),
+ I64Clz => exec_op!(executor; unary i64 => i64, |v| i64::from(v.leading_zeros())),
+ I32Ctz => exec_op!(executor; unary i32 => i32, |v| v.trailing_zeros() as i32),
+ I64Ctz => exec_op!(executor; unary i64 => i64, |v| i64::from(v.trailing_zeros())),
+ I32Popcnt => exec_op!(executor; unary i32 => i32, |v| v.count_ones() as i32),
+ I64Popcnt => exec_op!(executor; unary i64 => i64, |v| i64::from(v.count_ones())),
+
+ // Reference types
+ RefFunc(func_idx) => ValueRef::stack_push(&mut executor.store.value_stack, ValueRef::from_category_addr(executor.module.resolve_func_addr(*func_idx)))?,
+ RefNull(_) => ValueRef::stack_push(&mut executor.store.value_stack, ValueRef::NULL)?,
+ RefIsNull => executor.exec_ref_is_null()?,
+ RefAsNonNull => executor.exec_ref_as_non_null()?,
+ RefI31 => exec_op!(executor; unary i32 => ValueRef, |v| ValueRef::from_i31(v)),
+ I31GetS => executor.exec_i31_get(true)?,
+ I31GetU => executor.exec_i31_get(false)?,
+ RefEq => exec_op!(executor; binary ValueRef => i32, |a, b| i32::from(a == b)),
+ RefTest(ty) => executor.exec_ref_test(*ty)?,
+ RefCast(ty) => executor.exec_ref_cast(*ty)?,
+
+ // GC objects
+ StructNew(ty) => executor.exec_struct_new(*ty, false)?,
+ StructNewDefault(ty) => executor.exec_struct_new(*ty, true)?,
+ StructGet(idx) => executor.exec_struct_get(*idx, None)?,
+ StructGetS(idx) => executor.exec_struct_get(*idx, Some(true))?,
+ StructGetU(idx) => executor.exec_struct_get(*idx, Some(false))?,
+ StructSet(idx) => executor.exec_struct_set(*idx)?,
+ ArrayNew(ty) => executor.exec_array_new(*ty, false)?,
+ ArrayNewDefault(ty) => executor.exec_array_new(*ty, true)?,
+ ArrayNewFixed(idx) => executor.exec_array_new_fixed(*idx)?,
+ ArrayNewData(idx) => executor.exec_array_new_data(*idx)?,
+ ArrayNewElem(idx) => executor.exec_array_new_elem(*idx)?,
+ ArrayGet(ty) => executor.exec_array_get(*ty, None)?,
+ ArrayGetS(ty) => executor.exec_array_get(*ty, Some(true))?,
+ ArrayGetU(ty) => executor.exec_array_get(*ty, Some(false))?,
+ ArraySet(ty) => executor.exec_array_set(*ty)?,
+ ArrayLen => executor.exec_array_len()?,
+ ArrayFill(ty) => executor.exec_array_fill(*ty)?,
+ ArrayCopy(idx) => executor.exec_array_copy(*idx)?,
+ ArrayInitData(idx) => executor.exec_array_init_data(*idx)?,
+ ArrayInitElem(idx) => executor.exec_array_init_elem(*idx)?,
+ MemorySize(addr) => executor.exec_memory_size(*addr)?,
+ MemoryGrow(addr) => executor.exec_memory_grow(*addr)?,
+
+ // Bulk memory operations
+ MemoryCopy(idx) => executor.exec_memory_copy(*idx)?,
+ MemoryFill(addr) => executor.exec_memory_fill(*addr)?,
+ MemoryFillConst(idx) => executor.exec_memory_fill_const(*idx)?,
+ MemoryInit(idx) => executor.exec_memory_init(*idx)?,
+ DataDrop(data_index) => executor.store.state.get_data_mut(executor.module.resolve_data_addr(*data_index)).drop(),
+ ElemDrop(elem_index) => executor.store.state.get_elem_mut(executor.module.resolve_elem_addr(*elem_index)).drop(),
+
+ // Table instructions
+ TableGet(table_idx) => executor.exec_table_get(*table_idx)?,
+ TableSet(table_idx) => executor.exec_table_set(*table_idx)?,
+ TableSize(table_idx) => executor.exec_table_size(*table_idx)?,
+ TableInit(idx) => executor.exec_table_init(*idx)?,
+ TableGrow(table_idx) => executor.exec_table_grow(*table_idx)?,
+ TableFill(table_idx) => executor.exec_table_fill(*table_idx)?,
+ TableCopy(idx) => executor.exec_table_copy(*idx)?,
+
+ // Core memory load/store operations
+ I32Store(idx) => executor.exec_mem_store::<i32, i32, 4>(idx.resolve(&executor.func.data), identity)?,
+ I64Store(idx) => executor.exec_mem_store::<i64, i64, 8>(idx.resolve(&executor.func.data), identity)?,
+ F32Store(idx) => executor.exec_mem_store::<f32, f32, 4>(idx.resolve(&executor.func.data), identity)?,
+ F64Store(idx) => executor.exec_mem_store::<f64, f64, 8>(idx.resolve(&executor.func.data), identity)?,
+ FMaStoreF32(m) => executor.exec_fma_store::<f32, 4>(*m)?,
+ FMaStoreF64(m) => executor.exec_fma_store::<f64, 8>(*m)?,
+ I32Store8(idx) => executor.exec_mem_store::<i32, i8, 1>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?,
+ I32Store16(idx) => executor.exec_mem_store::<i32, i16, 2>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?,
+ I64Store8(idx) => executor.exec_mem_store::<i64, i8, 1>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i8)?,
+ I64Store16(idx) => executor.exec_mem_store::<i64, i16, 2>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i16)?,
+ I64Store32(idx) => executor.exec_mem_store::<i64, i32, 4>(idx.resolve(&executor.func.data), #[inline(always)] |v| v as i32)?,
+ I32Load(idx) => executor.exec_mem_load::<i32, 4, _>(idx.resolve(&executor.func.data), identity)?,
+ I64Load(idx) => executor.exec_mem_load::<i64, 8, _>(idx.resolve(&executor.func.data), identity)?,
+ F32Load(idx) => executor.exec_mem_load::<f32, 4, _>(idx.resolve(&executor.func.data), identity)?,
+ F64Load(idx) => executor.exec_mem_load::<f64, 8, _>(idx.resolve(&executor.func.data), identity)?,
+ I32Load8S(idx) => executor.exec_mem_load::<i8, 1, _>(idx.resolve(&executor.func.data), i32::from)?,
+ I32Load8U(idx) => executor.exec_mem_load::<u8, 1, _>(idx.resolve(&executor.func.data), i32::from)?,
+ I32Load16S(idx) => executor.exec_mem_load::<i16, 2, _>(idx.resolve(&executor.func.data), i32::from)?,
+ I32Load16U(idx) => executor.exec_mem_load::<u16, 2, _>(idx.resolve(&executor.func.data), i32::from)?,
+ I64Load8S(idx) => executor.exec_mem_load::<i8, 1, _>(idx.resolve(&executor.func.data), i64::from)?,
+ I64Load8U(idx) => executor.exec_mem_load::<u8, 1, _>(idx.resolve(&executor.func.data), i64::from)?,
+ I64Load16S(idx) => executor.exec_mem_load::<i16, 2, _>(idx.resolve(&executor.func.data), i64::from)?,
+ I64Load16U(idx) => executor.exec_mem_load::<u16, 2, _>(idx.resolve(&executor.func.data), i64::from)?,
+ I64Load32S(idx) => executor.exec_mem_load::<i32, 4, _>(idx.resolve(&executor.func.data), i64::from)?,
+ I64Load32U(idx) => executor.exec_mem_load::<u32, 4, _>(idx.resolve(&executor.func.data), i64::from)?,
+
+ // Numeric conversion operations
+ F32ConvertI32S => exec_op!(executor; unary i32 => f32, |v| v as f32),
+ F32ConvertI64S => exec_op!(executor; unary i64 => f32, |v| v as f32),
+ F64ConvertI32S => exec_op!(executor; unary i32 => f64, |v| f64::from(v)),
+ F64ConvertI64S => exec_op!(executor; unary i64 => f64, |v| v as f64),
+ F32ConvertI32U => exec_op!(executor; unary u32 => f32, |v| v as f32),
+ F32ConvertI64U => exec_op!(executor; unary u64 => f32, |v| v as f32),
+ F64ConvertI32U => exec_op!(executor; unary u32 => f64, |v| f64::from(v)),
+ F64ConvertI64U => exec_op!(executor; unary u64 => f64, |v| v as f64),
+
+ // Sign-extension operations
+ I32Extend8S => exec_op!(executor; unary i32 => i32, |v| i32::from(v as i8)),
+ I32Extend16S => exec_op!(executor; unary i32 => i32, |v| i32::from(v as i16)),
+ I64Extend8S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i8)),
+ I64Extend16S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i16)),
+ I64Extend32S => exec_op!(executor; unary i64 => i64, |v| i64::from(v as i32)),
+ I64ExtendI32U => exec_op!(executor; unary u32 => i64, |v| i64::from(v)),
+ I64ExtendI32S => exec_op!(executor; unary i32 => i64, |v| i64::from(v)),
+ I32WrapI64 => exec_op!(executor; unary i64 => i32, |v| v as i32),
+ F32DemoteF64 => exec_op!(executor; unary f64 => f32, |v| v as f32),
+ F64PromoteF32 => exec_op!(executor; unary f32 => f64, |v| f64::from(v)),
+ F32Abs => exec_op!(executor; unary f32 => f32, |v| v.abs()),
+ F64Abs => exec_op!(executor; unary f64 => f64, |v| v.abs()),
+ F32Neg => exec_op!(executor; unary f32 => f32, |v| -v),
+ F64Neg => exec_op!(executor; unary f64 => f64, |v| -v),
+ F32Ceil => exec_op!(executor; unary f32 => f32, |v| v.ceil()),
+ F64Ceil => exec_op!(executor; unary f64 => f64, |v| v.ceil()),
+ F32Floor => exec_op!(executor; unary f32 => f32, |v| v.floor()),
+ F64Floor => exec_op!(executor; unary f64 => f64, |v| v.floor()),
+ F32Trunc => exec_op!(executor; unary f32 => f32, |v| v.trunc()),
+ F64Trunc => exec_op!(executor; unary f64 => f64, |v| v.trunc()),
+ F32Nearest => exec_op!(executor; unary f32 => f32, |v| v.tw_nearest()),
+ F64Nearest => exec_op!(executor; unary f64 => f64, |v| v.tw_nearest()),
+ F32Sqrt => exec_op!(executor; unary f32 => f32, |v| v.sqrt()),
+ F64Sqrt => exec_op!(executor; unary f64 => f64, |v| v.sqrt()),
+ F32Min => exec_op!(executor; binary f32 => f32, |a, b| a.tw_minimum(b)),
+ F64Min => exec_op!(executor; binary f64 => f64, |a, b| a.tw_minimum(b)),
+ F32Max => exec_op!(executor; binary f32 => f32, |a, b| a.tw_maximum(b)),
+ F64Max => exec_op!(executor; binary f64 => f64, |a, b| a.tw_maximum(b)),
+ F32Copysign => exec_op!(executor; binary f32 => f32, |a, b| a.copysign(b)),
+ F64Copysign => exec_op!(executor; binary f64 => f64, |a, b| a.copysign(b)),
+ I32TruncF32S => checked_conv_float!(f32, i32, executor),
+ I32TruncF64S => checked_conv_float!(f64, i32, executor),
+ I32TruncF32U => checked_conv_float!(f32, u32, i32, executor),
+ I32TruncF64U => checked_conv_float!(f64, u32, i32, executor),
+ I64TruncF32S => checked_conv_float!(f32, i64, executor),
+ I64TruncF64S => checked_conv_float!(f64, i64, executor),
+ I64TruncF32U => checked_conv_float!(f32, u64, i64, executor),
+ I64TruncF64U => checked_conv_float!(f64, u64, i64, executor),
+
+ // Non-trapping float-to-int conversions
+ I32TruncSatF32S => exec_op!(executor; unary f32 => i32, |v| v.trunc() as i32),
+ I32TruncSatF32U => exec_op!(executor; unary f32 => u32, |v| v.trunc() as u32),
+ I32TruncSatF64S => exec_op!(executor; unary f64 => i32, |v| v.trunc() as i32),
+ I32TruncSatF64U => exec_op!(executor; unary f64 => u32, |v| v.trunc() as u32),
+ I64TruncSatF32S => exec_op!(executor; unary f32 => i64, |v| v.trunc() as i64),
+ I64TruncSatF32U => exec_op!(executor; unary f32 => u64, |v| v.trunc() as u64),
+ I64TruncSatF64S => exec_op!(executor; unary f64 => i64, |v| v.trunc() as i64),
+ I64TruncSatF64U => exec_op!(executor; unary f64 => u64, |v| v.trunc() as u64),
+
+ // SIMD extension
+ V128Not => exec_op!(executor; unary Value128 => Value128, |v| v.v128_not()),
+ V128And => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_and(b)),
+ V128AndNot => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_andnot(b)),
+ V128Or => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_or(b)),
+ V128Xor => exec_op!(executor; binary Value128 => Value128, |a, b| a.v128_xor(b)),
+ V128Bitselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)),
+ V128AnyTrue => exec_op!(executor; unary Value128 => i32, |v| v.v128_any_true() as i32),
+ I8x16Swizzle => exec_op!(executor; binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)),
+ I8x16RelaxedSwizzle => exec_op!(executor; binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)),
+ V128Load(idx) => executor.exec_mem_load::<Value128, 16, _>(idx.resolve(&executor.func.data), identity)?,
+ V128Load8x8S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?,
+ V128Load8x8U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?,
+ V128Load16x4S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?,
+ V128Load16x4U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?,
+ V128Load32x2S(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?,
+ V128Load32x2U(idx) => executor.exec_mem_load::<u64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?,
+ V128Load8Splat(idx) => executor.exec_mem_load::<i8, 1, Value128>(idx.resolve(&executor.func.data), Value128::splat_i8)?,
+ V128Load16Splat(idx) => executor.exec_mem_load::<i16, 2, Value128>(idx.resolve(&executor.func.data), Value128::splat_i16)?,
+ V128Load32Splat(idx) => executor.exec_mem_load::<i32, 4, Value128>(idx.resolve(&executor.func.data), Value128::splat_i32)?,
+ V128Load64Splat(idx) => executor.exec_mem_load::<i64, 8, Value128>(idx.resolve(&executor.func.data), Value128::splat_i64)?,
+ V128Store(idx) => executor.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&executor.func.data), identity)?,
+ V128Store8Lane(arg) => executor.exec_mem_store_lane::<i8, 1>(*arg)?,
+ V128Store16Lane(arg) => executor.exec_mem_store_lane::<i16, 2>(*arg)?,
+ V128Store32Lane(arg) => executor.exec_mem_store_lane::<i32, 4>(*arg)?,
+ V128Store64Lane(arg) => executor.exec_mem_store_lane::<i64, 8>(*arg)?,
+ V128Load32Zero(idx) => executor.exec_mem_load::<i32, 4, Value128>(idx.resolve(&executor.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?,
+ V128Load64Zero(idx) => executor.exec_mem_load::<i64, 8, Value128>(idx.resolve(&executor.func.data), |v| Value128::from_i64x2([v, 0]))?,
+ Const128(arg) => Value128::stack_push(&mut executor.store.value_stack, Value128(arg.resolve(&executor.func.data).value()))?,
+ I8x16ExtractLaneS(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?,
+ I8x16ExtractLaneU(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?,
+ I16x8ExtractLaneS(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?,
+ I16x8ExtractLaneU(lane) => executor.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?,
+ I32x4ExtractLane(lane) => executor.exec_simd_extract_lane::<i32>(*lane, Value128::extract_lane_i32)?,
+ I64x2ExtractLane(lane) => executor.exec_simd_extract_lane::<i64>(*lane, Value128::extract_lane_i64)?,
+ F32x4ExtractLane(lane) => executor.exec_simd_extract_lane::<f32>(*lane, Value128::extract_lane_f32)?,
+ F64x2ExtractLane(lane) => executor.exec_simd_extract_lane::<f64>(*lane, Value128::extract_lane_f64)?,
+ V128Load8Lane(arg) => executor.exec_mem_load_lane::<i8, 1>(*arg)?,
+ V128Load16Lane(arg) => executor.exec_mem_load_lane::<i16, 2>(*arg)?,
+ V128Load32Lane(arg) => executor.exec_mem_load_lane::<i32, 4>(*arg)?,
+ V128Load64Lane(arg) => executor.exec_mem_load_lane::<i64, 8>(*arg)?,
+ I8x16ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?,
+ I16x8ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?,
+ I32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?,
+ I64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::<i64>(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?,
+ F32x4ReplaceLane(lane) => executor.exec_simd_replace_lane::<f32>(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?,
+ F64x2ReplaceLane(lane) => executor.exec_simd_replace_lane::<f64>(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?,
+ I8x16Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i8(v as i8)),
+ I16x8Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i16(v as i16)),
+ I32x4Splat => exec_op!(executor; unary i32 => Value128, |v| Value128::splat_i32(v)),
+ I64x2Splat => exec_op!(executor; unary i64 => Value128, |v| Value128::splat_i64(v)),
+ F32x4Splat => exec_op!(executor; unary f32 => Value128, |v| Value128::splat_f32(v)),
+ F64x2Splat => exec_op!(executor; unary f64 => Value128, |v| Value128::splat_f64(v)),
+ I8x16Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_eq(b)),
+ I16x8Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_eq(b)),
+ I32x4Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_eq(b)),
+ I64x2Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_eq(b)),
+ F32x4Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_eq(b)),
+ F64x2Eq => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_eq(b)),
+ I8x16Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ne(b)),
+ I16x8Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ne(b)),
+ I32x4Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ne(b)),
+ I64x2Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_ne(b)),
+ F32x4Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_ne(b)),
+ F64x2Ne => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_ne(b)),
+ I8x16LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)),
+ I16x8LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)),
+ I32x4LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)),
+ I64x2LtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)),
+ I8x16LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)),
+ I16x8LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)),
+ I32x4LtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)),
+ F32x4Lt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_lt(b)),
+ F64x2Lt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_lt(b)),
+ F32x4Gt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_gt(b)),
+ F64x2Gt => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_gt(b)),
+ I8x16GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)),
+ I16x8GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)),
+ I32x4GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)),
+ I64x2GtS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)),
+ I64x2LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_le_s(b)),
+ F32x4Le => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_le(b)),
+ F64x2Le => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_le(b)),
+ I8x16GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)),
+ I16x8GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)),
+ I32x4GtU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)),
+ F32x4Ge => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_ge(b)),
+ F64x2Ge => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_ge(b)),
+ I8x16LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_le_s(b)),
+ I16x8LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_le_s(b)),
+ I32x4LeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_le_s(b)),
+ I8x16LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_le_u(b)),
+ I16x8LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_le_u(b)),
+ I32x4LeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_le_u(b)),
+ I8x16GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)),
+ I16x8GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)),
+ I32x4GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)),
+ I64x2GeS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)),
+ I8x16GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)),
+ I16x8GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)),
+ I32x4GeU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)),
+ I8x16Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i8x16_abs()),
+ I16x8Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_abs()),
+ I32x4Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_abs()),
+ I64x2Abs => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_abs()),
+ I8x16Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i8x16_neg()),
+ I16x8Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_neg()),
+ I32x4Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_neg()),
+ I64x2Neg => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_neg()),
+ I8x16AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i8x16_all_true() as i32),
+ I16x8AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i16x8_all_true() as i32),
+ I32x4AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i32x4_all_true() as i32),
+ I64x2AllTrue => exec_op!(executor; unary Value128 => i32, |v| v.i64x2_all_true() as i32),
+ I8x16Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i8x16_bitmask() as i32),
+ I16x8Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i16x8_bitmask() as i32),
+ I32x4Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i32x4_bitmask() as i32),
+ I64x2Bitmask => exec_op!(executor; unary Value128 => i32, |v| v.i64x2_bitmask() as i32),
+ I8x16Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)),
+ I16x8Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)),
+ I32x4Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)),
+ I64x2Shl => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)),
+ I8x16ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)),
+ I16x8ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)),
+ I32x4ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)),
+ I64x2ShrS => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)),
+ I8x16ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)),
+ I16x8ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)),
+ I32x4ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)),
+ I64x2ShrU => exec_op!(executor; binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)),
+ I8x16Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add(b)),
+ I16x8Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add(b)),
+ I32x4Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_add(b)),
+ I64x2Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_add(b)),
+ I8x16Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub(b)),
+ I16x8Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub(b)),
+ I32x4Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_sub(b)),
+ I64x2Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_sub(b)),
+ I8x16MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_min_s(b)),
+ I16x8MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_min_s(b)),
+ I32x4MinS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_min_s(b)),
+ I8x16MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_min_u(b)),
+ I16x8MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_min_u(b)),
+ I32x4MinU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_min_u(b)),
+ I8x16MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_max_s(b)),
+ I16x8MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_max_s(b)),
+ I32x4MaxS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_max_s(b)),
+ I8x16MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_max_u(b)),
+ I16x8MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_max_u(b)),
+ I32x4MaxU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_max_u(b)),
+ I64x2Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_mul(b)),
+ I16x8Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_mul(b)),
+ I32x4Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_mul(b)),
+ I8x16NarrowI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)),
+ I8x16NarrowI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)),
+ I16x8NarrowI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)),
+ I16x8NarrowI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)),
+ I8x16AddSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)),
+ I16x8AddSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)),
+ I8x16AddSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)),
+ I16x8AddSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)),
+ I8x16SubSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)),
+ I16x8SubSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)),
+ I8x16SubSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)),
+ I16x8SubSatU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)),
+ I8x16AvgrU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)),
+ I16x8AvgrU => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)),
+ I16x8ExtAddPairwiseI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()),
+ I16x8ExtAddPairwiseI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()),
+ I32x4ExtAddPairwiseI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()),
+ I32x4ExtAddPairwiseI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()),
+ I16x8ExtMulLowI8x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)),
+ I16x8ExtMulLowI8x16U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)),
+ I16x8ExtMulHighI8x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)),
+ I16x8ExtMulHighI8x16U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)),
+ I32x4ExtMulLowI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)),
+ I32x4ExtMulLowI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)),
+ I32x4ExtMulHighI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)),
+ I32x4ExtMulHighI16x8U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)),
+ I64x2ExtMulLowI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)),
+ I64x2ExtMulLowI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)),
+ I64x2ExtMulHighI32x4S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)),
+ I64x2ExtMulHighI32x4U => exec_op!(executor; binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)),
+ I16x8ExtendLowI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()),
+ I16x8ExtendLowI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()),
+ I16x8ExtendHighI8x16S => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()),
+ I16x8ExtendHighI8x16U => exec_op!(executor; unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()),
+ I32x4ExtendLowI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()),
+ I32x4ExtendLowI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()),
+ I32x4ExtendHighI16x8S => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()),
+ I32x4ExtendHighI16x8U => exec_op!(executor; unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()),
+ I64x2ExtendLowI32x4S => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()),
+ I64x2ExtendLowI32x4U => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()),
+ I64x2ExtendHighI32x4S => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()),
+ I64x2ExtendHighI32x4U => exec_op!(executor; unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()),
+ I8x16Popcnt => exec_op!(executor; unary Value128 => Value128, |v| v.i8x16_popcnt()),
+ I8x16Shuffle(idx) => executor.exec_simd_shuffle(Value128(idx.resolve(&executor.func.data).value()))?,
+ I16x8Q15MulrSatS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)),
+ I32x4DotI16x8S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)),
+ I8x16RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)),
+ I16x8RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)),
+ I32x4RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)),
+ I64x2RelaxedLaneselect => exec_op!(executor; ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)),
+ I16x8RelaxedQ15mulrS => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)),
+ I16x8RelaxedDotI8x16I7x16S => exec_op!(executor; binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)),
+ I32x4RelaxedDotI8x16I7x16AddS => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)),
+ F32x4Ceil => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_ceil()),
+ F64x2Ceil => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_ceil()),
+ F32x4Floor => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_floor()),
+ F64x2Floor => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_floor()),
+ F32x4Trunc => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_trunc()),
+ F64x2Trunc => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_trunc()),
+ F32x4Nearest => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_nearest()),
+ F64x2Nearest => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_nearest()),
+ F32x4Abs => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_abs()),
+ F64x2Abs => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_abs()),
+ F32x4Neg => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_neg()),
+ F64x2Neg => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_neg()),
+ F32x4Sqrt => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_sqrt()),
+ F64x2Sqrt => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_sqrt()),
+ F32x4Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_add(b)),
+ F64x2Add => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_add(b)),
+ F32x4Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_sub(b)),
+ F64x2Sub => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_sub(b)),
+ F32x4Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_mul(b)),
+ F64x2Mul => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_mul(b)),
+ F32x4Div => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_div(b)),
+ F64x2Div => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_div(b)),
+ F32x4Min => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_min(b)),
+ F64x2Min => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_min(b)),
+ F32x4Max => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_max(b)),
+ F64x2Max => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_max(b)),
+ F32x4PMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_pmin(b)),
+ F32x4PMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_pmax(b)),
+ F64x2PMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_pmin(b)),
+ F64x2PMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_pmax(b)),
+ F32x4RelaxedMadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)),
+ F32x4RelaxedNmadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)),
+ F64x2RelaxedMadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)),
+ F64x2RelaxedNmadd => exec_op!(executor; ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)),
+ F32x4RelaxedMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)),
+ F32x4RelaxedMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)),
+ F64x2RelaxedMin => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)),
+ F64x2RelaxedMax => exec_op!(executor; binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)),
+ I32x4TruncSatF32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()),
+ I32x4TruncSatF32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()),
+ F32x4ConvertI32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()),
+ F32x4ConvertI32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()),
+ F64x2ConvertLowI32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()),
+ F64x2ConvertLowI32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()),
+ F32x4DemoteF64x2Zero => exec_op!(executor; unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()),
+ F64x2PromoteLowF32x4 => exec_op!(executor; unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()),
+ I32x4TruncSatF64x2SZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()),
+ I32x4TruncSatF64x2UZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()),
+ I32x4RelaxedTruncF32x4S => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()),
+ I32x4RelaxedTruncF32x4U => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()),
+ I32x4RelaxedTruncF64x2SZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()),
+ I32x4RelaxedTruncF64x2UZero => exec_op!(executor; unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()),
+ }
+ };
+}
diff --git a/crates/tinywasm/src/interpreter/executor/mod.rs b/crates/tinywasm/src/interpreter/executor/mod.rs
new file mode 100644
index 0000000..48a99a6
--- /dev/null
+++ b/crates/tinywasm/src/interpreter/executor/mod.rs
@@ -0,0 +1,1561 @@
+use core::convert::identity;
+
+#[cfg(not(feature = "std"))]
+#[allow(unused_imports)]
+use super::no_std_floats::NoStdFloatExt;
+
+use alloc::boxed::Box;
+use alloc::vec::Vec;
+
+use interpreter::stack::{CallFrame, ValueStack};
+use tinywasm_types::*;
+
+use super::ExecState;
+use super::num_helpers::*;
+use super::values::*;
+use crate::engine::FuelPolicy;
+use crate::func::HostFunction;
+use crate::interpreter::Value128;
+use crate::*;
+
+#[macro_use]
+mod instructions;
+
+#[cfg(not(feature = "nightly-tail-calls"))]
+mod dispatch;
+#[cfg(feature = "nightly-tail-calls")]
+mod dispatch_become;
+
+const CHECKPOINT_INTERVAL: u32 = 128;
+const FUEL_COST_CALL_TOTAL: u32 = 5;
+
+struct ExecError(Box<Error>);
+
+type ExecResult<T> = core::result::Result<T, ExecError>;
+
+impl From<Trap> for ExecError {
+ #[cold]
+ fn from(trap: Trap) -> Self {
+ Self(Box::new(Error::Trap(trap)))
+ }
+}
+
+impl From<Error> for ExecError {
+ #[cold]
+ fn from(error: Error) -> Self {
+ Self(Box::new(error))
+ }
+}
+
+impl From<ExecError> for Error {
+ #[cold]
+ fn from(error: ExecError) -> Self {
+ *error.0
+ }
+}
+
+#[derive(Clone, Copy)]
+struct ExecFlow(usize);
+
+impl ExecFlow {
+ const COMPLETE: Self = Self(usize::MAX);
+
+ #[inline(always)]
+ fn next(instr_ptr: usize) -> Self {
+ debug_assert_ne!(instr_ptr, Self::COMPLETE.0);
+ Self(instr_ptr)
+ }
+
+ #[inline(always)]
+ fn next_instr_ptr(self) -> Option<usize> {
+ (self.0 != Self::COMPLETE.0).then_some(self.0)
+ }
+}
+
+pub(crate) struct Executor<'store> {
+ cf: CallFrame,
+ func: Shared<WasmFunction>,
+ module: ModuleInstance,
+ store: &'store mut Store,
+ call_stack_base: u32,
+ mem0: MemAddr,
+ fuel_metered: bool,
+ #[cfg(feature = "nightly-tail-calls")]
+ completed: bool,
+}
+
+impl<'store> Executor<'store> {
+ pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self {
+ let wasm_func = store.state.funcs.wasm(cf.func_addr);
+ let module = store.get_module_instance(wasm_func.owner).expect("invalid module instance").clone();
+ let mem0 = module.mem0_addr();
+ Self {
+ module,
+ cf,
+ func: wasm_func.func.clone(),
+ store,
+ call_stack_base,
+ mem0,
+ fuel_metered: false,
+ #[cfg(feature = "nightly-tail-calls")]
+ completed: false,
+ }
+ }
+
+ /// Resolves a module-local memory index to its store address, caching the common memory-0 case.
+ #[inline(always)]
+ fn mem_addr(&self, idx: MemAddr) -> MemAddr {
+ if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) }
+ }
+
+ /// Switches the executor to another module, keeping the cached memory-0 address in sync.
+ #[inline]
+ fn set_module(&mut self, owner: ModuleInstanceId) {
+ self.module = self.store.get_module_instance(owner).expect("invalid module instance").clone();
+ self.mem0 = self.module.mem0_addr();
+ }
+
+ #[inline(always)]
+ fn charge_call_fuel(&mut self, total_fuel_cost: u32) {
+ if self.fuel_metered {
+ let extra = match self.store.engine.config().fuel_policy {
+ FuelPolicy::PerInstruction => 0,
+ FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1),
+ };
+
+ self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra);
+ }
+ }
+
+ #[inline(always)]
+ fn exec_jump_if_ref<const ON_NULL: bool>(&mut self) -> bool {
+ let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null();
+ if is_null {
+ ValueRef::stack_pop(&mut self.store.value_stack);
+ }
+ is_null == ON_NULL
+ }
+
+ #[inline(always)]
+ fn exec_br_on_cast<const ON_MATCH: bool>(&self, index: Operand64Idx<(u32, u32)>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let ty = RefType::from_bits(operand.b()).expect("invalid ref type");
+ (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_if_local<T: InternalValue + Default + PartialEq, const ON_ZERO: bool>(
+ &self,
+ local: LocalAddr,
+ ) -> bool {
+ (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64<CmpOp, (u32, i32)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128<CmpOp, (u32, i64)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64<CmpOp, (u32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::stack_pop(&mut self.store.value_stack);
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64<CmpOp, (u32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_const_jump(&mut self, packed: PackedOp128<BinOp, LocalUpdateOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| {
+ packed.op.exec(value as u32, operand.value() as u32) as i32
+ });
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_const_jump_cmp_local(
+ &mut self,
+ packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>,
+ ) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| {
+ packed.op.0.exec(value as u32, operand.value() as u32) as i32
+ });
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right());
+ packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_const_tee_local_jump(
+ &mut self,
+ packed: PackedOp128<BinOp, LocalUpdateOperand>,
+ ) -> Result<Option<usize>, Trap> {
+ let operand = packed.index.resolve(&self.func.data);
+ let value = i32::stack_update(&mut self.store.value_stack, |lhs| {
+ packed.op.exec(lhs as u32, operand.value() as u32) as i32
+ });
+ i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value);
+ Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize))
+ }
+
+ #[inline(always)]
+ fn exec_binop_global_const_jump(&mut self, packed: PackedOp128<BinOp, GlobalUpdateOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let global = self.module.resolve_global_addr(operand.global());
+ let value = i32::global_update(&mut self.store.state.globals, global, |value| {
+ packed.op.exec(value as u32, operand.value() as u32) as i32
+ });
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_local_jump(&mut self, index: Operand128Idx<LocalUpdateOperand>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let value = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| {
+ value.wrapping_add(operand.value())
+ });
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_stack_tee_local_jump(
+ &mut self,
+ index: Operand128Idx<LocalUpdateOperand>,
+ ) -> Result<Option<usize>, Trap> {
+ let operand = index.resolve(&self.func.data);
+ let value = i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(operand.value()));
+ i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value);
+ Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize))
+ }
+
+ #[inline(always)]
+ fn exec_inc_global_jump(&mut self, index: Operand128Idx<GlobalUpdateOperand>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let global = self.module.resolve_global_addr(operand.global());
+ let value =
+ i32::global_update(&mut self.store.state.globals, global, |value| value.wrapping_add(operand.value()));
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128<CmpOp, LocalUpdateCmpOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| {
+ value.wrapping_add(operand.value())
+ });
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_const32(&self, packed: PackedOp128<CmpOp, (u32, i32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_const64(&self, packed: PackedOp128<CmpOp, (u32, i32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_local32(&self, packed: PackedOp64<CmpOp, (u32, u16, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b());
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_local64(&self, packed: PackedOp64<CmpOp, (u32, u16, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b());
+ let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ fn exec_i64_add128(&mut self) -> Result<(), Trap> {
+ let b_hi = i64::stack_pop(&mut self.store.value_stack);
+ let b_lo = i64::stack_pop(&mut self.store.value_stack);
+ let a_hi = i64::stack_pop(&mut self.store.value_stack);
+ let a_lo = i64::stack_pop(&mut self.store.value_stack);
+ let lo = a_lo.wrapping_add(b_lo);
+ let carry = u64::from((lo as u64) < (a_lo as u64));
+ let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64);
+ i64::stack_push(&mut self.store.value_stack, lo)?;
+ i64::stack_push(&mut self.store.value_stack, hi)
+ }
+
+ fn exec_i64_sub128(&mut self) -> Result<(), Trap> {
+ let b_hi = i64::stack_pop(&mut self.store.value_stack);
+ let b_lo = i64::stack_pop(&mut self.store.value_stack);
+ let a_hi = i64::stack_pop(&mut self.store.value_stack);
+ let a_lo = i64::stack_pop(&mut self.store.value_stack);
+ let lo = a_lo.wrapping_sub(b_lo);
+ let borrow = u64::from((a_lo as u64) < (b_lo as u64));
+ let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64);
+ i64::stack_push(&mut self.store.value_stack, lo)?;
+ i64::stack_push(&mut self.store.value_stack, hi)
+ }
+
+ fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> {
+ let rhs = i64::stack_pop(&mut self.store.value_stack);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let product = (lhs as i128).wrapping_mul(rhs as i128);
+ i64::stack_push(&mut self.store.value_stack, product as i64)?;
+ i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64)
+ }
+
+ fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> {
+ let rhs = i64::stack_pop(&mut self.store.value_stack);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128);
+ i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?;
+ i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64)
+ }
+
+ #[inline(always)]
+ fn exec_simd_extract_lane<TO: InternalValue>(
+ &mut self,
+ lane: u8,
+ operation: impl FnOnce(Value128, u8) -> TO,
+ ) -> Result<(), Trap> {
+ let vector = Value128::stack_pop(&mut self.store.value_stack);
+ TO::stack_push(&mut self.store.value_stack, operation(vector, lane))
+ }
+
+ #[inline(always)]
+ fn exec_simd_replace_lane<VALUE: InternalValue>(
+ &mut self,
+ lane: u8,
+ operation: impl FnOnce(VALUE, Value128, u8) -> Value128,
+ ) -> Result<(), Trap> {
+ let vector = Value128::stack_pop(&mut self.store.value_stack);
+ let value = VALUE::stack_pop(&mut self.store.value_stack);
+ Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane))
+ }
+
+ fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> {
+ let rhs = Value128::stack_pop(&mut self.store.value_stack);
+ let lhs = Value128::stack_pop(&mut self.store.value_stack);
+ Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes))
+ }
+
+ #[inline(always)]
+ fn exec_local_set_pop<T: InternalValue>(&mut self, local: LocalAddr) {
+ let value = T::stack_pop(&mut self.store.value_stack);
+ T::local_set(&mut self.store.value_stack, &self.cf, local, value);
+ }
+
+ #[inline(always)]
+ fn exec_local_tee<T: InternalValue>(&mut self, local: LocalAddr) {
+ let value = T::stack_peek(&self.store.value_stack);
+ T::local_set(&mut self.store.value_stack, &self.cf, local, value);
+ }
+
+ #[inline(always)]
+ fn exec_global_get<T: InternalValue>(&mut self, global: GlobalAddr) -> Result<(), Trap> {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::global_get(&self.store.state.globals, addr);
+ T::stack_push(&mut self.store.value_stack, value)
+ }
+
+ #[inline(always)]
+ fn exec_global_set<T: InternalValue>(&mut self, global: GlobalAddr) {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::stack_pop(&mut self.store.value_stack);
+ T::global_set(&mut self.store.state.globals, addr, value);
+ }
+
+ #[inline(always)]
+ fn exec_global_tee<T: InternalValue>(&mut self, global: GlobalAddr) {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::stack_peek(&self.store.value_stack);
+ T::global_set(&mut self.store.state.globals, addr, value);
+ }
+
+ #[inline(always)]
+ fn exec_binop_result<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ dst: Option<LocalAddr>,
+ val: T,
+ ) -> Result<(), Trap> {
+ if let Some(dst) = dst {
+ T::local_set(&mut self.store.value_stack, &self.cf, dst, val);
+ }
+ if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) }
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_local<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ lhs: LocalAddr,
+ rhs: LocalAddr,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_local_indexed<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ index: Operand64Idx<(u16, u16, u16)>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let operands = index.resolve(&self.func.data);
+ self.exec_binop_local_local::<T, PUSH>(operands.a(), operands.b(), Some(operands.c()), op)
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_const<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ lhs: LocalAddr,
+ rhs: T,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_global_const<T: InternalValue>(
+ &mut self,
+ lhs: GlobalAddr,
+ rhs: T,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs));
+ T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_cmp_local_local<T>(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap>
+ where
+ T: InternalValue,
+ CmpOp: CmpOpExt<T>,
+ {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs);
+ i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs)))
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_global<T: InternalValue>(
+ &mut self,
+ global: GlobalAddr,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let addr = self.module.resolve_global_addr(global);
+ let rhs = T::global_get(&self.store.state.globals, addr);
+ T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs));
+ Ok(())
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_local<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ local: LocalAddr,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, local);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_const_tee<T: InternalValue>(
+ &mut self,
+ rhs: T,
+ destination: LocalAddr,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs));
+ T::local_set(&mut self.store.value_stack, &self.cf, destination, value);
+ Ok(())
+ }
+
+ #[inline(always)]
+ fn exec_mul_acc_local<T: InternalValue>(
+ &mut self,
+ accumulator: LocalAddr,
+ multiply: fn(T, T) -> T,
+ add: fn(T, T) -> T,
+ ) {
+ let rhs = T::stack_pop(&mut self.store.value_stack);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ let product = multiply(lhs, rhs);
+ T::local_update(&mut self.store.value_stack, &self.cf, accumulator, |value| add(product, value));
+ }
+
+ fn exec_branch_table(&mut self, index: Operand128Idx<BranchTableOperand>) -> usize {
+ let v = index.resolve(&self.func.data);
+ let idx = <i32>::stack_pop(&mut self.store.value_stack);
+ let target_ip = if idx >= 0 && (idx as u32) < v.size() {
+ self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target())
+ } else {
+ v.target()
+ };
+
+ target_ip as usize
+ }
+
+ fn create_exception(&mut self, tag_index: TagAddr) -> Result<ValueRef, Trap> {
+ let tag_addr = self.module.resolve_tag_addr(tag_index);
+ let type_addr = self.store.state.get_tag(tag_addr).type_addr;
+ let payload_len = self.store.state.get_canonical_func_type(type_addr).params().len();
+ self.store.state.gc.check_allocation(payload_len, true)?;
+ let mut payload = Vec::new();
+ cold_err!(payload.try_reserve_exact(payload_len)).map_err(|_| Trap::OutOfMemory)?;
+ let value_stack = &mut self.store.value_stack;
+ for index in (0..payload_len).rev() {
+ let ty = self.store.state.get_canonical_func_type(type_addr).params()[index];
+ payload.push(match ty {
+ WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::stack_pop(value_stack)),
+ WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::stack_pop(value_stack)),
+ WasmType::V128 => RuntimeValue::Value128(Value128::stack_pop(value_stack)),
+ WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::stack_pop(value_stack)),
+ });
+ }
+ payload.reverse();
+ let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw);
+ self.store.state.alloc_exception(tag_addr, payload, roots)
+ }
+
+ fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> ExecResult<ExecFlow> {
+ let exception = self.create_exception(tag_index)?;
+ self.throw_exception(exception, instr_ptr)
+ }
+
+ fn exec_throw_ref(&mut self, instr_ptr: usize) -> ExecResult<ExecFlow> {
+ let exception = ValueRef::stack_pop(&mut self.store.value_stack);
+ if exception.is_null() {
+ return Err(Trap::NullReference.into());
+ }
+ self.throw_exception(exception, instr_ptr)
+ }
+
+ fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> ExecResult<ExecFlow> {
+ match self.dispatch_exception(exception, protected_ip)? {
+ Some(landing_pad) => Ok(ExecFlow::next(landing_pad)),
+ None => match self.store.root_exception(exception) {
+ Ok(exception) => Err(Error::Exception(exception).into()),
+ Err(error) => Err(error.into()),
+ },
+ }
+ }
+
+ fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option<ExceptionCatch> {
+ let handlers = &self.func.data.exception_handlers;
+ let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip);
+ handlers[..end]
+ .iter()
+ .rev()
+ .filter(|handler| protected_ip < handler.end_ip as usize)
+ .flat_map(|handler| handler.catches.iter().copied())
+ .find(|catch| match catch {
+ ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr,
+ ExceptionCatch::All { .. } => true,
+ })
+ }
+
+ #[inline(always)]
+ fn switch_to_frame(&mut self, frame: CallFrame) {
+ let previous = core::mem::replace(&mut self.cf, frame);
+ if previous.func_addr == self.cf.func_addr {
+ return;
+ }
+
+ let wasm_func = self.store.state.funcs.wasm(self.cf.func_addr);
+ if !Shared::ptr_eq(&self.func, &wasm_func.func) {
+ self.func = wasm_func.func.clone();
+ }
+ if wasm_func.owner != self.module.id() {
+ self.set_module(wasm_func.owner);
+ }
+ }
+
+ fn dispatch_exception(&mut self, exception: ValueRef, mut protected_ip: usize) -> Result<Option<usize>, Trap> {
+ let object = self.store.state.gc.get(exception).ok_or(Trap::InvalidReference)?;
+ let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else {
+ return Err(Trap::InvalidReference);
+ };
+ loop {
+ if let Some(catch) = self.matching_catch(protected_ip, tag_addr) {
+ let (landing_pad, base, with_ref, include_payload) = match catch {
+ ExceptionCatch::Tag { landing_pad, base, with_ref, .. } => (landing_pad, base, with_ref, true),
+ ExceptionCatch::All { landing_pad, base, with_ref } => (landing_pad, base, with_ref, false),
+ };
+ let stack_base = self.cf.stack_base();
+ let target = interpreter::stack::StackBase {
+ s32: stack_base.s32 + base.c32 as u32,
+ s64: stack_base.s64 + base.c64 as u32,
+ s128: stack_base.s128 + base.c128 as u32,
+ };
+ self.store.value_stack.truncate_to_base(target);
+ if include_payload {
+ let Store { state, value_stack, .. } = self.store;
+ let object = state.gc.get(exception).ok_or(Trap::InvalidReference)?;
+ for value in object.values.iter().copied() {
+ value_stack.push_dyn(value)?;
+ }
+ }
+ if with_ref {
+ ValueRef::stack_push(&mut self.store.value_stack, exception)?;
+ }
+ return Ok(Some(landing_pad as usize));
+ }
+
+ self.store.value_stack.truncate_to_base(self.cf.locals_base);
+ let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else {
+ return Ok(None);
+ };
+ self.switch_to_frame(caller);
+ protected_ip = self.cf.instr_ptr.checked_sub(1).expect("invalid caller IP");
+ }
+ }
+
+ fn exec_call_host<const TAIL: bool>(
+ &mut self,
+ host_func: HostFunction,
+ type_addr: TypeAddr,
+ return_instr_ptr: usize,
+ ) -> ExecResult<ExecFlow> {
+ if let Some(host_func) = host_func.typed_callback() {
+ cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr))
+ .map_err(|error| Trap::HostFunction(Box::new(error)))?;
+ if TAIL {
+ return Ok(self.exec_return());
+ }
+ return Ok(ExecFlow::next(return_instr_ptr));
+ }
+
+ let (param_count, result_count, base) = {
+ let ty = self.store.state.get_canonical_func_type(type_addr);
+ (ty.params().len(), ty.results().len(), self.store.value_stack.base_before(ty.params().iter().collect()))
+ };
+ let module_id = self.module.id();
+ self.store
+ .with_scratch_values(param_count + result_count, |store, values| {
+ let host_values = store.stack_value_iter(type_addr, crate::store::FuncValueTypes::Params, base)?;
+ for (slot, value) in values[..param_count].iter_mut().zip(host_values) {
+ *slot = value;
+ }
+ store.value_stack.truncate_to_base(base);
+ let (params, results) = values.split_at_mut(param_count);
+ host_func
+ .call_values(store, module_id, type_addr, params, results)
+ .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?;
+ store.push_wasm_values(results)
+ })
+ .map_err(|error| match error {
+ Error::Trap(trap) => trap,
+ other => Trap::HostFunction(Box::new(other)),
+ })?;
+ if TAIL { Ok(self.exec_return()) } else { Ok(ExecFlow::next(return_instr_ptr)) }
+ }
+
+ fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> ExecResult<ExecFlow> {
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+ let addr = self.module.resolve_func_addr(v);
+ if self.store.state.funcs.is_host(addr) {
+ let host_func = self.store.state.funcs.host(addr);
+ let type_addr = host_func.type_addr;
+ let host_func = host_func.func.clone();
+ self.exec_call_host::<false>(host_func, type_addr, return_instr_ptr)
+ } else {
+ self.exec_call_wasm::<false>(addr, return_instr_ptr)
+ }
+ }
+
+ fn exec_return_call_direct(&mut self, v: u32) -> ExecResult<ExecFlow> {
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+ let addr = self.module.resolve_func_addr(v);
+ if self.store.state.funcs.is_host(addr) {
+ let host_func = self.store.state.funcs.host(addr);
+ let type_addr = host_func.type_addr;
+ let host_func = host_func.func.clone();
+ self.exec_call_host::<true>(host_func, type_addr, 0)
+ } else {
+ self.exec_call_wasm::<true>(addr, 0)
+ }
+ }
+
+ fn exec_call_self(&mut self, return_instr_ptr: usize) -> ExecResult<()> {
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+ let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
+ return cold!(Err(Trap::CallStackOverflow.into()));
+ };
+ let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
+ self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?;
+ Ok(())
+ }
+
+ fn exec_return_call_self(&mut self) -> ExecResult<()> {
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+
+ self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params);
+ let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
+ return cold!(Err(Trap::CallStackOverflow.into()));
+ };
+ self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
+ Ok(())
+ }
+
+ fn exec_call_indirect<const TAIL: bool>(
+ &mut self,
+ index: Operand64Idx<(u32, u32)>,
+ return_instr_ptr: usize,
+ ) -> ExecResult<ExecFlow> {
+ let operand = index.resolve(&self.func.data);
+ let type_addr = operand.a();
+ let table_addr = operand.b();
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+ // verify that the table is of the right type, this should be validated by the parser already
+ 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);
+
+ let Ok(table) = table.get(table_idx) else {
+ return cold!(Err(Trap::UndefinedElement { index: table_idx }.into()));
+ };
+
+ let Some(func_ref) = table.addr() else {
+ return cold!(Err(Trap::UninitializedElement { index: table_idx }.into()));
+ };
+
+ self.exec_typed_call::<TAIL>(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr)
+ }
+
+ fn exec_typed_call<const TAIL: bool>(
+ &mut self,
+ func_addr: FuncAddr,
+ expected_type_addr: TypeAddr,
+ return_instr_ptr: usize,
+ ) -> ExecResult<ExecFlow> {
+ let type_addr = self.store.state.funcs.type_addr(func_addr);
+ if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) {
+ return cold!(Err(Trap::IndirectCallTypeMismatch {
+ actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()),
+ expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()),
+ }
+ .into()));
+ }
+ if self.store.state.funcs.is_host(func_addr) {
+ let host_func = self.store.state.funcs.host(func_addr);
+ let host_func = host_func.func.clone();
+ return self.exec_call_host::<TAIL>(host_func, type_addr, return_instr_ptr);
+ }
+
+ self.exec_call_wasm::<TAIL>(func_addr, return_instr_ptr)
+ }
+
+ #[inline(always)]
+ fn exec_call_wasm<const TAIL: bool>(
+ &mut self,
+ func_addr: FuncAddr,
+ return_instr_ptr: usize,
+ ) -> ExecResult<ExecFlow> {
+ let wasm_func = self.store.state.funcs.wasm(func_addr);
+ let (params, locals, owner, next_func) = {
+ let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone());
+ (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func)
+ };
+ if TAIL {
+ self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params);
+ }
+ let locals_base = self.store.value_stack.enter_locals(&params, &locals)?;
+ if TAIL {
+ self.cf = CallFrame::new(func_addr, locals_base, locals);
+ } else {
+ self.store.call_stack.push(self.cf, return_instr_ptr)?;
+ self.cf = CallFrame::new(func_addr, locals_base, locals);
+ }
+ if let Some(next_func) = next_func {
+ self.func = next_func;
+ }
+ if owner != self.module.id() {
+ self.set_module(owner);
+ }
+ Ok(ExecFlow::next(0))
+ }
+
+ fn exec_call_ref<const TAIL: bool>(&mut self, type_addr: u32, return_instr_ptr: usize) -> ExecResult<ExecFlow> {
+ self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
+ let func_ref = ValueRef::stack_pop(&mut self.store.value_stack);
+ let Some(func_addr) = func_ref.addr() else {
+ return cold!(Err(Trap::NullFunctionReference.into()));
+ };
+
+ self.exec_typed_call::<TAIL>(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr)
+ }
+
+ fn exec_return(&mut self) -> ExecFlow {
+ self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.results);
+ self.finish_return()
+ }
+
+ #[inline(always)]
+ fn finish_return(&mut self) -> ExecFlow {
+ let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else {
+ return ExecFlow::COMPLETE;
+ };
+ let instr_ptr = caller.instr_ptr;
+ if caller.func_addr == self.cf.func_addr {
+ self.cf = caller;
+ } else {
+ self.switch_to_frame(caller);
+ }
+ ExecFlow::next(instr_ptr)
+ }
+
+ fn exec_return_void(&mut self) -> ExecFlow {
+ self.store.value_stack.truncate_to_base(self.cf.locals_base);
+ self.finish_return()
+ }
+
+ fn exec_return_32(&mut self) -> ExecFlow {
+ self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize);
+ self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
+ self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize);
+ self.finish_return()
+ }
+
+ fn exec_return_64(&mut self) -> ExecFlow {
+ self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
+ self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize);
+ self.store.value_stack.stack_128.truncate_to(self.cf.locals_base.s128 as usize);
+ self.finish_return()
+ }
+
+ fn exec_return_128(&mut self) -> ExecFlow {
+ self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
+ self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
+ self.store.value_stack.stack_128.truncate_to_one_tail(self.cf.locals_base.s128 as usize);
+ self.finish_return()
+ }
+
+ fn exec_store_local_local<T: InternalValue + MemValue<N>, const N: usize>(
+ &mut self,
+ index: Operand64Idx<CompactMemoryOperand>,
+ addr_local: u8,
+ value_local: u8,
+ ) -> Result<(), Trap> {
+ let memarg = index.resolve(&self.func.data);
+ let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local));
+ let mem_addr = self.mem_addr(MemAddr::from(memarg.memory()));
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let addr = if mem.is_64bit() {
+ let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
+ let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds {
+ offset: usize::MAX,
+ len: N,
+ max: mem.inner.len(),
+ }))?;
+ cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?
+ } else {
+ let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
+ cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))?
+ };
+ value.store_at(&mut mem.inner, addr)
+ }
+
+ fn exec_inc_memory_local<T: MemValue<N>, const N: usize>(
+ &mut self,
+ index: Operand64Idx<CompactMemoryOperand>,
+ addr_local: u8,
+ increment: impl FnOnce(T) -> T,
+ ) -> Result<(), Trap> {
+ let memarg = index.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(MemAddr::from(memarg.memory()));
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let addr = if mem.is_64bit() {
+ let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
+ let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds {
+ offset: usize::MAX,
+ len: N,
+ max: mem.inner.len(),
+ }))?;
+ cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?
+ } else {
+ let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
+ cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))?
+ };
+
+ let value = cold_err!(T::load_at(&mem.inner, addr))?;
+ increment(value).store_at(&mut mem.inner, addr)
+ }
+
+ fn exec_fma_store<
+ T: InternalValue + MemValue<N> + core::ops::Add<Output = T> + core::ops::Mul<Output = T>,
+ const N: usize,
+ >(
+ &mut self,
+ m: CompactMemoryArg,
+ ) -> Result<(), Trap> {
+ let rhs = T::stack_pop(&mut self.store.value_stack);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ let acc = T::stack_pop(&mut self.store.value_stack);
+ let fma = acc + lhs * rhs;
+ let mem_addr = self.mem_addr(m.mem_addr());
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
+ let addr = cold_err!(mem.effective_addr::<N>(base, m.offset()))?;
+ cold_err!(fma.store_at(&mut mem.inner, addr))
+ }
+
+ fn exec_load_local<
+ LOAD: MemValue<N>,
+ const N: usize,
+ TARGET: InternalValue,
+ const SET_LOCAL: bool,
+ const TEE: bool,
+ >(
+ &mut self,
+ index: Operand64Idx<CompactMemoryOperand>,
+ addr_local: u8,
+ dst_local: u8,
+ cast: impl Fn(LOAD) -> TARGET,
+ ) -> Result<(), Trap> {
+ let memarg = index.resolve(&self.func.data);
+
+ let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory())));
+ let base = if mem.is_64bit() {
+ let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
+ cold_err!(usize::try_from(base)).map_err(|_| Trap::MemoryOutOfBounds {
+ offset: usize::MAX,
+ len: N,
+ max: mem.inner.len(),
+ })?
+ } else {
+ u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as usize
+ };
+
+ let addr = cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?;
+ let value = cast(cold_err!(LOAD::load_at(&mem.inner, addr))?);
+
+ if SET_LOCAL {
+ TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value);
+ }
+ if !SET_LOCAL || TEE {
+ TARGET::stack_push(&mut self.store.value_stack, value)?;
+ }
+ Ok(())
+ }
+
+ fn exec_ref_is_null(&mut self) -> Result<(), Trap> {
+ let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null());
+ i32::stack_push(&mut self.store.value_stack, is_null)
+ }
+
+ fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> {
+ if ValueRef::stack_peek(&self.store.value_stack).is_null() {
+ return cold!(Err(Trap::NullReference));
+ }
+ 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))
+ }
+
+ 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_ref_test(&mut self, ty: RefType) -> Result<(), Trap> {
+ let value = ValueRef::stack_pop(&mut self.store.value_stack);
+ let matches = self.store.state.value_ref_matches(value, self.canonical_ref_type(ty));
+ i32::stack_push(&mut self.store.value_stack, i32::from(matches))
+ }
+
+ fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> {
+ if !self.exec_ref_matches(ty) {
+ return cold!(Err(Trap::CastFailure));
+ }
+ Ok(())
+ }
+
+ fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> {
+ let value = ValueRef::stack_pop(&mut self.store.value_stack);
+ if value.is_null() {
+ return cold!(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
+ };
+ i32::stack_push(&mut self.store.value_stack, value)
+ }
+
+ fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec<RuntimeValue>) -> Result<(), Trap> {
+ let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw);
+ let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?;
+ ValueRef::stack_push(&mut self.store.value_stack, reference)
+ }
+
+ fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> {
+ let type_addr = self.module.resolve_type_addr(type_index);
+ let field_count =
+ self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields.len();
+ self.store.state.check_gc_allocation(type_addr, field_count)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?;
+ if default {
+ values.extend(
+ self.store
+ .state
+ .get_type(type_addr)
+ .as_struct()
+ .expect("validated struct.new type")
+ .fields
+ .iter()
+ .map(|field| default_value(field.storage)),
+ );
+ } else {
+ for index in (0..field_count).rev() {
+ let storage = self.store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage;
+ values.push(pop_value(&mut self.store.value_stack, storage));
+ }
+ values.reverse();
+ }
+ self.push_gc_object(type_addr, values)
+ }
+
+ fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option<bool>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let field_index = operand.b();
+ 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 object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?;
+ 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, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let field_index = operand.b();
+ 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);
+ let object = self.store.state.gc_object(reference, type_addr)?;
+ self.store.state.gc.set(object, 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;
+ self.store.state.check_gc_allocation(type_addr, len)?;
+ let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) };
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?;
+ values.resize(len, value);
+ self.push_gc_object(type_addr, values)
+ }
+
+ fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let len = operand.b();
+ 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;
+ self.store.state.check_gc_allocation(type_addr, len)?;
+ let mut values = Vec::new();
+ cold_err!(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();
+ self.push_gc_object(type_addr, values)
+ }
+
+ 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 object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?;
+ 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)?;
+ self.store.state.gc.set(object, index, value).ok_or(Trap::ArrayOutOfBounds)
+ }
+
+ 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"))?;
+ let crate::store::GcObjectKind::Composite(type_addr) = object.kind else {
+ return Err(Trap::Other("GC reference is not an array"));
+ };
+ if self.store.state.get_type(type_addr).as_array().is_none() {
+ return Err(Trap::Other("GC reference is not an array"));
+ }
+ i32::stack_push(&mut self.store.value_stack, 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 object_ref = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?;
+ let end = index.checked_add(len).filter(|end| *end <= object_ref.values.len()).ok_or(Trap::ArrayOutOfBounds)?;
+ self.store.state.gc.fill(object, index..end, value).expect("live array range");
+ Ok(())
+ }
+
+ fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_type = operand.a();
+ let src_type = operand.b();
+ 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_handle = self.store.state.gc_object(dst, dst_type)?;
+ let dst_len = self.store.state.gc.get_handle(dst_handle).expect("validated array").values.len();
+ let src_handle = self.store.state.gc_object(src, src_type)?;
+ let src_object = self.store.state.gc.get_handle(src_handle).expect("validated array");
+ 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_handle == dst_handle {
+ self.store.state.gc.copy_within(dst_handle, src_index..src_end, dst_index).expect("live array range");
+ return Ok(());
+ }
+ self.store
+ .state
+ .gc
+ .copy_between(src_handle, src_index..src_end, dst_handle, dst_index)
+ .expect("live array ranges");
+ Ok(())
+ }
+
+ fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let data_index = operand.b();
+ 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(&[]);
+ data_range(storage, data, src, len)?;
+ self.store.state.check_gc_allocation(type_addr, len)?;
+ let values = decode_data(storage, data, src, len)?;
+ self.push_gc_object(type_addr, values)
+ }
+
+ fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let elem_index = operand.b();
+ 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 elem_addr = self.module.resolve_elem_addr(elem_index);
+ let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?;
+ self.store.state.check_gc_allocation(type_addr, len)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(items.iter().copied().map(RuntimeValue::ValueRef));
+ self.push_gc_object(type_addr, values)
+ }
+
+ fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let data_index = operand.b();
+ 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 = self.store.state.gc_object(reference, type_addr)?;
+ let object_len = self.store.state.gc.get_handle(object).expect("validated array").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(object, dst, &values).expect("live array range");
+ Ok(())
+ }
+
+ fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let elem_index = operand.b();
+ 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 = self.store.state.gc_object(reference, type_addr)?;
+ let object_len = self.store.state.gc.get_handle(object).expect("validated array").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_range(src, len)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(items.iter().copied().map(RuntimeValue::ValueRef));
+ self.store.state.gc.set_slice(object, 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.mem_addr(addr));
+ match mem.is_64bit() {
+ true => i64::stack_push(&mut self.store.value_stack, mem.page_count as i64),
+ false => i32::stack_push(&mut self.store.value_stack, mem.page_count as i32),
+ }
+ }
+
+ fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> {
+ let mem_addr = self.mem_addr(addr);
+ let limiter = self.store.engine.config().resource_limiter.as_deref();
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let is_64bit = mem.is_64bit();
+ let pages_delta = match is_64bit {
+ true => i64::stack_pop(&mut self.store.value_stack),
+ false => i64::from(i32::stack_pop(&mut self.store.value_stack)),
+ };
+
+ let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1);
+ match is_64bit {
+ true => i64::stack_push(&mut self.store.value_stack, size)?,
+ false => i32::stack_push(&mut self.store.value_stack, size as i32)?,
+ };
+
+ Ok(())
+ }
+
+ fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_mem = operand.a();
+ let src_mem = operand.b();
+ let dst_mem_addr = self.mem_addr(dst_mem);
+ let src_mem_addr = self.mem_addr(src_mem);
+ let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch();
+ let src_arch = self.store.state.get_mem(src_mem_addr).kind.arch();
+ let len_arch =
+ if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 };
+ let size = self.store.value_stack.pop_memory_operand(len_arch)?;
+ let src = self.store.value_stack.pop_memory_operand(src_arch)?;
+ let dst = self.store.value_stack.pop_memory_operand(dst_arch)?;
+
+ if dst_mem_addr == src_mem_addr {
+ // copy within the same memory
+ let mem = self.store.state.get_mem_mut(dst_mem_addr);
+ mem.copy_within(dst, src, size)?;
+ } else {
+ // copy between two memories
+ let (dst_memory, src_memory) = self.store.state.get_mems_mut(dst_mem_addr, src_mem_addr);
+ dst_memory.copy_from_memory(dst, src_memory, src, size)?;
+ }
+ Ok(())
+ }
+
+ fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> {
+ let mem_addr = self.mem_addr(addr);
+ let arch = self.store.state.get_mem(mem_addr).kind.arch();
+ let size = self.store.value_stack.pop_memory_operand(arch)?;
+ let val = i32::stack_pop(&mut self.store.value_stack);
+ let dst = self.store.value_stack.pop_memory_operand(arch)?;
+ self.exec_memory_fill_impl(mem_addr, dst, val as u8, size)
+ }
+
+ fn exec_memory_fill_const(&mut self, index: Operand128Idx<MemoryFillOperand>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(operand.memory());
+ let arch = self.store.state.get_mem(mem_addr).kind.arch();
+ let dst = self.store.value_stack.pop_memory_operand(arch)?;
+ self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize)
+ }
+
+ fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> {
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let max = mem.inner.len();
+ if mem.inner.fill(dst, size, val).is_none() {
+ return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max }));
+ }
+ Ok(())
+ }
+
+ fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let data_index = operand.a();
+ let mem_index = operand.b();
+ let size = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let offset = u32::stack_pop(&mut self.store.value_stack) as usize;
+ let mem_addr = self.mem_addr(mem_index);
+ let arch = self.store.state.get_mem(mem_addr).kind.arch();
+ let dst = self.store.value_stack.pop_memory_operand(arch)?;
+
+ let data = &self.store.state.data[self.module.resolve_data_addr(data_index) as usize];
+ let mem = &mut self.store.state.memories[mem_addr as usize];
+ let data_len = data.data.as_ref().map_or(0, |d| d.len());
+ let mem_len = mem.inner.len();
+ if offset.checked_add(size).is_none_or(|end| end > data_len) {
+ return cold!(Err(Trap::MemoryOutOfBounds { offset, len: size, max: data_len }));
+ }
+ if dst.checked_add(size).is_none_or(|end| end > mem_len) {
+ return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len }));
+ }
+
+ if size == 0 {
+ return Ok(());
+ }
+
+ let Some(data) = &data.data else {
+ return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 }));
+ };
+
+ if mem.inner.write_all(dst, &data[offset..offset + size]).is_none() {
+ return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len }));
+ }
+ Ok(())
+ }
+
+ fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_table = operand.a();
+ let src_table = operand.b();
+ let dst_table_addr = self.module.resolve_table_addr(dst_table);
+ let src_table_addr = self.module.resolve_table_addr(src_table);
+ let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch();
+ let src_arch = self.store.state.get_table(src_table_addr).kind.arch();
+ let len_arch =
+ if dst_arch == MemoryArch::I32 || src_arch == MemoryArch::I32 { MemoryArch::I32 } else { MemoryArch::I64 };
+ let size = self.pop_table_operand(len_arch)?;
+ let src = self.pop_table_operand(src_arch)?;
+ let dst = self.pop_table_operand(dst_arch)?;
+
+ if dst_table_addr == src_table_addr {
+ // copy within the same table
+ self.store.state.get_table_mut(dst_table_addr).copy_within(dst, src, size)
+ } else {
+ // copy between two tables
+ let (dst_table_ref, src_table_ref) = self.store.state.get_tables_mut(dst_table_addr, src_table_addr);
+ dst_table_ref.copy_from_slice(dst, src_table_ref.load(src, size)?)
+ }
+ }
+
+ fn exec_mem_load_lane<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize>(
+ &mut self,
+ arg: MemoryLaneArg,
+ ) -> Result<(), Trap> {
+ let m = arg.memory_arg_idx.resolve(&self.func.data);
+ let mem = self.store.state.get_mem(self.mem_addr(m.memory()));
+ let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
+ let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?;
+ let val = cold_err!(LOAD::load_at(&mem.inner, addr))?;
+ let offset = arg.lane as usize * LOAD_SIZE;
+ Value128::stack_update(&mut self.store.value_stack, |value| {
+ let mut bytes = value.to_mem_bytes();
+ bytes[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes());
+ Value128(bytes)
+ });
+ Ok(())
+ }
+
+ #[inline(always)]
+ fn exec_mem_load<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize, TARGET: InternalValue>(
+ &mut self,
+ m: Operand128<MemoryOperand>,
+ cast: impl Fn(LOAD) -> TARGET,
+ ) -> Result<(), Trap> {
+ let mem = self.store.state.get_mem(self.mem_addr(m.memory()));
+ let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
+ let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?;
+ let value = cold_err!(LOAD::load_at(&mem.inner, addr))?;
+ TARGET::stack_push(&mut self.store.value_stack, cast(value))
+ }
+
+ #[inline(always)]
+ fn exec_mem_store_lane<U: MemValue<N> + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> {
+ let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes();
+ let lane_offset = arg.lane as usize * N;
+ let mut val_bytes = [0u8; N];
+ val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]);
+ let val = U::from_mem_bytes(val_bytes);
+ let m = arg.memory_arg_idx.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(m.memory());
+ let mem = self.store.state.get_mem_mut(mem_addr);
+ let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
+ let addr = cold_err!(mem.effective_addr::<N>(base, m.offset()))?;
+ cold_err!(val.store_at(&mut mem.inner, addr))?;
+ Ok(())
+ }
+
+ #[inline(always)]
+ fn exec_mem_store<T: InternalValue, U: MemValue<N>, const N: usize>(
+ &mut self,
+ memory: Operand128<MemoryOperand>,
+ cast: impl Fn(T) -> U,
+ ) -> Result<(), Trap> {
+ let val = cast(<T>::stack_pop(&mut self.store.value_stack));
+ self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val)
+ }
+
+ #[inline(always)]
+ fn exec_select_store<T: InternalValue + MemValue<N>, const N: usize>(
+ &mut self,
+ memory: Operand128<MemoryOperand>,
+ ) -> Result<(), Trap> {
+ let condition = Value32::stack_pop(&mut self.store.value_stack);
+ let false_value = T::stack_pop(&mut self.store.value_stack);
+ let true_value = T::stack_pop(&mut self.store.value_stack);
+ let value = if condition == 0 { false_value } else { true_value };
+ self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value)
+ }
+
+ #[inline(always)]
+ fn exec_mem_store_value<U: MemValue<N>, const N: usize>(
+ &mut self,
+ memory_addr: MemAddr,
+ offset: u64,
+ val: U,
+ ) -> Result<(), Trap> {
+ let mem = self.store.state.get_mem_mut(memory_addr);
+ let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
+ let addr = cold_err!(mem.effective_addr::<N>(base, offset))?;
+ cold_err!(val.store_at(&mut mem.inner, addr))
+ }
+
+ 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 value = *self.store.state.get_table(table_addr).get(idx)?;
+ ValueRef::stack_push(&mut self.store.value_stack, value)
+ }
+
+ fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> {
+ let val = ValueRef::stack_pop(&mut self.store.value_stack);
+ 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)
+ }
+
+ fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> {
+ let table = self.store.state.get_table(self.module.resolve_table_addr(table_index));
+ match table.kind.arch() {
+ MemoryArch::I32 => i32::stack_push(&mut self.store.value_stack, table.size() as i32),
+ MemoryArch::I64 => i64::stack_push(&mut self.store.value_stack, table.size() as i64),
+ }
+ }
+
+ fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let elem_index = operand.a();
+ let table_index = operand.b();
+ let size = self.pop_table_operand(MemoryArch::I32)?; // n
+ let offset = self.pop_table_operand(MemoryArch::I32)?; // s
+ let table_addr = self.module.resolve_table_addr(table_index);
+ let dst = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; // d
+ let elem_addr = self.module.resolve_elem_addr(elem_index) as usize;
+ let elem = self.store.state.elements.get(elem_addr).ok_or_else(|| Trap::Other("element not found"))?;
+ let items = elem.items_range(offset, size)?;
+
+ let table =
+ self.store.state.tables.get_mut(table_addr as usize).ok_or_else(|| Trap::Other("table not found"))?;
+ table.init(dst, items)
+ }
+
+ fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> {
+ let table_addr = self.module.resolve_table_addr(table_index);
+ let arch = self.store.state.get_table(table_addr).kind.arch();
+ let n = self.pop_table_operand(arch)?;
+ let val = ValueRef::stack_pop(&mut self.store.value_stack);
+ let limiter = self.store.engine.config().resource_limiter.as_deref();
+ let table = self.store.state.get_table_mut(table_addr);
+ let sz = table.size();
+ let grew = table.grow(n, val, limiter)?;
+ match (arch, grew) {
+ (MemoryArch::I32, true) => i32::stack_push(&mut self.store.value_stack, sz as i32),
+ (MemoryArch::I32, false) => i32::stack_push(&mut self.store.value_stack, -1),
+ (MemoryArch::I64, true) => i64::stack_push(&mut self.store.value_stack, sz as i64),
+ (MemoryArch::I64, false) => i64::stack_push(&mut self.store.value_stack, -1),
+ }
+ }
+
+ fn exec_table_fill(&mut self, table_index: u32) -> Result<(), Trap> {
+ let table_addr = self.module.resolve_table_addr(table_index);
+ let arch = self.store.state.get_table(table_addr).kind.arch();
+ 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)
+ }
+
+ fn pop_table_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> {
+ let value = match arch {
+ MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64,
+ MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64,
+ };
+ cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds {
+ offset: usize::MAX,
+ len: 1,
+ max: usize::MAX,
+ }))
+ }
+}
diff --git a/crates/tinywasm/src/interpreter/mod.rs b/crates/tinywasm/src/interpreter/mod.rs
index cece36a..0f7ae20 100644
--- a/crates/tinywasm/src/interpreter/mod.rs
+++ b/crates/tinywasm/src/interpreter/mod.rs
@@ -7,7 +7,7 @@ pub(crate) mod values;
#[cfg(not(feature = "std"))]
mod no_std_floats;
-use crate::{Result, Store, Trap, interpreter::stack::CallFrame};
+use crate::{Result, Store, interpreter::stack::CallFrame};
pub(crate) use simd::*;
pub(crate) use values::*;
@@ -26,12 +26,12 @@ pub(crate) enum ExecState {
pub(crate) struct InterpreterRuntime;
impl InterpreterRuntime {
- pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<(), Trap> {
- executor::Executor::<false>::new(store, cf, call_stack_base).run_to_completion()
+ pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<()> {
+ executor::Executor::new(store, cf, call_stack_base).run_to_completion()
}
- pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result<ExecState, Trap> {
- executor::Executor::<true>::new(store, cf, 0).run_with_fuel(fuel)
+ pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result<ExecState> {
+ executor::Executor::new(store, cf, 0).run_with_fuel(fuel)
}
#[cfg(feature = "std")]
@@ -39,7 +39,7 @@ impl InterpreterRuntime {
store: &mut Store,
cf: CallFrame,
time_budget: core::time::Duration,
- ) -> Result<ExecState, Trap> {
- executor::Executor::<false>::new(store, cf, 0).run_with_time_budget(time_budget)
+ ) -> Result<ExecState> {
+ executor::Executor::new(store, cf, 0).run_with_time_budget(time_budget)
}
}
diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs
index 7b3807e..591326f 100644
--- a/crates/tinywasm/src/interpreter/num_helpers.rs
+++ b/crates/tinywasm/src/interpreter/num_helpers.rs
@@ -7,38 +7,35 @@ pub(crate) trait TinywasmIntExt: Sized {
/// we need to check for overflow. This macro generates the min/max values
/// for a specific conversion, which are then used in the actual conversion.
/// Rust sadly doesn't have wrapping casts for floats yet.
-#[rustfmt::skip]
macro_rules! float_min_max {
- (f32, i32) => {(i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0)}; // 2^8: f32 precision margin
- (f64, i32) => {(i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0)};
- (f32, u32) => {(-1.0_f32, u32::MAX as f32 + 1.0)};
- (f64, u32) => {(-1.0_f64, u32::MAX as f64 + 1.0)};
- (f32, i64) => {(i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0)}; // 2^40: f32 has 23 mantissa bits
- (f64, i64) => {(i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0)}; // 2^11: f64 precision margin
- (f32, u64) => {(-1.0_f32, u64::MAX as f32 + 1.0)};
- (f64, u64) => {(-1.0_f64, u64::MAX as f64 + 1.0)};
- ($from:ty, $to:ty) => {compile_error!("invalid float conversion")};
+ (f32, i32) => {{ (i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0) }}; // 2^8: f32 precision margin
+ (f64, i32) => {{ (i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0) }};
+ (f32, u32) => {{ (-1.0_f32, u32::MAX as f32 + 1.0) }};
+ (f64, u32) => {{ (-1.0_f64, u32::MAX as f64 + 1.0) }};
+ (f32, i64) => {{ (i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0) }}; // 2^40: f32 has 23 mantissa bits
+ (f64, i64) => {{ (i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0) }}; // 2^11: f64 precision margin
+ (f32, u64) => {{ (-1.0_f32, u64::MAX as f32 + 1.0) }};
+ (f64, u64) => {{ (-1.0_f64, u64::MAX as f64 + 1.0) }};
+ ($from:ty, $to:ty) => {{ compile_error!("invalid float conversion") }};
}
/// Convert a value on the stack with error checking
macro_rules! checked_conv_float {
// Direct conversion with error checking (two types)
- ($from:tt, $to:tt, $self:expr) => {
- checked_conv_float!($from, $to, $to, $self)
- };
+ ($from:tt, $to:tt, $self:expr) => {{ checked_conv_float!($from, $to, $to, $self) }};
// Conversion with an intermediate unsigned type and error checking (three types)
($from:tt, $intermediate:tt, $to:tt, $self:expr) => {{
let v = <$from>::stack_pop(&mut $self.store.value_stack);
let (min, max) = float_min_max!($from, $intermediate);
if v.is_nan() {
core::hint::cold_path();
- return Err(crate::Trap::InvalidConversionToInt);
+ return Err(crate::Trap::InvalidConversionToInt.into());
}
if v <= min || v >= max {
core::hint::cold_path();
- return Err(crate::Trap::IntegerOverflow);
+ return Err(crate::Trap::IntegerOverflow.into());
}
- $self.store.value_stack.push::<$to>((v as $intermediate as $to).into())?;
+ <$to>::stack_push(&mut $self.store.value_stack, (v as $intermediate as $to).into())?;
}};
}
@@ -123,18 +120,16 @@ macro_rules! impl_checked_wrapping_rem {
impl TinywasmIntExt for $t {
fn tw_checked_wrapping_rem(self, rhs: Self) -> Result<Self, crate::Trap> {
if rhs == 0 {
- Err(crate::Trap::DivisionByZero)
- } else {
- Ok(self.wrapping_rem(rhs))
+ return Err(crate::Trap::DivisionByZero)
}
+ Ok(self.wrapping_rem(rhs))
}
fn tw_checked_div(self, rhs: Self) -> Result<Self, crate::Trap> {
if rhs == 0 {
- Err(crate::Trap::DivisionByZero)
- } else {
- self.checked_div(rhs).ok_or_else(|| crate::Trap::IntegerOverflow)
+ return Err(crate::Trap::DivisionByZero)
}
+ self.checked_div(rhs).ok_or_else(|| crate::Trap::IntegerOverflow)
}
}
)*)
diff --git a/crates/tinywasm/src/interpreter/simd/instructions.rs b/crates/tinywasm/src/interpreter/simd/instructions.rs
index c859caf..cd35d16 100644
--- a/crates/tinywasm/src/interpreter/simd/instructions.rs
+++ b/crates/tinywasm/src/interpreter/simd/instructions.rs
@@ -26,7 +26,7 @@ use core::arch::x86_64 as x86;
impl Value128 {
#[doc(alias = "v128.any_true")]
- pub fn v128_any_true(self) -> bool {
+ pub(crate) fn v128_any_true(self) -> bool {
simd_impl! {
wasm => { wasm::v128_any_true(self.to_wasm_v128()) }
generic => { self.0.iter().any(|&b| b != 0) }
@@ -34,7 +34,7 @@ impl Value128 {
}
#[doc(alias = "v128.not")]
- pub fn v128_not(self) -> Self {
+ pub(crate) fn v128_not(self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_not(self.to_wasm_v128())) }
generic => { Self(self.0.map(|b| !b)) }
@@ -42,7 +42,7 @@ impl Value128 {
}
#[doc(alias = "v128.and")]
- pub fn v128_and(self, rhs: Self) -> Self {
+ pub(crate) fn v128_and(self, rhs: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_and(self.to_wasm_v128(), rhs.to_wasm_v128())) }
generic => { (i128::from(self) & i128::from(rhs)).into() }
@@ -50,7 +50,7 @@ impl Value128 {
}
#[doc(alias = "v128.andnot")]
- pub fn v128_andnot(self, rhs: Self) -> Self {
+ pub(crate) fn v128_andnot(self, rhs: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_andnot(self.to_wasm_v128(), rhs.to_wasm_v128())) }
generic => { (i128::from(self) & !i128::from(rhs)).into() }
@@ -58,7 +58,7 @@ impl Value128 {
}
#[doc(alias = "v128.or")]
- pub fn v128_or(self, rhs: Self) -> Self {
+ pub(crate) fn v128_or(self, rhs: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_or(self.to_wasm_v128(), rhs.to_wasm_v128())) }
generic => { (i128::from(self) | i128::from(rhs)).into() }
@@ -66,7 +66,7 @@ impl Value128 {
}
#[doc(alias = "v128.xor")]
- pub fn v128_xor(self, rhs: Self) -> Self {
+ pub(crate) fn v128_xor(self, rhs: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_xor(self.to_wasm_v128(), rhs.to_wasm_v128())) }
generic => { (i128::from(self) ^ i128::from(rhs)).into() }
@@ -74,7 +74,7 @@ impl Value128 {
}
#[doc(alias = "v128.bitselect")]
- pub fn v128_bitselect(v1: Self, v2: Self, c: Self) -> Self {
+ pub(crate) fn v128_bitselect(v1: Self, v2: Self, c: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::v128_bitselect(v1.to_wasm_v128(), v2.to_wasm_v128(), c.to_wasm_v128())) }
generic => { ((i128::from(v1) & i128::from(c)) | (i128::from(v2) & !i128::from(c))).into() }
@@ -82,7 +82,7 @@ impl Value128 {
}
#[doc(alias = "v128.load8x8_s")]
- pub const fn v128_load8x8_s(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load8x8_s(src: [u8; 8]) -> Self {
Self::from_i16x8([
src[0] as i8 as i16,
src[1] as i8 as i16,
@@ -96,7 +96,7 @@ impl Value128 {
}
#[doc(alias = "v128.load8x8_u")]
- pub const fn v128_load8x8_u(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load8x8_u(src: [u8; 8]) -> Self {
Self::from_u16x8([
src[0] as u16,
src[1] as u16,
@@ -110,7 +110,7 @@ impl Value128 {
}
#[doc(alias = "v128.load16x4_s")]
- pub const fn v128_load16x4_s(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load16x4_s(src: [u8; 8]) -> Self {
Self::from_i32x4([
i16::from_le_bytes([src[0], src[1]]) as i32,
i16::from_le_bytes([src[2], src[3]]) as i32,
@@ -120,7 +120,7 @@ impl Value128 {
}
#[doc(alias = "v128.load16x4_u")]
- pub const fn v128_load16x4_u(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load16x4_u(src: [u8; 8]) -> Self {
Self::from_u32x4([
u16::from_le_bytes([src[0], src[1]]) as u32,
u16::from_le_bytes([src[2], src[3]]) as u32,
@@ -130,7 +130,7 @@ impl Value128 {
}
#[doc(alias = "v128.load32x2_s")]
- pub const fn v128_load32x2_s(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load32x2_s(src: [u8; 8]) -> Self {
Self::from_i64x2([
i32::from_le_bytes([src[0], src[1], src[2], src[3]]) as i64,
i32::from_le_bytes([src[4], src[5], src[6], src[7]]) as i64,
@@ -138,7 +138,7 @@ impl Value128 {
}
#[doc(alias = "v128.load32x2_u")]
- pub const fn v128_load32x2_u(src: [u8; 8]) -> Self {
+ pub(crate) const fn v128_load32x2_u(src: [u8; 8]) -> Self {
Self::from_u64x2([
u32::from_le_bytes([src[0], src[1], src[2], src[3]]) as u64,
u32::from_le_bytes([src[4], src[5], src[6], src[7]]) as u64,
@@ -146,7 +146,7 @@ impl Value128 {
}
#[doc(alias = "i8x16.swizzle")]
- pub fn i8x16_swizzle(self, s: Self) -> Self {
+ pub(crate) fn i8x16_swizzle(self, s: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::i8x16_swizzle(self.to_wasm_v128(), s.to_wasm_v128())) }
x86 => {
@@ -182,7 +182,7 @@ impl Value128 {
}
#[doc(alias = "i8x16.relaxed_swizzle")]
- pub fn i8x16_relaxed_swizzle(self, s: Self) -> Self {
+ pub(crate) fn i8x16_relaxed_swizzle(self, s: Self) -> Self {
simd_impl! {
wasm => { Self::from_wasm_v128(wasm::i8x16_relaxed_swizzle(self.to_wasm_v128(), s.to_wasm_v128())) }
generic => { self.i8x16_swizzle(s) }
@@ -190,7 +190,7 @@ impl Value128 {
}
#[doc(alias = "i8x16.shuffle")]
- pub fn i8x16_shuffle(a: Self, b: Self, idx: Self) -> Self {
+ pub(crate) fn i8x16_shuffle(a: Self, b: Self, idx: Self) -> Self {
simd_impl! {
x86 => {
let idx = idx.0;
@@ -235,62 +235,62 @@ impl Value128 {
}
#[doc(alias = "i8x16.splat")]
- pub fn splat_i8(src: i8) -> Self {
+ pub(crate) fn splat_i8(src: i8) -> Self {
Self([src as u8; 16])
}
#[doc(alias = "i8x16.replace_lane")]
- pub fn i8x16_replace_lane(self, lane: u8, value: i8) -> Self {
+ pub(crate) fn i8x16_replace_lane(self, lane: u8, value: i8) -> Self {
self.replace_lane_bytes::<1, 16>(lane, [value as u8])
}
#[doc(alias = "i16x8.replace_lane")]
- pub fn i16x8_replace_lane(self, lane: u8, value: i16) -> Self {
+ pub(crate) fn i16x8_replace_lane(self, lane: u8, value: i16) -> Self {
self.replace_lane_bytes::<2, 8>(lane, value.to_le_bytes())
}
#[doc(alias = "i32x4.replace_lane")]
- pub fn i32x4_replace_lane(self, lane: u8, value: i32) -> Self {
+ pub(crate) fn i32x4_replace_lane(self, lane: u8, value: i32) -> Self {
self.replace_lane_bytes::<4, 4>(lane, value.to_le_bytes())
}
#[doc(alias = "i64x2.replace_lane")]
- pub fn i64x2_replace_lane(self, lane: u8, value: i64) -> Self {
+ pub(crate) fn i64x2_replace_lane(self, lane: u8, value: i64) -> Self {
self.replace_lane_bytes::<8, 2>(lane, value.to_le_bytes())
}
#[doc(alias = "f32x4.replace_lane")]
- pub fn f32x4_replace_lane(self, lane: u8, value: f32) -> Self {
+ pub(crate) fn f32x4_replace_lane(self, lane: u8, value: f32) -> Self {
self.replace_lane_bytes::<4, 4>(lane, value.to_bits().to_le_bytes())
}
#[doc(alias = "f64x2.replace_lane")]
- pub fn f64x2_replace_lane(self, lane: u8, value: f64) -> Self {
+ pub(crate) fn f64x2_replace_lane(self, lane: u8, value: f64) -> Self {
self.replace_lane_bytes::<8, 2>(lane, value.to_bits().to_le_bytes())
}
#[doc(alias = "i8x16.all_true")]
- pub fn i8x16_all_true(self) -> bool {
+ pub(crate) fn i8x16_all_true(self) -> bool {
self.0.iter().all(|&b| b != 0)
}
#[doc(alias = "i16x8.all_true")]
- pub fn i16x8_all_true(self) -> bool {
+ pub(crate) fn i16x8_all_true(self) -> bool {
self.as_i16x8().iter().all(|&x| x != 0)
}
#[doc(alias = "i32x4.all_true")]
- pub fn i32x4_all_true(self) -> bool {
+ pub(crate) fn i32x4_all_true(self) -> bool {
self.as_i32x4().iter().all(|&x| x != 0)
}
#[doc(alias = "i64x2.all_true")]
- pub fn i64x2_all_true(self) -> bool {
+ pub(crate) fn i64x2_all_true(self) -> bool {
self.as_i64x2().iter().all(|&x| x != 0)
}
#[doc(alias = "i8x16.bitmask")]
- pub fn i8x16_bitmask(self) -> u32 {
+ pub(crate) fn i8x16_bitmask(self) -> u32 {
let bytes = self.0;
let mut mask = 0u32;
for (i, byte) in bytes.into_iter().enumerate() {
@@ -302,7 +302,7 @@ impl Value128 {
}
#[doc(alias = "i16x8.bitmask")]
- pub fn i16x8_bitmask(self) -> u32 {
+ pub(crate) fn i16x8_bitmask(self) -> u32 {
let bytes = self.0;
let mut mask = 0u32;
for (i, lane) in bytes.as_chunks::<2>().0.iter().enumerate() {
@@ -314,7 +314,7 @@ impl Value128 {
}
#[doc(alias = "i32x4.bitmask")]
- pub fn i32x4_bitmask(self) -> u32 {
+ pub(crate) fn i32x4_bitmask(self) -> u32 {
let bytes = self.0;
let mut mask = 0u32;
for (i, lane) in bytes.as_chunks::<4>().0.iter().enumerate() {
@@ -326,13 +326,13 @@ impl Value128 {
}
#[doc(alias = "i64x2.bitmask")]
- pub fn i64x2_bitmask(self) -> u32 {
+ pub(crate) fn i64x2_bitmask(self) -> u32 {
let x = u128::from_le_bytes(self.0);
(((x >> 63) & 1) as u32) | ((((x >> 127) & 1) as u32) << 1)
}
#[doc(alias = "i8x16.popcnt")]
- pub fn i8x16_popcnt(self) -> Self {
+ pub(crate) fn i8x16_popcnt(self) -> Self {
Self(self.0.map(|lane| lane.count_ones() as u8))
}
@@ -374,17 +374,17 @@ impl Value128 {
}
#[doc(alias = "i8x16.avgr_u")]
- pub fn i8x16_avgr_u(self, rhs: Self) -> Self {
+ pub(crate) fn i8x16_avgr_u(self, rhs: Self) -> Self {
simd_avgr_u!(self, rhs, u8x16_avgr, u8, u16, as_u8x16, from_u8x16)
}
#[doc(alias = "i16x8.avgr_u")]
- pub fn i16x8_avgr_u(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_avgr_u(self, rhs: Self) -> Self {
simd_avgr_u!(self, rhs, u16x8_avgr, u16, u32, as_u16x8, from_u16x8)
}
#[doc(alias = "i8x16.narrow_i16x8_s")]
- pub fn i8x16_narrow_i16x8_s(a: Self, b: Self) -> Self {
+ pub(crate) fn i8x16_narrow_i16x8_s(a: Self, b: Self) -> Self {
let av = a.as_i16x8();
let bv = b.as_i16x8();
let mut out = [0i8; 16];
@@ -397,7 +397,7 @@ impl Value128 {
}
#[doc(alias = "i8x16.narrow_i16x8_u")]
- pub fn i8x16_narrow_i16x8_u(a: Self, b: Self) -> Self {
+ pub(crate) fn i8x16_narrow_i16x8_u(a: Self, b: Self) -> Self {
let av = a.as_i16x8();
let bv = b.as_i16x8();
let mut out = [0u8; 16];
@@ -410,7 +410,7 @@ impl Value128 {
}
#[doc(alias = "i16x8.narrow_i32x4_s")]
- pub fn i16x8_narrow_i32x4_s(a: Self, b: Self) -> Self {
+ pub(crate) fn i16x8_narrow_i32x4_s(a: Self, b: Self) -> Self {
let av = a.as_i32x4();
let bv = b.as_i32x4();
let mut out = [0i16; 8];
@@ -423,7 +423,7 @@ impl Value128 {
}
#[doc(alias = "i16x8.narrow_i32x4_u")]
- pub fn i16x8_narrow_i32x4_u(a: Self, b: Self) -> Self {
+ pub(crate) fn i16x8_narrow_i32x4_u(a: Self, b: Self) -> Self {
let av = a.as_i32x4();
let bv = b.as_i32x4();
let mut out = [0u16; 8];
@@ -436,25 +436,25 @@ impl Value128 {
}
#[doc(alias = "i16x8.extadd_pairwise_i8x16_s")]
- pub fn i16x8_extadd_pairwise_i8x16_s(self) -> Self {
+ pub(crate) fn i16x8_extadd_pairwise_i8x16_s(self) -> Self {
let lanes = self.as_i8x16();
Self::from_i16x8(array::from_fn(|i| lanes[i * 2] as i16 + lanes[i * 2 + 1] as i16))
}
#[doc(alias = "i16x8.extadd_pairwise_i8x16_u")]
- pub fn i16x8_extadd_pairwise_i8x16_u(self) -> Self {
+ pub(crate) fn i16x8_extadd_pairwise_i8x16_u(self) -> Self {
let lanes = self.as_u8x16();
Self::from_u16x8(array::from_fn(|i| lanes[i * 2] as u16 + lanes[i * 2 + 1] as u16))
}
#[doc(alias = "i32x4.extadd_pairwise_i16x8_s")]
- pub fn i32x4_extadd_pairwise_i16x8_s(self) -> Self {
+ pub(crate) fn i32x4_extadd_pairwise_i16x8_s(self) -> Self {
let lanes = self.as_i16x8();
Self::from_i32x4(array::from_fn(|i| lanes[i * 2] as i32 + lanes[i * 2 + 1] as i32))
}
#[doc(alias = "i32x4.extadd_pairwise_i16x8_u")]
- pub fn i32x4_extadd_pairwise_i16x8_u(self) -> Self {
+ pub(crate) fn i32x4_extadd_pairwise_i16x8_u(self) -> Self {
let lanes = self.as_u16x8();
Self::from_u32x4(array::from_fn(|i| lanes[i * 2] as u32 + lanes[i * 2 + 1] as u32))
}
@@ -490,7 +490,7 @@ impl Value128 {
}
#[doc(alias = "i16x8.q15mulr_sat_s")]
- pub fn i16x8_q15mulr_sat_s(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_q15mulr_sat_s(self, rhs: Self) -> Self {
let a = self.as_i16x8();
let b = rhs.as_i16x8();
let mut out = [0i16; 8];
@@ -502,7 +502,7 @@ impl Value128 {
}
#[doc(alias = "i32x4.dot_i16x8_s")]
- pub fn i32x4_dot_i16x8_s(self, rhs: Self) -> Self {
+ pub(crate) fn i32x4_dot_i16x8_s(self, rhs: Self) -> Self {
let a = self.as_i16x8();
let b = rhs.as_i16x8();
Self::from_i32x4(array::from_fn(|i| {
@@ -521,12 +521,12 @@ impl Value128 {
}
#[doc(alias = "i16x8.relaxed_q15mulr_s")]
- pub fn i16x8_relaxed_q15mulr_s(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_relaxed_q15mulr_s(self, rhs: Self) -> Self {
self.i16x8_q15mulr_sat_s(rhs)
}
#[doc(alias = "i16x8.relaxed_dot_i8x16_i7x16_s")]
- pub fn i16x8_relaxed_dot_i8x16_i7x16_s(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_relaxed_dot_i8x16_i7x16_s(self, rhs: Self) -> Self {
let a = self.as_i8x16();
let b = rhs.as_i8x16();
Self::from_i16x8(array::from_fn(|i| {
@@ -538,7 +538,7 @@ impl Value128 {
}
#[doc(alias = "i32x4.relaxed_dot_i8x16_i7x16_add_s")]
- pub fn i32x4_relaxed_dot_i8x16_i7x16_add_s(self, rhs: Self, acc: Self) -> Self {
+ pub(crate) fn i32x4_relaxed_dot_i8x16_i7x16_add_s(self, rhs: Self, acc: Self) -> Self {
let a = self.as_i8x16();
let b = rhs.as_i8x16();
let c = acc.as_i32x4();
@@ -595,499 +595,499 @@ impl Value128 {
}
#[doc(alias = "i8x16.abs")]
- pub fn i8x16_abs(self) -> Self {
+ pub(crate) fn i8x16_abs(self) -> Self {
simd_abs_const!(self, as_i8x16, from_i8x16)
}
#[doc(alias = "i16x8.abs")]
- pub fn i16x8_abs(self) -> Self {
+ pub(crate) fn i16x8_abs(self) -> Self {
simd_abs_const!(self, as_i16x8, from_i16x8)
}
#[doc(alias = "i32x4.abs")]
- pub fn i32x4_abs(self) -> Self {
+ pub(crate) fn i32x4_abs(self) -> Self {
simd_abs_const!(self, as_i32x4, from_i32x4)
}
#[doc(alias = "i64x2.abs")]
- pub fn i64x2_abs(self) -> Self {
+ pub(crate) fn i64x2_abs(self) -> Self {
simd_abs_const!(self, as_i64x2, from_i64x2)
}
#[doc(alias = "i8x16.neg")]
- pub fn i8x16_neg(self) -> Self {
+ pub(crate) fn i8x16_neg(self) -> Self {
simd_neg!(self, i8x16_neg, as_i8x16, from_i8x16)
}
#[doc(alias = "i16x8.neg")]
- pub fn i16x8_neg(self) -> Self {
+ pub(crate) fn i16x8_neg(self) -> Self {
simd_neg!(self, i16x8_neg, as_i16x8, from_i16x8)
}
#[doc(alias = "i32x4.neg")]
- pub fn i32x4_neg(self) -> Self {
+ pub(crate) fn i32x4_neg(self) -> Self {
simd_neg!(self, i32x4_neg, as_i32x4, from_i32x4)
}
#[doc(alias = "i64x2.neg")]
- pub fn i64x2_neg(self) -> Self {
+ pub(crate) fn i64x2_neg(self) -> Self {
simd_neg!(self, i64x2_neg, as_i64x2, from_i64x2)
}
#[doc(alias = "i8x16.min_s")]
- pub fn i8x16_min_s(self, rhs: Self) -> Self {
+ pub(crate) fn i8x16_min_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i8x16_min, as_i8x16, from_i8x16, <)
}
#[doc(alias = "i16x8.min_s")]
- pub fn i16x8_min_s(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_min_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i16x8_min, as_i16x8, from_i16x8, <)
}
#[doc(alias = "i32x4.min_s")]
- pub fn i32x4_min_s(self, rhs: Self) -> Self {
+ pub(crate) fn i32x4_min_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i32x4_min, as_i32x4, from_i32x4, <)
}
#[doc(alias = "i8x16.min_u")]
- pub fn i8x16_min_u(self, rhs: Self) -> Self {
+ pub(crate) fn i8x16_min_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u8x16_min, as_u8x16, from_u8x16, <)
}
#[doc(alias = "i16x8.min_u")]
- pub fn i16x8_min_u(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_min_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u16x8_min, as_u16x8, from_u16x8, <)
}
#[doc(alias = "i32x4.min_u")]
- pub fn i32x4_min_u(self, rhs: Self) -> Self {
+ pub(crate) fn i32x4_min_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u32x4_min, as_u32x4, from_u32x4, <)
}
#[doc(alias = "i8x16.max_s")]
- pub fn i8x16_max_s(self, rhs: Self) -> Self {
+ pub(crate) fn i8x16_max_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i8x16_max, as_i8x16, from_i8x16, >)
}
#[doc(alias = "i16x8.max_s")]
- pub fn i16x8_max_s(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_max_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i16x8_max, as_i16x8, from_i16x8, >)
}
#[doc(alias = "i32x4.max_s")]
- pub fn i32x4_max_s(self, rhs: Self) -> Self {
+ pub(crate) fn i32x4_max_s(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, i32x4_max, as_i32x4, from_i32x4, >)
}
#[doc(alias = "i8x16.max_u")]
- pub fn i8x16_max_u(self, rhs: Self) -> Self {
+ pub(crate) fn i8x16_max_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u8x16_max, as_u8x16, from_u8x16, >)
}
#[doc(alias = "i16x8.max_u")]
- pub fn i16x8_max_u(self, rhs: Self) -> Self {
+ pub(crate) fn i16x8_max_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u16x8_max, as_u16x8, from_u16x8, >)
}
#[doc(alias = "i32x4.max_u")]
- pub fn i32x4_max_u(self, rhs: Self) -> Self {
+ pub(crate) fn i32x4_max_u(self, rhs: Self) -> Self {
simd_minmax!(self, rhs, u32x4_max, as_u32x4, from_u32x4, >)
}
#[doc(alias = "f32x4.eq")]
- pub fn f32x4_eq(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_eq(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, ==)
}
#[doc(alias = "f64x2.eq")]
- pub fn f64x2_eq(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_eq(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, ==)
}
#[doc(alias = "f32x4.ne")]
- pub fn f32x4_ne(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_ne(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, !=)
}
#[doc(alias = "f64x2.ne")]
- pub fn f64x2_ne(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_ne(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, !=)
}
#[doc(alias = "f32x4.lt")]
- pub fn f32x4_lt(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_lt(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, <)
}
#[doc(alias = "f64x2.lt")]
- pub fn f64x2_lt(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_lt(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, <)
}
#[doc(alias = "f32x4.gt")]
- pub fn f32x4_gt(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_gt(self, rhs: Self) -> Self {
rhs.f32x4_lt(self)
}
#[doc(alias = "f64x2.gt")]
- pub fn f64x2_gt(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_gt(self, rhs: Self) -> Self {
rhs.f64x2_lt(self)
}
#[doc(alias = "f32x4.le")]
- pub fn f32x4_le(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_le(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, <=)
}
#[doc(alias = "f64x2.le")]
- pub fn f64x2_le(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_le(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, <=)
}
#[doc(alias = "f32x4.ge")]
- pub fn f32x4_ge(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_ge(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f32x4, from_i32x4, >=)
}
#[doc(alias = "f64x2.ge")]
- pub fn f64x2_ge(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_ge(self, rhs: Self) -> Self {
simd_cmp_mask!(generic self, rhs, as_f64x2, from_i64x2, >=)
}
#[doc(alias = "f32x4.ceil")]
- pub fn f32x4_ceil(self) -> Self {
+ pub(crate) fn f32x4_ceil(self) -> Self {
self.map_f32x4(|x| canonicalize_simd_f32_nan(x.ceil()))
}
#[doc(alias = "f64x2.ceil")]
- pub fn f64x2_ceil(self) -> Self {
+ pub(crate) fn f64x2_ceil(self) -> Self {
self.map_f64x2(|x| canonicalize_simd_f64_nan(x.ceil()))
}
#[doc(alias = "f32x4.floor")]
- pub fn f32x4_floor(self) -> Self {
+ pub(crate) fn f32x4_floor(self) -> Self {
self.map_f32x4(|x| canonicalize_simd_f32_nan(x.floor()))
}
#[doc(alias = "f64x2.floor")]
- pub fn f64x2_floor(self) -> Self {
+ pub(crate) fn f64x2_floor(self) -> Self {
self.map_f64x2(|x| canonicalize_simd_f64_nan(x.floor()))
}
#[doc(alias = "f32x4.trunc")]
- pub fn f32x4_trunc(self) -> Self {
+ pub(crate) fn f32x4_trunc(self) -> Self {
self.map_f32x4(|x| canonicalize_simd_f32_nan(x.trunc()))
}
#[doc(alias = "f64x2.trunc")]
- pub fn f64x2_trunc(self) -> Self {
+ pub(crate) fn f64x2_trunc(self) -> Self {
self.map_f64x2(|x| canonicalize_simd_f64_nan(x.trunc()))
}
#[doc(alias = "f32x4.nearest")]
- pub fn f32x4_nearest(self) -> Self {
+ pub(crate) fn f32x4_nearest(self) -> Self {
self.map_f32x4(|x| canonicalize_simd_f32_nan(TinywasmFloatExt::tw_nearest(x)))
}
#[doc(alias = "f64x2.nearest")]
- pub fn f64x2_nearest(self) -> Self {
+ pub(crate) fn f64x2_nearest(self) -> Self {
self.map_f64x2(|x| canonicalize_simd_f64_nan(TinywasmFloatExt::tw_nearest(x)))
}
#[doc(alias = "f32x4.abs")]
- pub fn f32x4_abs(self) -> Self {
+ pub(crate) fn f32x4_abs(self) -> Self {
self.map_f32x4(f32::abs)
}
#[doc(alias = "f64x2.abs")]
- pub fn f64x2_abs(self) -> Self {
+ pub(crate) fn f64x2_abs(self) -> Self {
self.map_f64x2(f64::abs)
}
#[doc(alias = "f32x4.neg")]
- pub fn f32x4_neg(self) -> Self {
+ pub(crate) fn f32x4_neg(self) -> Self {
self.map_f32x4(|x| -x)
}
#[doc(alias = "f64x2.neg")]
- pub fn f64x2_neg(self) -> Self {
+ pub(crate) fn f64x2_neg(self) -> Self {
self.map_f64x2(|x| -x)
}
#[doc(alias = "f32x4.sqrt")]
- pub fn f32x4_sqrt(self) -> Self {
+ pub(crate) fn f32x4_sqrt(self) -> Self {
self.map_f32x4(|x| canonicalize_simd_f32_nan(x.sqrt()))
}
#[doc(alias = "f64x2.sqrt")]
- pub fn f64x2_sqrt(self) -> Self {
+ pub(crate) fn f64x2_sqrt(self) -> Self {
self.map_f64x2(|x| canonicalize_simd_f64_nan(x.sqrt()))
}
#[doc(alias = "f32x4.add")]
- pub fn f32x4_add(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_add(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a + b))
}
#[doc(alias = "f64x2.add")]
- pub fn f64x2_add(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_add(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a + b))
}
#[doc(alias = "f32x4.sub")]
- pub fn f32x4_sub(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_sub(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a - b))
}
#[doc(alias = "f64x2.sub")]
- pub fn f64x2_sub(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_sub(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a - b))
}
#[doc(alias = "f32x4.mul")]
- pub fn f32x4_mul(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_mul(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a * b))
}
#[doc(alias = "f64x2.mul")]
- pub fn f64x2_mul(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_mul(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a * b))
}
#[doc(alias = "f32x4.div")]
- pub fn f32x4_div(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_div(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| canonicalize_simd_f32_nan(a / b))
}
#[doc(alias = "f64x2.div")]
- pub fn f64x2_div(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_div(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| canonicalize_simd_f64_nan(a / b))
}
#[doc(alias = "f32x4.min")]
- pub fn f32x4_min(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_min(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, TinywasmFloatExt::tw_minimum)
}
#[doc(alias = "f64x2.min")]
- pub fn f64x2_min(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_min(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, TinywasmFloatExt::tw_minimum)
}
#[doc(alias = "f32x4.max")]
- pub fn f32x4_max(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_max(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, TinywasmFloatExt::tw_maximum)
}
#[doc(alias = "f64x2.max")]
- pub fn f64x2_max(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_max(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, TinywasmFloatExt::tw_maximum)
}
#[doc(alias = "f32x4.pmin")]
- pub fn f32x4_pmin(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_pmin(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| if b < a { b } else { a })
}
#[doc(alias = "f64x2.pmin")]
- pub fn f64x2_pmin(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_pmin(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| if b < a { b } else { a })
}
#[doc(alias = "f32x4.pmax")]
- pub fn f32x4_pmax(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_pmax(self, rhs: Self) -> Self {
self.zip_f32x4(rhs, |a, b| if b > a { b } else { a })
}
#[doc(alias = "f64x2.pmax")]
- pub fn f64x2_pmax(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_pmax(self, rhs: Self) -> Self {
self.zip_f64x2(rhs, |a, b| if b > a { b } else { a })
}
#[doc(alias = "f32x4.relaxed_madd")]
- pub fn f32x4_relaxed_madd(self, b: Self, c: Self) -> Self {
+ pub(crate) fn f32x4_relaxed_madd(self, b: Self, c: Self) -> Self {
self.zip_f32x4(b, |x, y| canonicalize_simd_f32_nan(x * y))
.zip_f32x4(c, |xy, z| canonicalize_simd_f32_nan(xy + z))
}
#[doc(alias = "f32x4.relaxed_nmadd")]
- pub fn f32x4_relaxed_nmadd(self, b: Self, c: Self) -> Self {
+ pub(crate) fn f32x4_relaxed_nmadd(self, b: Self, c: Self) -> Self {
self.zip_f32x4(b, |x, y| canonicalize_simd_f32_nan(-(x * y)))
.zip_f32x4(c, |neg_xy, z| canonicalize_simd_f32_nan(neg_xy + z))
}
#[doc(alias = "f64x2.relaxed_madd")]
- pub fn f64x2_relaxed_madd(self, b: Self, c: Self) -> Self {
+ pub(crate) fn f64x2_relaxed_madd(self, b: Self, c: Self) -> Self {
self.zip_f64x2(b, |x, y| canonicalize_simd_f64_nan(x * y))
.zip_f64x2(c, |xy, z| canonicalize_simd_f64_nan(xy + z))
}
#[doc(alias = "f64x2.relaxed_nmadd")]
- pub fn f64x2_relaxed_nmadd(self, b: Self, c: Self) -> Self {
+ pub(crate) fn f64x2_relaxed_nmadd(self, b: Self, c: Self) -> Self {
self.zip_f64x2(b, |x, y| canonicalize_simd_f64_nan(-(x * y)))
.zip_f64x2(c, |neg_xy, z| canonicalize_simd_f64_nan(neg_xy + z))
}
#[doc(alias = "f32x4.relaxed_min")]
- pub fn f32x4_relaxed_min(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_relaxed_min(self, rhs: Self) -> Self {
self.f32x4_min(rhs)
}
#[doc(alias = "f64x2.relaxed_min")]
- pub fn f64x2_relaxed_min(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_relaxed_min(self, rhs: Self) -> Self {
self.f64x2_min(rhs)
}
#[doc(alias = "f32x4.relaxed_max")]
- pub fn f32x4_relaxed_max(self, rhs: Self) -> Self {
+ pub(crate) fn f32x4_relaxed_max(self, rhs: Self) -> Self {
self.f32x4_max(rhs)
}
#[doc(alias = "f64x2.relaxed_max")]
- pub fn f64x2_relaxed_max(self, rhs: Self) -> Self {
+ pub(crate) fn f64x2_relaxed_max(self, rhs: Self) -> Self {
self.f64x2_max(rhs)
}
#[doc(alias = "i32x4.relaxed_trunc_f32x4_s")]
- pub fn i32x4_relaxed_trunc_f32x4_s(self) -> Self {
+ pub(crate) fn i32x4_relaxed_trunc_f32x4_s(self) -> Self {
self.i32x4_trunc_sat_f32x4_s()
}
#[doc(alias = "i32x4.relaxed_trunc_f32x4_u")]
- pub fn i32x4_relaxed_trunc_f32x4_u(self) -> Self {
+ pub(crate) fn i32x4_relaxed_trunc_f32x4_u(self) -> Self {
self.i32x4_trunc_sat_f32x4_u()
}
#[doc(alias = "i32x4.relaxed_trunc_f64x2_s_zero")]
- pub fn i32x4_relaxed_trunc_f64x2_s_zero(self) -> Self {
+ pub(crate) fn i32x4_relaxed_trunc_f64x2_s_zero(self) -> Self {
self.i32x4_trunc_sat_f64x2_s_zero()
}
#[doc(alias = "i32x4.relaxed_trunc_f64x2_u_zero")]
- pub fn i32x4_relaxed_trunc_f64x2_u_zero(self) -> Self {
+ pub(crate) fn i32x4_relaxed_trunc_f64x2_u_zero(self) -> Self {
self.i32x4_trunc_sat_f64x2_u_zero()
}
#[doc(alias = "i32x4.trunc_sat_f32x4_s")]
- pub fn i32x4_trunc_sat_f32x4_s(self) -> Self {
+ pub(crate) fn i32x4_trunc_sat_f32x4_s(self) -> Self {
Self::from_i32x4(self.as_f32x4().map(trunc_sat_f32_to_i32))
}
#[doc(alias = "i32x4.trunc_sat_f32x4_u")]
- pub fn i32x4_trunc_sat_f32x4_u(self) -> Self {
+ pub(crate) fn i32x4_trunc_sat_f32x4_u(self) -> Self {
Self::from_u32x4(self.as_f32x4().map(trunc_sat_f32_to_u32))
}
#[doc(alias = "i32x4.trunc_sat_f64x2_s_zero")]
- pub fn i32x4_trunc_sat_f64x2_s_zero(self) -> Self {
+ pub(crate) fn i32x4_trunc_sat_f64x2_s_zero(self) -> Self {
let v = self.as_f64x2();
Self::from_i32x4([trunc_sat_f64_to_i32(v[0]), trunc_sat_f64_to_i32(v[1]), 0, 0])
}
#[doc(alias = "i32x4.trunc_sat_f64x2_u_zero")]
- pub fn i32x4_trunc_sat_f64x2_u_zero(self) -> Self {
+ pub(crate) fn i32x4_trunc_sat_f64x2_u_zero(self) -> Self {
let v = self.as_f64x2();
Self::from_u32x4([trunc_sat_f64_to_u32(v[0]), trunc_sat_f64_to_u32(v[1]), 0, 0])
}
#[doc(alias = "f32x4.convert_i32x4_s")]
- pub fn f32x4_convert_i32x4_s(self) -> Self {
+ pub(crate) fn f32x4_convert_i32x4_s(self) -> Self {
Self::from_f32x4(self.as_i32x4().map(|x| x as f32))
}
#[doc(alias = "f32x4.convert_i32x4_u")]
- pub fn f32x4_convert_i32x4_u(self) -> Self {
+ pub(crate) fn f32x4_convert_i32x4_u(self) -> Self {
Self::from_f32x4(self.as_u32x4().map(|x| x as f32))
}
#[doc(alias = "f64x2.convert_low_i32x4_s")]
- pub fn f64x2_convert_low_i32x4_s(self) -> Self {
+ pub(crate) fn f64x2_convert_low_i32x4_s(self) -> Self {
let [a, b, ..] = self.as_i32x4();
Self::from_f64x2([a as f64, b as f64])
}
#[doc(alias = "f64x2.convert_low_i32x4_u")]
- pub fn f64x2_convert_low_i32x4_u(self) -> Self {
+ pub(crate) fn f64x2_convert_low_i32x4_u(self) -> Self {
let [a, b, ..] = self.as_u32x4();
Self::from_f64x2([a as f64, b as f64])
}
#[doc(alias = "f32x4.demote_f64x2_zero")]
- pub fn f32x4_demote_f64x2_zero(self) -> Self {
+ pub(crate) fn f32x4_demote_f64x2_zero(self) -> Self {
let [a, b] = self.as_f64x2();
Self::from_f32x4([a as f32, b as f32, 0.0, 0.0])
}
#[doc(alias = "f64x2.promote_low_f32x4")]
- pub fn f64x2_promote_low_f32x4(self) -> Self {
+ pub(crate) fn f64x2_promote_low_f32x4(self) -> Self {
let [a, b, ..] = self.as_f32x4();
Self::from_f64x2([a as f64, b as f64])
}
#[doc(alias = "i16x8.splat")]
- pub fn splat_i16(src: i16) -> Self {
+ pub(crate) fn splat_i16(src: i16) -> Self {
Self::from_i16x8([src; 8])
}
#[doc(alias = "i32x4.splat")]
- pub fn splat_i32(src: i32) -> Self {
+ pub(crate) fn splat_i32(src: i32) -> Self {
Self::from_i32x4([src; 4])
}
#[doc(alias = "i64x2.splat")]
- pub fn splat_i64(src: i64) -> Self {
+ pub(crate) fn splat_i64(src: i64) -> Self {
Self::from_i64x2([src; 2])
}
#[doc(alias = "f32x4.splat")]
- pub fn splat_f32(src: f32) -> Self {
+ pub(crate) fn splat_f32(src: f32) -> Self {
Self::splat_i32(src.to_bits() as i32)
}
#[doc(alias = "f64x2.splat")]
- pub fn splat_f64(src: f64) -> Self {
+ pub(crate) fn splat_f64(src: f64) -> Self {
Self::splat_i64(src.to_bits() as i64)
}
#[doc(alias = "i8x16.extract_lane_s")]
- pub fn extract_lane_i8(self, lane: u8) -> i8 {
+ pub(crate) fn extract_lane_i8(self, lane: u8) -> i8 {
debug_assert!(lane < 16);
self.0[lane as usize] as i8
}
#[doc(alias = "i8x16.extract_lane_u")]
- pub fn extract_lane_u8(self, lane: u8) -> u8 {
+ pub(crate) fn extract_lane_u8(self, lane: u8) -> u8 {
debug_assert!(lane < 16);
self.0[lane as usize]
}
#[doc(alias = "i16x8.extract_lane_s")]
- pub fn extract_lane_i16(self, lane: u8) -> i16 {
+ pub(crate) fn extract_lane_i16(self, lane: u8) -> i16 {
i16::from_le_bytes(self.extract_lane_bytes::<2, 8>(lane))
}
#[doc(alias = "i16x8.extract_lane_u")]
- pub fn extract_lane_u16(self, lane: u8) -> u16 {
+ pub(crate) fn extract_lane_u16(self, lane: u8) -> u16 {
u16::from_le_bytes(self.extract_lane_bytes::<2, 8>(lane))
}
#[doc(alias = "i32x4.extract_lane")]
- pub fn extract_lane_i32(self, lane: u8) -> i32 {
+ pub(crate) fn extract_lane_i32(self, lane: u8) -> i32 {
i32::from_le_bytes(self.extract_lane_bytes::<4, 4>(lane))
}
#[doc(alias = "i64x2.extract_lane")]
- pub fn extract_lane_i64(self, lane: u8) -> i64 {
+ pub(crate) fn extract_lane_i64(self, lane: u8) -> i64 {
i64::from_le_bytes(self.extract_lane_bytes::<8, 2>(lane))
}
#[doc(alias = "f32x4.extract_lane")]
- pub fn extract_lane_f32(self, lane: u8) -> f32 {
+ pub(crate) fn extract_lane_f32(self, lane: u8) -> f32 {
f32::from_bits(self.extract_lane_i32(lane) as u32)
}
#[doc(alias = "f64x2.extract_lane")]
- pub fn extract_lane_f64(self, lane: u8) -> f64 {
+ pub(crate) fn extract_lane_f64(self, lane: u8) -> f64 {
f64::from_bits(self.extract_lane_i64(lane) as u64)
}
}
diff --git a/crates/tinywasm/src/interpreter/simd/macros.rs b/crates/tinywasm/src/interpreter/simd/macros.rs
index bc7b805..e79ed77 100644
--- a/crates/tinywasm/src/interpreter/simd/macros.rs
+++ b/crates/tinywasm/src/interpreter/simd/macros.rs
@@ -118,7 +118,7 @@ macro_rules! impl_simd_shifts {
($($alias:literal => $name:ident($as_lanes:ident, $from_lanes:ident, $mask:expr, $op:ident);)*) => {
$(
#[doc(alias = $alias)]
- pub fn $name(self, shift: u32) -> Self {
+ pub(crate) fn $name(self, shift: u32) -> Self {
simd_shift!(self, shift, $as_lanes, $from_lanes, $mask, $op)
}
)*
@@ -129,7 +129,7 @@ macro_rules! impl_simd_binary_methods {
($helper:ident; $($alias:literal => $name:ident($($args:tt)*);)*) => {
$(
#[doc(alias = $alias)]
- pub fn $name(self, rhs: Self) -> Self {
+ pub(crate) fn $name(self, rhs: Self) -> Self {
$helper!(self, rhs, $($args)*)
}
)*
@@ -140,7 +140,7 @@ macro_rules! impl_simd_extend {
($($alias:literal => $name:ident($src_as:ident, $dst_from:ident, $dst_ty:ty, $offset:expr);)*) => {
$(
#[doc(alias = $alias)]
- pub fn $name(self) -> Self {
+ pub(crate) fn $name(self) -> Self {
simd_extend_cast!(self, $src_as, $dst_from, $dst_ty, $offset)
}
)*
@@ -151,7 +151,7 @@ macro_rules! impl_simd_relaxed_laneselect {
($($alias:literal => $name:ident;)*) => {
$(
#[doc(alias = $alias)]
- pub fn $name(v1: Self, v2: Self, c: Self) -> Self {
+ pub(crate) fn $name(v1: Self, v2: Self, c: Self) -> Self {
Self::v128_bitselect(v1, v2, c)
}
)*
@@ -162,7 +162,7 @@ macro_rules! impl_simd_reverse_comparisons {
($($alias:literal => $name:ident($reverse:ident);)*) => {
$(
#[doc(alias = $alias)]
- pub fn $name(self, rhs: Self) -> Self {
+ pub(crate) fn $name(self, rhs: Self) -> Self {
rhs.$reverse(self)
}
)*
@@ -183,25 +183,24 @@ macro_rules! lane_read {
(f64, $bytes:expr, $offset:expr) => { f64::from_bits(u64::from_le_bytes([$bytes[$offset], $bytes[$offset + 1], $bytes[$offset + 2], $bytes[$offset + 3], $bytes[$offset + 4], $bytes[$offset + 5], $bytes[$offset + 6], $bytes[$offset + 7]])) };
}
-#[rustfmt::skip]
macro_rules! lane_write {
- (i8, $value:expr) => { [$value as u8] };
- (u8, $value:expr) => { [$value] };
- (i16, $value:expr) => { $value.to_le_bytes() };
- (u16, $value:expr) => { $value.to_le_bytes() };
- (i32, $value:expr) => { $value.to_le_bytes() };
- (u32, $value:expr) => { $value.to_le_bytes() };
- (i64, $value:expr) => { $value.to_le_bytes() };
- (u64, $value:expr) => { $value.to_le_bytes() };
- (f32, $value:expr) => { $value.to_bits().to_le_bytes() };
- (f64, $value:expr) => { $value.to_bits().to_le_bytes() };
+ (i8, $value:expr) => {{ [$value as u8] }};
+ (u8, $value:expr) => {{ [$value] }};
+ (i16, $value:expr) => {{ $value.to_le_bytes() }};
+ (u16, $value:expr) => {{ $value.to_le_bytes() }};
+ (i32, $value:expr) => {{ $value.to_le_bytes() }};
+ (u32, $value:expr) => {{ $value.to_le_bytes() }};
+ (i64, $value:expr) => {{ $value.to_le_bytes() }};
+ (u64, $value:expr) => {{ $value.to_le_bytes() }};
+ (f32, $value:expr) => {{ $value.to_bits().to_le_bytes() }};
+ (f64, $value:expr) => {{ $value.to_bits().to_le_bytes() }};
}
macro_rules! impl_lane_accessors {
- ($($as_vis:vis $as_name:ident => $from_vis:vis $from_name:ident: $lane_ty:tt, $lane_count:expr, $lane_bytes:expr;)*) => {
+ ($($as_name:ident => $from_name:ident: $lane_ty:tt, $lane_count:expr, $lane_bytes:expr;)*) => {
$(
#[inline]
- $as_vis const fn $as_name(self) -> [$lane_ty; $lane_count] {
+ pub(crate) const fn $as_name(self) -> [$lane_ty; $lane_count] {
const { assert!($lane_count * $lane_bytes == 16); };
let bytes = self.0;
let mut out = [0 as $lane_ty; $lane_count];
@@ -214,7 +213,7 @@ macro_rules! impl_lane_accessors {
}
#[inline]
- $from_vis const fn $from_name(lanes: [$lane_ty; $lane_count]) -> Self {
+ pub(crate) const fn $from_name(lanes: [$lane_ty; $lane_count]) -> Self {
const { assert!($lane_count * $lane_bytes == 16); };
let mut bytes = [0u8; 16];
diff --git a/crates/tinywasm/src/interpreter/simd/mod.rs b/crates/tinywasm/src/interpreter/simd/mod.rs
index b05769c..62ea4ab 100644
--- a/crates/tinywasm/src/interpreter/simd/mod.rs
+++ b/crates/tinywasm/src/interpreter/simd/mod.rs
@@ -3,8 +3,6 @@
#[macro_use]
mod macros;
mod instructions;
-#[cfg(test)]
-mod tests;
mod utils;
#[cfg(target_arch = "wasm32")]
@@ -13,26 +11,9 @@ use core::arch::wasm32 as wasm;
use core::arch::wasm64 as wasm;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
/// A 128-bit SIMD value
-pub struct Value128(pub(super) [u8; 16]);
-
-impl From<[u8; 16]> for Value128 {
- fn from(bytes: [u8; 16]) -> Self {
- Self(bytes)
- }
-}
-
-impl Value128 {
- #[inline(always)]
- pub fn from_le_bytes(bytes: [u8; 16]) -> Self {
- Self(bytes)
- }
-
- #[inline(always)]
- pub fn to_le_bytes(self) -> [u8; 16] {
- self.0
- }
-}
+pub struct Value128(pub(crate) [u8; 16]);
impl From<Value128> for i128 {
fn from(val: Value128) -> Self {
@@ -53,10 +34,10 @@ impl Value128 {
as_u8x16 => from_u8x16: u8, 16, 1;
as_i16x8 => from_i16x8: i16, 8, 2;
as_u16x8 => from_u16x8: u16, 8, 2;
- as_i32x4 => pub from_i32x4: i32, 4, 4;
+ as_i32x4 => from_i32x4: i32, 4, 4;
as_u32x4 => from_u32x4: u32, 4, 4;
as_f32x4 => from_f32x4: f32, 4, 4;
- as_i64x2 => pub from_i64x2: i64, 2, 8;
+ as_i64x2 => from_i64x2: i64, 2, 8;
as_u64x2 => from_u64x2: u64, 2, 8;
as_f64x2 => from_f64x2: f64, 2, 8;
}
diff --git a/crates/tinywasm/src/interpreter/simd/tests.rs b/crates/tinywasm/src/interpreter/simd/tests.rs
deleted file mode 100644
index 7400f6b..0000000
--- a/crates/tinywasm/src/interpreter/simd/tests.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use super::Value128;
-
-fn ref_swizzle(a: [u8; 16], idx: [u8; 16]) -> [u8; 16] {
- let mut out = [0u8; 16];
- for i in 0..16 {
- let j = idx[i];
- out[i] = if j < 16 { a[(j & 0x0f) as usize] } else { 0 };
- }
- out
-}
-
-fn ref_shuffle(a: [u8; 16], b: [u8; 16], idx: [u8; 16]) -> [u8; 16] {
- let mut out = [0u8; 16];
- for i in 0..16 {
- let j = idx[i] & 31;
- out[i] = if j < 16 { a[j as usize] } else { b[(j & 0x0f) as usize] };
- }
- out
-}
-
-#[test]
-fn swizzle_matches_reference() {
- let a = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff];
-
- for seed in 0u32..512 {
- let mut s = [0u8; 16];
- let mut x = seed.wrapping_mul(0x9e37_79b9).wrapping_add(0x7f4a_7c15);
- for byte in &mut s {
- x ^= x << 13;
- x ^= x >> 17;
- x ^= x << 5;
- *byte = (x & 0xff) as u8;
- }
-
- let got = Value128(a).i8x16_swizzle(Value128(s));
- let expected = ref_swizzle(a, s).into();
- assert_eq!(got, expected, "seed={seed}");
- }
-}
-
-#[test]
-fn shuffle_matches_reference() {
- let a = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f];
- let b = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf];
-
- for seed in 0u32..512 {
- let mut idx = [0u8; 16];
- let mut x = seed.wrapping_mul(0x85eb_ca6b).wrapping_add(0xc2b2_ae35);
- for byte in &mut idx {
- x ^= x << 13;
- x ^= x >> 17;
- x ^= x << 5;
- *byte = (x & 0xff) as u8;
- }
-
- let got = Value128::i8x16_shuffle(Value128(a), Value128(b), Value128(idx));
- let expected = ref_shuffle(a, b, idx).into();
- assert_eq!(got, expected, "seed={seed}");
- }
-}
diff --git a/crates/tinywasm/src/interpreter/simd/utils.rs b/crates/tinywasm/src/interpreter/simd/utils.rs
index ebba815..3d90744 100644
--- a/crates/tinywasm/src/interpreter/simd/utils.rs
+++ b/crates/tinywasm/src/interpreter/simd/utils.rs
@@ -9,7 +9,6 @@ impl Value128 {
lane: u8,
) -> [u8; LANE_BYTES] {
const { assert!(LANE_BYTES * LANE_COUNT == 16) };
- assert!((lane as usize) < LANE_COUNT);
let start = lane as usize * LANE_BYTES;
core::array::from_fn(|i| self.0[start + i])
}
@@ -20,7 +19,6 @@ impl Value128 {
value: [u8; LANE_BYTES],
) -> Self {
const { assert!(LANE_BYTES * LANE_COUNT == 16) };
- assert!((lane as usize) < LANE_COUNT);
let mut bytes = self.0;
let start = lane as usize * LANE_BYTES;
bytes[start..start + LANE_BYTES].copy_from_slice(&value);
diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs
index 62f1f8e..411f327 100644
--- a/crates/tinywasm/src/interpreter/stack/call_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/call_stack.rs
@@ -1,5 +1,4 @@
use crate::{Result, Trap};
-use core::hint::cold_path;
use alloc::vec::Vec;
use tinywasm_types::{FuncAddr, ValueCounts};
@@ -37,29 +36,15 @@ impl CallStack {
}
#[inline(always)]
- pub(crate) fn push(&mut self, mut call_frame: CallFrame) -> Result<(), Trap> {
- self.ensure_capacity_for(self.stack.len() + 1)?;
- call_frame.incr_instr_ptr();
- self.stack.push(call_frame);
- Ok(())
- }
-
- #[inline(always)]
- fn ensure_capacity_for(&mut self, required_len: usize) -> Result<(), Trap> {
- if required_len <= self.stack.capacity() {
- return Ok(());
+ pub(crate) fn push(&mut self, mut call_frame: CallFrame, instr_ptr: usize) -> Result<(), Trap> {
+ // Check the limit only at capacity to avoid an extra hot-path check. Vec growth may
+ // intentionally overshoot max_size. Revisit when Vec::push_within_capacity is stable.
+ if self.stack.len() == self.stack.capacity() && (!self.dynamic || self.stack.len() >= self.max_size) {
+ return cold!(Err(Trap::CallStackOverflow));
}
- if required_len > self.max_size || !self.dynamic {
- cold_path();
- return Err(Trap::CallStackOverflow);
- }
-
- let target_capacity = required_len.max(self.stack.capacity().max(1).saturating_mul(2)).min(self.max_size);
- let Ok(()) = self.stack.try_reserve(target_capacity.saturating_sub(self.stack.len())) else {
- cold_path();
- return Err(Trap::CallStackOverflow);
- };
+ call_frame.instr_ptr = instr_ptr;
+ self.stack.push(call_frame);
Ok(())
}
}
@@ -94,9 +79,4 @@ impl CallFrame {
s128: self.locals_base.s128 + self.stack_offset.c128 as u32,
}
}
-
- #[inline(always)]
- pub(crate) fn incr_instr_ptr(&mut self) {
- self.instr_ptr += 1;
- }
}
diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs
index 853c5e4..814195a 100644
--- a/crates/tinywasm/src/interpreter/stack/value_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs
@@ -1,6 +1,5 @@
use alloc::vec::Vec;
-use core::hint::cold_path;
-use tinywasm_types::{ValueCounts, WasmType, WasmValue};
+use tinywasm_types::{MemoryArch, ValueCounts};
use super::StackBase;
use crate::engine::{Config, StackConfig};
@@ -8,6 +7,10 @@ use crate::interpreter::*;
use crate::{Result, Trap};
#[cfg_attr(feature = "debug", derive(Debug))]
+/// Physical value lanes used by the interpreter.
+///
+/// Guest values should normally be accessed through
+/// [`InternalValue`] so their stack and global representation stays consistent.
pub(crate) struct ValueStack {
pub(crate) stack_32: Stack<Value32>,
pub(crate) stack_64: Stack<Value64>,
@@ -21,6 +24,12 @@ pub(crate) struct Stack<T: Copy + Default> {
dynamic: bool,
}
+#[cold]
+#[inline(never)]
+fn stack_underflow() -> ! {
+ unreachable!("ValueStack underflow, this is a bug")
+}
+
impl<T: Copy + Default> Stack<T> {
pub(crate) fn new(config: StackConfig) -> Self {
Self { data: Vec::with_capacity(config.initial_size), max_size: config.max_size, dynamic: config.dynamic }
@@ -37,23 +46,40 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> {
- if !self.ensure_capacity_for(self.data.len() + 1) {
- cold_path();
- return Err(Trap::ValueStackOverflow);
+ // Check the limit only at capacity to avoid an extra hot-path check. Vec growth may
+ // intentionally overshoot max_size. Revisit when Vec::push_within_capacity is stable.
+ if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) {
+ return cold!(Err(Trap::ValueStackOverflow));
}
+ self.data.push(value);
+ Ok(())
+ }
+ #[inline(always)]
+ pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> {
+ // Keep the same capacity-based limit check as push, including intentional overshoot.
+ if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) {
+ return cold!(Err(Trap::ValueStackOverflow));
+ }
+ let value = self.data[index];
self.data.push(value);
Ok(())
}
#[inline(always)]
pub(crate) fn pop(&mut self) -> T {
- self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"))
+ match self.data.pop() {
+ Some(value) => value,
+ None => cold!(stack_underflow()),
+ }
}
#[inline(always)]
pub(crate) fn last(&self) -> &T {
- self.data.last().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"))
+ match self.data.last() {
+ Some(value) => value,
+ None => cold!(stack_underflow()),
+ }
}
#[inline(always)]
@@ -79,9 +105,9 @@ impl<T: Copy + Default> Stack<T> {
return;
}
- let keep = (len - n).min(end_keep);
- self.data.copy_within(len - keep..len, n);
- self.data.truncate(n + keep);
+ let keep = len.wrapping_sub(n).min(end_keep);
+ self.data.copy_within(len.wrapping_sub(keep)..len, n);
+ self.data.truncate(n.wrapping_add(keep));
}
#[inline(always)]
@@ -93,12 +119,12 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn truncate_to_one_tail(&mut self, n: usize) {
debug_assert!(n < self.data.len());
- let last = self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"));
+ let last = self.pop();
self.data.truncate(n);
self.data.push(last);
}
- #[inline(always)]
+ #[inline]
pub(crate) fn enter_locals(&mut self, param_count: usize, local_count: usize) -> Result<u32, Trap> {
debug_assert!(param_count <= local_count);
debug_assert!(param_count <= self.data.len());
@@ -108,13 +134,13 @@ impl<T: Copy + Default> Stack<T> {
let end = start + local_count;
if end > self.data.capacity() {
- cold_path();
+ core::hint::cold_path();
if end > self.max_size || !self.dynamic {
return Err(Trap::ValueStackOverflow);
}
let cap = self.data.capacity();
let target = end.max(cap.max(1).saturating_mul(2)).min(self.max_size);
- if self.data.try_reserve_exact(target - len).is_err() {
+ if self.data.try_reserve(target - len).is_err() {
return Err(Trap::ValueStackOverflow);
}
}
@@ -123,26 +149,6 @@ impl<T: Copy + Default> Stack<T> {
Ok(start as u32)
}
- fn ensure_capacity_for(&mut self, required_len: usize) -> bool {
- let cap = self.data.capacity();
-
- if required_len > cap {
- cold_path();
-
- if required_len > self.max_size || !self.dynamic {
- return false;
- }
- let doubled = cap.max(1).saturating_mul(2);
- let target = required_len.max(doubled).min(self.max_size);
- let additional = target - cap;
- if self.data.try_reserve_exact(additional).is_err() {
- return false;
- }
- }
-
- true
- }
-
#[inline(always)]
pub(crate) fn select_many(&mut self, count: usize, condition: bool) {
if count == 0 {
@@ -150,19 +156,28 @@ impl<T: Copy + Default> Stack<T> {
}
let len = self.data.len();
- let needed = count.checked_mul(2).unwrap_or_else(|| unreachable!("Stack underflow, this is a bug"));
+ let needed = count.wrapping_mul(2);
if len < needed {
- unreachable!("Stack underflow, this is a bug");
+ cold!(stack_underflow());
}
if !condition {
- let dst = len - needed;
- let src = len - count;
+ let dst = len.wrapping_sub(needed);
+ let src = len.wrapping_sub(count);
self.data.copy_within(src..len, dst);
}
- self.data.truncate(len - count);
+ self.data.truncate(len.wrapping_sub(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 {
@@ -189,14 +204,31 @@ impl ValueStack {
}
}
- #[inline(always)]
- pub(crate) fn len(&self) -> usize {
- self.stack_32.len() + self.stack_64.len() + self.stack_128.len()
+ pub(crate) fn base_before(&self, counts: ValueCounts) -> StackBase {
+ let base = self.base();
+ StackBase {
+ s32: base.s32 - counts.c32 as u32,
+ s64: base.s64 - counts.c64 as u32,
+ s128: base.s128 - counts.c128 as u32,
+ }
}
#[inline(always)]
- pub(crate) fn push<T: InternalValue>(&mut self, value: T) -> Result<(), Trap> {
- T::stack_push(self, value)
+ pub(crate) fn pop_memory_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> {
+ match arch {
+ MemoryArch::I32 => Ok(u32::stack_pop(self) as usize),
+ MemoryArch::I64 => {
+ let value = u64::stack_pop(self);
+ #[cfg(target_pointer_width = "64")]
+ return Ok(value as usize);
+ #[cfg(not(target_pointer_width = "64"))]
+ return cold_err!(usize::try_from(value).map_err(|_| Trap::MemoryOutOfBounds {
+ offset: usize::MAX,
+ len: 0,
+ max: usize::MAX,
+ }));
+ }
+ }
}
#[inline]
@@ -207,13 +239,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)?;
@@ -236,40 +261,12 @@ impl ValueStack {
self.stack_128.truncate_to(base.s128 as usize);
}
- pub(crate) fn push_dyn(&mut self, value: TinyWasmValue) -> Result<(), Trap> {
+ pub(crate) fn push_dyn(&mut self, value: RuntimeValue) -> Result<(), Trap> {
match value {
- TinyWasmValue::Value32(v) => self.stack_32.push(v)?,
- TinyWasmValue::Value64(v) => self.stack_64.push(v)?,
- TinyWasmValue::Value128(v) => self.stack_128.push(v)?,
- TinyWasmValue::ValueRef(v) => self.stack_32.push(v.raw())?,
- }
- Ok(())
- }
-
- pub(crate) fn pop_wasmvalue(&mut self, val_type: WasmType) -> WasmValue {
- 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),
+ RuntimeValue::Value32(value) => Value32::stack_push(self, value),
+ RuntimeValue::Value64(value) => Value64::stack_push(self, value),
+ RuntimeValue::Value128(value) => Value128::stack_push(self, value),
+ RuntimeValue::ValueRef(value) => ValueRef::stack_push(self, value),
}
}
-
- pub(crate) fn extend_from_wasmvalues(&mut self, values: &[WasmValue]) -> Result<(), Trap> {
- for value in values {
- match value {
- WasmValue::I32(v) => self.stack_32.push(*v as u32)?,
- WasmValue::I64(v) => self.stack_64.push(*v as u64)?,
- WasmValue::F32(v) => self.stack_32.push(v.to_bits())?,
- WasmValue::F64(v) => self.stack_64.push(v.to_bits())?,
- WasmValue::Ref(v) => {
- self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(*v)).as_ref().unwrap().raw())?
- }
- WasmValue::V128(v) => self.stack_128.push((*v).into())?,
- }
- }
- Ok(())
- }
}
diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs
index be2e0a1..b610fd8 100644
--- a/crates/tinywasm/src/interpreter/values.rs
+++ b/crates/tinywasm/src/interpreter/values.rs
@@ -1,23 +1,22 @@
+use super::num_helpers::TinywasmFloatExt;
use super::stack::{CallFrame, ValueStack};
-use crate::{Result, interpreter::simd::Value128};
-use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, LocalAddr, RefValue, WasmType, WasmValue};
+use crate::store::Globals;
+use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128};
+use tinywasm_types::{BinOp, BinOp128, CmpOp, GlobalAddr, LocalAddr, WasmType};
pub(crate) type Value32 = u32;
pub(crate) type Value64 = u64;
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+/// Packed internal representation of a WebAssembly reference.
+///
+/// Unlike the public [`RefValue`], this stores no explicit reference category.
+/// Converting it back therefore requires the value's canonical reference type.
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
- }
-}
-
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,180 +24,124 @@ 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 addr(self) -> Option<u32> {
- if self.is_null() { None } else { Some(self.0) }
+ pub(crate) const fn from_i31(value: i32) -> Self {
+ Self(((value as u32) << 1) | 1)
}
#[inline]
- pub(crate) const fn is_null(self) -> bool {
- self.0 == Self::NULL.0
+ pub(crate) const fn try_from_host_any(addr: u32) -> Option<Self> {
+ if addr >= Self::HOST_ANY_TAG - 1 {
+ return None;
+ }
+ Some(Self::from_category_addr(addr | Self::HOST_ANY_TAG))
}
- #[inline]
- pub(crate) const fn raw(self) -> u32 {
- self.0
+ pub(crate) const fn is_host_any(self) -> bool {
+ matches!(self.addr(), Some(addr) if addr & Self::HOST_ANY_TAG != 0)
}
-}
-
-#[allow(private_interfaces)]
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-/// A untyped WebAssembly value
-pub enum TinyWasmValue {
- /// A 32-bit value
- Value32(Value32),
- /// A 64-bit value
- Value64(Value64),
- /// A 128-bit value
- Value128(Value128),
- /// A reference value
- ValueRef(ValueRef),
-}
-impl TinyWasmValue {
- /// Converts the value to a 32-bit value (returns None if the value is not a 32-bit value)
- pub fn as_32(self) -> Option<Value32> {
- match self {
- Self::Value32(v) => Some(v),
- _ => None,
- }
+ #[inline]
+ pub(crate) const fn addr(self) -> Option<u32> {
+ if self.is_null() || self.is_i31() { None } else { Some(self.0 / 2 - 1) }
}
- /// Converts the value to a 64-bit value (returns None if the value is not a 64-bit value)
- pub fn as_64(self) -> Option<Value64> {
- match self {
- Self::Value64(v) => Some(v),
- _ => None,
- }
+ #[inline]
+ pub(crate) const fn is_null(self) -> bool {
+ self.0 == Self::NULL.0
}
- /// Converts the value to a 128-bit value (returns None if the value is not a 128-bit value)
- pub fn as_128(self) -> Option<Value128> {
- match self {
- Self::Value128(v) => Some(v),
- _ => None,
- }
+ #[inline]
+ pub(crate) const fn is_i31(self) -> bool {
+ self.0 & 1 != 0
}
- /// Converts the value to a reference value (returns None if the value is not a reference value)
- #[allow(private_interfaces, dead_code)]
- pub fn as_ref(self) -> Option<ValueRef> {
- match self {
- Self::ValueRef(v) => Some(v),
- _ => None,
- }
+ #[inline]
+ pub(crate) const fn i31_s(self) -> Option<i32> {
+ if self.is_i31() { Some((self.0 as i32) >> 1) } else { None }
}
- /// Attaches a type to the value (panics if the size of the value is not the same as the type)
- pub fn attach_type(self, ty: WasmType) -> Option<WasmValue> {
- match (self, ty) {
- (Self::Value32(v), WasmType::I32) => Some(WasmValue::I32(v as i32)),
- (Self::Value64(v), WasmType::I64) => Some(WasmValue::I64(v as i64)),
- (Self::Value32(v), WasmType::F32) => Some(WasmValue::F32(f32::from_bits(v))),
- (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()))))
- }
- (Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_extern() => {
- Some(WasmValue::Ref(RefValue::Extern(ExternRef::new(v.raw()))))
- }
- (Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_exn() => {
- Some(WasmValue::Ref(RefValue::Exn(ExnRef::new(v.raw()))))
- }
- (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)),
- (_, WasmType::I32 | WasmType::F32) => None,
- (_, WasmType::I64 | WasmType::F64) => None,
- (_, WasmType::Ref(_)) => None,
- (_, WasmType::V128) => None,
- }
+ #[inline]
+ pub(crate) const fn i31_u(self) -> Option<u32> {
+ if self.is_i31() { Some(self.0 >> 1) } else { None }
}
-}
-impl From<&WasmValue> for TinyWasmValue {
- fn from(value: &WasmValue) -> Self {
- match value {
- WasmValue::I32(v) => Self::Value32(*v as u32),
- 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::V128(v) => Self::Value128((*v).into()),
- }
+ #[inline]
+ pub(crate) const fn raw(self) -> u32 {
+ self.0
}
}
-impl From<WasmValue> for TinyWasmValue {
- fn from(value: WasmValue) -> Self {
- Self::from(&value)
- }
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+/// An untyped internal WebAssembly value.
+pub(crate) enum RuntimeValue {
+ /// A 32-bit value.
+ Value32(Value32),
+ /// A 64-bit value.
+ Value64(Value64),
+ /// A 128-bit value.
+ Value128(Value128),
+ /// A reference value.
+ ValueRef(ValueRef),
}
-impl From<[u8; 16]> for TinyWasmValue {
- fn from(value: [u8; 16]) -> Self {
- Self::Value128(Value128::from(value))
+impl RuntimeValue {
+ pub(crate) fn into_wasm(self, store: &mut Store, ty: WasmType) -> Result<WasmValue> {
+ Ok(match (self, ty) {
+ (Self::Value32(value), WasmType::I32) => WasmValue::I32(value as i32),
+ (Self::Value32(value), WasmType::F32) => WasmValue::F32(f32::from_bits(value)),
+ (Self::Value64(value), WasmType::I64) => WasmValue::I64(value as i64),
+ (Self::Value64(value), WasmType::F64) => WasmValue::F64(f64::from_bits(value)),
+ (Self::Value128(value), WasmType::V128) => WasmValue::V128(value.0),
+ (Self::ValueRef(value), WasmType::Ref(ty)) => WasmValue::Ref(store.decode_ref(value, ty)?),
+ _ => return Err(Error::other("internal value does not match its WebAssembly type")),
+ })
}
}
-mod sealed {
- #[expect(unreachable_pub)]
- pub trait Sealed {}
-}
-
-pub(crate) trait InternalValue: sealed::Sealed + Into<TinyWasmValue> + Copy + Default {
+/// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes.
+pub(crate) trait InternalValue: Copy + Default {
fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>;
fn stack_pop(stack: &mut ValueStack) -> Self;
fn stack_peek(stack: &ValueStack) -> Self;
- fn stack_select(stack: &mut ValueStack) -> Result<(), crate::Trap>;
+ fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Self;
+ fn stack_select(stack: &mut ValueStack);
fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self;
+ fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>;
fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self);
- fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self);
+ fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self) -> Self;
fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr);
+ fn global_get(globals: &Globals, addr: GlobalAddr) -> Self;
+ fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self);
+ fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self;
}
macro_rules! impl_internalvalue {
(
$(
- $variant:ident, $stack:ident, $stack_base:ident, $outer:ty,
- |$to_value_v:ident| $to_value:expr,
+ $stack:ident, $stack_base:ident, $global_get:ident, $global_set:ident, $outer:ty,
|$to_stack_v:ident| $to_stack:expr,
|$from_stack_v:ident| $from_stack:expr
)*
) => {
$(
- impl sealed::Sealed for $outer {}
-
- impl From<$outer> for TinyWasmValue {
- #[inline(always)]
- fn from(value: $outer) -> Self {
- let $to_value_v = value;
- TinyWasmValue::$variant($to_value)
- }
- }
-
impl InternalValue for $outer {
#[inline(always)]
- fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> {
- let $to_stack_v = value;
- if let Err(e) = stack.$stack.push($to_stack) {
- core::hint::cold_path();
- return Err(e);
- }
- Ok(())
+ fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self {
+ let $from_stack_v =
+ *stack.$stack.get(frame.locals_base.$stack_base as usize + index as usize);
+ $from_stack
}
#[inline(always)]
- fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self {
- let $from_stack_v = *stack.$stack.get(frame.locals_base.$stack_base as usize + index as usize);
- $from_stack
+ fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap> {
+ stack.$stack.push_copy(frame.locals_base.$stack_base as usize + index as usize)
}
#[inline(always)]
@@ -209,17 +152,53 @@ macro_rules! impl_internalvalue {
}
#[inline(always)]
- fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self) {
+ fn local_update(
+ stack: &mut ValueStack,
+ frame: &CallFrame,
+ index: LocalAddr,
+ f: impl FnOnce(Self) -> Self,
+ ) -> Self {
let abs_index = frame.locals_base.$stack_base as usize + index as usize;
let $from_stack_v = *stack.$stack.get(abs_index);
- let $to_stack_v = f($from_stack);
+ let value = f($from_stack);
+ let $to_stack_v = value;
stack.$stack.set(abs_index, $to_stack);
+ value
}
#[inline(always)]
fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr) {
- let base = frame.locals_base.$stack_base as usize;
- stack.$stack.copy(base + from as usize, base + to as usize);
+ let from = frame.locals_base.$stack_base as usize + from as usize;
+ let to = frame.locals_base.$stack_base as usize + to as usize;
+ stack.$stack.copy(from, to);
+ }
+
+ #[inline(always)]
+ fn global_get(globals: &Globals, addr: GlobalAddr) -> Self {
+ let $from_stack_v = globals.$global_get(addr);
+ $from_stack
+ }
+
+ #[inline(always)]
+ fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self) {
+ let $to_stack_v = value;
+ globals.$global_set(addr, $to_stack);
+ }
+
+ #[inline(always)]
+ fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self {
+ let $from_stack_v = globals.$global_get(addr);
+ let value = f($from_stack);
+ let $to_stack_v = value;
+ globals.$global_set(addr, $to_stack);
+ value
+ }
+
+ #[inline(always)]
+ fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> {
+ let $to_stack_v = value;
+ cold_err!(stack.$stack.push($to_stack))?;
+ Ok(())
}
#[inline(always)]
@@ -235,16 +214,24 @@ macro_rules! impl_internalvalue {
}
#[inline(always)]
- fn stack_select(stack: &mut ValueStack) -> Result<(), crate::Trap> {
+ fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Self {
+ let index = stack.$stack.len() - 1;
+ let $from_stack_v = *stack.$stack.get(index);
+ let value = f($from_stack);
+ let $to_stack_v = value;
+ stack.$stack.set(index, $to_stack);
+ value
+ }
+
+ #[inline(always)]
+ fn stack_select(stack: &mut ValueStack) {
let cond = stack.stack_32.pop() as i32;
let val2 = stack.$stack.pop();
if cond == 0 {
- Self::stack_pop(stack);
- stack.$stack.push(val2)?;
+ let val1 = stack.$stack.len() - 1;
+ stack.$stack.set(val1, val2);
}
-
- Ok(())
}
}
)*
@@ -252,12 +239,141 @@ macro_rules! impl_internalvalue {
}
impl_internalvalue! {
- Value32, stack_32, s32, u32, |v| v, |v| v, |v| v
- Value64, stack_64, s64, u64, |v| v, |v| v, |v| v
- Value32, stack_32, s32, i32, |v| v as u32, |v| v as u32, |v| v as i32
- Value64, stack_64, s64, i64, |v| v as u64, |v| v as u64, |v| v as i64
- Value32, stack_32, s32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v)
- Value64, stack_64, s64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v)
- ValueRef, stack_32, s32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v)
- Value128, stack_128, s128, Value128, |v| v, |v| v, |v| v
+ stack_32, s32, get_32, set_32, u32, |v| v, |v| v
+ stack_64, s64, get_64, set_64, u64, |v| v, |v| v
+ stack_32, s32, get_32, set_32, i32, |v| v as u32, |v| v as i32
+ stack_64, s64, get_64, set_64, i64, |v| v as u64, |v| v as i64
+ stack_32, s32, get_32, set_32, f32, |v| f32::to_bits(v), |v| f32::from_bits(v)
+ stack_64, s64, get_64, set_64, f64, |v| f64::to_bits(v), |v| f64::from_bits(v)
+ stack_32, s32, get_32, set_32, ValueRef, |v| v.raw(), |v| ValueRef(v)
+ stack_128, s128, get_128, set_128, Value128, |v| v, |v| v
+}
+
+pub(crate) trait BinOpExt<T>: Copy {
+ fn exec(self, lhs: T, rhs: T) -> T;
+}
+
+pub(crate) trait CmpOpExt<T>: Copy {
+ fn cmp(self, lhs: T, rhs: T) -> bool;
+}
+
+macro_rules! impl_value_ops {
+ ($unsigned:ty, $signed:ty, $binop:ident, $cmp:ident) => {
+ impl BinOpExt<$unsigned> for BinOp {
+ #[inline(always)]
+ fn exec(self, lhs: $unsigned, rhs: $unsigned) -> $unsigned {
+ $binop(self, lhs, rhs)
+ }
+ }
+
+ impl CmpOpExt<$signed> for CmpOp {
+ #[inline(always)]
+ fn cmp(self, lhs: $signed, rhs: $signed) -> bool {
+ $cmp(self, lhs, rhs)
+ }
+ }
+ };
+}
+
+impl_value_ops!(Value32, i32, exec_binop_32, exec_cmp_32);
+impl_value_ops!(Value64, i64, exec_binop_64, exec_cmp_64);
+
+fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 {
+ match op {
+ BinOp::IAdd => lhs.wrapping_add(rhs),
+ BinOp::ISub => lhs.wrapping_sub(rhs),
+ BinOp::IMul => lhs.wrapping_mul(rhs),
+ BinOp::IAnd => lhs & rhs,
+ BinOp::IOr => lhs | rhs,
+ BinOp::IXor => lhs ^ rhs,
+ BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32,
+ BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32,
+ BinOp::IShrU => lhs.wrapping_shr(rhs),
+ BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32,
+ BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32,
+ BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(),
+ BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(),
+ BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(),
+ BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(),
+ BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(),
+ BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(),
+ BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(),
+ }
+}
+
+fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 {
+ match op {
+ BinOp::IAdd => lhs.wrapping_add(rhs),
+ BinOp::ISub => lhs.wrapping_sub(rhs),
+ BinOp::IMul => lhs.wrapping_mul(rhs),
+ BinOp::IAnd => lhs & rhs,
+ BinOp::IOr => lhs | rhs,
+ BinOp::IXor => lhs ^ rhs,
+ BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64,
+ BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64,
+ BinOp::IShrU => lhs.wrapping_shr(rhs as u32),
+ BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64,
+ BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64,
+ BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(),
+ BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(),
+ BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(),
+ BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(),
+ BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(),
+ BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(),
+ BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(),
+ }
+}
+
+fn exec_cmp_32(op: CmpOp, lhs: i32, rhs: i32) -> bool {
+ match op {
+ CmpOp::Eq => lhs == rhs,
+ CmpOp::Ne => lhs != rhs,
+ CmpOp::LtS => lhs < rhs,
+ CmpOp::LtU => (lhs as u32) < (rhs as u32),
+ CmpOp::GtS => lhs > rhs,
+ CmpOp::GtU => (lhs as u32) > (rhs as u32),
+ CmpOp::LeS => lhs <= rhs,
+ CmpOp::LeU => (lhs as u32) <= (rhs as u32),
+ CmpOp::GeS => lhs >= rhs,
+ CmpOp::GeU => (lhs as u32) >= (rhs as u32),
+ }
+}
+
+fn exec_cmp_64(op: CmpOp, lhs: i64, rhs: i64) -> bool {
+ match op {
+ CmpOp::Eq => lhs == rhs,
+ CmpOp::Ne => lhs != rhs,
+ CmpOp::LtS => lhs < rhs,
+ CmpOp::LtU => (lhs as u64) < (rhs as u64),
+ CmpOp::GtS => lhs > rhs,
+ CmpOp::GtU => (lhs as u64) > (rhs as u64),
+ CmpOp::LeS => lhs <= rhs,
+ CmpOp::LeU => (lhs as u64) <= (rhs as u64),
+ CmpOp::GeS => lhs >= rhs,
+ CmpOp::GeU => (lhs as u64) >= (rhs as u64),
+ }
+}
+
+impl BinOpExt<Value128> for BinOp128 {
+ #[inline(always)]
+ fn exec(self, lhs: Value128, rhs: Value128) -> Value128 {
+ match self {
+ BinOp128::And => lhs.v128_and(rhs),
+ BinOp128::AndNot => lhs.v128_andnot(rhs),
+ BinOp128::Or => lhs.v128_or(rhs),
+ BinOp128::Xor => lhs.v128_xor(rhs),
+ BinOp128::I64x2Add => lhs.i64x2_add(rhs),
+ BinOp128::I64x2Mul => lhs.i64x2_mul(rhs),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ValueRef;
+
+ #[test]
+ fn value_ref_remains_four_bytes() {
+ assert_eq!(core::mem::size_of::<ValueRef>(), 4);
+ }
}
diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs
index 908f33b..47da470 100644
--- a/crates/tinywasm/src/lib.rs
+++ b/crates/tinywasm/src/lib.rs
@@ -1,4 +1,6 @@
#![no_std]
+#![cfg_attr(feature = "nightly-tail-calls", allow(incomplete_features))]
+#![cfg_attr(feature = "nightly-tail-calls", feature(explicit_tail_calls))]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_assignments, unused_variables))
@@ -7,68 +9,76 @@
#![cfg_attr(not(feature = "simd-x86"), forbid(unsafe_code))]
#![cfg_attr(feature = "simd-x86", deny(unsafe_code))]
-//! `tinywasm` provides a small, portable WebAssembly interpreter with support for
-//! the WebAssembly MVP, WebAssembly 2.0, and a growing set of newer proposals.
-//! It also supports the [Lime1](https://github.com/WebAssembly/tool-conventions/blob/main/Lime.md#lime1)
-//! interoperability target.
-//! It is designed to stay lightweight while still being practical to embed in
-//! applications, tools, and `no_std + alloc` environments.
+//! A small and portable WebAssembly interpreter.
+//!
+//! `tinywasm` passes the full WebAssembly 3.0 core testsuite and supports the
+//! [Lime1](https://github.com/WebAssembly/tool-conventions/blob/main/Lime.md#lime1)
+//! interoperability target. It is designed for embedding in applications, tools,
+//! and `no_std + alloc` environments.
#![cfg_attr(docsrs, feature(doc_cfg))]
//!
//! ## Getting started
//!
-//! The easiest way to get started is to use the `parse_bytes` function to load a
-//! WebAssembly module from bytes. This will parse the module and validate it, returning
-//! a [`Module`] that can be used to instantiate the module.
+//! Use [`parse_bytes`] to parse and validate a WebAssembly module, then instantiate it
+//! in a [`Store`]. A module can be reused, while each store owns its runtime state.
//!
//! ```rust
//! # #[cfg(feature = "parser")]
//! # fn main() -> tinywasm::Result<()> {
//! use tinywasm::{ModuleInstance, Store};
//!
-//! // Load a module from bytes
//! let wasm = include_bytes!("../../../examples/wasm/add.wasm");
//! let module = tinywasm::parse_bytes(wasm)?;
//!
-//! // # Create a new store
-//! // Stores are used to allocate objects like functions and globals
//! let mut store = Store::default();
-//!
-//! // # Instantiate the module
-//! // This will allocate the module and its globals into the store
-//! // and execute the module's start function.
//! let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
//!
-//! // # Get a typed handle to the exported "add" function
-//! // Alternatively, you can use `instance.func_untyped` to get an untyped handle
-//! // that takes and returns [`types::WasmValue`]s
-//! let func = instance.func::<(i32, i32), i32>(&store, "add")?;
-//! let res = func.call(&mut store, (1, 2))?;
+//! let add = instance.func::<(i32, i32), i32>(&store, "add")?;
+//! let result = add.call(&mut store, (1, 2))?;
//!
-//! assert_eq!(res, 3);
+//! assert_eq!(result, 3);
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "parser"))]
//! # fn main() {}
//! ```
//!
-//! For non-default runtime behavior, construct a [`Store`] with a custom [`Engine`]
-//! and [`engine::Config`] to control stack sizing, fuel accounting, memory backends,
-//! and trap-on-OOM behavior.
+//! Typed functions convert Rust values directly. Use [`ModuleInstance::func_untyped`]
+//! and [`WasmValue`] when types are selected at runtime. References such as [`StructRef`]
+//! and [`ExternRef`] are owned handles tied to their store. Cloning a managed reference
+//! keeps its referent live.
+//!
+//! Construct a store with a custom [`Engine`] and [`engine::Config`] to configure
+//! stack limits, fuel, and GC collection. A [`ResourceLimiter`] can bound guest memory,
+//! table, and GC heap growth.
//!
-//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory.
+//! ## References and GC
+//!
+//! Runtime references belong to a [`Store`]. Passing a reference to another store
+//! returns [`Trap::InvalidStore`]. Managed references are cloneable owned handles, and
+//! their referents become collectible after the last handle is dropped. Nullable typed
+//! parameters and results use `Option<T>`. Use [`RefValue`] for dynamic reference values
+//! and [`Store::gc`] to request collection explicitly.
+//!
+//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/next/examples) directory.
//!
//! ## Cargo features
//!
+//! - **`full`:** Enables `archive`, `debug`, `parallel-parser`, `parser`, `state`, and `validate`. Enabled by default.
//! - **`std`:** Enables `std` and parsing from files and streams. Enabled by default.
-//! - **`log`:** Enables integration with the `log` crate. Enabled by default.
//! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default.
+//! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`.
+//! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
//! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default.
-//! - **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default.
+//! - **`log`:** Enables integration with the `log` crate.
+//! - **`send`:** Makes stores and store-local handles movable across threads.
+//! - **`state`:** Adds store-owned host state for access from host callbacks. Enabled by default.
+//! - **`portable-atomic`:** Supports targets without native atomic compare-and-swap.
+//! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results.
//! - **`debug`:** Derives `Debug` for runtime types. Enabled by default.
-//! - **`parallel-parser`:** Parallelizes function parsing and validation when `std` is enabled. Enabled by default.
//! - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
+//! - **`nightly-tail-calls`:** Uses Rust's unstable explicit tail calls for interpreter dispatch. Requires nightly Rust (recommended for maximum performance).
//! - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally.
//!
//! With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`,
@@ -78,13 +88,18 @@
//!
//! To provide imports to a module, you can use the [`Imports`] struct.
//! This struct allows you to register custom functions, globals, memories, tables,
-//! and other modules to be linked into the module when it is instantiated.
+//! tags, and other modules to be linked into the module when it is instantiated.
//!
//! See the [`Imports`] documentation for more information.
+#[macro_use]
+mod macros;
mod std;
extern crate alloc;
+#[cfg(all(not(feature = "portable-atomic"), not(target_has_atomic = "32")))]
+compile_error!("tinywasm requires native 32-bit atomics; enable the `portable-atomic` feature");
+
// log for logging (optional).
#[cfg(feature = "log")]
#[expect(clippy::single_component_path_imports)]
@@ -105,8 +120,8 @@ pub(crate) mod log {
mod error;
pub use error::*;
pub use func::{
- ExecProgress, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, HostFunction, ToWasmTypes,
- WasmTupleChain,
+ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped,
+ HostFunction, HostFunctionCallback, IntoWasmValues, WasmTypes, WasmValueType,
};
pub use imports::*;
pub use instance::{ExternItem, ModuleInstance};
@@ -117,6 +132,7 @@ mod func;
mod imports;
mod instance;
mod reference;
+mod shared;
mod store;
mod interpreter;
@@ -124,7 +140,7 @@ use interpreter::InterpreterRuntime;
/// Global configuration for the WebAssembly interpreter
pub mod engine;
-pub use engine::{Engine, LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, StackConfig, VecMemory};
+pub use engine::{Engine, StackConfig};
#[cfg(feature = "parser")]
/// Re-export of [`tinywasm_parser`]. Requires `parser` feature.
@@ -139,6 +155,7 @@ pub use parser::{parse_file, parse_stream};
/// Re-export of [`tinywasm_types`].
pub mod types {
+ pub use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef, WasmValue};
pub use tinywasm_types::*;
}
diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs
new file mode 100644
index 0000000..351ae88
--- /dev/null
+++ b/crates/tinywasm/src/macros.rs
@@ -0,0 +1,18 @@
+macro_rules! cold {
+ ($value:expr) => {{
+ core::hint::cold_path();
+ $value
+ }};
+}
+
+// Mark the caller's error path cold. This makes a significant difference in interpreter benchmarks,
+// while doing it inside map_err or inspect_err is unreliable:
+// https://internals.rust-lang.org/t/err-automatic-hint-cold-path/24404
+macro_rules! cold_err {
+ ($result:expr) => {
+ match $result {
+ Ok(value) => Ok(value),
+ Err(error) => cold!(Err(error)),
+ }
+ };
+}
diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs
deleted file mode 100644
index dc54736..0000000
--- a/crates/tinywasm/src/reference.rs
+++ /dev/null
@@ -1,482 +0,0 @@
-use core::hint::cold_path;
-
-use alloc::ffi::CString;
-use alloc::format;
-use alloc::string::{String, ToString};
-use alloc::vec::Vec;
-
-use crate::store::{GlobalInstance, TableElement, TableInstance};
-use crate::{Error, MemoryInstance, Result, Store, Trap};
-use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue};
-
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) struct StoreItem {
- pub(crate) store_id: usize,
- pub(crate) addr: Addr,
-}
-
-impl StoreItem {
- #[inline]
- pub(crate) const fn new(store_id: usize, addr: Addr) -> Self {
- Self { store_id, addr }
- }
-
- #[inline]
- pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> {
- if self.store_id != store.id() {
- return Err(Trap::InvalidStore);
- }
- Ok(())
- }
-}
-
-/// A memory instance in a store.
-///
-/// ## Example
-/// ```rust
-/// # fn main() -> tinywasm::Result<()> {
-/// use tinywasm::types::MemoryType;
-/// use tinywasm::{Memory, Store};
-///
-/// let mut store = Store::default();
-/// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?;
-///
-/// memory.copy_from_slice(&mut store, 0, b"hi")?;
-/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi");
-/// assert_eq!(memory.page_count(&store)?, 1);
-/// memory.grow(&mut store, 1)?;
-/// assert_eq!(memory.page_count(&store)?, 2);
-/// # Ok(())
-/// # }
-/// ```
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct Memory(pub(crate) StoreItem);
-
-/// A table instance in a store.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct Table(pub(crate) StoreItem);
-
-/// A global instance in a store.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct Global(pub(crate) StoreItem);
-
-/// A cursor over a [`Memory`] instance.
-///
-/// Available with the `std` feature enabled.
-#[cfg(feature = "std")]
-pub struct MemoryCursor<'a> {
- memory: &'a mut MemoryInstance,
- position: u64,
-}
-
-#[cfg(feature = "std")]
-impl<'a> MemoryCursor<'a> {
- fn new(memory: &'a mut MemoryInstance, position: u64) -> Self {
- Self { memory, position }
- }
-
- fn offset(&self) -> crate::std::io::Result<usize> {
- usize::try_from(self.position).map_err(|_| {
- crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize")
- })
- }
-
- fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> {
- self.position = self.position.checked_add(amount as u64).ok_or_else(|| {
- crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow")
- })?;
- Ok(())
- }
-
- /// Returns the current cursor position.
- pub const fn position(&self) -> u64 {
- self.position
- }
-
- /// Sets the current cursor position.
- pub fn set_position(&mut self, position: u64) {
- self.position = position;
- }
-}
-
-#[cfg(feature = "std")]
-impl crate::std::io::Read for MemoryCursor<'_> {
- fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result<usize> {
- let offset = self.offset()?;
- let read = self.memory.inner.read(offset, buf);
- self.advance(read)?;
- Ok(read)
- }
-}
-
-#[cfg(feature = "std")]
-impl crate::std::io::Write for MemoryCursor<'_> {
- fn write(&mut self, buf: &[u8]) -> crate::std::io::Result<usize> {
- let offset = self.offset()?;
- let written = self.memory.inner.write(offset, buf);
- self.advance(written)?;
- Ok(written)
- }
-
- fn flush(&mut self) -> crate::std::io::Result<()> {
- Ok(())
- }
-}
-
-#[cfg(feature = "std")]
-impl crate::std::io::Seek for MemoryCursor<'_> {
- fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result<u64> {
- let len = self.memory.inner.len() as i128;
- let current = i128::from(self.position);
-
- let next = match pos {
- crate::std::io::SeekFrom::Start(offset) => i128::from(offset),
- crate::std::io::SeekFrom::End(offset) => len + i128::from(offset),
- crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset),
- };
-
- if next < 0 {
- return Err(crate::std::io::Error::new(
- crate::std::io::ErrorKind::InvalidInput,
- "invalid seek before start",
- ));
- }
-
- let next = u64::try_from(next).map_err(|_| {
- crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position")
- })?;
- self.position = next;
- Ok(next)
- }
-}
-
-impl Memory {
- /// Create a new memory in the given store.
- pub fn new(store: &mut Store, ty: MemoryType) -> Result<Self> {
- let addr = store.state.memories.len() as MemAddr;
- store.state.memories.push(MemoryInstance::new(ty, &store.engine.config().memory_backend)?);
- Ok(Self(StoreItem::new(store.id(), addr)))
- }
-
- /// Creates a cursor positioned at the start of this memory.
- ///
- /// Available with the `std` feature enabled.
- ///
- /// ## Example
- ///
- /// ```rust
- /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
- /// use std::io::{Read, Seek, SeekFrom, Write};
- /// use tinywasm::types::MemoryType;
- /// use tinywasm::{Memory, Store};
- ///
- /// let mut store = Store::default();
- /// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?;
- /// let mut cursor = memory.cursor(&mut store)?;
- ///
- /// cursor.seek(SeekFrom::Start(2))?;
- /// cursor.write_all(b"abc")?;
- /// cursor.seek(SeekFrom::Start(0))?;
- ///
- /// let mut bytes = [0; 5];
- /// cursor.read_exact(&mut bytes)?;
- /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']);
- /// # Ok(())
- /// # }
- /// ```
- #[cfg(feature = "std")]
- pub fn cursor<'a>(&self, store: &'a mut Store) -> Result<MemoryCursor<'a>> {
- self.cursor_at(store, 0)
- }
-
- /// Creates a cursor positioned at `position` bytes from the start of this memory.
- ///
- /// Available with the `std` feature enabled.
- #[cfg(feature = "std")]
- pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result<MemoryCursor<'a>> {
- Ok(MemoryCursor::new(self.instance_mut(store)?, position))
- }
-
- #[inline]
- fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> {
- self.0.validate_store(store)?;
- Ok(store.state.get_mem(self.0.addr))
- }
-
- #[inline]
- fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> {
- self.0.validate_store(store)?;
- Ok(store.state.get_mem_mut(self.0.addr))
- }
-
- /// Returns the raw memory byte length.
- pub fn len(&self, store: &Store) -> Result<usize> {
- Ok(self.instance(store)?.inner.len())
- }
-
- /// Returns the memory type, including page size and limits.
- pub fn ty(&self, store: &Store) -> Result<MemoryType> {
- Ok(self.instance(store)?.kind)
- }
-
- /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read.
- ///
- /// Depending on the configured backend, this may return fewer bytes than requested even when
- /// more data is available. Use [`Self::read_exact`] or [`Self::read_vec`] when you need a full
- /// range.
- pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<usize> {
- Ok(self.instance(store)?.inner.read(offset, dst))
- }
-
- /// Writes up to `src.len()` bytes into memory and returns the number of bytes written.
- ///
- /// Depending on the configured backend, this may return fewer bytes than requested even when
- /// more space is available. Use [`Self::copy_from_slice`] when you need the full slice written.
- pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result<usize> {
- Ok(self.instance_mut(store)?.inner.write(offset, src))
- }
-
- /// Reads exactly `dst.len()` bytes from memory.
- pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> {
- self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| {
- Error::Trap(crate::Trap::MemoryOutOfBounds {
- offset,
- len: dst.len(),
- max: self.instance(store).unwrap().inner.len(),
- })
- })
- }
-
- /// Reads `len` bytes from memory into a newly allocated buffer.
- pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result<Vec<u8>> {
- self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| {
- Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() })
- })
- }
-
- /// Grow the memory by the given number of pages.
- pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result<Option<i64>> {
- self.instance_mut(store)?.grow(delta_pages, true).map_err(Into::into)
- }
-
- /// Get the current size of the memory in pages.
- pub fn page_count(&self, store: &Store) -> Result<usize> {
- Ok(self.instance(store)?.page_count)
- }
-
- /// Copy a slice of memory to another place in memory.
- pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> {
- self.instance_mut(store)?.copy_within(dst, src, len)?;
- Ok(())
- }
-
- /// Fill a slice of memory with a value.
- pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> {
- self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| {
- Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() })
- })
- }
-
- /// Copies a full slice into memory.
- pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> {
- self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| {
- Error::Trap(crate::Trap::MemoryOutOfBounds {
- offset,
- len: data.len(),
- max: self.instance(store).unwrap().inner.len(),
- })
- })
- }
-
- /// Copies a nul-terminated C string into memory.
- pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> {
- self.copy_from_slice(store, offset, string.as_bytes_with_nul())
- }
-
- /// Copies a UTF-8 string into memory and appends a trailing nul byte.
- pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> {
- let mut bytes = Vec::with_capacity(string.len() + 1);
- bytes.extend_from_slice(string.as_bytes());
- bytes.push(0);
- self.copy_from_slice(store, offset, &bytes)
- }
-
- /// Reads a C-style string from memory.
- pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result<CString> {
- CString::from_vec_with_nul(self.read_vec(store, offset, len)?)
- .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}")))
- }
-
- /// Reads a C-style string from memory, stopping at the first null byte.
- pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result<CString> {
- let bytes = self.read_vec(store, offset, max_len)?;
- let Some(null) = bytes.iter().position(|byte| *byte == 0) else {
- return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string()));
- };
-
- CString::from_vec_with_nul(bytes[..=null].to_vec())
- .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}")))
- }
-
- /// Reads a UTF-8 string from memory.
- pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result<String> {
- String::from_utf8(self.read_vec(store, offset, len)?)
- .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}")))
- }
-
- /// Reads a JavaScript-style utf-16 string from memory.
- pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result<String> {
- let bytes = self.read_vec(store, offset, len)?;
- let mut string = String::new();
- for i in 0..(len / 2) {
- let c = u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]]);
- string.push(
- char::from_u32(u32::from(c)).ok_or_else(|| crate::Error::Other("Invalid UTF-16 string".to_string()))?,
- );
- }
- Ok(string)
- }
-}
-
-fn table_value_to_element(
- state: &crate::store::State,
- element_type: tinywasm_types::RefType,
- value: WasmValue,
-) -> Result<TableElement, 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()))
-}
-
-impl Table {
- /// Create a new table in the given store.
- pub fn new(store: &mut Store, ty: TableType, init: WasmValue) -> Result<Self> {
- if ty.element_type.is_concrete() {
- return Err(Error::other("host tables cannot use module-relative concrete reference types"));
- }
- let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?;
- let addr = store.state.tables.len() as TableAddr;
- store.state.tables.push(TableInstance::new_with_init(ty, init)?);
- Ok(Self(StoreItem::new(store.id(), addr)))
- }
-
- #[inline]
- fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> {
- self.0.validate_store(store)?;
- Ok(store.state.get_table(self.0.addr))
- }
-
- #[inline]
- fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut TableInstance, Trap> {
- self.0.validate_store(store)?;
- Ok(store.state.get_table_mut(self.0.addr))
- }
-
- /// Get the type of the table.
- pub fn ty(&self, store: &Store) -> Result<TableType> {
- Ok(self.instance(store)?.kind)
- }
-
- /// Get the current number of elements in the table.
- pub fn size(&self, store: &Store) -> Result<usize> {
- Ok(self.instance(store)?.size())
- }
-
- /// 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)?)
- }
-
- /// 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>> {
- 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())
- }
-
- /// Set a table element.
- pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> {
- self.0.validate_store(store)?;
- let element_type = store.state.get_table(self.0.addr).kind.element_type;
- let value = table_value_to_element(&store.state, element_type, value)?;
- store.state.get_table_mut(self.0.addr).set(index as usize, value)
- }
-
- /// Copy elements within the same table.
- pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> {
- self.instance_mut(store)?.copy_within(dst, src, len)
- }
-
- /// Grow the table and return the previous size.
- pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result<usize> {
- self.0.validate_store(store)?;
- let table = store.state.get_table(self.0.addr);
- let old_size = table.size();
- let init = table_value_to_element(&store.state, table.kind.element_type, init)?;
- let delta = usize::try_from(delta).map_err(|_| Trap::TableOutOfBounds { offset: 0, len: 1, max: old_size })?;
- store.state.get_table_mut(self.0.addr).grow(delta, init)?;
- Ok(old_size)
- }
-}
-
-impl Global {
- /// Create a new global in the given store.
- pub fn new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result<Self> {
- if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) {
- return Err(Error::other("host globals cannot use module-relative concrete reference types"));
- }
- if !store.state.value_matches_type(value, ty.ty) {
- cold_path();
- return Err(Error::Other("invalid global value type".to_string()));
- }
- let addr = store.state.globals.len() as GlobalAddr;
- store.state.globals.push(GlobalInstance::new(ty, value.into()));
- Ok(Self(StoreItem::new(store.id(), addr)))
- }
-
- #[inline]
- fn instance<'a>(&self, store: &'a Store) -> Result<&'a GlobalInstance> {
- self.0.validate_store(store)?;
- Ok(store.state.get_global(self.0.addr))
- }
-
- /// Get the type of the global.
- pub fn ty(&self, store: &Store) -> Result<GlobalType> {
- Ok(self.instance(store)?.ty)
- }
-
- /// 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")))
- }
-
- /// Set the current value of the global.
- pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> {
- self.0.validate_store(store)?;
- let global = store.state.get_global(self.0.addr);
- if !global.ty.mutable {
- cold_path();
- return Err(Error::Other("global is immutable".to_string()));
- }
- if !store.state.value_matches_type(value, global.ty.ty) {
- cold_path();
- return Err(Error::Other("invalid global value type".to_string()));
- }
- store.state.get_global_mut(self.0.addr).value = value.into();
- Ok(())
- }
-}
diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs
new file mode 100644
index 0000000..05edf04
--- /dev/null
+++ b/crates/tinywasm/src/reference/managed.rs
@@ -0,0 +1,219 @@
+use tinywasm_types::Shared;
+
+use crate::interpreter::ValueRef;
+use crate::shared::{AtomicU32, Ordering};
+use crate::{Result, Store, Trap};
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) struct StoreId(u32);
+
+impl StoreId {
+ pub(crate) fn fresh() -> Self {
+ static NEXT: AtomicU32 = AtomicU32::new(0);
+ let id = NEXT.fetch_add(1, Ordering::Relaxed);
+ assert_ne!(id, u32::MAX, "Store identity space exhausted");
+ StoreId(id)
+ }
+}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for StoreId {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str("StoreId(..)")
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub(crate) enum ReferentKind {
+ I31,
+ HostExtern,
+ Struct,
+ Array,
+ Exception,
+}
+
+#[derive(Clone)]
+pub(crate) struct RootedItem {
+ pub(crate) store: StoreId,
+ pub(crate) value: ValueRef,
+ pub(crate) kind: ReferentKind,
+ pub(crate) _token: Option<Shared<()>>,
+}
+
+impl PartialEq for RootedItem {
+ fn eq(&self, other: &Self) -> bool {
+ self.kind == other.kind
+ && self.value == other.value
+ && (self.kind == ReferentKind::I31 || self.store == other.store)
+ }
+}
+
+impl Eq for RootedItem {}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for RootedItem {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_struct("Reference").field("kind", &self.kind).finish_non_exhaustive()
+ }
+}
+
+pub(crate) trait StoredRef: Clone + Sized {
+ fn from_rooted_item(item: RootedItem) -> Self;
+ fn rooted_item(&self) -> &RootedItem;
+}
+
+macro_rules! reference_types {
+ ($($(#[$meta:meta])* $name:ident),* $(,)?) => {$($(
+ #[$meta]
+ )*
+ #[derive(Clone, PartialEq, Eq)]
+ #[cfg_attr(feature = "debug", derive(Debug))]
+ pub struct $name(RootedItem);
+
+ impl StoredRef for $name {
+ fn from_rooted_item(item: RootedItem) -> Self { Self(item) }
+ fn rooted_item(&self) -> &RootedItem { &self.0 }
+ }
+ )*};
+}
+
+reference_types! {
+ /// An owned WebAssembly `anyref`.
+ AnyRef,
+ /// An owned WebAssembly `eqref`.
+ EqRef,
+ /// An owned WebAssembly `i31ref`.
+ I31Ref,
+ /// An owned WebAssembly `structref`.
+ StructRef,
+ /// An owned WebAssembly `arrayref`.
+ ArrayRef,
+ /// An owned WebAssembly `externref`.
+ ExternRef,
+ /// An owned WebAssembly `exnref`.
+ ExnRef,
+}
+
+impl AnyRef {
+ /// Returns this reference as an `eqref` when its referent is comparable.
+ pub fn as_eq(&self) -> Option<EqRef> {
+ matches!(self.0.kind, ReferentKind::I31 | ReferentKind::Struct | ReferentKind::Array)
+ .then(|| EqRef(self.0.clone()))
+ }
+
+ /// Returns this reference as an `i31ref` when it contains an i31.
+ pub fn as_i31(&self) -> Option<I31Ref> {
+ (self.0.kind == ReferentKind::I31).then(|| I31Ref(self.0.clone()))
+ }
+
+ /// Returns this reference as a `structref` when it refers to a struct.
+ pub fn as_struct(&self) -> Option<StructRef> {
+ (self.0.kind == ReferentKind::Struct).then(|| StructRef(self.0.clone()))
+ }
+
+ /// Returns this reference as an `arrayref` when it refers to an array.
+ pub fn as_array(&self) -> Option<ArrayRef> {
+ (self.0.kind == ReferentKind::Array).then(|| ArrayRef(self.0.clone()))
+ }
+
+ /// Returns this reference with the `externref` view.
+ pub fn to_extern(&self) -> ExternRef {
+ ExternRef(self.0.clone())
+ }
+}
+
+macro_rules! impl_to_any {
+ ($($ty:ty),* $(,)?) => {$(
+ impl $ty {
+ /// Returns this reference with the `anyref` view.
+ pub fn to_any(&self) -> AnyRef { AnyRef(self.0.clone()) }
+ }
+ )*};
+}
+
+impl_to_any!(EqRef, I31Ref, StructRef, ArrayRef, ExternRef);
+
+/// A Store-aware WebAssembly function reference.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub struct FuncRef {
+ store: StoreId,
+ addr: u32,
+}
+
+impl FuncRef {
+ pub(crate) const fn new(store: StoreId, addr: u32) -> Self {
+ Self { store, addr }
+ }
+
+ pub(crate) fn addr(self, store: StoreId) -> Option<u32> {
+ (self.store == store).then_some(self.addr)
+ }
+}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for FuncRef {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.write_str("FuncRef(..)")
+ }
+}
+
+/// A host-facing WebAssembly reference value.
+#[derive(Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub enum RefValue {
+ /// A null reference.
+ Null,
+ /// A function reference.
+ Func(FuncRef),
+ /// An external reference.
+ Extern(ExternRef),
+ /// A reference in the `any` hierarchy.
+ Any(AnyRef),
+ /// An exception reference.
+ Exn(ExnRef),
+}
+
+impl ExternRef {
+ /// Creates an external reference containing a host-defined key.
+ ///
+ /// Keys must be in `0..=(1 << 30) - 2`.
+ pub fn try_new(store: &mut Store, key: u32) -> Result<Self> {
+ let value = ValueRef::try_from_host_any(key).ok_or(Trap::InvalidReference)?;
+ store.root_reference(value, ReferentKind::HostExtern)
+ }
+
+ /// Returns the host-defined key stored in this external reference.
+ ///
+ /// Returns an error for a reference produced by `extern.convert_any` from a
+ /// guest GC object or when `store` does not own the reference.
+ pub fn key(&self, store: &Store) -> Result<u32> {
+ let value = store.resolve_ref(self)?;
+ let addr = value.addr().filter(|_| value.is_host_any()).ok_or(Trap::InvalidReference)?;
+ Ok(addr & !(1 << 30))
+ }
+}
+
+impl I31Ref {
+ /// Creates a signed WebAssembly i31 reference.
+ ///
+ /// Values must be in `-2^30..=2^30 - 1`.
+ pub fn try_new(store: &mut Store, value: i32) -> Result<Self> {
+ if !(-(1 << 30)..(1 << 30)).contains(&value) {
+ return Err(Trap::InvalidReference.into());
+ }
+ store.root_reference(ValueRef::from_i31(value), ReferentKind::I31)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ extern crate std;
+ use super::*;
+
+ #[test]
+ fn host_reference_key_fits_internal_encoding() {
+ assert!(ValueRef::try_from_host_any((1 << 30) - 2).is_some());
+ assert!(ValueRef::try_from_host_any((1 << 30) - 1).is_none());
+ }
+}
diff --git a/crates/tinywasm/src/reference/mod.rs b/crates/tinywasm/src/reference/mod.rs
new file mode 100644
index 0000000..7bc61e5
--- /dev/null
+++ b/crates/tinywasm/src/reference/mod.rs
@@ -0,0 +1,13 @@
+mod managed;
+mod store;
+mod value;
+
+pub use managed::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef};
+pub(crate) use managed::{ReferentKind, RootedItem, StoreId, StoredRef};
+#[cfg(feature = "std")]
+pub use store::MemoryCursor;
+pub(crate) use store::StoreItem;
+pub use store::{
+ GcFieldType, GcHeapType, GcRefType, GcStorageType, GcType, GcTypeKind, GcValueType, Global, Memory, Table, Tag,
+};
+pub use value::WasmValue;
diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs
new file mode 100644
index 0000000..349feb4
--- /dev/null
+++ b/crates/tinywasm/src/reference/store.rs
@@ -0,0 +1,936 @@
+use core::hint::cold_path;
+
+use alloc::ffi::CString;
+use alloc::format;
+use alloc::string::{String, ToString};
+use alloc::vec::Vec;
+
+use super::managed::{ReferentKind, StoreId, StoredRef};
+use crate::interpreter::ValueRef;
+use crate::store::TableInstance;
+use crate::{ArrayRef, Error, ExnRef, I31Ref, MemoryInstance, Result, Store, StructRef, Trap, WasmValue};
+use tinywasm_types::{
+ AbstractHeapType, Addr, CompositeType, FieldType, FuncType, GlobalType, MemAddr, MemoryType, StorageType,
+ TableAddr, TableType, TagAddr, TypeAddr, WasmType,
+};
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub(crate) struct StoreItem {
+ pub(crate) store_id: StoreId,
+ pub(crate) addr: Addr,
+}
+
+impl StoreItem {
+ #[inline]
+ /// Creates a handle for an address owned by a store.
+ pub(crate) const fn new(store_id: StoreId, addr: Addr) -> Self {
+ Self { store_id, addr }
+ }
+
+ #[inline]
+ pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> {
+ if self.store_id != store.id() {
+ return Err(Trap::InvalidStore);
+ }
+ Ok(())
+ }
+}
+
+/// A memory instance in a store.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances>
+///
+/// ## Example
+/// ```rust
+/// # fn main() -> tinywasm::Result<()> {
+/// use tinywasm::types::MemoryType;
+/// use tinywasm::{Memory, Store};
+///
+/// let mut store = Store::default();
+/// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?;
+///
+/// memory.copy_from_slice(&mut store, 0, b"hi")?;
+/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi");
+/// assert_eq!(memory.page_count(&store)?, 1);
+/// memory.grow(&mut store, 1)?;
+/// assert_eq!(memory.page_count(&store)?, 2);
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct Memory(pub(crate) StoreItem);
+
+/// A table instance in a store.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#table-instances>
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct Table(pub(crate) StoreItem);
+
+/// A global instance in a store.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#global-instances>
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct Global(pub(crate) StoreItem);
+
+/// A tag instance in a store.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#tag-instances>
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct Tag(pub(crate) StoreItem);
+
+/// An opaque canonical function, struct, or array type owned by a Store.
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct GcType(StoreItem);
+
+/// The composite kind of a [`GcType`].
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub enum GcTypeKind {
+ /// A function type.
+ Function,
+ /// A struct type.
+ Struct,
+ /// An array type.
+ Array,
+}
+
+/// Metadata for a struct field or array element.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct GcFieldType {
+ storage: GcStorageType,
+ mutable: bool,
+}
+
+impl GcFieldType {
+ /// Returns the field's storage type.
+ pub const fn storage(self) -> GcStorageType {
+ self.storage
+ }
+
+ /// Returns whether the field can be changed.
+ pub const fn is_mutable(self) -> bool {
+ self.mutable
+ }
+}
+
+/// Host-visible storage metadata for a GC field or array element.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub enum GcStorageType {
+ /// A packed 8-bit integer.
+ I8,
+ /// A packed 16-bit integer.
+ I16,
+ /// An unpacked WebAssembly value.
+ Value(GcValueType),
+}
+
+/// Host-visible value metadata that does not expose concrete reference encodings.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub enum GcValueType {
+ /// A 32-bit integer.
+ I32,
+ /// A 64-bit integer.
+ I64,
+ /// A 32-bit float.
+ F32,
+ /// A 64-bit float.
+ F64,
+ /// A 128-bit vector.
+ V128,
+ /// A reference type.
+ Ref(GcRefType),
+}
+
+/// Host-visible reference metadata with opaque concrete types.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub struct GcRefType {
+ nullable: bool,
+ heap_type: GcHeapType,
+}
+
+impl GcRefType {
+ /// Returns whether the reference type accepts null.
+ pub const fn is_nullable(self) -> bool {
+ self.nullable
+ }
+
+ /// Returns the abstract or opaque concrete heap type.
+ pub const fn heap_type(self) -> GcHeapType {
+ self.heap_type
+ }
+}
+
+/// Host-visible heap type metadata.
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub enum GcHeapType {
+ /// An abstract WebAssembly heap type.
+ Abstract(AbstractHeapType),
+ /// An opaque canonical type owned by the Store.
+ Concrete(GcType),
+}
+
+impl GcType {
+ fn subtype(self, store: &Store) -> Result<&tinywasm_types::SubType> {
+ self.0.validate_store(store)?;
+ store.state.canonical_types.get(self.0.addr as usize).ok_or_else(|| Trap::InvalidReference.into())
+ }
+
+ /// Returns this type's composite kind.
+ pub fn kind(self, store: &Store) -> Result<GcTypeKind> {
+ Ok(match &self.subtype(store)?.composite {
+ CompositeType::Func(_) => GcTypeKind::Function,
+ CompositeType::Struct(_) => GcTypeKind::Struct,
+ CompositeType::Array(_) => GcTypeKind::Array,
+ })
+ }
+
+ /// Returns whether this type is a nominal subtype of `other`.
+ pub fn is_subtype_of(self, store: &Store, other: Self) -> Result<bool> {
+ self.subtype(store)?;
+ other.subtype(store)?;
+ Ok(store.state.type_addr_is_subtype(self.0.addr, other.0.addr))
+ }
+
+ /// Returns the number of struct fields.
+ pub fn field_count(self, store: &Store) -> Result<usize> {
+ self.subtype(store)?
+ .as_struct()
+ .map(|ty| ty.fields.len())
+ .ok_or_else(|| Error::other("GC type is not a struct"))
+ }
+
+ /// Returns metadata for one struct field.
+ pub fn field(self, store: &Store, index: usize) -> Result<GcFieldType> {
+ let field = self
+ .subtype(store)?
+ .as_struct()
+ .ok_or_else(|| Error::other("GC type is not a struct"))?
+ .fields
+ .get(index)
+ .copied()
+ .ok_or_else(|| Error::other("struct field out of bounds"))?;
+ Ok(gc_field_type(store, field))
+ }
+
+ /// Returns metadata for an array element.
+ pub fn array_element(self, store: &Store) -> Result<GcFieldType> {
+ let field = self.subtype(store)?.as_array().ok_or_else(|| Error::other("GC type is not an array"))?.field;
+ Ok(gc_field_type(store, field))
+ }
+}
+
+fn gc_field_type(store: &Store, field: FieldType) -> GcFieldType {
+ let storage = match field.storage {
+ StorageType::I8 => GcStorageType::I8,
+ StorageType::I16 => GcStorageType::I16,
+ StorageType::Value(ty) => GcStorageType::Value(match ty {
+ WasmType::I32 => GcValueType::I32,
+ WasmType::I64 => GcValueType::I64,
+ WasmType::F32 => GcValueType::F32,
+ WasmType::F64 => GcValueType::F64,
+ WasmType::V128 => GcValueType::V128,
+ WasmType::Ref(ty) => GcValueType::Ref(GcRefType {
+ nullable: ty.is_nullable(),
+ heap_type: match ty.type_index() {
+ Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.id(), addr))),
+ None => GcHeapType::Abstract(ty.abstract_heap_type().expect("abstract reference type")),
+ },
+ }),
+ }),
+ };
+ GcFieldType { storage, mutable: field.mutable }
+}
+
+fn rooted_object<T: StoredRef>(store: &Store, root: &T, kind: ReferentKind) -> Result<(ValueRef, TypeAddr)> {
+ let value = store.resolve_ref(root)?;
+ if root.rooted_item().kind != kind {
+ return Err(Trap::InvalidReference.into());
+ }
+ let object = store.state.gc.get(value).ok_or(Trap::InvalidReference)?;
+ let crate::store::GcObjectKind::Composite(type_addr) = object.kind else {
+ return Err(Trap::InvalidReference.into());
+ };
+ Ok((value, type_addr))
+}
+
+/// A cursor over a [`Memory`] instance.
+///
+/// Available with the `std` feature enabled.
+#[cfg(feature = "std")]
+pub struct MemoryCursor<'a> {
+ memory: &'a mut MemoryInstance,
+ position: u64,
+}
+
+#[cfg(feature = "std")]
+impl MemoryCursor<'_> {
+ fn offset(&self) -> crate::std::io::Result<usize> {
+ usize::try_from(self.position).map_err(|_| {
+ crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize")
+ })
+ }
+
+ fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> {
+ self.position = self.position.checked_add(amount as u64).ok_or_else(|| {
+ crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow")
+ })?;
+ Ok(())
+ }
+
+ /// Returns the current cursor position.
+ pub const fn position(&self) -> u64 {
+ self.position
+ }
+
+ /// Sets the current cursor position.
+ pub fn set_position(&mut self, position: u64) {
+ self.position = position;
+ }
+}
+
+#[cfg(feature = "std")]
+impl crate::std::io::Read for MemoryCursor<'_> {
+ fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result<usize> {
+ let offset = self.offset()?;
+ let read = self.memory.inner.read(offset, buf);
+ self.advance(read)?;
+ Ok(read)
+ }
+}
+
+#[cfg(feature = "std")]
+impl crate::std::io::Write for MemoryCursor<'_> {
+ fn write(&mut self, buf: &[u8]) -> crate::std::io::Result<usize> {
+ let offset = self.offset()?;
+ let written = self.memory.inner.write(offset, buf);
+ self.advance(written)?;
+ Ok(written)
+ }
+
+ fn flush(&mut self) -> crate::std::io::Result<()> {
+ Ok(())
+ }
+}
+
+#[cfg(feature = "std")]
+impl crate::std::io::Seek for MemoryCursor<'_> {
+ fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result<u64> {
+ let len = self.memory.inner.len() as i128;
+ let current = i128::from(self.position);
+
+ let next = match pos {
+ crate::std::io::SeekFrom::Start(offset) => i128::from(offset),
+ crate::std::io::SeekFrom::End(offset) => len + i128::from(offset),
+ crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset),
+ };
+
+ if next < 0 {
+ return Err(crate::std::io::Error::new(
+ crate::std::io::ErrorKind::InvalidInput,
+ "invalid seek before start",
+ ));
+ }
+
+ let next = u64::try_from(next).map_err(|_| {
+ crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position")
+ })?;
+ self.position = next;
+ Ok(next)
+ }
+}
+
+impl Memory {
+ /// **Unstable**: This method is for internal use only and may change or be removed at any time.
+ ///
+ /// Returns a raw mutable pointer to the memory's backing allocation.
+ /// Growth may invalidate the pointer. The caller must keep the store alive
+ /// and uphold Rust's aliasing rules when dereferencing it.
+ #[doc(hidden)]
+ pub fn data_ptr(&self, store: &mut Store) -> Result<*mut u8> {
+ Ok(self.instance_mut(store)?.inner.data_ptr())
+ }
+
+ /// Borrows the complete linear memory.
+ ///
+ /// The borrow prevents execution or growth through this store until it ends.
+ pub fn data<'a>(&self, store: &'a Store) -> Result<&'a [u8]> {
+ Ok(self.instance(store)?.inner.data())
+ }
+
+ /// Borrows the complete linear memory exclusively.
+ ///
+ /// The borrow prevents execution or growth through this store until it ends.
+ pub fn data_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut [u8]> {
+ Ok(self.instance_mut(store)?.inner.data_mut())
+ }
+
+ /// Create a new memory in the given store.
+ pub fn try_new(store: &mut Store, ty: MemoryType) -> Result<Self> {
+ let addr = store.state.memories.len() as MemAddr;
+ let limiter = store.engine.config().resource_limiter.clone();
+ store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?);
+ Ok(Self(StoreItem::new(store.id(), addr)))
+ }
+
+ /// Creates a cursor positioned at the start of this memory.
+ ///
+ /// Available with the `std` feature enabled.
+ ///
+ /// ## Example
+ ///
+ /// ```rust
+ /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
+ /// use std::io::{Read, Seek, SeekFrom, Write};
+ /// use tinywasm::types::MemoryType;
+ /// use tinywasm::{Memory, Store};
+ ///
+ /// let mut store = Store::default();
+ /// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?;
+ /// let mut cursor = memory.cursor(&mut store)?;
+ ///
+ /// cursor.seek(SeekFrom::Start(2))?;
+ /// cursor.write_all(b"abc")?;
+ /// cursor.seek(SeekFrom::Start(0))?;
+ ///
+ /// let mut bytes = [0; 5];
+ /// cursor.read_exact(&mut bytes)?;
+ /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']);
+ /// # Ok(())
+ /// # }
+ /// ```
+ #[cfg(feature = "std")]
+ pub fn cursor<'a>(&self, store: &'a mut Store) -> Result<MemoryCursor<'a>> {
+ self.cursor_at(store, 0)
+ }
+
+ /// Creates a cursor positioned at `position` bytes from the start of this memory.
+ ///
+ /// Available with the `std` feature enabled.
+ #[cfg(feature = "std")]
+ pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result<MemoryCursor<'a>> {
+ Ok(MemoryCursor { memory: self.instance_mut(store)?, position })
+ }
+
+ #[inline]
+ fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> {
+ self.0.validate_store(store)?;
+ Ok(store.state.get_mem(self.0.addr))
+ }
+
+ #[inline]
+ fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> {
+ self.0.validate_store(store)?;
+ Ok(store.state.get_mem_mut(self.0.addr))
+ }
+
+ /// Returns the raw memory byte length.
+ pub fn len(&self, store: &Store) -> Result<usize> {
+ Ok(self.instance(store)?.inner.len())
+ }
+
+ /// Returns the memory type, including page size and limits.
+ pub fn ty(&self, store: &Store) -> Result<MemoryType> {
+ Ok(self.instance(store)?.kind)
+ }
+
+ /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read.
+ ///
+ /// This returns fewer bytes than requested when the range extends past the end of memory. Use
+ /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range.
+ pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<usize> {
+ Ok(self.instance(store)?.inner.read(offset, dst))
+ }
+
+ /// Writes up to `src.len()` bytes into memory and returns the number of bytes written.
+ ///
+ /// This returns fewer bytes than requested when the range extends past the end of memory. Use
+ /// [`Self::copy_from_slice`] when you need the full slice written.
+ pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result<usize> {
+ Ok(self.instance_mut(store)?.inner.write(offset, src))
+ }
+
+ /// Reads exactly `dst.len()` bytes from memory.
+ pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> {
+ self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| {
+ Error::Trap(crate::Trap::MemoryOutOfBounds {
+ offset,
+ len: dst.len(),
+ max: self.instance(store).unwrap().inner.len(),
+ })
+ })
+ }
+
+ /// Reads `len` bytes from memory into a newly allocated buffer.
+ pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result<Vec<u8>> {
+ self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| {
+ Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() })
+ })
+ }
+
+ /// Grows the memory by the given number of pages.
+ ///
+ /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter.
+ /// A limiter-provided trap is returned as an error.
+ pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result<Option<i64>> {
+ let limiter = store.engine.config().resource_limiter.clone();
+ let mem = self.instance_mut(store)?;
+ mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into)
+ }
+
+ /// Get the current size of the memory in pages.
+ pub fn page_count(&self, store: &Store) -> Result<usize> {
+ Ok(self.instance(store)?.page_count)
+ }
+
+ /// Copy a slice of memory to another place in memory.
+ pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> {
+ self.instance_mut(store)?.copy_within(dst, src, len)?;
+ Ok(())
+ }
+
+ /// Fill a slice of memory with a value.
+ pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> {
+ self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| {
+ Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() })
+ })
+ }
+
+ /// Copies a full slice into memory.
+ pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> {
+ self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| {
+ Error::Trap(crate::Trap::MemoryOutOfBounds {
+ offset,
+ len: data.len(),
+ max: self.instance(store).unwrap().inner.len(),
+ })
+ })
+ }
+
+ /// Copies a nul-terminated C string into memory.
+ pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> {
+ self.copy_from_slice(store, offset, string.as_bytes_with_nul())
+ }
+
+ /// Copies a UTF-8 string into memory and appends a trailing nul byte.
+ pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> {
+ let mut bytes = Vec::with_capacity(string.len() + 1);
+ bytes.extend_from_slice(string.as_bytes());
+ bytes.push(0);
+ self.copy_from_slice(store, offset, &bytes)
+ }
+
+ /// Reads a C-style string from memory.
+ pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result<CString> {
+ CString::from_vec_with_nul(self.read_vec(store, offset, len)?)
+ .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}")))
+ }
+
+ /// Reads a C-style string from memory, stopping at the first null byte.
+ pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result<CString> {
+ let bytes = self.read_vec(store, offset, max_len)?;
+ let Some(null) = bytes.iter().position(|byte| *byte == 0) else {
+ return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string()));
+ };
+
+ CString::from_vec_with_nul(bytes[..=null].to_vec())
+ .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}")))
+ }
+
+ /// Reads a UTF-8 string from memory.
+ pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result<String> {
+ String::from_utf8(self.read_vec(store, offset, len)?)
+ .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}")))
+ }
+
+ /// Reads a JavaScript-style utf-16 string from memory.
+ pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result<String> {
+ if !len.is_multiple_of(2) {
+ return Err(crate::Error::Other("Invalid UTF-16 string: odd byte length".to_string()));
+ }
+ let bytes = self.read_vec(store, offset, len)?;
+ let code_units = bytes.as_chunks::<2>().0.iter().copied().map(u16::from_le_bytes).collect::<Vec<_>>();
+ String::from_utf16(&code_units).map_err(|error| crate::Error::Other(format!("Invalid UTF-16 string: {error}")))
+ }
+}
+
+fn table_value_to_element(
+ store: &Store,
+ element_type: tinywasm_types::RefType,
+ value: WasmValue,
+) -> Result<ValueRef, Trap> {
+ let WasmValue::Ref(reference) = &value else {
+ return Err(Trap::Other("invalid table value type"));
+ };
+ if !store.value_matches_type(&value, WasmType::Ref(element_type)) {
+ return Err(Trap::Other("invalid table value type"));
+ }
+ store.encode_ref(reference).map_err(|error| match error {
+ Error::Trap(trap) => trap,
+ _ => Trap::Other("invalid table value type"),
+ })
+}
+
+impl I31Ref {
+ /// Returns the signed i31 value.
+ pub fn value(&self, store: &Store) -> Result<i32> {
+ if self.rooted_item().kind != ReferentKind::I31 {
+ return Err(Trap::InvalidReference.into());
+ }
+ store.resolve_ref(self)?.i31_s().ok_or_else(|| Trap::InvalidReference.into())
+ }
+}
+
+impl StructRef {
+ /// Returns this struct's canonical type.
+ pub fn ty(&self, store: &Store) -> Result<GcType> {
+ let (_, type_addr) = rooted_object(store, self, ReferentKind::Struct)?;
+ Ok(GcType(StoreItem::new(store.id(), type_addr)))
+ }
+
+ /// Reads one field.
+ ///
+ /// Packed integer fields are returned as zero-extended `i32` values. Mutable
+ /// Store access is required to register owned reference results.
+ pub fn field(&self, store: &mut Store, index: usize) -> Result<WasmValue> {
+ let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?;
+ let storage = store
+ .state
+ .get_type(type_addr)
+ .as_struct()
+ .unwrap()
+ .fields
+ .get(index)
+ .ok_or_else(|| Error::other("struct field out of bounds"))?
+ .storage;
+ let value = *store.state.gc.get(reference).unwrap().values.get(index).unwrap();
+ value.into_wasm(store, storage.unpacked())
+ }
+
+ /// Reads all fields in declaration order.
+ ///
+ /// Mutable Store access is required because reference results are registered with the Store.
+ pub fn fields(&self, store: &mut Store) -> Result<Vec<WasmValue>> {
+ let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?;
+ let field_count = store.state.get_type(type_addr).as_struct().unwrap().fields.len();
+ let mut values = Vec::new();
+ values.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?;
+ for index in 0..field_count {
+ let storage = store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage;
+ let value = store.state.gc.get(reference).unwrap().values[index];
+ values.push(value.into_wasm(store, storage.unpacked())?);
+ }
+ Ok(values)
+ }
+
+ /// Writes one mutable field after validating its canonical value type.
+ ///
+ /// Writes to packed integer fields truncate the input to the field width.
+ pub fn set_field(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> {
+ let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?;
+ let field = *store
+ .state
+ .get_type(type_addr)
+ .as_struct()
+ .unwrap()
+ .fields
+ .get(index)
+ .ok_or_else(|| Error::other("struct field out of bounds"))?;
+ set_gc_value(store, reference, index, field, value, "struct field")
+ }
+}
+
+impl ArrayRef {
+ /// Returns this array's canonical type.
+ pub fn ty(&self, store: &Store) -> Result<GcType> {
+ let (_, type_addr) = rooted_object(store, self, ReferentKind::Array)?;
+ Ok(GcType(StoreItem::new(store.id(), type_addr)))
+ }
+
+ /// Returns the number of array elements.
+ pub fn len(&self, store: &Store) -> Result<usize> {
+ let (reference, _) = rooted_object(store, self, ReferentKind::Array)?;
+ Ok(store.state.gc.get(reference).unwrap().values.len())
+ }
+
+ /// Returns whether the array contains no elements.
+ pub fn is_empty(&self, store: &Store) -> Result<bool> {
+ Ok(self.len(store)? == 0)
+ }
+
+ /// Reads one array element.
+ ///
+ /// Packed integer elements are returned as zero-extended `i32` values. Mutable
+ /// Store access is required to register owned reference results.
+ pub fn get(&self, store: &mut Store, index: usize) -> Result<WasmValue> {
+ let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?;
+ let storage = store.state.get_type(type_addr).as_array().unwrap().field.storage;
+ let value = *store.state.gc.get(reference).unwrap().values.get(index).ok_or(Trap::ArrayOutOfBounds)?;
+ value.into_wasm(store, storage.unpacked())
+ }
+
+ /// Writes one mutable array element after validating its canonical value type.
+ ///
+ /// Writes to packed integer elements truncate the input to the element width.
+ pub fn set(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> {
+ let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?;
+ let field = store.state.get_type(type_addr).as_array().unwrap().field;
+ if index >= store.state.gc.get(reference).unwrap().values.len() {
+ return Err(Trap::ArrayOutOfBounds.into());
+ }
+ set_gc_value(store, reference, index, field, value, "array element")
+ }
+}
+
+fn set_gc_value(
+ store: &mut Store,
+ reference: ValueRef,
+ index: usize,
+ field: FieldType,
+ value: WasmValue,
+ field_name: &'static str,
+) -> Result<()> {
+ if !field.mutable {
+ return Err(Error::other(format!("{field_name} is immutable")));
+ }
+ let expected = field.storage.unpacked();
+ if !store.value_matches_type(&value, expected) {
+ return Err(Error::other(format!("invalid {field_name} value type")));
+ }
+ let value = match (field.storage, value.to_runtime(store)?) {
+ (StorageType::I8, crate::interpreter::RuntimeValue::Value32(value)) => {
+ crate::interpreter::RuntimeValue::Value32(value as u8 as u32)
+ }
+ (StorageType::I16, crate::interpreter::RuntimeValue::Value32(value)) => {
+ crate::interpreter::RuntimeValue::Value32(value as u16 as u32)
+ }
+ (_, value) => value,
+ };
+ let handle = store.state.gc.handle(reference).ok_or(Trap::InvalidReference)?;
+ store.state.gc.set(handle, index, value).ok_or_else(|| Trap::InvalidReference.into())
+}
+
+impl ExnRef {
+ /// Returns the exception's tag.
+ pub fn tag(&self, store: &Store) -> Result<Tag> {
+ let (_, tag_addr) = exception_object(store, self)?;
+ Ok(Tag(StoreItem::new(store.id(), tag_addr)))
+ }
+
+ /// Reads one exception payload field.
+ ///
+ /// Mutable Store access is required because reference results are registered with the Store.
+ pub fn field(&self, store: &mut Store, index: usize) -> Result<WasmValue> {
+ let (reference, tag_addr) = exception_object(store, self)?;
+ let type_addr = store.state.get_tag(tag_addr).type_addr;
+ let ty = *store
+ .state
+ .get_canonical_func_type(type_addr)
+ .params()
+ .get(index)
+ .ok_or_else(|| Error::other("exception payload field out of bounds"))?;
+ let value = *store
+ .state
+ .gc
+ .get(reference)
+ .unwrap()
+ .values
+ .get(index)
+ .ok_or_else(|| Error::other("exception payload field out of bounds"))?;
+ value.into_wasm(store, ty)
+ }
+
+ /// Reads all exception payload fields.
+ ///
+ /// Mutable Store access is required because reference results are registered with the Store.
+ pub fn fields(&self, store: &mut Store) -> Result<Vec<WasmValue>> {
+ let (reference, tag_addr) = exception_object(store, self)?;
+ let type_addr = store.state.get_tag(tag_addr).type_addr;
+ let field_count = store.state.gc.get(reference).unwrap().values.len();
+ let mut fields = Vec::new();
+ fields.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?;
+ for index in 0..field_count {
+ let ty = store.state.get_canonical_func_type(type_addr).params()[index];
+ let value = store.state.gc.get(reference).unwrap().values[index];
+ fields.push(value.into_wasm(store, ty)?);
+ }
+ Ok(fields)
+ }
+}
+
+fn exception_object(store: &Store, root: &ExnRef) -> Result<(ValueRef, TagAddr)> {
+ let reference = store.resolve_ref(root)?;
+ if root.rooted_item().kind != ReferentKind::Exception {
+ return Err(Trap::InvalidReference.into());
+ }
+ let object = store.state.gc.get(reference).ok_or(Trap::InvalidReference)?;
+ let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else {
+ return Err(Trap::InvalidReference.into());
+ };
+ Ok((reference, tag_addr))
+}
+
+impl Table {
+ /// Create a new table in the given store.
+ pub fn try_new(store: &mut Store, ty: TableType, init: WasmValue) -> Result<Self> {
+ if ty.element_type.is_concrete() {
+ return Err(Error::other("host tables cannot use module-relative concrete reference types"));
+ }
+ let init = table_value_to_element(store, ty.element_type, init).map_err(Error::from)?;
+ let limiter = store.engine.config().resource_limiter.clone();
+ let addr = store.state.tables.len() as TableAddr;
+ store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?);
+ Ok(Self(StoreItem::new(store.id(), addr)))
+ }
+
+ #[inline]
+ fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> {
+ self.0.validate_store(store)?;
+ Ok(store.state.get_table(self.0.addr))
+ }
+
+ /// Get the type of the table.
+ pub fn ty(&self, store: &Store) -> Result<TableType> {
+ Ok(self.instance(store)?.kind)
+ }
+
+ /// Get the current number of elements in the table.
+ pub fn size(&self, store: &Store) -> Result<usize> {
+ Ok(self.instance(store)?.size())
+ }
+
+ /// Get a table element as a wasm reference value.
+ ///
+ /// Mutable Store access is required because managed results are registered with the Store.
+ pub fn get(&self, store: &mut Store, index: TableAddr) -> Result<WasmValue> {
+ self.0.validate_store(store)?;
+ let table = store.state.get_table(self.0.addr);
+ let value = *table.get(index as usize)?;
+ let element_type = table.kind.element_type;
+ Ok(WasmValue::Ref(store.decode_ref(value, element_type)?))
+ }
+
+ /// Load a range of table elements and iterate over wasm reference values.
+ ///
+ /// Mutable Store access is required because managed results are registered with the Store.
+ pub fn load(&self, store: &mut Store, offset: usize, len: usize) -> Result<alloc::vec::IntoIter<WasmValue>> {
+ self.0.validate_store(store)?;
+ let table = store.state.get_table(self.0.addr);
+ let element_type = table.kind.element_type;
+ let elements = table.load(offset, len)?.to_vec();
+ let mut values = Vec::new();
+ values.try_reserve_exact(elements.len()).map_err(|_| Trap::OutOfMemory)?;
+ for value in elements {
+ values.push(WasmValue::Ref(store.decode_ref(value, element_type)?));
+ }
+ Ok(values.into_iter())
+ }
+
+ /// Set a table element.
+ pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> {
+ self.0.validate_store(store)?;
+ let element_type = store.state.get_table(self.0.addr).kind.element_type;
+ let value = table_value_to_element(store, element_type, value)?;
+ store.state.get_table_mut(self.0.addr).set(index as usize, value)
+ }
+
+ /// Copy elements within the same table.
+ pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> {
+ self.0.validate_store(store)?;
+ store.state.get_table_mut(self.0.addr).copy_within(dst, src, len)
+ }
+
+ /// Grows the table and returns the previous size.
+ ///
+ /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided
+ /// trap is returned as an error.
+ pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result<Option<usize>> {
+ self.0.validate_store(store)?;
+ let table = store.state.get_table(self.0.addr);
+ let old_size = table.size();
+ let init = table_value_to_element(store, table.kind.element_type, init)?;
+ let Ok(delta) = usize::try_from(delta) else {
+ return Ok(None);
+ };
+ let limiter = store.engine.config().resource_limiter.clone();
+ match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? {
+ true => Ok(Some(old_size)),
+ false => Ok(None),
+ }
+ }
+}
+
+impl Global {
+ /// Create a new global in the given store.
+ pub fn try_new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result<Self> {
+ if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) {
+ return Err(Error::other("host globals cannot use module-relative concrete reference types"));
+ }
+ if !store.value_matches_type(&value, ty.ty) {
+ cold_path();
+ return Err(Error::Other("invalid global value type".to_string()));
+ }
+ let value = value.to_runtime(store)?;
+ let addr = store.state.globals.push(ty, value);
+ Ok(Self(StoreItem::new(store.id(), addr)))
+ }
+
+ /// Get the type of the global.
+ pub fn ty(&self, store: &Store) -> Result<GlobalType> {
+ self.0.validate_store(store)?;
+ Ok(store.state.globals.ty(self.0.addr))
+ }
+
+ /// Get the current value of the global.
+ ///
+ /// Mutable Store access is required because an owned reference result is registered with the Store.
+ pub fn get(&self, store: &mut Store) -> Result<WasmValue> {
+ self.0.validate_store(store)?;
+ let ty = store.state.globals.ty(self.0.addr).ty;
+ let value = store.state.global_value(self.0.addr);
+ value.into_wasm(store, ty)
+ }
+
+ /// Set the current value of the global.
+ pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> {
+ self.0.validate_store(store)?;
+ let ty = store.state.globals.ty(self.0.addr).ty;
+ if !store.value_matches_type(&value, ty) {
+ return Err(Error::other("invalid global value type"));
+ }
+ let value = value.to_runtime(store)?;
+ store.state.set_global_value(self.0.addr, value)
+ }
+}
+
+impl Tag {
+ /// Create a new exception tag in the given store.
+ pub fn try_new(store: &mut Store, ty: FuncType) -> Result<Self> {
+ if !ty.results().is_empty() {
+ return Err(Error::other("tag types must not have results"));
+ }
+ if ty.params().iter().any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) {
+ return Err(Error::other("host tags cannot use concrete reference types"));
+ }
+ let type_addr = store.register_host_type(&ty);
+ let addr = store.state.tags.len() as TagAddr;
+ store.state.tags.push(crate::store::TagInstance { type_addr });
+ Ok(Self(StoreItem::new(store.id(), addr)))
+ }
+
+ /// Get the payload type of the tag.
+ pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> {
+ self.0.validate_store(store)?;
+ Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr))
+ }
+}
diff --git a/crates/tinywasm/src/reference/value.rs b/crates/tinywasm/src/reference/value.rs
new file mode 100644
index 0000000..7ef3dea
--- /dev/null
+++ b/crates/tinywasm/src/reference/value.rs
@@ -0,0 +1,232 @@
+use core::fmt::Debug;
+
+use tinywasm_types::{AbstractHeapType, RefType, WasmType};
+
+use crate::interpreter::{RuntimeValue, Value128};
+use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, Result, Store, StructRef};
+
+/// A host-facing WebAssembly value.
+///
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#values>
+#[derive(Clone, PartialEq)]
+pub enum WasmValue {
+ /// A 32-bit integer.
+ I32(i32),
+ /// A 64-bit integer.
+ I64(i64),
+ /// A 32-bit float.
+ F32(f32),
+ /// A 64-bit float.
+ F64(f64),
+ /// A 128-bit vector.
+ V128([u8; 16]),
+ /// A reference.
+ Ref(RefValue),
+}
+
+impl WasmValue {
+ pub(crate) fn to_runtime(&self, store: &Store) -> Result<RuntimeValue> {
+ Ok(match self {
+ Self::I32(value) => RuntimeValue::Value32(*value as u32),
+ Self::I64(value) => RuntimeValue::Value64(*value as u64),
+ Self::F32(value) => RuntimeValue::Value32(value.to_bits()),
+ Self::F64(value) => RuntimeValue::Value64(value.to_bits()),
+ Self::V128(value) => RuntimeValue::Value128(Value128(*value)),
+ Self::Ref(value) => RuntimeValue::ValueRef(store.encode_ref(value)?),
+ })
+ }
+
+ /// Returns this value's broad WebAssembly type, or `None` for null.
+ pub fn ty(&self) -> Option<WasmType> {
+ match self {
+ Self::I32(_) => Some(WasmType::I32),
+ Self::I64(_) => Some(WasmType::I64),
+ Self::F32(_) => Some(WasmType::F32),
+ Self::F64(_) => Some(WasmType::F64),
+ Self::V128(_) => Some(WasmType::V128),
+ Self::Ref(RefValue::Null) => None,
+ Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)),
+ Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)),
+ Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)),
+ Self::Ref(RefValue::Any(_)) => Some(WasmType::Ref(RefType::new_abstract(true, AbstractHeapType::Any))),
+ }
+ }
+
+ /// Returns whether this value matches a broad or abstract type.
+ ///
+ /// A non-null value does not match a concrete reference type because
+ /// concrete types require Store-specific subtype information.
+ pub fn matches_type(&self, ty: WasmType) -> bool {
+ match (self, ty) {
+ (Self::I32(_), WasmType::I32)
+ | (Self::I64(_), WasmType::I64)
+ | (Self::F32(_), WasmType::F32)
+ | (Self::F64(_), WasmType::F64)
+ | (Self::V128(_), WasmType::V128) => true,
+ (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(),
+ (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => {
+ ty.abstract_heap_type() == Some(AbstractHeapType::Func)
+ }
+ (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => {
+ ty.abstract_heap_type() == Some(AbstractHeapType::Extern)
+ }
+ (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => ty.abstract_heap_type() == Some(AbstractHeapType::Exn),
+ (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => match ty.abstract_heap_type() {
+ Some(AbstractHeapType::Any) => true,
+ Some(AbstractHeapType::Eq) => value.as_eq().is_some(),
+ Some(AbstractHeapType::I31) => value.as_i31().is_some(),
+ Some(AbstractHeapType::Struct) => value.as_struct().is_some(),
+ Some(AbstractHeapType::Array) => value.as_array().is_some(),
+ _ => false,
+ },
+ _ => false,
+ }
+ }
+
+ /// Returns the default value for `ty`, or `None` for a non-null reference type.
+ pub fn default_for(ty: WasmType) -> Option<Self> {
+ match ty {
+ WasmType::I32 => Some(Self::I32(0)),
+ WasmType::I64 => Some(Self::I64(0)),
+ WasmType::F32 => Some(Self::F32(0.0)),
+ WasmType::F64 => Some(Self::F64(0.0)),
+ WasmType::V128 => Some(Self::V128([0; 16])),
+ WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)),
+ WasmType::Ref(_) => None,
+ }
+ }
+
+ /// Compares values while treating NaN values with different payloads as equal.
+ pub fn eq_loose(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(),
+ (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(),
+ (Self::V128(a), Self::V128(b)) => a == b || vector_nan_eq(*a, *b),
+ _ => self == other,
+ }
+ }
+}
+
+fn vector_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool {
+ let f32_equal = a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).all(|(a, b)| {
+ let a = f32::from_le_bytes(*a);
+ let b = f32::from_le_bytes(*b);
+ a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits()
+ });
+ if f32_equal && a.as_chunks::<4>().0.iter().any(|v| f32::from_le_bytes(*v).is_nan()) {
+ return true;
+ }
+ a.as_chunks::<8>().0.iter().zip(b.as_chunks::<8>().0).all(|(a, b)| {
+ let a = f64::from_le_bytes(*a);
+ let b = f64::from_le_bytes(*b);
+ a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits()
+ }) && a.as_chunks::<8>().0.iter().any(|v| f64::from_le_bytes(*v).is_nan())
+}
+
+impl Debug for WasmValue {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match self {
+ Self::I32(value) => write!(f, "i32({value})"),
+ Self::I64(value) => write!(f, "i64({value})"),
+ Self::F32(value) => write!(f, "f32({value})"),
+ Self::F64(value) => write!(f, "f64({value})"),
+ Self::V128(value) => write!(f, "v128({value:?})"),
+ #[cfg(feature = "debug")]
+ Self::Ref(value) => write!(f, "ref({value:?})"),
+ #[cfg(not(feature = "debug"))]
+ Self::Ref(_) => f.write_str("ref(..)"),
+ }
+ }
+}
+
+macro_rules! value_conversions {
+ ($($ty:ty => $variant:ident, $method:ident);* $(;)?) => {$(
+ impl WasmValue {
+ #[doc = concat!("Returns the contained `", stringify!($ty), "` value.")]
+ pub fn $method(&self) -> Option<$ty> {
+ if let Self::$variant(value) = self { Some(value.clone()) } else { None }
+ }
+ }
+ impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::$variant(value) } }
+ impl TryFrom<WasmValue> for $ty {
+ type Error = ();
+ fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
+ if let WasmValue::$variant(value) = value { Ok(value) } else { Err(()) }
+ }
+ }
+ )*};
+}
+
+value_conversions! {
+ i32 => I32, as_i32;
+ i64 => I64, as_i64;
+ f32 => F32, as_f32;
+ f64 => F64, as_f64;
+ [u8; 16] => V128, as_v128;
+}
+
+impl WasmValue {
+ /// Returns the contained reference value.
+ pub const fn as_ref(&self) -> Option<&RefValue> {
+ if let Self::Ref(value) = self { Some(value) } else { None }
+ }
+}
+
+impl From<RefValue> for WasmValue {
+ fn from(value: RefValue) -> Self {
+ Self::Ref(value)
+ }
+}
+
+impl TryFrom<WasmValue> for RefValue {
+ type Error = ();
+
+ fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
+ if let WasmValue::Ref(value) = value { Ok(value) } else { Err(()) }
+ }
+}
+
+macro_rules! ref_conversions {
+ ($($ty:ty => $variant:ident),* $(,)?) => {$(
+ impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::$variant(value)) } }
+ impl TryFrom<WasmValue> for $ty {
+ type Error = ();
+ fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
+ if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) }
+ }
+ }
+ )*};
+}
+
+ref_conversions!(FuncRef => Func, ExternRef => Extern, AnyRef => Any, ExnRef => Exn);
+
+macro_rules! any_ref_conversions {
+ ($($ty:ty => $cast:ident),* $(,)?) => {$(
+ impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::Any(value.to_any())) } }
+ impl TryFrom<WasmValue> for $ty {
+ type Error = ();
+ fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
+ let WasmValue::Ref(RefValue::Any(value)) = value else { return Err(()) };
+ value.$cast().ok_or(())
+ }
+ }
+ )*};
+}
+
+any_ref_conversions!(EqRef => as_eq, I31Ref => as_i31, StructRef => as_struct, ArrayRef => as_array);
+
+macro_rules! nullable_conversions {
+ ($($ty:ty),* $(,)?) => {$(
+ impl From<Option<$ty>> for WasmValue {
+ fn from(value: Option<$ty>) -> Self { value.map(Into::into).unwrap_or(Self::Ref(RefValue::Null)) }
+ }
+ impl TryFrom<WasmValue> for Option<$ty> {
+ type Error = ();
+ fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
+ if matches!(value, WasmValue::Ref(RefValue::Null)) { Ok(None) } else { <$ty>::try_from(value).map(Some) }
+ }
+ }
+ )*};
+}
+
+nullable_conversions!(FuncRef, AnyRef, EqRef, I31Ref, StructRef, ArrayRef, ExternRef, ExnRef);
diff --git a/crates/tinywasm/src/shared.rs b/crates/tinywasm/src/shared.rs
new file mode 100644
index 0000000..97f42b7
--- /dev/null
+++ b/crates/tinywasm/src/shared.rs
@@ -0,0 +1,9 @@
+#[cfg(not(feature = "send"))]
+pub(crate) use alloc::rc::Rc as StoreShared;
+#[cfg(feature = "send")]
+pub(crate) use tinywasm_types::Shared as StoreShared;
+
+#[cfg(not(feature = "portable-atomic"))]
+pub(crate) use core::sync::atomic::{AtomicU32, Ordering};
+#[cfg(feature = "portable-atomic")]
+pub(crate) use portable_atomic::{AtomicU32, Ordering};
diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs
new file mode 100644
index 0000000..d896457
--- /dev/null
+++ b/crates/tinywasm/src/store/const_expr.rs
@@ -0,0 +1,237 @@
+use alloc::{format, vec::Vec};
+use tinywasm_types::*;
+
+use super::{State, default_value};
+use crate::interpreter::{InternalValue, RuntimeValue, Value32, Value64, Value128, ValueRef};
+use crate::{Error, Result, Trap};
+
+fn resolve<T: Copy>(items: &[T], index: u32, kind: &str) -> Result<T> {
+ items.get(index as usize).copied().ok_or_else(|| Error::Other(format!("{kind} {index} not found")))
+}
+
+fn pop_value(stack: &mut Vec<RuntimeValue>, storage: StorageType) -> Result<RuntimeValue> {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ match (storage, value) {
+ (StorageType::I8, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u8 as u32)),
+ (StorageType::I16, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u16 as u32)),
+ (StorageType::Value(WasmType::I32 | WasmType::F32), value @ RuntimeValue::Value32(_))
+ | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ RuntimeValue::Value64(_))
+ | (StorageType::Value(WasmType::V128), value @ RuntimeValue::Value128(_))
+ | (StorageType::Value(WasmType::Ref(_)), value @ RuntimeValue::ValueRef(_)) => Ok(value),
+ _ => Err(Error::other("type mismatch in GC constant")),
+ }
+}
+
+fn value_ref(value: &RuntimeValue) -> Option<ValueRef> {
+ match value {
+ RuntimeValue::ValueRef(value) => Some(*value),
+ _ => None,
+ }
+}
+
+fn alloc_object(
+ state: &mut State,
+ stack: &mut Vec<RuntimeValue>,
+ type_addr: TypeAddr,
+ values: Vec<RuntimeValue>,
+) -> Result<()> {
+ let roots = stack.iter().filter_map(value_ref);
+ let reference = state.alloc_gc_object(type_addr, values, roots)?;
+ stack.push(RuntimeValue::ValueRef(reference));
+ Ok(())
+}
+
+#[inline]
+pub(super) fn eval_const(
+ state: &mut State,
+ instructions: &[ConstInstruction],
+ global_addrs: &[GlobalAddr],
+ func_addrs: &[FuncAddr],
+ type_addrs: &[TypeAddr],
+) -> Result<RuntimeValue> {
+ use ConstInstruction::*;
+
+ if let [instruction] = instructions {
+ match instruction {
+ I32Const(value) => return Ok(RuntimeValue::Value32(*value as u32)),
+ I64Const(value) => return Ok(RuntimeValue::Value64(*value as u64)),
+ F32Const(value) => return Ok(RuntimeValue::Value32(value.to_bits())),
+ F64Const(value) => return Ok(RuntimeValue::Value64(value.to_bits())),
+ V128Const(value) => return Ok(RuntimeValue::Value128(Value128(*value))),
+ GlobalGet32(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ return Ok(RuntimeValue::Value32(Value32::global_get(&state.globals, addr)));
+ }
+ GlobalGet64(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ return Ok(RuntimeValue::Value64(Value64::global_get(&state.globals, addr)));
+ }
+ GlobalGet128(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ return Ok(RuntimeValue::Value128(Value128::global_get(&state.globals, addr)));
+ }
+ GlobalGetRef(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ return Ok(RuntimeValue::ValueRef(ValueRef::global_get(&state.globals, addr)));
+ }
+ RefNull(_) => return Ok(RuntimeValue::ValueRef(ValueRef::NULL)),
+ RefFunc(func) => {
+ let addr = resolve(func_addrs, func.index(), "function")?;
+ return Ok(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr)));
+ }
+ _ => {}
+ }
+ }
+
+ let mut stack = Vec::new();
+ for instruction in instructions {
+ match instruction {
+ I32Const(value) => stack.push(RuntimeValue::Value32(*value as u32)),
+ I64Const(value) => stack.push(RuntimeValue::Value64(*value as u64)),
+ F32Const(value) => stack.push(RuntimeValue::Value32(value.to_bits())),
+ F64Const(value) => stack.push(RuntimeValue::Value64(value.to_bits())),
+ V128Const(value) => stack.push(RuntimeValue::Value128(Value128(*value))),
+ GlobalGet32(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ stack.push(RuntimeValue::Value32(Value32::global_get(&state.globals, addr)));
+ }
+ GlobalGet64(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ stack.push(RuntimeValue::Value64(Value64::global_get(&state.globals, addr)));
+ }
+ GlobalGet128(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ stack.push(RuntimeValue::Value128(Value128::global_get(&state.globals, addr)));
+ }
+ GlobalGetRef(index) => {
+ let addr = resolve(global_addrs, *index, "global")?;
+ stack.push(RuntimeValue::ValueRef(ValueRef::global_get(&state.globals, addr)));
+ }
+ RefNull(_) => stack.push(RuntimeValue::ValueRef(ValueRef::NULL)),
+ RefFunc(func) => {
+ let addr = resolve(func_addrs, func.index(), "function")?;
+ stack.push(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr)));
+ }
+ RefI31 => {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ let RuntimeValue::Value32(value) = value else {
+ return Err(Error::other("type mismatch in const ref.i31"));
+ };
+ stack.push(RuntimeValue::ValueRef(ValueRef::from_i31(value as i32)));
+ }
+ AnyConvertExtern | ExternConvertAny => {
+ let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?;
+ if !matches!(value, RuntimeValue::ValueRef(_)) {
+ return Err(Error::other("type mismatch in const reference conversion"));
+ }
+ stack.push(value);
+ }
+ StructNew(type_index) | StructNewDefault(type_index) => {
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
+ let field_count = state
+ .get_type(type_addr)
+ .as_struct()
+ .ok_or_else(|| Error::other("GC constant type is not a struct"))?
+ .fields
+ .len();
+ let default = matches!(instruction, StructNewDefault(_));
+ state.check_gc_allocation(type_addr, field_count)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?;
+ if default {
+ values.extend(
+ state
+ .get_type(type_addr)
+ .as_struct()
+ .unwrap()
+ .fields
+ .iter()
+ .map(|field| default_value(field.storage)),
+ );
+ } else {
+ for index in (0..field_count).rev() {
+ let storage = state.get_type(type_addr).as_struct().unwrap().fields[index].storage;
+ values.push(pop_value(&mut stack, storage)?);
+ }
+ values.reverse();
+ }
+ alloc_object(state, &mut stack, type_addr, values)?;
+ }
+ ArrayNew(type_index) | ArrayNewDefault(type_index) => {
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
+ let storage = state
+ .get_type(type_addr)
+ .as_array()
+ .ok_or_else(|| Error::other("GC constant type is not an array"))?
+ .field
+ .storage;
+ let Some(RuntimeValue::Value32(len)) = stack.pop() else {
+ return Err(Error::other("type mismatch in const array length"));
+ };
+ state.check_gc_allocation(type_addr, len as usize)?;
+ let value = if matches!(instruction, ArrayNewDefault(_)) {
+ default_value(storage)
+ } else {
+ pop_value(&mut stack, storage)?
+ };
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(len as usize)).map_err(|_| Trap::OutOfMemory)?;
+ values.resize(len as usize, value);
+ alloc_object(state, &mut stack, type_addr, values)?;
+ }
+ ArrayNewFixed(type_index, len) => {
+ let type_addr = resolve(type_addrs, *type_index, "type")?;
+ let storage = state
+ .get_type(type_addr)
+ .as_array()
+ .ok_or_else(|| Error::other("GC constant type is not an array"))?
+ .field
+ .storage;
+ state.check_gc_allocation(type_addr, *len as usize)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(*len as usize)).map_err(|_| Trap::OutOfMemory)?;
+ for _ in 0..*len {
+ values.push(pop_value(&mut stack, storage)?);
+ }
+ values.reverse();
+ alloc_object(state, &mut stack, type_addr, values)?;
+ }
+ 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"))?;
+ let (RuntimeValue::Value32(lhs), RuntimeValue::Value32(rhs)) = (lhs, rhs) else {
+ return cold!(Err(Error::other("type mismatch in const i32 op")));
+ };
+ let out = match instruction {
+ I32Add => (lhs as i32).wrapping_add(rhs as i32),
+ I32Sub => (lhs as i32).wrapping_sub(rhs as i32),
+ I32Mul => (lhs as i32).wrapping_mul(rhs as i32),
+ _ => unreachable!(),
+ };
+ stack.push(RuntimeValue::Value32(out as u32));
+ }
+ I64Add | I64Sub | I64Mul => {
+ let rhs = stack.pop();
+ let lhs = stack.pop();
+ let (Some(RuntimeValue::Value64(lhs)), Some(RuntimeValue::Value64(rhs))) = (lhs, rhs) else {
+ return cold!(Err(Error::other("type mismatch in const i64 op")));
+ };
+ let out = match instruction {
+ I64Add => (lhs as i64).wrapping_add(rhs as i64),
+ I64Sub => (lhs as i64).wrapping_sub(rhs as i64),
+ I64Mul => (lhs as i64).wrapping_mul(rhs as i64),
+ _ => unreachable!(),
+ };
+ stack.push(RuntimeValue::Value64(out as u64));
+ }
+ }
+ }
+
+ let Some(value) = stack.pop() else {
+ return cold!(Err(Error::other("empty const expression")));
+ };
+ if !stack.is_empty() {
+ return cold!(Err(Error::other("const expression did not reduce to single value")));
+ }
+ Ok(value)
+}
diff --git a/crates/tinywasm/src/store/data.rs b/crates/tinywasm/src/store/data.rs
index f9d5f5d..75c57ca 100644
--- a/crates/tinywasm/src/store/data.rs
+++ b/crates/tinywasm/src/store/data.rs
@@ -1,11 +1,11 @@
-use alloc::vec::Vec;
+use tinywasm_types::Shared;
/// A WebAssembly Data Instance
///
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#data-instances>
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct DataInstance {
- pub(crate) data: Option<Vec<u8>>,
+ pub(crate) data: Option<Shared<[u8]>>,
}
impl DataInstance {
diff --git a/crates/tinywasm/src/store/element.rs b/crates/tinywasm/src/store/element.rs
index f3a8602..8119fe8 100644
--- a/crates/tinywasm/src/store/element.rs
+++ b/crates/tinywasm/src/store/element.rs
@@ -1,16 +1,27 @@
-use crate::TableElement;
+use crate::{Trap, 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 {
pub(crate) fn drop(&mut self) {
self.items.take();
}
+
+ pub(crate) fn items_range(&self, offset: usize, len: usize) -> Result<&[ValueRef], Trap> {
+ let items = self.items.as_deref().unwrap_or(&[]);
+ let end = offset.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| {
+ core::hint::cold_path();
+ Trap::TableOutOfBounds { offset, len, max: items.len() }
+ })?;
+ Ok(&items[offset..end])
+ }
}
diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs
index e3c79b4..e1d537d 100644
--- a/crates/tinywasm/src/store/function.rs
+++ b/crates/tinywasm/src/store/function.rs
@@ -1,31 +1,93 @@
-use alloc::sync::Arc;
+use alloc::{rc::Rc, sync::Arc, vec::Vec};
+use core::ops::Range;
use tinywasm_types::*;
use crate::func::HostFunction;
-/// A WebAssembly Function Instance
-///
-/// See <https://webassembly.github.io/spec/core/exec/runtime.html#function-instances>
-#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) struct FunctionInstance {
+pub(crate) struct HostFunctionInstance {
pub(crate) type_addr: TypeAddr,
- pub(crate) kind: FunctionKind,
+ pub(crate) func: HostFunction,
}
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) enum FunctionKind {
- /// A host function
- Host(Arc<HostFunction>),
+pub(crate) struct WasmFunctionInstance {
+ pub(crate) type_addr: TypeAddr,
+ pub(crate) func: Shared<WasmFunction>,
+ pub(crate) owner: ModuleInstanceId,
+}
- /// A pointer to a WebAssembly function
- Wasm(WasmFunctionInstance),
+#[derive(Default)]
+pub(crate) struct Functions {
+ wasm: Vec<WasmFunctionInstance>,
+ host: Vec<HostFunctionInstance>,
}
-#[derive(Clone)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) struct WasmFunctionInstance {
- pub(crate) func: Arc<WasmFunction>,
- pub(crate) owner: ModuleInstanceId,
+impl Functions {
+ const HOST_TAG: u32 = 1 << 29;
+ const INDEX_MASK: u32 = Self::HOST_TAG - 1;
+ const MAX_ADDR: u32 = Self::HOST_TAG | Self::INDEX_MASK;
+
+ #[inline(always)]
+ pub(crate) const fn is_host(&self, addr: FuncAddr) -> bool {
+ addr & Self::HOST_TAG != 0
+ }
+
+ #[inline(always)]
+ fn index(addr: FuncAddr) -> usize {
+ (addr & Self::INDEX_MASK) as usize
+ }
+
+ pub(crate) fn extend_wasm(
+ &mut self,
+ funcs: impl ExactSizeIterator<Item = (TypeAddr, Shared<WasmFunction>)>,
+ owner: ModuleInstanceId,
+ ) -> Range<FuncAddr> {
+ let start = self.wasm.len();
+ let end = start.checked_add(funcs.len()).expect("too many Wasm functions");
+ assert!(end <= Self::HOST_TAG as usize, "too many Wasm functions");
+ self.wasm.reserve_exact(funcs.len());
+ self.wasm.extend(funcs.map(|(type_addr, func)| WasmFunctionInstance { type_addr, func, owner }));
+ start as FuncAddr..end as FuncAddr
+ }
+
+ pub(crate) fn push_host(&mut self, type_addr: TypeAddr, func: HostFunction) -> FuncAddr {
+ let index = self.host.len();
+ assert!(index <= Self::INDEX_MASK as usize, "too many host functions");
+ self.host.push(HostFunctionInstance { type_addr, func });
+ Self::HOST_TAG | index as FuncAddr
+ }
+
+ #[inline]
+ pub(crate) fn type_addr(&self, addr: FuncAddr) -> TypeAddr {
+ if self.is_host(addr) {
+ self.host[Self::index(addr)].type_addr
+ } else {
+ self.wasm[Self::index(addr)].type_addr
+ }
+ }
+
+ pub(crate) fn contains(&self, addr: FuncAddr) -> bool {
+ if addr > Self::MAX_ADDR {
+ return false;
+ }
+ if self.is_host(addr) {
+ Self::index(addr) < self.host.len()
+ } else {
+ Self::index(addr) < self.wasm.len()
+ }
+ }
+
+ #[inline]
+ pub(crate) fn wasm(&self, addr: FuncAddr) -> &WasmFunctionInstance {
+ debug_assert!(!self.is_host(addr), "host address used for a Wasm function");
+ &self.wasm[Self::index(addr)]
+ }
+
+ #[inline]
+ pub(crate) fn host(&self, addr: FuncAddr) -> &HostFunctionInstance {
+ debug_assert!(self.is_host(addr), "Wasm address used for a host function");
+ &self.host[Self::index(addr)]
+ }
}
diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs
new file mode 100644
index 0000000..56170ce
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/arena.rs
@@ -0,0 +1,281 @@
+//! 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,
+ pub(super) 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 = Self::allocation_size(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 exclusive references for two distinct live handles.
+ pub(crate) fn get_disjoint_mut(&mut self, first: Handle, second: Handle) -> Option<(&mut T, &mut T)> {
+ let [first_slot, second_slot] =
+ self.slots.get_disjoint_mut([first.index as usize, second.index as usize]).ok()?;
+ if first_slot.generation != first.generation || second_slot.generation != second.generation {
+ return None;
+ }
+ match (&mut first_slot.state, &mut second_slot.state) {
+ (SlotState::Occupied { value: first, .. }, SlotState::Occupied { value: second, .. }) => {
+ Some((first, second))
+ }
+ _ => None,
+ }
+ }
+
+ /// Returns whether an allocation of this size should trigger collection.
+ pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool {
+ Self::allocation_size(out_of_line_bytes)
+ .and_then(|bytes| self.allocated_bytes.checked_add(bytes))
+ .is_none_or(|bytes| bytes >= self.next_collection)
+ }
+
+ pub(super) fn allocation_size(out_of_line_bytes: usize) -> Option<usize> {
+ size_of::<Slot<T>>().checked_add(out_of_line_bytes)
+ }
+}
+
+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..152d651
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/mod.rs
@@ -0,0 +1,102 @@
+mod arena;
+mod object;
+mod roots;
+
+use alloc::vec::Vec;
+use core::ops::Range;
+use tinywasm_types::{StorageType, WasmType};
+
+use crate::Trap;
+use crate::interpreter::stack::ValueStack;
+use crate::interpreter::{InternalValue, RuntimeValue, Value128, ValueRef};
+
+pub(crate) use arena::{AllocError, Arena, Handle, Trace};
+pub(crate) use object::{GcHeap, GcObjectKind};
+pub(crate) use roots::Roots;
+
+/// Returns the zero value for a GC field or array element.
+pub(crate) fn default_value(storage: StorageType) -> RuntimeValue {
+ match storage {
+ StorageType::I8 | StorageType::I16 | StorageType::Value(WasmType::I32 | WasmType::F32) => {
+ RuntimeValue::Value32(0)
+ }
+ StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(0),
+ StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128([0; 16])),
+ StorageType::Value(WasmType::Ref(_)) => RuntimeValue::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) -> RuntimeValue {
+ match storage {
+ StorageType::I8 => RuntimeValue::Value32(i32::stack_pop(stack) as u8 as u32),
+ StorageType::I16 => RuntimeValue::Value32(i32::stack_pop(stack) as u16 as u32),
+ StorageType::Value(WasmType::I32 | WasmType::F32) => RuntimeValue::Value32(u32::stack_pop(stack)),
+ StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(u64::stack_pop(stack)),
+ StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128::stack_pop(stack)),
+ StorageType::Value(WasmType::Ref(_)) => RuntimeValue::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: RuntimeValue,
+ storage: StorageType,
+ signed: Option<bool>,
+) -> Result<(), Trap> {
+ let value = match (value, storage, signed) {
+ (RuntimeValue::Value32(value), StorageType::I8, Some(true)) => RuntimeValue::Value32(value as i8 as i32 as u32),
+ (RuntimeValue::Value32(value), StorageType::I16, Some(true)) => {
+ RuntimeValue::Value32(value as i16 as i32 as u32)
+ }
+ (RuntimeValue::Value32(value), StorageType::I8, Some(false)) => RuntimeValue::Value32(value & u8::MAX as u32),
+ (RuntimeValue::Value32(value), StorageType::I16, Some(false)) => RuntimeValue::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 data_range(
+ storage: StorageType,
+ data: &[u8],
+ src: usize,
+ len: usize,
+) -> Result<(Range<usize>, usize), 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() });
+ };
+ Ok((src..end, width))
+}
+
+/// Decodes numeric array elements from a data segment.
+pub(crate) fn decode_data(
+ storage: StorageType,
+ data: &[u8],
+ src: usize,
+ len: usize,
+) -> Result<Vec<RuntimeValue>, Trap> {
+ let (range, width) = data_range(storage, data, src, len)?;
+ let mut values = Vec::new();
+ cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?;
+ values.extend(data[range].chunks_exact(width).map(|bytes| match width {
+ 1 => RuntimeValue::Value32(u32::from(bytes[0])),
+ 2 => RuntimeValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))),
+ 4 => RuntimeValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())),
+ 8 => RuntimeValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())),
+ 16 => RuntimeValue::Value128(Value128(<[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..c76d7e9
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/object.rs
@@ -0,0 +1,286 @@
+use alloc::{boxed::Box, vec::Vec};
+use core::mem::size_of;
+
+use tinywasm_types::{TagAddr, TypeAddr};
+
+use crate::engine::Config;
+use crate::interpreter::{RuntimeValue, ValueRef};
+use crate::shared::StoreShared;
+use crate::{ResourceLimiter, Trap};
+
+use super::{AllocError, Arena, Handle, Trace};
+
+pub(crate) struct GcObject {
+ pub(crate) kind: GcObjectKind,
+ pub(crate) values: Box<[RuntimeValue]>,
+ references: Option<Box<[Option<Handle>]>>,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) enum GcObjectKind {
+ Composite(TypeAddr),
+ Exception(TagAddr),
+}
+
+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)>,
+ next_key: u32,
+ resource_limiter: Option<StoreShared<dyn ResourceLimiter>>,
+}
+
+impl Default for GcHeap {
+ fn default() -> Self {
+ Self::new(&Config::default())
+ }
+}
+
+impl GcHeap {
+ /// Creates a heap with the configured allocation threshold.
+ pub(crate) fn new(config: &Config) -> Self {
+ Self {
+ objects: Arena::new(config.gc_collection_threshold),
+ directory: Vec::new(),
+ next_key: 0,
+ resource_limiter: config.resource_limiter.clone(),
+ }
+ }
+
+ #[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_handle(&self, handle: Handle) -> Option<&GcObject> {
+ self.objects.get(handle)
+ }
+
+ pub(crate) fn check_allocation(&self, value_count: usize, trace_references: bool) -> Result<(), Trap> {
+ let element_size = size_of::<RuntimeValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
+ let out_of_line_bytes = value_count.checked_mul(element_size).ok_or(Trap::OutOfMemory)?;
+ let allocation_size = Arena::<GcObject>::allocation_size(out_of_line_bytes).ok_or(Trap::OutOfMemory)?;
+ let desired = self.objects.allocated_bytes.checked_add(allocation_size).ok_or(Trap::OutOfMemory)?;
+ if let Some(limiter) = &self.resource_limiter
+ && !limiter.gc_growing(self.objects.allocated_bytes, desired, None)?
+ {
+ return Err(Trap::OutOfMemory);
+ }
+ Ok(())
+ }
+
+ /// Allocates an object and returns its compact runtime reference.
+ pub(crate) fn alloc(
+ &mut self,
+ type_addr: TypeAddr,
+ values: Vec<RuntimeValue>,
+ trace_references: bool,
+ ) -> Result<ValueRef, Trap> {
+ self.alloc_kind(GcObjectKind::Composite(type_addr), values, trace_references, None)
+ }
+
+ /// Allocates an exception and traces references in its payload.
+ pub(crate) fn alloc_exception(
+ &mut self,
+ tag_addr: TagAddr,
+ payload: Vec<RuntimeValue>,
+ trace_fields: &[bool],
+ ) -> Result<ValueRef, Trap> {
+ self.alloc_kind(GcObjectKind::Exception(tag_addr), payload, true, Some(trace_fields))
+ }
+
+ fn alloc_kind(
+ &mut self,
+ kind: GcObjectKind,
+ values: Vec<RuntimeValue>,
+ trace_references: bool,
+ trace_fields: Option<&[bool]>,
+ ) -> Result<ValueRef, Trap> {
+ let element_size = size_of::<RuntimeValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
+ let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?;
+ if self.next_key >= 1 << 30 {
+ return Err(Trap::OutOfMemory);
+ }
+ let key = self.next_key;
+ self.next_key += 1;
+ let references = if trace_references {
+ let mut references = Vec::new();
+ references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?;
+ references.extend(values.iter().enumerate().map(|(index, value)| match value {
+ RuntimeValue::ValueRef(value) if trace_fields.is_none_or(|fields| fields[index]) => self.handle(*value),
+ _ => None,
+ }));
+ Some(references.into_boxed_slice())
+ } else {
+ None
+ };
+ let object = GcObject { kind, values: values.into_boxed_slice(), references };
+ self.directory.try_reserve(1).map_err(|_| Trap::OutOfMemory)?;
+ let handle = self.objects.alloc(object, out_of_line_bytes).map_err(|_| Trap::OutOfMemory)?;
+ self.directory.push((key, handle));
+ Ok(ValueRef::from_category_addr(key))
+ }
+
+ pub(crate) fn set(&mut self, object: Handle, index: usize, value: RuntimeValue) -> Option<()> {
+ let reference = match value {
+ RuntimeValue::ValueRef(value) => self.handle(value),
+ _ => None,
+ };
+ let object = self.objects.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: Handle, index: usize, values: &[RuntimeValue]) -> Option<()> {
+ let end = index.checked_add(values.len())?;
+ let directory = &self.directory;
+ let object = self.objects.get_mut(object)?;
+ 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 = match value {
+ RuntimeValue::ValueRef(value) => value.addr().and_then(|key| {
+ directory.binary_search_by_key(&key, |entry| entry.0).ok().map(|index| directory[index].1)
+ }),
+ _ => None,
+ };
+ }
+ }
+ Some(())
+ }
+
+ /// Fills a contiguous range and updates its traced references.
+ pub(crate) fn fill(&mut self, object: Handle, range: core::ops::Range<usize>, value: RuntimeValue) -> Option<()> {
+ let reference = match value {
+ RuntimeValue::ValueRef(value) => self.handle(value),
+ _ => None,
+ };
+ let object = self.objects.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::<RuntimeValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
+ self.objects.should_collect(value_count.saturating_mul(element_size))
+ }
+
+ /// Reclaims objects unreachable from runtime roots.
+ pub(crate) fn collect(&mut self, roots: impl IntoIterator<Item = ValueRef>) -> Result<(), AllocError> {
+ 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(root_handles)?;
+ self.directory.retain(|(_, handle)| self.objects.get(*handle).is_some());
+ Ok(())
+ }
+
+ pub(crate) fn copy_within(&mut self, object: Handle, src: core::ops::Range<usize>, dst: usize) -> Option<()> {
+ let object = self.objects.get_mut(object)?;
+ object.values.copy_within(src.clone(), dst);
+ if let Some(references) = &mut object.references {
+ references.copy_within(src, dst);
+ }
+ Some(())
+ }
+
+ /// Copies values and tracing metadata between two distinct objects.
+ pub(crate) fn copy_between(
+ &mut self,
+ src: Handle,
+ src_range: core::ops::Range<usize>,
+ dst: Handle,
+ dst_index: usize,
+ ) -> Option<()> {
+ let (src, dst) = self.objects.get_disjoint_mut(src, dst)?;
+ let src_values = src.values.get(src_range.clone())?;
+ let dst_end = dst_index.checked_add(src_values.len())?;
+ dst.values.get_mut(dst_index..dst_end)?.copy_from_slice(src_values);
+ if let Some(dst_refs) = &mut dst.references {
+ if let Some(src_refs) = &src.references {
+ dst_refs[dst_index..dst_end].copy_from_slice(&src_refs[src_range]);
+ } else {
+ dst_refs[dst_index..dst_end].fill(None);
+ }
+ }
+ 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![RuntimeValue::ValueRef(ValueRef::NULL)], true).unwrap();
+ let second = heap.alloc(0, alloc::vec![RuntimeValue::ValueRef(first)], true).unwrap();
+ heap.set(heap.handle(first).unwrap(), 0, RuntimeValue::ValueRef(second)).unwrap();
+
+ heap.collect([]).unwrap();
+
+ assert!(heap.get(first).is_none());
+ assert!(heap.get(second).is_none());
+ }
+
+ #[test]
+ fn exception_payload_traces_managed_objects() {
+ let mut heap = GcHeap::default();
+ let payload = heap.alloc(0, Vec::new(), false).unwrap();
+ let exception = heap.alloc_exception(0, alloc::vec![RuntimeValue::ValueRef(payload)], &[true]).unwrap();
+
+ heap.collect([exception]).unwrap();
+ assert!(heap.get(payload).is_some());
+
+ heap.collect([]).unwrap();
+ assert!(heap.get(exception).is_none());
+ assert!(heap.get(payload).is_none());
+ }
+}
diff --git a/crates/tinywasm/src/store/gc/roots.rs b/crates/tinywasm/src/store/gc/roots.rs
new file mode 100644
index 0000000..ea6c47a
--- /dev/null
+++ b/crates/tinywasm/src/store/gc/roots.rs
@@ -0,0 +1,59 @@
+use alloc::vec::Vec;
+use tinywasm_types::{Shared, WeakShared};
+
+use crate::Trap;
+use crate::interpreter::ValueRef;
+
+pub(crate) struct Roots {
+ entries: Vec<Option<Root>>,
+ free: Vec<u32>,
+}
+
+struct Root {
+ value: ValueRef,
+ token: WeakShared<()>,
+}
+
+impl Roots {
+ pub(crate) const fn new() -> Self {
+ Self { entries: Vec::new(), free: Vec::new() }
+ }
+
+ pub(crate) fn reserve(&mut self, additional: usize) -> Result<(), Trap> {
+ self.remove_dead();
+ let needed = additional.saturating_sub(self.free.len());
+ self.entries.try_reserve(needed).map_err(|_| Trap::OutOfMemory)
+ }
+
+ pub(crate) fn insert(&mut self, value: ValueRef) -> Result<Shared<()>, Trap> {
+ if self.free.is_empty() && self.entries.len() == self.entries.capacity() {
+ self.remove_dead();
+ }
+ let index = if let Some(index) = self.free.pop() {
+ index
+ } else {
+ let index = u32::try_from(self.entries.len()).map_err(|_| Trap::OutOfMemory)?;
+ self.entries.try_reserve(1).map_err(|_| Trap::OutOfMemory)?;
+ self.entries.push(None);
+ index
+ };
+
+ let token = Shared::new(());
+ self.entries[index as usize] = Some(Root { value, token: Shared::downgrade(&token) });
+ Ok(token)
+ }
+
+ pub(crate) fn values(&mut self) -> impl Iterator<Item = ValueRef> + '_ {
+ self.remove_dead();
+ self.entries.iter().flatten().map(|root| root.value)
+ }
+
+ fn remove_dead(&mut self) {
+ for (index, root) in self.entries.iter_mut().enumerate() {
+ if root.as_ref().is_some_and(|root| root.token.strong_count() == 0) {
+ *root = None;
+ self.free.push(index as u32);
+ }
+ }
+ }
+}
diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs
index 9280494..75aa163 100644
--- a/crates/tinywasm/src/store/global.rs
+++ b/crates/tinywasm/src/store/global.rs
@@ -1,17 +1,154 @@
-use crate::interpreter::TinyWasmValue;
+use alloc::vec::Vec;
use tinywasm_types::*;
-/// A WebAssembly Global Instance
+use crate::interpreter::{RuntimeValue, Value32, Value64, Value128};
+
+#[derive(Default)]
+struct GlobalLane<T> {
+ values: Vec<T>,
+ types: Vec<GlobalType>,
+}
+
+impl<T: Copy> GlobalLane<T> {
+ fn reserve(&mut self, additional: usize) {
+ self.values.reserve_exact(additional);
+ self.types.reserve_exact(additional);
+ }
+
+ fn push(&mut self, ty: GlobalType, value: T) -> usize {
+ debug_assert_eq!(self.values.len(), self.types.len());
+ let index = self.values.len();
+ self.values.push(value);
+ self.types.push(ty);
+ index
+ }
+
+ #[inline]
+ fn get(&self, index: usize) -> T {
+ self.values[index]
+ }
+
+ #[inline]
+ fn set(&mut self, index: usize, value: T) {
+ self.values[index] = value;
+ }
+
+ fn ty(&self, index: usize) -> GlobalType {
+ self.types[index]
+ }
+}
+
+/// Global instances split into their physical value lanes.
///
-/// See <https://webassembly.github.io/spec/core/exec/runtime.html#global-instances>
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) struct GlobalInstance {
- pub(crate) value: TinyWasmValue,
- pub(crate) ty: GlobalType,
+/// Guest values should normally be accessed through
+/// [`InternalValue`](crate::interpreter::InternalValue). Dynamic access is
+/// reserved for initialization and host boundaries.
+#[derive(Default)]
+pub(crate) struct Globals {
+ globals_32: GlobalLane<Value32>,
+ globals_64: GlobalLane<Value64>,
+ globals_128: GlobalLane<Value128>,
}
-impl GlobalInstance {
- pub(crate) fn new(ty: GlobalType, value: TinyWasmValue) -> Self {
- Self { ty, value }
+impl Globals {
+ const LANE_SHIFT: u32 = 30;
+ const INDEX_MASK: u32 = (1 << Self::LANE_SHIFT) - 1;
+ const LANE_32: u32 = 0;
+ const LANE_64: u32 = 1 << Self::LANE_SHIFT;
+ const LANE_128: u32 = 2 << Self::LANE_SHIFT;
+
+ pub(crate) fn reserve(&mut self, globals: &[Global]) {
+ let (mut count_32, mut count_64, mut count_128) = (0, 0, 0);
+ for global in globals {
+ match global.ty.ty {
+ WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => count_32 += 1,
+ WasmType::I64 | WasmType::F64 => count_64 += 1,
+ WasmType::V128 => count_128 += 1,
+ }
+ }
+ self.globals_32.reserve(count_32);
+ self.globals_64.reserve(count_64);
+ self.globals_128.reserve(count_128);
+ }
+
+ fn addr(lane: u32, index: usize) -> GlobalAddr {
+ assert!(index <= Self::INDEX_MASK as usize, "too many globals in one value lane");
+ lane | index as u32
+ }
+
+ #[inline(always)]
+ fn index(addr: GlobalAddr, lane: u32) -> usize {
+ debug_assert_eq!(addr & !Self::INDEX_MASK, lane, "global address has the wrong value lane");
+ (addr & Self::INDEX_MASK) as usize
+ }
+
+ /// Returns a global's logical type and mutability.
+ pub(crate) fn ty(&self, addr: GlobalAddr) -> GlobalType {
+ match addr & !Self::INDEX_MASK {
+ Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32)),
+ Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64)),
+ Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128)),
+ _ => unreachable!("invalid global address: {addr}"),
+ }
+ }
+
+ /// Adds a global and returns its packed store address.
+ pub(crate) fn push(&mut self, ty: GlobalType, value: RuntimeValue) -> GlobalAddr {
+ match (ty.ty, value) {
+ (WasmType::I32 | WasmType::F32, RuntimeValue::Value32(value)) => {
+ Self::addr(Self::LANE_32, self.globals_32.push(ty, value))
+ }
+ (WasmType::Ref(_), RuntimeValue::ValueRef(value)) => {
+ Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw()))
+ }
+ (WasmType::I64 | WasmType::F64, RuntimeValue::Value64(value)) => {
+ Self::addr(Self::LANE_64, self.globals_64.push(ty, value))
+ }
+ (WasmType::V128, RuntimeValue::Value128(value)) => {
+ Self::addr(Self::LANE_128, self.globals_128.push(ty, value))
+ }
+ _ => unreachable!("global value does not match its declared type"),
+ }
+ }
+
+ /// Returns a raw value from the 32-bit lane.
+ #[inline(always)]
+ pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 {
+ self.globals_32.get(Self::index(addr, Self::LANE_32))
+ }
+
+ /// Returns a raw value from the 64-bit lane.
+ #[inline(always)]
+ pub(crate) fn get_64(&self, addr: GlobalAddr) -> Value64 {
+ self.globals_64.get(Self::index(addr, Self::LANE_64))
+ }
+
+ /// Returns a raw value from the 128-bit lane.
+ #[inline(always)]
+ pub(crate) fn get_128(&self, addr: GlobalAddr) -> Value128 {
+ self.globals_128.get(Self::index(addr, Self::LANE_128))
+ }
+
+ /// Sets a raw value in the 32-bit lane.
+ #[inline(always)]
+ pub(crate) fn set_32(&mut self, addr: GlobalAddr, value: Value32) {
+ self.globals_32.set(Self::index(addr, Self::LANE_32), value);
+ }
+
+ /// Sets a raw value in the 64-bit lane.
+ #[inline(always)]
+ pub(crate) fn set_64(&mut self, addr: GlobalAddr, value: Value64) {
+ self.globals_64.set(Self::index(addr, Self::LANE_64), value);
+ }
+
+ /// Sets a raw value in the 128-bit lane.
+ #[inline(always)]
+ pub(crate) fn set_128(&mut self, addr: GlobalAddr, value: Value128) {
+ self.globals_128.set(Self::index(addr, Self::LANE_128), value);
+ }
+
+ /// Iterates over globals in the 32-bit lane for root tracing.
+ pub(crate) fn globals_32(&self) -> impl Iterator<Item = (&Value32, &GlobalType)> {
+ self.globals_32.values.iter().zip(&self.globals_32.types)
}
}
diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs
index be0f3b4..9da327b 100644
--- a/crates/tinywasm/src/store/memory/instance.rs
+++ b/crates/tinywasm/src/store/memory/instance.rs
@@ -1,10 +1,10 @@
-use alloc::format;
use tinywasm_types::{MemoryArch, MemoryType};
-use crate::{Error, MemoryBackend, Result, Trap};
+use crate::{Error, ResourceLimiter, Result, Trap};
use super::{MemoryStorage, memory_oob};
-use core::hint::cold_path;
+
+const MEMORY64_MAX_BYTES: u64 = 16 * 1024 * 1024 * 1024;
/// A WebAssembly Memory Instance
///
@@ -23,44 +23,54 @@ impl core::fmt::Debug for MemoryInstance {
}
impl MemoryInstance {
- const COPY_CHUNK_SIZE: usize = 4 * 1024;
+ #[inline]
+ fn host_size(kind: MemoryType, pages: u64) -> Option<usize> {
+ pages.checked_mul(kind.page_size()).and_then(|size| usize::try_from(size).ok())
+ }
- #[inline(always)]
- pub(crate) fn effective_addr_32<const N: usize>(&self, base: u32, offset: u64) -> Result<usize, Trap> {
- #[cfg(target_pointer_width = "64")]
- {
- debug_assert!(u32::try_from(offset).is_ok(), "validated memory32 offsets fit in u32");
- Ok(base as usize + offset as usize)
- }
+ #[inline]
+ fn maximum_size(kind: MemoryType) -> Option<usize> {
+ kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX))
+ }
- #[cfg(not(target_pointer_width = "64"))]
- {
- match usize::try_from(u64::from(base) + offset) {
- Ok(addr) => Ok(addr),
- Err(_) => {
- cold_path();
- Err(memory_oob(base as usize, N, self.inner.len()))
- }
- }
+ #[inline]
+ fn page_count_max(kind: MemoryType) -> u64 {
+ match kind.arch() {
+ MemoryArch::I32 => kind.page_count_max(),
+ MemoryArch::I64 => kind.page_count_max().min(MEMORY64_MAX_BYTES / kind.page_size()),
}
}
+ #[cfg(target_pointer_width = "64")]
#[inline(always)]
- pub(crate) fn effective_addr_64<const N: usize>(&self, base: u64, offset: u64) -> Result<usize, Trap> {
- match base.checked_add(offset).and_then(|addr| usize::try_from(addr).ok()) {
+ pub(crate) fn effective_addr<const N: usize>(&self, base: usize, offset: u64) -> Result<usize, Trap> {
+ match base.checked_add(offset as usize) {
Some(addr) => Ok(addr),
- None => {
- cold_path();
- Err(memory_oob(base as usize, N, self.inner.len()))
- }
+ None => cold!(Err(memory_oob(base, N, self.inner.len()))),
}
}
- pub(crate) fn new(kind: MemoryType, backend: &MemoryBackend) -> Result<Self> {
- assert!(kind.page_count_initial() <= kind.page_count_max());
+ #[cfg(not(target_pointer_width = "64"))]
+ #[inline(always)]
+ pub(crate) fn effective_addr<const N: usize>(&self, base: usize, offset: u64) -> Result<usize, Trap> {
+ match usize::try_from(offset).ok().and_then(|offset| base.checked_add(offset)) {
+ Some(addr) => Ok(addr),
+ None => cold!(Err(memory_oob(base, N, self.inner.len()))),
+ }
+ }
- let initial_len = usize::try_from(kind.initial_size())
- .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?;
+ pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result<Self> {
+ if kind.page_size() == 0 {
+ return Err(Error::UnsupportedFeature("zero-byte memory pages"));
+ }
+ let max_pages = Self::page_count_max(kind);
+ if kind.page_count_initial() > max_pages {
+ return Err(Trap::OutOfMemory.into());
+ }
+ let initial_len = cold_err!(
+ Self::host_size(kind, kind.page_count_initial())
+ .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))
+ )?;
crate::log::debug!(
"initializing memory with {} pages of {} bytes",
@@ -68,30 +78,15 @@ impl MemoryInstance {
kind.page_size()
);
- let storage = backend.create(kind, initial_len)?;
- if storage.len() != initial_len {
- return Err(Error::Other(format!(
- "memory backend returned {} bytes for a memory that requires {initial_len}",
- storage.len()
- )));
+ if initial_len != 0
+ && let Some(limiter) = limiter
+ && !limiter.memory_growing(0, initial_len, Self::maximum_size(kind))?
+ {
+ return cold!(Err(Trap::OutOfMemory.into()));
}
- Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize })
- }
-
- pub(crate) fn new_lazy(kind: MemoryType, backend: &MemoryBackend) -> Result<Self> {
- assert!(kind.page_count_initial() <= kind.page_count_max());
-
- let initial_len = usize::try_from(kind.initial_size())
- .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?;
-
- crate::log::debug!(
- "initializing lazy memory with {} pages of {} bytes",
- kind.page_count_initial(),
- kind.page_size()
- );
-
- let storage = backend.create_lazy(kind, initial_len)?;
+ let max_len = Self::host_size(kind, max_pages).unwrap_or(usize::MAX);
+ let storage = MemoryStorage::try_new(kind.arch(), initial_len, max_len)?;
Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize })
}
@@ -102,98 +97,51 @@ impl MemoryInstance {
pub(crate) fn copy_from_memory(
&mut self,
dst: usize,
- src_memory: &MemoryInstance,
+ src_mem: &MemoryInstance,
src: usize,
len: usize,
) -> Result<(), Trap> {
- fn check_range(mem: &MemoryStorage, addr: usize, len: usize) -> Result<(), crate::Trap> {
- let Some(end) = addr.checked_add(len) else {
- cold_path();
- return Err(memory_oob(addr, len, mem.len()));
- };
-
- if end > mem.len() || end < addr {
- cold_path();
- return Err(memory_oob(addr, len, mem.len()));
- }
- Ok(())
- }
-
- check_range(&src_memory.inner, src, len)?;
- check_range(&self.inner, dst, len)?;
-
- if len == 0 {
- return Ok(());
- }
-
- let mut buf = [0u8; Self::COPY_CHUNK_SIZE];
- let mut copied = 0;
- while copied < len {
- let chunk_len = buf.len().min(len - copied);
- src_memory.inner.read_exact(src + copied, &mut buf[..chunk_len]).ok_or_else(|| {
- cold_path();
- memory_oob(src + copied, chunk_len, src_memory.inner.len())
- })?;
- self.inner.write_all(dst + copied, &buf[..chunk_len]).ok_or_else(|| {
- cold_path();
- memory_oob(dst + copied, chunk_len, self.inner.len())
- })?;
- copied += chunk_len;
- }
-
- Ok(())
+ self.inner.copy_from(dst, &src_mem.inner, src, len)
}
pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result<(), Trap> {
- self.inner.copy_within(dst, src, len).ok_or_else(|| {
- cold_path();
- memory_oob(dst, len, self.inner.len())
- })
+ cold_err!(self.inner.copy_within(dst, src, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))
}
- pub(crate) fn grow(&mut self, pages_delta: i64, trap_on_oom: bool) -> Result<Option<i64>, Trap> {
- if pages_delta < 0 {
- cold_path();
- crate::log::debug!("memory.grow failed: negative delta {}", pages_delta);
- return Ok(None);
- }
-
+ pub(crate) fn grow(
+ &mut self,
+ pages_delta: i64,
+ limiter: Option<&dyn ResourceLimiter>,
+ ) -> Result<Option<i64>, Trap> {
let current_pages = self.page_count;
- let Some(pages_delta) = usize::try_from(pages_delta).ok() else {
- return Ok(None);
+ let Some(new_pages) = usize::try_from(pages_delta).ok().and_then(|delta| current_pages.checked_add(delta))
+ else {
+ return cold!(Ok(None));
};
- let Some(new_pages) = current_pages.checked_add(pages_delta) else {
- return Ok(None);
- };
- let max_pages = self.kind.page_count_max().try_into().unwrap_or(usize::MAX);
+ let max_pages = Self::page_count_max(self.kind).try_into().unwrap_or(usize::MAX);
if new_pages > max_pages {
- cold_path();
- crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages);
- return Ok(None);
- }
-
- let Some(new_size) = (new_pages as u64).checked_mul(self.kind.page_size()) else {
- return Ok(None);
- };
- if new_size > self.kind.max_size() {
- cold_path();
- crate::log::debug!("memory.grow failed: new_size={}, max_size={}", new_size, self.kind.max_size());
- return Ok(None);
+ return cold!({
+ crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages);
+ Ok(None)
+ });
}
- let Some(new_size) = usize::try_from(new_size).ok() else {
- return Ok(None);
+ let Some(new_size) = Self::host_size(self.kind, new_pages as u64) else {
+ return cold!(Ok(None));
};
if new_size == self.inner.len() {
return Ok(i64::try_from(current_pages).ok());
}
- if let Err(err) = self.inner.grow_to(new_size) {
- if trap_on_oom {
- return Err(err);
- }
- return Ok(None);
+ if let Some(limiter) = limiter
+ && !limiter.memory_growing(self.inner.len(), new_size, Self::maximum_size(self.kind))?
+ {
+ return cold!(Ok(None));
+ }
+
+ if self.inner.grow_to(new_size).is_err() {
+ return cold!(Ok(None));
}
self.page_count = new_pages;
Ok(i64::try_from(current_pages).ok())
diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs
deleted file mode 100644
index 91759c4..0000000
--- a/crates/tinywasm/src/store/memory/lazy.rs
+++ /dev/null
@@ -1,125 +0,0 @@
-use alloc::boxed::Box;
-use core::hint::cold_path;
-
-use tinywasm_types::MemoryType;
-
-use crate::{Error, MemoryBackend, Result};
-
-use super::LinearMemory;
-
-/// A linear memory wrapper that allocates its backend on the first mutation.
-///
-/// Before materialization, the memory is represented by its logical length and
-/// reads return the zeroes required by WebAssembly semantics.
-pub struct LazyLinearMemory {
- ty: MemoryType,
- initial_len: usize,
- backend: MemoryBackend,
- inner: Option<Box<dyn LinearMemory + Send + Sync>>,
-}
-
-impl LazyLinearMemory {
- /// Creates a lazy memory for `ty` using `backend` for eventual storage.
- pub fn try_new(ty: MemoryType, backend: MemoryBackend) -> Result<Self> {
- let initial_len = usize::try_from(ty.initial_size())
- .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?;
- Ok(Self::new_with_initial_len(ty, initial_len, backend))
- }
-
- pub(crate) fn new_with_initial_len(ty: MemoryType, initial_len: usize, backend: MemoryBackend) -> Self {
- Self { ty, initial_len, backend, inner: None }
- }
-
- fn materialize(&mut self) -> &mut dyn LinearMemory {
- if self.inner.is_none() {
- self.inner =
- Some(self.backend.create(self.ty, self.initial_len).expect("lazy memory materialization failed"));
- }
- self.inner.as_deref_mut().expect("lazy memory should be materialized")
- }
-
- fn try_materialize(&mut self) -> core::result::Result<&mut dyn LinearMemory, crate::Trap> {
- if self.inner.is_none() {
- let storage = match self.backend.create(self.ty, self.initial_len) {
- Ok(storage) => storage,
- Err(Error::Trap(trap)) => {
- cold_path();
- return Err(trap);
- }
- Err(err) => panic!("lazy memory materialization failed: {err}"),
- };
- self.inner = Some(storage);
- }
- Ok(self.inner.as_deref_mut().expect("lazy memory should be materialized"))
- }
-}
-
-impl LinearMemory for LazyLinearMemory {
- fn len(&self) -> usize {
- self.inner.as_deref().map_or(self.initial_len, LinearMemory::len)
- }
-
- fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> {
- self.try_materialize()?.grow_to(new_len)
- }
-
- fn read(&self, addr: usize, dst: &mut [u8]) -> usize {
- if let Some(inner) = self.inner.as_deref() {
- return inner.read(addr, dst);
- }
- if addr >= self.initial_len {
- return 0;
- }
- let read_len = dst.len().min(self.initial_len - addr);
- dst[..read_len].fill(0);
- read_len
- }
-
- fn write(&mut self, addr: usize, src: &[u8]) -> usize {
- if src.is_empty() || addr >= self.len() {
- return 0;
- }
- self.materialize().write(addr, src)
- }
-
- fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> {
- let end = addr.checked_add(src.len())?;
- if end > self.len() {
- return None;
- }
- if src.is_empty() {
- return Some(());
- }
- self.materialize().write_all(addr, src)
- }
-
- fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> {
- let end = addr.checked_add(len)?;
- if end > self.len() {
- return None;
- }
- if len == 0 || val == 0 && self.inner.is_none() {
- return Some(());
- }
- self.materialize().fill(addr, len, val)
- }
-
- fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> {
- let src_end = src.checked_add(len)?;
- let dst_end = dst.checked_add(len)?;
- if src_end > self.len() || dst_end > self.len() {
- return None;
- }
- if self.inner.is_none() || len == 0 || dst == src {
- return Some(());
- }
- self.materialize().copy_within(dst, src, len)
- }
-}
-
-#[cfg(feature = "debug")]
-impl core::fmt::Debug for LazyLinearMemory {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- f.debug_struct("LazyLinearMemory").field("ty", &self.ty).field("materialized", &self.inner.is_some()).finish()
- }
-}
diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs
index 6b36f42..6219c60 100644
--- a/crates/tinywasm/src/store/memory/mod.rs
+++ b/crates/tinywasm/src/store/memory/mod.rs
@@ -1,33 +1,15 @@
-use alloc::{boxed::Box, format, sync::Arc};
-use alloc::{vec, vec::Vec};
-use core::cmp::min;
-use core::hint::cold_path;
-
-use tinywasm_types::MemoryType;
-
use crate::interpreter::Value128;
-use crate::{Error, Result};
mod instance;
-mod lazy;
-
-mod paged;
-#[path = "vec.rs"]
-mod vec_memory;
+mod vec;
pub(crate) use instance::MemoryInstance;
-pub use {lazy::LazyLinearMemory, paged::PagedMemory, vec_memory::VecMemory};
+pub(crate) use vec::VecMemory;
-/// Backend storage for a linear memory
-///
-/// This is a low-level trait that abstracts over the actual storage mechanism for linear memory.
-/// This will probably change in the future to allow more efficient implementations.
-/// See [`MemoryBackend`] for a higher-level interface to configuring memory storage.
-/// The runtime passes slices of the exact indicated width to the fixed-width `write_*` methods.
-pub trait LinearMemory {
- /// Returns the current memory length in bytes.
- fn len(&self) -> usize;
+/// Internal storage for a linear memory.
+pub(crate) type MemoryStorage = VecMemory;
+<<<<<<< HEAD
/// Returns true if the memory is empty.
fn is_empty(&self) -> bool {
self.len() == 0
@@ -352,18 +334,15 @@ pub(crate) type MemoryStorage = Box<dyn LinearMemory + Send + Sync>;
/// A trait for types that can be converted to and from static byte arrays
pub(crate) trait MemValue<const N: usize>: Copy + Default {
- /// Store a value in memory
+ /// Store a value in memory.
fn to_mem_bytes(self) -> [u8; N];
-
fn from_mem_bytes(bytes: [u8; N]) -> Self;
-
- fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result<Self, crate::Trap>;
-
- fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap>;
+ fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result<Self, crate::Trap>;
+ fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap>;
}
macro_rules! impl_mem_traits {
- ($($ty:ty, $size:expr, $read:ident, $write:ident),* $(,)?) => {
+ ($($ty:ty, $size:expr),* $(,)?) => {
$(
impl MemValue<$size> for $ty {
#[inline(always)]
@@ -377,217 +356,43 @@ macro_rules! impl_mem_traits {
}
#[inline(always)]
- fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result<Self, crate::Trap> {
- Ok(Self::from_le_bytes(match mem.$read(addr) {
- Ok(bytes) => bytes,
- Err(trap) => {
- cold_path();
- return Err(trap);
- }
- }))
+ fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result<Self, crate::Trap> {
+ Ok(Self::from_le_bytes(cold_err!(mem.read_fixed::<$size>(addr))?))
}
#[inline(always)]
- fn store_at(
- self,
- mem: &mut dyn LinearMemory,
- addr: usize,
- ) -> core::result::Result<(), crate::Trap> {
- mem.$write(addr, &self.to_mem_bytes())
+ fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> {
+ mem.write_fixed::<$size>(addr, &self.to_mem_bytes())
}
}
)*
};
}
-impl_mem_traits!(
- u8, 1, read_8, write_8, i8, 1, read_8, write_8, u16, 2, read_16, write_16, i16, 2, read_16, write_16, u32, 4,
- read_32, write_32, i32, 4, read_32, write_32, f32, 4, read_32, write_32, u64, 8, read_64, write_64, i64, 8,
- read_64, write_64, f64, 8, read_64, write_64, Value128, 16, read_128, write_128
-);
-
-fn memory_oob(offset: usize, len: usize, max: usize) -> crate::Trap {
- crate::Trap::MemoryOutOfBounds { offset, len, max }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use tinywasm_types::MemoryArch;
-
- fn create_test_memory(kind: MemoryType, backend: MemoryBackend) -> MemoryInstance {
- MemoryInstance::new(kind, &backend).unwrap()
- }
-
- fn test_backends() -> [MemoryBackend; 2] {
- [MemoryBackend::vec(), MemoryBackend::paged(4)]
- }
-
- #[test]
- fn effective_memory_addresses_handle_host_and_wasm_overflow() {
- let memory = create_test_memory(MemoryType::new(MemoryArch::I32, 1, Some(1), None), MemoryBackend::vec());
- assert_eq!(memory.effective_addr_32::<1>(1, 2), Ok(3));
- assert_eq!(memory.effective_addr_64::<1>(1, 2), Ok(3));
- assert!(memory.effective_addr_64::<1>(u64::MAX, 1).is_err());
-
- #[cfg(target_pointer_width = "64")]
- assert_eq!(
- memory.effective_addr_32::<1>(u32::MAX, u64::from(u32::MAX)),
- Ok(usize::try_from(u64::from(u32::MAX) * 2).unwrap())
- );
-
- #[cfg(target_pointer_width = "32")]
- assert!(memory.effective_addr_32::<1>(u32::MAX, 1).is_err());
- }
-
- #[test]
- fn memory_copy_from_slice_and_read_vec_work() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2, 3, 4];
- assert!(memory.inner.write_all(0, &data).is_some());
- assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data);
- }
- }
-
- #[test]
- fn memory_read_returns_partial_count() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4));
- let memory = create_test_memory(kind, backend);
- let mut dst = [9; 8];
- assert_eq!(memory.inner.read(2, &mut dst), 2);
- assert_eq!(&dst[..2], &[0, 0]);
- assert_eq!(&dst[2..], &[9; 6]);
- }
- }
-
- #[test]
- fn memory_copy_from_slice_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2, 3, 4];
- let len = memory.inner.len();
- assert!(memory.inner.write_all(len, &data).is_none());
- }
- }
-
- #[test]
- fn fixed_width_access_out_of_bounds_traps() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let len = memory.inner.len();
-
- assert!(memory.inner.read_8(len).is_err());
- assert!(memory.inner.read_32(len - 3).is_err());
- assert!(memory.inner.write_8(len, &[0]).is_err());
- assert!(memory.inner.write_32(len - 3, &[0; 4]).is_err());
- }
- }
-
- #[test]
- fn memory_fill_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert!(memory.inner.fill(0, 10, 42).is_some());
- assert_eq!(memory.inner.read_vec(0, 10).unwrap(), vec![42; 10]);
- }
- }
-
- #[test]
- fn memory_fill_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let len = memory.inner.len();
- assert!(memory.inner.fill(len, 10, 42).is_none());
- }
- }
+impl_mem_traits!(u8, 1, i8, 1, u16, 2, i16, 2, u32, 4, i32, 4, f32, 4, u64, 8, i64, 8, f64, 8);
- #[test]
- fn memory_copy_within_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- memory.inner.fill(0, 10, 1).unwrap();
- assert!(memory.copy_within(10, 0, 10).is_ok());
- assert_eq!(memory.inner.read_vec(10, 10).unwrap(), vec![1; 10]);
- }
+impl MemValue<16> for Value128 {
+ #[inline(always)]
+ fn to_mem_bytes(self) -> [u8; 16] {
+ self.0
}
- #[test]
- fn memory_copy_within_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert!(memory.copy_within(memory.inner.len(), 0, 10).is_err());
- }
+ #[inline(always)]
+ fn from_mem_bytes(bytes: [u8; 16]) -> Self {
+ Self(bytes)
}
- #[test]
- fn memory_grow_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let original_pages = memory.page_count;
- assert_eq!(memory.grow(1, false).unwrap(), Some(original_pages as i64));
- assert_eq!(memory.page_count, original_pages + 1);
- }
+ #[inline(always)]
+ fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result<Self, crate::Trap> {
+ Ok(Self(cold_err!(mem.read_fixed::<16>(addr))?))
}
- #[test]
- fn memory_grow_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(memory.kind.max_size() as i64 + 1, false).unwrap(), None);
- }
- }
-
- #[test]
- fn memory_grow_respects_max_pages() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(1, false).unwrap(), Some(1));
- assert_eq!(memory.grow(1, false).unwrap(), None);
- }
- }
-
- #[test]
- fn memory_grow_negative_delta_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None);
- let mut memory = create_test_memory(kind, backend);
- let original_pages = memory.page_count;
- assert_eq!(memory.grow(-1, false).unwrap(), None);
- assert_eq!(memory.page_count, original_pages);
- }
- }
-
- #[test]
- fn memory_custom_page_size_out_of_bounds_fails() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1));
- let mut memory = create_test_memory(kind, backend);
- let data = [1, 2];
- assert!(memory.inner.write_all(0, &data).is_none());
- }
+ #[inline(always)]
+ fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> {
+ mem.write_fixed::<16>(addr, &self.0)
}
+}
- #[test]
- fn memory_custom_page_size_grow_works() {
- for backend in test_backends() {
- let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1));
- let mut memory = create_test_memory(kind, backend);
- assert_eq!(memory.grow(1, false).unwrap(), Some(1));
- let data = [1, 2];
- assert!(memory.inner.write_all(0, &data).is_some());
- assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data);
- }
- }
+const fn memory_oob(offset: usize, len: usize, max: usize) -> crate::Trap {
+ crate::Trap::MemoryOutOfBounds { offset, len, max }
}
diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs
deleted file mode 100644
index 6ae65af..0000000
--- a/crates/tinywasm/src/store/memory/paged.rs
+++ /dev/null
@@ -1,344 +0,0 @@
-use alloc::boxed::Box;
-use alloc::vec::Vec;
-use core::cmp::min;
-use core::hint::cold_path;
-
-use super::{LinearMemory, memory_oob};
-
-/// A sparse chunked linear memory.
-///
-/// This backend stores memory in fixed-size chunks, which makes growth cheaper because it avoids
-/// resizing and copying one large contiguous buffer.
-///
-/// The tradeoff is that reads and writes do a bit more bookkeeping and may need to cross chunk
-/// boundaries, so they are usually slightly slower than [`super::VecMemory`].
-///
-/// In particular, [`LinearMemory::read`] and [`LinearMemory::write`] return at most the bytes up to
-/// the end of the current chunk. Higher-level exact helpers loop over these short operations when
-/// they need a full range.
-pub struct PagedMemory {
- len: usize,
- chunk_size: usize,
- chunk_shift: u32,
- chunk_mask: usize,
- chunks: Vec<Option<Box<[u8]>>>,
-}
-
-impl PagedMemory {
- /// Tries to create a new sparse memory with `len` addressable bytes and the given `chunk_size`.
- ///
- /// Prefer this backend when grow behavior matters more than absolute read and write speed.
- pub fn try_new(len: usize, chunk_size: usize) -> Result<Self, crate::Trap> {
- assert!(chunk_size.is_power_of_two(), "chunk_size must be a power of two");
-
- let mut memory = Self {
- len: 0,
- chunk_size,
- chunk_shift: chunk_size.trailing_zeros(),
- chunk_mask: chunk_size - 1,
- chunks: Vec::new(),
- };
- memory.grow_to(len)?;
- Ok(memory)
- }
-
- #[inline(always)]
- fn allocate_chunk(&self) -> Result<Box<[u8]>, crate::Trap> {
- let mut chunk = Vec::new();
- match chunk.try_reserve_exact(self.chunk_size) {
- Ok(()) => {}
- Err(_) => {
- cold_path();
- return Err(crate::Trap::OutOfMemory);
- }
- }
- chunk.resize(self.chunk_size, 0);
- Ok(chunk.into_boxed_slice())
- }
-
- #[inline(always)]
- fn chunk_mut(&mut self, chunk_idx: usize) -> Result<&mut [u8], crate::Trap> {
- if self.chunks[chunk_idx].is_none() {
- self.chunks[chunk_idx] = Some(self.allocate_chunk()?);
- }
-
- Ok(self.chunks[chunk_idx].as_deref_mut().unwrap_or_else(|| unreachable!()))
- }
-
- #[inline(always)]
- fn chunk_slice(&self, chunk_idx: usize) -> Option<&[u8]> {
- self.chunks[chunk_idx].as_deref()
- }
-
- #[inline(always)]
- fn checked_end(&self, addr: usize, len: usize) -> Option<usize> {
- let end = addr.checked_add(len)?;
- if end > self.len {
- return None;
- }
- Some(end)
- }
-
- #[inline(always)]
- fn copy_within_single_chunk(&mut self, dst: usize, src: usize, len: usize) -> bool {
- if len == 0 {
- return true;
- }
-
- if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() {
- return false;
- }
-
- let src_chunk_idx = src >> self.chunk_shift;
- let dst_chunk_idx = dst >> self.chunk_shift;
- if src_chunk_idx != dst_chunk_idx {
- return false;
- }
-
- let src_offset = src & self.chunk_mask;
- let dst_offset = dst & self.chunk_mask;
- if src_offset + len > self.chunk_size || dst_offset + len > self.chunk_size {
- return false;
- }
-
- if let Some(Some(chunk)) = self.chunks.get_mut(src_chunk_idx) {
- chunk.copy_within(src_offset..src_offset + len, dst_offset);
- }
-
- true
- }
-}
-
-#[cfg(feature = "debug")]
-impl core::fmt::Debug for PagedMemory {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- let allocated_chunks = self.chunks.iter().filter(|chunk| chunk.is_some()).count();
- f.debug_struct("PagedMemory")
- .field("len", &self.len)
- .field("chunk_size", &self.chunk_size)
- .field("allocated_chunks", &allocated_chunks)
- .finish()
- }
-}
-
-impl LinearMemory for PagedMemory {
- #[inline(always)]
- fn len(&self) -> usize {
- self.len
- }
-
- #[inline(always)]
- fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> {
- if new_len < self.len {
- return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.len });
- }
-
- let new_chunk_count = if new_len == 0 { 0 } else { new_len.div_ceil(self.chunk_size) };
- if new_chunk_count > self.chunks.len() {
- match self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len()) {
- Ok(()) => {}
- Err(_) => {
- cold_path();
- return Err(crate::Trap::OutOfMemory);
- }
- }
- self.chunks.resize_with(new_chunk_count, || None);
- } else {
- self.chunks.truncate(new_chunk_count);
- }
-
- self.len = new_len;
- Ok(())
- }
-
- #[inline(always)]
- fn read(&self, addr: usize, dst: &mut [u8]) -> usize {
- if addr >= self.len || dst.is_empty() {
- return 0;
- }
-
- let chunk_idx = addr >> self.chunk_shift;
- let chunk_offset = addr & self.chunk_mask;
- let chunk_end = min((chunk_idx + 1) << self.chunk_shift, self.len);
- let read_len = min(chunk_end - addr, dst.len());
- if let Some(chunk) = self.chunk_slice(chunk_idx) {
- dst[..read_len].copy_from_slice(&chunk[chunk_offset..chunk_offset + read_len]);
- } else {
- dst[..read_len].fill(0);
- }
-
- read_len
- }
-
- #[inline(always)]
- fn write(&mut self, addr: usize, src: &[u8]) -> usize {
- if addr >= self.len || src.is_empty() {
- return 0;
- }
-
- let chunk_idx = addr >> self.chunk_shift;
- let chunk_offset = addr & self.chunk_mask;
- let write_len = min(min(self.chunk_size - chunk_offset, self.len - addr), src.len());
-
- let Ok(chunk) = self.chunk_mut(chunk_idx) else {
- return 0;
- };
- chunk[chunk_offset..chunk_offset + write_len].copy_from_slice(&src[..write_len]);
- write_len
- }
-
- #[inline(always)]
- fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> {
- let end = self.checked_end(addr, src.len())?;
- let mut pos = addr;
- let mut src_offset = 0;
-
- while pos < end {
- let chunk_idx = pos >> self.chunk_shift;
- let chunk_offset = pos & self.chunk_mask;
- let copy_len = min(self.chunk_size - chunk_offset, end - pos);
-
- let chunk = self.chunk_mut(chunk_idx).ok()?;
- chunk[chunk_offset..chunk_offset + copy_len].copy_from_slice(&src[src_offset..src_offset + copy_len]);
-
- pos += copy_len;
- src_offset += copy_len;
- }
-
- Some(())
- }
-
- #[inline(always)]
- fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> {
- let end = self.checked_end(addr, len)?;
- let mut pos = addr;
-
- while pos < end {
- let chunk_idx = pos >> self.chunk_shift;
- let chunk_offset = pos & self.chunk_mask;
- let chunk_start = chunk_idx << self.chunk_shift;
- let chunk_full_len = min(self.chunk_size, self.len - chunk_start);
- let chunk_end = min(chunk_start + self.chunk_size, end);
- let fill_len = chunk_end - pos;
-
- if val == 0 {
- if chunk_offset == 0 && fill_len == chunk_full_len {
- self.chunks[chunk_idx] = None;
- } else if let Some(Some(chunk)) = self.chunks.get_mut(chunk_idx) {
- chunk[chunk_offset..chunk_offset + fill_len].fill(0);
- }
- } else {
- self.chunk_mut(chunk_idx).ok()?[chunk_offset..chunk_offset + fill_len].fill(val);
- }
-
- pos = chunk_end;
- }
-
- Some(())
- }
-
- #[inline(always)]
- fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> {
- self.checked_end(src, len)?;
- self.checked_end(dst, len)?;
-
- if len == 0 || dst == src {
- return Some(());
- }
-
- if self.copy_within_single_chunk(dst, src, len) {
- return Some(());
- }
-
- let mut buf = [0u8; 256];
-
- if dst < src || dst >= src + len {
- let mut copied = 0;
- while copied < len {
- let chunk_len = min(buf.len(), len - copied);
- self.read_exact(src + copied, &mut buf[..chunk_len])?;
- self.write_all(dst + copied, &buf[..chunk_len])?;
- copied += chunk_len;
- }
- } else {
- let mut remaining = len;
- while remaining > 0 {
- let chunk_len = min(buf.len(), remaining);
- let chunk_start = remaining - chunk_len;
- self.read_exact(src + chunk_start, &mut buf[..chunk_len])?;
- self.write_all(dst + chunk_start, &buf[..chunk_len])?;
- remaining = chunk_start;
- }
- }
-
- Some(())
- }
-
- #[inline(always)]
- fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> {
- if addr >= self.len {
- cold_path();
- return Err(memory_oob(addr, 1, self.len));
- }
- let chunk_idx = addr >> self.chunk_shift;
- let chunk_offset = addr & self.chunk_mask;
- Ok([self.chunk_slice(chunk_idx).map_or(0, |chunk| chunk[chunk_offset])])
- }
-
- #[inline(always)]
- fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- if addr >= self.len {
- cold_path();
- return Err(memory_oob(addr, 1, self.len));
- }
- let chunk_idx = addr >> self.chunk_shift;
- let chunk_offset = addr & self.chunk_mask;
- self.chunk_mut(chunk_idx)?[chunk_offset] = bytes[0];
- Ok(())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::{LinearMemory, PagedMemory};
-
- #[test]
- fn paged_memory_reads_zeroes_from_sparse_chunks() {
- let memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- let mut dst = [1; 6];
- assert_eq!(memory.read(5, &mut dst), 3);
- assert_eq!(&dst[..3], &[0; 3]);
- assert_eq!(&dst[3..], &[1; 3]);
- }
-
- #[test]
- fn paged_memory_store_and_load_crosses_chunk_boundaries() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- memory.write_all(3, &[1, 2, 3, 4, 5, 6]).unwrap();
-
- let mut dst = [0; 6];
- memory.read_exact(3, &mut dst).unwrap();
- assert_eq!(dst, [1, 2, 3, 4, 5, 6]);
- }
-
- #[test]
- fn paged_memory_copy_within_handles_overlap() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- memory.write_all(0, &[1, 2, 3, 4, 5, 6]).unwrap();
- memory.copy_within(2, 0, 6).unwrap();
-
- let mut dst = [0; 8];
- memory.read_exact(0, &mut dst).unwrap();
- assert_eq!(dst, [1, 2, 1, 2, 3, 4, 5, 6]);
- }
-
- #[test]
- fn paged_memory_write_stops_at_chunk_boundary() {
- let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible");
- assert_eq!(memory.write(3, &[1, 2, 3, 4]), 1);
-
- let mut dst = [0; 4];
- memory.read_exact(3, &mut dst).unwrap();
- assert_eq!(dst, [1, 0, 0, 0]);
- }
-}
diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs
index 2737159..b14f54d 100644
--- a/crates/tinywasm/src/store/memory/vec.rs
+++ b/crates/tinywasm/src/store/memory/vec.rs
@@ -1,77 +1,87 @@
use alloc::vec::Vec;
-use core::hint::cold_path;
+use core::ops::Range;
+use tinywasm_types::MemoryArch;
-use super::{LinearMemory, memory_oob};
+use super::memory_oob;
-/// A contiguous `Vec<u8>`-backed linear memory.
+/// A contiguous `Vec<u8>`-backed linear memory storage.
///
-/// This is the simplest backend and typically gives the best read and write throughput because
-/// the whole memory lives in one contiguous allocation.
-///
-/// The tradeoff is growth cost: large grows may need to reallocate and copy the full buffer,
-/// which can get expensive for large memories.
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct VecMemory {
+/// This is the default internal storage for [`super::MemoryInstance`].
+pub(crate) struct VecMemory {
data: Vec<u8>,
}
impl VecMemory {
+ /// Returns a raw mutable pointer to the memory's backing allocation.
+ /// Growth may invalidate the pointer. The caller must keep the store alive
+ /// and uphold Rust's aliasing rules when dereferencing it.
+ pub(crate) fn data_ptr(&mut self) -> *mut u8 {
+ self.data.as_mut_ptr()
+ }
+
+ /// Borrows the backing bytes.
+ pub(crate) fn data(&self) -> &[u8] {
+ &self.data
+ }
+
+ /// Borrows the backing bytes exclusively.
+ pub(crate) fn data_mut(&mut self) -> &mut [u8] {
+ &mut self.data
+ }
+
/// Tries to create a new memory with `len` zero-initialized bytes.
- ///
- /// Prefer this backend when contiguous access is more important than grow performance.
- pub fn try_new(len: usize) -> Result<Self, crate::Trap> {
+ pub(crate) fn try_new(_arch: MemoryArch, len: usize, _max_len: usize) -> Result<Self, crate::Trap> {
let mut data = Vec::new();
- match data.try_reserve_exact(len) {
- Ok(()) => {}
- Err(_) => {
- cold_path();
- return Err(crate::Trap::OutOfMemory);
- }
- }
+ cold_err!(data.try_reserve(len)).map_err(|_| crate::Trap::OutOfMemory)?;
data.resize(len, 0);
Ok(Self { data })
}
#[inline(always)]
- fn read_fixed<const N: usize>(&self, addr: usize) -> Result<[u8; N], crate::Trap> {
- self.check_fixed_addr::<N>(addr)?;
- Ok(self.data[addr..addr + N].try_into().unwrap_or_else(|_| unreachable!("slice length should be {N}")))
+ pub(crate) fn len(&self) -> usize {
+ self.data.len()
}
#[inline(always)]
- fn check_fixed_addr<const N: usize>(&self, addr: usize) -> Result<(), crate::Trap> {
- if N > self.data.len() || addr > self.data.len() - N {
- cold_path();
- return Err(memory_oob(addr, N, self.data.len()));
- }
- Ok(())
+ pub(super) fn checked_range(&self, addr: usize, len: usize) -> Option<Range<usize>> {
+ let end = addr.checked_add(len)?;
+ (end <= self.data.len()).then_some(addr..end)
}
-}
-impl LinearMemory for VecMemory {
+ /// Grows the backing allocation to `new_len`. Only called after the Wasm limits and any user
+ /// limiter have accepted the grow.
#[inline(always)]
- fn len(&self) -> usize {
- self.data.len()
+ pub(crate) fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> {
+ debug_assert!(new_len >= self.data.len(), "memory only grows");
+ cold_err!(self.data.try_reserve(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?;
+ self.data.resize(new_len, 0);
+ Ok(())
}
+ /// Reads exactly `N` bytes at `addr` into a fixed-size array.
#[inline(always)]
- fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> {
- if new_len < self.data.len() {
- return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.data.len() });
+ pub(crate) fn read_fixed<const N: usize>(&self, addr: usize) -> Result<[u8; N], crate::Trap> {
+ if N > self.data.len() || addr > self.data.len() - N {
+ return cold!(Err(memory_oob(addr, N, self.data.len())));
}
- match self.data.try_reserve_exact(new_len.saturating_sub(self.data.len())) {
- Ok(()) => {}
- Err(_) => {
- cold_path();
- return Err(crate::Trap::OutOfMemory);
- }
+ let mut bytes = [0u8; N];
+ bytes.copy_from_slice(&self.data[addr..addr + N]);
+ Ok(bytes)
+ }
+
+ /// Writes exactly `N` bytes from `bytes` at `addr`.
+ #[inline(always)]
+ pub(crate) fn write_fixed<const N: usize>(&mut self, addr: usize, bytes: &[u8; N]) -> Result<(), crate::Trap> {
+ if N > self.data.len() || addr > self.data.len() - N {
+ return cold!(Err(memory_oob(addr, N, self.data.len())));
}
- self.data.resize(new_len, 0);
+ self.data[addr..addr + N].copy_from_slice(bytes);
Ok(())
}
+ /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read.
#[inline(always)]
- fn read(&self, addr: usize, dst: &mut [u8]) -> usize {
+ pub(crate) fn read(&self, addr: usize, dst: &mut [u8]) -> usize {
if addr >= self.data.len() {
return 0;
}
@@ -80,111 +90,70 @@ impl LinearMemory for VecMemory {
read_len
}
+ /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written.
#[inline(always)]
- fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> {
- dst.copy_from_slice(self.data.get(addr..addr.checked_add(dst.len())?)?);
- Some(())
- }
-
- #[inline(always)]
- fn read_vec(&self, addr: usize, len: usize) -> Option<Vec<u8>> {
- Some(self.data.get(addr..addr.checked_add(len)?)?.to_vec())
- }
-
- #[inline(always)]
- fn write(&mut self, addr: usize, src: &[u8]) -> usize {
+ pub(crate) fn write(&mut self, addr: usize, src: &[u8]) -> usize {
if addr >= self.data.len() {
return 0;
}
-
let write_len = src.len().min(self.data.len() - addr);
self.data[addr..addr + write_len].copy_from_slice(&src[..write_len]);
write_len
}
+ /// Reads exactly `dst.len()` bytes starting at `addr`, returning `None` for an invalid range.
#[inline(always)]
- fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> {
- let dst = self.data.get_mut(addr..addr.checked_add(src.len())?)?;
- dst.copy_from_slice(src);
+ pub(crate) fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> {
+ dst.copy_from_slice(&self.data[self.checked_range(addr, dst.len())?]);
Some(())
}
+ /// Reads `len` bytes starting at `addr` into a newly allocated buffer, returning `None` for an
+ /// invalid range.
#[inline(always)]
- fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> {
- self.data.get_mut(addr..addr.checked_add(len)?)?.fill(val);
- Some(())
+ pub(crate) fn read_vec(&self, addr: usize, len: usize) -> Option<Vec<u8>> {
+ Some(self.data[self.checked_range(addr, len)?].to_vec())
}
+ /// Writes all of `src` at `addr`, returning `None` for an invalid range.
#[inline(always)]
- fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> {
- let src_end = src.checked_add(len)?;
- let dst_end = dst.checked_add(len)?;
- if src_end > self.data.len() || dst_end > self.data.len() {
- return None;
- }
-
- self.data.copy_within(src..src_end, dst);
+ pub(crate) fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> {
+ let range = self.checked_range(addr, src.len())?;
+ self.data[range].copy_from_slice(src);
Some(())
}
+ /// Fills the range `[addr, addr + len)` with `val`, returning `None` for an invalid range.
#[inline(always)]
- fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> {
- self.check_fixed_addr::<1>(addr)?;
- Ok([self.data[addr]])
- }
-
- #[inline(always)]
- fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> {
- self.read_fixed::<2>(addr)
- }
-
- #[inline(always)]
- fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> {
- self.read_fixed::<4>(addr)
- }
-
- #[inline(always)]
- fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> {
- self.read_fixed::<8>(addr)
- }
-
- #[inline(always)]
- fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> {
- self.read_fixed::<16>(addr)
- }
-
- #[inline(always)]
- fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- self.check_fixed_addr::<1>(addr)?;
- self.data[addr] = bytes[0];
- Ok(())
- }
-
- #[inline(always)]
- fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- self.check_fixed_addr::<2>(addr)?;
- self.data[addr..addr + 2].copy_from_slice(bytes);
- Ok(())
- }
-
- #[inline(always)]
- fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- self.check_fixed_addr::<4>(addr)?;
- self.data[addr..addr + 4].copy_from_slice(bytes);
- Ok(())
+ pub(crate) fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> {
+ let range = self.checked_range(addr, len)?;
+ self.data[range].fill(val);
+ Some(())
}
+ /// Copies `len` bytes from `src` to `dst` within the memory, returning `None` for an invalid
+ /// range.
#[inline(always)]
- fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- self.check_fixed_addr::<8>(addr)?;
- self.data[addr..addr + 8].copy_from_slice(bytes);
- Ok(())
+ pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> {
+ let src = self.checked_range(src, len)?;
+ self.checked_range(dst, len)?;
+ self.data.copy_within(src, dst);
+ Some(())
}
+ /// Copies from another memory, checking both ranges before mutation and reporting source errors first.
#[inline(always)]
- fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> {
- self.check_fixed_addr::<16>(addr)?;
- self.data[addr..addr + 16].copy_from_slice(bytes);
+ pub(super) fn copy_from(
+ &mut self,
+ dst: usize,
+ src_memory: &Self,
+ src: usize,
+ len: usize,
+ ) -> Result<(), crate::Trap> {
+ let src_range =
+ cold_err!(src_memory.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_memory.len())))?;
+ let dst_range = cold_err!(self.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.len())))?;
+ self.data[dst_range].copy_from_slice(&src_memory.data[src_range]);
Ok(())
}
}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index 517a561..b065f2a 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -1,46 +1,139 @@
-use alloc::sync::Arc;
+#[cfg(feature = "state")]
+use alloc::collections::BTreeMap;
use alloc::{boxed::Box, format, vec::Vec};
+#[cfg(feature = "state")]
+use core::any::{Any, TypeId};
use core::hint::cold_path;
-use core::sync::atomic::{AtomicUsize, Ordering};
use tinywasm_types::*;
-use crate::interpreter::stack::{CallStack, ValueStack};
-use crate::interpreter::{TinyWasmValue, ValueRef};
-use crate::{Engine, Error, ModuleInstance, Result, Trap};
+use crate::func::{FromWasmValues, HostFunction};
+use crate::interpreter::stack::{CallStack, StackBase, ValueStack};
+use crate::interpreter::{RuntimeValue, ValueRef};
+use crate::reference::{ReferentKind, RootedItem, StoreId, StoredRef};
+use crate::{Engine, Error, ExnRef, FuncRef, ModuleInstance, RefValue, Result, Trap, WasmValue};
+mod const_expr;
mod data;
mod element;
mod function;
+mod gc;
mod global;
mod memory;
+mod state;
mod table;
+mod tag;
+mod types;
-pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory};
+use const_expr::eval_const;
+pub(crate) use gc::{GcObjectKind, data_range, decode_data, default_value, pop_value, push_value};
pub(crate) use memory::{MemValue, MemoryInstance};
-pub(crate) use {data::*, element::*, function::*, global::*, table::*};
+pub(crate) use state::State;
+pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type};
+pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*};
-// global store id counter
-static STORE_ID: AtomicUsize = AtomicUsize::new(0);
+/// Controls selected allocation requests from WebAssembly instances.
+///
+/// Configure a limiter with
+/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). The callbacks
+/// cover linear memory, tables, and the logical GC heap. They do not account for stacks, runtime
+/// metadata, temporary buffers, backing-capacity overhead, or other host allocations.
+///
+/// `Ok(true)` allows an allocation attempt, `Ok(false)` rejects it, and `Err` returns the supplied
+/// trap. Allowing a request does not guarantee that the backing allocation will succeed. Rejected
+/// growth uses the operation's normal failed-growth result. Rejected initial allocation and GC
+/// allocation produce [`Trap::OutOfMemory`].
+///
+/// # Example
+/// ```rust
+/// use tinywasm::engine::Config;
+/// use tinywasm::types::{MemoryArch, MemoryType};
+/// use tinywasm::{Engine, Memory, ResourceLimiter, Store};
+///
+/// struct MemoryLimit(usize);
+///
+/// impl ResourceLimiter for MemoryLimit {
+/// fn memory_growing(
+/// &self,
+/// _current: usize,
+/// desired: usize,
+/// _maximum: Option<usize>,
+/// ) -> Result<bool, tinywasm::Trap> {
+/// Ok(desired <= self.0)
+/// }
+/// }
+///
+/// let config = Config::new().with_resource_limiter(MemoryLimit(64 * 1024));
+/// let mut store = Store::new(Engine::new(config));
+/// let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?;
+/// assert_eq!(memory.grow(&mut store, 1)?, None);
+/// # Ok::<(), tinywasm::Error>(())
+/// ```
+pub trait ResourceLimiter: Send + Sync {
+ /// Checks a nonzero memory allocation or growth request.
+ ///
+ /// Sizes are in bytes. `current` is zero for initial allocation. `maximum` is the declared
+ /// maximum in bytes, saturated to `usize::MAX` if needed, or `None` if no maximum was declared.
+ /// Growth limits are checked before this callback. The default implementation allows the
+ /// request.
+ fn memory_growing(
+ &self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> core::result::Result<bool, Trap> {
+ Ok(true)
+ }
-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()
-}
+ /// Checks a nonzero table allocation or growth request.
+ ///
+ /// Sizes are in elements. `current` is zero for initial allocation. `maximum` is the declared
+ /// maximum element count when it fits `usize`, or `None` otherwise. Table limits are checked
+ /// before this callback. The default implementation allows the request.
+ fn table_growing(
+ &self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> core::result::Result<bool, Trap> {
+ Ok(true)
+ }
-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,
+ /// Checks a GC object allocation request.
+ ///
+ /// Sizes are the current TinyWasm-accounted heap bytes and that count plus the requested
+ /// allocation. They include unreachable objects until collection but not all allocator
+ /// overhead. `maximum` is currently always `None`. This callback runs before threshold-triggered
+ /// collection.
+ fn gc_growing(
+ &self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> core::result::Result<bool, Trap> {
+ Ok(true)
}
}
-/// 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).
+/// A value stored as host state.
+#[doc(hidden)]
+#[cfg(all(feature = "state", not(feature = "send")))]
+pub trait StoreState: Any {}
+#[cfg(all(feature = "state", not(feature = "send")))]
+impl<T: Any> StoreState for T {}
+
+/// A value stored as host state.
+#[doc(hidden)]
+#[cfg(all(feature = "state", feature = "send"))]
+pub trait StoreState: Any + Send {}
+#[cfg(all(feature = "state", feature = "send"))]
+impl<T: Any + Send> StoreState for T {}
+
+#[cfg(all(feature = "state", not(feature = "send")))]
+type StoredState = dyn Any;
+#[cfg(all(feature = "state", feature = "send"))]
+type StoredState = dyn Any + Send;
+
+/// Runtime state used by WebAssembly instances and host functions.
///
/// ## Example
/// ```rust
@@ -52,69 +145,95 @@ pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) ->
/// # _ = store;
/// ```
///
-/// See <https://webassembly.github.io/spec/core/exec/runtime.html#store>
+/// See <https://webassembly.github.io/spec/core/exec/runtime.html#store>
pub struct Store {
- id: usize,
+ id: StoreId,
pub(crate) module_instances: Vec<ModuleInstance>,
-
pub(crate) engine: Engine,
pub(crate) execution_fuel: u32,
pub(crate) execution_active: bool,
+ pub(crate) reentrant_call_depth: usize,
pub(crate) state: State,
pub(crate) call_stack: CallStack,
pub(crate) value_stack: ValueStack,
+ value_scratch: ValueScratch,
+ #[cfg(feature = "state")]
+ host_state: BTreeMap<TypeId, Box<StoredState>>,
}
-#[cfg(feature = "debug")]
-impl core::fmt::Debug for Store {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- f.debug_struct("Store")
- .field("id", &self.id)
- .field("module_instances", &self.module_instances)
- .field("engine", &self.engine)
- .finish()
+#[derive(Default)]
+struct ValueScratch(Vec<WasmValue>);
+
+impl ValueScratch {
+ fn take_resized(&mut self, len: usize) -> Result<Vec<WasmValue>> {
+ self.0.clear();
+ self.0.try_reserve(len).map_err(|_| Trap::OutOfMemory)?;
+ self.0.resize(len, WasmValue::I32(0));
+ Ok(core::mem::take(&mut self.0))
}
-}
-impl Store {
- /// Create a new store
- pub fn new(engine: Engine) -> Self {
- let id = STORE_ID.fetch_add(1, Ordering::Relaxed);
- Self {
- id,
- module_instances: Vec::new(),
- state: State::default(),
- call_stack: CallStack::new(engine.config()),
- value_stack: ValueStack::new(engine.config()),
- engine,
- execution_fuel: 0,
- execution_active: false,
+ fn restore(&mut self, mut values: Vec<WasmValue>) {
+ values.clear();
+ if values.capacity() > self.0.capacity() {
+ self.0 = values;
}
}
+}
- /// Get a module instance by the internal id
- pub fn get_module_instance(&self, id: ModuleInstanceId) -> Option<ModuleInstance> {
- self.module_instances.get(id as usize).cloned()
- }
+#[derive(Clone, Copy)]
+pub(crate) enum FuncValueTypes {
+ Params,
+ Results,
+}
- #[inline]
- pub(crate) fn get_module_instance_internal(&self, id: ModuleInstanceId) -> ModuleInstance {
- self.module_instances.get(id as usize).unwrap_or_else(|| unreachable!("invalid module instance: {id}")).clone()
- }
+pub(crate) struct StackValueIter<'a> {
+ store: &'a mut Store,
+ type_addr: TypeAddr,
+ types: FuncValueTypes,
+ index: StackBase,
+ position: usize,
+ len: usize,
+}
- pub(crate) fn enter_execution(&mut self) -> Result<()> {
- if self.execution_active {
- return Err(Trap::Other(
- "cannot call a function while another invocation is active; use FuncContext::call from host functions",
- )
- .into());
+impl Iterator for StackValueIter<'_> {
+ type Item = WasmValue;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.position == self.len {
+ return None;
}
- self.execution_active = true;
- Ok(())
+ let ty = {
+ let func_ty = self.store.state.get_canonical_func_type(self.type_addr);
+ match self.types {
+ FuncValueTypes::Params => func_ty.params()[self.position],
+ FuncValueTypes::Results => func_ty.results()[self.position],
+ }
+ };
+ self.position += 1;
+ let value = self.store.stack_value(ty, &mut self.index);
+ Some(
+ value
+ .into_wasm(self.store, ty)
+ .unwrap_or_else(|_| unreachable!("invalid internal value at a typed host boundary")),
+ )
}
- pub(crate) fn exit_execution(&mut self) {
- self.execution_active = false;
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let remaining = self.len - self.position;
+ (remaining, Some(remaining))
+ }
+}
+
+impl ExactSizeIterator for StackValueIter<'_> {}
+
+#[cfg(feature = "debug")]
+impl core::fmt::Debug for Store {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ f.debug_struct("Store")
+ .field("id", &self.id)
+ .field("module_instances", &self.module_instances)
+ .field("engine", &self.engine)
+ .finish()
}
}
@@ -130,144 +249,228 @@ 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),
+impl Store {
+ /// Create a new store
+ pub fn new(engine: Engine) -> Self {
+ let id = StoreId::fresh();
+ let state = State::new(engine.config());
+ Self {
+ id,
+ module_instances: Vec::new(),
+ state,
+ call_stack: CallStack::new(engine.config()),
+ value_stack: ValueStack::new(engine.config()),
+ value_scratch: ValueScratch::default(),
+ engine,
+ execution_fuel: 0,
+ execution_active: false,
+ reentrant_call_depth: 0,
+ #[cfg(feature = "state")]
+ host_state: BTreeMap::new(),
}
}
- #[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")
+ /// Adds host state to this store.
+ ///
+ /// Host callbacks can access the value through [`Store::state`] and
+ /// [`Store::state_mut`]. If state of the same type already exists, this
+ /// method replaces it.
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ /// use tinywasm::Store;
+ ///
+ /// struct AppState {
+ /// requests: usize,
+ /// }
+ ///
+ /// let store = Store::default().with_state(AppState { requests: 0 });
+ /// assert_eq!(store.state::<AppState>().unwrap().requests, 0);
+ /// ```
+ #[cfg(feature = "state")]
+ pub fn with_state<T: StoreState>(mut self, state: T) -> Self {
+ self.host_state.insert(TypeId::of::<T>(), Box::new(state));
+ self
}
- #[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}"))
+ /// Get host state.
+ #[cfg(feature = "state")]
+ pub fn state<T: StoreState>(&self) -> Option<&T> {
+ self.host_state.get(&TypeId::of::<T>()).and_then(|state| state.downcast_ref())
}
- 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}"))
+ /// Get mutable access to host state.
+ #[cfg(feature = "state")]
+ pub fn state_mut<T: StoreState>(&mut self) -> Option<&mut T> {
+ self.host_state.get_mut(&TypeId::of::<T>()).and_then(|state| state.downcast_mut())
}
- 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)
+ pub(crate) const fn id(&self) -> StoreId {
+ self.id
}
- /// 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")
+ pub(crate) fn with_scratch_values<T>(
+ &mut self,
+ len: usize,
+ use_values: impl FnOnce(&mut Self, &mut Vec<WasmValue>) -> Result<T>,
+ ) -> Result<T> {
+ let mut values = self.value_scratch.take_resized(len)?;
+ let result = use_values(self, &mut values);
+ self.value_scratch.restore(values);
+ result
}
- /// 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}"),
- }
+ pub(crate) fn root_reference<T: StoredRef>(&mut self, value: ValueRef, kind: ReferentKind) -> Result<T> {
+ let token = match kind {
+ ReferentKind::Struct | ReferentKind::Array | ReferentKind::Exception => {
+ Some(self.state.roots.insert(value)?)
+ }
+ ReferentKind::I31 | ReferentKind::HostExtern => None,
+ };
+ Ok(T::from_rooted_item(RootedItem { store: self.id, value, kind, _token: token }))
}
- /// 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")
+ pub(crate) fn root_exception(&mut self, value: ValueRef) -> Result<ExnRef> {
+ if !matches!(self.state.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))) {
+ return Err(Trap::InvalidReference.into());
+ }
+ self.root_reference(value, ReferentKind::Exception)
}
- /// 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")
+ pub(crate) fn resolve_ref<T: StoredRef>(&self, reference: &T) -> Result<ValueRef, Trap> {
+ let item = reference.rooted_item();
+ if item.store != self.id {
+ return Err(Trap::InvalidStore);
+ }
+ Ok(item.value)
}
- /// 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")
+ pub(crate) fn encode_ref(&self, value: &RefValue) -> Result<ValueRef> {
+ Ok(match value {
+ RefValue::Null => ValueRef::NULL,
+ RefValue::Func(value) => ValueRef::from_category_addr(value.addr(self.id).ok_or(Trap::InvalidStore)?),
+ RefValue::Any(value) => self.resolve_ref(value)?,
+ RefValue::Extern(value) => self.resolve_ref(value)?,
+ RefValue::Exn(value) => self.resolve_ref(value)?,
+ })
}
- /// 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")
+ pub(crate) fn decode_ref(&mut self, value: ValueRef, ty: RefType) -> Result<RefValue> {
+ if value.is_null() {
+ return Ok(RefValue::Null);
+ }
+ if ty.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some()) || ty.is_func() {
+ return Ok(RefValue::Func(FuncRef::new(self.id, value.addr().ok_or(Trap::InvalidReference)?)));
+ }
+ if ty.is_exn() {
+ return self.root_exception(value).map(RefValue::Exn);
+ }
+ let kind = if value.is_i31() {
+ ReferentKind::I31
+ } else if value.is_host_any() {
+ ReferentKind::HostExtern
+ } else {
+ match self.state.gc.get(value).map(|object| object.kind) {
+ Some(gc::GcObjectKind::Composite(type_addr)) => match &self.state.get_type(type_addr).composite {
+ CompositeType::Struct(_) => ReferentKind::Struct,
+ CompositeType::Array(_) => ReferentKind::Array,
+ CompositeType::Func(_) => return Err(Trap::InvalidReference.into()),
+ },
+ _ => return Err(Trap::InvalidReference.into()),
+ }
+ };
+ if ty.is_extern() {
+ Ok(RefValue::Extern(self.root_reference(value, kind)?))
+ } else {
+ Ok(RefValue::Any(self.root_reference(value, kind)?))
+ }
}
- /// 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")
+ fn stack_value(&self, ty: WasmType, index: &mut StackBase) -> RuntimeValue {
+ match ty {
+ WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => {
+ let value = *self.value_stack.stack_32.get(index.s32 as usize);
+ index.s32 += 1;
+ if matches!(ty, WasmType::Ref(_)) {
+ RuntimeValue::ValueRef(ValueRef::from_raw(value))
+ } else {
+ RuntimeValue::Value32(value)
+ }
+ }
+ WasmType::I64 | WasmType::F64 => {
+ let value = *self.value_stack.stack_64.get(index.s64 as usize);
+ index.s64 += 1;
+ RuntimeValue::Value64(value)
+ }
+ WasmType::V128 => {
+ let value = *self.value_stack.stack_128.get(index.s128 as usize);
+ index.s128 += 1;
+ RuntimeValue::Value128(value)
+ }
+ }
}
- /// Get two mutable tables at the actual index in the store
- pub(crate) fn get_tables_mut(
+ pub(crate) fn stack_value_iter(
&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")
+ type_addr: TypeAddr,
+ types: FuncValueTypes,
+ index: StackBase,
+ ) -> Result<StackValueIter<'_>, Trap> {
+ let canonical = self.state.get_canonical_func_type(type_addr);
+ let canonical = match types {
+ FuncValueTypes::Params => canonical.params(),
+ FuncValueTypes::Results => canonical.results(),
+ };
+ let len = canonical.len();
+ let reference_count = canonical.iter().filter(|ty| matches!(ty, WasmType::Ref(_))).count();
+ self.state.roots.reserve(reference_count)?;
+ Ok(StackValueIter { store: self, type_addr, types, index, position: 0, len })
}
- /// 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")
+ pub(crate) fn push_wasm_values(&mut self, values: &[WasmValue]) -> Result<()> {
+ for value in values {
+ let value = value.to_runtime(self)?;
+ self.value_stack.push_dyn(value)?;
+ }
+ Ok(())
}
- /// 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
+ pub(crate) fn pop_stack_values(&mut self, type_addr: TypeAddr, results: &mut [WasmValue]) -> Result<()> {
+ let (result_count, result_counts) = {
+ let types = self.state.get_canonical_func_type(type_addr).results();
+ (types.len(), types.iter().collect())
+ };
+ if result_count != results.len() {
+ return Err(Error::other("result buffer has the wrong length"));
+ }
+ let base = self.value_stack.base_before(result_counts);
+ let result = (|| {
+ let mut index = base;
+ for (position, result) in results.iter_mut().enumerate() {
+ let ty = self.state.get_canonical_func_type(type_addr).results()[position];
+ let value = self.stack_value(ty, &mut index);
+ *result = value.into_wasm(self, ty)?;
+ }
+ Ok(())
+ })();
+ self.value_stack.truncate_to_base(base);
+ result
}
- /// 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;
+ /// Reclaims unreachable managed objects.
+ ///
+ /// Globals, tables, operand stacks, and owned host references are traced as
+ /// roots. Objects also become eligible for automatic threshold collection
+ /// after the last owned handle is dropped.
+ pub fn gc(&mut self) -> Result<()> {
+ let stack_roots = self.value_stack.stack_32.into_iter().copied().map(ValueRef::from_raw).collect::<Vec<_>>();
+ self.state.collect_gc(stack_roots).map_err(|_| Trap::OutOfMemory.into())
}
-}
-impl Store {
- /// Get the store's ID (unique per process)
- pub fn id(&self) -> usize {
- self.id
+ /// Get a module instance by the internal id
+ pub fn get_module_instance(&self, id: ModuleInstanceId) -> Option<&ModuleInstance> {
+ self.module_instances.get(id as usize)
}
pub(crate) fn next_module_instance_id(&self) -> ModuleInstanceId {
@@ -279,83 +482,113 @@ impl Store {
self.module_instances.push(instance);
}
- /// Get the global at the actual index in the store
- #[doc(hidden)]
- pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue {
- self.state.get_global_val(addr)
+ pub(crate) fn value_matches_type(&self, value: &WasmValue, ty: WasmType) -> bool {
+ let (WasmValue::Ref(value), WasmType::Ref(expected)) = (value, ty) else {
+ return value.matches_type(ty);
+ };
+ let category_matches = match value {
+ RefValue::Null => return expected.is_nullable(),
+ RefValue::Func(_) => {
+ expected.is_func()
+ || expected.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some())
+ }
+ RefValue::Extern(_) => expected.is_extern(),
+ RefValue::Exn(_) => expected.is_exn(),
+ RefValue::Any(_) => !expected.is_func() && !expected.is_extern() && !expected.is_exn(),
+ };
+ if !category_matches {
+ return false;
+ }
+ match self.encode_ref(value) {
+ Ok(value) => self.state.value_ref_matches(value, expected),
+ _ => false,
+ }
}
- /// Set the global at the actual index in the store
- #[doc(hidden)]
- pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) {
- self.state.set_global_val(addr, value);
+ /// Marks the store as executing and rejects nested root calls.
+ pub(crate) fn enter_execution(&mut self) -> Result<()> {
+ if self.execution_active {
+ return Err(Trap::Other(
+ "cannot call a function while another invocation is active; use FuncContext::call from host functions",
+ )
+ .into());
+ }
+ self.execution_active = true;
+ Ok(())
}
-}
-// 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;
- }
+ /// Marks the current root execution as complete.
+ pub(crate) fn exit_execution(&mut self) {
+ self.execution_active = false;
+ }
- 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())
+ /// Validates and pushes typed parameters or results onto the value stack.
+ pub(crate) fn push_typed_values<const RESULTS: bool>(
+ &mut self,
+ type_addr: TypeAddr,
+ values: impl Iterator<Item = WasmValue>,
+ stack_base: StackBase,
+ ) -> Result<()> {
+ let result: Result<()> = (|| {
+ let ty = self.state.get_canonical_func_type(type_addr);
+ let expected = if RESULTS { ty.results() } else { ty.params() };
+ let mut values = values;
+ for &ty in expected {
+ let value = values.next().ok_or_else(|| Error::other("not enough typed function values"))?;
+ let internal = value.to_runtime(self)?;
+ if !self.value_matches_type(&value, ty) {
+ return Err(Error::other("typed function value does not match its signature"));
}
- 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));
+ self.value_stack.push_dyn(internal)?;
+ }
+ if values.next().is_some() {
+ return Err(Error::other("too many typed function values"));
+ }
+ Ok(())
+ })();
+ if result.is_err() {
+ self.value_stack.truncate_to_base(stack_base);
}
- type_addrs.into_boxed_slice()
+ result
}
- 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
+ /// Reads typed results from the value stack and restores its previous base.
+ #[inline]
+ pub(crate) fn take_typed_results<R: FromWasmValues>(
+ &mut self,
+ type_addr: TypeAddr,
+ stack_base: StackBase,
+ ) -> Result<R> {
+ let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?;
+ let result = cold_err!(R::from_wasm_values(&mut values));
+ self.value_stack.truncate_to_base(stack_base);
+ result
}
/// Add functions to the store, returning their addresses in the store
pub(crate) fn init_funcs(
&mut self,
- funcs: &[Arc<WasmFunction>],
+ funcs: &[Shared<WasmFunction>],
owner: ModuleInstanceId,
+ module_type_idxs: &[TypeAddr],
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 }),
- }));
- start..start + funcs.len() as FuncAddr
+ debug_assert_eq!(funcs.len(), module_type_idxs.len());
+ let funcs =
+ funcs.iter().cloned().zip(module_type_idxs).map(|(func, &type_idx)| (type_addrs[type_idx as usize], func));
+ self.state.funcs.extend_wasm(funcs, owner)
+ }
+
+ /// Add tags to the store, returning their addresses in the store.
+ pub(crate) fn init_tags(
+ &mut self,
+ tags: &[TagType],
+ type_addrs: &[TypeAddr],
+ ) -> impl ExactSizeIterator<Item = TagAddr> {
+ let start = self.state.tags.len() as TagAddr;
+ self.state.tags.reserve_exact(tags.len());
+ self.state.tags.extend(tags.iter().map(|tag| TagInstance { type_addr: type_addrs[tag.type_idx as usize] }));
+ start..start + tags.len() as TagAddr
}
/// Add tables to the store, returning their addresses in the store
@@ -367,21 +600,22 @@ impl Store {
type_addrs: &[TypeAddr],
) -> Result<impl ExactSizeIterator<Item = TableAddr>> {
let start = self.state.tables.len() as TableAddr;
+ let limiter = self.engine.config().resource_limiter.clone();
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 eval_const(&mut self.state, expr, global_addrs, func_addrs, type_addrs)? {
+ RuntimeValue::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() {
MemoryArch::I32 => TableType::new(element_type, table.ty.size_initial, table.ty.size_max),
MemoryArch::I64 => TableType::new64(element_type, table.ty.size_initial, table.ty.size_max),
};
- self.state.tables.push(TableInstance::new_with_init(ty, init)?);
+ self.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?);
}
Ok(start..start + tables.len() as TableAddr)
}
@@ -390,17 +624,12 @@ impl Store {
pub(crate) fn init_memories(
&mut self,
memories: &[MemoryType],
- init: impl Fn(MemoryType, &MemoryBackend) -> Result<MemoryInstance>,
+ init: impl Fn(MemoryType) -> Result<MemoryInstance>,
) -> Result<impl ExactSizeIterator<Item = MemAddr>> {
let start = self.state.memories.len() as MemAddr;
+ self.state.memories.reserve_exact(memories.len());
for mem in memories {
- self.state.memories.push(match init(*mem, &self.engine.config().memory_backend) {
- Ok(mem) => mem,
- Err(e) => {
- cold_path();
- return Err(e);
- }
- });
+ self.state.memories.push(cold_err!(init(*mem))?);
}
Ok(start..start + memories.len() as MemAddr)
}
@@ -413,35 +642,33 @@ impl Store {
func_addrs: &[FuncAddr],
type_addrs: &[TypeAddr],
) -> Result<()> {
- let start = self.state.globals.len() as Addr;
- out.extend(start..start + globals.len() as Addr);
-
+ self.state.globals.reserve(globals);
for global in globals {
- let value = match self.eval_const(&global.init, out, func_addrs) {
- Ok(val) => val,
- Err(e) => {
- cold_path();
- return Err(e);
- }
- };
+ let value = cold_err!(eval_const(&mut self.state, &global.init, out, func_addrs, type_addrs))?;
let ty = global.ty.with_ty(canonicalize_value_type(global.ty.ty, type_addrs));
- self.state.globals.push(GlobalInstance::new(ty, value));
+ out.push(self.state.globals.push(ty, value));
}
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 eval_const(&mut self.state, expr, globals, funcs, type_addrs)? {
+ RuntimeValue::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!(
@@ -452,34 +679,58 @@ impl Store {
}
}
- /// Add elements to the store, returning their addresses in the store
- /// Should be called after the tables have been added
- pub(crate) fn init_elements(
+ /// Allocates all element segments before applying initialization effects.
+ pub(crate) fn alloc_elements(
&mut self,
- table_addrs: &[TableAddr],
func_addrs: &[FuncAddr],
global_addrs: &[Addr],
elements: &[Element],
- ) -> Result<(Box<[Addr]>, Option<Trap>)> {
+ type_addrs: &[TypeAddr],
+ ) -> Result<Box<[ElemAddr]>> {
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());
+ self.state.elements.reserve_exact(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);
+ }
+ elem_addrs.push((i + elem_count) as ElemAddr);
+ }
+ Ok(elem_addrs.into_boxed_slice())
+ }
- let items = match &element.kind {
+ /// Applies element initialization effects in segment order.
+ pub(crate) fn init_elements(
+ &mut self,
+ table_addrs: &[TableAddr],
+ func_addrs: &[FuncAddr],
+ global_addrs: &[Addr],
+ elements: &[Element],
+ type_addrs: &[TypeAddr],
+ elem_addrs: &[ElemAddr],
+ ) -> Result<()> {
+ for (i, element) in elements.iter().enumerate() {
+ let elem_addr = elem_addrs[i] as usize;
+ match &element.kind {
// doesn't need to be initialized, can be initialized lazily using the `table.init` instruction
- ElementKind::Passive => 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 = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? {
+ RuntimeValue::Value32(value) => u64::from(value),
+ RuntimeValue::Value64(value) => value,
+ other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))),
+ };
let table_addr = table_addrs
.get(*table as usize)
.copied()
@@ -489,234 +740,82 @@ impl Store {
return Err(Error::Other(format!("table {table} not found for element {i}")));
};
- // In wasm 2.0, it's possible to call a function that hasn't been instantiated yet,
- // when using a partially initialized active element segments.
- // This isn't mentioned in the spec, but the "unofficial" testsuite has a test for it:
- // https://github.com/WebAssembly/testsuite/blob/5a1a590603d81f40ef471abba70a90a9ae5f4627/linking.wast#L264-L276
- // I have NO IDEA why this is allowed, but it is.
let Ok(offset) = usize::try_from(offset) else {
- return Ok((
- elem_addrs.into_boxed_slice(),
- Some(Trap::TableOutOfBounds { offset: usize::MAX, len: init.len(), max: table.size() }),
- ));
+ return Err(Trap::TableOutOfBounds {
+ offset: usize::MAX,
+ len: self.state.elements[elem_addr].items.as_ref().unwrap().len(),
+ max: table.size(),
+ }
+ .into());
};
- if let Err(trap) = table.init(offset, &init) {
- return Ok((elem_addrs.into_boxed_slice(), Some(trap)));
- }
+ let State { elements, tables, .. } = &mut self.state;
+ let init = elements[elem_addr].items.as_deref().unwrap();
+ let table = &mut tables[table_addr as usize];
+ table.init(offset, init)?;
// 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);
+ }
}
- // this should be optimized out by the compiler
- Ok((elem_addrs.into_boxed_slice(), None))
+ Ok(())
+ }
+
+ /// Allocates all data segments before applying initialization effects.
+ pub(crate) fn alloc_data(&mut self, data: &[Data]) -> Box<[DataAddr]> {
+ let start = self.state.data.len() as DataAddr;
+ self.state.data.reserve_exact(data.len());
+ self.state.data.extend(data.iter().map(|data| DataInstance { data: Some(data.data.clone()) }));
+ (start..start + data.len() as DataAddr).collect()
}
- /// Add data to the store, returning their addresses in the store
+ /// Applies data initialization effects in segment order.
pub(crate) fn init_data(
&mut self,
mem_addrs: &[MemAddr],
global_addrs: &[Addr],
func_addrs: &[FuncAddr],
data: &[Data],
- ) -> Result<(Box<[Addr]>, Option<Trap>)> {
- let data_count = self.state.data.len();
- let mut data_addrs = Vec::with_capacity(data_count);
+ type_addrs: &[TypeAddr],
+ data_addrs: &[DataAddr],
+ ) -> Result<()> {
for (i, data) in data.iter().enumerate() {
- let data_val = match &data.kind {
+ match &data.kind {
tinywasm_types::DataKind::Active { mem: mem_addr, offset } => {
let Some(mem_addr) = mem_addrs.get(*mem_addr as usize) else {
return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}")));
};
- let offset = self.eval_size_const(offset, global_addrs, func_addrs)?;
+ let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? {
+ RuntimeValue::Value32(value) => u64::from(value),
+ RuntimeValue::Value64(value) => value,
+ other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))),
+ };
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}")));
};
let offset = usize::try_from(offset).unwrap_or(usize::MAX);
match mem.inner.write_all(offset, &data.data) {
- Some(()) => None,
+ Some(()) => self.state.data[data_addrs[i] as usize].drop(),
None => {
- return Ok((
- data_addrs.into_boxed_slice(),
- Some(crate::Trap::MemoryOutOfBounds {
- offset,
- len: data.data.len(),
- max: mem.inner.len(),
- }),
- ));
+ return Err(
+ Trap::MemoryOutOfBounds { offset, len: data.data.len(), max: mem.inner.len() }.into()
+ );
}
}
}
- tinywasm_types::DataKind::Passive => Some(data.data.to_vec()),
+ tinywasm_types::DataKind::Passive => {}
};
-
- self.state.data.push(DataInstance { data: data_val });
- data_addrs.push((i + data_count) as Addr);
}
- // this should be optimized out by the compiler
- Ok((data_addrs.into_boxed_slice(), None))
- }
-
- pub(crate) fn add_func(&mut self, func: FunctionInstance) -> FuncAddr {
- self.state.funcs.push(func);
- self.state.funcs.len() as FuncAddr - 1
- }
-
- /// Evaluate a constant expression that's either a i32 or a i64 as a global or a const instruction
- fn eval_size_const(
- &self,
- const_instrs: &[tinywasm_types::ConstInstruction],
- module_global_addrs: &[Addr],
- module_func_addrs: &[FuncAddr],
- ) -> Result<u64> {
- let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs)?;
- match value {
- TinyWasmValue::Value32(i) => Ok(u64::from(i)),
- TinyWasmValue::Value64(i) => Ok(i),
- other => Err(Error::Other(format!("expected i32 or i64, got {other:?}"))),
- }
+ Ok(())
}
- /// Evaluate a constant expression
- #[inline]
- fn eval_const(
- &self,
- const_instrs: &[tinywasm_types::ConstInstruction],
- module_global_addrs: &[Addr],
- module_func_addrs: &[FuncAddr],
- ) -> 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 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"
- )))
- }
- }
- };
-
- 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),
- 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(val);
- }
-
- let mut stack = Vec::new();
- for instr in const_instrs {
- match instr {
- I32Const(i) => stack.push(TinyWasmValue::Value32(*i as u32)),
- I64Const(i) => stack.push(TinyWasmValue::Value64(*i as u64)),
- 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)?),
- 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())?)))
- }
- Ref(_) => {
- cold_path();
- return Err(Error::other("unsupported reference constant"));
- }
- 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"))?;
- let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else {
- cold_path();
- return Err(Error::other("type mismatch in const i32 op"));
- };
- let lhs = lhs as i32;
- let rhs = rhs as i32;
- let out = match instr {
- I32Add => lhs.wrapping_add(rhs),
- I32Sub => lhs.wrapping_sub(rhs),
- I32Mul => lhs.wrapping_mul(rhs),
- _ => {
- cold_path();
- return Err(Error::other("invalid const instruction in i32 op"));
- }
- };
- stack.push(TinyWasmValue::Value32(out as u32));
- }
- I64Add | I64Sub | I64Mul => {
- let rhs = stack.pop();
- let lhs = stack.pop();
- let (Some(TinyWasmValue::Value64(lhs)), Some(TinyWasmValue::Value64(rhs))) = (lhs, rhs) else {
- cold_path();
- return Err(Error::other("type mismatch in const i64 op"));
- };
-
- let lhs = lhs as i64;
- let rhs = rhs as i64;
- let out = match instr {
- I64Add => lhs.wrapping_add(rhs),
- I64Sub => lhs.wrapping_sub(rhs),
- I64Mul => lhs.wrapping_mul(rhs),
- _ => {
- cold_path();
- return Err(Error::other("invalid const instruction in i64 op"));
- }
- };
- stack.push(TinyWasmValue::Value64(out as u64));
- }
- }
- }
-
- let Some(value) = stack.pop() else {
- cold_path();
- return Err(Error::other("empty const expression"));
- };
-
- if !stack.is_empty() {
- cold_path();
- return Err(Error::other("const expression did not reduce to single value"));
- }
-
- Ok(value)
+ /// Adds a function and returns its store address.
+ pub(crate) fn add_host_func(&mut self, type_addr: TypeAddr, func: HostFunction) -> FuncAddr {
+ self.state.funcs.push_host(type_addr, func)
}
}
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
new file mode 100644
index 0000000..f1ba616
--- /dev/null
+++ b/crates/tinywasm/src/store/state.rs
@@ -0,0 +1,386 @@
+use alloc::vec::Vec;
+
+use super::*;
+use crate::engine::Config;
+use crate::interpreter::{InternalValue, Value32, Value64, Value128};
+
+/// 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: Functions,
+ pub(crate) tables: Vec<TableInstance>,
+ pub(crate) memories: Vec<MemoryInstance>,
+ pub(crate) globals: Globals,
+ pub(crate) tags: Vec<TagInstance>,
+ pub(crate) elements: Vec<ElementInstance>,
+ pub(crate) data: Vec<DataInstance>,
+ pub(crate) gc: gc::GcHeap,
+ pub(crate) roots: gc::Roots,
+}
+
+impl State {
+ pub(crate) fn new(config: &Config) -> Self {
+ Self {
+ canonical_types: Vec::new(),
+ canonical_rec_group_lengths: Vec::new(),
+ funcs: Functions::default(),
+ tables: Vec::new(),
+ memories: Vec::new(),
+ globals: Globals::default(),
+ tags: Vec::new(),
+ elements: Vec::new(),
+ data: Vec::new(),
+ gc: gc::GcHeap::new(config),
+ roots: gc::Roots::new(),
+ }
+ }
+
+ pub(crate) fn collect_gc(&mut self, additional: impl IntoIterator<Item = ValueRef>) -> Result<(), gc::AllocError> {
+ let canonical_types = &self.canonical_types;
+ let store_roots = self
+ .globals
+ .globals_32()
+ .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty))
+ .map(|(value, _)| ValueRef::from_raw(*value))
+ .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(additional);
+ let roots = self.roots.values().chain(store_roots);
+ self.gc.collect(roots)
+ }
+
+ 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
+ | AbstractHeapType::Exn
+ )
+ )
+ }
+
+ pub(crate) fn check_gc_allocation(&self, type_addr: TypeAddr, value_count: usize) -> Result<(), 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"),
+ };
+ self.gc.check_allocation(value_count, trace_references)
+ }
+
+ /// Allocates an object, collecting from all runtime roots when needed.
+ pub(crate) fn alloc_gc_object(
+ &mut self,
+ type_addr: TypeAddr,
+ values: Vec<RuntimeValue>,
+ additional_roots: impl IntoIterator<Item = ValueRef>,
+ ) -> 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 roots = additional_roots.into_iter().chain(values.iter().filter_map(|value| match value {
+ RuntimeValue::ValueRef(value) => Some(*value),
+ _ => None,
+ }));
+ cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?;
+ }
+ self.gc.alloc(type_addr, values, trace_references)
+ }
+
+ /// Allocates a traced exception object, collecting with its payload as temporary roots.
+ pub(crate) fn alloc_exception(
+ &mut self,
+ tag_addr: TagAddr,
+ payload: Vec<RuntimeValue>,
+ additional_roots: impl IntoIterator<Item = ValueRef>,
+ ) -> Result<ValueRef, Trap> {
+ let type_addr = self.get_tag(tag_addr).type_addr;
+ let mut trace_fields = Vec::new();
+ trace_fields.try_reserve_exact(payload.len()).map_err(|_| Trap::OutOfMemory)?;
+ trace_fields.extend(
+ self.get_canonical_func_type(type_addr)
+ .params()
+ .iter()
+ .map(|ty| Self::type_may_contain_gc_in(&self.canonical_types, ty)),
+ );
+ if self.gc.should_collect(payload.len(), true) {
+ let roots = additional_roots.into_iter().chain(payload.iter().filter_map(|value| match value {
+ RuntimeValue::ValueRef(value) => Some(*value),
+ _ => None,
+ }));
+ cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?;
+ }
+ self.gc.alloc_exception(tag_addr, payload, &trace_fields)
+ }
+
+ /// Resolves a non-null object of the expected canonical type.
+ pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result<gc::Handle, 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"))?;
+ let gc::GcObjectKind::Composite(type_addr) = object.kind else {
+ return Err(Trap::Other("GC reference is not a struct or array"));
+ };
+ if !self.type_addr_is_subtype(type_addr, expected_type) {
+ return Err(Trap::Other("GC reference type mismatch"));
+ }
+ self.gc.handle(reference).ok_or(Trap::Other("invalid GC reference"))
+ }
+
+ /// 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 };
+ if !self.funcs.contains(func_addr) {
+ return false;
+ }
+ let type_addr = self.funcs.type_addr(func_addr);
+ return self.ref_type_is_subtype(RefType::new_concrete(false, type_addr), expected);
+ }
+ if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) {
+ return matches!(self.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_)));
+ }
+ if value.is_i31() {
+ return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected);
+ }
+ if value.is_host_any() {
+ return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::Any), expected);
+ }
+
+ let Some(object) = self.gc.get(value) else { return false };
+ let gc::GcObjectKind::Composite(type_addr) = object.kind else { return false };
+ let actual = RefType::new_concrete(false, type_addr);
+ self.ref_type_is_subtype(actual, expected)
+ }
+
+ #[inline]
+ pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType {
+ self.get_canonical_func_type(self.funcs.type_addr(addr))
+ }
+
+ #[inline]
+ pub(crate) fn get_type(&self, addr: TypeAddr) -> &SubType {
+ &self.canonical_types[addr as usize]
+ }
+
+ #[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")
+ }
+
+ #[inline]
+ 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)
+ }
+
+ #[inline]
+ pub(crate) fn get_tag(&self, addr: TagAddr) -> &TagInstance {
+ &self.tags[addr as usize]
+ }
+
+ /// Get the memory at the actual index in the store
+ #[inline]
+ pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance {
+ &self.memories[addr as usize]
+ }
+
+ /// Get the memory at the actual index in the store
+ #[inline]
+ pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance {
+ &mut self.memories[addr as usize]
+ }
+
+ /// Get the memory at the actual index in the store
+ #[inline]
+ 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
+ #[inline]
+ pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance {
+ &self.tables[addr as usize]
+ }
+
+ /// Get the table at the actual index in the store
+ #[inline]
+ pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance {
+ &mut self.tables[addr as usize]
+ }
+
+ /// 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
+ #[inline]
+ pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance {
+ &mut self.data[addr as usize]
+ }
+
+ /// Get the element at the actual index in the store
+ #[inline]
+ pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance {
+ &mut self.elements[addr as usize]
+ }
+
+ /// Returns a global in its internal value representation.
+ pub(crate) fn global_value(&self, addr: GlobalAddr) -> RuntimeValue {
+ let ty = self.globals.ty(addr).ty;
+ match ty {
+ WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::global_get(&self.globals, addr)),
+ WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::global_get(&self.globals, addr)),
+ WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::global_get(&self.globals, addr)),
+ WasmType::V128 => RuntimeValue::Value128(Value128::global_get(&self.globals, addr)),
+ }
+ }
+
+ /// Sets a global from its internal value representation.
+ pub(crate) fn set_global_value(&mut self, addr: GlobalAddr, value: RuntimeValue) -> Result<()> {
+ let ty = self.globals.ty(addr);
+ if !ty.mutable {
+ cold_path();
+ return Err(Error::other("global is immutable"));
+ }
+ match value {
+ RuntimeValue::Value32(value) => Value32::global_set(&mut self.globals, addr, value),
+ RuntimeValue::Value64(value) => Value64::global_set(&mut self.globals, addr, value),
+ RuntimeValue::ValueRef(value) => ValueRef::global_set(&mut self.globals, addr, value),
+ RuntimeValue::Value128(value) => Value128::global_set(&mut self.globals, addr, value),
+ }
+ Ok(())
+ }
+}
+
+impl Default for State {
+ fn default() -> Self {
+ Self::new(&Config::default())
+ }
+}
diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs
index 68ed99f..71d0184 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::{ResourceLimiter, Result, Trap, interpreter::ValueRef};
use alloc::vec::Vec;
use core::ops::Range;
use tinywasm_types::*;
@@ -10,23 +10,28 @@ 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)
- }
-
- pub(crate) fn new_with_init(kind: TableType, init: TableElement) -> Result<Self> {
- let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?;
+ /// Creates a table filled with the given initial reference.
+ pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result<Self> {
+ if kind.size_max.is_some_and(|maximum| maximum < kind.size_initial) {
+ return Err(Trap::OutOfMemory.into());
+ }
+ let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?;
if size > MAX_TABLE_SIZE {
return Err(Trap::OutOfMemory.into());
}
+ if size != 0
+ && let Some(limiter) = limiter
+ && !limiter.table_growing(0, size, Self::maximum_size(kind))?
+ {
+ return Err(Trap::OutOfMemory.into());
+ }
let mut elements = Vec::new();
- elements.try_reserve_exact(size).map_err(|_| Trap::OutOfMemory)?;
+ cold_err!(elements.try_reserve_exact(size)).map_err(|_| Trap::OutOfMemory)?;
elements.resize(size, init);
Ok(Self { elements, kind })
}
@@ -45,27 +50,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,147 +77,53 @@ 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> {
- let len = n.checked_add(self.elements.len()).ok_or(Trap::OutOfMemory)?;
+ pub(crate) fn grow(
+ &mut self,
+ n: usize,
+ init: ValueRef,
+ limiter: Option<&dyn ResourceLimiter>,
+ ) -> Result<bool, Trap> {
+ let Some(len) = n.checked_add(self.elements.len()) else {
+ return Ok(false);
+ };
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);
if len > max {
- return Err(crate::Trap::TableOutOfBounds { offset: len, len: 1, max: self.elements.len() });
+ return Ok(false);
+ }
+ if len == self.elements.len() {
+ return Ok(true);
+ }
+ if let Some(limiter) = limiter
+ && !limiter.table_growing(self.elements.len(), len, Self::maximum_size(self.kind))?
+ {
+ return Ok(false);
}
- self.elements.try_reserve_exact(n).map_err(|_| Trap::OutOfMemory)?;
+ if self.elements.try_reserve_exact(n).is_err() {
+ return cold!(Ok(false));
+ }
self.elements.resize(len, init);
- Ok(())
+ Ok(true)
+ }
+
+ fn maximum_size(kind: TableType) -> Option<usize> {
+ kind.size_max.and_then(|maximum| usize::try_from(maximum).ok())
}
pub(crate) fn size(&self) -> usize {
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::*;
- use alloc::vec;
-
- // Helper to create a dummy TableType
- fn dummy_table_type() -> TableType {
- TableType::new(RefType::FUNCREF, 10, Some(20))
- }
-
- #[test]
- fn test_table_instance_creation() {
- let kind = dummy_table_type();
- let table_instance = TableInstance::new(kind).unwrap();
- assert_eq!(table_instance.size() as u64, kind.size_initial, "Table instance creation failed: size mismatch");
- }
-
- #[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));
- 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"
- );
- }
-
- #[test]
- fn test_table_init() {
- let kind = dummy_table_type();
- let mut table_instance = TableInstance::new(kind).unwrap();
-
- let init_elements = vec![TableElement::Initialized(0); 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}"
- );
- }
- }
-}
diff --git a/crates/tinywasm/src/store/tag.rs b/crates/tinywasm/src/store/tag.rs
new file mode 100644
index 0000000..49c16d8
--- /dev/null
+++ b/crates/tinywasm/src/store/tag.rs
@@ -0,0 +1,7 @@
+use tinywasm_types::TypeAddr;
+
+#[derive(Clone, Copy)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+pub(crate) struct TagInstance {
+ pub(crate) type_addr: TypeAddr,
+}
diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs
new file mode 100644
index 0000000..e9fa6d1
--- /dev/null
+++ b/crates/tinywasm/src/store/types.rs
@@ -0,0 +1,211 @@
+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)
+}
+
+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() => WasmType::Ref(RefType::new_concrete(
+ ty.is_nullable(),
+ resolve(ty.type_index().expect("concrete reference has a type index")),
+ )),
+ 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)
+ if !ty
+ .params()
+ .iter()
+ .chain(ty.results())
+ .any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) =>
+ {
+ CompositeType::Func(ty.clone())
+ }
+ 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/branch_target_local_tee.rs b/crates/tinywasm/tests/branch_target_local_tee.rs
new file mode 100644
index 0000000..a58a315
--- /dev/null
+++ b/crates/tinywasm/tests/branch_target_local_tee.rs
@@ -0,0 +1,77 @@
+use tinywasm::{ModuleInstance, Store};
+
+/// A `local.get` right before a label and a `local.tee` right after it must
+/// not be fused: branches land on the label with the value on the stack and
+/// still have to execute the tee.
+#[test]
+fn branches_landing_on_local_tee_still_tee() -> Result<(), Box<dyn core::error::Error>> {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (func $forty_two (result i32) i32.const 42)
+
+ ;; block end label: `br` out of the `if` carries the callee result
+ (func (export "block_end") (param i32 i32) (result i32)
+ block (result i32)
+ local.get 0
+ i32.eqz
+ if
+ call $forty_two
+ br 1
+ end
+ local.get 0
+ end
+ local.tee 1
+ drop
+ local.get 1)
+
+ ;; if/else join label: the then-arm's implicit jump lands on the tee
+ (func (export "if_else_join") (param i32 i32) (result i32)
+ local.get 0
+ if (result i32)
+ call $forty_two
+ else
+ local.get 0
+ end
+ local.tee 1
+ drop
+ local.get 1)
+
+ ;; loop start label: `br 0` re-enters at the tee with the loop param
+ (func (export "loop_start") (param i32 i32) (result i32)
+ local.get 0
+ loop (param i32) (result i32)
+ local.tee 1
+ i32.const 40
+ i32.lt_u
+ if (result i32)
+ local.get 1
+ i32.const 21
+ i32.add
+ br 1
+ else
+ local.get 1
+ end
+ end)
+ )
+ "#,
+ )?;
+
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ let block_end = instance.func::<(i32, i32), i32>(&store, "block_end")?;
+ assert_eq!(block_end.call(&mut store, (5, 7))?, 5, "fallthrough keeps local 0");
+ assert_eq!(block_end.call(&mut store, (0, 7))?, 42, "branch path must tee the callee result");
+
+ let if_else_join = instance.func::<(i32, i32), i32>(&store, "if_else_join")?;
+ assert_eq!(if_else_join.call(&mut store, (0, 7))?, 0, "else arm keeps local 0");
+ assert_eq!(if_else_join.call(&mut store, (1, 7))?, 42, "then arm must tee the callee result");
+
+ let loop_start = instance.func::<(i32, i32), i32>(&store, "loop_start")?;
+ assert_eq!(loop_start.call(&mut store, (40, 7))?, 40, "no iteration keeps the param");
+ assert_eq!(loop_start.call(&mut store, (0, 7))?, 42, "re-entering the loop must tee the carried value");
+
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs
new file mode 100644
index 0000000..9662bee
--- /dev/null
+++ b/crates/tinywasm/tests/gc_refs.rs
@@ -0,0 +1,135 @@
+use tinywasm::types::{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_rooted_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 mut results = [WasmValue::Ref(RefValue::Null)];
+ new.call(&mut first_store, &[], &mut results).unwrap();
+ let [value] = results;
+ assert!(matches!(value, WasmValue::Ref(RefValue::Any(_))));
+ churn.call(&mut first_store, &[], &mut []).unwrap();
+ let mut results = [WasmValue::I32(0)];
+ read.call(&mut first_store, std::slice::from_ref(&value), &mut results).unwrap();
+ assert_eq!(results, [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], &mut [WasmValue::I32(0)]).is_err());
+}
+
+#[test]
+fn externalized_gc_result_is_rooted() {
+ 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 mut results = [WasmValue::Ref(RefValue::Null)];
+ new.call(&mut store, &[], &mut results).unwrap();
+ let [value] = results;
+ assert!(matches!(value, WasmValue::Ref(RefValue::Extern(_))));
+ churn.call(&mut store, &[], &mut []).unwrap();
+ let mut results = [WasmValue::I32(0)];
+ read.call(&mut store, &[value], &mut results).unwrap();
+ assert_eq!(results, [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, &[], &mut [WasmValue::Ref(RefValue::Null)]).unwrap();
+ let host_ref = tinywasm::ExternRef::try_new(&mut store, 0).unwrap().into();
+ assert!(read.call(&mut store, &[host_ref], &mut [WasmValue::I32(0)]).is_err());
+}
+
+#[test]
+fn resumable_gc_result_is_rooted() {
+ 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 results = [WasmValue::Ref(RefValue::Null)];
+ {
+ let mut execution = new.call_resumable(&mut store, &[], &mut results).unwrap();
+ match execution.resume_with_fuel(1000).unwrap() {
+ ExecProgress::Completed(()) => {}
+ ExecProgress::Suspended => panic!("constructor unexpectedly suspended"),
+ }
+ }
+ let [value] = results;
+
+ churn.call(&mut store, &[], &mut []).unwrap();
+ let mut results = [WasmValue::I32(0)];
+ read.call(&mut store, &[value], &mut results).unwrap();
+ assert_eq!(results, [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();
+
+ let mut results = [WasmValue::I32(0)];
+ instance.func_untyped(&store, "first").unwrap().call(&mut store, &[], &mut results).unwrap();
+ assert_eq!(results, [WasmValue::I32(1)]);
+}
diff --git a/crates/tinywasm/tests/generated/wasm-1.csv b/crates/tinywasm/tests/generated/wasm-1.csv
index 8fbf08d..535e57c 100644
--- a/crates/tinywasm/tests/generated/wasm-1.csv
+++ b/crates/tinywasm/tests/generated/wasm-1.csv
@@ -8,4 +8,5 @@
0.9.0,19241,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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,19241,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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,19241,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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,19241,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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,19245,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":81,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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,19245,0,[{"name":"address.wast","passed":243,"failed":0},{"name":"align.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":81,"failed":0},{"name":"binary.wast","passed":67,"failed":0},{"name":"block.wast","passed":171,"failed":0},{"name":"br.wast","passed":84,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":168,"failed":0},{"name":"break-drop.wast","passed":4,"failed":0},{"name":"call.wast","passed":82,"failed":0},{"name":"call_indirect.wast","passed":152,"failed":0},{"name":"comments.wast","passed":4,"failed":0},{"name":"const.wast","passed":668,"failed":0},{"name":"conversions.wast","passed":435,"failed":0},{"name":"custom.wast","passed":10,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":55,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":82,"failed":0},{"name":"f32.wast","passed":2512,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2512,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":7,"failed":0},{"name":"float_exprs.wast","passed":900,"failed":0},{"name":"float_literals.wast","passed":161,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":441,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":121,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"globals.wast","passed":78,"failed":0},{"name":"i32.wast","passed":443,"failed":0},{"name":"i64.wast","passed":389,"failed":0},{"name":"if.wast","passed":151,"failed":0},{"name":"imports.wast","passed":146,"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":116,"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":81,"failed":0},{"name":"memory.wast","passed":71,"failed":0},{"name":"memory_grow.wast","passed":94,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":173,"failed":0},{"name":"names.wast","passed":483,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":111,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":5,"failed":0},{"name":"start.wast","passed":19,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"token.wast","passed":2,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":62,"failed":0},{"name":"unreached-invalid.wast","passed":110,"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-2.csv b/crates/tinywasm/tests/generated/wasm-2.csv
index c2472a7..ac2825c 100644
--- a/crates/tinywasm/tests/generated/wasm-2.csv
+++ b/crates/tinywasm/tests/generated/wasm-2.csv
@@ -13,4 +13,5 @@
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,28012,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":136,"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}]
+0.11.0,28012,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":136,"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..df606ee 100644
--- a/crates/tinywasm/tests/generated/wasm-3.csv
+++ b/crates/tinywasm/tests/generated/wasm-3.csv
@@ -1,3 +1,4 @@
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,21228,0,[{"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":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"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":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":34,"failed":0},{"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}]
+0.11.0,21228,0,[{"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":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"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":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":34,"failed":0},{"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-annotations.csv b/crates/tinywasm/tests/generated/wasm-annotations.csv
deleted file mode 100644
index f24ba50..0000000
--- a/crates/tinywasm/tests/generated/wasm-annotations.csv
+++ /dev/null
@@ -1,5 +0,0 @@
-0.8.0,142,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"annotations/simd_lane.wast (skipped)","passed":0,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.9.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.9.1,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.10.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
-0.11.0-pre.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv b/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv
index e3f7540..c0a9ae5 100644
--- a/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv
+++ b/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv
@@ -3,3 +3,4 @@
0.9.1,207,0,[{"name":"binary.wast","passed":127,"failed":0},{"name":"custom-page-sizes-invalid.wast","passed":23,"failed":0},{"name":"custom-page-sizes.wast","passed":45,"failed":0},{"name":"memory_max.wast","passed":6,"failed":0},{"name":"memory_max_i64.wast","passed":6,"failed":0}]
0.10.0,207,0,[{"name":"binary.wast","passed":127,"failed":0},{"name":"custom-page-sizes-invalid.wast","passed":23,"failed":0},{"name":"custom-page-sizes.wast","passed":45,"failed":0},{"name":"memory_max.wast","passed":6,"failed":0},{"name":"memory_max_i64.wast","passed":6,"failed":0}]
0.11.0-pre.0,207,0,[{"name":"binary.wast","passed":127,"failed":0},{"name":"custom-page-sizes-invalid.wast","passed":23,"failed":0},{"name":"custom-page-sizes.wast","passed":45,"failed":0},{"name":"memory_max.wast","passed":6,"failed":0},{"name":"memory_max_i64.wast","passed":6,"failed":0}]
+0.11.0,207,0,[{"name":"binary.wast","passed":127,"failed":0},{"name":"custom-page-sizes-invalid.wast","passed":23,"failed":0},{"name":"custom-page-sizes.wast","passed":45,"failed":0},{"name":"memory_max.wast","passed":6,"failed":0},{"name":"memory_max_i64.wast","passed":6,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-extended-const.csv b/crates/tinywasm/tests/generated/wasm-extended-const.csv
deleted file mode 100644
index 8677772..0000000
--- a/crates/tinywasm/tests/generated/wasm-extended-const.csv
+++ /dev/null
@@ -1,5 +0,0 @@
-0.8.0,211,79,[{"name":"data.wast","passed":61,"failed":4},{"name":"elem.wast","passed":99,"failed":12},{"name":"global.wast","passed":51,"failed":63}]
-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}]
diff --git a/crates/tinywasm/tests/generated/wasm-function-references.csv b/crates/tinywasm/tests/generated/wasm-function-references.csv
deleted file mode 100644
index 3e59535..0000000
--- a/crates/tinywasm/tests/generated/wasm-function-references.csv
+++ /dev/null
@@ -1,3 +0,0 @@
-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}]
diff --git a/crates/tinywasm/tests/generated/wasm-gc.csv b/crates/tinywasm/tests/generated/wasm-gc.csv
index 5b2995f..0057d7a 100644
--- a/crates/tinywasm/tests/generated/wasm-gc.csv
+++ b/crates/tinywasm/tests/generated/wasm-gc.csv
@@ -1,2 +1,4 @@
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}]
+0.11.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..0af70c7 100644
--- a/crates/tinywasm/tests/generated/wasm-latest.csv
+++ b/crates/tinywasm/tests/generated/wasm-latest.csv
@@ -1,2 +1,4 @@
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,21233,0,[{"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":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"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":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":34,"failed":0},{"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}]
+0.11.0,21233,0,[{"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":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"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":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":34,"failed":0},{"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-memory64.csv b/crates/tinywasm/tests/generated/wasm-memory64.csv
index 6f87044..2a307a1 100644
--- a/crates/tinywasm/tests/generated/wasm-memory64.csv
+++ b/crates/tinywasm/tests/generated/wasm-memory64.csv
@@ -2,4 +2,5 @@
0.9.0,1598,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":169,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
0.9.1,1598,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":169,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
0.10.0,1598,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":169,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
-0.11.0-pre.0,1598,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":169,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
+0.11.0-pre.0,1606,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":177,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
+0.11.0,1606,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"address64.wast","passed":242,"failed":0},{"name":"align64.wast","passed":156,"failed":0},{"name":"binary-leb128.wast","passed":93,"failed":0},{"name":"binary.wast","passed":177,"failed":0},{"name":"endianness64.wast","passed":69,"failed":0},{"name":"float_memory64.wast","passed":90,"failed":0},{"name":"load64.wast","passed":97,"failed":0},{"name":"memory.wast","passed":79,"failed":0},{"name":"memory64.wast","passed":65,"failed":0},{"name":"memory_grow64.wast","passed":49,"failed":0},{"name":"memory_redundancy64.wast","passed":8,"failed":0},{"name":"memory_trap64.wast","passed":172,"failed":0},{"name":"simd_address.wast","passed":49,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-multi-memory.csv b/crates/tinywasm/tests/generated/wasm-multi-memory.csv
index a167d76..145bfb4 100644
--- a/crates/tinywasm/tests/generated/wasm-multi-memory.csv
+++ b/crates/tinywasm/tests/generated/wasm-multi-memory.csv
@@ -3,3 +3,4 @@
0.9.1,912,0,[{"name":"address0.wast","passed":92,"failed":0},{"name":"address1.wast","passed":127,"failed":0},{"name":"align0.wast","passed":5,"failed":0},{"name":"binary0.wast","passed":7,"failed":0},{"name":"data0.wast","passed":7,"failed":0},{"name":"data1.wast","passed":14,"failed":0},{"name":"data_drop0.wast","passed":11,"failed":0},{"name":"exports0.wast","passed":8,"failed":0},{"name":"float_exprs0.wast","passed":14,"failed":0},{"name":"float_exprs1.wast","passed":3,"failed":0},{"name":"float_memory0.wast","passed":30,"failed":0},{"name":"imports0.wast","passed":8,"failed":0},{"name":"imports1.wast","passed":5,"failed":0},{"name":"imports2.wast","passed":20,"failed":0},{"name":"imports3.wast","passed":10,"failed":0},{"name":"imports4.wast","passed":16,"failed":0},{"name":"linking0.wast","passed":6,"failed":0},{"name":"linking1.wast","passed":14,"failed":0},{"name":"linking2.wast","passed":11,"failed":0},{"name":"linking3.wast","passed":14,"failed":0},{"name":"load0.wast","passed":3,"failed":0},{"name":"load1.wast","passed":18,"failed":0},{"name":"load2.wast","passed":38,"failed":0},{"name":"memory-multi.wast","passed":6,"failed":0},{"name":"memory_copy0.wast","passed":29,"failed":0},{"name":"memory_copy1.wast","passed":14,"failed":0},{"name":"memory_fill0.wast","passed":16,"failed":0},{"name":"memory_grow.wast","passed":51,"failed":0},{"name":"memory_init0.wast","passed":13,"failed":0},{"name":"memory_size0.wast","passed":8,"failed":0},{"name":"memory_size1.wast","passed":15,"failed":0},{"name":"memory_size2.wast","passed":21,"failed":0},{"name":"memory_size3.wast","passed":2,"failed":0},{"name":"memory_size_import.wast","passed":7,"failed":0},{"name":"memory_trap0.wast","passed":14,"failed":0},{"name":"memory_trap1.wast","passed":168,"failed":0},{"name":"start0.wast","passed":9,"failed":0},{"name":"store0.wast","passed":5,"failed":0},{"name":"store1.wast","passed":13,"failed":0},{"name":"store2.wast","passed":25,"failed":0},{"name":"traps0.wast","passed":15,"failed":0}]
0.10.0,912,0,[{"name":"address0.wast","passed":92,"failed":0},{"name":"address1.wast","passed":127,"failed":0},{"name":"align0.wast","passed":5,"failed":0},{"name":"binary0.wast","passed":7,"failed":0},{"name":"data0.wast","passed":7,"failed":0},{"name":"data1.wast","passed":14,"failed":0},{"name":"data_drop0.wast","passed":11,"failed":0},{"name":"exports0.wast","passed":8,"failed":0},{"name":"float_exprs0.wast","passed":14,"failed":0},{"name":"float_exprs1.wast","passed":3,"failed":0},{"name":"float_memory0.wast","passed":30,"failed":0},{"name":"imports0.wast","passed":8,"failed":0},{"name":"imports1.wast","passed":5,"failed":0},{"name":"imports2.wast","passed":20,"failed":0},{"name":"imports3.wast","passed":10,"failed":0},{"name":"imports4.wast","passed":16,"failed":0},{"name":"linking0.wast","passed":6,"failed":0},{"name":"linking1.wast","passed":14,"failed":0},{"name":"linking2.wast","passed":11,"failed":0},{"name":"linking3.wast","passed":14,"failed":0},{"name":"load0.wast","passed":3,"failed":0},{"name":"load1.wast","passed":18,"failed":0},{"name":"load2.wast","passed":38,"failed":0},{"name":"memory-multi.wast","passed":6,"failed":0},{"name":"memory_copy0.wast","passed":29,"failed":0},{"name":"memory_copy1.wast","passed":14,"failed":0},{"name":"memory_fill0.wast","passed":16,"failed":0},{"name":"memory_grow.wast","passed":51,"failed":0},{"name":"memory_init0.wast","passed":13,"failed":0},{"name":"memory_size0.wast","passed":8,"failed":0},{"name":"memory_size1.wast","passed":15,"failed":0},{"name":"memory_size2.wast","passed":21,"failed":0},{"name":"memory_size3.wast","passed":2,"failed":0},{"name":"memory_size_import.wast","passed":7,"failed":0},{"name":"memory_trap0.wast","passed":14,"failed":0},{"name":"memory_trap1.wast","passed":168,"failed":0},{"name":"start0.wast","passed":9,"failed":0},{"name":"store0.wast","passed":5,"failed":0},{"name":"store1.wast","passed":13,"failed":0},{"name":"store2.wast","passed":25,"failed":0},{"name":"traps0.wast","passed":15,"failed":0}]
0.11.0-pre.0,912,0,[{"name":"address0.wast","passed":92,"failed":0},{"name":"address1.wast","passed":127,"failed":0},{"name":"align0.wast","passed":5,"failed":0},{"name":"binary0.wast","passed":7,"failed":0},{"name":"data0.wast","passed":7,"failed":0},{"name":"data1.wast","passed":14,"failed":0},{"name":"data_drop0.wast","passed":11,"failed":0},{"name":"exports0.wast","passed":8,"failed":0},{"name":"float_exprs0.wast","passed":14,"failed":0},{"name":"float_exprs1.wast","passed":3,"failed":0},{"name":"float_memory0.wast","passed":30,"failed":0},{"name":"imports0.wast","passed":8,"failed":0},{"name":"imports1.wast","passed":5,"failed":0},{"name":"imports2.wast","passed":20,"failed":0},{"name":"imports3.wast","passed":10,"failed":0},{"name":"imports4.wast","passed":16,"failed":0},{"name":"linking0.wast","passed":6,"failed":0},{"name":"linking1.wast","passed":14,"failed":0},{"name":"linking2.wast","passed":11,"failed":0},{"name":"linking3.wast","passed":14,"failed":0},{"name":"load0.wast","passed":3,"failed":0},{"name":"load1.wast","passed":18,"failed":0},{"name":"load2.wast","passed":38,"failed":0},{"name":"memory-multi.wast","passed":6,"failed":0},{"name":"memory_copy0.wast","passed":29,"failed":0},{"name":"memory_copy1.wast","passed":14,"failed":0},{"name":"memory_fill0.wast","passed":16,"failed":0},{"name":"memory_grow.wast","passed":51,"failed":0},{"name":"memory_init0.wast","passed":13,"failed":0},{"name":"memory_size0.wast","passed":8,"failed":0},{"name":"memory_size1.wast","passed":15,"failed":0},{"name":"memory_size2.wast","passed":21,"failed":0},{"name":"memory_size3.wast","passed":2,"failed":0},{"name":"memory_size_import.wast","passed":7,"failed":0},{"name":"memory_trap0.wast","passed":14,"failed":0},{"name":"memory_trap1.wast","passed":168,"failed":0},{"name":"start0.wast","passed":9,"failed":0},{"name":"store0.wast","passed":5,"failed":0},{"name":"store1.wast","passed":13,"failed":0},{"name":"store2.wast","passed":25,"failed":0},{"name":"traps0.wast","passed":15,"failed":0}]
+0.11.0,912,0,[{"name":"address0.wast","passed":92,"failed":0},{"name":"address1.wast","passed":127,"failed":0},{"name":"align0.wast","passed":5,"failed":0},{"name":"binary0.wast","passed":7,"failed":0},{"name":"data0.wast","passed":7,"failed":0},{"name":"data1.wast","passed":14,"failed":0},{"name":"data_drop0.wast","passed":11,"failed":0},{"name":"exports0.wast","passed":8,"failed":0},{"name":"float_exprs0.wast","passed":14,"failed":0},{"name":"float_exprs1.wast","passed":3,"failed":0},{"name":"float_memory0.wast","passed":30,"failed":0},{"name":"imports0.wast","passed":8,"failed":0},{"name":"imports1.wast","passed":5,"failed":0},{"name":"imports2.wast","passed":20,"failed":0},{"name":"imports3.wast","passed":10,"failed":0},{"name":"imports4.wast","passed":16,"failed":0},{"name":"linking0.wast","passed":6,"failed":0},{"name":"linking1.wast","passed":14,"failed":0},{"name":"linking2.wast","passed":11,"failed":0},{"name":"linking3.wast","passed":14,"failed":0},{"name":"load0.wast","passed":3,"failed":0},{"name":"load1.wast","passed":18,"failed":0},{"name":"load2.wast","passed":38,"failed":0},{"name":"memory-multi.wast","passed":6,"failed":0},{"name":"memory_copy0.wast","passed":29,"failed":0},{"name":"memory_copy1.wast","passed":14,"failed":0},{"name":"memory_fill0.wast","passed":16,"failed":0},{"name":"memory_grow.wast","passed":51,"failed":0},{"name":"memory_init0.wast","passed":13,"failed":0},{"name":"memory_size0.wast","passed":8,"failed":0},{"name":"memory_size1.wast","passed":15,"failed":0},{"name":"memory_size2.wast","passed":21,"failed":0},{"name":"memory_size3.wast","passed":2,"failed":0},{"name":"memory_size_import.wast","passed":7,"failed":0},{"name":"memory_trap0.wast","passed":14,"failed":0},{"name":"memory_trap1.wast","passed":168,"failed":0},{"name":"start0.wast","passed":9,"failed":0},{"name":"store0.wast","passed":5,"failed":0},{"name":"store1.wast","passed":13,"failed":0},{"name":"store2.wast","passed":25,"failed":0},{"name":"traps0.wast","passed":15,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv b/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv
deleted file mode 100644
index 66d5329..0000000
--- a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.9.1,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.10.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
-0.11.0-pre.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-reference-types.csv b/crates/tinywasm/tests/generated/wasm-reference-types.csv
deleted file mode 100644
index 92a4650..0000000
--- a/crates/tinywasm/tests/generated/wasm-reference-types.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"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":"select.wast","passed":141,"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":50,"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":"unreached-invalid.wast","passed":111,"failed":0}]
-0.9.1,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"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":"select.wast","passed":141,"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":50,"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":"unreached-invalid.wast","passed":111,"failed":0}]
-0.10.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"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":"select.wast","passed":141,"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":50,"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":"unreached-invalid.wast","passed":111,"failed":0}]
-0.11.0-pre.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"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":"select.wast","passed":141,"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":50,"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":"unreached-invalid.wast","passed":111,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv b/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv
index 56ca1b5..4716ba8 100644
--- a/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv
+++ b/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv
@@ -2,3 +2,4 @@
0.9.1,77,0,[{"name":"i16x8_relaxed_q15mulr_s.wast","passed":3,"failed":0},{"name":"i32x4_relaxed_trunc.wast","passed":1,"failed":0},{"name":"i8x16_relaxed_swizzle.wast","passed":6,"failed":0},{"name":"relaxed_dot_product.wast","passed":11,"failed":0},{"name":"relaxed_laneselect.wast","passed":12,"failed":0},{"name":"relaxed_madd_nmadd.wast","passed":19,"failed":0},{"name":"relaxed_min_max.wast","passed":25,"failed":0}]
0.10.0,77,0,[{"name":"i16x8_relaxed_q15mulr_s.wast","passed":3,"failed":0},{"name":"i32x4_relaxed_trunc.wast","passed":1,"failed":0},{"name":"i8x16_relaxed_swizzle.wast","passed":6,"failed":0},{"name":"relaxed_dot_product.wast","passed":11,"failed":0},{"name":"relaxed_laneselect.wast","passed":12,"failed":0},{"name":"relaxed_madd_nmadd.wast","passed":19,"failed":0},{"name":"relaxed_min_max.wast","passed":25,"failed":0}]
0.11.0-pre.0,77,0,[{"name":"i16x8_relaxed_q15mulr_s.wast","passed":3,"failed":0},{"name":"i32x4_relaxed_trunc.wast","passed":1,"failed":0},{"name":"i8x16_relaxed_swizzle.wast","passed":6,"failed":0},{"name":"relaxed_dot_product.wast","passed":11,"failed":0},{"name":"relaxed_laneselect.wast","passed":12,"failed":0},{"name":"relaxed_madd_nmadd.wast","passed":19,"failed":0},{"name":"relaxed_min_max.wast","passed":25,"failed":0}]
+0.11.0,77,0,[{"name":"i16x8_relaxed_q15mulr_s.wast","passed":3,"failed":0},{"name":"i32x4_relaxed_trunc.wast","passed":1,"failed":0},{"name":"i8x16_relaxed_swizzle.wast","passed":6,"failed":0},{"name":"relaxed_dot_product.wast","passed":11,"failed":0},{"name":"relaxed_laneselect.wast","passed":12,"failed":0},{"name":"relaxed_madd_nmadd.wast","passed":19,"failed":0},{"name":"relaxed_min_max.wast","passed":25,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv b/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv
deleted file mode 100644
index 4e7e2ee..0000000
--- a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.9.1,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.10.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
-0.11.0-pre.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-simd.csv b/crates/tinywasm/tests/generated/wasm-simd.csv
index 605c09d..5921e05 100644
--- a/crates/tinywasm/tests/generated/wasm-simd.csv
+++ b/crates/tinywasm/tests/generated/wasm-simd.csv
@@ -3,3 +3,4 @@
0.9.1,25990,0,[{"name":"simd_address.wast","passed":49,"failed":0},{"name":"simd_align.wast","passed":100,"failed":0},{"name":"simd_bit_shift.wast","passed":252,"failed":0},{"name":"simd_bitwise.wast","passed":169,"failed":0},{"name":"simd_boolean.wast","passed":277,"failed":0},{"name":"simd_const.wast","passed":758,"failed":0},{"name":"simd_conversions.wast","passed":282,"failed":0},{"name":"simd_f32x4.wast","passed":790,"failed":0},{"name":"simd_f32x4_arith.wast","passed":1822,"failed":0},{"name":"simd_f32x4_cmp.wast","passed":2607,"failed":0},{"name":"simd_f32x4_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f32x4_rounding.wast","passed":201,"failed":0},{"name":"simd_f64x2.wast","passed":803,"failed":0},{"name":"simd_f64x2_arith.wast","passed":1825,"failed":0},{"name":"simd_f64x2_cmp.wast","passed":2685,"failed":0},{"name":"simd_f64x2_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f64x2_rounding.wast","passed":201,"failed":0},{"name":"simd_i16x8_arith.wast","passed":194,"failed":0},{"name":"simd_i16x8_arith2.wast","passed":172,"failed":0},{"name":"simd_i16x8_cmp.wast","passed":465,"failed":0},{"name":"simd_i16x8_extadd_pairwise_i8x16.wast","passed":21,"failed":0},{"name":"simd_i16x8_extmul_i8x16.wast","passed":117,"failed":0},{"name":"simd_i16x8_q15mulr_sat_s.wast","passed":30,"failed":0},{"name":"simd_i16x8_sat_arith.wast","passed":222,"failed":0},{"name":"simd_i32x4_arith.wast","passed":194,"failed":0},{"name":"simd_i32x4_arith2.wast","passed":149,"failed":0},{"name":"simd_i32x4_cmp.wast","passed":475,"failed":0},{"name":"simd_i32x4_dot_i16x8.wast","passed":32,"failed":0},{"name":"simd_i32x4_extadd_pairwise_i16x8.wast","passed":21,"failed":0},{"name":"simd_i32x4_extmul_i16x8.wast","passed":117,"failed":0},{"name":"simd_i32x4_trunc_sat_f32x4.wast","passed":107,"failed":0},{"name":"simd_i32x4_trunc_sat_f64x2.wast","passed":107,"failed":0},{"name":"simd_i64x2_arith.wast","passed":200,"failed":0},{"name":"simd_i64x2_arith2.wast","passed":25,"failed":0},{"name":"simd_i64x2_cmp.wast","passed":113,"failed":0},{"name":"simd_i64x2_extmul_i32x4.wast","passed":117,"failed":0},{"name":"simd_i8x16_arith.wast","passed":131,"failed":0},{"name":"simd_i8x16_arith2.wast","passed":211,"failed":0},{"name":"simd_i8x16_cmp.wast","passed":445,"failed":0},{"name":"simd_i8x16_sat_arith.wast","passed":214,"failed":0},{"name":"simd_int_to_int_extend.wast","passed":253,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"simd_linking.wast","passed":3,"failed":0},{"name":"simd_load.wast","passed":39,"failed":0},{"name":"simd_load16_lane.wast","passed":36,"failed":0},{"name":"simd_load32_lane.wast","passed":24,"failed":0},{"name":"simd_load64_lane.wast","passed":16,"failed":0},{"name":"simd_load8_lane.wast","passed":52,"failed":0},{"name":"simd_load_extend.wast","passed":104,"failed":0},{"name":"simd_load_splat.wast","passed":126,"failed":0},{"name":"simd_load_zero.wast","passed":39,"failed":0},{"name":"simd_memory-multi.wast","passed":1,"failed":0},{"name":"simd_select.wast","passed":7,"failed":0},{"name":"simd_splat.wast","passed":185,"failed":0},{"name":"simd_store.wast","passed":28,"failed":0},{"name":"simd_store16_lane.wast","passed":36,"failed":0},{"name":"simd_store32_lane.wast","passed":24,"failed":0},{"name":"simd_store64_lane.wast","passed":16,"failed":0},{"name":"simd_store8_lane.wast","passed":52,"failed":0}]
0.10.0,25990,0,[{"name":"simd_address.wast","passed":49,"failed":0},{"name":"simd_align.wast","passed":100,"failed":0},{"name":"simd_bit_shift.wast","passed":252,"failed":0},{"name":"simd_bitwise.wast","passed":169,"failed":0},{"name":"simd_boolean.wast","passed":277,"failed":0},{"name":"simd_const.wast","passed":758,"failed":0},{"name":"simd_conversions.wast","passed":282,"failed":0},{"name":"simd_f32x4.wast","passed":790,"failed":0},{"name":"simd_f32x4_arith.wast","passed":1822,"failed":0},{"name":"simd_f32x4_cmp.wast","passed":2607,"failed":0},{"name":"simd_f32x4_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f32x4_rounding.wast","passed":201,"failed":0},{"name":"simd_f64x2.wast","passed":803,"failed":0},{"name":"simd_f64x2_arith.wast","passed":1825,"failed":0},{"name":"simd_f64x2_cmp.wast","passed":2685,"failed":0},{"name":"simd_f64x2_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f64x2_rounding.wast","passed":201,"failed":0},{"name":"simd_i16x8_arith.wast","passed":194,"failed":0},{"name":"simd_i16x8_arith2.wast","passed":172,"failed":0},{"name":"simd_i16x8_cmp.wast","passed":465,"failed":0},{"name":"simd_i16x8_extadd_pairwise_i8x16.wast","passed":21,"failed":0},{"name":"simd_i16x8_extmul_i8x16.wast","passed":117,"failed":0},{"name":"simd_i16x8_q15mulr_sat_s.wast","passed":30,"failed":0},{"name":"simd_i16x8_sat_arith.wast","passed":222,"failed":0},{"name":"simd_i32x4_arith.wast","passed":194,"failed":0},{"name":"simd_i32x4_arith2.wast","passed":149,"failed":0},{"name":"simd_i32x4_cmp.wast","passed":475,"failed":0},{"name":"simd_i32x4_dot_i16x8.wast","passed":32,"failed":0},{"name":"simd_i32x4_extadd_pairwise_i16x8.wast","passed":21,"failed":0},{"name":"simd_i32x4_extmul_i16x8.wast","passed":117,"failed":0},{"name":"simd_i32x4_trunc_sat_f32x4.wast","passed":107,"failed":0},{"name":"simd_i32x4_trunc_sat_f64x2.wast","passed":107,"failed":0},{"name":"simd_i64x2_arith.wast","passed":200,"failed":0},{"name":"simd_i64x2_arith2.wast","passed":25,"failed":0},{"name":"simd_i64x2_cmp.wast","passed":113,"failed":0},{"name":"simd_i64x2_extmul_i32x4.wast","passed":117,"failed":0},{"name":"simd_i8x16_arith.wast","passed":131,"failed":0},{"name":"simd_i8x16_arith2.wast","passed":211,"failed":0},{"name":"simd_i8x16_cmp.wast","passed":445,"failed":0},{"name":"simd_i8x16_sat_arith.wast","passed":214,"failed":0},{"name":"simd_int_to_int_extend.wast","passed":253,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"simd_linking.wast","passed":3,"failed":0},{"name":"simd_load.wast","passed":39,"failed":0},{"name":"simd_load16_lane.wast","passed":36,"failed":0},{"name":"simd_load32_lane.wast","passed":24,"failed":0},{"name":"simd_load64_lane.wast","passed":16,"failed":0},{"name":"simd_load8_lane.wast","passed":52,"failed":0},{"name":"simd_load_extend.wast","passed":104,"failed":0},{"name":"simd_load_splat.wast","passed":126,"failed":0},{"name":"simd_load_zero.wast","passed":39,"failed":0},{"name":"simd_memory-multi.wast","passed":1,"failed":0},{"name":"simd_select.wast","passed":7,"failed":0},{"name":"simd_splat.wast","passed":185,"failed":0},{"name":"simd_store.wast","passed":28,"failed":0},{"name":"simd_store16_lane.wast","passed":36,"failed":0},{"name":"simd_store32_lane.wast","passed":24,"failed":0},{"name":"simd_store64_lane.wast","passed":16,"failed":0},{"name":"simd_store8_lane.wast","passed":52,"failed":0}]
0.11.0-pre.0,25990,0,[{"name":"simd_address.wast","passed":49,"failed":0},{"name":"simd_align.wast","passed":100,"failed":0},{"name":"simd_bit_shift.wast","passed":252,"failed":0},{"name":"simd_bitwise.wast","passed":169,"failed":0},{"name":"simd_boolean.wast","passed":277,"failed":0},{"name":"simd_const.wast","passed":758,"failed":0},{"name":"simd_conversions.wast","passed":282,"failed":0},{"name":"simd_f32x4.wast","passed":790,"failed":0},{"name":"simd_f32x4_arith.wast","passed":1822,"failed":0},{"name":"simd_f32x4_cmp.wast","passed":2607,"failed":0},{"name":"simd_f32x4_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f32x4_rounding.wast","passed":201,"failed":0},{"name":"simd_f64x2.wast","passed":803,"failed":0},{"name":"simd_f64x2_arith.wast","passed":1825,"failed":0},{"name":"simd_f64x2_cmp.wast","passed":2685,"failed":0},{"name":"simd_f64x2_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f64x2_rounding.wast","passed":201,"failed":0},{"name":"simd_i16x8_arith.wast","passed":194,"failed":0},{"name":"simd_i16x8_arith2.wast","passed":172,"failed":0},{"name":"simd_i16x8_cmp.wast","passed":465,"failed":0},{"name":"simd_i16x8_extadd_pairwise_i8x16.wast","passed":21,"failed":0},{"name":"simd_i16x8_extmul_i8x16.wast","passed":117,"failed":0},{"name":"simd_i16x8_q15mulr_sat_s.wast","passed":30,"failed":0},{"name":"simd_i16x8_sat_arith.wast","passed":222,"failed":0},{"name":"simd_i32x4_arith.wast","passed":194,"failed":0},{"name":"simd_i32x4_arith2.wast","passed":149,"failed":0},{"name":"simd_i32x4_cmp.wast","passed":475,"failed":0},{"name":"simd_i32x4_dot_i16x8.wast","passed":32,"failed":0},{"name":"simd_i32x4_extadd_pairwise_i16x8.wast","passed":21,"failed":0},{"name":"simd_i32x4_extmul_i16x8.wast","passed":117,"failed":0},{"name":"simd_i32x4_trunc_sat_f32x4.wast","passed":107,"failed":0},{"name":"simd_i32x4_trunc_sat_f64x2.wast","passed":107,"failed":0},{"name":"simd_i64x2_arith.wast","passed":200,"failed":0},{"name":"simd_i64x2_arith2.wast","passed":25,"failed":0},{"name":"simd_i64x2_cmp.wast","passed":113,"failed":0},{"name":"simd_i64x2_extmul_i32x4.wast","passed":117,"failed":0},{"name":"simd_i8x16_arith.wast","passed":131,"failed":0},{"name":"simd_i8x16_arith2.wast","passed":211,"failed":0},{"name":"simd_i8x16_cmp.wast","passed":445,"failed":0},{"name":"simd_i8x16_sat_arith.wast","passed":214,"failed":0},{"name":"simd_int_to_int_extend.wast","passed":253,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"simd_linking.wast","passed":3,"failed":0},{"name":"simd_load.wast","passed":39,"failed":0},{"name":"simd_load16_lane.wast","passed":36,"failed":0},{"name":"simd_load32_lane.wast","passed":24,"failed":0},{"name":"simd_load64_lane.wast","passed":16,"failed":0},{"name":"simd_load8_lane.wast","passed":52,"failed":0},{"name":"simd_load_extend.wast","passed":104,"failed":0},{"name":"simd_load_splat.wast","passed":126,"failed":0},{"name":"simd_load_zero.wast","passed":39,"failed":0},{"name":"simd_memory-multi.wast","passed":1,"failed":0},{"name":"simd_select.wast","passed":7,"failed":0},{"name":"simd_splat.wast","passed":185,"failed":0},{"name":"simd_store.wast","passed":28,"failed":0},{"name":"simd_store16_lane.wast","passed":36,"failed":0},{"name":"simd_store32_lane.wast","passed":24,"failed":0},{"name":"simd_store64_lane.wast","passed":16,"failed":0},{"name":"simd_store8_lane.wast","passed":52,"failed":0}]
+0.11.0,25990,0,[{"name":"simd_address.wast","passed":49,"failed":0},{"name":"simd_align.wast","passed":100,"failed":0},{"name":"simd_bit_shift.wast","passed":252,"failed":0},{"name":"simd_bitwise.wast","passed":169,"failed":0},{"name":"simd_boolean.wast","passed":277,"failed":0},{"name":"simd_const.wast","passed":758,"failed":0},{"name":"simd_conversions.wast","passed":282,"failed":0},{"name":"simd_f32x4.wast","passed":790,"failed":0},{"name":"simd_f32x4_arith.wast","passed":1822,"failed":0},{"name":"simd_f32x4_cmp.wast","passed":2607,"failed":0},{"name":"simd_f32x4_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f32x4_rounding.wast","passed":201,"failed":0},{"name":"simd_f64x2.wast","passed":803,"failed":0},{"name":"simd_f64x2_arith.wast","passed":1825,"failed":0},{"name":"simd_f64x2_cmp.wast","passed":2685,"failed":0},{"name":"simd_f64x2_pmin_pmax.wast","passed":3887,"failed":0},{"name":"simd_f64x2_rounding.wast","passed":201,"failed":0},{"name":"simd_i16x8_arith.wast","passed":194,"failed":0},{"name":"simd_i16x8_arith2.wast","passed":172,"failed":0},{"name":"simd_i16x8_cmp.wast","passed":465,"failed":0},{"name":"simd_i16x8_extadd_pairwise_i8x16.wast","passed":21,"failed":0},{"name":"simd_i16x8_extmul_i8x16.wast","passed":117,"failed":0},{"name":"simd_i16x8_q15mulr_sat_s.wast","passed":30,"failed":0},{"name":"simd_i16x8_sat_arith.wast","passed":222,"failed":0},{"name":"simd_i32x4_arith.wast","passed":194,"failed":0},{"name":"simd_i32x4_arith2.wast","passed":149,"failed":0},{"name":"simd_i32x4_cmp.wast","passed":475,"failed":0},{"name":"simd_i32x4_dot_i16x8.wast","passed":32,"failed":0},{"name":"simd_i32x4_extadd_pairwise_i16x8.wast","passed":21,"failed":0},{"name":"simd_i32x4_extmul_i16x8.wast","passed":117,"failed":0},{"name":"simd_i32x4_trunc_sat_f32x4.wast","passed":107,"failed":0},{"name":"simd_i32x4_trunc_sat_f64x2.wast","passed":107,"failed":0},{"name":"simd_i64x2_arith.wast","passed":200,"failed":0},{"name":"simd_i64x2_arith2.wast","passed":25,"failed":0},{"name":"simd_i64x2_cmp.wast","passed":113,"failed":0},{"name":"simd_i64x2_extmul_i32x4.wast","passed":117,"failed":0},{"name":"simd_i8x16_arith.wast","passed":131,"failed":0},{"name":"simd_i8x16_arith2.wast","passed":211,"failed":0},{"name":"simd_i8x16_cmp.wast","passed":445,"failed":0},{"name":"simd_i8x16_sat_arith.wast","passed":214,"failed":0},{"name":"simd_int_to_int_extend.wast","passed":253,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"simd_linking.wast","passed":3,"failed":0},{"name":"simd_load.wast","passed":39,"failed":0},{"name":"simd_load16_lane.wast","passed":36,"failed":0},{"name":"simd_load32_lane.wast","passed":24,"failed":0},{"name":"simd_load64_lane.wast","passed":16,"failed":0},{"name":"simd_load8_lane.wast","passed":52,"failed":0},{"name":"simd_load_extend.wast","passed":104,"failed":0},{"name":"simd_load_splat.wast","passed":126,"failed":0},{"name":"simd_load_zero.wast","passed":39,"failed":0},{"name":"simd_memory-multi.wast","passed":1,"failed":0},{"name":"simd_select.wast","passed":7,"failed":0},{"name":"simd_splat.wast","passed":185,"failed":0},{"name":"simd_store.wast","passed":28,"failed":0},{"name":"simd_store16_lane.wast","passed":36,"failed":0},{"name":"simd_store32_lane.wast","passed":24,"failed":0},{"name":"simd_store64_lane.wast","passed":16,"failed":0},{"name":"simd_store8_lane.wast","passed":52,"failed":0}]
diff --git a/crates/tinywasm/tests/generated/wasm-tail-call.csv b/crates/tinywasm/tests/generated/wasm-tail-call.csv
deleted file mode 100644
index 316895d..0000000
--- a/crates/tinywasm/tests/generated/wasm-tail-call.csv
+++ /dev/null
@@ -1,4 +0,0 @@
-0.9.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.9.1,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.10.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}]
-0.11.0-pre.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"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/generated/wasm-wide-arithmetic.csv b/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv
index dfbff12..d740038 100644
--- a/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv
+++ b/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv
@@ -2,3 +2,4 @@
0.9.1,109,0,[{"name":"wide-arithmetic.wast","passed":109,"failed":0}]
0.10.0,109,0,[{"name":"wide-arithmetic.wast","passed":109,"failed":0}]
0.11.0-pre.0,109,0,[{"name":"wide-arithmetic.wast","passed":109,"failed":0}]
+0.11.0,109,0,[{"name":"wide-arithmetic.wast","passed":109,"failed":0}]
diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs
index b3b5048..5eee068 100644
--- a/crates/tinywasm/tests/host_func_signature_check.rs
+++ b/crates/tinywasm/tests/host_func_signature_check.rs
@@ -1,8 +1,30 @@
-use eyre::Result;
use std::fmt::Write;
-use tinywasm::types::{FuncType, RefValue, WasmType, WasmValue};
-use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store};
-use tinywasm_types::ExternRef;
+use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue};
+use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, WasmTypes};
+
+struct TooFewParams;
+
+impl WasmTypes for TooFewParams {
+ const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32];
+}
+
+impl IntoWasmValues for TooFewParams {
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> {
+ [WasmValue::I32(1)].into_iter()
+ }
+}
+
+struct TooManyParams;
+
+impl WasmTypes for TooManyParams {
+ const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32];
+}
+
+impl IntoWasmValues for TooManyParams {
+ fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> {
+ [WasmValue::I32(1), WasmValue::I32(2), WasmValue::I32(3)].into_iter()
+ }
+}
const VAL_LISTS: &[&[WasmValue]] = &[
&[],
@@ -10,7 +32,6 @@ const VAL_LISTS: &[&[WasmValue]] = &[
&[WasmValue::I32(0), WasmValue::I32(0)],
&[WasmValue::I32(0), WasmValue::I32(0), WasmValue::F64(0.0)],
&[WasmValue::I32(0), WasmValue::F64(0.0), WasmValue::I32(0)],
- &[WasmValue::Ref(RefValue::Extern(ExternRef::new(0))), WasmValue::F64(0.0), WasmValue::I32(0)],
];
fn module_cases() -> Vec<(Module, FuncType, Vec<WasmValue>)> {
@@ -27,22 +48,29 @@ fn module_cases() -> Vec<(Module, FuncType, Vec<WasmValue>)> {
}
#[test]
-fn test_return_invalid_type() -> Result<()> {
+fn test_return_invalid_type() -> Result<(), Box<dyn core::error::Error>> {
let cases = module_cases();
for (module, ty, args) in cases {
for returned_values in VAL_LISTS {
let mut store = Store::default();
let mut imports = Imports::new();
- let hfn = HostFunction::from_untyped(&mut store, &ty, |_: FuncContext<'_>, _| Ok(returned_values.to_vec()));
+ let hfn = HostFunction::from_untyped(&ty, move |_: FuncContext<'_>, _, results| {
+ if results.len() != returned_values.len() {
+ return Err(tinywasm::Error::Other("invalid fixture result count".into()));
+ }
+ results.clone_from_slice(returned_values);
+ Ok(())
+ });
imports.define("host", "hfn", hfn);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports)).unwrap();
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap();
let caller = instance.func_untyped(&store, "call_hfn").unwrap();
// Return-type mismatch is only observable at call time.
let should_succeed = returned_values.len() == ty.results().len()
&& returned_values.iter().zip(ty.results()).all(|(value, ty)| value.matches_type(*ty));
- let call_res = caller.call(&mut store, &args);
+ let mut results = vec![WasmValue::I32(0); ty.results().len()];
+ let call_res = caller.call(&mut store, &args, &mut results);
assert_eq!(call_res.is_ok(), should_succeed);
}
}
@@ -51,18 +79,18 @@ fn test_return_invalid_type() -> Result<()> {
}
#[test]
-fn test_linking_invalid_untyped_func() -> Result<()> {
+fn test_linking_invalid_untyped_func() -> Result<(), Box<dyn core::error::Error>> {
let cases = module_cases();
for (module, expected_func_ty, _) in &cases {
for (_, ty, _) in &cases {
let mut store = Store::default();
let tried_fn =
- HostFunction::from_untyped(&mut store, ty, |_: FuncContext<'_>, _| panic!("not intended to be called"));
+ HostFunction::from_untyped(ty, |_: FuncContext<'_>, _, _| panic!("not intended to be called"));
let mut imports = Imports::new();
imports.define("host", "hfn", tried_fn);
let should_succeed = ty == expected_func_ty;
- let link_res = ModuleInstance::instantiate(&mut store, module, Some(imports));
+ let link_res = ModuleInstance::instantiate(&mut store, module, Some(&imports));
assert_eq!(link_res.is_ok(), should_succeed);
}
}
@@ -70,7 +98,7 @@ fn test_linking_invalid_untyped_func() -> Result<()> {
}
#[test]
-fn test_linking_invalid_typed_func() -> Result<()> {
+fn test_linking_invalid_typed_func() -> Result<(), Box<dyn core::error::Error>> {
type Existing = (i32, i32, f64);
type NonMatchingSingle = f64;
type NonMatchingTuple = (f64, i32, i32);
@@ -80,26 +108,18 @@ fn test_linking_invalid_typed_func() -> Result<()> {
for (module, _, _) in cases {
let mut store = Store::default();
let matching_none = vec![
- HostFunction::from(&mut store, |_, _: NonMatchingTuple| -> tinywasm::Result<Existing> {
- panic!("{DONT_CALL}")
- }),
- HostFunction::from(&mut store, |_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }),
- HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<Existing> {
- panic!("{DONT_CALL}")
- }),
- HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }),
- HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result<NonMatchingTuple> {
+ HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result<Existing> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<Existing> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: Existing| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: Existing| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: ()| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: ()| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }),
+ HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingTuple> {
panic!("{DONT_CALL}")
}),
- HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result<NonMatchingSingle> {
- panic!("{DONT_CALL}")
- }),
- HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }),
- HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }),
- HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingTuple> {
- panic!("{DONT_CALL}")
- }),
- HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingSingle> {
+ HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingSingle> {
panic!("{DONT_CALL}")
}),
];
@@ -107,7 +127,7 @@ fn test_linking_invalid_typed_func() -> Result<()> {
for typed_fn in matching_none {
let mut imports = Imports::new();
imports.define("host", "hfn", typed_fn);
- let link_failure = ModuleInstance::instantiate(&mut store, &module, Some(imports));
+ let link_failure = ModuleInstance::instantiate(&mut store, &module, Some(&imports));
assert!(link_failure.is_err(), "Expected linking to fail for mismatched typed func, but it succeeded");
}
}
@@ -116,7 +136,79 @@ fn test_linking_invalid_typed_func() -> Result<()> {
}
#[test]
-fn concrete_host_references_use_canonical_types() -> Result<()> {
+fn typed_v128_values_roundtrip() -> Result<(), Box<dyn core::error::Error>> {
+ let module = tinywasm::parse_bytes(&wat::parse_str(
+ r#"
+ (module
+ (import "host" "identity" (func $identity (param v128) (result v128)))
+ (func (export "identity") (param v128) (result v128)
+ local.get 0
+ call $identity))
+ "#,
+ )?)?;
+ let mut store = Store::default();
+ let mut imports = Imports::new();
+ imports.define("host", "identity", HostFunction::from(|_, value: [u8; 16]| Ok(value)));
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ let identity = instance.func::<[u8; 16], [u8; 16]>(&store, "identity")?;
+ let value = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
+
+ assert_eq!(identity.call(&mut store, value)?, value);
+ Ok(())
+}
+
+#[test]
+fn untyped_host_callbacks_must_write_all_results() -> Result<(), Box<dyn core::error::Error>> {
+ let ty = FuncType::new(&[], &[WasmType::I32]);
+ let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(()));
+ let mut store = Store::default();
+ let function = host.clone().instantiate(&mut store)?;
+ let mut results = [WasmValue::I32(7)];
+
+ assert!(function.call(&mut store, &[], &mut results).is_err());
+ assert!(function.call_resumable(&mut store, &[], &mut results).is_err());
+
+ let module = tinywasm::parse_bytes(&wat::parse_str(
+ r#"
+ (module
+ (import "host" "value" (func $value (result i32)))
+ (func (export "value") (result i32) call $value))
+ "#,
+ )?)?;
+ let mut imports = Imports::new();
+ imports.define("host", "value", host);
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ let function = instance.func_untyped(&store, "value")?;
+
+ assert!(function.call(&mut store, &[], &mut results).is_err());
+ Ok(())
+}
+
+#[test]
+fn typed_untyped_bridge_rejects_inexact_parameter_iterators() -> Result<(), Box<dyn core::error::Error>> {
+ let module = tinywasm::parse_bytes(&wat::parse_str(
+ r#"
+ (module
+ (import "host" "take" (func $take (param i32 i32)))
+ (export "take" (func $take)))
+ "#,
+ )?)?;
+ let mut store = Store::default();
+ let mut imports = Imports::new();
+ imports.define(
+ "host",
+ "take",
+ HostFunction::from_untyped(&FuncType::new(&[WasmType::I32, WasmType::I32], &[]), |_, _, _| Ok(())),
+ );
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+
+ assert!(instance.func::<TooFewParams, ()>(&store, "take")?.call(&mut store, TooFewParams).is_err());
+ assert!(instance.func::<TooManyParams, ()>(&store, "take")?.call(&mut store, TooManyParams).is_err());
+ Ok(())
+}
+
+#[test]
+fn standalone_host_functions_reject_concrete_types() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -136,24 +228,45 @@ fn concrete_host_references_use_canonical_types() -> Result<()> {
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- let right_ref = instance.func_untyped(&store, "right-ref")?.call(&mut store, &[])?;
- let wrong_ref = instance.func_untyped(&store, "wrong-ref")?.call(&mut store, &[])?;
let return_ty = instance.func_untyped(&store, "right-ref")?.ty(&store)?.clone();
let param_ty = instance.func_untyped(&store, "takes-a")?.ty(&store)?.clone();
- let wrong_result = wrong_ref.clone();
- let wrong_return = HostFunction::from_untyped(&mut store, &return_ty, move |_, _| Ok(wrong_result.clone()));
- assert!(wrong_return.call(&mut store, &[]).is_err());
+ assert!(HostFunction::from_untyped(&return_ty, |_, _, _| Ok(())).instantiate(&mut store).is_err());
+ assert!(HostFunction::from_untyped(&param_ty, |_, _, _| Ok(())).instantiate(&mut store).is_err());
- let accept_a = HostFunction::from_untyped(&mut store, &param_ty, |_, _| Ok(Vec::new()));
- assert!(accept_a.call(&mut store, &wrong_ref).is_err());
- assert!(accept_a.call(&mut store, &right_ref).is_ok());
+ Ok(())
+}
+#[test]
+fn imported_host_functions_resolve_concrete_types() -> Result<(), Box<dyn core::error::Error>> {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (type $object (struct))
+ (import "host" "inspect" (func $inspect (param (ref null $object))))
+ (func (export "call")
+ ref.null $object
+ call $inspect))
+ "#,
+ )?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let concrete = RefType::new_concrete(true, 0);
+ let host_ty = FuncType::new(&[WasmType::Ref(concrete)], &[]);
+ let host = HostFunction::from_untyped(&host_ty, |_, args, _| {
+ assert_eq!(args, &[WasmValue::Ref(RefValue::Null)]);
+ Ok(())
+ });
+ let mut imports = Imports::new();
+ imports.define("host", "inspect", host);
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+
+ instance.func::<(), ()>(&store, "call")?.call(&mut store, ())?;
Ok(())
}
#[test]
-fn host_tail_calls_return_from_the_current_frame() -> Result<()> {
+fn host_tail_calls_return_from_the_current_frame() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -178,8 +291,8 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> {
let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
let mut imports = Imports::new();
- imports.define("host", "answer", HostFunction::from(&mut store, |_, ()| Ok(42_i32)));
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ imports.define("host", "answer", HostFunction::from(|_, ()| Ok(42_i32)));
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
for name in ["direct", "indirect", "reference"] {
assert_eq!(instance.func::<(), i32>(&store, name)?.call(&mut store, ())?, 42);
@@ -190,13 +303,16 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> {
}
#[test]
-fn host_calls_reject_unknown_function_references() {
+fn host_calls_reject_unknown_function_references() -> Result<(), Box<dyn core::error::Error>> {
let mut store = Store::default();
let ty = FuncType::new(&[WasmType::Ref(tinywasm::types::RefType::FUNCREF)], &[]);
- let host = HostFunction::from_untyped(&mut store, &ty, |_, _| Ok(Vec::new()));
- let invalid = WasmValue::Ref(RefValue::Func(tinywasm::types::FuncRef::new(u32::MAX)));
+ let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(())).instantiate(&mut store)?;
+ let mut other_store = Store::default();
+ let other = HostFunction::from_untyped(&FuncType::new(&[], &[]), |_, _, _| Ok(())).instantiate(&mut other_store)?;
+ let invalid = WasmValue::Ref(RefValue::Func(other.as_func_ref(&other_store)?));
- assert!(host.call(&mut store, &[invalid]).is_err());
+ assert!(host.call(&mut store, &[invalid], &mut []).is_err());
+ Ok(())
}
fn to_name(ty: &WasmType) -> &str {
diff --git a/crates/tinywasm/tests/host_import_arg_order.rs b/crates/tinywasm/tests/host_import_arg_order.rs
index 2004641..b04ef77 100644
--- a/crates/tinywasm/tests/host_import_arg_order.rs
+++ b/crates/tinywasm/tests/host_import_arg_order.rs
@@ -15,17 +15,16 @@ fn multi_arg_host_imports_preserve_source_order() {
.unwrap();
let module = tinywasm::parse_bytes(&wasm).unwrap();
- let mut store = Store::default();
-
- let pair = HostFunction::from(&mut store, |_ctx, (left, right): (i32, i32)| -> tinywasm::Result<i32> {
- Ok(left * 1000 + right)
- });
-
+ let pair =
+ HostFunction::from(|_ctx, (left, right): (i32, i32)| -> tinywasm::Result<i32> { Ok(left * 1000 + right) });
let mut imports = Imports::new();
imports.define("env", "pair", pair);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports)).unwrap();
- let func = instance.func::<(i32, i32), i32>(&store, "call_pair").unwrap();
+ for _ in 0..2 {
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap();
+ let func = instance.func::<(i32, i32), i32>(&store, "call_pair").unwrap();
- assert_eq!(func.call(&mut store, (12, 34)).unwrap(), 12034);
+ assert_eq!(func.call(&mut store, (12, 34)).unwrap(), 12034);
+ }
}
diff --git a/crates/tinywasm/tests/host_reentrancy.rs b/crates/tinywasm/tests/host_reentrancy.rs
new file mode 100644
index 0000000..60724a5
--- /dev/null
+++ b/crates/tinywasm/tests/host_reentrancy.rs
@@ -0,0 +1,109 @@
+#![cfg(feature = "state")]
+
+use tinywasm::engine::{Config, StackConfig};
+use tinywasm::{Engine, Error, ExecProgress, HostFunction, Imports, ModuleInstance, Result, Store, Trap};
+
+#[derive(Default)]
+struct Recursion {
+ remaining: usize,
+ visits: usize,
+ catch_overflow: bool,
+ caught: usize,
+}
+
+fn assert_call_stack_overflow(result: &Result<()>) {
+ let mut error = result.as_ref().unwrap_err();
+ while let Error::Trap(Trap::HostFunction(inner)) = error {
+ error = inner.downcast_ref::<Error>().expect("nested TinyWasm error");
+ }
+ assert!(matches!(error, Error::Trap(Trap::CallStackOverflow)), "{error:?}");
+}
+
+#[test]
+fn host_reentrancy_obeys_call_stack_policy() -> Result<()> {
+ let wasm = wat::parse_str(
+ r#"(module
+ (import "env" "recurse" (func $host))
+ (export "host" (func $host))
+ (func (export "wasm") call $host)
+ (func (export "leaf")))"#,
+ )
+ .unwrap();
+ let module = tinywasm::parse_bytes(&wasm)?;
+
+ for policy in [StackConfig::fixed(3), StackConfig::dynamic(0, 3), StackConfig::fixed(0)] {
+ for path in 0..3 {
+ for target in ["wasm", "host"] {
+ let mut imports = Imports::new();
+ imports.define(
+ "env",
+ "recurse",
+ HostFunction::from(move |mut ctx, (): ()| -> Result<()> {
+ let state = ctx.state_mut::<Recursion>().unwrap();
+ state.visits += 1;
+ state.remaining -= 1;
+ if state.remaining == 0 {
+ return Ok(());
+ }
+ let function = ctx.module().func_untyped(&ctx, target)?;
+ let result = match path {
+ 0 => {
+ let typed = ctx.module().func::<(), ()>(&ctx, target)?;
+ ctx.call(&typed, ())
+ }
+ 1 => ctx.call_untyped(&function, &[], &mut []),
+ _ => ctx.call_ref(function.as_func_ref(&ctx)?, &[], &mut []),
+ };
+ if ctx.state::<Recursion>().unwrap().catch_overflow && result.is_err() {
+ assert_call_stack_overflow(&result);
+ ctx.state_mut::<Recursion>().unwrap().caught += 1;
+ // The failed nested call must release its depth before
+ // another call is attempted in the same invocation.
+ let leaf = ctx.module().func::<(), ()>(&ctx, "leaf")?;
+ ctx.call(&leaf, ())?;
+ ctx.call(&leaf, ())?;
+ return Ok(());
+ }
+ result
+ }),
+ );
+ let mut store =
+ Store::new(Engine::new(Config::new().with_call_stack(policy))).with_state(Recursion::default());
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ let function = instance.func::<(), ()>(&store, "wasm")?;
+
+ // Finite recursion would succeed without reentrancy accounting.
+ // Run twice to check cleanup after an error, including resumable entry.
+ for resumable in [false, true] {
+ *store.state_mut::<Recursion>().unwrap() = Recursion { remaining: 16, ..Default::default() };
+ let result = if resumable {
+ function.call_resumable(&mut store, ())?.resume_with_fuel(100).map(|_| ())
+ } else {
+ function.call(&mut store, ())
+ };
+ assert_call_stack_overflow(&result);
+ assert_eq!(store.state::<Recursion>().unwrap().visits, policy.max_size + 1);
+
+ *store.state_mut::<Recursion>().unwrap() =
+ Recursion { remaining: policy.max_size + 1, ..Default::default() };
+ function.call(&mut store, ())?;
+ assert_eq!(store.state::<Recursion>().unwrap().remaining, 0);
+ }
+
+ if policy.max_size > 0 {
+ *store.state_mut::<Recursion>().unwrap() =
+ Recursion { remaining: 16, catch_overflow: true, ..Default::default() };
+ function.call(&mut store, ())?;
+ assert!(store.state::<Recursion>().unwrap().caught > 0);
+ }
+
+ *store.state_mut::<Recursion>().unwrap() = Recursion { remaining: 1, ..Default::default() };
+ assert!(matches!(
+ function.call_resumable(&mut store, ())?.resume_with_fuel(100)?,
+ ExecProgress::Completed(())
+ ));
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/import_linking.rs b/crates/tinywasm/tests/import_linking.rs
index e7948fa..a65c8a4 100644
--- a/crates/tinywasm/tests/import_linking.rs
+++ b/crates/tinywasm/tests/import_linking.rs
@@ -1,4 +1,3 @@
-use eyre::Result;
use tinywasm::{Error, Imports, Module, ModuleInstance, Store, Trap};
const WASM_ADD: &str = r#"
@@ -19,14 +18,14 @@ const WASM_IMPORT: &str = r#"
call $add))
"#;
-fn parse_modules() -> Result<(Module, Module)> {
+fn parse_modules() -> Result<(Module, Module), Box<dyn core::error::Error>> {
let add = tinywasm::parse_bytes(&wat::parse_str(WASM_ADD)?)?;
let import = tinywasm::parse_bytes(&wat::parse_str(WASM_IMPORT)?)?;
Ok((add, import))
}
#[test]
-fn link_module_links_same_store_instance() -> Result<()> {
+fn link_module_links_same_store_instance() -> Result<(), Box<dyn core::error::Error>> {
let (add_module, import_module) = parse_modules()?;
let mut store = Store::default();
@@ -34,14 +33,14 @@ fn link_module_links_same_store_instance() -> Result<()> {
let mut imports = Imports::new();
imports.link_module("adder", add_instance)?;
- let instance = ModuleInstance::instantiate(&mut store, &import_module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?;
let main = instance.func::<(), i32>(&store, "main")?;
assert_eq!(main.call(&mut store, ())?, 3);
Ok(())
}
#[test]
-fn link_module_rejects_cross_store_instance() -> Result<()> {
+fn link_module_rejects_cross_store_instance() -> Result<(), Box<dyn core::error::Error>> {
let (add_module, import_module) = parse_modules()?;
let mut source_store = Store::default();
@@ -51,7 +50,7 @@ fn link_module_rejects_cross_store_instance() -> Result<()> {
let mut imports = Imports::new();
imports.link_module("adder", add_instance)?;
- let err = ModuleInstance::instantiate(&mut target_store, &import_module, Some(imports)).unwrap_err();
+ let err = ModuleInstance::instantiate(&mut target_store, &import_module, Some(&imports)).unwrap_err();
assert_eq!(err, Error::from(Trap::InvalidStore));
Ok(())
}
diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs
index d7ed636..aa27b85 100644
--- a/crates/tinywasm/tests/imported_table_init.rs
+++ b/crates/tinywasm/tests/imported_table_init.rs
@@ -1,9 +1,8 @@
-use eyre::Result;
-use tinywasm::types::{FuncRef, RefType, TableType};
+use tinywasm::types::{RefType, TableType};
use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Table};
#[test]
-fn imported_table_uses_provided_init_value() -> Result<()> {
+fn imported_table_uses_provided_init_value() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -19,11 +18,12 @@ fn imported_table_uses_provided_init_value() -> Result<()> {
let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
let mut imports = Imports::new();
- let _function_at_zero = HostFunction::from(&mut store, |_, ()| Ok(()));
- let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 3, None), FuncRef::new(0).into())?;
+ let function_at_zero = HostFunction::from(|_, ()| Ok(())).instantiate(&mut store)?;
+ let init = function_at_zero.as_func_ref(&store)?.into();
+ let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 3, None), init)?;
imports.define("host", "table", table);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let slot_is_null = instance.func::<i32, i32>(&store, "slot_is_null")?;
assert_eq!(slot_is_null.call(&mut store, 0)?, 0);
diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs
index 7a68f01..410ea20 100644
--- a/crates/tinywasm/tests/internal_refs.rs
+++ b/crates/tinywasm/tests/internal_refs.rs
@@ -1,18 +1,17 @@
-use eyre::Result;
-use tinywasm::types::WasmValue;
#[cfg(feature = "guest-debug")]
-use tinywasm::types::{FuncRef, RefValue};
+use tinywasm::types::RefValue;
+use tinywasm::types::WasmValue;
use tinywasm::{ExternItem, ModuleInstance, Store};
#[test]
#[cfg(feature = "guest-debug")]
-fn private_items_are_accessible_by_index() -> Result<()> {
+fn private_items_are_accessible_by_index() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
(func (result i32)
i32.const 7)
- (memory 1)
+ (memory (export "memory") 1)
(global (mut i32) (i32.const 11))
(table 2 funcref)
(elem (i32.const 0) func 0)
@@ -25,24 +24,27 @@ fn private_items_are_accessible_by_index() -> Result<()> {
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let func = instance.func_by_index(&store, 0)?;
- assert_eq!(func.call(&mut store, &[])?, vec![WasmValue::I32(7)]);
+ let mut results = [WasmValue::I32(0)];
+ func.call(&mut store, &[], &mut results)?;
+ assert_eq!(results, [WasmValue::I32(7)]);
instance.memory_by_index(0)?.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?;
assert_eq!(instance.memory_by_index(0)?.read_vec(&store, 0, 4)?, &[1, 2, 3, 4]);
assert_eq!(instance.table_by_index(0)?.size(&store)?, 2);
- assert_eq!(instance.table_by_index(0)?.get(&store, 0)?, WasmValue::Ref(RefValue::Func(FuncRef::new(0))));
- assert_eq!(instance.table_by_index(0)?.get(&store, 1)?, WasmValue::Ref(tinywasm::types::RefValue::Null));
+ let function = instance.func_by_index(&store, 0)?.as_func_ref(&store)?;
+ assert_eq!(instance.table_by_index(0)?.get(&mut store, 0)?, WasmValue::Ref(RefValue::Func(function)));
+ assert_eq!(instance.table_by_index(0)?.get(&mut store, 1)?, WasmValue::Ref(tinywasm::types::RefValue::Null));
- assert_eq!(instance.global_by_index(0)?.get(&store)?, WasmValue::I32(11));
+ assert_eq!(instance.global_by_index(0)?.get(&mut store)?, WasmValue::I32(11));
instance.global_by_index(0)?.set(&mut store, WasmValue::I32(23))?;
- assert_eq!(instance.global_by_index(0)?.get(&store)?, WasmValue::I32(23));
+ assert_eq!(instance.global_by_index(0)?.get(&mut store)?, WasmValue::I32(23));
Ok(())
}
#[test]
-fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> {
+fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -56,24 +58,24 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> {
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- assert_eq!(instance.global_get(&store, "g")?, WasmValue::I32(3));
- assert_eq!(instance.global("g")?.get(&store)?, WasmValue::I32(3));
+ assert_eq!(instance.global_get(&mut store, "g")?, WasmValue::I32(3));
+ assert_eq!(instance.global("g")?.get(&mut store)?, WasmValue::I32(3));
instance.global_set(&mut store, "g", WasmValue::I32(9))?;
- assert_eq!(instance.global("g")?.get(&store)?, WasmValue::I32(9));
+ assert_eq!(instance.global("g")?.get(&mut store)?, WasmValue::I32(9));
let table = instance.table("t")?;
assert_eq!(table.size(&store)?, 1);
- assert_eq!(table.get(&store, 0)?, WasmValue::Ref(tinywasm::types::RefValue::Null));
+ assert_eq!(table.get(&mut store, 0)?, WasmValue::Ref(tinywasm::types::RefValue::Null));
let old_size = instance.table("t")?.grow(&mut store, 1, tinywasm::types::RefValue::Null.into())?;
- assert_eq!(old_size, 1);
+ assert_eq!(old_size, Some(1));
assert_eq!(instance.table("t")?.size(&store)?, 2);
Ok(())
}
#[test]
-fn extern_item_lookup_returns_expected_kinds() -> Result<()> {
+fn extern_item_lookup_returns_expected_kinds() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -98,7 +100,7 @@ fn extern_item_lookup_returns_expected_kinds() -> Result<()> {
}
#[test]
-fn extern_item_and_exports_use_actual_function_type() -> Result<()> {
+fn extern_item_and_exports_use_actual_function_type() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -117,24 +119,24 @@ fn extern_item_and_exports_use_actual_function_type() -> Result<()> {
imports.define(
"host",
"imported",
- tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())),
+ tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())),
);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") };
- assert_eq!(func.call(&mut store, &[])?, vec![]);
+ func.call(&mut store, &[], &mut [])?;
let (_, ExternItem::Func(func)) = instance.exports().find(|(name, _)| *name == "f").expect("export f not found")
else {
panic!("expected function export")
};
- assert_eq!(func.call(&mut store, &[])?, vec![]);
+ func.call(&mut store, &[], &mut [])?;
Ok(())
}
#[test]
-fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<()> {
+fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -149,8 +151,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(), &[]);
@@ -161,18 +168,18 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<()
imports.define(
"spectest",
"print_i64",
- tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())),
+ tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())),
);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") };
- assert_eq!(func.call(&mut store, &[])?, vec![]);
+ func.call(&mut store, &[], &mut [])?;
Ok(())
}
#[test]
-fn start_resolves_module_func_index_to_store_addr() -> Result<()> {
+fn start_resolves_module_func_index_to_store_addr() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -187,11 +194,12 @@ fn start_resolves_module_func_index_to_store_addr() -> Result<()> {
let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
- let _unused = tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, (): ()| Ok(()));
+ let _unused =
+ tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, (): ()| Ok(())).instantiate(&mut store)?;
let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?;
instance.start(&mut store)?;
- assert_eq!(instance.global_get(&store, "g")?, WasmValue::I32(1));
+ assert_eq!(instance.global_get(&mut store, "g")?, WasmValue::I32(1));
Ok(())
}
diff --git a/crates/tinywasm/tests/managed_exceptions.rs b/crates/tinywasm/tests/managed_exceptions.rs
new file mode 100644
index 0000000..ecb6a12
--- /dev/null
+++ b/crates/tinywasm/tests/managed_exceptions.rs
@@ -0,0 +1,141 @@
+use std::sync::{Arc, Mutex};
+
+use tinywasm::engine::Config;
+use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue};
+use tinywasm::{Engine, Error, ExnRef, ModuleInstance, ResourceLimiter, Store, Tag, Trap};
+
+const MODULE: &str = r#"
+ (module
+ (tag $scalar (export "scalar-tag") (param i32))
+ (tag $graph (export "graph-tag") (param anyref))
+ (type $node (struct (field i32)))
+
+ (func (export "throw-scalar") (param i32)
+ local.get 0
+ throw $scalar)
+
+ (func (export "catch-scalar") (param i32)
+ (drop
+ (block $caught (result i32)
+ (try_table (result i32) (catch $scalar $caught)
+ local.get 0
+ throw $scalar
+ i32.const 0))))
+
+ (func (export "throw-graph")
+ i32.const 42
+ struct.new $node
+ throw $graph)
+
+ (func (export "rethrow") (param exnref)
+ local.get 0
+ throw_ref)
+
+ (func (export "read-node") (param anyref) (result i32)
+ local.get 0
+ ref.cast (ref $node)
+ struct.get $node 0)
+ )
+"#;
+
+fn instantiate(store: &mut Store) -> ModuleInstance {
+ let wasm = wat::parse_str(MODULE).unwrap();
+ let module = tinywasm::parse_bytes(&wasm).unwrap();
+ ModuleInstance::instantiate(store, &module, None).unwrap()
+}
+
+fn exception(error: Error) -> ExnRef {
+ let Error::Exception(exception) = error else { panic!("expected exception") };
+ exception
+}
+
+#[test]
+fn exception_accessors_validate_store_and_expose_payload() {
+ let mut store = Store::default();
+ let instance = instantiate(&mut store);
+ let throw = instance.func_untyped(&store, "throw-scalar").unwrap();
+ let exception = exception(throw.call(&mut store, &[WasmValue::I32(17)], &mut []).unwrap_err());
+
+ assert_eq!(exception.tag(&store).unwrap(), instance.tag("scalar-tag").unwrap());
+ assert_eq!(exception.field(&mut store, 0).unwrap(), WasmValue::I32(17));
+ assert_eq!(exception.fields(&mut store).unwrap(), [WasmValue::I32(17)]);
+ assert!(exception.field(&mut store, 1).is_err());
+
+ let other = Store::default();
+ assert_eq!(exception.tag(&other).unwrap_err(), Error::Trap(Trap::InvalidStore));
+}
+
+#[test]
+fn exception_roots_keep_payload_graphs_live() {
+ let mut store = Store::new(Engine::new(Config::new().with_gc_collection_threshold(1)));
+ let instance = instantiate(&mut store);
+ let throw = instance.func_untyped(&store, "throw-graph").unwrap();
+ let read = instance.func_untyped(&store, "read-node").unwrap();
+ let exception = exception(throw.call(&mut store, &[], &mut []).unwrap_err());
+
+ store.gc().unwrap();
+ let payload = exception.field(&mut store, 0).unwrap();
+ assert!(matches!(payload, WasmValue::Ref(RefValue::Any(_))));
+ let mut results = [WasmValue::I32(0)];
+ read.call(&mut store, &[payload], &mut results).unwrap();
+ assert_eq!(results, [WasmValue::I32(42)]);
+}
+
+#[test]
+fn owned_exception_references_survive_collection_and_reject_another_store() {
+ let mut store = Store::default();
+ let instance = instantiate(&mut store);
+ let throw = instance.func_untyped(&store, "throw-scalar").unwrap();
+ let first = exception(throw.call(&mut store, &[WasmValue::I32(1)], &mut []).unwrap_err());
+
+ store.gc().unwrap();
+ let current = exception(throw.call(&mut store, &[WasmValue::I32(2)], &mut []).unwrap_err());
+ assert_eq!(current.field(&mut store, 0).unwrap(), WasmValue::I32(2));
+ assert_eq!(first.field(&mut store, 0).unwrap(), WasmValue::I32(1));
+ let rethrow = instance.func_untyped(&store, "rethrow").unwrap();
+ let rethrown = exception(rethrow.call(&mut store, &[WasmValue::Ref(RefValue::Exn(first))], &mut []).unwrap_err());
+ assert_eq!(rethrown.field(&mut store, 0).unwrap(), WasmValue::I32(1));
+
+ let mut other = Store::default();
+ let other_instance = instantiate(&mut other);
+ let other_rethrow = other_instance.func_untyped(&other, "rethrow").unwrap();
+ assert_eq!(
+ other_rethrow.call(&mut other, &[WasmValue::Ref(RefValue::Exn(current))], &mut []).unwrap_err(),
+ Error::Trap(Trap::InvalidStore)
+ );
+}
+
+#[test]
+fn host_tags_reject_unbranded_concrete_types() {
+ let mut store = Store::default();
+ let ty = FuncType::new(&[WasmType::Ref(RefType::new_concrete(true, 0))], &[]);
+
+ assert!(Tag::try_new(&mut store, ty).is_err());
+}
+
+struct GcUsage(Arc<Mutex<Vec<(usize, usize)>>>);
+
+impl ResourceLimiter for GcUsage {
+ fn gc_growing(&self, current: usize, desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ self.0.lock().unwrap().push((current, desired));
+ Ok(true)
+ }
+}
+
+#[test]
+fn dropped_exception_roots_release_counted_gc_bytes() {
+ let usage = Arc::new(Mutex::new(Vec::new()));
+ let config = Config::new().with_gc_collection_threshold(usize::MAX).with_resource_limiter(GcUsage(usage.clone()));
+ let mut store = Store::new(Engine::new(config));
+ let instance = instantiate(&mut store);
+ let catch = instance.func_untyped(&store, "catch-scalar").unwrap();
+
+ for value in 0..32 {
+ catch.call(&mut store, &[WasmValue::I32(value)], &mut []).unwrap();
+ }
+ store.gc().unwrap();
+ usage.lock().unwrap().clear();
+
+ catch.call(&mut store, &[WasmValue::I32(33)], &mut []).unwrap();
+ assert_eq!(usage.lock().unwrap()[0].0, 0);
+}
diff --git a/crates/tinywasm/tests/memory.rs b/crates/tinywasm/tests/memory.rs
new file mode 100644
index 0000000..cf90c13
--- /dev/null
+++ b/crates/tinywasm/tests/memory.rs
@@ -0,0 +1,202 @@
+use tinywasm::engine::Config;
+use tinywasm::types::{MemoryArch, MemoryType, RefType, RefValue, TableType};
+use tinywasm::{Engine, Memory, ModuleInstance, ResourceLimiter, Store, Table, Trap};
+
+type TestResult<T = ()> = Result<T, Box<dyn core::error::Error>>;
+
+fn store_with_limiter(limiter: impl ResourceLimiter + 'static) -> Store {
+ let engine = Engine::new(Config::new().with_resource_limiter(limiter));
+ Store::new(engine)
+}
+
+#[test]
+fn memory_read_write_roundtrip() -> TestResult {
+ let mut store = Store::default();
+ let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?;
+
+ memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5])?;
+ assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 3, 4, 5]);
+ memory.fill(&mut store, 2, 2, 0)?;
+ assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 0, 0, 5]);
+ Ok(())
+}
+
+#[test]
+fn read_returns_short_count_at_end_of_memory() -> TestResult {
+ let mut store = Store::default();
+ let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?;
+ memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?;
+
+ let mut dst = [9; 8];
+ assert_eq!(memory.read(&store, 2, &mut dst)?, 2);
+ assert_eq!(&dst[..2], &[3, 4]);
+ assert_eq!(&dst[2..], &[9; 6]);
+
+ Ok(())
+}
+
+#[test]
+fn memory64_default_limit_is_not_memory32_limit() {
+ let ty = MemoryType::new(MemoryArch::I64, 65_537, None, None);
+ assert!(ty.page_count_max() > 65_536);
+}
+
+struct DenyAll;
+
+impl ResourceLimiter for DenyAll {
+ fn memory_growing(&self, _current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ Ok(false)
+ }
+
+ fn table_growing(&self, _current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ Ok(false)
+ }
+}
+
+struct DenyGrowth;
+
+impl ResourceLimiter for DenyGrowth {
+ fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ Ok(current == 0)
+ }
+
+ fn table_growing(&self, current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ Ok(current == 0)
+ }
+}
+
+struct TrapGrowth;
+
+impl ResourceLimiter for TrapGrowth {
+ fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ if current == 0 { Ok(true) } else { Err(Trap::Unreachable) }
+ }
+
+ fn table_growing(&self, current: usize, _desired: usize, _maximum: Option<usize>) -> Result<bool, Trap> {
+ if current == 0 { Ok(true) } else { Err(Trap::Unreachable) }
+ }
+}
+
+#[test]
+fn resource_limiter_can_reject_growth() -> TestResult {
+ let mut store = store_with_limiter(DenyGrowth);
+ let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?;
+
+ assert_eq!(memory.grow(&mut store, 1)?, None);
+ assert_eq!(memory.page_count(&store)?, 1);
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_rejects_guest_memory_grow() -> TestResult {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (memory 1)
+ (func (export "grow") (result i32)
+ i32.const 1
+ memory.grow))
+ "#,
+ )?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = store_with_limiter(DenyGrowth);
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ let grow = instance.func::<(), i32>(&store, "grow")?;
+ assert_eq!(grow.call(&mut store, ())?, -1);
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_can_trap_guest_memory_grow() -> TestResult {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (memory 1)
+ (func (export "grow") (result i32)
+ i32.const 1
+ memory.grow))
+ "#,
+ )?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = store_with_limiter(TrapGrowth);
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ let grow = instance.func::<(), i32>(&store, "grow")?;
+ assert!(matches!(grow.call(&mut store, ()), Err(tinywasm::Error::Trap(Trap::Unreachable))));
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_rejects_host_memory_initial_size() {
+ let mut store = store_with_limiter(DenyAll);
+ let result = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None));
+
+ assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
+}
+
+#[test]
+fn resource_limiter_rejects_module_memory_initial_size() -> TestResult {
+ let wasm = wat::parse_str("(module (memory (export \"memory\") 1))")?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = store_with_limiter(DenyAll);
+ let result = ModuleInstance::instantiate(&mut store, &module, None);
+
+ assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_rejects_table_initial_size() {
+ let mut store = store_with_limiter(DenyAll);
+ let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into());
+
+ assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
+}
+
+#[test]
+fn table_rejects_initial_size_above_maximum() {
+ let mut store = Store::default();
+ let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 2, Some(1)), RefValue::Null.into());
+
+ assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
+}
+
+#[test]
+fn resource_limiter_can_reject_table_growth() -> TestResult {
+ let mut store = store_with_limiter(DenyGrowth);
+ let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?;
+
+ assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None);
+ assert_eq!(table.size(&store)?, 1);
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_can_trap_table_growth() -> TestResult {
+ let mut store = store_with_limiter(TrapGrowth);
+ let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?;
+
+ assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable))));
+ Ok(())
+}
+
+#[test]
+fn resource_limiter_allows_guest_memory_grow_by_default() -> TestResult {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (memory 1)
+ (func (export "grow") (result i32)
+ i32.const 1
+ memory.grow))
+ "#,
+ )?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ let grow = instance.func::<(), i32>(&store, "grow")?;
+ assert_eq!(grow.call(&mut store, ())?, 1);
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs
deleted file mode 100644
index c231bc1..0000000
--- a/crates/tinywasm/tests/memory_backends.rs
+++ /dev/null
@@ -1,262 +0,0 @@
-extern crate alloc;
-
-use alloc::sync::Arc;
-use core::sync::atomic::{AtomicUsize, Ordering};
-
-#[cfg(feature = "std")]
-use std::io::{Read, Seek, SeekFrom, Write};
-
-use eyre::Result;
-use tinywasm::engine::Config;
-use tinywasm::types::{MemoryArch, MemoryType};
-use tinywasm::{Engine, Memory, MemoryBackend, Module, ModuleInstance, PagedMemory, Store};
-use tinywasm_parser::{Parser, ParserOptions};
-
-fn instantiate_module_with_counting_backend(module: Module) -> Result<usize> {
- let created = Arc::new(AtomicUsize::new(0));
- let factory_calls = created.clone();
- let backend = MemoryBackend::custom(move |ty| {
- factory_calls.fetch_add(1, Ordering::Relaxed);
- Ok(PagedMemory::try_new(ty.initial_size() as usize, 16)?)
- });
- let engine = Engine::new(Config::new().with_memory_backend(backend));
- let mut store = Store::new(engine);
-
- let _ = ModuleInstance::instantiate(&mut store, &module, None)?;
-
- Ok(created.load(Ordering::Relaxed))
-}
-
-fn instantiate_with_counting_backend(wat: &str) -> Result<usize> {
- let wasm = wat::parse_str(wat)?;
- let module = tinywasm::parse_bytes(&wasm)?;
- instantiate_module_with_counting_backend(module)
-}
-
-fn instantiate_exported_memory_with_counting_backend(
- wat: &str,
-) -> Result<(Store, tinywasm::ModuleInstance, Arc<AtomicUsize>)> {
- let wasm = wat::parse_str(wat)?;
- let module = tinywasm::parse_bytes(&wasm)?;
- let created = Arc::new(AtomicUsize::new(0));
- let factory_calls = created.clone();
- let backend = MemoryBackend::custom(move |ty| {
- factory_calls.fetch_add(1, Ordering::Relaxed);
- Ok(PagedMemory::try_new(ty.initial_size() as usize, 16)?)
- });
- let engine = Engine::new(Config::new().with_memory_backend(backend));
- let mut store = Store::new(engine);
- let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- Ok((store, instance, created))
-}
-
-#[test]
-fn paged_backend_works_for_module_memories() -> Result<()> {
- let wasm = wat::parse_str(
- r#"
- (module
- (memory (export "memory") 1)
- )
- "#,
- )?;
-
- let module = tinywasm::parse_bytes(&wasm)?;
- let config = Config::new().with_memory_backend(MemoryBackend::paged(8));
- let mut store = Store::new(Engine::new(config));
- let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- let memory = instance.memory("memory")?;
-
- memory.copy_from_slice(&mut store, 6, &[1, 2, 3, 4, 5, 6, 7, 8])?;
- assert_eq!(memory.read_vec(&store, 6, 8)?, &[1, 2, 3, 4, 5, 6, 7, 8]);
-
- Ok(())
-}
-
-#[test]
-fn custom_backend_factory_is_used_for_host_memories() -> Result<()> {
- let created = Arc::new(AtomicUsize::new(0));
- let seen_page_size = Arc::new(AtomicUsize::new(0));
- let factory_calls = created.clone();
- let page_size_seen = seen_page_size.clone();
-
- let backend = MemoryBackend::custom(move |ty| {
- factory_calls.fetch_add(1, Ordering::Relaxed);
- page_size_seen.store(ty.page_size() as usize, Ordering::Relaxed);
- Ok(PagedMemory::try_new(ty.initial_size() as usize, 16)?)
- });
-
- let engine = Engine::new(Config::new().with_memory_backend(backend));
- let mut store = Store::new(engine);
-
- let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(2), Some(32)))?;
- assert_eq!(memory.ty(&store)?.page_size(), 32);
- memory.copy_from_slice(&mut store, 12, &[9, 8, 7, 6, 5])?;
-
- assert_eq!(memory.read_vec(&store, 12, 5)?, &[9, 8, 7, 6, 5]);
- assert_eq!(created.load(Ordering::Relaxed), 1);
- assert_eq!(seen_page_size.load(Ordering::Relaxed), 32);
-
- Ok(())
-}
-
-#[test]
-fn local_memory_without_observable_use_is_not_allocated() -> Result<()> {
- let created = instantiate_with_counting_backend(
- r#"
- (module
- (memory 1)
- (func (export "run"))
- )
- "#,
- )?;
-
- assert_eq!(created, 0);
- Ok(())
-}
-
-#[test]
-fn exported_local_memory_is_not_eagerly_allocated() -> Result<()> {
- let created = instantiate_with_counting_backend(
- r#"
- (module
- (memory (export "memory") 1)
- )
- "#,
- )?;
-
- assert_eq!(created, 0);
- Ok(())
-}
-
-#[test]
-fn exported_local_memory_reads_zeroes_without_materializing() -> Result<()> {
- let (mut store, instance, created) = instantiate_exported_memory_with_counting_backend(
- r#"
- (module
- (memory (export "memory") 1)
- )
- "#,
- )?;
-
- let memory = instance.memory("memory")?;
- assert_eq!(created.load(Ordering::Relaxed), 0);
- assert_eq!(memory.len(&store)?, 65536);
- assert_eq!(memory.read_vec(&store, 65534, 2)?, &[0, 0]);
- assert_eq!(created.load(Ordering::Relaxed), 0);
-
- memory.copy_from_slice(&mut store, 65534, &[1, 2])?;
- assert_eq!(created.load(Ordering::Relaxed), 1);
- assert_eq!(memory.read_vec(&store, 65534, 2)?, &[1, 2]);
- Ok(())
-}
-
-#[test]
-fn active_data_segment_on_local_memory_is_allocated() -> Result<()> {
- let created = instantiate_with_counting_backend(
- r#"
- (module
- (memory 1)
- (data (i32.const 0) "hi")
- )
- "#,
- )?;
-
- assert_eq!(created, 1);
- Ok(())
-}
-
-#[test]
-fn local_memory_instruction_is_allocated() -> Result<()> {
- let created = instantiate_with_counting_backend(
- r#"
- (module
- (memory 1)
- (func (export "run") (drop (memory.size)))
- )
- "#,
- )?;
-
- assert_eq!(created, 1);
- Ok(())
-}
-
-#[test]
-fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result<()> {
- let wasm = wat::parse_str(
- r#"
- (module
- (memory 1)
- (func (export "run"))
- )
- "#,
- )?;
- let parser = Parser::with_options(ParserOptions::default().with_local_memory_allocation_optimization(false));
- let module = parser.parse_module_bytes(&wasm)?;
-
- let created = instantiate_module_with_counting_backend(module)?;
-
- assert_eq!(created, 1);
- Ok(())
-}
-
-#[test]
-fn read_returns_short_count_at_end_of_memory() -> Result<()> {
- let mut store = Store::default();
- let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?;
- memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?;
-
- let mut dst = [9; 8];
- assert_eq!(memory.read(&store, 2, &mut dst)?, 2);
- assert_eq!(&dst[..2], &[3, 4]);
- assert_eq!(&dst[2..], &[9; 6]);
-
- Ok(())
-}
-
-#[test]
-fn paged_read_and_write_stop_at_chunk_boundaries() -> Result<()> {
- let engine = Engine::new(Config::new().with_memory_backend(MemoryBackend::paged(4)));
- let mut store = Store::new(engine);
- let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(16)))?;
-
- memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5, 6, 7, 8])?;
-
- let mut read_buf = [9; 6];
- assert_eq!(memory.read(&store, 2, &mut read_buf)?, 2);
- assert_eq!(&read_buf[..2], &[3, 4]);
- assert_eq!(&read_buf[2..], &[9; 4]);
-
- let mut exact_buf = [0; 6];
- memory.read_exact(&store, 2, &mut exact_buf)?;
- assert_eq!(exact_buf, [3, 4, 5, 6, 7, 8]);
-
- assert_eq!(memory.write(&mut store, 6, &[10, 11, 12, 13])?, 2);
- assert_eq!(memory.read_vec(&store, 6, 4)?, &[10, 11, 0, 0]);
-
- memory.copy_from_slice(&mut store, 6, &[20, 21, 22, 23])?;
- assert_eq!(memory.read_vec(&store, 6, 4)?, &[20, 21, 22, 23]);
-
- Ok(())
-}
-
-#[cfg(feature = "std")]
-#[test]
-fn memory_cursor_supports_read_write_and_seek() -> Result<()> {
- let mut store = Store::default();
- let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(8)))?;
-
- let mut cursor = memory.cursor(&mut store)?;
- cursor.seek(SeekFrom::Start(2))?;
- cursor.write_all(b"abc")?;
- cursor.seek(SeekFrom::Start(0))?;
-
- let mut buf = [0; 5];
- cursor.read_exact(&mut buf)?;
- assert_eq!(buf, [0, 0, b'a', b'b', b'c']);
-
- cursor.seek(SeekFrom::End(-1))?;
- cursor.write_all(b"z")?;
-
- assert_eq!(memory.read_vec(&store, 0, 8)?, &[0, 0, b'a', b'b', b'c', 0, 0, b'z']);
- Ok(())
-}
diff --git a/crates/tinywasm/tests/memory_ref_api.rs b/crates/tinywasm/tests/memory_ref_api.rs
index 6f72477..65b91ba 100644
--- a/crates/tinywasm/tests/memory_ref_api.rs
+++ b/crates/tinywasm/tests/memory_ref_api.rs
@@ -1,8 +1,7 @@
-use eyre::Result;
use tinywasm::{ModuleInstance, Store};
#[test]
-fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<()> {
+fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -23,3 +22,16 @@ fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<()> {
Ok(())
}
+
+#[test]
+fn read_js_string_decodes_surrogate_pairs() -> Result<(), Box<dyn core::error::Error>> {
+ let mut store = Store::default();
+ let memory =
+ tinywasm::Memory::try_new(&mut store, tinywasm::types::MemoryType::default().with_page_count_initial(1))?;
+ memory.copy_from_slice(&mut store, 0, &[0x3d, 0xd8, 0x00, 0xde])?;
+
+ assert_eq!(memory.read_js_string(&store, 0, 4)?, "😀");
+ assert!(memory.read_js_string(&store, 0, 3).is_err());
+
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/module_descriptors.rs b/crates/tinywasm/tests/module_descriptors.rs
index 81ab5ab..8bd73b6 100644
--- a/crates/tinywasm/tests/module_descriptors.rs
+++ b/crates/tinywasm/tests/module_descriptors.rs
@@ -1,9 +1,7 @@
-use eyre::Result;
-use tinywasm::types::WasmType;
-use tinywasm_types::{ExportType, ImportType};
+use tinywasm::types::{ExportType, ImportType, WasmType};
#[test]
-fn module_descriptors_resolve_imported_and_local_export_types() -> Result<()> {
+fn module_descriptors_resolve_imported_and_local_export_types() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -91,7 +89,7 @@ fn module_descriptors_resolve_imported_and_local_export_types() -> Result<()> {
}
#[test]
-fn module_descriptors_resolve_imported_and_local_table_and_memory_exports() -> Result<()> {
+fn module_descriptors_resolve_imported_and_local_table_and_memory_exports() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
diff --git a/crates/tinywasm/tests/reference_roots.rs b/crates/tinywasm/tests/reference_roots.rs
new file mode 100644
index 0000000..775047e
--- /dev/null
+++ b/crates/tinywasm/tests/reference_roots.rs
@@ -0,0 +1,104 @@
+use std::sync::{Arc, Mutex};
+use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue};
+use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Trap};
+
+#[test]
+fn direct_references_stay_live_until_the_last_clone_is_dropped() {
+ let mut store = Store::default();
+ let reference = ExternRef::try_new(&mut store, 7).unwrap();
+ let clone = reference.clone();
+ drop(reference);
+ store.gc().unwrap();
+
+ assert_eq!(clone.key(&store), Ok(7));
+}
+
+#[test]
+fn roots_and_function_references_reject_another_store() {
+ let mut first = Store::default();
+ let mut second = Store::default();
+ let root = ExternRef::try_new(&mut first, 1).unwrap();
+ let function = HostFunction::from(|_, ()| -> tinywasm::Result<()> { Ok(()) }).instantiate(&mut first).unwrap();
+ let func_ref = function.as_func_ref(&first).unwrap();
+ let accepts_func_ref =
+ HostFunction::from(|_, _: Option<tinywasm::types::FuncRef>| -> tinywasm::Result<()> { Ok(()) })
+ .instantiate(&mut second)
+ .unwrap();
+
+ assert!(matches!(root.key(&second), Err(tinywasm::Error::Trap(Trap::InvalidStore))));
+ assert!(matches!(
+ accepts_func_ref.call(&mut second, &[WasmValue::Ref(RefValue::Func(func_ref))], &mut []),
+ Err(tinywasm::Error::Trap(Trap::InvalidStore))
+ ));
+}
+
+#[test]
+fn callback_results_and_captured_clones_remain_valid() {
+ let mut store = Store::default();
+ let captured = Arc::new(Mutex::new(None));
+ let callback_root = captured.clone();
+ let ty = FuncType::new(&[], &[WasmType::Ref(RefType::EXTERNREF)]);
+ let function = HostFunction::from_untyped(&ty, move |mut context, _, results| {
+ let root = ExternRef::try_new(context.store_mut(), 17)?;
+ *callback_root.lock().unwrap() = Some(root.clone());
+ results[0] = root.into();
+ Ok(())
+ })
+ .instantiate(&mut store)
+ .unwrap();
+
+ let mut results = [WasmValue::Ref(RefValue::Null)];
+ function.call(&mut store, &[], &mut results).unwrap();
+ let [result] = results;
+ let WasmValue::Ref(RefValue::Extern(result)) = result else { panic!("expected externref") };
+ assert_eq!(result.key(&store), Ok(17));
+ assert_eq!(captured.lock().unwrap().as_ref().unwrap().key(&store), Ok(17));
+}
+
+#[test]
+fn guest_callback_arguments_are_rooted_before_entering_untyped_host_code() {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (import "host" "make" (func $make (result (ref extern))))
+ (import "host" "check" (func $check (param externref)))
+ (func (export "call")
+ call $make
+ call $check))
+ "#,
+ )
+ .unwrap();
+ let module = tinywasm::parse_bytes(&wasm).unwrap();
+ let mut store = Store::default();
+ let mut imports = Imports::new();
+ imports.define("host", "make", HostFunction::from(|mut context, ()| ExternRef::try_new(context.store_mut(), 23)));
+ imports.define(
+ "host",
+ "check",
+ HostFunction::from_untyped(
+ &FuncType::new(&[WasmType::Ref(RefType::EXTERNREF)], &[]),
+ |context, args, _results| {
+ let WasmValue::Ref(RefValue::Extern(value)) = &args[0] else { panic!("expected externref") };
+ assert_eq!(value.key(context.store()), Ok(23));
+ Ok(())
+ },
+ ),
+ );
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap();
+
+ instance.func::<(), ()>(&store, "call").unwrap().call(&mut store, ()).unwrap();
+}
+
+#[test]
+fn typed_option_reference_signatures_are_nullable() {
+ let mut store = Store::default();
+ let function =
+ HostFunction::from(|_context, value: Option<ExternRef>| -> tinywasm::Result<Option<ExternRef>> { Ok(value) })
+ .instantiate(&mut store)
+ .unwrap();
+
+ assert_eq!(function.ty(&store).unwrap().params(), &[WasmType::Ref(RefType::EXTERNREF)]);
+ let mut results = [WasmValue::Ref(RefValue::Null)];
+ function.call(&mut store, &[WasmValue::Ref(RefValue::Null)], &mut results).unwrap();
+ assert_eq!(results, [WasmValue::Ref(RefValue::Null)]);
+}
diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs
index 060cefb..431a696 100644
--- a/crates/tinywasm/tests/resume_execution.rs
+++ b/crates/tinywasm/tests/resume_execution.rs
@@ -1,6 +1,5 @@
-use eyre::Result;
use tinywasm::engine::{Config, FuelPolicy};
-use tinywasm::{ExecProgress, ModuleInstance, types::WasmValue};
+use tinywasm::{ExecProgress, ModuleInstance, Result, types::WasmValue};
#[cfg(feature = "std")]
use std::time::Duration;
@@ -43,15 +42,17 @@ fn untyped_resume_supports_zero_fuel() -> Result<()> {
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let func = instance.func_untyped(&store, "add")?;
- let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?;
- assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended));
+ let mut results = [WasmValue::I32(0)];
+ {
+ let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?;
+ assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended));
- match exec.resume_with_fuel(16)? {
- ExecProgress::Completed(values) => {
- assert_eq!(values, vec![WasmValue::I32(42)])
+ match exec.resume_with_fuel(16)? {
+ ExecProgress::Completed(()) => {}
+ ExecProgress::Suspended => panic!("expected completion"),
}
- ExecProgress::Suspended => panic!("expected completion"),
}
+ assert_eq!(results, [WasmValue::I32(42)]);
Ok(())
}
@@ -69,7 +70,7 @@ fn weighted_call_fuel_requires_more_rounds() -> Result<()> {
let instance_weighted = ModuleInstance::instantiate(&mut weighted_store, &module, None)?;
let func_weighted = instance_weighted.func::<i32, i32>(&weighted_store, "fibonacci_recursive")?;
- let fuel = 64;
+ let fuel = 512;
let n = 20;
let mut per_exec = func_per_instr.call_resumable(&mut per_instr_store, n)?;
@@ -93,7 +94,7 @@ fn weighted_call_fuel_requires_more_rounds() -> Result<()> {
};
assert_eq!(weighted_result, per_result);
- assert!(weighted_rounds >= per_rounds, "weighted call fuel should not use fewer rounds than per-instruction");
+ assert!(weighted_rounds > per_rounds, "weighted call fuel should require more rounds than per-instruction");
Ok(())
}
diff --git a/crates/tinywasm/tests/start_function.rs b/crates/tinywasm/tests/start_function.rs
index 077c0fc..912b200 100644
--- a/crates/tinywasm/tests/start_function.rs
+++ b/crates/tinywasm/tests/start_function.rs
@@ -1,8 +1,7 @@
-use eyre::Result;
use tinywasm::{ModuleInstance, Store};
#[test]
-fn exported_wasi_start_is_not_run_during_instantiation() -> Result<()> {
+fn exported_wasi_start_is_not_run_during_instantiation() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs
index 8577d73..72c9478 100644
--- a/crates/tinywasm/tests/store_ownership.rs
+++ b/crates/tinywasm/tests/store_ownership.rs
@@ -1,5 +1,5 @@
-use eyre::Result;
-use tinywasm::{ModuleInstance, Store};
+use tinywasm::types::{GlobalType, WasmType};
+use tinywasm::{Global, Imports, ModuleInstance, Store};
const MODULE_WAT: &str = r#"
(module
@@ -12,7 +12,7 @@ const MODULE_WAT: &str = r#"
"#;
#[test]
-fn func_handle_rejects_wrong_store() -> Result<()> {
+fn func_handle_rejects_wrong_store() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(MODULE_WAT)?;
let module = tinywasm::parse_bytes(&wasm)?;
@@ -21,14 +21,14 @@ fn func_handle_rejects_wrong_store() -> Result<()> {
let func = instance.func_untyped(&owner_store, "add")?;
let mut other_store = Store::default();
- let err = func.call(&mut other_store, &[1.into(), 2.into()]).unwrap_err();
+ let err = func.call(&mut other_store, &[1.into(), 2.into()], &mut [0.into()]).unwrap_err();
assert!(err.to_string().contains("invalid store"));
Ok(())
}
#[test]
-fn memory_access_rejects_wrong_store() -> Result<()> {
+fn memory_access_rejects_wrong_store() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(MODULE_WAT)?;
let module = tinywasm::parse_bytes(&wasm)?;
@@ -44,7 +44,7 @@ fn memory_access_rejects_wrong_store() -> Result<()> {
}
#[test]
-fn global_access_rejects_wrong_store() -> Result<()> {
+fn global_access_rejects_wrong_store() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -58,15 +58,15 @@ fn global_access_rejects_wrong_store() -> Result<()> {
let instance = ModuleInstance::instantiate(&mut owner_store, &module, None)?;
let global = instance.global("g")?;
- let other_store = Store::default();
- let err = global.get(&other_store).unwrap_err();
+ let mut other_store = Store::default();
+ let err = global.get(&mut other_store).unwrap_err();
assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore));
Ok(())
}
#[test]
-fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> {
+fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -86,3 +86,18 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> {
Ok(())
}
+
+#[test]
+fn global_import_rejects_wrong_store() -> Result<(), Box<dyn core::error::Error>> {
+ let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut owner_store = Store::default();
+ let global = Global::try_new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?;
+ let mut imports = Imports::default();
+ imports.define("env", "g", global);
+
+ let mut other_store = Store::default();
+ let err = ModuleInstance::instantiate(&mut other_store, &module, Some(&imports)).unwrap_err();
+ assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore));
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/store_state.rs b/crates/tinywasm/tests/store_state.rs
new file mode 100644
index 0000000..573c250
--- /dev/null
+++ b/crates/tinywasm/tests/store_state.rs
@@ -0,0 +1,36 @@
+#![cfg(feature = "state")]
+
+use tinywasm::types::WasmValue;
+use tinywasm::{HostFunction, Store};
+
+struct Counter(i32);
+struct Label(&'static str);
+
+#[test]
+fn stores_state_by_type() {
+ let mut store = Store::default().with_state(Counter(1)).with_state(Label("first")).with_state(Counter(2));
+
+ assert_eq!(store.state::<Counter>().unwrap().0, 2);
+ assert_eq!(store.state::<Label>().unwrap().0, "first");
+
+ store.state_mut::<Counter>().unwrap().0 = 3;
+ assert_eq!(store.state::<Counter>().unwrap().0, 3);
+}
+
+#[test]
+fn host_function_mutates_store_state() -> tinywasm::Result<()> {
+ let mut store = Store::default().with_state(Counter(40));
+ let function = HostFunction::from(|mut ctx, value: i32| {
+ let counter = ctx.state_mut::<Counter>().expect("counter state");
+ counter.0 += value;
+ Ok(counter.0)
+ })
+ .instantiate(&mut store)?;
+
+ let mut results = [WasmValue::I32(0)];
+ function.call(&mut store, &[WasmValue::I32(2)], &mut results)?;
+
+ assert_eq!(results, [WasmValue::I32(42)]);
+ assert_eq!(store.state::<Counter>().unwrap().0, 42);
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/test-wasm-1.rs b/crates/tinywasm/tests/test-wasm-1.rs
index be235ae..723f007 100644
--- a/crates/tinywasm/tests/test-wasm-1.rs
+++ b/crates/tinywasm/tests/test-wasm-1.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{SpecVersion, spec};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-2.rs b/crates/tinywasm/tests/test-wasm-2.rs
index 0379ca6..c762eec 100644
--- a/crates/tinywasm/tests/test-wasm-2.rs
+++ b/crates/tinywasm/tests/test-wasm-2.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{SpecVersion, spec};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-3.rs b/crates/tinywasm/tests/test-wasm-3.rs
index 11ebbc8..a843ae0 100644
--- a/crates/tinywasm/tests/test-wasm-3.rs
+++ b/crates/tinywasm/tests/test-wasm-3.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{SpecVersion, spec};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-annotations.rs b/crates/tinywasm/tests/test-wasm-annotations.rs
deleted file mode 100644
index 8655d15..0000000
--- a/crates/tinywasm/tests/test-wasm-annotations.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::Annotations))?;
- test_suite.save_csv("./tests/generated/wasm-annotations.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs b/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs
index e4aacfc..a71266a 100644
--- a/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs
+++ b/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-custom.rs b/crates/tinywasm/tests/test-wasm-custom.rs
index ae08142..b516428 100644
--- a/crates/tinywasm/tests/test-wasm-custom.rs
+++ b/crates/tinywasm/tests/test-wasm-custom.rs
@@ -1,8 +1,6 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let custom_dir = std::path::Path::new("./tests/wasm-custom");
diff --git a/crates/tinywasm/tests/test-wasm-extended-const.rs b/crates/tinywasm/tests/test-wasm-extended-const.rs
deleted file mode 100644
index 888a49f..0000000
--- a/crates/tinywasm/tests/test-wasm-extended-const.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::ExtendedConst))?;
- test_suite.save_csv("./tests/generated/wasm-extended-const.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-function-references.rs b/crates/tinywasm/tests/test-wasm-function-references.rs
deleted file mode 100644
index d91ff82..0000000
--- a/crates/tinywasm/tests/test-wasm-function-references.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::FunctionReferences))?;
- test_suite.save_csv("./tests/generated/wasm-function-references.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-gc.rs b/crates/tinywasm/tests/test-wasm-gc.rs
index a80d347..86496c4 100644
--- a/crates/tinywasm/tests/test-wasm-gc.rs
+++ b/crates/tinywasm/tests/test-wasm-gc.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-latest.rs b/crates/tinywasm/tests/test-wasm-latest.rs
index af83c2f..649c44c 100644
--- a/crates/tinywasm/tests/test-wasm-latest.rs
+++ b/crates/tinywasm/tests/test-wasm-latest.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{SpecVersion, spec};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-memory64.rs b/crates/tinywasm/tests/test-wasm-memory64.rs
index 447bbfc..717ae03 100644
--- a/crates/tinywasm/tests/test-wasm-memory64.rs
+++ b/crates/tinywasm/tests/test-wasm-memory64.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-multi-memory.rs b/crates/tinywasm/tests/test-wasm-multi-memory.rs
index e4487f1..b0963b2 100644
--- a/crates/tinywasm/tests/test-wasm-multi-memory.rs
+++ b/crates/tinywasm/tests/test-wasm-multi-memory.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs b/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs
deleted file mode 100644
index 0475fac..0000000
--- a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::NontrappingFloatToIntConversions))?;
- test_suite
- .save_csv("./tests/generated/wasm-nontrapping-float-to-int-conversions.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-reference-types.rs b/crates/tinywasm/tests/test-wasm-reference-types.rs
deleted file mode 100644
index b6f1155..0000000
--- a/crates/tinywasm/tests/test-wasm-reference-types.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::ReferenceTypes))?;
- test_suite.save_csv("./tests/generated/wasm-reference-types.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-relaxed-simd.rs b/crates/tinywasm/tests/test-wasm-relaxed-simd.rs
index 0851d18..92a5991 100644
--- a/crates/tinywasm/tests/test-wasm-relaxed-simd.rs
+++ b/crates/tinywasm/tests/test-wasm-relaxed-simd.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs b/crates/tinywasm/tests/test-wasm-sign-extension-op.rs
deleted file mode 100644
index c0ef143..0000000
--- a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
- let mut test_suite = TestSuite::new();
-
- test_suite.run_files(proposal(&Proposal::SignExtensionOps))?;
- test_suite.save_csv("./tests/generated/wasm-sign-extension-ops.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-simd.rs b/crates/tinywasm/tests/test-wasm-simd.rs
index d8f15ea..3d1932f 100644
--- a/crates/tinywasm/tests/test-wasm-simd.rs
+++ b/crates/tinywasm/tests/test-wasm-simd.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-tail-call.rs b/crates/tinywasm/tests/test-wasm-tail-call.rs
deleted file mode 100644
index b6d8b2b..0000000
--- a/crates/tinywasm/tests/test-wasm-tail-call.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
-use wasm_testsuite::data::{Proposal, proposal};
-
-fn main() -> Result<()> {
- TestSuite::set_log_level(log::LevelFilter::Off);
-
- let mut test_suite = TestSuite::new();
- test_suite.run_files(proposal(&Proposal::TailCall))?;
- test_suite.print_errors();
- test_suite.save_csv("./tests/generated/wasm-tail-call.csv", env!("CARGO_PKG_VERSION"))?;
- test_suite.report_status()
-}
diff --git a/crates/tinywasm/tests/test-wasm-threads.rs b/crates/tinywasm/tests/test-wasm-threads.rs
index 2fd5a9b..5cff235 100644
--- a/crates/tinywasm/tests/test-wasm-threads.rs
+++ b/crates/tinywasm/tests/test-wasm-threads.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs b/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs
index 2aa6b43..e4b5647 100644
--- a/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs
+++ b/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs
@@ -1,9 +1,7 @@
-mod testsuite;
-use eyre::Result;
-use testsuite::TestSuite;
+use tinywasm_cli::testsuite::TestSuite;
use wasm_testsuite::data::{Proposal, proposal};
-fn main() -> Result<()> {
+fn main() -> Result<(), Box<dyn core::error::Error>> {
TestSuite::set_log_level(log::LevelFilter::Off);
let mut test_suite = TestSuite::new();
diff --git a/crates/tinywasm/tests/test-wast.rs b/crates/tinywasm/tests/test-wast.rs
index 92fcbd2..fcf3044 100644
--- a/crates/tinywasm/tests/test-wast.rs
+++ b/crates/tinywasm/tests/test-wast.rs
@@ -1,12 +1,9 @@
-use std::path::PathBuf;
-
-use eyre::{Result, bail};
use tinywasm_cli::wast_runner::WastRunner;
-fn main() -> Result<()> {
- let args = std::env::args().collect::<Vec<_>>();
- if args.len() < 2 {
- bail!("usage: cargo test-wast <wast-file>");
+fn main() -> Result<(), Box<dyn core::error::Error>> {
+ let Some(input) = std::env::args().nth(1) else {
+ eprintln!("usage: cargo test-wast <wast-file>");
+ std::process::exit(2);
};
let mut cwd = std::env::current_dir()?;
@@ -15,16 +12,10 @@ fn main() -> Result<()> {
cwd.pop();
}
- // if its a folder, run all the wast files in the folder
- let arg = PathBuf::from(cwd.clone()).join(&args[1]);
+ let arg = cwd.join(input);
println!("running tests in {:?}", arg);
- let files = if arg.is_dir() {
- std::fs::read_dir(&arg)?.map(|entry| entry.map(|e| e.path())).collect::<Result<Vec<_>, _>>()?
- } else {
- vec![arg]
- };
-
let mut test_suite = WastRunner::new();
- test_suite.run_paths(&files)
+ test_suite.run_paths(&[arg])?;
+ Ok(())
}
diff --git a/crates/tinywasm/tests/typed_gc_access.rs b/crates/tinywasm/tests/typed_gc_access.rs
new file mode 100644
index 0000000..26b2362
--- /dev/null
+++ b/crates/tinywasm/tests/typed_gc_access.rs
@@ -0,0 +1,49 @@
+use tinywasm::types::{ArrayRef, RefValue, StructRef, WasmValue};
+use tinywasm::{GcStorageType, ModuleInstance, Store};
+
+#[test]
+fn typed_struct_and_array_access() -> tinywasm::Result<()> {
+ let wasm = wat::parse_str(
+ r#"(module
+ (type $s (struct (field (mut i32)) (field i8)))
+ (type $refs (struct (field (ref $s)) (field (ref null $s))))
+ (type $a (array (mut i16)))
+ (func $make-struct (result (ref $s))
+ i32.const 7
+ i32.const 258
+ struct.new $s)
+ (func (export "struct") (result (ref struct))
+ call $make-struct)
+ (func (export "refs") (result (ref struct))
+ call $make-struct
+ ref.null $s
+ struct.new $refs)
+ (func (export "array") (result (ref array))
+ i32.const 65537
+ i32.const 2
+ array.new $a))"#,
+ )
+ .expect("valid WAT");
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &tinywasm::parse_bytes(&wasm)?, None)?;
+
+ let structure: StructRef = instance.func::<(), StructRef>(&store, "struct")?.call(&mut store, ())?;
+ assert_eq!(structure.fields(&mut store)?, [WasmValue::I32(7), WasmValue::I32(2)]);
+ structure.set_field(&mut store, 0, WasmValue::I32(9))?;
+ assert_eq!(structure.field(&mut store, 0)?, WasmValue::I32(9));
+ assert_eq!(structure.ty(&store)?.field(&store, 1)?.storage(), GcStorageType::I8);
+
+ let references: StructRef = instance.func::<(), StructRef>(&store, "refs")?.call(&mut store, ())?;
+ let fields = references.fields(&mut store)?;
+ let WasmValue::Ref(RefValue::Any(nested)) = &fields[0] else { panic!("expected struct reference") };
+ assert_eq!(fields[1], WasmValue::Ref(RefValue::Null));
+ store.gc()?;
+ assert_eq!(nested.as_struct().unwrap().field(&mut store, 0)?, WasmValue::I32(7));
+
+ let array: ArrayRef = instance.func::<(), ArrayRef>(&store, "array")?.call(&mut store, ())?;
+ assert_eq!(array.len(&store)?, 2);
+ assert_eq!(array.get(&mut store, 0)?, WasmValue::I32(1));
+ array.set(&mut store, 1, WasmValue::I32(3))?;
+ assert_eq!(array.get(&mut store, 1)?, WasmValue::I32(3));
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs
new file mode 100644
index 0000000..34f402d
--- /dev/null
+++ b/crates/tinywasm/tests/typed_globals.rs
@@ -0,0 +1,94 @@
+use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue};
+use tinywasm::{Global, Imports, ModuleInstance, Store};
+
+#[test]
+fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box<dyn core::error::Error>> {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (global (mut i32) (i32.const 1))
+ (global (mut f32) (f32.const 2))
+ (global (mut i64) (i64.const 3))
+ (global (mut f64) (f64.const 4))
+ (global (mut v128) (v128.const i32x4 1 2 3 4))
+ (global (mut funcref) (ref.null func))
+
+ (func (export "i32") (param i32) (result i32)
+ local.get 0 global.set 0 global.get 0)
+ (func (export "f32") (param f32) (result f32)
+ local.get 0 global.set 1 global.get 1)
+ (func (export "i64") (param i64) (result i64)
+ local.get 0 global.set 2 global.get 2)
+ (func (export "f64") (param f64) (result f64)
+ local.get 0 global.set 3 global.get 3)
+ (func (export "v128") (param v128) (result v128)
+ local.get 0 global.set 4 global.get 4)
+ (func (export "ref") (param funcref) (result funcref)
+ local.get 0 global.set 5 global.get 5)
+ (func (export "add-i32") (param i32) (result i32)
+ local.get 0 global.get 0 i32.add)
+ (func (export "add-i64") (param i64) (result i64)
+ local.get 0 global.get 2 i64.add)
+ )
+ "#,
+ )?;
+
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let instructions = module.funcs.iter().flat_map(|func| func.instructions.iter());
+ let (mut tee32, mut tee64, mut tee128, mut fused32, mut fused64) = (0, 0, 0, 0, 0);
+ for instruction in instructions {
+ match instruction {
+ Instruction::GlobalTee32(_) => tee32 += 1,
+ Instruction::GlobalTee64(_) => tee64 += 1,
+ Instruction::GlobalTee128(_) => tee128 += 1,
+ Instruction::BinOpStackGlobal32(..) => fused32 += 1,
+ Instruction::BinOpStackGlobal64(..) => fused64 += 1,
+ _ => {}
+ }
+ }
+ assert_eq!((tee32, tee64, tee128), (3, 2, 1));
+ assert_eq!((fused32, fused64), (1, 1));
+
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ let cases = [
+ ("i32", WasmValue::I32(11)),
+ ("f32", WasmValue::F32(12.5)),
+ ("i64", WasmValue::I64(13)),
+ ("f64", WasmValue::F64(14.5)),
+ ("v128", WasmValue::V128([15; 16])),
+ ("ref", WasmValue::Ref(RefValue::Null)),
+ ];
+ for (name, value) in cases {
+ let mut results = [value.clone()];
+ instance.func_untyped(&store, name)?.call(&mut store, std::slice::from_ref(&value), &mut results)?;
+ assert_eq!(results, [value]);
+ }
+ assert_eq!(instance.func::<i32, i32>(&store, "add-i32")?.call(&mut store, 2)?, 13);
+ assert_eq!(instance.func::<i64, i64>(&store, "add-i64")?.call(&mut store, 2)?, 15);
+
+ Ok(())
+}
+
+#[test]
+fn imported_global_keeps_its_typed_store_address() -> Result<(), Box<dyn core::error::Error>> {
+ let wasm = wat::parse_str(
+ r#"
+ (module
+ (import "env" "g" (global (mut i64)))
+ (func (export "roundtrip") (param i64) (result i64)
+ local.get 0 global.set 0 global.get 0)
+ )
+ "#,
+ )?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let global = Global::try_new(&mut store, GlobalType::new(WasmType::I64, true), WasmValue::I64(1))?;
+ let mut imports = Imports::default();
+ imports.define("env", "g", global);
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+
+ assert_eq!(instance.func::<i64, i64>(&store, "roundtrip")?.call(&mut store, 42)?, 42);
+ assert_eq!(global.get(&mut store)?, WasmValue::I64(42));
+ Ok(())
+}
diff --git a/crates/tinywasm/tests/typed_lookup.rs b/crates/tinywasm/tests/typed_lookup.rs
index 15b31b1..c5e052e 100644
--- a/crates/tinywasm/tests/typed_lookup.rs
+++ b/crates/tinywasm/tests/typed_lookup.rs
@@ -1,8 +1,7 @@
-use eyre::Result;
use tinywasm::ModuleInstance;
#[test]
-fn func_typed_rejects_wrong_param_or_result_types() -> Result<()> {
+fn func_typed_rejects_wrong_param_or_result_types() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
@@ -26,7 +25,7 @@ fn func_typed_rejects_wrong_param_or_result_types() -> Result<()> {
}
#[test]
-fn func_typed_rejects_partial_multi_value_results() -> Result<()> {
+fn func_typed_rejects_partial_multi_value_results() -> Result<(), Box<dyn core::error::Error>> {
let wasm = wat::parse_str(
r#"
(module
diff --git a/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast
new file mode 100644
index 0000000..bc92b30
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast
@@ -0,0 +1,35 @@
+(module
+ (func (export "retained-value-before-update-branch") (param i32 i32) (result i32)
+ (block (result i32)
+ local.get 0
+ i32.eqz
+ local.get 1
+ i32.const 1
+ i32.add
+ local.tee 1
+ br_if 0
+ )
+ drop
+ local.get 1
+ )
+
+ (func (export "compare-eqz-br-if") (param i32 i32) (result i32)
+ block
+ i32.const 1
+ local.get 0
+ local.get 1
+ i32.lt_u
+ i32.eqz
+ br_if 0
+ drop
+ i32.const 2
+ return
+ end
+ i32.const 3
+ )
+)
+
+(assert_return (invoke "retained-value-before-update-branch" (i32.const 0) (i32.const 0)) (i32.const 1))
+(assert_return (invoke "retained-value-before-update-branch" (i32.const 1) (i32.const -1)) (i32.const 0))
+(assert_return (invoke "compare-eqz-br-if" (i32.const 1) (i32.const 2)) (i32.const 2))
+(assert_return (invoke "compare-eqz-br-if" (i32.const 2) (i32.const 1)) (i32.const 3))
diff --git a/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast b/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast
new file mode 100644
index 0000000..975b89a
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/failed-instantiation-segments.wast
@@ -0,0 +1,104 @@
+;; A function exposed before data initialization traps can still drop that data.
+(module $host
+ (table (export "table") 1 funcref)
+ (func (export "run")
+ i32.const 0
+ call_indirect))
+(register "host" $host)
+(assert_trap
+ (module
+ (import "host" "table" (table 1 funcref))
+ (memory 0)
+ (func $f data.drop 0)
+ (elem (i32.const 0) $f)
+ (data (i32.const 0) "x"))
+ "out of bounds memory access")
+(assert_return (invoke $host "run"))
+(assert_return (invoke $host "run"))
+
+(module $shared
+ (table (export "table") 8 funcref)
+ (memory (export "memory") 1)
+ (func (export "run") (param i32)
+ (call_indirect (local.get 0)))
+ (func (export "load") (param i32) (result i32)
+ (i32.load8_u (local.get 0))))
+(register "shared" $shared)
+
+;; Earlier data writes persist, but the failing and later segments are not dropped.
+(assert_trap
+ (module
+ (import "shared" "table" (table 8 funcref))
+ (import "shared" "memory" (memory 1))
+ (func $earlier
+ (memory.init $earlier (i32.const 10) (i32.const 0) (i32.const 1)))
+ (func $remaining
+ (memory.init $failed (i32.const 10) (i32.const 0) (i32.const 1))
+ (memory.init $later (i32.const 11) (i32.const 0) (i32.const 1))
+ (memory.init $passive (i32.const 12) (i32.const 0) (i32.const 1)))
+ (func $drop
+ data.drop $earlier
+ data.drop $failed
+ data.drop $later
+ data.drop $passive)
+ (elem (i32.const 0) $earlier $remaining $drop)
+ (data $earlier (i32.const 0) "a")
+ (data $failed (i32.const 65535) "bc")
+ (data $later (i32.const 1) "d")
+ (data $passive "e"))
+ "out of bounds memory access")
+(assert_return (invoke $shared "load" (i32.const 0)) (i32.const 97))
+(assert_return (invoke $shared "load" (i32.const 1)) (i32.const 0))
+(assert_return (invoke $shared "load" (i32.const 65535)) (i32.const 0))
+(assert_trap (invoke $shared "run" (i32.const 0)) "out of bounds memory access")
+(assert_return (invoke $shared "run" (i32.const 1)))
+(assert_return (invoke $shared "load" (i32.const 10)) (i32.const 98))
+(assert_return (invoke $shared "load" (i32.const 11)) (i32.const 100))
+(assert_return (invoke $shared "load" (i32.const 12)) (i32.const 101))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_trap (invoke $shared "run" (i32.const 1)) "out of bounds memory access")
+
+;; An element trap stops all later effects, including declarative drops and data writes.
+(assert_trap
+ (module
+ (import "shared" "table" (table 8 funcref))
+ (import "shared" "memory" (memory 1))
+ (func $earlier
+ (table.init $earlier (i32.const 6) (i32.const 0) (i32.const 1)))
+ (func $remaining
+ (table.init $failed (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $later (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $passive (i32.const 6) (i32.const 0) (i32.const 1))
+ (table.init $declared (i32.const 6) (i32.const 0) (i32.const 1))
+ (memory.init $active (i32.const 20) (i32.const 0) (i32.const 1))
+ (memory.init $data (i32.const 21) (i32.const 0) (i32.const 1)))
+ (func $drop
+ elem.drop $earlier
+ elem.drop $failed
+ elem.drop $later
+ elem.drop $passive
+ elem.drop $declared
+ data.drop $active
+ data.drop $data)
+ (func $marker
+ (i32.store8 (i32.const 22) (i32.const 42)))
+ (elem $earlier (i32.const 0) $earlier $remaining $drop)
+ (elem $failed (i32.const 7) $marker $marker)
+ (elem $later (i32.const 7) $marker)
+ (elem $passive func $marker)
+ (elem $declared declare func $marker)
+ (data $active (i32.const 0) "x")
+ (data $data "y"))
+ "out of bounds table access")
+(assert_return (invoke $shared "load" (i32.const 0)) (i32.const 97))
+(assert_trap (invoke $shared "run" (i32.const 7)) "uninitialized element")
+(assert_trap (invoke $shared "run" (i32.const 0)) "out of bounds table access")
+(assert_return (invoke $shared "run" (i32.const 1)))
+(assert_return (invoke $shared "load" (i32.const 20)) (i32.const 120))
+(assert_return (invoke $shared "load" (i32.const 21)) (i32.const 121))
+(assert_return (invoke $shared "run" (i32.const 6)))
+(assert_return (invoke $shared "load" (i32.const 22)) (i32.const 42))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_return (invoke $shared "run" (i32.const 2)))
+(assert_trap (invoke $shared "run" (i32.const 1)) "out of bounds table access")
diff --git a/crates/tinywasm/tests/wasm-custom/memory64-bulk.wast b/crates/tinywasm/tests/wasm-custom/memory64-bulk.wast
new file mode 100644
index 0000000..3302a72
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/memory64-bulk.wast
@@ -0,0 +1,74 @@
+;; Memory64 bulk operations use the target memory's address width.
+(module
+ (memory (export "memory") i64 1)
+ (data "abc")
+ (func (export "run")
+ (memory.init 0 (i64.const 4) (i32.const 0) (i32.const 3))
+ (memory.copy (i64.const 8) (i64.const 4) (i64.const 3))
+ (memory.fill (i64.const 12) (i32.const 120) (i64.const 2)))
+ (func (export "load8") (param i64) (result i32)
+ (i32.load8_u (local.get 0))))
+
+(invoke "run")
+(assert_return (invoke "load8" (i64.const 4)) (i32.const 97))
+(assert_return (invoke "load8" (i64.const 6)) (i32.const 99))
+(assert_return (invoke "load8" (i64.const 8)) (i32.const 97))
+(assert_return (invoke "load8" (i64.const 10)) (i32.const 99))
+(assert_return (invoke "load8" (i64.const 12)) (i32.const 120))
+(assert_return (invoke "load8" (i64.const 13)) (i32.const 120))
+
+;; Mixed-width memory.copy pops each operand from the correct value lane.
+(module
+ (memory $src 1)
+ (memory $dst i64 1)
+ (data (memory $src) (i32.const 0) "abc")
+ (func (export "run")
+ (memory.copy $dst $src (i64.const 5) (i32.const 0) (i32.const 3)))
+ (func (export "load8") (param i64) (result i32)
+ (i32.load8_u $dst (local.get 0))))
+
+(invoke "run")
+(assert_return (invoke "load8" (i64.const 5)) (i32.const 97))
+(assert_return (invoke "load8" (i64.const 7)) (i32.const 99))
+
+;; Unsigned memory.init source bounds produce a Wasm trap rather than a host panic.
+(module
+ (memory 1)
+ (data "x")
+ (func (export "run")
+ (memory.init 0 (i32.const 0) (i32.const -1) (i32.const 1))))
+
+(assert_trap (invoke "run") "out of bounds memory access")
+
+;; memory.init must mark its target local memory as used by allocation analysis.
+(module $host
+ (memory (export "memory") 1))
+(register "host" $host)
+
+(module
+ (import "host" "memory" (memory 1))
+ (memory $local 1)
+ (data $data "x")
+ (func (export "run")
+ (memory.init $local $data (i32.const 0) (i32.const 0) (i32.const 1))))
+
+(assert_return (invoke "run"))
+
+;; Store superinstructions select the address lane from the target memory.
+(module
+ (memory i64 1)
+ (func (export "store") (param i64 i32)
+ (i32.store (local.get 0) (local.get 1)))
+ (func (export "fma") (param i64 f32 f32 f32)
+ (f32.store
+ (local.get 0)
+ (f32.add (local.get 1) (f32.mul (local.get 2) (local.get 3)))))
+ (func (export "load_i32") (param i64) (result i32)
+ (i32.load (local.get 0)))
+ (func (export "load_f32") (param i64) (result f32)
+ (f32.load (local.get 0))))
+
+(invoke "store" (i64.const 4) (i32.const 42))
+(invoke "fma" (i64.const 8) (f32.const 1) (f32.const 2) (f32.const 3))
+(assert_return (invoke "load_i32" (i64.const 4)) (i32.const 42))
+(assert_return (invoke "load_f32" (i64.const 8)) (f32.const 7))
diff --git a/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast
new file mode 100644
index 0000000..147858a
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast
@@ -0,0 +1,59 @@
+(module
+ (func (export "i32-shift-8") (param i32) (result i32)
+ local.get 0
+ i32.const 8
+ i32.shl
+ i32.const 8
+ i32.shr_s
+ )
+ (func (export "i32-extend-8") (param i32) (result i32)
+ local.get 0
+ i32.const 24
+ i32.shl
+ i32.const 24
+ i32.shr_s
+ )
+ (func (export "i32-extend-16") (param i32) (result i32)
+ local.get 0
+ i32.const 16
+ i32.shl
+ i32.const 16
+ i32.shr_s
+ )
+ (func (export "i64-shift-16") (param i64) (result i64)
+ local.get 0
+ i64.const 16
+ i64.shl
+ i64.const 16
+ i64.shr_s
+ )
+ (func (export "i64-extend-8") (param i64) (result i64)
+ local.get 0
+ i64.const 56
+ i64.shl
+ i64.const 56
+ i64.shr_s
+ )
+ (func (export "i64-extend-16") (param i64) (result i64)
+ local.get 0
+ i64.const 48
+ i64.shl
+ i64.const 48
+ i64.shr_s
+ )
+ (func (export "i64-extend-32") (param i64) (result i64)
+ local.get 0
+ i64.const 32
+ i64.shl
+ i64.const 32
+ i64.shr_s
+ )
+)
+
+(assert_return (invoke "i32-shift-8" (i32.const 0x80)) (i32.const 0x80))
+(assert_return (invoke "i32-extend-8" (i32.const 0x80)) (i32.const -128))
+(assert_return (invoke "i32-extend-16" (i32.const 0x8000)) (i32.const -32768))
+(assert_return (invoke "i64-shift-16" (i64.const 0x80)) (i64.const 0x80))
+(assert_return (invoke "i64-extend-8" (i64.const 0x80)) (i64.const -128))
+(assert_return (invoke "i64-extend-16" (i64.const 0x8000)) (i64.const -32768))
+(assert_return (invoke "i64-extend-32" (i64.const 0x80000000)) (i64.const -2147483648))
diff --git a/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast
new file mode 100644
index 0000000..0dabf4e
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast
@@ -0,0 +1,53 @@
+(module
+ (func (export "and") (param v128 v128) (result v128)
+ local.get 0
+ local.get 1
+ v128.and
+ )
+ (func (export "or") (param v128 v128) (result v128)
+ local.get 0
+ local.get 1
+ v128.or
+ )
+ (func (export "add") (param v128 v128) (result v128)
+ local.get 0
+ local.get 1
+ i64x2.add
+ )
+ (func (export "mul") (param v128 v128) (result v128)
+ local.get 0
+ local.get 1
+ i64x2.mul
+ )
+ (func (export "deep-xor") (param v128 v128 v128) (result v128 v128)
+ local.get 0
+ local.get 1
+ local.get 2
+ v128.xor
+ )
+)
+
+(assert_return
+ (invoke "and" (v128.const i32x4 -1 0 -1 0) (v128.const i32x4 1 2 3 4))
+ (v128.const i32x4 1 0 3 0)
+)
+(assert_return
+ (invoke "or" (v128.const i32x4 1 0 3 0) (v128.const i32x4 0 2 0 4))
+ (v128.const i32x4 1 2 3 4)
+)
+(assert_return
+ (invoke "add" (v128.const i64x2 1 2) (v128.const i64x2 3 4))
+ (v128.const i64x2 4 6)
+)
+(assert_return
+ (invoke "mul" (v128.const i64x2 2 3) (v128.const i64x2 4 5))
+ (v128.const i64x2 8 15)
+)
+(assert_return
+ (invoke "deep-xor"
+ (v128.const i32x4 1 2 3 4)
+ (v128.const i32x4 8 4 2 1)
+ (v128.const i32x4 1 1 1 1))
+ (v128.const i32x4 1 2 3 4)
+ (v128.const i32x4 9 5 3 0)
+)
diff --git a/crates/tinywasm/tests/wasm-custom/table-basics.wast b/crates/tinywasm/tests/wasm-custom/table-basics.wast
new file mode 100644
index 0000000..64bda6c
--- /dev/null
+++ b/crates/tinywasm/tests/wasm-custom/table-basics.wast
@@ -0,0 +1,32 @@
+(module
+ (type $result (func (result i32)))
+ (func $seven (type $result) (i32.const 7))
+ (func $nine (type $result) (i32.const 9))
+
+ (table $table 3 5 funcref)
+ (elem (table $table) (i32.const 1) func $seven)
+ (elem $passive func $nine)
+
+ (func (export "size") (result i32)
+ (table.size $table))
+ (func (export "is-null") (param $index i32) (result i32)
+ (ref.is_null (table.get $table (local.get $index))))
+ (func (export "call") (param $index i32) (result i32)
+ (call_indirect $table (type $result) (local.get $index)))
+ (func (export "set-nine") (param $index i32)
+ (table.set $table (local.get $index) (ref.func $nine)))
+ (func (export "init-nine") (param $index i32)
+ (table.init $table $passive (local.get $index) (i32.const 0) (i32.const 1)))
+)
+
+(assert_return (invoke "size") (i32.const 3))
+(assert_return (invoke "is-null" (i32.const 0)) (i32.const 1))
+(assert_return (invoke "is-null" (i32.const 1)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 1)) (i32.const 7))
+(assert_return (invoke "set-nine" (i32.const 0)))
+(assert_return (invoke "is-null" (i32.const 0)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 0)) (i32.const 9))
+(assert_return (invoke "is-null" (i32.const 2)) (i32.const 1))
+(assert_return (invoke "init-nine" (i32.const 2)))
+(assert_return (invoke "is-null" (i32.const 2)) (i32.const 0))
+(assert_return (invoke "call" (i32.const 2)) (i32.const 9))
diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml
index 3587143..2d2bf91 100644
--- a/crates/types/Cargo.toml
+++ b/crates/types/Cargo.toml
@@ -4,21 +4,31 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Shared runtime, module, and archive types for TinyWasm"
-readme = "README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
categories.workspace = true
[dependencies]
-log = { workspace = true, optional = true }
+portable-atomic-util = { version = "0.2.8", default-features = false, features = ["alloc"], optional = true }
postcard = { version = "1.1", default-features = false, features = ["alloc"], optional = true }
-serde = { version = "1.0", default-features = false, features = ["alloc", "rc"], optional = true }
+serde = { version = "1.0", default-features = false, features = ["alloc"], optional = true }
[features]
-default = ["archive", "debug", "log", "std"]
+default = ["archive", "debug", "std"]
-archive = ["dep:postcard", "dep:serde"]
+# support serializing and deserializing twasm archives
+archive = ["dep:postcard", "dep:serde", "portable-atomic-util?/serde", "serde/rc"]
+
+# derive Debug for runtime and module types
debug = []
-log = ["dep:log"]
+
+# enable standard library support
std = ["serde?/std"]
+
+# support targets without native atomic CAS
+portable-atomic = ["dep:portable-atomic-util"]
+
+[lints]
+workspace = true
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index 99238ab..6a03605 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 {
@@ -64,6 +64,12 @@ impl Module {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::Operand128Idx;
+ use crate::{
+ AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, Operand128,
+ RefType, Shared, WasmFunction, WasmType,
+ };
+ use alloc::boxed::Box;
#[test]
fn test_invalid_magic() {
@@ -80,4 +86,59 @@ mod tests {
twasm[4] = 0;
assert!(matches!(Module::try_from_twasm(&twasm), Err(TwasmError::InvalidVersion)));
}
+
+ #[test]
+ fn v128_operands_round_trip_archive() {
+ let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90];
+ let mut function = WasmFunction::default();
+ let constant = Operand128Idx::new(0);
+ function.data.operands128 = Box::new([Operand128::<[u8; 16]>::new(bytes).cast()]);
+ function.instructions = Box::new([Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)]);
+ let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() });
+
+ let archive = module.serialize_twasm().expect("serialize archive");
+ assert_eq!(&archive[..6], b"TWAS05");
+ let decoded = Module::try_from_twasm(&archive).expect("deserialize archive");
+ let function = &decoded.funcs[0];
+
+ for instruction in function.instructions.iter() {
+ let index = match instruction {
+ Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index,
+ _ => panic!("unexpected instruction"),
+ };
+ assert_eq!(index.resolve(&function.data).value(), bytes);
+ }
+ }
+
+ #[test]
+ fn const_reference_expressions_round_trip_archive() {
+ let null_type = RefType::new_abstract(true, AbstractHeapType::Extern);
+ let module = Module::from(ModuleInner {
+ globals: Box::new([
+ Global {
+ ty: GlobalType::new(WasmType::Ref(null_type), false),
+ init: Box::new([ConstInstruction::RefNull(null_type)]),
+ },
+ Global {
+ ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false),
+ init: Box::new([ConstInstruction::RefFunc(ModuleFuncIdx::new(7))]),
+ },
+ Global {
+ ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false),
+ init: Box::new([ConstInstruction::I32Const(42), ConstInstruction::RefI31]),
+ },
+ ]),
+ ..ModuleInner::default()
+ });
+
+ let archive = module.serialize_twasm().expect("serialize archive");
+ let decoded = Module::try_from_twasm(&archive).expect("deserialize archive");
+
+ assert!(matches!(decoded.globals[0].init.as_ref(), [ConstInstruction::RefNull(ty)] if *ty == null_type));
+ assert!(matches!(
+ decoded.globals[1].init.as_ref(),
+ [ConstInstruction::RefFunc(index)] if index.index() == 7
+ ));
+ assert!(matches!(decoded.globals[2].init.as_ref(), [ConstInstruction::I32Const(42), ConstInstruction::RefI31]));
+ }
}
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index a53576e..3bc71a2 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -1,48 +1,390 @@
-use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts};
-use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue};
+use alloc::boxed::Box;
-/// Represents a memory immediate in a WebAssembly memory instruction.
+use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts};
+use crate::operands::{read_field, write_field};
+use crate::{
+ DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType,
+};
+
+/// Identifies the packed full-width memory operand layout.
+pub enum MemoryOperand {}
+
+/// Identifies the packed compact memory operand layout.
+pub enum CompactMemoryOperand {}
+
+/// Identifies a packed branch-table operand.
+pub enum BranchTableOperand {}
+
+/// Identifies a packed constant memory-fill operand.
+pub enum MemoryFillOperand {}
+
+/// Identifies a packed local update and branch operand.
+pub enum LocalUpdateOperand {}
+
+/// Identifies a packed global update and branch operand.
+pub enum GlobalUpdateOperand {}
+
+/// Identifies a packed local update, comparison, and branch operand.
+pub enum LocalUpdateCmpOperand {}
+
+/// A compact memory immediate used by optimized instructions.
+///
+/// Optimized instructions use this representation when the offset and
+/// module-local memory index fit its narrower fields.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct CompactMemoryArg {
+ offset: u32,
+ mem_addr: u16,
+}
+
+/// An indexed memory argument and up to two local operands.
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
#[repr(Rust, packed)]
-pub struct MemoryArg {
- offset: u64,
- mem_addr: MemAddr,
+pub struct MemoryLocalArg {
+ pub memory_arg_idx: Operand64Idx<CompactMemoryOperand>,
+ pub local1: u8,
+ pub local2: u8,
+}
+
+/// An indexed memory argument and SIMD lane.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct MemoryLaneArg {
+ pub memory_arg_idx: Operand128Idx<MemoryOperand>,
+ pub lane: u8,
+}
+
+/// A 32-bit immediate and local operand that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct I32LocalArg {
+ pub value: i32,
+ pub local: LocalAddr,
+}
+
+/// Three local operands that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct LocalTripleArg {
+ pub left: LocalAddr,
+ pub right: LocalAddr,
+ pub dst: LocalAddr,
+}
+
+/// A branch target and local operand that fit in an instruction payload.
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[repr(Rust, packed)]
+pub struct TargetLocalArg {
+ pub target_ip: u32,
+ pub local: LocalAddr,
+}
+
+/// An operation packed inline with an indexed operand.
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(
+ feature = "archive",
+ serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",))
+)]
+#[repr(Rust, packed)]
+pub struct PackedOp<Op, T, const WIDTH: usize> {
+ pub op: Op,
+ pub index: OperandIdx<T, WIDTH>,
+}
+
+/// An operation packed with an index into the 64-bit operand lane.
+pub type PackedOp64<Op, T> = PackedOp<Op, T, 8>;
+
+/// An operation packed with an index into the 128-bit operand lane.
+pub type PackedOp128<Op, T> = PackedOp<Op, T, 16>;
+
+impl<Op: Copy, T, const WIDTH: usize> Copy for PackedOp<Op, T, WIDTH> {}
+
+impl<Op: Copy, T, const WIDTH: usize> Clone for PackedOp<Op, T, WIDTH> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<Op: Copy + PartialEq, T, const WIDTH: usize> PartialEq for PackedOp<Op, T, WIDTH> {
+ fn eq(&self, other: &Self) -> bool {
+ let (op, index) = (self.op, self.index);
+ let (other_op, other_index) = (other.op, other.index);
+ op == other_op && index == other_index
+ }
+}
+
+impl<Op: Copy + Eq, T, const WIDTH: usize> Eq for PackedOp<Op, T, WIDTH> {}
+
+#[cfg(feature = "debug")]
+impl<Op: Copy + core::fmt::Debug, T, const WIDTH: usize> core::fmt::Debug for PackedOp<Op, T, WIDTH> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ let (op, index) = (self.op, self.index);
+ formatter.debug_struct("PackedOp").field("op", &op).field("index", &index).finish()
+ }
+}
+
+impl<Op, T, const WIDTH: usize> PackedOp<Op, T, WIDTH> {
+ /// Creates a packed operation from an operator and operand index.
+ #[inline]
+ pub const fn new(op: Op, index: OperandIdx<T, WIDTH>) -> Self {
+ Self { op, index }
+ }
}
-/// Stack lanes discarded and retained when branching to a control frame.
+/// A catch clause attached to a lowered `try_table` instruction.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct DropKeep {
- pub base: ValueCounts,
- pub keep: ValueCounts,
+pub enum ExceptionCatch {
+ /// Catch exceptions carrying the specified module-local tag.
+ Tag { tag: TagAddr, landing_pad: u32, base: ValueCounts, with_ref: bool },
+ /// Catch any exception.
+ All { landing_pad: u32, base: ValueCounts, with_ref: bool },
}
-impl From<(ValueCounts, ValueCounts)> for DropKeep {
- fn from((base, keep): (ValueCounts, ValueCounts)) -> Self {
- Self { base, keep }
+impl ExceptionCatch {
+ /// Returns the catch landing pad instruction pointer.
+ pub const fn landing_pad(self) -> u32 {
+ match self {
+ Self::Tag { landing_pad, .. } | Self::All { landing_pad, .. } => landing_pad,
+ }
+ }
+
+ /// Returns whether this clause exposes the caught exception reference.
+ pub const fn with_ref(self) -> bool {
+ match self {
+ Self::Tag { with_ref, .. } | Self::All { with_ref, .. } => with_ref,
+ }
}
}
-impl MemoryArg {
+/// A statically lowered exception handler range.
+#[derive(Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct ExceptionHandler {
+ /// First protected instruction, inclusive.
+ pub start_ip: u32,
+ /// End of the protected instruction range, exclusive.
+ pub end_ip: u32,
+ /// Catch clauses in source order.
+ pub catches: Box<[ExceptionCatch]>,
+}
+
+impl Operand128<MemoryOperand> {
+ /// Creates a full-width memory operand.
#[inline]
- pub const fn new(offset: u64, mem_addr: MemAddr) -> Self {
- Self { offset, mem_addr }
+ pub fn new(offset: u64, memory: MemAddr) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u64, 0, offset);
+ write_field!(operand, u32, 8, memory);
+ operand
+ }
+
+ /// Returns the static byte offset.
+ #[inline(always)]
+ pub fn offset(&self) -> u64 {
+ read_field!(self, u64, 0)
}
+ /// Returns the module-local memory index.
+ #[inline(always)]
+ pub fn memory(&self) -> MemAddr {
+ read_field!(self, u32, 8)
+ }
+}
+
+impl Operand64<CompactMemoryOperand> {
+ /// Creates a compact memory operand.
+ #[inline]
+ pub fn new(offset: u32, memory: u16) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, offset);
+ write_field!(operand, u16, 4, memory);
+ operand
+ }
+
+ /// Returns the static byte offset.
+ #[inline(always)]
+ pub fn offset(&self) -> u32 {
+ read_field!(self, u32, 0)
+ }
+
+ /// Returns the module-local memory index.
+ #[inline(always)]
+ pub fn memory(&self) -> u16 {
+ read_field!(self, u16, 4)
+ }
+}
+
+impl Operand128<BranchTableOperand> {
+ #[inline]
+ pub fn new(target: u32, start: u32, len: u32) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, target);
+ write_field!(operand, u32, 4, start);
+ write_field!(operand, u32, 8, len);
+ operand
+ }
+ #[inline(always)]
+ pub fn start(&self) -> u32 {
+ read_field!(self, u32, 4)
+ }
+ #[inline(always)]
+ pub fn size(&self) -> u32 {
+ read_field!(self, u32, 8)
+ }
+}
+
+impl Operand128<MemoryFillOperand> {
+ #[inline]
+ pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, memory);
+ write_field!(operand, u8, 4, byte);
+ write_field!(operand, i32, 5, value);
+ operand
+ }
+ #[inline(always)]
+ pub fn memory(&self) -> MemAddr {
+ read_field!(self, u32, 0)
+ }
+ #[inline(always)]
+ pub fn byte(&self) -> u8 {
+ read_field!(self, u8, 4)
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 5)
+ }
+}
+
+impl Operand128<LocalUpdateOperand> {
+ #[inline]
+ pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, target);
+ write_field!(operand, i32, 4, value);
+ write_field!(operand, u16, 8, local);
+ write_field!(operand, u8, 10, u8::from(on_zero));
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
+ #[inline(always)]
+ pub fn local(&self) -> LocalAddr {
+ read_field!(self, u16, 8)
+ }
+ #[inline(always)]
+ pub fn on_zero(&self) -> bool {
+ read_field!(self, u8, 10) != 0
+ }
+}
+
+impl Operand128<GlobalUpdateOperand> {
+ #[inline]
+ pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, target);
+ write_field!(operand, i32, 4, value);
+ write_field!(operand, u32, 8, global);
+ write_field!(operand, u8, 12, u8::from(on_zero));
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
+ #[inline(always)]
+ pub fn global(&self) -> GlobalAddr {
+ read_field!(self, u32, 8)
+ }
+ #[inline(always)]
+ pub fn on_zero(&self) -> bool {
+ read_field!(self, u8, 12) != 0
+ }
+}
+
+impl Operand128<LocalUpdateCmpOperand> {
+ #[inline]
+ pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, u32, 0, target);
+ write_field!(operand, i32, 4, value);
+ write_field!(operand, u16, 8, local);
+ write_field!(operand, u16, 10, right);
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
+ #[inline(always)]
+ pub fn local(&self) -> LocalAddr {
+ read_field!(self, u16, 8)
+ }
+ #[inline(always)]
+ pub fn right(&self) -> LocalAddr {
+ read_field!(self, u16, 10)
+ }
+}
+
+impl CompactMemoryArg {
+ /// Returns the static byte offset.
#[inline]
pub const fn offset(self) -> u64 {
- self.offset
+ self.offset as u64
}
+ /// Returns the module-local memory index.
#[inline]
pub const fn mem_addr(self) -> MemAddr {
- self.mem_addr
+ self.mem_addr as MemAddr
}
}
+impl TryFrom<Operand128<MemoryOperand>> for CompactMemoryArg {
+ type Error = ();
+
+ #[inline]
+ fn try_from(arg: Operand128<MemoryOperand>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ offset: u32::try_from(arg.offset()).map_err(|_| ())?,
+ mem_addr: u16::try_from(arg.memory()).map_err(|_| ())?,
+ })
+ }
+}
+
+impl From<CompactMemoryArg> for Operand64<CompactMemoryOperand> {
+ #[inline]
+ fn from(arg: CompactMemoryArg) -> Self {
+ Self::new(arg.offset, arg.mem_addr)
+ }
+}
+
+const _: () = {
+ assert!(core::mem::size_of::<Operand64Idx<i64>>() == 4);
+ assert!(core::mem::size_of::<Operand64>() == 8);
+ assert!(core::mem::size_of::<Operand128>() == 16);
+ assert!(core::mem::size_of::<CompactMemoryArg>() == 6);
+ assert!(core::mem::size_of::<MemoryLocalArg>() == 6);
+ assert!(core::mem::size_of::<LocalTripleArg>() == 6);
+};
+
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -52,8 +394,20 @@ pub enum ConstInstruction {
F32Const(f32),
F64Const(f64),
V128Const([u8; 16]),
- GlobalGet(GlobalAddr),
- Ref(RefValue),
+ GlobalGet32(GlobalAddr),
+ GlobalGet64(GlobalAddr),
+ GlobalGet128(GlobalAddr),
+ GlobalGetRef(GlobalAddr),
+ RefNull(RefType),
+ RefFunc(ModuleFuncIdx),
+ RefI31,
+ AnyConvertExtern,
+ ExternConvertAny,
+ StructNew(TypeAddr),
+ StructNewDefault(TypeAddr),
+ ArrayNew(TypeAddr),
+ ArrayNewDefault(TypeAddr),
+ ArrayNewFixed(TypeAddr, u32),
I32Add,
I32Sub,
I32Mul,
@@ -79,6 +433,25 @@ pub enum CmpOp {
GeU,
}
+impl CmpOp {
+ /// Returns the comparison that is true exactly when `self` is false.
+ #[inline]
+ pub const fn inverse(self) -> Self {
+ match self {
+ Self::Eq => Self::Ne,
+ Self::Ne => Self::Eq,
+ Self::LtS => Self::GeS,
+ Self::LtU => Self::GeU,
+ Self::GtS => Self::LeS,
+ Self::GtU => Self::LeU,
+ Self::LeS => Self::GtS,
+ Self::LeU => Self::GtU,
+ Self::GeS => Self::LtS,
+ Self::GeU => Self::LtU,
+ }
+ }
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -103,6 +476,18 @@ pub enum BinOp {
FCopysign,
}
+impl BinOp {
+ /// Returns the update delta for `local OP immediate`, when it is a simple increment.
+ #[inline]
+ pub const fn inc_delta(self, immediate: i32) -> Option<i32> {
+ match self {
+ Self::IAdd => Some(immediate),
+ Self::ISub => Some(immediate.wrapping_neg()),
+ _ => None,
+ }
+ }
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -115,76 +500,95 @@ pub enum BinOp128 {
I64x2Mul,
}
-/// A TinyWasm bytecode instruction.
-///
-/// These instructions are an internal, version-specific representation and do not
-/// map one-to-one to WebAssembly instructions. Their variants and serialized form
-/// may change between TinyWasm releases.
-///
-/// See <https://webassembly.github.io/spec/core/binary/instructions.html>
-#[rustfmt::skip]
-#[derive(Clone, Copy, PartialEq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub enum Instruction {
+macro_rules! define_instructions {
+ ($($variant:ident $(($($field:ty),* $(,)?))? $({ $($name:ident: $named_field:ty),* $(,)? })?),* $(,)?) => {
+ /// A TinyWasm bytecode instruction.
+ ///
+ /// These instructions are an internal, version-specific representation and do not
+ /// map one-to-one to WebAssembly instructions. Their variants and serialized form
+ /// may change between TinyWasm releases.
+ #[derive(Clone, Copy, PartialEq)]
+ #[cfg_attr(feature = "debug", derive(Debug))]
+ #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+ pub enum Instruction {
+ $($variant $(($($field),*))? $({ $($name: $named_field),* })?),*
+ }
+
+ #[doc(hidden)]
+ #[repr(u16)]
+ #[derive(Clone, Copy)]
+ pub enum InstructionOpcode {
+ $($variant,)*
+ }
+
+ impl InstructionOpcode {
+ #[doc(hidden)]
+ pub const COUNT: usize = [$(Self::$variant),*].len();
+ }
+
+ impl Instruction {
+ /// Returns the compact opcode used to dispatch this instruction.
+ #[inline(always)]
+ pub const fn opcode(&self) -> InstructionOpcode {
+ match self {
+ $(Self::$variant { .. } => InstructionOpcode::$variant,)*
+ }
+ }
+ }
+ };
+}
+
+define_instructions! {
LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr),
- AddConst32(i32), AddConst64(i64),
- IncLocal32(LocalAddr, i32), IncLocal64(LocalAddr, i64),
+ AddConst32(i32), AndConst32(i32), XorConst32(i32), ShrUConst32(i32), AddConst64(Operand64Idx<i64>),
+ IncLocal32(I32LocalArg), IncLocal64(PackedOp64<LocalAddr, i64>),
+
// The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results.
BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr),
BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr),
- BinOpLocalLocalSet32(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalSet64(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalSet128(BinOp128, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee32(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee64(BinOp, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalLocalTee128(BinOp128, LocalAddr, LocalAddr, LocalAddr),
- BinOpLocalConst32(BinOp, LocalAddr, i32), BinOpLocalConst64(BinOp, LocalAddr, i64),
- BinOpLocalConst128(BinOp128, LocalAddr, ConstIdx),
- BinOpLocalConstSet32(BinOp, LocalAddr, i32, LocalAddr),
- BinOpLocalConstSet64(BinOp, LocalAddr, i64, LocalAddr),
- BinOpLocalConstSet128(BinOp128, LocalAddr, ConstIdx, LocalAddr),
- BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr),
- BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr),
- BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr),
+ CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr),
+ AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg),
+ BinOpLocalLocalSet32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet128(PackedOp64<BinOp128, (u16, u16, u16)>),
+ BinOpLocalLocalTee32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee128(PackedOp64<BinOp128, (u16, u16, u16)>),
+
+ AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg),
+ AndLocalConst32(I32LocalArg), ShrULocalConst32(I32LocalArg),
+ BinOpLocalConst32(PackedOp64<BinOp, (u16, u32)>), BinOpLocalConst64(PackedOp128<BinOp, (u16, u64)>),
+ BinOpLocalConst128(PackedOp64<BinOp128, (u16, Operand128Idx<[u8; 16]>)>),
+ BinOpLocalConstSet32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstSet64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstSet128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>),
+ BinOpLocalConstTee32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstTee64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstTee128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>),
+
+ BinOpStackConst32(BinOp, i32), BinOpStackConst64(PackedOp64<BinOp, i64>),
+
+ BinOpStackLocal32(BinOp, LocalAddr),
+ BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr),
+ BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr),
+ BinOpStackLocal128(BinOp128, LocalAddr),
BinOpStackGlobal32(BinOp, u32),
BinOpStackGlobal64(BinOp, u32),
- SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx),
- IncMemoryLocal32(MemoryArg, u8),
- IncMemoryLocal64(MemoryArg, u8),
- StoreLocalLocal32(MemoryArg, u8, u8),
- StoreLocalLocal64(MemoryArg, u8, u8),
- StoreLocalLocal128(MemoryArg, u8, u8),
- LoadLocal32(MemoryArg, u8),
- LoadLocal64(MemoryArg, u8),
- LoadLocal8S32(MemoryArg, u8),
- LoadLocal8U32(MemoryArg, u8),
- LoadLocal16S32(MemoryArg, u8),
- LoadLocal16U32(MemoryArg, u8),
- LoadLocalTee32(MemoryArg, u8, u8),
- LoadLocalSet32(MemoryArg, u8, u8),
- LoadLocalTee8S32(MemoryArg, u8, u8),
- LoadLocalTee8U32(MemoryArg, u8, u8),
- LoadLocalTee16S32(MemoryArg, u8, u8),
- LoadLocalTee16U32(MemoryArg, u8, u8),
- LoadLocalSet8S32(MemoryArg, u8, u8),
- LoadLocalSet8U32(MemoryArg, u8, u8),
- LoadLocalSet16S32(MemoryArg, u8, u8),
- LoadLocalSet16U32(MemoryArg, u8, u8),
- LoadLocalTee128(MemoryArg, u8, u8),
- LoadLocalSet128(MemoryArg, u8, u8),
- AndConstTee32(i32, LocalAddr),
- SubConstTee32(i32, LocalAddr),
- AndConstTee64(i64, LocalAddr),
- SubConstTee64(i64, LocalAddr),
- MulAccLocal32(LocalAddr),
- MulAccLocal64(LocalAddr),
- FMulAccLocal32(LocalAddr),
- FMulAccLocal64(LocalAddr),
+ BinOpGlobalConst32(PackedOp64<BinOp, (u32, u32)>), BinOpGlobalConst64(PackedOp128<BinOp, (u32, u64)>),
+ BinOpGlobalConst128(PackedOp64<BinOp128, (u32, Operand128Idx<[u8; 16]>)>),
+
+ SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64<LocalAddr, i64>), SetLocalConst128(PackedOp128<LocalAddr, [u8; 16]>),
+ IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg),
+ StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg),
+ LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg),
+ LoadLocal8S32(MemoryLocalArg), LoadLocal8U32(MemoryLocalArg),
+ LoadLocal16S32(MemoryLocalArg), LoadLocal16U32(MemoryLocalArg),
+ LoadLocalTee32(MemoryLocalArg), LoadLocalSet32(MemoryLocalArg),
+ LoadLocalTee8S32(MemoryLocalArg), LoadLocalTee8U32(MemoryLocalArg),
+ LoadLocalTee16S32(MemoryLocalArg), LoadLocalTee16U32(MemoryLocalArg),
+ LoadLocalSet8S32(MemoryLocalArg), LoadLocalSet8U32(MemoryLocalArg),
+ LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg),
+ LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg),
+ AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg),
+ AndConstTee64(PackedOp64<LocalAddr, i64>), SubConstTee64(PackedOp64<LocalAddr, i64>),
+ MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr),
+ FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr),
I32Add3,
I64Add3,
- FMaStoreF32(MemoryArg),
- FMaStoreF64(MemoryArg),
+ FMaStoreF32(CompactMemoryArg),
+ FMaStoreF64(CompactMemoryArg),
// > Control Instructions (jump-oriented, lowered from structured control during parsing)
// See <https://webassembly.github.io/spec/core/binary/instructions.html#control-instructions>
@@ -196,18 +600,16 @@ pub enum Instruction {
JumpIfNonZero64(u32),
JumpIfRefNull(u32),
JumpIfRefNonNull(u32),
- JumpIfLocalZero32 { target_ip: u32, local: LocalAddr },
- JumpIfLocalNonZero32 { target_ip: u32, local: LocalAddr },
- JumpIfLocalZero64 { target_ip: u32, local: LocalAddr },
- JumpIfLocalNonZero64 { target_ip: u32, local: LocalAddr },
- JumpCmpStackConst32 { target_ip: u32, imm: i32, op: CmpOp },
- JumpCmpStackConst64 { target_ip: u32, imm: i64, op: CmpOp },
- JumpCmpLocalConst32 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp },
- JumpCmpLocalConst64 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp },
- JumpCmpLocalLocal32 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp },
- JumpCmpLocalLocal64 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp },
- DropKeep(DropKeep),
- BranchTable(u32, u32, u32), // (default_landing_pad_ip, branch_table_start, target_count)
+ JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg),
+ JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg),
+ JumpCmpStackConst32(PackedOp64<CmpOp, (u32, i32)>), JumpCmpStackConst64(PackedOp128<CmpOp, (u32, i64)>),
+ JumpCmpStackLocal32(PackedOp64<CmpOp, (u32, u16)>), JumpCmpStackLocal64(PackedOp64<CmpOp, (u32, u16)>),
+ BinOpLocalConstJump32(PackedOp128<BinOp, LocalUpdateOperand>), BinOpLocalConstJumpCmpLocal32(PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>),
+ BinOpStackConstTeeLocalJump32(PackedOp128<BinOp, LocalUpdateOperand>), BinOpGlobalConstJump32(PackedOp128<BinOp, GlobalUpdateOperand>),
+ IncLocalJump32(Operand128Idx<LocalUpdateOperand>), IncStackTeeLocalJump32(Operand128Idx<LocalUpdateOperand>), IncGlobalJump32(Operand128Idx<GlobalUpdateOperand>),
+ IncLocalJumpCmpLocal32(PackedOp128<CmpOp, LocalUpdateCmpOperand>), JumpCmpLocalConst32(PackedOp128<CmpOp, (u32, i32, u16)>), JumpCmpLocalConst64(PackedOp128<CmpOp, (u32, i32, u16)>),
+ JumpCmpLocalLocal32(PackedOp64<CmpOp, (u32, u16, u16)>), JumpCmpLocalLocal64(PackedOp64<CmpOp, (u32, u16, u16)>),
+ DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(Operand128Idx<BranchTableOperand>),
Return,
ReturnVoid,
Return32,
@@ -215,12 +617,14 @@ pub enum Instruction {
Return128,
Call(FuncAddr),
CallSelf,
- CallIndirect(TypeAddr, TableAddr),
+ CallIndirect(Operand64Idx<(u32, u32)>),
CallRef(TypeAddr),
ReturnCall(FuncAddr),
ReturnCallSelf,
- ReturnCallIndirect(TypeAddr, TableAddr),
+ ReturnCallIndirect(Operand64Idx<(u32, u32)>),
ReturnCallRef(TypeAddr),
+ Throw(TagAddr),
+ ThrowRef,
// > Parametric Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#parametric-instructions>
@@ -231,47 +635,53 @@ pub enum Instruction {
// > Variable Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#variable-instructions>
- GlobalGet(GlobalAddr),
- LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr),
- LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr),
- LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr),
+ GlobalGet32(GlobalAddr), GlobalSet32(GlobalAddr), GlobalTee32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr),
+ GlobalGet64(GlobalAddr), GlobalSet64(GlobalAddr), GlobalTee64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr),
+ GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr),
// > Memory Instructions
- I32Load(MemoryArg),
- I64Load(MemoryArg),
- F32Load(MemoryArg),
- F64Load(MemoryArg),
- I32Load8S(MemoryArg),
- I32Load8U(MemoryArg),
- I32Load16S(MemoryArg),
- I32Load16U(MemoryArg),
- I64Load8S(MemoryArg),
- I64Load8U(MemoryArg),
- I64Load16S(MemoryArg),
- I64Load16U(MemoryArg),
- I64Load32S(MemoryArg),
- I64Load32U(MemoryArg),
- I32Store(MemoryArg),
- I64Store(MemoryArg),
- F32Store(MemoryArg),
- F64Store(MemoryArg),
- I32Store8(MemoryArg),
- I32Store16(MemoryArg),
- I64Store8(MemoryArg),
- I64Store16(MemoryArg),
- I64Store32(MemoryArg),
+ I32Load(Operand128Idx<MemoryOperand>), I64Load(Operand128Idx<MemoryOperand>), F32Load(Operand128Idx<MemoryOperand>), F64Load(Operand128Idx<MemoryOperand>),
+ I32Load8S(Operand128Idx<MemoryOperand>), I32Load8U(Operand128Idx<MemoryOperand>), I32Load16S(Operand128Idx<MemoryOperand>), I32Load16U(Operand128Idx<MemoryOperand>),
+ I64Load8S(Operand128Idx<MemoryOperand>), I64Load8U(Operand128Idx<MemoryOperand>), I64Load16S(Operand128Idx<MemoryOperand>), I64Load16U(Operand128Idx<MemoryOperand>), I64Load32S(Operand128Idx<MemoryOperand>), I64Load32U(Operand128Idx<MemoryOperand>),
+ I32Store(Operand128Idx<MemoryOperand>), I64Store(Operand128Idx<MemoryOperand>), F32Store(Operand128Idx<MemoryOperand>), F64Store(Operand128Idx<MemoryOperand>),
+ I32Store8(Operand128Idx<MemoryOperand>), I32Store16(Operand128Idx<MemoryOperand>), I64Store8(Operand128Idx<MemoryOperand>), I64Store16(Operand128Idx<MemoryOperand>), I64Store32(Operand128Idx<MemoryOperand>),
MemorySize(MemAddr),
MemoryGrow(MemAddr),
// > Constants
Const32(i32),
- Const64(i64),
+ Const64Imm(i32),
+ Const64(Operand64Idx<i64>),
// > Reference Types
RefNull(RefType),
RefFunc(FuncAddr),
RefIsNull,
RefAsNonNull,
+ RefI31,
+ I31GetS,
+ I31GetU,
+ RefEq,
+ RefTest(RefType),
+ RefCast(RefType),
+ BrOnCast(Operand64Idx<(u32, u32)>),
+ BrOnCastFail(Operand64Idx<(u32, u32)>),
+
+ // > GC Objects
+ StructNew(TypeAddr),
+ StructNewDefault(TypeAddr),
+ StructGet(Operand64Idx<(u32, u32)>), StructGetS(Operand64Idx<(u32, u32)>), StructGetU(Operand64Idx<(u32, u32)>), StructSet(Operand64Idx<(u32, u32)>),
+ ArrayNew(TypeAddr),
+ ArrayNewDefault(TypeAddr),
+ ArrayNewFixed(Operand64Idx<(u32, u32)>),
+ ArrayNewData(Operand64Idx<(u32, u32)>), ArrayNewElem(Operand64Idx<(u32, u32)>),
+ ArrayGet(TypeAddr),
+ ArrayGetS(TypeAddr),
+ ArrayGetU(TypeAddr),
+ ArraySet(TypeAddr),
+ ArrayLen,
+ ArrayFill(TypeAddr),
+ ArrayCopy(Operand64Idx<(u32, u32)>), ArrayInitData(Operand64Idx<(u32, u32)>), ArrayInitElem(Operand64Idx<(u32, u32)>),
// > Numeric Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions>
@@ -301,19 +711,18 @@ pub enum Instruction {
I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U,
// > Table Instructions
- TableInit(ElemAddr, TableAddr),
+ TableInit(Operand64Idx<(u32, u32)>),
TableGet(TableAddr),
TableSet(TableAddr),
- TableCopy { dst_table: TableAddr, src_table: TableAddr },
+ TableCopy(Operand64Idx<(u32, u32)>),
TableGrow(TableAddr),
TableSize(TableAddr),
TableFill(TableAddr),
// > Bulk Memory Instructions
- MemoryInit(MemAddr, DataAddr),
- MemoryCopy { dst_mem: MemAddr, src_mem: MemAddr },
+ MemoryInit(Operand64Idx<(u32, u32)>), MemoryCopy(Operand64Idx<(u32, u32)>),
MemoryFill(MemAddr),
- MemoryFillImm(MemAddr, u8, i32),
+ MemoryFillConst(Operand128Idx<MemoryFillOperand>),
DataDrop(DataAddr),
ElemDrop(ElemAddr),
@@ -321,20 +730,18 @@ pub enum Instruction {
I64Add128, I64Sub128, I64MulWideS, I64MulWideU,
// > SIMD
- V128Load(MemoryArg),
- V128Load8x8S(MemoryArg), V128Load8x8U(MemoryArg),
- V128Load16x4S(MemoryArg), V128Load16x4U(MemoryArg),
- V128Load32x2S(MemoryArg), V128Load32x2U(MemoryArg),
+ V128Load(Operand128Idx<MemoryOperand>), V128Load8x8S(Operand128Idx<MemoryOperand>), V128Load8x8U(Operand128Idx<MemoryOperand>),
+ V128Load16x4S(Operand128Idx<MemoryOperand>), V128Load16x4U(Operand128Idx<MemoryOperand>), V128Load32x2S(Operand128Idx<MemoryOperand>), V128Load32x2U(Operand128Idx<MemoryOperand>),
- V128Load8Splat(MemoryArg), V128Load16Splat(MemoryArg), V128Load32Splat(MemoryArg), V128Load64Splat(MemoryArg),
- V128Load8Lane(MemoryArg, u8), V128Load16Lane(MemoryArg, u8), V128Load32Lane(MemoryArg, u8), V128Load64Lane(MemoryArg, u8),
+ V128Load8Splat(Operand128Idx<MemoryOperand>), V128Load16Splat(Operand128Idx<MemoryOperand>), V128Load32Splat(Operand128Idx<MemoryOperand>), V128Load64Splat(Operand128Idx<MemoryOperand>),
+ V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg),
- V128Load32Zero(MemoryArg), V128Load64Zero(MemoryArg),
+ V128Load32Zero(Operand128Idx<MemoryOperand>), V128Load64Zero(Operand128Idx<MemoryOperand>),
- V128Store(MemoryArg), V128Store8Lane(MemoryArg, u8), V128Store16Lane(MemoryArg, u8), V128Store32Lane(MemoryArg, u8), V128Store64Lane(MemoryArg, u8),
+ V128Store(Operand128Idx<MemoryOperand>), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg),
- I8x16Shuffle(ConstIdx),
- Const128(ConstIdx),
+ I8x16Shuffle(Operand128Idx<[u8; 16]>),
+ Const128Imm(u32), Const128(Operand128Idx<[u8; 16]>),
I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8),
I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8),
@@ -386,108 +793,41 @@ pub enum Instruction {
I32x4RelaxedTruncF64x2SZero, I32x4RelaxedTruncF64x2UZero,
F32x4RelaxedMadd, F32x4RelaxedNmadd,
F64x2RelaxedMadd, F64x2RelaxedNmadd,
- I8x16RelaxedLaneselect,
- I16x8RelaxedLaneselect,
- I32x4RelaxedLaneselect,
- I64x2RelaxedLaneselect,
+ I8x16RelaxedLaneselect, I16x8RelaxedLaneselect,
+ I32x4RelaxedLaneselect, I64x2RelaxedLaneselect,
F32x4RelaxedMin, F32x4RelaxedMax,
F64x2RelaxedMin, F64x2RelaxedMax,
I16x8RelaxedQ15mulrS,
I16x8RelaxedDotI8x16I7x16S,
- I32x4RelaxedDotI8x16I7x16AddS
-}
+ I32x4RelaxedDotI8x16I7x16AddS,
-impl Instruction {
- #[inline]
- pub const fn memory_addr(&self) -> Option<MemAddr> {
- match self {
- Self::IncMemoryLocal32(arg, ..)
- | Self::IncMemoryLocal64(arg, ..)
- | Self::StoreLocalLocal32(arg, ..)
- | Self::StoreLocalLocal64(arg, ..)
- | Self::StoreLocalLocal128(arg, ..)
- | Self::LoadLocal32(arg, ..)
- | Self::LoadLocal64(arg, ..)
- | Self::LoadLocal8S32(arg, ..)
- | Self::LoadLocal8U32(arg, ..)
- | Self::LoadLocal16S32(arg, ..)
- | Self::LoadLocal16U32(arg, ..)
- | Self::LoadLocalTee32(arg, ..)
- | Self::LoadLocalSet32(arg, ..)
- | Self::LoadLocalTee8S32(arg, ..)
- | Self::LoadLocalTee8U32(arg, ..)
- | Self::LoadLocalTee16S32(arg, ..)
- | Self::LoadLocalTee16U32(arg, ..)
- | Self::LoadLocalSet8S32(arg, ..)
- | Self::LoadLocalSet8U32(arg, ..)
- | Self::LoadLocalSet16S32(arg, ..)
- | Self::LoadLocalSet16U32(arg, ..)
- | Self::LoadLocalTee128(arg, ..)
- | Self::LoadLocalSet128(arg, ..)
- | Self::I32Load(arg)
- | Self::I64Load(arg)
- | Self::F32Load(arg)
- | Self::F64Load(arg)
- | Self::I32Load8S(arg)
- | Self::I32Load8U(arg)
- | Self::I32Load16S(arg)
- | Self::I32Load16U(arg)
- | Self::I64Load8S(arg)
- | Self::I64Load8U(arg)
- | Self::I64Load16S(arg)
- | Self::I64Load16U(arg)
- | Self::I64Load32S(arg)
- | Self::I64Load32U(arg)
- | Self::I32Store(arg)
- | Self::I64Store(arg)
- | Self::F32Store(arg)
- | Self::F64Store(arg)
- | Self::FMaStoreF32(arg)
- | Self::FMaStoreF64(arg)
- | Self::I32Store8(arg)
- | Self::I32Store16(arg)
- | Self::I64Store8(arg)
- | Self::I64Store16(arg)
- | Self::I64Store32(arg)
- | Self::V128Load(arg)
- | Self::V128Load8x8S(arg)
- | Self::V128Load8x8U(arg)
- | Self::V128Load16x4S(arg)
- | Self::V128Load16x4U(arg)
- | Self::V128Load32x2S(arg)
- | Self::V128Load32x2U(arg)
- | Self::V128Load8Splat(arg)
- | Self::V128Load16Splat(arg)
- | Self::V128Load32Splat(arg)
- | Self::V128Load64Splat(arg)
- | Self::V128Load8Lane(arg, ..)
- | Self::V128Load16Lane(arg, ..)
- | Self::V128Load32Lane(arg, ..)
- | Self::V128Load64Lane(arg, ..)
- | Self::V128Load32Zero(arg)
- | Self::V128Load64Zero(arg)
- | Self::V128Store(arg)
- | Self::V128Store8Lane(arg, ..)
- | Self::V128Store16Lane(arg, ..)
- | Self::V128Store32Lane(arg, ..)
- | Self::V128Store64Lane(arg, ..) => Some(arg.mem_addr()),
- Self::MemorySize(mem)
- | Self::MemoryGrow(mem)
- | Self::MemoryInit(mem, ..)
- | Self::MemoryFill(mem)
- | Self::MemoryFillImm(mem, ..) => Some(*mem),
- Self::MemoryCopy { dst_mem, src_mem } => Some(if *dst_mem >= *src_mem { *dst_mem } else { *src_mem }),
- _ => None,
- }
- }
+ SelectStore32(Operand128Idx<MemoryOperand>), SelectStore64(Operand128Idx<MemoryOperand>),
}
+const _: () = assert!(core::mem::size_of::<Instruction>() == 8);
+
#[cfg(test)]
mod tests {
- use super::Instruction;
+ use super::*;
#[test]
- fn instruction_layout_size_is_stable() {
- assert_eq!(core::mem::size_of::<Instruction>(), 16);
+ fn compact_instruction_layout_is_exact() {
+ assert_eq!(core::mem::size_of::<Instruction>(), 8);
+ assert_eq!(core::mem::size_of::<CompactMemoryArg>(), 6);
+ assert_eq!(core::mem::size_of::<MemoryLocalArg>(), 6);
+ assert_eq!(core::mem::size_of::<LocalTripleArg>(), 6);
+ }
+
+ #[test]
+ fn operand_lanes_round_trip_max_values() {
+ let memory = Operand128::<MemoryOperand>::new(u64::MAX, u32::MAX);
+ assert_eq!(memory.offset(), u64::MAX);
+ assert_eq!(memory.memory(), u32::MAX);
+
+ let value = Operand128::<LocalUpdateOperand>::new(u32::MAX, i32::MIN, u16::MAX, true);
+ assert_eq!(value.target(), u32::MAX);
+ assert_eq!(value.value(), i32::MIN);
+ assert_eq!(value.local(), u16::MAX);
+ assert!(value.on_zero());
}
}
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index 0b15927..a3f26f2 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -9,22 +9,45 @@
//! Types used by [`tinywasm`](https://docs.rs/tinywasm) and [`tinywasm_parser`](https://docs.rs/tinywasm_parser).
extern crate alloc;
-use alloc::{boxed::Box, sync::Arc};
+use alloc::boxed::Box;
use core::ops::{Deref, Range};
+#[cfg(all(not(feature = "portable-atomic"), not(target_has_atomic = "ptr")))]
+compile_error!(
+ "this target does not support atomic operations, enable the `portable-atomic` feature to use `portable-atomic`"
+);
+
+/// An atomically reference-counted pointer.
+#[cfg(not(feature = "portable-atomic"))]
+pub use alloc::sync::Arc as Shared;
+/// A non-owning pointer paired with [`Shared`].
+#[cfg(not(feature = "portable-atomic"))]
+pub use alloc::sync::Weak as WeakShared;
+/// An atomically reference-counted pointer.
+#[cfg(feature = "portable-atomic")]
+pub use portable_atomic_util::Arc as Shared;
+/// A non-owning pointer paired with [`Shared`].
+#[cfg(feature = "portable-atomic")]
+pub use portable_atomic_util::Weak as WeakShared;
+
// Memory defaults
const MEM_PAGE_SIZE: u64 = 65536;
-const MAX_MEMORY_SIZE: u64 = 4294967296;
-
-const fn max_page_count(page_size: u64) -> u64 {
- MAX_MEMORY_SIZE / page_size
+const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 {
+ match arch {
+ MemoryArch::I32 => (1u64 << 32) / page_size,
+ MemoryArch::I64 => u64::MAX / page_size,
+ }
}
mod instructions;
+mod operands;
mod reference;
+mod types;
mod value;
pub use instructions::*;
+pub use operands::*;
pub use reference::*;
+pub use types::*;
pub use value::*;
#[cfg(feature = "archive")]
@@ -42,19 +65,20 @@ pub mod archive {
impl core::error::Error for TwasmError {}
}
-/// A `TinyWasm` WebAssembly Module
+/// TinyWasm's parsed and lowered representation of a WebAssembly module.
///
-/// This is the internal representation of a WebAssembly module in `TinyWasm`.
/// Modules produced by the parser are validated by default, but validation can be
/// disabled for trusted input. Do not trust modules or archives from third parties.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/modules.html#syntax-module>
#[derive(Clone, Default, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct Module(Arc<ModuleInner>);
+pub struct Module(Shared<ModuleInner>);
impl From<ModuleInner> for Module {
fn from(inner: ModuleInner) -> Self {
- Self(Arc::new(inner))
+ Self(Shared::new(inner))
}
}
@@ -79,12 +103,12 @@ pub struct ModuleInner {
/// Optimized WebAssembly functions
///
/// Contains data from to the `code`, `func`, and `type` sections of the original WebAssembly module.
- pub funcs: Box<[Arc<WasmFunction>]>,
+ pub funcs: Box<[Shared<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]>,
@@ -92,7 +116,7 @@ pub struct ModuleInner {
/// Exported items of the WebAssembly module.
///
/// Corresponds to the `export` section of the original WebAssembly module.
- pub exports: Arc<[Export]>,
+ pub exports: Shared<[Export]>,
/// Global components of the WebAssembly module.
///
@@ -109,6 +133,14 @@ pub struct ModuleInner {
/// Corresponds to the `memory` section of the original WebAssembly module.
pub memory_types: Box<[MemoryType]>,
+ /// Whether instantiation should omit unexported local memories that guest code cannot access.
+ pub skip_local_memory_allocation: bool,
+
+ /// Tag components of the WebAssembly module.
+ ///
+ /// Corresponds to the `tag` section of the original WebAssembly module.
+ pub tags: Box<[TagType]>,
+
/// Imports of the WebAssembly module.
///
/// Corresponds to the `import` section of the original WebAssembly module.
@@ -123,9 +155,6 @@ pub struct ModuleInner {
///
/// Corresponds to the `elem` section of the original WebAssembly module.
pub elements: Box<[Element]>,
-
- /// How instantiation should prepare the module's local memories.
- pub local_memory_allocation: LocalMemoryAllocation,
}
impl Module {
@@ -135,10 +164,11 @@ 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)),
+ ImportKind::Tag(tag_ty) => Some(ImportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?)),
}?;
Some(ModuleImport { module: import.module.as_ref(), name: import.name.as_ref(), ty })
@@ -160,6 +190,7 @@ impl Module {
| (ExternalKind::Table, ImportKind::Table(_))
| (ExternalKind::Memory, ImportKind::Memory(_))
| (ExternalKind::Global, ImportKind::Global(_))
+ | (ExternalKind::Tag, ImportKind::Tag(_))
)
})
.count()
@@ -173,15 +204,17 @@ impl Module {
| (ExternalKind::Table, ImportKind::Table(_))
| (ExternalKind::Memory, ImportKind::Memory(_))
| (ExternalKind::Global, ImportKind::Global(_))
+ | (ExternalKind::Tag, ImportKind::Tag(_))
)
});
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)),
+ ImportKind::Tag(tag_ty) => Some(ExportType::Tag(module.types.get(tag_ty.type_idx)?.as_func()?)),
}
}
@@ -194,7 +227,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 => {
@@ -221,6 +254,15 @@ impl Module {
ExportType::Global(&self.0.globals.get(idx - imported_globals)?.ty)
}
}
+ ExternalKind::Tag => {
+ let imported_tags = imported_count(&self.0, ExternalKind::Tag);
+ if idx < imported_tags {
+ imported_type(&self.0, ExternalKind::Tag, idx)?
+ } else {
+ let tag_ty = self.0.tags.get(idx - imported_tags)?;
+ ExportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?)
+ }
+ }
};
Some(ModuleExport { name: export.name.as_ref(), ty })
@@ -256,6 +298,8 @@ pub enum ImportType<'a> {
Memory(&'a MemoryType),
/// Imported global type.
Global(&'a GlobalType),
+ /// Imported tag type.
+ Tag(&'a FuncType),
}
/// Exported entity type.
@@ -268,20 +312,8 @@ pub enum ExportType<'a> {
Memory(&'a MemoryType),
/// Exported global type.
Global(&'a GlobalType),
-}
-
-/// How instantiation should prepare local memories declared by the module.
-#[derive(Clone, Copy, PartialEq, Eq, Default)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub enum LocalMemoryAllocation {
- /// The module's local memories are unobservable and can be skipped entirely.
- #[default]
- Skip,
- /// The module's local memories may be observed through exports, but can be delayed until first use.
- Lazy,
- /// The module's local memories must be allocated during instantiation.
- Eager,
+ /// Exported tag type.
+ Tag(&'a FuncType),
}
/// A WebAssembly External Kind.
@@ -299,6 +331,8 @@ pub enum ExternalKind {
Memory,
/// A WebAssembly Global.
Global,
+ /// A WebAssembly Tag.
+ Tag,
}
/// A WebAssembly Address.
@@ -313,12 +347,36 @@ pub type FuncAddr = Addr;
pub type TableAddr = Addr;
pub type MemAddr = Addr;
pub type GlobalAddr = Addr;
+pub type TagAddr = Addr;
pub type ElemAddr = Addr;
pub type DataAddr = Addr;
pub type ExternAddr = Addr;
pub type ConstIdx = Addr;
// additional internal addresses
+/// A function index in a WebAssembly module's function index space.
+///
+/// This remains module-local until instantiation resolves it to a [`FuncAddr`].
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "archive", serde(transparent))]
+pub struct ModuleFuncIdx(u32);
+
+impl ModuleFuncIdx {
+ /// Creates a module-local function index.
+ #[inline]
+ pub const fn new(index: u32) -> Self {
+ Self(index)
+ }
+
+ /// Returns the module-local function index.
+ #[inline]
+ pub const fn index(self) -> u32 {
+ self.0
+ }
+}
+
/// An address in the current type space.
///
/// Parsed modules use module-local addresses; instantiated types use their store's canonical addresses.
@@ -336,6 +394,7 @@ pub enum ExternVal {
Table(TableAddr),
Memory(MemAddr),
Global(GlobalAddr),
+ Tag(TagAddr),
}
impl ExternVal {
@@ -346,6 +405,7 @@ impl ExternVal {
Self::Table(_) => ExternalKind::Table,
Self::Memory(_) => ExternalKind::Memory,
Self::Global(_) => ExternalKind::Global,
+ Self::Tag(_) => ExternalKind::Tag,
}
}
@@ -356,91 +416,41 @@ impl ExternVal {
ExternalKind::Table => Self::Table(addr),
ExternalKind::Memory => Self::Memory(addr),
ExternalKind::Global => Self::Global(addr),
+ ExternalKind::Tag => Self::Tag(addr),
}
}
}
-/// The type of a WebAssembly Function.
-///
-/// See <https://webassembly.github.io/spec/core/syntax/types.html#function-types>
-#[derive(Clone, PartialEq, Eq, Default)]
+/// The physical storage lane used by a [`WasmType`].
+#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct FuncType {
- data: Box<[WasmType]>,
- param_count: u16,
+pub enum ValueLane {
+ /// A 32-bit value or reference.
+ S32,
+ /// A 64-bit value.
+ S64,
+ /// A 128-bit SIMD value.
+ S128,
}
-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,
- },
- )
+impl ValueLane {
+ /// Selects one of three values based on this lane.
+ pub fn select<T>(self, s32: T, s64: T, s128: T) -> T {
+ match self {
+ Self::S32 => s32,
+ Self::S64 => s64,
+ Self::S128 => s128,
}
+ }
+}
- if core::ptr::eq(types, other_types) && self == other {
- return true;
+impl From<&WasmType> for ValueLane {
+ fn from(ty: &WasmType) -> Self {
+ match ty {
+ WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32,
+ WasmType::I64 | WasmType::F64 => Self::S64,
+ WasmType::V128 => Self::S128,
}
- funcs_equal(self, types, other, other_types, &mut alloc::vec::Vec::new())
}
}
@@ -466,10 +476,10 @@ impl<'a> FromIterator<&'a WasmType> for ValueCounts {
let mut counts = Self::default();
for ty in iter {
- match ty {
- WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => counts.c32 += 1,
- WasmType::I64 | WasmType::F64 => counts.c64 += 1,
- WasmType::V128 => counts.c128 += 1,
+ match ValueLane::from(ty) {
+ ValueLane::S32 => counts.c32 += 1,
+ ValueLane::S64 => counts.c64 += 1,
+ ValueLane::S128 => counts.c128 += 1,
}
}
counts
@@ -491,16 +501,10 @@ pub struct WasmFunction {
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct WasmFunctionData {
- pub v128_constants: Box<[[u8; 16]]>,
+ pub operands64: Box<[Operand64]>,
+ pub operands128: Box<[Operand128]>,
pub branch_table_targets: Box<[u32]>,
-}
-
-impl WasmFunctionData {
- /// Panics if `idx` is out of bounds.
- #[inline(always)]
- pub fn v128_const(&self, idx: ConstIdx) -> [u8; 16] {
- *self.v128_constants.get(idx as usize).unwrap_or_else(|| unreachable!("invalid v128 constant index: {idx}"))
- }
+ pub exception_handlers: Box<[ExceptionHandler]>,
}
/// A WebAssembly Module Export
@@ -524,6 +528,9 @@ pub struct Global {
pub init: Box<[ConstInstruction]>,
}
+/// A WebAssembly global type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-globaltype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -557,6 +564,9 @@ impl Default for GlobalType {
}
}
+/// A WebAssembly table type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-tabletype>
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -596,7 +606,9 @@ impl TableType {
}
}
-/// Represents a memory's type.
+/// A WebAssembly memory type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-memtype>
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -630,22 +642,22 @@ impl MemoryType {
#[inline]
pub const fn page_count_max(&self) -> u64 {
- if let Some(page_count_max) = self.page_count_max { page_count_max } else { max_page_count(self.page_size()) }
- }
-
- #[inline]
- pub const fn page_size(&self) -> u64 {
- if let Some(page_size) = self.page_size { page_size } else { MEM_PAGE_SIZE }
+ if let Some(page_count_max) = self.page_count_max {
+ page_count_max
+ } else {
+ max_page_count(self.arch, self.page_size())
+ }
}
+ /// Returns the declared maximum page count, or `None` if no maximum was declared.
#[inline]
- pub const fn initial_size(&self) -> u64 {
- self.page_count_initial * self.page_size()
+ pub const fn page_count_max_declared(&self) -> Option<u64> {
+ self.page_count_max
}
#[inline]
- pub const fn max_size(&self) -> u64 {
- self.page_count_max() * self.page_size()
+ pub const fn page_size(&self) -> u64 {
+ if let Some(page_size) = self.page_size { page_size } else { MEM_PAGE_SIZE }
}
/// Set a different memory architecture.
@@ -687,6 +699,24 @@ pub enum MemoryArch {
I64,
}
+/// A WebAssembly tag type.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-tagtype>
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "debug", derive(Debug))]
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+pub struct TagType {
+ /// The module-local function type index used by this tag.
+ pub type_idx: TypeAddr,
+}
+
+impl TagType {
+ /// Creates a tag type from a module-local function type index.
+ pub const fn new(type_idx: TypeAddr) -> Self {
+ Self { type_idx }
+ }
+}
+
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
@@ -704,6 +734,7 @@ pub enum ImportKind {
Table(TableType),
Memory(MemoryType),
Global(GlobalType),
+ Tag(TagType),
}
impl From<&ImportKind> for ExternalKind {
@@ -713,6 +744,7 @@ impl From<&ImportKind> for ExternalKind {
ImportKind::Table(_) => Self::Table,
ImportKind::Memory(_) => Self::Memory,
ImportKind::Global(_) => Self::Global,
+ ImportKind::Tag(_) => Self::Tag,
}
}
}
@@ -721,8 +753,8 @@ impl From<&ImportKind> for ExternalKind {
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct Data {
- pub data: Box<[u8]>,
- pub range: Range<usize>,
+ pub data: Shared<[u8]>,
+ pub range: Range<u64>,
pub kind: DataKind,
}
@@ -740,7 +772,7 @@ pub enum DataKind {
pub struct Element {
pub kind: ElementKind,
pub items: Box<[ElementItem]>,
- pub range: Range<usize>,
+ pub range: Range<u64>,
pub ty: RefType,
}
diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs
new file mode 100644
index 0000000..af1b17f
--- /dev/null
+++ b/crates/types/src/operands.rs
@@ -0,0 +1,342 @@
+use core::marker::PhantomData;
+
+/// An index into the operand lane used by `T`.
+#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "archive", serde(transparent))]
+#[repr(transparent)]
+pub struct OperandIdx<T, const WIDTH: usize> {
+ index: u32,
+ #[cfg_attr(feature = "archive", serde(skip))]
+ marker: PhantomData<T>,
+}
+
+/// An index into the 64-bit operand lane.
+pub type Operand64Idx<T> = OperandIdx<T, 8>;
+
+/// An index into the 128-bit operand lane.
+pub type Operand128Idx<T> = OperandIdx<T, 16>;
+
+impl<T, const WIDTH: usize> OperandIdx<T, WIDTH> {
+ #[inline]
+ #[doc(hidden)]
+ pub const fn new(index: u32) -> Self {
+ Self { index, marker: PhantomData }
+ }
+
+ /// Returns the underlying lane index.
+ #[inline]
+ pub const fn index(self) -> usize {
+ self.index as usize
+ }
+}
+
+impl<T, const WIDTH: usize> Copy for OperandIdx<T, WIDTH> {}
+impl<T, const WIDTH: usize> Clone for OperandIdx<T, WIDTH> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+impl<T, const WIDTH: usize> PartialEq for OperandIdx<T, WIDTH> {
+ fn eq(&self, other: &Self) -> bool {
+ self.index == other.index
+ }
+}
+impl<T, const WIDTH: usize> Eq for OperandIdx<T, WIDTH> {}
+
+#[cfg(feature = "debug")]
+impl<T, const WIDTH: usize> core::fmt::Debug for OperandIdx<T, WIDTH> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ self.index.fmt(formatter)
+ }
+}
+
+macro_rules! define_operand {
+ ($name:ident, $len:literal) => {
+ #[doc = concat!("A typed packed ", $len, "-byte operand value.")]
+ #[repr(C)]
+ pub struct $name<T = ()> {
+ pub(crate) bytes: [u8; $len],
+ marker: PhantomData<T>,
+ }
+
+ #[allow(dead_code)]
+ impl<T> $name<T> {
+ #[inline]
+ pub(crate) fn write_u8<const OFFSET: usize>(&mut self, value: u8) {
+ const { assert!(OFFSET < $len) };
+ self.bytes[OFFSET] = value;
+ }
+
+ #[inline]
+ pub(crate) fn write_u16<const OFFSET: usize>(&mut self, value: u16) {
+ const { assert!(OFFSET + 2 <= $len) };
+ self.bytes[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes());
+ }
+
+ #[inline]
+ pub(crate) fn write_u32<const OFFSET: usize>(&mut self, value: u32) {
+ const { assert!(OFFSET + 4 <= $len) };
+ self.bytes[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes());
+ }
+
+ #[inline]
+ pub(crate) fn write_u64<const OFFSET: usize>(&mut self, value: u64) {
+ const { assert!(OFFSET + 8 <= $len) };
+ self.bytes[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes());
+ }
+
+ #[inline(always)]
+ #[doc(hidden)]
+ pub fn cast<U>(self) -> $name<U> {
+ $name { bytes: self.bytes, marker: PhantomData }
+ }
+ }
+
+ impl<T> Copy for $name<T> {}
+ impl<T> Clone for $name<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+ }
+ impl<T> PartialEq for $name<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.bytes == other.bytes
+ }
+ }
+ impl<T> Eq for $name<T> {}
+ impl<T> PartialOrd for $name<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+ }
+ impl<T> Ord for $name<T> {
+ fn cmp(&self, other: &Self) -> core::cmp::Ordering {
+ self.bytes.cmp(&other.bytes)
+ }
+ }
+ impl<T> Default for $name<T> {
+ fn default() -> Self {
+ Self { bytes: [0; $len], marker: PhantomData }
+ }
+ }
+
+ #[cfg(feature = "debug")]
+ impl<T> core::fmt::Debug for $name<T> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ self.bytes.fmt(formatter)
+ }
+ }
+
+ #[cfg(feature = "archive")]
+ impl<T> serde::Serialize for $name<T> {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ self.bytes.serialize(serializer)
+ }
+ }
+
+ #[cfg(feature = "archive")]
+ impl<'de, T> serde::Deserialize<'de> for $name<T> {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData })
+ }
+ }
+ };
+}
+
+define_operand!(Operand64, 8);
+define_operand!(Operand128, 16);
+
+impl<T> Operand64Idx<T> {
+ /// Resolves this index to a copied 64-bit packed operand.
+ #[inline(always)]
+ pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64<T> {
+ data.operands64[self.index as usize].cast()
+ }
+}
+
+impl<T> Operand128Idx<T> {
+ /// Resolves this index to a copied 128-bit packed operand.
+ #[inline(always)]
+ pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128<T> {
+ data.operands128[self.index as usize].cast()
+ }
+}
+
+macro_rules! field_ty {
+ (u8) => { u8 }; (u16) => { u16 }; (u32) => { u32 }; (u64) => { u64 };
+ (i32) => { i32 }; (i64) => { i64 }; (idx128) => { Operand128Idx<[u8; 16]> };
+}
+macro_rules! field_size {
+ (u8) => {{ 1 }};
+ (u16) => {{ 2 }};
+ (u32) => {{ 4 }};
+ (u64) => {{ 8 }};
+ (i32) => {{ 4 }};
+ (i64) => {{ 8 }};
+ (idx128) => {{ 4 }};
+}
+
+macro_rules! read_field {
+ ($self:ident, u8, $offset:expr) => {{ $self.bytes[$offset] }};
+ ($self:ident, u16, $offset:expr) => {{ u16::from_le_bytes($crate::operands::read_bytes!($self, $offset, 2)) }};
+ ($self:ident, u32, $offset:expr) => {{ u32::from_le_bytes($crate::operands::read_bytes!($self, $offset, 4)) }};
+ ($self:ident, u64, $offset:expr) => {{ u64::from_le_bytes($crate::operands::read_bytes!($self, $offset, 8)) }};
+ ($self:ident, i32, $offset:expr) => {{ read_field!($self, u32, $offset) as i32 }};
+ ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }};
+ ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }};
+}
+
+macro_rules! read_bytes {
+ ($self:ident, $offset:expr, $len:literal) => {{
+ match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) {
+ Ok(bytes) => bytes,
+ Err(_) => {
+ core::hint::cold_path();
+ unreachable!("invalid operand field read")
+ }
+ }
+ }};
+}
+
+macro_rules! write_field {
+ ($self:ident, u8, $offset:expr, $value:expr) => {{ $self.write_u8::<{ $offset }>($value) }};
+ ($self:ident, u16, $offset:expr, $value:expr) => {{ $self.write_u16::<{ $offset }>($value) }};
+ ($self:ident, u32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value) }};
+ ($self:ident, u64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value) }};
+ ($self:ident, i32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value as u32) }};
+ ($self:ident, i64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value as u64) }};
+ ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }};
+}
+
+pub(crate) use {read_bytes, read_field, write_field};
+
+impl<T> Operand64<T> {
+ /// Returns the jump target stored at the start of a retargetable operand.
+ #[inline(always)]
+ pub fn target(&self) -> u32 {
+ read_field!(self, u32, 0)
+ }
+
+ /// Replaces the jump target stored at the start of a retargetable operand.
+ #[inline]
+ pub fn with_target(mut self, target: u32) -> Self {
+ write_field!(self, u32, 0, target);
+ self
+ }
+}
+
+impl<T> Operand128<T> {
+ /// Returns the jump target stored at the start of a retargetable operand.
+ #[inline(always)]
+ pub fn target(&self) -> u32 {
+ read_field!(self, u32, 0)
+ }
+
+ /// Replaces the jump target stored at the start of a retargetable operand.
+ #[inline]
+ pub fn with_target(mut self, target: u32) -> Self {
+ write_field!(self, u32, 0, target);
+ self
+ }
+}
+
+macro_rules! packed_layout {
+ ($operand:ident, $lane:ident, $field:tt) => {
+ impl $operand<field_ty!($field)> {
+ #[inline]
+ pub fn new(value: field_ty!($field)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $field, 0, value);
+ operand
+ }
+
+ #[inline(always)]
+ pub fn value(&self) -> field_ty!($field) {
+ read_field!(self, $field, 0)
+ }
+ }
+ };
+ ($operand:ident, $lane:ident, $a:tt, $b:tt) => {
+ impl $operand<(field_ty!($a), field_ty!($b))> {
+ #[inline]
+ pub fn new(a: field_ty!($a), b: field_ty!($b)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $a, 0, a);
+ write_field!(operand, $b, field_size!($a), b);
+ operand
+ }
+
+ #[inline(always)]
+ pub fn a(&self) -> field_ty!($a) {
+ read_field!(self, $a, 0)
+ }
+
+ #[inline(always)]
+ pub fn b(&self) -> field_ty!($b) {
+ read_field!(self, $b, field_size!($a))
+ }
+ }
+ };
+ ($operand:ident, $lane:ident, $a:tt, $b:tt, $c:tt) => {
+ impl $operand<(field_ty!($a), field_ty!($b), field_ty!($c))> {
+ #[inline]
+ pub fn new(a: field_ty!($a), b: field_ty!($b), c: field_ty!($c)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $a, 0, a);
+ write_field!(operand, $b, field_size!($a), b);
+ write_field!(operand, $c, field_size!($a) + field_size!($b), c);
+ operand
+ }
+
+ #[inline(always)]
+ pub fn a(&self) -> field_ty!($a) {
+ read_field!(self, $a, 0)
+ }
+
+ #[inline(always)]
+ pub fn b(&self) -> field_ty!($b) {
+ read_field!(self, $b, field_size!($a))
+ }
+
+ #[inline(always)]
+ pub fn c(&self) -> field_ty!($c) {
+ read_field!(self, $c, field_size!($a) + field_size!($b))
+ }
+ }
+ };
+}
+
+packed_layout!(Operand64, operands64, i64);
+packed_layout!(Operand64, operands64, u32, u32);
+packed_layout!(Operand64, operands64, u16, u32);
+packed_layout!(Operand64, operands64, u32, u16);
+packed_layout!(Operand64, operands64, u16, u16, u16);
+packed_layout!(Operand64, operands64, u16, u16, u32);
+packed_layout!(Operand64, operands64, u32, i32);
+packed_layout!(Operand64, operands64, u32, u16, u16);
+packed_layout!(Operand64, operands64, u16, idx128);
+packed_layout!(Operand64, operands64, u32, idx128);
+packed_layout!(Operand64, operands64, u16, u16, idx128);
+packed_layout!(Operand128, operands128, u16, u64);
+packed_layout!(Operand128, operands128, u32, u64);
+packed_layout!(Operand128, operands128, u16, u16, u64);
+packed_layout!(Operand128, operands128, u32, i64);
+packed_layout!(Operand128, operands128, u32, i32, u16);
+
+impl Operand128<[u8; 16]> {
+ #[inline]
+ pub fn new(value: [u8; 16]) -> Self {
+ Self { bytes: value, marker: PhantomData }
+ }
+
+ #[inline(always)]
+ pub fn value(&self) -> [u8; 16] {
+ self.bytes
+ }
+}
+
+const _: () = {
+ assert!(core::mem::size_of::<Operand64Idx<i64>>() == 4);
+ assert!(core::mem::size_of::<Operand64>() == 8);
+ assert!(core::mem::size_of::<Operand128>() == 16);
+};
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
index ee66965..d195a81 100644
--- a/crates/types/src/reference.rs
+++ b/crates/types/src/reference.rs
@@ -1,6 +1,8 @@
/// An abstract WebAssembly heap type.
///
/// This contains exactly the abstract heap types in core Wasm 3.0.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-absheaptype>
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "debug", derive(Debug))]
@@ -31,8 +33,11 @@ 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`].
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype>
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct RefType(u32);
@@ -58,17 +63,27 @@ impl RefType {
pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn);
#[inline]
+ #[doc(hidden)]
+ pub const fn to_bits(self) -> u32 {
+ self.0
+ }
+
+ #[inline]
+ #[doc(hidden)]
+ pub const fn from_bits(bits: u32) -> Option<Self> {
+ let ty = Self(bits);
+ if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None }
+ }
+
+ #[inline]
pub const fn new_abstract(nullable: bool, heap_type: AbstractHeapType) -> Self {
Self((nullable as u32) << 31 | heap_type as u32)
}
#[inline]
- pub const fn new_concrete(nullable: bool, type_index: u32) -> Option<Self> {
- if type_index <= Self::PAYLOAD_MASK {
- Some(Self(((nullable as u32) << 31) | Self::CONCRETE | type_index))
- } else {
- None
- }
+ pub const fn new_concrete(nullable: bool, type_index: u32) -> Self {
+ assert!(type_index <= Self::PAYLOAD_MASK, "type index is too large for a reference type");
+ Self(((nullable as u32) << 31) | Self::CONCRETE | type_index)
}
#[inline]
@@ -116,9 +131,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]
@@ -131,125 +144,3 @@ impl RefType {
matches!(self.abstract_heap_type(), Some(AbstractHeapType::Exn | AbstractHeapType::NoExn))
}
}
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub enum RefValue {
- Null,
- Func(FuncRef),
- Extern(ExternRef),
- Any(AnyRef),
- 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()),
- }
- }
-}
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct FuncRef(u32);
-
-impl FuncRef {
- #[inline]
- pub const fn new(addr: u32) -> Self {
- Self(addr)
- }
-
- #[inline]
- pub const fn addr(self) -> u32 {
- self.0
- }
-}
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct ExternRef(u32);
-
-impl ExternRef {
- #[inline]
- pub const fn new(addr: u32) -> Self {
- Self(addr)
- }
-
- #[inline]
- pub const fn addr(self) -> u32 {
- self.0
- }
-}
-
-#[derive(Clone, Copy, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct ExnRef(u32);
-
-impl ExnRef {
- #[inline]
- pub const fn new(addr: u32) -> Self {
- Self(addr)
- }
-
- #[inline]
- pub const fn addr(self) -> u32 {
- self.0
- }
-}
-
-#[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.
-
- #[doc(hidden)]
- #[inline]
- pub const fn from_raw(raw: u32) -> Self {
- Self(raw)
- }
-
- pub const fn from_i31(value: i32) -> Option<Self> {
- if value < -(1 << 30) || value >= (1 << 30) {
- return None;
- }
-
- Some(Self(((value as u32) << 1) | 1))
- }
-
- pub const fn as_i31(self) -> Option<i32> {
- 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
- }
-}
diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs
new file mode 100644
index 0000000..273c762
--- /dev/null
+++ b/crates/types/src/types.rs
@@ -0,0 +1,182 @@
+use alloc::boxed::Box;
+
+use crate::{Shared, TypeAddr, WasmType};
+
+/// The dense type index space of a WebAssembly module.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-rectype>
+#[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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-subtype>
+#[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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-comptype>
+#[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: Shared<[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: data.into(), 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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-structtype>
+#[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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-arraytype>
+#[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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-fieldtype>
+#[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.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-storagetype>
+#[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),
+}
+
+impl StorageType {
+ /// Returns the unpacked WebAssembly value type used on the stack.
+ pub const fn unpacked(self) -> WasmType {
+ match self {
+ Self::I8 | Self::I16 => WasmType::I32,
+ Self::Value(ty) => ty,
+ }
+ }
+}
diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs
index 8a6fb61..3a396a2 100644
--- a/crates/types/src/value.rs
+++ b/crates/types/src/value.rs
@@ -1,317 +1,31 @@
-use core::fmt::Debug;
-
-use crate::{ConstInstruction, RefType, RefValue};
-
-/// A WebAssembly value.
-///
-/// See <https://webassembly.github.io/spec/core/syntax/types.html#value-types>
-#[derive(Clone, Copy, PartialEq)]
-pub enum WasmValue {
- // Num types
- /// A 32-bit integer
- I32(i32),
- /// A 64-bit integer
- I64(i64),
- /// A 32-bit float
- F32(f32),
- /// A 64-bit float
- F64(f64),
- /// A 128-bit vector
- V128([u8; 16]),
- /// A reference type
- Ref(RefValue),
-}
-
-impl WasmValue {
- /// Return this value's broad WebAssembly type.
- ///
- /// A null reference has no intrinsic heap type and returns `None`.
- pub const fn ty(self) -> Option<WasmType> {
- match self {
- Self::I32(_) => Some(WasmType::I32),
- Self::I64(_) => Some(WasmType::I64),
- Self::F32(_) => Some(WasmType::F32),
- Self::F64(_) => Some(WasmType::F64),
- Self::V128(_) => Some(WasmType::V128),
- Self::Ref(RefValue::Null) => None,
- Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)),
- Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)),
- Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)),
- Self::Ref(RefValue::Any(_)) => {
- Some(WasmType::Ref(RefType::new_abstract(true, crate::AbstractHeapType::Any)))
- }
- }
- }
-
- #[inline]
- pub const fn matches_type(self, ty: WasmType) -> bool {
- // Concrete references require a store lookup; this method only classifies their broad heap type.
- match (self, ty) {
- (Self::I32(_), WasmType::I32)
- | (Self::I64(_), WasmType::I64)
- | (Self::F32(_), WasmType::F32)
- | (Self::F64(_), WasmType::F64)
- | (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))
- }
- (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => {
- matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern))
- }
- (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(),
- _ => false,
- }
- }
-}
-
-impl Debug for WasmValue {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- match self {
- Self::I32(i) => write!(f, "i32({i})"),
- Self::I64(i) => write!(f, "i64({i})"),
- Self::F32(i) => write!(f, "f32({i})"),
- Self::F64(i) => write!(f, "f64({i})"),
- Self::V128(i) => write!(f, "v128({i:?})"),
- #[cfg(feature = "debug")]
- Self::Ref(i) => write!(f, "ref({i:?})"),
- #[cfg(not(feature = "debug"))]
- Self::Ref(_) => write!(f, "ref(...)"),
- }
- }
-}
-
-impl WasmValue {
- #[inline]
- /// Get the matching [`ConstInstruction`] for this value.
- pub fn const_instr(&self) -> alloc::boxed::Box<[ConstInstruction]> {
- alloc::boxed::Box::new([match self {
- Self::I32(i) => ConstInstruction::I32Const(*i),
- Self::I64(i) => ConstInstruction::I64Const(*i),
- Self::F32(i) => ConstInstruction::F32Const(*i),
- Self::F64(i) => ConstInstruction::F64Const(*i),
- Self::V128(i) => ConstInstruction::V128Const(*i),
- Self::Ref(i) => ConstInstruction::Ref(*i),
- }])
- }
-
- #[inline]
- /// Get the default value for a given type.
- pub const fn default_for(ty: WasmType) -> Option<Self> {
- match ty {
- WasmType::I32 => Some(Self::I32(0)),
- WasmType::I64 => Some(Self::I64(0)),
- WasmType::F32 => Some(Self::F32(0.0)),
- WasmType::F64 => Some(Self::F64(0.0)),
- WasmType::V128 => Some(Self::V128([0; 16])),
- WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)),
- WasmType::Ref(_) => None,
- }
- }
-
- #[inline]
- /// Check if two values are equal, ignoring differences in NaN values.
- pub fn eq_loose(&self, other: &Self) -> bool {
- match (self, other) {
- (Self::I32(a), Self::I32(b)) => a == b,
- (Self::I64(a), Self::I64(b)) => a == b,
- (Self::V128(a), Self::V128(b)) => a == b || Self::v128_nan_eq(*a, *b),
- (Self::Ref(a), Self::Ref(b)) => a == b,
- (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(),
- (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(),
- _ => false,
- }
- }
-
- fn v128_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool {
- let a_f32x4: [f32; 4] = [
- f32::from_le_bytes([a[0], a[1], a[2], a[3]]),
- f32::from_le_bytes([a[4], a[5], a[6], a[7]]),
- f32::from_le_bytes([a[8], a[9], a[10], a[11]]),
- f32::from_le_bytes([a[12], a[13], a[14], a[15]]),
- ];
- let b_f32x4: [f32; 4] = [
- f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
- f32::from_le_bytes([b[4], b[5], b[6], b[7]]),
- f32::from_le_bytes([b[8], b[9], b[10], b[11]]),
- f32::from_le_bytes([b[12], b[13], b[14], b[15]]),
- ];
-
- let all_nan_match = a_f32x4.iter().zip(b_f32x4.iter()).all(|(x, y)| {
- if x.is_nan() && y.is_nan() {
- true
- } else if x.is_nan() || y.is_nan() {
- false
- } else {
- x.to_bits() == y.to_bits()
- }
- });
-
- if all_nan_match && a_f32x4.iter().any(|x| x.is_nan()) {
- return true;
- }
-
- let a_f64x2: [f64; 2] = [
- f64::from_le_bytes([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]),
- f64::from_le_bytes([a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]),
- ];
- let b_f64x2: [f64; 2] = [
- f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]),
- f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]),
- ];
-
- a_f64x2.iter().zip(b_f64x2.iter()).all(|(x, y)| {
- if x.is_nan() && y.is_nan() {
- true
- } else if x.is_nan() || y.is_nan() {
- false
- } else {
- x.to_bits() == y.to_bits()
- }
- }) && a_f64x2.iter().any(|x| x.is_nan())
- }
-}
+use crate::{RefType, StorageType};
/// Type of a WebAssembly value.
+///
+/// See <https://webassembly.github.io/spec/core/syntax/types.html#syntax-valtype>
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub enum WasmType {
- /// A 32-bit integer
+ /// A 32-bit integer.
I32,
- /// A 64-bit integer
+ /// A 64-bit integer.
I64,
- /// A 32-bit float
+ /// A 32-bit float.
F32,
- /// A 64-bit float
+ /// A 64-bit float.
F64,
- /// A 128-bit vector
+ /// A 128-bit vector.
V128,
- /// A reference type
+ /// A reference type.
Ref(RefType),
}
-impl WasmType {
- #[inline]
- pub const fn default_value(&self) -> Option<WasmValue> {
- WasmValue::default_for(*self)
- }
-
- #[inline]
- pub const fn is_simd(&self) -> bool {
- matches!(self, Self::V128)
- }
-}
-
-macro_rules! impl_conversion_for_wasmvalue {
- ($($t:ty => $variant:ident, $accessor:ident, $doc:literal);* $(;)?) => {
- impl WasmValue {
- $(
- #[doc = $doc]
- pub const fn $accessor(&self) -> Option<$t> {
- match self {
- Self::$variant(value) => Some(*value),
- _ => None,
- }
- }
- )*
- }
-
- $(
- impl From<$t> for WasmValue {
- #[inline]
- fn from(i: $t) -> Self {
- Self::$variant(i)
- }
- }
-
- impl TryFrom<WasmValue> for $t {
- type Error = ();
-
- #[inline]
- fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
- if let WasmValue::$variant(i) = value { Ok(i) } else { Err(()) }
- }
- }
- )*
- }
-}
-
-impl_conversion_for_wasmvalue! {
- i32 => I32, as_i32, "Return the `i32` from a `WasmValue`, if it is an `I32`.";
- i64 => I64, as_i64, "Return the `i64` from a `WasmValue`, if it is an `I64`.";
- f32 => F32, as_f32, "Return the `f32` from a `WasmValue`, if it is a `F32`.";
- f64 => F64, as_f64, "Return the `f64` from a `WasmValue`, if it is a `F64`.";
- [u8; 16] => V128, as_v128, "Return the raw little-endian bytes from a `WasmValue`, if it is a `V128`.";
- RefValue => Ref, as_ref, "Return the `RefValue` from a `WasmValue`, if it is a `Ref`.";
-}
-
-macro_rules! impl_ref_conversion_for_wasmvalue {
- ($($ty:ty => $variant:ident);* $(;)?) => {
- $(
- impl From<$ty> for WasmValue {
- fn from(value: $ty) -> Self {
- Self::Ref(RefValue::$variant(value))
- }
- }
-
- impl TryFrom<WasmValue> for $ty {
- type Error = ();
-
- fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
- if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) }
- }
- }
- )*
- };
-}
-
-impl_ref_conversion_for_wasmvalue! {
- crate::FuncRef => Func;
- crate::ExternRef => Extern;
- crate::AnyRef => Any;
- crate::ExnRef => Exn;
-}
-
-impl From<u32> for WasmValue {
- #[inline]
- fn from(i: u32) -> Self {
- Self::I32(i as i32)
- }
-}
-
-impl TryFrom<WasmValue> for u32 {
- type Error = ();
-
- #[inline]
- fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
- if let WasmValue::I32(i) = value {
- Ok(i as u32)
- } else {
- Err(())
- }
- }
-}
-
-impl From<u64> for WasmValue {
- #[inline]
- fn from(i: u64) -> Self {
- Self::I64(i as i64)
- }
-}
-
-impl TryFrom<WasmValue> for u64 {
- type Error = ();
-
- #[inline]
- fn try_from(value: WasmValue) -> Result<Self, Self::Error> {
- if let WasmValue::I64(i) = value {
- Ok(i as u64)
- } else {
- Err(())
+impl From<StorageType> for WasmType {
+ fn from(value: StorageType) -> Self {
+ match value {
+ StorageType::I8 | StorageType::I16 => Self::I32,
+ StorageType::Value(value) => value,
}
}
}
diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml
new file mode 100644
index 0000000..e93f087
--- /dev/null
+++ b/crates/wasi/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "tinywasm-wasi"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+description = "WASI support for TinyWasm"
+homepage.workspace = true
+repository.workspace = true
+license.workspace = true
+keywords = ["tinywasm", "wasi", "wasm", "webassembly"]
+categories = ["wasm"]
+
+[dependencies]
+cap-fs-ext = "4.0.3"
+cap-std = "4.0.3"
+getrandom = "0.4.3"
+rustix = { version = "1.1.5", features = ["event", "fs", "net"] }
+tinywasm = { workspace = true, default-features = false, features = ["state"] }
+
+[dev-dependencies]
+tinywasm = { workspace = true, features = ["parser", "state"] }
+wat.workspace = true
+
+[lints]
+workspace = true
diff --git a/crates/wasi/README.md b/crates/wasi/README.md
new file mode 100644
index 0000000..d67adaf
--- /dev/null
+++ b/crates/wasi/README.md
@@ -0,0 +1,10 @@
+# tinywasm-wasi
+
+Experimental WASI support for TinyWasm mainly targeting \*nix systems (Windows support is very limited).
+
+Some behavior is based on the Bytecode Alliance `wasi-common` and
+`wasmtime-wasi` implementations.
+
+## Future WASI support
+
+Preview 2 and 3 are not planned for TinyWasm, we're probably going to wait for the final WASI 1.0 release and implement that instead.
diff --git a/crates/wasi/src/lib.rs b/crates/wasi/src/lib.rs
new file mode 100644
index 0000000..ef47a4d
--- /dev/null
+++ b/crates/wasi/src/lib.rs
@@ -0,0 +1,4 @@
+//! WASI support for TinyWasm.
+
+/// WASI Preview 1
+pub mod p1;
diff --git a/crates/wasi/src/p1/abi.rs b/crates/wasi/src/p1/abi.rs
new file mode 100644
index 0000000..c331a6b
--- /dev/null
+++ b/crates/wasi/src/p1/abi.rs
@@ -0,0 +1,300 @@
+use std::ffi::OsStr;
+use std::io;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use cap_fs_ext::{MetadataExt, SystemTimeSpec};
+use cap_std::fs::Metadata;
+
+#[derive(Clone, Copy)]
+pub(super) struct Errno(u16);
+
+impl From<Errno> for i32 {
+ fn from(errno: Errno) -> Self {
+ i32::from(errno.0)
+ }
+}
+
+pub(super) const SUCCESS: Errno = Errno(0);
+pub(super) const ACCESS: Errno = Errno(2);
+pub(super) const ADDRINUSE: Errno = Errno(3);
+pub(super) const ADDRNOTAVAIL: Errno = Errno(4);
+pub(super) const AGAIN: Errno = Errno(6);
+pub(super) const BADF: Errno = Errno(8);
+pub(super) const CONNABORTED: Errno = Errno(13);
+pub(super) const CONNREFUSED: Errno = Errno(14);
+pub(super) const CONNRESET: Errno = Errno(15);
+pub(super) const EXIST: Errno = Errno(20);
+pub(super) const FAULT: Errno = Errno(21);
+pub(super) const FBIG: Errno = Errno(22);
+pub(super) const ILSEQ: Errno = Errno(25);
+pub(super) const INTR: Errno = Errno(27);
+pub(super) const INVAL: Errno = Errno(28);
+pub(super) const IO: Errno = Errno(29);
+pub(super) const ISDIR: Errno = Errno(31);
+pub(super) const LOOP: Errno = Errno(32);
+pub(super) const MFILE: Errno = Errno(33);
+pub(super) const MLINK: Errno = Errno(34);
+pub(super) const NAMETOOLONG: Errno = Errno(37);
+pub(super) const NOMEM: Errno = Errno(48);
+pub(super) const NOENT: Errno = Errno(44);
+pub(super) const NOSPC: Errno = Errno(51);
+pub(super) const NOTCONN: Errno = Errno(53);
+pub(super) const NOTDIR: Errno = Errno(54);
+pub(super) const NOTEMPTY: Errno = Errno(55);
+pub(super) const NOTSOCK: Errno = Errno(57);
+pub(super) const NOTSUP: Errno = Errno(58);
+pub(super) const OVERFLOW: Errno = Errno(61);
+pub(super) const PIPE: Errno = Errno(64);
+pub(super) const ROFS: Errno = Errno(69);
+pub(super) const SPIPE: Errno = Errno(70);
+pub(super) const TIMEDOUT: Errno = Errno(73);
+pub(super) const XDEV: Errno = Errno(75);
+pub(super) const NOTCAPABLE: Errno = Errno(76);
+
+pub(super) const FILETYPE_UNKNOWN: u8 = 0;
+pub(super) const FILETYPE_BLOCK_DEVICE: u8 = 1;
+pub(super) const FILETYPE_CHARACTER_DEVICE: u8 = 2;
+pub(super) const FILETYPE_DIRECTORY: u8 = 3;
+pub(super) const FILETYPE_REGULAR_FILE: u8 = 4;
+pub(super) const FILETYPE_SOCKET_DGRAM: u8 = 5;
+pub(super) const FILETYPE_SOCKET_STREAM: u8 = 6;
+pub(super) const FILETYPE_SYMBOLIC_LINK: u8 = 7;
+
+pub(super) const FDFLAG_APPEND: u16 = 1;
+pub(super) const FDFLAG_DSYNC: u16 = 2;
+pub(super) const FDFLAG_NONBLOCK: u16 = 4;
+pub(super) const FDFLAG_RSYNC: u16 = 8;
+pub(super) const FDFLAG_SYNC: u16 = 16;
+pub(super) const FDFLAGS_ALL: u16 = 31;
+
+pub(super) const OFLAG_CREAT: u16 = 1;
+pub(super) const OFLAG_DIRECTORY: u16 = 2;
+pub(super) const OFLAG_EXCL: u16 = 4;
+pub(super) const OFLAG_TRUNC: u16 = 8;
+pub(super) const OFLAGS_ALL: u16 = 15;
+pub(super) const LOOKUP_SYMLINK_FOLLOW: u32 = 1;
+
+pub(super) const RIGHT_FD_DATASYNC: u64 = 1 << 0;
+pub(super) const RIGHT_FD_READ: u64 = 1 << 1;
+pub(super) const RIGHT_FD_SEEK: u64 = 1 << 2;
+pub(super) const RIGHT_FD_FDSTAT_SET_FLAGS: u64 = 1 << 3;
+pub(super) const RIGHT_FD_SYNC: u64 = 1 << 4;
+pub(super) const RIGHT_FD_TELL: u64 = 1 << 5;
+pub(super) const RIGHT_FD_WRITE: u64 = 1 << 6;
+pub(super) const RIGHT_FD_ADVISE: u64 = 1 << 7;
+pub(super) const RIGHT_FD_ALLOCATE: u64 = 1 << 8;
+pub(super) const RIGHT_PATH_CREATE_DIRECTORY: u64 = 1 << 9;
+pub(super) const RIGHT_PATH_CREATE_FILE: u64 = 1 << 10;
+pub(super) const RIGHT_PATH_LINK_SOURCE: u64 = 1 << 11;
+pub(super) const RIGHT_PATH_LINK_TARGET: u64 = 1 << 12;
+pub(super) const RIGHT_PATH_OPEN: u64 = 1 << 13;
+pub(super) const RIGHT_FD_READDIR: u64 = 1 << 14;
+pub(super) const RIGHT_PATH_READLINK: u64 = 1 << 15;
+pub(super) const RIGHT_PATH_RENAME_SOURCE: u64 = 1 << 16;
+pub(super) const RIGHT_PATH_RENAME_TARGET: u64 = 1 << 17;
+pub(super) const RIGHT_PATH_FILESTAT_GET: u64 = 1 << 18;
+pub(super) const RIGHT_PATH_FILESTAT_SET_SIZE: u64 = 1 << 19;
+pub(super) const RIGHT_PATH_FILESTAT_SET_TIMES: u64 = 1 << 20;
+pub(super) const RIGHT_FD_FILESTAT_GET: u64 = 1 << 21;
+pub(super) const RIGHT_FD_FILESTAT_SET_SIZE: u64 = 1 << 22;
+pub(super) const RIGHT_FD_FILESTAT_SET_TIMES: u64 = 1 << 23;
+pub(super) const RIGHT_PATH_SYMLINK: u64 = 1 << 24;
+pub(super) const RIGHT_PATH_REMOVE_DIRECTORY: u64 = 1 << 25;
+pub(super) const RIGHT_PATH_UNLINK_FILE: u64 = 1 << 26;
+pub(super) const RIGHT_POLL_FD_READWRITE: u64 = 1 << 27;
+pub(super) const RIGHT_SOCK_SHUTDOWN: u64 = 1 << 28;
+pub(super) const RIGHT_SOCK_ACCEPT: u64 = 1 << 29;
+pub(super) const FILE_RIGHTS: u64 = RIGHT_FD_DATASYNC
+ | RIGHT_FD_READ
+ | RIGHT_FD_SEEK
+ | RIGHT_FD_FDSTAT_SET_FLAGS
+ | RIGHT_FD_SYNC
+ | RIGHT_FD_TELL
+ | RIGHT_FD_WRITE
+ | RIGHT_FD_ADVISE
+ | RIGHT_FD_ALLOCATE
+ | RIGHT_FD_FILESTAT_GET
+ | RIGHT_FD_FILESTAT_SET_SIZE
+ | RIGHT_FD_FILESTAT_SET_TIMES
+ | RIGHT_POLL_FD_READWRITE;
+pub(super) const DIRECTORY_RIGHTS: u64 = RIGHT_PATH_CREATE_DIRECTORY
+ | RIGHT_PATH_CREATE_FILE
+ | RIGHT_PATH_LINK_SOURCE
+ | RIGHT_PATH_LINK_TARGET
+ | RIGHT_PATH_OPEN
+ | RIGHT_FD_READDIR
+ | RIGHT_PATH_READLINK
+ | RIGHT_PATH_RENAME_SOURCE
+ | RIGHT_PATH_RENAME_TARGET
+ | RIGHT_PATH_FILESTAT_GET
+ | RIGHT_PATH_FILESTAT_SET_SIZE
+ | RIGHT_PATH_FILESTAT_SET_TIMES
+ | RIGHT_FD_FILESTAT_GET
+ | RIGHT_FD_FILESTAT_SET_TIMES
+ | RIGHT_PATH_SYMLINK
+ | RIGHT_PATH_REMOVE_DIRECTORY
+ | RIGHT_PATH_UNLINK_FILE;
+
+pub(super) const FSTFLAG_ATIM: u16 = 1;
+pub(super) const FSTFLAG_ATIM_NOW: u16 = 2;
+pub(super) const FSTFLAG_MTIM: u16 = 4;
+pub(super) const FSTFLAG_MTIM_NOW: u16 = 8;
+pub(super) const FSTFLAGS_ALL: u16 = 15;
+
+pub(super) fn io_errno(error: &io::Error) -> Errno {
+ use io::ErrorKind;
+ match error.kind() {
+ ErrorKind::NotFound => NOENT,
+ ErrorKind::PermissionDenied => ACCESS,
+ ErrorKind::AddrInUse => ADDRINUSE,
+ ErrorKind::AddrNotAvailable => ADDRNOTAVAIL,
+ ErrorKind::AlreadyExists => EXIST,
+ ErrorKind::ConnectionAborted => CONNABORTED,
+ ErrorKind::ConnectionRefused => CONNREFUSED,
+ ErrorKind::ConnectionReset => CONNRESET,
+ ErrorKind::InvalidInput | ErrorKind::InvalidData => INVAL,
+ ErrorKind::WouldBlock => AGAIN,
+ ErrorKind::WriteZero | ErrorKind::UnexpectedEof => IO,
+ ErrorKind::BrokenPipe => PIPE,
+ ErrorKind::StorageFull => NOSPC,
+ ErrorKind::NotADirectory => NOTDIR,
+ ErrorKind::NotConnected => NOTCONN,
+ ErrorKind::IsADirectory => ISDIR,
+ ErrorKind::DirectoryNotEmpty => NOTEMPTY,
+ ErrorKind::FileTooLarge => FBIG,
+ ErrorKind::CrossesDevices => XDEV,
+ ErrorKind::Interrupted => INTR,
+ ErrorKind::OutOfMemory => NOMEM,
+ ErrorKind::ReadOnlyFilesystem => ROFS,
+ ErrorKind::TooManyLinks => MLINK,
+ ErrorKind::TimedOut => TIMEDOUT,
+ ErrorKind::Unsupported => NOTSUP,
+ _ => platform_io_errno(error),
+ }
+}
+
+#[cfg(any(target_os = "android", target_os = "linux"))]
+fn platform_io_errno(error: &io::Error) -> Errno {
+ match error.raw_os_error() {
+ Some(36) => NAMETOOLONG,
+ Some(40) => LOOP,
+ _ => IO,
+ }
+}
+
+#[cfg(not(any(target_os = "android", target_os = "linux")))]
+fn platform_io_errno(_error: &io::Error) -> Errno {
+ IO
+}
+
+impl From<rustix::io::Errno> for Errno {
+ fn from(error: rustix::io::Errno) -> Self {
+ use rustix::io::Errno as E;
+ match error {
+ E::INTR => INTR,
+ E::ACCESS | E::PERM => ACCESS,
+ E::BADF => BADF,
+ E::INVAL => INVAL,
+ E::MFILE => MFILE,
+ E::NOMEM => NOMEM,
+ E::NOSPC => NOSPC,
+ E::NOSYS | E::NOTSUP => NOTSUP,
+ E::XDEV => XDEV,
+ E::LOOP => LOOP,
+ _ => io_errno(&io::Error::from(error)),
+ }
+ }
+}
+
+pub(super) fn path_errno(error: &io::Error) -> Errno {
+ if error.kind() == io::ErrorKind::PermissionDenied { NOTCAPABLE } else { io_errno(error) }
+}
+
+pub(super) fn file_type(metadata: &Metadata) -> u8 {
+ use cap_fs_ext::FileTypeExt;
+
+ let ty = metadata.file_type();
+ if ty.is_dir() {
+ FILETYPE_DIRECTORY
+ } else if ty.is_file() {
+ FILETYPE_REGULAR_FILE
+ } else if ty.is_symlink() {
+ FILETYPE_SYMBOLIC_LINK
+ } else if ty.is_block_device() {
+ FILETYPE_BLOCK_DEVICE
+ } else if ty.is_char_device() {
+ FILETYPE_CHARACTER_DEVICE
+ } else if ty.is_socket() {
+ FILETYPE_SOCKET_STREAM
+ } else {
+ FILETYPE_UNKNOWN
+ }
+}
+
+fn timestamp(time: io::Result<cap_std::time::SystemTime>) -> u64 {
+ time.ok()
+ .and_then(|time| time.into_std().duration_since(UNIX_EPOCH).ok())
+ .and_then(|duration| u64::try_from(duration.as_nanos()).ok())
+ .unwrap_or(0)
+}
+
+pub(super) fn realtime_now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .ok()
+ .and_then(|duration| u64::try_from(duration.as_nanos()).ok())
+ .unwrap_or(0)
+}
+
+pub(super) fn filestat(metadata: &Metadata) -> [u8; 64] {
+ let mut bytes = [0; 64];
+ put(&mut bytes, 0, metadata.dev().to_le_bytes());
+ put(&mut bytes, 8, metadata.ino().to_le_bytes());
+ bytes[16] = file_type(metadata);
+ put(&mut bytes, 24, metadata.nlink().to_le_bytes());
+ put(&mut bytes, 32, metadata.len().to_le_bytes());
+ put(&mut bytes, 40, timestamp(metadata.accessed()).to_le_bytes());
+ put(&mut bytes, 48, timestamp(metadata.modified()).to_le_bytes());
+ put(&mut bytes, 56, status_change_timestamp(metadata).to_le_bytes());
+ bytes
+}
+
+fn status_change_timestamp(metadata: &Metadata) -> u64 {
+ #[cfg(unix)]
+ {
+ let seconds = cap_std::fs::MetadataExt::ctime(metadata);
+ let nanoseconds = cap_std::fs::MetadataExt::ctime_nsec(metadata);
+ if seconds < 0 || nanoseconds < 0 {
+ return 0;
+ }
+ (seconds as u64).saturating_mul(1_000_000_000).saturating_add(nanoseconds as u64)
+ }
+ #[cfg(not(unix))]
+ timestamp(metadata.created())
+}
+
+pub(super) fn time_spec(flags: u16, explicit: u16, now: u16, timestamp: u64) -> Option<SystemTimeSpec> {
+ if flags & now != 0 {
+ Some(SystemTimeSpec::SymbolicNow)
+ } else if flags & explicit != 0 {
+ Some(SystemTimeSpec::Absolute(cap_std::time::SystemTime::from_std(
+ UNIX_EPOCH + Duration::from_nanos(timestamp),
+ )))
+ } else {
+ None
+ }
+}
+
+pub(super) fn os_bytes(value: &OsStr) -> Vec<u8> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::ffi::OsStrExt;
+ value.as_bytes().to_vec()
+ }
+ #[cfg(not(unix))]
+ value.to_string_lossy().into_owned().into_bytes()
+}
+
+pub(super) fn put<const N: usize>(buffer: &mut [u8], offset: usize, bytes: [u8; N]) {
+ buffer[offset..offset + N].copy_from_slice(&bytes);
+}
diff --git a/crates/wasi/src/p1/ctx.rs b/crates/wasi/src/p1/ctx.rs
new file mode 100644
index 0000000..e7b8652
--- /dev/null
+++ b/crates/wasi/src/p1/ctx.rs
@@ -0,0 +1,293 @@
+use std::fmt::{Display, Formatter};
+use std::net::{TcpListener, TcpStream, UdpSocket};
+use std::path::Path;
+
+use cap_std::ambient_authority;
+use cap_std::fs::{Dir, File};
+use tinywasm::{Error, FuncContext};
+
+use super::abi::*;
+
+pub(super) const MAX_DESCRIPTORS: usize = 4096;
+const SOCKET_RIGHTS: u64 = RIGHT_FD_READ
+ | RIGHT_FD_WRITE
+ | RIGHT_FD_FDSTAT_SET_FLAGS
+ | RIGHT_FD_FILESTAT_GET
+ | RIGHT_POLL_FD_READWRITE
+ | RIGHT_SOCK_SHUTDOWN;
+
+pub(super) enum Resource {
+ Stdin,
+ Stdout,
+ Stderr,
+ File(File),
+ Directory(Dir),
+ TcpListener(TcpListener),
+ TcpStream(TcpStream),
+ UdpSocket(UdpSocket),
+}
+
+pub(super) struct Descriptor {
+ pub(super) resource: Resource,
+ pub(super) rights: u64,
+ pub(super) inheriting_rights: u64,
+ pub(super) flags: u16,
+ pub(super) preopen_path: Option<Vec<u8>>,
+}
+
+impl Descriptor {
+ pub(super) fn file_type(&self) -> u8 {
+ match &self.resource {
+ Resource::Stdin | Resource::Stdout | Resource::Stderr => FILETYPE_CHARACTER_DEVICE,
+ Resource::File(_) => FILETYPE_REGULAR_FILE,
+ Resource::Directory(_) => FILETYPE_DIRECTORY,
+ Resource::TcpListener(_) | Resource::TcpStream(_) => FILETYPE_SOCKET_STREAM,
+ Resource::UdpSocket(_) => FILETYPE_SOCKET_DGRAM,
+ }
+ }
+
+ pub(super) fn require_rights(&self, rights: u64) -> Result<(), Errno> {
+ if self.rights & rights == rights { Ok(()) } else { Err(super::abi::NOTCAPABLE) }
+ }
+}
+
+/// Configures the host resources available to a WASI Preview 1 command.
+pub struct WasiCtx {
+ pub(super) args: Vec<Vec<u8>>,
+ pub(super) env: Vec<Vec<u8>>,
+ pub(super) descriptors: Vec<Option<Descriptor>>,
+ pub(super) exit_status: Option<u32>,
+ pub(super) monotonic_start: std::time::Instant,
+}
+
+impl Default for WasiCtx {
+ fn default() -> Self {
+ Self {
+ args: Vec::new(),
+ env: Vec::new(),
+ descriptors: vec![None, None, None],
+ exit_status: None,
+ monotonic_start: std::time::Instant::now(),
+ }
+ }
+}
+
+impl WasiCtx {
+ /// Creates an empty context without access to host standard I/O or files.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Sets UTF-8 command-line arguments visible to the guest.
+ pub fn with_args(self, args: impl IntoIterator<Item = impl Into<String>>) -> Result<Self, WasiCtxError> {
+ self.with_args_bytes(args.into_iter().map(|value| value.into().into_bytes()))
+ }
+
+ /// Sets byte command-line arguments visible to the guest.
+ pub fn with_args_bytes(mut self, args: impl IntoIterator<Item = impl Into<Vec<u8>>>) -> Result<Self, WasiCtxError> {
+ self.args = args.into_iter().map(|value| validate_bytes(value.into())).collect::<Result<_, _>>()?;
+ Ok(self)
+ }
+
+ /// Sets UTF-8 environment variables visible to the guest.
+ pub fn with_env(
+ self,
+ env: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
+ ) -> Result<Self, WasiCtxError> {
+ self.with_env_bytes(env.into_iter().map(|(key, value)| (key.into().into_bytes(), value.into().into_bytes())))
+ }
+
+ /// Sets byte environment variables visible to the guest.
+ pub fn with_env_bytes(
+ mut self,
+ env: impl IntoIterator<Item = (impl Into<Vec<u8>>, impl Into<Vec<u8>>)>,
+ ) -> Result<Self, WasiCtxError> {
+ self.env = env
+ .into_iter()
+ .map(|(key, value)| {
+ let mut entry = key.into();
+ entry.push(b'=');
+ entry.extend(value.into());
+ validate_bytes(entry)
+ })
+ .collect::<Result<_, _>>()?;
+ Ok(self)
+ }
+
+ /// Allows the guest to read inherited standard input.
+ pub fn inherit_stdin(self) -> Self {
+ self.inherit_fd(0, Resource::Stdin, RIGHT_FD_READ)
+ }
+
+ /// Allows the guest to write inherited standard output.
+ pub fn inherit_stdout(self) -> Self {
+ self.inherit_fd(1, Resource::Stdout, RIGHT_FD_WRITE)
+ }
+
+ /// Allows the guest to write inherited standard error.
+ pub fn inherit_stderr(self) -> Self {
+ self.inherit_fd(2, Resource::Stderr, RIGHT_FD_WRITE)
+ }
+
+ /// Allows the guest to use inherited standard input, output, and error.
+ pub fn inherit_stdio(self) -> Self {
+ self.inherit_stdin().inherit_stdout().inherit_stderr()
+ }
+
+ /// Adds a capability directory and returns it as a guest preopen at fd 3 or above.
+ pub fn preopen_dir(
+ mut self,
+ host_path: impl AsRef<Path>,
+ guest_path: impl AsRef<[u8]>,
+ ) -> Result<Self, WasiCtxError> {
+ let guest_path = validate_bytes(guest_path.as_ref().to_vec())?;
+ if guest_path.is_empty() {
+ return Err(WasiCtxError::InvalidPreopenPath);
+ }
+ let dir = Dir::open_ambient_dir(host_path, ambient_authority()).map_err(WasiCtxError::Io)?;
+ self.insert_descriptor(Descriptor {
+ resource: Resource::Directory(dir),
+ rights: DIRECTORY_RIGHTS,
+ inheriting_rights: DIRECTORY_RIGHTS | FILE_RIGHTS,
+ flags: 0,
+ preopen_path: Some(guest_path),
+ })
+ .map_err(|_| WasiCtxError::TooManyDescriptors)?;
+ Ok(self)
+ }
+
+ /// Inserts a TCP listener capability and returns its guest file descriptor.
+ pub fn insert_tcp_listener(&mut self, listener: TcpListener) -> Result<u32, WasiCtxError> {
+ listener.set_nonblocking(false).map_err(WasiCtxError::Io)?;
+ self.insert_descriptor(Descriptor {
+ resource: Resource::TcpListener(listener),
+ rights: RIGHT_FD_READ
+ | RIGHT_FD_FDSTAT_SET_FLAGS
+ | RIGHT_FD_FILESTAT_GET
+ | RIGHT_POLL_FD_READWRITE
+ | RIGHT_SOCK_ACCEPT,
+ inheriting_rights: SOCKET_RIGHTS,
+ flags: 0,
+ preopen_path: None,
+ })
+ .map_err(|_| WasiCtxError::TooManyDescriptors)
+ }
+
+ /// Inserts a connected TCP stream capability and returns its guest file descriptor.
+ pub fn insert_tcp_stream(&mut self, stream: TcpStream) -> Result<u32, WasiCtxError> {
+ self.insert_socket(Resource::TcpStream(stream))
+ }
+
+ /// Inserts a UDP socket capability and returns its guest file descriptor.
+ ///
+ /// `sock_send` requires the supplied socket to be connected. Receiving is
+ /// supported for connected and unconnected sockets.
+ pub fn insert_udp_socket(&mut self, socket: UdpSocket) -> Result<u32, WasiCtxError> {
+ self.insert_socket(Resource::UdpSocket(socket))
+ }
+
+ /// Returns the status supplied to `proc_exit`, if it was called.
+ pub fn exit_status(&self) -> Option<u32> {
+ self.exit_status
+ }
+
+ /// Takes and clears the status supplied to `proc_exit`.
+ pub fn take_exit_status(&mut self) -> Option<u32> {
+ self.exit_status.take()
+ }
+
+ pub(super) fn descriptor(&self, fd: i32) -> Result<&Descriptor, Errno> {
+ self.descriptors.get(fd as u32 as usize).and_then(Option::as_ref).ok_or(super::abi::BADF)
+ }
+
+ pub(super) fn descriptor_mut(&mut self, fd: i32) -> Result<&mut Descriptor, Errno> {
+ self.descriptors.get_mut(fd as u32 as usize).and_then(Option::as_mut).ok_or(super::abi::BADF)
+ }
+
+ pub(super) fn insert_descriptor(&mut self, descriptor: Descriptor) -> Result<u32, Errno> {
+ if let Some((index, slot)) = self.descriptors.iter_mut().enumerate().skip(3).find(|(_, slot)| slot.is_none()) {
+ *slot = Some(descriptor);
+ Ok(index as u32)
+ } else {
+ if self.descriptors.len() >= MAX_DESCRIPTORS {
+ return Err(super::abi::MFILE);
+ }
+ let fd = self.descriptors.len() as u32;
+ self.descriptors.push(Some(descriptor));
+ Ok(fd)
+ }
+ }
+
+ fn inherit_fd(mut self, fd: usize, resource: Resource, rights: u64) -> Self {
+ self.descriptors[fd] = Some(Descriptor {
+ resource,
+ rights: rights | RIGHT_FD_FILESTAT_GET | RIGHT_POLL_FD_READWRITE,
+ inheriting_rights: 0,
+ flags: 0,
+ preopen_path: None,
+ });
+ self
+ }
+
+ fn insert_socket(&mut self, resource: Resource) -> Result<u32, WasiCtxError> {
+ match &resource {
+ Resource::TcpStream(stream) => stream.set_nonblocking(false),
+ Resource::UdpSocket(socket) => socket.set_nonblocking(false),
+ _ => unreachable!(),
+ }
+ .map_err(WasiCtxError::Io)?;
+ self.insert_descriptor(Descriptor {
+ resource,
+ rights: SOCKET_RIGHTS,
+ inheriting_rights: 0,
+ flags: 0,
+ preopen_path: None,
+ })
+ .map_err(|_| WasiCtxError::TooManyDescriptors)
+ }
+}
+
+/// An invalid WASI context configuration.
+#[derive(Debug)]
+pub enum WasiCtxError {
+ /// An argument, environment variable, or guest path contains a nul byte.
+ NulByte,
+ /// A preopen guest path is empty.
+ InvalidPreopenPath,
+ /// A host preopen directory could not be opened.
+ Io(std::io::Error),
+ /// The context has reached its descriptor limit.
+ TooManyDescriptors,
+}
+
+impl Display for WasiCtxError {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::NulByte => f.write_str("WASI strings cannot contain nul bytes"),
+ Self::InvalidPreopenPath => f.write_str("WASI preopen guest paths cannot be empty"),
+ Self::Io(error) => write!(f, "failed to configure WASI host resource: {error}"),
+ Self::TooManyDescriptors => f.write_str("WASI descriptor limit reached"),
+ }
+ }
+}
+
+impl std::error::Error for WasiCtxError {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ match self {
+ Self::Io(error) => Some(error),
+ _ => None,
+ }
+ }
+}
+
+fn validate_bytes(value: Vec<u8>) -> Result<Vec<u8>, WasiCtxError> {
+ if value.contains(&0) { Err(WasiCtxError::NulByte) } else { Ok(value) }
+}
+
+pub(super) fn state<'a>(ctx: &'a FuncContext<'_>) -> tinywasm::Result<&'a WasiCtx> {
+ ctx.state::<WasiCtx>().ok_or_else(|| Error::Other("WasiCtx is missing from the store".into()))
+}
+
+pub(super) fn state_mut<'a>(ctx: &'a mut FuncContext<'_>) -> tinywasm::Result<&'a mut WasiCtx> {
+ ctx.state_mut::<WasiCtx>().ok_or_else(|| Error::Other("WasiCtx is missing from the store".into()))
+}
diff --git a/crates/wasi/src/p1/imports/clock.rs b/crates/wasi/src/p1/imports/clock.rs
new file mode 100644
index 0000000..d8eedbf
--- /dev/null
+++ b/crates/wasi/src/p1/imports/clock.rs
@@ -0,0 +1,28 @@
+use tinywasm::FuncContext;
+
+use crate::p1::abi::{Errno, INVAL, SUCCESS, realtime_now};
+use crate::p1::ctx::state;
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+pub(super) fn clock_res_get(mut ctx: FuncContext<'_>, (clock_id, result_ptr): (i32, i32)) -> WasiResult<Errno> {
+ if !matches!(clock_id, 0 | 1) {
+ return Ok(INVAL);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &1_u64.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn clock_time_get(
+ mut ctx: FuncContext<'_>,
+ (clock_id, _precision, result_ptr): (i32, i64, i32),
+) -> WasiResult<Errno> {
+ let timestamp = match clock_id {
+ 0 => realtime_now(),
+ 1 => state(&ctx)?.monotonic_start.elapsed().as_nanos().try_into().unwrap_or(u64::MAX),
+ _ => return Ok(INVAL),
+ };
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &timestamp.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
diff --git a/crates/wasi/src/p1/imports/command.rs b/crates/wasi/src/p1/imports/command.rs
new file mode 100644
index 0000000..129bf04
--- /dev/null
+++ b/crates/wasi/src/p1/imports/command.rs
@@ -0,0 +1,72 @@
+use tinywasm::FuncContext;
+
+use crate::p1::abi::{Errno, OVERFLOW, SUCCESS};
+use crate::p1::ctx::state;
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+pub(super) fn args_sizes_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> {
+ let sizes = sizes(&state(&ctx)?.args)?;
+ sizes_get(ctx, pointers, sizes)
+}
+
+pub(super) fn environ_sizes_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> {
+ let sizes = sizes(&state(&ctx)?.env)?;
+ sizes_get(ctx, pointers, sizes)
+}
+
+fn sizes_get(
+ mut ctx: FuncContext<'_>,
+ (count_ptr, size_ptr): (i32, i32),
+ (count, size): (u32, u32),
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, count_ptr as u32 as usize, 4)?;
+ memory.check_range(&ctx, size_ptr as u32 as usize, 4)?;
+ memory.write(ctx.store_mut(), count_ptr, &count.to_le_bytes())?;
+ Ok(memory.write(ctx.store_mut(), size_ptr, &size.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+fn sizes(values: &[Vec<u8>]) -> Result<(u32, u32), Errno> {
+ Ok((values.len().try_into().map_err(|_| OVERFLOW)?, string_array_size(values).ok_or(OVERFLOW)?))
+}
+
+pub(super) fn args_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> {
+ let values = state(&ctx)?.args.clone();
+ array_get(ctx, pointers, values)
+}
+
+pub(super) fn environ_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> {
+ let values = state(&ctx)?.env.clone();
+ array_get(ctx, pointers, values)
+}
+
+fn array_get(mut ctx: FuncContext<'_>, (array_ptr, buffer_ptr): (i32, i32), values: Vec<Vec<u8>>) -> WasiResult<Errno> {
+ let Some(pointer_len) = values.len().checked_mul(4) else { return Ok(OVERFLOW) };
+ let Some(buffer_len) = string_array_size(&values).map(|value| value as usize) else { return Ok(OVERFLOW) };
+ let array_offset = array_ptr as u32 as usize;
+ let buffer_offset = buffer_ptr as u32 as usize;
+ let mut pointers = Vec::with_capacity(pointer_len);
+ let mut buffer = Vec::with_capacity(buffer_len);
+ for value in values {
+ let Some(pointer) = buffer_offset.checked_add(buffer.len()).and_then(|value| u32::try_from(value).ok()) else {
+ return Ok(OVERFLOW);
+ };
+ pointers.extend_from_slice(&pointer.to_le_bytes());
+ buffer.extend_from_slice(&value);
+ buffer.push(0);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, array_offset, pointers.len())?;
+ memory.check_range(&ctx, buffer_offset, buffer.len())?;
+ memory.write_at(ctx.store_mut(), array_offset, &pointers)?;
+ Ok(memory.write_at(ctx.store_mut(), buffer_offset, &buffer).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+fn string_array_size(values: &[Vec<u8>]) -> Option<u32> {
+ values
+ .iter()
+ .try_fold(0usize, |size, value| size.checked_add(value.len())?.checked_add(1))
+ .and_then(|size| u32::try_from(size).ok())
+}
diff --git a/crates/wasi/src/p1/imports/fd.rs b/crates/wasi/src/p1/imports/fd.rs
new file mode 100644
index 0000000..18eb122
--- /dev/null
+++ b/crates/wasi/src/p1/imports/fd.rs
@@ -0,0 +1,423 @@
+use std::io::{Read, Seek, SeekFrom, Write};
+
+use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt};
+use cap_std::fs::FileExt;
+use tinywasm::FuncContext;
+
+use crate::p1::abi::*;
+use crate::p1::ctx::{MAX_DESCRIPTORS, Resource, state, state_mut};
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+pub(super) fn fd_close(mut ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> {
+ let index = fd as u32 as usize;
+ let Some(slot) = state_mut(&mut ctx)?.descriptors.get_mut(index) else { return Ok(BADF) };
+ if slot.take().is_none() { Ok(BADF) } else { Ok(SUCCESS) }
+}
+
+pub(super) fn fd_renumber(mut ctx: FuncContext<'_>, (from, to): (i32, i32)) -> WasiResult<Errno> {
+ let from = from as u32 as usize;
+ let to = to as u32 as usize;
+ let wasi = state_mut(&mut ctx)?;
+ if from >= wasi.descriptors.len() || wasi.descriptors[from].is_none() {
+ return Ok(BADF);
+ }
+ if from == to {
+ return Ok(SUCCESS);
+ }
+ if to >= MAX_DESCRIPTORS {
+ return Ok(MFILE);
+ }
+ if to >= wasi.descriptors.len() {
+ wasi.descriptors.resize_with(to + 1, || None);
+ }
+ wasi.descriptors[to] = wasi.descriptors[from].take();
+ Ok(SUCCESS)
+}
+
+pub(super) fn fd_fdstat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> {
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ let mut bytes = [0; 24];
+ bytes[0] = match &descriptor.resource {
+ Resource::File(file) => file_type(&file.metadata().map_err(|error| io_errno(&error))?),
+ _ => descriptor.file_type(),
+ };
+ put(&mut bytes, 2, descriptor.flags.to_le_bytes());
+ put(&mut bytes, 8, descriptor.rights.to_le_bytes());
+ put(&mut bytes, 16, descriptor.inheriting_rights.to_le_bytes());
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_fdstat_set_flags(mut ctx: FuncContext<'_>, (fd, flags): (i32, i32)) -> WasiResult<Errno> {
+ let flags = flags as u32;
+ if flags > FDFLAGS_ALL.into() {
+ return Ok(INVAL);
+ }
+ if flags & u32::from(FDFLAG_DSYNC | FDFLAG_RSYNC | FDFLAG_SYNC) != 0 {
+ return Ok(INVAL);
+ }
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_FDSTAT_SET_FLAGS)?;
+ let flags = flags as u16;
+ let nonblocking = flags & FDFLAG_NONBLOCK != 0;
+ match &descriptor.resource {
+ Resource::TcpListener(listener) if flags == FDFLAG_NONBLOCK || flags == 0 => {
+ listener.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))?
+ }
+ Resource::TcpStream(stream) if flags == FDFLAG_NONBLOCK || flags == 0 => {
+ stream.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))?
+ }
+ Resource::UdpSocket(socket) if flags == FDFLAG_NONBLOCK || flags == 0 => {
+ socket.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))?
+ }
+ Resource::TcpListener(_) | Resource::TcpStream(_) | Resource::UdpSocket(_) => return Ok(INVAL),
+ Resource::File(file) => set_file_status_flags(file, flags)?,
+ Resource::Stdin | Resource::Stdout | Resource::Stderr | Resource::Directory(_) => return Ok(BADF),
+ };
+ descriptor.flags = flags;
+ Ok(SUCCESS)
+}
+
+pub(super) fn fd_fdstat_set_rights(
+ mut ctx: FuncContext<'_>,
+ (fd, rights, inheriting_rights): (i32, i64, i64),
+) -> WasiResult<Errno> {
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ let rights = rights as u64;
+ let inheriting_rights = inheriting_rights as u64;
+ if rights & !descriptor.rights != 0 || inheriting_rights & !descriptor.inheriting_rights != 0 {
+ return Ok(NOTCAPABLE);
+ }
+ descriptor.rights = rights;
+ descriptor.inheriting_rights = inheriting_rights;
+ Ok(SUCCESS)
+}
+
+pub(super) fn fd_filestat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> {
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_FD_FILESTAT_GET)?;
+ let bytes = match &descriptor.resource {
+ Resource::File(file) => filestat(&file.metadata().map_err(|error| io_errno(&error))?),
+ Resource::Directory(dir) => filestat(&dir.dir_metadata().map_err(|error| io_errno(&error))?),
+ Resource::Stdin
+ | Resource::Stdout
+ | Resource::Stderr
+ | Resource::TcpListener(_)
+ | Resource::TcpStream(_)
+ | Resource::UdpSocket(_) => {
+ let mut bytes = [0; 64];
+ bytes[16] = descriptor.file_type();
+ bytes
+ }
+ };
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_filestat_set_size(mut ctx: FuncContext<'_>, (fd, size): (i32, i64)) -> WasiResult<Errno> {
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_FILESTAT_SET_SIZE)?;
+ let Resource::File(file) = &descriptor.resource else { return Ok(ISDIR) };
+ Ok(file.set_len(size as u64).map_or_else(|error| io_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn fd_filestat_set_times(
+ mut ctx: FuncContext<'_>,
+ (fd, atim, mtim, flags): (i32, i64, i64, i32),
+) -> WasiResult<Errno> {
+ let flags = flags as u32;
+ if flags > u32::from(FSTFLAGS_ALL)
+ || flags & u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) == u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW)
+ || flags & u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) == u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW)
+ {
+ return Ok(INVAL);
+ }
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_FILESTAT_SET_TIMES)?;
+ if flags == 0 {
+ return Ok(SUCCESS);
+ }
+ if let Resource::Directory(dir) = &descriptor.resource {
+ let atime = time_spec(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64);
+ let mtime = time_spec(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64);
+ return Ok(dir.set_times(".", atime, mtime).map_or_else(|error| io_errno(&error), |()| SUCCESS));
+ }
+ #[cfg(any(target_os = "android", target_os = "linux"))]
+ {
+ let Resource::File(file) = &descriptor.resource else { return Ok(NOTSUP) };
+ let access = rustix_time(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64)?;
+ let modification = rustix_time(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64)?;
+ let times = rustix::fs::Timestamps { last_access: access, last_modification: modification };
+ Ok(rustix::fs::futimens(file, &times).map_or_else(Errno::from, |()| SUCCESS))
+ }
+ #[cfg(not(any(target_os = "android", target_os = "linux")))]
+ {
+ let _ = (atim, mtim, descriptor);
+ Ok(NOTSUP)
+ }
+}
+
+pub(super) fn fd_read(ctx: FuncContext<'_>, args: (i32, i32, i32, i32)) -> WasiResult<Errno> {
+ read_from_fd(ctx, args, None)
+}
+
+pub(super) fn fd_pread(
+ ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, offset, result_ptr): (i32, i32, i32, i64, i32),
+) -> WasiResult<Errno> {
+ read_from_fd(ctx, (fd, iovecs_ptr, iovecs_len, result_ptr), Some(offset as u64))
+}
+
+fn read_from_fd(
+ mut ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, result_ptr): (i32, i32, i32, i32),
+ offset: Option<u64>,
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 4)?;
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_READ | if offset.is_some() { RIGHT_FD_SEEK } else { 0 })?;
+ let mut buffer = Vec::new();
+ buffer.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?;
+ buffer.resize(iovecs.byte_len, 0);
+ let read = match &mut descriptor.resource {
+ Resource::Stdin => std::io::stdin().lock().read(&mut buffer),
+ Resource::File(file) if let Some(offset) = offset => {
+ file.read_at(&mut buffer, checked_offset(offset, iovecs.byte_len)?)
+ }
+ Resource::File(file) => file.read(&mut buffer),
+ Resource::TcpStream(stream) => stream.read(&mut buffer),
+ Resource::UdpSocket(socket) => socket.recv(&mut buffer),
+ Resource::Directory(_) => return Ok(ISDIR),
+ _ => return Ok(BADF),
+ }
+ .map_err(|error| io_errno(&error))?;
+ memory.scatter(ctx.store_mut(), &iovecs, &buffer[..read])?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &(read as u32).to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_write(ctx: FuncContext<'_>, args: (i32, i32, i32, i32)) -> WasiResult<Errno> {
+ write_to_fd(ctx, args, None)
+}
+
+pub(super) fn fd_pwrite(
+ ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, offset, result_ptr): (i32, i32, i32, i64, i32),
+) -> WasiResult<Errno> {
+ write_to_fd(ctx, (fd, iovecs_ptr, iovecs_len, result_ptr), Some(offset as u64))
+}
+
+fn write_to_fd(
+ mut ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, result_ptr): (i32, i32, i32, i32),
+ offset: Option<u64>,
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 4)?;
+ let data = memory.gather(&ctx, &iovecs)?;
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_WRITE | if offset.is_some() { RIGHT_FD_SEEK } else { 0 })?;
+ let written = match &mut descriptor.resource {
+ Resource::Stdout => std::io::stdout().lock().write(&data),
+ Resource::Stderr => std::io::stderr().lock().write(&data),
+ Resource::File(file) if let Some(offset) = offset => file.write_at(&data, checked_offset(offset, data.len())?),
+ Resource::File(file) => file.write(&data),
+ Resource::TcpStream(stream) => stream.write(&data),
+ Resource::UdpSocket(socket) => socket.send(&data),
+ Resource::Directory(_) => return Ok(ISDIR),
+ _ => return Ok(BADF),
+ }
+ .map_err(|error| io_errno(&error))?;
+ Ok(memory
+ .write(ctx.store_mut(), result_ptr, &(written as u32).to_le_bytes())
+ .map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+fn checked_offset(offset: u64, len: usize) -> Result<u64, Errno> {
+ offset.checked_add(len as u64).map(|_| offset).ok_or(OVERFLOW)
+}
+
+#[cfg(unix)]
+fn set_file_status_flags(file: &cap_std::fs::File, flags: u16) -> Result<(), Errno> {
+ let mut host_flags = rustix::fs::fcntl_getfl(file).map_err(Errno::from)?;
+ host_flags.set(rustix::fs::OFlags::APPEND, flags & FDFLAG_APPEND != 0);
+ host_flags.set(rustix::fs::OFlags::NONBLOCK, flags & FDFLAG_NONBLOCK != 0);
+ rustix::fs::fcntl_setfl(file, host_flags).map_err(Errno::from)
+}
+
+#[cfg(not(unix))]
+fn set_file_status_flags(_file: &cap_std::fs::File, _flags: u16) -> Result<(), Errno> {
+ Err(NOTSUP)
+}
+
+pub(super) fn fd_seek(
+ mut ctx: FuncContext<'_>,
+ (fd, offset, whence, result_ptr): (i32, i64, i32, i32),
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 8)?;
+ let position = match whence {
+ 0 if offset >= 0 => SeekFrom::Start(offset as u64),
+ 0 => return Ok(INVAL),
+ 1 => SeekFrom::Current(offset),
+ 2 => SeekFrom::End(offset),
+ _ => return Ok(INVAL),
+ };
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(if whence == 1 && offset == 0 { RIGHT_FD_TELL } else { RIGHT_FD_SEEK })?;
+ let Resource::File(file) = &mut descriptor.resource else { return Ok(SPIPE) };
+ let offset = file.seek(position).map_err(|error| io_errno(&error))?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &offset.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_tell(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> {
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_TELL)?;
+ let Resource::File(file) = &mut descriptor.resource else { return Ok(SPIPE) };
+ let offset = file.stream_position().map_err(|error| io_errno(&error))?;
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &offset.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_sync(ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> {
+ sync_fd(ctx, fd, false)
+}
+
+pub(super) fn fd_datasync(ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> {
+ sync_fd(ctx, fd, true)
+}
+
+fn sync_fd(mut ctx: FuncContext<'_>, fd: i32, data_only: bool) -> WasiResult<Errno> {
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(if data_only { RIGHT_FD_DATASYNC } else { RIGHT_FD_SYNC })?;
+ let Resource::File(file) = &descriptor.resource else { return Ok(INVAL) };
+ Ok((if data_only { file.sync_data() } else { file.sync_all() }).map_or_else(|error| io_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn fd_allocate(mut ctx: FuncContext<'_>, (fd, offset, len): (i32, i64, i64)) -> WasiResult<Errno> {
+ let offset = offset as u64;
+ let len = len as u64;
+ if offset.checked_add(len).is_none() {
+ return Ok(FBIG);
+ }
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_ALLOCATE)?;
+ let Resource::File(_) = &descriptor.resource else { return Ok(BADF) };
+ Ok(NOTSUP)
+}
+
+pub(super) fn fd_advise(
+ mut ctx: FuncContext<'_>,
+ (fd, offset, len, advice): (i32, i64, i64, i32),
+) -> WasiResult<Errno> {
+ if !(0..=5).contains(&advice) {
+ return Ok(INVAL);
+ }
+ let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?;
+ descriptor.require_rights(RIGHT_FD_ADVISE)?;
+ let Resource::File(file) = &descriptor.resource else { return Ok(BADF) };
+ if (offset as u64).checked_add(len as u64).is_none() {
+ return Ok(OVERFLOW);
+ }
+ #[cfg(any(target_os = "android", target_os = "linux"))]
+ {
+ let advice = match advice {
+ 0 => rustix::fs::Advice::Normal,
+ 1 => rustix::fs::Advice::Sequential,
+ 2 => rustix::fs::Advice::Random,
+ 3 => rustix::fs::Advice::WillNeed,
+ 4 => rustix::fs::Advice::DontNeed,
+ 5 => rustix::fs::Advice::NoReuse,
+ _ => unreachable!(),
+ };
+ Ok(rustix::fs::fadvise(file, offset as u64, std::num::NonZeroU64::new(len as u64), advice)
+ .map_or_else(Errno::from, |()| SUCCESS))
+ }
+ #[cfg(not(any(target_os = "android", target_os = "linux")))]
+ {
+ let _ = (file, offset, len);
+ Ok(SUCCESS)
+ }
+}
+
+pub(super) fn fd_prestat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> {
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ let Some(path) = &descriptor.preopen_path else { return Ok(BADF) };
+ let Some(len) = u32::try_from(path.len()).ok() else { return Ok(OVERFLOW) };
+ let mut bytes = [0; 8];
+ put(&mut bytes, 4, len.to_le_bytes());
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_prestat_dir_name(
+ mut ctx: FuncContext<'_>,
+ (fd, path_ptr, path_len): (i32, i32, i32),
+) -> WasiResult<Errno> {
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ let Some(path) = descriptor.preopen_path.clone() else { return Ok(BADF) };
+ if path.len() > path_len as u32 as usize {
+ return Ok(NAMETOOLONG);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), path_ptr, &path).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn fd_readdir(
+ mut ctx: FuncContext<'_>,
+ (fd, buffer_ptr, buffer_len, cookie, used_ptr): (i32, i32, i32, i64, i32),
+) -> WasiResult<Errno> {
+ let capacity = buffer_len as u32 as usize;
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, buffer_ptr as u32 as usize, buffer_len as u32 as usize)?;
+ memory.check_range(&ctx, used_ptr as u32 as usize, 4)?;
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_FD_READDIR)?;
+ let Resource::Directory(dir) = &descriptor.resource else { return Ok(NOTDIR) };
+ let entries = dir.entries().map_err(|error| io_errno(&error))?;
+ let cookie = usize::try_from(cookie as u64).map_err(|_| OVERFLOW)?;
+ let mut output = Vec::new();
+ output.try_reserve_exact(capacity).map_err(|_| NOMEM)?;
+ for (index, entry) in entries.enumerate().skip(cookie) {
+ let entry = entry.map_err(|error| io_errno(&error))?;
+ let name = os_bytes(&entry.file_name());
+ let metadata = entry.full_metadata().map_err(|error| io_errno(&error))?;
+ let mut header = [0; 24];
+ let Some(next) = u64::try_from(index).ok().and_then(|index| index.checked_add(1)) else {
+ return Ok(OVERFLOW);
+ };
+ put(&mut header, 0, next.to_le_bytes());
+ put(&mut header, 8, metadata.ino().to_le_bytes());
+ put(&mut header, 16, u32::try_from(name.len()).unwrap_or(u32::MAX).to_le_bytes());
+ header[20] = file_type(&metadata);
+ let remaining = capacity.saturating_sub(output.len());
+ output.extend_from_slice(&header[..remaining.min(header.len())]);
+ let remaining = capacity.saturating_sub(output.len());
+ output.extend_from_slice(&name[..remaining.min(name.len())]);
+ if output.len() == capacity {
+ break;
+ }
+ }
+ memory.write(ctx.store_mut(), buffer_ptr, &output)?;
+ Ok(memory
+ .write(ctx.store_mut(), used_ptr, &(output.len() as u32).to_le_bytes())
+ .map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+#[cfg(any(target_os = "android", target_os = "linux"))]
+fn rustix_time(flags: u16, explicit: u16, now: u16, timestamp: u64) -> Result<rustix::fs::Timespec, Errno> {
+ if flags & now != 0 {
+ Ok(rustix::fs::Timespec { tv_sec: 0, tv_nsec: rustix::fs::UTIME_NOW })
+ } else if flags & explicit != 0 {
+ Ok(rustix::fs::Timespec {
+ tv_sec: i64::try_from(timestamp / 1_000_000_000).map_err(|_| OVERFLOW)?,
+ tv_nsec: (timestamp % 1_000_000_000) as _,
+ })
+ } else {
+ Ok(rustix::fs::Timespec { tv_sec: 0, tv_nsec: rustix::fs::UTIME_OMIT })
+ }
+}
diff --git a/crates/wasi/src/p1/imports/mod.rs b/crates/wasi/src/p1/imports/mod.rs
new file mode 100644
index 0000000..eff8d0f
--- /dev/null
+++ b/crates/wasi/src/p1/imports/mod.rs
@@ -0,0 +1,101 @@
+mod clock;
+mod command;
+mod fd;
+mod path;
+mod poll;
+mod process;
+mod random;
+mod sock;
+
+use tinywasm::{HostFunction, Imports};
+
+use super::abi::Errno;
+
+const MODULE: &str = "wasi_snapshot_preview1";
+
+type WasiResult<T> = Result<T, WasiError>;
+
+enum WasiError {
+ Errno(Errno),
+ Host(tinywasm::Error),
+}
+
+impl From<Errno> for WasiError {
+ fn from(errno: Errno) -> Self {
+ Self::Errno(errno)
+ }
+}
+
+impl From<tinywasm::Error> for WasiError {
+ fn from(error: tinywasm::Error) -> Self {
+ Self::Host(error)
+ }
+}
+
+pub(super) fn register(imports: &mut Imports) {
+ register_import(imports, "args_get", command::args_get);
+ register_import(imports, "args_sizes_get", command::args_sizes_get);
+ register_import(imports, "environ_get", command::environ_get);
+ register_import(imports, "environ_sizes_get", command::environ_sizes_get);
+ register_import(imports, "clock_res_get", clock::clock_res_get);
+ register_import(imports, "clock_time_get", clock::clock_time_get);
+ register_import(imports, "fd_advise", fd::fd_advise);
+ register_import(imports, "fd_allocate", fd::fd_allocate);
+ register_import(imports, "fd_close", fd::fd_close);
+ register_import(imports, "fd_datasync", fd::fd_datasync);
+ register_import(imports, "fd_fdstat_get", fd::fd_fdstat_get);
+ register_import(imports, "fd_fdstat_set_flags", fd::fd_fdstat_set_flags);
+ register_import(imports, "fd_fdstat_set_rights", fd::fd_fdstat_set_rights);
+ register_import(imports, "fd_filestat_get", fd::fd_filestat_get);
+ register_import(imports, "fd_filestat_set_size", fd::fd_filestat_set_size);
+ register_import(imports, "fd_filestat_set_times", fd::fd_filestat_set_times);
+ register_import(imports, "fd_pread", fd::fd_pread);
+ register_import(imports, "fd_prestat_get", fd::fd_prestat_get);
+ register_import(imports, "fd_prestat_dir_name", fd::fd_prestat_dir_name);
+ register_import(imports, "fd_pwrite", fd::fd_pwrite);
+ register_import(imports, "fd_read", fd::fd_read);
+ register_import(imports, "fd_readdir", fd::fd_readdir);
+ register_import(imports, "fd_renumber", fd::fd_renumber);
+ register_import(imports, "fd_seek", fd::fd_seek);
+ register_import(imports, "fd_sync", fd::fd_sync);
+ register_import(imports, "fd_tell", fd::fd_tell);
+ register_import(imports, "fd_write", fd::fd_write);
+ register_import(imports, "path_create_directory", path::path_create_directory);
+ register_import(imports, "path_filestat_get", path::path_filestat_get);
+ register_import(imports, "path_filestat_set_times", path::path_filestat_set_times);
+ register_import(imports, "path_link", path::path_link);
+ register_import(imports, "path_open", path::path_open);
+ register_import(imports, "path_readlink", path::path_readlink);
+ register_import(imports, "path_remove_directory", path::path_remove_directory);
+ register_import(imports, "path_rename", path::path_rename);
+ register_import(imports, "path_symlink", path::path_symlink);
+ register_import(imports, "path_unlink_file", path::path_unlink_file);
+ register_import(imports, "poll_oneoff", poll::poll_oneoff);
+ imports.define(MODULE, "proc_exit", HostFunction::from(process::proc_exit));
+ register_import(imports, "proc_raise", process::proc_raise);
+ register_import(imports, "sched_yield", process::sched_yield);
+ register_import(imports, "random_get", random::random_get);
+ register_import(imports, "sock_accept", sock::sock_accept);
+ register_import(imports, "sock_recv", sock::sock_recv);
+ register_import(imports, "sock_send", sock::sock_send);
+ register_import(imports, "sock_shutdown", sock::sock_shutdown);
+}
+
+fn register_import<P>(
+ imports: &mut Imports,
+ name: &str,
+ function: fn(tinywasm::FuncContext<'_>, P) -> WasiResult<Errno>,
+) where
+ P: tinywasm::FromWasmValues + 'static,
+{
+ imports.define(
+ MODULE,
+ name,
+ HostFunction::from(move |ctx: tinywasm::FuncContext<'_>, args: P| -> tinywasm::Result<i32> {
+ match function(ctx, args) {
+ Ok(errno) | Err(WasiError::Errno(errno)) => Ok(errno.into()),
+ Err(WasiError::Host(error)) => Err(error),
+ }
+ }),
+ );
+}
diff --git a/crates/wasi/src/p1/imports/path.rs b/crates/wasi/src/p1/imports/path.rs
new file mode 100644
index 0000000..648f0cb
--- /dev/null
+++ b/crates/wasi/src/p1/imports/path.rs
@@ -0,0 +1,258 @@
+use std::path::PathBuf;
+
+use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt, OpenOptionsMaybeDirExt, OpenOptionsSyncExt};
+use cap_std::fs::{Dir, OpenOptions};
+use tinywasm::FuncContext;
+
+use crate::p1::abi::*;
+use crate::p1::ctx::{Descriptor, Resource, state, state_mut};
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+const MAX_PATH_BYTES: usize = 4096;
+
+pub(super) fn path_create_directory(
+ ctx: FuncContext<'_>,
+ (fd, path_ptr, path_len): (i32, i32, i32),
+) -> WasiResult<Errno> {
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_CREATE_DIRECTORY)?;
+ Ok(dir.create_dir(path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_remove_directory(
+ ctx: FuncContext<'_>,
+ (fd, path_ptr, path_len): (i32, i32, i32),
+) -> WasiResult<Errno> {
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_REMOVE_DIRECTORY)?;
+ Ok(dir.remove_dir(path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_unlink_file(ctx: FuncContext<'_>, (fd, path_ptr, path_len): (i32, i32, i32)) -> WasiResult<Errno> {
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_UNLINK_FILE)?;
+ Ok(dir.remove_file_or_symlink(path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_open(
+ mut ctx: FuncContext<'_>,
+ (fd, lookup_flags, path_ptr, path_len, open_flags, rights, inheriting_rights, fd_flags, result_ptr): (
+ i32,
+ i32,
+ i32,
+ i32,
+ i32,
+ i64,
+ i64,
+ i32,
+ i32,
+ ),
+) -> WasiResult<Errno> {
+ let lookup_flags = lookup_flags as u32;
+ if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0
+ || open_flags as u32 > OFLAGS_ALL.into()
+ || fd_flags as u32 > FDFLAGS_ALL.into()
+ {
+ return Ok(INVAL);
+ }
+ let open_flags = open_flags as u16;
+ let fd_flags = fd_flags as u16;
+ if fd_flags & (FDFLAG_DSYNC | FDFLAG_RSYNC | FDFLAG_SYNC) != 0 {
+ return Ok(NOTSUP);
+ }
+ let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0;
+ let create = open_flags & OFLAG_CREAT != 0;
+ let exclusive = open_flags & OFLAG_EXCL != 0;
+ let truncate = open_flags & OFLAG_TRUNC != 0;
+ if exclusive && !create {
+ return Ok(INVAL);
+ }
+ if open_flags & OFLAG_DIRECTORY != 0 && (create || truncate) {
+ return Ok(ISDIR);
+ }
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 4)?;
+ let parent = state(&ctx)?.descriptor(fd)?;
+ parent.require_rights(RIGHT_PATH_OPEN)?;
+ let rights = rights as u64;
+ let inheriting_rights = inheriting_rights as u64;
+ if rights & !parent.inheriting_rights != 0 || inheriting_rights & !parent.inheriting_rights != 0 {
+ return Ok(NOTCAPABLE);
+ }
+ if create && parent.rights & RIGHT_PATH_CREATE_FILE == 0 {
+ return Ok(NOTCAPABLE);
+ }
+ if truncate && parent.rights & RIGHT_PATH_FILESTAT_SET_SIZE == 0 {
+ return Ok(NOTCAPABLE);
+ }
+ let Resource::Directory(parent_dir) = &parent.resource else { return Ok(NOTDIR) };
+ let parent_dir = parent_dir.try_clone().map_err(|error| path_errno(&error))?;
+ let mut options = OpenOptions::new();
+ let write = create || truncate || rights & (RIGHT_FD_WRITE | RIGHT_FD_ALLOCATE | RIGHT_FD_FILESTAT_SET_SIZE) != 0;
+ options
+ .read(rights & RIGHT_FD_READ != 0 || !write)
+ .write(write)
+ .append(write && fd_flags & FDFLAG_APPEND != 0)
+ .create(create)
+ .create_new(exclusive)
+ .truncate(truncate)
+ .follow(if follow { FollowSymlinks::Yes } else { FollowSymlinks::No })
+ .nonblock(fd_flags & FDFLAG_NONBLOCK != 0)
+ .maybe_dir(true);
+ let file = parent_dir.open_with(&path, &options).map_err(|error| path_errno(&error))?;
+ let descriptor = if file.metadata().map_err(|error| path_errno(&error))?.is_dir() {
+ Descriptor {
+ resource: Resource::Directory(Dir::reopen_dir(&file).map_err(|error| path_errno(&error))?),
+ rights: rights & DIRECTORY_RIGHTS,
+ inheriting_rights,
+ flags: fd_flags,
+ preopen_path: None,
+ }
+ } else {
+ if open_flags & OFLAG_DIRECTORY != 0 {
+ return Ok(NOTDIR);
+ }
+ Descriptor {
+ resource: Resource::File(file),
+ rights: rights & FILE_RIGHTS,
+ inheriting_rights: 0,
+ flags: fd_flags,
+ preopen_path: None,
+ }
+ };
+ let new_fd = state_mut(&mut ctx)?.insert_descriptor(descriptor)?;
+ if let Err(errno) = memory.write(ctx.store_mut(), result_ptr, &new_fd.to_le_bytes()) {
+ let _ = state_mut(&mut ctx)?.descriptors[new_fd as usize].take();
+ return Ok(errno);
+ }
+ Ok(SUCCESS)
+}
+
+pub(super) fn path_filestat_get(
+ mut ctx: FuncContext<'_>,
+ (fd, lookup_flags, path_ptr, path_len, result_ptr): (i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ let lookup_flags = lookup_flags as u32;
+ if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0 {
+ return Ok(INVAL);
+ }
+ let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0;
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_FILESTAT_GET)?;
+ let metadata = if follow { dir.metadata(&path) } else { dir.symlink_metadata(&path) };
+ let metadata = metadata.map_err(|error| path_errno(&error))?;
+ let bytes = filestat(&metadata);
+ let memory = GuestMemory::new(&ctx)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn path_filestat_set_times(
+ ctx: FuncContext<'_>,
+ (fd, lookup_flags, path_ptr, path_len, atim, mtim, flags): (i32, i32, i32, i32, i64, i64, i32),
+) -> WasiResult<Errno> {
+ let lookup_flags = lookup_flags as u32;
+ let flags = flags as u32;
+ if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0
+ || flags > FSTFLAGS_ALL.into()
+ || flags & u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) == u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW)
+ || flags & u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) == u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW)
+ {
+ return Ok(INVAL);
+ }
+ let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0;
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_FILESTAT_SET_TIMES)?;
+ if flags == 0 {
+ return Ok(SUCCESS);
+ }
+ let atime = time_spec(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64);
+ let mtime = time_spec(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64);
+ let result = if follow { dir.set_times(&path, atime, mtime) } else { dir.set_symlink_times(&path, atime, mtime) };
+ Ok(result.map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_link(
+ ctx: FuncContext<'_>,
+ (old_fd, flags, old_ptr, old_len, new_fd, new_ptr, new_len): (i32, i32, i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ if flags != 0 {
+ return Ok(INVAL);
+ }
+ let old_path = guest_path(&ctx, old_ptr, old_len)?;
+ let new_path = guest_path(&ctx, new_ptr, new_len)?;
+ let old_dir = directory(&ctx, old_fd, RIGHT_PATH_LINK_SOURCE)?;
+ let new_dir = directory(&ctx, new_fd, RIGHT_PATH_LINK_TARGET)?;
+ Ok(old_dir.hard_link(old_path, &new_dir, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_rename(
+ ctx: FuncContext<'_>,
+ (old_fd, old_ptr, old_len, new_fd, new_ptr, new_len): (i32, i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ let old_path = guest_path(&ctx, old_ptr, old_len)?;
+ let new_path = guest_path(&ctx, new_ptr, new_len)?;
+ let old_dir = directory(&ctx, old_fd, RIGHT_PATH_RENAME_SOURCE)?;
+ let new_dir = directory(&ctx, new_fd, RIGHT_PATH_RENAME_TARGET)?;
+ Ok(old_dir.rename(old_path, &new_dir, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+pub(super) fn path_readlink(
+ mut ctx: FuncContext<'_>,
+ (fd, path_ptr, path_len, buffer_ptr, buffer_len, used_ptr): (i32, i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, buffer_ptr as u32 as usize, buffer_len as u32 as usize)?;
+ memory.check_range(&ctx, used_ptr as u32 as usize, 4)?;
+ let path = guest_path(&ctx, path_ptr, path_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_READLINK)?;
+ let target = dir.read_link_contents(path).map_err(|error| path_errno(&error))?;
+ let bytes = os_bytes(target.as_os_str());
+ let written = bytes.len().min(buffer_len as u32 as usize);
+ memory.write(ctx.store_mut(), buffer_ptr, &bytes[..written])?;
+ Ok(memory
+ .write(ctx.store_mut(), used_ptr, &(written as u32).to_le_bytes())
+ .map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn path_symlink(
+ ctx: FuncContext<'_>,
+ (old_ptr, old_len, fd, new_ptr, new_len): (i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ if old_len as u32 as usize > MAX_PATH_BYTES {
+ return Ok(NAMETOOLONG);
+ }
+ let target_bytes = memory.read(&ctx, old_ptr, old_len)?;
+ if target_bytes.contains(&0) {
+ return Ok(ILSEQ);
+ }
+ let target = PathBuf::from(std::str::from_utf8(&target_bytes).map_err(|_| ILSEQ)?);
+ let new_path = guest_path(&ctx, new_ptr, new_len)?;
+ let dir = directory(&ctx, fd, RIGHT_PATH_SYMLINK)?;
+ Ok(DirExt::symlink(&dir, target, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS))
+}
+
+fn directory(ctx: &FuncContext<'_>, fd: i32, right: u64) -> Result<Dir, Errno> {
+ let descriptor = state(ctx).map_err(|_| IO)?.descriptor(fd)?;
+ descriptor.require_rights(right)?;
+ let Resource::Directory(dir) = &descriptor.resource else { return Err(NOTDIR) };
+ dir.try_clone().map_err(|error| path_errno(&error))
+}
+
+fn guest_path(ctx: &FuncContext<'_>, pointer: i32, len: i32) -> Result<PathBuf, Errno> {
+ if len as u32 as usize > MAX_PATH_BYTES {
+ return Err(NAMETOOLONG);
+ }
+ let memory = GuestMemory::new(ctx).map_err(|_| IO)?;
+ let bytes = memory.read(ctx, pointer, len)?;
+ if bytes.is_empty() {
+ return Err(NOENT);
+ }
+ if bytes.contains(&0) {
+ return Err(INVAL);
+ }
+ Ok(PathBuf::from(std::str::from_utf8(&bytes).map_err(|_| ILSEQ)?))
+}
diff --git a/crates/wasi/src/p1/imports/poll.rs b/crates/wasi/src/p1/imports/poll.rs
new file mode 100644
index 0000000..8098b74
--- /dev/null
+++ b/crates/wasi/src/p1/imports/poll.rs
@@ -0,0 +1,219 @@
+use std::io::Seek;
+
+use rustix::event::{PollFd, PollFlags, Timespec};
+use tinywasm::FuncContext;
+
+use crate::p1::abi::*;
+use crate::p1::ctx::{Resource, state};
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+enum Readiness {
+ Ready,
+ Clock(u64),
+ Poll,
+}
+
+struct PendingEvent {
+ bytes: [u8; 32],
+ readiness: Readiness,
+}
+
+struct PollTarget {
+ event_index: usize,
+ fd: i32,
+ event_type: u8,
+}
+
+impl PendingEvent {
+ fn new(userdata: u64, error: Errno, event_type: u8, available: u64, readiness: Readiness) -> Self {
+ let mut bytes = [0; 32];
+ put(&mut bytes, 0, userdata.to_le_bytes());
+ put(&mut bytes, 8, (i32::from(error) as u16).to_le_bytes());
+ bytes[10] = event_type;
+ put(&mut bytes, 16, available.to_le_bytes());
+ Self { bytes, readiness }
+ }
+}
+
+pub(super) fn poll_oneoff(
+ mut ctx: FuncContext<'_>,
+ (subscriptions_ptr, events_ptr, count, result_ptr): (i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ let count = count as u32 as usize;
+ if count == 0 || count > 1024 {
+ return Ok(INVAL);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ let subscriptions = memory.read_at(&ctx, subscriptions_ptr as u32 as usize, count * 48)?;
+ memory.check_range(&ctx, events_ptr as u32 as usize, count * 32)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 4)?;
+
+ let mut pending_events = Vec::with_capacity(count);
+ let mut poll_targets = Vec::new();
+ let mut minimum_wait: Option<u64> = None;
+ for subscription in subscriptions.as_chunks::<48>().0 {
+ let userdata = u64::from_le_bytes(subscription[..8].try_into().expect("userdata"));
+ let event_type = subscription[8];
+ if event_type == 0 {
+ let wait = clock_wait(&ctx, subscription)?;
+ minimum_wait = Some(minimum_wait.map_or(wait, |current| current.min(wait)));
+ pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, 0, Readiness::Clock(wait)));
+ } else if matches!(event_type, 1 | 2) {
+ let fd = u32::from_le_bytes(subscription[16..20].try_into().expect("fd")) as i32;
+ subscribe_fd(&ctx, fd, userdata, event_type, &mut pending_events, &mut poll_targets)?;
+ } else {
+ return Ok(INVAL);
+ }
+ }
+
+ let immediately_ready =
+ pending_events.iter().any(|event| matches!(event.readiness, Readiness::Ready | Readiness::Clock(0)));
+ let timeout = if immediately_ready { Some(0) } else { minimum_wait };
+ let elapsed = wait_for_events(&ctx, &poll_targets, &mut pending_events, timeout)?;
+ let mut bytes = Vec::with_capacity(pending_events.len() * 32);
+ for event in pending_events {
+ if matches!(event.readiness, Readiness::Ready)
+ || matches!(event.readiness, Readiness::Clock(wait) if wait <= elapsed)
+ {
+ bytes.extend_from_slice(&event.bytes);
+ }
+ }
+ let event_count = (bytes.len() / 32) as u32;
+ memory.write(ctx.store_mut(), events_ptr, &bytes)?;
+ Ok(memory.write(ctx.store_mut(), result_ptr, &event_count.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+fn clock_wait(ctx: &FuncContext<'_>, subscription: &[u8; 48]) -> WasiResult<u64> {
+ let clock_id = u32::from_le_bytes(subscription[16..20].try_into().expect("clock id"));
+ let timeout = u64::from_le_bytes(subscription[24..32].try_into().expect("timeout"));
+ let flags = u16::from_le_bytes(subscription[40..42].try_into().expect("flags"));
+ if !matches!(clock_id, 0 | 1) || flags & !1 != 0 {
+ return Err(INVAL.into());
+ }
+ let now = if clock_id == 0 {
+ realtime_now()
+ } else {
+ state(ctx)?.monotonic_start.elapsed().as_nanos().try_into().unwrap_or(u64::MAX)
+ };
+ Ok(if flags & 1 != 0 { timeout.saturating_sub(now) } else { timeout })
+}
+
+fn subscribe_fd(
+ ctx: &FuncContext<'_>,
+ fd: i32,
+ userdata: u64,
+ event_type: u8,
+ pending_events: &mut Vec<PendingEvent>,
+ poll_targets: &mut Vec<PollTarget>,
+) -> WasiResult<()> {
+ let required_right = if event_type == 1 { RIGHT_FD_READ } else { RIGHT_FD_WRITE };
+ let descriptor = match state(ctx)?.descriptor(fd) {
+ Ok(descriptor) => descriptor,
+ Err(errno) => {
+ pending_events.push(PendingEvent::new(userdata, errno, event_type, 0, Readiness::Ready));
+ return Ok(());
+ }
+ };
+ if let Err(errno) = descriptor.require_rights(required_right | RIGHT_POLL_FD_READWRITE) {
+ pending_events.push(PendingEvent::new(userdata, errno, event_type, 0, Readiness::Ready));
+ return Ok(());
+ }
+ if let Resource::File(file) = &descriptor.resource {
+ let available = if event_type == 1 {
+ file.try_clone()
+ .and_then(|mut file| {
+ let position = file.stream_position()?;
+ Ok(file.metadata()?.len().saturating_sub(position))
+ })
+ .unwrap_or(0)
+ } else {
+ 0
+ };
+ pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, available, Readiness::Ready));
+ return Ok(());
+ }
+ poll_targets.push(PollTarget { event_index: pending_events.len(), fd, event_type });
+ pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, 0, Readiness::Poll));
+ Ok(())
+}
+
+fn wait_for_events(
+ ctx: &FuncContext<'_>,
+ poll_targets: &[PollTarget],
+ pending_events: &mut [PendingEvent],
+ timeout_ns: Option<u64>,
+) -> WasiResult<u64> {
+ let started = std::time::Instant::now();
+ let stdin = std::io::stdin();
+ let stdout = std::io::stdout();
+ let stderr = std::io::stderr();
+ let wasi = state(ctx)?;
+ let mut poll_fds = Vec::with_capacity(poll_targets.len());
+ for target in poll_targets {
+ let flags = if target.event_type == 1 { PollFlags::IN } else { PollFlags::OUT };
+ let descriptor = wasi.descriptor(target.fd)?;
+ let poll_fd = match &descriptor.resource {
+ Resource::Stdin => PollFd::new(&stdin, flags),
+ Resource::Stdout => PollFd::new(&stdout, flags),
+ Resource::Stderr => PollFd::new(&stderr, flags),
+ Resource::TcpListener(listener) => PollFd::new(listener, flags),
+ Resource::TcpStream(stream) => PollFd::new(stream, flags),
+ Resource::UdpSocket(socket) => PollFd::new(socket, flags),
+ Resource::File(_) | Resource::Directory(_) => unreachable!(),
+ };
+ poll_fds.push(poll_fd);
+ }
+ let timeout = timeout_ns.map(|nanoseconds| Timespec {
+ tv_sec: (nanoseconds / 1_000_000_000).try_into().unwrap_or(i64::MAX),
+ tv_nsec: (nanoseconds % 1_000_000_000) as _,
+ });
+ if poll_fds.is_empty() {
+ if let Some(nanoseconds) = timeout_ns {
+ std::thread::sleep(std::time::Duration::from_nanos(nanoseconds));
+ }
+ } else {
+ loop {
+ match rustix::event::poll(&mut poll_fds, timeout.as_ref()) {
+ Err(rustix::io::Errno::INTR) => continue,
+ result => {
+ result.map_err(Errno::from)?;
+ break;
+ }
+ }
+ }
+ }
+ for (target, poll_fd) in poll_targets.iter().zip(poll_fds) {
+ let flags = poll_fd.revents();
+ if flags.intersects(PollFlags::IN | PollFlags::OUT | PollFlags::ERR | PollFlags::HUP | PollFlags::NVAL) {
+ pending_events[target.event_index].readiness = Readiness::Ready;
+ let error = if flags.contains(PollFlags::NVAL) {
+ BADF
+ } else if flags.contains(PollFlags::ERR) {
+ IO
+ } else {
+ SUCCESS
+ };
+ put(&mut pending_events[target.event_index].bytes, 8, (i32::from(error) as u16).to_le_bytes());
+ if target.event_type == 1 {
+ let resource = &wasi.descriptor(target.fd)?.resource;
+ let available = match resource {
+ Resource::Stdin => rustix::io::ioctl_fionread(&stdin),
+ Resource::TcpStream(stream) => rustix::io::ioctl_fionread(stream),
+ Resource::UdpSocket(socket) => rustix::io::ioctl_fionread(socket),
+ _ => Ok(0),
+ }
+ .unwrap_or(0);
+ put(&mut pending_events[target.event_index].bytes, 16, available.to_le_bytes());
+ if matches!(resource, Resource::TcpStream(_)) && available == 0 {
+ put(&mut pending_events[target.event_index].bytes, 24, 1_u16.to_le_bytes());
+ }
+ }
+ if flags.contains(PollFlags::HUP) {
+ put(&mut pending_events[target.event_index].bytes, 24, 1_u16.to_le_bytes());
+ }
+ }
+ }
+ Ok(u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX))
+}
diff --git a/crates/wasi/src/p1/imports/process.rs b/crates/wasi/src/p1/imports/process.rs
new file mode 100644
index 0000000..9d9571e
--- /dev/null
+++ b/crates/wasi/src/p1/imports/process.rs
@@ -0,0 +1,20 @@
+use tinywasm::{Error, FuncContext};
+
+use crate::p1::abi::{Errno, NOTSUP, SUCCESS};
+use crate::p1::ctx::state_mut;
+
+use super::WasiResult;
+
+pub(super) fn proc_exit(mut ctx: FuncContext<'_>, status: i32) -> tinywasm::Result<()> {
+ state_mut(&mut ctx)?.exit_status = Some(status as u32);
+ Err(Error::Other("WASI process exited".into()))
+}
+
+pub(super) fn proc_raise(_ctx: FuncContext<'_>, _signal: i32) -> WasiResult<Errno> {
+ Ok(NOTSUP)
+}
+
+pub(super) fn sched_yield(_ctx: FuncContext<'_>, (): ()) -> WasiResult<Errno> {
+ std::thread::yield_now();
+ Ok(SUCCESS)
+}
diff --git a/crates/wasi/src/p1/imports/random.rs b/crates/wasi/src/p1/imports/random.rs
new file mode 100644
index 0000000..84d06e9
--- /dev/null
+++ b/crates/wasi/src/p1/imports/random.rs
@@ -0,0 +1,25 @@
+use tinywasm::FuncContext;
+
+use crate::p1::abi::{Errno, IO, SUCCESS};
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+pub(super) fn random_get(mut ctx: FuncContext<'_>, (buffer_ptr, buffer_len): (i32, i32)) -> WasiResult<Errno> {
+ let memory = GuestMemory::new(&ctx)?;
+ let offset = buffer_ptr as u32 as usize;
+ let len = buffer_len as u32 as usize;
+ memory.check_range(&ctx, offset, len)?;
+
+ let mut chunk = [0_u8; 64 * 1024];
+ let mut written = 0;
+ while written < len {
+ let chunk_len = (len - written).min(chunk.len());
+ if getrandom::fill(&mut chunk[..chunk_len]).is_err() {
+ return Ok(IO);
+ }
+ memory.write_at(ctx.store_mut(), offset + written, &chunk[..chunk_len])?;
+ written += chunk_len;
+ }
+ Ok(SUCCESS)
+}
diff --git a/crates/wasi/src/p1/imports/sock.rs b/crates/wasi/src/p1/imports/sock.rs
new file mode 100644
index 0000000..f938835
--- /dev/null
+++ b/crates/wasi/src/p1/imports/sock.rs
@@ -0,0 +1,124 @@
+use std::io::{IoSliceMut, Write};
+
+use tinywasm::FuncContext;
+
+use crate::p1::abi::*;
+use crate::p1::ctx::{Descriptor, Resource, state, state_mut};
+use crate::p1::memory::GuestMemory;
+
+use super::WasiResult;
+
+pub(super) fn sock_accept(mut ctx: FuncContext<'_>, (fd, flags, result_ptr): (i32, i32, i32)) -> WasiResult<Errno> {
+ if flags as u32 > FDFLAGS_ALL.into() {
+ return Ok(INVAL);
+ }
+ let flags = flags as u16;
+ let memory = GuestMemory::new(&ctx)?;
+ memory.check_range(&ctx, result_ptr as u32 as usize, 4)?;
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_SOCK_ACCEPT)?;
+ let Resource::TcpListener(listener) = &descriptor.resource else { return Ok(NOTSOCK) };
+ let rights = descriptor.inheriting_rights;
+ let (stream, _) = listener.accept().map_err(|error| io_errno(&error))?;
+ stream.set_nonblocking(flags & FDFLAG_NONBLOCK != 0).map_err(|error| io_errno(&error))?;
+ let new_fd = state_mut(&mut ctx)?.insert_descriptor(Descriptor {
+ resource: Resource::TcpStream(stream),
+ rights,
+ inheriting_rights: 0,
+ flags,
+ preopen_path: None,
+ })?;
+ if let Err(errno) = memory.write(ctx.store_mut(), result_ptr, &new_fd.to_le_bytes()) {
+ let _ = state_mut(&mut ctx)?.descriptors[new_fd as usize].take();
+ return Ok(errno);
+ }
+ Ok(SUCCESS)
+}
+
+pub(super) fn sock_recv(
+ mut ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, flags, data_len_ptr, result_flags_ptr): (i32, i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ if flags as u32 & !3 != 0 {
+ return Ok(INVAL);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?;
+ memory.check_range(&ctx, data_len_ptr as u32 as usize, 4)?;
+ memory.check_range(&ctx, result_flags_ptr as u32 as usize, 2)?;
+ let mut buffer = Vec::new();
+ buffer.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?;
+ buffer.resize(iovecs.byte_len, 0);
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_FD_READ)?;
+ let mut recv_flags = rustix::net::RecvFlags::empty();
+ if flags & 1 != 0 {
+ recv_flags |= rustix::net::RecvFlags::PEEK;
+ }
+ if flags & 2 != 0 {
+ recv_flags |= rustix::net::RecvFlags::WAITALL;
+ }
+ let (received, truncated) = match &descriptor.resource {
+ Resource::TcpStream(stream) => {
+ (rustix::net::recv(stream, &mut buffer[..], recv_flags).map_err(Errno::from)?.1, false)
+ }
+ Resource::UdpSocket(socket) => {
+ let mut slices = [IoSliceMut::new(&mut buffer)];
+ let mut control = rustix::net::RecvAncillaryBuffer::default();
+ let message = rustix::net::recvmsg(socket, &mut slices, &mut control, recv_flags).map_err(Errno::from)?;
+ (message.bytes, message.flags.contains(rustix::net::ReturnFlags::TRUNC))
+ }
+ _ => return Ok(NOTSOCK),
+ };
+ let written = received;
+ memory.scatter(ctx.store_mut(), &iovecs, &buffer[..written])?;
+ memory.write(ctx.store_mut(), data_len_ptr, &(written as u32).to_le_bytes())?;
+ let result_flags = u16::from(truncated);
+ Ok(memory
+ .write(ctx.store_mut(), result_flags_ptr, &result_flags.to_le_bytes())
+ .map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn sock_send(
+ mut ctx: FuncContext<'_>,
+ (fd, iovecs_ptr, iovecs_len, flags, data_len_ptr): (i32, i32, i32, i32, i32),
+) -> WasiResult<Errno> {
+ if flags != 0 {
+ return Ok(INVAL);
+ }
+ let memory = GuestMemory::new(&ctx)?;
+ let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?;
+ memory.check_range(&ctx, data_len_ptr as u32 as usize, 4)?;
+ let data = memory.gather(&ctx, &iovecs)?;
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_FD_WRITE)?;
+ let sent = match &descriptor.resource {
+ Resource::TcpStream(stream) => {
+ let mut stream = stream;
+ stream.write(&data)
+ }
+ Resource::UdpSocket(socket) => socket.send(&data),
+ _ => return Ok(NOTSOCK),
+ }
+ .map_err(|error| io_errno(&error))?;
+ Ok(memory
+ .write(ctx.store_mut(), data_len_ptr, &(sent as u32).to_le_bytes())
+ .map_or_else(|errno| errno, |()| SUCCESS))
+}
+
+pub(super) fn sock_shutdown(ctx: FuncContext<'_>, (fd, how): (i32, i32)) -> WasiResult<Errno> {
+ let how = match how {
+ 1 => rustix::net::Shutdown::Read,
+ 2 => rustix::net::Shutdown::Write,
+ 3 => rustix::net::Shutdown::Both,
+ _ => return Ok(INVAL),
+ };
+ let descriptor = state(&ctx)?.descriptor(fd)?;
+ descriptor.require_rights(RIGHT_SOCK_SHUTDOWN)?;
+ let result = match &descriptor.resource {
+ Resource::TcpStream(stream) => rustix::net::shutdown(stream, how),
+ Resource::UdpSocket(socket) => rustix::net::shutdown(socket, how),
+ _ => return Ok(NOTSOCK),
+ };
+ Ok(result.map_or_else(Errno::from, |()| SUCCESS))
+}
diff --git a/crates/wasi/src/p1/memory.rs b/crates/wasi/src/p1/memory.rs
new file mode 100644
index 0000000..38b4c6a
--- /dev/null
+++ b/crates/wasi/src/p1/memory.rs
@@ -0,0 +1,115 @@
+use tinywasm::types::MemoryArch;
+use tinywasm::{Error, FuncContext, Memory, Store};
+
+use super::abi::{Errno, FAULT, INVAL, NOMEM};
+
+const MAX_IOVECS: usize = 1024;
+const MAX_IO_BYTES: usize = 16 * 1024 * 1024;
+
+/// Provides checked access to a guest's wasm32 memory.
+pub(super) struct GuestMemory(Memory);
+
+/// A bounded and validated guest iovec array.
+pub(super) struct GuestIovecs {
+ pub(super) entries: Vec<(usize, usize)>,
+ pub(super) byte_len: usize,
+}
+
+impl GuestMemory {
+ /// Finds and validates the guest's exported memory.
+ pub(super) fn new(ctx: &FuncContext<'_>) -> tinywasm::Result<Self> {
+ let memory = ctx.memory("memory")?;
+ if memory.ty(ctx.store())?.arch() != MemoryArch::I32 {
+ return Err(Error::UnsupportedFeature("WASI Preview 1 requires wasm32 memory"));
+ }
+ Ok(Self(memory))
+ }
+
+ /// Reads bytes using a wasm32 pointer and length.
+ pub(super) fn read(&self, store: &Store, pointer: i32, len: i32) -> Result<Vec<u8>, Errno> {
+ let len = len as u32 as usize;
+ self.read_at(store, pointer as u32 as usize, len)
+ }
+
+ /// Reads bytes using host-sized offsets.
+ pub(super) fn read_at(&self, store: &Store, offset: usize, len: usize) -> Result<Vec<u8>, Errno> {
+ if !self.is_valid_range(store, offset, len) {
+ return Err(FAULT);
+ }
+ let mut bytes = Vec::new();
+ bytes.try_reserve_exact(len).map_err(|_| NOMEM)?;
+ bytes.resize(len, 0);
+ self.0.read_exact(store, offset, &mut bytes).map_err(|_| FAULT)?;
+ Ok(bytes)
+ }
+
+ /// Writes bytes using a wasm32 pointer.
+ pub(super) fn write(&self, store: &mut Store, pointer: i32, bytes: &[u8]) -> Result<(), Errno> {
+ self.write_at(store, pointer as u32 as usize, bytes)
+ }
+
+ /// Writes bytes using a host-sized offset.
+ pub(super) fn write_at(&self, store: &mut Store, offset: usize, bytes: &[u8]) -> Result<(), Errno> {
+ self.check_range(store, offset, bytes.len())?;
+ self.0.copy_from_slice(store, offset, bytes).map_err(|_| FAULT)
+ }
+
+ /// Validates that a guest memory range is accessible.
+ pub(super) fn check_range(&self, store: &Store, offset: usize, len: usize) -> Result<(), Errno> {
+ if self.is_valid_range(store, offset, len) { Ok(()) } else { Err(FAULT) }
+ }
+
+ /// Reads and validates a guest iovec array.
+ pub(super) fn read_iovecs(&self, store: &Store, pointer: i32, count: i32) -> Result<GuestIovecs, Errno> {
+ let count = count as u32 as usize;
+ if count > MAX_IOVECS {
+ return Err(INVAL);
+ }
+ let table_len = count.checked_mul(8).ok_or(INVAL)?;
+ let table = self.read_at(store, pointer as u32 as usize, table_len)?;
+ let mut total = 0usize;
+ let mut entries = Vec::new();
+ entries.try_reserve_exact(count).map_err(|_| NOMEM)?;
+ for entry in table.as_chunks::<8>().0 {
+ let offset = u32::from_le_bytes(entry[..4].try_into().expect("iovec field")) as usize;
+ let len = u32::from_le_bytes(entry[4..].try_into().expect("iovec field")) as usize;
+ total = total.checked_add(len).ok_or(INVAL)?;
+ if total > MAX_IO_BYTES || !self.is_valid_range(store, offset, len) {
+ return Err(if total > MAX_IO_BYTES { INVAL } else { FAULT });
+ }
+ entries.push((offset, len));
+ }
+ Ok(GuestIovecs { entries, byte_len: total })
+ }
+
+ /// Copies guest iovec contents into one contiguous buffer.
+ pub(super) fn gather(&self, store: &Store, iovecs: &GuestIovecs) -> Result<Vec<u8>, Errno> {
+ let mut bytes = Vec::new();
+ bytes.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?;
+ bytes.resize(iovecs.byte_len, 0);
+ let mut destination = 0;
+ for &(offset, len) in &iovecs.entries {
+ self.0.read_exact(store, offset, &mut bytes[destination..destination + len]).map_err(|_| FAULT)?;
+ destination += len;
+ }
+ Ok(bytes)
+ }
+
+ /// Copies one contiguous buffer into guest iovecs.
+ pub(super) fn scatter(&self, store: &mut Store, iovecs: &GuestIovecs, bytes: &[u8]) -> Result<(), Errno> {
+ let mut source = 0;
+ for &(offset, len) in &iovecs.entries {
+ let len = len.min(bytes.len() - source);
+ self.write_at(store, offset, &bytes[source..source + len])?;
+ source += len;
+ if source == bytes.len() {
+ break;
+ }
+ }
+ Ok(())
+ }
+
+ fn is_valid_range(&self, store: &Store, offset: usize, len: usize) -> bool {
+ self.0.len(store).ok().is_some_and(|memory_len| offset.checked_add(len).is_some_and(|end| end <= memory_len))
+ }
+}
diff --git a/crates/wasi/src/p1/mod.rs b/crates/wasi/src/p1/mod.rs
new file mode 100644
index 0000000..8a852e8
--- /dev/null
+++ b/crates/wasi/src/p1/mod.rs
@@ -0,0 +1,22 @@
+//! Synchronous WASI Preview 1 command support.
+
+mod abi;
+mod ctx;
+mod imports;
+mod memory;
+
+pub use ctx::{WasiCtx, WasiCtxError};
+
+use tinywasm::Imports;
+
+/// Creates a new [`Imports`] object with the WASI Preview 1 namespace registered.
+pub fn imports() -> Imports {
+ let mut imports = Imports::new();
+ register(&mut imports);
+ imports
+}
+
+/// Registers the frozen WASI Preview 1 namespace on an [`Imports`] object.
+pub fn register(imports: &mut Imports) {
+ self::imports::register(imports);
+}
diff --git a/crates/wasi/tests/p1.rs b/crates/wasi/tests/p1.rs
new file mode 100644
index 0000000..e41ca39
--- /dev/null
+++ b/crates/wasi/tests/p1.rs
@@ -0,0 +1,357 @@
+use tinywasm::{Imports, ModuleInstance, Store};
+use tinywasm_wasi::p1::{WasiCtx, imports, register};
+
+struct TempDir(std::path::PathBuf);
+
+impl TempDir {
+ fn new(name: &str) -> Self {
+ let path = std::env::temp_dir().join(format!(
+ "tinywasm-wasi-{name}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
+ ));
+ std::fs::create_dir(&path).unwrap();
+ Self(path)
+ }
+}
+
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+fn module(source: &str) -> tinywasm::Module {
+ tinywasm::parse_bytes(&wat::parse_str(source).unwrap()).unwrap()
+}
+
+#[test]
+fn links_the_frozen_preview1_surface() -> tinywasm::Result<()> {
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "clock_res_get" (func (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_advise" (func (param i32 i64 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_allocate" (func (param i32 i64 i64) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_close" (func (param i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_datasync" (func (param i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_fdstat_set_flags" (func (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_fdstat_set_rights" (func (param i32 i64 i64) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_filestat_set_size" (func (param i32 i64) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_filestat_set_times" (func (param i32 i64 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_pread" (func (param i32 i32 i32 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_pwrite" (func (param i32 i32 i32 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_readdir" (func (param i32 i32 i32 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_renumber" (func (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_seek" (func (param i32 i64 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_sync" (func (param i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_tell" (func (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_create_directory" (func (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_filestat_get" (func (param i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_filestat_set_times" (func (param i32 i32 i32 i32 i64 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_link" (func (param i32 i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_readlink" (func (param i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_remove_directory" (func (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_rename" (func (param i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_symlink" (func (param i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_unlink_file" (func (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "poll_oneoff" (func (param i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "proc_raise" (func (param i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sched_yield" (func (result i32)))
+ (import "wasi_snapshot_preview1" "sock_accept" (func (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_recv" (func (param i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_send" (func (param i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_shutdown" (func (param i32 i32) (result i32))))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new());
+ let mut imports = Imports::new();
+ register(&mut imports);
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ Ok(())
+}
+
+#[test]
+fn writes_arguments_and_environment() -> tinywasm::Result<()> {
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "args_sizes_get" (func $args_sizes_get (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "args_get" (func $args_get (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "environ_sizes_get" (func $environ_sizes_get (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "environ_get" (func $environ_get (param i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (func (export "run") (result i32)
+ i32.const 0 i32.const 4 call $args_sizes_get drop
+ i32.const 8 i32.const 32 call $args_get drop
+ i32.const 16 i32.const 20 call $environ_sizes_get drop
+ i32.const 24 i32.const 48 call $environ_get))"#,
+ );
+ let wasi = WasiCtx::new().with_args(["app.wasm", "one"]).unwrap().with_env([("MODE", "test")]).unwrap();
+ let mut store = Store::default().with_state(wasi);
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+
+ let memory = instance.memory("memory")?;
+ let mut sizes = [0; 24];
+ memory.read_exact(&store, 0, &mut sizes)?;
+ assert_eq!(u32::from_le_bytes(sizes[0..4].try_into().unwrap()), 2);
+ assert_eq!(u32::from_le_bytes(sizes[4..8].try_into().unwrap()), 13);
+ assert_eq!(u32::from_le_bytes(sizes[16..20].try_into().unwrap()), 1);
+ assert_eq!(u32::from_le_bytes(sizes[20..24].try_into().unwrap()), 10);
+ assert_eq!(memory.read_vec(&store, 32, 13)?, b"app.wasm\0one\0");
+ assert_eq!(memory.read_vec(&store, 48, 10)?, b"MODE=test\0");
+ Ok(())
+}
+
+#[test]
+fn handles_process_exit_and_unsupported_raise() -> tinywasm::Result<()> {
+ let exit_module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "proc_exit" (func $proc_exit (param i32)))
+ (func (export "_start")
+ i32.const 7
+ call $proc_exit
+ unreachable))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new());
+ let instance = ModuleInstance::instantiate(&mut store, &exit_module, Some(&imports()))?;
+ assert!(instance.func::<(), ()>(&store, "_start")?.call(&mut store, ()).is_err());
+ let wasi = store.state_mut::<WasiCtx>().unwrap();
+ assert_eq!(wasi.exit_status(), Some(7));
+ assert_eq!(wasi.take_exit_status(), Some(7));
+ assert_eq!(wasi.exit_status(), None);
+
+ let raise_module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "proc_raise" (func $proc_raise (param i32) (result i32)))
+ (func (export "run") (result i32)
+ i32.const 15 call $proc_raise))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new());
+ let instance = ModuleInstance::instantiate(&mut store, &raise_module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 58);
+ Ok(())
+}
+
+#[test]
+fn uses_preopened_files_and_enforces_descriptor_rights() -> tinywasm::Result<()> {
+ let temp = TempDir::new("preopen-rights");
+ std::fs::write(temp.0.join("hello.txt"), b"hello").unwrap();
+ let read_module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "fd_prestat_get" (func $prestat (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_prestat_dir_name" (func $prestat_name (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_read" (func $read (param i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_filestat_get" (func $stat (param i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\c8\00\00\00\05\00\00\00")
+ (data (i32.const 100) "hello.txt")
+ (func (export "run") (result i32)
+ i32.const 3 i32.const 20 call $prestat drop
+ i32.const 3 i32.const 32 i32.const 16 call $prestat_name drop
+ i32.const 3 i32.const 1 i32.const 100 i32.const 9 i32.const 0
+ i64.const 2097154 i64.const 0 i32.const 0 i32.const 12 call $open drop
+ i32.const 12 i32.load i32.const 0 i32.const 1 i32.const 16 call $read drop
+ i32.const 12 i32.load i32.const 256 call $stat))"#,
+ );
+ let wasi = WasiCtx::new().preopen_dir(&temp.0, "/sandbox").unwrap();
+ let mut store = Store::default().with_state(wasi);
+ let instance = ModuleInstance::instantiate(&mut store, &read_module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+ let memory = instance.memory("memory")?;
+ assert_eq!(memory.read_vec(&store, 32, 8)?, b"/sandbox");
+ assert_eq!(memory.read_vec(&store, 200, 5)?, b"hello");
+ assert_eq!(memory.read_vec(&store, 256 + 16, 1)?, [4]);
+ let stat = memory.read_vec(&store, 256, 64)?;
+ assert_eq!(u64::from_le_bytes(stat[32..40].try_into().unwrap()), 5);
+
+ let rights_module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_fdstat_set_rights" (func $rights (param i32 i64 i64) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_read" (func $read (param i32 i32 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\80\00\00\00\01\00\00\00")
+ (data (i32.const 32) "hello.txt")
+ (func (export "run") (result i32)
+ i32.const 3 i32.const 1 i32.const 32 i32.const 9 i32.const 0
+ i64.const 2 i64.const 0 i32.const 0 i32.const 64 call $open drop
+ i32.const 64 i32.load i64.const 0 i64.const 0 call $rights drop
+ i32.const 64 i32.load i32.const 0 i32.const 1 i32.const 68 call $read))"#,
+ );
+ let wasi = WasiCtx::new().preopen_dir(&temp.0, "/").unwrap();
+ let mut store = Store::default().with_state(wasi);
+ let instance = ModuleInstance::instantiate(&mut store, &rights_module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 76);
+ Ok(())
+}
+
+#[test]
+fn prevents_preopen_capability_escape() -> tinywasm::Result<()> {
+ let parent = TempDir::new("escape");
+ let sandbox = parent.0.join("sandbox");
+ std::fs::create_dir(&sandbox).unwrap();
+ std::fs::write(parent.0.join("outside.txt"), b"secret").unwrap();
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 32) "../outside.txt")
+ (func (export "run") (result i32)
+ i32.const 3 i32.const 1 i32.const 32 i32.const 14 i32.const 0
+ i64.const 2 i64.const 0 i32.const 0 i32.const 0 call $open))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new().preopen_dir(&sandbox, "/").unwrap());
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 76);
+ assert_eq!(std::fs::read(parent.0.join("outside.txt")).unwrap(), b"secret");
+ Ok(())
+}
+
+#[test]
+fn provides_clocks_randomness_and_timer_polling() -> tinywasm::Result<()> {
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "clock_time_get" (func $clock (param i32 i64 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "random_get" (func $random (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "poll_oneoff" (func $poll (param i32 i32 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\2a\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\01\00\00\00\00\00\00\00\40\42\0f\00\00\00\00\00\01\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00")
+ (func (export "run") (result i32)
+ i32.const 0 i32.const 64 i32.const 1 i32.const 128 call $poll drop
+ i32.const 0 i64.const 1 i32.const 160 call $clock drop
+ i32.const 1 i64.const 1 i32.const 168 call $clock drop
+ i32.const 192 i32.const 32 call $random))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new());
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+ let memory = instance.memory("memory")?;
+ let event = memory.read_vec(&store, 64, 32)?;
+ assert_eq!(u64::from_le_bytes(event[0..8].try_into().unwrap()), 42);
+ assert_eq!(u16::from_le_bytes(event[8..10].try_into().unwrap()), 0);
+ assert_eq!(event[10], 0);
+ assert_eq!(memory.read_vec(&store, 128, 4)?, 1_u32.to_le_bytes());
+ assert_ne!(u64::from_le_bytes(memory.read_vec(&store, 160, 8)?.try_into().unwrap()), 0);
+ assert!(memory.read_vec(&store, 192, 32)?.iter().any(|byte| *byte != 0));
+ Ok(())
+}
+
+#[test]
+fn polls_accepts_and_uses_tcp_streams() -> tinywasm::Result<()> {
+ use std::io::{Read, Write};
+
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let peer = std::thread::spawn(move || {
+ let mut stream = std::net::TcpStream::connect(address).unwrap();
+ stream.write_all(b"hello").unwrap();
+ let mut reply = [0; 5];
+ stream.read_exact(&mut reply).unwrap();
+ reply
+ });
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "poll_oneoff" (func $poll (param i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_accept" (func $accept (param i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_recv" (func $recv (param i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_send" (func $send (param i32 i32 i32 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\64\00\00\00\05\00\00\00\78\00\00\00\05\00\00\00")
+ (data (i32.const 120) "world")
+ (data (i32.const 160) "\2a\00\00\00\00\00\00\00\01\00\00\00\00\00\00\00\03\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00")
+ (func (export "run") (result i32)
+ i32.const 160 i32.const 224 i32.const 1 i32.const 256 call $poll drop
+ i32.const 3 i32.const 0 i32.const 32 call $accept drop
+ i32.const 32 i32.load i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv drop
+ i32.const 32 i32.load i32.const 8 i32.const 1 i32.const 0 i32.const 24 call $send))"#,
+ );
+ let mut wasi = WasiCtx::new();
+ assert_eq!(wasi.insert_tcp_listener(listener).unwrap(), 3);
+ let mut store = Store::default().with_state(wasi);
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+ let memory = instance.memory("memory")?;
+ let event = memory.read_vec(&store, 224, 32)?;
+ assert_eq!(u64::from_le_bytes(event[0..8].try_into().unwrap()), 42);
+ assert_eq!(event[10], 1);
+ assert_eq!(memory.read_vec(&store, 256, 4)?, 1_u32.to_le_bytes());
+ assert_eq!(memory.read_vec(&store, 100, 5)?, b"hello");
+ assert_eq!(memory.read_vec(&store, 16, 4)?, 5_u32.to_le_bytes());
+ assert_eq!(memory.read_vec(&store, 24, 4)?, 5_u32.to_le_bytes());
+ assert_eq!(peer.join().unwrap(), *b"world");
+ Ok(())
+}
+
+#[test]
+fn sends_and_receives_udp_datagrams() -> tinywasm::Result<()> {
+ let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
+ let peer = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
+ socket.connect(peer.local_addr().unwrap()).unwrap();
+ peer.connect(socket.local_addr().unwrap()).unwrap();
+ peer.send(b"hello!").unwrap();
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "fd_fdstat_set_flags" (func $set_flags (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_recv" (func $recv (param i32 i32 i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "sock_send" (func $send (param i32 i32 i32 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\64\00\00\00\05\00\00\00\78\00\00\00\05\00\00\00")
+ (data (i32.const 120) "world")
+ (func (export "run") (result i32)
+ i32.const 3 i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv drop
+ i32.const 3 i32.const 8 i32.const 1 i32.const 0 i32.const 24 call $send)
+ (func (export "nonblocking_recv") (result i32)
+ i32.const 3 i32.const 4 call $set_flags drop
+ i32.const 3 i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv))"#,
+ );
+ let mut wasi = WasiCtx::new();
+ assert_eq!(wasi.insert_udp_socket(socket).unwrap(), 3);
+ let mut store = Store::default().with_state(wasi);
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+ let memory = instance.memory("memory")?;
+ assert_eq!(memory.read_vec(&store, 100, 5)?, b"hello");
+ assert_eq!(memory.read_vec(&store, 20, 2)?, 1_u16.to_le_bytes());
+ let mut reply = [0; 5];
+ peer.recv(&mut reply).unwrap();
+ assert_eq!(reply, *b"world");
+ assert_eq!(instance.func::<(), i32>(&store, "nonblocking_recv")?.call(&mut store, ())?, 6);
+ Ok(())
+}
+
+#[test]
+fn performs_descriptor_io_and_lifecycle_operations() -> tinywasm::Result<()> {
+ let temp = TempDir::new("descriptor-lifecycle");
+ let module = module(
+ r#"(module
+ (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_write" (func $write (param i32 i32 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_tell" (func $tell (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_seek" (func $seek (param i32 i64 i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_renumber" (func $renumber (param i32 i32) (result i32)))
+ (import "wasi_snapshot_preview1" "fd_close" (func $close (param i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 0) "\80\00\00\00\05\00\00\00\85\00\00\00\01\00\00\00")
+ (data (i32.const 32) "data")
+ (data (i32.const 128) "hello!")
+ (func (export "run") (result i32)
+ i32.const 3 i32.const 1 i32.const 32 i32.const 4 i32.const 9
+ i64.const 100 i64.const 0 i32.const 0 i32.const 64 call $open drop
+ i32.const 64 i32.load i32.const 0 i32.const 1 i32.const 68 call $write drop
+ i32.const 64 i32.load i32.const 72 call $tell drop
+ i32.const 64 i32.load i64.const 1 i32.const 0 i32.const 80 call $seek drop
+ i32.const 64 i32.load i32.const 10 call $renumber drop
+ i32.const 10 i32.const 8 i32.const 1 i32.const 88 call $write drop
+ i32.const 10 call $close))"#,
+ );
+ let mut store = Store::default().with_state(WasiCtx::new().preopen_dir(&temp.0, "/").unwrap());
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0);
+ let memory = instance.memory("memory")?;
+ assert_eq!(memory.read_vec(&store, 68, 4)?, 5_u32.to_le_bytes());
+ assert_eq!(memory.read_vec(&store, 72, 8)?, 5_u64.to_le_bytes());
+ assert_eq!(memory.read_vec(&store, 80, 8)?, 1_u64.to_le_bytes());
+ assert_eq!(memory.read_vec(&store, 88, 4)?, 1_u32.to_le_bytes());
+ assert_eq!(std::fs::read(temp.0.join("data")).unwrap(), b"h!llo");
+ Ok(())
+}
diff --git a/examples/archive.rs b/examples/archive.rs
index 7a2ebab..3f118f2 100644
--- a/examples/archive.rs
+++ b/examples/archive.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::{Module, ModuleInstance, Store, parser::Parser};
const WASM: &str = r#"
@@ -11,13 +11,13 @@ const WASM: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("Failed to parse WAT");
+ let wasm = wat::parse_str(WASM)?;
let module = Parser::default().parse_module_bytes(wasm)?;
- let twasm = module.serialize_twasm()?;
- // Now, you could e.g. write `twasm` to a file called `add.twasm`
- // and load it later in a different program.
+ // Serialize the optimized module for storage or distribution.
+ let twasm = module.serialize_twasm()?;
+ // Archived modules load without parsing Wasm again and should only come from trusted sources.
let module = Module::try_from_twasm(&twasm)?;
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
diff --git a/examples/simple.rs b/examples/basic.rs
index a902b4c..1f717c5 100644
--- a/examples/simple.rs
+++ b/examples/basic.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::{ModuleInstance, Store};
const WASM: &str = r#"
@@ -11,10 +11,14 @@ const WASM: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
+ let wasm = wat::parse_str(WASM)?;
let module = tinywasm::parse_bytes(&wasm)?;
+
+ // Module is reusable, while Store owns the runtime state for this instance.
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ // Typed handles validate parameters and results. Use func_untyped for dynamic values.
let add = instance.func::<(i32, i32), i32>(&store, "add")?;
assert_eq!(add.call(&mut store, (1, 2))?, 3);
diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml
index 38e16c4..c096db6 100644
--- a/examples/doom/Cargo.toml
+++ b/examples/doom/Cargo.toml
@@ -7,13 +7,14 @@ publish = false
[workspace]
[dependencies]
-eyre = "0.6"
+anyhow = "1.0"
log = "0.4"
pretty_env_logger = "0.5"
softbuffer = "0.4"
tinywasm = { path = "../../crates/tinywasm", features = [
"archive",
"canonicalize-nans",
+ "state",
"debug",
"log",
"parallel-parser",
diff --git a/examples/doom/src/main.rs b/examples/doom/src/main.rs
index 095183d..a8e98ef 100644
--- a/examples/doom/src/main.rs
+++ b/examples/doom/src/main.rs
@@ -4,7 +4,7 @@ use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::rc::Rc;
-use eyre::{ContextCompat, Result, bail, eyre};
+use anyhow::{Context, Result, anyhow, bail};
use runtime::{Runtime, SCREEN_HEIGHT, SCREEN_WIDTH};
use softbuffer::{Context as SoftbufferContext, Surface};
use winit::application::ApplicationHandler;
@@ -60,10 +60,10 @@ impl DoomApp {
surface
.resize(NonZeroU32::new(SCREEN_WIDTH as u32).unwrap(), NonZeroU32::new(SCREEN_HEIGHT as u32).unwrap())
- .map_err(|err| eyre!(err.to_string()))?;
- let mut buffer = surface.buffer_mut().map_err(|err| eyre!(err.to_string()))?;
+ .map_err(|err| anyhow!(err.to_string()))?;
+ let mut buffer = surface.buffer_mut().map_err(|err| anyhow!(err.to_string()))?;
self.runtime.write_framebuffer(&mut buffer)?;
- buffer.present().map_err(|err| eyre!(err.to_string()))?;
+ buffer.present().map_err(|err| anyhow!(err.to_string()))?;
Ok(())
}
}
@@ -129,7 +129,7 @@ impl ApplicationHandler for DoomApp {
window.request_redraw();
}
- if self.runtime.host_state.borrow().exit_code.is_some() {
+ if self.runtime.exited() {
event_loop.exit();
}
}
diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs
index 980dc21..2e50a20 100644
--- a/examples/doom/src/runtime.rs
+++ b/examples/doom/src/runtime.rs
@@ -1,12 +1,10 @@
-use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions, create_dir_all};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
-use std::rc::Rc;
-use std::time::Instant;
+use std::time::{Duration, Instant};
-use eyre::Result;
+use anyhow::{Context, Result};
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
const IMPORT_MODULE: &str = "env";
@@ -20,17 +18,14 @@ pub struct Runtime {
key_down: tinywasm::FunctionTyped<i32, ()>,
key_up: tinywasm::FunctionTyped<i32, ()>,
memory: tinywasm::Memory,
- framebuffer_bytes: Vec<u8>,
- pub host_state: Rc<RefCell<HostState>>,
}
impl Runtime {
pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result<Self> {
let module = tinywasm::parse_file(&guest_path)?;
- let mut store = Store::default();
- let host_state = Rc::new(RefCell::new(HostState::new(wad_path)));
- let imports = build_imports(&mut store, host_state.clone());
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let mut store = Store::default().with_state(HostState::new(wad_path));
+ let imports = build_imports();
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?;
let init = instance.func::<(), ()>(&store, "tinywasm_doom_init")?;
@@ -41,23 +36,11 @@ impl Runtime {
let memory = instance.memory("memory")?;
let buf_ptr = wad_path_buf.call(&mut store, ())? as usize;
- let wad_path_string = host_state.borrow().wad_path.to_string_lossy().into_owned();
+ let wad_path_string = store.state::<HostState>().unwrap().wad_path.to_string_lossy().into_owned();
memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?;
init.call(&mut store, ())?;
- let width = SCREEN_WIDTH;
- let height = SCREEN_HEIGHT;
-
- Ok(Self {
- store,
- update,
- framebuffer,
- key_down,
- key_up,
- memory,
- framebuffer_bytes: vec![0; width * height * 4],
- host_state,
- })
+ Ok(Self { store, update, framebuffer, key_down, key_up, memory })
}
pub fn tick(&mut self) -> Result<()> {
@@ -66,11 +49,15 @@ impl Runtime {
}
pub fn write_framebuffer(&mut self, dst: &mut [u32]) -> Result<()> {
- let ptr = self.framebuffer.call(&mut self.store, ())? as usize;
- self.memory.read_exact(&self.store, ptr, &mut self.framebuffer_bytes)?;
- for (index, pixel) in dst.iter_mut().enumerate() {
- let byte_index = index * 4;
- let chunk = &self.framebuffer_bytes[byte_index..byte_index + 4];
+ let ptr = self.framebuffer.call(&mut self.store, ())? as u32 as usize;
+ let framebuffer = self
+ .memory
+ .data(&self.store)?
+ .get(ptr..)
+ .and_then(|data| data.get(..SCREEN_WIDTH * SCREEN_HEIGHT * 4))
+ .context("framebuffer is outside guest memory")?;
+ anyhow::ensure!(dst.len() <= SCREEN_WIDTH * SCREEN_HEIGHT, "framebuffer destination is too large");
+ for (pixel, chunk) in dst.iter_mut().zip(framebuffer.chunks_exact(4)) {
*pixel = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
}
Ok(())
@@ -85,15 +72,19 @@ impl Runtime {
self.key_up.call(&mut self.store, key)?;
Ok(())
}
+
+ pub fn exited(&self) -> bool {
+ self.store.state::<HostState>().unwrap().exit_code.is_some()
+ }
}
pub struct HostState {
- pub wad_path: PathBuf,
+ wad_path: PathBuf,
runtime_dir: PathBuf,
start: Instant,
files: BTreeMap<i32, File>,
next_file: i32,
- pub exit_code: Option<i32>,
+ exit_code: Option<i32>,
}
impl HostState {
@@ -161,183 +152,164 @@ impl HostState {
}
}
-fn build_imports(store: &mut Store, state: Rc<RefCell<HostState>>) -> Imports {
+fn build_imports() -> Imports {
let mut imports = Imports::new();
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_open",
- HostFunction::from(store, move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| {
- let memory = ctx.memory("memory")?;
- let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?;
- let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?;
- let filename = filename.to_string_lossy();
- let mode = mode.to_string_lossy();
- let mut state = state.borrow_mut();
- let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) {
- state.wad_path.clone()
- } else {
- state.resolve_path(&filename)
- };
+ imports.define(
+ IMPORT_MODULE,
+ "host_open",
+ HostFunction::from(|mut ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| {
+ let memory = ctx.memory("memory")?;
+ let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?;
+ let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?;
+ let filename = filename.to_string_lossy();
+ let mode = mode.to_string_lossy();
+ let state = ctx.state_mut::<HostState>().unwrap();
+ let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) {
+ state.wad_path.clone()
+ } else {
+ state.resolve_path(&filename)
+ };
+
+ if path.is_dir() {
+ log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode);
+ return Ok(-1);
+ }
- if path.is_dir() {
- log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode);
+ let file = match HostState::open_mode_options(&mode).open(&path) {
+ Ok(file) => file,
+ Err(err) => {
+ log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode);
return Ok(-1);
}
+ };
- let file = match HostState::open_mode_options(&mode).open(&path) {
- Ok(file) => file,
- Err(err) => {
- log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode);
- return Ok(-1);
- }
- };
-
- let handle = state.next_file;
- state.next_file += 1;
- state.files.insert(handle, file);
- Ok(handle)
- }),
- );
- }
+ let handle = state.next_file;
+ state.next_file += 1;
+ state.files.insert(handle, file);
+ Ok(handle)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_close",
- HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| {
- state.borrow_mut().files.remove(&handle);
- Ok(())
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_close",
+ HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
+ ctx.state_mut::<HostState>().unwrap().files.remove(&handle);
+ Ok(())
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_read",
- HostFunction::from(store, move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
- let mut state = state.borrow_mut();
+ imports.define(
+ IMPORT_MODULE,
+ "host_read",
+ HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
+ let mut buffer = vec![0; count.max(0) as usize];
+ let read = {
+ let state = ctx.state_mut::<HostState>().unwrap();
let Some(file) = state.files.get_mut(&handle) else {
return Ok(0);
};
- let mut buffer = vec![0; count.max(0) as usize];
- let read = file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?;
- Ok(read as i32)
- }),
- );
- }
+ file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))?
+ };
+ ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?;
+ Ok(read as i32)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_write",
- HostFunction::from(store, move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
- let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?;
- let mut state = state.borrow_mut();
- let Some(file) = state.files.get_mut(&handle) else {
- return Ok(-1);
- };
- let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- Ok(written as i32)
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_write",
+ HostFunction::from(|ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| {
+ let data = ctx.memory("memory")?.data(ctx.store())?;
+ let offset = buf_ptr as u32 as usize;
+ let len = count.max(0) as usize;
+ let data = data
+ .get(offset..)
+ .and_then(|data| data.get(..len))
+ .ok_or(tinywasm::Trap::MemoryOutOfBounds { offset, len, max: data.len() })?;
+ let state = ctx.state::<HostState>().unwrap();
+ let Some(mut file) = state.files.get(&handle) else {
+ return Ok(-1);
+ };
+ let written = file.write(data).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ Ok(written as i32)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_seek",
- HostFunction::from(store, move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| {
- let seek_from = match origin {
- 0 => SeekFrom::Start(offset.max(0) as u64),
- 1 => SeekFrom::Current(offset as i64),
- 2 => SeekFrom::End(offset as i64),
- _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))),
- };
- let mut state = state.borrow_mut();
- let Some(file) = state.files.get_mut(&handle) else {
- return Ok(-1);
- };
- let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- Ok(pos.min(i32::MAX as u64) as i32)
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_seek",
+ HostFunction::from(|mut ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| {
+ let seek_from = match origin {
+ 0 => SeekFrom::Start(offset.max(0) as u64),
+ 1 => SeekFrom::Current(offset as i64),
+ 2 => SeekFrom::End(offset as i64),
+ _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))),
+ };
+ let state = ctx.state_mut::<HostState>().unwrap();
+ let Some(file) = state.files.get_mut(&handle) else {
+ return Ok(-1);
+ };
+ let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ Ok(pos.min(i32::MAX as u64) as i32)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_tell",
- HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| {
- let mut state = state.borrow_mut();
- let Some(file) = state.files.get_mut(&handle) else {
- return Ok(-1);
- };
- let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- Ok(pos.min(i32::MAX as u64) as i32)
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_tell",
+ HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
+ let state = ctx.state_mut::<HostState>().unwrap();
+ let Some(file) = state.files.get_mut(&handle) else {
+ return Ok(-1);
+ };
+ let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ Ok(pos.min(i32::MAX as u64) as i32)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_eof",
- HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| {
- let mut state = state.borrow_mut();
- let Some(file) = state.files.get_mut(&handle) else {
- return Ok(1);
- };
- let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len();
- Ok((pos >= len) as i32)
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_eof",
+ HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| {
+ let state = ctx.state_mut::<HostState>().unwrap();
+ let Some(file) = state.files.get_mut(&handle) else {
+ return Ok(1);
+ };
+ let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len();
+ Ok((pos >= len) as i32)
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_gettime",
- HostFunction::from(store, move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| {
- let elapsed = state.borrow().start.elapsed();
- let sec = elapsed.as_secs().min(i32::MAX as u64) as i32;
- let usec = elapsed.subsec_micros() as i32;
- let memory = ctx.memory("memory")?;
- memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?;
- memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?;
- Ok(())
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_gettime",
+ HostFunction::from(|mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| {
+ let elapsed = ctx.state::<HostState>().unwrap().start.elapsed() + Duration::from_secs(1);
+ let sec = elapsed.as_secs().min(i32::MAX as u64) as i32;
+ let usec = elapsed.subsec_micros() as i32;
+ let memory = ctx.memory("memory")?;
+ memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?;
+ memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?;
+ Ok(())
+ }),
+ );
- {
- let state = state.clone();
- imports.define(
- IMPORT_MODULE,
- "host_exit",
- HostFunction::from(store, move |_ctx: FuncContext<'_>, code: i32| {
- state.borrow_mut().exit_code = Some(code);
- Ok(())
- }),
- );
- }
+ imports.define(
+ IMPORT_MODULE,
+ "host_exit",
+ HostFunction::from(|mut ctx: FuncContext<'_>, code: i32| {
+ ctx.state_mut::<HostState>().unwrap().exit_code = Some(code);
+ Ok(())
+ }),
+ );
imports.define(
IMPORT_MODULE,
"host_print",
- HostFunction::from(store, move |ctx: FuncContext<'_>, ptr: i32| {
+ HostFunction::from(|ctx: FuncContext<'_>, ptr: i32| {
let text = ctx.memory("memory")?.read_cstring_until_null(ctx.store(), ptr as usize, 4096)?;
log::info!("guest: {}", text.to_string_lossy());
Ok(())
diff --git a/examples/exceptions.rs b/examples/exceptions.rs
new file mode 100644
index 0000000..7c2f88e
--- /dev/null
+++ b/examples/exceptions.rs
@@ -0,0 +1,28 @@
+use anyhow::{Result, bail};
+use tinywasm::{Error, ModuleInstance, Store, WasmValue};
+
+const WASM: &str = r#"
+(module
+ (tag $failure (export "failure") (param i32))
+ (func (export "fail") (param i32)
+ local.get 0
+ throw $failure))
+"#;
+
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ let fail = instance.func::<i32, ()>(&store, "fail")?;
+
+ // Uncaught guest exceptions cross the host boundary as owned ExnRef handles.
+ let Err(Error::Exception(exception)) = fail.call(&mut store, 42) else {
+ bail!("expected a guest exception");
+ };
+
+ // The handle exposes the exception tag and typed payload values.
+ assert_eq!(exception.tag(&store)?, instance.tag("failure")?);
+ assert_eq!(exception.fields(&mut store)?, [WasmValue::I32(42)]);
+ Ok(())
+}
diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs
deleted file mode 100644
index 8ff9b49..0000000
--- a/examples/funcref_callbacks.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use eyre::Result;
-use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef};
-
-const LHS: i32 = 5;
-const RHS: i32 = 3;
-
-fn main() -> Result<()> {
- run_passed_funcref_example()?;
- run_returned_funcref_example()?;
- Ok(())
-}
-
-fn run_passed_funcref_example() -> Result<()> {
- // Host receives funcref and calls it via an exported proxy.
- const WASM: &str = r#"
- (module
- (import "host" "call_this" (func $host_callback_caller (param funcref)))
- (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32)))
-
- (func $tell_host_to_call (export "tell_host_to_call")
- (call $host_callback_caller (ref.func $add))
- (call $host_callback_caller (ref.func $sub))
- (call $host_callback_caller (ref.func $host_mul))
- )
-
- (type $binop (func (param i32 i32) (result i32)))
-
- (table 3 funcref)
- (elem (i32.const 0) $add $sub $host_mul)
- (func $add (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.add
- )
- (func $sub (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.sub
- )
-
- (table $callback_register 1 funcref)
- (func (export "call_binop_by_ref") (param funcref i32 i32) (result i32)
- (table.set $callback_register (i32.const 0) (local.get 0))
- (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0))
- )
- )
- "#;
-
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
-
- let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) });
- let call_this =
- HostFunction::from(&mut store, |mut ctx: FuncContext<'_>, func_ref: FuncRef| -> tinywasm::Result<()> {
- // Host cannot call a funcref directly, so it routes through Wasm.
- let call_by_ref = ctx.module().func::<(FuncRef, i32, i32), i32>(ctx.store(), "call_binop_by_ref")?;
- let _result = call_by_ref.call(ctx.store_mut(), (func_ref, LHS, RHS))?;
- Ok(())
- });
-
- let mut imports = Imports::new();
- imports.define("host", "call_this", call_this).define("host", "mul", mul);
-
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
- let caller = instance.func::<(), ()>(&store, "tell_host_to_call")?;
-
- caller.call(&mut store, ())?;
-
- Ok(())
-}
-
-fn run_returned_funcref_example() -> Result<()> {
- // Wasm returns funcref values, host executes them through the same proxy.
- const WASM: &str = r#"
- (module
- (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32)))
- (type $binop (func (param i32 i32) (result i32)))
- (table 3 funcref)
- (elem (i32.const 0) $add $sub $host_mul)
- (func $add (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.add
- )
- (func $sub (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.sub
- )
- (func $ref_to_funcs (export "what_should_host_call") (result funcref funcref funcref)
- (ref.func $add)
- (ref.func $sub)
- (ref.func $host_mul)
- )
-
- (table $callback_register 1 funcref)
- (func $call (export "call_binop_by_ref") (param funcref i32 i32) (result i32)
- (table.set $callback_register (i32.const 0) (local.get 0))
- (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0))
- )
- )
- "#;
-
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
- let mut imports = Imports::new();
-
- let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) });
- imports.define("host", "mul", mul);
-
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
- let (add_ref, sub_ref, mul_ref) = {
- let get_funcrefs = instance.func::<(), (FuncRef, FuncRef, FuncRef)>(&store, "what_should_host_call")?;
- get_funcrefs.call(&mut store, ())?
- };
-
- let call_by_ref = instance.func::<(FuncRef, i32, i32), i32>(&store, "call_binop_by_ref")?;
- for func_ref in [add_ref, sub_ref, mul_ref] {
- let _result = call_by_ref.call(&mut store, (func_ref, LHS, RHS))?;
- }
- Ok(())
-}
diff --git a/examples/gc.rs b/examples/gc.rs
new file mode 100644
index 0000000..9a73d04
--- /dev/null
+++ b/examples/gc.rs
@@ -0,0 +1,33 @@
+use anyhow::Result;
+use tinywasm::{ModuleInstance, Store, StructRef, WasmValue};
+
+const WASM: &str = r#"
+(module
+ (type $cube (struct (field (mut i32)) (field (mut i32))))
+ (func $make-cube (result (ref $cube))
+ i32.const 3
+ i32.const 4
+ struct.new $cube)
+ (func (export "cube") (result (ref struct))
+ call $make-cube))
+"#;
+
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?;
+
+ // GC handles are Store-bound and expose typed field access through that Store.
+ assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]);
+ cube.set_field(&mut store, 0, WasmValue::I32(5))?;
+
+ // Cloned handles keep their guest objects live across explicit collection.
+ let retained = cube.clone();
+ drop(cube);
+ store.gc()?;
+
+ assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive
+ Ok(())
+}
diff --git a/examples/linking.rs b/examples/linking.rs
index b3164ae..92c0b7d 100644
--- a/examples/linking.rs
+++ b/examples/linking.rs
@@ -1,7 +1,6 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::{ModuleInstance, Store};
-// WebAssembly module defining and exporting an `add` function.
const WASM_ADD: &str = r#"
(module
(func $add (param $lhs i32) (param $rhs i32) (result i32)
@@ -11,7 +10,6 @@ const WASM_ADD: &str = r#"
(export "add" (func $add)))
"#;
-// WebAssembly module importing an `add` function and using it.
const WASM_IMPORT: &str = r#"
(module
(import "adder" "add" (func $add (param i32 i32) (result i32)))
@@ -24,25 +22,23 @@ const WASM_IMPORT: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm_add = wat::parse_str(WASM_ADD).expect("failed to parse wat");
- let wasm_import = wat::parse_str(WASM_IMPORT).expect("failed to parse wat");
+ let wasm_add = wat::parse_str(WASM_ADD)?;
+ let wasm_import = wat::parse_str(WASM_IMPORT)?;
let add_module = tinywasm::parse_bytes(&wasm_add)?;
let import_module = tinywasm::parse_bytes(&wasm_import)?;
let mut store = Store::default();
- // Instantiate the `add` module.
let add_instance = ModuleInstance::instantiate(&mut store, &add_module, None)?;
- // Link the `adder` namespace to the `add` module's instance.
+ // Imports can link a module namespace and define individual host items together.
let mut imports = tinywasm::Imports::new();
imports.link_module("adder", add_instance)?;
- // Instantiate the `import` module with the linked imports.
- let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(imports))?;
+ let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?;
- // Call the `main` function, which uses the imported `add` function.
+ // Calling `main` crosses the linked module boundary to `add`.
let main = import_instance.func::<(), i32>(&store, "main")?;
assert_eq!(main.call(&mut store, ())?, 3);
diff --git a/examples/reentrance.rs b/examples/reentrance.rs
index 432fac7..cf57891 100644
--- a/examples/reentrance.rs
+++ b/examples/reentrance.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
const WASM: &str = r#"
@@ -22,11 +22,12 @@ fn main() -> Result<()> {
let module = tinywasm::parse_bytes(&wasm)?;
let mut store = Store::default();
- let call_add_twice = HostFunction::from(&mut store, |mut ctx: FuncContext<'_>, value: i32| {
+ let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| {
+ // FuncContext exposes the active module and its Store to the callback.
let add_one = ctx.module().func::<i32, i32>(ctx.store(), "add_one")?;
- // Use ctx.call for reentrant calls from host functions. Function::call
- // starts a root invocation and cannot preserve the active call stacks.
+ // Use ctx.call while a host callback has an active Wasm invocation.
+ // Function::call only starts top-level invocations.
let value = ctx.call(&add_one, value)?;
ctx.call(&add_one, value)
});
@@ -34,7 +35,7 @@ fn main() -> Result<()> {
let mut imports = Imports::new();
imports.define("host", "call_add_twice", call_add_twice);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let run = instance.func::<i32, i32>(&store, "run")?;
assert_eq!(run.call(&mut store, 40)?, 52);
diff --git a/examples/references.rs b/examples/references.rs
new file mode 100644
index 0000000..b02dd07
--- /dev/null
+++ b/examples/references.rs
@@ -0,0 +1,34 @@
+use anyhow::Result;
+use tinywasm::{FuncRef, HostFunction, Imports, ModuleInstance, Store};
+
+const WASM: &str = r#"
+(module
+ (type $callback (func (param i32) (result i32)))
+ (import "host" "double" (func $double (type $callback)))
+ (elem declare func $double)
+ (func (export "callback") (result funcref)
+ ref.func $double)
+ (func (export "apply") (param funcref i32) (result i32)
+ local.get 1
+ local.get 0
+ ref.cast (ref $callback)
+ call_ref $callback))
+"#;
+
+fn main() -> Result<()> {
+ let mut store = Store::default();
+ let mut imports = Imports::new();
+ // Imports resolve reusable host definitions against each module's runtime types.
+ // HostFunction::instantiate is available when a standalone Function is needed.
+ imports.define("host", "double", HostFunction::from(|_, value: i32| -> tinywasm::Result<i32> { Ok(value * 2) }));
+
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ // Option<FuncRef> maps nullable funcref. Bare FuncRef maps a non-null reference.
+ let callback = instance.func::<(), Option<FuncRef>>(&store, "callback")?.call(&mut store, ())?;
+ let apply = instance.func::<(Option<FuncRef>, i32), i32>(&store, "apply")?;
+
+ assert_eq!(apply.call(&mut store, (callback, 21))?, 42);
+ Ok(())
+}
diff --git a/examples/resumable.rs b/examples/resumable.rs
index 0163414..70b0db1 100644
--- a/examples/resumable.rs
+++ b/examples/resumable.rs
@@ -1,4 +1,4 @@
-use eyre::Result;
+use anyhow::Result;
use tinywasm::{ExecProgress, ModuleInstance, Store};
const WASM: &str = r#"
@@ -29,10 +29,12 @@ fn main() -> Result<()> {
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let count_down = instance.func::<i32, i32>(&store, "count_down")?;
+ // A resumable call returns execution state instead of running to completion.
let mut execution = count_down.call_resumable(&mut store, 10_000)?;
let fuel_per_round = 128;
let mut fuel_rounds = 0;
+ // Each resume call limits one round. std builds also support wall-clock budgets.
let result = loop {
fuel_rounds += 1;
match execution.resume_with_fuel(fuel_per_round)? {
diff --git a/examples/wasm-rust.rs b/examples/rust.rs
index e0b9968..58fd11e 100644
--- a/examples/wasm-rust.rs
+++ b/examples/rust.rs
@@ -1,12 +1,12 @@
use std::hint::black_box;
-use eyre::{Result, eyre};
+use anyhow::{Result, anyhow};
use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
/// Examples of using WebAssembly compiled from Rust with tinywasm.
///
-/// These examples are meant to be run with `cargo run --example wasm-rust <example>`.
-/// For example, `cargo run --example wasm-rust hello`.
+/// These examples are meant to be run with `cargo run --example rust <example>`.
+/// For example, `cargo run --example rust hello`.
///
/// To run these, you first need to compile the Rust examples to WebAssembly:
///
@@ -23,18 +23,19 @@ fn main() -> Result<()> {
pretty_env_logger::init();
if !std::path::Path::new("./examples/rust/out/").exists() {
- return Err(eyre!("No WebAssembly files found. See examples/wasm-rust.rs for instructions."));
+ return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions."));
}
let args = std::env::args().collect::<Vec<_>>();
if args.len() < 2 {
- println!("Usage: cargo run --example wasm-rust <rust_example>");
+ println!("Usage: cargo run --example rust <rust_example>");
println!("Available examples:");
println!(" hello");
println!(" printi32");
- println!(" host_fn");
+ println!(" host-fn");
println!(" fibonacci - calculate fibonacci(30)");
println!(" tinywasm - run printi32 inside of tinywasm inside of itself");
+ println!(" tinywasm-no-std - run a precompiled module inside of no_std tinywasm");
println!(" argon2id - run argon2id(1000, 2, 1)");
return Ok(());
}
@@ -44,9 +45,9 @@ fn main() -> Result<()> {
"printi32" => printi32()?,
"fibonacci" => fibonacci()?,
"tinywasm" => tinywasm()?,
- "tinywasm_no_std" => tinywasm_no_std()?,
+ "tinywasm-no-std" => tinywasm_no_std()?,
"argon2id" => argon2id()?,
- "host_fn" => host_fn()?,
+ "host-fn" => host_fn()?,
"all" => {
println!("Running all examples");
println!("\nhello.wasm:");
@@ -57,11 +58,11 @@ fn main() -> Result<()> {
fibonacci()?;
println!("\ntinywasm.wasm:");
tinywasm()?;
- println!("\ntinywasm_no_std.wasm:");
+ println!("\ntinywasm-no-std.wasm:");
tinywasm_no_std()?;
println!("argon2id.wasm:");
argon2id()?;
- println!("\nhost_fn.wasm:");
+ println!("\nhost-fn.wasm:");
host_fn()?;
}
_ => {}
@@ -75,8 +76,8 @@ fn tinywasm() -> Result<()> {
let mut store = Store::default();
let mut imports = Imports::new();
- imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _x: i32| Ok(())));
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(imports)))?;
+ imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(())));
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?;
let hello = instance.func::<(), ()>(&store, "hello")?;
hello.call(&mut store, black_box(()))?;
@@ -86,12 +87,12 @@ fn tinywasm() -> Result<()> {
}
fn tinywasm_no_std() -> Result<()> {
- let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?;
+ let module = tinywasm::parse_file("./examples/rust/out/tinywasm-no-std.wasm")?;
let mut store = Store::default();
let mut imports = Imports::new();
- imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _x: i32| Ok(())));
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(imports)))?;
+ imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(())));
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?;
let hello = instance.func::<(), ()>(&store, "hello")?;
hello.call(&mut store, black_box(()))?;
@@ -104,7 +105,8 @@ fn hello() -> Result<()> {
let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?;
let mut store = Store::default();
- let print_utf8 = HostFunction::from(&mut store, |ctx: FuncContext<'_>, (ptr, len): (i64, i32)| {
+ // The host callback reads the guest's exported memory through FuncContext.
+ let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| {
let mem = ctx.memory("memory")?;
let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?;
println!("{string}");
@@ -114,10 +116,11 @@ fn hello() -> Result<()> {
let mut imports = Imports::new();
imports.define("env", "print_utf8", print_utf8);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?;
let arg = b"world";
+ // Write the host argument into guest memory before calling the Rust export.
instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?;
let hello = instance.func::<i32, ()>(&store, "hello")?;
hello.call(&mut store, arg.len() as i32)?;
@@ -126,10 +129,10 @@ fn hello() -> Result<()> {
}
fn host_fn() -> Result<()> {
- let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?;
+ let module = tinywasm::parse_file("./examples/rust/out/host-fn.opt.wasm")?;
let mut store = Store::default();
- let bar = HostFunction::from(&mut store, |_: FuncContext<'_>, (left, right): (i64, i32)| {
+ let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| {
assert_eq!(left, 1);
assert_eq!(right, 2);
Ok(left as i32 + right)
@@ -138,7 +141,7 @@ fn host_fn() -> Result<()> {
let mut imports = Imports::new();
imports.define("env", "bar", bar);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let host_fn = instance.func::<(), i32>(&store, "foo")?;
assert_eq!(host_fn.call(&mut store, ())?, 3);
Ok(())
@@ -148,7 +151,7 @@ fn printi32() -> Result<()> {
let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?;
let mut store = Store::default();
- let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, x: i32| {
+ let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| {
println!("{x}");
Ok(())
});
@@ -156,7 +159,7 @@ fn printi32() -> Result<()> {
let mut imports = Imports::new();
imports.define("env", "printi32", printi32);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?;
add_and_print.call(&mut store, (1, 2))?;
diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml
index efce27a..74d38e7 100644
--- a/examples/rust/Cargo.toml
+++ b/examples/rust/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "rust-wasm-examples"
-edition = "2021"
+edition = "2024"
publish = false
# treat this as an independent package
@@ -11,7 +11,7 @@ name = "hello"
path = "src/hello.rs"
[[bin]]
-name = "host_fn"
+name = "host-fn"
path = "src/host_fn.rs"
[[bin]]
@@ -23,7 +23,7 @@ name = "tinywasm"
path = "src/tinywasm.rs"
[[bin]]
-name = "tinywasm_no_std"
+name = "tinywasm-no-std"
path = "src/tinywasm_no_std.rs"
[[bin]]
@@ -35,17 +35,17 @@ name = "argon2id"
path = "src/argon2id.rs"
[dependencies]
-argon2 = { version = "0.5" }
+argon2 = { version = "0.6", default-features = false, features = ["alloc"] }
dlmalloc = { version = "0.2", features = ["global"] }
-tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [
- "archive",
- "parser"
-] }
+tinywasm = { path = "../../crates/tinywasm", default-features = false, features = ["archive", "parser"] }
[features]
default = ["std"]
std = ["tinywasm/std"]
+[lints.clippy]
+missing_safety_doc = "allow"
+
[profile.wasm]
inherits = "release"
opt-level = 3
diff --git a/examples/rust/README.md b/examples/rust/README.md
index 8d3178a..305a29c 100644
--- a/examples/rust/README.md
+++ b/examples/rust/README.md
@@ -1,9 +1,9 @@
# WebAssembly Rust Examples
This is a separate crate that generates WebAssembly from Rust code.
-It is used by the `wasm-rust` example.
+It is used by the `rust` example.
Requires the `wasm32-unknown-unknown` target to be installed.
-To build the example artifacts used by `cargo run --example wasm-rust -- <name>`, run `./examples/rust/build.sh`.
+To build the example artifacts used by `cargo run --example rust -- <name>`, run `./examples/rust/build.sh`.
That script also requires `binaryen` and `wabt` to be installed.
diff --git a/examples/rust/build.sh b/examples/rust/build.sh
index db4cb43..e19b8b8 100755
--- a/examples/rust/build.sh
+++ b/examples/rust/build.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
cd "$(dirname "$0")" || exit
-bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id")
+bins=("host-fn" "hello" "fibonacci" "print" "tinywasm" "argon2id")
exclude_wat=("tinywasm")
out_dir="./target/wasm32-unknown-unknown/wasm"
dest_dir="out"
@@ -12,9 +12,14 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl
# ensure out dir exists
mkdir -p "$dest_dir"
+# Keep the embedded archive synchronized with the current archive version and instruction layout.
+cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \
+ compile "src/print.wasm" --output "src/print.twasm" --force || exit
+
# build no_std
-cargo build --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features
-cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/"
+RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm-no-std --no-default-features
+cp "$out_dir/tinywasm-no-std.wasm" "$dest_dir/"
+wasm-opt "$dest_dir/tinywasm-no-std.wasm" -o "$dest_dir/tinywasm-no-std.opt.wasm" -O3 $wasmopt_features
for bin in "${bins[@]}"; do
RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin"
diff --git a/examples/rust/src/hello.rs b/examples/rust/src/hello.rs
index 3d9f400..06ef5c9 100644
--- a/examples/rust/src/hello.rs
+++ b/examples/rust/src/hello.rs
@@ -19,10 +19,12 @@ pub unsafe extern "C" fn arg_size() -> i32 {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn hello(len: i32) {
- let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap();
- let res = format!("Hello, {}!", arg).as_bytes().to_vec();
+ unsafe {
+ let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap();
+ let res = format!("Hello, {}!", arg).as_bytes().to_vec();
- let len = res.len() as i32;
- let ptr = res.leak().as_ptr() as i64;
- print_utf8(ptr, len);
+ let len = res.len() as i32;
+ let ptr = res.leak().as_ptr() as i64;
+ print_utf8(ptr, len);
+ }
}
diff --git a/examples/rust/src/print.rs b/examples/rust/src/print.rs
index d2934f0..991ea4a 100644
--- a/examples/rust/src/print.rs
+++ b/examples/rust/src/print.rs
@@ -7,5 +7,7 @@ unsafe extern "C" {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) {
- printi32(lh + rh);
+ unsafe {
+ printi32(lh + rh);
+ }
}
diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm
new file mode 100644
index 0000000..8ad32e3
--- /dev/null
+++ b/examples/rust/src/print.twasm
Binary files differ
diff --git a/examples/rust/src/tinywasm.rs b/examples/rust/src/tinywasm.rs
index 70de73e..b0a2e47 100644
--- a/examples/rust/src/tinywasm.rs
+++ b/examples/rust/src/tinywasm.rs
@@ -15,7 +15,7 @@ fn run() -> tinywasm::Result<()> {
let module = tinywasm::parse_stream(&include_bytes!("./print.wasm")[..])?;
let mut store = tinywasm::Store::default();
- let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| {
+ let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| {
unsafe { printi32(v) }
Ok(())
});
@@ -23,7 +23,7 @@ fn run() -> tinywasm::Result<()> {
let mut imports = tinywasm::Imports::new();
imports.define("env", "printi32", printi32);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?;
add_and_print.call(&mut store, (1, 2))?;
Ok(())
diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs
index c1dd910..a70abb9 100644
--- a/examples/rust/src/tinywasm_no_std.rs
+++ b/examples/rust/src/tinywasm_no_std.rs
@@ -1,7 +1,7 @@
#![no_main]
#![no_std]
use dlmalloc::GlobalDlmalloc;
-use tinywasm::{FuncContext, HostFunction, ModuleInstance};
+use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance};
extern crate alloc;
@@ -28,17 +28,15 @@ fn run() -> tinywasm::Result<()> {
let mut store = tinywasm::Store::default();
let mut imports = tinywasm::Imports::new();
- let res = tinywasm::parser::Parser::new().parse_module_bytes(include_bytes!("./print.wasm"))?;
- let twasm = res.serialize_twasm()?;
- let module = tinywasm::parse_bytes(&twasm)?;
+ let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?;
- let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| {
+ let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| {
unsafe { printi32(v) }
Ok(())
});
imports.define("env", "printi32", printi32);
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?;
add_and_print.call(&mut store, (1, 2))?;
Ok(())
diff --git a/examples/simple2.rs b/examples/simple2.rs
deleted file mode 100644
index da7def7..0000000
--- a/examples/simple2.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use eyre::Result;
-use tinywasm::{ModuleInstance, Store};
-
-const WASM: &str = r#"
-(module
- (func $return (param $lhs i32) (param $rhs i64) (result i32 i64)
- local.get $lhs
- local.get $rhs)
- (export "return" (func $return)))
-"#;
-
-fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
- let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- let add = instance.func::<(i32, i64), (i32, i64)>(&store, "return")?;
-
- assert_eq!(add.call(&mut store, (1, 2))?, (1, 2));
- Ok(())
-}
diff --git a/examples/state.rs b/examples/state.rs
new file mode 100644
index 0000000..ecc74fd
--- /dev/null
+++ b/examples/state.rs
@@ -0,0 +1,51 @@
+use anyhow::Result;
+use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
+
+const WASM: &str = r#"
+(module
+ (import "host" "record" (func $record (param i32) (result i32)))
+
+ (func (export "run") (result i32)
+ i32.const 20
+ call $record
+ drop
+ i32.const 22
+ call $record))
+"#;
+
+#[derive(Default)]
+struct State {
+ calls: u32,
+ total: i32,
+}
+
+// Requires the `parser`, `std`, and `state` features.
+// Run with `cargo run --example state` from the repository root.
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+
+ // State is owned by the Store and is available to its host-function calls.
+ let mut store = Store::default().with_state(State::default());
+
+ let record = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| {
+ // FuncContext accesses the active Store without captured shared state.
+ let state = ctx.state_mut::<State>().expect("State was added to the store");
+ state.calls += 1;
+ state.total += value;
+ Ok(state.total)
+ });
+
+ // The import definition captures no state and can be reused with other stores.
+ let mut imports = Imports::new();
+ imports.define("host", "record", record);
+
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ let run = instance.func::<(), i32>(&store, "run")?;
+
+ assert_eq!(run.call(&mut store, ())?, 42);
+
+ // Host code can inspect the same state after guest execution.
+ assert_eq!(store.state::<State>().unwrap().calls, 2);
+ Ok(())
+}
diff --git a/examples/wasi_p1.rs b/examples/wasi_p1.rs
new file mode 100644
index 0000000..22024dc
--- /dev/null
+++ b/examples/wasi_p1.rs
@@ -0,0 +1,42 @@
+use anyhow::Result;
+use tinywasm::{ModuleInstance, Store};
+use tinywasm_wasi::p1::{WasiCtx, imports};
+
+const WASM: &str = r#"
+(module
+ (import "wasi_snapshot_preview1" "fd_write"
+ (func $fd_write (param i32 i32 i32 i32) (result i32)))
+ (memory (export "memory") 1)
+ (data (i32.const 16) "Hello from WASI Preview 1!\n")
+
+ (func (export "_start")
+ i32.const 0
+ i32.const 16
+ i32.store
+ i32.const 4
+ i32.const 27
+ i32.store
+
+ i32.const 1
+ i32.const 0
+ i32.const 1
+ i32.const 8
+ call $fd_write
+ drop))
+"#;
+
+// Requires TinyWasm's `parser`, `std`, and `state` features.
+// Run with `cargo run --example wasi_p1` from the repository root.
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+
+ // The host explicitly chooses what the guest can observe.
+ let wasi = WasiCtx::new().with_args(["wasi_p1.wasm", "example"])?.with_env([("MODE", "example")])?.inherit_stdio();
+ let mut store = Store::default().with_state(wasi);
+
+ // Preview 1 imports are reusable because their state comes from the Store.
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?;
+ instance.func::<(), ()>(&store, "_start")?.call(&mut store, ())?;
+ Ok(())
+}