From d0c74255f9d6c57a243cf34037af0e8f371504b3 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sat, 8 Aug 2026 15:43:26 +0200 Subject: feat: initial support for the webassembly gc proposal (#50) Signed-off-by: Henry --- Cargo.lock | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index 680b8fb..df0e601 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -171,9 +171,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.5" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" dependencies = [ "clap_builder", "clap_derive", @@ -181,9 +181,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.5" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" dependencies = [ "anstream", "anstyle", @@ -193,9 +193,9 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f84a88507dbd05c695f2cb5e8558e747179134005e9893882dec964190ed89" +checksum = "3be2ad0423bdbbb0e25bc89add796f3559706d4a95e1bc98e4d9662a957b6a19" dependencies = [ "clap", ] @@ -690,9 +690,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.16" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasm-testsuite" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fd62746cfcc437a1bdadbe75bf29df08d5a3ae67336e4ac6cea37e0194fce47" +checksum = "9d451d78ea8b19bbed461065802e8797edf21cfb6aa2e9cbeea0aede114f8fb4" dependencies = [ "include_dir", "wast", @@ -1071,18 +1071,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.55" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.55" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" dependencies = [ "proc-macro2", "quote", -- cgit v1.3.1 From 9893a51d2712f82a2ee57316a66bc26500eb3fdd Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 9 Aug 2026 16:11:57 +0200 Subject: feat: add reusable host imports and simplify function calls - make host definitions reusable across stores with gc-aware import linking - reorganize function calls, resumable execution, and typed value handling - expand typed tuples to arity 20 and update parser and store APIs Signed-off-by: Henry --- CHANGELOG.md | 9 +- Cargo.lock | 16 +- crates/cli/src/wast_runner.rs | 20 +- crates/parser/README.md | 6 +- crates/parser/src/lib.rs | 20 +- crates/tinywasm/benches/argon2id.rs | 2 +- crates/tinywasm/benches/fibonacci.rs | 2 +- crates/tinywasm/benches/tinywasm.rs | 8 +- crates/tinywasm/benches/tinywasm_modes.rs | 6 +- crates/tinywasm/src/func.rs | 892 --------------------- crates/tinywasm/src/func/context.rs | 151 ++++ crates/tinywasm/src/func/host.rs | 259 ++++++ crates/tinywasm/src/func/mod.rs | 201 +++++ crates/tinywasm/src/func/resume.rs | 265 ++++++ crates/tinywasm/src/func/values.rs | 201 +++++ crates/tinywasm/src/imports.rs | 113 +-- crates/tinywasm/src/instance.rs | 31 +- crates/tinywasm/src/interpreter/executor.rs | 20 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 116 ++- crates/tinywasm/src/lib.rs | 6 +- crates/tinywasm/src/reference.rs | 22 +- crates/tinywasm/src/store/const_expr.rs | 194 +++++ crates/tinywasm/src/store/function.rs | 4 +- crates/tinywasm/src/store/global.rs | 19 + crates/tinywasm/src/store/mod.rs | 407 +++------- crates/tinywasm/src/store/state.rs | 21 +- crates/tinywasm/tests/host_func_signature_check.rs | 83 +- crates/tinywasm/tests/host_import_arg_order.rs | 17 +- crates/tinywasm/tests/import_linking.rs | 4 +- crates/tinywasm/tests/imported_table_init.rs | 4 +- crates/tinywasm/tests/internal_refs.rs | 11 +- crates/tinywasm/tests/memory_backends.rs | 2 +- crates/tinywasm/tests/store_ownership.rs | 2 +- crates/tinywasm/tests/typed_globals.rs | 2 +- examples/doom/src/runtime.rs | 22 +- examples/funcref_callbacks.rs | 21 +- examples/linking.rs | 2 +- examples/reentrance.rs | 4 +- examples/rust/src/tinywasm.rs | 4 +- examples/rust/src/tinywasm_no_std.rs | 6 +- examples/wasm-rust.rs | 20 +- 41 files changed, 1812 insertions(+), 1403 deletions(-) delete mode 100644 crates/tinywasm/src/func.rs create mode 100644 crates/tinywasm/src/func/context.rs create mode 100644 crates/tinywasm/src/func/host.rs create mode 100644 crates/tinywasm/src/func/mod.rs create mode 100644 crates/tinywasm/src/func/resume.rs create mode 100644 crates/tinywasm/src/func/values.rs create mode 100644 crates/tinywasm/src/store/const_expr.rs (limited to 'Cargo.lock') diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ef6fb5..4ae416e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- `HostFunction` is now a reusable definition, and module instantiation borrows `Imports` so host imports can be shared across stores. +- Host function callbacks now require `Send + Sync` so the same definition can be used safely with multiple stores. +- Typed function tuples now support up to 20 parameters or results. `WasmTupleChain` is deprecated. Use untyped functions for larger signatures. - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. - Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. @@ -27,7 +30,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking Changes -- Renamed `ModuleInstanceAddr` to `ModuleInstanceId` for consistency. +- `HostFunction::from` and `HostFunction::from_untyped` no longer take a `Store` and now return reusable `HostFunction` definitions +- `ModuleInstance::instantiate` and `instantiate_no_start` now borrow `Imports`. +- `Store::id` now returns `u32` instead of `usize`. +- `Parser::new` now takes `ParserOptions`, use `Parser::default()` for default settings. `Parser::with_options` was removed. +- Renamed `ModuleInstanceAddr` to `ModuleInstanceId`. - 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 }`. diff --git a/Cargo.lock b/Cargo.lock index df0e601..5312e7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,9 +128,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.0" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9" +checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" dependencies = [ "find-msvc-tools", "shlex", @@ -369,9 +369,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" [[package]] name = "float-cmp" @@ -840,18 +840,18 @@ 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", diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index ad1742e..2ca622d 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -177,20 +177,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 { @@ -235,7 +235,7 @@ impl WastRunner { 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 module_instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)) .expect("failed to instantiate module"); (name, module_instance) }) @@ -331,7 +331,7 @@ impl WastRunner { 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))?; + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; return Ok(()); } wast::WastExecute::Get { .. } => panic!("get not supported"), @@ -376,7 +376,7 @@ impl WastRunner { 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)) + ModuleInstance::instantiate(&mut store, &module, Some(&imports)) }); match res { Err(err) => test_group.add_result( diff --git a/crates/parser/README.md b/crates/parser/README.md index 05c2af2..cf1a6c4 100644 --- a/crates/parser/README.md +++ b/crates/parser/README.md @@ -16,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")?; @@ -27,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/lib.rs b/crates/parser/src/lib.rs index 5439558..fe968d8 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -90,6 +90,11 @@ impl Default for ParserOptions { } 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. @@ -152,13 +157,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 } } @@ -352,17 +352,17 @@ impl TryFrom> for Module { /// Parse a module from bytes pub fn parse_bytes(wasm: &[u8]) -> Result { - 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 + Clone) -> Result { - 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 { - Parser::new().parse_module_stream(stream) + Parser::default().parse_module_stream(stream) } diff --git a/crates/tinywasm/benches/argon2id.rs b/crates/tinywasm/benches/argon2id.rs index dbd86e5..d2845c5 100644 --- a/crates/tinywasm/benches/argon2id.rs +++ b/crates/tinywasm/benches/argon2id.rs @@ -6,7 +6,7 @@ use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/argon2id.wasm"); fn argon2id_parse() -> Result { - 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/crates/tinywasm/benches/fibonacci.rs index e0737da..1bf0791 100644 --- a/crates/tinywasm/benches/fibonacci.rs +++ b/crates/tinywasm/benches/fibonacci.rs @@ -6,7 +6,7 @@ use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/fibonacci.wasm"); fn fibonacci_parse() -> Result { - 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/tinywasm.rs b/crates/tinywasm/benches/tinywasm.rs index 67db886..3560d3c 100644 --- a/crates/tinywasm/benches/tinywasm.rs +++ b/crates/tinywasm/benches/tinywasm.rs @@ -1,13 +1,13 @@ 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, Store, types}; use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm"); fn tinywasm_parse() -> Result { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); let data = parser.parse_module_bytes(WASM)?; Ok(data) } @@ -26,8 +26,8 @@ fn tinywasm_run(module: &Module) -> Result<()> { 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/crates/tinywasm/benches/tinywasm_modes.rs index ed89b7b..6c1badf 100644 --- a/crates/tinywasm/benches/tinywasm_modes.rs +++ b/crates/tinywasm/benches/tinywasm_modes.rs @@ -10,7 +10,7 @@ const TIME_BUDGET_PER_ROUND: core::time::Duration = core::time::Duration::from_m const BENCH_MEASUREMENT_TIME: core::time::Duration = core::time::Duration::from_secs(10); fn tinywasm_parse() -> Result { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); Ok(parser.parse_module_bytes(WASM)?) } @@ -21,9 +21,9 @@ fn setup_typed_func(module: &Module, engine: Option) -> 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/tinywasm/src/func.rs b/crates/tinywasm/src/func.rs deleted file mode 100644 index c4409cd..0000000 --- a/crates/tinywasm/src/func.rs +++ /dev/null @@ -1,892 +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, rc::Rc, 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 - #[inline] - pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result> { - #[inline] - fn call_inner(func: &Function, store: &mut Store, params: &[WasmValue]) -> Result> { - 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, - store.state.get_canonical_func_type(func_instance.type_addr), - ) - } - - self.item.validate_store(store)?; - validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; - - store.enter_execution()?; - let result = call_inner(self, store, params); - store.exit_execution(); - - if results_may_gc && let Ok(values) = &result { - store.state.pin_host_values(values); - } - - result - } - - /// 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> { - #[inline] - fn call_resumable_inner( - func: &Function, - store: &mut Store, - params: &[WasmValue], - ) -> Result { - 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)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; - - store.enter_execution()?; - let result = call_resumable_inner(self, store, params); - store.exit_execution(); - - let state = result?; - if results_may_gc && let FuncExecutionState::Completed { result: Some(values) } = &state { - store.state.pin_host_values(values); - } - Ok(FuncExecution { store, state }) - } -} - -#[derive(Clone, PartialEq, Eq)] -/// Progress for fuel-limited function execution. -pub enum ExecProgress { - /// 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 { - /// 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> { - (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::(&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> + 'static, - ) -> Function { - let type_addr = store.register_host_type(ty); - let addr = store.add_func(FunctionInstance { - type_addr, - gc: store.state.func_gc_metadata(type_addr), - kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(func) })), - }); - Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } - } - - /// 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::(&store, "call")?; - /// # assert_eq!(call.call(&mut store, 41)?, 42); - /// # Ok(()) - /// # } - /// ``` - pub fn from(store: &mut Store, func: impl Fn(FuncContext<'_>, P) -> Result + 'static) -> Function - where - P: FromWasmValues + ToWasmTypes, - R: IntoWasmValues + ToWasmTypes, - { - let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result> { - 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, - gc: store.state.func_gc_metadata(type_addr), - kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(inner_func) })), - }); - Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } - } -} - -pub(crate) type HostFuncInner = Box, &[WasmValue]) -> Result>>; - -/// 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)) - .clone() - } - - /// Get a memory export. - pub fn memory(&self, name: &str) -> Result { - self.module().memory(name) - } - - /// Get any exported extern value by name. - pub fn extern_item(&self, name: &str) -> Result { - self.module().extern_item(name) - } - - /// Get a table export. - pub fn table(&self, name: &str) -> Result { - self.module().table(name) - } - - /// Get the value of a global export. - pub fn global_get(&self, name: &str) -> Result { - self.module().global_get(self.store, name) - } - - /// Get a global export. - pub fn global(&self, name: &str) -> Result { - 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> { - 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(); - let result = match func_instance.kind { - crate::store::FunctionKind::Host(host_func) => { - let result = - host_func.call(FuncContext { store: &mut *self.store, module_id: func.module_id }, args)?; - 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, - self.store.state.get_canonical_func_type(func_instance.type_addr), - ) - } - }; - if func_instance.gc.results - && let Ok(values) = &result - { - self.store.state.pin_host_values(values); - } - result - } - - /// Call a typed function from within the current host-function invocation. - /// - /// See [`Self::call_untyped`] for reentrancy and resumable-execution - /// limitations. - pub fn call(&mut self, func: &FunctionTyped, params: P) -> Result - where - P: IntoWasmValues, - R: FromWasmValues, - { - R::from_wasm_values(&self.call_untyped(&func.func, ¶ms.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> }, -} - -/// 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, -} - -impl<'store> FuncExecution<'store> { - fn resume( - &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, - ) -> Result>> { - 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 func = self.store.state.get_func(root_func_addr); - let result_ty = func.type_addr; - let results_may_gc = func.gc.results; - self.state = FuncExecutionState::Completed { result: None }; - let values = collect_call_results( - &mut self.store.value_stack, - &self.store.state, - self.store.state.get_canonical_func_type(result_ty), - )?; - if results_may_gc { - self.store.state.pin_host_values(&values); - } - Ok(ExecProgress::Completed(values)) - } - crate::interpreter::ExecState::Suspended(callframe) => { - let FuncExecutionState::Running { exec_state, .. } = &mut self.state else { - 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>> { - 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>> { - 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, -) -> Result> { - let expected = store.state.get_canonical_func_type(type_addr); - if result.len() == expected.results().len() - && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) - { - return Ok(result); - } - - Err(Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) -} - -fn collect_call_results( - value_stack: &mut ValueStack, - state: &crate::store::State, - func_ty: &FuncType, -) -> Result> { - debug_assert!(value_stack.len() >= func_ty.results().len()); // m values are on the top of the stack (Ensured by validation) - let results = func_ty.results(); - let mut res = vec![WasmValue::I32(0); results.len()]; - for (i, &ty) in results.iter().enumerate().rev() { - res[i] = value_stack.pop_wasmvalue(state, ty); - } - Ok(res) -} - -pub trait IntoWasmValues { - fn into_wasm_values(self) -> Vec; -} - -pub trait FromWasmValues: Sized { - fn from_wasm_values(values: &[WasmValue]) -> Result; -} - -impl FunctionTyped { - /// Call a typed function - pub fn call(&self, store: &mut Store, params: P) -> Result { - // Convert params into Vec - let wasm_values = params.into_wasm_values(); - - // Call the underlying WASM function - let result = self.func.call(store, &wasm_values)?; - - // Convert the Vec 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> { - 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> { - 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> { - 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 { - vec![self.into()] - } - } - - impl FromWasmValues for $T { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result { - 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,)+ - { - #[allow(non_snake_case)] - #[inline] - fn into_wasm_values(self) -> Vec { - let ($($T,)+) = self; - vec![$($T.into(),)+] - } - } - - impl<$($T),+> FromWasmValues for ($($T,)+) - where - $($T: TryFrom,)+ - { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result { - 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, - 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::(&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); - -impl WasmTupleChain { - /// 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 From<(T1, T2)> for WasmTupleChain { - fn from((left, right): (T1, T2)) -> Self { - Self::new(left, right) - } -} - -impl ToWasmTypes for WasmTupleChain { - 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 IntoWasmValues for WasmTupleChain { - #[inline] - fn into_wasm_values(self) -> Vec { - 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 FromWasmValues for WasmTupleChain { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result { - 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 { - vec![] - } -} - -impl FromWasmValues for () { - #[inline] - fn from_wasm_values(_values: &[WasmValue]) -> Result { - Ok(()) - } -} diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs new file mode 100644 index 0000000..95a2cec --- /dev/null +++ b/crates/tinywasm/src/func/context.rs @@ -0,0 +1,151 @@ +use alloc::vec::Vec; +use tinywasm_types::{ModuleInstanceId, WasmValue}; + +use crate::{Error, FromWasmValues, Function, FunctionTyped, IntoWasmValues, Result}; + +/// 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)) + .clone() + } + + /// Get a memory export. + pub fn memory(&self, name: &str) -> Result { + self.module().memory(name) + } + + /// Get any exported extern value by name. + pub fn extern_item(&self, name: &str) -> Result { + self.module().extern_item(name) + } + + /// Get a table export. + pub fn table(&self, name: &str) -> Result { + self.module().table(name) + } + + /// Get the value of a global export. + pub fn global_get(&self, name: &str) -> Result { + self.module().global_get(self.store, name) + } + + /// Get a global export. + pub fn global(&self, name: &str) -> Result { + 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> { + if !self.store.execution_active { + return Err(Error::other("FuncContext::call requires an active host-function invocation")); + } + + func.item.validate_store(self.store)?; + func.validate_params(self.store, args)?; + + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.call_untyped(self.store, args, call_stack_base, value_stack_base) + } + + /// Call a typed function from within the current host-function invocation. + /// + /// See [`Self::call_untyped`] for reentrancy and resumable-execution + /// limitations. + pub fn call(&mut self, func: &FunctionTyped, params: P) -> Result + 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 func_instance = self.store.state.get_func(func.func.addr()).clone(); + if matches!(&func_instance.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::>(); + let results = self.call_untyped(&func.func, ¶ms)?; + let mut values = results.into_iter(); + let result = R::from_wasm_values(&mut values)?; + return if values.next().is_none() { + Ok(result) + } else { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + }; + } + + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.func.call_typed(self.store, &func_instance, params.into_wasm_values(), call_stack_base, value_stack_base) + } +} + +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 } + } +} diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs new file mode 100644 index 0000000..83b17f9 --- /dev/null +++ b/crates/tinywasm/src/func/host.rs @@ -0,0 +1,259 @@ +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue}; + +use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; +use crate::{Function, FunctionInstance, Result, Store}; + +/// A reusable host function definition. +#[derive(Clone)] +pub struct HostFunction(Arc); + +impl HostFunction { + fn instantiate_canonical(&self, store: &mut Store, ty: &FuncType) -> Function { + let type_addr = store.register_host_type(ty); + let addr = store.add_func(FunctionInstance { + type_addr, + gc: store.state.func_gc_metadata(type_addr), + kind: crate::store::FunctionKind::Host(self.clone()), + }); + Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } + } + + /// Instantiates this definition after resolving the importing module's types. + pub(crate) fn instantiate_for_import(&self, store: &mut Store, type_addrs: &[TypeAddr]) -> Result { + let resolve = |ty: WasmType| -> Result { + 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) + .expect("canonical type addresses fit in references"), + )) + }; + let params = self.0.ty.params().iter().copied().map(resolve).collect::>>()?; + let results = self.0.ty.results().iter().copied().map(resolve).collect::>>()?; + Ok(self.instantiate_canonical(store, &FuncType::new(¶ms, &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], + ) -> Result> { + let result = match &self.0.callback { + HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args), + HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args), + }?; + let expected = store.state.get_canonical_func_type(type_addr); + if result.len() == expected.results().len() + && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) + { + Ok(result) + } else { + Err(crate::Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) + } + } + + /// 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 uses a store-specific reference type + /// that is not registered in `store`. + /// + /// ## 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)?; + /// + /// assert_eq!(function.call(&mut store, &[WasmValue::I32(41)])?, [WasmValue::I32(42)]); + /// # Ok(()) + /// # } + /// ``` + pub fn instantiate(&self, store: &mut Store) -> Result { + if self + .0 + .ty + .params() + .iter() + .chain(self.0.ty.results()) + .filter_map(|ty| match ty { + WasmType::Ref(ty) => ty.type_index(), + _ => None, + }) + .any(|type_addr| type_addr as usize >= store.state.canonical_types.len()) + { + return Err(crate::Error::other("host function signature contains a concrete type from another store")); + } + Ok(self.instantiate_canonical(store, &self.0.ty)) + } + + /// 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| { + /// 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::(&store, "call")?; + /// # assert_eq!(call.call(&mut store, 41)?, 42); + /// # Ok(()) + /// # } + /// ``` + pub fn from_untyped( + ty: &FuncType, + func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync + 'static, + ) -> Self { + Self(Arc::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::(&store, "call")?; + /// # assert_eq!(call.call(&mut store, 41)?, 42); + /// # Ok(()) + /// # } + /// ``` + pub fn from(func: impl Fn(FuncContext<'_>, P) -> Result + Send + Sync + 'static) -> Self + where + P: FromWasmValues + ToWasmTypes + 'static, + R: IntoWasmValues + ToWasmTypes + 'static, + { + let ty = FuncType::new(&P::wasm_types(), &R::wasm_types()); + let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData }; + Self(Arc::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) })) + } +} + +struct HostFunctionInner { + ty: FuncType, + callback: HostCallback, +} + +enum HostCallback { + Untyped(Box), + Typed(Box), +} + +type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync; + +pub(crate) trait TypedHostCallback: Send + Sync { + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result>; + fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>; +} + +struct TypedHostCallbackImpl { + func: F, + marker: core::marker::PhantomData R>, +} + +impl TypedHostCallback for TypedHostCallbackImpl +where + F: Fn(FuncContext<'_>, P) -> Result + Send + Sync, + P: FromWasmValues, + R: IntoWasmValues, +{ + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result> { + let mut values = args.iter().copied(); + let params = P::from_wasm_values(&mut values)?; + if values.next().is_some() { + return Err(crate::Error::other("typed conversion did not consume all WebAssembly values")); + } + Ok((self.func)(ctx, params)?.into_wasm_values().collect()) + } + + fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()> { + let params = store.state.get_canonical_func_type(type_addr).params(); + let base = store.value_stack.base_before(params.iter().collect()); + let mut values = store.value_stack.wasm_values(&store.state, params, base, true); + let params = P::from_wasm_values(&mut values).and_then(|params| { + if values.next().is_some() { + Err(crate::Error::other("typed conversion did not consume all WebAssembly values")) + } else { + Ok(params) + } + }); + drop(values); + store.value_stack.truncate_to_base(base); + let params = params?; + let result = (self.func)(FuncContext { store, module_id }, params)?; + store.push_typed_values::(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..34a1938 --- /dev/null +++ b/crates/tinywasm/src/func/mod.rs @@ -0,0 +1,201 @@ +use crate::interpreter::stack::{CallFrame, StackBase}; +use crate::reference::StoreItem; +use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; +use alloc::{format, vec::Vec}; +use core::hint::cold_path; +use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId, WasmValue}; + +mod context; +mod host; +mod resume; +mod values; +pub use context::FuncContext; +pub use host::HostFunction; +pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped}; +#[allow(deprecated)] +pub use values::WasmTupleChain; +pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes}; + +/// 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, +} + +impl Function { + #[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())) + } + + /// Call a function (Invocation) + /// + /// See + #[inline] + pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result> { + self.item.validate_store(store)?; + self.validate_params(store, params)?; + + store.enter_execution()?; + store.call_stack.clear(); + store.value_stack.clear(); + let result = self.call_untyped(store, params, 0, StackBase::default()); + store.exit_execution(); + result + } + + fn validate_params(&self, store: &Store, params: &[WasmValue]) -> Result<()> { + let func_ty = store.state.get_func_type(self.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() + ))); + } + + if !func_ty.params().iter().zip(params).all(|(ty, param)| store.state.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::>() + ))); + #[cfg(not(feature = "debug"))] + return Err(Error::Other("param type mismatch".into())); + } + Ok(()) + } + + #[inline] + fn call_untyped( + &self, + store: &mut Store, + params: &[WasmValue], + call_stack_base: u32, + value_stack_base: StackBase, + ) -> Result> { + let instance = store.state.get_func(self.addr()); + let type_addr = instance.type_addr; + let results_may_gc = instance.gc.results; + let result = match &instance.kind { + crate::store::FunctionKind::Host(host) => { + let host = host.clone(); + host.call_values(store, self.module_id, type_addr, params) + } + crate::store::FunctionKind::Wasm(wasm) => { + let wasm_params = wasm.func.params; + let wasm_locals = wasm.func.locals; + let locals_base = + store.value_stack.enter_wasm_call(params, wasm_params, wasm_locals, 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); + })?; + let result_types = store.state.get_canonical_func_type(type_addr).results(); + Ok(store.value_stack.pop_wasmvalues(&store.state, result_types)) + } + }; + if results_may_gc && let Ok(values) = &result { + store.state.pin_host_values(values); + } + result + } + + fn prepare_typed( + &self, + store: &mut Store, + instance: &FunctionInstance, + params: impl Iterator, + stack_base: StackBase, + ) -> Result> { + store.push_typed_values::(instance.type_addr, params, stack_base)?; + match &instance.kind { + crate::store::FunctionKind::Wasm(wasm) => { + let locals_base = store + .value_stack + .enter_locals(&wasm.func.params, &wasm.func.locals) + .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; + Ok(Some(CallFrame::new(self.addr(), locals_base, wasm.func.locals))) + } + crate::store::FunctionKind::Host(host) => { + host.typed_callback() + .expect("typed host function") + .call_stack(store, self.module_id, instance.type_addr) + .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; + Ok(None) + } + } + } + + #[inline] + fn call_typed( + &self, + store: &mut Store, + instance: &FunctionInstance, + params: impl Iterator, + call_stack_base: u32, + value_stack_base: StackBase, + ) -> Result { + if let Some(callframe) = self.prepare_typed(store, instance, params, value_stack_base)? { + 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(instance.type_addr, value_stack_base, instance.gc.results) + } +} + +/// 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 { + /// The underlying function handle + pub func: Function, + pub(crate) marker: core::marker::PhantomData<(P, R)>, +} + +impl FunctionTyped { + /// Call a typed function + pub fn call(&self, store: &mut Store, params: P) -> Result { + self.func.item.validate_store(store)?; + let func = store.state.get_func(self.func.addr()).clone(); + if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::>(); + let result = self.func.call(store, ¶ms)?; + let mut values = result.into_iter(); + let result = R::from_wasm_values(&mut values)?; + return if values.next().is_none() { + Ok(result) + } else { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + }; + } + + store.enter_execution()?; + let result: Result = { + store.call_stack.clear(); + store.value_stack.clear(); + self.func.call_typed(store, &func, 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..a71be32 --- /dev/null +++ b/crates/tinywasm/src/func/resume.rs @@ -0,0 +1,265 @@ +use alloc::vec::Vec; +use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; + +use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; +use crate::interpreter::stack::{CallFrame, StackBase}; +use crate::{Error, InterpreterRuntime, Result, Store, Trap}; + +#[derive(Clone, PartialEq, Eq)] +/// Progress for fuel-limited function execution. +pub enum ExecProgress { + /// 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> { + store: &'store mut Store, + state: FuncExecutionState, +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +enum FuncExecutionState { + Running { callframe: CallFrame, root_func_addr: FuncAddr }, + Completed(Option), +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +enum CallResult { + Stack { type_addr: TypeAddr, pin_refs: bool }, + Values(Vec), +} + +/// 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, +} + +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], + ) -> Result> { + self.item.validate_store(store)?; + self.validate_params(store, params)?; + let results_may_gc = store.state.get_func(self.addr()).gc.results; + + store.enter_execution()?; + let result: Result = (|| { + let func_instance = store.state.get_func(self.addr()).clone(); + match &func_instance.kind { + crate::store::FunctionKind::Host(host_func) => { + let result = + host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params)?; + Ok(FuncExecutionState::Completed(Some(CallResult::Values(result)))) + } + crate::store::FunctionKind::Wasm(wasm_func) => { + store.call_stack.clear(); + store.value_stack.clear(); + let locals = wasm_func.func.locals; + let locals_base = store.value_stack.enter_wasm_call( + params, + wasm_func.func.params, + locals, + StackBase::default(), + )?; + let callframe = CallFrame::new(self.addr(), locals_base, locals); + + Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) + } + } + })(); + store.exit_execution(); + + let state = result?; + if results_may_gc && let FuncExecutionState::Completed(Some(CallResult::Values(values))) = &state { + store.state.pin_host_values(values); + } + Ok(FuncExecution { store, state }) + } +} + +impl<'store> FuncExecution<'store> { + fn resume_raw( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result, + ) -> Result> { + let (callframe, root_func_addr) = match &mut self.state { + FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), + FuncExecutionState::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(); + + match result? { + crate::interpreter::ExecState::Completed => { + let func = self.store.state.get_func(root_func_addr); + let result_ty = func.type_addr; + let results_may_gc = func.gc.results; + self.state = FuncExecutionState::Completed(None); + Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty, pin_refs: results_may_gc })) + } + crate::interpreter::ExecState::Suspended(callframe) => { + let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { + unreachable!("invalid function execution state") + }; + *current = callframe; + Ok(ExecProgress::Suspended) + } + } + } + + fn resume( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result, + ) -> Result>> { + match self.resume_raw(run)? { + ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { + let types = self.store.state.get_canonical_func_type(type_addr).results(); + let values = self.store.value_stack.pop_wasmvalues(&self.store.state, types); + if pin_refs { + self.store.state.pin_host_values(&values); + } + Ok(ExecProgress::Completed(values)) + } + ExecProgress::Completed(CallResult::Values(values)) => Ok(ExecProgress::Completed(values)), + 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`] with the final values once the invocation + /// returns. + /// + /// 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>> { + 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>> { + self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget)) + } +} + +impl FunctionTyped { + /// 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> { + self.func.item.validate_store(store)?; + let func = store.state.get_func(self.func.addr()).clone(); + if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::>(); + let execution = self.func.call_resumable(store, ¶ms)?; + return Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }); + } + + store.enter_execution()?; + let result: Result = (|| { + store.call_stack.clear(); + store.value_stack.clear(); + match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { + Some(callframe) => Ok(FuncExecutionState::Running { callframe, root_func_addr: self.func.addr() }), + None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { + type_addr: func.type_addr, + pin_refs: func.gc.results, + }))), + } + })(); + store.exit_execution(); + let execution = FuncExecution { store, state: result? }; + Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }) + } +} + +impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { + fn resume( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result, + ) -> Result> { + match self.execution.resume_raw(run)? { + ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( + self.execution.store.take_typed_results(type_addr, StackBase::default(), pin_refs)?, + )), + ExecProgress::Completed(CallResult::Values(values)) => { + let mut values = values.into_iter(); + let result = R::from_wasm_values(&mut values)?; + if values.next().is_some() { + return Err(Error::other("typed conversion did not consume all WebAssembly values")); + } + Ok(ExecProgress::Completed(result)) + } + 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> { + 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> { + 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..319b493 --- /dev/null +++ b/crates/tinywasm/src/func/values.rs @@ -0,0 +1,201 @@ +use crate::{Error, Result}; +use alloc::{borrow::Cow, vec::Vec}; +use tinywasm_types::{ExternRef, FuncRef, WasmType, WasmValue}; + +/// Convert a Rust value or tuple into WebAssembly values. +pub trait IntoWasmValues { + /// Return the flattened WebAssembly values. + fn into_wasm_values(self) -> impl Iterator; +} + +/// Convert WebAssembly values into a Rust value or tuple. +pub trait FromWasmValues: Sized { + /// Read this value from a flattened WebAssembly value iterator. + fn from_wasm_values(values: &mut impl Iterator) -> Result; +} + +/// 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; +} + +fn next_value>(values: &mut impl Iterator) -> Result { + let value = values.next().ok_or_else(|| { + core::hint::cold_path(); + Error::other("not enough WebAssembly values") + })?; + T::try_from(value).map_err(|_| { + core::hint::cold_path(); + Error::other("WebAssembly value does not match the expected type") + }) +} + +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) -> impl Iterator { + core::iter::once(self.into()) + } + } + + impl FromWasmValues for $T { + #[inline] + fn from_wasm_values(values: &mut impl Iterator) -> Result { + next_value(values) + } + } + )+ + }; +} + +macro_rules! impl_tuple_traits { + (@next $head:ident, $($tail:ident),+) => { + impl_tuple_traits!($($tail),+); + }; + (@next $head:ident) => {}; + ($($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,)+ + { + #[allow(non_snake_case)] + #[inline] + fn into_wasm_values(self) -> impl Iterator { + let ($($T,)+) = self; + [$($T.into(),)+].into_iter() + } + } + + impl<$($T),+> FromWasmValues for ($($T,)+) + where + $($T: TryFrom,)+ + { + #[inline] + fn from_wasm_values(values: &mut impl Iterator) -> Result { + Ok(($(next_value::<$T>(values)?,)+)) + } + } + + impl_tuple_traits!(@next $($T),+); + } +} + +impl_scalar_wasm_traits!( + i32 => WasmType::I32, + i64 => WasmType::I64, + f32 => WasmType::F32, + f64 => WasmType::F64, + FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF), + ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), +); +impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); + +/// Concatenates two typed parameter or result groups. +/// +/// Direct tuple conversions are supported up to arity 20. Use untyped functions +/// for larger signatures. +#[deprecated(note = "direct tuples are supported up to arity 20, use untyped functions for larger signatures")] +#[derive(Default)] +pub struct WasmTupleChain(T1, T2); + +#[allow(deprecated)] +impl WasmTupleChain { + /// 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) + } +} + +#[allow(deprecated)] +impl From<(T1, T2)> for WasmTupleChain { + fn from((left, right): (T1, T2)) -> Self { + Self::new(left, right) + } +} + +#[allow(deprecated)] +impl ToWasmTypes for WasmTupleChain { + 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) + } +} + +#[allow(deprecated)] +impl IntoWasmValues for WasmTupleChain { + #[inline] + fn into_wasm_values(self) -> impl Iterator { + let (left, right) = self.into_inner(); + left.into_wasm_values().chain(right.into_wasm_values()) + } +} + +#[allow(deprecated)] +impl FromWasmValues for WasmTupleChain { + #[inline] + fn from_wasm_values(values: &mut impl Iterator) -> Result { + let left = T1::from_wasm_values(values)?; + let right = T2::from_wasm_values(values)?; + Ok(Self::new(left, right)) + } +} + +impl ToWasmTypes for () { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); +} + +impl IntoWasmValues for () { + #[inline] + fn into_wasm_values(self) -> impl Iterator { + core::iter::empty() + } +} + +impl FromWasmValues for () { + #[inline] + fn from_wasm_values(_values: &mut impl Iterator) -> Result { + Ok(()) + } +} diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 6a399ee..a35cf2c 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -1,14 +1,13 @@ 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}; 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 +19,28 @@ pub enum Extern { Memory(Memory), /// A function import. Function(Function), + /// A reusable host function definition. + HostFunction(HostFunction), } -impl From for Extern { - fn from(value: Global) -> Self { - Self::Global(value) - } -} - -impl From for Extern { - fn from(value: Table) -> Self { - Self::Table(value) - } -} - -impl From for Extern { - fn from(value: Memory) -> Self { - Self::Memory(value) - } -} - -impl From 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, } /// Imports for a module instance @@ -75,7 +59,7 @@ 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(()) /// }); @@ -101,11 +85,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, + externs: BTreeMap>, modules: BTreeMap, } @@ -124,7 +110,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,15 +126,46 @@ impl Imports { } /// Define an import value. + /// + /// A [`Function`], [`Global`], [`Table`], or [`Memory`] 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) -> &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 { - let name = ExternName::from(import); - self.externs.get(&name).cloned() + self.externs.get(import.module.as_ref())?.get(import.name.as_ref()).cloned() } fn compare_types(import: &Import, actual: &T, expected: &T) -> Result<()> { @@ -237,10 +256,12 @@ impl Imports { (ExternVal::Memory(memory.0.addr), None) } Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), + Extern::HostFunction(func) => { + (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) + } } } else { - let name = ExternName::from(import); - let Some(instance) = self.modules.get(&name.module) else { + let Some(instance) = self.modules.get(import.module.as_ref()) else { cold_path(); return Err(LinkingError::unknown_import(import).into()); }; diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index be38419..52bb948 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -45,7 +45,7 @@ pub struct ModuleInstance(Rc); #[cfg_attr(feature = "debug", derive(Debug))] struct ModuleInstanceInner { - store_id: usize, + store_id: u32, id: ModuleInstanceId, type_addrs: Box<[TypeAddr]>, func_addrs: Box<[FuncAddr]>, @@ -117,7 +117,7 @@ impl ModuleInstance { /// Instantiate the module in the given store /// /// See - pub fn instantiate(store: &mut Store, module: &Module, imports: Option) -> Result { + pub fn instantiate(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result { let instance = ModuleInstance::instantiate_no_start(store, module, imports)?; let _ = instance.start(store)?; Ok(instance) @@ -150,15 +150,13 @@ impl ModuleInstance { /// ``` /// /// See - pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option) -> Result { + pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result { 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::>(); - addrs.funcs.extend(store.init_funcs(&module.funcs, id, &local_type_addrs)); + let default_imports = Imports::default(); + let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; + let imported_funcs = addrs.funcs.len(); + addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); match module.local_memory_allocation { LocalMemoryAllocation::Skip => { #[cfg(feature = "guest-debug")] @@ -246,13 +244,10 @@ impl ModuleInstance { pub fn exports(&self) -> impl Iterator + '_ { 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)))) } @@ -364,7 +359,6 @@ impl ModuleInstance { pub fn func_by_index(&self, store: &Store, func_index: FuncAddr) -> Result { 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,8 +386,7 @@ 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::, _>(...)`. + /// Tuples are supported up to arity 20. Use [`Self::func_untyped`] for larger signatures. pub fn func( &self, store: &Store, diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 1c80dac..f5c9351 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -5,7 +5,6 @@ use core::hint::cold_path; use super::no_std_floats::NoStdFloatExt; use alloc::boxed::Box; -use alloc::rc::Rc; use alloc::vec::Vec; use alloc::sync::Arc; @@ -16,7 +15,7 @@ use super::ExecState; use super::num_helpers::*; use super::values::*; use crate::engine::FuelPolicy; -use crate::func::{FuncContext, HostFunction}; +use crate::func::HostFunction; use crate::interpreter::Value128; use crate::*; @@ -1042,10 +1041,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_host( &mut self, - host_func: Rc, + host_func: HostFunction, type_addr: TypeAddr, params_may_gc: bool, ) -> Result { + if let Some(host_func) = host_func.typed_callback() { + if let Err(error) = host_func.call_stack(self.store, self.module.id(), type_addr) { + cold_path(); + return Err(Trap::HostFunction(Box::new(error))); + } + if TAIL { + return Ok(self.exec_return()); + } + self.cf.instr_ptr += 1; + return Ok(false); + } + let param_types = self.store.state.get_canonical_func_type(type_addr).params(); let mut params = Vec::new(); params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?; @@ -1056,8 +1067,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if params_may_gc { self.store.state.pin_host_values(¶ms); } - let result = host_func.call(FuncContext { store: self.store, module_id: self.module.id() }, ¶ms); - let res = match result.and_then(|result| crate::func::validate_host_results(self.store, type_addr, result)) { + let res = match host_func.call_values(self.store, self.module.id(), type_addr, ¶ms) { Ok(res) => res, Err(err) => { cold_path(); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 852618d..1824d20 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,4 +1,4 @@ -use alloc::vec::Vec; +use alloc::{vec, vec::Vec}; use core::hint::cold_path; use tinywasm_types::{ValueCounts, WasmType, WasmValue}; @@ -18,6 +18,66 @@ pub(crate) struct ValueStack { pub(crate) stack_128: Stack, } +struct WasmValues<'a> { + stack: &'a ValueStack, + state: &'a crate::store::State, + types: core::slice::Iter<'a, WasmType>, + index: StackBase, + pin_refs: bool, +} + +impl Iterator for WasmValues<'_> { + type Item = WasmValue; + + fn next(&mut self) -> Option { + let value = match *self.types.next()? { + WasmType::I32 => { + let value = *self.stack.stack_32.get(self.index.s32 as usize) as i32; + self.index.s32 += 1; + WasmValue::I32(value) + } + WasmType::I64 => { + let value = *self.stack.stack_64.get(self.index.s64 as usize) as i64; + self.index.s64 += 1; + WasmValue::I64(value) + } + WasmType::F32 => { + let value = f32::from_bits(*self.stack.stack_32.get(self.index.s32 as usize)); + self.index.s32 += 1; + WasmValue::F32(value) + } + WasmType::F64 => { + let value = f64::from_bits(*self.stack.stack_64.get(self.index.s64 as usize)); + self.index.s64 += 1; + WasmValue::F64(value) + } + WasmType::Ref(ty) => { + let value = + self.state.to_ref_value(ValueRef::from_raw(*self.stack.stack_32.get(self.index.s32 as usize)), ty); + self.index.s32 += 1; + WasmValue::Ref(value) + } + WasmType::V128 => { + let value = self.stack.stack_128.get(self.index.s128 as usize).0; + self.index.s128 += 1; + WasmValue::V128(value) + } + }; + if self.pin_refs + && let WasmValue::Ref(value) = value + { + self.state.pin_host_ref(value); + } + Some(value) + } + + fn size_hint(&self) -> (usize, Option) { + self.types.size_hint() + } +} + +impl ExactSizeIterator for WasmValues<'_> {} + #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct Stack { data: Vec, @@ -202,6 +262,15 @@ impl ValueStack { } } + 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 len(&self) -> usize { self.stack_32.len() + self.stack_64.len() + self.stack_128.len() @@ -228,6 +297,19 @@ impl ValueStack { Ok(StackBase { s32: locals_base32, s64: locals_base64, s128: locals_base128 }) } + #[inline] + /// Pushes call arguments and allocates the function's local lanes. + pub(crate) fn enter_wasm_call( + &mut self, + values: &[WasmValue], + params: ValueCounts, + locals: ValueCounts, + base: StackBase, + ) -> Result { + self.extend_from_wasmvalues(values).inspect_err(|_| self.truncate_to_base(base))?; + self.enter_locals(¶ms, &locals).inspect_err(|_| self.truncate_to_base(base)) + } + #[inline(always)] pub(crate) fn truncate_keep_counts(&mut self, base: StackBase, keep: ValueCounts) { self.stack_32.truncate_keep(base.s32 as usize, keep.c32 as usize); @@ -262,17 +344,41 @@ impl ValueStack { } } + /// Pops values in their logical WebAssembly order. + pub(crate) fn pop_wasmvalues(&mut self, state: &crate::store::State, types: &[WasmType]) -> Vec { + debug_assert!(self.len() >= types.len()); + let mut values = vec![WasmValue::I32(0); types.len()]; + for (index, &ty) in types.iter().enumerate().rev() { + values[index] = self.pop_wasmvalue(state, ty); + } + values + } + + pub(crate) fn wasm_values<'a>( + &'a self, + state: &'a crate::store::State, + types: &'a [WasmType], + index: StackBase, + pin_refs: bool, + ) -> impl ExactSizeIterator + 'a { + WasmValues { stack: self, state, types: types.iter(), index, pin_refs } + } + pub(crate) fn extend_from_wasmvalues(&mut self, values: &[WasmValue]) -> Result<(), Trap> { + self.extend_wasmvalues(values.iter().copied()) + } + + pub(crate) fn extend_wasmvalues(&mut self, values: impl Iterator) -> 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::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())? + self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(v)).as_ref().unwrap().raw())? } - WasmValue::V128(v) => self.stack_128.push((*v).into())?, + WasmValue::V128(v) => self.stack_128.push(v.into())?, } } Ok(()) diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index 1c2bcb4..2e2dce0 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -105,9 +105,11 @@ pub(crate) mod log { mod error; pub use error::*; +#[allow(deprecated)] +pub use func::WasmTupleChain; pub use func::{ - ExecProgress, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, HostFunction, ToWasmTypes, - WasmTupleChain, + ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, + HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes, }; pub use imports::*; pub use instance::{ExternItem, ModuleInstance}; diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 00f966e..6e904af 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -13,13 +13,14 @@ use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct StoreItem { - pub(crate) store_id: usize, + pub(crate) store_id: u32, pub(crate) addr: Addr, } impl StoreItem { #[inline] - pub(crate) const fn new(store_id: usize, addr: Addr) -> Self { + /// Creates a handle for an address owned by a store. + pub(crate) const fn new(store_id: u32, addr: Addr) -> Self { Self { store_id, addr } } @@ -75,11 +76,7 @@ pub struct MemoryCursor<'a> { } #[cfg(feature = "std")] -impl<'a> MemoryCursor<'a> { - fn new(memory: &'a mut MemoryInstance, position: u64) -> Self { - Self { memory, position } - } - +impl MemoryCursor<'_> { fn offset(&self) -> crate::std::io::Result { usize::try_from(self.position).map_err(|_| { crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize") @@ -199,7 +196,7 @@ impl Memory { /// Available with the `std` feature enabled. #[cfg(feature = "std")] pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result> { - Ok(MemoryCursor::new(self.instance_mut(store)?, position)) + Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) } #[inline] @@ -375,12 +372,6 @@ impl Table { 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 { Ok(self.instance(store)?.kind) @@ -428,7 +419,8 @@ impl Table { /// 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) + self.0.validate_store(store)?; + store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) } /// Grow the table and return the previous size. diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs new file mode 100644 index 0000000..201a1e1 --- /dev/null +++ b/crates/tinywasm/src/store/const_expr.rs @@ -0,0 +1,194 @@ +use alloc::{format, vec::Vec}; +use core::hint::cold_path; +use tinywasm_types::*; + +use super::{State, default_value}; +use crate::interpreter::{TinyWasmValue, ValueRef}; +use crate::{Error, Result, Trap}; + +#[inline] +pub(super) fn eval_const( + state: &mut State, + instructions: &[ConstInstruction], + global_addrs: &[GlobalAddr], + func_addrs: &[FuncAddr], + type_addrs: &[TypeAddr], +) -> Result { + use ConstInstruction::*; + + let global_value = |state: &State, index: u32| -> Result { + let addr = + *global_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("global {index} not found")))?; + Ok(state.globals.get(addr)) + }; + let func_ref = |index: u32| -> Result { + let addr = + *func_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("function {index} not found")))?; + Ok(ValueRef::from_category_addr(addr)) + }; + let type_addr = |index: TypeAddr| -> Result { + type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) + }; + let pop_value = |stack: &mut Vec, storage: StorageType| -> Result { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + match (storage, value) { + (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), + (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), + _ => Err(Error::other("type mismatch in GC constant")), + } + }; + + if let [instruction] = instructions { + match instruction { + I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), + I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), + F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), + F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), + V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), + GlobalGet(index) => return global_value(state, *index), + Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), + Ref(RefValue::Func(func)) => return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + _ => {} + } + } + + let mut stack = Vec::new(); + for instruction in instructions { + match instruction { + I32Const(value) => stack.push(TinyWasmValue::Value32(*value as u32)), + I64Const(value) => stack.push(TinyWasmValue::Value64(*value as u64)), + F32Const(value) => stack.push(TinyWasmValue::Value32(value.to_bits())), + F64Const(value) => stack.push(TinyWasmValue::Value64(value.to_bits())), + V128Const(value) => stack.push(TinyWasmValue::Value128((*value).into())), + GlobalGet(index) => stack.push(global_value(state, *index)?), + Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), + Ref(RefValue::Func(func)) => stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + Ref(_) => { + cold_path(); + return Err(Error::other("unsupported reference constant")); + } + RefI31 => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let TinyWasmValue::Value32(value) = value else { + return Err(Error::other("type mismatch in const ref.i31")); + }; + stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); + } + AnyConvertExtern | ExternConvertAny => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + if !matches!(value, TinyWasmValue::ValueRef(_)) { + return Err(Error::other("type mismatch in const reference conversion")); + } + stack.push(value); + } + StructNew(type_index) | StructNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let fields = state + .get_type(type_addr) + .as_struct() + .ok_or_else(|| Error::other("GC constant type is not a struct"))? + .fields + .clone(); + let default = matches!(instruction, StructNewDefault(_)); + let mut values = Vec::new(); + values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + if default { + values.extend(fields.iter().map(|field| default_value(field.storage))); + } else { + for field in fields.iter().rev() { + values.push(pop_value(&mut stack, field.storage)?); + } + values.reverse(); + } + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNew(type_index) | ArrayNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let storage = state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let Some(TinyWasmValue::Value32(len)) = stack.pop() else { + return Err(Error::other("type mismatch in const array length")); + }; + let value = if matches!(instruction, ArrayNewDefault(_)) { + default_value(storage) + } else { + pop_value(&mut stack, storage)? + }; + let mut values = Vec::new(); + values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; + values.resize(len as usize, value); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNewFixed(type_index, len) => { + let type_addr = type_addr(*type_index)?; + let storage = state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let mut values = Vec::new(); + values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; + for _ in 0..*len { + values.push(pop_value(&mut stack, storage)?); + } + values.reverse(); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + I32Add | I32Sub | I32Mul => { + let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else { + cold_path(); + return 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(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 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(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) +} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 367fadb..3580e9d 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -1,4 +1,4 @@ -use alloc::{rc::Rc, sync::Arc}; +use alloc::sync::Arc; use tinywasm_types::*; use crate::func::HostFunction; @@ -25,7 +25,7 @@ pub(crate) struct FunctionGcMetadata { #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) enum FunctionKind { /// A host function - Host(Rc), + Host(HostFunction), /// A pointer to a WebAssembly function Wasm(WasmFunctionInstance), diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index c685d89..638b01d 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -15,6 +15,11 @@ impl Default for GlobalLane { } impl GlobalLane { + 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(); @@ -57,6 +62,20 @@ impl Globals { 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 diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 9d5622a..0cd5e5b 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,12 +1,14 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; -use core::sync::atomic::{AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicU32, Ordering}; use tinywasm_types::*; -use crate::interpreter::stack::{CallStack, ValueStack}; +use crate::func::FromWasmValues; +use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; use crate::interpreter::{TinyWasmValue, ValueRef}; use crate::{Engine, Error, ModuleInstance, Result, Trap}; +mod const_expr; mod data; mod element; mod function; @@ -17,6 +19,7 @@ mod state; mod table; mod types; +use const_expr::eval_const; pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; @@ -25,7 +28,7 @@ pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; pub(crate) use {data::*, element::*, function::*, global::*, table::*}; // global store id counter -static STORE_ID: AtomicUsize = AtomicUsize::new(0); +static STORE_ID: AtomicU32 = AtomicU32::new(0); /// Global state that can be manipulated by WebAssembly programs /// @@ -46,7 +49,7 @@ static STORE_ID: AtomicUsize = AtomicUsize::new(0); /// /// See pub struct Store { - id: usize, + id: u32, pub(crate) module_instances: Vec, pub(crate) engine: Engine, @@ -68,12 +71,24 @@ impl core::fmt::Debug for Store { } } +impl PartialEq for Store { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Default for Store { + fn default() -> Self { + Self::new(Engine::default()) + } +} + impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { - let id = STORE_ID.fetch_add(1, Ordering::Relaxed); - let state = - State { gc: Box::new(gc::GcHeap::new(engine.config().gc_collection_threshold)), ..State::default() }; + let id = + STORE_ID.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)).expect("too many stores"); + let state = State::new(engine.config().gc_collection_threshold); Self { id, module_instances: Vec::new(), @@ -86,45 +101,16 @@ impl Store { } } + /// Get the store's ID (unique per process) + pub fn id(&self) -> u32 { + 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 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(()) - } - - pub(crate) fn exit_execution(&mut self) { - self.execution_active = false; - } -} - -impl PartialEq for Store { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } -} - -impl Default for Store { - fn default() -> Self { - Self::new(Engine::default()) - } -} - -impl Store { - /// Get the store's ID (unique per process) - pub fn id(&self) -> usize { - self.id - } - pub(crate) fn next_module_instance_id(&self) -> ModuleInstanceId { self.module_instances.len() as ModuleInstanceId } @@ -151,19 +137,87 @@ impl Store { pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { self.state.value_matches_type(value, ty) } -} -impl Store { + /// 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(()) + } + + /// Marks the current root execution as complete. + pub(crate) fn exit_execution(&mut self) { + self.execution_active = false; + } + + /// Validates and pushes typed parameters or results onto the value stack. + pub(crate) fn push_typed_values( + &mut self, + type_addr: TypeAddr, + values: impl Iterator, + 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"))?; + if !self.state.value_matches_type(value, ty) { + return Err(Error::other("typed function value does not match its signature")); + } + self.value_stack.extend_wasmvalues(core::iter::once(value))?; + } + 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); + } + result + } + + /// Reads typed results from the value stack and restores its previous base. + pub(crate) fn take_typed_results( + &mut self, + type_addr: TypeAddr, + stack_base: StackBase, + pin_refs: bool, + ) -> Result { + let types = self.state.get_canonical_func_type(type_addr).results(); + let mut values = self.value_stack.wasm_values(&self.state, types, stack_base, pin_refs); + let result = R::from_wasm_values(&mut values).and_then(|result| { + if values.next().is_some() { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + } else { + Ok(result) + } + }); + drop(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: &[alloc::sync::Arc], owner: ModuleInstanceId, + module_type_idxs: &[TypeAddr], type_addrs: &[TypeAddr], ) -> impl ExactSizeIterator { let start = self.state.funcs.len() as FuncAddr; - debug_assert_eq!(funcs.len(), type_addrs.len()); - for (func, &type_addr) in funcs.iter().cloned().zip(type_addrs) { + debug_assert_eq!(funcs.len(), module_type_idxs.len()); + self.state.funcs.reserve_exact(funcs.len()); + for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) { + let type_addr = type_addrs[type_idx as usize]; self.state.funcs.push(FunctionInstance { type_addr, gc: self.state.func_gc_metadata(type_addr), @@ -185,7 +239,7 @@ impl Store { self.state.tables.reserve_exact(tables.len()); for table in tables { let init = match &table.init { - Some(expr) => match self.eval_const(expr, global_addrs, func_addrs, type_addrs)? { + Some(expr) => match eval_const(&mut self.state, expr, global_addrs, func_addrs, type_addrs)? { TinyWasmValue::ValueRef(value) => value, _ => return Err(Error::other("table initializer is not a reference value")), }, @@ -208,6 +262,7 @@ impl Store { init: impl Fn(MemoryType, &MemoryBackend) -> Result, ) -> Result> { 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, @@ -228,8 +283,9 @@ impl Store { func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], ) -> Result<()> { + self.state.globals.reserve(globals); for global in globals { - let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { + let value = match eval_const(&mut self.state, &global.init, out, func_addrs, type_addrs) { Ok(val) => val, Err(e) => { cold_path(); @@ -251,7 +307,7 @@ impl Store { type_addrs: &[TypeAddr], ) -> Result { match item { - ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs, type_addrs)? { + ElementItem::Expr(expr) => match eval_const(&mut self.state, expr, globals, funcs, type_addrs)? { TinyWasmValue::ValueRef(value) => Ok(value), other => { cold_path(); @@ -279,9 +335,10 @@ impl Store { global_addrs: &[Addr], elements: &[Element], type_addrs: &[TypeAddr], - ) -> Result<(Box<[Addr]>, Option)> { + ) -> Result<(Box<[ElemAddr]>, Option)> { let elem_count = self.state.elements.len(); let mut elem_addrs = Vec::with_capacity(elements.len()); + self.state.elements.reserve_exact(elements.len()); for (i, element) in elements.iter().enumerate() { let elem_addr = self.state.elements.len(); self.state.elements.push(ElementInstance { @@ -302,7 +359,11 @@ impl Store { // 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, type_addrs)?; + let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { + TinyWasmValue::Value32(value) => u64::from(value), + TinyWasmValue::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() @@ -339,8 +400,7 @@ impl Store { elements[elem_addr].drop(); } } - - elem_addrs.push((i + elem_count) as Addr); + elem_addrs.push((i + elem_count) as ElemAddr); } // this should be optimized out by the compiler @@ -355,9 +415,10 @@ impl Store { func_addrs: &[FuncAddr], data: &[Data], type_addrs: &[TypeAddr], - ) -> Result<(Box<[Addr]>, Option)> { + ) -> Result<(Box<[DataAddr]>, Option)> { let data_count = self.state.data.len(); - let mut data_addrs = Vec::with_capacity(data_count); + let mut data_addrs = Vec::with_capacity(data.len()); + self.state.data.reserve_exact(data.len()); for (i, data) in data.iter().enumerate() { let data_val = match &data.kind { tinywasm_types::DataKind::Active { mem: mem_addr, offset } => { @@ -365,7 +426,11 @@ impl Store { return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}"))); }; - let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?; + let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { + TinyWasmValue::Value32(value) => u64::from(value), + TinyWasmValue::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}"))); }; @@ -389,241 +454,17 @@ impl Store { }; self.state.data.push(DataInstance { data: data_val }); - data_addrs.push((i + data_count) as Addr); + data_addrs.push((i + data_count) as DataAddr); } // this should be optimized out by the compiler Ok((data_addrs.into_boxed_slice(), None)) } + /// Adds a function and returns its store address. pub(crate) fn add_func(&mut self, func: FunctionInstance) -> FuncAddr { + let addr = self.state.funcs.len() as 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( - &mut self, - const_instrs: &[tinywasm_types::ConstInstruction], - module_global_addrs: &[Addr], - module_func_addrs: &[FuncAddr], - module_type_addrs: &[TypeAddr], - ) -> Result { - let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs, module_type_addrs)?; - match value { - TinyWasmValue::Value32(i) => Ok(u64::from(i)), - TinyWasmValue::Value64(i) => Ok(i), - other => Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), - } - } - - /// Evaluate a constant expression - #[inline] - fn eval_const( - &mut self, - const_instrs: &[tinywasm_types::ConstInstruction], - module_global_addrs: &[Addr], - module_func_addrs: &[FuncAddr], - module_type_addrs: &[TypeAddr], - ) -> Result { - use tinywasm_types::ConstInstruction::*; - - let global_value = |state: &State, index: u32| -> Result { - let addr = *module_global_addrs - .get(index as usize) - .ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr)) - }; - let func_ref = |index: u32| -> Result { - let addr = *module_func_addrs - .get(index as usize) - .ok_or_else(|| Error::Other(format!("function {index} not found")))?; - Ok(ValueRef::from_category_addr(addr)) - }; - let type_addr = |index: TypeAddr| -> Result { - module_type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) - }; - let pop_value = |stack: &mut Vec, storage: StorageType| -> Result { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - match (storage, value) { - (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), - (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), - (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) - | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) - | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) - | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), - _ => Err(Error::other("type mismatch in GC constant")), - } - }; - - if let [instr] = const_instrs { - match instr { - I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), - I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), - F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), - F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), - V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), - GlobalGet(index) => return global_value(&self.state, *index), - Ref(tinywasm_types::RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(tinywasm_types::RefValue::Func(func)) => { - return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)); - } - _ => {} - } - } - - 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(index) => stack.push(global_value(&self.state, *index)?), - Ref(tinywasm_types::RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(tinywasm_types::RefValue::Func(func)) => { - stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)) - } - Ref(_) => { - cold_path(); - return Err(Error::other("unsupported reference constant")); - } - RefI31 => { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let TinyWasmValue::Value32(value) = value else { - return Err(Error::other("type mismatch in const ref.i31")); - }; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); - } - AnyConvertExtern | ExternConvertAny => { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - if !matches!(value, TinyWasmValue::ValueRef(_)) { - return Err(Error::other("type mismatch in const reference conversion")); - } - stack.push(value); - } - StructNew(type_index) | StructNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; - let fields = self - .state - .get_type(type_addr) - .as_struct() - .ok_or_else(|| Error::other("GC constant type is not a struct"))? - .fields - .clone(); - let default = matches!(instr, StructNewDefault(_)); - let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; - if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); - } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut stack, field.storage)?); - } - values.reverse(); - } - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - ArrayNew(type_index) | ArrayNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; - let storage = self - .state - .get_type(type_addr) - .as_array() - .ok_or_else(|| Error::other("GC constant type is not an array"))? - .field - .storage; - let Some(TinyWasmValue::Value32(len)) = stack.pop() else { - return Err(Error::other("type mismatch in const array length")); - }; - let value = if matches!(instr, ArrayNewDefault(_)) { - default_value(storage) - } else { - pop_value(&mut stack, storage)? - }; - let mut values = Vec::new(); - values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; - values.resize(len as usize, value); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - ArrayNewFixed(type_index, len) => { - let type_addr = type_addr(*type_index)?; - let storage = self - .state - .get_type(type_addr) - .as_array() - .ok_or_else(|| Error::other("GC constant type is not an array"))? - .field - .storage; - let mut values = Vec::new(); - values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; - for _ in 0..*len { - values.push(pop_value(&mut stack, storage)?); - } - values.reverse(); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - I32Add | I32Sub | I32Mul => { - let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - 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) + addr } } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 5cb561a..3371d4c 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -2,7 +2,6 @@ use alloc::vec::Vec; use super::*; -#[derive(Default)] /// Global state that can be manipulated by WebAssembly programs /// /// Data should only be addressable by the module that owns it @@ -21,6 +20,20 @@ pub(crate) struct State { } impl State { + pub(crate) fn new(gc_collection_threshold: usize) -> Self { + Self { + canonical_types: Vec::new(), + canonical_rec_group_lengths: Vec::new(), + funcs: Vec::new(), + tables: Vec::new(), + memories: Vec::new(), + globals: Globals::default(), + elements: Vec::new(), + data: Vec::new(), + gc: Box::new(gc::GcHeap::new(gc_collection_threshold)), + } + } + /// Returns whether values of this type can contain a managed GC object. pub(crate) fn type_may_contain_gc(&self, ty: &WasmType) -> bool { Self::type_may_contain_gc_in(&self.canonical_types, ty) @@ -406,3 +419,9 @@ impl State { Ok(()) } } + +impl Default for State { + fn default() -> Self { + Self::new(1024 * 1024) + } +} diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index b3b5048..35e0d9b 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,6 +1,6 @@ use eyre::Result; use std::fmt::Write; -use tinywasm::types::{FuncType, RefValue, WasmType, WasmValue}; +use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; use tinywasm_types::ExternRef; @@ -34,10 +34,10 @@ fn test_return_invalid_type() -> Result<()> { 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, |_: FuncContext<'_>, _| Ok(returned_values.to_vec())); 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() @@ -56,13 +56,12 @@ fn test_linking_invalid_untyped_func() -> Result<()> { 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")); + let tried_fn = 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); } } @@ -80,26 +79,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 { + HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: Existing| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: Existing| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: ()| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: ()| -> tinywasm::Result { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result { + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result { panic!("{DONT_CALL}") }), ]; @@ -107,7 +98,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"); } } @@ -142,16 +133,45 @@ fn concrete_host_references_use_canonical_types() -> Result<()> { 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())); + let wrong_return = + HostFunction::from_untyped(&return_ty, move |_, _| Ok(wrong_result.clone())).instantiate(&mut store)?; assert!(wrong_return.call(&mut store, &[]).is_err()); - let accept_a = HostFunction::from_untyped(&mut store, ¶m_ty, |_, _| Ok(Vec::new())); + let accept_a = HostFunction::from_untyped(¶m_ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; 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<()> { + 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).expect("valid module-local type index"); + let host_ty = FuncType::new(&[WasmType::Ref(concrete)], &[]); + let host = HostFunction::from_untyped(&host_ty, |_, args| { + assert_eq!(args, &[WasmValue::Ref(RefValue::Null)]); + Ok(Vec::new()) + }); + 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<()> { let wasm = wat::parse_str( @@ -178,8 +198,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 +210,14 @@ 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<()> { 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 host = HostFunction::from_untyped(&ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; let invalid = WasmValue::Ref(RefValue::Func(tinywasm::types::FuncRef::new(u32::MAX))); assert!(host.call(&mut store, &[invalid]).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 { - Ok(left * 1000 + right) - }); - + let pair = + HostFunction::from(|_ctx, (left, right): (i32, i32)| -> tinywasm::Result { 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/import_linking.rs b/crates/tinywasm/tests/import_linking.rs index e7948fa..1d5db1b 100644 --- a/crates/tinywasm/tests/import_linking.rs +++ b/crates/tinywasm/tests/import_linking.rs @@ -34,7 +34,7 @@ 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(()) @@ -51,7 +51,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..ca52e9e 100644 --- a/crates/tinywasm/tests/imported_table_init.rs +++ b/crates/tinywasm/tests/imported_table_init.rs @@ -19,11 +19,11 @@ 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 _function_at_zero = HostFunction::from(|_, ()| Ok(())).instantiate(&mut store)?; let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 3, None), FuncRef::new(0).into())?; 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::(&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 04279cc..196ad0a 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -117,9 +117,9 @@ 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![]); @@ -166,9 +166,9 @@ 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![]); @@ -192,7 +192,8 @@ 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)?; diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs index c231bc1..0cf5707 100644 --- a/crates/tinywasm/tests/memory_backends.rs +++ b/crates/tinywasm/tests/memory_backends.rs @@ -190,7 +190,7 @@ fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result< ) "#, )?; - let parser = Parser::with_options(ParserOptions::default().with_local_memory_allocation_optimization(false)); + let parser = Parser::new(ParserOptions::default().with_local_memory_allocation_optimization(false)); let module = parser.parse_module_bytes(&wasm)?; let created = instantiate_module_with_counting_backend(module)?; diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index 6cae984..bcb8e07 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -98,7 +98,7 @@ fn global_import_rejects_wrong_store() -> Result<()> { imports.define("env", "g", global); let mut other_store = Store::default(); - let err = ModuleInstance::instantiate(&mut other_store, &module, Some(imports)).unwrap_err(); + 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/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index 80494e0..9d88ec8 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -85,7 +85,7 @@ fn imported_global_keeps_its_typed_store_address() -> Result<()> { let global = Global::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))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; assert_eq!(instance.func::(&store, "roundtrip")?.call(&mut store, 42)?, 42); assert_eq!(global.get(&store)?, WasmValue::I64(42)); diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index 980dc21..bee961c 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -30,7 +30,7 @@ impl Runtime { 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 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")?; @@ -169,7 +169,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_open", - HostFunction::from(store, move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { + HostFunction::from(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)?; @@ -208,7 +208,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_close", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { state.borrow_mut().files.remove(&handle); Ok(()) }), @@ -220,7 +220,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_read", - HostFunction::from(store, move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); @@ -238,7 +238,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_write", - HostFunction::from(store, move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + HostFunction::from(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 { @@ -255,7 +255,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_seek", - HostFunction::from(store, move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { + HostFunction::from(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), @@ -277,7 +277,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_tell", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); @@ -293,7 +293,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_eof", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(1); @@ -310,7 +310,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_gettime", - HostFunction::from(store, move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { + HostFunction::from(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; @@ -327,7 +327,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_exit", - HostFunction::from(store, move |_ctx: FuncContext<'_>, code: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { state.borrow_mut().exit_code = Some(code); Ok(()) }), @@ -337,7 +337,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_print", - HostFunction::from(store, move |ctx: FuncContext<'_>, ptr: i32| { + HostFunction::from(move |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/funcref_callbacks.rs b/examples/funcref_callbacks.rs index 8ff9b49..5e21a6b 100644 --- a/examples/funcref_callbacks.rs +++ b/examples/funcref_callbacks.rs @@ -50,19 +50,18 @@ fn run_passed_funcref_example() -> Result<()> { let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); - let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { 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 mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); + let call_this = HostFunction::from(|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 instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let caller = instance.func::<(), ()>(&store, "tell_host_to_call")?; caller.call(&mut store, ())?; @@ -107,10 +106,10 @@ fn run_returned_funcref_example() -> Result<()> { let mut store = Store::default(); let mut imports = Imports::new(); - let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); + let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); imports.define("host", "mul", mul); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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, ())? diff --git a/examples/linking.rs b/examples/linking.rs index b3164ae..02cb88d 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -40,7 +40,7 @@ fn main() -> Result<()> { 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. let main = import_instance.func::<(), i32>(&store, "main")?; diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 432fac7..8a1988e 100644 --- a/examples/reentrance.rs +++ b/examples/reentrance.rs @@ -22,7 +22,7 @@ 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| { let add_one = ctx.module().func::(ctx.store(), "add_one")?; // Use ctx.call for reentrant calls from host functions. Function::call @@ -34,7 +34,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::(&store, "run")?; assert_eq!(run.call(&mut store, 40)?, 52); 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..cbf10f4 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -28,17 +28,17 @@ 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 res = tinywasm::parser::Parser::default().parse_module_bytes(include_bytes!("./print.wasm"))?; let twasm = res.serialize_twasm()?; let module = tinywasm::parse_bytes(&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/wasm-rust.rs b/examples/wasm-rust.rs index e0b9968..e4af3cd 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -75,8 +75,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(()))?; @@ -90,8 +90,8 @@ fn tinywasm_no_std() -> 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(()))?; @@ -104,7 +104,7 @@ 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)| { + 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,7 +114,7 @@ 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"; @@ -129,7 +129,7 @@ fn host_fn() -> Result<()> { 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 +138,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 +148,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 +156,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))?; -- cgit v1.3.1 From 70c5bb2e4816f7ee458a6180845af3bd6b1d2d1d Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 10 Aug 2026 16:21:47 +0200 Subject: chore: cleanup tests / devdeps, fix doom example Signed-off-by: Henry --- Cargo.lock | 36 ++--- Cargo.toml | 26 +++- benches/argon2id.rs | 46 ++++++ benches/fibonacci.rs | 52 +++++++ benches/memory_backends.rs | 152 +++++++++++++++++++ benches/tinywasm.rs | 49 ++++++ benches/tinywasm_modes.rs | 100 +++++++++++++ crates/cli/Cargo.toml | 6 +- crates/cli/src/bin.rs | 2 +- crates/cli/src/cmd/compile.rs | 2 +- crates/cli/src/cmd/completion.rs | 2 +- crates/cli/src/cmd/dump.rs | 2 +- crates/cli/src/cmd/inspect.rs | 2 +- crates/cli/src/cmd/run.rs | 8 +- crates/cli/src/cmd/wast.rs | 2 +- crates/cli/src/engine_flags.rs | 2 +- crates/cli/src/lib.rs | 4 +- crates/cli/src/load.rs | 2 +- crates/cli/src/testsuite.rs | 166 +++++++++++++++++++++ crates/cli/src/value_parse.rs | 6 +- crates/cli/src/wast_runner.rs | 80 +++++----- crates/tinywasm/Cargo.toml | 27 +--- crates/tinywasm/benches/argon2id.rs | 47 ------ crates/tinywasm/benches/fibonacci.rs | 53 ------- crates/tinywasm/benches/memory_backends.rs | 152 ------------------- crates/tinywasm/benches/tinywasm.rs | 50 ------- crates/tinywasm/benches/tinywasm_modes.rs | 99 ------------ crates/tinywasm/tests/host_func_signature_check.rs | 18 +-- crates/tinywasm/tests/import_linking.rs | 7 +- crates/tinywasm/tests/imported_table_init.rs | 3 +- crates/tinywasm/tests/internal_refs.rs | 13 +- crates/tinywasm/tests/memory_backends.rs | 31 ++-- crates/tinywasm/tests/memory_ref_api.rs | 3 +- crates/tinywasm/tests/module_descriptors.rs | 8 +- crates/tinywasm/tests/resume_execution.rs | 3 +- crates/tinywasm/tests/start_function.rs | 3 +- crates/tinywasm/tests/store_ownership.rs | 11 +- crates/tinywasm/tests/test-wasm-1.rs | 6 +- crates/tinywasm/tests/test-wasm-2.rs | 6 +- crates/tinywasm/tests/test-wasm-3.rs | 6 +- .../tinywasm/tests/test-wasm-custom-page-sizes.rs | 6 +- crates/tinywasm/tests/test-wasm-custom.rs | 6 +- crates/tinywasm/tests/test-wasm-gc.rs | 6 +- crates/tinywasm/tests/test-wasm-latest.rs | 6 +- crates/tinywasm/tests/test-wasm-memory64.rs | 6 +- crates/tinywasm/tests/test-wasm-multi-memory.rs | 6 +- crates/tinywasm/tests/test-wasm-relaxed-simd.rs | 6 +- crates/tinywasm/tests/test-wasm-simd.rs | 6 +- crates/tinywasm/tests/test-wasm-threads.rs | 6 +- crates/tinywasm/tests/test-wasm-wide-arithmetic.rs | 6 +- crates/tinywasm/tests/test-wast.rs | 17 +-- crates/tinywasm/tests/testsuite/mod.rs | 150 ------------------- crates/tinywasm/tests/typed_globals.rs | 5 +- crates/tinywasm/tests/typed_lookup.rs | 5 +- examples/archive.rs | 2 +- examples/doom/Cargo.toml | 2 +- examples/doom/src/main.rs | 10 +- examples/doom/src/runtime.rs | 35 +++-- examples/funcref_callbacks.rs | 2 +- examples/linking.rs | 2 +- examples/reentrance.rs | 2 +- examples/resumable.rs | 2 +- examples/simple.rs | 2 +- examples/simple2.rs | 2 +- examples/wasm-rust.rs | 4 +- 65 files changed, 781 insertions(+), 814 deletions(-) create mode 100644 benches/argon2id.rs create mode 100644 benches/fibonacci.rs create mode 100644 benches/memory_backends.rs create mode 100644 benches/tinywasm.rs create mode 100644 benches/tinywasm_modes.rs create mode 100644 crates/cli/src/testsuite.rs delete mode 100644 crates/tinywasm/benches/argon2id.rs delete mode 100644 crates/tinywasm/benches/fibonacci.rs delete mode 100644 crates/tinywasm/benches/memory_backends.rs delete mode 100644 crates/tinywasm/benches/tinywasm.rs delete mode 100644 crates/tinywasm/benches/tinywasm_modes.rs delete mode 100644 crates/tinywasm/tests/testsuite/mod.rs (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index 5312e7f..c4dbba7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,6 +76,12 @@ dependencies = [ "windows-sys", ] +[[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" @@ -351,16 +357,6 @@ dependencies = [ "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", -] - [[package]] name = "fastrand" version = "2.5.0" @@ -447,12 +443,6 @@ dependencies = [ "quote", ] -[[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" @@ -872,13 +862,8 @@ dependencies = [ name = "tinywasm" version = "0.11.0-pre.0" dependencies = [ - "criterion", - "eyre", "libm", "log", - "owo-colors", - "serde", - "serde_json", "tinywasm-cli", "tinywasm-parser", "tinywasm-types", @@ -891,16 +876,19 @@ name = "tinywasm-cli" version = "0.11.0-pre.0" dependencies = [ "anstream", + "anyhow", "assert_cmd", "clap", "clap_complete", - "eyre", "log", "owo-colors", "predicates", "pretty_env_logger", + "serde", + "serde_json", "tempfile", "tinywasm", + "wasm-testsuite", "wast", "wat", ] @@ -918,9 +906,11 @@ dependencies = [ name = "tinywasm-root" version = "0.11.0-pre.0" dependencies = [ - "eyre", + "anyhow", + "criterion", "pretty_env_logger", "tinywasm", + "tinywasm-parser", "wat", ] diff --git a/Cargo.toml b/Cargo.toml index ca80b66..5a4e83f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ tinywasm = { path = "crates/tinywasm", version = "0.11.0-pre.0", default-feature tinywasm-parser = { path = "crates/parser", version = "0.11.0-pre.0", default-features = false } tinywasm-types = { path = "crates/types", version = "0.11.0-pre.0", default-features = false } -eyre = "0.6" +anyhow = "1.0" log = "0.4" owo-colors = { version = "4.3" } pretty_env_logger = "0.5" @@ -44,10 +44,32 @@ criterion = { version = "0.8", default-features = false, features = [ name = "wasm-rust" test = false +[[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" + [dev-dependencies] -eyre.workspace = true +anyhow.workspace = true +criterion.workspace = true pretty_env_logger.workspace = true tinywasm = { path = "crates/tinywasm" } +tinywasm-parser.workspace = true wat.workspace = true [profile.bench] diff --git a/benches/argon2id.rs b/benches/argon2id.rs new file mode 100644 index 0000000..3121062 --- /dev/null +++ b/benches/argon2id.rs @@ -0,0 +1,46 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::{ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/argon2id.wasm"); + +fn argon2id_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn argon2id_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn argon2id_from_twasm(twasm: &[u8]) -> Result { + let module = Module::try_from_twasm(twasm)?; + Ok(module) +} + +fn argon2id_run(module: Module) -> Result<()> { + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2 = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; + argon2.call(&mut store, (1000, 2, 1))?; + Ok(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = argon2id_parse().expect("argon2id_parse"); + let twasm = argon2id_to_twasm(&module).expect("argon2id_to_twasm"); + let mut group = c.benchmark_group("argon2id"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("argon2id_parse", |b| b.iter(argon2id_parse)); + group.bench_function("argon2id_to_twasm", |b| b.iter(|| argon2id_to_twasm(&module))); + group.bench_function("argon2id_from_twasm", |b| b.iter(|| argon2id_from_twasm(&twasm))); + + group.measurement_time(std::time::Duration::from_secs(10)); + group.bench_function("argon2id", |b| b.iter(|| argon2id_run(module.clone()))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/fibonacci.rs b/benches/fibonacci.rs new file mode 100644 index 0000000..51fd2d3 --- /dev/null +++ b/benches/fibonacci.rs @@ -0,0 +1,52 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::{ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/fibonacci.wasm"); + +fn fibonacci_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn fibonacci_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn fibonacci_from_twasm(twasm: &[u8]) -> Result { + Ok(Module::try_from_twasm(twasm)?) +} + +fn fibonacci_run(module: Module, recursive: bool, n: i32) -> Result<()> { + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2 = instance.func::( + &store, + match recursive { + true => "fibonacci_recursive", + false => "fibonacci", + }, + )?; + argon2.call(&mut store, n)?; + Ok(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = fibonacci_parse().expect("fibonacci_parse"); + let twasm = fibonacci_to_twasm(&module).expect("fibonacci_to_twasm"); + let mut group = c.benchmark_group("fibonacci"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("fibonacci_parse", |b| b.iter(fibonacci_parse)); + group.bench_function("fibonacci_to_twasm", |b| b.iter(|| fibonacci_to_twasm(&module))); + 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_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/memory_backends.rs b/benches/memory_backends.rs new file mode 100644 index 0000000..3a59f8c --- /dev/null +++ b/benches/memory_backends.rs @@ -0,0 +1,152 @@ +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(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( + 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( + 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/benches/tinywasm.rs b/benches/tinywasm.rs new file mode 100644 index 0000000..aff8c70 --- /dev/null +++ b/benches/tinywasm.rs @@ -0,0 +1,49 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::engine::Config; +use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/tinywasm.wasm"); + +fn tinywasm_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn tinywasm_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn tinywasm_from_twasm(twasm: &[u8]) -> Result { + let module = Module::try_from_twasm(twasm)?; + Ok(module) +} + +fn tinywasm_run(module: &Module) -> Result<()> { + let engine = Engine::new(Config::default()); + let mut store = Store::new(engine); + let mut imports = Imports::default(); + 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(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = tinywasm_parse().expect("tinywasm_parse"); + let twasm = tinywasm_to_twasm(&module).expect("tinywasm_to_twasm"); + let mut group = c.benchmark_group("tinywasm"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("tinywasm_parse", |b| b.iter(tinywasm_parse)); + group.bench_function("tinywasm_to_twasm", |b| b.iter(|| tinywasm_to_twasm(&module))); + group.bench_function("tinywasm_from_twasm", |b| b.iter(|| tinywasm_from_twasm(&twasm))); + group.measurement_time(std::time::Duration::from_secs(10)); + group.bench_function("tinywasm", |b| b.iter(|| tinywasm_run(&module))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/tinywasm_modes.rs b/benches/tinywasm_modes.rs new file mode 100644 index 0000000..7d1d993 --- /dev/null +++ b/benches/tinywasm_modes.rs @@ -0,0 +1,100 @@ +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; +use tinywasm::engine::{Config, FuelPolicy}; +use tinywasm::types::Module; +use tinywasm::{ + Engine, ExecProgress, FuncContext, FunctionTyped, HostFunction, Imports, ModuleInstance, Result, Store, +}; + +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 { + let parser = tinywasm_parser::Parser::default(); + Ok(parser.parse_module_bytes(WASM)?) +} + +fn setup_typed_func(module: &Module, engine: Option) -> Result<(Store, FunctionTyped<(), ()>)> { + let mut store = match engine { + Some(engine) => Store::new(engine), + None => Store::default(), + }; + + let mut imports = Imports::default(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); + + let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?; + let func = instance.func::<(), ()>(&store, "hello")?; + Ok((store, func)) +} + +fn run_call(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + func.call(store, ())?; + Ok(()) +} + +fn run_resume_with_fuel(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + let mut execution = func.call_resumable(store, ())?; + loop { + match execution.resume_with_fuel(FUEL_PER_ROUND)? { + ExecProgress::Completed(_) => return Ok(()), + ExecProgress::Suspended => {} + } + } +} + +fn run_resume_with_time_budget(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + let mut execution = func.call_resumable(store, ())?; + loop { + match execution.resume_with_time_budget(TIME_BUDGET_PER_ROUND)? { + ExecProgress::Completed(_) => return Ok(()), + ExecProgress::Suspended => {} + } + } +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = tinywasm_parse().expect("tinywasm_parse"); + let mut group = c.benchmark_group("tinywasm_modes"); + group.measurement_time(BENCH_MEASUREMENT_TIME); + + let per_instruction_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::PerInstruction)); + group.bench_function("resume_fuel_per_instruction", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, Some(per_instruction_engine.clone())).expect("setup fuel per-instruction"), + |(store, func)| run_resume_with_fuel(store, func).expect("run fuel per-instruction"), + BatchSize::LargeInput, + ) + }); + + let weighted_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::Weighted)); + group.bench_function("resume_fuel_weighted", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, Some(weighted_engine.clone())).expect("setup fuel weighted"), + |(store, func)| run_resume_with_fuel(store, func).expect("run fuel weighted"), + BatchSize::LargeInput, + ) + }); + + group.bench_function("resume_time_budget", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, None).expect("setup time budget"), + |(store, func)| run_resume_with_time_budget(store, func).expect("run time budget"), + BatchSize::LargeInput, + ) + }); + + group.bench_function("call", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, None).expect("setup call"), + |(store, func)| run_call(store, func).expect("run call"), + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 17b56e6..1aae437 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -23,12 +23,14 @@ 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", @@ -39,6 +41,7 @@ tinywasm = { workspace = true, features = [ "std", "validate", ] } +wasm-testsuite = { workspace = true, optional = true } wast = { workspace = true, optional = true } wat = { workspace = true, optional = true } @@ -49,5 +52,6 @@ tempfile = "3.27" [features] default = ["wast", "wat"] +tests = ["dep:serde", "dep:serde_json", "dep:wasm-testsuite", "wast"] wast = ["dep:wast"] wat = ["dep:wat"] 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..3d25641 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,7 +26,7 @@ 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, ¶ms)?; @@ -40,7 +40,7 @@ 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 {module_path}`" ) })?; 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..3d90847 100644 --- a/crates/cli/src/engine_flags.rs +++ b/crates/cli/src/engine_flags.rs @@ -1,5 +1,5 @@ +use anyhow::{Result, bail}; use clap::{Args, ValueEnum}; -use eyre::{Result, bail}; use tinywasm::{Engine, StackConfig, engine::FuelPolicy}; #[derive(Args, Clone, Default)] 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/testsuite.rs b/crates/cli/src/testsuite.rs new file mode 100644 index 0000000..032aa88 --- /dev/null +++ b/crates/cli/src/testsuite.rs @@ -0,0 +1,166 @@ +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}; + +/// Result type used by the WAST test utilities. +pub type TestResult = core::result::Result>; + +#[derive(Debug)] +struct TestFailure(String); + +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 { + pub name: String, + pub passed: usize, + pub failed: usize, +} + +pub struct TestSuite { + runner: WastRunner, +} + +impl TestSuite { + pub fn set_log_level(level: log::LevelFilter) { + WastRunner::set_log_level(level); + } + + pub fn new() -> Self { + Self { runner: WastRunner::new() } + } + + pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> TestResult<()> { + let mut files = Vec::new(); + for path in tests { + if path.is_dir() { + for entry in std::fs::read_dir(path)? { + let entry = entry?; + let path = entry.path(); + if path.extension().is_some_and(|ext| ext == "wast") { + files.push(path); + } + } + } else { + files.push(path.clone()); + } + } + files.sort(); + + let runner_files = files + .iter() + .map(|path| { + let contents = std::fs::read_to_string(path)?; + let name = path.to_string_lossy().into_owned(); + Ok((name, contents)) + }) + .collect::>>()?; + + 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>, + ) -> 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) -> TestResult<()> { + if self.runner.failed() { + println!(); + Err(TestFailure(format!("{}:\n{self}", "failed one or more tests".red().bold())).into()) + } else { + println!("{self}"); + Ok(()) + } + } + + pub fn save_csv(&self, path: &str, version: &str) -> TestResult<()> { + use std::fs::OpenOptions; + use std::io::Write; + + let mut file = OpenOptions::new().create(true).append(true).read(true).open(path)?; + let last_line = BufReader::new(&file).lines().last().transpose()?; + + if let Some(last) = last_line + && last.starts_with(version) + { + let len_to_truncate = last.len() as i64; + file.set_len(file.metadata()?.len() - len_to_truncate as u64 - 1)?; + } + + file.seek(SeekFrom::End(0))?; + + let mut passed = 0; + let mut failed = 0; + let mut groups = Vec::new(); + + for group in self.runner.group_results() { + passed += group.passed; + failed += group.failed; + groups.push(TestGroupResult { name: group.name, passed: group.passed, failed: group.failed }); + } + + let groups = serde_json::to_string(&groups)?; + let line = format!("{version},{passed},{failed},{groups}\n"); + file.write_all(line.as_bytes())?; + Ok(()) + } + + fn group_results(&self) -> Vec { + self.runner.group_results() + } +} + +impl Default for TestSuite { + fn default() -> Self { + Self::new() + } +} + +impl Display for TestSuite { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut total_passed = 0; + let mut total_failed = 0; + + for group in self.group_results() { + total_passed += group.passed; + total_failed += group.failed; + + writeln!(f, "{}", group.name.bold().underline())?; + writeln!(f, " Tests Passed: {}", group.passed.to_string().green())?; + if group.failed != 0 { + writeln!(f, " Tests Failed: {}", group.failed.to_string().red())?; + } + } + + writeln!(f, "\n{}", "Total Test Summary:".bold().underline())?; + writeln!(f, " Total Tests: {}", total_passed + total_failed)?; + writeln!(f, " Total Passed: {}", total_passed.to_string().green())?; + writeln!(f, " Total Failed: {}", total_failed.to_string().red())?; + Ok(()) + } +} 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 { 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 24483b6..1b8ae9c 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -5,7 +5,7 @@ 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::{ AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, @@ -111,7 +111,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(()) @@ -238,7 +238,7 @@ impl WastRunner { test_group.add_result( &format!("Register({i})"), span.linecol_in(wast_raw), - Err(eyre!("module instance to register was not found")), + Err(anyhow!("module instance to register was not found")), ); continue; } @@ -251,7 +251,7 @@ impl WastRunner { .expect("failed to instantiate module"); (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:?}"), @@ -263,7 +263,7 @@ impl WastRunner { ModuleDefinition(module) => { let result = catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition")) - .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))); + .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()); @@ -280,10 +280,10 @@ impl WastRunner { let result = catch_unwind_silent(|| { let module = module_registry .definition(module) - .ok_or_else(|| eyre!("module definition was not found"))?; + .ok_or_else(|| anyhow!("module definition was not found"))?; Self::instantiate_module(&mut store, &module_registry, &module) }) - .map_err(|err| eyre!("failed to instantiate module definition: {}", try_downcast_panic(err))) + .map_err(|err| anyhow!("failed to instantiate module definition: {}", try_downcast_panic(err))) .and_then(|result| result); if let Ok(instance) = &result { @@ -301,7 +301,7 @@ 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})"), @@ -314,7 +314,7 @@ impl WastRunner { { continue; } - Err(eyre!("expected module to be malformed: {message}")) + Err(anyhow!("expected module to be malformed: {message}")) } Err(_) => Ok(()), }, @@ -326,13 +326,13 @@ impl WastRunner { 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(_) => Err(anyhow!("expected module to be invalid")), Err(_) => Ok(()), }, ); @@ -346,7 +346,7 @@ impl WastRunner { test_group.add_result( &format!("AssertExhaustion({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap")), + Err(anyhow!("expected trap")), ); continue; }; @@ -354,7 +354,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; } @@ -382,14 +382,14 @@ impl WastRunner { 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; } @@ -398,12 +398,12 @@ 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)), ), } } @@ -426,10 +426,10 @@ impl WastRunner { exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) }); let result = match res { - Err(err) => Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))), Ok(Err(tinywasm::Error::Exception(_))) => Ok(()), - Ok(Err(err)) => Err(eyre!("expected exception, got: {err:?}")), - Ok(Ok(())) => Err(eyre!("expected exception, got 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); } @@ -444,7 +444,7 @@ impl WastRunner { 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 @@ -454,7 +454,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; } @@ -463,12 +463,12 @@ 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)), ), } } @@ -483,7 +483,7 @@ impl WastRunner { })?; 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 } => { @@ -492,7 +492,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; } @@ -500,13 +500,13 @@ 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; }; @@ -516,7 +516,7 @@ impl WastRunner { 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; } @@ -529,7 +529,7 @@ impl WastRunner { 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 )), @@ -550,7 +550,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; } @@ -565,7 +565,7 @@ impl WastRunner { e })?; if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) { - return Err(eyre!( + return Err(anyhow!( "expected {} results, got {}", expected_alternatives.first().map_or(0, |v| v.len()), outcomes.len() @@ -580,17 +580,17 @@ impl WastRunner { }) { 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")), ), } } @@ -828,7 +828,7 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { I32(i) => WasmValue::I32(i), I64(i) => WasmValue::I64(i), V128(i) => WasmValue::V128(i.to_le_bytes()), - RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), + RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), RefNull(t) => match t { wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(), wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => { @@ -839,7 +839,8 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { } }, RefHost(value) => { - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into() + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) + .into() } }) } @@ -918,7 +919,7 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), RefNull(_) => ExpectedValue::RefNull, RefExtern(Some(v)) => ExpectedValue::Exact( - ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), + ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), ), RefExtern(None) => ExpectedValue::RefExtern, RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()), @@ -932,7 +933,8 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::RefStruct, RefArray => ExpectedValue::RefArray, RefHost(value) => ExpectedValue::Exact( - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into(), + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) + .into(), ), a => { bail!("unsupported arg type {:?}", a); diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 65ef7f8..eb5dd94 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -85,26 +85,6 @@ name = "test-wasm-simd" harness = false name = "test-wasm-wide-arithmetic" -[[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 } @@ -112,12 +92,7 @@ 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 diff --git a/crates/tinywasm/benches/argon2id.rs b/crates/tinywasm/benches/argon2id.rs deleted file mode 100644 index d2845c5..0000000 --- a/crates/tinywasm/benches/argon2id.rs +++ /dev/null @@ -1,47 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::{ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/argon2id.wasm"); - -fn argon2id_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn argon2id_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn argon2id_from_twasm(twasm: &[u8]) -> Result { - let module = Module::try_from_twasm(twasm)?; - Ok(module) -} - -fn argon2id_run(module: Module) -> Result<()> { - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2 = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; - argon2.call(&mut store, (1000, 2, 1))?; - Ok(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = argon2id_parse().expect("argon2id_parse"); - let twasm = argon2id_to_twasm(&module).expect("argon2id_to_twasm"); - let mut group = c.benchmark_group("argon2id"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("argon2id_parse", |b| b.iter(argon2id_parse)); - group.bench_function("argon2id_to_twasm", |b| b.iter(|| argon2id_to_twasm(&module))); - group.bench_function("argon2id_from_twasm", |b| b.iter(|| argon2id_from_twasm(&twasm))); - - group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("argon2id", |b| b.iter(|| argon2id_run(module.clone()))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/fibonacci.rs b/crates/tinywasm/benches/fibonacci.rs deleted file mode 100644 index 1bf0791..0000000 --- a/crates/tinywasm/benches/fibonacci.rs +++ /dev/null @@ -1,53 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::{ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/fibonacci.wasm"); - -fn fibonacci_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn fibonacci_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn fibonacci_from_twasm(twasm: &[u8]) -> Result { - Ok(Module::try_from_twasm(twasm)?) -} - -fn fibonacci_run(module: Module, recursive: bool, n: i32) -> Result<()> { - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2 = instance.func::( - &store, - match recursive { - true => "fibonacci_recursive", - false => "fibonacci", - }, - )?; - argon2.call(&mut store, n)?; - Ok(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = fibonacci_parse().expect("fibonacci_parse"); - let twasm = fibonacci_to_twasm(&module).expect("fibonacci_to_twasm"); - let mut group = c.benchmark_group("fibonacci"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("fibonacci_parse", |b| b.iter(fibonacci_parse)); - group.bench_function("fibonacci_to_twasm", |b| b.iter(|| fibonacci_to_twasm(&module))); - 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_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); 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(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( - 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( - 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/benches/tinywasm.rs b/crates/tinywasm/benches/tinywasm.rs deleted file mode 100644 index 3560d3c..0000000 --- a/crates/tinywasm/benches/tinywasm.rs +++ /dev/null @@ -1,50 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::engine::Config; -use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm"); - -fn tinywasm_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn tinywasm_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn tinywasm_from_twasm(twasm: &[u8]) -> Result { - let module = Module::try_from_twasm(twasm)?; - Ok(module) -} - -fn tinywasm_run(module: &Module) -> Result<()> { - let engine = Engine::new(Config::default()); - let mut store = Store::new(engine); - let mut imports = Imports::default(); - 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(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = tinywasm_parse().expect("tinywasm_parse"); - let twasm = tinywasm_to_twasm(&module).expect("tinywasm_to_twasm"); - let mut group = c.benchmark_group("tinywasm"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("tinywasm_parse", |b| b.iter(tinywasm_parse)); - group.bench_function("tinywasm_to_twasm", |b| b.iter(|| tinywasm_to_twasm(&module))); - group.bench_function("tinywasm_from_twasm", |b| b.iter(|| tinywasm_from_twasm(&twasm))); - group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("tinywasm", |b| b.iter(|| tinywasm_run(&module))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/tinywasm_modes.rs b/crates/tinywasm/benches/tinywasm_modes.rs deleted file mode 100644 index 6c1badf..0000000 --- a/crates/tinywasm/benches/tinywasm_modes.rs +++ /dev/null @@ -1,99 +0,0 @@ -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}; - -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 { - let parser = tinywasm_parser::Parser::default(); - Ok(parser.parse_module_bytes(WASM)?) -} - -fn setup_typed_func(module: &Module, engine: Option) -> Result<(Store, FunctionTyped<(), ()>)> { - let mut store = match engine { - Some(engine) => Store::new(engine), - None => Store::default(), - }; - - let mut imports = Imports::default(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); - - let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?; - let func = instance.func::<(), ()>(&store, "hello")?; - Ok((store, func)) -} - -fn run_call(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - func.call(store, ())?; - Ok(()) -} - -fn run_resume_with_fuel(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - let mut execution = func.call_resumable(store, ())?; - loop { - match execution.resume_with_fuel(FUEL_PER_ROUND)? { - ExecProgress::Completed(_) => return Ok(()), - ExecProgress::Suspended => {} - } - } -} - -fn run_resume_with_time_budget(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - let mut execution = func.call_resumable(store, ())?; - loop { - match execution.resume_with_time_budget(TIME_BUDGET_PER_ROUND)? { - ExecProgress::Completed(_) => return Ok(()), - ExecProgress::Suspended => {} - } - } -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = tinywasm_parse().expect("tinywasm_parse"); - let mut group = c.benchmark_group("tinywasm_modes"); - group.measurement_time(BENCH_MEASUREMENT_TIME); - - let per_instruction_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::PerInstruction)); - group.bench_function("resume_fuel_per_instruction", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, Some(per_instruction_engine.clone())).expect("setup fuel per-instruction"), - |(store, func)| run_resume_with_fuel(store, func).expect("run fuel per-instruction"), - BatchSize::LargeInput, - ) - }); - - let weighted_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::Weighted)); - group.bench_function("resume_fuel_weighted", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, Some(weighted_engine.clone())).expect("setup fuel weighted"), - |(store, func)| run_resume_with_fuel(store, func).expect("run fuel weighted"), - BatchSize::LargeInput, - ) - }); - - group.bench_function("resume_time_budget", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, None).expect("setup time budget"), - |(store, func)| run_resume_with_time_budget(store, func).expect("run time budget"), - BatchSize::LargeInput, - ) - }); - - group.bench_function("call", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, None).expect("setup call"), - |(store, func)| run_call(store, func).expect("run call"), - BatchSize::LargeInput, - ) - }); - - group.finish(); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 35e0d9b..128f1ed 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,8 +1,6 @@ -use eyre::Result; use std::fmt::Write; -use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; -use tinywasm_types::ExternRef; const VAL_LISTS: &[&[WasmValue]] = &[ &[], @@ -27,7 +25,7 @@ fn module_cases() -> Vec<(Module, FuncType, Vec)> { } #[test] -fn test_return_invalid_type() -> Result<()> { +fn test_return_invalid_type() -> Result<(), Box> { let cases = module_cases(); for (module, ty, args) in cases { @@ -51,7 +49,7 @@ fn test_return_invalid_type() -> Result<()> { } #[test] -fn test_linking_invalid_untyped_func() -> Result<()> { +fn test_linking_invalid_untyped_func() -> Result<(), Box> { let cases = module_cases(); for (module, expected_func_ty, _) in &cases { for (_, ty, _) in &cases { @@ -69,7 +67,7 @@ fn test_linking_invalid_untyped_func() -> Result<()> { } #[test] -fn test_linking_invalid_typed_func() -> Result<()> { +fn test_linking_invalid_typed_func() -> Result<(), Box> { type Existing = (i32, i32, f64); type NonMatchingSingle = f64; type NonMatchingTuple = (f64, i32, i32); @@ -107,7 +105,7 @@ fn test_linking_invalid_typed_func() -> Result<()> { } #[test] -fn concrete_host_references_use_canonical_types() -> Result<()> { +fn concrete_host_references_use_canonical_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -145,7 +143,7 @@ fn concrete_host_references_use_canonical_types() -> Result<()> { } #[test] -fn imported_host_functions_resolve_concrete_types() -> Result<()> { +fn imported_host_functions_resolve_concrete_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -173,7 +171,7 @@ fn imported_host_functions_resolve_concrete_types() -> Result<()> { } #[test] -fn host_tail_calls_return_from_the_current_frame() -> Result<()> { +fn host_tail_calls_return_from_the_current_frame() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -210,7 +208,7 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> { } #[test] -fn host_calls_reject_unknown_function_references() -> Result<()> { +fn host_calls_reject_unknown_function_references() -> Result<(), Box> { let mut store = Store::default(); let ty = FuncType::new(&[WasmType::Ref(tinywasm::types::RefType::FUNCREF)], &[]); let host = HostFunction::from_untyped(&ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; diff --git a/crates/tinywasm/tests/import_linking.rs b/crates/tinywasm/tests/import_linking.rs index 1d5db1b..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> { 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> { let (add_module, import_module) = parse_modules()?; let mut store = Store::default(); @@ -41,7 +40,7 @@ fn link_module_links_same_store_instance() -> Result<()> { } #[test] -fn link_module_rejects_cross_store_instance() -> Result<()> { +fn link_module_rejects_cross_store_instance() -> Result<(), Box> { let (add_module, import_module) = parse_modules()?; let mut source_store = Store::default(); diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs index ca52e9e..aaa781b 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::{HostFunction, Imports, ModuleInstance, Store, Table}; #[test] -fn imported_table_uses_provided_init_value() -> Result<()> { +fn imported_table_uses_provided_init_value() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 196ad0a..07cbde2 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -1,4 +1,3 @@ -use eyre::Result; use tinywasm::types::WasmValue; #[cfg(feature = "guest-debug")] use tinywasm::types::{FuncRef, RefValue}; @@ -6,7 +5,7 @@ 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> { let wasm = wat::parse_str( r#" (module @@ -42,7 +41,7 @@ fn private_items_are_accessible_by_index() -> Result<()> { } #[test] -fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> { +fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -73,7 +72,7 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> { } #[test] -fn extern_item_lookup_returns_expected_kinds() -> Result<()> { +fn extern_item_lookup_returns_expected_kinds() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -98,7 +97,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> { let wasm = wat::parse_str( r#" (module @@ -134,7 +133,7 @@ fn extern_item_and_exports_use_actual_function_type() -> Result<()> { } #[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> { let wasm = wat::parse_str( r#" (module @@ -177,7 +176,7 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<() } #[test] -fn start_resolves_module_func_index_to_store_addr() -> Result<()> { +fn start_resolves_module_func_index_to_store_addr() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs index 0cf5707..b7f9438 100644 --- a/crates/tinywasm/tests/memory_backends.rs +++ b/crates/tinywasm/tests/memory_backends.rs @@ -6,13 +6,14 @@ 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 { +type TestResult = Result>; + +fn instantiate_module_with_counting_backend(module: Module) -> TestResult { let created = Arc::new(AtomicUsize::new(0)); let factory_calls = created.clone(); let backend = MemoryBackend::custom(move |ty| { @@ -27,7 +28,7 @@ fn instantiate_module_with_counting_backend(module: Module) -> Result { Ok(created.load(Ordering::Relaxed)) } -fn instantiate_with_counting_backend(wat: &str) -> Result { +fn instantiate_with_counting_backend(wat: &str) -> TestResult { let wasm = wat::parse_str(wat)?; let module = tinywasm::parse_bytes(&wasm)?; instantiate_module_with_counting_backend(module) @@ -35,7 +36,7 @@ fn instantiate_with_counting_backend(wat: &str) -> Result { fn instantiate_exported_memory_with_counting_backend( wat: &str, -) -> Result<(Store, tinywasm::ModuleInstance, Arc)> { +) -> TestResult<(Store, tinywasm::ModuleInstance, Arc)> { let wasm = wat::parse_str(wat)?; let module = tinywasm::parse_bytes(&wasm)?; let created = Arc::new(AtomicUsize::new(0)); @@ -51,7 +52,7 @@ fn instantiate_exported_memory_with_counting_backend( } #[test] -fn paged_backend_works_for_module_memories() -> Result<()> { +fn paged_backend_works_for_module_memories() -> TestResult { let wasm = wat::parse_str( r#" (module @@ -73,7 +74,7 @@ fn paged_backend_works_for_module_memories() -> Result<()> { } #[test] -fn custom_backend_factory_is_used_for_host_memories() -> Result<()> { +fn custom_backend_factory_is_used_for_host_memories() -> TestResult { let created = Arc::new(AtomicUsize::new(0)); let seen_page_size = Arc::new(AtomicUsize::new(0)); let factory_calls = created.clone(); @@ -100,7 +101,7 @@ fn custom_backend_factory_is_used_for_host_memories() -> Result<()> { } #[test] -fn local_memory_without_observable_use_is_not_allocated() -> Result<()> { +fn local_memory_without_observable_use_is_not_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -115,7 +116,7 @@ fn local_memory_without_observable_use_is_not_allocated() -> Result<()> { } #[test] -fn exported_local_memory_is_not_eagerly_allocated() -> Result<()> { +fn exported_local_memory_is_not_eagerly_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -129,7 +130,7 @@ fn exported_local_memory_is_not_eagerly_allocated() -> Result<()> { } #[test] -fn exported_local_memory_reads_zeroes_without_materializing() -> Result<()> { +fn exported_local_memory_reads_zeroes_without_materializing() -> TestResult { let (mut store, instance, created) = instantiate_exported_memory_with_counting_backend( r#" (module @@ -151,7 +152,7 @@ fn exported_local_memory_reads_zeroes_without_materializing() -> Result<()> { } #[test] -fn active_data_segment_on_local_memory_is_allocated() -> Result<()> { +fn active_data_segment_on_local_memory_is_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -166,7 +167,7 @@ fn active_data_segment_on_local_memory_is_allocated() -> Result<()> { } #[test] -fn local_memory_instruction_is_allocated() -> Result<()> { +fn local_memory_instruction_is_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -181,7 +182,7 @@ fn local_memory_instruction_is_allocated() -> Result<()> { } #[test] -fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result<()> { +fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> TestResult { let wasm = wat::parse_str( r#" (module @@ -200,7 +201,7 @@ fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result< } #[test] -fn read_returns_short_count_at_end_of_memory() -> Result<()> { +fn read_returns_short_count_at_end_of_memory() -> TestResult { 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])?; @@ -214,7 +215,7 @@ fn read_returns_short_count_at_end_of_memory() -> Result<()> { } #[test] -fn paged_read_and_write_stop_at_chunk_boundaries() -> Result<()> { +fn paged_read_and_write_stop_at_chunk_boundaries() -> TestResult { 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)))?; @@ -241,7 +242,7 @@ fn paged_read_and_write_stop_at_chunk_boundaries() -> Result<()> { #[cfg(feature = "std")] #[test] -fn memory_cursor_supports_read_write_and_seek() -> Result<()> { +fn memory_cursor_supports_read_write_and_seek() -> TestResult { let mut store = Store::default(); let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(8)))?; diff --git a/crates/tinywasm/tests/memory_ref_api.rs b/crates/tinywasm/tests/memory_ref_api.rs index 6f72477..768c873 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> { let wasm = wat::parse_str( r#" (module 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> { 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> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs index 060cefb..2798e7b 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; 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> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index bcb8e07..a508817 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -1,4 +1,3 @@ -use eyre::Result; use tinywasm::types::{GlobalType, WasmType}; use tinywasm::{Global, Imports, ModuleInstance, Store}; @@ -13,7 +12,7 @@ const MODULE_WAT: &str = r#" "#; #[test] -fn func_handle_rejects_wrong_store() -> Result<()> { +fn func_handle_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(MODULE_WAT)?; let module = tinywasm::parse_bytes(&wasm)?; @@ -29,7 +28,7 @@ fn func_handle_rejects_wrong_store() -> Result<()> { } #[test] -fn memory_access_rejects_wrong_store() -> Result<()> { +fn memory_access_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(MODULE_WAT)?; let module = tinywasm::parse_bytes(&wasm)?; @@ -45,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> { let wasm = wat::parse_str( r#" (module @@ -67,7 +66,7 @@ fn global_access_rejects_wrong_store() -> Result<()> { } #[test] -fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { +fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -89,7 +88,7 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { } #[test] -fn global_import_rejects_wrong_store() -> Result<()> { +fn global_import_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; let module = tinywasm::parse_bytes(&wasm)?; let mut owner_store = Store::default(); 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> { 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> { 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> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); 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> { 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> { 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-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> { 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> { 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> { 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> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); 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> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); 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> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); 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> { 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> { 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..004bafa 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::>(); - if args.len() < 2 { - bail!("usage: cargo test-wast "); +fn main() -> Result<(), Box> { + let Some(input) = std::env::args().nth(1) else { + eprintln!("usage: cargo test-wast "); + std::process::exit(2); }; let mut cwd = std::env::current_dir()?; @@ -15,8 +12,7 @@ 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() { @@ -26,5 +22,6 @@ fn main() -> Result<()> { }; let mut test_suite = WastRunner::new(); - test_suite.run_paths(&files) + test_suite.run_paths(&files)?; + Ok(()) } diff --git a/crates/tinywasm/tests/testsuite/mod.rs b/crates/tinywasm/tests/testsuite/mod.rs deleted file mode 100644 index ea44c29..0000000 --- a/crates/tinywasm/tests/testsuite/mod.rs +++ /dev/null @@ -1,150 +0,0 @@ -#![allow(dead_code)] - -use eyre::{Result, eyre}; -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}; - -#[derive(Serialize, Deserialize)] -pub struct TestGroupResult { - pub name: String, - pub passed: usize, - pub failed: usize, -} - -pub struct TestSuite { - runner: WastRunner, -} - -impl TestSuite { - pub fn set_log_level(level: log::LevelFilter) { - WastRunner::set_log_level(level); - } - - pub fn new() -> Self { - Self { runner: WastRunner::new() } - } - - pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> Result<()> { - let mut files = Vec::new(); - for path in tests { - if path.is_dir() { - for entry in std::fs::read_dir(path)? { - let entry = entry?; - let path = entry.path(); - if path.extension().is_some_and(|ext| ext == "wast") { - files.push(path); - } - } - } else { - files.push(path.clone()); - } - } - files.sort(); - - let runner_files = files - .iter() - .map(|path| { - let contents = std::fs::read_to_string(path)?; - let name = path.to_string_lossy().into_owned(); - Ok((name, contents)) - }) - .collect::>>()?; - - self.runner.run_files(runner_files.iter().map(|(name, contents)| RunnerTestFile { - name: name.clone(), - parent: name.clone(), - contents, - })) - } - - pub fn run_files<'a>(&mut self, tests: impl IntoIterator>) -> Result<()> { - self.runner.run_files(tests.into_iter().map(|file| RunnerTestFile { - name: file.name().to_string(), - parent: file.parent().to_string(), - contents: file.raw(), - })) - } - - 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 save_csv(&self, path: &str, version: &str) -> Result<()> { - use std::fs::OpenOptions; - use std::io::Write; - - let mut file = OpenOptions::new().create(true).append(true).read(true).open(path)?; - let last_line = BufReader::new(&file).lines().last().transpose()?; - - if let Some(last) = last_line - && last.starts_with(version) - { - let len_to_truncate = last.len() as i64; - file.set_len(file.metadata()?.len() - len_to_truncate as u64 - 1)?; - } - - file.seek(SeekFrom::End(0))?; - - let mut passed = 0; - let mut failed = 0; - let mut groups = Vec::new(); - - for group in self.runner.group_results() { - passed += group.passed; - failed += group.failed; - groups.push(TestGroupResult { name: group.name, passed: group.passed, failed: group.failed }); - } - - let groups = serde_json::to_string(&groups)?; - let line = format!("{version},{passed},{failed},{groups}\n"); - file.write_all(line.as_bytes())?; - Ok(()) - } - - fn group_results(&self) -> Vec { - self.runner.group_results() - } -} - -impl Default for TestSuite { - fn default() -> Self { - Self::new() - } -} - -impl Display for TestSuite { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - let mut total_passed = 0; - let mut total_failed = 0; - - for group in self.group_results() { - total_passed += group.passed; - total_failed += group.failed; - - writeln!(f, "{}", group.name.bold().underline())?; - writeln!(f, " Tests Passed: {}", group.passed.to_string().green())?; - if group.failed != 0 { - writeln!(f, " Tests Failed: {}", group.failed.to_string().red())?; - } - } - - writeln!(f, "\n{}", "Total Test Summary:".bold().underline())?; - writeln!(f, " Total Tests: {}", total_passed + total_failed)?; - writeln!(f, " Total Passed: {}", total_passed.to_string().green())?; - writeln!(f, " Total Failed: {}", total_failed.to_string().red())?; - Ok(()) - } -} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index 9d88ec8..ac79f6a 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -1,9 +1,8 @@ -use eyre::Result; use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue}; use tinywasm::{Global, Imports, ModuleInstance, Store}; #[test] -fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { +fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -70,7 +69,7 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { } #[test] -fn imported_global_keeps_its_typed_store_address() -> Result<()> { +fn imported_global_keeps_its_typed_store_address() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module 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> { 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> { let wasm = wat::parse_str( r#" (module diff --git a/examples/archive.rs b/examples/archive.rs index 7a2ebab..3f64704 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#" diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml index 38e16c4..abec73d 100644 --- a/examples/doom/Cargo.toml +++ b/examples/doom/Cargo.toml @@ -7,7 +7,7 @@ publish = false [workspace] [dependencies] -eyre = "0.6" +anyhow = "1.0" log = "0.4" pretty_env_logger = "0.5" softbuffer = "0.4" diff --git a/examples/doom/src/main.rs b/examples/doom/src/main.rs index 095183d..c5e49b5 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.host_state.lock().unwrap().exit_code.is_some() { event_loop.exit(); } } diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index bee961c..2ad02ae 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -1,12 +1,11 @@ -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::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const IMPORT_MODULE: &str = "env"; @@ -21,15 +20,15 @@ pub struct Runtime { key_up: tinywasm::FunctionTyped, memory: tinywasm::Memory, framebuffer_bytes: Vec, - pub host_state: Rc>, + pub host_state: Arc>, } impl Runtime { pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result { 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 host_state = Arc::new(Mutex::new(HostState::new(wad_path))); + let imports = build_imports(host_state.clone()); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?; @@ -41,7 +40,7 @@ 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 = host_state.lock().unwrap().wad_path.to_string_lossy().into_owned(); memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; @@ -161,7 +160,7 @@ impl HostState { } } -fn build_imports(store: &mut Store, state: Rc>) -> Imports { +fn build_imports(state: Arc>) -> Imports { let mut imports = Imports::new(); { @@ -175,7 +174,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { 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 mut state = state.lock().unwrap(); let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { state.wad_path.clone() } else { @@ -209,7 +208,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_close", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - state.borrow_mut().files.remove(&handle); + state.lock().unwrap().files.remove(&handle); Ok(()) }), ); @@ -221,7 +220,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_read", HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); }; @@ -240,7 +239,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { "host_write", HostFunction::from(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 mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -262,7 +261,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { 2 => SeekFrom::End(offset as i64), _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), }; - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -278,7 +277,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_tell", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -294,7 +293,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_eof", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(1); }; @@ -311,7 +310,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_gettime", HostFunction::from(move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { - let elapsed = state.borrow().start.elapsed(); + let elapsed = state.lock().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")?; @@ -328,7 +327,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_exit", HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { - state.borrow_mut().exit_code = Some(code); + state.lock().unwrap().exit_code = Some(code); Ok(()) }), ); diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs index 5e21a6b..959d798 100644 --- a/examples/funcref_callbacks.rs +++ b/examples/funcref_callbacks.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef}; const LHS: i32 = 5; diff --git a/examples/linking.rs b/examples/linking.rs index 02cb88d..2df7133 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; // WebAssembly module defining and exporting an `add` function. diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 8a1988e..0084a61 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#" diff --git a/examples/resumable.rs b/examples/resumable.rs index 0163414..26b5f47 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#" diff --git a/examples/simple.rs b/examples/simple.rs index a902b4c..0d57265 100644 --- a/examples/simple.rs +++ b/examples/simple.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/simple2.rs b/examples/simple2.rs index da7def7..f673dfe 100644 --- a/examples/simple2.rs +++ b/examples/simple2.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index e4af3cd..672b290 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -1,6 +1,6 @@ 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. @@ -23,7 +23,7 @@ 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/wasm-rust.rs for instructions.")); } let args = std::env::args().collect::>(); -- cgit v1.3.1 From e862a9ef83957b2e1e92e211922ce4e131c6e2b3 Mon Sep 17 00:00:00 2001 From: Henry Date: Wed, 12 Aug 2026 18:00:11 +0200 Subject: chore: improve interpreter performance, add cold path macros Signed-off-by: Henry --- Cargo.lock | 20 +- Cargo.toml | 6 +- crates/parser/src/optimize.rs | 48 +- crates/tinywasm/src/error.rs | 4 + crates/tinywasm/src/imports.rs | 31 +- crates/tinywasm/src/instance.rs | 15 +- crates/tinywasm/src/interpreter/executor.rs | 492 ++++++++------------- .../tinywasm/src/interpreter/stack/call_stack.rs | 7 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 3 +- crates/tinywasm/src/interpreter/values.rs | 5 +- crates/tinywasm/src/lib.rs | 2 + crates/tinywasm/src/macros.rs | 18 + crates/tinywasm/src/store/const_expr.rs | 22 +- crates/tinywasm/src/store/element.rs | 11 +- crates/tinywasm/src/store/gc/mod.rs | 2 +- crates/tinywasm/src/store/memory/instance.rs | 12 +- crates/tinywasm/src/store/memory/lazy.rs | 4 +- crates/tinywasm/src/store/memory/mod.rs | 34 +- crates/tinywasm/src/store/memory/paged.rs | 17 +- crates/tinywasm/src/store/memory/vec.rs | 21 +- crates/tinywasm/src/store/mod.rs | 18 +- crates/tinywasm/src/store/state.rs | 4 +- crates/tinywasm/src/store/table.rs | 6 +- crates/tinywasm/tests/typed_globals.rs | 10 +- crates/types/src/instructions.rs | 3 + 25 files changed, 343 insertions(+), 472 deletions(-) create mode 100644 crates/tinywasm/src/macros.rs (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index c4dbba7..b06f70f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,9 +111,9 @@ checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" [[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", @@ -962,9 +962,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.255.0" +version = "0.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42" +checksum = "ec1492381bfd5ea51c2a99a919b676662559925cb8d7490547ec2e14c1ad3eb1" dependencies = [ "leb128fmt", "wasmparser", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.255.0" +version = "0.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b" +checksum = "60bd825ffedc6cba8a642924ba7ae424afbc47811cffbcb7b92031ec24e59b4c" dependencies = [ "bitflags", "indexmap", @@ -993,9 +993,9 @@ dependencies = [ [[package]] name = "wast" -version = "255.0.0" +version = "256.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ffec530f199bd3d553ac442c13dd108353cad533cad8514bc41e1f1f0fe686" +checksum = "a3ad42723fc9222da007f05812a3249c9a4ee7af79d497fc2a2079579ad7efe6" dependencies = [ "bumpalo", "leb128fmt", @@ -1006,9 +1006,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.255.0" +version = "1.256.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dda82c82e1486c7eed42a0465e544d80fff37abc3b39482e0d34dbaabe2fe5b1" +checksum = "37cc86c54d8011b3202e265bfebada440733ea3a788ffaf46d395f7d2fdeacfb" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 5a4e83f..3af064c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,9 @@ 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.256", default-features = false } +wast = "256" +wat = "1.256" criterion = { version = "0.8", default-features = false, features = [ "cargo_bench_support", diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 7081187..969d686 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -96,9 +96,14 @@ fn rewrite( rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); rewrite!(instrs, i, [I32Add] => I32Add3); + rewrite!(instrs, i, + [BinOpStackLocal32(BinOp::IAdd, local)] => + [LocalGet32(local), I32Add3] + ); } } instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { @@ -107,6 +112,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); 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]); @@ -152,12 +158,14 @@ fn rewrite( rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); } 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)); rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); + rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); } instr @ (F64Add | F64Mul | F64Min | F64Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; @@ -198,6 +206,10 @@ fn rewrite( IncMemoryLocal32(memarg, load_addr) ); rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg)); + rewrite!(instrs, i, + [BinOpStackLocal32(BinOp::FMul, local), F32Add] => + [LocalGet32(local), 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))) => @@ -313,6 +325,15 @@ fn rewrite( ); 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!(instrs, i, + [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => + MulAccLocal32(dst) + ); + rewrite!(instrs, i, + [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => + FMulAccLocal32(dst) + ); + rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, dst)); rewrite_local_set_direct!( instrs, i, @@ -403,6 +424,7 @@ fn rewrite( ); } LocalTee32(dst) => { + rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, dst)); fold_local_binop!( instrs, i, dst, source = resolve_local_source_32, @@ -501,16 +523,22 @@ fn rewrite( 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 - ), + Drop32 => { + rewrite!(instrs, i, + [BinOpStackLocalTee32(op, local, dst)] => + BinOpStackLocalSet32(op, local, dst) + ); + 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, diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index 0597847..05e36aa 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -250,18 +250,21 @@ impl LinkingError { } impl From for Error { + #[cold] fn from(value: LinkingError) -> Self { Self::Linker(value) } } impl From for Error { + #[cold] fn from(value: TwasmError) -> Self { Self::Twasm(value) } } impl From for Error { + #[cold] fn from(value: Trap) -> Self { Self::Trap(value) } @@ -364,6 +367,7 @@ impl From for crate::std::io::Error { #[cfg(feature = "parser")] impl From for Error { + #[cold] fn from(value: tinywasm_parser::ParseError) -> Self { Self::Parser(value) } diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index b8de4e0..eb2351b 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -1,7 +1,6 @@ use alloc::collections::BTreeMap; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use core::hint::cold_path; use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag}; use tinywasm_types::*; @@ -175,8 +174,7 @@ impl Imports { fn compare_types(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(()) } @@ -187,14 +185,12 @@ impl Imports { 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(()), } @@ -268,8 +264,7 @@ impl Imports { } Extern::HostFunction(func) => { let ImportKind::Function(type_idx) = import.kind else { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); }; let expected_type_addr = type_addrs .get(type_idx as usize) @@ -277,8 +272,7 @@ impl Imports { 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) { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr()) } @@ -289,16 +283,14 @@ impl Imports { } } else { let Some(instance) = self.modules.get(import.module.as_ref()) else { - cold_path(); - return Err(LinkingError::unknown_import(import).into()); + return cold!(Err(LinkingError::unknown_import(import).into())); }; instance.validate_store(store)?; instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))? }; 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) { @@ -309,8 +301,7 @@ impl Imports { && 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); } @@ -336,8 +327,7 @@ impl Imports { type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?; if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.funcs.push(func_addr); } @@ -346,8 +336,7 @@ impl Imports { .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 { - cold_path(); - return Err(LinkingError::incompatible_import_type(import).into()); + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.tags.push(tag_addr); } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 23bb298..f45b718 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -111,8 +111,7 @@ impl ModuleInstance { #[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(()) } @@ -205,8 +204,7 @@ impl ModuleInstance { store.add_instance(instance.clone()); if let Some(trap) = elem_trapped.or(data_trapped) { - cold_path(); - return Err(trap.into()); + return cold!(Err(trap.into())); } Ok(instance) } @@ -356,8 +354,7 @@ impl ModuleInstance { 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() }) @@ -410,8 +407,7 @@ impl ModuleInstance { 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() }; @@ -464,8 +460,7 @@ impl ModuleInstance { 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}")))) } } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 051b12f..585819e 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -67,12 +67,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result> { macro_rules! exec_op { - (branch $target:expr, $condition:expr) => {{ - if $condition { - self.cf.instr_ptr = *$target as usize; - return Ok(None); - } - }}; (binary_fallible $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); @@ -185,6 +179,24 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); self.store.value_stack.push($exec(*$op, stack_val, global_val))?; }}; + (binop_stack_local $vt:ty, $exec:ident, $op:ident, $local:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; + }}; + (binop_stack_local_set $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + let value = $exec(*$op, lhs, rhs); + <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); + }}; + (binop_stack_local_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ + let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); + let lhs = <$vt>::stack_pop(&mut self.store.value_stack); + let value = $exec(*$op, lhs, rhs); + <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); + <$vt>::stack_push(&mut self.store.value_stack, value)?; + }}; (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ let rhs = <$ty>::stack_pop(&mut self.store.value_stack); let lhs = <$ty>::stack_pop(&mut self.store.value_stack); @@ -215,115 +227,83 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } - JumpIfZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) == 0), - JumpIfNonZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) != 0), - JumpIfZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) == 0), - JumpIfNonZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) != 0), - JumpIfRefNull(ip) => { + JumpIfZero32(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i32::stack_pop(&mut self.store.value_stack) == 0) { return Ok(None) }, + JumpIfNonZero32(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i32::stack_pop(&mut self.store.value_stack) != 0) { return Ok(None) }, + JumpIfZero64(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i64::stack_pop(&mut self.store.value_stack) == 0) { return Ok(None) }, + JumpIfNonZero64(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| i64::stack_pop(&mut self.store.value_stack) != 0) { return Ok(None) }, + JumpIfRefNull(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| { let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - exec_op!(branch ip, is_null); - }, - JumpIfRefNonNull(ip) => { + if is_null { ValueRef::stack_pop(&mut self.store.value_stack); } + is_null + }) { return Ok(None) }, + JumpIfRefNonNull(ip) => if Self::exec_jump_if(&mut self.cf, *ip, |_| { 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); - } - exec_op!(branch ip, is_non_null); - }, + if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } + is_non_null + }) { return Ok(None) }, BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) == 0), - JumpIfLocalNonZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) != 0), - JumpIfLocalZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) == 0), - JumpIfLocalNonZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) != 0), - JumpCmpStackConst32 { target_ip, imm, op } => { - let lhs = i32::stack_pop(&mut self.store.value_stack); - exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); - }, - JumpCmpStackConst64 { target_ip, imm, op } => { - let lhs = i64::stack_pop(&mut self.store.value_stack); - exec_op!(branch target_ip, cmp_i64(lhs, *imm, *op)); - }, - JumpCmpStackLocal32 { target_ip, local, op } => { + JumpIfLocalZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, + JumpIfLocalNonZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, + JumpIfLocalZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, + JumpIfLocalNonZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, + JumpCmpStackConst32 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, + JumpCmpStackConst64 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, + JumpCmpStackLocal32 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { let lhs = i32::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpStackLocal64 { target_ip, local, op } => { + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *local), *op) + }) { return Ok(None) }, + JumpCmpStackLocal64 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { let lhs = i64::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); - }, - BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - let lhs = exec_binop_32(*binop, lhs as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *cmp)); - }, + cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, *local), *op) + }) { return Ok(None) }, + BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let value = exec_binop_32(*op, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, cf, *local, value); + (value == 0) == *on_zero + }) { return Ok(None) }, + BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let lhs = exec_binop_32(*binop, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, cf, *local, lhs); + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *cmp) + }) { return Ok(None) }, BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { - let lhs = i32::stack_pop(&mut self.store.value_stack); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + let value = exec_binop_32(*op, i32::stack_pop(&mut self.store.value_stack) as u32, *imm as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); i32::stack_push(&mut self.store.value_stack, value)?; - exec_op!(branch target_ip, (value == 0) == *on_zero); + if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } }, - BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => { + BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { let global = self.module.resolve_global_addr(*global); - let lhs = i32::global_get(&self.store.state.globals, global); - let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + let value = exec_binop_32(*op, i32::global_get(&self.store.state.globals, global) as u32, *imm as u32) as i32; i32::global_set(&mut self.store.state.globals, global, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - IncLocalJump32 { target_ip, local, delta, on_zero } => { - let value = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, + (value == 0) == *on_zero + }) { return Ok(None) }, + IncLocalJump32 { target_ip, local, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let value = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, cf, *local, value); + (value == 0) == *on_zero + }) { return Ok(None) }, IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); i32::stack_push(&mut self.store.value_stack, value)?; - exec_op!(branch target_ip, (value == 0) == *on_zero); + if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } }, - IncGlobalJump32 { target_ip, global, delta, on_zero } => { + IncGlobalJump32 { target_ip, global, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { let global = self.module.resolve_global_addr(*global); let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); i32::global_set(&mut self.store.state.globals, global, value); - exec_op!(branch target_ip, (value == 0) == *on_zero); - }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); - }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, *local); - exec_op!(branch target_ip, cmp_i64(lhs, i64::from(*imm), *op)); - }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, *left); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); - }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, *left); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, *right); - exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); - }, + (value == 0) == *on_zero + }) { return Ok(None) }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + let lhs = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, cf, *local, lhs); + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *op) + }) { return Ok(None) }, + JumpCmpLocalConst32 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *local), *imm, *op)) { return Ok(None) }, + JumpCmpLocalConst64 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *local), i64::from(*imm), *op)) { return Ok(None) }, + JumpCmpLocalLocal32 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *left), i32::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, + JumpCmpLocalLocal64 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *left), i64::local_get(&self.store.value_stack, cf, *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); } @@ -375,6 +355,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), + BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), + BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), + BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), 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))), @@ -383,24 +366,24 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, - LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, |v| v)?, - LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, i32::from)?, - LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, + LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, + LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, + LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, + LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, + LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } @@ -921,6 +904,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(None) } + #[inline(always)] + fn exec_jump_if(cf: &mut CallFrame, target_ip: u32, condition: impl FnOnce(&CallFrame) -> bool) -> bool { + let condition = condition(cf); + if condition { + cf.instr_ptr = target_ip as usize; + } + condition + } + fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { let idx = ::stack_pop(&mut self.store.value_stack); let target_ip = if idx >= 0 && (idx as u32) < len { @@ -943,28 +935,23 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; - let addr = u32::try_from(self.store.state.exceptions.len()).map_err(|_| Trap::OutOfMemory)?; - self.store.state.exceptions.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + let addr = cold_err!(u32::try_from(self.store.state.exceptions.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.store.state.exceptions.try_reserve(1)).map_err(|_| Trap::OutOfMemory)?; let params = self.store.state.get_canonical_func_type(type_addr).params(); let mut payload = Vec::new(); - payload.try_reserve_exact(params.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(payload.try_reserve_exact(params.len())).map_err(|_| Trap::OutOfMemory)?; + let value_stack = &mut self.store.value_stack; for &ty in params.iter().rev() { payload.push(match ty { - WasmType::I32 | WasmType::F32 => { - TinyWasmValue::Value32(Value32::stack_pop(&mut self.store.value_stack)) - } - WasmType::I64 | WasmType::F64 => { - TinyWasmValue::Value64(Value64::stack_pop(&mut self.store.value_stack)) - } - WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(&mut self.store.value_stack)), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(&mut self.store.value_stack)), + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(Value32::stack_pop(value_stack)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(Value64::stack_pop(value_stack)), + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(value_stack)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(value_stack)), }); } payload.reverse(); - self.store - .state - .exceptions - .push(crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }); + let exception = crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }; + self.store.state.exceptions.push(exception); Ok(addr) } @@ -1076,8 +1063,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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); + return cold!(Err(Trap::CallStackOverflow)); }; self.store.call_stack.push(self.cf)?; @@ -1101,8 +1087,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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); + return cold!(Err(Trap::CallStackOverflow)); }; self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); if wasm_func.owner != self.module.id() { @@ -1123,10 +1108,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { params_may_gc: bool, ) -> Result { if let Some(host_func) = host_func.typed_callback() { - if let Err(error) = host_func.call_stack(self.store, self.module.id(), type_addr) { - cold_path(); - return Err(Trap::HostFunction(Box::new(error))); - } + 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()); } @@ -1135,8 +1118,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } let param_types = self.store.state.get_canonical_func_type(type_addr).params(); - let mut params = Vec::new(); - params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?; + let mut params = core::mem::take(&mut self.store.host_params); + debug_assert!(params.is_empty()); + cold_err!(params.try_reserve_exact(param_types.len())).map_err(|_| Trap::OutOfMemory)?; for &ty in param_types.iter().rev() { params.push(self.store.value_stack.pop_wasmvalue(&self.store.state, ty)); } @@ -1144,13 +1128,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if params_may_gc { self.store.state.pin_host_values(¶ms); } - let res = match host_func.call_values(self.store, self.module.id(), type_addr, ¶ms) { - Ok(res) => res, - Err(err) => { - cold_path(); - return Err(Trap::HostFunction(Box::new(err))); - } - }; + let result = host_func.call_values(self.store, self.module.id(), type_addr, ¶ms); + params.clear(); + self.store.host_params = params; + let res = cold_err!(result).map_err(|error| Trap::HostFunction(Box::new(error)))?; self.store.value_stack.extend_from_wasmvalues(&res)?; if TAIL { @@ -1192,8 +1173,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_self(&mut self) -> Result<(), Trap> { 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 { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(Err(Trap::CallStackOverflow)); }; 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))?; @@ -1206,8 +1186,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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); + return cold!(Err(Trap::CallStackOverflow)); }; self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); Ok(()) @@ -1226,13 +1205,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table = self.store.state.get_table(table_addr); let Ok(table) = table.get(table_idx) else { - cold_path(); - return Err(Trap::UndefinedElement { index: table_idx }); + return cold!(Err(Trap::UndefinedElement { index: table_idx })); }; let Some(func_ref) = table.addr() else { - cold_path(); - return Err(Trap::UninitializedElement { index: table_idx }); + return cold!(Err(Trap::UninitializedElement { index: table_idx })); }; self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr)) @@ -1245,11 +1222,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result { let func = self.store.state.get_func(func_addr).clone(); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { - cold_path(); - return Err(Trap::IndirectCallTypeMismatch { + return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - }); + })); } match func.kind { crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL { @@ -1267,8 +1243,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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); + return cold!(Err(Trap::NullFunctionReference)); }; self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr)) @@ -1284,7 +1259,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { return true; }; - self.switch_to_frame(caller); + if caller.func_addr == self.cf.func_addr { + self.cf = caller; + } else { + self.switch_to_frame(caller); + } false } @@ -1391,32 +1370,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec_load_local, const N: usize, TARGET: InternalValue>( - &mut self, - memarg: MemoryArg, - addr_local: u8, - cast: impl Fn(LOAD) -> TARGET, - ) -> Result<(), Trap> { - let value = cast(self.exec_load_local_value::(memarg, addr_local)?); - TARGET::stack_push(&mut self.store.value_stack, value) - } - - #[inline(always)] - fn exec_load_local_tee, 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::(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(()) - } - - #[inline(always)] - fn exec_load_local_set, const N: usize, TARGET: InternalValue>( + fn exec_load_local< + LOAD: MemValue, + const N: usize, + TARGET: InternalValue, + const SET_LOCAL: bool, + const TEE: bool, + >( &mut self, memarg: MemoryArg, addr_local: u8, @@ -1424,7 +1384,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let value = cast(self.exec_load_local_value::(memarg, addr_local)?); - TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); + 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(()) } @@ -1435,8 +1400,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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); + return cold!(Err(Trap::NullReference)); } Ok(()) } @@ -1459,8 +1423,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { if !self.exec_ref_matches(ty) { - cold_path(); - return Err(Trap::CastFailure); + return cold!(Err(Trap::CastFailure)); } Ok(()) } @@ -1468,8 +1431,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> { let value = ValueRef::stack_pop(&mut self.store.value_stack); if value.is_null() { - cold_path(); - return Err(Trap::NullI31Reference); + return cold!(Err(Trap::NullI31Reference)); } let value = if signed { value.i31_s().expect("validated i31.get operand") @@ -1479,11 +1441,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.push(value) } + fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { + let roots = (&self.store.value_stack.stack_32).into_iter().copied(); + let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; + self.store.value_stack.push(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 fields = &self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields; let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; if default { values.extend(fields.iter().map(|field| default_value(field.storage))); } else { @@ -1492,12 +1460,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } values.reverse(); } - let value = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(value) + self.push_gc_object(type_addr, values) } fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { @@ -1529,14 +1492,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let len = u32::stack_pop(&mut self.store.value_stack) as usize; let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; values.resize(len, value); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { @@ -1545,17 +1503,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; let len = len as usize; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + 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(); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option) -> Result<(), Trap> { @@ -1574,12 +1527,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = pop_value(&mut self.store.value_stack, storage); let index = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); - let object = self.store.state.gc_object(reference, type_addr)?; - if index >= object.values.len() { - return Err(Trap::ArrayOutOfBounds); - } - self.store.state.gc.set(reference, index, value).expect("live array element"); - Ok(()) + self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(reference, index, value).ok_or(Trap::ArrayOutOfBounds) } fn exec_array_len(&mut self) -> Result<(), Trap> { @@ -1636,34 +1585,19 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let data_addr = self.module.resolve_data_addr(data_index); let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); let values = decode_data(storage, data, src, len)?; - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let elem_addr = self.module.resolve_elem_addr(elem_index); - let items = self.store.state.elements[elem_addr as usize].items.as_deref().unwrap_or(&[]); - let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { - offset: src, - len, - max: items.len(), - })?; + let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; - values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); let type_addr = self.module.resolve_type_addr(type_index); - let reference = self.store.state.alloc_gc_object( - type_addr, - values, - (&self.store.value_stack.stack_32).into_iter().copied(), - )?; - self.store.value_stack.push(reference) + self.push_gc_object(type_addr, values) } fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { @@ -1690,18 +1624,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; - let items = self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize] - .items - .as_deref() - .unwrap_or(&[]); - let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { - offset: src, - len, - max: items.len(), - })?; + let items = + self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; - values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; + values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); Ok(()) } @@ -1764,13 +1691,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)); + let max = mem.inner.len(); 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(), - }); + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max })); } Ok(()) } @@ -1783,9 +1706,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 }); + let mem_len = mem.inner.len(); + if ((size + offset) as usize > data_len) || ((dst + size) as usize > mem_len) { + return cold!(Err(Trap::MemoryOutOfBounds { offset: offset as usize, len: size as usize, max: data_len })); } if size == 0 { @@ -1793,13 +1716,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } let Some(data) = &data.data else { - cold_path(); - return Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 }); + return cold!(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() }); + return cold!(Err(Trap::MemoryOutOfBounds { offset: dst as usize, len: size as usize, max: mem_len })); } Ok(()) } @@ -1850,17 +1771,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result<(), Trap> { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); let addr = Self::pop_memory_addr::(&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) - } - } + let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + self.store.value_stack.push(cast(value)) } fn exec_mem_store_lane + Copy, const N: usize>( @@ -1877,13 +1789,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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::(&mut self.store.value_stack, mem, offset)?; - match val.store_at(&mut *mem.inner, addr) { - Ok(()) => Ok(()), - Err(e) => { - cold_path(); - Err(e) - } - } + cold_err!(val.store_at(&mut *mem.inner, addr))?; + Ok(()) } fn exec_mem_store, const N: usize>( @@ -1898,13 +1805,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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::(&mut self.store.value_stack, mem, offset)?; - match val.store_at(&mut *mem.inner, addr) { - Ok(()) => Ok(()), - Err(e) => { - cold_path(); - Err(e) - } - } + cold_err!(val.store_at(&mut *mem.inner, addr))?; + Ok(()) } fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1937,19 +1839,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 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[offset..end]) + table.init(dst, items) } fn exec_table_grow(&mut self, table_index: u32) -> Result<(), Trap> { diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs index 62f1f8e..f4e2595 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}; @@ -51,14 +50,12 @@ impl CallStack { } if required_len > self.max_size || !self.dynamic { - cold_path(); - return Err(Trap::CallStackOverflow); + return cold!(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); + return cold!(Err(Trap::CallStackOverflow)); }; Ok(()) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index ceea9eb..0b37f51 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -102,8 +102,7 @@ impl Stack { #[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); + return cold!(Err(Trap::ValueStackOverflow)); } self.data.push(value); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index cc91a55..e2cbef0 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -168,10 +168,7 @@ macro_rules! impl_internalvalue { #[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); - } + cold_err!(stack.$stack.push($to_stack))?; Ok(()) } diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e6c9ab8..e941430 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -83,6 +83,8 @@ //! //! See the [`Imports`] documentation for more information. +#[macro_use] +mod macros; mod std; extern crate alloc; 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/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index c371763..2c847a7 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -1,5 +1,4 @@ use alloc::{format, vec::Vec}; -use core::hint::cold_path; use tinywasm_types::*; use super::{State, default_value}; @@ -108,8 +107,7 @@ pub(super) fn eval_const( stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); } Ref(_) => { - cold_path(); - return Err(Error::other("unsupported reference constant")); + return cold!(Err(Error::other("unsupported reference constant"))); } RefI31 => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; @@ -135,7 +133,7 @@ pub(super) fn eval_const( .as_ref(); let default = matches!(instruction, StructNewDefault(_)); let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; if default { values.extend(fields.iter().map(|field| default_value(field.storage))); } else { @@ -163,7 +161,7 @@ pub(super) fn eval_const( pop_value(&mut stack, storage)? }; let mut values = Vec::new(); - values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; + 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)?; } @@ -176,7 +174,7 @@ pub(super) fn eval_const( .field .storage; let mut values = Vec::new(); - values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(*len as usize)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..*len { values.push(pop_value(&mut stack, storage)?); } @@ -187,8 +185,7 @@ pub(super) fn eval_const( 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")); + return cold!(Err(Error::other("type mismatch in const i32 op"))); }; let out = match instruction { I32Add => (lhs as i32).wrapping_add(rhs as i32), @@ -202,8 +199,7 @@ pub(super) fn eval_const( 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")); + return cold!(Err(Error::other("type mismatch in const i64 op"))); }; let out = match instruction { I64Add => (lhs as i64).wrapping_add(rhs as i64), @@ -217,12 +213,10 @@ pub(super) fn eval_const( } let Some(value) = stack.pop() else { - cold_path(); - return Err(Error::other("empty const expression")); + return cold!(Err(Error::other("empty const expression"))); }; if !stack.is_empty() { - cold_path(); - return Err(Error::other("const expression did not reduce to single value")); + return cold!(Err(Error::other("const expression did not reduce to single value"))); } Ok(value) } diff --git a/crates/tinywasm/src/store/element.rs b/crates/tinywasm/src/store/element.rs index 4437bd4..8119fe8 100644 --- a/crates/tinywasm/src/store/element.rs +++ b/crates/tinywasm/src/store/element.rs @@ -1,4 +1,4 @@ -use crate::interpreter::ValueRef; +use crate::{Trap, interpreter::ValueRef}; use alloc::vec::Vec; use tinywasm_types::RefType; @@ -15,4 +15,13 @@ 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/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs index 2a87a5f..6431037 100644 --- a/crates/tinywasm/src/store/gc/mod.rs +++ b/crates/tinywasm/src/store/gc/mod.rs @@ -79,7 +79,7 @@ pub(crate) fn decode_data( return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() }); }; let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; values.extend(data[src..end].chunks_exact(width).map(|bytes| match width { 1 => TinyWasmValue::Value32(u32::from(bytes[0])), 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index be0f3b4..d9c7990 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -38,8 +38,7 @@ impl MemoryInstance { 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())) + cold!(Err(memory_oob(base as usize, N, self.inner.len()))) } } } @@ -50,8 +49,7 @@ impl MemoryInstance { match base.checked_add(offset).and_then(|addr| usize::try_from(addr).ok()) { Some(addr) => Ok(addr), None => { - cold_path(); - Err(memory_oob(base as usize, N, self.inner.len())) + cold!(Err(memory_oob(base as usize, N, self.inner.len()))) } } } @@ -108,13 +106,11 @@ impl MemoryInstance { ) -> 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())); + return cold!(Err(memory_oob(addr, len, mem.len()))); }; if end > mem.len() || end < addr { - cold_path(); - return Err(memory_oob(addr, len, mem.len())); + return cold!(Err(memory_oob(addr, len, mem.len()))); } Ok(()) } diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs index ef6dace..40451bb 100644 --- a/crates/tinywasm/src/store/memory/lazy.rs +++ b/crates/tinywasm/src/store/memory/lazy.rs @@ -1,5 +1,4 @@ use alloc::boxed::Box; -use core::hint::cold_path; use tinywasm_types::MemoryType; @@ -43,8 +42,7 @@ impl LazyLinearMemory { let storage = match self.backend.create(self.ty, self.initial_len) { Ok(storage) => storage, Err(Error::Trap(trap)) => { - cold_path(); - return Err(trap); + return cold!(Err(trap)); } Err(err) => panic!("lazy memory materialization failed: {err}"), }; diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index f25d4ae..739a6a4 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -54,21 +54,18 @@ pub trait LinearMemory { /// Writes all bytes in `src` starting at `addr`, or returns `None` if any byte could not be written. fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> { let Some(end) = addr.checked_add(src.len()) else { - cold_path(); - return None; + return cold!(None); }; if end > self.len() { - cold_path(); - return None; + return cold!(None); } let mut offset = 0; while offset < src.len() { let written = self.write(addr + offset, &src[offset..]); if written == 0 { - cold_path(); - return None; + return cold!(None); } offset += written; } @@ -134,21 +131,18 @@ pub trait LinearMemory { /// Reads exactly `dst.len()` bytes starting at `addr`. fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { let Some(end) = addr.checked_add(dst.len()) else { - cold_path(); - return None; + return cold!(None); }; if end > self.len() { - cold_path(); - return None; + return cold!(None); } let mut offset = 0; while offset < dst.len() { let read = self.read(addr + offset, &mut dst[offset..]); if read == 0 { - cold_path(); - return None; + return cold!(None); } offset += read; } @@ -377,13 +371,7 @@ macro_rules! impl_mem_traits { #[inline(always)] fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - match mem.$read(addr) { - Ok(bytes) => Ok(Self::from_le_bytes(bytes)), - Err(trap) => { - cold_path(); - Err(trap) - } - } + Ok(Self::from_le_bytes(cold_err!(mem.$read(addr))?)) } #[inline(always)] @@ -418,13 +406,7 @@ impl MemValue<16> for Value128 { #[inline(always)] fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - match mem.read_128(addr) { - Ok(bytes) => Ok(Self(bytes)), - Err(trap) => { - cold_path(); - Err(trap) - } - } + Ok(Self(cold_err!(mem.read_128(addr))?)) } #[inline(always)] diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs index fc5947c..206014e 100644 --- a/crates/tinywasm/src/store/memory/paged.rs +++ b/crates/tinywasm/src/store/memory/paged.rs @@ -45,13 +45,7 @@ impl PagedMemory { #[inline(always)] fn allocate_chunk(&self) -> Result, crate::Trap> { let mut chunk = Vec::new(); - match chunk.try_reserve_exact(self.chunk_size) { - Ok(()) => {} - Err(_) => { - cold_path(); - return Err(crate::Trap::OutOfMemory); - } - } + cold_err!(chunk.try_reserve_exact(self.chunk_size)).map_err(|_| crate::Trap::OutOfMemory)?; chunk.resize(self.chunk_size, 0); Ok(chunk.into_boxed_slice()) } @@ -135,13 +129,8 @@ impl LinearMemory for PagedMemory { 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); - } - } + cold_err!(self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len())) + .map_err(|_| crate::Trap::OutOfMemory)?; self.chunks.resize_with(new_chunk_count, || None); } else { self.chunks.truncate(new_chunk_count); diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index aa468ec..17b1f83 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,5 +1,4 @@ use alloc::vec::Vec; -use core::hint::cold_path; use super::{LinearMemory, memory_oob}; @@ -21,13 +20,7 @@ impl VecMemory { /// Prefer this backend when contiguous access is more important than grow performance. pub fn try_new(len: usize) -> Result { 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_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); Ok(Self { data }) } @@ -43,8 +36,7 @@ impl VecMemory { #[inline(always)] fn check_fixed_addr(&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())); + return cold!(Err(memory_oob(addr, N, self.data.len()))); } Ok(()) } @@ -61,13 +53,8 @@ impl LinearMemory for VecMemory { if new_len < self.data.len() { return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: 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); - } - } + cold_err!(self.data.try_reserve_exact(new_len.saturating_sub(self.data.len()))) + .map_err(|_| crate::Trap::OutOfMemory)?; self.data.resize(new_len, 0); Ok(()) } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 1aabfb3..46bb727 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -60,6 +60,7 @@ pub struct Store { pub(crate) state: State, pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, + pub(crate) host_params: Vec, } #[cfg(feature = "debug")] @@ -97,6 +98,7 @@ impl Store { state, call_stack: CallStack::new(engine.config()), value_stack: ValueStack::new(engine.config()), + host_params: Vec::new(), engine, execution_fuel: 0, execution_active: false, @@ -266,13 +268,7 @@ impl Store { 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, &self.engine.config().memory_backend))?); } Ok(start..start + memories.len() as MemAddr) } @@ -287,13 +283,7 @@ impl Store { ) -> Result<()> { self.state.globals.reserve(globals); for global in globals { - let value = match eval_const(&mut self.state, &global.init, out, func_addrs, type_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)); out.push(self.state.globals.push(ty, value)); } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 6d13579..601bb6a 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -118,9 +118,9 @@ impl State { TinyWasmValue::ValueRef(value) => Some(*value), _ => None, })); - self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.gc.collect(roots)).map_err(|_| Trap::OutOfMemory)?; } - self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory) + cold_err!(self.gc.alloc(type_addr, values, trace_references)).map_err(|_| Trap::OutOfMemory) } /// Pins a host-visible reference when it resolves to a managed GC object. diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 5cbce74..8e6c055 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -17,12 +17,12 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { - let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?; + let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { 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 }) } @@ -82,7 +82,7 @@ impl TableInstance { return Err(crate::Trap::TableOutOfBounds { offset: len, len: 1, max: self.elements.len() }); } - self.elements.try_reserve_exact(n).map_err(|_| Trap::OutOfMemory)?; + cold_err!(self.elements.try_reserve_exact(n)).map_err(|_| Trap::OutOfMemory)?; self.elements.resize(len, init); Ok(()) } diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index ac79f6a..e57309f 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -35,18 +35,18 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box get32 += 1, - Instruction::GlobalGet64(_) => get64 += 1, - Instruction::GlobalGet128(_) => get128 += 1, + Instruction::GlobalTee32(_) => tee32 += 1, + Instruction::GlobalTee64(_) => tee64 += 1, + Instruction::GlobalTee128(_) => tee128 += 1, Instruction::BinOpStackGlobal32(..) => fused32 += 1, Instruction::BinOpStackGlobal64(..) => fused64 += 1, _ => {} } } - assert_eq!((get32, get64, get128), (3, 2, 1)); + assert_eq!((tee32, tee64, tee128), (3, 2, 1)); assert_eq!((fused32, fused64), (1, 1)); let mut store = Store::default(); diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index a505aed..a43c82c 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -203,6 +203,9 @@ pub enum Instruction { BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr), BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr), BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr), + BinOpStackLocal32(BinOp, LocalAddr), + BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), + BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx), -- cgit v1.3.1 From 358a183e5c12c32b8836acf9c71799f56e00b036 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 17 Aug 2026 20:07:51 +0200 Subject: chore: reduce instruction enum size (#52) this is a fairly big commit since I've been just playing around with this for a while now. the main goal is to reduce instruction size by moving some operands into two separate vecs. memory operations still seem like the biggest issue right now, so as a follow op I'll probably remove the public linear memory trait again but let's see how this goes first. performance wise this is about the same as before, but serialization/deserialization is about 20% faster now. Signed-off-by: Henry --------- Signed-off-by: Henry --- CHANGELOG.md | 1 + Cargo.lock | 8 +- crates/parser/src/conversion.rs | 33 +- crates/parser/src/lib.rs | 16 + crates/parser/src/macros.rs | 155 +-- crates/parser/src/module.rs | 42 +- crates/parser/src/optimize.rs | 1201 ----------------- crates/parser/src/optimize/mod.rs | 4 + crates/parser/src/optimize/rewrite.rs | 1397 ++++++++++++++++++++ crates/parser/src/optimize/targets.rs | 290 ++++ crates/parser/src/parallel.rs | 12 +- crates/parser/src/visit.rs | 281 +++- crates/tinywasm/src/interpreter/executor.rs | 543 ++++---- .../tinywasm/src/interpreter/stack/value_stack.rs | 11 + crates/tinywasm/src/interpreter/values.rs | 6 + .../tests/wasm-custom/conditional-rewrite.wast | 35 + .../tests/wasm-custom/sign-extension-rewrite.wast | 59 + .../tests/wasm-custom/simd-stack-local.wast | 53 + crates/types/src/archive.rs | 26 + crates/types/src/instructions.rs | 795 ++++++++--- crates/types/src/lib.rs | 13 +- crates/types/src/operands.rs | 177 +++ crates/types/src/reference.rs | 12 + 23 files changed, 3221 insertions(+), 1949 deletions(-) delete mode 100644 crates/parser/src/optimize.rs create mode 100644 crates/parser/src/optimize/mod.rs create mode 100644 crates/parser/src/optimize/rewrite.rs create mode 100644 crates/parser/src/optimize/targets.rs create mode 100644 crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/simd-stack-local.wast create mode 100644 crates/types/src/operands.rs (limited to 'Cargo.lock') diff --git a/CHANGELOG.md b/CHANGELOG.md index 3427a80..701fc84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `WasmValue::ty` and `WasmValue::matches_type` - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. +- Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. ### Changed diff --git a/Cargo.lock b/Cargo.lock index b06f70f..3c13501 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.2" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" dependencies = [ "find-msvc-tools", "shlex", @@ -365,9 +365,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" [[package]] name = "float-cmp" diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 480a8d0..b94ebe6 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,7 +1,7 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources}; #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; -use crate::{Result, module::FunctionCode, visit::process_operators}; +use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators}; use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; @@ -149,6 +149,7 @@ pub(crate) fn convert_module_code( reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, ty_idx: u32, + options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let locals_reader = func.get_locals_reader()?; #[cfg(feature = "validate")] @@ -194,32 +195,40 @@ pub(crate) fn convert_module_code( let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, - local_types, - local_addr_map, + (local_types, local_addr_map), metadata, ty_idx, reader_allocs, + options.deduplicate_operands(), )?; (body, data, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) }; - Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false }, - validator_allocs, - reader_allocs, - )) + Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 8db7920..90e239b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -65,6 +65,10 @@ pub struct ParserOptions { pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. + /// + /// This uses more parse CPU to reduce precompiled module and archive size. + pub deduplicate_operands: bool, #[cfg(parallel_parser)] /// Number of threads to use for parallel parsing. @@ -83,6 +87,7 @@ impl Default for ParserOptions { validation: cfg!(feature = "validate"), optimize_local_memory_allocation: true, optimize_rewrite: true, + deduplicate_operands: false, #[cfg(parallel_parser)] parser_threads: None, } @@ -134,6 +139,17 @@ impl ParserOptions { self.optimize_rewrite } + /// 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 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. /// diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 9fa7a01..5e675e6 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,10 +72,17 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; + let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into()) + lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } }; + (@memory_instruction $instr:ident $memory_arg_idx:ident) => { + Instruction::$instr($memory_arg_idx) + }; + (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { + Instruction::$instr(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)*); }; @@ -191,6 +198,20 @@ pub(crate) mod optimize { ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { replace!($instructions, $read, $consumed => [$out]); }; + ($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()); + *$read = $instructions.len() - 1; + }}; + ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { + replace!($instructions, *$read, $consumed => [$out]) + }; } macro_rules! rewrite { @@ -201,16 +222,13 @@ pub(crate) mod optimize { }; ($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 - { + if $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 + continue; } } }}; @@ -221,128 +239,5 @@ pub(crate) mod optimize { }; } - 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, 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 {replace, rewrite}; } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 3d38ad6..8138666 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -10,6 +10,12 @@ use tinywasm_types::*; use wasmparser::{OperatorsReaderAllocations, Payload}; pub(crate) struct FunctionCode { + pub instructions: Vec, + pub data: crate::visit::FunctionDataBuilder, + pub locals: ValueCounts, +} + +pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, @@ -22,19 +28,15 @@ pub(crate) fn optimize_function_code( function_results: ValueCounts, self_func_addr: u32, imported_memory_count: u32, -) -> Result { - 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) +) -> Result { + let optimized = + optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; + let data = code.data.finish(); + let uses_local_memory = optimized + .instructions + .iter() + .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) } #[derive(Default)] @@ -53,7 +55,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, - pub(crate) code: Vec, + pub(crate) code: Vec, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -402,7 +404,7 @@ impl<'a> ModuleReader<'a> { 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, ty_idx, options)?; self.code.push(optimize_function_code( code, @@ -565,7 +567,7 @@ impl<'a> ModuleReader<'a> { .into_iter() .zip(self.code_type_addrs) .zip(self.code_results) - .map(|((code, ty_idx), results)| { + .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()); @@ -573,15 +575,15 @@ impl<'a> ModuleReader<'a> { local_memory_allocation = LocalMemoryAllocation::Eager; } - Arc::new(WasmFunction { - instructions: code.instructions.into(), + Ok(Arc::new(WasmFunction { + instructions: code.instructions.into_boxed_slice(), data: code.data, locals: code.locals, params, results, - }) + })) }) - .collect(); + .collect::>()?; Ok(ModuleInner { funcs, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs deleted file mode 100644 index 969d686..0000000 --- a/crates/parser/src/optimize.rs +++ /dev/null @@ -1,1201 +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, - pub(crate) uses_local_memory: bool, -} - -struct CompactOutput { - instructions: Vec, - block_start: usize, - tail_rewritten: bool, -} - -impl Deref for CompactOutput { - type Target = Vec; - - 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, - function_data: &mut WasmFunctionData, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, - imported_memory_count: u32, -) -> Result { - 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, - boundaries: &[bool], - function_results: ValueCounts, - self_func_addr: u32, -) -> (Vec, Vec) { - 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, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); - rewrite!(instrs, i, [I32Add] => I32Add3); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::IAdd, local)] => - [LocalGet32(local), 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, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - 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, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(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, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(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 @ (I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(left), LocalGet32(right)] => CmpLocalLocal32(op, left, right)); - } - instr @ (I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(left), LocalGet64(right)] => CmpLocalLocal64(op, left, right)); - } - 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, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - 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)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - 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, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, 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)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, 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, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); - rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, 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)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, 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, - [BinOpStackLocal32(BinOp::FMul, local), F32Add] => - [LocalGet32(local), 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)) - } - GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - 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!(instrs, i, - [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => - MulAccLocal32(dst) - ); - rewrite!(instrs, i, - [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => - FMulAccLocal32(dst) - ); - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, 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) => { - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, 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!(instrs, i, - [BinOpStackLocalTee32(op, local, dst)] => - BinOpStackLocalSet32(op, local, dst) - ); - 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, [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, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - 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 }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - 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, [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, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op } - ); - 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 }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - 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 { - 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 inc_delta(op: BinOp, imm: i32) -> Option { - match op { - BinOp::IAdd => Some(imm), - BinOp::ISub => Some(imm.wrapping_neg()), - _ => None, - } -} - -fn int_bin_op(instr: Instruction) -> Option { - 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 { - 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 { - int_bin_op(instr).or_else(|| float_bin_op(instr)) -} - -fn scalar_const_32(instr: Instruction, op_instr: Instruction) -> Option { - 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 { - 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 { - 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 { - 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::BrOnCast(ip, _, _) - | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } - | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } - | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } - | Instruction::IncLocalJump32 { target_ip: ip, .. } - | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } - | Instruction::IncGlobalJump32 { target_ip: ip, .. } - | Instruction::IncLocalJumpCmpLocal32 { 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 { - let mut instr = *instr; - instruction_target_mut(&mut instr).copied() -} - -fn canonicalize_jump_like(source: &[Instruction], instrs: &mut Vec, 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, 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(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} - -fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &function_data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })?; - *boundary = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; - *boundary = true; - } - } - 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 { - let len = instructions.len() as u32; - for handler in &mut function_data.exception_handlers { - if let Some(old_to_new) = old_to_new { - handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) - })?; - handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) - })?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) - })?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { - return Err(ParseError::Other("exception landing pad out of bounds".into())); - } - } - 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/optimize/mod.rs b/crates/parser/src/optimize/mod.rs new file mode 100644 index 0000000..09501f9 --- /dev/null +++ b/crates/parser/src/optimize/mod.rs @@ -0,0 +1,4 @@ +mod rewrite; +mod targets; + +pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs new file mode 100644 index 0000000..1146da7 --- /dev/null +++ b/crates/parser/src/optimize/rewrite.rs @@ -0,0 +1,1397 @@ +use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; +use crate::macros::optimize::{replace, rewrite}; +use crate::visit::FunctionDataBuilder as WasmFunctionData; +use crate::{ParserOptions, Result}; +use alloc::vec::Vec; +use core::ops::{Deref, DerefMut}; +use tinywasm_types::{ + BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, + I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, + LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, + MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, + ValueCounts, +}; + +pub(crate) struct OptimizeResult { + pub(crate) instructions: Vec, +} + +struct CompactOutput { + instructions: Vec, + block_start: usize, +} + +macro_rules! operand { + ($data:expr, $value:expr) => { + $data.push_operand($value) + }; +} + +macro_rules! target_operand { + ($data:expr, $value:expr) => { + $data.push_target_operand($value) + }; +} + +impl Deref for CompactOutput { + type Target = Vec; + + 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( + mut instructions: Vec, + function_data: &mut WasmFunctionData, + options: &ParserOptions, + function_results: ValueCounts, + self_func_addr: u32, +) -> Result { + let boundaries = target_boundaries(&instructions, function_data)?; + let (rewritten, old_to_new) = if options.optimize_rewrite() { + let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; + (instructions, Some(map)) + } else { + (instructions, None) + }; + instructions = rewritten; + finalize(&mut instructions, function_data, old_to_new.as_deref())?; + Ok(OptimizeResult { instructions }) +} + +fn rewrite( + source: Vec, + data: &mut WasmFunctionData, + boundaries: &[bool], + function_results: ValueCounts, + self_func_addr: u32, +) -> Result<(Vec, Vec)> { + #![allow(unused_assignments)] + use Instruction::*; + + let return_instruction = 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, + }; + let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; + let mut old_to_new = alloc::vec![0; source.len() + 1]; + let mut after_terminator = false; + + for (old_index, instruction) in source.iter().copied().enumerate() { + if boundaries[old_index] || after_terminator { + output.block_start = output.len(); + } + after_terminator = is_unconditional_terminator(instruction); + old_to_new[old_index] = output.len() as u32; + output.push(instruction); + let mut read = output.len() - 1; + + match output[read] { + LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { + output.pop(); + } + Call(address) if address == self_func_addr => output[read] = CallSelf, + ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, + Return if let Some(specialized) = return_instruction => output[read] = specialized, + raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const32(value)] => AddConst32(value)); + rewrite!(output, read, [I32Add] => I32Add3); + if read > output.block_start + && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] + { + output.truncate(read - 1); + output.extend([LocalGet32(local), I32Add3]); + read = output.len() - 1; + } + } + } + raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend32(&mut output, &mut read, data, op); + } + raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const64(index)] => AddConst64(index)); + rewrite!(output, read, [I64Add] => I64Add3); + } + } + raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend64(&mut output, &mut read, data, op); + } + raw if cmp_op(raw).is_some() => { + let op = cmp_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); + } + raw @ (F32Add | F32Mul | F32Min | F32Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + } + raw @ (F32Sub | F32Div | F32Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + } + raw @ (F64Add | F64Mul | F64Min | F64Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + } + raw @ (F64Sub | F64Div | F64Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + } + raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { + let op = bin_op_128(raw).unwrap(); + rewrite!(output, read, [LocalGet128(local)] => + BinOpStackLocal128(op, local) + ); + rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; + } + I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, + I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, + V128Store(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, + [LocalGet32(addr), LocalGet128(value)] if + (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => + StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) + ); + } + } + I32Load(index) | F32Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + I64Load(index) | F64Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => match raw { + I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + _ => unreachable!(), + } + ); + } + } + MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { + let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + replace!(output, read, 2 => MemoryFillConst(index)); + }), + GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), + LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), + LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), + LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), + LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, + LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, + LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, + LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, + LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, + LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, + Drop32 => { + rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); + rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); + rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); + rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); + rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); + } + Drop64 => { + rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); + rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); + rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); + } + Drop128 => { + rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); + rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); + rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); + } + Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, + JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, + JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, + JumpIfZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpIfNonZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpCmpStackConst32(_) + | JumpCmpStackConst64(_) + | JumpCmpLocalConst32(_) + | JumpCmpLocalConst64(_) + | JumpCmpLocalLocal32(_) + | JumpCmpLocalLocal64(_) + | JumpIfLocalZero32(_) + | JumpIfLocalNonZero32(_) + | JumpIfLocalZero64(_) + | JumpIfLocalNonZero64(_) => {} + _ => {} + } + } + for instruction in &mut output.instructions { + match *instruction { + Instruction::Const64(index) => { + let value = data.operand(index).value; + if value == i64::from(value as i32) { + *instruction = Instruction::Const64Imm(value as i32); + } + } + Instruction::Const128(index) => { + let value = u128::from_le_bytes(data.operand(index).value); + if let Ok(value) = u32::try_from(value) { + *instruction = Instruction::Const128Imm(value); + } + } + _ => {} + } + } + let end = old_to_new.len() - 1; + old_to_new[end] = output.len() as u32; + Ok((output.instructions, old_to_new)) +} + +fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::BinOpLocalConst32(packed) => { + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i32)) + } + _ => None, + } +} + +fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i64)) +} + +fn local_const128( + data: &WasmFunctionData, + instruction: Instruction, +) -> Option<(BinOp128, u16, OperandIdx)> { + let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value)) +} + +fn compact_memory_arg( + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; + Ok(Some(operand!(data, arg)?)) +} + +fn rewrite_scalar_const32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = &output[*read - 2..*read]; + let replacement = match previous { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::ISub => Instruction::SubLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( + PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + ), + [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { + Instruction::BinOpGlobalConst32(PackedOp::new( + op, + operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_scalar_const64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( + op, + operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + )), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( + PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( + PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) + && let Instruction::Const32(right) = output[*read - 1] + && shift == right + && matches!(shift, 16 | 24) + { + output.truncate(*read - 2); + output.extend([ + Instruction::LocalGet32(local), + if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, + ]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) + && let Instruction::Const64(index) = output[*read - 1] + && shift == data.operand(index).value + { + let instruction = match shift { + 56 => Instruction::I64Extend8S, + 48 => Instruction::I64Extend16S, + 32 => Instruction::I64Extend32S, + _ => return false, + }; + output.truncate(*read - 2); + output.extend([Instruction::LocalGet64(local), instruction]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_vector_binop( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp128, + commutative: bool, +) -> Result<()> { + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), + [Instruction::LocalGet128(local), Instruction::Const128(value)] => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + _ => return Ok(()), + }; + replace!(output, *read, 2 => replacement); + } + Ok(()) +} + +fn rewrite_store32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal32(arg), + Instruction::AddConst32(1), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + match previous { + [Instruction::F32Mul, Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); + } + [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_store64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal64(arg), + Instruction::Const64(one), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + && data.operand(one).value == 1 + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::F64Mul, Instruction::F64Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +macro_rules! local_const_set { + ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + if $tee { + Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) + } + }}; + ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + if $tee { + Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) + } + }}; + ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + if $tee { + Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) + } + }}; +} + +fn rewrite_local_set32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); + return Ok(()); + } + [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), + Instruction::Const32(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) + } + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalSet32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + if src == dst + && let Some(delta) = op.inc_delta(value) + { + replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); + } else { + let replacement = local_const_set!(data, 32, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 3 { + match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); + return Ok(()); + } + [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), + Instruction::Const64(index) => { + replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); + } + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); + } + 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() }; + let index = operand!(data, I64Operand { value: delta })?; + replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); + } else { + let replacement = local_const_set!(data, 64, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), + Instruction::Const128(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) + } + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const32(value), Instruction::I32And] => { + replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + [Instruction::Const32(value), Instruction::I32Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalTee32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + let replacement = local_const_set!(data, 32, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const64(value), Instruction::I64And] => { + replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + [Instruction::Const64(value), Instruction::I64Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + let replacement = local_const_set!(data, 64, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn int_bin_op(instruction: Instruction) -> Option { + Some(match instruction { + 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(instruction: Instruction) -> Option { + Some(match instruction { + 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 cmp_op(instruction: Instruction) -> Option { + Some(match instruction { + 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 bin_op_128(instruction: Instruction) -> Option { + Some(match instruction { + 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 jump_cmp_local_local( + data: &mut WasmFunctionData, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + Ok(if width64 { + Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +fn rewrite_jump( + source: &[Instruction], + output: &mut CompactOutput, + index: usize, + data: &mut WasmFunctionData, + old_index: u32, + target: u32, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + let exit = old_index + 1; + let body = target + 1; + if let Some(instruction) = source.get(target as usize).copied() { + match instruction { + Instruction::JumpCmpLocalLocal32(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + return Ok(()); + } + Instruction::JumpCmpLocalLocal64(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + return Ok(()); + } + _ => {} + } + } + if matches!(output[index], Instruction::Jump(_)) && target == exit { + output.truncate(index); + } else { + set_rewrite_target(&mut output[index], data, target)?; + } + Ok(()) +} + +fn jump_cmp_stack_local( + data: &mut WasmFunctionData, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, TargetLocal { target, local })?; + Ok(if width64 { + Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +fn jump_cmp_local_const32( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + return Ok(match op { + CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), + CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), + _ => Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + )), + }); + } + Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_local_const64( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), + CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), + _ => {} + } + } + Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) +} + +fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) +} + +fn update_jump( + data: &mut WasmFunctionData, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + Instruction::IncGlobalJump32(target_operand!( + data, + GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } + )?) + } else { + Instruction::IncLocalJump32(target_operand!( + data, + LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } + )?) + }) + } else { + Ok(if global { + Instruction::BinOpGlobalConstJump32(PackedOp::new( + op, + target_operand!( + data, + GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } + )?, + )) + } else { + Instruction::BinOpLocalConstJump32(PackedOp::new( + op, + target_operand!( + data, + LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } + )?, + )) + }) + } +} + +fn rewrite_conditional( + source: &[Instruction], + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + target: u32, + on_zero: bool, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + if *read > output.block_start + && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] + { + let value = data.operand(packed.index); + if value.local == value.dst { + let replacement = + update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 + && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = + [output[*read - 2], output[*read - 1]] + { + let value = data.operand(packed.index); + if value.global == dst { + let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && local == cond + { + let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + if *read >= output.block_start + 2 { + let update = match [output[*read - 2], output[*read - 1]] { + [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value, Some(BinOp::IAnd))) + } + [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value.wrapping_neg(), None)) + } + _ => None, + }; + if let Some((local, value, op)) = update { + let replacement = if let Some(op) = op { + Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + )) + } else { + Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?) + }; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && let Some(mut cmp) = cmp_op(raw_cmp) + { + let value = data.operand(packed.index); + if value.local == value.dst { + if on_zero { + cmp = cmp.inverse(); + } + let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + Instruction::IncLocalJumpCmpLocal32(PackedOp::new( + cmp, + target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + )) + } else { + Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( + (packed.op, cmp), + target_operand!( + data, + LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } + )?, + )) + }; + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::LocalGet32(local), Instruction::I32Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::LocalGet64(local), Instruction::I64Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { + let op = if on_zero { op } else { op.inverse() }; + let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + let previous = output[*read - 1]; + let replacement = match previous { + Instruction::I32Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) + } + Instruction::I64Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) + } + Instruction::CmpLocalLocal32(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) + } + Instruction::CmpLocalLocal64(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) + } + Instruction::LocalGet32(local) => Some(if on_zero { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + }), + Instruction::LocalGet64(local) => Some(if on_zero { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + }), + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match [output[*read - 3], output[*read - 2]] { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + Some(jump_cmp_local_const32(data, target, local, value, op)?) + } + [Instruction::LocalGet64(local), Instruction::Const64(index)] + if let Ok(value) = i32::try_from(data.operand(index).value) => + { + Some(jump_cmp_local_const64(data, target, local, value, op)?) + } + [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, false)?) + } + [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, true)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + } + if *read >= output.block_start + 2 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match output[*read - 2] { + Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), + Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), + Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), + Instruction::Const64(index) => { + Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + } + Ok(()) +} + +fn is_unconditional_terminator(instruction: Instruction) -> bool { + matches!( + instruction, + Instruction::Unreachable + | Instruction::Jump(_) + | Instruction::BranchTable(_) + | Instruction::Return + | Instruction::ReturnVoid + | Instruction::Return32 + | Instruction::Return64 + | Instruction::Return128 + | Instruction::ReturnCall(_) + | Instruction::ReturnCallSelf + | Instruction::ReturnCallIndirect(_) + | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef + ) +} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs new file mode 100644 index 0000000..36bdf2f --- /dev/null +++ b/crates/parser/src/optimize/targets.rs @@ -0,0 +1,290 @@ +use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::{ParseError, Result}; +use alloc::vec::Vec; +use tinywasm_types::{ + BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, + OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, +}; + +pub(super) trait TargetOperand: OperandType { + fn set_target(&mut self, target: u32); +} + +macro_rules! target_operands { + ($($name:ty),+ $(,)?) => {$( + impl TargetOperand for $name { + fn set_target(&mut self, target: u32) { self.target = target; } + } + )+}; +} + +target_operands!( + TargetLocal, + CastBranch, + StackConst32, + StackConst64, + LocalUpdate, + GlobalUpdate, + LocalUpdateCmp, + LocalConstCmp, + LocalLocalCmp, + BranchTableArg, +); + +pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { + let mut index = target as usize; + let mut steps = 0; + while let Some(instruction) = instructions.get(index) + && let Some(next) = instruction_target(data, *instruction) + && matches!(instruction, Instruction::Jump(_)) + && steps < instructions.len() + { + index = next as usize; + steps += 1; + } + index as u32 +} + +pub(super) fn set_rewrite_target( + instruction: &mut Instruction, + data: &mut FunctionDataBuilder, + target: u32, +) -> Result<()> { + use Instruction::*; + match instruction { + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BranchTable(index) => *index = push_target_copy(data, *index, target)?, + _ => set_target(instruction, data, target), + } + Ok(()) +} + +fn push_target_copy( + data: &mut FunctionDataBuilder, + index: OperandIdx, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.push_target_operand(value) +} + +fn push_packed_target_copy( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) +} + +fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { + use Instruction::*; + Some(match instruction { + Jump(target) + | JumpIfZero32(target) + | JumpIfNonZero32(target) + | JumpIfZero64(target) + | JumpIfNonZero64(target) + | JumpIfRefNull(target) + | JumpIfRefNonNull(target) => target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, + BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, + JumpCmpStackConst32(packed) => data.operand(packed.index).target, + JumpCmpStackConst64(packed) => data.operand(packed.index).target, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, + BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, + BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, + IncGlobalJump32(index) => data.operand(index).target, + IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, + BranchTable(index) => data.operand(index).target, + _ => return None, + }) +} + +fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + 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) => set_packed_operand_target(data, *packed, target), + BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), + JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + set_packed_operand_target(data, *packed, target) + } + BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), + IncGlobalJump32(index) => set_operand_target(data, *index, target), + IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), + BranchTable(index) => set_operand_target(data, *index, target), + _ => {} + } +} + +fn set_operand_target(data: &mut FunctionDataBuilder, index: OperandIdx, target: u32) +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.set_operand(index, value); +} + +fn set_packed_operand_target( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + data.set_operand(packed.index, value); +} + +fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { + let Instruction::BranchTable(index) = instruction else { return None }; + let operand = data.operand(index); + Some((operand.start, operand.len)) +} + +pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { + let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })? = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = + true; + } + } + for &instruction in instructions { + if let Some(target) = instruction_target(data, instruction) { + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; + } + if let Some((start, count)) = branch_table_range(data, instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let targets = 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 { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) + })? = true; + } + } + } + Ok(boundaries) +} + +fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result { + let target = if let Some(map) = old_to_new { + *map.get(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? + } else { + target + }; + if target >= len { + return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); + } + Ok(target) +} + +pub(super) fn finalize( + instructions: &mut [Instruction], + data: &mut FunctionDataBuilder, + old_to_new: Option<&[u32]>, +) -> Result<()> { + let len = instructions.len() as u32; + for handler in &mut data.exception_handlers { + if let Some(map) = old_to_new { + handler.start_ip = *map + .get(handler.start_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + handler.end_ip = *map + .get(handler.end_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = remap_target(*landing_pad, Some(map), len)?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + for target in &mut data.branch_table_targets { + *target = remap_target(*target, old_to_new, len)?; + } + for instruction in instructions { + if let Some(target) = instruction_target(data, *instruction) { + set_target(instruction, data, remap_target(target, old_to_new, len)?); + } + if let Some((start, count)) = branch_table_range(data, *instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + data.branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + } + } + Ok(()) +} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e0e3858..e29b38f 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{FunctionCode, optimize_function_code}; +use crate::module::{OptimizedFunctionCode, optimize_function_code}; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::sync::Arc; @@ -64,7 +64,7 @@ fn process_function_job( imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, -) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { +) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -74,12 +74,12 @@ fn process_function_job( }; 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, job.ty_idx, 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, job.ty_idx, options)? } }; @@ -100,7 +100,7 @@ fn process_chunk<'a>( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -130,7 +130,7 @@ pub(crate) fn process_pending( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index cecbb8c..8315fb5 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,10 +3,11 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::{boxed::Box, string::ToString, vec::Vec}; +use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, + MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, + TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -52,19 +53,107 @@ pub(crate) struct ModuleMetadata { aggregate_fields: Vec, } +pub(crate) struct FunctionDataBuilder { + pub(crate) operands64: Vec, + pub(crate) operands128: Vec, + pub(crate) branch_table_targets: Vec, + pub(crate) exception_handlers: Vec, + deduplicate64: Option>, + deduplicate128: Option>, +} + +pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result; + fn get(builder: &FunctionDataBuilder, index: u32) -> Self; + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); +} + +macro_rules! builder_raw_operand { + ($raw:ty, $lane:ident, $map:ident) => { + impl BuilderRawOperand for $raw { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result { + if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { + return Ok(*index); + } + let index = u32::try_from(builder.$lane.len()) + .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; + builder.$lane.push(raw); + if deduplicate && let Some(map) = &mut builder.$map { + map.insert(raw, index); + } + Ok(index) + } + + fn get(builder: &FunctionDataBuilder, index: u32) -> Self { + *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { + *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; + } + } + }; +} + +builder_raw_operand!(Operand64, operands64, deduplicate64); +builder_raw_operand!(Operand128, operands128, deduplicate128); + +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), + } + } + + pub(crate) fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), true).map(OperandIdx::new) + } + + pub(crate) fn push_target_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), false).map(OperandIdx::new) + } + + pub(crate) fn operand(&self, index: OperandIdx) -> T + where + T::Raw: BuilderRawOperand, + { + T::decode(::get(self, index.index())) + } + + pub(crate) fn set_operand(&mut self, index: OperandIdx, operand: T) + where + T::Raw: BuilderRawOperand, + { + ::set(self, index.index(), operand.encode()) + } + + 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(), + } + } +} + enum AggregateFields { Other, Struct(Box<[ValueLane]>), Array(ValueLane), } -#[derive(Default)] -struct FunctionDataBuilder { - v128_constants: Vec<[u8; 16]>, - branch_table_targets: Vec, - exception_handlers: Vec, -} - pub(crate) struct FunctionBuilder<'a> { instructions: Vec, data: FunctionDataBuilder, @@ -83,13 +172,14 @@ impl<'a> FunctionBuilder<'a> { local_types: Vec, local_addr_map: Vec, body_size: usize, + deduplicate_operands: bool, ) -> Self { Self { local_types, local_addr_map, metadata, instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::default(), + data: FunctionDataBuilder::new(deduplicate_operands), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, @@ -112,10 +202,18 @@ impl<'a> FunctionBuilder<'a> { &mut self, type_index: u32, field_index: u32, - instruction: fn(u32, u32) -> Instruction, + instruction: fn(OperandIdx) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32], &[size], instruction(operand)) + } + + fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + self.data.push_operand(operand) } } @@ -294,17 +392,19 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, 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 mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -319,29 +419,26 @@ pub(crate) fn process_operators( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, reader.into_allocations())) + Ok((builder.instructions, builder.data, reader.into_allocations())) } #[cfg(feature = "validate")] pub(crate) fn process_operators_and_validate( mut validator: FuncValidator, body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, FuncValidatorAllocations, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, 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(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -356,12 +453,7 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) + Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -395,7 +487,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } - fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } heap false [] => [S32] { visit_ref_null => RefNull } heap false [S32] => [S32] { visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, @@ -483,22 +574,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { 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, } - fixed [S32, S32] => [S32] { - visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, - visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, - } - fixed [S32, S32, S32, S32] => [] { - visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, - visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, - } - fixed [S32, S32, S32, S32, S32] => [] { - visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, - } array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } array_field [S32, S32] => [Field] { visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, @@ -533,7 +612,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -542,7 +622,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -555,7 +636,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { 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)) + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.emit(&inputs, &signature.results, Instruction::CallIndirect(operand)) } fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { @@ -579,7 +661,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { inputs.push(self.metadata.table_size(table_index)?); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index)); + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -851,7 +934,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { 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)); + let branch_operand = + self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { depth: u32, @@ -894,8 +979,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .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; + if let Instruction::BranchTable(index) = self.instructions[header_ip] { + let mut operand = self.data.operand(index); + operand.target = default_pad.pad_start as u32; + self.data.set_operand(index, operand); } for pad in &pads { @@ -921,26 +1008,66 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) + let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + } + + fn visit_i64_const(&mut self, value: i64) -> Self::Output { + let operand = self.push_operand(I64Operand { value })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) + let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) + let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(data_index, memory)) + let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) + } + + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + let address = self.metadata.table_size(table)?; + let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) + } + + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) + } + + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) + } + + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) + } + + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) + } + + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } fn visit_br_on_cast( @@ -1187,19 +1314,13 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - self.emit( - &[ValueLane::S128, ValueLane::S128], - &[ValueLane::S128], - Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), - )?; - self.data.v128_constants.push(lanes); - Ok(()) + let index = self.push_operand(V128Operand { value: 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(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; - self.data.v128_constants.push(*value.bytes()); - Ok(()) + let index = self.push_operand(V128Operand { value: *value.bytes() })?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1213,7 +1334,12 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + self.instructions.push(if branch_on_fail { + Instruction::BrOnCastFail(operand) + } else { + Instruction::BrOnCast(operand) + }); self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; @@ -1357,10 +1483,15 @@ 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; + if self.lane_counts.c32 != target.c32 { + self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + } + if self.lane_counts.c64 != target.c64 { + self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + } + if self.lane_counts.c128 != target.c128 { + self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); } - self.instructions.push(Instruction::DropKeep((base, keep).into())); } fn patch_jump(&mut self, jump_ip: usize, target: usize) { @@ -1369,10 +1500,14 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) => { + | Instruction::JumpIfRefNonNull(ip) => { *ip = target as u32; } + Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { + let mut operand = self.data.operand(*index); + operand.target = target as u32; + self.data.set_operand(*index, operand); + } _ => {} } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 0bdb474..9da4a7a 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -205,11 +205,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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::(*ty, *table)?; return Ok(None); } + CallIndirect(idx) => { self.exec_call_indirect::(*idx)?; return Ok(None); } CallRef(ty) => { self.exec_call_ref::(*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::(*ty, *table)? { return Ok(Some(())); } return Ok(None); } + ReturnCallIndirect(idx) => { if self.exec_call_indirect::(*idx)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::(*ty)? { return Ok(Some(())); } return Ok(None); } Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } @@ -228,79 +228,56 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } is_non_null }) { return Ok(None) }, - BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + JumpIfLocalZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpIfLocalZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::stack_pop(&mut self.store.value_stack); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i64::stack_pop(&mut self.store.value_stack); - cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = exec_binop_32(*op, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = exec_binop_32(*binop, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *cmp) - }) { return Ok(None) }, - BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { - let value = exec_binop_32(*op, i32::stack_pop(&mut self.store.value_stack) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = exec_binop_32(*op, i32::global_get(&self.store.state.globals, global) as u32, *imm as u32) as i32; + cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(None) } }, + BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32; i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { - let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - IncGlobalJump32 { target_ip, global, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value); i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *op) - }) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *local), *imm, *op)) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *local), i64::from(*imm), *op)) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *left), i32::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *left), i64::local_get(&self.store.value_stack, cf, *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); } + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(None) } }, + JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(None) } }, + JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(None) } }, + JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), + DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), + DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), + BranchTable(idx) => { self.exec_branch_table(*idx); 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))?, + LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), @@ -308,9 +285,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), - AddConst64(c) => exec_op!(unary i64 => 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 )), + AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); }, + IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)), + IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), @@ -322,59 +299,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), - BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), - BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); }, + AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, + AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; }, + BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; }, + BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; }, + BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), - 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::(*m, *addr_local, |v| v.wrapping_add(1))?, - IncMemoryLocal64(m, addr_local) => self.exec_inc_memory_local::(*m, *addr_local, |v| v.wrapping_add(1))?, - StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local), + SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), + SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)), + IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, + SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), @@ -388,7 +371,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, - Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, + Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?, + Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), @@ -502,32 +487,32 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { // GC objects StructNew(ty) => self.exec_struct_new(*ty, false)?, StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, - StructGet(ty, field) => self.exec_struct_get(*ty, *field, None)?, - StructGetS(ty, field) => self.exec_struct_get(*ty, *field, Some(true))?, - StructGetU(ty, field) => self.exec_struct_get(*ty, *field, Some(false))?, - StructSet(ty, field) => self.exec_struct_set(*ty, *field)?, + StructGet(idx) => self.exec_struct_get(*idx, None)?, + StructGetS(idx) => self.exec_struct_get(*idx, Some(true))?, + StructGetU(idx) => self.exec_struct_get(*idx, Some(false))?, + StructSet(idx) => self.exec_struct_set(*idx)?, ArrayNew(ty) => self.exec_array_new(*ty, false)?, ArrayNewDefault(ty) => self.exec_array_new(*ty, true)?, - ArrayNewFixed(ty, len) => self.exec_array_new_fixed(*ty, *len)?, - ArrayNewData(ty, data) => self.exec_array_new_data(*ty, *data)?, - ArrayNewElem(ty, elem) => self.exec_array_new_elem(*ty, *elem)?, + ArrayNewFixed(idx) => self.exec_array_new_fixed(*idx)?, + ArrayNewData(idx) => self.exec_array_new_data(*idx)?, + ArrayNewElem(idx) => self.exec_array_new_elem(*idx)?, ArrayGet(ty) => self.exec_array_get(*ty, None)?, ArrayGetS(ty) => self.exec_array_get(*ty, Some(true))?, ArrayGetU(ty) => self.exec_array_get(*ty, Some(false))?, ArraySet(ty) => self.exec_array_set(*ty)?, ArrayLen => self.exec_array_len()?, ArrayFill(ty) => self.exec_array_fill(*ty)?, - ArrayCopy(dst, src) => self.exec_array_copy(*dst, *src)?, - ArrayInitData(ty, data) => self.exec_array_init_data(*ty, *data)?, - ArrayInitElem(ty, elem) => self.exec_array_init_elem(*ty, *elem)?, + ArrayCopy(idx) => self.exec_array_copy(*idx)?, + ArrayInitData(idx) => self.exec_array_init_data(*idx)?, + ArrayInitElem(idx) => self.exec_array_init_elem(*idx)?, 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)?, + MemoryCopy(idx) => self.exec_memory_copy(*idx)?, 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)?, + MemoryFillConst(idx) => self.exec_memory_fill_const(*idx)?, + MemoryInit(idx) => self.exec_memory_init(*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(), @@ -535,37 +520,37 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)?, + TableInit(idx) => self.exec_table_init(*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)?, + TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - I64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, + I32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + I64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I32Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I64Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store32(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i32)?, - I32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I32Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I64Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, + I32Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I32Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I64Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store32(idx) => self.exec_mem_store::(*idx, |v| v as i32)?, + I32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I32Load8S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load8U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I64Load8S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load8U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32U(idx) => self.exec_mem_load::(*idx, i64::from)?, // Numeric conversion operations F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), @@ -637,25 +622,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i8)?, - V128Load16Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i16)?, - V128Load32Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i32)?, - V128Load64Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i64)?, - V128Store(arg) => self.exec_mem_store::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Store8Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store16Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store32Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + V128Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + V128Load8x8S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i8)?, + V128Load16Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i16)?, + V128Load32Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i32)?, + V128Load64Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i64)?, + V128Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Load32Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?, I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), @@ -664,10 +649,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), - V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, + V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), @@ -822,7 +807,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&self.func.data).value))), I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), @@ -900,25 +885,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { condition } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { + fn exec_branch_table(&mut self, index: OperandIdx) { + let v = index.get(&self.func.data); let idx = ::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) + let target_ip = if idx >= 0 && (idx as u32) < v.len { + self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target) } else { - default_ip + v.target }; 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 create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; @@ -1043,22 +1021,26 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - 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 { + fn exec_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(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() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1066,21 +1048,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 { + fn exec_return_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.params); + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); - if wasm_func.owner != self.module.id() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1132,11 +1118,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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), + let func = self.store.state.get_func(addr); + match &func.kind { + crate::store::FunctionKind::Wasm(wasm_func) => { + self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr) + } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params)?; + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params)?; Ok(()) } } @@ -1145,14 +1133,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_return_call_direct(&mut self, v: u32) -> Result { 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 { + let func = self.store.state.get_func(addr); + match &func.kind { crate::store::FunctionKind::Wasm(wasm_func) => { - self.exec_return_call(wasm_func, addr)?; + self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; Ok(false) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params) + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params) } } } @@ -1179,11 +1167,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_call_indirect( - &mut self, - type_addr: u32, - table_addr: u32, - ) -> Result { + fn exec_call_indirect(&mut self, index: OperandIdx) -> Result { + let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); 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 @@ -1207,20 +1192,20 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { func_addr: FuncAddr, expected_type_addr: TypeAddr, ) -> Result { - let func = self.store.state.get_func(func_addr).clone(); + let func = self.store.state.get_func(func_addr); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), })); } - match func.kind { + 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), + true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), + false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr), }, crate::store::FunctionKind::Host(host_func) => { - return self.exec_call_host::(host_func, func.type_addr, func.gc.params); + return self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params); } }?; Ok(false) @@ -1287,7 +1272,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, value_local: u8, ) -> Result<(), Trap> { @@ -1313,7 +1298,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_inc_memory_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { @@ -1333,7 +1318,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = T::load_at(&*mem.inner, addr)?; + let value = cold_err!(T::load_at(&*mem.inner, addr))?; increment(value).store_at(&mut *mem.inner, addr) } @@ -1343,7 +1328,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const N: usize, >( &mut self, - m: MemoryArg, + m: CompactMemoryArg, ) -> Result<(), Trap> { let rhs = T::stack_pop(&mut self.store.value_stack); let lhs = T::stack_pop(&mut self.store.value_stack); @@ -1361,7 +1346,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_load_local_value, const N: usize>( &self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, ) -> Result { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); @@ -1377,7 +1362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - T::load_at(&*mem.inner, addr) + cold_err!(T::load_at(&*mem.inner, addr)) } #[inline(always)] @@ -1389,7 +1374,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const TEE: bool, >( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, dst_local: u8, cast: impl Fn(LOAD) -> TARGET, @@ -1474,7 +1459,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { + fn exec_struct_get(&mut self, index: OperandIdx, signed: Option) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); 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 @@ -1485,7 +1471,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { push_value(&mut self.store.value_stack, value, storage, signed) } - fn exec_struct_set(&mut self, type_index: TypeAddr, field_index: u32) -> Result<(), Trap> { + fn exec_struct_set(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); 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] @@ -1508,7 +1495,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { + fn exec_array_new_fixed(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: len } = index.get(&self.func.data); 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; @@ -1567,7 +1555,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_copy(&mut self, dst_type: TypeAddr, src_type: TypeAddr) -> Result<(), Trap> { + fn exec_array_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data); 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); @@ -1588,7 +1577,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_new_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_new_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); 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); @@ -1599,7 +1589,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_new_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let elem_addr = self.module.resolve_elem_addr(elem_index); @@ -1611,7 +1602,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_init_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); 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; @@ -1627,7 +1619,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_init_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_init_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); 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; @@ -1669,7 +1662,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<(), Trap> { + fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); let src_mem_addr = self.module.resolve_mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); @@ -1701,7 +1695,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) } - fn exec_memory_fill_imm(&mut self, addr: u32, val: u8, size: i32) -> Result<(), Trap> { + fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { + let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); let mem_addr = self.module.resolve_mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; @@ -1717,7 +1712,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_init(&mut self, data_index: u32, mem_index: u32) -> Result<(), Trap> { + fn exec_memory_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); 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.module.resolve_mem_addr(mem_index); @@ -1749,7 +1745,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<(), Trap> { + fn exec_table_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data); 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(); @@ -1772,15 +1769,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_load_lane, const LOAD_SIZE: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, + arg: MemoryLaneArg, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; - let val = LOAD::load_at(&*mem.inner, addr)?; - let offset = lane as usize * LOAD_SIZE; + let addr = mem.effective_addr::(base, m.offset())?; + let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::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))?; @@ -1790,32 +1786,28 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = index.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; self.store.value_stack.push(cast(value)) } - fn exec_mem_store_lane + Copy, const N: usize>( - &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, - ) -> Result<(), Trap> { + fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { let bytes = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); - let lane_offset = lane as usize * N; + 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 mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1823,17 +1815,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_store, const N: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(T) -> U, ) -> Result<(), Trap> { let val = ::stack_pop(&mut self.store.value_stack); let val = cast(val); - let mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = index.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1862,7 +1854,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_table_init(&mut self, elem_index: u32, table_index: u32) -> Result<(), Trap> { + fn exec_table_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data); 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); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 43c214a..f2c0c28 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -109,6 +109,17 @@ impl Stack { Ok(()) } + #[inline(always)] + pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> { + if !self.ensure_capacity_for(self.data.len() + 1) { + 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")) diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index e2cbef0..4fb81c9 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -137,6 +137,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_peek(stack: &ValueStack) -> 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_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); @@ -178,6 +179,11 @@ macro_rules! impl_internalvalue { $from_stack } + #[inline(always)] + 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)] fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self) { let $to_stack_v = value; 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/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/types/src/archive.rs b/crates/types/src/archive.rs index 9904a7d..db40263 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -64,6 +64,9 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::{Instruction, ModuleInner, V128Operand, WasmFunction}; + use crate::{OperandIdx, OperandType}; + use alloc::{boxed::Box, sync::Arc, vec}; #[test] fn test_invalid_magic() { @@ -80,4 +83,27 @@ 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 = OperandIdx::new(0); + function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice(); + function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into(); + let module = Module::from(ModuleInner { funcs: Box::new([Arc::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.get(&function.data).value, bytes); + } + } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 10ab028..797f703 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,7 +1,8 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; +use crate::operands::sealed; +use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -13,13 +14,275 @@ pub struct MemoryArg { mem_addr: MemAddr, } -/// Stack lanes discarded and retained when branching to a control frame. -#[derive(Clone, Copy, PartialEq, Eq)] +/// 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 MemoryLocalArg { + pub memory_arg_idx: OperandIdx, + 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: OperandIdx, + 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, +} + +impl sealed::Sealed for LocalTripleArg {} + +impl OperandType for LocalTripleArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst) + } +} + +/// 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, +} + +macro_rules! operand_view { + ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => { + #[derive(Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "debug", derive(Debug))] + pub struct $name { + $(pub $field: $ty),+ + } + + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { $($field: raw.$read::<$offset>() as $ty),+ } + } + + #[inline] + fn encode(self) -> Self::Raw { + <$raw>::default()$(.$write::<$offset>(self.$field as _))+ + } + } + }; +} + +operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) }); +operand_view!(TwoU32, operands64, Operand64, { + first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4) +}); +operand_view!(LocalU32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2) +}); +operand_view!(TargetLocal, operands64, Operand64, { + target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4) +}); + +operand_view!(LocalConst64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2) +}); +operand_view!(GlobalConst32, operands64, Operand64, { + global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4) +}); +operand_view!(GlobalConst64, operands128, Operand128, { + global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4) +}); +operand_view!(LocalConstSet32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4) +}); +operand_view!(LocalConstSet64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4) +}); +operand_view!(MemoryFillConstOp, operands128, Operand128, { + memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5) +}); +operand_view!(CastBranch, operands64, Operand64, { + target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4) +}); +operand_view!(BranchTableArg, operands128, Operand128, { + target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8) +}); +operand_view!(StackConst32, operands64, Operand64, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4) +}); +operand_view!(StackConst64, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4) +}); +operand_view!(LocalConstCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8) +}); +operand_view!(LocalLocalCmp, operands64, Operand64, { + target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6) +}); +operand_view!(LocalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10) +}); +operand_view!(GlobalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12) +}); +operand_view!(LocalUpdateCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10) +}); + +/// An operation packed inline with an indexed operand. +#[derive(Copy, Clone, 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, +#[cfg_attr( + feature = "archive", + serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",)) +)] +#[repr(Rust, packed)] +pub struct PackedOp { + pub op: Op, + pub index: OperandIdx, +} + +impl PackedOp { + /// Creates a packed operation from an operator and operand index. + #[inline] + pub const fn new(op: Op, index: OperandIdx) -> Self { + Self { op, index } + } +} + +/// A SIMD value stored in the 128-bit operand lane. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct V128Operand { + pub value: [u8; 16], +} + +/// A local SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalV128 { + pub local: u16, + pub value: OperandIdx, +} + +/// A global SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GlobalV128 { + pub global: u32, + pub value: OperandIdx, +} + +/// A local SIMD operation, indexed constant, and destination local. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalConstSetV128 { + pub local: u16, + pub dst: u16, + pub value: OperandIdx, +} + +macro_rules! operand_raw_view { + ($name:ident, $raw:ty, $decode:expr, $encode:expr) => { + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + $decode(raw) + } + + #[inline] + fn encode(self) -> Self::Raw { + $encode(self) + } + } + }; +} + +operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| { + Operand128::from_le_bytes(value.value) +}); +operand_raw_view!( + LocalV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) }, + |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) } +); +operand_raw_view!( + GlobalV128, + Operand64, + |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) } +); +operand_raw_view!( + LocalConstSetV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { + Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index()) + } +); + +impl CastBranch { + #[inline] + pub const fn ref_type(self) -> RefType { + match RefType::from_bits(self.ref_type_bits) { + Some(value) => value, + None => unreachable!(), + } + } } /// A catch clause attached to a lowered `try_table` instruction. @@ -62,12 +325,6 @@ pub struct ExceptionHandler { pub catches: Box<[ExceptionCatch]>, } -impl From<(ValueCounts, ValueCounts)> for DropKeep { - fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { - Self { base, keep } - } -} - impl MemoryArg { #[inline] pub const fn new(offset: u64, mem_addr: MemAddr) -> Self { @@ -85,6 +342,80 @@ impl MemoryArg { } } +impl sealed::Sealed for MemoryArg {} + +impl OperandType for MemoryArg { + type Raw = Operand128; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self::new(raw.u64::<0>(), raw.u32::<8>()) + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr) + } +} + +impl CompactMemoryArg { + /// Returns the static byte offset. + #[inline] + pub const fn offset(self) -> u64 { + self.offset as u64 + } + + /// Returns the module-local memory index. + #[inline] + pub const fn mem_addr(self) -> MemAddr { + self.mem_addr as MemAddr + } +} + +impl sealed::Sealed for CompactMemoryArg {} + +impl OperandType for CompactMemoryArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr) + } +} + +impl TryFrom for CompactMemoryArg { + type Error = (); + + #[inline] + fn try_from(arg: MemoryArg) -> Result { + Ok(Self { + offset: u32::try_from(arg.offset()).map_err(|_| ())?, + mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?, + }) + } +} + +impl From for MemoryArg { + #[inline] + fn from(arg: CompactMemoryArg) -> Self { + Self::new(arg.offset(), arg.mem_addr()) + } +} + +const _: () = { + assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::() == 8); + assert!(core::mem::size_of::() == 16); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); +}; + #[derive(Clone, Copy, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -132,6 +463,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))] @@ -156,6 +506,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 { + 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))] @@ -181,69 +543,47 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(i64), - IncLocal32(LocalAddr, i32), IncLocal64(LocalAddr, i64), + AddConst32(i32), AddConst64(OperandIdx), + IncLocal32(I32LocalArg), IncLocal64(PackedOp), // 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), CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, 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), - BinOpGlobalConst32(BinOp, GlobalAddr, i32), BinOpGlobalConst64(BinOp, GlobalAddr, i64), - BinOpGlobalConst128(BinOp128, GlobalAddr, ConstIdx), - 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), + AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), + BinOpLocalLocalSet32(PackedOp), BinOpLocalLocalSet64(PackedOp), BinOpLocalLocalSet128(PackedOp), + BinOpLocalLocalTee32(PackedOp), BinOpLocalLocalTee64(PackedOp), BinOpLocalLocalTee128(PackedOp), + AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), + BinOpLocalConst32(PackedOp), BinOpLocalConst64(PackedOp), + BinOpGlobalConst32(PackedOp), BinOpGlobalConst64(PackedOp), + BinOpGlobalConst128(PackedOp), BinOpLocalConst128(PackedOp), + BinOpLocalConstSet32(PackedOp), BinOpLocalConstSet64(PackedOp), BinOpLocalConstSet128(PackedOp), + BinOpLocalConstTee32(PackedOp), BinOpLocalConstTee64(PackedOp), BinOpLocalConstTee128(PackedOp), 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), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp), SetLocalConst128(PackedOp), + 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(PackedOp), SubConstTee64(PackedOp), + 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 @@ -255,28 +595,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 }, - JumpCmpStackLocal32 { target_ip: u32, local: LocalAddr, op: CmpOp }, - JumpCmpStackLocal64 { target_ip: u32, local: LocalAddr, op: CmpOp }, - BinOpLocalConstJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpLocalConstJumpCmpLocal32 { target_ip: u32, local: LocalAddr, imm: i32, binop: BinOp, right: LocalAddr, cmp: CmpOp }, - BinOpStackConstTeeLocalJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpGlobalConstJump32 { target_ip: u32, global: GlobalAddr, imm: i32, op: BinOp, on_zero: bool }, - IncLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncStackTeeLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncGlobalJump32 { target_ip: u32, global: GlobalAddr, delta: i32, on_zero: bool }, - IncLocalJumpCmpLocal32 { target_ip: u32, local: LocalAddr, delta: i32, right: LocalAddr, 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(PackedOp), JumpCmpStackConst64(PackedOp), + JumpCmpStackLocal32(PackedOp), JumpCmpStackLocal64(PackedOp), + BinOpLocalConstJump32(PackedOp), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>), + BinOpStackConstTeeLocalJump32(PackedOp), BinOpGlobalConstJump32(PackedOp), + IncLocalJump32(OperandIdx), IncStackTeeLocalJump32(OperandIdx), IncGlobalJump32(OperandIdx), + IncLocalJumpCmpLocal32(PackedOp), JumpCmpLocalConst32(PackedOp), JumpCmpLocalConst64(PackedOp), + JumpCmpLocalLocal32(PackedOp), JumpCmpLocalLocal64(PackedOp), + DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx), Return, ReturnVoid, Return32, @@ -284,11 +612,11 @@ pub enum Instruction { Return128, Call(FuncAddr), CallSelf, - CallIndirect(TypeAddr, TableAddr), + CallIndirect(OperandIdx), CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, - ReturnCallIndirect(TypeAddr, TableAddr), + ReturnCallIndirect(OperandIdx), ReturnCallRef(TypeAddr), Throw(TagAddr), ThrowRef, @@ -307,35 +635,18 @@ pub enum Instruction { 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(OperandIdx), I64Load(OperandIdx), F32Load(OperandIdx), F64Load(OperandIdx), + I32Load8S(OperandIdx), I32Load8U(OperandIdx), I32Load16S(OperandIdx), I32Load16U(OperandIdx), + I64Load8S(OperandIdx), I64Load8U(OperandIdx), I64Load16S(OperandIdx), I64Load16U(OperandIdx), I64Load32S(OperandIdx), I64Load32U(OperandIdx), + I32Store(OperandIdx), I64Store(OperandIdx), F32Store(OperandIdx), F64Store(OperandIdx), + I32Store8(OperandIdx), I32Store16(OperandIdx), I64Store8(OperandIdx), I64Store16(OperandIdx), I64Store32(OperandIdx), MemorySize(MemAddr), MemoryGrow(MemAddr), // > Constants Const32(i32), - Const64(i64), + Const64Imm(i32), + Const64(OperandIdx), // > Reference Types RefNull(RefType), @@ -348,29 +659,24 @@ pub enum Instruction { RefEq, RefTest(RefType), RefCast(RefType), - BrOnCast(u32, RefType, bool), + BrOnCast(OperandIdx), + BrOnCastFail(OperandIdx), // > GC Objects StructNew(TypeAddr), StructNewDefault(TypeAddr), - StructGet(TypeAddr, u32), - StructGetS(TypeAddr, u32), - StructGetU(TypeAddr, u32), - StructSet(TypeAddr, u32), + StructGet(OperandIdx), StructGetS(OperandIdx), StructGetU(OperandIdx), StructSet(OperandIdx), ArrayNew(TypeAddr), ArrayNewDefault(TypeAddr), - ArrayNewFixed(TypeAddr, u32), - ArrayNewData(TypeAddr, DataAddr), - ArrayNewElem(TypeAddr, ElemAddr), + ArrayNewFixed(OperandIdx), + ArrayNewData(OperandIdx), ArrayNewElem(OperandIdx), ArrayGet(TypeAddr), ArrayGetS(TypeAddr), ArrayGetU(TypeAddr), ArraySet(TypeAddr), ArrayLen, ArrayFill(TypeAddr), - ArrayCopy(TypeAddr, TypeAddr), - ArrayInitData(TypeAddr, DataAddr), - ArrayInitElem(TypeAddr, ElemAddr), + ArrayCopy(OperandIdx), ArrayInitData(OperandIdx), ArrayInitElem(OperandIdx), // > Numeric Instructions // See @@ -400,19 +706,18 @@ pub enum Instruction { I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // > Table Instructions - TableInit(ElemAddr, TableAddr), + TableInit(OperandIdx), TableGet(TableAddr), TableSet(TableAddr), - TableCopy { dst_table: TableAddr, src_table: TableAddr }, + TableCopy(OperandIdx), TableGrow(TableAddr), TableSize(TableAddr), TableFill(TableAddr), // > Bulk Memory Instructions - MemoryInit(DataAddr, MemAddr), - MemoryCopy { dst_mem: MemAddr, src_mem: MemAddr }, + MemoryInit(OperandIdx), MemoryCopy(OperandIdx), MemoryFill(MemAddr), - MemoryFillImm(MemAddr, u8, i32), + MemoryFillConst(OperandIdx), DataDrop(DataAddr), ElemDrop(ElemAddr), @@ -420,20 +725,18 @@ pub enum Instruction { I64Add128, I64Sub128, I64MulWideS, I64MulWideU, // > SIMD - V128Load(MemoryArg), - V128Load8x8S(MemoryArg), V128Load8x8U(MemoryArg), - V128Load16x4S(MemoryArg), V128Load16x4U(MemoryArg), - V128Load32x2S(MemoryArg), V128Load32x2U(MemoryArg), + V128Load(OperandIdx), V128Load8x8S(OperandIdx), V128Load8x8U(OperandIdx), + V128Load16x4S(OperandIdx), V128Load16x4U(OperandIdx), V128Load32x2S(OperandIdx), V128Load32x2U(OperandIdx), - V128Load8Splat(MemoryArg), V128Load16Splat(MemoryArg), V128Load32Splat(MemoryArg), V128Load64Splat(MemoryArg), - V128Load8Lane(MemoryArg, u8), V128Load16Lane(MemoryArg, u8), V128Load32Lane(MemoryArg, u8), V128Load64Lane(MemoryArg, u8), + V128Load8Splat(OperandIdx), V128Load16Splat(OperandIdx), V128Load32Splat(OperandIdx), V128Load64Splat(OperandIdx), + V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg), - V128Load32Zero(MemoryArg), V128Load64Zero(MemoryArg), + V128Load32Zero(OperandIdx), V128Load64Zero(OperandIdx), - V128Store(MemoryArg), V128Store8Lane(MemoryArg, u8), V128Store16Lane(MemoryArg, u8), V128Store32Lane(MemoryArg, u8), V128Store64Lane(MemoryArg, u8), + V128Store(OperandIdx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), - I8x16Shuffle(ConstIdx), - Const128(ConstIdx), + I8x16Shuffle(OperandIdx), + Const128Imm(u32), Const128(OperandIdx), I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8), I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8), @@ -485,10 +788,8 @@ pub enum Instruction { I32x4RelaxedTruncF64x2SZero, I32x4RelaxedTruncF64x2UZero, F32x4RelaxedMadd, F32x4RelaxedNmadd, F64x2RelaxedMadd, F64x2RelaxedNmadd, - I8x16RelaxedLaneselect, - I16x8RelaxedLaneselect, - I32x4RelaxedLaneselect, - I64x2RelaxedLaneselect, + I8x16RelaxedLaneselect, I16x8RelaxedLaneselect, + I32x4RelaxedLaneselect, I64x2RelaxedLaneselect, F32x4RelaxedMin, F32x4RelaxedMax, F64x2RelaxedMin, F64x2RelaxedMax, I16x8RelaxedQ15mulrS, @@ -496,88 +797,144 @@ pub enum Instruction { I32x4RelaxedDotI8x16I7x16AddS, } -const _: () = assert!(core::mem::size_of::() <= 16); +const _: () = assert!(core::mem::size_of::() == 8); impl Instruction { + /// Returns the largest module-local memory index used by this instruction. #[inline] - pub const fn memory_addr(&self) -> Option { - 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::MemoryFill(mem) | Self::MemoryFillImm(mem, ..) => { - Some(*mem) + pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { + use Instruction::*; + match *self { + IncMemoryLocal32(arg) + | IncMemoryLocal64(arg) + | StoreLocalLocal32(arg) + | StoreLocalLocal64(arg) + | StoreLocalLocal128(arg) + | LoadLocal32(arg) + | LoadLocal64(arg) + | LoadLocal8S32(arg) + | LoadLocal8U32(arg) + | LoadLocal16S32(arg) + | LoadLocal16U32(arg) + | LoadLocalTee32(arg) + | LoadLocalSet32(arg) + | LoadLocalTee8S32(arg) + | LoadLocalTee8U32(arg) + | LoadLocalTee16S32(arg) + | LoadLocalTee16U32(arg) + | LoadLocalSet8S32(arg) + | LoadLocalSet8U32(arg) + | LoadLocalSet16S32(arg) + | LoadLocalSet16U32(arg) + | LoadLocalTee128(arg) + | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), + I32Load(index) + | I64Load(index) + | F32Load(index) + | F64Load(index) + | I32Load8S(index) + | I32Load8U(index) + | I32Load16S(index) + | I32Load16U(index) + | I64Load8S(index) + | I64Load8U(index) + | I64Load16S(index) + | I64Load16U(index) + | I64Load32S(index) + | I64Load32U(index) + | I32Store(index) + | I64Store(index) + | F32Store(index) + | F64Store(index) + | I32Store8(index) + | I32Store16(index) + | I64Store8(index) + | I64Store16(index) + | I64Store32(index) + | V128Load(index) + | V128Load8x8S(index) + | V128Load8x8U(index) + | V128Load16x4S(index) + | V128Load16x4U(index) + | V128Load32x2S(index) + | V128Load32x2U(index) + | V128Load8Splat(index) + | V128Load16Splat(index) + | V128Load32Splat(index) + | V128Load64Splat(index) + | V128Load32Zero(index) + | V128Load64Zero(index) + | V128Store(index) => Some(index.get(data).mem_addr()), + V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) + | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { + Some(arg.memory_arg_idx.get(data).mem_addr()) + } + FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), + MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), + MemoryFillConst(index) => Some(index.get(data).memory), + MemoryInit(index) => Some(index.get(data).second), + MemoryCopy(index) => { + let value = index.get(data); + Some(value.first.max(value.second)) } - Self::MemoryInit(_, mem) => Some(*mem), - Self::MemoryCopy { dst_mem, src_mem } => Some(if *dst_mem >= *src_mem { *dst_mem } else { *src_mem }), _ => None, } } } + +#[cfg(test)] +mod tests { + use alloc::vec; + + use super::*; + + #[test] + fn compact_instruction_layout_is_exact() { + assert_eq!(core::mem::size_of::(), 8); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + } + + #[test] + fn operand_lanes_round_trip_max_values() { + let memory = MemoryArg::new(u64::MAX, u32::MAX); + assert_eq!(MemoryArg::decode(memory.encode()), memory); + + let value = Operand128::default() + .with_u8::<0>(u8::MAX) + .with_u16::<1>(u16::MAX) + .with_u32::<3>(u32::MAX) + .with_u64::<7>(u64::MAX); + assert_eq!( + (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()), + (u8::MAX, u16::MAX, u32::MAX, u64::MAX) + ); + + let bytes = [u8::MAX; 16]; + assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes); + } + + #[test] + fn v128_operand_views_round_trip_max_bytes() { + let value = OperandIdx::::new(0); + let local = OperandIdx::::new(0); + let global = OperandIdx::::new(1); + let set = OperandIdx::::new(2); + let data = super::super::WasmFunctionData { + operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(), + operands64: vec![ + LocalV128 { local: u16::MAX, value }.encode(), + GlobalV128 { global: u32::MAX, value }.encode(), + LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(), + ] + .into_boxed_slice(), + ..Default::default() + }; + + assert_eq!(value.get(&data).value, [u8::MAX; 16]); + assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value }); + assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value }); + assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }); + } +} diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 9a7071c..bd92753 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -22,10 +22,12 @@ const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 { } 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::*; @@ -472,19 +474,12 @@ 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]>, pub exception_handlers: Box<[ExceptionHandler]>, } -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}")) - } -} - /// A WebAssembly Module Export #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs new file mode 100644 index 0000000..3cc311c --- /dev/null +++ b/crates/types/src/operands.rs @@ -0,0 +1,177 @@ +use core::marker::PhantomData; + +use crate::WasmFunctionData; + +/// 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 { + index: u32, + #[cfg_attr(feature = "archive", serde(skip))] + marker: PhantomData, +} + +impl OperandIdx { + #[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) -> u32 { + self.index + } +} + +impl OperandIdx { + /// Returns the typed operand at this index. + /// + /// Panics if the index is outside its statically selected operand lane. + #[inline(always)] + pub fn get(self, data: &WasmFunctionData) -> T { + T::decode(T::Raw::get(data, self.index)) + } +} + +impl Copy for OperandIdx {} + +impl Clone for OperandIdx { + fn clone(&self) -> Self { + *self + } +} + +impl PartialEq for OperandIdx { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} + +impl Eq for OperandIdx {} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for OperandIdx { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.index.fmt(formatter) + } +} + +pub(crate) mod sealed { + pub trait Sealed {} +} + +/// A typed view stored in one of the per-function operand lanes. +pub trait OperandType: sealed::Sealed + Copy { + #[doc(hidden)] + type Raw: RawOperand; + + #[doc(hidden)] + fn decode(raw: Self::Raw) -> Self; + #[doc(hidden)] + fn encode(self) -> Self::Raw; +} + +#[doc(hidden)] +pub trait RawOperand: sealed::Sealed + Copy { + fn get(data: &WasmFunctionData, index: u32) -> Self; +} + +macro_rules! define_operand { + ($name:ident, $len:literal, $lane:ident) => { + #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")] + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] + #[cfg_attr(feature = "debug", derive(Debug))] + #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] + #[repr(transparent)] + pub struct $name([u8; $len]); + + impl sealed::Sealed for $name {} + + impl RawOperand for $name { + #[inline(always)] + fn get(data: &WasmFunctionData, index: u32) -> Self { + *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + } + + impl $name { + /// Returns the byte at `OFFSET`. + #[inline] + pub fn u8(self) -> u8 { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] + } + + /// Returns the little-endian `u16` at `OFFSET`. + #[inline] + pub fn u16(self) -> u16 { + const { assert!(OFFSET + 2 <= $len) }; + u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u32` at `OFFSET`. + #[inline] + pub fn u32(self) -> u32 { + const { assert!(OFFSET + 4 <= $len) }; + u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u64` at `OFFSET`. + #[inline] + pub fn u64(self) -> u64 { + const { assert!(OFFSET + 8 <= $len) }; + u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Builds an operand from its raw little-endian bytes. + #[inline] + pub fn from_le_bytes(value: [u8; $len]) -> Self { + Self(value) + } + + /// Returns the raw little-endian bytes. + #[inline] + pub fn to_le_bytes(self) -> [u8; $len] { + self.0 + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u8(mut self, value: u8) -> Self { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] = value; + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u16(mut self, value: u16) -> Self { + const { assert!(OFFSET + 2 <= $len) }; + self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u32(mut self, value: u32) -> Self { + const { assert!(OFFSET + 4 <= $len) }; + self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u64(mut self, value: u64) -> Self { + const { assert!(OFFSET + 8 <= $len) }; + self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); + self + } + } + }; +} + +define_operand!(Operand64, 8, operands64); +define_operand!(Operand128, 16, operands128); diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 9ed5df1..ed59ae5 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -67,6 +67,18 @@ impl RefType { pub const EXTERNREF: Self = Self::new_abstract(true, AbstractHeapType::Extern); pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn); + #[inline] + #[doc(hidden)] + pub const fn to_bits(self) -> u32 { + self.0 + } + + #[inline] + pub(crate) const fn from_bits(bits: u32) -> Option { + 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) -- cgit v1.3.1 From 951c8070169e8bd970940029156f305e741aecdb Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sun, 23 Aug 2026 13:40:38 +0200 Subject: chore: remove LinearMemory trait (#53) Signed-off-by: Henry --- ARCHITECTURE.md | 23 +- CHANGELOG.md | 10 +- Cargo.lock | 28 +- Cargo.toml | 12 +- README.md | 2 +- benches/memory_backends.rs | 151 ----------- crates/cli/src/engine_flags.rs | 36 +-- crates/parser/src/conversion.rs | 19 +- crates/parser/src/error.rs | 2 +- crates/parser/src/lib.rs | 39 +-- crates/parser/src/module.rs | 47 +--- crates/parser/src/parallel.rs | 31 +-- crates/parser/src/visit.rs | 2 +- crates/tinywasm/src/engine.rs | 58 ++-- crates/tinywasm/src/instance.rs | 27 +- crates/tinywasm/src/interpreter/executor.rs | 107 ++++---- crates/tinywasm/src/lib.rs | 7 +- crates/tinywasm/src/reference.rs | 50 ++-- crates/tinywasm/src/store/memory/instance.rs | 138 +++------- crates/tinywasm/src/store/memory/lazy.rs | 114 -------- crates/tinywasm/src/store/memory/mod.rs | 390 ++------------------------- crates/tinywasm/src/store/memory/paged.rs | 368 ------------------------- crates/tinywasm/src/store/memory/vec.rs | 185 +++++-------- crates/tinywasm/src/store/mod.rs | 80 +++++- crates/tinywasm/src/store/table.rs | 41 ++- crates/tinywasm/tests/internal_refs.rs | 2 +- crates/tinywasm/tests/memory.rs | 198 ++++++++++++++ crates/tinywasm/tests/memory_backends.rs | 307 --------------------- crates/types/src/instructions.rs | 83 ------ crates/types/src/lib.rs | 27 +- examples/rust/Cargo.toml | 14 +- examples/rust/build.sh | 4 +- examples/rust/src/hello.rs | 12 +- examples/rust/src/print.rs | 4 +- examples/rust/src/print.twasm | Bin 154 -> 154 bytes examples/rust/src/tinywasm_precompiled.rs | 30 --- examples/wasm-rust.rs | 24 -- 37 files changed, 663 insertions(+), 2009 deletions(-) delete mode 100644 benches/memory_backends.rs delete mode 100644 crates/tinywasm/src/store/memory/lazy.rs delete mode 100644 crates/tinywasm/src/store/memory/paged.rs create mode 100644 crates/tinywasm/tests/memory.rs delete mode 100644 crates/tinywasm/tests/memory_backends.rs delete mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'Cargo.lock') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9405d38..62fa503 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,6 @@ # TinyWasm Architecture -TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and configurable linear-memory backends. +TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and a contiguous `Vec`-backed linear memory. ## Execution Pipeline @@ -40,29 +40,20 @@ The default runtime remains safe Rust throughout rather than relying on unchecke SIMD instructions have a portable safe-Rust implementation built from fixed-size arrays and lane operations, relying on the compiler to auto-vectorize where possible. Generated code is inspected with `cargo asm`, and benchmarks determine where architecture-specific alternatives are worthwhile. WebAssembly targets use native SIMD intrinsics where available, while the optional `simd-x86` feature provides selected x86 implementations for operations where the generic code produces worse results. -## Memory Backends +## Linear Memory -Linear memory is implemented through the `LinearMemory` trait. The backend is selected with `engine::Config::with_memory_backend()`. +Linear memory is a contiguous `Vec` allocation owned by a `MemoryInstance`. The interpreter accesses it through the internal `MemoryStorage` type, a small concrete boundary that keeps the `Vec` representation out of the executor so an mmap-backed storage can be substituted later without touching load and store paths. -`LinearMemory` exposes separate fixed-width read and write methods for 8-, 16-, 32-, 64-, and 128-bit accesses. A const-generic method would not be callable through a `dyn LinearMemory` trait object, so each width is an explicit vtable entry that backends can optimize independently. +Fixed-width loads and stores use a single const-generic `read_fixed::` / `write_fixed::` pair rather than per-width vtable methods. Scalar operations reduce to an effective-address computation, a bounds check, a slice access, and a `from_le_bytes` / `to_le_bytes` conversion, with out-of-bounds construction kept on cold paths. Bulk operations such as `fill` and `copy_within` map directly to native slice methods. -This flexibility has a measurable cost: guest loads and stores cross the `dyn LinearMemory` boundary, adding an indirect call and generally preventing the backend operation from being inlined into the interpreter. The fixed-width methods keep the work behind that boundary as small and specialized as possible. +Memory growth keeps the Wasm page count and limits on `MemoryInstance`. Before memory or table backing storage is allocated or resized, the configured `ResourceLimiter` is consulted so a host can bound guest resource consumption. The limiter is shared across the stores created from one `Engine` and lives behind an `Arc`. -Available backends: - -- `VecMemory` - contiguous `Vec` backing and the default backend. -- `PagedMemory` - sparse chunk-based allocation, with untouched chunks left unallocated and growth avoiding relocation of one contiguous buffer. -- `LazyLinearMemory` - serves zero-filled reads without allocation and creates the configured backend on the first mutation or growth. -- Custom backends through `MemoryBackend::custom()`. - -`VecMemory` growth may reallocate, though operating-system allocators can often grow page-backed allocations without copying the full buffer. Applications on conventional operating systems should generally keep it unless sparse allocation or non-relocating growth is specifically needed. Bounded dynamic stacks and sparse paged memory trade some runtime overhead for a smaller initial footprint on embedded and other resource-constrained systems. +For conventional operating systems, a future mmap-backed storage could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. ## Future Experiments Future work may explore additional dispatch and code-generation strategies, including Rust's experimental `loop_match` state-machine work, a tail-call-based interpreter once Rust's explicit tail-call support matures, more aggressive superinstruction fusion, top-of-stack register allocation, or optional JIT compilation. -For conventional operating systems, a future `mmap`-based memory backend could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. - ## Important Modules - [visit.rs](./crates/parser/src/visit.rs) - function-body operator lowering @@ -71,4 +62,4 @@ For conventional operating systems, a future `mmap`-based memory backend could r - [instructions.rs](./crates/types/src/instructions.rs) - internal instruction set - [value_stack.rs](./crates/tinywasm/src/interpreter/stack/value_stack.rs) - width-specific 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 +- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - linear memory storage diff --git a/CHANGELOG.md b/CHANGELOG.md index 701fc84..c6c8ff7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. - Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. +- Added a `ResourceLimiter` trait, configurable through `engine::Config::with_resource_limiter`, to bound guest memory and table allocation and growth. ### Changed @@ -25,14 +26,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Typed function tuples now support up to 20 parameters or results. `WasmTupleChain` is deprecated. Use untyped functions for larger signatures. - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. - Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. -- `LinearMemory` mutation methods and custom memory-backend factories now return `Trap` errors so lazy backend failures can be propagated. +- Linear memory now uses a single contiguous `Vec`-backed storage with const-generic fixed-width loads and stores. +- Increased the minimum supported Rust version from 1.95 to 1.98. ### Fixed - Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. - Fixed Memory64 bulk-memory operations and optimized stores using the wrong value-stack lane. -- Fixed `memory.init` bounds checks, operand lowering, and local-memory allocation analysis. +- Fixed `memory.init` bounds checks and operand lowering. - Fixed Memory64 default limits and host-size handling, including 32-bit targets. ### Breaking Changes @@ -44,6 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Renamed `ModuleInstanceAddr` to `ModuleInstanceId`. - 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 }`. +- Removed the pluggable memory backend system (`LinearMemory`, `MemoryBackend`, `VecMemory`, `PagedMemory`, `LazyLinearMemory`, and `Config::with_memory_backend`). Linear memory is always `Vec`-backed. To limit initial memory allocation and growth, configure a `ResourceLimiter` with `Config::with_resource_limiter`. +- Removed the local-memory allocation analysis (`LocalMemoryAllocation` and `ParserOptions::optimize_local_memory_allocation`). Local memories are always allocated eagerly. +- Removed `Config::with_trap_on_oom`. A `ResourceLimiter` can return a trap when rejecting a memory or table allocation or growth request. +- `Table::grow` now returns `Result>`, matching `Memory::grow`. Growth limits and allocation failures return `None`, while limiter-provided traps return an error. ## [0.10.0] - 2026-07-24 diff --git a/Cargo.lock b/Cargo.lock index 3c13501..ac0895a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.3" +version = "1.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" dependencies = [ "find-msvc-tools", "shlex", @@ -312,9 +312,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" @@ -511,9 +511,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "memchr" @@ -962,9 +962,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1492381bfd5ea51c2a99a919b676662559925cb8d7490547ec2e14c1ad3eb1" +checksum = "7d8ad9f0a39050867bda22e6486c316e2e52d20a42154d5bc433934bf738d085" dependencies = [ "leb128fmt", "wasmparser", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60bd825ffedc6cba8a642924ba7ae424afbc47811cffbcb7b92031ec24e59b4c" +checksum = "d92fc335fb6d48f46bda1d8b26b69e28320c15ac3272208333833d6e217e2b4a" dependencies = [ "bitflags", "indexmap", @@ -993,9 +993,9 @@ dependencies = [ [[package]] name = "wast" -version = "256.0.0" +version = "257.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ad42723fc9222da007f05812a3249c9a4ee7af79d497fc2a2079579ad7efe6" +checksum = "3c416ee8044cf88c5280e3d87c322b009525eb25142cf7428f0a90ea88febc3b" dependencies = [ "bumpalo", "leb128fmt", @@ -1006,9 +1006,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.256.0" +version = "1.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37cc86c54d8011b3202e265bfebada440733ea3a788ffaf46d395f7d2fdeacfb" +checksum = "672e5495f00c5fc6c6b502205bae4708aa4dd13d969754438743afe0a8af0f1d" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 7ea5181..764ae53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ default-members = [".", "crates/parser", "crates/tinywasm", "crates/types"] [workspace.package] version = "0.11.0-pre.0" edition = "2024" -rust-version = "1.95" +rust-version = "1.98" repository = "https://github.com/explodingcamera/tinywasm" license = "MIT OR Apache-2.0" keywords = ["interpreter", "no-std", "tinywasm", "wasm", "webassembly"] @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.256", default-features = false } -wast = "256" -wat = "1.256" +wasmparser = { version = "0.257", default-features = false } +wast = "257" +wat = "1.257" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } @@ -57,10 +57,6 @@ name = "tinywasm" harness = false name = "tinywasm_modes" -[[bench]] -harness = false -name = "memory_backends" - [dev-dependencies] anyhow.workspace = true criterion.workspace = true diff --git a/README.md b/README.md index 3d3bc4c..7f27ea4 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ TinyWasm modules can be compiled to the internal `twasm` bytecode format, which With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. -Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, the GC collection threshold, or trap-on-OOM behavior. +Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, or the GC collection threshold. A `ResourceLimiter` attached to the engine's config bounds guest memory and table allocation and growth and can trap rejected requests. [^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. diff --git a/benches/memory_backends.rs b/benches/memory_backends.rs deleted file mode 100644 index d7b8703..0000000 --- a/benches/memory_backends.rs +++ /dev/null @@ -1,151 +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(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( - 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( - 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/cli/src/engine_flags.rs b/crates/cli/src/engine_flags.rs index 3d90847..edc56aa 100644 --- a/crates/cli/src/engine_flags.rs +++ b/crates/cli/src/engine_flags.rs @@ -1,4 +1,4 @@ -use anyhow::{Result, bail}; +use anyhow::Result; use clap::{Args, ValueEnum}; use tinywasm::{Engine, StackConfig, engine::FuelPolicy}; @@ -8,18 +8,6 @@ pub struct EngineFlags { #[arg(long, value_enum)] pub fuel_policy: Option, - /// 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, - - /// 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, @@ -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/parser/src/conversion.rs b/crates/parser/src/conversion.rs index b94ebe6..364bae8 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -151,29 +151,26 @@ pub(crate) fn convert_module_code( ty_idx: u32, options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { - let locals_reader = func.get_locals_reader()?; - #[cfg(feature = "validate")] - let locals_position = locals_reader.original_position(); + let mut locals_reader = func.get_locals_reader()?; let signature = metadata.signature(ty_idx)?.clone(); let mut local_types = signature.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; - #[cfg(feature = "validate")] - for (local_index, local) in locals_reader.into_iter().enumerate() { - let local = local?; + 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(locals_position + local_index, local.0, local.1)?; + validator.define_locals(position, local.0, local.1)?; } extend_local_types(&mut local_types, local.0, local.1)?; } #[cfg(not(feature = "validate"))] - for local in locals_reader { - let local = local?; - extend_local_types(&mut local_types, local.0, local.1)?; - } + 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()); 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 90e239b..262cc07 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -61,8 +61,6 @@ pub struct ParserOptions { /// 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 deduplicate immutable function operands while parsing. @@ -85,7 +83,6 @@ impl Default for ParserOptions { fn default() -> Self { Self { validation: cfg!(feature = "validate"), - optimize_local_memory_allocation: true, optimize_rewrite: true, deduplicate_operands: false, #[cfg(parallel_parser)] @@ -117,17 +114,6 @@ 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; - self - } - - /// Returns whether unused local memory allocation optimization is enabled. - pub const fn optimize_local_memory_allocation(&self) -> bool { - self.optimize_local_memory_allocation - } - /// Enable or disable the peephole rewrite optimizer. pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self { self.optimize_rewrite = enabled; @@ -234,7 +220,7 @@ impl Parser { } reader.process_pending_functions(&self.options)?; - reader.into_module(&self.options) + reader.into_module() } #[cfg(feature = "std")] @@ -263,7 +249,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 } => { @@ -272,17 +258,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))] @@ -298,21 +279,21 @@ 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())?; + reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?; parser.skip_section(); buffer_offset = section_end; continue; @@ -335,7 +316,7 @@ impl Parser { if reader.end_reached || eof { reader.process_pending_functions(&self.options)?; - return reader.into_module(&self.options); + return reader.into_module(); } } }; @@ -347,7 +328,7 @@ impl TryFrom> for Module { type Error = ParseError; fn try_from(reader: ModuleReader<'_>) -> Result { - reader.into_module(&ParserOptions::default()) + reader.into_module() } } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 8138666..c076035 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -19,7 +19,6 @@ pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, - pub uses_local_memory: bool, } pub(crate) fn optimize_function_code( @@ -27,16 +26,11 @@ pub(crate) fn optimize_function_code( options: &ParserOptions, function_results: ValueCounts, self_func_addr: u32, - imported_memory_count: u32, ) -> Result { let optimized = optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; let data = code.data.finish(); - let uses_local_memory = optimized - .instructions - .iter() - .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); - Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals }) } #[derive(Default)] @@ -65,7 +59,6 @@ pub(crate) struct ModuleReader<'a> { pub(crate) elements: Box<[Element]>, pub(crate) end_reached: bool, imported_func_count: usize, - imported_memory_count: u32, global_types: Vec, #[cfg(parallel_parser)] @@ -277,7 +270,6 @@ impl<'a> ModuleReader<'a> { } self.imported_func_count += 1; } - ImportKind::Memory(_) => self.imported_memory_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(|| { @@ -338,7 +330,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn begin_code_section( &mut self, count: u32, - range: Range, + range: Range, size: u32, validator: Option<&mut Validator>, options: &ParserOptions, @@ -411,7 +403,6 @@ impl<'a> ModuleReader<'a> { options, self.code_results[self.code.len()], (self.imported_func_count + self.code.len()) as u32, - self.imported_memory_count, )?); self.func_validator_allocations = func_validator_allocs; @@ -443,7 +434,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn queue_owned_code_section( &mut self, count: u32, - body_offset: usize, + body_offset: u64, section_bytes: Arc<[u8]>, validator: Option<&mut Validator>, ) -> Result<()> { @@ -455,6 +446,8 @@ impl<'a> ModuleReader<'a> { for _ in 0..count { let body_reader = reader.read_reader()?; let body_range = body_reader.range(); + 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); @@ -465,7 +458,7 @@ impl<'a> ModuleReader<'a> { 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, @@ -512,10 +505,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(()) } @@ -525,7 +516,7 @@ impl<'a> ModuleReader<'a> { Ok(()) } - pub(crate) fn into_module(self, options: &ParserOptions) -> Result { + pub(crate) fn into_module(self) -> Result { if !self.end_reached { return Err(ParseError::EndNotReached); } @@ -534,24 +525,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() @@ -571,9 +544,6 @@ impl<'a> ModuleReader<'a> { 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; - } Ok(Arc::new(WasmFunction { instructions: code.instructions.into_boxed_slice(), @@ -598,7 +568,6 @@ impl<'a> ModuleReader<'a> { elements: self.elements, memory_types: self.memory_types, tags: self.tags, - local_memory_allocation, } .into()) } diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e29b38f..9b96c7a 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -17,7 +17,7 @@ pub(crate) struct OwnedFunctionBody { // function jobs from that section. pub section_bytes: Arc<[u8]>, pub body_range: Range, - pub body_offset: usize, + pub body_offset: u64, } pub(crate) struct PendingFunction<'a> { @@ -61,7 +61,6 @@ fn process_function_job( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, ) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { @@ -83,13 +82,7 @@ fn process_function_job( } }; - let code = optimize_function_code( - code, - options, - job.results, - (imported_func_count + job.ordinal) as u32, - imported_memory_count, - )?; + let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?; Ok((code, validator_allocs, reader_allocs)) } @@ -99,7 +92,6 @@ fn process_chunk<'a>( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); @@ -107,15 +99,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; @@ -129,11 +114,10 @@ pub(crate) fn process_pending( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { 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); @@ -151,10 +135,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/visit.rs b/crates/parser/src/visit.rs index 8315fb5..f48e1cf 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -221,7 +221,7 @@ impl<'a> FunctionBuilder<'a> { struct ValidateThenVisit<'a, 'm> { validator: &'a mut FuncValidator, builder: &'a mut FunctionBuilder<'m>, - position: usize, + position: u64, } impl ModuleMetadata { diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 64ef6be..f1feae6 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -1,5 +1,6 @@ -/// Memory backend types and traits. -pub use crate::store::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; +use alloc::sync::Arc; + +use crate::ResourceLimiter; /// Global configuration for the WebAssembly interpreter /// @@ -88,21 +89,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 +116,8 @@ 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>, /// Initial number of GC heap bytes that triggers collection. /// Defaults to 1 MiB. pub gc_collection_threshold: usize, @@ -140,12 +135,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; @@ -178,9 +167,9 @@ 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. + pub fn with_resource_limiter(mut self, limiter: Arc) -> Self { + self.resource_limiter = Some(limiter); self } @@ -194,15 +183,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 { @@ -213,9 +193,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/instance.rs b/crates/tinywasm/src/instance.rs index f45b718..6700d53 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -85,6 +85,17 @@ impl ModuleInstance { *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}")) } + /// 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 { @@ -165,18 +176,10 @@ impl ModuleInstance { 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)); - 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 limiter = store.engine.config().resource_limiter.clone(); + 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)?); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 9da4a7a..b203980 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -27,6 +27,7 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { module: ModuleInstance, store: &'store mut Store, call_stack_base: u32, + mem0: MemAddr, } impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { @@ -36,7 +37,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { .get_module_instance(wasm_func.owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); - Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base } + let mem0 = module.mem0_addr(); + Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } + } + + /// 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).unwrap_or_else(|| unreachable!("invalid module instance")).clone(); + self.mem0 = self.module.mem0_addr(); } #[inline(always)] @@ -975,11 +991,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); self.func = wasm_func.func.clone(); if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(wasm_func.owner); } } @@ -1038,11 +1050,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1064,11 +1072,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1277,7 +1281,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { value_local: u8, ) -> Result<(), Trap> { let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(memarg.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let addr = if mem.is_64bit() { let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); @@ -1292,7 +1296,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { mem.effective_addr::(base as usize, memarg.offset())? }; let mem = self.store.state.get_mem_mut(mem_addr); - value.store_at(&mut *mem.inner, addr) + value.store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1302,7 +1306,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.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; @@ -1318,8 +1322,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = cold_err!(T::load_at(&*mem.inner, addr))?; - increment(value).store_at(&mut *mem.inner, addr) + let value = cold_err!(T::load_at(&mem.inner, addr))?; + increment(value).store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1334,12 +1338,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - fma.store_at(&mut *mem.inner, addr)?; + fma.store_at(&mut mem.inner, addr)?; Ok(()) } @@ -1349,7 +1353,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { memarg: CompactMemoryArg, addr_local: u8, ) -> Result { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); + let mem = self.store.state.get_mem(self.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; let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { @@ -1362,7 +1366,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - cold_err!(T::load_at(&*mem.inner, addr)) + cold_err!(T::load_at(&mem.inner, addr)) } #[inline(always)] @@ -1638,7 +1642,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(addr)); + let mem = self.store.state.get_mem(self.mem_addr(addr)); match mem.is_64bit() { true => self.store.value_stack.push::(mem.page_count as i64), false => self.store.value_stack.push::(mem.page_count as i32), @@ -1646,14 +1650,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } 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 mem_addr = self.mem_addr(addr); + let is_64bit = self.store.state.get_mem(mem_addr).is_64bit(); let pages_delta = match is_64bit { true => ::stack_pop(&mut self.store.value_stack), false => i64::from(::stack_pop(&mut self.store.value_stack)), }; + let limiter = self.store.engine.config().resource_limiter.as_deref(); - let size = mem.grow(pages_delta, self.store.engine.config().trap_on_oom())?.unwrap_or(-1); + let mem = self.store.state.get_mem_mut(mem_addr); + let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); match is_64bit { true => self.store.value_stack.push::(size)?, false => self.store.value_stack.push::(size as i32)?, @@ -1664,8 +1670,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); - let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); - let src_mem_addr = self.module.resolve_mem_addr(src_mem); + 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 = @@ -1687,7 +1693,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(addr); + 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); @@ -1697,7 +1703,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(addr); + let mem_addr = self.mem_addr(addr); 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, val, size as u32 as usize) @@ -1706,7 +1712,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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() { + if mem.inner.fill(dst, size, val).is_none() { return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max })); } Ok(()) @@ -1716,7 +1722,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); 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.module.resolve_mem_addr(mem_index); + 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)?; @@ -1739,7 +1745,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); }; - if mem.inner.write_all(dst, &data[offset..offset + size])?.is_none() { + 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(()) @@ -1772,10 +1778,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { arg: MemoryLaneArg, ) -> Result<(), Trap> { let m = arg.memory_arg_idx.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); @@ -1790,10 +1796,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let m = index.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; self.store.value_stack.push(cast(value)) } @@ -1804,12 +1810,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1822,12 +1828,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = cast(val); let m = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1874,14 +1880,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; let val = ::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 result = table.grow(n, val); - match (arch, result) { - (MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32), - (MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32), - (MemoryArch::I64, Ok(())) => self.store.value_stack.push(sz as i64), - (MemoryArch::I64, Err(_)) => self.store.value_stack.push(-1_i64), + let grew = table.grow(n, val, limiter)?; + match (arch, grew) { + (MemoryArch::I32, true) => self.store.value_stack.push(sz as i32), + (MemoryArch::I32, false) => self.store.value_stack.push(-1_i32), + (MemoryArch::I64, true) => self.store.value_stack.push(sz as i64), + (MemoryArch::I64, false) => self.store.value_stack.push(-1_i64), } } diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e941430..bd80ef1 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -54,8 +54,9 @@ //! ``` //! //! 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. +//! and [`engine::Config`] to control stack sizing and fuel accounting. A [`ResourceLimiter`] can be +//! attached to the engine configuration to bound memory and table allocation and growth for stores +//! created from that engine and to trap rejected requests. //! //! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory. //! @@ -129,7 +130,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. diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index f5d9c23..271e71c 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -122,7 +122,7 @@ impl crate::std::io::Read for MemoryCursor<'_> { impl crate::std::io::Write for MemoryCursor<'_> { fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { let offset = self.offset()?; - let written = self.memory.inner.write(offset, buf).map_err(Error::from)?; + let written = self.memory.inner.write(offset, buf); self.advance(written)?; Ok(written) } @@ -163,7 +163,8 @@ impl Memory { /// Create a new memory in the given store. pub fn new(store: &mut Store, ty: MemoryType) -> Result { let addr = store.state.memories.len() as MemAddr; - store.state.memories.push(MemoryInstance::new(ty, &store.engine.config().memory_backend)?); + 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))) } @@ -230,19 +231,18 @@ impl Memory { /// 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. + /// 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 { 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. + /// 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 { - Ok(self.instance_mut(store)?.inner.write(offset, src)?) + Ok(self.instance_mut(store)?.inner.write(offset, src)) } /// Reads exactly `dst.len()` bytes from memory. @@ -263,9 +263,14 @@ impl Memory { }) } - /// Grow the memory by the given number of pages. + /// 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> { - self.instance_mut(store)?.grow(delta_pages, true).map_err(Into::into) + 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. @@ -281,14 +286,14 @@ impl Memory { /// 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(|| { + 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(|| { + self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len: data.len(), @@ -368,8 +373,9 @@ impl Table { 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 limiter = store.engine.config().resource_limiter.clone(); let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new(ty, init)?); + store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); Ok(Self(StoreItem::new(store.id(), addr))) } @@ -430,15 +436,23 @@ impl Table { store.state.get_table_mut(self.0.addr).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 { + /// 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> { 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) + 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), + } } } diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index 68a075b..a075d25 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -1,10 +1,8 @@ -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; /// A WebAssembly Memory Instance /// @@ -23,25 +21,17 @@ impl core::fmt::Debug for MemoryInstance { } impl MemoryInstance { - const COPY_CHUNK_SIZE: usize = 4 * 1024; - + #[inline] fn host_size(kind: MemoryType, pages: u64) -> Result { - #[cfg(target_pointer_width = "64")] - { - pages - .checked_mul(kind.page_size()) - .map(|size| size as usize) - .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + let size = pages + .checked_mul(kind.page_size()) + .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))?; + usize::try_from(size).map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space")) + } - #[cfg(not(target_pointer_width = "64"))] - { - let page_size = usize::try_from(kind.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(pages) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - pages.checked_mul(page_size).ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + #[inline] + fn maximum_size(kind: MemoryType) -> Option { + kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } #[inline(always)] @@ -67,7 +57,7 @@ impl MemoryInstance { } } - pub(crate) fn new(kind: MemoryType, backend: &MemoryBackend) -> Result { + pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result { let initial_len = Self::host_size(kind, kind.page_count_initial())?; crate::log::debug!( @@ -76,27 +66,14 @@ 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 { - let initial_len = Self::host_size(kind, kind.page_count_initial())?; - - 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 storage = MemoryStorage::try_new(initial_len)?; Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) } @@ -111,82 +88,49 @@ impl 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 { - return cold!(Err(memory_oob(addr, len, mem.len()))); - }; - - if end > mem.len() || end < addr { - return cold!(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; - } - + src_memory.inner.checked_range(src, len).ok_or_else(|| cold!(memory_oob(src, len, src_memory.inner.len())))?; + self.inner.checked_range(dst, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len())))?; + self.inner.copy_from(dst, &src_memory.inner, src, len); Ok(()) } 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()) - }) + self.inner.copy_within(dst, src, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len()))) } - pub(crate) fn grow(&mut self, pages_delta: i64, trap_on_oom: bool) -> Result, 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, 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) = current_pages.checked_add(pages_delta) 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 max_pages = self.kind.page_count_max().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); + return cold!({ + crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages); + Ok(None) + }); } let Ok(new_size) = Self::host_size(self.kind, new_pages as u64) else { - return Ok(None); + 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); - } + if let Some(limiter) = limiter + && !limiter.memory_growing(self.inner.len(), new_size, Self::maximum_size(self.kind))? + { + return cold!(Ok(None)); + } + + if cold_err!(self.inner.grow_to(new_size)).is_err() { return Ok(None); } self.page_count = new_pages; diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs deleted file mode 100644 index 780d5b5..0000000 --- a/crates/tinywasm/src/store/memory/lazy.rs +++ /dev/null @@ -1,114 +0,0 @@ -use alloc::boxed::Box; - -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>, -} - -impl LazyLinearMemory { - /// Creates a lazy memory for `ty` using `backend` for eventual storage. - pub fn try_new(ty: MemoryType, backend: MemoryBackend) -> Result { - let page_size = usize::try_from(ty.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(ty.page_count_initial()) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - let initial_len = pages - .checked_mul(page_size) - .ok_or(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) -> core::result::Result<&mut dyn LinearMemory, crate::Trap> { - if self.inner.is_none() { - let storage = cold_err!(self.backend.create(self.ty, self.initial_len))?; - 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.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]) -> core::result::Result { - if src.is_empty() || addr >= self.len() { - return Ok(0); - } - self.materialize()?.write(addr, src) - } - - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if src.is_empty() { - return Ok(Some(())); - } - self.materialize()?.write_all(addr, src) - } - - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if len == 0 || val == 0 && self.inner.is_none() { - return Ok(Some(())); - } - self.materialize()?.fill(addr, len, val) - } - - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - if self.inner.is_none() || len == 0 || dst == src { - return Ok(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 70ffb20..24f295b 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -1,372 +1,32 @@ -use alloc::{boxed::Box, sync::Arc}; -use alloc::{vec, vec::Vec}; -use core::cmp::min; -use core::hint::cold_path; - -use tinywasm_types::MemoryType; - -use crate::Result; use crate::interpreter::Value128; 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 +/// Internal 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; - - /// Returns true if the memory is empty. - fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Grows the memory to `new_len` bytes. - /// - /// The runtime only calls this with lengths that are exact multiples of the Wasm page size for - /// the owning memory. - fn grow_to(&mut self, new_len: usize) -> core::result::Result<(), crate::Trap>; - - /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. - /// - /// Backends may return fewer bytes than requested even when more data is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. - fn read(&self, addr: usize, dst: &mut [u8]) -> usize; - - /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. - /// - /// Backends may return fewer bytes than requested even when more space is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. Backend - /// failures are returned as traps. - fn write(&mut self, addr: usize, src: &[u8]) -> core::result::Result; - - /// Writes all bytes in `src`, returns `Ok(None)` for an invalid range, or returns a backend trap. - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { - return cold!(Ok(None)); - }; - - if end > self.len() { - return cold!(Ok(None)); - } - - let mut offset = 0; - while offset < src.len() { - let written = self.write(addr + offset, &src[offset..])?; - if written == 0 { - return cold!(Ok(None)); - } - offset += written; - } - - Ok(Some(())) - } - - /// Fills the range `[addr, addr + len)` with `val`. - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - - let chunk = [val; 1024]; - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.write_all(addr + offset, &chunk[..chunk_len])?.is_none() { - return Ok(None); - } - offset += chunk_len; - } - - Ok(Some(())) - } - - /// Copies `len` bytes from `src` to `dst` within the same memory. - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - let mut chunk = [0; 1024]; - - // If the source and destination ranges are disjoint, we can copy forward without a temporary buffer. - if dst < src || dst >= src_end { - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - offset += chunk_len; - } - } else { - // Otherwise, we need to copy backward to avoid overwriting the source data before it's read. - let mut offset = len; - while offset > 0 { - let chunk_len = min(offset, 1024); - offset -= chunk_len; - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - } - } - - Ok(Some(())) - } - - /// Reads exactly `dst.len()` bytes starting at `addr`. - fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { - let Some(end) = addr.checked_add(dst.len()) else { - return cold!(None); - }; - - if end > self.len() { - return cold!(None); - } - - let mut offset = 0; - while offset < dst.len() { - let read = self.read(addr + offset, &mut dst[offset..]); - if read == 0 { - return cold!(None); - } - offset += read; - } - - Some(()) - } - - /// Reads `len` bytes starting at `addr` into a newly allocated buffer. - fn read_vec(&self, addr: usize, len: usize) -> Option> { - let end = addr.checked_add(len)?; - if end > self.len() { - return None; - } - - let mut data = vec![0; len]; - self.read_exact(addr, &mut data)?; - Some(data) - } - - /// Reads exactly 1 byte at `addr`. - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - let mut bytes = [0; 1]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 2 bytes at `addr`. - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - let mut bytes = [0; 2]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 4 bytes at `addr`. - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - let mut bytes = [0; 4]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 8 bytes at `addr`. - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - let mut bytes = [0; 8]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 16 bytes at `addr`. - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - let mut bytes = [0; 16]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - })?; - Ok(bytes) - } - - /// Writes exactly 1 byte at `addr`. - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - }) - } - - /// Writes exactly 2 bytes at `addr`. - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - }) - } - - /// Writes exactly 4 bytes at `addr`. - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - }) - } - - /// Writes exactly 8 bytes at `addr`. - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - }) - } - - /// Writes exactly 16 bytes at `addr`. - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - }) - } -} - -type MemoryFactory = dyn Fn(MemoryType) -> core::result::Result, crate::Trap> + Send + Sync; - -/// Configures how runtime memory instances are created. -#[derive(Clone, Default)] -pub struct MemoryBackend(MemoryBackendInner); - -#[derive(Clone, Default)] -enum MemoryBackendInner { - #[default] - Vec, - Paged { - chunk_size: usize, - }, - Custom(Arc), -} - -impl MemoryBackend { - /// Uses a contiguous [`VecMemory`] for each memory instance. - /// - /// This is usually the fastest option for reads and writes, but large grows can be expensive - /// because they may reallocate and copy the entire buffer. - pub const fn vec() -> Self { - Self(MemoryBackendInner::Vec) - } - - /// Uses sparse chunked storage for each memory instance. - /// - /// `chunk_size` is the backend chunk size in bytes. It must be a non-zero power - /// of two and is independent from the Wasm page size. - /// - /// This generally makes growth cheaper than [`Self::vec`], but read and write operations do a - /// little more work and may be slightly slower. - pub fn paged(chunk_size: usize) -> Self { - assert!(chunk_size.is_power_of_two(), "chunk_size must be a non-zero power of two"); - Self(MemoryBackendInner::Paged { chunk_size }) - } - - /// Uses a custom factory to create memory instances. - /// - /// Factory traps are returned during eager creation or when a lazy memory first materializes. - pub fn custom(factory: F) -> Self - where - F: Fn(MemoryType) -> core::result::Result + Send + Sync + 'static, - M: LinearMemory + 'static, - { - Self(MemoryBackendInner::Custom(Arc::new(move |ty| { - let memory = factory(ty)?; - Ok(Box::new(memory) as Box) - }))) - } - - pub(crate) fn create( - &self, - ty: MemoryType, - initial_len: usize, - ) -> core::result::Result { - let storage = match &self.0 { - MemoryBackendInner::Vec => Box::new(VecMemory::try_new(initial_len)?) as Box, - MemoryBackendInner::Paged { chunk_size } => { - Box::new(PagedMemory::try_new(initial_len, *chunk_size)?) as Box - } - MemoryBackendInner::Custom(factory) => factory(ty)?, - }; - - if storage.len() < initial_len { - return Err(crate::Trap::Other("memory backend returned less storage than required")); - } - - Ok(storage) - } - - pub(crate) fn create_lazy(&self, ty: MemoryType, initial_len: usize) -> Result { - Ok(Box::new(LazyLinearMemory::new_with_initial_len(ty, initial_len, self.clone()))) - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for MemoryBackend { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match &self.0 { - MemoryBackendInner::Vec => f.debug_tuple("MemoryBackend::Vec").finish(), - MemoryBackendInner::Paged { chunk_size } => { - f.debug_struct("MemoryBackend::Paged").field("chunk_size", chunk_size).finish() - } - MemoryBackendInner::Custom(_) => f.debug_tuple("MemoryBackend::Custom").finish(), - } - } -} - -pub(crate) type MemoryStorage = Box; +/// This is the boundary between the interpreter and the backing representation. Keeping it a +/// concrete type selected at compile time means the executor's load and store paths stay the same +/// whether the memory is `Vec`-backed or, later, mmap-backed. +pub(crate) type MemoryStorage = VecMemory; -/// A trait for types that can be converted to and from static byte arrays +/// A trait for types that can be converted to and from static byte arrays. pub(crate) trait MemValue: 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; + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result; - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), 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)] @@ -380,28 +40,20 @@ macro_rules! impl_mem_traits { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self::from_le_bytes(cold_err!(mem.$read(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + 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 -); +impl_mem_traits!(u8, 1, i8, 1, u16, 2, i16, 2, u32, 4, i32, 4, f32, 4, u64, 8, i64, 8, f64, 8); impl MemValue<16> for Value128 { #[inline(always)] @@ -415,13 +67,13 @@ impl MemValue<16> for Value128 { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self(cold_err!(mem.read_128(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + Ok(Self(cold_err!(mem.read_fixed::<16>(addr))?)) } #[inline(always)] - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap> { - mem.write_128(addr, &self.0) + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> { + mem.write_fixed::<16>(addr, &self.0) } } diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs deleted file mode 100644 index 3e6e5ea..0000000 --- a/crates/tinywasm/src/store/memory/paged.rs +++ /dev/null @@ -1,368 +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>>, -} - -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 { - 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, crate::Trap> { - let mut chunk = Vec::new(); - cold_err!(chunk.try_reserve_exact(self.chunk_size)).map_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 read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - let mut bytes = [0; N]; - if let Some(chunk) = self.chunk_slice(chunk_idx) { - bytes.copy_from_slice(&chunk[chunk_offset..chunk_offset + N]); - } - return Ok(bytes); - } - cold_path(); - let mut bytes = [0; N]; - self.read_exact(addr, &mut bytes).ok_or_else(|| memory_oob(addr, N, self.len))?; - Ok(bytes) - } - - #[inline(always)] - fn write_fixed(&mut self, addr: usize, bytes: &[u8]) -> Result<(), crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - self.chunk_mut(chunk_idx)?[chunk_offset..chunk_offset + N].copy_from_slice(bytes); - return Ok(()); - } - cold_path(); - self.write_all(addr, bytes)?.ok_or_else(|| memory_oob(addr, N, self.len)) - } - - #[inline(always)] - fn checked_end(&self, addr: usize, len: usize) -> Option { - 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() { - cold_err!(self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len())) - .map_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]) -> Result { - if addr >= self.len || src.is_empty() { - return Ok(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 chunk = self.chunk_mut(chunk_idx)?; - chunk[chunk_offset..chunk_offset + write_len].copy_from_slice(&src[..write_len]); - Ok(write_len) - } - - #[inline(always)] - fn write_all(&mut self, addr: usize, src: &[u8]) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, src.len()) else { return Ok(None) }; - 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)?; - chunk[chunk_offset..chunk_offset + copy_len].copy_from_slice(&src[src_offset..src_offset + copy_len]); - - pos += copy_len; - src_offset += copy_len; - } - - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, len) else { return Ok(None) }; - 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)?[chunk_offset..chunk_offset + fill_len].fill(val); - } - - pos = chunk_end; - } - - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - if self.copy_within_single_chunk(dst, src, len) { - return Ok(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); - if self.read_exact(src + copied, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + copied, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - copied += chunk_len; - } - } else { - let mut remaining = len; - while remaining > 0 { - let chunk_len = min(buf.len(), remaining); - let chunk_start = remaining - chunk_len; - if self.read_exact(src + chunk_start, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + chunk_start, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - remaining = chunk_start; - } - } - - Ok(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 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> { - 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(()) - } - - #[inline(always)] - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<2>(addr, bytes) - } - - #[inline(always)] - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<4>(addr, bytes) - } - - #[inline(always)] - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<8>(addr, bytes) - } - - #[inline(always)] - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<16>(addr, bytes) - } -} diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index be85e9b..98c24d6 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,24 +1,20 @@ use alloc::vec::Vec; +use core::ops::Range; -use super::{LinearMemory, memory_oob}; +use super::memory_oob; -/// A contiguous `Vec`-backed linear memory. +/// A contiguous `Vec`-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 internal storage boundary for [`super::MemoryInstance`]. Keeping it a concrete type +/// rather than a `Vec` directly means the backing representation can later be swapped for an +/// mmap-backed implementation without touching the interpreter's load and store paths. +pub(crate) struct VecMemory { data: Vec, } impl VecMemory { /// 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 { + pub(crate) fn try_new(len: usize) -> Result { let mut data = Vec::new(); cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); @@ -26,11 +22,24 @@ impl VecMemory { } #[inline(always)] - fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - self.check_fixed_addr::(addr)?; - let mut bytes = [0u8; N]; - bytes.copy_from_slice(&self.data[addr..addr + N]); - Ok(bytes) + pub(crate) fn len(&self) -> usize { + self.data.len() + } + + #[inline(always)] + pub(super) fn checked_range(&self, addr: usize, len: usize) -> Option> { + let end = addr.checked_add(len)?; + (end <= self.data.len()).then_some(addr..end) + } + + /// Grows the backing allocation to `new_len`. Only called after the Wasm limits and any user + /// limiter have accepted the grow. + #[inline(always)] + 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_exact(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; + self.data.resize(new_len, 0); + Ok(()) } #[inline(always)] @@ -40,27 +49,27 @@ impl VecMemory { } Ok(()) } -} -impl LinearMemory for VecMemory { + /// Reads exactly `N` bytes at `addr` into a fixed-size array. #[inline(always)] - fn len(&self) -> usize { - self.data.len() + pub(crate) fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { + self.check_fixed_addr::(addr)?; + 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)] - 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() }); - } - cold_err!(self.data.try_reserve_exact(new_len.saturating_sub(self.data.len()))) - .map_err(|_| crate::Trap::OutOfMemory)?; - self.data.resize(new_len, 0); + pub(crate) fn write_fixed(&mut self, addr: usize, bytes: &[u8; N]) -> Result<(), crate::Trap> { + self.check_fixed_addr::(addr)?; + 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; } @@ -69,114 +78,60 @@ 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> { - Some(self.data.get(addr..addr.checked_add(len)?)?.to_vec()) - } - - #[inline(always)] - fn write(&mut self, addr: usize, src: &[u8]) -> Result { + pub(crate) fn write(&mut self, addr: usize, src: &[u8]) -> usize { if addr >= self.data.len() { - return Ok(0); + return 0; } - let write_len = src.len().min(self.data.len() - addr); self.data[addr..addr + write_len].copy_from_slice(&src[..write_len]); - Ok(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]) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.copy_from_slice(src); - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.fill(val); - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.data.len() || dst_end > self.data.len() { - return Ok(None); - } - - self.data.copy_within(src..src_end, dst); - Ok(Some(())) - } - - #[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) + 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 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(()) + pub(crate) fn read_vec(&self, addr: usize, len: usize) -> Option> { + 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 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(()) + 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 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 a previously checked range from another memory. #[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); - Ok(()) + pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) { + self.data[dst..dst + len].copy_from_slice(&src_memory.data[src..src + len]); } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 33a549c..f0e426f 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -23,7 +23,6 @@ mod types; use const_expr::eval_const; pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; -pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; @@ -32,12 +31,72 @@ pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); -/// Global state that can be manipulated by WebAssembly programs +/// Controls resource usage by WebAssembly instances. /// -/// Managed WebAssembly GC objects are collected automatically. Other Store -/// instances, such as modules, functions, memories, and tables, live until the -/// Store is dropped. GC references exposed through the copyable host value API -/// are retained for the Store's lifetime. +/// Configure a limiter with +/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently +/// controls guest linear-memory and table allocation and growth. It does not account for stacks, +/// GC storage, runtime metadata, or other host allocations. +/// +/// # Example +/// ```rust +/// use std::sync::Arc; +/// 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, +/// ) -> Result { +/// Ok(desired <= self.0) +/// } +/// } +/// +/// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024))); +/// let mut store = Store::new(Engine::new(config)); +/// let memory = Memory::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 { + /// Returns whether a memory allocation or growth is allowed. + /// + /// Sizes are in bytes. `current` is zero for initial allocation, and `maximum` is `None` for an + /// unbounded memory. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn memory_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } + + /// Returns whether a table allocation or growth is allowed. + /// + /// Sizes are in elements. `current` is zero for initial allocation, and `maximum` is `None` for + /// an unbounded table. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn table_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } +} + +/// Runtime state used by WebAssembly instances and host functions. /// /// ## Example /// ```rust @@ -240,6 +299,7 @@ impl Store { type_addrs: &[TypeAddr], ) -> Result> { 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 { @@ -254,7 +314,7 @@ impl Store { 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(ty, init)?); + self.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); } Ok(start..start + tables.len() as TableAddr) } @@ -263,12 +323,12 @@ impl Store { pub(crate) fn init_memories( &mut self, memories: &[MemoryType], - init: impl Fn(MemoryType, &MemoryBackend) -> Result, + init: impl Fn(MemoryType) -> Result, ) -> Result> { let start = self.state.memories.len() as MemAddr; self.state.memories.reserve_exact(memories.len()); for mem in memories { - self.state.memories.push(cold_err!(init(*mem, &self.engine.config().memory_backend))?); + self.state.memories.push(cold_err!(init(*mem))?); } Ok(start..start + memories.len() as MemAddr) } @@ -428,7 +488,7 @@ impl Store { }; let offset = usize::try_from(offset).unwrap_or(usize::MAX); - match mem.inner.write_all(offset, &data.data)? { + match mem.inner.write_all(offset, &data.data) { Some(()) => None, None => { return Ok(( diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 8e6c055..da52660 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -1,4 +1,4 @@ -use crate::{Result, Trap, interpreter::ValueRef}; +use crate::{ResourceLimiter, Result, Trap, interpreter::ValueRef}; use alloc::vec::Vec; use core::ops::Range; use tinywasm_types::*; @@ -16,11 +16,17 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. - pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { + pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result { 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(); cold_err!(elements.try_reserve_exact(size)).map_err(|_| Trap::OutOfMemory)?; elements.resize(size, init); @@ -74,17 +80,38 @@ impl TableInstance { Ok(()) } - pub(crate) fn grow(&mut self, n: usize, init: ValueRef) -> 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 { + 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); } - cold_err!(self.elements.try_reserve_exact(n)).map_err(|_| Trap::OutOfMemory)?; + if cold_err!(self.elements.try_reserve_exact(n)).is_err() { + return Ok(false); + } self.elements.resize(len, init); - Ok(()) + Ok(true) + } + + fn maximum_size(kind: TableType) -> Option { + kind.size_max.and_then(|maximum| usize::try_from(maximum).ok()) } pub(crate) fn size(&self) -> usize { diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 07cbde2..1793e05 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -65,7 +65,7 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box = Result>; + +fn store_with_limiter(limiter: Arc) -> 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::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::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) -> Result { + Ok(false) + } + + fn table_growing(&self, _current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(false) + } +} + +struct DenyGrowth; + +impl ResourceLimiter for DenyGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } +} + +struct TrapGrowth; + +impl ResourceLimiter for TrapGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } +} + +#[test] +fn resource_limiter_can_reject_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let memory = Memory::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(Arc::new(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(Arc::new(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(Arc::new(DenyAll)); + let result = Memory::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 1))")?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(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(Arc::new(DenyAll)); + let result = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), 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(Arc::new(DenyGrowth)); + let table = Table::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(Arc::new(TrapGrowth)); + let table = Table::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 73657df..0000000 --- a/crates/tinywasm/tests/memory_backends.rs +++ /dev/null @@ -1,307 +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 tinywasm::engine::Config; -use tinywasm::types::{MemoryArch, MemoryType}; -use tinywasm::{Engine, Memory, MemoryBackend, Module, ModuleInstance, PagedMemory, Store}; -use tinywasm_parser::{Parser, ParserOptions}; - -type TestResult = Result>; - -fn initial_memory_size(ty: MemoryType) -> usize { - usize::try_from(ty.page_count_initial()) - .ok() - .and_then(|pages| pages.checked_mul(usize::try_from(ty.page_size()).ok()?)) - .expect("test memory size should fit usize") -} - -fn instantiate_module_with_counting_backend(module: Module) -> TestResult { - 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); - PagedMemory::try_new(initial_memory_size(ty), 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) -> TestResult { - 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, -) -> TestResult<(Store, tinywasm::ModuleInstance, Arc)> { - 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); - PagedMemory::try_new(initial_memory_size(ty), 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() -> TestResult { - 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() -> TestResult { - 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); - PagedMemory::try_new(initial_memory_size(ty), 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() -> TestResult { - 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() -> TestResult { - 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() -> TestResult { - 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() -> TestResult { - 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() -> TestResult { - 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() -> TestResult { - let wasm = wat::parse_str( - r#" - (module - (memory 1) - (func (export "run")) - ) - "#, - )?; - let parser = Parser::new(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() -> TestResult { - 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() -> TestResult { - 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(()) -} - -#[test] -fn paged_fixed_width_accesses_cross_chunk_boundaries() -> TestResult { - use tinywasm::LinearMemory; - - let mut memory = PagedMemory::try_new(32, 4).map_err(tinywasm::Error::from)?; - memory.write_32(2, &0x1234_5678u32.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_64(6, &0x0123_4567_89ab_cdefu64.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_128(14, &u128::MAX.to_le_bytes()).map_err(tinywasm::Error::from)?; - - assert_eq!(u32::from_le_bytes(memory.read_32(2).map_err(tinywasm::Error::from)?), 0x1234_5678); - assert_eq!(u64::from_le_bytes(memory.read_64(6).map_err(tinywasm::Error::from)?), 0x0123_4567_89ab_cdef); - assert_eq!(u128::from_le_bytes(memory.read_128(14).map_err(tinywasm::Error::from)?), u128::MAX); - Ok(()) -} - -#[test] -fn lazy_custom_backend_creation_trap_is_propagated() -> TestResult { - let wasm = wat::parse_str(r#"(module (memory (export "memory") 1))"#)?; - let module = tinywasm::parse_bytes(&wasm)?; - let backend = MemoryBackend::custom(|_| Err::(tinywasm::Trap::Other("backend unavailable"))); - let mut store = Store::new(Engine::new(Config::new().with_memory_backend(backend))); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let memory = instance.memory("memory")?; - - assert_eq!( - memory.copy_from_slice(&mut store, 0, &[1]).unwrap_err(), - tinywasm::Error::from(tinywasm::Trap::Other("backend unavailable")) - ); - 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); -} - -#[cfg(feature = "std")] -#[test] -fn memory_cursor_supports_read_write_and_seek() -> TestResult { - 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/types/src/instructions.rs b/crates/types/src/instructions.rs index 797f703..c9786d3 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -799,89 +799,6 @@ pub enum Instruction { const _: () = assert!(core::mem::size_of::() == 8); -impl Instruction { - /// Returns the largest module-local memory index used by this instruction. - #[inline] - pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { - use Instruction::*; - match *self { - IncMemoryLocal32(arg) - | IncMemoryLocal64(arg) - | StoreLocalLocal32(arg) - | StoreLocalLocal64(arg) - | StoreLocalLocal128(arg) - | LoadLocal32(arg) - | LoadLocal64(arg) - | LoadLocal8S32(arg) - | LoadLocal8U32(arg) - | LoadLocal16S32(arg) - | LoadLocal16U32(arg) - | LoadLocalTee32(arg) - | LoadLocalSet32(arg) - | LoadLocalTee8S32(arg) - | LoadLocalTee8U32(arg) - | LoadLocalTee16S32(arg) - | LoadLocalTee16U32(arg) - | LoadLocalSet8S32(arg) - | LoadLocalSet8U32(arg) - | LoadLocalSet16S32(arg) - | LoadLocalSet16U32(arg) - | LoadLocalTee128(arg) - | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), - I32Load(index) - | I64Load(index) - | F32Load(index) - | F64Load(index) - | I32Load8S(index) - | I32Load8U(index) - | I32Load16S(index) - | I32Load16U(index) - | I64Load8S(index) - | I64Load8U(index) - | I64Load16S(index) - | I64Load16U(index) - | I64Load32S(index) - | I64Load32U(index) - | I32Store(index) - | I64Store(index) - | F32Store(index) - | F64Store(index) - | I32Store8(index) - | I32Store16(index) - | I64Store8(index) - | I64Store16(index) - | I64Store32(index) - | V128Load(index) - | V128Load8x8S(index) - | V128Load8x8U(index) - | V128Load16x4S(index) - | V128Load16x4U(index) - | V128Load32x2S(index) - | V128Load32x2U(index) - | V128Load8Splat(index) - | V128Load16Splat(index) - | V128Load32Splat(index) - | V128Load64Splat(index) - | V128Load32Zero(index) - | V128Load64Zero(index) - | V128Store(index) => Some(index.get(data).mem_addr()), - V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) - | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { - Some(arg.memory_arg_idx.get(data).mem_addr()) - } - FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), - MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), - MemoryFillConst(index) => Some(index.get(data).memory), - MemoryInit(index) => Some(index.get(data).second), - MemoryCopy(index) => { - let value = index.get(data); - Some(value.first.max(value.second)) - } - _ => None, - } - } -} - #[cfg(test)] mod tests { use alloc::vec; diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index bd92753..d1f7453 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -133,9 +133,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 { @@ -297,20 +294,6 @@ pub enum ExportType<'a> { Tag(&'a FuncType), } -/// 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, -} - /// A WebAssembly External Kind. /// /// See @@ -614,6 +597,12 @@ impl MemoryType { } } + /// The declared maximum page count, or `None` when the memory is unbounded. + #[inline] + pub const fn page_count_max_declared(&self) -> Option { + self.page_count_max + } + #[inline] pub const fn page_size(&self) -> u64 { if let Some(page_size) = self.page_size { page_size } else { MEM_PAGE_SIZE } @@ -711,7 +700,7 @@ impl From<&ImportKind> for ExternalKind { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct Data { pub data: Box<[u8]>, - pub range: Range, + pub range: Range, pub kind: DataKind, } @@ -729,7 +718,7 @@ pub enum DataKind { pub struct Element { pub kind: ElementKind, pub items: Box<[ElementItem]>, - pub range: Range, + pub range: Range, pub ty: RefType, } diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index b338bd2..6701074 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 @@ -22,10 +22,6 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" -[[bin]] -name = "tinywasm_precompiled" -path = "src/tinywasm_precompiled.rs" - [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -41,10 +37,10 @@ path = "src/argon2id.rs" [dependencies] argon2 = { version = "0.5" } 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"] } + +[lints.clippy] +missing_safety_doc = "allow" [features] default = ["std"] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index b2a6149..cbd3b27 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") -exclude_wat=("tinywasm" "tinywasm_precompiled") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") +exclude_wat=("tinywasm") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" 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 index f0fa9a8..7841329 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs deleted file mode 100644 index bc0e0c1..0000000 --- a/examples/rust/src/tinywasm_precompiled.rs +++ /dev/null @@ -1,30 +0,0 @@ -#![no_main] -use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; - -#[link(wasm_import_module = "env")] -unsafe extern "C" { - fn printi32(x: i32); -} - -#[unsafe(no_mangle)] -pub extern "C" fn hello() { - let _ = run(); -} - -fn run() -> tinywasm::Result<()> { - let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; - let mut store = tinywasm::Store::default(); - - let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { - unsafe { printi32(v) } - Ok(()) - }); - - let mut imports = tinywasm::Imports::new(); - imports.define("env", "printi32", printi32); - - 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/wasm-rust.rs b/examples/wasm-rust.rs index b3398f8..0cfb0ce 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,7 +35,6 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); @@ -46,7 +45,6 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, - "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -60,8 +58,6 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; - println!("\ntinywasm_precompiled.wasm:"); - tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -105,21 +101,6 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } -fn tinywasm_precompiled() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - 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(()))?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - Ok(()) -} - fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -231,11 +212,6 @@ mod tests { tinywasm().unwrap(); } - #[test] - fn test_tinywasm_precompiled() { - tinywasm_precompiled().unwrap(); - } - #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From e5f234b1604511d0463252ee173caee6e9cd18f4 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 25 Aug 2026 18:05:11 +0200 Subject: feat: add support for portable-atomic, add send feature Signed-off-by: Henry --- CHANGELOG.md | 2 ++ Cargo.lock | 18 ++++++++++ README.md | 3 +- crates/parser/Cargo.toml | 11 ++++++ crates/parser/src/lib.rs | 3 +- crates/parser/src/module.rs | 16 ++++----- crates/parser/src/parallel.rs | 5 ++- crates/tinywasm/Cargo.toml | 7 ++++ crates/tinywasm/src/engine.rs | 15 ++++++--- crates/tinywasm/src/func/context.rs | 3 +- crates/tinywasm/src/func/host.rs | 52 +++++++++++++++++++++++------ crates/tinywasm/src/func/mod.rs | 16 +++++---- crates/tinywasm/src/func/resume.rs | 13 ++++---- crates/tinywasm/src/instance.rs | 11 +++--- crates/tinywasm/src/interpreter/executor.rs | 35 +++++++++---------- crates/tinywasm/src/lib.rs | 6 +++- crates/tinywasm/src/reference/managed.rs | 25 ++++---------- crates/tinywasm/src/shared.rs | 9 +++++ crates/tinywasm/src/store/function.rs | 7 ++-- crates/tinywasm/src/store/gc/object.rs | 13 ++++---- crates/tinywasm/src/store/gc/roots.rs | 11 +++--- crates/tinywasm/src/store/mod.rs | 12 +++---- crates/tinywasm/src/store/state.rs | 4 +-- crates/tinywasm/tests/managed_exceptions.rs | 3 +- crates/tinywasm/tests/memory.rs | 22 +++++------- crates/types/Cargo.toml | 15 +++++++-- crates/types/src/archive.rs | 21 ++++++------ crates/types/src/lib.rs | 28 +++++++++++++--- crates/types/src/types.rs | 6 ++-- 29 files changed, 244 insertions(+), 148 deletions(-) create mode 100644 crates/tinywasm/src/shared.rs (limited to 'Cargo.lock') diff --git a/CHANGELOG.md b/CHANGELOG.md index bad8caf..a786aa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `ResourceLimiter` callbacks for memory and table allocation or growth - A default `validate` Cargo feature & parser option to skip wasm 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 ### Changed diff --git a/Cargo.lock b/Cargo.lock index ac0895a..1663c7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -570,6 +570,22 @@ dependencies = [ "winapi", ] +[[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.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", + "serde", +] + [[package]] name = "postcard" version = "1.1.3" @@ -864,6 +880,7 @@ version = "0.11.0-pre.0" dependencies = [ "libm", "log", + "portable-atomic", "tinywasm-cli", "tinywasm-parser", "tinywasm-types", @@ -919,6 +936,7 @@ name = "tinywasm-types" version = "0.11.0-pre.0" dependencies = [ "log", + "portable-atomic-util", "postcard", "serde", ] diff --git a/README.md b/README.md index 70578dd..8b400de 100644 --- a/README.md +++ b/README.md @@ -57,9 +57,10 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin - **`debug`:** Derives `Debug` for runtime types. Enabled by default. - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`). +- **`send`:** Makes stores and store-local handles movable across threads - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally. -With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `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. diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml index 561ac45..042eeda 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -17,7 +17,18 @@ wasmparser = { workspace = true, features = ["simd"] } [features] 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"] diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 262cc07..3369f7b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -292,7 +292,8 @@ impl Parser { } let section_end = buffer_offset + section_size; - let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec()); + 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; diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index c076035..bfb28ce 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -3,7 +3,7 @@ use crate::log::debug; use crate::validation::{FuncToValidate, ValidatorResources}; use crate::validation::{FuncValidatorAllocations, Validator}; use crate::{ParseError, ParserOptions, Result, conversion::*, optimize}; -use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec}; +use alloc::{boxed::Box, format, string::ToString, vec::Vec}; use core::marker::PhantomData; use core::ops::Range; use tinywasm_types::*; @@ -37,7 +37,7 @@ pub(crate) fn optimize_function_code( pub(crate) struct ModuleReader<'a> { func_validator_allocations: Option, operators_reader_allocations: Option, - translation_metadata: Option>, + translation_metadata: Option, has_code_section: bool, has_type_section: bool, @@ -48,7 +48,7 @@ pub(crate) struct ModuleReader<'a> { 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, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, @@ -68,7 +68,7 @@ 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.translation_metadata = Some(crate::visit::ModuleMetadata::new( &self.types, &self.code_type_addrs, &self.imports, @@ -76,9 +76,9 @@ impl<'a> ModuleReader<'a> { &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<'_>, validator: Option<&mut Validator>) -> Result<()> { @@ -435,7 +435,7 @@ impl<'a> ModuleReader<'a> { &mut self, count: u32, body_offset: u64, - section_bytes: Arc<[u8]>, + section_bytes: Shared<[u8]>, validator: Option<&mut Validator>, ) -> Result<()> { #[cfg(feature = "validate")] @@ -545,7 +545,7 @@ impl<'a> ModuleReader<'a> { self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); - Ok(Arc::new(WasmFunction { + Ok(Shared::new(WasmFunction { instructions: code.instructions.into_boxed_slice(), data: code.data, locals: code.locals, diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index 9b96c7a..4ad16cf 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,10 +1,9 @@ use crate::module::{OptimizedFunctionCode, optimize_function_code}; 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 tinywasm_types::{Shared, ValueCounts}; use wasmparser::OperatorsReaderAllocations; pub(crate) enum FunctionBodyInput<'a> { @@ -15,7 +14,7 @@ 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, pub body_offset: u64, } diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index eb5dd94..954ae40 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -88,6 +88,7 @@ name = "test-wasm-wide-arithmetic" [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 } @@ -111,6 +112,9 @@ default = [ log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] +# make stores, instances, references, and host callbacks movable across threads +send = [] + # support for parsing WebAssembly parser = ["dep:tinywasm-parser"] @@ -120,6 +124,9 @@ validate = ["parser", "tinywasm-parser/validate"] # parallelize function parsing/validation across threads (requires std) parallel-parser = ["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"] diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index f1feae6..4fc74d5 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -1,10 +1,12 @@ -use alloc::sync::Arc; +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 @@ -117,7 +119,7 @@ pub struct Config { /// Fuel accounting policy used by budgeted execution. Defaults to [`FuelPolicy::PerInstruction`]. pub fuel_policy: FuelPolicy, /// Resource limiter shared across all stores created from this engine. Defaults to `None`. - pub resource_limiter: Option>, + pub resource_limiter: Option>, /// Initial number of GC heap bytes that triggers collection. /// Defaults to 1 MiB. pub gc_collection_threshold: usize, @@ -168,8 +170,11 @@ impl Config { } /// Set the resource limiter shared across all stores created from this engine. - pub fn with_resource_limiter(mut self, limiter: Arc) -> Self { - self.resource_limiter = Some(limiter); + /// + /// 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)); self } diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index 7e289f6..0b9e1f9 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -119,7 +119,8 @@ impl FuncContext<'_> { } func.func.item.validate_store(self.store)?; let func_instance = self.store.state.get_func(func.func.addr()).clone(); - if matches!(&func_instance.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + if matches!(&func_instance.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) + { let ty = self.store.state.get_canonical_func_type(func_instance.type_addr); let (param_count, result_count) = (ty.params().len(), ty.results().len()); self.store.with_scratch_values(param_count + result_count, |store, values| { diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 8f36761..1dcf3c1 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -1,18 +1,38 @@ -use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use alloc::{boxed::Box, vec::Vec}; use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; +use crate::shared::StoreShared; use crate::store::FuncValueTypes; use crate::{Function, FunctionInstance, 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 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 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(Arc); +pub struct HostFunction(StoreShared); 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_func(FunctionInstance { type_addr, kind: crate::store::FunctionKind::Host(self.clone()) }); + let addr = store + .add_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) }); Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 } } @@ -155,11 +175,11 @@ impl HostFunction { /// # Ok(()) /// # } /// ``` - pub fn from_untyped( - ty: &FuncType, - func: impl Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync + 'static, - ) -> Self { - Self(Arc::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) })) + pub fn from_untyped(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. @@ -190,14 +210,15 @@ impl HostFunction { /// # Ok(()) /// # } /// ``` - pub fn from(func: impl Fn(FuncContext<'_>, P) -> Result + Send + Sync + 'static) -> Self + pub fn from(func: F) -> Self where + F: Fn(FuncContext<'_>, P) -> Result + HostFunctionCallback + 'static, P: FromWasmValues + ToWasmTypes + 'static, R: IntoWasmValues + ToWasmTypes + 'static, { let ty = FuncType::new(&P::wasm_types(), &R::wasm_types()); let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData }; - Self(Arc::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) })) + Self(StoreShared::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) })) } } @@ -211,8 +232,17 @@ enum HostCallback { Typed(Box), } +#[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<()>; @@ -225,7 +255,7 @@ struct TypedHostCallbackImpl { impl TypedHostCallback for TypedHostCallbackImpl where - F: Fn(FuncContext<'_>, P) -> Result + Send + Sync, + F: Fn(FuncContext<'_>, P) -> Result + HostFunctionCallback, P: FromWasmValues, R: IntoWasmValues, { diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index c29b3db..2fbc22f 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -13,6 +13,8 @@ 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, ToWasmType, ToWasmTypes}; @@ -122,12 +124,12 @@ impl Function { ) -> Result<()> { let instance = store.state.get_func(self.addr()); let type_addr = instance.type_addr; - match &instance.kind { - crate::store::FunctionKind::Host(host) => { + match &instance.inner { + crate::store::FunctionInstanceInner::Host(host) => { let host = host.clone(); host.call_values(store, self.module_id, type_addr, params, results) } - crate::store::FunctionKind::Wasm(wasm) => { + crate::store::FunctionInstanceInner::Wasm(wasm) => { let wasm_params = wasm.func.params; let wasm_locals = wasm.func.locals; store @@ -156,15 +158,15 @@ impl Function { stack_base: StackBase, ) -> Result> { store.push_typed_values::(instance.type_addr, params, stack_base)?; - match &instance.kind { - crate::store::FunctionKind::Wasm(wasm) => { + match &instance.inner { + crate::store::FunctionInstanceInner::Wasm(wasm) => { let locals_base = store .value_stack .enter_locals(&wasm.func.params, &wasm.func.locals) .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; Ok(Some(CallFrame::new(self.addr(), locals_base, wasm.func.locals))) } - crate::store::FunctionKind::Host(host) => { + crate::store::FunctionInstanceInner::Host(host) => { host.typed_callback() .expect("typed host function") .call_stack(store, self.module_id, instance.type_addr) @@ -209,7 +211,7 @@ impl FunctionTyped { pub fn call(&self, store: &mut Store, params: P) -> Result { self.func.item.validate_store(store)?; let func = store.state.get_func(self.func.addr()).clone(); - if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { let ty = store.state.get_canonical_func_type(func.type_addr); let (param_count, result_count) = (ty.params().len(), ty.results().len()); store.with_scratch_values(param_count + result_count, |store, values| { diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index 6772eb8..cc461a7 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -62,18 +62,17 @@ impl Function { store.enter_execution()?; let result: Result = (|| { let func_instance = store.state.get_func(self.addr()).clone(); - match &func_instance.kind { - crate::store::FunctionKind::Host(host_func) => { + match &func_instance.inner { + crate::store::FunctionInstanceInner::Host(host_func) => { host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; Ok(FuncExecutionState::Completed(Some(CallResult::Written))) } - crate::store::FunctionKind::Wasm(wasm_func) => { + crate::store::FunctionInstanceInner::Wasm(wasm_func) => { store.call_stack.clear(); store.value_stack.clear(); - let locals = wasm_func.func.locals; store.push_wasm_values(params.iter().cloned())?; - let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &locals)?; - let callframe = CallFrame::new(self.addr(), locals_base, locals); + let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; + let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals); Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) } @@ -205,7 +204,7 @@ impl FunctionTyped { pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result> { self.func.item.validate_store(store)?; let func = store.state.get_func(self.func.addr()).clone(); - if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { let result = self.call(store, params)?; let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) }; return Ok(FuncExecutionTyped { execution, result: Some(result) }); diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 4a92212..bd78a57 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -1,9 +1,10 @@ -use alloc::{boxed::Box, format, rc::Rc, sync::Arc}; +use alloc::{boxed::Box, format}; use core::hint::cold_path; use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; use crate::reference::StoreId; +use crate::shared::StoreShared; use crate::store::MemoryInstance; use crate::{ Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap, WasmValue, @@ -41,12 +42,12 @@ pub enum ExternItem { /// # } /// ``` /// -/// Backed by an Rc, so cloning is cheap +/// Cloning an instance handle is cheap. /// /// See #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] -pub struct ModuleInstance(Rc); +pub struct ModuleInstance(StoreShared); #[cfg_attr(feature = "debug", derive(Debug))] struct ModuleInstanceInner { @@ -61,7 +62,7 @@ struct ModuleInstanceInner { elem_addrs: Box<[ElemAddr]>, data_addrs: Box<[DataAddr]>, func_start: Option, - exports: Arc<[Export]>, + exports: Shared<[Export]>, } impl ModuleInstance { @@ -206,7 +207,7 @@ impl ModuleInstance { exports: module.exports.clone(), }; - let instance = ModuleInstance(Rc::new(instance)); + let instance = ModuleInstance(StoreShared::new(instance)); store.add_instance(instance.clone()); if let Some(trap) = elem_trapped.or(data_trapped) { diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 76c6364..4824b63 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -8,7 +8,6 @@ use super::no_std_floats::NoStdFloatExt; use alloc::boxed::Box; use alloc::vec::Vec; -use alloc::sync::Arc; use interpreter::stack::CallFrame; use tinywasm_types::*; @@ -24,7 +23,7 @@ const FUEL_COST_CALL_TOTAL: u32 = 5; pub(crate) struct Executor<'store, const BUDGETED: bool> { cf: CallFrame, - func: Arc, + func: Shared, module: ModuleInstance, store: &'store mut Store, call_stack_base: u32, @@ -1020,7 +1019,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call( &mut self, - wasm_func: Arc, + wasm_func: Shared, owner: ModuleInstanceId, func_addr: FuncAddr, return_instr_ptr: usize, @@ -1030,11 +1029,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; self.store.call_stack.push(self.cf, return_instr_ptr)?; - let locals = wasm_func.locals; - if !Arc::ptr_eq(&self.func, &wasm_func) { + self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); + if !Shared::ptr_eq(&self.func, &wasm_func) { self.func = wasm_func; } - self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { self.set_module(owner); } @@ -1044,7 +1042,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_return_call( &mut self, - wasm_func: Arc, + wasm_func: Shared, owner: ModuleInstanceId, func_addr: FuncAddr, ) -> Result<(), Trap> { @@ -1052,11 +1050,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; - let locals = wasm_func.locals; - if !Arc::ptr_eq(&self.func, &wasm_func) { + self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); + if !Shared::ptr_eq(&self.func, &wasm_func) { self.func = wasm_func; } - self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { self.set_module(owner); } @@ -1108,12 +1105,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); - match &func.kind { - crate::store::FunctionKind::Wasm(wasm_func) => { + match &func.inner { + crate::store::FunctionInstanceInner::Wasm(wasm_func) => { self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr, return_instr_ptr)?; Ok(ControlFlow::Continue(0)) } - crate::store::FunctionKind::Host(host_func) => { + crate::store::FunctionInstanceInner::Host(host_func) => { self.exec_call_host::(host_func.clone(), func.type_addr, return_instr_ptr) } } @@ -1123,12 +1120,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); - match &func.kind { - crate::store::FunctionKind::Wasm(wasm_func) => { + match &func.inner { + crate::store::FunctionInstanceInner::Wasm(wasm_func) => { self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; Ok(ControlFlow::Continue(0)) } - crate::store::FunctionKind::Host(host_func) => { + crate::store::FunctionInstanceInner::Host(host_func) => { self.exec_call_host::(host_func.clone(), func.type_addr, 0) } } @@ -1192,12 +1189,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), })); } - match &func.kind { - crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL { + match &func.inner { + crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL { true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr, return_instr_ptr), }, - crate::store::FunctionKind::Host(host_func) => { + crate::store::FunctionInstanceInner::Host(host_func) => { return self.exec_call_host::(host_func.clone(), func.type_addr, return_instr_ptr); } }?; diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index 15ccd0e..d89bfa1 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -90,6 +90,9 @@ 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)] @@ -111,7 +114,7 @@ mod error; pub use error::*; pub use func::{ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, - HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes, + HostFunction, HostFunctionCallback, IntoWasmValues, ToWasmType, ToWasmTypes, }; pub use imports::*; pub use instance::{ExternItem, ModuleInstance}; @@ -122,6 +125,7 @@ mod func; mod imports; mod instance; mod reference; +mod shared; mod store; mod interpreter; diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs index 1e5f38a..79bd0b9 100644 --- a/crates/tinywasm/src/reference/managed.rs +++ b/crates/tinywasm/src/reference/managed.rs @@ -1,7 +1,7 @@ -use alloc::sync::Arc; -use core::sync::atomic::{AtomicU32, Ordering}; +use tinywasm_types::Shared; use crate::interpreter::ValueRef; +use crate::shared::{AtomicU32, Ordering}; use crate::{Result, Store, Trap}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] @@ -10,7 +10,9 @@ pub(crate) struct StoreId(u32); impl StoreId { pub(crate) fn fresh() -> Self { static NEXT: AtomicU32 = AtomicU32::new(0); - next_store_id(&NEXT) + let id = NEXT.fetch_add(1, Ordering::Relaxed); + assert_ne!(id, u32::MAX, "Store identity space exhausted"); + StoreId(id) } pub(crate) const fn get(self) -> u32 { @@ -18,13 +20,6 @@ impl StoreId { } } -fn next_store_id(counter: &AtomicU32) -> StoreId { - let id = counter - .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) - .expect("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 { @@ -47,7 +42,7 @@ pub(crate) struct RootedItem { pub(crate) store: StoreId, pub(crate) value: ValueRef, pub(crate) kind: ReferentKind, - pub(crate) _token: Option>, + pub(crate) _token: Option>, } impl PartialEq for RootedItem { @@ -220,14 +215,6 @@ mod tests { extern crate std; use super::*; - #[test] - fn exhausted_store_identity_counter_never_wraps() { - let counter = AtomicU32::new(u32::MAX - 1); - assert_eq!(next_store_id(&counter).get(), u32::MAX - 1); - assert!(std::panic::catch_unwind(|| next_store_id(&counter)).is_err()); - assert!(std::panic::catch_unwind(|| next_store_id(&counter)).is_err()); - } - #[test] fn host_reference_key_fits_internal_encoding() { assert!(ValueRef::try_from_host_any((1 << 30) - 2).is_some()); 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/function.rs b/crates/tinywasm/src/store/function.rs index 3c716a7..88fff5d 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -1,4 +1,3 @@ -use alloc::sync::Arc; use tinywasm_types::*; use crate::func::HostFunction; @@ -10,12 +9,12 @@ use crate::func::HostFunction; #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct FunctionInstance { pub(crate) type_addr: TypeAddr, - pub(crate) kind: FunctionKind, + pub(crate) inner: FunctionInstanceInner, } #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) enum FunctionKind { +pub(crate) enum FunctionInstanceInner { /// A host function Host(HostFunction), @@ -26,6 +25,6 @@ pub(crate) enum FunctionKind { #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct WasmFunctionInstance { - pub(crate) func: Arc, + pub(crate) func: Shared, pub(crate) owner: ModuleInstanceId, } diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs index cf27cd5..b92e07a 100644 --- a/crates/tinywasm/src/store/gc/object.rs +++ b/crates/tinywasm/src/store/gc/object.rs @@ -1,11 +1,11 @@ -use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use alloc::{boxed::Box, vec::Vec}; use core::mem::size_of; -use core::sync::atomic::{AtomicU32, Ordering}; use tinywasm_types::{TagAddr, TypeAddr}; use crate::engine::Config; use crate::interpreter::{RuntimeValue, ValueRef}; +use crate::shared::{AtomicU32, Ordering, StoreShared}; use crate::{ResourceLimiter, Trap}; use super::{AllocError, Arena, Handle, Trace}; @@ -35,7 +35,7 @@ impl Trace for GcObject { pub(crate) struct GcHeap { objects: Arena, directory: Vec<(u32, Handle)>, - resource_limiter: Option>, + resource_limiter: Option>, } impl Default for GcHeap { @@ -114,11 +114,10 @@ impl GcHeap { ) -> Result { let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?; - let key = - NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1)); - let Ok(key) = key else { + let key = NEXT_GC_REF.fetch_add(1, Ordering::Relaxed); + if key >= 1 << 30 { return Err(Trap::OutOfMemory); - }; + } let references = if trace_references { let mut references = Vec::new(); references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?; diff --git a/crates/tinywasm/src/store/gc/roots.rs b/crates/tinywasm/src/store/gc/roots.rs index 7107295..ea6c47a 100644 --- a/crates/tinywasm/src/store/gc/roots.rs +++ b/crates/tinywasm/src/store/gc/roots.rs @@ -1,4 +1,5 @@ -use alloc::{sync::Arc, sync::Weak, vec::Vec}; +use alloc::vec::Vec; +use tinywasm_types::{Shared, WeakShared}; use crate::Trap; use crate::interpreter::ValueRef; @@ -10,7 +11,7 @@ pub(crate) struct Roots { struct Root { value: ValueRef, - token: Weak<()>, + token: WeakShared<()>, } impl Roots { @@ -24,7 +25,7 @@ impl Roots { self.entries.try_reserve(needed).map_err(|_| Trap::OutOfMemory) } - pub(crate) fn insert(&mut self, value: ValueRef) -> Result, Trap> { + pub(crate) fn insert(&mut self, value: ValueRef) -> Result, Trap> { if self.free.is_empty() && self.entries.len() == self.entries.capacity() { self.remove_dead(); } @@ -37,8 +38,8 @@ impl Roots { index }; - let token = Arc::new(()); - self.entries[index as usize] = Some(Root { value, token: Arc::downgrade(&token) }); + let token = Shared::new(()); + self.entries[index as usize] = Some(Root { value, token: Shared::downgrade(&token) }); Ok(token) } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 91895b4..57c7575 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -41,7 +41,6 @@ pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*}; /// /// # Example /// ```rust -/// use std::sync::Arc; /// use tinywasm::engine::Config; /// use tinywasm::types::{MemoryArch, MemoryType}; /// use tinywasm::{Engine, Memory, ResourceLimiter, Store}; @@ -59,7 +58,7 @@ pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*}; /// } /// } /// -/// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024))); +/// 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); @@ -506,7 +505,7 @@ impl Store { /// Add functions to the store, returning their addresses in the store pub(crate) fn init_funcs( &mut self, - funcs: &[alloc::sync::Arc], + funcs: &[Shared], owner: ModuleInstanceId, module_type_idxs: &[TypeAddr], type_addrs: &[TypeAddr], @@ -516,9 +515,10 @@ impl Store { self.state.funcs.reserve_exact(funcs.len()); for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) { let type_addr = type_addrs[type_idx as usize]; - self.state - .funcs - .push(FunctionInstance { type_addr, kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }) }); + self.state.funcs.push(FunctionInstance { + type_addr, + inner: FunctionInstanceInner::Wasm(WasmFunctionInstance { func, owner }), + }); } start..start + funcs.len() as FuncAddr } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 11ea70d..769fc8b 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -309,8 +309,8 @@ impl State { /// 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, + match self.funcs.get(addr as usize).map(|func| &func.inner) { + Some(FunctionInstanceInner::Wasm(wasm_func)) => wasm_func, _ => unreachable!("invalid wasm function address: {addr}"), } } diff --git a/crates/tinywasm/tests/managed_exceptions.rs b/crates/tinywasm/tests/managed_exceptions.rs index bb75459..ecb6a12 100644 --- a/crates/tinywasm/tests/managed_exceptions.rs +++ b/crates/tinywasm/tests/managed_exceptions.rs @@ -125,8 +125,7 @@ impl ResourceLimiter for GcUsage { #[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(Arc::new(GcUsage(usage.clone()))); + 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(); diff --git a/crates/tinywasm/tests/memory.rs b/crates/tinywasm/tests/memory.rs index 819fe85..608b9e1 100644 --- a/crates/tinywasm/tests/memory.rs +++ b/crates/tinywasm/tests/memory.rs @@ -1,14 +1,10 @@ -extern crate alloc; - -use alloc::sync::Arc; - use tinywasm::engine::Config; use tinywasm::types::{MemoryArch, MemoryType, RefType, RefValue, TableType}; use tinywasm::{Engine, Memory, ModuleInstance, ResourceLimiter, Store, Table, Trap}; type TestResult = Result>; -fn store_with_limiter(limiter: Arc) -> Store { +fn store_with_limiter(limiter: impl ResourceLimiter + 'static) -> Store { let engine = Engine::new(Config::new().with_resource_limiter(limiter)); Store::new(engine) } @@ -83,7 +79,7 @@ impl ResourceLimiter for TrapGrowth { #[test] fn resource_limiter_can_reject_growth() -> TestResult { - let mut store = store_with_limiter(Arc::new(DenyGrowth)); + 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); @@ -103,7 +99,7 @@ fn resource_limiter_rejects_guest_memory_grow() -> TestResult { "#, )?; let module = tinywasm::parse_bytes(&wasm)?; - let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let mut store = store_with_limiter(DenyGrowth); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let grow = instance.func::<(), i32>(&store, "grow")?; @@ -123,7 +119,7 @@ fn resource_limiter_can_trap_guest_memory_grow() -> TestResult { "#, )?; let module = tinywasm::parse_bytes(&wasm)?; - let mut store = store_with_limiter(Arc::new(TrapGrowth)); + let mut store = store_with_limiter(TrapGrowth); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let grow = instance.func::<(), i32>(&store, "grow")?; @@ -133,7 +129,7 @@ fn resource_limiter_can_trap_guest_memory_grow() -> TestResult { #[test] fn resource_limiter_rejects_host_memory_initial_size() { - let mut store = store_with_limiter(Arc::new(DenyAll)); + 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)))); @@ -143,7 +139,7 @@ fn resource_limiter_rejects_host_memory_initial_size() { fn resource_limiter_rejects_module_memory_initial_size() -> TestResult { let wasm = wat::parse_str("(module (memory 1))")?; let module = tinywasm::parse_bytes(&wasm)?; - let mut store = store_with_limiter(Arc::new(DenyAll)); + let mut store = store_with_limiter(DenyAll); let result = ModuleInstance::instantiate(&mut store, &module, None); assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); @@ -152,7 +148,7 @@ fn resource_limiter_rejects_module_memory_initial_size() -> TestResult { #[test] fn resource_limiter_rejects_table_initial_size() { - let mut store = store_with_limiter(Arc::new(DenyAll)); + 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)))); @@ -168,7 +164,7 @@ fn table_rejects_initial_size_above_maximum() { #[test] fn resource_limiter_can_reject_table_growth() -> TestResult { - let mut store = store_with_limiter(Arc::new(DenyGrowth)); + 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); @@ -178,7 +174,7 @@ fn resource_limiter_can_reject_table_growth() -> TestResult { #[test] fn resource_limiter_can_trap_table_growth() -> TestResult { - let mut store = store_with_limiter(Arc::new(TrapGrowth)); + 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)))); diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 3587143..7f701cf 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -12,13 +12,24 @@ categories.workspace = true [dependencies] log = { workspace = true, optional = true } +portable-atomic-util = { version = "0.2.7", 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"] -archive = ["dep:postcard", "dep:serde"] +# support serializing and deserializing twasm archives +archive = ["dep:postcard", "dep:serde", "serde/rc", "portable-atomic-util?/serde"] + +# derive Debug for runtime and module types debug = [] + +# enable integration with the log crate log = ["dep:log"] + +# enable standard library support std = ["serde?/std"] + +# support targets without native atomic CAS +portable-atomic = ["dep:portable-atomic-util"] diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index b568155..db13ab0 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -66,10 +66,10 @@ mod tests { use super::*; use crate::{ AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType, - V128Operand, WasmFunction, WasmType, + Shared, V128Operand, WasmFunction, WasmType, }; use crate::{OperandIdx, OperandType}; - use alloc::{boxed::Box, sync::Arc, vec}; + use alloc::boxed::Box; #[test] fn test_invalid_magic() { @@ -92,9 +92,9 @@ mod tests { 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 = OperandIdx::new(0); - function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice(); - function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into(); - let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() }); + function.data.operands128 = Box::new([V128Operand { value: bytes }.encode()]); + 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"TWAS06"); @@ -114,21 +114,20 @@ mod tests { fn const_reference_expressions_round_trip_archive() { let null_type = RefType::new_abstract(true, AbstractHeapType::Extern); let module = Module::from(ModuleInner { - globals: vec![ + globals: Box::new([ Global { ty: GlobalType::new(WasmType::Ref(null_type), false), - init: vec![ConstInstruction::RefNull(null_type)].into_boxed_slice(), + init: Box::new([ConstInstruction::RefNull(null_type)]), }, Global { ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false), - init: vec![ConstInstruction::RefFunc(ModuleFuncIdx::new(7))].into_boxed_slice(), + init: Box::new([ConstInstruction::RefFunc(ModuleFuncIdx::new(7))]), }, Global { ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false), - init: vec![ConstInstruction::I32Const(42), ConstInstruction::RefI31].into_boxed_slice(), + init: Box::new([ConstInstruction::I32Const(42), ConstInstruction::RefI31]), }, - ] - .into_boxed_slice(), + ]), ..ModuleInner::default() }); diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 686433d..9f363d3 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -9,9 +9,27 @@ //! 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 fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 { @@ -56,11 +74,11 @@ pub mod archive { #[derive(Clone, Default, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct Module(Arc); +pub struct Module(Shared); impl From for Module { fn from(inner: ModuleInner) -> Self { - Self(Arc::new(inner)) + Self(Shared::new(inner)) } } @@ -85,7 +103,7 @@ 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]>, + pub funcs: Box<[Shared]>, /// The dense type definitions, indexed by `TypeAddr`. /// @@ -98,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. /// diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs index 12386f1..273c762 100644 --- a/crates/types/src/types.rs +++ b/crates/types/src/types.rs @@ -1,6 +1,6 @@ -use alloc::{boxed::Box, sync::Arc}; +use alloc::boxed::Box; -use crate::{TypeAddr, WasmType}; +use crate::{Shared, TypeAddr, WasmType}; /// The dense type index space of a WebAssembly module. /// @@ -106,7 +106,7 @@ impl CompositeType { #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct FuncType { - data: Arc<[WasmType]>, + data: Shared<[WasmType]>, param_count: u16, } -- cgit v1.3.1 From e73c92160041ed0db5bda81e5c55b0e4c6293a87 Mon Sep 17 00:00:00 2001 From: Henry Date: Fri, 28 Aug 2026 00:57:49 +0200 Subject: chore: simplify ToWasmTypes traits, general cleanup Signed-off-by: Henry --- CHANGELOG.md | 1 + Cargo.lock | 26 +- Cargo.toml | 6 +- crates/cli/src/wast_runner.rs | 77 ++---- crates/tinywasm/src/engine.rs | 8 +- crates/tinywasm/src/func/context.rs | 13 +- crates/tinywasm/src/func/host.rs | 14 +- crates/tinywasm/src/func/mod.rs | 6 +- crates/tinywasm/src/func/resume.rs | 52 ++-- crates/tinywasm/src/func/values.rs | 93 +++---- crates/tinywasm/src/instance.rs | 41 +-- crates/tinywasm/src/interpreter/executor.rs | 132 ++++------ crates/tinywasm/src/interpreter/num_helpers.rs | 12 +- .../tinywasm/src/interpreter/simd/instructions.rs | 288 ++++++++++----------- crates/tinywasm/src/interpreter/simd/macros.rs | 16 +- crates/tinywasm/src/interpreter/simd/mod.rs | 4 +- crates/tinywasm/src/interpreter/simd/utils.rs | 2 - .../tinywasm/src/interpreter/stack/value_stack.rs | 17 +- crates/tinywasm/src/interpreter/values.rs | 158 +++++------ crates/tinywasm/src/lib.rs | 2 +- crates/tinywasm/src/reference/managed.rs | 4 - crates/tinywasm/src/reference/store.rs | 18 +- crates/tinywasm/src/store/const_expr.rs | 28 +- crates/tinywasm/src/store/memory/instance.rs | 37 ++- crates/tinywasm/src/store/memory/vec.rs | 4 +- crates/tinywasm/src/store/mod.rs | 10 +- crates/tinywasm/src/store/state.rs | 17 +- crates/tinywasm/src/store/table.rs | 4 +- crates/tinywasm/tests/host_func_signature_check.rs | 10 +- crates/types/src/instructions.rs | 74 ++---- crates/types/src/operands.rs | 50 ++-- crates/types/src/value.rs | 7 - 32 files changed, 529 insertions(+), 702 deletions(-) (limited to 'Cargo.lock') diff --git a/CHANGELOG.md b/CHANGELOG.md index a786aa0..a24ba43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. `Parser::with_options` was removed. - 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. - `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. - The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. ## [0.10.0] - 2026-07-24 diff --git a/Cargo.lock b/Cargo.lock index 1663c7c..fc5ea63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -215,7 +215,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.4", ] [[package]] @@ -766,7 +766,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.4", ] [[package]] @@ -807,9 +807,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" dependencies = [ "proc-macro2", "quote", @@ -861,7 +861,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.4", ] [[package]] @@ -980,9 +980,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.257.1" +version = "0.258.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d8ad9f0a39050867bda22e6486c316e2e52d20a42154d5bc433934bf738d085" +checksum = "e974fe6821a8cf64575d51ea2194e2c8f77e7b66e9afe7419ce8a97f9ee0d251" dependencies = [ "leb128fmt", "wasmparser", @@ -1000,9 +1000,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.257.1" +version = "0.258.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d92fc335fb6d48f46bda1d8b26b69e28320c15ac3272208333833d6e217e2b4a" +checksum = "d9a61719f93a87b16d325921e251800c4833f8fab50fa21c7de73aed50086313" dependencies = [ "bitflags", "indexmap", @@ -1011,9 +1011,9 @@ dependencies = [ [[package]] name = "wast" -version = "257.0.1" +version = "258.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c416ee8044cf88c5280e3d87c322b009525eb25142cf7428f0a90ea88febc3b" +checksum = "97f7defc7ecca8b19ac7f824598eadd0c53985ee00c74060d65051e9da5b58a1" dependencies = [ "bumpalo", "leb128fmt", @@ -1024,9 +1024,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.257.1" +version = "1.258.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "672e5495f00c5fc6c6b502205bae4708aa4dd13d969754438743afe0a8af0f1d" +checksum = "7555c008cca87f2ac58d9f83ccda7e7b44611093ce28eb28f052e7c78024b9bf" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 12fad7e..ac39ea0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.257", default-features = false } -wast = "257" -wat = "1.257" +wasmparser = { version = "0.258", default-features = false } +wast = "258" +wat = "1.258" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 3f905d4..0cd5c34 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -9,7 +9,8 @@ use anyhow::{Context, Result, anyhow, bail}; use log::{debug, error}; 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; @@ -18,6 +19,15 @@ 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 { definitions: HashMap, @@ -845,10 +855,10 @@ fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result [u8; 16] { let res: Vec = 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(), @@ -920,8 +930,8 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result 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))), @@ -945,63 +955,6 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result 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(arg: wast::core::NanPattern) -> Result -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::*; diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 4fc74d5..b4ad0b8 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -51,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)] diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index aa54e1d..bdc50a3 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -21,12 +21,11 @@ impl FuncContext<'_> { } /// Get the module instance. - pub fn module(&self) -> crate::ModuleInstance { + pub fn module(&self) -> &crate::ModuleInstance { unwrap_or_unreachable!( self.store.get_module_instance(self.module_id), "invalid module instance id in host function context" ) - .clone() } /// Get a memory export. @@ -46,7 +45,7 @@ impl FuncContext<'_> { /// Get the value of a global export. pub fn global_get(&mut self, name: &str) -> Result { - self.module().global_get(self.store, name) + self.module().clone().global_get(self.store, name) } /// Get a global export. @@ -56,7 +55,7 @@ impl FuncContext<'_> { /// 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) + self.module().clone().global_set(self.store, name, value) } /// Charge additional fuel from the currently running resumable invocation. @@ -98,11 +97,11 @@ impl FuncContext<'_> { /// 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.store_id()).ok_or(crate::Trap::InvalidStore)?; + let addr = func.addr(self.store.id()).ok_or(crate::Trap::InvalidStore)?; if self.store.state.funcs.get(addr as usize).is_none() { return Err(crate::Trap::InvalidReference.into()); } - let function = Function { item: crate::StoreItem::new(self.store.store_id(), addr), module_id: self.module_id }; + let function = Function { item: crate::StoreItem::new(self.store.id(), addr), module_id: self.module_id }; self.call_untyped(&function, args, results) } @@ -132,7 +131,7 @@ impl FuncContext<'_> { let value_stack_base = store.value_stack.base(); func.func.call_untyped(store, params, results, call_stack_base, value_stack_base)?; values.drain(..param_count); - R::from_wasm_values_exact(&mut values.drain(..)) + R::from_wasm_values(&mut values.drain(..)) }) } else { let call_stack_base = self.store.call_stack.len(); diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 064f6c7..5e3fefa 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -1,7 +1,7 @@ use alloc::{boxed::Box, vec::Vec}; use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; -use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; +use super::{FromWasmValues, FuncContext, IntoWasmValues}; use crate::shared::StoreShared; use crate::store::FuncValueTypes; use crate::{Function, FunctionInstance, Result, Store, WasmValue}; @@ -33,7 +33,7 @@ impl HostFunction { pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function { let addr = store .add_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) }); - Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 } + Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } } /// Resolves the importing module's types without allocating a function instance. @@ -213,10 +213,10 @@ impl HostFunction { pub fn from(func: F) -> Self where F: Fn(FuncContext<'_>, P) -> Result + HostFunctionCallback + 'static, - P: FromWasmValues + ToWasmTypes + 'static, - R: IntoWasmValues + ToWasmTypes + 'static, + P: FromWasmValues + 'static, + R: IntoWasmValues + 'static, { - let ty = FuncType::new(&P::wasm_types(), &R::wasm_types()); + 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)) })) } @@ -261,7 +261,7 @@ where { 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_exact(&mut values))?; + 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")))?; @@ -279,7 +279,7 @@ where }; let params = { let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; - cold_err!(P::from_wasm_values_exact(&mut values)) + 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?))?; diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 2fbc22f..3f5ef54 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -16,7 +16,7 @@ pub use host::HostFunction; #[doc(hidden)] pub use host::HostFunctionCallback; pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped}; -pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes}; +pub use values::{FromWasmValues, IntoWasmValues, WasmTypes, WasmValueType}; fn write_typed_params(params: &mut [WasmValue], mut values: impl Iterator) -> Result<()> { for param in params { @@ -42,7 +42,7 @@ impl Function { /// Returns this function as a Store-aware WebAssembly function reference. pub fn as_func_ref(&self, store: &Store) -> Result { self.item.validate_store(store)?; - Ok(FuncRef::new(store.store_id(), self.addr())) + Ok(FuncRef::new(store.id(), self.addr())) } #[inline] @@ -219,7 +219,7 @@ impl FunctionTyped { let (params, results) = values.split_at_mut(param_count); self.func.call(store, params, results)?; values.drain(..param_count); - R::from_wasm_values_exact(&mut values.drain(..)) + R::from_wasm_values(&mut values.drain(..)) }) } else { store.enter_execution()?; diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index cc461a7..c0d7f23 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -16,18 +16,25 @@ pub enum ExecProgress { /// Resumable execution for an untyped function call. #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct FuncExecution<'store> { - execution: ExecutionCore<'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, +} + #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -struct ExecutionCore<'store> { +struct ExecutionInner<'store> { store: &'store mut Store, - state: FuncExecutionState, + state: ExecState, } #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -enum FuncExecutionState { +enum ExecState { Running { callframe: CallFrame, root_func_addr: FuncAddr }, Completed(Option), } @@ -38,13 +45,6 @@ enum CallResult { Written, } -/// Resumable execution for a typed function call. -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FuncExecutionTyped<'store, R> { - execution: ExecutionCore<'store>, - result: Option, -} - impl Function { /// Call a function and return a resumable execution handle. /// @@ -60,12 +60,12 @@ impl Function { self.validate_call(store, params, results.len())?; store.enter_execution()?; - let result: Result = (|| { + let result: Result = (|| { let func_instance = store.state.get_func(self.addr()).clone(); match &func_instance.inner { crate::store::FunctionInstanceInner::Host(host_func) => { host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; - Ok(FuncExecutionState::Completed(Some(CallResult::Written))) + Ok(ExecState::Completed(Some(CallResult::Written))) } crate::store::FunctionInstanceInner::Wasm(wasm_func) => { store.call_stack.clear(); @@ -74,25 +74,25 @@ impl Function { let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals); - Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) + Ok(ExecState::Running { callframe, root_func_addr: self.addr() }) } } })(); store.exit_execution(); let state = result?; - Ok(FuncExecution { execution: ExecutionCore { store, state }, results }) + Ok(FuncExecution { execution: ExecutionInner { store, state }, results }) } } -impl ExecutionCore<'_> { +impl ExecutionInner<'_> { fn resume_raw( &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { let (callframe, root_func_addr) = match &mut self.state { - FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), - FuncExecutionState::Completed(result) => { + ExecState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), + ExecState::Completed(result) => { return result .take() .map(ExecProgress::Completed) @@ -109,7 +109,7 @@ impl ExecutionCore<'_> { Err(error) => { self.store.call_stack.clear(); self.store.value_stack.clear(); - self.state = FuncExecutionState::Completed(None); + self.state = ExecState::Completed(None); return Err(error); } }; @@ -118,11 +118,11 @@ impl ExecutionCore<'_> { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; - self.state = FuncExecutionState::Completed(None); + self.state = ExecState::Completed(None); Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty })) } crate::interpreter::ExecState::Suspended(callframe) => { - let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { + let ExecState::Running { callframe: current, .. } = &mut self.state else { unreachable!("invalid function execution state") }; *current = callframe; @@ -206,21 +206,21 @@ impl FunctionTyped { let func = store.state.get_func(self.func.addr()).clone(); if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { let result = self.call(store, params)?; - let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) }; + let execution = ExecutionInner { store, state: ExecState::Completed(None) }; return Ok(FuncExecutionTyped { execution, result: Some(result) }); } store.enter_execution()?; - let result: Result = (|| { + let result: Result = (|| { store.call_stack.clear(); store.value_stack.clear(); match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { - Some(callframe) => Ok(FuncExecutionState::Running { callframe, root_func_addr: self.func.addr() }), - None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), + Some(callframe) => Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() }), + None => Ok(ExecState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), } })(); store.exit_execution(); - let execution = ExecutionCore { store, state: result? }; + let execution = ExecutionInner { store, state: result? }; Ok(FuncExecutionTyped { execution, result: None }) } } diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs index 19d0673..11d3b17 100644 --- a/crates/tinywasm/src/func/values.rs +++ b/crates/tinywasm/src/func/values.rs @@ -1,70 +1,53 @@ use crate::{Error, Result}; -use alloc::borrow::Cow; 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 { +pub trait IntoWasmValues: WasmTypes { /// Return the flattened WebAssembly values. fn into_wasm_values(self) -> impl Iterator; } /// Convert WebAssembly values into a Rust value or tuple. -pub trait FromWasmValues: Sized { - /// Read this value from a flattened WebAssembly value iterator. +pub trait FromWasmValues: WasmTypes + Sized { + /// Read this value and reject unconsumed WebAssembly values. fn from_wasm_values(values: &mut impl Iterator) -> Result; - - /// Read one value and reject unconsumed iterator items. - fn from_wasm_values_exact(values: &mut impl Iterator) -> Result { - let result = Self::from_wasm_values(values)?; - if values.next().is_some() { - return Err(Error::other("typed conversion did not consume all WebAssembly values")); - } - Ok(result) - } } -/// 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; +fn next_value>(values: &mut impl Iterator) -> Result { + 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 next_value>(values: &mut impl Iterator) -> Result { - let value = values.next().ok_or_else(|| { - core::hint::cold_path(); - Error::other("not enough WebAssembly values") - })?; - T::try_from(value).map_err(|_| { - core::hint::cold_path(); - Error::other("WebAssembly value does not match the expected type") - }) +fn finish_values(result: T, values: &mut impl Iterator) -> Result { + 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 ToWasmType for $T { + impl WasmValueType for $T { const WASM_TYPE: WasmType = $val_ty; } - impl ToWasmTypes for $T { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$val_ty]); + impl WasmTypes for $T { + const WASM_TYPES: &'static [WasmType] = &[$val_ty]; } impl IntoWasmValues for $T { @@ -77,7 +60,8 @@ macro_rules! impl_scalar_wasm_traits { impl FromWasmValues for $T { #[inline] fn from_wasm_values(values: &mut impl Iterator) -> Result { - next_value(values) + let result = next_value(values)?; + finish_values(result, values) } } )+ @@ -90,16 +74,16 @@ macro_rules! impl_tuple_traits { }; (@next $head:ident) => {}; ($($T:ident),+) => { - impl<$($T),+> ToWasmTypes for ($($T,)+) + impl<$($T),+> WasmTypes for ($($T,)+) where - $($T: ToWasmType,)+ + $($T: WasmValueType,)+ { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]); + const WASM_TYPES: &'static [WasmType] = &[$($T::WASM_TYPE,)+]; } impl<$($T),+> IntoWasmValues for ($($T,)+) where - $($T: Into,)+ + $($T: Into + WasmValueType,)+ { #[allow(non_snake_case)] #[inline] @@ -111,11 +95,12 @@ macro_rules! impl_tuple_traits { impl<$($T),+> FromWasmValues for ($($T,)+) where - $($T: TryFrom,)+ + $($T: TryFrom + WasmValueType,)+ { #[inline] fn from_wasm_values(values: &mut impl Iterator) -> Result { - Ok(($(next_value::<$T>(values)?,)+)) + let result = ($(next_value::<$T>(values)?,)+); + finish_values(result, values) } } @@ -151,8 +136,8 @@ impl_scalar_wasm_traits!( ); impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); -impl ToWasmTypes for () { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); +impl WasmTypes for () { + const WASM_TYPES: &'static [WasmType] = &[]; } impl IntoWasmValues for () { @@ -164,7 +149,7 @@ impl IntoWasmValues for () { impl FromWasmValues for () { #[inline] - fn from_wasm_values(_values: &mut impl Iterator) -> Result { - Ok(()) + fn from_wasm_values(values: &mut impl Iterator) -> Result { + finish_values((), values) } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index ea97961..08682e3 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -2,7 +2,7 @@ use alloc::{boxed::Box, format}; 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; @@ -125,7 +125,7 @@ impl ModuleInstance { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { - if self.0.store_id != store.store_id() { + if self.0.store_id != store.id() { return cold!(Err(Trap::InvalidStore.into())); } Ok(()) @@ -195,7 +195,7 @@ impl ModuleInstance { store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?; let instance = ModuleInstanceInner { - store_id: store.store_id(), + store_id: store.id(), id, type_addrs, func_addrs: addrs.funcs.into_boxed_slice(), @@ -362,7 +362,6 @@ impl ModuleInstance { /// For typed access, see [`Self::func`]. pub fn func_untyped(&self, store: &Store, name: &str) -> Result { self.validate_store(store)?; - let ExternVal::Func(func_addr) = self.require_export(name)? else { return cold!(Err(Error::Other(format!("Export is not a function: {name}")))); }; @@ -409,19 +408,13 @@ impl ModuleInstance { /// For untyped access, see [`Self::func_untyped`] and [`Self::extern_item`]. /// /// Tuples are supported up to arity 20. Use [`Self::func_untyped`] for larger signatures. - pub fn func( - &self, - store: &Store, - name: &str, - ) -> Result> { + pub fn func(&self, store: &Store, name: &str) -> Result> { self.validate_store(store)?; - let ExternVal::Func(func_addr) = self.require_export(name)? else { 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::(store, &func, name)?; Ok(FunctionTyped { func, marker: core::marker::PhantomData }) } @@ -429,7 +422,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( + pub fn func_typed_by_index( &self, store: &Store, func_index: FuncAddr, @@ -440,21 +433,17 @@ impl ModuleInstance { } #[inline] - fn validate_typed_func( - store: &Store, - func: &Function, - func_name: &str, - ) -> Result<()> { - let params = P::wasm_types(); - let results = R::wasm_types(); + fn validate_typed_func(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(¶ms, &results), + FuncType::new(params, results), ty ))); @@ -469,9 +458,7 @@ impl ModuleInstance { pub fn memory(&self, name: &str) -> Result { match self.require_export(name)? { ExternVal::Memory(mem_addr) => Ok(Memory(StoreItem::new(self.0.store_id, mem_addr))), - _ => { - cold!(Err(Error::Other(format!("Export is not a memory: {name}")))) - } + _ => cold!(Err(Error::Other(format!("Export is not a memory: {name}")))), } } @@ -491,7 +478,7 @@ impl ModuleInstance { pub fn table(&self, name: &str) -> Result
{ 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}")))), } } @@ -511,7 +498,7 @@ impl ModuleInstance { pub fn tag(&self, name: &str) -> Result { match self.require_export(name)? { ExternVal::Tag(tag_addr) => Ok(Tag(StoreItem::new(self.0.store_id, tag_addr))), - _ => Err(Error::Other(format!("Export is not a tag: {name}"))), + _ => cold!(Err(Error::Other(format!("Export is not a tag: {name}")))), } } @@ -531,7 +518,7 @@ impl ModuleInstance { pub fn global(&self, name: &str) -> Result { 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}")))), } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 4011e96..fa3f3f1 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -178,16 +178,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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) => { i32::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(*c))?; }, - AddConst64(idx) => { let constant = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(constant))?; }, - IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)); }, - IncLocal64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, + AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(*c)); }, + AddConst64(idx) => { let rhs = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(rhs)); }, + IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |value| value.wrapping_add(arg.value)); }, + IncLocal64(packed) => { let rhs = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |value| value.wrapping_add(rhs)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), MulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, i32::wrapping_mul, i32::wrapping_add), MulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, i64::wrapping_mul, i64::wrapping_add), - FMulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - FMulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), + FMulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), + FMulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, #[inline(always)] |a, b| a * b, #[inline(always)] |a, b| a + b), BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, @@ -808,13 +808,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_binop_local_const_jump(&mut self, packed: PackedOp128) -> Option { let operand = packed.index.resolve(&self.func.data); - let value = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| packed.op.exec(value as u32, operand.value() as u32) as i32, - ); + 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) } @@ -824,13 +820,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, ) -> Option { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| packed.op.0.exec(value as u32, operand.value() as u32) as i32, - ); + 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.1.cmp(lhs, rhs).then_some(operand.target() as usize) } @@ -841,10 +833,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { packed: PackedOp128, ) -> Result, Trap> { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::stack_pop(&mut self.store.value_stack); - let value = packed.op.exec(lhs as u32, operand.value() as u32) as i32; + 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); - i32::stack_push(&mut self.store.value_stack, value)?; Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) } @@ -852,25 +844,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_binop_global_const_jump(&mut self, packed: PackedOp128) -> Option { 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, - #[inline(always)] - |value| packed.op.exec(value as u32, operand.value() as u32) as i32, - ); + 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) -> Option { let operand = index.resolve(&self.func.data); - let value = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + 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) } @@ -880,9 +865,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { index: Operand128Idx, ) -> Result, Trap> { let operand = index.resolve(&self.func.data); - let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(operand.value()); + 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); - i32::stack_push(&mut self.store.value_stack, value)?; Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) } @@ -890,25 +874,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_inc_global_jump(&mut self, index: Operand128Idx) -> Option { 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, - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + 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) -> Option { let operand = packed.index.resolve(&self.func.data); - let lhs = i32::local_update( - &mut self.store.value_stack, - &self.cf, - operand.local(), - #[inline(always)] - |value| value.wrapping_add(operand.value()), - ); + 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) } @@ -1118,8 +1094,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Result<(), Trap> { let addr = self.module.resolve_global_addr(global); let rhs = T::global_get(&self.store.state.globals, addr); - let lhs = T::stack_pop(&mut self.store.value_stack); - T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs)); + Ok(()) } #[inline(always)] @@ -1141,7 +1117,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { destination: LocalAddr, op: impl BinOpExt, ) -> Result<(), Trap> { - let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs))?; + 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(()) } @@ -1156,13 +1132,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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, - #[inline(always)] - |value| add(product, value), - ); + T::local_update(&mut self.store.value_stack, &self.cf, accumulator, |value| add(product, value)); } fn exec_branch_table(&mut self, index: Operand128Idx) -> usize { @@ -1273,7 +1243,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } if with_ref { - self.store.value_stack.push(exception)?; + ValueRef::stack_push(&mut self.store.value_stack, exception)?; } return Ok(Some(landing_pad as usize)); } @@ -1649,7 +1619,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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::(is_null) + i32::stack_push(&mut self.store.value_stack, is_null) } fn exec_ref_as_non_null(&mut self) -> Result<(), Trap> { @@ -1672,7 +1642,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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)); - self.store.value_stack.push(i32::from(matches)) + i32::stack_push(&mut self.store.value_stack, i32::from(matches)) } fn exec_ref_cast(&self, ty: RefType) -> Result<(), Trap> { @@ -1692,13 +1662,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } else { value.i31_u().expect("validated i31.get operand") as i32 }; - self.store.value_stack.push(value) + i32::stack_push(&mut self.store.value_stack, value) } fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> 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)?; - self.store.value_stack.push(reference) + ValueRef::stack_push(&mut self.store.value_stack, reference) } fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { @@ -1822,7 +1792,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if self.store.state.get_type(type_addr).as_array().is_none() { return Err(Trap::Other("GC reference is not an array")); } - self.store.value_stack.push(object.values.len() as i32) + i32::stack_push(&mut self.store.value_stack, object.values.len() as i32) } fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> { @@ -1945,8 +1915,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 => self.store.value_stack.push::(mem.page_count as i64), - false => self.store.value_stack.push::(mem.page_count as i32), + 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), } } @@ -2090,9 +2060,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.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))?; + 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(()) } @@ -2106,7 +2078,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; - self.store.value_stack.push(cast(value)) + TARGET::stack_push(&mut self.store.value_stack, cast(value)) } #[inline(always)] @@ -2164,7 +2136,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let value = *self.store.state.get_table(table_addr).get(idx)?; - self.store.value_stack.push(value) + ValueRef::stack_push(&mut self.store.value_stack, value) } fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { @@ -2178,8 +2150,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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), + 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), } } @@ -2210,10 +2182,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let sz = table.size(); let grew = table.grow(n, val, limiter)?; match (arch, grew) { - (MemoryArch::I32, true) => self.store.value_stack.push(sz as i32), - (MemoryArch::I32, false) => self.store.value_stack.push(-1_i32), - (MemoryArch::I64, true) => self.store.value_stack.push(sz as i64), - (MemoryArch::I64, false) => self.store.value_stack.push(-1_i64), + (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), } } diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index d35b217..591326f 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -35,7 +35,7 @@ macro_rules! checked_conv_float { core::hint::cold_path(); 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())?; }}; } @@ -120,18 +120,16 @@ macro_rules! impl_checked_wrapping_rem { impl TinywasmIntExt for $t { fn tw_checked_wrapping_rem(self, rhs: Self) -> Result { 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 { 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 9306d8f..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) } )* @@ -197,10 +197,10 @@ macro_rules! lane_write { } 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]; @@ -213,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 8a3ca84..62ea4ab 100644 --- a/crates/tinywasm/src/interpreter/simd/mod.rs +++ b/crates/tinywasm/src/interpreter/simd/mod.rs @@ -34,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/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/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 3748ef9..92b4d93 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -221,17 +221,12 @@ impl ValueStack { } } - #[inline(always)] - pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { - T::stack_push(self, value) - } - #[inline(always)] pub(crate) fn pop_memory_operand(&mut self, arch: MemoryArch) -> Result { match arch { - MemoryArch::I32 => Ok(self.stack_32.pop() as usize), + MemoryArch::I32 => Ok(u32::stack_pop(self) as usize), MemoryArch::I64 => { - let value = self.stack_64.pop(); + let value = u64::stack_pop(self); #[cfg(target_pointer_width = "64")] return Ok(value as usize); #[cfg(not(target_pointer_width = "64"))] @@ -276,10 +271,10 @@ impl ValueStack { pub(crate) fn push_dyn(&mut self, value: RuntimeValue) -> Result<(), Trap> { match value { - RuntimeValue::Value32(v) => self.stack_32.push(v), - RuntimeValue::Value64(v) => self.stack_64.push(v), - RuntimeValue::Value128(v) => self.stack_128.push(v), - RuntimeValue::ValueRef(v) => self.stack_32.push(v.raw()), + 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), } } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 83b520b..38b7a04 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -105,21 +105,12 @@ impl RuntimeValue { } } -mod sealed { - #[expect(unreachable_pub)] - pub trait Sealed {} -} - /// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes. -pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { +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_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Result { - let value = f(Self::stack_pop(stack)); - Self::stack_push(stack, value)?; - Ok(value) - } + 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>; @@ -128,11 +119,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { 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 { - let value = f(Self::global_get(globals, addr)); - Self::global_set(globals, addr, value); - value - } + fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self; } macro_rules! impl_internalvalue { @@ -144,8 +131,6 @@ macro_rules! impl_internalvalue { )* ) => { $( - impl sealed::Sealed for $outer {} - impl InternalValue for $outer { #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { @@ -200,6 +185,15 @@ macro_rules! impl_internalvalue { 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; @@ -219,6 +213,16 @@ macro_rules! impl_internalvalue { $from_stack } + #[inline(always)] + 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; @@ -249,81 +253,41 @@ pub(crate) trait BinOpExt: Copy { fn exec(self, lhs: T, rhs: T) -> T; } -impl BinOpExt for BinOp { - #[inline(always)] - fn exec(self, lhs: Value32, rhs: Value32) -> Value32 { - match self { - 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(), - } - } -} - -impl BinOpExt for BinOp { - #[inline(always)] - fn exec(self, lhs: Value64, rhs: Value64) -> Value64 { - match self { - 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(), - } - } -} - -impl BinOpExt 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), - } - } -} - pub(crate) trait CmpOpExt: Copy { fn cmp(self, lhs: T, rhs: T) -> bool; } -macro_rules! impl_cmp_value { - ($ty:ty, $unsigned:ty) => { - impl CmpOpExt<$ty> for CmpOp { +macro_rules! impl_value_ops { + ($unsigned:ty, $signed:ty, $float:ty) => { + impl BinOpExt<$unsigned> for BinOp { + #[inline(always)] + fn exec(self, lhs: $unsigned, rhs: $unsigned) -> $unsigned { + match self { + 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(), + } + } + } + + impl CmpOpExt<$signed> for CmpOp { #[inline(always)] - fn cmp(self, lhs: $ty, rhs: $ty) -> bool { + fn cmp(self, lhs: $signed, rhs: $signed) -> bool { match self { CmpOp::Eq => lhs == rhs, CmpOp::Ne => lhs != rhs, @@ -341,8 +305,22 @@ macro_rules! impl_cmp_value { }; } -impl_cmp_value!(i32, u32); -impl_cmp_value!(i64, u64); +impl_value_ops!(Value32, i32, f32); +impl_value_ops!(Value64, i64, f64); + +impl BinOpExt 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 { diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index d89bfa1..e2ee684 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -114,7 +114,7 @@ mod error; pub use error::*; pub use func::{ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, - HostFunction, HostFunctionCallback, IntoWasmValues, ToWasmType, ToWasmTypes, + HostFunction, HostFunctionCallback, IntoWasmValues, WasmTypes, WasmValueType, }; pub use imports::*; pub use instance::{ExternItem, ModuleInstance}; diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs index 79bd0b9..05edf04 100644 --- a/crates/tinywasm/src/reference/managed.rs +++ b/crates/tinywasm/src/reference/managed.rs @@ -14,10 +14,6 @@ impl StoreId { assert_ne!(id, u32::MAX, "Store identity space exhausted"); StoreId(id) } - - pub(crate) const fn get(self) -> u32 { - self.0 - } } #[cfg(feature = "debug")] diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs index d0eba6b..07d8eb2 100644 --- a/crates/tinywasm/src/reference/store.rs +++ b/crates/tinywasm/src/reference/store.rs @@ -30,7 +30,7 @@ impl StoreItem { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { - if self.store_id != store.store_id() { + if self.store_id != store.id() { return Err(Trap::InvalidStore); } Ok(()) @@ -243,7 +243,7 @@ fn gc_field_type(store: &Store, field: FieldType) -> GcFieldType { WasmType::Ref(ty) => GcValueType::Ref(GcRefType { nullable: ty.is_nullable(), heap_type: match ty.type_index() { - Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.store_id(), addr))), + Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.id(), addr))), None => GcHeapType::Abstract(ty.abstract_heap_type().expect("abstract reference type")), }, }), @@ -356,7 +356,7 @@ impl Memory { 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.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Creates a cursor positioned at the start of this memory. @@ -574,7 +574,7 @@ impl StructRef { /// Returns this struct's canonical type. pub fn ty(&self, store: &Store) -> Result { let (_, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; - Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + Ok(GcType(StoreItem::new(store.id(), type_addr))) } /// Reads one field. @@ -633,7 +633,7 @@ impl ArrayRef { /// Returns this array's canonical type. pub fn ty(&self, store: &Store) -> Result { let (_, type_addr) = rooted_object(store, self, ReferentKind::Array)?; - Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + Ok(GcType(StoreItem::new(store.id(), type_addr))) } /// Returns the number of array elements. @@ -703,7 +703,7 @@ impl ExnRef { /// Returns the exception's tag. pub fn tag(&self, store: &Store) -> Result { let (_, tag_addr) = exception_object(store, self)?; - Ok(Tag(StoreItem::new(store.store_id(), tag_addr))) + Ok(Tag(StoreItem::new(store.id(), tag_addr))) } /// Reads one exception payload field. @@ -769,7 +769,7 @@ impl Table { 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.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } #[inline] @@ -861,7 +861,7 @@ impl Global { } let value = value.to_runtime(store)?; let addr = store.state.globals.push(ty, value); - Ok(Self(StoreItem::new(store.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Get the type of the global. @@ -904,7 +904,7 @@ impl Tag { 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.store_id(), addr))) + Ok(Self(StoreItem::new(store.id(), addr))) } /// Get the payload type of the tag. diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index cd01648..d896457 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -2,7 +2,7 @@ use alloc::{format, vec::Vec}; use tinywasm_types::*; use super::{State, default_value}; -use crate::interpreter::{RuntimeValue, Value128, ValueRef}; +use crate::interpreter::{InternalValue, RuntimeValue, Value32, Value64, Value128, ValueRef}; use crate::{Error, Result, Trap}; fn resolve(items: &[T], index: u32, kind: &str) -> Result { @@ -59,17 +59,20 @@ pub(super) fn eval_const( F64Const(value) => return Ok(RuntimeValue::Value64(value.to_bits())), V128Const(value) => return Ok(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - return Ok(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value32(Value32::global_get(&state.globals, addr))); } GlobalGet64(index) => { - return Ok(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value64(Value64::global_get(&state.globals, addr))); } GlobalGet128(index) => { - return Ok(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + return Ok(RuntimeValue::Value128(Value128::global_get(&state.globals, addr))); } GlobalGetRef(index) => { - let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - return Ok(RuntimeValue::ValueRef(ValueRef::from_raw(value))); + 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) => { @@ -89,17 +92,20 @@ pub(super) fn eval_const( F64Const(value) => stack.push(RuntimeValue::Value64(value.to_bits())), V128Const(value) => stack.push(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - stack.push(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value32(Value32::global_get(&state.globals, addr))); } GlobalGet64(index) => { - stack.push(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value64(Value64::global_get(&state.globals, addr))); } GlobalGet128(index) => { - stack.push(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + let addr = resolve(global_addrs, *index, "global")?; + stack.push(RuntimeValue::Value128(Value128::global_get(&state.globals, addr))); } GlobalGetRef(index) => { - let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - stack.push(RuntimeValue::ValueRef(ValueRef::from_raw(value))); + 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) => { diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index d7edd15..3a478fb 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -31,26 +31,21 @@ impl MemoryInstance { kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } + #[cfg(target_pointer_width = "64")] #[inline(always)] pub(crate) fn effective_addr(&self, base: usize, offset: u64) -> Result { - #[cfg(target_pointer_width = "64")] - { - if !self.is_64bit() { - debug_assert!(u32::try_from(offset).is_ok(), "validated memory32 offsets fit in u32"); - return Ok(base + offset as usize); - } - match base.checked_add(offset as usize) { - Some(addr) => Ok(addr), - None => cold!(Err(memory_oob(base, N, self.inner.len()))), - } + match base.checked_add(offset as usize) { + Some(addr) => Ok(addr), + None => cold!(Err(memory_oob(base, N, self.inner.len()))), } + } - #[cfg(not(target_pointer_width = "64"))] - { - 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()))), - } + #[cfg(not(target_pointer_width = "64"))] + #[inline(always)] + pub(crate) fn effective_addr(&self, base: usize, offset: u64) -> Result { + 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()))), } } @@ -84,18 +79,18 @@ impl MemoryInstance { pub(crate) fn copy_from_memory( &mut self, dst: usize, - src_memory: &MemoryInstance, + src_mem: &MemoryInstance, src: usize, len: usize, ) -> Result<(), Trap> { - src_memory.inner.checked_range(src, len).ok_or_else(|| cold!(memory_oob(src, len, src_memory.inner.len())))?; - self.inner.checked_range(dst, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len())))?; - self.inner.copy_from(dst, &src_memory.inner, src, len); + cold_err!(src_mem.inner.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_mem.inner.len())))?; + cold_err!(self.inner.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))?; + self.inner.copy_from(dst, &src_mem.inner, src, len); Ok(()) } 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!(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( diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index 89bce83..ef2d4df 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -16,7 +16,7 @@ impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. pub(crate) fn try_new(len: usize) -> Result { let mut data = Vec::new(); - cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; + cold_err!(data.try_reserve(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); Ok(Self { data }) } @@ -37,7 +37,7 @@ impl VecMemory { #[inline(always)] 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_exact(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; + cold_err!(self.data.try_reserve(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; self.data.resize(new_len, 0); Ok(()) } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index d4c8b15..862cb4f 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -126,7 +126,6 @@ pub trait ResourceLimiter: Send + Sync { pub struct Store { id: StoreId, pub(crate) module_instances: Vec, - pub(crate) engine: Engine, pub(crate) execution_fuel: u32, pub(crate) execution_active: bool, @@ -242,12 +241,7 @@ impl Store { } } - /// Get the store's ID (unique per process) - pub fn id(&self) -> u32 { - self.id.get() - } - - pub(crate) const fn store_id(&self) -> StoreId { + pub(crate) const fn id(&self) -> StoreId { self.id } @@ -496,7 +490,7 @@ impl Store { stack_base: StackBase, ) -> Result { let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?; - let result = cold_err!(R::from_wasm_values_exact(&mut values)); + let result = cold_err!(R::from_wasm_values(&mut values)); self.value_stack.truncate_to_base(stack_base); result } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 49efcdc..cad0208 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -2,6 +2,7 @@ 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 /// @@ -363,10 +364,10 @@ impl State { pub(crate) fn global_value(&self, addr: GlobalAddr) -> RuntimeValue { let ty = self.globals.ty(addr).ty; match ty { - WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(self.globals.get_32(addr)), - WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(self.globals.get_64(addr)), - WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), - WasmType::V128 => RuntimeValue::Value128(self.globals.get_128(addr)), + 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)), } } @@ -378,10 +379,10 @@ impl State { return Err(Error::other("global is immutable")); } match value { - RuntimeValue::Value32(value) => self.globals.set_32(addr, value), - RuntimeValue::Value64(value) => self.globals.set_64(addr, value), - RuntimeValue::ValueRef(value) => self.globals.set_32(addr, value.raw()), - RuntimeValue::Value128(value) => self.globals.set_128(addr, 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(()) } diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index cb8ded0..71d0184 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -106,8 +106,8 @@ impl TableInstance { return Ok(false); } - if cold_err!(self.elements.try_reserve_exact(n)).is_err() { - return Ok(false); + if self.elements.try_reserve_exact(n).is_err() { + return cold!(Ok(false)); } self.elements.resize(len, init); Ok(true) diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 484b3cc..5eee068 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,11 +1,11 @@ use std::fmt::Write; use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; -use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, ToWasmTypes}; +use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, WasmTypes}; struct TooFewParams; -impl ToWasmTypes for TooFewParams { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +impl WasmTypes for TooFewParams { + const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32]; } impl IntoWasmValues for TooFewParams { @@ -16,8 +16,8 @@ impl IntoWasmValues for TooFewParams { struct TooManyParams; -impl ToWasmTypes for TooManyParams { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +impl WasmTypes for TooManyParams { + const WASM_TYPES: &'static [WasmType] = &[WasmType::I32, WasmType::I32]; } impl IntoWasmValues for TooManyParams { diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 9330af6..b92a0f4 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::operands::read_field; +use crate::operands::{read_field, write_field}; use crate::{ DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType, }; @@ -188,8 +188,8 @@ impl Operand128 { #[inline] pub fn new(offset: u64, memory: MemAddr) -> Self { let mut operand = Self::default(); - operand.write_u64::<0>(offset); - operand.write_u32::<8>(memory); + write_field!(operand, u64, 0, offset); + write_field!(operand, u32, 8, memory); operand } @@ -211,8 +211,8 @@ impl Operand64 { #[inline] pub fn new(offset: u32, memory: u16) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(offset); - operand.write_u16::<4>(memory); + write_field!(operand, u32, 0, offset); + write_field!(operand, u16, 4, memory); operand } @@ -233,9 +233,9 @@ impl Operand128 { #[inline] pub fn new(target: u32, start: u32, len: u32) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(start); - operand.write_u32::<8>(len); + write_field!(operand, u32, 0, target); + write_field!(operand, u32, 4, start); + write_field!(operand, u32, 8, len); operand } #[inline(always)] @@ -252,9 +252,9 @@ impl Operand128 { #[inline] pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(memory); - operand.write_u8::<4>(byte); - operand.write_u32::<5>(value as u32); + write_field!(operand, u32, 0, memory); + write_field!(operand, u8, 4, byte); + write_field!(operand, i32, 5, value); operand } #[inline(always)] @@ -275,10 +275,10 @@ impl Operand128 { #[inline] pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u16::<8>(local); - operand.write_u8::<10>(u8::from(on_zero)); + 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)] @@ -299,10 +299,10 @@ impl Operand128 { #[inline] pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u32::<8>(global); - operand.write_u8::<12>(u8::from(on_zero)); + 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)] @@ -323,10 +323,10 @@ impl Operand128 { #[inline] pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self { let mut operand = Self::default(); - operand.write_u32::<0>(target); - operand.write_u32::<4>(value as u32); - operand.write_u16::<8>(local); - operand.write_u16::<10>(right); + 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)] @@ -771,8 +771,6 @@ const _: () = assert!(core::mem::size_of::() == 8); #[cfg(test)] mod tests { - use alloc::vec; - use super::*; #[test] @@ -795,30 +793,4 @@ mod tests { assert_eq!(value.local(), u16::MAX); assert!(value.on_zero()); } - - #[test] - fn v128_operand_views_round_trip_max_bytes() { - let value = Operand128Idx::<[u8; 16]>::new(0); - let local = Operand64Idx::<(u16, Operand128Idx<[u8; 16]>)>::new(0); - let global = Operand64Idx::<(u32, Operand128Idx<[u8; 16]>)>::new(1); - let set = Operand64Idx::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(2); - let data = super::super::WasmFunctionData { - operands128: vec![Operand128::<[u8; 16]>::new([u8::MAX; 16]).cast()].into_boxed_slice(), - operands64: vec![ - Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, value).cast(), - Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(u32::MAX, value).cast(), - Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, u16::MAX, value).cast(), - ] - .into_boxed_slice(), - ..Default::default() - }; - - assert_eq!(value.resolve(&data).value(), [u8::MAX; 16]); - assert_eq!((local.resolve(&data).a(), local.resolve(&data).b()), (u16::MAX, value)); - assert_eq!((global.resolve(&data).a(), global.resolve(&data).b()), (u32::MAX, value)); - assert_eq!( - (set.resolve(&data).a(), set.resolve(&data).b(), set.resolve(&data).c()), - (u16::MAX, u16::MAX, value) - ); - } } diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index 1bc4a28..edbab26 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -129,20 +129,14 @@ macro_rules! define_operand { #[cfg(feature = "archive")] impl serde::Serialize for $name { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { + fn serialize(&self, serializer: S) -> Result { self.bytes.serialize(serializer) } } #[cfg(feature = "archive")] impl<'de, T> serde::Deserialize<'de> for $name { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { + fn deserialize>(deserializer: D) -> Result { Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData }) } } @@ -153,19 +147,18 @@ define_operand!(Operand64, 8); define_operand!(Operand128, 16); macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ unwrap_or_unreachable!($value, "entered unreachable code") }}; - ($value:expr, $message:literal) => {{ + ($value:expr) => {{ match $value { Some(value) => value, - None => operand_unreachable($message), + None => { core::hint::cold_path(); unreachable!() }, + } + }}; + ($value:expr, $($arg:tt)+) => {{ + match $value { + Some(value) => value, + None => { core::hint::cold_path(); unreachable!($($arg)+) }, } }}; -} - -#[cold] -#[inline(never)] -pub(crate) fn operand_unreachable(message: &'static str) -> ! { - unreachable!("{message}") } impl Operand64Idx { @@ -207,17 +200,19 @@ macro_rules! read_field { ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }}; ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }}; } -pub(crate) use read_field; macro_rules! read_bytes { ($self:ident, $offset:expr, $len:literal) => {{ match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) { Ok(bytes) => bytes, - Err(_) => $crate::operands::operand_unreachable("invalid operand field"), + Err(_) => { + core::hint::cold_path(); + unreachable!("invalid operand field read") + } } }}; } -pub(crate) use read_bytes; + 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) }}; @@ -228,6 +223,8 @@ macro_rules! write_field { ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }}; } +pub(crate) use {read_bytes, read_field, write_field}; + impl Operand64 { /// Returns the jump target stored at the start of a retargetable operand. #[inline(always)] @@ -238,7 +235,7 @@ impl Operand64 { /// Replaces the jump target stored at the start of a retargetable operand. #[inline] pub fn with_target(mut self, target: u32) -> Self { - self.write_u32::<0>(target); + write_field!(self, u32, 0, target); self } } @@ -253,7 +250,7 @@ impl Operand128 { /// Replaces the jump target stored at the start of a retargetable operand. #[inline] pub fn with_target(mut self, target: u32) -> Self { - self.write_u32::<0>(target); + write_field!(self, u32, 0, target); self } } @@ -267,6 +264,7 @@ macro_rules! packed_layout { write_field!(operand, $field, 0, value); operand } + #[inline(always)] pub fn value(&self) -> field_ty!($field) { read_field!(self, $field, 0) @@ -282,10 +280,12 @@ macro_rules! packed_layout { 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)) @@ -302,14 +302,17 @@ macro_rules! packed_layout { 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)) @@ -329,7 +332,6 @@ 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); @@ -341,11 +343,13 @@ impl Operand128<[u8; 16]> { 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::>() == 4); assert!(core::mem::size_of::() == 8); diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 847e5e1..3a396a2 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -21,13 +21,6 @@ pub enum WasmType { Ref(RefType), } -impl WasmType { - #[inline] - pub const fn is_simd(self) -> bool { - matches!(self, Self::V128) - } -} - impl From for WasmType { fn from(value: StorageType) -> Self { match value { -- cgit v1.3.1 From bb17468c990ba2ef819e5d3349539bb7a4aaedbd Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 29 Aug 2026 14:34:58 +0200 Subject: chore: improve optimizer and simplify function execution - add stack-constant and fused local-update rewrites - split host and Wasm function storage and execution paths - add the default full feature - recursively discover WAST test files Signed-off-by: Henry --- Cargo.lock | 8 +- Cargo.toml | 2 +- README.md | 1 + crates/cli/Cargo.toml | 5 +- crates/cli/src/wast_runner.rs | 23 +- crates/parser/src/optimize/rewrite.rs | 86 +++++- crates/tinywasm/Cargo.toml | 27 +- crates/tinywasm/src/func/context.rs | 40 +-- crates/tinywasm/src/func/host.rs | 31 +- crates/tinywasm/src/func/mod.rs | 172 +++++------ crates/tinywasm/src/func/resume.rs | 65 +++-- crates/tinywasm/src/imports.rs | 3 +- crates/tinywasm/src/instance.rs | 16 +- crates/tinywasm/src/interpreter/executor.rs | 313 +++++++++++---------- .../tinywasm/src/interpreter/stack/call_stack.rs | 22 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 47 +--- crates/tinywasm/src/interpreter/values.rs | 128 ++++++--- crates/tinywasm/src/lib.rs | 1 + crates/tinywasm/src/macros.rs | 15 - crates/tinywasm/src/store/function.rs | 88 ++++-- crates/tinywasm/src/store/global.rs | 41 ++- crates/tinywasm/src/store/memory/instance.rs | 28 +- crates/tinywasm/src/store/memory/mod.rs | 4 - crates/tinywasm/src/store/memory/vec.rs | 16 +- crates/tinywasm/src/store/mod.rs | 36 ++- crates/tinywasm/src/store/state.rs | 59 ++-- crates/tinywasm/tests/test-wast.rs | 8 +- crates/types/Cargo.toml | 2 +- crates/types/src/instructions.rs | 14 +- crates/types/src/operands.rs | 19 +- examples/rust/Cargo.toml | 8 +- 31 files changed, 726 insertions(+), 602 deletions(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index fc5ea63..edc0bbf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -445,9 +445,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" dependencies = [ "equivalent", "hashbrown", @@ -556,9 +556,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" diff --git a/Cargo.toml b/Cargo.toml index ac39ea0..1d709e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ tinywasm-types = { path = "crates/types", version = "0.11.0-pre.0", default-feat 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" } diff --git a/README.md b/README.md index 8b400de..20c432a 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin ## Cargo Features +- **`full`:** Enables `archive`, `parallel-parser`, `parser`, 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. diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 069a4e2..861d349 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -32,15 +32,12 @@ 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", - "validate", ] } wasm-testsuite = { workspace = true, optional = true } wast = { workspace = true, optional = true } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 0cd5c34..02add87 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -669,17 +669,20 @@ struct TestCase { fn expand_paths(paths: &[PathBuf]) -> Result> { 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(); @@ -973,6 +976,18 @@ mod tests { 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(); diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs index d0dfb66..4a64f77 100644 --- a/crates/parser/src/optimize/rewrite.rs +++ b/crates/parser/src/optimize/rewrite.rs @@ -107,6 +107,8 @@ fn rewrite( output.extend([LocalGet32(local), I32Add3]); read = output.len() - 1; } + } else { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); } } raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { @@ -117,7 +119,10 @@ fn rewrite( if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { continue; } - rewrite_sign_extend32(&mut output, &mut read, data, op); + if rewrite_sign_extend32(&mut output, &mut read, data, op) { + continue; + } + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); } raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { let op = int_bin_op(raw).unwrap(); @@ -129,6 +134,8 @@ fn rewrite( if op == BinOp::IAdd { rewrite!(output, read, [Const64(index)] => AddConst64(index)); rewrite!(output, read, [I64Add] => I64Add3); + } else { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); } } raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { @@ -138,7 +145,10 @@ fn rewrite( if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { continue; } - rewrite_sign_extend64(&mut output, &mut read, data, op); + if rewrite_sign_extend64(&mut output, &mut read, data, op) { + continue; + } + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); } raw if cmp_op(raw).is_some() => { let op = cmp_op(raw).unwrap(); @@ -149,23 +159,31 @@ fn rewrite( let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + if !rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); + } } raw @ (F32Sub | F32Div | F32Copysign) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + if !rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); + } } raw @ (F64Add | F64Mul | F64Min | F64Max) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + if !rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); + } } raw @ (F64Sub | F64Div | F64Copysign) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + if !rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); + } } raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { let op = bin_op_128(raw).unwrap(); @@ -299,6 +317,8 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), + Instruction::ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), Instruction::BinOpLocalConst32(packed) => { let value = data.operand64(packed.index); Some((packed.op, value.a(), value.b() as i32)) @@ -348,6 +368,8 @@ fn rewrite_scalar_const32( BinOp::IAdd => Instruction::AddLocalConst32(arg), BinOp::ISub => Instruction::SubLocalConst32(arg), BinOp::IMul => Instruction::MulLocalConst32(arg), + BinOp::IAnd => Instruction::AndLocalConst32(arg), + BinOp::IShrU => Instruction::ShrULocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, @@ -362,6 +384,7 @@ fn rewrite_scalar_const32( match op { BinOp::IAdd => Instruction::AddLocalConst32(arg), BinOp::IMul => Instruction::MulLocalConst32(arg), + BinOp::IAnd => Instruction::AndLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, @@ -380,6 +403,15 @@ fn rewrite_scalar_const32( Ok(true) } +fn stack_const32(op: BinOp, value: i32) -> Instruction { + match op { + BinOp::IAnd => Instruction::AndConst32(value), + BinOp::IXor => Instruction::XorConst32(value), + BinOp::IShrU => Instruction::ShrUConst32(value), + _ => Instruction::BinOpStackConst32(op, value), + } +} + fn rewrite_scalar_const64( output: &mut CompactOutput, read: &mut usize, @@ -568,7 +600,7 @@ fn rewrite_store64( if let [ Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), Instruction::LoadLocal64(arg), - Instruction::Const64(one), + Instruction::AddConst64(one), ] = previous && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) @@ -820,6 +852,12 @@ fn rewrite_local_tee32( } if *read > output.block_start { match output[*read - 1] { + Instruction::AndConst32(value) => { + replace!(output, *read, 1 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + } + Instruction::BinOpStackConst32(BinOp::ISub, value) => { + replace!(output, *read, 1 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + } Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), Instruction::BinOpLocalLocal32(op, left, right) => { let replacement = if op == BinOp::IAdd { @@ -886,6 +924,12 @@ fn rewrite_local_tee64( } if *read > output.block_start { match output[*read - 1] { + Instruction::BinOpStackConst64(packed) if packed.op == BinOp::IAnd => { + replace!(output, *read, 1 => Instruction::AndConstTee64(PackedOp::new(dst, packed.index))); + } + Instruction::BinOpStackConst64(packed) if packed.op == BinOp::ISub => { + replace!(output, *read, 1 => Instruction::SubConstTee64(PackedOp::new(dst, packed.index))); + } Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), Instruction::BinOpLocalLocal64(op, left, right) => { let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; @@ -1222,6 +1266,34 @@ fn rewrite_conditional( replace!(output, *read, 3 => replacement); return Ok(()); } + if *read >= output.block_start + 3 { + let update = match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::XorConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] + if local == cond => + { + Some((BinOp::IXor, value, local)) + } + [Instruction::ShrUConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] + if local == cond => + { + Some((BinOp::IShrU, value, local)) + } + [ + Instruction::BinOpStackConst32(op, value), + Instruction::LocalTee32(local), + Instruction::LocalGet32(cond), + ] if local == cond => Some((op, value, local)), + _ => None, + }; + if let Some((op, value, local)) = update { + let replacement = Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, + )); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } if *read >= output.block_start + 2 { let update = match [output[*read - 2], output[*read - 1]] { [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 954ae40..e20f6c6 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -11,16 +11,7 @@ keywords.workspace = true categories.workspace = true [package.metadata.docs.rs] -features = [ - "std", - "validate", - "parser", - "archive", - "log", - "canonicalize-nans", - "debug", - "guest-debug" -] +features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "debug", "guest-debug"] rustdoc-args = ["--cfg", "docsrs"] [lib] @@ -98,16 +89,8 @@ wasm-testsuite.workspace = true wat.workspace = true [features] -default = [ - "archive", - "canonicalize-nans", - "debug", - "log", - "parallel-parser", - "parser", - "std", - "validate" -] +default = ["full", "std"] +full = ["archive", "parallel-parser", "parser", "validate"] log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] @@ -119,10 +102,10 @@ send = [] parser = ["dep:tinywasm-parser"] # validate WebAssembly while parsing -validate = ["parser", "tinywasm-parser/validate"] +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"] diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index bdc50a3..9a05f8b 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -22,10 +22,7 @@ impl FuncContext<'_> { /// Get the module instance. pub fn module(&self) -> &crate::ModuleInstance { - unwrap_or_unreachable!( - self.store.get_module_instance(self.module_id), - "invalid module instance id in host function context" - ) + self.store.get_module_instance(self.module_id).expect("invalid module instance id in host function context") } /// Get a memory export. @@ -88,17 +85,17 @@ impl FuncContext<'_> { return Err(Error::other("FuncContext::call requires an active host-function invocation")); } - func.validate_call(self.store, args, results.len())?; + 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(); - func.call_untyped(self.store, args, results, call_stack_base, value_stack_base) + func.call_untyped(self.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.get(addr as usize).is_none() { + 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 }; @@ -118,32 +115,9 @@ impl FuncContext<'_> { return Err(Error::other("FuncContext::call requires an active host-function invocation")); } func.func.item.validate_store(self.store)?; - let func_instance = self.store.state.get_func(func.func.addr()).clone(); - if matches!(&func_instance.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) - { - let ty = self.store.state.get_canonical_func_type(func_instance.type_addr); - let (param_count, result_count) = (ty.params().len(), ty.results().len()); - self.store.with_scratch_values(param_count + result_count, |store, values| { - super::write_typed_params(&mut values[..param_count], params.into_wasm_values())?; - let (params, results) = values.split_at_mut(param_count); - func.func.validate_call(store, params, results.len())?; - let call_stack_base = store.call_stack.len(); - let value_stack_base = store.value_stack.base(); - func.func.call_untyped(store, params, results, call_stack_base, value_stack_base)?; - values.drain(..param_count); - R::from_wasm_values(&mut values.drain(..)) - }) - } else { - let call_stack_base = self.store.call_stack.len(); - let value_stack_base = self.store.value_stack.base(); - func.func.call_typed( - self.store, - &func_instance, - params.into_wasm_values(), - call_stack_base, - value_stack_base, - ) - } + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.func.call_typed(self.store, params.into_wasm_values(), call_stack_base, value_stack_base) } } diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 5e3fefa..ec81926 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -4,7 +4,7 @@ use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; use super::{FromWasmValues, FuncContext, IntoWasmValues}; use crate::shared::StoreShared; use crate::store::FuncValueTypes; -use crate::{Function, FunctionInstance, Result, Store, WasmValue}; +use crate::{Function, Result, Store, WasmValue}; /// Trait bounds required for a host callback in the current build mode. #[doc(hidden)] @@ -31,8 +31,7 @@ pub struct HostFunction(StoreShared); 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_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) }); + let addr = store.add_host_func(type_addr, self.clone()); Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } } @@ -64,22 +63,28 @@ impl HostFunction { args: &[WasmValue], results: &mut [WasmValue], ) -> Result<()> { - let expected = store.state.get_canonical_func_type(type_addr).clone(); - 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), - }; + { + 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), actual: results.to_vec() }); + return Err(crate::Error::InvalidHostFnReturn { + expected: Box::new(expected.clone()), + actual: results.to_vec(), + }); } Ok(()) } diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 3f5ef54..744356d 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -1,6 +1,6 @@ use crate::interpreter::stack::{CallFrame, StackBase}; use crate::reference::StoreItem; -use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; +use crate::{Error, InterpreterRuntime, Result, Store}; use alloc::format; use core::hint::cold_path; use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId}; @@ -65,19 +65,36 @@ impl Function { /// match the function signature. #[inline] pub fn call(&self, store: &mut Store, params: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { - self.validate_call(store, params, results.len())?; + 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, params, results, 0, StackBase::default()); + 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<()> { + fn validate_call( + &self, + store: &Store, + params: &[WasmValue], + result_count: usize, + ) -> Result { self.item.validate_store(store)?; - let func_ty = store.state.get_func_type(self.addr()); + 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!( @@ -117,62 +134,33 @@ impl Function { 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<()> { - let instance = store.state.get_func(self.addr()); - let type_addr = instance.type_addr; - match &instance.inner { - crate::store::FunctionInstanceInner::Host(host) => { - let host = host.clone(); - host.call_values(store, self.module_id, type_addr, params, results) - } - crate::store::FunctionInstanceInner::Wasm(wasm) => { + 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; - store - .push_wasm_values(params.iter().cloned()) - .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); - })?; - let result_type = store.state.get_canonical_func_type(type_addr).clone(); - store.pop_stack_values(result_type.results(), results) - } - } - } - - fn prepare_typed( - &self, - store: &mut Store, - instance: &FunctionInstance, - params: impl Iterator, - stack_base: StackBase, - ) -> Result> { - store.push_typed_values::(instance.type_addr, params, stack_base)?; - match &instance.inner { - crate::store::FunctionInstanceInner::Wasm(wasm) => { - let locals_base = store - .value_stack - .enter_locals(&wasm.func.params, &wasm.func.locals) - .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; - Ok(Some(CallFrame::new(self.addr(), locals_base, wasm.func.locals))) - } - crate::store::FunctionInstanceInner::Host(host) => { - host.typed_callback() - .expect("typed host function") - .call_stack(store, self.module_id, instance.type_addr) - .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; - Ok(None) - } + (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) } } @@ -180,18 +168,53 @@ impl Function { fn call_typed( &self, store: &mut Store, - instance: &FunctionInstance, params: impl Iterator, call_stack_base: u32, value_stack_base: StackBase, ) -> Result { - if let Some(callframe) = self.prepare_typed(store, instance, params, value_stack_base)? { - 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); - })?; + 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::(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(..)) + }) + } + }; } - store.take_typed_results(instance.type_addr, value_stack_base) + + 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::(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) } } @@ -210,26 +233,11 @@ impl FunctionTyped { /// Call a typed function pub fn call(&self, store: &mut Store, params: P) -> Result { self.func.item.validate_store(store)?; - let func = store.state.get_func(self.func.addr()).clone(); - if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { - let ty = store.state.get_canonical_func_type(func.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.into_wasm_values())?; - let (params, results) = values.split_at_mut(param_count); - self.func.call(store, params, results)?; - values.drain(..param_count); - R::from_wasm_values(&mut values.drain(..)) - }) - } else { - store.enter_execution()?; - let result: Result = { - store.call_stack.clear(); - store.value_stack.clear(); - self.func.call_typed(store, &func, params.into_wasm_values(), 0, StackBase::default()) - }; - store.exit_execution(); - result - } + 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 index c0d7f23..95c5bde 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -57,27 +57,36 @@ impl Function { params: &[WasmValue], results: &'store mut [WasmValue], ) -> Result> { - self.validate_call(store, params, results.len())?; + let type_addr = self.validate_call(store, params, results.len())?; store.enter_execution()?; let result: Result = (|| { - let func_instance = store.state.get_func(self.addr()).clone(); - match &func_instance.inner { - crate::store::FunctionInstanceInner::Host(host_func) => { - host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; - Ok(ExecState::Completed(Some(CallResult::Written))) - } - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - store.call_stack.clear(); - store.value_stack.clear(); - store.push_wasm_values(params.iter().cloned())?; - let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; - let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals); - - Ok(ExecState::Running { callframe, root_func_addr: self.addr() }) - } + 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?; @@ -116,8 +125,7 @@ impl ExecutionInner<'_> { match result { crate::interpreter::ExecState::Completed => { - let func = self.store.state.get_func(root_func_addr); - let result_ty = func.type_addr; + 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 })) } @@ -139,8 +147,7 @@ impl FuncExecution<'_> { ) -> Result> { match self.execution.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr }) => { - let ty = self.execution.store.state.get_canonical_func_type(type_addr).clone(); - self.execution.store.pop_stack_values(ty.results(), self.results)?; + self.execution.store.pop_stack_values(type_addr, self.results)?; Ok(ExecProgress::Completed(())) } ExecProgress::Completed(CallResult::Written) => Ok(ExecProgress::Completed(())), @@ -203,21 +210,27 @@ impl FunctionTyped { /// ``` pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result> { self.func.item.validate_store(store)?; - let func = store.state.get_func(self.func.addr()).clone(); - if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { + 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 = (|| { store.call_stack.clear(); store.value_stack.clear(); - match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { - Some(callframe) => Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() }), - None => Ok(ExecState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), - } + store.push_typed_values::(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? }; diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 6859bbf..35affab 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -328,8 +328,7 @@ 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 !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) - { + 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); diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 08682e3..581eb9e 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -68,25 +68,25 @@ struct ModuleInstanceInner { impl ModuleInstance { #[inline] pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr { - *unwrap_or_unreachable!(self.0.type_addrs.get(type_addr as usize), "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 { - *unwrap_or_unreachable!(self.0.func_addrs.get(addr as usize), "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 { - *unwrap_or_unreachable!(self.0.table_addrs.get(addr as usize), "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 { - *unwrap_or_unreachable!(self.0.mem_addrs.get(addr as usize), "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 @@ -103,24 +103,24 @@ impl ModuleInstance { /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { - *unwrap_or_unreachable!(self.0.data_addrs.get(addr as usize), "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 { - *unwrap_or_unreachable!(self.0.elem_addrs.get(addr as usize), "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 { - *unwrap_or_unreachable!(self.0.global_addrs.get(addr as usize), "invalid global address: {addr}") + self.0.global_addrs[addr as usize] } #[inline] pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { - *unwrap_or_unreachable!(self.0.tag_addrs.get(addr as usize), "invalid tag address: {addr}") + self.0.tag_addrs[addr as usize] } #[inline] diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index fa3f3f1..5266084 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -1,4 +1,4 @@ -use core::ops::ControlFlow; +use core::{convert::identity, ops::ControlFlow}; #[cfg(not(feature = "std"))] #[allow(unused_imports)] @@ -31,38 +31,12 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 = - unwrap_or_unreachable!(store.get_module_instance(wasm_func.owner), "invalid module instance").clone(); + 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 } } - /// 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 = unwrap_or_unreachable!(self.store.get_module_instance(owner), "invalid module instance").clone(); - self.mem0 = self.module.mem0_addr(); - } - - #[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, instr_ptr: usize) -> Result> { macro_rules! exec_op { @@ -179,7 +153,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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) => { i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(*c)); }, + AndConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value & *c); }, + XorConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value ^ *c); }, + ShrUConst32(c) => { u32::stack_update(&mut self.store.value_stack, |value| value.wrapping_shr(*c as u32)); }, AddConst64(idx) => { let rhs = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(rhs)); }, + BinOpStackConst32(op, rhs) => { u32::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, *rhs as u32)); }, + BinOpStackConst64(packed) => { let rhs = packed.index.resolve(&self.func.data).value() as u64; u64::stack_update(&mut self.store.value_stack, |lhs| packed.op.exec(lhs, rhs)); }, IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |value| value.wrapping_add(arg.value)); }, IncLocal64(packed) => { let rhs = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |value| value.wrapping_add(rhs)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), @@ -204,24 +183,26 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { AddLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAdd)?, SubLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::ISub)?, MulLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IMul)?, + AndLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAnd)?, + ShrULocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IShrU)?, BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, None, packed.op)?; }, - BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, - BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, - BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, BinOpStackLocal32(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, BinOpStackLocal128(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, + BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())), @@ -230,14 +211,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, - LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, identity)?, LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, - LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, @@ -246,8 +227,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, - LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, AndConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::IAnd)?, SubConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::ISub)?, AndConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, @@ -405,10 +386,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - I64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, + I64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, + F32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, + F64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, I32Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, @@ -416,10 +397,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, I64Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, I64Store32(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - I64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, + I64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, + F32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, + F64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, I32Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, I32Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, I32Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, @@ -501,7 +482,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| v)?, + V128Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), identity)?, V128Load8x8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, V128Load8x8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, V128Load16x4S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, @@ -512,7 +493,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128Load16Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i16)?, V128Load32Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i32)?, V128Load64Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), |v| v)?, + V128Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), identity)?, V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, @@ -753,6 +734,31 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(ControlFlow::Continue(instr_ptr + 1)) } + /// 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 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_jump_if_ref(&mut self) -> bool { let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); @@ -765,7 +771,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_br_on_cast(&self, index: Operand64Idx<(u32, u32)>) -> Option { let operand = index.resolve(&self.func.data); - let ty = unwrap_or_unreachable!(RefType::from_bits(operand.b())); + let ty = RefType::from_bits(operand.b()).expect("invalid ref type"); (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) } @@ -821,7 +827,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Option { 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()) + 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) @@ -959,6 +965,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) } + #[inline(always)] fn exec_simd_extract_lane( &mut self, lane: u8, @@ -968,6 +975,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) } + #[inline(always)] fn exec_simd_replace_lane( &mut self, lane: u8, @@ -1210,8 +1218,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return; } - let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); - self.func = wasm_func.func.clone(); + 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); } @@ -1253,54 +1263,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(None); }; self.switch_to_frame(caller); - protected_ip = unwrap_or_unreachable!(self.cf.instr_ptr.checked_sub(1), "invalid caller IP"); + protected_ip = self.cf.instr_ptr.checked_sub(1).expect("invalid caller IP"); } } - fn exec_call( - &mut self, - wasm_func: Shared, - owner: ModuleInstanceId, - func_addr: FuncAddr, - return_instr_ptr: usize, - ) -> Result<(), Trap> { - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); - }; - - self.store.call_stack.push(self.cf, return_instr_ptr)?; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); - if !Shared::ptr_eq(&self.func, &wasm_func) { - self.func = wasm_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - - Ok(()) - } - - fn exec_return_call( - &mut self, - wasm_func: Shared, - owner: ModuleInstanceId, - func_addr: FuncAddr, - ) -> Result<(), Trap> { - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.params); - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); - }; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); - if !Shared::ptr_eq(&self.func, &wasm_func) { - self.func = wasm_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - - Ok(()) - } - fn exec_call_host( &mut self, host_func: HostFunction, @@ -1332,7 +1298,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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.iter().cloned()) + store.push_wasm_values(results) }) .map_err(|error| match error { Error::Trap(trap) => trap, @@ -1344,30 +1310,56 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr); - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr, return_instr_ptr)?; - Ok(ControlFlow::Continue(0)) + 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::(host_func, type_addr, return_instr_ptr) + } else { + let wasm_func = self.store.state.funcs.wasm(addr); + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) + else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + + self.store.call_stack.push(self.cf, return_instr_ptr)?; + self.cf = CallFrame::new(addr, locals_base, wasm_func.func.locals); + if !Shared::ptr_eq(&self.func, &wasm_func.func) { + self.func = wasm_func.func.clone(); } - crate::store::FunctionInstanceInner::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, return_instr_ptr) + if wasm_func.owner != self.module.id() { + self.set_module(wasm_func.owner); } + Ok(ControlFlow::Continue(0)) } } fn exec_return_call_direct(&mut self, v: u32) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr); - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; - Ok(ControlFlow::Continue(0)) + 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::(host_func, type_addr, 0) + } else { + let wasm_func = self.store.state.funcs.wasm(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) + }; + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); + let Ok(locals_base) = self.store.value_stack.enter_locals(¶ms, &locals) else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + self.cf = CallFrame::new(addr, locals_base, locals); + if let Some(next_func) = next_func { + self.func = next_func; } - crate::store::FunctionInstanceInner::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, 0) + if owner != self.module.id() { + self.set_module(owner); } + Ok(ControlFlow::Continue(0)) } } @@ -1378,7 +1370,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; 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(ControlFlow::Continue(0)) } @@ -1424,23 +1415,51 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { expected_type_addr: TypeAddr, return_instr_ptr: usize, ) -> Result> { - let func = self.store.state.get_func(func_addr); - if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { + if self.store.state.funcs.is_host(func_addr) { + let host_func = self.store.state.funcs.host(func_addr); + let type_addr = host_func.type_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())); + } + let host_func = host_func.func.clone(); + return self.exec_call_host::(host_func, type_addr, return_instr_ptr); + } + + let wasm_func = self.store.state.funcs.wasm(func_addr); + let type_addr = wasm_func.type_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(func.type_addr).clone()), + 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())); } - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL { - true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), - false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr, return_instr_ptr), - }, - crate::store::FunctionInstanceInner::Host(host_func) => { - return self.exec_call_host::(host_func.clone(), func.type_addr, return_instr_ptr); - } + 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) + }; + let locals_base = if IS_RETURN_CALL { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); + self.store.value_stack.enter_locals(¶ms, &locals) + } else { + self.store.value_stack.enter_locals(¶ms, &locals) }?; + if IS_RETURN_CALL { + 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(ControlFlow::Continue(0)) } @@ -1572,27 +1591,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cold_err!(fma.store_at(&mut mem.inner, addr)) } - fn exec_load_local_value, const N: usize>( - &self, - memarg: Operand64, - addr_local: u8, - ) -> Result { - let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); - 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::(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::(base as usize, u64::from(memarg.offset())))? - }; - cold_err!(T::load_at(&mem.inner, addr)) - } - fn exec_load_local< LOAD: MemValue, const N: usize, @@ -1607,7 +1605,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let memarg = index.resolve(&self.func.data); - let value = cast(self.exec_load_local_value::(memarg, addr_local)?); + + 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::(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); } @@ -1953,7 +1966,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 == src_mem { + 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)?; @@ -2218,7 +2231,7 @@ impl<'store> Executor<'store, false> { loop { match self.exec(instr_ptr)? { ControlFlow::Continue(next_instr_ptr) => instr_ptr = next_instr_ptr, - ControlFlow::Break(()) => return Ok(()), + ControlFlow::Break(()) => return cold!(Ok(())), } } } diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs index 8506a04..d2c515a 100644 --- a/crates/tinywasm/src/interpreter/stack/call_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/call_stack.rs @@ -36,27 +36,13 @@ impl CallStack { } #[inline(always)] - pub(crate) fn push(&mut self, mut call_frame: CallFrame, return_instr_ptr: usize) -> Result<(), Trap> { - self.ensure_capacity_for(self.stack.len() + 1)?; - call_frame.instr_ptr = return_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(()); - } - - if required_len > self.max_size || !self.dynamic { + pub(crate) fn push(&mut self, mut call_frame: CallFrame, instr_ptr: usize) -> Result<(), Trap> { + if self.stack.len() == self.stack.capacity() && (!self.dynamic || self.stack.len() >= self.max_size) { return cold!(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 { - return cold!(Err(Trap::CallStackOverflow)); - }; + call_frame.instr_ptr = instr_ptr; + self.stack.push(call_frame); Ok(()) } } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 92b4d93..a9c86b7 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,5 +1,4 @@ use alloc::vec::Vec; -use core::hint::cold_path; use tinywasm_types::{MemoryArch, ValueCounts}; use super::StackBase; @@ -41,20 +40,18 @@ impl Stack { #[inline(always)] pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { - if !self.ensure_capacity_for(self.data.len() + 1) { + 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> { - if !self.ensure_capacity_for(self.data.len() + 1) { + 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(()) @@ -62,12 +59,18 @@ impl Stack { #[inline(always)] pub(crate) fn pop(&mut self) -> T { - unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug") + match self.data.pop() { + Some(value) => value, + None => cold!(unreachable!("ValueStack underflow, this is a bug")), + } } #[inline(always)] pub(crate) fn last(&self) -> &T { - unwrap_or_unreachable!(self.data.last(), "ValueStack underflow, this is a bug") + match self.data.last() { + Some(value) => value, + None => cold!(unreachable!("ValueStack underflow, this is a bug")), + } } #[inline(always)] @@ -107,12 +110,12 @@ impl Stack { #[inline(always)] pub(crate) fn truncate_to_one_tail(&mut self, n: usize) { debug_assert!(n < self.data.len()); - let last = unwrap_or_unreachable!(self.data.pop(), "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 { debug_assert!(param_count <= local_count); debug_assert!(param_count <= self.data.len()); @@ -122,13 +125,13 @@ impl Stack { 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); } } @@ -137,26 +140,6 @@ impl Stack { 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 { @@ -164,7 +147,7 @@ impl Stack { } let len = self.data.len(); - let needed = unwrap_or_unreachable!(count.checked_mul(2), "Stack underflow, this is a bug"); + let needed = count.wrapping_mul(2); if len < needed { unreachable!("Stack underflow, this is a bug"); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 38b7a04..b610fd8 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -135,19 +135,19 @@ macro_rules! impl_internalvalue { #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { let $from_stack_v = - *stack.$stack.get(frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize); + *stack.$stack.get(frame.locals_base.$stack_base as usize + index as usize); $from_stack } #[inline(always)] fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap> { - stack.$stack.push_copy(frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize) + stack.$stack.push_copy(frame.locals_base.$stack_base as usize + index as usize) } #[inline(always)] fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self) { let $to_stack_v = value; - let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; + let abs_index = frame.locals_base.$stack_base as usize + index as usize; stack.$stack.set(abs_index, $to_stack); } @@ -158,7 +158,7 @@ macro_rules! impl_internalvalue { index: LocalAddr, f: impl FnOnce(Self) -> Self, ) -> Self { - let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; + let abs_index = frame.locals_base.$stack_base as usize + index as usize; let $from_stack_v = *stack.$stack.get(abs_index); let value = f($from_stack); let $to_stack_v = value; @@ -168,8 +168,8 @@ macro_rules! impl_internalvalue { #[inline(always)] fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr) { - let from = frame.locals_base.$stack_base.wrapping_add(u32::from(from)) as usize; - let to = frame.locals_base.$stack_base.wrapping_add(u32::from(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); } @@ -258,55 +258,101 @@ pub(crate) trait CmpOpExt: Copy { } macro_rules! impl_value_ops { - ($unsigned:ty, $signed:ty, $float:ty) => { + ($unsigned:ty, $signed:ty, $binop:ident, $cmp:ident) => { impl BinOpExt<$unsigned> for BinOp { #[inline(always)] fn exec(self, lhs: $unsigned, rhs: $unsigned) -> $unsigned { - match self { - 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(), - } + $binop(self, lhs, rhs) } } impl CmpOpExt<$signed> for CmpOp { #[inline(always)] fn cmp(self, lhs: $signed, rhs: $signed) -> bool { - match self { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as $unsigned) < (rhs as $unsigned), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as $unsigned) > (rhs as $unsigned), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as $unsigned) <= (rhs as $unsigned), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as $unsigned) >= (rhs as $unsigned), - } + $cmp(self, lhs, rhs) } } }; } -impl_value_ops!(Value32, i32, f32); -impl_value_ops!(Value64, i64, f64); +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 for BinOp128 { #[inline(always)] diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e2ee684..fe74fcf 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -63,6 +63,7 @@ //! //! ## Cargo features //! +//! - **`full`:** Enables `archive`, `parallel-parser`, `parser`, 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. diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs index 96a2e40..351ae88 100644 --- a/crates/tinywasm/src/macros.rs +++ b/crates/tinywasm/src/macros.rs @@ -16,18 +16,3 @@ macro_rules! cold_err { } }; } - -macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ - match $value { - Some(value) => value, - None => cold!(unreachable!()), - } - }}; - ($value:expr, $($arg:tt)+) => {{ - match $value { - Some(value) => value, - None => cold!(unreachable!($($arg)+)), - } - }}; -} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 88fff5d..3eae3ab 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -1,30 +1,84 @@ +use alloc::vec::Vec; +use core::ops::Range; use tinywasm_types::*; use crate::func::HostFunction; -/// A WebAssembly Function Instance -/// -/// See -#[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct FunctionInstance { +pub(crate) struct HostFunctionInstance { pub(crate) type_addr: TypeAddr, - pub(crate) inner: FunctionInstanceInner, + pub(crate) func: HostFunction, } -#[derive(Clone)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) enum FunctionInstanceInner { - /// A host function - Host(HostFunction), - - /// A pointer to a WebAssembly function - Wasm(WasmFunctionInstance), -} - -#[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct WasmFunctionInstance { + pub(crate) type_addr: TypeAddr, pub(crate) func: Shared, pub(crate) owner: ModuleInstanceId, } + +#[derive(Default)] +pub(crate) struct Functions { + wasm: Vec, + host: Vec, +} + +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)>, + owner: ModuleInstanceId, + ) -> Range { + 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/global.rs b/crates/tinywasm/src/store/global.rs index 42a2acf..75aa163 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -3,17 +3,12 @@ use tinywasm_types::*; use crate::interpreter::{RuntimeValue, Value32, Value64, Value128}; +#[derive(Default)] struct GlobalLane { values: Vec, types: Vec, } -impl Default for GlobalLane { - fn default() -> Self { - Self { values: Vec::new(), types: Vec::new() } - } -} - impl GlobalLane { fn reserve(&mut self, additional: usize) { self.values.reserve_exact(additional); @@ -28,18 +23,18 @@ impl GlobalLane { index } - #[inline(always)] - fn get(&self, index: usize, addr: GlobalAddr) -> T { - *unwrap_or_unreachable!(self.values.get(index), "invalid global address: {addr}") + #[inline] + fn get(&self, index: usize) -> T { + self.values[index] } - #[inline(always)] - fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { - *unwrap_or_unreachable!(self.values.get_mut(index), "invalid global address: {addr}") = value; + #[inline] + fn set(&mut self, index: usize, value: T) { + self.values[index] = value; } - fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { - *unwrap_or_unreachable!(self.types.get(index), "invalid global address: {addr}") + fn ty(&self, index: usize) -> GlobalType { + self.types[index] } } @@ -90,9 +85,9 @@ impl Globals { /// 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), addr), - Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64), addr), - Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128), addr), + 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}"), } } @@ -119,37 +114,37 @@ impl Globals { /// 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), addr) + 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), addr) + 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), addr) + 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), addr, value); + 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), addr, value); + 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), addr, value); + self.globals_128.set(Self::index(addr, Self::LANE_128), value); } /// Iterates over globals in the 32-bit lane for root tracing. diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index 3a478fb..b947916 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -4,6 +4,8 @@ use crate::{Error, ResourceLimiter, Result, Trap}; use super::{MemoryStorage, memory_oob}; +const MEMORY64_MAX_BYTES: u64 = 16 * 1024 * 1024 * 1024; + /// A WebAssembly Memory Instance /// /// See @@ -31,6 +33,14 @@ impl MemoryInstance { kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } + #[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(&self, base: usize, offset: u64) -> Result { @@ -50,6 +60,13 @@ impl MemoryInstance { } pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result { + 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")) @@ -68,7 +85,8 @@ impl MemoryInstance { return cold!(Err(Trap::OutOfMemory.into())); } - let storage = MemoryStorage::try_new(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 }) } @@ -85,7 +103,11 @@ impl MemoryInstance { ) -> Result<(), Trap> { cold_err!(src_mem.inner.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_mem.inner.len())))?; cold_err!(self.inner.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))?; - self.inner.copy_from(dst, &src_mem.inner, src, len); + cold_err!(self.inner.copy_from(dst, &src_mem.inner, src, len).ok_or_else(|| memory_oob( + dst, + len, + self.inner.len() + )))?; Ok(()) } @@ -103,7 +125,7 @@ impl MemoryInstance { else { return cold!(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 { return cold!({ diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index 4d701ae..9f059ac 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -7,10 +7,6 @@ pub(crate) use instance::MemoryInstance; pub(crate) use vec::VecMemory; /// Internal storage for a linear memory. -/// -/// This is the boundary between the interpreter and the backing representation. Keeping it a -/// concrete type selected at compile time means the executor's load and store paths stay the same -/// whether the memory is `Vec`-backed or, later, mmap-backed. pub(crate) type MemoryStorage = VecMemory; /// A trait for types that can be converted to and from static byte arrays. diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index ef2d4df..c2daa16 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,20 +1,19 @@ use alloc::vec::Vec; use core::ops::Range; +use tinywasm_types::MemoryArch; use super::memory_oob; /// A contiguous `Vec`-backed linear memory storage. /// -/// This is the internal storage boundary for [`super::MemoryInstance`]. Keeping it a concrete type -/// rather than a `Vec` directly means the backing representation can later be swapped for an -/// mmap-backed implementation without touching the interpreter's load and store paths. +/// This is the default internal storage for [`super::MemoryInstance`]. pub(crate) struct VecMemory { data: Vec, } impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. - pub(crate) fn try_new(len: usize) -> Result { + pub(crate) fn try_new(_arch: MemoryArch, len: usize, _max_len: usize) -> Result { let mut data = Vec::new(); cold_err!(data.try_reserve(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); @@ -125,9 +124,12 @@ impl VecMemory { Some(()) } - /// Copies a previously checked range from another memory. + /// Copies a valid range from another memory. #[inline(always)] - pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) { - self.data[dst..dst + len].copy_from_slice(&src_memory.data[src..src + len]); + pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) -> Option<()> { + let src_range = src_memory.checked_range(src, len)?; + let dst_range = self.checked_range(dst, len)?; + self.data[dst_range].copy_from_slice(&src_memory.data[src_range]); + Some(()) } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 862cb4f..e157240 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -2,7 +2,7 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; use tinywasm_types::*; -use crate::func::FromWasmValues; +use crate::func::{FromWasmValues, HostFunction}; use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; use crate::interpreter::{RuntimeValue, ValueRef}; use crate::reference::{ReferentKind, RootedItem, StoreId, StoredRef}; @@ -363,7 +363,7 @@ impl Store { Ok(StackValueIter { store: self, type_addr, types, index, position: 0, len }) } - pub(crate) fn push_wasm_values(&mut self, values: impl IntoIterator) -> Result<()> { + 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)?; @@ -371,14 +371,19 @@ impl Store { Ok(()) } - pub(crate) fn pop_stack_values(&mut self, types: &[WasmType], results: &mut [WasmValue]) -> Result<()> { - if types.len() != results.len() { + 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(types.iter().collect()); + let base = self.value_stack.base_before(result_counts); let result = (|| { let mut index = base; - for (&ty, result) in types.iter().zip(results) { + 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)?; } @@ -503,17 +508,10 @@ impl Store { module_type_idxs: &[TypeAddr], type_addrs: &[TypeAddr], ) -> impl ExactSizeIterator { - let start = self.state.funcs.len() as FuncAddr; debug_assert_eq!(funcs.len(), module_type_idxs.len()); - self.state.funcs.reserve_exact(funcs.len()); - for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) { - let type_addr = type_addrs[type_idx as usize]; - self.state.funcs.push(FunctionInstance { - type_addr, - inner: FunctionInstanceInner::Wasm(WasmFunctionInstance { func, owner }), - }); - } - start..start + funcs.len() as FuncAddr + 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. @@ -752,9 +750,7 @@ impl Store { } /// Adds a function and returns its store address. - pub(crate) fn add_func(&mut self, func: FunctionInstance) -> FuncAddr { - let addr = self.state.funcs.len() as FuncAddr; - self.state.funcs.push(func); - addr + 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 index cad0208..f1ba616 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -12,7 +12,7 @@ pub(crate) struct State { // Concrete type indexes in store instances address this canonical type space. pub(crate) canonical_types: Vec, pub(crate) canonical_rec_group_lengths: Vec, - pub(crate) funcs: Vec, + pub(crate) funcs: Functions, pub(crate) tables: Vec, pub(crate) memories: Vec, pub(crate) globals: Globals, @@ -28,7 +28,7 @@ impl State { Self { canonical_types: Vec::new(), canonical_rec_group_lengths: Vec::new(), - funcs: Vec::new(), + funcs: Functions::default(), tables: Vec::new(), memories: Vec::new(), globals: Globals::default(), @@ -250,8 +250,11 @@ impl State { || expected.abstract_heap_type() == Some(AbstractHeapType::Func); if expected_func { let Some(func_addr) = value.addr() else { return false }; - let Some(func) = self.funcs.get(func_addr as usize) else { return false }; - return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); + 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(_))); @@ -271,12 +274,12 @@ impl State { #[inline] pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType { - self.get_canonical_func_type(self.get_func(addr).type_addr) + self.get_canonical_func_type(self.funcs.type_addr(addr)) } #[inline] pub(crate) fn get_type(&self, addr: TypeAddr) -> &SubType { - Self::get(&self.canonical_types, addr, "canonical type") + &self.canonical_types[addr as usize] } #[inline] @@ -284,14 +287,7 @@ impl State { self.get_type(addr).as_func().expect("validated function address references a function type") } - pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { - unwrap_or_unreachable!(items.get(addr as usize), "invalid {kind} address: {addr}") - } - - fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { - unwrap_or_unreachable!(items.get_mut(addr as usize), "invalid {kind} address: {addr}") - } - + #[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]) @@ -299,46 +295,39 @@ impl State { (item_a, item_b) } - /// Get the function at the actual index in the store - pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance { - Self::get(&self.funcs, addr, "function") - } - + #[inline] pub(crate) fn get_tag(&self, addr: TagAddr) -> &TagInstance { - Self::get(&self.tags, addr, "tag") - } - - /// 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.inner) { - Some(FunctionInstanceInner::Wasm(wasm_func)) => wasm_func, - _ => unreachable!("invalid wasm function address: {addr}"), - } + &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::get(&self.memories, addr, "memory") + &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 { - Self::get_mut(&mut self.memories, addr, "memory") + &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::get(&self.tables, addr, "table") + &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 { - Self::get_mut(&mut self.tables, addr, "table") + &mut self.tables[addr as usize] } /// Get two mutable tables at the actual index in the store @@ -351,13 +340,15 @@ impl State { } /// Get the data at the actual index in the store + #[inline] pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance { - Self::get_mut(&mut self.data, addr, "data") + &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 { - Self::get_mut(&mut self.elements, addr, "element") + &mut self.elements[addr as usize] } /// Returns a global in its internal value representation. diff --git a/crates/tinywasm/tests/test-wast.rs b/crates/tinywasm/tests/test-wast.rs index 004bafa..fcf3044 100644 --- a/crates/tinywasm/tests/test-wast.rs +++ b/crates/tinywasm/tests/test-wast.rs @@ -15,13 +15,7 @@ fn main() -> Result<(), Box> { 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::, _>>()? - } else { - vec![arg] - }; - let mut test_suite = WastRunner::new(); - test_suite.run_paths(&files)?; + test_suite.run_paths(&[arg])?; Ok(()) } diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 7f701cf..091bb9f 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -20,7 +20,7 @@ serde = { version = "1.0", default-features = false, features = ["alloc"], optio default = ["archive", "debug", "log", "std"] # support serializing and deserializing twasm archives -archive = ["dep:postcard", "dep:serde", "serde/rc", "portable-atomic-util?/serde"] +archive = ["dep:postcard", "dep:serde", "portable-atomic-util?/serde", "serde/rc"] # derive Debug for runtime and module types debug = [] diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index b92a0f4..6a357ea 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -511,8 +511,9 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(Operand64Idx), + AddConst32(i32), AndConst32(i32), XorConst32(i32), ShrUConst32(i32), AddConst64(Operand64Idx), IncLocal32(I32LocalArg), IncLocal64(PackedOp64), + // 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), @@ -520,18 +521,25 @@ pub enum Instruction { AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), BinOpLocalLocalSet32(PackedOp64), BinOpLocalLocalSet64(PackedOp64), BinOpLocalLocalSet128(PackedOp64), BinOpLocalLocalTee32(PackedOp64), BinOpLocalLocalTee64(PackedOp64), BinOpLocalLocalTee128(PackedOp64), + AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), + AndLocalConst32(I32LocalArg), ShrULocalConst32(I32LocalArg), BinOpLocalConst32(PackedOp64), BinOpLocalConst64(PackedOp128), - BinOpGlobalConst32(PackedOp64), BinOpGlobalConst64(PackedOp128), - BinOpGlobalConst128(PackedOp64)>), BinOpLocalConst128(PackedOp64)>), + BinOpLocalConst128(PackedOp64)>), BinOpLocalConstSet32(PackedOp64), BinOpLocalConstSet64(PackedOp128), BinOpLocalConstSet128(PackedOp64)>), BinOpLocalConstTee32(PackedOp64), BinOpLocalConstTee64(PackedOp128), BinOpLocalConstTee128(PackedOp64)>), + + BinOpStackConst32(BinOp, i32), BinOpStackConst64(PackedOp64), + BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), + BinOpGlobalConst32(PackedOp64), BinOpGlobalConst64(PackedOp128), + BinOpGlobalConst128(PackedOp64)>), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64), SetLocalConst128(PackedOp128), IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index edbab26..af1b17f 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -146,26 +146,11 @@ macro_rules! define_operand { define_operand!(Operand64, 8); define_operand!(Operand128, 16); -macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ - match $value { - Some(value) => value, - None => { core::hint::cold_path(); unreachable!() }, - } - }}; - ($value:expr, $($arg:tt)+) => {{ - match $value { - Some(value) => value, - None => { core::hint::cold_path(); unreachable!($($arg)+) }, - } - }}; -} - impl Operand64Idx { /// Resolves this index to a copied 64-bit packed operand. #[inline(always)] pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64 { - (*unwrap_or_unreachable!(data.operands64.get(self.index()), "invalid 64-bit operand index")).cast() + data.operands64[self.index as usize].cast() } } @@ -173,7 +158,7 @@ impl Operand128Idx { /// Resolves this index to a copied 128-bit packed operand. #[inline(always)] pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128 { - (*unwrap_or_unreachable!(data.operands128.get(self.index()), "invalid 128-bit operand index")).cast() + data.operands128[self.index as usize].cast() } } diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 6701074..e0bdba6 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -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"] } -[lints.clippy] -missing_safety_doc = "allow" - [features] default = ["std"] std = ["tinywasm/std"] +[lints.clippy] +missing_safety_doc = "allow" + [profile.wasm] inherits = "release" opt-level = 3 -- cgit v1.3.1 From ded2780129ef8c58edfc1af51ea23be2524a15b1 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 13 Sep 2026 17:45:53 +0200 Subject: chore: update deps, remove inline from dispatch handlers (closes #55) Signed-off-by: Henry --- Cargo.lock | 71 +++++++++++----------- Cargo.toml | 9 ++- crates/cli/Cargo.toml | 1 - crates/parser/Cargo.toml | 1 - crates/tinywasm/Cargo.toml | 2 +- .../src/interpreter/executor/dispatch_become.rs | 2 - crates/types/Cargo.toml | 9 +-- 7 files changed, 44 insertions(+), 51 deletions(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index edc0bbf..a22eba9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -105,9 +105,9 @@ 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" @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.4" +version = "1.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" dependencies = [ "find-msvc-tools", "shlex", @@ -215,7 +215,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.5", ] [[package]] @@ -275,9 +275,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", @@ -285,18 +285,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" @@ -365,9 +365,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" [[package]] name = "float-cmp" @@ -414,9 +414,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" @@ -445,9 +445,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.1" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", @@ -578,9 +578,9 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ "portable-atomic", "serde", @@ -766,7 +766,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.5", ] [[package]] @@ -807,9 +807,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.4" +version = "3.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" dependencies = [ "proc-macro2", "quote", @@ -861,7 +861,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.5", ] [[package]] @@ -935,7 +935,6 @@ dependencies = [ name = "tinywasm-types" version = "0.11.0-pre.0" dependencies = [ - "log", "portable-atomic-util", "postcard", "serde", @@ -980,9 +979,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.258.0" +version = "0.259.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e974fe6821a8cf64575d51ea2194e2c8f77e7b66e9afe7419ce8a97f9ee0d251" +checksum = "b1d0246511d901aacf25d2dc9111f0054947de5e093fe662099e709ff7530dc3" dependencies = [ "leb128fmt", "wasmparser", @@ -1000,9 +999,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.258.0" +version = "0.259.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9a61719f93a87b16d325921e251800c4833f8fab50fa21c7de73aed50086313" +checksum = "0f7c12eac7bb587801590f6a67ff0bc84d0748513864b71108e4b311cc3df694" dependencies = [ "bitflags", "indexmap", @@ -1011,9 +1010,9 @@ dependencies = [ [[package]] name = "wast" -version = "258.0.0" +version = "259.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97f7defc7ecca8b19ac7f824598eadd0c53985ee00c74060d65051e9da5b58a1" +checksum = "c69beba8d9da07af9a0971b559149a2ac4729895b55144de4fddbf5a02660648" dependencies = [ "bumpalo", "leb128fmt", @@ -1024,9 +1023,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.258.0" +version = "1.259.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7555c008cca87f2ac58d9f83ccda7e7b44611093ce28eb28f052e7c78024b9bf" +checksum = "c6eec44b0c80391b20fb7ad9ea440c72c5d382385bdf74444bb18321c425017e" dependencies = [ "wast", ] @@ -1079,18 +1078,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.56" +version = "0.8.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.56" +version = "0.8.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 1d709e2..a3fdd3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.258", default-features = false } -wast = "258" -wat = "1.258" +wasmparser = { version = "0.259", default-features = false } +wast = "259" +wat = "1.259" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } @@ -65,6 +65,9 @@ tinywasm = { path = "crates/tinywasm" } tinywasm-parser.workspace = true wat.workspace = true +[lints.cargo] +unused_dependencies = "allow" # false-positive on libm + [profile.bench] opt-level = 3 debug = true diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 861d349..22f1bf8 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -5,7 +5,6 @@ edition.workspace = true rust-version.workspace = true description = "Minimal command-line interface for TinyWasm" documentation = "https://docs.rs/tinywasm-cli" -readme = "README.md" repository.workspace = true license.workspace = true keywords = ["cli", "runtime", "tinywasm", "wasm", "webassembly"] diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml index 7d781a4..f868beb 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -4,7 +4,6 @@ version.workspace = true edition.workspace = true rust-version.workspace = true description = "Parser and lowering pipeline for TinyWasm" -readme = "README.md" repository.workspace = true license.workspace = true keywords.workspace = true diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 3d78fca..15744a3 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -92,7 +92,7 @@ wat.workspace = true default = ["full", "std"] full = ["archive", "parallel-parser", "parser", "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 diff --git a/crates/tinywasm/src/interpreter/executor/dispatch_become.rs b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs index 66cbb51..0dc8d5e 100644 --- a/crates/tinywasm/src/interpreter/executor/dispatch_become.rs +++ b/crates/tinywasm/src/interpreter/executor/dispatch_become.rs @@ -15,7 +15,6 @@ fn 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(instruction: &Instruction) -> UnbudgetedHandler { use tinywasm_types::Instruction::*; @@ -64,7 +63,6 @@ macro_rules! define_unbudgeted_tail_dispatch { 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(instruction: &Instruction) -> BoundedHandler { use tinywasm_types::Instruction::*; diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 091bb9f..4046896 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -4,20 +4,18 @@ version.workspace = true edition.workspace = true rust-version.workspace = true description = "Shared runtime, module, and archive types for TinyWasm" -readme = "README.md" repository.workspace = true license.workspace = true keywords.workspace = true categories.workspace = true [dependencies] -log = { workspace = true, optional = true } -portable-atomic-util = { version = "0.2.7", default-features = false, features = ["alloc"], 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"], optional = true } [features] -default = ["archive", "debug", "log", "std"] +default = ["archive", "debug", "std"] # support serializing and deserializing twasm archives archive = ["dep:postcard", "dep:serde", "portable-atomic-util?/serde", "serde/rc"] @@ -25,9 +23,6 @@ archive = ["dep:postcard", "dep:serde", "portable-atomic-util?/serde", "serde/rc # derive Debug for runtime and module types debug = [] -# enable integration with the log crate -log = ["dep:log"] - # enable standard library support std = ["serde?/std"] -- cgit v1.3.1 From dc8e5732d71b6f66e730b090ab02bdccc69ec888 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 15 Sep 2026 15:23:11 +0200 Subject: feat: initial wasi p1 implementation Signed-off-by: Henry --- Cargo.lock | 308 +++++++++++++++++++++++-- Cargo.toml | 16 +- crates/cli/Cargo.toml | 4 + crates/parser/Cargo.toml | 4 +- crates/tinywasm/Cargo.toml | 3 + crates/types/Cargo.toml | 3 + crates/wasi/Cargo.toml | 25 ++ crates/wasi/README.md | 10 + crates/wasi/src/lib.rs | 4 + crates/wasi/src/p1/abi.rs | 300 ++++++++++++++++++++++++ crates/wasi/src/p1/ctx.rs | 293 +++++++++++++++++++++++ crates/wasi/src/p1/imports/clock.rs | 28 +++ crates/wasi/src/p1/imports/command.rs | 72 ++++++ crates/wasi/src/p1/imports/fd.rs | 423 ++++++++++++++++++++++++++++++++++ crates/wasi/src/p1/imports/mod.rs | 101 ++++++++ crates/wasi/src/p1/imports/path.rs | 258 +++++++++++++++++++++ crates/wasi/src/p1/imports/poll.rs | 219 ++++++++++++++++++ crates/wasi/src/p1/imports/process.rs | 20 ++ crates/wasi/src/p1/imports/random.rs | 25 ++ crates/wasi/src/p1/imports/sock.rs | 124 ++++++++++ crates/wasi/src/p1/memory.rs | 115 +++++++++ crates/wasi/src/p1/mod.rs | 22 ++ crates/wasi/tests/p1.rs | 357 ++++++++++++++++++++++++++++ examples/wasi_p1.rs | 42 ++++ 24 files changed, 2753 insertions(+), 23 deletions(-) create mode 100644 crates/wasi/Cargo.toml create mode 100644 crates/wasi/README.md create mode 100644 crates/wasi/src/lib.rs create mode 100644 crates/wasi/src/p1/abi.rs create mode 100644 crates/wasi/src/p1/ctx.rs create mode 100644 crates/wasi/src/p1/imports/clock.rs create mode 100644 crates/wasi/src/p1/imports/command.rs create mode 100644 crates/wasi/src/p1/imports/fd.rs create mode 100644 crates/wasi/src/p1/imports/mod.rs create mode 100644 crates/wasi/src/p1/imports/path.rs create mode 100644 crates/wasi/src/p1/imports/poll.rs create mode 100644 crates/wasi/src/p1/imports/process.rs create mode 100644 crates/wasi/src/p1/imports/random.rs create mode 100644 crates/wasi/src/p1/imports/sock.rs create mode 100644 crates/wasi/src/p1/memory.rs create mode 100644 crates/wasi/src/p1/mod.rs create mode 100644 crates/wasi/tests/p1.rs create mode 100644 examples/wasi_p1.rs (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index a22eba9..8db3177 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,6 +20,12 @@ dependencies = [ "cc", ] +[[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" @@ -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,7 +79,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -126,6 +132,48 @@ version = "3.20.3" 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" @@ -177,9 +225,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.6" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" dependencies = [ "clap_builder", "clap_derive", @@ -187,9 +235,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.6" +version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" dependencies = [ "anstream", "anstyle", @@ -199,18 +247,18 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.9" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be2ad0423bdbbb0e25bc89add796f3559706d4a95e1bc98e4d9662a957b6a19" +checksum = "78ab9a1a7094014a0d0813f8e7c5a0058ad8fe6cf7475b9151364259f5a35d0f" 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", @@ -220,9 +268,9 @@ dependencies = [ [[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" @@ -354,7 +402,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -378,6 +426,17 @@ dependencies = [ "num-traits", ] +[[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" @@ -453,6 +512,34 @@ dependencies = [ "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" @@ -461,7 +548,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -515,6 +602,12 @@ 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 = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "memchr" version = "2.8.3" @@ -721,7 +814,17 @@ dependencies = [ "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]] @@ -826,7 +929,7 @@ dependencies = [ "getrandom", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -905,6 +1008,7 @@ dependencies = [ "serde_json", "tempfile", "tinywasm", + "tinywasm-wasi", "wasm-testsuite", "wast", "wat", @@ -928,6 +1032,7 @@ dependencies = [ "pretty_env_logger", "tinywasm", "tinywasm-parser", + "tinywasm-wasi", "wat", ] @@ -940,6 +1045,18 @@ dependencies = [ "serde", ] +[[package]] +name = "tinywasm-wasi" +version = "0.11.0-pre.0" +dependencies = [ + "cap-fs-ext", + "cap-std", + "getrandom", + "rustix", + "tinywasm", + "wat", +] + [[package]] name = "unicode-ident" version = "1.0.24" @@ -1052,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]] @@ -1067,6 +1184,24 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" 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" @@ -1076,6 +1211,145 @@ dependencies = [ "windows-link", ] +[[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.57" diff --git a/Cargo.toml b/Cargo.toml index a3fdd3b..8f40398 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ 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" @@ -23,6 +23,7 @@ categories = ["compilers", "embedded", "no-std", "virtualization", "wasm"] tinywasm = { path = "crates/tinywasm", 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-wasi = { path = "crates/wasi", version = "0.11.0-pre.0" } anyhow = "1.0" log = "0.4" @@ -37,6 +38,12 @@ wat = "1.259" 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 = "rust" test = false @@ -61,12 +68,13 @@ name = "tinywasm_modes" 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.cargo] -unused_dependencies = "allow" # false-positive on libm +[lints] +workspace = true [profile.bench] opt-level = 3 diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 22f1bf8..aff21a2 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -38,6 +38,7 @@ tinywasm = { workspace = true, features = [ "log", "std", ] } +tinywasm-wasi.workspace = true wasm-testsuite = { workspace = true, optional = true } wast = { workspace = true, optional = true } wat = { workspace = true, optional = true } @@ -52,3 +53,6 @@ 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/parser/Cargo.toml b/crates/parser/Cargo.toml index f868beb..3cd3097 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -32,5 +32,5 @@ std = ["tinywasm-types/std", "wasmparser/std"] # validate WebAssembly while parsing validate = ["wasmparser/features", "wasmparser/validate"] -[lints.rust] -unexpected_cfgs = { level = "warn", check-cfg = ["cfg(rust_analyzer)"] } +[lints] +workspace = true diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 15b151c..9ed5fa7 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -132,3 +132,6 @@ nightly-tail-calls = [] # 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/types/Cargo.toml b/crates/types/Cargo.toml index 4046896..3837fdc 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -28,3 +28,6 @@ std = ["serde?/std"] # support targets without native atomic CAS portable-atomic = ["dep:portable-atomic-util"] + +[lints] +workspace = true diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml new file mode 100644 index 0000000..e4d0ef0 --- /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" +repository.workspace = true +license.workspace = true +keywords = ["tinywasm", "wasi", "wasm", "webassembly"] +categories = ["wasm"] +publish = false + +[dependencies] +cap-fs-ext = "4.0.3" +cap-std = "4.0.3" +getrandom = "0.4.3" +rustix = { version = "1.1.4", 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..1c173aa --- /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). Currently unreleased. + +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 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 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) -> 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 { + 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 { + #[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(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>, +} + +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>, + pub(super) env: Vec>, + pub(super) descriptors: Vec>, + pub(super) exit_status: Option, + 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>) -> Result { + 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>>) -> Result { + self.args = args.into_iter().map(|value| validate_bytes(value.into())).collect::>()?; + Ok(self) + } + + /// Sets UTF-8 environment variables visible to the guest. + pub fn with_env( + self, + env: impl IntoIterator, impl Into)>, + ) -> Result { + 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>, impl Into>)>, + ) -> Result { + self.env = env + .into_iter() + .map(|(key, value)| { + let mut entry = key.into(); + entry.push(b'='); + entry.extend(value.into()); + validate_bytes(entry) + }) + .collect::>()?; + 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, + guest_path: impl AsRef<[u8]>, + ) -> Result { + 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 { + 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 { + 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 { + self.insert_socket(Resource::UdpSocket(socket)) + } + + /// Returns the status supplied to `proc_exit`, if it was called. + pub fn exit_status(&self) -> Option { + self.exit_status + } + + /// Takes and clears the status supplied to `proc_exit`. + pub fn take_exit_status(&mut self) -> Option { + 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 { + 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 { + 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) -> Result, 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::().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::().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 { + 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 { + 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, ×tamp.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 { + let sizes = sizes(&state(&ctx)?.args)?; + sizes_get(ctx, pointers, sizes) +} + +pub(super) fn environ_sizes_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult { + 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 { + 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]) -> 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 { + let values = state(&ctx)?.args.clone(); + array_get(ctx, pointers, values) +} + +pub(super) fn environ_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult { + 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>) -> WasiResult { + 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]) -> Option { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, ×).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 { + 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 { + 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, +) -> WasiResult { + 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 { + 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 { + 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, +) -> WasiResult { + 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 { + 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 { + 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 { + 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 { + sync_fd(ctx, fd, false) +} + +pub(super) fn fd_datasync(ctx: FuncContext<'_>, fd: i32) -> WasiResult { + sync_fd(ctx, fd, true) +} + +fn sync_fd(mut ctx: FuncContext<'_>, fd: i32, data_only: bool) -> WasiResult { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 = Result; + +enum WasiError { + Errno(Errno), + Host(tinywasm::Error), +} + +impl From for WasiError { + fn from(errno: Errno) -> Self { + Self::Errno(errno) + } +} + +impl From 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

( + imports: &mut Imports, + name: &str, + function: fn(tinywasm::FuncContext<'_>, P) -> WasiResult, +) where + P: tinywasm::FromWasmValues + 'static, +{ + imports.define( + MODULE, + name, + HostFunction::from(move |ctx: tinywasm::FuncContext<'_>, args: P| -> tinywasm::Result { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 = 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 { + 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, + poll_targets: &mut Vec, +) -> 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, +) -> WasiResult { + 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 { + Ok(NOTSUP) +} + +pub(super) fn sched_yield(_ctx: FuncContext<'_>, (): ()) -> WasiResult { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, 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, 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 { + 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, 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::().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/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(()) +} -- cgit v1.3.1 From f8b66d0480ecb9d52be9516af5360f092883ccc8 Mon Sep 17 00:00:00 2001 From: Henry Date: Wed, 16 Sep 2026 12:13:16 +0200 Subject: chore: 0.11.0-beta.0 Signed-off-by: Henry --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 10 +++++----- README.md | 4 ++-- crates/wasi/Cargo.toml | 1 - crates/wasi/README.md | 2 +- 5 files changed, 16 insertions(+), 17 deletions(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index 8db3177..690c747 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -247,9 +247,9 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.10" +version = "4.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ab9a1a7094014a0d0813f8e7c5a0058ad8fe6cf7475b9151364259f5a35d0f" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" dependencies = [ "clap", ] @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "tinywasm" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "libm", "log", @@ -993,7 +993,7 @@ dependencies = [ [[package]] name = "tinywasm-cli" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "anstream", "anyhow", @@ -1016,7 +1016,7 @@ dependencies = [ [[package]] name = "tinywasm-parser" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "log", "tinywasm-types", @@ -1025,7 +1025,7 @@ dependencies = [ [[package]] name = "tinywasm-root" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "anyhow", "criterion", @@ -1038,7 +1038,7 @@ dependencies = [ [[package]] name = "tinywasm-types" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "portable-atomic-util", "postcard", @@ -1047,7 +1047,7 @@ dependencies = [ [[package]] name = "tinywasm-wasi" -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" dependencies = [ "cap-fs-ext", "cap-std", diff --git a/Cargo.toml b/Cargo.toml index 8f40398..66fc96d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ members = ["crates/*"] default-members = [".", "crates/parser", "crates/tinywasm", "crates/types", "crates/wasi"] [workspace.package] -version = "0.11.0-pre.0" +version = "0.11.0-beta.0" edition = "2024" rust-version = "1.98" repository = "https://github.com/explodingcamera/tinywasm" @@ -20,10 +20,10 @@ 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-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-wasi = { path = "crates/wasi", version = "0.11.0-pre.0" } +tinywasm = { path = "crates/tinywasm", version = "0.11.0-beta.0", default-features = false } +tinywasm-parser = { path = "crates/parser", version = "0.11.0-beta.0", default-features = false } +tinywasm-types = { path = "crates/types", version = "0.11.0-beta.0", default-features = false } +tinywasm-wasi = { path = "crates/wasi", version = "0.11.0-beta.0" } anyhow = "1.0" log = "0.4" diff --git a/README.md b/README.md index 1c2803c..d77abdb 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ > [!WARNING] -> This is the `next` branch and contains unreleased changes. See [`v0.10.0`](https://github.com/explodingcamera/tinywasm/tree/v0.10.0) for the latest released version. +> This is the `next` branch and contains changes for the 0.11 beta. See [`v0.10.0`](https://github.com/explodingcamera/tinywasm/tree/v0.10.0) for the latest stable version. # `tinywasm` @@ -19,7 +19,7 @@ ```toml [dependencies] -tinywasm = "0.10" +tinywasm = "0.11.0-beta.0" ``` ## Usage diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml index e4d0ef0..bbf6242 100644 --- a/crates/wasi/Cargo.toml +++ b/crates/wasi/Cargo.toml @@ -8,7 +8,6 @@ repository.workspace = true license.workspace = true keywords = ["tinywasm", "wasi", "wasm", "webassembly"] categories = ["wasm"] -publish = false [dependencies] cap-fs-ext = "4.0.3" diff --git a/crates/wasi/README.md b/crates/wasi/README.md index 1c173aa..d67adaf 100644 --- a/crates/wasi/README.md +++ b/crates/wasi/README.md @@ -1,6 +1,6 @@ # tinywasm-wasi -Experimental WASI support for TinyWasm mainly targeting \*nix systems (Windows support is very limited). Currently unreleased. +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. -- cgit v1.3.1 From fd0718f1cdbb08ecd3305d5790c099ef43a9c7c3 Mon Sep 17 00:00:00 2001 From: Henry Date: Fri, 18 Sep 2026 11:46:27 +0200 Subject: fix: store gc keys in heap, fix utf 16 string handling Signed-off-by: Henry --- Cargo.lock | 22 +++++++++++----------- crates/tinywasm/src/func/resume.rs | 9 +++++++++ crates/tinywasm/src/reference/store.rs | 13 +++++-------- crates/tinywasm/src/store/gc/object.rs | 11 ++++++----- crates/tinywasm/tests/generated/wasm-1.csv | 1 + crates/tinywasm/tests/generated/wasm-2.csv | 1 + crates/tinywasm/tests/generated/wasm-3.csv | 1 + .../tests/generated/wasm-custom-page-sizes.csv | 1 + crates/tinywasm/tests/generated/wasm-gc.csv | 1 + crates/tinywasm/tests/generated/wasm-latest.csv | 1 + crates/tinywasm/tests/generated/wasm-memory64.csv | 1 + .../tinywasm/tests/generated/wasm-multi-memory.csv | 1 + .../tinywasm/tests/generated/wasm-relaxed-simd.csv | 1 + crates/tinywasm/tests/generated/wasm-simd.csv | 1 + .../tests/generated/wasm-wide-arithmetic.csv | 1 + crates/tinywasm/tests/memory_ref_api.rs | 13 +++++++++++++ crates/wasi/Cargo.toml | 2 +- 17 files changed, 56 insertions(+), 25 deletions(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index 690c747..eeb9e4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,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" @@ -263,7 +263,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -806,9 +806,9 @@ 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", @@ -869,7 +869,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -910,9 +910,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ "proc-macro2", "quote", @@ -964,7 +964,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -1059,9 +1059,9 @@ dependencies = [ [[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" diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index 95c5bde..a035ffc 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -33,6 +33,15 @@ struct ExecutionInner<'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 }, diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs index 07d8eb2..e763e70 100644 --- a/crates/tinywasm/src/reference/store.rs +++ b/crates/tinywasm/src/reference/store.rs @@ -531,15 +531,12 @@ impl Memory { /// Reads a JavaScript-style utf-16 string from memory. pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result { - 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()))?, - ); + if !len.is_multiple_of(2) { + return Err(crate::Error::Other("Invalid UTF-16 string: odd byte length".to_string())); } - Ok(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::>(); + String::from_utf16(&code_units).map_err(|error| crate::Error::Other(format!("Invalid UTF-16 string: {error}"))) } } diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs index b92e07a..c76d7e9 100644 --- a/crates/tinywasm/src/store/gc/object.rs +++ b/crates/tinywasm/src/store/gc/object.rs @@ -5,13 +5,11 @@ use tinywasm_types::{TagAddr, TypeAddr}; use crate::engine::Config; use crate::interpreter::{RuntimeValue, ValueRef}; -use crate::shared::{AtomicU32, Ordering, StoreShared}; +use crate::shared::StoreShared; use crate::{ResourceLimiter, Trap}; use super::{AllocError, Arena, Handle, Trace}; -static NEXT_GC_REF: AtomicU32 = AtomicU32::new(0); - pub(crate) struct GcObject { pub(crate) kind: GcObjectKind, pub(crate) values: Box<[RuntimeValue]>, @@ -35,6 +33,7 @@ impl Trace for GcObject { pub(crate) struct GcHeap { objects: Arena, directory: Vec<(u32, Handle)>, + next_key: u32, resource_limiter: Option>, } @@ -50,6 +49,7 @@ impl GcHeap { Self { objects: Arena::new(config.gc_collection_threshold), directory: Vec::new(), + next_key: 0, resource_limiter: config.resource_limiter.clone(), } } @@ -114,10 +114,11 @@ impl GcHeap { ) -> Result { let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?; - let key = NEXT_GC_REF.fetch_add(1, Ordering::Relaxed); - if key >= 1 << 30 { + 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)?; diff --git a/crates/tinywasm/tests/generated/wasm-1.csv b/crates/tinywasm/tests/generated/wasm-1.csv index a46baf3..ae14c99 100644 --- a/crates/tinywasm/tests/generated/wasm-1.csv +++ b/crates/tinywasm/tests/generated/wasm-1.csv @@ -9,3 +9,4 @@ 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,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-beta.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 19bfb0e..4d83eb6 100644 --- a/crates/tinywasm/tests/generated/wasm-2.csv +++ b/crates/tinywasm/tests/generated/wasm-2.csv @@ -14,3 +14,4 @@ 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,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-beta.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 fdc0e86..952c9cf 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,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-beta.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-custom-page-sizes.csv b/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv index e3f7540..99d3ed4 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-beta.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-gc.csv b/crates/tinywasm/tests/generated/wasm-gc.csv index ea39c56..a75f559 100644 --- a/crates/tinywasm/tests/generated/wasm-gc.csv +++ b/crates/tinywasm/tests/generated/wasm-gc.csv @@ -1,3 +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-beta.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 b25ec13..a9bbe0b 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,3 +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-beta.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 8cf6dbb..7ebc68d 100644 --- a/crates/tinywasm/tests/generated/wasm-memory64.csv +++ b/crates/tinywasm/tests/generated/wasm-memory64.csv @@ -3,3 +3,4 @@ 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,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-beta.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..c17d08a 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-beta.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-relaxed-simd.csv b/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv index 56ca1b5..6190168 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-beta.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-simd.csv b/crates/tinywasm/tests/generated/wasm-simd.csv index 605c09d..158668b 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-beta.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-wide-arithmetic.csv b/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv index dfbff12..a40fa28 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-beta.0,109,0,[{"name":"wide-arithmetic.wast","passed":109,"failed":0}] diff --git a/crates/tinywasm/tests/memory_ref_api.rs b/crates/tinywasm/tests/memory_ref_api.rs index 768c873..65b91ba 100644 --- a/crates/tinywasm/tests/memory_ref_api.rs +++ b/crates/tinywasm/tests/memory_ref_api.rs @@ -22,3 +22,16 @@ fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<(), Box Result<(), Box> { + 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/wasi/Cargo.toml b/crates/wasi/Cargo.toml index bbf6242..f6923d4 100644 --- a/crates/wasi/Cargo.toml +++ b/crates/wasi/Cargo.toml @@ -13,7 +13,7 @@ categories = ["wasm"] cap-fs-ext = "4.0.3" cap-std = "4.0.3" getrandom = "0.4.3" -rustix = { version = "1.1.4", features = ["event", "fs", "net"] } +rustix = { version = "1.1.5", features = ["event", "fs", "net"] } tinywasm = { workspace = true, default-features = false, features = ["state"] } [dev-dependencies] -- cgit v1.3.1 From fa7b34fb0ad7fe8afa7e78af712a40c209923eb2 Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 19 Sep 2026 22:37:35 +0200 Subject: chore: v0.11.0 Signed-off-by: Henry --- CHANGELOG.md | 2 +- Cargo.lock | 20 ++++++++++---------- Cargo.toml | 11 ++++++----- README.md | 13 +++++-------- crates/cli/Cargo.toml | 2 +- crates/parser/Cargo.toml | 1 + crates/tinywasm/Cargo.toml | 1 + crates/tinywasm/tests/generated/wasm-1.csv | 2 +- crates/tinywasm/tests/generated/wasm-2.csv | 2 +- crates/tinywasm/tests/generated/wasm-3.csv | 2 +- .../tests/generated/wasm-custom-page-sizes.csv | 2 +- crates/tinywasm/tests/generated/wasm-gc.csv | 2 +- crates/tinywasm/tests/generated/wasm-latest.csv | 2 +- crates/tinywasm/tests/generated/wasm-memory64.csv | 2 +- .../tinywasm/tests/generated/wasm-multi-memory.csv | 2 +- .../tinywasm/tests/generated/wasm-relaxed-simd.csv | 2 +- crates/tinywasm/tests/generated/wasm-simd.csv | 2 +- .../tests/generated/wasm-wide-arithmetic.csv | 2 +- crates/types/Cargo.toml | 1 + crates/wasi/Cargo.toml | 1 + 20 files changed, 38 insertions(+), 36 deletions(-) (limited to 'Cargo.lock') diff --git a/CHANGELOG.md b/CHANGELOG.md index 82af4d3..0059446 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [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). diff --git a/Cargo.lock b/Cargo.lock index eeb9e4a..f49bf9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,9 +182,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.6" +version = "1.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" dependencies = [ "find-msvc-tools", "shlex", @@ -413,9 +413,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" [[package]] name = "float-cmp" @@ -979,7 +979,7 @@ dependencies = [ [[package]] name = "tinywasm" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "libm", "log", @@ -993,7 +993,7 @@ dependencies = [ [[package]] name = "tinywasm-cli" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "anstream", "anyhow", @@ -1016,7 +1016,7 @@ dependencies = [ [[package]] name = "tinywasm-parser" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "log", "tinywasm-types", @@ -1025,7 +1025,7 @@ dependencies = [ [[package]] name = "tinywasm-root" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "anyhow", "criterion", @@ -1038,7 +1038,7 @@ dependencies = [ [[package]] name = "tinywasm-types" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "portable-atomic-util", "postcard", @@ -1047,7 +1047,7 @@ dependencies = [ [[package]] name = "tinywasm-wasi" -version = "0.11.0-beta.0" +version = "0.11.0" dependencies = [ "cap-fs-ext", "cap-std", diff --git a/Cargo.toml b/Cargo.toml index 66fc96d..57526e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,19 +11,20 @@ members = ["crates/*"] default-members = [".", "crates/parser", "crates/tinywasm", "crates/types", "crates/wasi"] [workspace.package] -version = "0.11.0-beta.0" +version = "0.11.0" edition = "2024" 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-beta.0", default-features = false } -tinywasm-parser = { path = "crates/parser", version = "0.11.0-beta.0", default-features = false } -tinywasm-types = { path = "crates/types", version = "0.11.0-beta.0", default-features = false } -tinywasm-wasi = { path = "crates/wasi", version = "0.11.0-beta.0" } +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" } anyhow = "1.0" log = "0.4" diff --git a/README.md b/README.md index d77abdb..6d2ca69 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,3 @@ -> [!WARNING] -> This is the `next` branch and contains changes for the 0.11 beta. See [`v0.10.0`](https://github.com/explodingcamera/tinywasm/tree/v0.10.0) for the latest stable version. - # `tinywasm` [![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) @@ -19,7 +16,7 @@ ```toml [dependencies] -tinywasm = "0.11.0-beta.0" +tinywasm = "0.11.0" ``` ## Usage @@ -103,10 +100,10 @@ TinyWasm generally implements non-JavaScript core proposals at [phase 4](https:/ | [**Memory64**](https://github.com/WebAssembly/memory64) | 🟢 | 0.9.0 | | [**Wide Arithmetic**](https://github.com/WebAssembly/wide-arithmetic) | 🟢 | 0.9.0 | | [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes) | 🟢 | 0.9.0 | -| [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` | -| [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` | -| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🟢 | `next` | -| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🟢 | `next` | +| [**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) | 🌑 | - | diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index aff21a2..73b537f 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -4,7 +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" +homepage.workspace = true repository.workspace = true license.workspace = true keywords = ["cli", "runtime", "tinywasm", "wasm", "webassembly"] diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml index 3cd3097..afedeed 100644 --- a/crates/parser/Cargo.toml +++ b/crates/parser/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true rust-version.workspace = true description = "Parser and lowering pipeline for TinyWasm" +homepage.workspace = true repository.workspace = true license.workspace = true keywords.workspace = true diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 9ed5fa7..4f35466 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -5,6 +5,7 @@ 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 diff --git a/crates/tinywasm/tests/generated/wasm-1.csv b/crates/tinywasm/tests/generated/wasm-1.csv index ae14c99..535e57c 100644 --- a/crates/tinywasm/tests/generated/wasm-1.csv +++ b/crates/tinywasm/tests/generated/wasm-1.csv @@ -9,4 +9,4 @@ 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,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-beta.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 4d83eb6..ac2825c 100644 --- a/crates/tinywasm/tests/generated/wasm-2.csv +++ b/crates/tinywasm/tests/generated/wasm-2.csv @@ -14,4 +14,4 @@ 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,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-beta.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 952c9cf..df606ee 100644 --- a/crates/tinywasm/tests/generated/wasm-3.csv +++ b/crates/tinywasm/tests/generated/wasm-3.csv @@ -1,4 +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,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-beta.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-custom-page-sizes.csv b/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv index 99d3ed4..c0a9ae5 100644 --- a/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv +++ b/crates/tinywasm/tests/generated/wasm-custom-page-sizes.csv @@ -3,4 +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-beta.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-gc.csv b/crates/tinywasm/tests/generated/wasm-gc.csv index a75f559..0057d7a 100644 --- a/crates/tinywasm/tests/generated/wasm-gc.csv +++ b/crates/tinywasm/tests/generated/wasm-gc.csv @@ -1,4 +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-beta.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 a9bbe0b..0af70c7 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,4 +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-beta.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 7ebc68d..2a307a1 100644 --- a/crates/tinywasm/tests/generated/wasm-memory64.csv +++ b/crates/tinywasm/tests/generated/wasm-memory64.csv @@ -3,4 +3,4 @@ 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,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-beta.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 c17d08a..145bfb4 100644 --- a/crates/tinywasm/tests/generated/wasm-multi-memory.csv +++ b/crates/tinywasm/tests/generated/wasm-multi-memory.csv @@ -3,4 +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-beta.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-relaxed-simd.csv b/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv index 6190168..4716ba8 100644 --- a/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv +++ b/crates/tinywasm/tests/generated/wasm-relaxed-simd.csv @@ -2,4 +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-beta.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-simd.csv b/crates/tinywasm/tests/generated/wasm-simd.csv index 158668b..5921e05 100644 --- a/crates/tinywasm/tests/generated/wasm-simd.csv +++ b/crates/tinywasm/tests/generated/wasm-simd.csv @@ -3,4 +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-beta.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-wide-arithmetic.csv b/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv index a40fa28..d740038 100644 --- a/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv +++ b/crates/tinywasm/tests/generated/wasm-wide-arithmetic.csv @@ -2,4 +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-beta.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/types/Cargo.toml b/crates/types/Cargo.toml index 3837fdc..2d2bf91 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true rust-version.workspace = true description = "Shared runtime, module, and archive types for TinyWasm" +homepage.workspace = true repository.workspace = true license.workspace = true keywords.workspace = true diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml index f6923d4..e93f087 100644 --- a/crates/wasi/Cargo.toml +++ b/crates/wasi/Cargo.toml @@ -4,6 +4,7 @@ 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"] -- cgit v1.3.1